From 6bf01c61bd5a8b6156a468e0cc8911516699a7bf Mon Sep 17 00:00:00 2001 From: Aqib Nawab Date: Thu, 3 Dec 2026 18:14:51 +0500 Subject: [PATCH] Greet new learners with a 3-tap walkthrough and a plan, not empty progress A new learner now answers three tap-only questions on the home screen (why they are here, which area, where they are now), gets one quick question from that area, then a plan: one course to start with a single "Start lesson 1" button, two other choices, and an optional daily pace. Skip and Back are always there. Answers are saved on the user (firstRun, firstRunAt) through PUT /api/v1/learner/first-run, and the daily pace becomes the study goal. Learners who already began a course, or who were given one by an invite or an organization, never see it. An enrolled course that nobody has opened now shows "Ready to begin" instead of "In progress, 0%". On a learner's first day the course cards drop the empty 0% bars and say how many lessons each course has. Co-Authored-By: Claude Opus 5.5 --- .../src/app/(learn)/(main)/dashboard/page.tsx | 5 +- .../learn/dashboard/first-run-walkthrough.tsx | 519 ++++++++++++++++++ .../learn/dashboard/mentee-dashboard.tsx | 38 +- frontend/src/lib/first-run.ts | 113 ++++ frontend/src/lib/learner-onboarding.ts | 8 +- frontend/src/server/actions/first-run.ts | 14 + frontend/src/shared/api/learner.ts | 18 + frontend/tests/unit/lib/first-run.test.ts | 71 +++ .../20261203180000_first_run/migration.sql | 3 + server/prisma/schema.prisma | 4 + server/src/controllers/learner.ts | 7 + server/src/routes/v1/learner.ts | 2 + .../src/services/learner/dashboard-model.ts | 26 +- server/src/services/learner/first-run.ts | 17 + .../services/learner/load-mentee-dashboard.ts | 5 + server/src/shared/api/learner.ts | 18 + server/src/validations/learner.ts | 12 + server/tests/api/learner.test.ts | 27 +- .../services/learner/dashboard-model.test.ts | 28 +- 19 files changed, 919 insertions(+), 16 deletions(-) create mode 100644 frontend/src/components/learn/dashboard/first-run-walkthrough.tsx create mode 100644 frontend/src/lib/first-run.ts create mode 100644 frontend/src/server/actions/first-run.ts create mode 100644 frontend/tests/unit/lib/first-run.test.ts create mode 100644 server/prisma/migrations/20261203180000_first_run/migration.sql create mode 100644 server/src/services/learner/first-run.ts diff --git a/frontend/src/app/(learn)/(main)/dashboard/page.tsx b/frontend/src/app/(learn)/(main)/dashboard/page.tsx index 40d19b359..86b933fa1 100644 --- a/frontend/src/app/(learn)/(main)/dashboard/page.tsx +++ b/frontend/src/app/(learn)/(main)/dashboard/page.tsx @@ -12,9 +12,10 @@ export default async function MenteeDashboardPage() { await requireLearnSurface(); const model = await serverApiFetch("/api/v1/learner/dashboard"); - // Only load starter catalog courses when the learner has no active courses yet. + // Only load starter catalog courses when the learner has no active courses yet, or when the + // first-run walkthrough will suggest courses. const hasActiveCourse = model.courses.some((course) => course.state !== "DROPPED"); - const starterCourses = hasActiveCourse + const starterCourses = hasActiveCourse && !model.firstRun?.show ? [] : await serverApiFetch<{ courses: CatalogCourseSummary[] }>("/api/v1/catalog") .then((catalog) => withoutGuidedTracks(catalog.courses)) diff --git a/frontend/src/components/learn/dashboard/first-run-walkthrough.tsx b/frontend/src/components/learn/dashboard/first-run-walkthrough.tsx new file mode 100644 index 000000000..679f36d55 --- /dev/null +++ b/frontend/src/components/learn/dashboard/first-run-walkthrough.tsx @@ -0,0 +1,519 @@ +"use client"; + +import { useEffect, useMemo, useRef, useState, useTransition } from "react"; +import { useRouter } from "next/navigation"; +import { + ArrowRight, + BookOpen, + Briefcase, + Check, + Cloud, + Code2, + Compass, + Rocket, + Sparkles, + Sprout, + Users, + type LucideIcon, +} from "lucide-react"; +import type { CatalogCourseSummary } from "@/shared/api/catalog"; +import type { FirstRunGoal, FirstRunLevel } from "@/shared/api/learner"; +import type { CourseCategory } from "@/shared/domain/enums"; +import { COURSE_CATEGORY_INFO } from "@/lib/course-categories"; +import { + GOAL_OPTIONS, + LEVEL_OPTIONS, + PACE_OPTIONS, + TASTE_QUESTIONS, + availableDomains, + recommendCourses, + startHref, +} from "@/lib/first-run"; +import { formatPriceCents } from "@/lib/format-price"; +import { saveFirstRun } from "@/server/actions/first-run"; +import { CourseCover } from "@/components/learn/course-cover"; +import { Dot, type DotMood } from "@/components/brand/dot"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; + +const GOAL_ICONS: Record = { JOB: Briefcase, CAREER: Rocket, CURIOUS: Sparkles, ASSIGNED: Users }; +const LEVEL_ICONS: Record = { NEW: Sprout, SOME: Compass, WORK: Briefcase }; +const DOMAIN_ICONS: Record = { TECH: Code2, CLOUD_DEVOPS: Cloud, SOFT_SKILLS: Users }; + +type Step = "goal" | "domain" | "level" | "taste" | "plan"; + +const LEVEL_REASON: Record = { + NEW: "you are new to it", + SOME: "you have tried a little", + WORK: "you already use it at work", +}; + +/** How long a tapped card stays highlighted before the next question slides in. */ +const ADVANCE_MS = 220; + +export function FirstRunWalkthrough({ name, courses }: { name: string; courses: CatalogCourseSummary[] }) { + const router = useRouter(); + const domains = useMemo( + () => availableDomains(courses, COURSE_CATEGORY_INFO.map((info) => info.value)), + [courses] + ); + // With one area there is nothing to choose, so that tap is skipped. + const steps: Step[] = domains.length > 1 ? ["goal", "domain", "level", "taste", "plan"] : ["goal", "level", "taste", "plan"]; + const questionSteps = steps.filter((step) => step === "goal" || step === "domain" || step === "level"); + + const [step, setStep] = useState("goal"); + const [goal, setGoal] = useState(null); + const [domain, setDomain] = useState(domains.length === 1 ? domains[0]! : null); + const [level, setLevel] = useState(null); + const [picked, setPicked] = useState(null); + const [tasteAnswer, setTasteAnswer] = useState(null); + const [pace, setPace] = useState<5 | 10 | 20 | null>(null); + const [leaving, startLeaving] = useTransition(); + const headingRef = useRef(null); + + useEffect(() => { + headingRef.current?.focus({ preventScroll: true }); + }, [step]); + + const firstName = name.split(" ")[0] || name; + const questionIndex = questionSteps.indexOf(step as (typeof questionSteps)[number]); + + function next() { + const at = steps.indexOf(step); + setPicked(null); + setStep(steps[Math.min(at + 1, steps.length - 1)]!); + } + + function back() { + const at = steps.indexOf(step); + if (at <= 0) return; + setPicked(null); + setTasteAnswer(null); + setStep(steps[at - 1]!); + } + + /** A tap answers and moves on by itself: no Next button. */ + function tap(value: T, save: (value: T) => void) { + if (picked) return; + setPicked(value); + save(value); + window.setTimeout(next, ADVANCE_MS); + } + + function skipAll() { + startLeaving(async () => { + await saveFirstRun({ skipped: true }); + router.refresh(); + }); + } + + function finish(href: string | null) { + if (!goal || !domain || !level) return; + startLeaving(async () => { + await saveFirstRun({ goal, domain, level, dailyMinutes: pace }); + if (href) router.push(href); + else router.refresh(); + }); + } + + const mood: DotMood = step === "plan" ? "cheer" : step === "taste" ? "think" : "wave"; + + return ( +
+
+
+ {questionSteps.map((item, index) => ( + + ))} + {questionIndex >= 0 ? ( + + {questionIndex + 1} of {questionSteps.length} + + ) : null} +
+
+ {steps.indexOf(step) > 0 && step !== "plan" ? ( + + ) : null} + {step !== "plan" ? ( + + ) : null} +
+
+ +
+
+
+ +
+
+ {step === "goal" ? ( + <> +

Hi {firstName}. 3 quick taps and your plan is ready.

+ What brings you here? + + {GOAL_OPTIONS.map((option) => ( + tap(option.value, setGoal)} + /> + ))} + + + ) : null} + + {step === "domain" ? ( + <> + Which area do you want to grow in? + + {domains.map((value) => { + const info = COURSE_CATEGORY_INFO.find((item) => item.value === value)!; + return ( + tap(value, setDomain)} + /> + ); + })} + + + ) : null} + + {step === "level" ? ( + <> + Where are you now? + + {LEVEL_OPTIONS.map((option) => ( + tap(option.value, setLevel)} + /> + ))} + + + ) : null} + + {step === "taste" && domain ? ( + + ) : null} + + {step === "plan" && domain && level && goal ? ( + + ) : null} +
+
+
+
+ ); +} + +function Heading({ children, refEl }: { children: React.ReactNode; refEl: React.RefObject }) { + return ( +

+ {children} +

+ ); +} + +function CardGrid({ children }: { children: React.ReactNode }) { + return
{children}
; +} + +function ChoiceCard({ + icon: Icon, + label, + hint, + selected, + onClick, +}: { + icon: LucideIcon; + label: string; + hint: string; + selected: boolean; + onClick: () => void; +}) { + return ( + + ); +} + +function TasteStep({ + domain, + headingRef, + answer, + onAnswer, + onDone, +}: { + domain: CourseCategory; + headingRef: React.RefObject; + answer: string | null; + onAnswer: (id: string) => void; + onDone: () => void; +}) { + const question = TASTE_QUESTIONS[domain]; + const right = answer === question.correct; + return ( + <> +

One quick question while we build your plan

+ {question.question} +
+ {question.options.map((option) => { + const isAnswer = option.id === question.correct; + const chosen = answer === option.id; + return ( + + ); + })} +
+
+ {answer !== null ? ( +
+

{right ? "Exactly right." : "Good guess. Here is the answer."}

+

{question.reveal}

+ +
+ ) : ( + + )} +
+ + ); +} + +function PlanStep({ + courses, + goal, + domain, + level, + pace, + onPace, + leaving, + onStart, + headingRef, +}: { + courses: CatalogCourseSummary[]; + goal: FirstRunGoal; + domain: CourseCategory; + level: FirstRunLevel; + pace: 5 | 10 | 20 | null; + onPace: (minutes: 5 | 10 | 20 | null) => void; + leaving: boolean; + onStart: (href: string | null) => void; + headingRef: React.RefObject; +}) { + const { main, others, inDomain } = recommendCourses(courses, { domain, level }); + const areaLabel = COURSE_CATEGORY_INFO.find((info) => info.value === domain)?.label ?? "this area"; + const levelText = LEVEL_REASON[level]; + const reason = inDomain + ? `Because you picked ${areaLabel} and ${levelText}.` + : `We are still adding ${areaLabel} courses. This is the best place to start today.`; + + if (!main) { + return ( + <> + You are all set +

New courses are on the way. Open the catalog any time.

+ + + ); + } + + const isFree = main.pricingType === "FREE"; + const meta = [ + main.difficulty, + main.estimatedHours ? `${main.estimatedHours} ${main.estimatedHours === 1 ? "hour" : "hours"}` : null, + `${main.chapterCount} ${main.chapterCount === 1 ? "lesson" : "lessons"}`, + ] + .filter(Boolean) + .join(" · "); + + return ( + <> +

Your plan is ready

+ Start here, {isFree ? "lesson 1 is waiting" : "your best first course"} +

{reason}

+ {goal === "ASSIGNED" ? ( +

+ If your mentor or team sent you an invite link, open it to join their course. Until then, this is a good start. +

+ ) : null} + +
+
+
+ +
+
+
+ + {meta} + + {isFree ? "Free" : formatPriceCents(main.priceCents, main.currency)} + +
+

{main.title}

+ {main.description ?

{main.description}

: null} + +
+
+
+ +
    + + +
  1. + + Make it a habit: +
    + {PACE_OPTIONS.map((option) => ( + + ))} +
    +
  2. +
+ +
+ {others.length ? Or start with: : null} + {others.map((course) => ( + + ))} + +
+ + ); +} + +function PlanMark({ done = false }: { done?: boolean }) { + return ( + + {done ? : null} + + ); +} + +function PlanItem({ label, done = false }: { label: string; done?: boolean }) { + return ( +
  • + + {label} + {done ? (done) : null} +
  • + ); +} diff --git a/frontend/src/components/learn/dashboard/mentee-dashboard.tsx b/frontend/src/components/learn/dashboard/mentee-dashboard.tsx index 6f2700fa1..28ac20669 100644 --- a/frontend/src/components/learn/dashboard/mentee-dashboard.tsx +++ b/frontend/src/components/learn/dashboard/mentee-dashboard.tsx @@ -21,6 +21,7 @@ import { WeeklyQuests } from "@/components/learn/dashboard/weekly-quests"; import { LeagueGoalCard } from "@/components/learn/dashboard/league-goal-card"; import { CourseStageLine, LearningMomentum } from "@/components/learn/dashboard/gamification"; import { StarterOnboarding } from "@/components/learn/dashboard/starter-onboarding"; +import { FirstRunWalkthrough } from "@/components/learn/dashboard/first-run-walkthrough"; import { QuickGoalNudge } from "@/components/learn/dashboard/quick-goal-nudge"; import { showsGameElements } from "@/lib/gamification"; import { dashboardVisibility, getLearnerOnboardingStage, type LearnerOnboardingStage } from "@/lib/learner-onboarding"; @@ -296,7 +297,8 @@ const ACTION_ICONS: Record = { function shortCourseAction(course: DashboardCourse) { if (course.state === "COMPLETED") return "Review"; - if (course.state === "NOT_STARTED" || course.state === "PAYMENT_REQUIRED") return "Open"; + if (course.state === "PAYMENT_REQUIRED") return "Open"; + if (course.state === "NOT_STARTED") return "Start"; return "Continue"; } @@ -354,12 +356,16 @@ function ActionCenter({ actions, hasCourse }: { actions: DashboardAction[]; hasC function CourseListPreview({ courses }: { courses: DashboardCourse[] }) { const visible = courses.slice(0, 3); + // Nothing finished yet: "pick up where you left off" and a row of empty bars would mean nothing. + const anyProgress = courses.some((course) => course.chaptersCompleted > 0); return (

    My learning

    -

    Pick up where you left off.

    +

    + {anyProgress ? "Pick up where you left off." : "Your courses. Finish one lesson to see your progress here."} +

    {visible.map((course) => { - const status = statusDetails(course.state); + const fresh = course.state === "IN_PROGRESS" && course.chaptersCompleted === 0; + const status = fresh ? { label: "Started", variant: "outline" as const } : statusDetails(course.state); const percent = course.percentComplete === 0 && course.chaptersCompleted > 0 ? "<1" : course.percentComplete; + const showBar = course.chaptersCompleted > 0 || course.percentComplete > 0; return (
  • @@ -388,10 +396,17 @@ function CourseListPreview({ courses }: { courses: DashboardCourse[] }) {

    {course.targetChapter?.title ?? course.currentModule ?? "Ready when you are"}

    -
    - - {percent}% -
    + {showBar ? ( +
    + + {percent}% +
    + ) : ( +

    + {course.chaptersTotal} {course.chaptersTotal === 1 ? "lesson" : "lessons"} + {course.state === "NOT_STARTED" ? " · not started" : " · first lesson open"} +

    + )} 0) { + return ( +
    + +
    + ); + } + return (
    diff --git a/frontend/src/lib/first-run.ts b/frontend/src/lib/first-run.ts new file mode 100644 index 000000000..80a4d9e85 --- /dev/null +++ b/frontend/src/lib/first-run.ts @@ -0,0 +1,113 @@ +import type { CatalogCourseSummary } from "@/shared/api/catalog"; +import type { FirstRunAnswers, FirstRunGoal, FirstRunLevel } from "@/shared/api/learner"; +import type { CourseCategory } from "@/shared/domain/enums"; +import { difficultyRank } from "@/lib/learner-onboarding"; + +// The first-run walkthrough: three taps (why you are here, which area, where you are now), +// one quick question from that area, then a plan. Everything here is a tap on a card. + +export const GOAL_OPTIONS: ReadonlyArray<{ value: FirstRunGoal; label: string; hint: string }> = [ + { value: "JOB", label: "Get better at my job", hint: "Skills I can use this week" }, + { value: "CAREER", label: "Change my career", hint: "Build skills for a new role" }, + { value: "CURIOUS", label: "Learn something new", hint: "Just for me" }, + { value: "ASSIGNED", label: "My team or mentor sent me", hint: "I was asked to join" }, +]; + +export const LEVEL_OPTIONS: ReadonlyArray<{ value: FirstRunLevel; label: string; hint: string }> = [ + { value: "NEW", label: "I am completely new", hint: "Start from the very first step" }, + { value: "SOME", label: "I have tried a little", hint: "I know a few basics" }, + { value: "WORK", label: "I already use it at work", hint: "Skip what I know" }, +]; + +export const PACE_OPTIONS: ReadonlyArray<{ minutes: 5 | 10 | 20; label: string }> = [ + { minutes: 5, label: "5 min a day" }, + { minutes: 10, label: "10 min a day" }, + { minutes: 20, label: "20 min a day" }, +]; + +export type TasteQuestion = { + question: string; + options: ReadonlyArray<{ id: string; label: string }>; + correct: string; + reveal: string; +}; + +/** One short question per area, so the learner learns something before they see a dashboard. */ +export const TASTE_QUESTIONS: Record = { + TECH: { + question: "What does HTML do on a web page?", + options: [ + { id: "structure", label: "Gives the page its structure: headings, text, buttons" }, + { id: "colors", label: "Picks the colors and fonts" }, + { id: "passwords", label: "Stores the users' passwords" }, + ], + correct: "structure", + reveal: "HTML is the structure of the page. CSS adds the colors and fonts, and the server keeps the data. You will build all three step by step.", + }, + CLOUD_DEVOPS: { + question: "An app works on your laptop but breaks on the server. What packs the app with everything it needs, so it runs the same everywhere?", + options: [ + { id: "container", label: "A container" }, + { id: "spreadsheet", label: "A spreadsheet" }, + { id: "extension", label: "A browser extension" }, + ], + correct: "container", + reveal: "A container holds the app and everything it needs to run. The same container runs on your laptop and on the server, so there are no surprises.", + }, + SOFT_SKILLS: { + question: "A teammate misses a deadline that blocks your work. What is the best first step?", + options: [ + { id: "ask", label: "Ask what happened and what they need" }, + { id: "escalate", label: "Tell the manager right away" }, + { id: "silent", label: "Say nothing and wait" }, + ], + correct: "ask", + reveal: "Asking first gets you the facts and keeps trust. Often the blocker is something you can help with. Going to the manager comes later, if it keeps happening.", + }, +}; + +/** Areas that have at least one course to start, in catalog order. */ +export function availableDomains(courses: readonly CatalogCourseSummary[], order: readonly CourseCategory[]): CourseCategory[] { + return order.filter((category) => courses.some((course) => course.category === category)); +} + +function levelFit(difficulty: string | null, level: FirstRunLevel): number { + const rank = difficultyRank(difficulty); + if (level === "NEW") return rank; + if (level === "SOME") return Math.abs(rank - 0.5); + return 2 - rank; +} + +/** + * The course to start with and up to two others. Free courses come first (they open lesson 1 + * with one tap), then the best fit for the learner's level, then rating. + */ +export function recommendCourses( + courses: readonly CatalogCourseSummary[], + answers: Pick +): { main: CatalogCourseSummary | null; others: CatalogCourseSummary[]; inDomain: boolean } { + // One card per title: a course published in several copies shows once. + const unique = courses.filter((course, index) => courses.findIndex((other) => other.title === course.title) === index); + const inArea = unique.filter((course) => course.category === answers.domain); + const pool = inArea.length ? inArea : unique; + const sorted = [...pool].sort((a, b) => { + const free = Number(a.pricingType !== "FREE") - Number(b.pricingType !== "FREE"); + if (free) return free; + const fit = levelFit(a.difficulty, answers.level) - levelFit(b.difficulty, answers.level); + if (fit) return fit; + const rating = (b.ratingAverage ?? 0) - (a.ratingAverage ?? 0); + if (rating) return rating; + const reviews = b.ratingCount - a.ratingCount; + if (reviews) return reviews; + // A fuller course is a better first step than a one-lesson demo. + const size = b.chapterCount - a.chapterCount; + if (size) return size; + return a.title.localeCompare(b.title); + }); + return { main: sorted[0] ?? null, others: sorted.slice(1, 3), inDomain: inArea.length > 0 }; +} + +/** Where the start button goes: free courses enroll and open lesson 1; paid ones show the course. */ +export function startHref(course: CatalogCourseSummary): string { + return course.pricingType === "FREE" ? `/enroll/${course.slug}` : `/catalog/${course.slug}`; +} diff --git a/frontend/src/lib/learner-onboarding.ts b/frontend/src/lib/learner-onboarding.ts index e32ddc343..c961369ad 100644 --- a/frontend/src/lib/learner-onboarding.ts +++ b/frontend/src/lib/learner-onboarding.ts @@ -65,11 +65,11 @@ export function dashboardVisibility(stage: LearnerOnboardingStage): DashboardVis }; } -function difficultyRank(difficulty: string | null): number { +export function difficultyRank(difficulty: string | null): number { const normalized = difficulty?.trim().toLowerCase() ?? ""; - if (normalized === "beginner" || normalized === "foundations" || normalized === "introductory") return 0; - if (normalized === "intermediate") return 1; - if (normalized === "advanced") return 2; + if (normalized === "beginner" || normalized === "foundations" || normalized === "introductory" || normalized === "easy") return 0; + if (normalized === "intermediate" || normalized === "medium") return 1; + if (normalized === "advanced" || normalized === "hard") return 2; return 1; } diff --git a/frontend/src/server/actions/first-run.ts b/frontend/src/server/actions/first-run.ts new file mode 100644 index 000000000..b4c2d5803 --- /dev/null +++ b/frontend/src/server/actions/first-run.ts @@ -0,0 +1,14 @@ +"use server"; + +import type { FirstRunInput } from "@/shared/api/learner"; +import { serverApiFetch } from "@/lib/api-server"; + +/** Save the walkthrough answers (or a skip). Never throws: a failed save must not block the learner. */ +export async function saveFirstRun(input: FirstRunInput): Promise<{ ok: boolean }> { + try { + await serverApiFetch("/api/v1/learner/first-run", { method: "PUT", json: input }); + return { ok: true }; + } catch { + return { ok: false }; + } +} diff --git a/frontend/src/shared/api/learner.ts b/frontend/src/shared/api/learner.ts index 6a22e824a..76c03bd3f 100644 --- a/frontend/src/shared/api/learner.ts +++ b/frontend/src/shared/api/learner.ts @@ -76,8 +76,26 @@ export type DashboardEvent = { href: string; }; +/** First-run walkthrough answers. Every value is a tap on a card; nothing is typed. */ +export const FIRST_RUN_GOALS = ["CAREER", "JOB", "CURIOUS", "ASSIGNED"] as const; +export const FIRST_RUN_LEVELS = ["NEW", "SOME", "WORK"] as const; +export type FirstRunGoal = (typeof FIRST_RUN_GOALS)[number]; +export type FirstRunLevel = (typeof FIRST_RUN_LEVELS)[number]; +export type FirstRunAnswers = { + goal: FirstRunGoal; + /** A course category value, e.g. TECH. */ + domain: string; + level: FirstRunLevel; + /** Daily study minutes picked on the plan screen, if any. */ + dailyMinutes?: number | null; +}; +/** PUT /api/v1/learner/first-run */ +export type FirstRunInput = FirstRunAnswers | { skipped: true }; + export type MenteeDashboardViewModel = { learner: { name: string }; + /** Show the first-run walkthrough instead of the normal home (new learners only). */ + firstRun: { show: boolean }; primaryCourse: DashboardCourse | null; actions: DashboardAction[]; courses: DashboardCourse[]; diff --git a/frontend/tests/unit/lib/first-run.test.ts b/frontend/tests/unit/lib/first-run.test.ts new file mode 100644 index 000000000..1e98f9e10 --- /dev/null +++ b/frontend/tests/unit/lib/first-run.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from "vitest"; +import type { CatalogCourseSummary } from "@/shared/api/catalog"; +import { availableDomains, recommendCourses, startHref } from "@/lib/first-run"; + +function course(overrides: Partial): CatalogCourseSummary { + return { + id: overrides.slug ?? "c", + slug: "course", + title: "Course", + description: null, + coverUrl: null, + difficulty: "Beginner", + estimatedHours: 4, + category: "TECH", + subcategory: null, + tags: [], + pricingType: "FREE", + priceCents: 0, + currency: "USD", + projectGoal: null, + instructorName: null, + moduleCount: 2, + chapterCount: 6, + ratingAverage: null, + ratingCount: 0, + enrollmentLifecycle: null, + ...overrides, + }; +} + +const catalog = [ + course({ slug: "html", title: "HTML", difficulty: "Beginner", chapterCount: 27 }), + course({ slug: "demo", title: "A one-lesson demo", difficulty: "Beginner", chapterCount: 1 }), + course({ slug: "html-copy", title: "HTML", difficulty: "Beginner", chapterCount: 27 }), + course({ slug: "design", title: "System design", difficulty: "Advanced" }), + course({ slug: "paid", title: "Paid basics", difficulty: "Beginner", pricingType: "PAID", priceCents: 1000 }), + course({ slug: "talk", title: "Hard talks", category: "SOFT_SKILLS" }), +]; + +describe("first-run suggestions", () => { + it("lists only areas that have a course", () => { + expect(availableDomains(catalog, ["TECH", "SOFT_SKILLS", "CLOUD_DEVOPS"])).toEqual(["TECH", "SOFT_SKILLS"]); + }); + + it("starts a new learner on a free beginner course, preferring a full course over a demo", () => { + const { main, others, inDomain } = recommendCourses(catalog, { domain: "TECH", level: "NEW" }); + expect(inDomain).toBe(true); + expect(main?.slug).toBe("html"); + expect(others.map((item) => item.slug)).toEqual(["demo", "design"]); + }); + + it("shows a course published twice under one title only once", () => { + const { main, others } = recommendCourses(catalog, { domain: "TECH", level: "NEW" }); + expect([main, ...others].filter((item) => item?.title === "HTML")).toHaveLength(1); + }); + + it("puts advanced courses first for someone who uses it at work", () => { + expect(recommendCourses(catalog, { domain: "TECH", level: "WORK" }).main?.slug).toBe("design"); + }); + + it("falls back to the whole catalog when the area has no course yet", () => { + const result = recommendCourses(catalog, { domain: "CLOUD_DEVOPS", level: "NEW" }); + expect(result.inDomain).toBe(false); + expect(result.main?.slug).toBe("html"); + }); + + it("opens lesson 1 for free courses and the course page for paid ones", () => { + expect(startHref(catalog[0]!)).toBe("/enroll/html"); + expect(startHref(catalog[4]!)).toBe("/catalog/paid"); + }); +}); diff --git a/server/prisma/migrations/20261203180000_first_run/migration.sql b/server/prisma/migrations/20261203180000_first_run/migration.sql new file mode 100644 index 000000000..6234cba0d --- /dev/null +++ b/server/prisma/migrations/20261203180000_first_run/migration.sql @@ -0,0 +1,3 @@ +-- AlterTable +ALTER TABLE "User" ADD COLUMN "firstRun" JSONB, +ADD COLUMN "firstRunAt" TIMESTAMP(3); diff --git a/server/prisma/schema.prisma b/server/prisma/schema.prisma index 3c95d862d..48a2b945a 100644 --- a/server/prisma/schema.prisma +++ b/server/prisma/schema.prisma @@ -265,6 +265,10 @@ enum CareerTier { model User { id String @id @default(cuid()) + /// Answers from the first-run walkthrough (goal, domain, level), or { skipped: true }. + firstRun Json? + /// When the learner finished or skipped the first-run walkthrough; null means not yet. + firstRunAt DateTime? email String @unique emailVerified DateTime? name String? diff --git a/server/src/controllers/learner.ts b/server/src/controllers/learner.ts index 29d883bab..977fe1780 100644 --- a/server/src/controllers/learner.ts +++ b/server/src/controllers/learner.ts @@ -9,6 +9,8 @@ import { loadMenteeDashboard } from "../services/learner/load-mentee-dashboard.j import { loadLearnerHabit } from "../services/progress/learner-habit.js"; import { loadLearnerProgress } from "../services/learner/progress.js"; import * as weeklyGoal from "../services/learner/weekly-goal.js"; +import { saveFirstRun } from "../services/learner/first-run.js"; +import type { FirstRunInput } from "../shared/api/learner.js"; import { dismissStreakPopup, loadStreakPopup } from "../services/learner/streak-popup.js"; import { loadProfile, updateProfile } from "../services/learner/profile.js"; import { getPublicProfileSettings, loadOwnProfile, updatePublicProfileSettings } from "../services/profile/public-profile.js"; @@ -59,6 +61,11 @@ export async function progress(req: Request, res: Response) { } // PUT /api/v1/learner/weekly-goal +export async function putFirstRun(req: Request, res: Response) { + await saveFirstRun(req.user!.id, req.body as FirstRunInput); + noContent(res); +} + export async function putWeeklyGoal(req: Request, res: Response) { await weeklyGoal.setWeeklyGoal(req.user!.id, req.body as WeeklyGoalInput); noContent(res); diff --git a/server/src/routes/v1/learner.ts b/server/src/routes/v1/learner.ts index 330139c65..041ca1664 100644 --- a/server/src/routes/v1/learner.ts +++ b/server/src/routes/v1/learner.ts @@ -17,6 +17,7 @@ import { rewardsActiveBody, streakMilestoneParams, weeklyGoalBody, + firstRunBody, } from "../../validations/learner.js"; import { highlightIdParams, highlightUpdateBody } from "../../validations/chapters.js"; @@ -30,6 +31,7 @@ router.get("/dashboard", learner.dashboard); router.get("/habit", learner.habit); router.get("/progress", learner.progress); router.put("/weekly-goal", validateBody(weeklyGoalBody), learner.putWeeklyGoal); +router.put("/first-run", validateBody(firstRunBody), learner.putFirstRun); router.delete("/weekly-goal", learner.deleteWeeklyGoal); router.post("/streak-milestones/:milestone/acknowledge", validateParams(streakMilestoneParams), learner.acknowledgeStreakMilestone); router.get("/streak-popup", learner.streakPopup); diff --git a/server/src/services/learner/dashboard-model.ts b/server/src/services/learner/dashboard-model.ts index 828b16018..ca543d9fa 100644 --- a/server/src/services/learner/dashboard-model.ts +++ b/server/src/services/learner/dashboard-model.ts @@ -48,6 +48,9 @@ export type DashboardEnrollmentInput = { startedAt: Date | null; completedAt: Date | null; createdAt: Date; + /** How the learner got the course. An invite or an organization means someone chose it for them. */ + source?: string; + organizationId?: string | null; course: { id: string; slug: string; @@ -152,8 +155,27 @@ function latestResponses(responses: DashboardResponseInput[]) { return [...byBlock.values()]; } +/** True once the learner has opened or worked on any chapter of the course. */ +function hasBegun(enrollment: DashboardEnrollmentInput): boolean { + return enrollment.chapterProgress.some( + (row) => Boolean(row.startedAt) || Boolean(row.completedAt) || row.timeSpentSeconds > 0 || row.blocksCompleted > 0 + ); +} + +/** + * Whether the home screen should offer the first-run walkthrough: the learner has not done it, + * has not begun any course, and was not given a course by a mentor invite or an organization. + */ +export function firstRunEligible(firstRunAt: Date | null, enrollments: DashboardEnrollmentInput[]): boolean { + if (firstRunAt) return false; + if (enrollments.some(hasBegun)) return false; + return !enrollments.some((row) => row.source === "INVITE" || row.source === "PATHMENT" || Boolean(row.organizationId)); +} + export function buildMenteeDashboardViewModel(args: { learnerId?: string; + /** When the learner finished or skipped the first-run walkthrough. Omitted means done. */ + firstRunAt?: Date | null; learnerName: string; enrollments: DashboardEnrollmentInput[]; responses: DashboardResponseInput[]; @@ -234,7 +256,8 @@ export function buildMenteeDashboardViewModel(args: { actionLabel = "Review completed course"; actionReason = "The course is complete and available to revisit."; priority = 50; - } else if (enrollment.percentComplete === 0 && !enrollment.startedAt) { + } else if (enrollment.percentComplete === 0 && (!enrollment.startedAt || !hasBegun(enrollment))) { + // Enrolling sets startedAt, but a course nobody has opened is not "in progress". state = "NOT_STARTED"; actionLabel = target ? `Start ${target.title}` : "Open course"; actionReason = target ? "Begin with the first available chapter." : "This course has no published chapters yet."; @@ -376,6 +399,7 @@ export function buildMenteeDashboardViewModel(args: { return { learner: { name: args.learnerName }, + firstRun: { show: args.firstRunAt === undefined ? false : firstRunEligible(args.firstRunAt, args.enrollments) }, primaryCourse, actions: actions.slice(0, 6), courses, diff --git a/server/src/services/learner/first-run.ts b/server/src/services/learner/first-run.ts new file mode 100644 index 000000000..4b879b62d --- /dev/null +++ b/server/src/services/learner/first-run.ts @@ -0,0 +1,17 @@ +import type { Prisma } from "../../generated/prisma/index.js"; +import { prisma } from "../../db/prisma.js"; +import type { FirstRunInput } from "../../shared/api/learner.js"; +import { setWeeklyGoal } from "./weekly-goal.js"; + +/** + * Save the first-run walkthrough. Finishing and skipping both mark it done, so the home screen + * never shows it again. A daily pace picked on the plan screen becomes the learner's study goal. + */ +export async function saveFirstRun(userId: string, input: FirstRunInput): Promise { + await prisma.user.update({ + where: { id: userId }, + data: { firstRun: input as Prisma.InputJsonValue, firstRunAt: new Date() }, + }); + if ("skipped" in input || !input.dailyMinutes) return; + await setWeeklyGoal(userId, { period: "DAILY", kind: "MINUTES", target: input.dailyMinutes, note: "", dailyReminder: false }); +} diff --git a/server/src/services/learner/load-mentee-dashboard.ts b/server/src/services/learner/load-mentee-dashboard.ts index c8e4c3b5c..40dc9174a 100644 --- a/server/src/services/learner/load-mentee-dashboard.ts +++ b/server/src/services/learner/load-mentee-dashboard.ts @@ -59,6 +59,8 @@ export async function loadMenteeDashboard(args: { lifecycle: true, status: true, percentComplete: true, + source: true, + organizationId: true, chaptersCompleted: true, totalScore: true, maxScore: true, @@ -245,8 +247,11 @@ export async function loadMenteeDashboard(args: { }); const lastChapterByEnrollment = new Map(lastSessions.map((session) => [session.enrollmentId, session.chapter.slug])); + const firstRun = await prisma.user.findUnique({ where: { id: args.learnerId }, select: { firstRunAt: true } }); + return buildMenteeDashboardViewModel({ learnerId: args.learnerId, + firstRunAt: firstRun?.firstRunAt ?? null, learnerName: args.learnerName, enrollments: enrollmentsWithRelease, responses, diff --git a/server/src/shared/api/learner.ts b/server/src/shared/api/learner.ts index fe8fd3da6..85920b0ae 100644 --- a/server/src/shared/api/learner.ts +++ b/server/src/shared/api/learner.ts @@ -75,8 +75,26 @@ export type DashboardEvent = { href: string; }; +/** First-run walkthrough answers. Every value is a tap on a card; nothing is typed. */ +export const FIRST_RUN_GOALS = ["CAREER", "JOB", "CURIOUS", "ASSIGNED"] as const; +export const FIRST_RUN_LEVELS = ["NEW", "SOME", "WORK"] as const; +export type FirstRunGoal = (typeof FIRST_RUN_GOALS)[number]; +export type FirstRunLevel = (typeof FIRST_RUN_LEVELS)[number]; +export type FirstRunAnswers = { + goal: FirstRunGoal; + /** A course category value, e.g. TECH. */ + domain: string; + level: FirstRunLevel; + /** Daily study minutes picked on the plan screen, if any. */ + dailyMinutes?: number | null; +}; +/** PUT /api/v1/learner/first-run */ +export type FirstRunInput = FirstRunAnswers | { skipped: true }; + export type MenteeDashboardViewModel = { learner: { name: string }; + /** Show the first-run walkthrough instead of the normal home (new learners only). */ + firstRun: { show: boolean }; primaryCourse: DashboardCourse | null; actions: DashboardAction[]; courses: DashboardCourse[]; diff --git a/server/src/validations/learner.ts b/server/src/validations/learner.ts index 28e84e530..e86a0d2ec 100644 --- a/server/src/validations/learner.ts +++ b/server/src/validations/learner.ts @@ -2,6 +2,18 @@ import { z } from "zod"; import { STREAK_MILESTONES } from "../shared/lib/streak.js"; import { realNameSchema } from "../shared/lib/auth-validation.js"; +export const firstRunBody = z.union([ + z.object({ skipped: z.literal(true) }).strict(), + z + .object({ + goal: z.enum(["CAREER", "JOB", "CURIOUS", "ASSIGNED"]), + domain: z.enum(["TECH", "SOFT_SKILLS", "CLOUD_DEVOPS"]), + level: z.enum(["NEW", "SOME", "WORK"]), + dailyMinutes: z.union([z.literal(5), z.literal(10), z.literal(20)]).nullable().optional(), + }) + .strict(), +]); + export const weeklyGoalBody = z.object({ period: z.enum(["DAILY", "WEEKLY"]).optional().default("WEEKLY"), kind: z.enum(["SESSIONS", "CHAPTERS", "MINUTES"]), diff --git a/server/tests/api/learner.test.ts b/server/tests/api/learner.test.ts index eb0480973..65b878496 100644 --- a/server/tests/api/learner.test.ts +++ b/server/tests/api/learner.test.ts @@ -2,6 +2,8 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest"; import request from "supertest"; import { createApp } from "../../src/app.js"; import { prisma } from "../../src/db/prisma.js"; +import { Prisma } from "../../src/generated/prisma/index.js"; +import { clearWeeklyGoal } from "../../src/services/learner/weekly-goal.js"; import { completeChapter, createCourseFixture } from "../helpers/fixtures.js"; const app = createApp(); @@ -41,10 +43,33 @@ describe("/api/v1/learner", () => { const model = res.body.data; expect(model.learner.name).toBe("Test Learner"); expect(model.courses).toHaveLength(1); - expect(model.courses[0]).toMatchObject({ slug: fx.course.slug, chaptersTotal: 2, state: "IN_PROGRESS" }); + // Enrolled but no chapter opened yet: ready to begin, not "in progress". + expect(model.courses[0]).toMatchObject({ slug: fx.course.slug, chaptersTotal: 2, state: "NOT_STARTED" }); expect(model.habit).toMatchObject({ streakCount: 0, weeklyGoal: null }); }); + it("offers the first-run walkthrough until it is finished or skipped", async () => { + const before = await request(app).get("/api/v1/learner/dashboard").set(auth()); + expect(before.body.data.firstRun).toEqual({ show: true }); + + const bad = await request(app).put("/api/v1/learner/first-run").set(auth()).send({ goal: "JOB", domain: "TECH", level: "NEW", note: "typed text" }); + expect(bad.status).toBe(400); + + const saved = await request(app) + .put("/api/v1/learner/first-run") + .set(auth()) + .send({ goal: "JOB", domain: "TECH", level: "NEW", dailyMinutes: 10 }); + expect(saved.status).toBe(204); + + const after = await request(app).get("/api/v1/learner/dashboard").set(auth()); + expect(after.body.data.firstRun).toEqual({ show: false }); + expect(after.body.data.habit.goal).toMatchObject({ period: "DAILY", kind: "MINUTES", target: 10 }); + + // Put the shared fixture learner back for the other tests. + await prisma.user.update({ where: { id: fx.learner.id }, data: { firstRun: Prisma.DbNull, firstRunAt: null } }); + await clearWeeklyGoal(fx.learner.id); + }); + it("reports progress per course and overall", async () => { await completeChapter(fx.enrollment.id, fx.chapterA.id); const res = await request(app).get("/api/v1/learner/progress").set(auth()); diff --git a/server/tests/unit/services/learner/dashboard-model.test.ts b/server/tests/unit/services/learner/dashboard-model.test.ts index f3bcaf194..2eb00e881 100644 --- a/server/tests/unit/services/learner/dashboard-model.test.ts +++ b/server/tests/unit/services/learner/dashboard-model.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { buildMenteeDashboardViewModel } from "../../../../src/services/learner/dashboard-model.js"; +import { buildMenteeDashboardViewModel, firstRunEligible } from "../../../../src/services/learner/dashboard-model.js"; import type { DashboardEnrollmentInput, DashboardHelpInput, @@ -196,3 +196,29 @@ describe("buildMenteeDashboardViewModel", () => { for (const forbidden of ["config", "correct", "rubric", "sampleAnswer", "hiddenTests", "payload"]) expect(json).not.toContain(`"${forbidden}"`); }); }); + +describe("first-run walkthrough and fresh enrollments", () => { + it("calls an enrolled course nobody has opened ready to begin, not in progress", () => { + const model = build({ enrollments: [enrollment({ percentComplete: 0, chaptersCompleted: 0, chapterProgress: [] })] }); + expect(model.courses[0]!.state).toBe("NOT_STARTED"); + }); + + it("keeps a course whose first chapter was opened in progress", () => { + const model = build({ enrollments: [enrollment({ percentComplete: 0, chaptersCompleted: 0 })] }); + expect(model.courses[0]!.state).toBe("IN_PROGRESS"); + }); + + it("offers the walkthrough only to new learners who chose for themselves", () => { + const fresh = enrollment({ chapterProgress: [], source: "SELF" }); + expect(firstRunEligible(null, [])).toBe(true); + expect(firstRunEligible(null, [fresh])).toBe(true); + expect(firstRunEligible(new Date(), [])).toBe(false); + expect(firstRunEligible(null, [enrollment()])).toBe(false); + expect(firstRunEligible(null, [enrollment({ chapterProgress: [], source: "INVITE" })])).toBe(false); + expect(firstRunEligible(null, [enrollment({ chapterProgress: [], organizationId: "org-1" })])).toBe(false); + }); + + it("does not show the walkthrough when the caller gives no first-run date", () => { + expect(build({ enrollments: [] }).firstRun).toEqual({ show: false }); + }); +});