Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: write attempts challenge attempts and lesson completions to database
Brad Barbinc5d8ecf6bb00
diff --git a/apps/university/app/components/Hero.tsx b/apps/university/app/components/Hero.tsxindex f8e4e8113a..bb9a3a274a 100644--- a/apps/university/app/components/Hero.tsx+++ b/apps/university/app/components/Hero.tsx@@ -1,7 +1,7 @@export function Hero({ children }: { children: React.ReactNode }) {return (<div className="w-full bg-[linear-gradient(to_bottom_right,#f7f5ff_35.67%,#c9fff8_88.95%)] dark:bg-[linear-gradient(to_bottom_right,#0e0338_35.67%,#1b433e_88.95%)]">- <div className="flex flex-col gap-6 w-full px-4 max-w-6xl mx-auto my-20 mb-28">+ <div className="flex flex-col gap-6 w-full px-4 max-w-5xl mx-auto my-20 mb-28">{children}</div></div>diff --git a/apps/university/app/components/Share.tsx b/apps/university/app/components/Share.tsxindex a100c34ceb..4281047791 100644--- a/apps/university/app/components/Share.tsx+++ b/apps/university/app/components/Share.tsx@@ -20,7 +20,7 @@ const Share = ({}) => {const [isCopied, setIsCopied] = useState(false);- const handleCopy = () => {+ const onCopy = () => {copyToClipboard(text);setIsCopied(true);setTimeout(() => setIsCopied(false), 1500);@@ -32,7 +32,6 @@ const Share = ({<Buttonvariant="secondary"aria-label="Copy"- size="sm"className={cn(isCopied && "text-emerald-500 hover:text-emerald-500",className@@ -44,7 +43,7 @@ const Share = ({<LuCopy className="w-3 h-3" />)}- onClick={handleCopy}+ onClick={onCopy}>Share</Button>diff --git a/apps/university/app/config.tsx b/apps/university/app/config.tsxindex ff103bc03a..fdd7dab893 100644--- a/apps/university/app/config.tsx+++ b/apps/university/app/config.tsx@@ -33,7 +33,12 @@ type Topic = {lessons: Lesson[];};-type Question = any;+interface Question {+ id: string;+ question: string;+ options: string[];+ correctAnswer: number; // index of the correct option+}type Lesson = {name: string;@@ -55,14 +60,48 @@ export const sections: Config = [name: "Carbon Overview",id: "carbon-overview",description:- "Welcome to Carbon, a powerful ERP/MES/QMS software that uses web technology and a modular platform to offer a wide variety of configurations based on the customer’s needs. Learn about Carbon's architecture and setup in this first course.",+ "Welcome to Carbon, a powerful ERP/MES/QMS software that uses web technology and a modular platform to offer a wide variety of configurations based on the customer's needs. Learn about Carbon's architecture and setup in this first course.",topics: [{name: "Introducing Carbon",id: "introduction",description:"This topic covers the basics of Carbon. Here you will learn what it is, how the platform and modules work, and the architecture.",- challenge: [],+ challenge: [+ {+ id: "q1",+ question: "What is Carbon?",+ options: [+ "A programming language",+ "A powerful ERP/MES/QMS software",+ "A database management system",+ "A web framework",+ ],+ correctAnswer: 1,+ },+ {+ id: "q2",+ question: "What technology does Carbon primarily use?",+ options: [+ "Mobile apps",+ "Desktop software",+ "Web technology",+ "Cloud computing only",+ ],+ correctAnswer: 2,+ },+ {+ id: "q3",+ question: "How is Carbon designed to be?",+ options: [+ "Complex and difficult to use",+ "Approachable and easy to get started with",+ "Only for large enterprises",+ "Limited in functionality",+ ],+ correctAnswer: 1,+ },+ ],lessons: [{id: "what-is-carbon",@@ -100,7 +139,32 @@ export const sections: Config = [id: "company-setup",description:"Learn how to setup your company in Carbon. This includes creating your company, adding users, and setting up your company's preferences. This is the first step to getting your organization ready to use Carbon.",- challenge: [],+ challenge: [+ {+ id: "q1",+ question:+ "What is the first step to getting your organization ready to use Carbon?",+ options: [+ "Setting up integrations",+ "Creating your company",+ "Adding users",+ "Setting up resources",+ ],+ correctAnswer: 1,+ },+ {+ id: "q2",+ question:+ "Which of the following is NOT part of company setup?",+ options: [+ "Creating your company",+ "Adding users",+ "Setting up preferences",+ "Installing software",+ ],+ correctAnswer: 3,+ },+ ],lessons: [{id: "company-setup",diff --git a/apps/university/app/root.tsx b/apps/university/app/root.tsxindex f0b4fca3c3..c5768d186a 100644--- a/apps/university/app/root.tsx+++ b/apps/university/app/root.tsx@@ -8,6 +8,7 @@ import {Button,Heading,IconButton,+ Progress,toast,Toaster,TooltipProvider,@@ -33,6 +34,7 @@ import type {} from "@vercel/remix";import { json } from "@vercel/remix";import React, { useEffect } from "react";+import { sections } from "~/config";import { getMode, setMode } from "~/services/mode.server";import Background from "~/styles/background.css?url";import NProgress from "~/styles/nprogress.css?url";@@ -75,25 +77,35 @@ export async function loader({ request }: LoaderFunctionArgs) {let session = await getOrRefreshAuthSession(request);let user = null;+ let completedChallenges: {+ courseId: string;+ topicId: string;+ }[] = [];if (session) {const client = getCarbon(session.accessToken);- const authUser = await client- .from("user")- .select("*")- .eq("id", session.userId)- .single();+ const [authUser, challengeAttempts] = await Promise.all([+ client.from("user").select("*").eq("id", session.userId).single(),+ client+ .from("challengeAttempt")+ .select("courseId, topicId")+ .eq("userId", session.userId)+ .eq("passed", true),+ ]);if (authUser.data) {user = authUser.data;}++ completedChallenges = challengeAttempts.data ?? [];}const sessionFlash = await getSessionFlash(request);return json({+ completedChallenges,env: {POSTHOG_API_HOST,POSTHOG_PROJECT_PUBLIC_KEY,@@ -167,6 +179,7 @@ export default function App() {const env = loaderData?.env ?? {};const result = loaderData?.result;const theme = loaderData?.theme ?? "zinc";+ const completedChallenges = loaderData?.completedChallenges ?? [];/* Toast Messages */useEffect(() => {@@ -183,10 +196,29 @@ export default function App() {const fetcher = useFetcher<typeof action>();const user = useOptionalUser();+ // Calculate total challenges from sections config+ const totalChallenges = sections.reduce((total, section) => {+ return (+ total ++ section.courses.reduce((courseTotal, course) => {+ return (+ courseTotal ++ course.topics.reduce((topicTotal, topic) => {+ return topicTotal + (topic.challenge ? 1 : 0);+ }, 0)+ );+ }, 0)+ );+ }, 0);++ const completionPercentage = Math.round(+ (completedChallenges.length / totalChallenges) * 100+ );+return (<Document mode={mode} theme={theme}><header className="flex select-none items-center py-4 pl-5 pr-2 h-[var(--header-height)]">- <div className="max-w-6xl mx-auto px-4 flex items-center justify-between gap-2 z-logo text-foreground w-full">+ <div className="max-w-5xl mx-auto px-4 flex items-center justify-between gap-2 z-logo text-foreground w-full"><Linkto="/"className="cursor-pointer flex flex-row items-end gap-2 flex-shrink-0 font-display"@@ -239,6 +271,13 @@ export default function App() {</div></div></header>+ {user && (+ <div className="w-full bg-primary dark:bg-[#6041d0]">+ <div className="max-w-5xl mx-auto px-3 py-4 flex flex-col gap-2 z-logo text-white w-full">+ <Progress value={completionPercentage} />+ </div>+ </div>+ )}<Outlet /><scriptdangerouslySetInnerHTML={{diff --git a/apps/university/app/routes/_auth+/login.tsx b/apps/university/app/routes/_auth+/login.tsxindex 8d9830f0d4..943f72b02f 100644--- a/apps/university/app/routes/_auth+/login.tsx+++ b/apps/university/app/routes/_auth+/login.tsx@@ -37,7 +37,7 @@ export const meta: MetaFunction = () => {export async function loader({ request }: LoaderFunctionArgs) {const authSession = await getAuthSession(request);if (authSession && (await verifyAuthSession(authSession))) {- throw redirect(path.to.authenticatedRoot);+ throw redirect(path.to.root);}return null;diff --git a/apps/university/app/routes/about.tsx b/apps/university/app/routes/about.tsxindex badf4f7d82..862ed4e1a1 100644--- a/apps/university/app/routes/about.tsx+++ b/apps/university/app/routes/about.tsx@@ -31,7 +31,7 @@ export default function AboutRoute() {</div></Hero><section className="border-b">- <div className="flex flex-row gap-8 w-full px-4 max-w-6xl mx-auto my-24">+ <div className="flex flex-row gap-8 w-full px-4 max-w-5xl mx-auto my-24"><div className="flex flex-col max-w-2xl gap-6"><h3 className="text-muted-foreground uppercase text-sm font-display leading-[140%] tracking-tighter">How it works@@ -50,7 +50,7 @@ export default function AboutRoute() {</div></section><section>- <div className="flex flex-row gap-8 w-full px-4 max-w-6xl mx-auto my-24">+ <div className="flex flex-row gap-8 w-full px-4 max-w-5xl mx-auto my-24"><div className="flex flex-col max-w-2xl gap-6"><h3 className="text-muted-foreground uppercase text-sm font-display leading-[140%] tracking-tighter">Challengesdiff --git a/apps/university/app/routes/challenge+/$id.tsx b/apps/university/app/routes/challenge+/$id.tsxnew file mode 100644index 0000000000..455e647147--- /dev/null+++ b/apps/university/app/routes/challenge+/$id.tsx@@ -0,0 +1,423 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import { Alert, AlertDescription, AlertTitle, Button, cn } from "@carbon/react";+import type { ActionFunctionArgs } from "@remix-run/node";+import {+ Form,+ Link,+ useActionData,+ useParams,+ useSubmit,+} from "@remix-run/react";+import { useEffect, useMemo, useState } from "react";+import ConfettiExplosion from "react-confetti-explosion";+import {+ LuChevronLeft,+ LuCircleCheck,+ LuFlag,+ LuRefreshCcw,+ LuTriangleAlert,+} from "react-icons/lu";+import { useOptionalUser } from "~/hooks/useUser";+import { path } from "~/utils/path";+import { findTopicContext } from "~/utils/video";++interface ActionData {+ passed: boolean;+ score: number;+ totalQuestions: number;+ userAnswers: number[];+ incorrectQuestions: number[];+ shuffledIndices: number[];+}++export async function action({ request }: ActionFunctionArgs) {+ const { client, userId } = await requirePermissions(request, {});+ const formData = await request.formData();+ const reset = formData.get("reset");++ // Handle reset case+ if (reset === "true") {+ return null;+ }++ const topicId = formData.get("topicId") as string;+ const answers = JSON.parse(formData.get("answers") as string);+ const shuffledIndices = JSON.parse(formData.get("shuffledIndices") as string);++ const context = findTopicContext(topicId);+ if (!context) {+ throw new Error("Topic not found");+ }++ const { topic, course } = context;+ let correctAnswers = 0;+ const totalQuestions = topic.challenge.length;+ const incorrectQuestions: number[] = [];++ // Map answers back to original question order using shuffled indices+ shuffledIndices.forEach((originalIndex: number, shuffledIndex: number) => {+ if (+ answers[shuffledIndex] === topic.challenge[originalIndex].correctAnswer+ ) {+ correctAnswers++;+ } else {+ incorrectQuestions.push(originalIndex);+ }+ });++ const passed = correctAnswers === totalQuestions; // 100% to pass++ const { error } = await client.from("challengeAttempt").insert({+ userId,+ courseId: course.id,+ topicId,+ passed,+ });++ if (error) {+ console.error(error);+ }++ return {+ passed,+ score: correctAnswers,+ totalQuestions,+ userAnswers: answers,+ incorrectQuestions,+ shuffledIndices,+ };+}++export default function ChallengeRoute() {+ const { id } = useParams();+ const user = useOptionalUser();+ const actionData = useActionData<ActionData>();++ const submit = useSubmit();++ if (!id) {+ throw new Error("Topic ID is required");+ }++ const context = findTopicContext(id);++ if (!context) {+ throw new Error("Topic not found");+ }++ const { section, course, topic } = context;++ // Shuffle the questions+ const shuffledQuestions = useMemo(+ () => [...topic.challenge].sort(() => Math.random() - 0.5),+ [topic.challenge]+ );++ const [answers, setAnswers] = useState<number[]>([]);+ const [isSubmitted, setIsSubmitted] = useState(false);++ useEffect(() => {+ if (actionData) {+ setIsSubmitted(true);+ }+ }, [actionData]);++ const onAnswerChange = (questionIndex: number, answerIndex: number) => {+ const newAnswers = [...answers];+ newAnswers[questionIndex] = answerIndex;+ setAnswers(newAnswers);+ };++ const onTryAgain = () => {+ setIsSubmitted(false);+ setAnswers([]);++ // Clear the action data by submitting a reset form+ const formData = new FormData();+ formData.append("reset", "true");+ submit(formData, { method: "post", replace: true });+ };++ const onSubmit = () => {+ if (answers.length !== shuffledQuestions.length) {+ alert("Please answer all questions before submitting.");+ return;+ }++ // Smooth scroll to top when submitting+ window.scrollTo({ top: 0, behavior: "smooth" });++ const formData = new FormData();+ formData.append("topicId", id);+ formData.append("answers", JSON.stringify(answers));+ formData.append(+ "shuffledIndices",+ JSON.stringify(shuffledQuestions.map((q) => topic.challenge.indexOf(q)))+ );+ submit(formData, { method: "post" });+ };++ const getAnswerStatus = (questionIndex: number, optionIndex: number) => {+ if (!actionData || isSubmitted === false) return null;++ const originalQuestionIndex = actionData.shuffledIndices[questionIndex];+ const question = topic.challenge[originalQuestionIndex];+ const userAnswer = actionData.userAnswers[questionIndex];+ const isCorrect = optionIndex === question.correctAnswer;+ const isSelected = optionIndex === userAnswer;++ if (isCorrect && isSelected) return "correct";+ if (!isCorrect && isSelected) return "incorrect";+ return null;+ };++ const getAnswerStyles = (status: string | null) => {+ switch (status) {+ case "correct":+ return "bg-green-100 border-green-500 text-green-800";+ case "incorrect":+ return "bg-red-100 border-red-500 text-red-800";+ default:+ return "hover:bg-accent";+ }+ };++ return (+ <div className="w-full px-4 max-w-5xl mx-auto mt-8 pb-24 flex flex-col gap-8">+ <div className="flex items-center gap-2">+ <Button+ variant="primary"+ leftIcon={<LuChevronLeft />}+ className="mr-2"+ asChild+ >+ <Link to={path.to.course(section.id, course.id)}>Back to course</Link>+ </Button>++ <Button+ variant="link"+ className="text-sm text-muted-foreground"+ asChild+ >+ <Link to={path.to.course(section.id, course.id)}>{course.name}</Link>+ </Button>++ <span className="text-muted-foreground text-sm">/</span>++ <span className="text-muted-foreground text-sm font-bold">+ {topic.name}+ </span>+ </div>++ <div className="flex flex-col w-full">+ <div+ className="border rounded-lg rounded-b-none p-4"+ style={{+ backgroundColor: section?.background,+ color: section?.foreground,+ }}+ >+ <div className="flex flex-col gap-4">+ <div className="flex items-start gap-4">+ <div+ className="flex-shrink-0 size-12 text-2xl p-3 rounded-full border"+ style={{+ backgroundColor: section?.background,+ borderColor: section?.foreground,+ color: section?.foreground,+ }}+ >+ <LuFlag />+ </div>+ <div className="flex flex-col">+ <h1 className="uppercase text-[10px] font-display font-bold">+ Challenge+ </h1>+ <h2 className="text-2xl font-display tracking-tight">+ {topic.name}+ </h2>+ </div>+ </div>+ </div>+ </div>+ <div className="flex flex-col gap-4 border rounded-b-lg border-t-0 px-6 py-4">+ <p className="text-base text-muted-foreground">+ Test your knowledge with these multiple choice questions. You need+ to get at least 100% correct to pass.+ </p>+ </div>+ </div>++ {isSubmitted && actionData && (+ <div className="border rounded-lg px-6 py-10">+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">+ <div className="flex flex-col items-center justify-center gap-2">+ <span className="text-sm font-display uppercase">Scoreboard</span>+ <span+ className={cn(+ "text-xl font-display uppercase font-bold tracking-tight",+ actionData.passed ? "text-emerald-500" : "text-red-500"+ )}+ >+ You Scored+ </span>+ <div+ className={cn(+ "text-6xl font-display font-bold",+ actionData.passed ? "text-emerald-500" : "text-red-500"+ )}+ >+ {Math.round(+ (actionData.score / actionData.totalQuestions) * 100+ )}+ %+ </div>+ </div>+ <div className="flex flex-col gap-4">+ <p className="text-base text-muted-foreground">+ You can continue by returning to the course listing or you can+ retry this challenge and try for 100%.+ </p>+ <div className="flex items-center gap-4 w-full justify-center">+ <Button+ size="lg"+ variant="secondary"+ leftIcon={<LuChevronLeft />}+ asChild+ >+ <Link to={path.to.course(section.id, course.id)}>+ Return to Course Page+ </Link>+ </Button>+ {!actionData?.passed && (+ <Button+ size="lg"+ variant="primary"+ onClick={onTryAgain}+ rightIcon={<LuRefreshCcw />}+ >+ Retry Challenge+ </Button>+ )}+ </div>+ </div>+ </div>+ </div>+ )}++ {user ? (+ <Form method="post" className="flex flex-col gap-6">+ <input type="hidden" name="topicId" value={id} />+ <input type="hidden" name="answers" value={JSON.stringify(answers)} />++ {shuffledQuestions.map((question, questionIndex) => (+ <div key={question.id} className="border rounded-lg p-6">+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">+ <div className="flex flex-col gap-2">+ <h3 className="text-lg font-display font-bold">+ Question {questionIndex + 1}:+ </h3>+ <p className="text-base text-muted-foreground">+ {question.question}+ </p>+ </div>+ <div className="flex flex-col gap-3">+ {question.options.map((option, optionIndex) => {+ const answerStatus = getAnswerStatus(+ questionIndex,+ optionIndex+ );+ const isDisabled = isSubmitted && !!actionData;++ return (+ <label+ key={optionIndex}+ className={`flex items-center gap-3 p-3 border rounded-md cursor-pointer transition-colors ${+ isDisabled ? "cursor-default" : "hover:bg-accent"+ } ${getAnswerStyles(answerStatus)}`}+ >+ <input+ type="radio"+ name={`question-${questionIndex}`}+ value={optionIndex}+ checked={answers[questionIndex] === optionIndex}+ onChange={() =>+ onAnswerChange(questionIndex, optionIndex)+ }+ disabled={isDisabled}+ className="size-4"+ />+ <span className="text-sm">{option}</span>+ {answerStatus && (+ <span className="ml-auto text-xs font-medium">+ {answerStatus === "correct" && "✓ Correct"}+ {answerStatus === "incorrect" && "✗ Incorrect"}+ </span>+ )}+ </label>+ );+ })}+ </div>+ </div>+ </div>+ ))}++ {!isSubmitted && (+ <div className="rounded-lg border flex flex-row-reverse justify-between p-6 gap-12 items-center">+ <Button+ type="button"+ size="lg"+ variant="primary"+ leftIcon={<LuCircleCheck />}+ onClick={onSubmit}+ disabled={answers.length !== topic.challenge.length}+ className={+ answers.length !== topic.challenge.length+ ? "opacity-50 cursor-not-allowed"+ : ""+ }+ >+ Submit Answers+ </Button>+ <Alert variant="warning" className="border-none">+ <LuTriangleAlert className="h-4 w-4" />+ <AlertTitle>+ Please ensure that all questions are answered correctly+ </AlertTitle>+ <AlertDescription>+ You can retake challenges, but they will be completely+ randomized when a new one is started.+ </AlertDescription>+ </Alert>+ </div>+ )}+ </Form>+ ) : (+ <div className="flex justify-between items-center gap-4 border rounded-lg py-6 px-8">+ <div className="flex flex-col gap-1">+ <h3 className="text-lg font-display font-bold">Challenge Rules</h3>+ <p className="text-base text-muted-foreground">+ There is no limit on attempts, but retries will be randomized.+ </p>+ </div>+ <Button size="lg" variant="primary" asChild>+ <Link to={`${path.to.login}?redirectTo=${path.to.challenge(id)}`}>+ Login to Take Challenge+ </Link>+ </Button>+ </div>+ )}++ {actionData?.passed && (+ <div className="fixed inset-0 flex items-center justify-center pointer-events-none">+ <ConfettiExplosion+ particleCount={200}+ force={1}+ duration={3000}+ width={1600}+ />+ </div>+ )}+ </div>+ );+}diff --git a/apps/university/app/routes/challenge+/_index.tsx b/apps/university/app/routes/challenge+/_index.tsxdeleted file mode 100644index d56e10f963..0000000000--- a/apps/university/app/routes/challenge+/_index.tsx+++ /dev/null@@ -1,38 +0,0 @@-import { Heading, cn } from "@carbon/react";-import { getLocalTimeZone } from "@internationalized/date";-import { useLocale } from "@react-aria/i18n";-import { useMemo, type ComponentProps } from "react";-import { useUser } from "~/hooks";--export default function AppIndexRoute() {- const user = useUser();- const { locale } = useLocale();- const date = new Date();-- const formatter = useMemo(- () =>- new Intl.DateTimeFormat(locale, {- dateStyle: "full",- timeZone: getLocalTimeZone(),- }),- [locale]- );-- return (- <div className="p-8 w-full h-full bg-muted">- <Heading size="h3">Hello, {user.firstName}</Heading>- <Subheading>{formatter.format(date)}</Subheading>- <Hr />- </div>- );-}--const Hr = () => (- <hr className="h-px my-8 bg-black/10 border-0 dark:bg-white/10" />-);--const Subheading = ({ children, className }: ComponentProps<"p">) => (- <p className={cn("text-muted-foreground text-base font-light", className)}>- {children}- </p>-);diff --git a/apps/university/app/routes/challenge+/_layout.tsx b/apps/university/app/routes/challenge+/_layout.tsxdeleted file mode 100644index 5c39520226..0000000000--- a/apps/university/app/routes/challenge+/_layout.tsx+++ /dev/null@@ -1,20 +0,0 @@-import { Outlet } from "@remix-run/react";-import type { LoaderFunctionArgs } from "@vercel/remix";-import { redirect } from "@vercel/remix";--import { getAuthSession } from "@carbon/auth/session.server";-import { path } from "~/utils/path";--export async function loader({ request }: LoaderFunctionArgs) {- const session = await getAuthSession(request);-- if (!session) {- throw redirect(path.to.login);- }-- return null;-}--export default function AuthenticatedRoute() {- return <Outlet />;-}diff --git a/apps/university/app/routes/course+/$sectionId.$courseId.tsx b/apps/university/app/routes/course+/$sectionId.$courseId.tsxindex 78d686e627..04e268a4e1 100644--- a/apps/university/app/routes/course+/$sectionId.$courseId.tsx+++ b/apps/university/app/routes/course+/$sectionId.$courseId.tsx@@ -1,11 +1,57 @@+import { requirePermissions } from "@carbon/auth/auth.server";import { Button, cn, Progress, VStack } from "@carbon/react";-import { Link, useParams } from "@remix-run/react";-import { LuCirclePlay, LuFlag } from "react-icons/lu";+import { json, Link, useLoaderData, useParams } from "@remix-run/react";+import type { LoaderFunctionArgs } from "@vercel/remix";+import { LuCircleCheck, LuCirclePlay, LuRotateCcw } from "react-icons/lu";import { sections } from "~/config";import { path } from "~/utils/path";import { formatDuration } from "~/utils/video";+export const loader = async ({ request, params }: LoaderFunctionArgs) => {+ const { client, userId } = await requirePermissions(request, {});+ const { courseId } = params;++ if (!courseId) {+ throw new Error("Course ID is required");+ }++ const [lessonCompletions, challengeAttempts] = await Promise.all([+ client+ .from("lessonCompletion")+ .select("lessonId")+ .eq("userId", userId)+ .eq("courseId", courseId),+ client+ .from("challengeAttempt")+ .select("topicId, passed")+ .eq("userId", userId)+ .eq("courseId", courseId),+ ]);++ const completedLessons =+ lessonCompletions.data?.map((completion) => completion.lessonId) ?? [];++ const completedChallenges = Array.from(+ new Set(+ challengeAttempts.data+ ?.filter((completion) => completion.passed)+ .map((completion) => completion.topicId) ?? []+ )+ );++ const attemptsByTopic =+ challengeAttempts.data?.reduce<Record<string, number>>((acc, attempt) => {+ acc[attempt.topicId] = (acc[attempt.topicId] ?? 0) + 1;+ return acc;+ }, {}) ?? {};++ return json({ completedLessons, completedChallenges, attemptsByTopic });+};+export default function CourseRoute() {+ const { completedLessons, completedChallenges, attemptsByTopic } =+ useLoaderData<typeof loader>();+const { sectionId, courseId } = useParams();const section = sections.find((section) => section.id === sectionId);const course = section?.courses.find((course) => course.id === courseId);@@ -26,11 +72,15 @@ export default function CourseRoute() {throw new Error("Course not found");}+ const completionPercentage = Math.round(+ (completedChallenges.length / totalChallenges) * 100+ );+return (<VStack spacing={4} className="w-full"><div className="flex flex-col w-full"><div- className="border rounded rounded-b-none px-8 py-3"+ className="border rounded-lg rounded-b-none px-8 py-3"style={{backgroundColor: section?.background,color: section?.foreground,@@ -66,7 +116,7 @@ export default function CourseRoute() {<p className="text-sm">{course.description}</p></div></div>- <div className="border rounded rounded-t-none px-8 py-3">+ <div className="border rounded-lg rounded-t-none px-8 py-3"><div className="flex items-center justify-between gap-2"><div className="flex items-center gap-4 text-xs"><div className="flex items-center gap-1">@@ -81,8 +131,10 @@ export default function CourseRoute() {</div></div><div className="flex items-center gap-1 text-xs">- <span className="font-bold text-emerald-500">0%</span>- <Progress value={0} />+ <span className="font-bold text-emerald-500">+ {completionPercentage}%+ </span>+ <Progress value={completionPercentage} /></div></div></div>@@ -90,6 +142,12 @@ export default function CourseRoute() {<div className="flex flex-col w-full">{course.topics.map((topic, index) => {+ const hasChallenge = topic.challenge && topic.challenge.length > 0;+ const isChallengeCompleted =+ hasChallenge && completedChallenges.includes(topic.id);+ const isChallengeAttempted =+ hasChallenge && attemptsByTopic[topic.id];+ const challengeAttempts = attemptsByTopic[topic.id] ?? 0;const isFirst = index === 0;const isLast = index === course.topics.length - 1;return (@@ -97,8 +155,8 @@ export default function CourseRoute() {key={topic.id}className={cn("border p-8 w-full",- isFirst && "rounded-t",- isLast && "rounded-b",+ isFirst && "rounded-t-lg",+ isLast && "rounded-b-lg",isFirst && !isLast && "rounded-b-none",isLast && !isFirst && "border-t-0 rounded-t-none")}@@ -115,33 +173,60 @@ export default function CourseRoute() {</div><div className="flex flex-col gap-8 py-8 w-full text-sm"><div className="flex flex-col gap-0">- {topic.lessons.map((lesson) => (- <Link- key={lesson.id}- to={path.to.lesson(lesson.id)}- className="flex items-center justify-between gap-2 w-full rounded-md py-1.5 px-3 hover:bg-accent"- >- <div className="flex items-center gap-2">- <LuCirclePlay className="size-4 text-muted-foreground" />- <span>{lesson.name}</span>- </div>- <span className="text-muted-foreground text-xs">- {formatDuration(lesson.duration)}- </span>- </Link>- ))}+ {topic.lessons.map((lesson) => {+ const isCompleted = completedLessons.includes(lesson.id);+ return (+ <Link+ key={lesson.id}+ to={path.to.lesson(lesson.id)}+ className="flex items-center justify-between gap-2 w-full rounded-md py-1.5 px-3 hover:bg-accent"+ >+ <div className="flex items-center gap-2">+ {isCompleted ? (+ <LuCircleCheck className="size-4 text-emerald-500" />+ ) : (+ <LuCirclePlay className="size-4 text-muted-foreground" />+ )}+ <span>{lesson.name}</span>+ </div>+ <span className="text-muted-foreground text-xs">+ {formatDuration(lesson.duration)}+ </span>+ </Link>+ );+ })}</div>- {topic.challenge && (- <Button- leftIcon={<LuFlag className="size-4" />}- variant="secondary"- asChild- >- <Link to={path.to.challenge(topic.id)}>- Take Topic Challenge- </Link>- </Button>- )}+ {hasChallenge ? (+ isChallengeCompleted ? (+ <Button+ variant="primary"+ leftIcon={+ <LuCircleCheck className="size-4 text-emerald-500" />+ }+ >+ Topic Challenge Completed+ </Button>+ ) : (+ <Button+ variant="secondary"+ leftIcon={<LuRotateCcw className="size-4" />}+ asChild+ >+ <Link to={path.to.challenge(topic.id)}>+ {isChallengeAttempted ? (+ <span>+ Retake Topic Challenge{" "}+ <span className="text-xs text-muted-foreground italic">+ {challengeAttempts} attempt made+ </span>+ </span>+ ) : (+ "Take Topic Challenge"+ )}+ </Link>+ </Button>+ )+ ) : null}</div></div></div>diff --git a/apps/university/app/routes/course+/_layout.tsx b/apps/university/app/routes/course+/_layout.tsxindex 09f8c4afdd..3e9806d392 100644--- a/apps/university/app/routes/course+/_layout.tsx+++ b/apps/university/app/routes/course+/_layout.tsx@@ -48,7 +48,7 @@ export default function CourseLayout() {</div></Hero>)}- <div className="w-full px-4 max-w-6xl mx-auto my-16">+ <div className="w-full px-4 max-w-5xl mx-auto my-16"><div className="grid grid-cols-1 md:grid-cols-[250px_1fr] gap-6"><nav className="space-y-4">{sections.map((section) => (diff --git a/apps/university/app/routes/lesson+/$id.tsx b/apps/university/app/routes/lesson+/$id.tsxindex f5d7ad38c0..af55d9924f 100644--- a/apps/university/app/routes/lesson+/$id.tsx+++ b/apps/university/app/routes/lesson+/$id.tsx@@ -1,41 +1,154 @@+import { requirePermissions } from "@carbon/auth/auth.server";import { Button } from "@carbon/react";-import { Link, useParams } from "@remix-run/react";import {+ json,+ Link,+ useFetcher,+ useLoaderData,+ useParams,+} from "@remix-run/react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";+import {+ LuCheck,LuChevronLeft,LuChevronRight,+ LuCircleCheck,LuCirclePlay,LuFlag,} from "react-icons/lu";import Share from "~/components/Share";import { path } from "~/utils/path";import {- findLessonContext,- findNextLesson,- findPreviousLesson,formatDuration,+ getLessonContext,+ getNextLesson,+ getPreviousLesson,} from "~/utils/video";+export const loader = async ({ request, params }: LoaderFunctionArgs) => {+ const { client, userId } = await requirePermissions(request, {});+ const { id: lessonId } = params;++ if (!lessonId) {+ throw new Error("Lesson ID is required");+ }+ const context = getLessonContext(lessonId);++ if (!context) {+ throw new Error("Lesson not found");+ }++ const { course, topic } = context;++ const [lessonCompletions, challengeAttempts] = await Promise.all([+ client+ .from("lessonCompletion")+ .select("lessonId")+ .eq("userId", userId)+ .eq("courseId", course.id),+ client+ .from("challengeAttempt")+ .select("topicId, passed")+ .eq("userId", userId)+ .eq("topicId", topic.id),+ ]);++ const completedLessons =+ lessonCompletions.data?.map((completion) => completion.lessonId) ?? [];+ const completedChallenges =+ challengeAttempts.data+ ?.filter((completion) => completion.passed)+ .map((completion) => completion.topicId) ?? [];+ const attemptsByTopic =+ challengeAttempts.data?.reduce<Record<string, number>>(+ (acc, completion) => {+ acc[completion.topicId] = (acc[completion.topicId] ?? 0) + 1;+ return acc;+ },+ {}+ ) ?? {};++ return json({ completedLessons, completedChallenges, attemptsByTopic });+};++export const action = async ({ request, params }: ActionFunctionArgs) => {+ const { client, userId } = await requirePermissions(request, {});+ const { id: lessonId } = params;++ if (!lessonId) {+ return json(+ { success: false, message: "Lesson ID is required" },+ { status: 400 }+ );+ }++ const context = getLessonContext(lessonId);+ if (!context) {+ return json(+ { success: false, message: "Lesson not found" },+ { status: 404 }+ );+ }+ const { course } = context;++ const insert = await client.from("lessonCompletion").insert({+ userId,+ courseId: course.id,+ lessonId,+ });++ if (insert.error) {+ return json(+ { success: false, message: "Failed to complete lesson" },+ { status: 500 }+ );+ }++ return json({ success: true });+};+export default function LessonRoute() {+ const { completedLessons, completedChallenges, attemptsByTopic } =+ useLoaderData<typeof loader>();const { id } = useParams();if (!id) {throw new Error("Lesson ID is required");}- const context = findLessonContext(id);+ const context = getLessonContext(id);if (!context) {throw new Error("Lesson not found");}const { section, course, topic, lesson } = context;- const nextLesson = findNextLesson(id);- const previousLesson = findPreviousLesson(id);+ const nextLesson = getNextLesson(id);+ const previousLesson = getPreviousLesson(id);+ const hasChallenge = topic.challenge && topic.challenge.length > 0;+ const isChallengeCompleted =+ hasChallenge && completedChallenges.includes(topic.id);+ const isChallengeAttempted = hasChallenge && attemptsByTopic[topic.id];+ const challengeAttempts = attemptsByTopic[topic.id] ?? 0;++ const fetcher = useFetcher<typeof action>();++ const onComplete = async () => {+ fetcher.submit(null, {+ method: "POST",+ action: path.to.lesson(id),+ });+ };return (- <div className="w-full px-4 max-w-6xl mx-auto mt-4 pb-24 flex flex-col gap-8">+ <div className="w-full px-4 max-w-5xl mx-auto mt-4 pb-24 flex flex-col gap-8"><div className="flex items-center gap-2">- <Button variant="primary" leftIcon={<LuChevronLeft />} asChild>+ <Button+ variant="primary"+ leftIcon={<LuChevronLeft />}+ className="mr-2"+ asChild+ ><Link to={path.to.course(section.id, course.id)}>Back to course</Link></Button>@@ -64,11 +177,20 @@ export default function LessonRoute() {/></div><div- className="w-full h-12 rounded-b-lg flex items-center justify-end px-3"+ className="w-full h-12 rounded-b-lg flex items-center justify-end gap-2 px-3"style={{backgroundColor: section.background,}}>+ <Button+ variant="secondary"+ leftIcon={<LuCheck className="size-4" />}+ onClick={onComplete}+ isDisabled={fetcher.state !== "idle"}+ isLoading={fetcher.state !== "idle"}+ >+ Complete Lesson+ </Button><Sharetext={typeof window !== "undefined" ? window.location.href : ""}/>@@ -78,7 +200,7 @@ export default function LessonRoute() {<div className="grid grid-cols-1 md:grid-cols-[1fr_360px] gap-6"><div className="flex flex-col w-full"><div- className="border rounded rounded-b-none p-4"+ className="border rounded-lg rounded-b-none p-4"style={{backgroundColor: section?.background,color: section?.foreground,@@ -107,7 +229,7 @@ export default function LessonRoute() {</div></div></div>- <div className="flex flex-col gap-4 border rounded-b border-t-0 px-6 py-4">+ <div className="flex flex-col gap-4 border rounded-b-lg border-t-0 px-6 py-4"><h4 className="text-lg font-display font-bold">Description</h4><p className="text-base text-muted-foreground">{lesson.description}@@ -156,42 +278,64 @@ export default function LessonRoute() {Lessons in this topic</h3><div className="flex flex-col gap-1">- {topic.lessons.map((topicLesson) => (- <Link- key={topicLesson.id}- to={path.to.lesson(topicLesson.id)}- className={`flex items-center justify-between gap-2 w-full rounded-md py-2 px-3 text-sm transition-colors ${- topicLesson.id === lesson.id- ? "bg-accent text-accent-foreground"- : "hover:bg-accent"- }`}- >- <div className="flex items-center gap-2">- <LuCirclePlay className="size-4 text-muted-foreground" />- <span- className={- topicLesson.id === lesson.id ? "font-medium" : ""- }- >- {topicLesson.name}+ {topic.lessons.map((topicLesson) => {+ const isCompleted = completedLessons.includes(topicLesson.id);+ return (+ <Link+ key={topicLesson.id}+ to={path.to.lesson(topicLesson.id)}+ className={`flex items-center justify-between gap-2 w-full rounded-md py-2 px-3 text-sm transition-colors ${+ topicLesson.id === lesson.id+ ? "bg-accent text-accent-foreground"+ : "hover:bg-accent"+ }`}+ >+ <div className="flex items-center gap-2">+ {isCompleted ? (+ <LuCircleCheck className="size-4 text-emerald-500" />+ ) : (+ <LuCirclePlay className="size-4 text-muted-foreground" />+ )}+ <span+ className={+ topicLesson.id === lesson.id ? "font-medium" : ""+ }+ >+ {topicLesson.name}+ </span>+ </div>+ <span className="text-muted-foreground text-xs">+ {formatDuration(topicLesson.duration)}</span>- </div>- <span className="text-muted-foreground text-xs">- {formatDuration(topicLesson.duration)}- </span>- </Link>- ))}+ </Link>+ );+ })}</div></div>- {topic.challenge && (- <Button- variant={!nextLesson ? "primary" : "secondary"}- leftIcon={<LuFlag className="size-4" />}- asChild- >- <Link to={path.to.challenge(topic.id)}>Take Topic Challenge</Link>- </Button>- )}+ {hasChallenge ? (+ isChallengeCompleted ? (+ <Button+ variant="primary"+ leftIcon={<LuCircleCheck className="size-4 text-emerald-500" />}+ >+ Topic Challenge Completed+ </Button>+ ) : (+ <Button+ variant="secondary"+ leftIcon={<LuFlag className="size-4" />}+ asChild+ >+ <Link to={path.to.challenge(topic.id)}>+ {isChallengeAttempted+ ? `Retake Topic Challenge (${challengeAttempts} attempt${+ challengeAttempts === 1 ? "" : "s"+ })`+ : "Take Topic Challenge"}+ </Link>+ </Button>+ )+ ) : null}</div></div></div>diff --git a/apps/university/app/utils/video.ts b/apps/university/app/utils/video.tsindex 44fa7e5b8e..195e908f46 100644--- a/apps/university/app/utils/video.ts+++ b/apps/university/app/utils/video.ts@@ -6,7 +6,25 @@ export function formatDuration(duration: number) {return `${minutes}:${seconds.toString().padStart(2, "0")}`;}-export function findLessonContext(lessonId: string) {+export function findTopicContext(topicId: string) {+ for (const section of sections) {+ for (const course of section.courses) {+ const topic = course.topics.find(+ (topic: { id: string }) => topic.id === topicId+ );+ if (topic) {+ return {+ section,+ course,+ topic,+ };+ }+ }+ }+ return null;+}++export function getLessonContext(lessonId: string) {for (const section of sections) {for (const course of section.courses) {for (const topic of course.topics) {@@ -27,8 +45,8 @@ export function findLessonContext(lessonId: string) {return null;}-export function findNextLesson(lessonId: string) {- const context = findLessonContext(lessonId);+export function getNextLesson(lessonId: string) {+ const context = getLessonContext(lessonId);if (!context) return null;const { topic } = context;@@ -43,8 +61,8 @@ export function findNextLesson(lessonId: string) {return topic.lessons[currentIndex + 1];}-export function findPreviousLesson(lessonId: string) {- const context = findLessonContext(lessonId);+export function getPreviousLesson(lessonId: string) {+ const context = getLessonContext(lessonId);if (!context) return null;const { topic } = context;diff --git a/apps/university/package.json b/apps/university/package.jsonindex 2f47494b2d..516e7be54f 100644--- a/apps/university/package.json+++ b/apps/university/package.json@@ -28,6 +28,7 @@"isbot": "3.6.13","non.geist": "~1.0.3","react": "^18.3.1",+ "react-confetti-explosion": "^3.0.3","react-dom": "^18.3.1","react-dropzone": "^14.2.3","react-hotkeys-hook": "~4.5.0",diff --git a/package-lock.json b/package-lock.jsonindex 4686ae3c05..728d08d688 100644--- a/package-lock.json+++ b/package-lock.json@@ -336,6 +336,83 @@"uncrypto": "^0.1.3"}},+ "apps/university": {+ "dependencies": {+ "@carbon/auth": "*",+ "@carbon/database": "*",+ "@carbon/documents": "*",+ "@carbon/form": "*",+ "@carbon/kv": "*",+ "@carbon/logger": "*",+ "@carbon/react": "*",+ "@carbon/utils": "*",+ "@react-aria/i18n": "^3.11.0",+ "@remix-run/dev": "~2.11.2",+ "@remix-run/eslint-config": "~2.11.2",+ "@remix-run/react": "~2.11.2",+ "@remix-run/serve": "~2.11.2",+ "@supabase/functions-js": "2.1.5",+ "@supabase/supabase-js": "^2.40.0",+ "@tailwindcss/container-queries": "^0.1.1",+ "@tailwindcss/forms": "^0.5.7",+ "@tailwindcss/line-clamp": "^0.4.4",+ "@tailwindcss/typography": "^0.5.10",+ "@upstash/ratelimit": "^2.0.5",+ "@vercel/analytics": "^1.2.2",+ "@vercel/remix": "2.11.2",+ "framer-motion": "^11.1.7",+ "isbot": "3.6.13",+ "non.geist": "~1.0.3",+ "react": "^18.3.1",+ "react-confetti-explosion": "^3.0.3",+ "react-dom": "^18.3.1",+ "react-dropzone": "^14.2.3",+ "react-hotkeys-hook": "~4.5.0",+ "react-icons": "^5.4.0",+ "tailwind-merge": "^2.2.1",+ "tailwindcss-animate": "^1.0.7",+ "zod": "^3.24.1",+ "zod-form-data": "*"+ },+ "devDependencies": {+ "@carbon/tailwind": "*",+ "@carbon/tsconfig": "*",+ "@types/react": "^18.2.74",+ "@types/react-dom": "^18.2.24",+ "autoprefixer": "10.4.14",+ "cross-env": "7.0.3",+ "nodemon": "^3.0.1",+ "npm-run-all": "^4.1.5",+ "postcss": "^8.4.33",+ "tailwind-scrollbar": "^2.0.1",+ "tailwind-scrollbar-hide": "^1.1.7",+ "tailwindcss": "3.4.6",+ "typescript": "^5.2.2",+ "vite": "^5.3.3",+ "vite-tsconfig-paths": "^4.3.2",+ "wait-on": "7.2.0"+ }+ },+ "apps/university/node_modules/@upstash/ratelimit": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/@upstash/ratelimit/-/ratelimit-2.0.5.tgz",+ "integrity": "sha512-1FRv0cs3ZlBjCNOCpCmKYmt9BYGIJf0J0R3pucOPE88R21rL7jNjXG+I+rN/BVOvYJhI9niRAS/JaSNjiSICxA==",+ "dependencies": {+ "@upstash/core-analytics": "^0.0.10"+ },+ "peerDependencies": {+ "@upstash/redis": "^1.34.3"+ }+ },+ "apps/university/node_modules/@upstash/redis": {+ "version": "1.35.0",+ "resolved": "https://registry.npmjs.org/@upstash/redis/-/redis-1.35.0.tgz",+ "integrity": "sha512-WUm0Jz1xN4DBDGeJIi2Y0kVsolWRB2tsVds4SExaiLg4wBdHFMB+8IfZtBWr+BP0FvhuBr5G1/VLrJ9xzIWHsg==",+ "peer": true,+ "dependencies": {+ "uncrypto": "^0.1.3"+ }+ },"ci": {"version": "0.0.1","dependencies": {@@ -28758,6 +28835,15 @@"react-dom": ">=16.8.0"}},+ "node_modules/react-confetti-explosion": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/react-confetti-explosion/-/react-confetti-explosion-3.0.3.tgz",+ "integrity": "sha512-ow5ns/1ttzXsIlbbfJmWJNiyQK8lTHBL6lRSUXGaK44K/3NIMngR57Ja96l+D6txTeFhfe0BfXGvORMxhtRDng==",+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },"node_modules/react-css-styled": {"version": "1.1.9","resolved": "https://registry.npmjs.org/react-css-styled/-/react-css-styled-1.1.9.tgz",@@ -33853,6 +33939,10 @@"node": ">= 10.0.0"}},+ "node_modules/university": {+ "resolved": "apps/university",+ "link": true+ },"node_modules/unpipe": {"version": "1.0.0","resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 5656bd4ca3..fdd92f5b6e 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -1904,6 +1904,126 @@ export type Database = {},]}+ challengeAttempt: {+ Row: {+ courseId: string+ createdAt: string+ id: number+ passed: boolean+ topicId: string+ userId: string+ }+ Insert: {+ courseId: string+ createdAt?: string+ id?: number+ passed?: boolean+ topicId: string+ userId: string+ }+ Update: {+ courseId?: string+ createdAt?: string+ id?: number+ passed?: boolean+ topicId?: string+ userId?: string+ }+ Relationships: [+ {+ foreignKeyName: "challengeAttempt_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "challengeAttempt_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "challengeAttempt_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "challengeAttempt_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "challengeAttempt_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ challengeCompletion: {+ Row: {+ courseId: string+ createdAt: string+ topicId: string+ userId: string+ }+ Insert: {+ courseId: string+ createdAt?: string+ topicId: string+ userId: string+ }+ Update: {+ courseId?: string+ createdAt?: string+ topicId?: string+ userId?: string+ }+ Relationships: [+ {+ foreignKeyName: "challengeCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "challengeCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "challengeCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "challengeCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "challengeCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }company: {Row: {addressLine1: string | null@@ -11412,6 +11532,63 @@ export type Database = {},]}+ lessonCompletion: {+ Row: {+ courseId: string+ createdAt: string+ lessonId: string+ userId: string+ }+ Insert: {+ courseId: string+ createdAt?: string+ lessonId: string+ userId: string+ }+ Update: {+ courseId?: string+ createdAt?: string+ lessonId?: string+ userId?: string+ }+ Relationships: [+ {+ foreignKeyName: "lessonCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "lessonCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "lessonCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "lessonCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "lessonCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }location: {Row: {addressLine1: stringdiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 5656bd4ca3..fdd92f5b6e 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -1904,6 +1904,126 @@ export type Database = {},]}+ challengeAttempt: {+ Row: {+ courseId: string+ createdAt: string+ id: number+ passed: boolean+ topicId: string+ userId: string+ }+ Insert: {+ courseId: string+ createdAt?: string+ id?: number+ passed?: boolean+ topicId: string+ userId: string+ }+ Update: {+ courseId?: string+ createdAt?: string+ id?: number+ passed?: boolean+ topicId?: string+ userId?: string+ }+ Relationships: [+ {+ foreignKeyName: "challengeAttempt_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "challengeAttempt_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "challengeAttempt_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "challengeAttempt_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "challengeAttempt_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ challengeCompletion: {+ Row: {+ courseId: string+ createdAt: string+ topicId: string+ userId: string+ }+ Insert: {+ courseId: string+ createdAt?: string+ topicId: string+ userId: string+ }+ Update: {+ courseId?: string+ createdAt?: string+ topicId?: string+ userId?: string+ }+ Relationships: [+ {+ foreignKeyName: "challengeCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "challengeCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "challengeCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "challengeCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "challengeCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }company: {Row: {addressLine1: string | null@@ -11412,6 +11532,63 @@ export type Database = {},]}+ lessonCompletion: {+ Row: {+ courseId: string+ createdAt: string+ lessonId: string+ userId: string+ }+ Insert: {+ courseId: string+ createdAt?: string+ lessonId: string+ userId: string+ }+ Update: {+ courseId?: string+ createdAt?: string+ lessonId?: string+ userId?: string+ }+ Relationships: [+ {+ foreignKeyName: "lessonCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "lessonCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "lessonCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "lessonCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "lessonCompletion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }location: {Row: {addressLine1: stringdiff --git a/packages/database/supabase/migrations/20250628020925_university.sql b/packages/database/supabase/migrations/20250628020925_university.sqlnew file mode 100644index 0000000000..b7ea235786--- /dev/null+++ b/packages/database/supabase/migrations/20250628020925_university.sql@@ -0,0 +1,43 @@+CREATE TABLE "lessonCompletion" (+ "userId" TEXT NOT NULL,+ "courseId" TEXT NOT NULL,+ "lessonId" TEXT NOT NULL,+ "createdAt" timestamp with time zone NOT NULL DEFAULT now(),+ PRIMARY KEY ("userId", "courseId", "lessonId"),+ FOREIGN KEY ("userId") REFERENCES "user"("id")+);+++CREATE INDEX "lessonCompletion_userId_courseId_lessonId_idx" ON "lessonCompletion" ("userId", "courseId", "lessonId");+CREATE INDEX "lessonCompletion_courseId_idx" ON "lessonCompletion" ("courseId");++ALTER TABLE "lessonCompletion" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "lessonCompletion"+ FOR SELECT USING (auth.uid()::text = "userId");++CREATE POLICY "INSERT" ON "lessonCompletion"+ FOR INSERT WITH CHECK (auth.uid()::text = "userId");+++CREATE TABLE "challengeAttempt" (+ "id" SERIAL PRIMARY KEY,+ "userId" TEXT NOT NULL,+ "courseId" TEXT NOT NULL,+ "passed" BOOLEAN NOT NULL DEFAULT FALSE,+ "topicId" TEXT NOT NULL,+ "createdAt" timestamp with time zone NOT NULL DEFAULT now(),++ FOREIGN KEY ("userId") REFERENCES "user"("id")+);++CREATE INDEX "challengeAttempt_userId_courseId_topicId_idx" ON "challengeAttempt" ("userId", "courseId", "topicId");+CREATE INDEX "challengeAttempt_courseId_idx" ON "challengeAttempt" ("courseId");++ALTER TABLE "challengeAttempt" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "challengeAttempt"+ FOR SELECT USING (auth.uid()::text = "userId");++CREATE POLICY "INSERT" ON "challengeAttempt"+ FOR INSERT WITH CHECK (auth.uid()::text = "userId");\ No newline at end of file