From 4d714b9439ca6ca2be3134f7135964eeb49f68f6 Mon Sep 17 00:00:00 2001 From: kartik Date: Mon, 30 Nov 2026 05:30:32 +0530 Subject: [PATCH] Show college cutoffs as one all-categories grid and drop the eligibility check - MHT-CET and JEE college cutoff tables lose the "Your seat" view and its row expanders; the all-categories grid is the only table. A column header selects that category and sorts by it, Program sorts by name, and "Only what I clear" filters the grid on both exams. - The MHT-CET grid gains Defence, PWD and Orphan columns, Minority joins the Special options, and Home university gains "None (Type E candidature)". Choice codes and their copy button sit under each program name. A saved category the college does not publish falls back to Open on that page. - The Eligibility check section, its form, /api/admissions/fit and the profile modules behind it are removed. The saved profile and table-view keys are cleared from local storage, and the cookie policy table no longer lists them. - The 2024 seat matrix is a wide grid: intake, seats per category with the ladies count, then TFWS, Defence, PWD, Orphan and, where present, EWS, Minority, All India and Institute seats. Home and other university seats sit under each program's totals. - The chart e2e test reads the college trend chart, since the per-program chart lived in the removed expander. --- app/api/admissions/fit/route.ts | 83 --- app/compliance/cookie-policy/page.tsx | 14 +- app/globals.css | 6 - components/admissions/AdmissionsFitGate.tsx | 64 --- components/admissions/AdmissionsFitPanel.tsx | 472 ----------------- components/admissions/CutoffObservations.tsx | 529 +++++-------------- components/admissions/FitSection.tsx | 16 - components/admissions/MhtCetDetailView.tsx | 33 +- components/admissions/MhtSeatMatrix.tsx | 139 +++++ components/admissions/mht-college.css | 56 +- components/admissions/mht-explorer.css | 276 +--------- components/jee-cutoffs/JeeYearExplorer.tsx | 493 +++++------------ components/jee-cutoffs/jee.css | 8 - e2e/jee-cutoffs.spec.ts | 4 +- lib/admissions/data.ts | 55 +- lib/admissions/fit.ts | 246 --------- lib/admissions/mht-cet-seat-view.ts | 53 +- lib/admissions/profile-codec.ts | 101 ---- lib/admissions/profile.ts | 82 --- lib/admissions/types.ts | 63 +-- 20 files changed, 505 insertions(+), 2288 deletions(-) delete mode 100644 app/api/admissions/fit/route.ts delete mode 100644 components/admissions/AdmissionsFitGate.tsx delete mode 100644 components/admissions/AdmissionsFitPanel.tsx delete mode 100644 components/admissions/FitSection.tsx create mode 100644 components/admissions/MhtSeatMatrix.tsx delete mode 100644 lib/admissions/fit.ts delete mode 100644 lib/admissions/profile-codec.ts delete mode 100644 lib/admissions/profile.ts diff --git a/app/api/admissions/fit/route.ts b/app/api/admissions/fit/route.ts deleted file mode 100644 index 11538d2f..00000000 --- a/app/api/admissions/fit/route.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { NextRequest, NextResponse } from "next/server"; -import { AdmissionsDataError } from "@/lib/admissions/data"; -import { evaluateAdmissionsFit } from "@/lib/admissions/fit"; -import { FitRequestV1Schema } from "@/lib/admissions/profile"; -import { isAdmissionsV2Enabled } from "@/lib/admissions/flags"; -import { isRoundAvailableForYear } from "@/lib/mht-cet/state-cutoffs/config"; - -const MAX_REQUEST_BYTES = 16 * 1024; -const RESPONSE_HEADERS = { - "Cache-Control": "no-store, max-age=0", - "Content-Type": "application/json; charset=utf-8", - "X-Content-Type-Options": "nosniff", -}; - -function json(body: unknown, status = 200) { - return NextResponse.json(body, { status, headers: RESPONSE_HEADERS }); -} - -export async function POST(request: NextRequest) { - const contentType = request.headers.get("content-type") || ""; - if (!contentType.toLowerCase().startsWith("application/json")) { - return json({ error: "Content-Type must be application/json" }, 415); - } - - const declaredLength = Number(request.headers.get("content-length") || 0); - if (declaredLength > MAX_REQUEST_BYTES) { - return json({ error: "Request body is too large" }, 413); - } - - let text: string; - try { - text = await request.text(); - } catch { - return json({ error: "Unable to read request body" }, 400); - } - if (new TextEncoder().encode(text).byteLength > MAX_REQUEST_BYTES) { - return json({ error: "Request body is too large" }, 413); - } - - let body: unknown; - try { - body = JSON.parse(text); - } catch { - return json({ error: "Request body must contain valid JSON" }, 400); - } - const parsed = FitRequestV1Schema.safeParse(body); - if (!parsed.success) { - return json( - { - error: "Invalid fit request", - fieldErrors: parsed.error.issues.map((issue) => ({ - path: issue.path.join("."), - message: issue.message, - })), - }, - 400, - ); - } - if (!isAdmissionsV2Enabled(parsed.data.system)) { - return json({ error: "Admissions fit is unavailable" }, 404); - } - if ( - parsed.data.system === "mht-cet" && - !isRoundAvailableForYear(parsed.data.round, parsed.data.year) - ) { - return json({ error: "Unsupported MHT-CET year and round" }, 400); - } - - try { - return json(await evaluateAdmissionsFit(parsed.data)); - } catch (error) { - if (error instanceof AdmissionsDataError) { - return json( - { - error: "Official cutoff data is temporarily unavailable", - code: error.code, - }, - 503, - ); - } - return json({ error: "Unable to calculate historical fit" }, 500); - } -} diff --git a/app/compliance/cookie-policy/page.tsx b/app/compliance/cookie-policy/page.tsx index cf452d54..5ea279b7 100644 --- a/app/compliance/cookie-policy/page.tsx +++ b/app/compliance/cookie-policy/page.tsx @@ -96,21 +96,15 @@ const FUNCTIONAL: Row[] = [ duration: "Until you select System or clear site data.", }, { - name: deetnuts:admissions-profile:v1:*, + name: <>deetnuts:mht-cet-score:v1, deetnuts:mht-cet-seat-view:v1, type: "Local storage", - purpose: "Stores a candidate profile that you save for comparison on this device.", - duration: "Until you select Clear profile, replace the profile or clear site data.", - }, - { - name: <>deetnuts:mht-cet-score:v1, deetnuts:mht-cet-seat-view:v1, deetnuts:mht-cet-cutoff-mode:v1, - type: "Local storage", - purpose: "Remember the rank or percentile you entered, the seat categories you selected and the list or grid view on MHT-CET cutoff pages.", + purpose: "Remember the rank or percentile you entered and the seat categories you selected on MHT-CET cutoff pages.", duration: "Until you change or clear the value, or clear site data.", }, { - name: <>deetnuts:jee-seat:v1, deetnuts:jee-cutoff-mode:v1, + name: deetnuts:jee-seat:v1, type: "Local storage", - purpose: "Remember the seat pool and view mode you selected on JEE cutoff pages.", + purpose: "Remembers the seat pool you selected on JEE cutoff pages.", duration: "Until you change the selection or clear site data.", }, { diff --git a/app/globals.css b/app/globals.css index 69336cf7..d6dd5c1e 100644 --- a/app/globals.css +++ b/app/globals.css @@ -114,12 +114,6 @@ html.dark .theme-settings-backdrop { color: var(--admissions-ink); } -.admissions-panel { - border: 1px solid var(--admissions-line); - background: #ffffff; - box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04); -} - .admissions-surface section[id] { scroll-margin-top: 5.5rem; } diff --git a/components/admissions/AdmissionsFitGate.tsx b/components/admissions/AdmissionsFitGate.tsx deleted file mode 100644 index 2d80ca34..00000000 --- a/components/admissions/AdmissionsFitGate.tsx +++ /dev/null @@ -1,64 +0,0 @@ -"use client"; - -import { lazy, Suspense, useEffect, useState } from "react"; -import type { AdmissionsFitPanelProps } from "@/components/admissions/AdmissionsFitPanel"; -import FitSection from "@/components/admissions/FitSection"; - -const LazyAdmissionsFitPanel = lazy( - () => import("@/components/admissions/AdmissionsFitPanel"), -); - -function shouldOpenFromBrowserState(system: AdmissionsFitPanelProps["system"]) { - const profileKey = `deetnuts:admissions-profile:v1:${system}`; - const fragmentParts = window.location.hash.replace(/^#/, "").split("&"); - return ( - fragmentParts.includes("fit") || - fragmentParts.some((part) => part.startsWith("profile=v1.")) || - window.localStorage.getItem(profileKey) !== null - ); -} - -export default function AdmissionsFitGate(props: AdmissionsFitPanelProps) { - const [open, setOpen] = useState(false); - - useEffect(() => { - const revealFromBrowserState = () => { - if (shouldOpenFromBrowserState(props.system)) setOpen(true); - }; - revealFromBrowserState(); - window.addEventListener("hashchange", revealFromBrowserState); - return () => window.removeEventListener("hashchange", revealFromBrowserState); - }, [props.system]); - - if (open) { - return ( - -
-

Loading…

-
- - } - > - -
- ); - } - - return ( - -
- -

Stays on this device.

-
-
- ); -} diff --git a/components/admissions/AdmissionsFitPanel.tsx b/components/admissions/AdmissionsFitPanel.tsx deleted file mode 100644 index 42c9f75d..00000000 --- a/components/admissions/AdmissionsFitPanel.tsx +++ /dev/null @@ -1,472 +0,0 @@ -"use client"; - -import { useEffect, useRef, useState } from "react"; -import { CheckCircle2, CircleAlert, Eraser, LockKeyhole, Save } from "lucide-react"; -import { - MhtCetAdmissionsProfileSchema, - type AdmissionsStoredProfile, -} from "@/lib/admissions/profile"; -import { - encodeAdmissionsProfileFragment, - getAdmissionsProfileStorageKey, - resolveAdmissionsProfileSources, - setProfileFragmentInUrl, -} from "@/lib/admissions/profile-codec"; -import type { FitResponseV1 } from "@/lib/admissions/types"; -import FitSection from "@/components/admissions/FitSection"; -import { - MHT_CET_CANDIDATURE_OPTIONS, - MHT_CET_CATEGORY_OPTIONS, - MHT_CET_HOME_UNIVERSITIES, - MHT_CET_MINORITY_OPTIONS, - type MhtCetCandidateProfile, -} from "@/lib/mht-cet/state-cutoffs/candidate-profile"; - -export type AdmissionsFitPanelProps = { - system: "mht-cet"; - year: number; - round: number; - collegeId: string; -}; - -type MhtCetCandidateForm = Omit< - MhtCetCandidateProfile, - "candidatureType" | "homeUniversityId" -> & { - candidatureType: MhtCetCandidateProfile["candidatureType"] | ""; - homeUniversityId?: MhtCetCandidateProfile["homeUniversityId"] | ""; -}; - -const DEFAULT_MHT_CANDIDATE: MhtCetCandidateForm = { - candidatureType: "", - homeUniversityId: "", - categoryId: "open", - ladiesSeatEligible: false, - eligibilities: { - ewsCertificate: false, - tfwsEligible: false, - pwd: false, - orphanCertificate: false, - }, -}; - -function persistProfile(value: AdmissionsStoredProfile) { - window.localStorage.setItem( - getAdmissionsProfileStorageKey(value.system), - JSON.stringify(value), - ); - const fragment = encodeAdmissionsProfileFragment(value); - const nextUrl = setProfileFragmentInUrl(new URL(window.location.href), fragment); - window.history.replaceState(window.history.state, "", nextUrl); -} - -function formatMargin(value: number, metric: "rank" | "percentile") { - return new Intl.NumberFormat("en-IN", { - maximumFractionDigits: metric === "rank" ? 0 : 4, - }).format(Math.abs(value)); -} - -function Field({ - label, - className, - children, -}: { - label: React.ReactNode; - className?: string; - children: React.ReactNode; -}) { - return ( - - ); -} - -function CheckboxField({ - checked, - onChange, - children, -}: { - checked: boolean; - onChange: (checked: boolean) => void; - children: React.ReactNode; -}) { - return ( - - ); -} - -function marginText(observation: { outcome: "cleared" | "missed"; margin: number; metric: "rank" | "percentile" }) { - return `${observation.outcome === "cleared" ? "Cleared by" : "Missed by"} ${formatMargin(observation.margin, observation.metric)} ${observation.metric === "rank" ? "ranks" : "percentile points"}`; -} - -export default function AdmissionsFitPanel(props: AdmissionsFitPanelProps) { - const [loaded, setLoaded] = useState(false); - const [savedSource, setSavedSource] = useState<"link" | "device" | null>(null); - const [mhtScoreMode, setMhtScoreMode] = useState<"rank" | "percentile">("percentile"); - const [mhtScore, setMhtScore] = useState(""); - const [mhtCandidate, setMhtCandidate] = useState( - DEFAULT_MHT_CANDIDATE, - ); - const [error, setError] = useState(null); - const [requestBody, setRequestBody] = useState(null); - const [result, setResult] = useState(null); - const [loading, setLoading] = useState(false); - const requestSequence = useRef(0); - - useEffect(() => { - const resolved = resolveAdmissionsProfileSources( - window.location.hash, - window.localStorage.getItem(getAdmissionsProfileStorageKey(props.system)), - props.system, - ); - const stored = resolved?.profile; - if (stored) { - setMhtScoreMode(stored.profile.scoreMode); - setMhtScore(String(stored.profile.score)); - setMhtCandidate(stored.profile.candidate); - setSavedSource(resolved?.source || null); - } - setLoaded(true); - }, [props.system]); - - useEffect(() => { - if (!requestBody) return; - const sequence = ++requestSequence.current; - const controller = new AbortController(); - const timer = window.setTimeout(async () => { - setLoading(true); - setError(null); - try { - const response = await fetch("/api/admissions/fit", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(requestBody), - signal: controller.signal, - }); - const payload = await response.json(); - if (!response.ok) throw new Error(payload.error || "Unable to compare cutoffs"); - if (sequence === requestSequence.current) setResult(payload as FitResponseV1); - } catch (requestError) { - if ((requestError as Error).name !== "AbortError" && sequence === requestSequence.current) { - setResult(null); - setError((requestError as Error).message); - } - } finally { - if (sequence === requestSequence.current) setLoading(false); - } - }, 250); - - return () => { - window.clearTimeout(timer); - controller.abort(); - }; - }, [requestBody]); - - function clearProfile() { - window.localStorage.removeItem(getAdmissionsProfileStorageKey(props.system)); - const nextUrl = setProfileFragmentInUrl(new URL(window.location.href), null); - window.history.replaceState(window.history.state, "", nextUrl); - setSavedSource(null); - setRequestBody(null); - setResult(null); - setError(null); - setMhtScore(""); - setMhtScoreMode("percentile"); - setMhtCandidate(DEFAULT_MHT_CANDIDATE); - } - - function submit(event: React.FormEvent) { - event.preventDefault(); - const profileResult = MhtCetAdmissionsProfileSchema.safeParse({ - scoreMode: mhtScoreMode, - score: Number(mhtScore), - candidate: mhtCandidate, - }); - if (!profileResult.success) { - setError(profileResult.error.issues[0]?.message || "Check the MHT-CET profile fields."); - return; - } - const stored: AdmissionsStoredProfile = { - version: 1, - system: "mht-cet", - profile: profileResult.data, - }; - persistProfile(stored); - setSavedSource("device"); - setRequestBody({ - version: 1, - system: "mht-cet", - entity: { kind: "college", id: props.collegeId }, - year: props.year, - round: props.round, - profile: profileResult.data, - }); - } - - const best = result?.observations[0]; - - return ( - -
-
-
- - - - - setMhtScore(event.target.value)} - placeholder={mhtScoreMode === "rank" ? "e.g. 4500" : "e.g. 97.85"} - className="mht-input" - required - /> - - - - - - - - {mhtCandidate.candidatureType && mhtCandidate.candidatureType !== "type-e" && ( - - - - )} - - - -
-
- setMhtCandidate((candidate) => ({ ...candidate, ladiesSeatEligible: checked }))} - > - Ladies seat pools - - setMhtCandidate((candidate) => ({ - ...candidate, - eligibilities: { ...candidate.eligibilities, ewsCertificate: checked }, - }))} - > - EWS certificate - - setMhtCandidate((candidate) => ({ - ...candidate, - eligibilities: { ...candidate.eligibilities, tfwsEligible: checked }, - }))} - > - TFWS eligible - - setMhtCandidate((candidate) => ({ - ...candidate, - eligibilities: { ...candidate.eligibilities, pwd: checked }, - }))} - > - PwD reservation - - setMhtCandidate((candidate) => ({ - ...candidate, - eligibilities: { ...candidate.eligibilities, orphanCertificate: checked }, - }))} - > - Orphan certificate - -
- -
-
-
-
- {loaded && savedSource && ( - - )} - -
-
-
- -
- {error && ( -
-
- )} - {result?.status === "no-comparable-data" && ( -
-

- No published cutoff for this seat in {props.year} Round {props.round}. -

-
- )} - {best && ( -
-
- {best.outcome === "cleared" ? ( -
- {result.history && ( -

- Would have cleared {result.history.clearedYears} of {result.history.comparableYears} comparable years. -

- )} -
- - View all {result.observations.length} exact {result.observations.length === 1 ? "result" : "results"} - -
    - {result.observations.map((observation) => ( -
  • - {observation.programName} - {observation.seatPool} - {marginText(observation)} -
  • - ))} -
- {result.status === "partial" && ( -

- Showing the first 200 results. -

- )} -
-
- )} -
-
-
- ); -} diff --git a/components/admissions/CutoffObservations.tsx b/components/admissions/CutoffObservations.tsx index 7239da92..c9a98b5b 100644 --- a/components/admissions/CutoffObservations.tsx +++ b/components/admissions/CutoffObservations.tsx @@ -2,51 +2,42 @@ import type { AdmissionsCutoffObservation } from "@/lib/admissions/types"; import { + MHT_CET_POOL_FAMILIES, groupMhtCetPrograms, poolFamilyLabel, type MhtCetProgramGroup, - type MhtCetProgramRow, } from "@/lib/admissions/mht-cet-seat-pool"; import { DEFAULT_MHT_CET_SEAT_VIEW, + MHT_CET_NO_HOME_UNIVERSITY, MHT_CET_SEAT_SPECIALS, MHT_CET_SEAT_VIEW_STORAGE_KEY, matchFamilySeat, matchProgramSeat, parseMhtCetSeatView, - seatCaption, - seatViewFromCandidate, type MhtCetSeatView, } from "@/lib/admissions/mht-cet-seat-view"; import { MHT_CET_SCORE_STORAGE_KEY, compareMhtCetScore, - describeMhtCetMargin, - formatMhtCetMargin, parseMhtCetScore, - percentileScale, rankHeat, readStoredMhtCetScore, - scalePosition, - type MhtCetScore, type MhtCetScoreMode, - type MhtCetVerdict, - type PercentileScale, } from "@/lib/admissions/mht-cet-score"; -import { getAdmissionsProfileStorageKey, decodeAdmissionsDeviceProfile } from "@/lib/admissions/profile-codec"; import { MHT_CET_CATEGORY_OPTIONS, MHT_CET_HOME_UNIVERSITIES } from "@/lib/mht-cet/state-cutoffs/candidate-profile"; import CopyCollegeCode from "@/components/admissions/CopyCollegeCode"; import MhtPill from "@/components/admissions/MhtPill"; -import { Fragment, useEffect, useId, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react"; +import { useEffect, useId, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react"; -type ExplorerMode = "seat" | "grid"; type SortKey = "cutoff-desc" | "cutoff-asc" | "name-asc" | "name-desc"; -const EXPLORER_MODE_STORAGE_KEY = "deetnuts:mht-cet-cutoff-mode:v1"; +// Keys left behind by the removed eligibility form and table switch. +const RETIRED_STORAGE_KEYS = ["deetnuts:admissions-profile:v1:mht-cet", "deetnuts:mht-cet-cutoff-mode:v1"]; -// Official CET Cell order. Defence, PWD and orphan pools are split by category, -// so they stay in the program detail. -const GRID_FAMILIES = ["open", "sc", "st", "vj-dt", "nt-b", "nt-c", "nt-d", "obc", "sebc", "ews", "tfws", "minority"]; +// Official CET Cell order. Defence and PWD pools are split by category, so their +// columns follow the reader's category. +const GRID_FAMILIES = MHT_CET_POOL_FAMILIES.map(([family]) => family); const GENDER_OPTIONS = [ { value: "general", label: "General" }, @@ -55,10 +46,6 @@ const GENDER_OPTIONS = [ const HOME_SCOPES = new Set(["Home university", "Other university"]); const CATEGORY_IDS = new Set(MHT_CET_CATEGORY_OPTIONS.map((option) => option.value)); -const SELECTABLE_FAMILIES = new Set([ - ...CATEGORY_IDS, - ...MHT_CET_SEAT_SPECIALS.map((option) => option.value).filter((value) => value !== "none"), -]); function formatRank(value: number | null | undefined): ReactNode { if (value === null || value === undefined || !Number.isFinite(value)) return —; @@ -80,48 +67,6 @@ function Percentile({ value, short = false }: { value: number | null | undefined ); } -function Verdict({ verdict, mode }: { verdict: MhtCetVerdict | null; mode: MhtCetScoreMode }) { - if (!verdict) return —; - return ( - - - {describeMhtCetMargin(verdict, mode)} - - ); -} - -function ScaleBar({ - value, - scale, - you, - status, -}: { - value: number | null | undefined; - scale: PercentileScale; - you: number | null; - status?: string; -}) { - const position = value === null || value === undefined ? null : scalePosition(value, scale); - return ( - - ); -} - -// Rows sit under a category heading, so "OBC, General, State level" reads as "General". -function poolLine(row: MhtCetProgramRow, showScope: boolean): string { - const prefix = `${poolFamilyLabel(row.poolFamily)}, `; - const label = row.poolLabel.startsWith(prefix) ? row.poolLabel.slice(prefix.length) : row.poolLabel; - return showScope && row.poolScope ? `${label}, ${row.poolScope}` : label; -} - function familyOf(view: MhtCetSeatView): string { return view.special === "none" ? view.categoryId : view.special; } @@ -146,78 +91,6 @@ function isTyping(target: EventTarget | null): boolean { ); } -function ProgramDetail({ - group, - headline, - score, -}: { - group: MhtCetProgramGroup; - headline: MhtCetProgramRow | null; - score: MhtCetScore | null; -}) { - const showScope = - new Set(group.rows.map((row) => row.poolScope).filter((scope) => scope !== null)).size > 1; - const families: Array<[string, MhtCetProgramRow[]]> = []; - for (const row of group.rows) { - const last = families.at(-1); - if (last && last[0] === row.poolFamily) last[1].push(row); - else families.push([row.poolFamily, [row]]); - } - return ( -
-
- {group.codes.map((code) => ( - - Choice code - {code} - - - ))} - - {group.rows.length === 1 ? "1 seat pool" : `${group.rows.length} seat pools`} - -
-
- {families.map(([family, rows]) => ( -
-

{poolFamilyLabel(family)}

-
    - {rows.map((row) => { - const verdict = compareMhtCetScore(row, score); - return ( -
  • - - {poolLine(row, showScope)} - {row === headline ? Your seat : null} - - {row.category} - {row.showChoiceCode ? ` · ${row.programCode}` : ""} - - - - - - {formatRank(row.rankValue)} - {score ? ( - - - - ) : null} -
  • - ); - })} -
-
- ))} -
-
- ); -} - export default function CutoffObservations({ observations, period, @@ -233,9 +106,7 @@ export default function CutoffObservations({ }) { const [query, setQuery] = useState(""); const [view, setView] = useState(DEFAULT_MHT_CET_SEAT_VIEW); - const [openId, setOpenId] = useState(null); const [sort, setSort] = useState("cutoff-desc"); - const [mode, setMode] = useState("seat"); const [scoreMode, setScoreMode] = useState("percentile"); const [scoreText, setScoreText] = useState(""); const [onlyCleared, setOnlyCleared] = useState(false); @@ -247,22 +118,14 @@ export default function CutoffObservations({ const scoreInvalid = scoreText.trim() !== "" && !score; useEffect(() => { - const fit = decodeAdmissionsDeviceProfile( - window.localStorage.getItem(getAdmissionsProfileStorageKey("mht-cet")), - "mht-cet", - ); + for (const key of RETIRED_STORAGE_KEYS) window.localStorage.removeItem(key); const storedView = parseMhtCetSeatView(window.localStorage.getItem(MHT_CET_SEAT_VIEW_STORAGE_KEY)); - const seededView = storedView ?? (fit ? seatViewFromCandidate(fit.profile.candidate) : null); - if (seededView) setView(seededView); + if (storedView) setView(storedView); const storedScore = readStoredMhtCetScore(window.localStorage.getItem(MHT_CET_SCORE_STORAGE_KEY)); if (storedScore) { setScoreMode(storedScore.mode); setScoreText(storedScore.text); - } else if (fit) { - setScoreMode(fit.profile.scoreMode); - setScoreText(String(fit.profile.score)); } - if (window.localStorage.getItem(EXPLORER_MODE_STORAGE_KEY) === "grid") setMode("grid"); }, []); useEffect(() => { @@ -302,34 +165,27 @@ export default function CutoffObservations({ } } - function updateMode(next: ExplorerMode) { - setMode(next); - window.localStorage.setItem(EXPLORER_MODE_STORAGE_KEY, next); - } - - // Offer only the seats this college publishes, plus whatever is already selected. + // Offer only the seats this college publishes. A saved seat it doesn't publish falls + // back to Open here and stays saved for other colleges. const families = useMemo(() => new Set(observations.map((row) => row.poolFamily)), [observations]); - const categoryOptions = MHT_CET_CATEGORY_OPTIONS.filter( - (option) => families.has(option.value) || option.value === view.categoryId, - ); + const seat: MhtCetSeatView = { + ...view, + categoryId: families.has(view.categoryId) ? view.categoryId : "open", + special: families.has(view.special) ? view.special : "none", + }; + const categoryOptions = MHT_CET_CATEGORY_OPTIONS.filter((option) => families.has(option.value)); const specialOptions = MHT_CET_SEAT_SPECIALS.filter( - (option) => option.value === "none" || families.has(option.value) || option.value === view.special, + (option) => option.value === "none" || families.has(option.value), ); const hasLadies = observations.some((row) => row.poolLabel.split(", ").includes("Ladies")); const hasHomeSplit = observations.some((row) => row.poolScope !== null && HOME_SCOPES.has(row.poolScope)); const gridFamilies = GRID_FAMILIES.filter((family) => families.has(family)); - const selectedFamily = familyOf(view); + const selectedFamily = familyOf(seat); const search = query.trim().toLocaleLowerCase("en-IN"); const rows = groups.map((group) => { - const headline = matchProgramSeat(group.rows, view, collegeHomeUniversityId); - const verdict = compareMhtCetScore(headline, score); - return { - group, - headline, - verdict, - visible: programMatches(group, search) && (!onlyCleared || verdict?.status === "cleared"), - }; + const headline = matchProgramSeat(group.rows, seat, collegeHomeUniversityId); + return { group, headline, verdict: compareMhtCetScore(headline, score), matches: programMatches(group, search) }; }); rows.sort((a, b) => { if (sort === "name-asc" || sort === "name-desc") { @@ -344,26 +200,20 @@ export default function CutoffObservations({ return sort === "cutoff-desc" ? right - left : left - right; }); - const visibleCount = rows.filter((row) => row.visible).length; - const publishedCount = rows.filter((row) => row.headline).length; const compared = rows.filter((row) => row.verdict); const clearedCount = compared.filter((row) => row.verdict?.status === "cleared").length; - const youPercentile = score?.mode === "percentile" ? score.value : null; - const seatScale = percentileScale( - rows.map((row) => row.headline?.percentileValue), - youPercentile, + // The filter needs a published cutoff in the reader's column to compare against. + const filterCleared = onlyCleared && compared.length > 0; + const isVisible = (row: (typeof rows)[number]) => + row.matches && (!filterCleared || row.verdict?.status === "cleared"); + const visibleCount = rows.filter(isVisible).length; + const gridCells = new Map( + groups.map((group) => [ + group.id, + gridFamilies.map((family) => matchFamilySeat(group.rows, family, seat, collegeHomeUniversityId)), + ]), ); - const gridCells = - mode === "grid" - ? new Map( - groups.map((group) => [ - group.id, - gridFamilies.map((family) => matchFamilySeat(group.rows, family, view, collegeHomeUniversityId)), - ]), - ) - : null; - const gridRanks = gridCells ? [...gridCells.values()].flat().map((cell) => cell?.rankValue) : []; - const caption = seatCaption(view); + const gridRanks = [...gridCells.values()].flat().map((cell) => cell?.rankValue); const sortDirection = (key: "cutoff" | "name") => sort.startsWith(key) ? (sort.endsWith("desc") ? "descending" : "ascending") : "none"; @@ -424,7 +274,7 @@ export default function CutoffObservations({ {categoryOptions.length > 1 ? ( updateView({ ...view, categoryId })} /> @@ -441,7 +291,10 @@ export default function CutoffObservations({ ({ value: option.id, label: option.label }))} + options={[ + ...MHT_CET_HOME_UNIVERSITIES.map((option) => ({ value: option.id as string, label: option.label })), + { value: MHT_CET_NO_HOME_UNIVERSITY, label: "None (Type E candidature)", short: "None" }, + ]} emptyLabel="Choose" wide attention={!view.homeUniversityId} @@ -451,7 +304,7 @@ export default function CutoffObservations({ {specialOptions.length > 1 ? ( updateView({ ...view, special })} /> @@ -459,7 +312,6 @@ export default function CutoffObservations({ ); - // Say only what the controls above and the stat strip don't already show. const statusMain = score && compared.length > 0 ? ( <> @@ -469,12 +321,10 @@ export default function CutoffObservations({ {" "} {compared.length === 1 ? "program" : "programs"}. - ) : publishedCount > 0 && publishedCount < groups.length ? ( - `${publishedCount} of ${groups.length} programs publish this seat.` ) : null; const searchHint = search && visibleCount > 0 ? `${visibleCount} of ${groups.length} match “${query.trim()}”` : null; const homeHint = - hasHomeSplit && !view.homeUniversityId && publishedCount > 0 + hasHomeSplit && !view.homeUniversityId ? "Showing home university cutoffs until you choose yours." : null; const scoreHint = scoreInvalid @@ -503,27 +353,6 @@ export default function CutoffObservations({ ) : null; - const noSeat = - publishedCount === 0 ? ( -
-

This seat isn’t published here. Try:

-
- {[...SELECTABLE_FAMILIES] - .filter((family) => families.has(family) && family !== selectedFamily) - .map((family) => ( - - ))} -
-
- ) : null; - if (observations.length === 0) { return (
@@ -534,7 +363,7 @@ export default function CutoffObservations({ } return ( -
+
{scoreBox} @@ -564,8 +393,8 @@ export default function CutoffObservations({ /> -
- {score ? ( + {score && compared.length > 0 ? ( +
- ) : null} -
- -
-
+ ) : null}
{status} - {noSeat} - {visibleCount === 0 && publishedCount > 0 ? ( + {visibleCount === 0 ? (
{/* With only the filter active, the status line above already says "Clears 0 of N". */} {search ?

No program matches “{query.trim()}”.

: null} @@ -600,7 +420,7 @@ export default function CutoffObservations({ Clear search ) : null} - {onlyCleared ? ( + {filterCleared ? ( @@ -609,14 +429,25 @@ export default function CutoffObservations({
) : null} - {mode === "seat" ? ( - + {gridFamilies.length > 2 ? ( + + ) : null} + - - - - - {score ? ( - - ) : null} + {gridFamilies.map((family) => { + const selected = family === selectedFamily; + return ( + + ); + })} - {rows.map(({ group, headline, verdict, visible }) => { - const open = openId === group.id; - const panelId = `${group.anchor}-pools`; - return ( - - - - - - - {score ? ( - - ) : null} - - - + + {gridFamilies.map((family, index) => { + const cell = gridCells.get(row.group.id)?.[index] ?? null; + const verdict = compareMhtCetScore(cell, score); + const heat = rankHeat(cell?.rankValue, gridRanks); + return ( + - - - ); - })} + ); + })} + + ))}
- {period} cutoffs, {caption} + {period} cutoffs by category, {view.gender === "ladies" ? "Ladies" : "General"} seats
+ - - - Rank - - - Position on the percentile scale - - vs you - + +
- ) : ( - <> - {gridFamilies.length > 2 ? ( - - ) : null} - - - )} +
{footer}
); diff --git a/components/admissions/FitSection.tsx b/components/admissions/FitSection.tsx deleted file mode 100644 index 4017959d..00000000 --- a/components/admissions/FitSection.tsx +++ /dev/null @@ -1,16 +0,0 @@ -export default function FitSection({ children }: { children: React.ReactNode }) { - return ( -
-
-
-

Eligibility check

-
- {children} -
-
- ); -} diff --git a/components/admissions/MhtCetDetailView.tsx b/components/admissions/MhtCetDetailView.tsx index eb5fde6a..4537a356 100644 --- a/components/admissions/MhtCetDetailView.tsx +++ b/components/admissions/MhtCetDetailView.tsx @@ -1,11 +1,11 @@ import Link from "next/link"; -import AdmissionsFitGate from "@/components/admissions/AdmissionsFitGate"; import AdmissionsFilters from "@/components/admissions/AdmissionsFilters"; import AdmissionsJsonLd from "@/components/admissions/AdmissionsJsonLd"; import { ShareAdmissionsPage } from "@/components/admissions/AdmissionsActions"; import CopyCollegeCode from "@/components/admissions/CopyCollegeCode"; import CollegeIdentityMedia from "@/components/admissions/CollegeIdentityMedia"; import CutoffObservations from "@/components/admissions/CutoffObservations"; +import MhtSeatMatrix from "@/components/admissions/MhtSeatMatrix"; import ProvenanceCard from "@/components/admissions/ProvenanceCard"; import type { MhtCetCollegeDetailModel } from "@/lib/admissions/types"; import type { MhtCetPeerCollege } from "@/lib/admissions/mht-cet-peers"; @@ -151,41 +151,14 @@ export default function MhtCetDetailView({
- - {model.seatMatrix.length > 0 ? (
-
+

2024 seat matrix

- - - - - - - - - - {model.seatMatrix.map((row) => ( - - - - - - ))} - -
ProgramSeat typeSeats
- {row.course_name} - {row.choice_code} - {row.seat_type || "Not listed"}{row.SI || row.Total || "—"}
+
diff --git a/components/admissions/MhtSeatMatrix.tsx b/components/admissions/MhtSeatMatrix.tsx new file mode 100644 index 00000000..53dc50cc --- /dev/null +++ b/components/admissions/MhtSeatMatrix.tsx @@ -0,0 +1,139 @@ +import { Fragment, type CSSProperties } from "react"; +import type { MhtCetSeatMatrixRow } from "@/lib/admissions/types"; + +type CountField = { + [Key in keyof MhtCetSeatMatrixRow]: MhtCetSeatMatrixRow[Key] extends number ? Key : never; +}[keyof MhtCetSeatMatrixRow]; + +// Official CET Cell order; each category splits into General and Ladies seats. +const CATEGORIES: Array<[label: string, general: CountField, ladies: CountField]> = [ + ["Open", "OPEN_General", "OPEN_Ladies"], + ["SC", "SC_General", "SC_Ladies"], + ["ST", "ST_General", "ST_Ladies"], + ["VJ/DT", "VJ_DT_General", "VJ_DT_Ladies"], + ["NT-B", "NTB_General", "NTB_Ladies"], + ["NT-C", "NTC_General", "NTC_Ladies"], + ["NT-D", "NTD_General", "NTD_Ladies"], + ["OBC", "OBC_General", "OBC_Ladies"], + ["SEBC", "SEBC_General", "SEBC_Ladies"], +]; + +// Counted once per program, however its category seats are split between universities. +const PROGRAM_COUNTS: ReadonlyArray<[label: string, field: CountField]> = [ + ["EWS", "EWS_seat"], + ["TFWS", "TFWS_seats"], + ["Defence", "DEF_total"], + ["PWD", "PWD_total"], + ["Orphan", "orphan"], + ["Minority", "minority_seats"], + ["All India", "all_india"], + ["Institute", "institute_seats"], +]; + +const SCOPES: Record = { + HU: { label: "Home university", order: 0 }, + OHU: { label: "Other university", order: 1 }, + State_Level: { label: "State level", order: 2 }, +}; + +const formatCount = (value: number) => new Intl.NumberFormat("en-IN").format(value); + +function CategoryCells({ + categories, + rows, +}: { + categories: typeof CATEGORIES; + rows: MhtCetSeatMatrixRow[]; +}) { + return categories.map(([label, general, ladies]) => { + const seats = rows.reduce((sum, row) => sum + row[general] + row[ladies], 0); + const ladiesSeats = rows.reduce((sum, row) => sum + row[ladies], 0); + return ( + + {seats > 0 ? {formatCount(seats)} : —} + {ladiesSeats > 0 ? Ladies {formatCount(ladiesSeats)} : null} + + ); + }); +} + +export default function MhtSeatMatrix({ rows }: { rows: MhtCetSeatMatrixRow[] }) { + const programs = new Map(); + for (const row of rows) { + const scopes = programs.get(row.choice_code); + if (scopes) scopes.push(row); + else programs.set(row.choice_code, [row]); + } + + const categories = CATEGORIES.filter(([, general, ladies]) => rows.some((row) => row[general] + row[ladies] > 0)); + const programCounts = PROGRAM_COUNTS.filter(([, field]) => rows.some((row) => row[field] > 0)); + + return ( +
+ + + + + + + {[...categories, ...programCounts].map(([label]) => ( + + ))} + + + + {[...programs.values()].map((scopes) => { + const program = scopes[0]; + // Home and other university seats sit under the program's own totals. + const split = scopes.some((row) => row.seat_type !== "State_Level"); + return ( + + + + + + {programCounts.map(([label, field]) => ( + + ))} + + {split + ? [...scopes] + .sort((a, b) => (SCOPES[a.seat_type]?.order ?? 9) - (SCOPES[b.seat_type]?.order ?? 9)) + .map((row) => ( + + + + )) + : null} + + ); + })} + +
2024 seats for each program, by category
ProgramIntake + {label} +
+ {program.course_name} + {program.choice_code} + + {formatCount(program.SI)} + + {program[field] > 0 ? ( + {formatCount(program[field])} + ) : ( + — + )} +
+ {row.course_name}, + {SCOPES[row.seat_type]?.label ?? row.seat_type} + + + {programCounts.map(([label]) => ( + + ))} +
+
+ ); +} diff --git a/components/admissions/mht-college.css b/components/admissions/mht-college.css index d18562eb..739483d5 100644 --- a/components/admissions/mht-college.css +++ b/components/admissions/mht-college.css @@ -1,4 +1,4 @@ -/* MHT-CET college pages: hero and eligibility check. Tokens and controls come from +/* MHT-CET college pages: hero and seat matrix. Tokens and controls come from mht-base.css; the stats strip, cutoff explorer and source card from mht-explorer.css. */ .mht-college-section { scroll-margin-top: 1rem; } @@ -78,47 +78,20 @@ .mht-stats { order: 4; } } -/* ---------- Eligibility check ---------- */ -.mht-fit-start { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 0.75rem 1.25rem; - padding: 1.25rem 1.5rem; -} -.mht-fit-start .mht-note { margin-top: 0; } -.mht-form { display: grid; gap: 1.25rem; } -.mht-fields { display: grid; grid-template-columns: 1fr; gap: 1rem; } -.mht-form-foot { - display: flex; - flex-wrap: wrap; - align-items: center; - justify-content: space-between; - gap: 1rem; - padding-top: 1.25rem; - border-top: 1px solid var(--mht-line); +/* ---------- Seat matrix: the cutoff grid, counting seats ---------- */ +.mht-seats { width: 100%; } +.mht-seats :is(th, td) { vertical-align: top; } +.mht-seats thead th:nth-child(2), +.mht-seats td:nth-child(2) { border-right: 1px solid var(--mht-line-soft); padding-right: 0.9rem; } +.mht-seats thead th:nth-child(3), +.mht-seats td:nth-child(3) { padding-left: 0.9rem; } +/* Home and other university seats read as part of the program above them. */ +.mht-seats tr[data-sub] > * { padding-top: 0; border-top: 0; } +.mht-seats tr[data-sub] > th { color: var(--mht-ink-soft); font-size: 0.8125rem; font-weight: 500; } +.mht-seats tr[data-sub] .mht-grid-pct { color: var(--mht-ink-soft); font-weight: 500; } +@media (max-width: 639px) { + .mht-seats tr > :first-child { min-width: 8.5rem; max-width: 10rem; padding-left: 1rem; } } -.mht-privacy { display: flex; gap: 0.5rem; max-width: 40rem; color: var(--mht-muted); font-size: 0.78rem; line-height: 1.5; } -.mht-privacy svg { width: 14px; height: 14px; flex: none; margin-top: 0.15rem; } -.mht-alert { display: flex; gap: 0.6rem; padding: 1rem; border-radius: 12px; background: var(--mht-warn-wash); color: var(--mht-ink); font-size: 0.9rem; } -.mht-alert svg { width: 18px; height: 18px; flex: none; margin-top: 0.1rem; color: var(--mht-warn); } -.mht-result { padding: 1.25rem; border-radius: 12px; background: var(--mht-panel-2); } -.mht-result[data-outcome="cleared"] { background: var(--mht-good-wash); } -.mht-result[data-outcome="missed"] { background: var(--mht-warn-wash); } -.mht-result-head { display: flex; gap: 0.75rem; } -.mht-result-head svg { width: 20px; height: 20px; flex: none; margin-top: 0.2rem; } -.mht-result[data-outcome="cleared"] .mht-result-head svg { color: var(--mht-good); } -.mht-result[data-outcome="missed"] .mht-result-head svg { color: var(--mht-warn); } -.mht-result-kicker { color: var(--mht-muted); font-size: 0.75rem; font-weight: 600; } -.mht-result-title { margin-top: 0.15rem; color: var(--mht-ink); font-size: 1.1rem; font-weight: 600; line-height: 1.35; } -.mht-result-meta { margin-top: 0.3rem; color: var(--mht-muted); font-size: 0.875rem; } -.mht-result-history { margin-top: 1rem; padding-top: 1rem; border-top: 1px solid var(--mht-line); color: var(--mht-ink-soft); font-size: 0.9rem; } -.mht-result details { margin-top: 1rem; padding-top: 0.5rem; border-top: 1px solid var(--mht-line); } -.mht-result summary { padding: 0.5rem 0; color: var(--mht-ink); font-size: 0.875rem; font-weight: 600; cursor: pointer; } -.mht-result-list { display: grid; margin: 0.5rem 0 0; padding: 0; list-style: none; max-height: 28rem; overflow: auto; } -.mht-result-list li { display: grid; gap: 0.1rem; padding: 0.7rem 0; border-top: 1px solid var(--mht-line-soft); font-size: 0.875rem; } -.mht-result-list li span { color: var(--mht-muted); } -.mht-result-list li span:first-child { color: var(--mht-ink); font-weight: 600; } /* ---------- Responsive ---------- */ @media (min-width: 640px) { @@ -132,5 +105,4 @@ } .mht-college .mht-college-identity h1 { font-size: 2.25rem; } .mht-college .mht-cutoffs { padding-top: 2.5rem; } - .mht-fields { grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr)); } } diff --git a/components/admissions/mht-explorer.css b/components/admissions/mht-explorer.css index cd6e8218..ff4cdbb9 100644 --- a/components/admissions/mht-explorer.css +++ b/components/admissions/mht-explorer.css @@ -1,5 +1,5 @@ /* Data views shared by MHT-CET and JEE college pages: fact chips, the stats strip, the - cutoff explorer (seat table and all-categories grid), the source card and college lists. */ + cutoff explorer (all-categories grid), the source card and college lists. */ .mht-college-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 0.4rem; margin-top: 0.85rem; } @@ -48,7 +48,7 @@ .mht-cutoffs { padding-top: 2rem; } /* Jumping to the score box keeps the section heading and year filters in view. */ .mht-cutoff-explorer { container: mht-cutoff / inline-size; scroll-margin-top: 5rem; } -.mht-cutoffs:has(.mht-year-round[data-pending]) :is(.mht-compare, .mht-grid, .mht-xstatus) { +.mht-cutoffs:has(.mht-year-round[data-pending]) :is(.mht-grid, .mht-xstatus) { opacity: 0.4; transition: opacity 0.15s ease; } @@ -84,233 +84,6 @@ .mht-legend [data-status="close"]::before { background: var(--mht-warn); } .mht-legend [data-status="short"]::before { background: var(--mht-muted); opacity: 0.6; } -.mht-verdict { - display: inline-flex; - align-items: center; - justify-content: flex-end; - min-width: 4.25rem; - padding: 0.15rem 0.5rem; - border-radius: 999px; - font-family: var(--mht-num); - font-size: 0.8rem; - font-weight: 600; - font-variant-numeric: tabular-nums; -} -.mht-verdict[data-status="cleared"] { background: var(--mht-good-wash); color: var(--mht-good); } -.mht-verdict[data-status="close"] { background: var(--mht-warn-wash); color: var(--mht-warn); } -.mht-verdict[data-status="short"] { background: var(--mht-chip); color: var(--mht-muted); } - -/* Seat table */ -.mht-compare { - width: 100%; - margin-top: 0.5rem; - border-collapse: collapse; - table-layout: fixed; - font-size: 0.95rem; -} -.mht-compare caption { padding: 0; } -.mht-compare > thead th { - padding: 0.6rem 0 0.55rem; - border-bottom: 1px solid var(--mht-line); - color: var(--mht-muted); - font-size: 0.75rem; - font-weight: 500; - text-align: left; -} -.mht-compare > :is(thead, tbody) > tr > :first-child { padding-left: 1.25rem; } -.mht-compare > :is(thead, tbody) > tr > :last-child { padding-right: 1.25rem; } -.mht-compare .mht-c-pct { width: 9rem; text-align: right; } -.mht-compare .mht-c-rank { width: 6.5rem; text-align: right; } -.mht-compare .mht-c-bar { width: 34%; padding-left: 2.5rem; } -.mht-compare .mht-c-you { width: 7rem; text-align: right; } -.mht-axis { - display: flex; - justify-content: space-between; - font-family: var(--mht-num); - font-size: 0.7rem; - font-variant-numeric: tabular-nums; -} - -.mht-program-row { position: relative; } -.mht-program-row > :is(th, td) { - padding-top: 0.8rem; - padding-bottom: 0.8rem; - border-top: 1px solid var(--mht-line-soft); - vertical-align: middle; -} -.mht-compare > tbody > tr:first-child > :is(th, td) { border-top: 0; } -.mht-program-row:hover > *, -.mht-program-row[data-open] > * { background: var(--mht-panel-2); } -.mht-program-row > th { padding-right: 1rem; color: var(--mht-ink); font-weight: 600; text-align: left; } -.mht-program-row[data-status="cleared"] > th { box-shadow: inset 3px 0 0 var(--mht-good); } -.mht-program-row[data-status="close"] > th { box-shadow: inset 3px 0 0 var(--mht-warn); } -.mht-program-row[data-status="short"] :is(.mht-program-toggle, td) { color: var(--mht-muted); } -.mht-program-row > td { - color: var(--mht-ink); - font-family: var(--mht-num); - font-size: 0.95rem; - font-variant-numeric: tabular-nums; - white-space: nowrap; -} -.mht-program-row > td strong { font-weight: 600; } -.mht-program-toggle { - position: static; - display: flex; - align-items: baseline; - gap: 0.6rem; - width: 100%; - padding: 0; - border: 0; - background: none; - color: inherit; - font: inherit; - font-weight: 600; - line-height: 1.35; - text-align: left; - cursor: pointer; -} -.mht-program-toggle::after { content: ""; position: absolute; inset: 0; } -.mht-program-toggle::before { - content: ""; - flex: 0 0 auto; - width: 0.38rem; - height: 0.38rem; - margin-bottom: 0.12rem; - border-right: 1.5px solid var(--mht-muted); - border-bottom: 1.5px solid var(--mht-muted); - transform: rotate(-45deg); - transition: transform 0.15s ease; -} -.mht-program-toggle[aria-expanded="true"]::before { transform: rotate(45deg); } -/* The row verdict moves under the program name once the "vs you" column is hidden. */ -.mht-program-meta { - display: none; - flex-wrap: wrap; - align-items: center; - gap: 0.3rem 0.6rem; - margin: 0.2rem 0 0 0.98rem; - color: var(--mht-muted); - font-family: var(--mht-num); - font-size: 0.75rem; - font-variant-numeric: tabular-nums; - font-weight: 400; -} - -/* Percentile scale: one shared axis, with the reader's score as a line through every row. */ -.mht-bar { position: relative; height: 1.25rem; pointer-events: none; } -.mht-bar::before { - content: ""; - position: absolute; - top: 50%; - left: 0; - right: 0; - height: 2px; - margin-top: -1px; - border-radius: 2px; - background: var(--mht-line); -} -.mht-bar-fill { - position: absolute; - top: 50%; - left: 0; - height: 2px; - margin-top: -1px; - border-radius: 2px; - background: var(--mht-muted); - opacity: 0.55; -} -.mht-bar-dot { - position: absolute; - top: 50%; - width: 0.7rem; - height: 0.7rem; - border: 2px solid var(--mht-panel); - border-radius: 999px; - background: var(--mht-ink); - transform: translate(-50%, -50%); -} -.mht-bar[data-status="cleared"] .mht-bar-dot { background: var(--mht-good); } -.mht-bar[data-status="close"] .mht-bar-dot { background: var(--mht-warn); } -.mht-bar[data-status="short"] .mht-bar-dot { background: var(--mht-muted); } -.mht-bar-you { - position: absolute; - top: calc(-0.8rem - 1px); - bottom: -0.8rem; - width: 2px; - margin-left: -1px; - background: var(--mht-accent); - opacity: 0.85; -} - -/* Program detail: every seat pool, grouped by category */ -.mht-compare-pools > td { padding: 0 1.25rem; border-top: 0; text-align: left; white-space: normal; } -.mht-compare-pools details[open] { padding: 0.25rem 0 1.25rem; } -.mht-detail { - padding: 1rem 1.25rem 1.25rem; - border: 1px solid var(--mht-line); - border-radius: 14px; - background: var(--mht-bg); -} -.mht-detail-head { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 0.5rem 1.25rem; - padding-bottom: 0.85rem; - border-bottom: 1px solid var(--mht-line-soft); - color: var(--mht-muted); - font-size: 0.8125rem; -} -.mht-detail-code { display: inline-flex; align-items: center; gap: 0.4rem; } -.mht-detail-code strong { color: var(--mht-ink); font-family: var(--mht-mono); font-weight: 600; } -.mht-detail-count { margin-left: auto; } -.mht-family-grid { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(min(100%, 23rem), 1fr)); - gap: 1rem 1.5rem; - margin-top: 1rem; -} -.mht-family h4 { - margin-bottom: 0.3rem; - padding: 0 0.5rem; - color: var(--mht-muted); - font-size: 0.7rem; - font-weight: 600; - letter-spacing: 0.06em; - text-transform: uppercase; -} -.mht-family ul { margin: 0; padding: 0; list-style: none; } -.mht-family li { - display: flex; - align-items: baseline; - gap: 0.75rem; - padding: 0.4rem 0.5rem; - border-radius: 8px; - font-size: 0.875rem; -} -.mht-family li[data-current] { background: var(--mht-accent-wash); } -.mht-pool-name { flex: 1; min-width: 6.5rem; color: var(--mht-ink-soft); } -.mht-pool-name .mht-chip { min-height: 1.15rem; margin-left: 0.4rem; padding: 0 0.45rem; font-size: 0.66rem; vertical-align: 1px; } -.mht-pool-name small { - display: block; - color: var(--mht-muted); - font-family: var(--mht-mono); - font-size: 0.7rem; -} -.mht-pool-num { - flex: none; - min-width: 4.5rem; - color: var(--mht-ink); - font-family: var(--mht-num); - font-size: 0.875rem; - font-variant-numeric: tabular-nums; - text-align: right; - white-space: nowrap; -} -.mht-pool-rank { min-width: 3.5rem; font-weight: 600; } -.mht-pool-num .mht-verdict { min-width: 0; padding: 0.05rem 0.4rem; font-size: 0.72rem; } -.mht-family li[data-status="short"] .mht-pool-num:not(:last-child) { color: var(--mht-muted); } - /* All-categories grid */ .mht-grid-scroll { margin-top: 0.5rem; overflow-x: auto; overscroll-behavior-x: contain; } .mht-grid-scroll:focus-visible { outline-offset: -2px; } @@ -351,7 +124,7 @@ .mht-grid tbody th { color: var(--mht-ink); font-weight: 600; line-height: 1.35; } .mht-grid tbody tr:first-child > * { border-top: 0; } .mht-grid td { - min-width: 4.25rem; + min-width: 3.75rem; background-color: color-mix(in srgb, var(--mht-accent) calc(var(--heat, 0) * 30%), transparent); font-family: var(--mht-num); font-variant-numeric: tabular-nums; @@ -364,6 +137,15 @@ .mht-grid td[data-status="cleared"] .mht-grid-pct { color: var(--mht-good); } .mht-grid td[data-status="close"] .mht-grid-pct { color: var(--mht-warn); } .mht-grid td[data-status="short"] > * { opacity: 0.5; } +.mht-grid-code { + display: flex; + align-items: center; + gap: 0.1rem; + color: var(--mht-muted); + font-family: var(--mht-mono); + font-size: 0.72rem; + font-weight: 400; +} @media (min-width: 768px) { /* The controls follow the reader down long tables. */ @@ -377,16 +159,8 @@ } } -.mht-inline-rank { display: none; } .mht-grid-hint { display: none; padding: 0.5rem 1rem 0; color: var(--mht-muted); font-size: 0.75rem; } -/* Pool rows span every column, so narrow layouts collapse columns to zero width - instead of removing them. */ -@container mht-cutoff (max-width: 860px) { - .mht-compare > :is(thead, tbody) > tr > .mht-c-bar { width: 0; padding: 0; overflow: hidden; } - .mht-compare .mht-c-bar > * { display: none; } -} - @container mht-cutoff (max-width: 600px) { .mht-xbar { padding: 0.9rem 1rem; } .mht-score { @@ -402,39 +176,13 @@ .mht-score .mht-seg { margin: 0 0 0.15rem -0.6rem; } .mht-seat-pills { min-width: 0; } .mht-xbar-tools { flex: 1 1 100%; margin-left: 0; } - .mht-xbar-tools .mht-seg { flex: 1 1 auto; } - .mht-xbar-tools .mht-seg button { flex: 1; } .mht-legend { margin-left: 0; } .mht-xstatus { padding: 0.9rem 1rem 0.25rem; } - .mht-compare > :is(thead, tbody) > tr > :is(.mht-c-you, .mht-c-rank) { - width: 0; - padding: 0; - overflow: hidden; - font-size: 0; - } - .mht-compare :is(.mht-c-you, .mht-c-rank) > * { display: none; } - .mht-inline-rank { display: block; color: var(--mht-muted); font-size: 0.75rem; font-weight: 600; } - .mht-program-meta { display: flex; } - .mht-compare > :is(thead, tbody) > tr > .mht-c-pct { width: 6.75rem; padding-right: 1rem; } - .mht-compare { font-size: 0.9rem; } - .mht-program-row > td { font-size: 0.875rem; } - .mht-compare > :is(thead, tbody) > tr > :first-child { padding-left: 1rem; } - .mht-compare-pools > td { padding: 0 0.6rem; } - .mht-detail { padding: 0.85rem 0.75rem 1rem; } - .mht-detail-count { margin-left: 0; } - .mht-family li { flex-wrap: wrap; row-gap: 0.15rem; } - .mht-family .mht-pool-name { flex: 1 1 100%; } - .mht-family .mht-pool-name + .mht-pool-num { margin-left: auto; } .mht-kbd { display: none; } .mht-grid tr > :first-child { min-width: 9.5rem; padding-left: 1rem; } .mht-grid-hint { display: block; } } -@container mht-cutoff (max-width: 400px) { - .mht-program-row .mht-dim { display: none; } - .mht-compare > :is(thead, tbody) > tr > .mht-c-pct { width: 5rem; } -} - /* ---------- Source ---------- */ .mht-source { display: grid; grid-template-columns: 1fr; } .mht-source > div { display: flex; flex-direction: column; gap: 0.5rem; padding: 1.5rem; } diff --git a/components/jee-cutoffs/JeeYearExplorer.tsx b/components/jee-cutoffs/JeeYearExplorer.tsx index f56477d2..19add1fc 100644 --- a/components/jee-cutoffs/JeeYearExplorer.tsx +++ b/components/jee-cutoffs/JeeYearExplorer.tsx @@ -1,7 +1,6 @@ "use client"; import { - Fragment, useEffect, useId, useMemo, @@ -12,18 +11,13 @@ import { import { useRouter } from "next/navigation"; import Link from "next/link"; import MhtPill from "@/components/admissions/MhtPill"; -import CutoffChart from "./CutoffChart"; import { compareMhtCetScore, - describeMhtCetMargin, - formatMhtCetMargin, rankHeat, type MhtCetScore, - type MhtCetVerdict, } from "@/lib/admissions/mht-cet-score"; import type { CounsellingBody, - CutoffChartPoint, CutoffSelection, JeeExamId, } from "@/lib/jee-cutoffs/types"; @@ -38,7 +32,6 @@ import { quotaLabel, } from "@/lib/jee-cutoffs/labels"; -type Mode = "grid" | "seat"; type Sort = "rank" | "name"; type Slice = { body: CounsellingBody; @@ -49,7 +42,8 @@ type Slice = { }; type Cell = { opening: number; closing: number; pool: YearPool }; -const MODE_STORAGE_KEY = "deetnuts:jee-cutoff-mode:v1"; +// Left behind by the removed table switch. +const RETIRED_MODE_STORAGE_KEY = "deetnuts:jee-cutoff-mode:v1"; const SEAT_STORAGE_KEY = "deetnuts:jee-seat:v1"; // JoSAA ranks each category seat against that category's rank list. @@ -92,16 +86,6 @@ function parseRank(text: string): MhtCetScore | null { return value >= 1 && value <= 2_000_000 ? { mode: "rank", value } : null; } -function Verdict({ verdict }: { verdict: MhtCetVerdict | null }) { - if (!verdict) return —; - return ( - - - {describeMhtCetMargin(verdict, "rank")} - - ); -} - type SeatMemory = Partial< Record< JeeExamId, @@ -182,8 +166,6 @@ export function JeeYearExplorer({ gender: initial.gender, seatType: initial.seatType, })); - const [openId, setOpenId] = useState(null); - const [mode, setMode] = useState("grid"); const [sort, setSort] = useState("rank"); const [query, setQuery] = useState(""); const [rankText, setRankText] = useState(""); @@ -237,12 +219,7 @@ export function JeeYearExplorer({ return { body, round, quota, gender, seatType }; }; - const writeHash = ( - next: Slice, - nextOpen: string | null, - nextMode: Mode, - push: boolean, - ) => { + const writeHash = (next: Slice) => { const params = new URLSearchParams({ body: next.body, round: String(next.round), @@ -250,13 +227,7 @@ export function JeeYearExplorer({ seatType: next.seatType, gender: next.gender, }); - if (nextOpen) params.set("offering", nextOpen); - if (nextMode === "seat") params.set("view", "seat"); - history[push ? "pushState" : "replaceState"]( - null, - "", - `${location.pathname}#${params}`, - ); + history.pushState(null, "", `${location.pathname}#${params}`); }; const update = (next: Partial) => { @@ -272,9 +243,11 @@ export function JeeYearExplorer({ seatType: resolved.seatType, gender: resolved.gender, }); - setRankText(readSeatMemory()[exam]?.ranks?.[resolved.seatType] ?? ""); + const rank = readSeatMemory()[exam]?.ranks?.[resolved.seatType] ?? ""; + setRankText(rank); + if (!rank) setOnlyCleared(false); } - writeHash(resolved, openId, mode, true); + writeHash(resolved); }; useEffect(() => { @@ -289,8 +262,6 @@ export function JeeYearExplorer({ gender: hash.get("gender") ?? undefined, seatType: hash.get("seatType") ?? undefined, }), - open: hash.get("offering"), - mode: hash.get("view") === "seat" ? ("seat" as const) : null, }; }; const memory = readSeatMemory()[exam]; @@ -303,14 +274,12 @@ export function JeeYearExplorer({ gender: memory?.gender ?? state.slice.gender, }); setSlice(restored); - setOpenId(state.open); setRankText(memory?.ranks?.[restored.seatType] ?? ""); - setMode( - state.mode ?? - (window.localStorage.getItem(MODE_STORAGE_KEY) === "seat" - ? "seat" - : "grid"), - ); + try { + window.localStorage.removeItem(RETIRED_MODE_STORAGE_KEY); + } catch { + // Nothing to clear without storage. + } const atAnchor = () => Boolean(anchorId) && location.hash === `#${anchorId}`; @@ -324,10 +293,7 @@ export function JeeYearExplorer({ rankRef.current?.focus({ preventScroll: true }); return; } - const next = fromHash(); - setSlice(next.slice); - setOpenId(next.open); - if (next.mode) setMode(next.mode); + setSlice(fromHash().slice); }; const focusSearch = (event: KeyboardEvent) => { if ( @@ -410,10 +376,7 @@ export function JeeYearExplorer({ cell, paperTwo, verdict, - visible: - matches && - (mode === "grid" || cell !== null) && - (!onlyCleared || verdict?.status === "cleared"), + visible: matches && (!onlyCleared || verdict?.status === "cleared"), }; }); listed.sort((a, b) => { @@ -463,36 +426,6 @@ export function JeeYearExplorer({ : `${degree} · ${duration} years`; }; - const chartFor = (index: number): CutoffChartPoint[] => { - const maxRound = rounds.at(-1) ?? 1; - const matching = bodyRows.filter( - (row) => - row.program === index && - row.pool.quota === slice.quota && - row.pool.gender === slice.gender && - row.pool.seatType === slice.seatType, - ); - return Array.from({ length: maxRound }, (_, offset) => { - const row = matching.find((candidate) => candidate.round === offset + 1); - return { - label: `R${offset + 1}`, - round: offset + 1, - openingRank: row?.opening ?? null, - closingRank: row?.closing ?? null, - }; - }); - }; - - const changeMode = (next: Mode) => { - setMode(next); - window.localStorage.setItem(MODE_STORAGE_KEY, next); - writeHash(slice, openId, next, false); - }; - const toggleProgram = (id: string) => { - const next = openId === id ? null : id; - setOpenId(next); - writeHash(slice, next, mode, false); - }; const changeRank = (text: string) => { setRankText(text); writeSeatMemory(exam, { rank: [slice.seatType, text.trim()] }); @@ -505,7 +438,6 @@ export function JeeYearExplorer({
@@ -645,8 +577,8 @@ export function JeeYearExplorer({ / -
- {score && mode === "seat" ? ( + {score && compared.length > 0 ? ( +
- ) : null} -
- -
-
+ ) : null}
@@ -711,11 +627,8 @@ export function JeeYearExplorer({ {visibleCount === 0 ? (
-

- {search - ? `No program matches “${query.trim()}”.` - : `No ${slice.seatType} seats in this round.`} -

+ {/* With only the filter active, the status line above already says "Clears 0 of N". */} + {search ?

No program matches “{query.trim()}”.

: null}
{search ? ( - ) : onlyCleared ? ( + ) : null} + {onlyCleared ? ( - ) : ( - - )} + ) : null}
) : null} - {mode === "seat" ? ( + {columns.length > 3 ? ( + + ) : null} +
); } diff --git a/components/jee-cutoffs/jee.css b/components/jee-cutoffs/jee.css index 1ae334c7..e6ccfaf9 100644 --- a/components/jee-cutoffs/jee.css +++ b/components/jee-cutoffs/jee.css @@ -86,11 +86,9 @@ font-size: 0.75rem; font-weight: 400; } -.jee-explorer .mht-program-toggle > span { min-width: 0; } .jee-grid tbody th a { color: inherit; text-decoration: none; } .jee-grid tbody th a:hover { text-decoration: underline; text-underline-offset: 3px; } -.jee-grid tbody tr[data-current] > th { box-shadow: inset 3px 0 0 var(--mht-accent); } .jee-grid td:has(.jee-cell) { padding: 0; } .jee-cell { display: block; @@ -103,12 +101,6 @@ .jee-grid .mht-grid-rank { color: var(--mht-ink-soft); } .jee-grid tr > td:last-child .jee-cell { padding-right: 1.25rem; } -.jee-detail { margin-bottom: 0.25rem; } -.jee-detail .mht-detail-head { margin-bottom: 0.75rem; } -.jee-detail-links { display: inline-flex; gap: 1rem; } -.jee-detail-links a { color: var(--mht-ink); font-weight: 500; text-decoration: none; } -.jee-detail-links a:hover { text-decoration: underline; text-underline-offset: 3px; } - .jee-years { display: flex; flex-wrap: wrap; gap: 0.4rem; margin-top: 1rem; } .jee-years .mht-chip { text-decoration: none; } .jee-years .mht-chip:hover { color: var(--mht-ink); } diff --git a/e2e/jee-cutoffs.spec.ts b/e2e/jee-cutoffs.spec.ts index 3c9c3cc1..392fbe02 100644 --- a/e2e/jee-cutoffs.spec.ts +++ b/e2e/jee-cutoffs.spec.ts @@ -74,9 +74,7 @@ test("filters cascade, persist in the fragment, and support browser history", as }); test("chart hover shows the exact opening and closing ranks", async ({ page }) => { - await page.goto(pagePath); - await page.getByRole("button", { name: "Your seat" }).click(); - await page.locator(".mht-program-toggle").first().click(); + await page.goto(collegePath); const chart = page.locator(".jee-chart svg").first(); await chart.waitFor({ state: "attached" }); await chart.hover(); diff --git a/lib/admissions/data.ts b/lib/admissions/data.ts index dcb7d524..7b681005 100644 --- a/lib/admissions/data.ts +++ b/lib/admissions/data.ts @@ -185,6 +185,46 @@ const getCachedMhtCetMasterCollege = unstable_cache( { revalidate: 60 * 60 * 24 }, ); +const SEAT_MATRIX_TEXT_FIELDS = [ + "id", + "college_code", + "choice_code", + "course_name", + "seat_type", +] as const; +const SEAT_MATRIX_COUNT_FIELDS = [ + "SI", + "MS_seats", + "all_india", + "institute_seats", + "minority_seats", + "CAP_seats", + "Total", + "OPEN_General", + "OPEN_Ladies", + "SC_General", + "SC_Ladies", + "ST_General", + "ST_Ladies", + "VJ_DT_General", + "VJ_DT_Ladies", + "NTB_General", + "NTB_Ladies", + "NTC_General", + "NTC_Ladies", + "NTD_General", + "NTD_Ladies", + "OBC_General", + "OBC_Ladies", + "SEBC_General", + "SEBC_Ladies", + "EWS_seat", + "TFWS_seats", + "DEF_total", + "PWD_total", + "orphan", +] as const satisfies ReadonlyArray; + const getCachedMhtCetSeatMatrix = unstable_cache( async (collegeId: string): Promise => { let data: MhtCetSeatMatrixRow[]; @@ -192,8 +232,7 @@ const getCachedMhtCetSeatMatrix = unstable_cache( data = await getPocketBase() .collection("2024_mht_cet_colleges_seat_matrix") .getFullList({ - fields: - "id,college_code,choice_code,course_name,seat_type,SI,MS_seats,all_india,institute_seats,minority_seats,CAP_seats,Total", + fields: [...SEAT_MATRIX_TEXT_FIELDS, ...SEAT_MATRIX_COUNT_FIELDS].join(","), filter: `(${collegeCodeFilter(collegeId)})`, sort: "course_name", }); @@ -209,16 +248,12 @@ const getCachedMhtCetSeatMatrix = unstable_cache( } return data.map((row) => ({ ...row, - SI: Number(row.SI) || 0, - MS_seats: Number(row.MS_seats) || 0, - all_india: Number(row.all_india) || 0, - institute_seats: Number(row.institute_seats) || 0, - minority_seats: Number(row.minority_seats) || 0, - CAP_seats: Number(row.CAP_seats) || 0, - Total: Number(row.Total) || 0, + ...Object.fromEntries( + SEAT_MATRIX_COUNT_FIELDS.map((field) => [field, Number(row[field]) || 0]), + ), })); }, - ["admissions-v2-mht-seat-matrix"], + ["admissions-v2-mht-seat-matrix-categories"], { revalidate: 60 * 60 * 24 }, ); diff --git a/lib/admissions/fit.ts b/lib/admissions/fit.ts deleted file mode 100644 index b29bab3d..00000000 --- a/lib/admissions/fit.ts +++ /dev/null @@ -1,246 +0,0 @@ -import "server-only"; - -import { - getCachedMhtCetCollegeCutoffs, - type MhtCetCutoffRow, -} from "@/lib/admissions/data"; -import { - calculatePercentileMargin, - calculateRankMargin, - MhtCetAdmissionsProfileSchema, - type FitRequestV1, -} from "@/lib/admissions/profile"; -import type { - FitObservation, - FitResponseV1, - HistoricalFitSummary, -} from "@/lib/admissions/types"; -import { - deriveEligibleSeatPools, - isAllocationSectionEligible, -} from "@/lib/mht-cet/state-cutoffs/candidate-profile"; -import { isRoundAvailableForYear, ROUNDS_BY_YEAR } from "@/lib/mht-cet/state-cutoffs/config"; - -const MAX_FIT_OBSERVATIONS = 200; - -export interface AdmissionsFitRepository { - getMhtCetCollegeCutoffs( - collegeId: string, - year: number, - round: number, - ): Promise; -} - -const liveRepository: AdmissionsFitRepository = { - getMhtCetCollegeCutoffs: getCachedMhtCetCollegeCutoffs, -}; - -function numberOrNull(value: unknown): number | null { - const parsed = Number(value); - return Number.isFinite(parsed) ? parsed : null; -} - -function summarizeHistory( - observations: FitObservation[], - candidateYears: number[], -): HistoricalFitSummary | null { - const years = candidateYears - .map((year) => { - const rows = observations.filter((row) => row.year === year); - const bestMargin = - rows.length > 0 ? Math.max(...rows.map((row) => row.margin)) : null; - return { - year, - comparable: rows.length > 0, - cleared: bestMargin !== null && bestMargin >= 0, - bestMargin, - }; - }) - .sort((a, b) => b.year - a.year); - const comparableYears = years.filter((year) => year.comparable).length; - if (comparableYears === 0) return null; - return { - comparableYears, - clearedYears: years.filter((year) => year.cleared).length, - years, - }; -} - -function fitStatus( - selected: FitObservation[], - total: number, - incomplete = false, -): FitResponseV1["status"] { - if (incomplete) return "partial"; - if (selected.length === 0) return "no-comparable-data"; - return total > MAX_FIT_OBSERVATIONS ? "partial" : "ok"; -} - - -function isMhtRowEligible( - row: MhtCetCutoffRow, - categoryCodes: Set, - minorityInstituteIds: Set, - candidate: Parameters[0], -): boolean { - if (!categoryCodes.has(row.category)) return false; - if ( - !isAllocationSectionEligible( - candidate, - row.seat_allocation_section, - row.institute_home_university_id, - ) - ) { - return false; - } - if (row.category !== "MI") return true; - return Boolean( - row.minority_community_id && - minorityInstituteIds.has(row.minority_community_id), - ); -} - -function mhtFitObservation( - row: MhtCetCutoffRow, - year: number, - round: number, - scoreMode: "rank" | "percentile", - score: number, -): FitObservation | null { - const closing = - scoreMode === "rank" - ? numberOrNull(row.last_rank) - : numberOrNull(row.cutoff_score); - if (closing === null || (scoreMode === "rank" && closing <= 0)) return null; - const margin = - scoreMode === "rank" - ? calculateRankMargin(score, closing) - : calculatePercentileMargin(score, closing); - return { - id: row.id, - programId: row.course_code, - programCode: row.course_code, - programName: row.course_name, - seatPool: `${row.category} · ${row.seat_allocation_section}`, - year, - round, - metric: scoreMode, - candidateValue: score, - closingValue: closing, - margin, - outcome: margin >= 0 ? "cleared" : "missed", - sourceDocument: row.source_pdf, - sourcePage: row.source_page, - sourceUrl: row.source_index_url, - }; -} - -async function evaluateMhtCetFit( - request: FitRequestV1, - repository: AdmissionsFitRepository, -): Promise { - if (request.entity.kind !== "college") { - return { - status: "no-comparable-data", - observations: [], - history: null, - provenance: { - sourceName: "Maharashtra State CET Cell", - year: request.year, - round: request.round, - }, - }; - } - const parsedProfile = MhtCetAdmissionsProfileSchema.safeParse(request.profile); - if (!parsedProfile.success) throw new TypeError("Invalid MHT-CET profile"); - const profile = parsedProfile.data; - const derived = deriveEligibleSeatPools(profile.candidate); - const categories = new Set(derived.categoryCodes); - const minorities = new Set(derived.minorityInstituteIds); - const comparableYears = Object.keys(ROUNDS_BY_YEAR) - .map(Number) - .filter((year) => isRoundAvailableForYear(request.round, year)); - const yearResults = await Promise.allSettled( - comparableYears.map(async (year) => ({ - year, - rows: await repository.getMhtCetCollegeCutoffs( - request.entity.id, - year, - request.round, - ), - })), - ); - const requestedYearResult = yearResults[comparableYears.indexOf(request.year)]; - if (requestedYearResult?.status === "rejected") { - throw requestedYearResult.reason; - } - const rowsByYear = yearResults.flatMap((result) => - result.status === "fulfilled" ? [result.value] : [], - ); - const missingHistoryYears = yearResults.flatMap((result, index) => - result.status === "rejected" ? [comparableYears[index]] : [], - ); - const allObservations = rowsByYear.flatMap(({ year, rows }) => - rows - .filter((row) => - isMhtRowEligible( - row, - categories, - minorities, - profile.candidate, - ), - ) - .map((row) => - mhtFitObservation( - row, - year, - request.round, - profile.scoreMode, - profile.score, - ), - ) - .filter((row): row is FitObservation => Boolean(row)), - ); - const selectedAll = allObservations - .filter((row) => row.year === request.year) - .sort((a, b) => b.margin - a.margin || a.programName.localeCompare(b.programName)); - const bestSelected = selectedAll[0]; - const exactHistoryObservations = bestSelected - ? allObservations.filter( - (observation) => - observation.programId === bestSelected.programId && - observation.seatPool === bestSelected.seatPool && - observation.metric === bestSelected.metric, - ) - : []; - - return { - status: fitStatus( - selectedAll, - selectedAll.length, - missingHistoryYears.length > 0, - ), - observations: selectedAll.slice(0, MAX_FIT_OBSERVATIONS), - history: summarizeHistory(exactHistoryObservations, comparableYears), - provenance: { - sourceName: "Maharashtra State CET Cell", - year: request.year, - round: request.round, - sourceDocument: selectedAll[0]?.sourceDocument, - sourcePage: selectedAll[0]?.sourcePage, - sourceUrl: selectedAll[0]?.sourceUrl, - note: - missingHistoryYears.length > 0 - ? `Compared only with exactly eligible category and allocation pools. Historical source data was unavailable for ${missingHistoryYears.join(", ")}.` - : "Compared only with category and allocation pools derived as exactly eligible from the submitted profile.", - }, - }; -} - - -export async function evaluateAdmissionsFit( - request: FitRequestV1, - repository: AdmissionsFitRepository = liveRepository, -): Promise { - return evaluateMhtCetFit(request, repository); -} diff --git a/lib/admissions/mht-cet-seat-view.ts b/lib/admissions/mht-cet-seat-view.ts index f961c117..3e5d4e08 100644 --- a/lib/admissions/mht-cet-seat-view.ts +++ b/lib/admissions/mht-cet-seat-view.ts @@ -9,11 +9,19 @@ export const MHT_CET_SEAT_SPECIALS = [ { value: "defence", label: "Defence" }, { value: "pwd", label: "PWD" }, { value: "orphan", label: "Orphan" }, + { value: "minority", label: "Minority" }, ] as const; +// Type E (border-area) candidates have no home university, so they compete for +// the seats open to other universities. +export const MHT_CET_NO_HOME_UNIVERSITY = "none"; + const CATEGORY_IDS = MHT_CET_CATEGORY_OPTIONS.map((option) => option.value); const SPECIAL_IDS = MHT_CET_SEAT_SPECIALS.map((option) => option.value); -const UNIVERSITY_IDS = new Set(MHT_CET_HOME_UNIVERSITIES.map((option) => option.id)); +const UNIVERSITY_IDS = new Set([ + ...MHT_CET_HOME_UNIVERSITIES.map((option) => option.id), + MHT_CET_NO_HOME_UNIVERSITY, +]); const HOME_SCOPE = "Home university"; const OTHER_SCOPE = "Other university"; @@ -74,34 +82,7 @@ export function parseMhtCetSeatView(raw: string | null): MhtCetSeatView | null { } } -export function seatViewFromCandidate(candidate: { - categoryId: string; - ladiesSeatEligible: boolean; - homeUniversityId?: string | null; -}): MhtCetSeatView | null { - if (!isCategoryId(candidate.categoryId)) return null; - const homeUniversityId = - candidate.homeUniversityId && UNIVERSITY_IDS.has(candidate.homeUniversityId) - ? candidate.homeUniversityId - : null; - return { - categoryId: candidate.categoryId, - gender: candidate.ladiesSeatEligible ? "ladies" : "general", - homeUniversityId, - special: "none", - }; -} - -export function seatCaption(view: MhtCetSeatView): string { - if (view.special !== "none") { - return MHT_CET_SEAT_SPECIALS.find((option) => option.value === view.special)?.label ?? view.special; - } - const category = - MHT_CET_CATEGORY_OPTIONS.find((option) => option.value === view.categoryId)?.label ?? view.categoryId; - return `${category}, ${view.gender === "ladies" ? "Ladies" : "General"}`; -} - -export function seatCandidates(rows: T[], view: MhtCetSeatView): T[] { +function seatCandidates(rows: T[], view: MhtCetSeatView): T[] { const family = view.special === "none" ? view.categoryId : view.special; const inFamily = rows.filter((row) => row.poolFamily === family); if (view.special !== "none") { @@ -159,17 +140,3 @@ export function matchFamilySeat( : { ...view, special: family as MhtCetSeatSpecial }; return matchProgramSeat(rows, familyView, collegeHomeUniversityId); } - -export function seatPlaceLine( - rows: SeatRow[], - view: MhtCetSeatView, - collegeHomeUniversityId: string | null, -): string { - const pool = seatCandidates(rows, view); - if (pool.length === 0) return "This seat is not published for this college."; - if (!hasHomeSplit(pool)) return "This college has one statewide cutoff."; - if (!view.homeUniversityId) return "Choose your home university."; - return view.homeUniversityId === collegeHomeUniversityId - ? "Your home university" - : "Outside your home university"; -} diff --git a/lib/admissions/profile-codec.ts b/lib/admissions/profile-codec.ts deleted file mode 100644 index a9455692..00000000 --- a/lib/admissions/profile-codec.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { - AdmissionsStoredProfileSchema, - type AdmissionsStoredProfile, -} from "@/lib/admissions/profile"; -import type { AdmissionsSystem } from "@/lib/admissions/types"; - -export const PROFILE_FRAGMENT_PREFIX = "profile=v1."; - -export function getAdmissionsProfileStorageKey(system: AdmissionsSystem): string { - return `deetnuts:admissions-profile:v1:${system}`; -} - -function bytesToBase64Url(bytes: Uint8Array): string { - let binary = ""; - for (const byte of bytes) binary += String.fromCharCode(byte); - return btoa(binary) - .replace(/\+/g, "-") - .replace(/\//g, "_") - .replace(/=+$/g, ""); -} - -function base64UrlToBytes(value: string): Uint8Array { - const padded = value.replace(/-/g, "+").replace(/_/g, "/").padEnd( - Math.ceil(value.length / 4) * 4, - "=", - ); - const binary = atob(padded); - return Uint8Array.from(binary, (character) => character.charCodeAt(0)); -} - -export function encodeAdmissionsProfileFragment( - value: AdmissionsStoredProfile, -): string { - const parsed = AdmissionsStoredProfileSchema.parse(value); - const bytes = new TextEncoder().encode(JSON.stringify(parsed)); - return `${PROFILE_FRAGMENT_PREFIX}${bytesToBase64Url(bytes)}`; -} - -export function decodeAdmissionsProfileFragment( - hash: string, - expectedSystem?: AdmissionsSystem, -): AdmissionsStoredProfile | null { - const normalized = hash.replace(/^#/, ""); - const part = normalized - .split("&") - .find((entry) => entry.startsWith(PROFILE_FRAGMENT_PREFIX)); - if (!part) return null; - const encoded = part.slice(PROFILE_FRAGMENT_PREFIX.length); - if (!encoded || encoded.length > 12_000) return null; - - try { - const json = new TextDecoder().decode(base64UrlToBytes(encoded)); - const parsed = AdmissionsStoredProfileSchema.safeParse(JSON.parse(json)); - if (!parsed.success) return null; - if (expectedSystem && parsed.data.system !== expectedSystem) return null; - return parsed.data; - } catch { - return null; - } -} - -export function decodeAdmissionsDeviceProfile( - value: string | null, - expectedSystem?: AdmissionsSystem, -): AdmissionsStoredProfile | null { - if (!value || value.length > 12_000) return null; - try { - const parsed = AdmissionsStoredProfileSchema.safeParse(JSON.parse(value)); - if (!parsed.success) return null; - if (expectedSystem && parsed.data.system !== expectedSystem) return null; - return parsed.data; - } catch { - return null; - } -} - -export function resolveAdmissionsProfileSources( - hash: string, - deviceValue: string | null, - expectedSystem: AdmissionsSystem, -): { profile: AdmissionsStoredProfile; source: "link" | "device" } | null { - const linked = decodeAdmissionsProfileFragment(hash, expectedSystem); - if (linked) return { profile: linked, source: "link" }; - const stored = decodeAdmissionsDeviceProfile(deviceValue, expectedSystem); - return stored ? { profile: stored, source: "device" } : null; -} - -export function setProfileFragmentInUrl( - currentUrl: URL, - fragment: string | null, -): URL { - const next = new URL(currentUrl.toString()); - const existing = next.hash - .replace(/^#/, "") - .split("&") - .filter(Boolean) - .filter((entry) => !entry.startsWith("profile=")); - if (fragment) existing.push(fragment.replace(/^#/, "")); - next.hash = existing.length > 0 ? existing.join("&") : ""; - return next; -} diff --git a/lib/admissions/profile.ts b/lib/admissions/profile.ts deleted file mode 100644 index bd893a33..00000000 --- a/lib/admissions/profile.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { z } from "zod"; -import { - MhtCetCandidateProfileSchema, -} from "@/lib/mht-cet/state-cutoffs/candidate-profile"; - -export const MhtCetAdmissionsProfileSchema = z - .object({ - scoreMode: z.enum(["rank", "percentile"]), - score: z.number().finite(), - candidate: MhtCetCandidateProfileSchema, - }) - .strict() - .superRefine((profile, context) => { - if ( - profile.scoreMode === "rank" && - (!Number.isInteger(profile.score) || - profile.score < 1 || - profile.score > 1_000_000) - ) { - context.addIssue({ - code: "custom", - path: ["score"], - message: "Rank must be an integer from 1 to 1,000,000", - }); - } - if ( - profile.scoreMode === "percentile" && - (profile.score < 0 || profile.score > 100) - ) { - context.addIssue({ - code: "custom", - path: ["score"], - message: "Percentile must be between 0 and 100", - }); - } - }); - -export const AdmissionsStoredProfileSchema = z - .object({ - version: z.literal(1), - system: z.literal("mht-cet"), - profile: MhtCetAdmissionsProfileSchema, - }) - .strict(); - -export const FitRequestV1Schema = z - .object({ - version: z.literal(1), - system: z.literal("mht-cet"), - entity: z - .object({ - kind: z.literal("college"), - id: z.string().regex(/^\d{1,5}$/), - }) - .strict(), - year: z.number().int().min(2016).max(2100), - round: z.number().int().min(1).max(10), - profile: MhtCetAdmissionsProfileSchema, - }) - .strict(); - -export type MhtCetAdmissionsProfile = z.infer< - typeof MhtCetAdmissionsProfileSchema ->; -export type AdmissionsStoredProfile = z.infer< - typeof AdmissionsStoredProfileSchema ->; -export type FitRequestV1 = z.infer; - -export function calculateRankMargin( - candidateRank: number, - closingRank: number, -): number { - return closingRank - candidateRank; -} - -export function calculatePercentileMargin( - candidatePercentile: number, - closingPercentile: number, -): number { - return candidatePercentile - closingPercentile; -} diff --git a/lib/admissions/types.ts b/lib/admissions/types.ts index 5bfa76d6..a633cd24 100644 --- a/lib/admissions/types.ts +++ b/lib/admissions/types.ts @@ -71,6 +71,29 @@ export interface MhtCetSeatMatrixRow { minority_seats: number; CAP_seats: number; Total: number; + OPEN_General: number; + OPEN_Ladies: number; + SC_General: number; + SC_Ladies: number; + ST_General: number; + ST_Ladies: number; + VJ_DT_General: number; + VJ_DT_Ladies: number; + NTB_General: number; + NTB_Ladies: number; + NTC_General: number; + NTC_Ladies: number; + NTD_General: number; + NTD_Ladies: number; + OBC_General: number; + OBC_Ladies: number; + SEBC_General: number; + SEBC_Ladies: number; + EWS_seat: number; + TFWS_seats: number; + DEF_total: number; + PWD_total: number; + orphan: number; } export interface MhtCetCollegeDetailModel { @@ -91,43 +114,3 @@ export interface MhtCetCollegeDetailModel { } export type AdmissionsDetailModel = MhtCetCollegeDetailModel; - -export type FitOutcome = "cleared" | "missed"; - -export interface FitObservation { - id: string; - programId: string; - programCode: string; - programName: string; - seatPool: string; - year: number; - round: number; - metric: "rank" | "percentile"; - candidateValue: number; - closingValue: number; - margin: number; - outcome: FitOutcome; - sourceDocument?: string | null; - sourcePage?: number | null; - sourceUrl?: string | null; -} - -export interface HistoricalFitYear { - year: number; - comparable: boolean; - cleared: boolean; - bestMargin: number | null; -} - -export interface HistoricalFitSummary { - comparableYears: number; - clearedYears: number; - years: HistoricalFitYear[]; -} - -export interface FitResponseV1 { - status: "ok" | "no-comparable-data" | "partial"; - observations: FitObservation[]; - history: HistoricalFitSummary | null; - provenance: DataProvenance; -}