diff --git a/.env.example b/.env.example index 603c490..1711037 100644 --- a/.env.example +++ b/.env.example @@ -50,3 +50,8 @@ TEST_BASE_URL=http://localhost:3000 # Set automatically by Next.js/npm scripts — you usually don't need to set this yourself. # Not needed by the public site. NODE_ENV=development + +# Authorises the Vercel Cron call that refreshes the first-year tracker cache. +# Vercel sends it as "Authorization: Bearer ". Without it the cron route stays closed. +# Generate any long random string yourself. +CRON_SECRET=your-random-cron-secret diff --git a/app/admin/layout.tsx b/app/admin/layout.tsx index a256995..8b8c839 100644 --- a/app/admin/layout.tsx +++ b/app/admin/layout.tsx @@ -10,7 +10,7 @@ export default function AdminLayout({ children }: { children: ReactNode }) { return ( <> {/* /admin is only reachable by elevated users (proxy + page guard), all of whom can sign off journey milestones. */} - + {children} ); diff --git a/app/admin/page.tsx b/app/admin/page.tsx index f8266e3..907cc5a 100644 --- a/app/admin/page.tsx +++ b/app/admin/page.tsx @@ -76,6 +76,19 @@ export default async function AdminPage() {

+ {can(me, "tracker:view") && ( + +
+

First-year student tracker

+

Open-source progress, blockers and appreciation for every first-year student.

+
+ + + )} + {canManageMembers && ( }) { + const { github } = await params; + return { title: `${decodeURIComponent(github)} · Student tracker` }; +} + +function Stat({ label, value, hint }: { label: string; value: string | number; hint?: string }) { + return ( +
+
{value}
+
{label}
+
+ ); +} + +export default async function StudentTrackerPage({ params }: { params: Promise<{ github: string }> }) { + const { github } = await params; + const session = await getSession(); + if (!session) redirect(`/login?next=/admin/tracker/${github}`); + const me = await getMember(session.usn); + if (!me || me.status !== "approved" || !can(me, "tracker:view")) redirect("/dashboard"); + + const s = await loadStudent(decodeURIComponent(github)); + if (!s) notFound(); + const now = new Date(); + const t = s.totals; + const pct = (n: number | null) => (n === null ? "—" : `${n}%`); + + return ( +
+
+ + +
+ +
+

{s.name}

+ + @{s.github} + +
+ +
+ +
+ + {s.syncedAt ? `PR numbers refreshed ${ageLabel(s.syncedAt, now)}` : `PR numbers from the ${formatDate(s.snapshotDate)} sheet; not yet refreshed from GitHub`} + + + {s.syncError && Last sync failed: {s.syncError}. Showing the previous numbers.} +
+ +
+ + + + + + + + +
+ +
+

What needs doing

+
+
Blocker
{s.blocker ?? "None recorded"}
+
Waiting
{s.waitingDays !== null ? `${s.waitingDays} days on the primary PR` : "—"}
+
Last PR opened
{formatDate(s.lastStudentActivity)}{s.daysSinceActivity !== null && ` (${s.daysSinceActivity}d ago)`}
+
Last maintainer response
{s.daysSinceMaintainer !== null ? `${s.daysSinceMaintainer}d ago` : "None on record"}
+
Suggested next step
{s.recommendation ?? "—"}
+ {s.suggestedMessage &&
Draft message (edit before sending)
{s.suggestedMessage}
} +
+

These suggestions come from the mentorship sheet and may be out of date after a sync.

+
+ +
+

Change since 31 Oct

+

+ {s.progress.summary || "No change recorded."} (PRs {s.progress.prevTotal} → {t.total}, merged {s.progress.prevMerged} → {t.merged} + {s.progress.gradeChange && `, grade ${s.progress.gradeChange}`}) +

+
+ +
+

Pull requests ({s.prs.length})

+ {s.prs.length === 0 ? ( +

No public pull requests on record.

+ ) : ( + + )} +
+ +
+

Appreciation ({s.appreciation.length})

+ {s.appreciation.length === 0 ? ( +

No maintainer appreciation found yet.

+ ) : ( +
    + {s.appreciation.map((a, i) => ( +
  • +

    “{a.comment}”

    +

    + {a.reviewer} · {formatDate(a.date)} · {a.repo}#{a.prNumber ?? ""} +

    +
  • + ))} +
+ )} +
+
+
+ ); +} diff --git a/app/admin/tracker/page.tsx b/app/admin/tracker/page.tsx new file mode 100644 index 0000000..ef70579 --- /dev/null +++ b/app/admin/tracker/page.tsx @@ -0,0 +1,73 @@ +import { redirect } from "next/navigation"; +import Link from "next/link"; +import { ChevronRight } from "lucide-react"; +import { getMember, getSession } from "@/lib/session"; +import { can } from "@/lib/permissions"; +import { loadStudents } from "@/lib/tracker/store"; +import { toRow } from "@/lib/tracker/rows"; +import { summarize } from "@/lib/tracker/summary"; +import { ageLabel, formatDate } from "@/lib/tracker/format"; +import { TrackerDashboard, type FeedItem } from "@/components/tracker/tracker-dashboard"; +import { SyncButton } from "@/components/tracker/sync-button"; + +export const metadata = { title: "Open Source Student Tracker" }; +// Reads Firestore per request so a sync shows up on the next refresh; GitHub is never called from here. +export const dynamic = "force-dynamic"; + +export default async function TrackerPage() { + const session = await getSession(); + if (!session) redirect("/login?next=/admin/tracker"); + const me = await getMember(session.usn); + if (!me || me.status !== "approved" || !can(me, "tracker:view")) redirect("/dashboard"); + + const students = await loadStudents(); + const now = new Date(); + + if (students.length === 0) { + return ( +
+

Open Source Student Tracker

+

+ No first-year data has been imported yet. Run npm run import:tracker -- <export.txt> --commit to load the mentorship workbook. +

+
+ ); + } + + const summary = summarize(students); + const snapshotDate = students.reduce((latest, s) => (s.snapshotDate > latest ? s.snapshotDate : latest), ""); + const synced = students.filter((s) => s.syncedAt).map((s) => s.syncedAt as string).sort(); + const failing = students.filter((s) => s.syncError).length; + + const feed: FeedItem[] = students + .flatMap((s) => s.appreciation.map((a) => ({ github: s.github, name: s.name, reviewer: a.reviewer, comment: a.comment.slice(0, 220), date: a.date, repo: a.repo, url: a.url }))) + .sort((a, b) => (b.date ?? "").localeCompare(a.date ?? "")) + .slice(0, 8); + + return ( +
+
+ + +
+

Open Source Student Tracker

+

+ First-year progress in open source. Numbers describe public GitHub activity only, so a quiet student may be working privately. +

+

+ Imported snapshot {formatDate(snapshotDate)} · {synced.length}/{students.length} students refreshed from GitHub + {synced.length > 0 && ` · latest ${ageLabel(synced[synced.length - 1], now)}`} + {failing > 0 && ` · ${failing} failed their last sync`} +

+ +
+ + +
+
+ ); +} diff --git a/app/api/admin/tracker/sync/route.ts b/app/api/admin/tracker/sync/route.ts new file mode 100644 index 0000000..519b94f --- /dev/null +++ b/app/api/admin/tracker/sync/route.ts @@ -0,0 +1,42 @@ +import { NextResponse, type NextRequest } from "next/server"; +import { z } from "zod"; +import { authErrorResponse, requireCapability } from "@/lib/session"; +import { checkRateLimit } from "@/lib/rate-limit"; +import { syncStale, syncStudent } from "@/lib/tracker/sync"; + +export const maxDuration = 60; + +const Body = z.object({ github: z.string().trim().min(1).max(39).optional() }); + +/** + * A mentor's "refresh" press. Either one student, or the next batch of stale + * ones. Both honour the cache: anything synced recently is skipped, so pressing + * the button repeatedly cannot turn into repeated GitHub calls. + */ +export async function POST(request: NextRequest) { + let actor; + try { + actor = await requireCapability("tracker:view"); + } catch (error) { + return authErrorResponse(error); + } + + const limit = await checkRateLimit("tracker-sync", actor.session.usn, { limit: 12, windowMs: 15 * 60_000 }); + if (!limit.ok) { + return NextResponse.json( + { ok: false, message: `Slow down: try again in ${limit.retryAfterSeconds}s.` }, + { status: 429, headers: { "Retry-After": String(limit.retryAfterSeconds) } }, + ); + } + + const parsed = Body.safeParse(await request.json().catch(() => ({}))); + if (!parsed.success) return NextResponse.json({ ok: false, message: "Invalid request." }, { status: 400 }); + + if (parsed.data.github) { + const result = await syncStudent(parsed.data.github); + if (result === "missing") return NextResponse.json({ ok: false, message: "No such student." }, { status: 404 }); + return NextResponse.json({ ok: result !== "failed", result }); + } + + return NextResponse.json({ ok: true, report: await syncStale() }); +} diff --git a/app/api/cron/tracker-sync/route.ts b/app/api/cron/tracker-sync/route.ts new file mode 100644 index 0000000..29564be --- /dev/null +++ b/app/api/cron/tracker-sync/route.ts @@ -0,0 +1,20 @@ +import { timingSafeEqual } from "node:crypto"; +import { NextResponse, type NextRequest } from "next/server"; +import { syncStale } from "@/lib/tracker/sync"; + +export const maxDuration = 60; + +function authorised(request: NextRequest): boolean { + const secret = process.env.CRON_SECRET; + // No secret configured means the route is closed, never open. + if (!secret) return false; + const given = Buffer.from(request.headers.get("authorization") ?? ""); + const want = Buffer.from(`Bearer ${secret}`); + return given.length === want.length && timingSafeEqual(given, want); +} + +/** Vercel Cron: keeps the tracker cache current without anyone opening the page. */ +export async function GET(request: NextRequest) { + if (!authorised(request)) return NextResponse.json({ ok: false }, { status: 401 }); + return NextResponse.json({ ok: true, report: await syncStale() }); +} diff --git a/app/dashboard/layout.tsx b/app/dashboard/layout.tsx index 019b2ba..1136898 100644 --- a/app/dashboard/layout.tsx +++ b/app/dashboard/layout.tsx @@ -21,7 +21,7 @@ export default async function DashboardLayout({ children }: { children: ReactNod return ( <> - + {children} ); diff --git a/components/dashboard/dashboard-nav.tsx b/components/dashboard/dashboard-nav.tsx index 2c72673..271eb08 100644 --- a/components/dashboard/dashboard-nav.tsx +++ b/components/dashboard/dashboard-nav.tsx @@ -26,6 +26,8 @@ interface NavLink { elevated?: boolean; /** Only for members who can sign off 10 PR Journey milestones. */ reviewer?: boolean; + /** Only for members who can open the first-year tracker (mentors and admins). */ + tracker?: boolean; } const LINKS: NavLink[] = [ @@ -36,6 +38,7 @@ const LINKS: NavLink[] = [ { name: "Members", href: "/dashboard/members", icon: }, { name: "Leaderboard", href: "/dashboard/leaderboard", icon: }, { name: "Sign-offs", href: "/dashboard/journey", icon: , reviewer: true }, + { name: "Tracker", href: "/admin/tracker", icon: , tracker: true }, { name: "Admin", href: "/admin", icon: , elevated: true }, ]; @@ -47,11 +50,11 @@ const LINKS: NavLink[] = [ * Desktop shows a pill row; below `lg` it collapses to a hamburger, since seven * links scrolling sideways on a phone read as clutter. */ -export function DashboardNav({ elevated = false, reviewer = false }: { elevated?: boolean; reviewer?: boolean }) { +export function DashboardNav({ elevated = false, reviewer = false, tracker = false }: { elevated?: boolean; reviewer?: boolean; tracker?: boolean }) { const pathname = usePathname(); const [open, setOpen] = useState(false); - const links = LINKS.filter((link) => (!link.elevated || elevated) && (!link.reviewer || reviewer)); + const links = LINKS.filter((link) => (!link.elevated || elevated) && (!link.reviewer || reviewer) && (!link.tracker || tracker)); const isActive = (href: string) => href === "/dashboard" ? pathname === href : pathname.startsWith(href); diff --git a/components/tracker/status-badge.tsx b/components/tracker/status-badge.tsx new file mode 100644 index 0000000..57f9064 --- /dev/null +++ b/components/tracker/status-badge.tsx @@ -0,0 +1,25 @@ +import { AlertTriangle, CheckCircle2, CircleDashed, Clock, GitPullRequestClosed, MessageSquareWarning, PauseCircle, Hourglass } from "lucide-react"; +import type { ReactNode } from "react"; +import { STATUS_LABELS, type StatusKey } from "@/lib/tracker/types"; + +const STYLES: Record = { + merged: { tone: "bg-green-500/15 text-green-300 border-green-500/30", icon: }, + stuck: { tone: "bg-red-500/15 text-red-300 border-red-500/30", icon: }, + inactive: { tone: "bg-red-500/15 text-red-300 border-red-500/30", icon: }, + "changes-requested": { tone: "bg-yellow-500/15 text-yellow-300 border-yellow-500/30", icon: }, + "follow-up": { tone: "bg-yellow-500/15 text-yellow-300 border-yellow-500/30", icon: }, + "waiting-on-maintainer": { tone: "bg-sky-500/15 text-sky-300 border-sky-500/30", icon: }, + "closed-without-merge": { tone: "bg-neutral-500/15 text-neutral-300 border-neutral-500/30", icon: }, + "no-pr-data": { tone: "bg-neutral-500/15 text-neutral-300 border-neutral-500/30", icon: }, +}; + +/** Colour plus an icon plus the status in words, so colour is never the only cue. */ +export function StatusBadge({ status }: { status: StatusKey }) { + const { tone, icon } = STYLES[status]; + return ( + + {icon} + {STATUS_LABELS[status]} + + ); +} diff --git a/components/tracker/sync-button.tsx b/components/tracker/sync-button.tsx new file mode 100644 index 0000000..c66dc35 --- /dev/null +++ b/components/tracker/sync-button.tsx @@ -0,0 +1,65 @@ +"use client"; + +import { useState } from "react"; +import { useRouter } from "next/navigation"; +import { RefreshCw } from "lucide-react"; + +/** + * Asks the server to refresh from GitHub. The server skips anyone synced + * recently, so pressing this repeatedly is cheap and cannot hammer the API. + */ +export function SyncButton({ github, label }: { github?: string; label: string }) { + const router = useRouter(); + const [busy, setBusy] = useState(false); + const [message, setMessage] = useState(null); + + async function run() { + setBusy(true); + setMessage(null); + try { + const res = await fetch("/api/admin/tracker/sync", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(github ? { github } : {}), + }); + const data = (await res.json().catch(() => ({}))) as { + ok?: boolean; + message?: string; + result?: string; + report?: { updated: number; failed: number; skippedFresh: number; rateLimited: boolean }; + }; + if (!res.ok || data.ok === false) { + setMessage(data.message ?? "Sync failed. The cached numbers are unchanged."); + } else if (data.report) { + const r = data.report; + setMessage( + `${r.updated} updated, ${r.skippedFresh} already fresh${r.failed ? `, ${r.failed} failed` : ""}${r.rateLimited ? ". GitHub is rate limiting; try later." : "."}`, + ); + } else { + setMessage(data.result === "fresh" ? "Already up to date." : "Updated."); + } + router.refresh(); + } catch { + setMessage("Could not reach the server."); + } finally { + setBusy(false); + } + } + + return ( +
+ + + {message} + +
+ ); +} diff --git a/components/tracker/tracker-dashboard.tsx b/components/tracker/tracker-dashboard.tsx new file mode 100644 index 0000000..e10e4cd --- /dev/null +++ b/components/tracker/tracker-dashboard.tsx @@ -0,0 +1,275 @@ +"use client"; + +import { useMemo, useState } from "react"; +import Link from "next/link"; +import { Bar, BarChart, CartesianGrid, Cell, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts"; +import { Search, X, Heart } from "lucide-react"; +import { Avatar } from "@/components/ui/avatar"; +import { StatusBadge } from "@/components/tracker/status-badge"; +import { formatDate } from "@/lib/tracker/format"; +import { filterRows, NO_FILTERS, sortRows, type Filters, type SortKey, type TrackerRow } from "@/lib/tracker/rows"; +import type { CohortSummary } from "@/lib/tracker/summary"; +import { STATUS_LABELS, type Grade, type StatusKey } from "@/lib/tracker/types"; + +export interface FeedItem { + github: string; + name: string; + reviewer: string; + comment: string; + date: string | null; + repo: string; + url: string; +} + +interface Props { + rows: TrackerRow[]; + summary: CohortSummary; + feed: FeedItem[]; + snapshotDate: string; +} + +const PAGE_SIZE = 25; +const STATUS_COLOURS: Record = { + merged: "#4ade80", stuck: "#f87171", inactive: "#ef4444", "changes-requested": "#facc15", + "follow-up": "#fde047", "waiting-on-maintainer": "#38bdf8", "closed-without-merge": "#a3a3a3", "no-pr-data": "#737373", +}; + +interface CardDef { + label: string; + value: string | number; + hint: string; + /** Present only when the card has a matching table filter; the rest are plain tiles. */ + apply?: Partial; +} + +export function TrackerDashboard({ rows, summary, feed, snapshotDate }: Props) { + const [filters, setFilters] = useState(NO_FILTERS); + const [sortKey, setSortKey] = useState("waiting"); + const [dir, setDir] = useState<"asc" | "desc">("desc"); + const [page, setPage] = useState(0); + + const set = (patch: Partial) => { + setFilters((f) => ({ ...f, ...patch })); + setPage(0); + }; + + const cards: CardDef[] = [ + { label: "Students", value: summary.students, hint: "Everyone in the first-year cohort", apply: NO_FILTERS }, + { label: "Opened a PR", value: summary.withPR, hint: "At least one public pull request" }, + { label: "Merged a PR", value: summary.withMerge, hint: `${summary.withCredibleMerge} merged into a credible repo`, apply: { status: "merged" } }, + { label: "Active this week", value: summary.activeThisWeek, hint: `Opened a PR in the 7 days before ${formatDate(snapshotDate)}` }, + { label: "Quiet this week", value: summary.inactiveThisWeek, hint: "May be working privately; not a judgement", apply: { status: "inactive" } }, + { label: "Total PRs", value: summary.totalPRs, hint: `${summary.mergedPRs} merged · ${summary.openPRs} open · ${summary.closedPRs} closed` }, + { label: "Projects", value: summary.projects, hint: "Distinct repositories worked in" }, + { label: "Appreciation", value: summary.appreciation, hint: "Maintainer comments with praise" }, + { label: "Need mentor attention", value: summary.needAttention, hint: "Stuck, inactive, changes requested or follow-up", apply: { attentionOnly: true } }, + ]; + + const visible = useMemo(() => sortRows(filterRows(rows, filters), sortKey, dir), [rows, filters, sortKey, dir]); + + const pages = Math.max(1, Math.ceil(visible.length / PAGE_SIZE)); + const shown = visible.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE); + const dirty = filters.query !== "" || filters.status !== "all" || filters.grade !== "all" || filters.attentionOnly; + + const chart = (Object.keys(STATUS_LABELS) as StatusKey[]).map((k) => ({ key: k, label: STATUS_LABELS[k], count: summary.byStatus[k] })); + const attentionList = rows.filter((r) => r.attention).sort((a, b) => (b.waitingDays ?? 0) - (a.waitingDays ?? 0)).slice(0, 8); + + function sortBy(key: SortKey) { + if (key === sortKey) setDir((d) => (d === "asc" ? "desc" : "asc")); + else { + setSortKey(key); + setDir(key === "name" ? "asc" : "desc"); + } + } + const ariaSort = (key: SortKey) => (key === sortKey ? (dir === "asc" ? "ascending" : "descending") : "none"); + + return ( +
+
+ {cards.map((card) => { + const body = ( + <> +
{card.value}
+
{card.label}
+
{card.hint}
+ + ); + const { apply } = card; + return apply ? ( + + ) : ( +
{body}
+ ); + })} +
+ +
+
+

Where students are

+

Click a bar to filter the table.

+
+ + + + + + + set({ ...NO_FILTERS, status: (d as unknown as { key: StatusKey }).key })} style={{ cursor: "pointer" }}> + {chart.map((d) => )} + + + +
+
    + {chart.map((d) =>
  • {d.label}: {d.count} students
  • )} +
+
+ +
+

Students who may need support

+

Longest wait first. A wait can be on the maintainer, so check before nudging the student.

+ {attentionList.length === 0 ? ( +

Nobody is flagged right now.

+ ) : ( +
    + {attentionList.map((r) => ( +
  • + {r.name} + + {r.waitingDays !== null ? `${r.waitingDays}d waiting` : "no PR waiting"} + + +
  • + ))} +
+ )} +
+
+ +
+

Students

+
+ + + + + {dirty && ( + + )} +
+ +

+ Showing {visible.length} of {rows.length} students +

+ +
+ + + + + + + + + + + + + + + + + {shown.length === 0 && ( + + )} + {shown.map((r) => ( + + + + + + + + + + + + ))} + +
First-year students and their open-source progress
StatusPraiseDetails
No students match these filters.
+
+ +
+
{r.name}
+
@{r.github}
+
+
+
{r.grade ?? "—"}{r.total}{r.merged}{r.waitingDays !== null ? `${r.waitingDays}d` : "—"}{formatDate(r.lastStudentActivity)}{r.appreciation} + View +
+
+ + {pages > 1 && ( + + )} +
+ +
+

Recent appreciation from maintainers

+

Kind words found in review comments, newest first.

+ {feed.length === 0 ? ( +

No appreciation comments yet.

+ ) : ( +
    + {feed.map((f, i) => ( +
  • + {f.name} + · {f.repo} · {formatDate(f.date)} +

    “{f.comment}” — {f.reviewer}

    +
  • + ))} +
+ )} +
+
+ ); +} diff --git a/docs/first-year-tracker.md b/docs/first-year-tracker.md new file mode 100644 index 0000000..494b75b --- /dev/null +++ b/docs/first-year-tracker.md @@ -0,0 +1,31 @@ +# First-year student tracker + +Mentor/admin page at `/admin/tracker` (and `/admin/tracker/` per student) showing first-year open-source progress. Requires the `tracker:view` capability, which mentors and admins (and the President/VP) hold. + +## Where the data lives + +Private, in Firestore collection `devforge_first_year_tracker`, one document per student keyed by lower-cased GitHub handle. It is never written to `data/`, because the repo is public and the records name students who are stuck or inactive. + +## Load the mentorship workbook + +```bash +npm run import:tracker -- /path/to/export.txt # dry run: prints counts and warnings +npm run import:tracker -- /path/to/export.txt --commit # writes to Firestore +``` + +Needs the Firebase variables in `.env.local` (`--commit` only). Keep the export outside the repo. Re-importing replaces the sheet fields and resets `syncedAt`. + +## Caching and live updates + +Page views read Firestore only. They never call GitHub. + +GitHub is called by the sync (`lib/tracker/sync.ts`), from two places: + +- **Cron**: `GET /api/cron/tracker-sync`, every 30 minutes (`vercel.json`). Needs `CRON_SECRET`; without it the route returns 401. Vercel's Hobby plan only allows daily crons, so change the schedule there if needed. +- **Refresh buttons**: `POST /api/admin/tracker/sync` (`tracker:view`, 12 calls per 15 minutes). With `{ "github": "" }` it refreshes one student (skipped if synced in the last 5 minutes); with no body it refreshes the next stale batch. + +Each run refreshes up to 20 students whose cache is older than 3 hours (one search each, oldest first) and stops at the first rate-limit response. A failed fetch keeps the old numbers and records `syncError`; it never turns into zeros. A sync updates PR counts, the PR list and last-activity dates. Status, priority, blocker, recommendation and appreciation come from the sheet and are not re-judged. + +## Known limits + +The workbook has PR data only. Commits, reviews given, weekly reviews, mentor notes, tasks and a per-student consistency score are not in it, so the tracker does not show them. Credible-repo checks on synced PRs use stars and forks only (the workbook also checks open issues and archived status). diff --git a/lib/firebase/collections.ts b/lib/firebase/collections.ts index 07d87cb..8c1aaa4 100644 --- a/lib/firebase/collections.ts +++ b/lib/firebase/collections.ts @@ -28,6 +28,7 @@ export const COLLECTIONS = { rateLimits: "devforge_rate_limits", collabRequests: "devforge_collab_requests", prJourney: "devforge_pr_journey", + firstYearTracker: "devforge_first_year_tracker", } as const; export type ClubCollection = (typeof COLLECTIONS)[keyof typeof COLLECTIONS]; diff --git a/lib/permissions.test.ts b/lib/permissions.test.ts index df3443c..8b07f50 100644 --- a/lib/permissions.test.ts +++ b/lib/permissions.test.ts @@ -8,7 +8,7 @@ describe("capabilitiesFor", () => { it("gives a mentor exactly the mentor capability set", () => { expect(capabilitiesFor({ role: "mentor" })).toEqual( - new Set(["sessions:manage", "projects:manageAny", "journey:review"]), + new Set(["sessions:manage", "projects:manageAny", "journey:review", "tracker:view"]), ); }); @@ -24,6 +24,7 @@ describe("capabilitiesFor", () => { "sessions:manage", "projects:manageAny", "journey:review", + "tracker:view", "members:manage", "roles:manage", ]), @@ -57,3 +58,12 @@ describe("can", () => { } }); }); + +describe("tracker:view", () => { + it("is held by mentors and admins only", () => { + expect(can({ role: "mentor" }, "tracker:view")).toBe(true); + expect(can({ role: "admin" }, "tracker:view")).toBe(true); + expect(can({ role: "member" }, "tracker:view")).toBe(false); + expect(can({ role: "member", councilPosition: "Treasurer" }, "tracker:view")).toBe(false); + }); +}); diff --git a/lib/permissions.ts b/lib/permissions.ts index 59e54a2..102ea8b 100644 --- a/lib/permissions.ts +++ b/lib/permissions.ts @@ -12,6 +12,7 @@ type CapabilityInput = { role: string; councilPosition?: string }; * announcements:send push a notification to all members * projects:manageAny edit or delete any member's project * journey:review sign off 10 PR Journey milestones + * tracker:view see the first-year mentor tracker (blockers, notes, nudges) */ export type Capability = | "members:manage" @@ -19,7 +20,8 @@ export type Capability = | "sessions:manage" | "announcements:send" | "projects:manageAny" - | "journey:review"; + | "journey:review" + | "tracker:view"; export const ALL_CAPABILITIES: Capability[] = [ "members:manage", @@ -28,6 +30,7 @@ export const ALL_CAPABILITIES: Capability[] = [ "announcements:send", "projects:manageAny", "journey:review", + "tracker:view", ]; /** @@ -49,7 +52,7 @@ const POSITION_CAPABILITIES: Record = { }; /** Baseline for a plain mentor (e.g. an off-roster mentor with no council seat). */ -const MENTOR_CAPABILITIES: Capability[] = ["sessions:manage", "projects:manageAny", "journey:review"]; +const MENTOR_CAPABILITIES: Capability[] = ["sessions:manage", "projects:manageAny", "journey:review", "tracker:view"]; export function capabilitiesFor(member: CapabilityInput): Set { // The admin role remains the all-powers safety net (the President holds it). diff --git a/lib/tracker/csv.ts b/lib/tracker/csv.ts new file mode 100644 index 0000000..46f7b4a --- /dev/null +++ b/lib/tracker/csv.ts @@ -0,0 +1,63 @@ +/** + * Minimal RFC-4180 reader: quoted fields, doubled quotes, newlines inside + * quotes, CRLF. Sheet exports carry multi-line cells (a student's repo list is + * one cell with one repo per line), so splitting on "\n" is not an option. + */ +export function parseCsv(text: string): string[][] { + const rows: string[][] = []; + let row: string[] = []; + let field = ""; + let quoted = false; + + for (let i = 0; i < text.length; i++) { + const char = text[i]; + + if (quoted) { + if (char === '"') { + if (text[i + 1] === '"') { + field += '"'; + i++; + } else { + quoted = false; + } + } else { + field += char; + } + continue; + } + + if (char === '"') { + quoted = true; + } else if (char === ",") { + row.push(field); + field = ""; + } else if (char === "\n" || char === "\r") { + if (char === "\r" && text[i + 1] === "\n") i++; + row.push(field); + rows.push(row); + row = []; + field = ""; + } else { + field += char; + } + } + + if (field !== "" || row.length > 0) { + row.push(field); + rows.push(row); + } + return rows; +} + +/** Rows keyed by header. Rows shorter than the header get empty strings. */ +export function parseCsvRecords(text: string): Record[] { + const rows = parseCsv(text); + const header = rows[0] ?? []; + return rows.slice(1).map((cells) => { + const record: Record = {}; + header.forEach((name, index) => { + if (name) record[name] = cells[index] ?? ""; + }); + return record; + }); +} diff --git a/lib/tracker/format.ts b/lib/tracker/format.ts new file mode 100644 index 0000000..8fef00f --- /dev/null +++ b/lib/tracker/format.ts @@ -0,0 +1,18 @@ +/** "2026-11-13" → "13 Nov 2026". Fixed locale and UTC so server and client render the same text. */ +export function formatDate(iso: string | null | undefined): string { + if (!iso) return "—"; + const date = new Date(iso.length === 10 ? `${iso}T00:00:00Z` : iso); + if (Number.isNaN(date.getTime())) return "—"; + return date.toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }); +} + +/** "3h ago" style age for a sync timestamp, relative to `now`. */ +export function ageLabel(iso: string | null, now: Date): string { + if (!iso) return "never synced from GitHub"; + const minutes = Math.max(0, Math.round((now.getTime() - Date.parse(iso)) / 60_000)); + if (minutes < 1) return "just now"; + if (minutes < 60) return `${minutes} min ago`; + const hours = Math.round(minutes / 60); + if (hours < 48) return `${hours}h ago`; + return `${Math.round(hours / 24)}d ago`; +} diff --git a/lib/tracker/parse-sheet.test.ts b/lib/tracker/parse-sheet.test.ts new file mode 100644 index 0000000..0eafcd4 --- /dev/null +++ b/lib/tracker/parse-sheet.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, it } from "vitest"; +import { parseCsv } from "./csv"; +import { parseLongDate, parseSheetExport, statusFromCell } from "./parse-sheet"; + +const STUDENTS = `#,Student Name,GitHub Username,GitHub Profile,PR Grade,GSoC Readiness,Total PRs,Open,Merged,Closed (unmerged),Merged % of PRs,Open % of PRs,Closed % of PRs,Merge success % (of resolved),Credible merges,Credible open PRs,Review feedback handled,PR title hygiene %,PR approvals,Projects count,Projects / repos worked in,Merged PR links,Open PR links,Last student activity,Days since student activity,Last maintainer response,Days since maintainer response,Waiting days (primary PR),Primary blocker,Mentor recommendation,Suggested message,Appreciation highlights +1,Asha Rao,asha-r,https://github.com/asha-r,B,Nearly there,3,1,1,1,33%,33%,33%,50.0%,1,0,0,40.0%,0,2,"org/a +org/b",x,y,2026-11-06,7,,,52,no maintainer response since opening (52d),Post a nudge,"Hi Asha, a message",— +2,Ben Lee,Ben-L,https://github.com/Ben-L,D,No evidence,0,0,0,0,0%,0%,0%,,0,0,0,,0,0,,,,,,,,,no authored PRs,Ask for an issue,,— +`; + +const PROGRESS = `#,Student,GitHub Username,Status,Priority,Total PRs (31 Oct),Total PRs (13 Nov),Merged (31 Oct),Merged (13 Nov),Grade (prev),Grade (now),Grade change,Progress summary +1,Asha Rao,asha-r,🔴 Stuck,Critical,1,3,0,1,C,B,C → B,+2 PRs +2,Ben Lee,ben-l,❓ No PR data,High,0,0,0,0,D,D,No change,No change`; + +const ALL_PRS = `#,Student,GitHub Username,Student Status,Priority,Repo,Org,PR #,Title,State,Created,Merged / Closed on,Last update,Waiting days,Blocker,Draft,Credible repo,Teaching repo,Stars,Forks,Commits in PR,Maintainer comments,Approved,PR link +1,Asha Rao,asha-r,🔴 Stuck,Critical,org/a,org,5,Fix thing,Merged,2026-10-01,2026-10-02,2026-10-02,,—,No,Yes,No,500,600,1,0,No,https://github.com/org/a/pull/5 +2,Asha Rao,asha-r,🔴 Stuck,Critical,org/a,org,5,Fix thing,Merged,2026-10-01,2026-10-02,2026-10-02,,—,No,Yes,No,500,600,1,0,No,https://github.com/org/a/pull/5 +3,Ghost,nobody,x,x,o/r,o,1,t,Open,2026-10-01,,,,—,No,No,No,0,0,1,0,No,https://github.com/o/r/pull/1 +4,Asha Rao,asha-r,x,x,o/r,o,x,bad row,Open,2026-10-01,,,,—,No,No,No,0,0,1,0,No,not-a-url`; + +const APPRECIATION = `#,Student,GitHub Username,Repo,PR #,PR title,PR state,Mentor / reviewer,Role,Date,Type,Praise words found,Comment (verbatim),PR link +1,Asha Rao,asha-r,org/a,5,Fix thing,Merged,maint,MEMBER,2026-10-02,Personal praise,thanks,"Thanks, great fix",https://github.com/org/a/pull/5 +2,Asha Rao,asha-r,org/a,5,Fix thing,Merged,bot,NONE,2026-10-01,Template / automated welcome,welcome,Welcome!,https://github.com/org/a/pull/5`; + +const EXPORT = `## Sheet name: Dashboard +Student Mentorship Dashboard +Cohort snapshot: 13 November 2026 · 2 students + +## Sheet name: Students +${STUDENTS} +## Sheet name: All PRs +${ALL_PRS} +## Sheet name: Mentor Appreciation +${APPRECIATION} +## Sheet name: Monthly Progress +${PROGRESS} +`; + +describe("parseCsv", () => { + it("keeps newlines and commas inside quoted cells and unescapes doubled quotes", () => { + expect(parseCsv('a,"b\nc","d,""e"""\n1,2,3')).toEqual([["a", "b\nc", 'd,"e"'], ["1", "2", "3"]]); + }); +}); + +describe("parseLongDate / statusFromCell", () => { + it("reads long dates", () => expect(parseLongDate("13 November 2026")).toBe("2026-11-13")); + it("rejects unknown months", () => expect(parseLongDate("13 Smarch 2026")).toBeNull()); + it("strips emoji and matches the words", () => { + expect(statusFromCell("🔴 Stuck")).toBe("stuck"); + expect(statusFromCell("🟡 Follow-up needed")).toBe("follow-up"); + expect(statusFromCell("❓ No PR data")).toBe("no-pr-data"); + expect(statusFromCell("something else")).toBeNull(); + }); +}); + +describe("parseSheetExport", () => { + const result = parseSheetExport(EXPORT); + const asha = result.students.find((s) => s.github === "asha-r")!; + + it("reads the snapshot date and every student", () => { + expect(result.snapshotDate).toBe("2026-11-13"); + expect(result.students).toHaveLength(2); + }); + + it("joins tabs on the handle regardless of case", () => { + const ben = result.students.find((s) => s.github === "Ben-L")!; + expect(ben.status).toBe("no-pr-data"); + expect(ben.priority).toBe("High"); + }); + + it("maps counts, percentages and the multi-line repo list", () => { + expect(asha.totals).toMatchObject({ total: 3, merged: 1, open: 1, closed: 1, mergeSuccessPct: 50, projects: 2 }); + expect(asha.repos).toEqual(["org/a", "org/b"]); + expect(asha.waitingDays).toBe(52); + }); + + it("treats empty cells and dashes as null, not zero", () => { + const ben = result.students.find((s) => s.github === "Ben-L")!; + expect(ben.totals.mergeSuccessPct).toBeNull(); + expect(ben.waitingDays).toBeNull(); + expect(ben.lastStudentActivity).toBeNull(); + expect(ben.suggestedMessage).toBeNull(); + }); + + it("does not double count a PR repeated in the export", () => { + expect(asha.prs).toHaveLength(1); + expect(asha.prs[0]).toMatchObject({ state: "merged", credible: true, teaching: false }); + }); + + it("drops unreadable PR rows and PRs for unknown students, with warnings", () => { + expect(result.warnings.some((w) => w.includes("unreadable PR row"))).toBe(true); + expect(result.warnings.some((w) => w.includes('"nobody"'))).toBe(true); + }); + + it("keeps real appreciation and drops greeting-bot templates", () => { + expect(asha.appreciation).toHaveLength(1); + expect(asha.appreciation[0].comment).toBe("Thanks, great fix"); + }); + + it("warns when open + merged + closed disagree with total", () => { + const odd = parseSheetExport(EXPORT.replace("3,1,1,1,33%", "4,1,1,1,33%")); + expect(odd.warnings.some((w) => w.includes("does not equal total"))).toBe(true); + }); + + it("starts with no sync state", () => { + expect(asha.syncedAt).toBeNull(); + expect(asha.syncError).toBeNull(); + }); + + it("refuses an export with no Students tab", () => { + expect(() => parseSheetExport("## Sheet name: Dashboard\nCohort snapshot: 13 November 2026")).toThrow(/Students/); + }); +}); diff --git a/lib/tracker/parse-sheet.ts b/lib/tracker/parse-sheet.ts new file mode 100644 index 0000000..3e65b31 --- /dev/null +++ b/lib/tracker/parse-sheet.ts @@ -0,0 +1,280 @@ +import { parseCsvRecords } from "./csv"; +import { + STATUS_LABELS, + type Grade, + type Priority, + type PRState, + type StatusKey, + type TrackerAppreciation, + type TrackerPR, + type TrackerStudent, +} from "./types"; + +/** + * Turns the mentorship workbook export (every tab concatenated, each under a + * `## Sheet name: ` line) into one record per student. + * + * The workbook is the single source: this reads the tabs it needs and joins + * them on the GitHub handle. Nothing is computed from outside the file, so a + * number on the tracker is always a number somebody can find in the sheet. + */ + +export interface ParseResult { + snapshotDate: string; + students: TrackerStudent[]; + /** Things a person should look at before importing. Never fatal. */ + warnings: string[]; +} + +const MONTHS: Record = { + january: "01", february: "02", march: "03", april: "04", may: "05", june: "06", + july: "07", august: "08", september: "09", october: "10", november: "11", december: "12", +}; + +export function splitSheets(text: string): Record { + const parts = text.split(/^## Sheet name: (.+)$/m); + const sheets: Record = {}; + for (let i = 1; i < parts.length; i += 2) sheets[parts[i].trim()] = parts[i + 1].replace(/^\n+/, ""); + return sheets; +} + +/** "13 November 2026" → "2026-11-13". */ +export function parseLongDate(value: string): string | null { + const match = /(\d{1,2})\s+([A-Za-z]+)\s+(\d{4})/.exec(value); + if (!match) return null; + const month = MONTHS[match[2].toLowerCase()]; + if (!month) return null; + return `${match[3]}-${month}-${match[1].padStart(2, "0")}`; +} + +/** Only real yyyy-mm-dd dates survive; anything else is "no date", not a wrong one. */ +function isoDate(value: string | undefined): string | null { + const v = (value ?? "").trim(); + if (!/^\d{4}-\d{2}-\d{2}$/.test(v)) return null; + return Number.isNaN(Date.parse(v)) ? null : v; +} + +/** Non-negative whole number, or null. Negative or garbled counts are not data. */ +function count(value: string | undefined): number | null { + const v = (value ?? "").trim(); + if (!/^\d+$/.test(v)) return null; + return Number(v); +} + +function percent(value: string | undefined): number | null { + const v = (value ?? "").trim().replace("%", ""); + if (v === "" || !/^\d+(\.\d+)?$/.test(v)) return null; + const n = Number(v); + return n >= 0 && n <= 100 ? n : null; +} + +function text(value: string | undefined): string | null { + const v = (value ?? "").trim(); + return v === "" || v === "—" || v === "-" ? null : v; +} + +function yes(value: string | undefined): boolean { + return (value ?? "").trim().toLowerCase() === "yes"; +} + +const STATUS_BY_WORDS: [RegExp, StatusKey][] = [ + [/no pr data/i, "no-pr-data"], + [/closed without merge/i, "closed-without-merge"], + [/waiting on maintainer/i, "waiting-on-maintainer"], + [/follow-up/i, "follow-up"], + [/changes requested/i, "changes-requested"], + [/inactive/i, "inactive"], + [/stuck/i, "stuck"], + [/merged/i, "merged"], +]; + +export function statusFromCell(value: string | undefined): StatusKey | null { + const v = (value ?? "").trim(); + return STATUS_BY_WORDS.find(([pattern]) => pattern.test(v))?.[1] ?? null; +} + +const PRIORITIES: Priority[] = ["Critical", "High", "Medium", "Low", "Completed"]; + +function priorityFromCell(value: string | undefined): Priority | null { + const v = (value ?? "").trim(); + return PRIORITIES.find((p) => p.toLowerCase() === v.toLowerCase()) ?? null; +} + +function gradeFromCell(value: string | undefined): Grade | null { + const v = (value ?? "").trim().toUpperCase(); + return v === "A" || v === "B" || v === "C" || v === "D" ? v : null; +} + +function prStateFromCell(value: string | undefined): PRState | null { + const v = (value ?? "").trim().toLowerCase(); + return v === "merged" || v === "open" || v === "closed" ? v : null; +} + +/** Handles are matched case-insensitively; GitHub treats them that way too. */ +const key = (github: string) => github.trim().toLowerCase(); + +export function parseSheetExport(raw: string): ParseResult { + const sheets = splitSheets(raw); + const warnings: string[] = []; + + for (const required of ["Students", "Monthly Progress"]) { + if (!sheets[required]) throw new Error(`The export has no "${required}" tab, so it cannot be imported.`); + } + + const snapshotLine = /Cohort snapshot:\s*(\d{1,2}\s+[A-Za-z]+\s+\d{4})/.exec(sheets["Dashboard"] ?? ""); + const notesLine = /Snapshot date,(.+)/.exec(sheets["Notes & Method"] ?? ""); + const snapshotDate = parseLongDate(snapshotLine?.[1] ?? notesLine?.[1] ?? ""); + if (!snapshotDate) throw new Error("Could not find a snapshot date (expected 'Cohort snapshot: 13 November 2026')."); + + const progress = new Map( + parseCsvRecords(sheets["Monthly Progress"]) + .filter((r) => r["GitHub Username"]) + .map((r) => [key(r["GitHub Username"]), r]), + ); + const gsoc = new Map( + parseCsvRecords(sheets["GSoC Shortlist"] ?? "") + .filter((r) => r["GitHub Username"]) + .map((r) => [key(r["GitHub Username"]), r]), + ); + + const prsByStudent = new Map(); + for (const r of parseCsvRecords(sheets["All PRs"] ?? "")) { + const handle = key(r["GitHub Username"] ?? ""); + const state = prStateFromCell(r["State"]); + const number = count(r["PR #"]); + const url = (r["PR link"] ?? "").trim(); + if (!handle || !state || number === null || !/^https:\/\/github\.com\//.test(url)) { + if (handle) warnings.push(`Skipped an unreadable PR row for ${handle} (#${r["#"] ?? "?"}).`); + continue; + } + const list = prsByStudent.get(handle) ?? []; + // The same PR can appear twice if the export is concatenated twice. + if (list.some((p) => p.url === url)) continue; + list.push({ + repo: r["Repo"] ?? "", + number, + title: r["Title"] ?? "", + state, + createdAt: isoDate(r["Created"]), + closedAt: isoDate(r["Merged / Closed on"]), + lastUpdate: isoDate(r["Last update"]), + waitingDays: count(r["Waiting days"]), + blocker: text(r["Blocker"]), + credible: yes(r["Credible repo"]), + teaching: yes(r["Teaching repo"]), + approved: yes(r["Approved"]), + url, + }); + prsByStudent.set(handle, list); + } + + const appreciationByStudent = new Map(); + for (const r of parseCsvRecords(sheets["Mentor Appreciation"] ?? "")) { + const handle = key(r["GitHub Username"] ?? ""); + // Greeting bots are not appreciation; the sheet's own counts leave them out too. + if (!handle || /template|automated/i.test(r["Type"] ?? "")) continue; + const list = appreciationByStudent.get(handle) ?? []; + const url = (r["PR link"] ?? "").trim(); + const comment = (r["Comment (verbatim)"] ?? "").trim(); + if (list.some((a) => a.url === url && a.comment === comment)) continue; + list.push({ + repo: r["Repo"] ?? "", + prNumber: count(r["PR #"]), + prTitle: r["PR title"] ?? "", + reviewer: r["Mentor / reviewer"] ?? "", + reviewerRole: r["Role"] ?? "", + date: isoDate(r["Date"]), + type: r["Type"] ?? "", + comment, + url, + }); + appreciationByStudent.set(handle, list); + } + + const students: TrackerStudent[] = []; + const seen = new Set(); + + for (const r of parseCsvRecords(sheets["Students"])) { + const github = (r["GitHub Username"] ?? "").trim(); + if (!github) continue; + const handle = key(github); + if (seen.has(handle)) { + warnings.push(`Duplicate handle "${github}" in Students; the first row was kept.`); + continue; + } + seen.add(handle); + + const p = progress.get(handle); + const g = gsoc.get(handle); + const status = statusFromCell(p?.["Status"]) ?? statusFromCell(g?.["Status"]); + if (!status) { + warnings.push(`No readable status for ${github}; treated as "No PR data".`); + } + const resolvedStatus: StatusKey = status ?? "no-pr-data"; + const prs = (prsByStudent.get(handle) ?? []).sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? "")); + + const total = count(r["Total PRs"]) ?? 0; + const open = count(r["Open"]) ?? 0; + const merged = count(r["Merged"]) ?? 0; + const closed = count(r["Closed (unmerged)"]) ?? 0; + if (open + merged + closed !== total) { + warnings.push(`${github}: open + merged + closed (${open + merged + closed}) does not equal total PRs (${total}).`); + } + + students.push({ + github, + name: (r["Student Name"] ?? "").trim() || github, + snapshotDate, + status: resolvedStatus, + statusLabel: STATUS_LABELS[resolvedStatus], + priority: priorityFromCell(p?.["Priority"]) ?? priorityFromCell(g?.["Priority"]) ?? "Medium", + grade: gradeFromCell(r["PR Grade"]), + gsocReadiness: (r["GSoC Readiness"] ?? "").trim(), + gsocRank: count(g?.["Rank"]), + gsocScore: count(g?.["Score"]), + gsocNote: text(g?.["Readiness note"]), + totals: { + total, + open, + merged, + closed, + credibleMerges: count(r["Credible merges"]) ?? 0, + credibleOpen: count(r["Credible open PRs"]) ?? 0, + mergeSuccessPct: percent(r["Merge success % (of resolved)"]), + titleHygienePct: percent(r["PR title hygiene %"]), + approvals: count(r["PR approvals"]) ?? 0, + reviewFeedbackHandled: count(r["Review feedback handled"]) ?? 0, + projects: count(r["Projects count"]) ?? 0, + }, + repos: (r["Projects / repos worked in"] ?? "") + .split("\n") + .map((s) => s.trim()) + .filter(Boolean), + lastStudentActivity: isoDate(r["Last student activity"]), + daysSinceActivity: count(r["Days since student activity"]), + daysSinceMaintainer: count(r["Days since maintainer response"]), + waitingDays: count(r["Waiting days (primary PR)"]), + blocker: text(r["Primary blocker"]), + recommendation: text(r["Mentor recommendation"]), + suggestedMessage: text(r["Suggested message"]), + progress: { + prevTotal: count(p?.["Total PRs (31 Oct)"]) ?? 0, + prevMerged: count(p?.["Merged (31 Oct)"]) ?? 0, + prevGrade: gradeFromCell(p?.["Grade (prev)"]), + gradeChange: (p?.["Grade change"] ?? "").trim(), + summary: (p?.["Progress summary"] ?? "").trim(), + }, + prs, + appreciation: (appreciationByStudent.get(handle) ?? []).sort((a, b) => (b.date ?? "").localeCompare(a.date ?? "")), + syncedAt: null, + syncError: null, + }); + } + + const known = new Set(students.map((s) => key(s.github))); + for (const handle of new Set([...prsByStudent.keys(), ...appreciationByStudent.keys()])) { + if (!known.has(handle)) warnings.push(`PR or appreciation rows for "${handle}" match no student and were dropped.`); + } + + return { snapshotDate, students, warnings }; +} diff --git a/lib/tracker/rows.test.ts b/lib/tracker/rows.test.ts new file mode 100644 index 0000000..b8dd527 --- /dev/null +++ b/lib/tracker/rows.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from "vitest"; +import { filterRows, NO_FILTERS, sortRows, toRow, type TrackerRow } from "./rows"; +import { needsAttention, summarize } from "./summary"; +import type { TrackerStudent } from "./types"; + +function s(over: Partial & { github: string }): TrackerStudent { + return { + name: over.github, snapshotDate: "2026-11-13", status: "merged", statusLabel: "Merged", priority: "Completed", grade: "B", + gsocReadiness: "", gsocRank: null, gsocScore: null, gsocNote: null, + totals: { total: 2, open: 0, merged: 2, closed: 0, credibleMerges: 0, credibleOpen: 0, mergeSuccessPct: 100, titleHygienePct: null, approvals: 0, reviewFeedbackHandled: 0, projects: 1 }, + repos: ["org/a"], lastStudentActivity: null, daysSinceActivity: 3, daysSinceMaintainer: null, waitingDays: null, blocker: null, + recommendation: null, suggestedMessage: null, progress: { prevTotal: 0, prevMerged: 0, prevGrade: null, gradeChange: "", summary: "" }, + prs: [], appreciation: [], syncedAt: null, syncError: null, ...over, + }; +} + +const people = [ + s({ github: "ok", name: "Ok Person" }), + s({ github: "stuck1", name: "Stuck One", status: "stuck", priority: "Critical", waitingDays: 80, grade: "D", daysSinceActivity: 40 }), + s({ github: "quiet", name: "Quiet", status: "no-pr-data", priority: "Medium", grade: null, daysSinceActivity: null, totals: { ...s({ github: "x" }).totals, total: 0, merged: 0 } }), +]; + +describe("needsAttention / summarize", () => { + it("flags stuck students and critical priority only", () => { + expect(needsAttention(people[1])).toBe(true); + expect(needsAttention(people[0])).toBe(false); + expect(needsAttention(people[2])).toBe(false); + }); + + it("totals the cohort and counts activity within seven days", () => { + const sum = summarize(people); + expect(sum).toMatchObject({ students: 3, withPR: 2, totalPRs: 4, mergedPRs: 4, activeThisWeek: 1, inactiveThisWeek: 2, needAttention: 1, projects: 1 }); + expect(sum.byStatus.stuck).toBe(1); + expect(sum.byGrade).toEqual({ A: 0, B: 1, C: 0, D: 1 }); + }); + + it("handles an empty cohort", () => { + expect(summarize([])).toMatchObject({ students: 0, totalPRs: 0, needAttention: 0 }); + }); +}); + +describe("filterRows / sortRows", () => { + const rows: TrackerRow[] = people.map(toRow); + + it("searches name, handle, repo and PR titles case-insensitively", () => { + expect(filterRows(rows, { ...NO_FILTERS, query: "STUCK" }).map((r) => r.github)).toEqual(["stuck1"]); + expect(filterRows(rows, { ...NO_FILTERS, query: "org/a" })).toHaveLength(3); + expect(filterRows(rows, { ...NO_FILTERS, query: "zzz" })).toHaveLength(0); + }); + + it("combines status, grade and attention filters", () => { + expect(filterRows(rows, { ...NO_FILTERS, status: "stuck", grade: "D" })).toHaveLength(1); + expect(filterRows(rows, { ...NO_FILTERS, attentionOnly: true })).toHaveLength(1); + expect(filterRows(rows, { ...NO_FILTERS, grade: "A" })).toHaveLength(0); + }); + + it("sorts by waiting days both ways, with unknown waits last when ascending", () => { + expect(sortRows(rows, "waiting", "desc")[0].github).toBe("stuck1"); + expect(sortRows(rows, "waiting", "asc")[2].github).toBe("stuck1"); + }); + + it("sorts names alphabetically and does not mutate its input", () => { + const copy = [...rows]; + expect(sortRows(rows, "name", "asc").map((r) => r.name)).toEqual(["Ok Person", "Quiet", "Stuck One"]); + expect(rows).toEqual(copy); + }); +}); diff --git a/lib/tracker/rows.ts b/lib/tracker/rows.ts new file mode 100644 index 0000000..392f900 --- /dev/null +++ b/lib/tracker/rows.ts @@ -0,0 +1,83 @@ +import { needsAttention } from "./summary"; +import type { Grade, StatusKey, TrackerStudent } from "./types"; + +/** + * What the dashboard table needs per student. The full record, with every PR + * and comment, stays on the server; the browser gets this slim row. + */ +export interface TrackerRow { + github: string; + name: string; + status: StatusKey; + grade: Grade | null; + total: number; + merged: number; + open: number; + credibleMerges: number; + appreciation: number; + waitingDays: number | null; + daysSinceActivity: number | null; + lastStudentActivity: string | null; + attention: boolean; + /** Name, handle, repos and PR titles, lower-cased, for the search box. */ + haystack: string; +} + +export function toRow(s: TrackerStudent): TrackerRow { + return { + github: s.github, + name: s.name, + status: s.status, + grade: s.grade, + total: s.totals.total, + merged: s.totals.merged, + open: s.totals.open, + credibleMerges: s.totals.credibleMerges, + appreciation: s.appreciation.length, + waitingDays: s.waitingDays, + daysSinceActivity: s.daysSinceActivity, + lastStudentActivity: s.lastStudentActivity, + attention: needsAttention(s), + haystack: [s.name, s.github, ...s.repos, ...s.prs.map((p) => p.title)].join("\n").toLowerCase(), + }; +} + +export interface Filters { + query: string; + status: StatusKey | "all"; + grade: Grade | "all"; + attentionOnly: boolean; +} + +export const NO_FILTERS: Filters = { query: "", status: "all", grade: "all", attentionOnly: false }; + +export type SortKey = "name" | "merged" | "total" | "waiting" | "activity" | "grade"; + +export function filterRows(rows: TrackerRow[], f: Filters): TrackerRow[] { + const q = f.query.trim().toLowerCase(); + return rows.filter((r) => { + if (f.status !== "all" && r.status !== f.status) return false; + if (f.grade !== "all" && r.grade !== f.grade) return false; + if (f.attentionOnly && !r.attention) return false; + return !q || r.haystack.includes(q); + }); +} + +export function sortRows(rows: TrackerRow[], key: SortKey, dir: "asc" | "desc"): TrackerRow[] { + const value = (r: TrackerRow): number | string => { + switch (key) { + case "name": return r.name.toLowerCase(); + case "merged": return r.merged; + case "total": return r.total; + case "waiting": return r.waitingDays ?? -1; + case "activity": return r.daysSinceActivity ?? Number.MAX_SAFE_INTEGER; + case "grade": return r.grade ?? "Z"; + } + }; + const sign = dir === "asc" ? 1 : -1; + return [...rows].sort((a, b) => { + const x = value(a), y = value(b); + const c = typeof x === "string" || typeof y === "string" ? String(x).localeCompare(String(y)) : x - y; + return c !== 0 ? sign * c : a.name.localeCompare(b.name); + }); +} diff --git a/lib/tracker/store.ts b/lib/tracker/store.ts new file mode 100644 index 0000000..638c9ab --- /dev/null +++ b/lib/tracker/store.ts @@ -0,0 +1,24 @@ +import { club, COLLECTIONS } from "@/lib/firebase/collections"; +import type { TrackerStudent } from "./types"; + +/** + * Reads the tracker cache. This is the only thing a page view touches: + * Firestore, never GitHub. Fresh data arrives through lib/tracker/sync.ts. + */ +const tracker = () => club(COLLECTIONS.firstYearTracker); + +export const docId = (github: string) => github.trim().toLowerCase(); + +export async function loadStudents(): Promise { + const snap = await tracker().get(); + return snap.docs.map((d) => d.data()).sort((a, b) => a.name.localeCompare(b.name)); +} + +export async function loadStudent(github: string): Promise { + const snap = await tracker().doc(docId(github)).get(); + return snap.exists ? (snap.data() as TrackerStudent) : null; +} + +export async function saveStudent(student: TrackerStudent): Promise { + await tracker().doc(docId(student.github)).set(student); +} diff --git a/lib/tracker/summary.ts b/lib/tracker/summary.ts new file mode 100644 index 0000000..a3b330b --- /dev/null +++ b/lib/tracker/summary.ts @@ -0,0 +1,67 @@ +import type { Grade, StatusKey, TrackerStudent } from "./types"; + +/** Statuses a mentor should look at first. Colour is never the only signal; see the UI. */ +export const ATTENTION_STATUSES: StatusKey[] = ["stuck", "inactive", "changes-requested", "follow-up"]; + +export function needsAttention(s: TrackerStudent): boolean { + return ATTENTION_STATUSES.includes(s.status) || s.priority === "Critical"; +} + +/** Students who have not opened a PR in this window count as inactive this week. */ +export const ACTIVE_WINDOW_DAYS = 7; + +export function isActiveRecently(s: TrackerStudent): boolean { + return s.daysSinceActivity !== null && s.daysSinceActivity <= ACTIVE_WINDOW_DAYS; +} + +export interface CohortSummary { + students: number; + withPR: number; + withMerge: number; + withCredibleMerge: number; + activeThisWeek: number; + inactiveThisWeek: number; + totalPRs: number; + openPRs: number; + mergedPRs: number; + closedPRs: number; + projects: number; + appreciation: number; + needAttention: number; + byStatus: Record; + byGrade: Record; +} + +export function summarize(students: TrackerStudent[]): CohortSummary { + const byStatus = { + merged: 0, stuck: 0, inactive: 0, "changes-requested": 0, "follow-up": 0, + "waiting-on-maintainer": 0, "closed-without-merge": 0, "no-pr-data": 0, + } satisfies Record; + const byGrade: Record = { A: 0, B: 0, C: 0, D: 0 }; + const repos = new Set(); + + const out: CohortSummary = { + students: students.length, withPR: 0, withMerge: 0, withCredibleMerge: 0, activeThisWeek: 0, + inactiveThisWeek: 0, totalPRs: 0, openPRs: 0, mergedPRs: 0, closedPRs: 0, projects: 0, + appreciation: 0, needAttention: 0, byStatus, byGrade, + }; + + for (const s of students) { + byStatus[s.status]++; + if (s.grade) byGrade[s.grade]++; + if (s.totals.total > 0) out.withPR++; + if (s.totals.merged > 0) out.withMerge++; + if (s.totals.credibleMerges > 0) out.withCredibleMerge++; + if (isActiveRecently(s)) out.activeThisWeek++; + else out.inactiveThisWeek++; + out.totalPRs += s.totals.total; + out.openPRs += s.totals.open; + out.mergedPRs += s.totals.merged; + out.closedPRs += s.totals.closed; + out.appreciation += s.appreciation.length; + if (needsAttention(s)) out.needAttention++; + s.repos.forEach((r) => repos.add(r.toLowerCase())); + } + out.projects = repos.size; + return out; +} diff --git a/lib/tracker/sync-logic.test.ts b/lib/tracker/sync-logic.test.ts new file mode 100644 index 0000000..06b756f --- /dev/null +++ b/lib/tracker/sync-logic.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from "vitest"; +import { applyFailure, applyFetched, isCredibleRepo, isOwnRepo, pickStale, type FetchedPR } from "./sync-logic"; +import type { TrackerStudent } from "./types"; + +const NOW = new Date("2026-11-20T10:00:00Z"); + +function student(over: Partial = {}): TrackerStudent { + return { + github: "asha-r", name: "Asha", snapshotDate: "2026-11-13", status: "stuck", statusLabel: "Stuck", priority: "Critical", + grade: "C", gsocReadiness: "Nearly there", gsocRank: null, gsocScore: null, gsocNote: null, + totals: { total: 1, open: 1, merged: 0, closed: 0, credibleMerges: 0, credibleOpen: 0, mergeSuccessPct: null, titleHygienePct: 40, approvals: 2, reviewFeedbackHandled: 1, projects: 1 }, + repos: ["org/a"], lastStudentActivity: "2026-11-06", daysSinceActivity: 7, daysSinceMaintainer: null, waitingDays: 52, + blocker: "no response", recommendation: "nudge", suggestedMessage: "hi", + progress: { prevTotal: 0, prevMerged: 0, prevGrade: null, gradeChange: "", summary: "" }, + prs: [{ repo: "org/a", number: 1, title: "t", state: "open", createdAt: "2026-11-06", closedAt: null, lastUpdate: "2026-11-07", waitingDays: 52, blocker: "no response", credible: false, teaching: false, approved: true, url: "https://github.com/org/a/pull/1" }], + appreciation: [], syncedAt: null, syncError: null, ...over, + }; +} + +const pr = (over: Partial = {}): FetchedPR => ({ + repo: "org/a", number: 1, title: "t", state: "open", createdAt: "2026-11-06", closedAt: null, + url: "https://github.com/org/a/pull/1", stars: 10, forks: 1, ...over, +}); + +describe("repo rules", () => { + it("needs both stars and forks, and never counts teaching repos", () => { + expect(isCredibleRepo("a/b", 200, 300)).toBe(true); + expect(isCredibleRepo("a/b", 5000, 299)).toBe(false); + expect(isCredibleRepo("NST-DEVFORGE/workbook", 9999, 9999)).toBe(false); + }); + it("recognises a student's own repository, case-insensitively", () => { + expect(isOwnRepo("Asha-R/site", "asha-r")).toBe(true); + expect(isOwnRepo("org/site", "asha-r")).toBe(false); + }); +}); + +describe("applyFetched", () => { + it("recomputes counts from what GitHub returned", () => { + const out = applyFetched(student(), [pr({ state: "merged", closedAt: "2026-11-18" }), pr({ number: 2, url: "https://github.com/org/a/pull/2", state: "closed" })], NOW); + expect(out.totals).toMatchObject({ total: 2, merged: 1, closed: 1, open: 0, mergeSuccessPct: 50 }); + }); + + it("keeps mentor-owned fields and PR details it cannot see on GitHub", () => { + const out = applyFetched(student(), [pr()], NOW); + expect(out.status).toBe("stuck"); + expect(out.recommendation).toBe("nudge"); + expect(out.prs[0]).toMatchObject({ approved: true, waitingDays: 52 }); + expect(out.totals.approvals).toBe(2); + }); + + it("clears waiting info once a PR is no longer open", () => { + const out = applyFetched(student(), [pr({ state: "merged" })], NOW); + expect(out.prs[0]).toMatchObject({ waitingDays: null, blocker: null }); + }); + + it("ignores PRs into the student's own repo and duplicates", () => { + const out = applyFetched(student(), [pr(), pr(), pr({ repo: "asha-r/site", url: "https://github.com/asha-r/site/pull/1" })], NOW); + expect(out.prs).toHaveLength(1); + }); + + it("stamps the sync and recomputes days since activity, never moving activity backwards", () => { + const out = applyFetched(student({ lastStudentActivity: "2026-11-15" }), [pr({ createdAt: "2026-11-06" })], NOW); + expect(out.syncedAt).toBe(NOW.toISOString()); + expect(out.lastStudentActivity).toBe("2026-11-15"); + expect(out.daysSinceActivity).toBe(5); + }); + + it("gives null merge success when nothing has resolved", () => { + expect(applyFetched(student(), [pr()], NOW).totals.mergeSuccessPct).toBeNull(); + }); +}); + +describe("applyFailure", () => { + it("changes no numbers and does not mark the cache fresh", () => { + const before = student(); + const out = applyFailure(before, "rate limited"); + expect(out.totals).toEqual(before.totals); + expect(out.syncedAt).toBeNull(); + expect(out.syncError).toBe("rate limited"); + }); +}); + +describe("pickStale", () => { + const hour = 3_600_000; + const at = (h: number) => new Date(NOW.getTime() - h * hour).toISOString(); + const list = [ + student({ github: "fresh", syncedAt: at(1) }), + student({ github: "old", syncedAt: at(10) }), + student({ github: "never", syncedAt: null }), + student({ github: "older", syncedAt: at(20) }), + ]; + + it("skips fresh caches so a refresh does not touch GitHub for them", () => { + expect(pickStale(list, NOW, 3 * hour).map((s) => s.github)).not.toContain("fresh"); + }); + it("orders never-synced first, then oldest", () => { + expect(pickStale(list, NOW, 3 * hour).map((s) => s.github)).toEqual(["never", "older", "old"]); + }); + it("caps the batch", () => { + expect(pickStale(list, NOW, 3 * hour, 2)).toHaveLength(2); + }); +}); diff --git a/lib/tracker/sync-logic.ts b/lib/tracker/sync-logic.ts new file mode 100644 index 0000000..c9f211c --- /dev/null +++ b/lib/tracker/sync-logic.ts @@ -0,0 +1,133 @@ +import type { PRState, TrackerPR, TrackerStudent } from "./types"; + +/** + * The pure half of the GitHub sync: given what GitHub said, produce the record + * to store. No network and no clock of its own, so every rule here is testable + * and a page view can never trigger any of it. + */ + +/** A pull request as the sync sees it, already reduced from the search payload. */ +export interface FetchedPR { + repo: string; + number: number; + title: string; + state: PRState; + /** yyyy-mm-dd */ + createdAt: string; + closedAt: string | null; + url: string; + stars: number; + forks: number; +} + +/** How long a student's cached numbers are trusted before the sync may refetch them. */ +export const SYNC_TTL_MS = 3 * 60 * 60 * 1000; +/** Students per run. One search each against GitHub's 30-a-minute search budget. */ +export const SYNC_BATCH = 20; + +/** Repos the mentors run for teaching; a merge there never counts as credible. */ +const TEACHING_REPOS = new Set(["ssagar1999/our-dev-wall", "newton-priyanshu/dev-sena", "nst-devforge/workbook"]); +/** The workbook's rule for a credible repo (stars and forks; open-issues/archived are not in the search payload). */ +const CREDIBLE_STARS = 200; +const CREDIBLE_FORKS = 300; + +export function isTeachingRepo(repo: string): boolean { + return TEACHING_REPOS.has(repo.toLowerCase()); +} + +export function isCredibleRepo(repo: string, stars: number, forks: number): boolean { + return !isTeachingRepo(repo) && stars >= CREDIBLE_STARS && forks >= CREDIBLE_FORKS; +} + +/** PRs into a student's own repositories are practice, not contribution; the workbook leaves them out too. */ +export function isOwnRepo(repo: string, github: string): boolean { + return repo.split("/")[0]?.toLowerCase() === github.toLowerCase(); +} + +function daysBetween(fromIso: string, to: Date): number { + const from = Date.parse(`${fromIso}T00:00:00Z`); + const toDay = Date.UTC(to.getUTCFullYear(), to.getUTCMonth(), to.getUTCDate()); + return Math.max(0, Math.round((toDay - from) / 86_400_000)); +} + +const isoDay = (date: Date) => date.toISOString().slice(0, 10); + +/** Students whose cache is missing or older than the TTL, oldest first, capped at `limit`. */ +export function pickStale(students: TrackerStudent[], now: Date, ttlMs = SYNC_TTL_MS, limit = SYNC_BATCH): TrackerStudent[] { + const cutoff = now.getTime() - ttlMs; + return students + .filter((s) => s.syncedAt === null || Date.parse(s.syncedAt) < cutoff) + .sort((a, b) => Date.parse(a.syncedAt ?? "1970-01-01") - Date.parse(b.syncedAt ?? "1970-01-01")) + .slice(0, limit); +} + +/** + * The student's record after a successful fetch. + * + * Counts, PR list and activity dates come from GitHub. Everything a mentor or + * the sheet decided — status, priority, blocker, recommendation, appreciation — + * is kept untouched: a sync reports what happened, it does not re-judge anyone. + */ +export function applyFetched(student: TrackerStudent, fetched: FetchedPR[], now: Date): TrackerStudent { + const known = new Map(student.prs.map((p) => [p.url, p])); + const seen = new Set(); + + const prs: TrackerPR[] = []; + for (const f of fetched) { + if (isOwnRepo(f.repo, student.github) || seen.has(f.url)) continue; + seen.add(f.url); + const before = known.get(f.url); + prs.push({ + repo: f.repo, + number: f.number, + title: f.title, + state: f.state, + createdAt: f.createdAt, + closedAt: f.closedAt, + lastUpdate: before?.lastUpdate ?? null, + waitingDays: f.state === "open" ? (before?.waitingDays ?? null) : null, + blocker: f.state === "open" ? (before?.blocker ?? null) : null, + credible: isCredibleRepo(f.repo, f.stars, f.forks), + teaching: isTeachingRepo(f.repo), + approved: before?.approved ?? false, + url: f.url, + }); + } + prs.sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? "")); + + const merged = prs.filter((p) => p.state === "merged"); + const open = prs.filter((p) => p.state === "open"); + const closed = prs.filter((p) => p.state === "closed"); + const resolved = merged.length + closed.length; + + const newest = prs.reduce((latest, p) => (p.createdAt && (!latest || p.createdAt > latest) ? p.createdAt : latest), null); + const lastStudentActivity = + newest && student.lastStudentActivity ? (newest > student.lastStudentActivity ? newest : student.lastStudentActivity) : (newest ?? student.lastStudentActivity); + + return { + ...student, + totals: { + ...student.totals, + total: prs.length, + open: open.length, + merged: merged.length, + closed: closed.length, + credibleMerges: merged.filter((p) => p.credible).length, + credibleOpen: open.filter((p) => p.credible).length, + mergeSuccessPct: resolved === 0 ? null : Math.round((merged.length / resolved) * 1000) / 10, + projects: new Set(prs.map((p) => p.repo)).size, + }, + repos: [...new Set(prs.map((p) => p.repo))].sort(), + prs, + lastStudentActivity, + daysSinceActivity: lastStudentActivity ? daysBetween(lastStudentActivity, now) : null, + snapshotDate: isoDay(now), + syncedAt: now.toISOString(), + syncError: null, + }; +} + +/** A failed fetch changes nothing about the numbers: it only records why they are stale. */ +export function applyFailure(student: TrackerStudent, message: string): TrackerStudent { + return { ...student, syncError: message.slice(0, 300) }; +} diff --git a/lib/tracker/sync.ts b/lib/tracker/sync.ts new file mode 100644 index 0000000..96d9f30 --- /dev/null +++ b/lib/tracker/sync.ts @@ -0,0 +1,86 @@ +import { allPRsFor, GithubError, prState, repoFacts, repoNameFromUrl } from "@/lib/github-prs"; +import { applyFailure, applyFetched, pickStale, SYNC_BATCH, SYNC_TTL_MS, type FetchedPR } from "./sync-logic"; +import { loadStudent, loadStudents, saveStudent } from "./store"; +import type { TrackerStudent } from "./types"; + +/** + * The only code path that spends GitHub API calls for the tracker. + * + * Page views read Firestore. This runs from the cron route and from a mentor's + * explicit "refresh" press, spends at most one search per student, skips anyone + * whose cache is younger than the TTL, and stops the whole batch the moment + * GitHub says it is rate limiting, rather than burning the shared token's + * budget on calls that will fail. + */ + +export interface SyncReport { + checked: number; + updated: number; + failed: number; + skippedFresh: number; + /** True when the batch stopped early because GitHub rate-limited us. */ + rateLimited: boolean; +} + +async function fetchStudent(student: TrackerStudent): Promise { + const searched = await allPRsFor(student.github); + const out: FetchedPR[] = []; + for (const pr of searched) { + const repo = repoNameFromUrl(pr.repository_url); + // repoFacts is cached for an hour across students, so popular repos cost one call. + const facts = await repoFacts(pr.repository_url); + out.push({ + repo, + number: pr.number, + title: pr.title, + state: prState(pr), + createdAt: pr.created_at.slice(0, 10), + closedAt: pr.closed_at ? pr.closed_at.slice(0, 10) : null, + url: pr.html_url, + stars: facts?.stars ?? 0, + forks: facts?.forks ?? 0, + }); + } + return out; +} + +async function syncOne(student: TrackerStudent, now: Date): Promise<"updated" | "failed" | "rate-limited"> { + try { + await saveStudent(applyFetched(student, await fetchStudent(student), now)); + return "updated"; + } catch (error) { + const limited = error instanceof GithubError && (error.status === 403 || error.status === 429); + const message = error instanceof Error ? error.message : "Unknown error"; + // Keep the old numbers; just record why they are stale. + await saveStudent(applyFailure(student, message)); + return limited ? "rate-limited" : "failed"; + } +} + +/** Refreshes whoever's cache has expired, up to one batch. */ +export async function syncStale(now = new Date(), ttlMs = SYNC_TTL_MS, limit = SYNC_BATCH): Promise { + const all = await loadStudents(); + const stale = pickStale(all, now, ttlMs, limit); + const report: SyncReport = { checked: 0, updated: 0, failed: 0, skippedFresh: all.length - stale.length, rateLimited: false }; + + for (const student of stale) { + report.checked++; + const result = await syncOne(student, now); + if (result === "updated") report.updated++; + else report.failed++; + if (result === "rate-limited") { + report.rateLimited = true; + break; + } + } + return report; +} + +/** Refreshes one student unless their cache is younger than `minAgeMs` (default five minutes). */ +export async function syncStudent(github: string, now = new Date(), minAgeMs = 5 * 60_000): Promise<"updated" | "failed" | "fresh" | "missing"> { + const student = await loadStudent(github); + if (!student) return "missing"; + if (student.syncedAt && now.getTime() - Date.parse(student.syncedAt) < minAgeMs) return "fresh"; + const result = await syncOne(student, now); + return result === "updated" ? "updated" : "failed"; +} diff --git a/lib/tracker/types.ts b/lib/tracker/types.ts new file mode 100644 index 0000000..e53664a --- /dev/null +++ b/lib/tracker/types.ts @@ -0,0 +1,124 @@ +/** + * The first-year mentor tracker's record shape. + * + * One document per student in `devforge_first_year_tracker`, keyed by the + * lowercased GitHub handle. It holds mentor-facing material (who is stuck, what + * a maintainer said, a suggested nudge), so it lives in Firestore behind the + * `tracker:view` capability and is never written to a file under data/. + */ + +export type StatusKey = + | "merged" + | "stuck" + | "inactive" + | "changes-requested" + | "follow-up" + | "waiting-on-maintainer" + | "closed-without-merge" + | "no-pr-data"; + +export type Priority = "Critical" | "High" | "Medium" | "Low" | "Completed"; + +export type Grade = "A" | "B" | "C" | "D"; + +export type PRState = "merged" | "open" | "closed"; + +export interface TrackerPR { + repo: string; + number: number; + title: string; + state: PRState; + /** ISO dates (yyyy-mm-dd). `null` when the sheet left the cell empty. */ + createdAt: string | null; + closedAt: string | null; + lastUpdate: string | null; + waitingDays: number | null; + blocker: string | null; + /** Repo passes the credible-repo rule in the sheet's Notes & Method tab. */ + credible: boolean; + /** Teaching repos (our-dev-wall, workbook, ...) never count as credible. */ + teaching: boolean; + approved: boolean; + url: string; +} + +export interface TrackerAppreciation { + repo: string; + prNumber: number | null; + prTitle: string; + reviewer: string; + reviewerRole: string; + date: string | null; + type: string; + comment: string; + url: string; +} + +export interface TrackerTotals { + total: number; + open: number; + merged: number; + closed: number; + credibleMerges: number; + credibleOpen: number; + /** Merged ÷ resolved, 0-100. `null` when nothing has been resolved yet. */ + mergeSuccessPct: number | null; + titleHygienePct: number | null; + approvals: number; + reviewFeedbackHandled: number; + projects: number; +} + +export interface TrackerProgress { + prevTotal: number; + prevMerged: number; + prevGrade: Grade | null; + gradeChange: string; + summary: string; +} + +export interface TrackerStudent { + github: string; + name: string; + /** yyyy-mm-dd of the export every number here is as-of. */ + snapshotDate: string; + status: StatusKey; + statusLabel: string; + priority: Priority; + grade: Grade | null; + gsocReadiness: string; + gsocRank: number | null; + gsocScore: number | null; + gsocNote: string | null; + totals: TrackerTotals; + repos: string[]; + lastStudentActivity: string | null; + daysSinceActivity: number | null; + daysSinceMaintainer: number | null; + waitingDays: number | null; + blocker: string | null; + recommendation: string | null; + suggestedMessage: string | null; + progress: TrackerProgress; + prs: TrackerPR[]; + appreciation: TrackerAppreciation[]; + /** + * When the PR numbers were last refreshed from GitHub. `null` means they are + * still exactly what the imported sheet said. Pages read only this cache; + * GitHub is called by the sync, never by a page view. + */ + syncedAt: string | null; + /** Last failed sync, kept so a stale row explains itself. Cleared on success. */ + syncError: string | null; +} + +export const STATUS_LABELS: Record = { + merged: "Merged", + stuck: "Stuck", + inactive: "Inactive", + "changes-requested": "Changes requested", + "follow-up": "Follow-up needed", + "waiting-on-maintainer": "Waiting on maintainer", + "closed-without-merge": "Closed without merge", + "no-pr-data": "No PR data", +}; diff --git a/package.json b/package.json index 409ce8d..6674dec 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,8 @@ "generate-icons": "tsx scripts/generate-pwa-icons.ts", "set:photo": "tsx scripts/set-photo.ts", "import:cohort": "node scripts/import-cohort-csv.mjs", - "snapshot:oss": "tsx scripts/oss-snapshot.ts" + "snapshot:oss": "tsx scripts/oss-snapshot.ts", + "import:tracker": "tsx scripts/import-tracker-sheet.ts" }, "dependencies": { "bcrypt": "^6.0.0", diff --git a/scripts/import-tracker-sheet.ts b/scripts/import-tracker-sheet.ts new file mode 100644 index 0000000..77d1b27 --- /dev/null +++ b/scripts/import-tracker-sheet.ts @@ -0,0 +1,53 @@ +/** + * Loads the first-year mentorship workbook into Firestore. + * + * npx tsx scripts/import-tracker-sheet.ts # dry run, writes nothing + * npx tsx scripts/import-tracker-sheet.ts --commit # writes devforge_first_year_tracker + * + * The export holds who is stuck, what maintainers said and suggested nudges for + * named students. That is mentor-only material, so it goes to Firestore (read + * behind the tracker:view capability) and never to a file under data/ in this + * public repo. Keep the export itself outside the repo too. + * + * Re-importing replaces the sheet-derived fields and resets syncedAt, so the + * next sync refreshes the numbers from GitHub. + */ +import { config } from "dotenv"; +config({ path: ".env.local" }); + +import { readFileSync } from "node:fs"; +import { parseSheetExport } from "../lib/tracker/parse-sheet"; +import { summarize } from "../lib/tracker/summary"; + +const args = process.argv.slice(2); +const file = args.find((a) => !a.startsWith("--")); +const commit = args.includes("--commit"); + +if (!file) { + console.error("Usage: npx tsx scripts/import-tracker-sheet.ts [--commit]"); + process.exit(1); +} + +async function main() { + const result = parseSheetExport(readFileSync(file!, "utf8")); + const s = summarize(result.students); + + console.log(`Snapshot ${result.snapshotDate}: ${s.students} students, ${s.totalPRs} PRs (${s.mergedPRs} merged, ${s.openPRs} open, ${s.closedPRs} closed), ${s.appreciation} appreciation comments.`); + console.log("By status:", s.byStatus); + for (const w of result.warnings) console.warn("warning:", w); + + if (!commit) { + console.log("Dry run: nothing written. Add --commit to write to Firestore."); + return; + } + + // Imported lazily so a dry run needs no Firebase credentials. + const { saveStudent } = await import("../lib/tracker/store"); + for (const student of result.students) await saveStudent(student); + console.log(`Wrote ${result.students.length} documents to devforge_first_year_tracker.`); +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); diff --git a/vercel.json b/vercel.json index 7e87555..c37db17 100644 --- a/vercel.json +++ b/vercel.json @@ -6,5 +6,11 @@ "**": true } }, - "ignoreCommand": "bash scripts/vercel-ignore-build.sh" + "ignoreCommand": "bash scripts/vercel-ignore-build.sh", + "crons": [ + { + "path": "/api/cron/tracker-sync", + "schedule": "*/30 * * * *" + } + ] }