Connect, collaborate, and grow with a community of TypeScript developers
feat: show number of problems solved on profile (#1109)
Ayush Kumar Yadav59ce1fc601c9
diff --git a/apps/web/src/app/[locale]/(profile)/[username]/_components/dashboard/_actions.ts b/apps/web/src/app/[locale]/(profile)/[username]/_components/dashboard/_actions.tsindex 831efd69..048aee62 100644--- a/apps/web/src/app/[locale]/(profile)/[username]/_components/dashboard/_actions.ts+++ b/apps/web/src/app/[locale]/(profile)/[username]/_components/dashboard/_actions.ts@@ -1,6 +1,8 @@'use server';import { prisma } from '@repo/db';+import { getServerAuthSession } from '@repo/auth/server';+import type { DIFFICULTIES } from './challenges-progress';export type HistoricalChallenge = Awaited<ReturnType<typeof getChallengeHistoryByCategory>>[0];@@ -64,3 +66,89 @@ export async function getChallengeHistoryByCategory(type: HistoryType, userId: snew Date(challengeA.submissionDate!).getTime(),);}++export async function getSolvedChallenges() {+ const session = await getServerAuthSession();++ const successfulSubmissions = await prisma.submission.findMany({+ where: {+ userId: session?.user.id,+ isSuccessful: true,+ },+ select: {+ challenge: {+ select: {+ id: true,+ },+ },+ },+ distinct: ['challengeId'],+ });++ const challengesSolved = await prisma.challenge.groupBy({+ by: ['difficulty'],+ where: {+ id: {+ in: successfulSubmissions.map((challenge) => challenge.challenge.id),+ },+ },+ _count: {+ _all: true,+ },+ });++ const allChallenges = await prisma.challenge.groupBy({+ by: ['difficulty'],+ _count: {+ _all: true,+ },+ });++ const totalSolved = challengesSolved.reduce((acc, challenge) => acc + challenge._count._all, 0);+ const totalChallenges = allChallenges.reduce((acc, challenge) => acc + challenge._count._all, 0);+ const percentage = ((totalSolved / totalChallenges) * 100).toFixed(1);++ const challenges: Record<+ (typeof DIFFICULTIES)[number],+ {+ solved: number;+ total: number;+ }+ > = {+ BEGINNER: {+ solved: 0,+ total: 0,+ },+ EASY: {+ solved: 0,+ total: 0,+ },+ MEDIUM: {+ solved: 0,+ total: 0,+ },+ HARD: {+ solved: 0,+ total: 0,+ },+ EXTREME: {+ solved: 0,+ total: 0,+ },+ };++ // assign values+ allChallenges.forEach((challenge) => {+ const difficulty = challenge.difficulty as (typeof DIFFICULTIES)[number];+ challenges[difficulty].total = challenge._count._all;+ challenges[difficulty].solved =+ challengesSolved.find((challenge) => challenge.difficulty === difficulty)?._count._all ?? 0;+ });++ return {+ challenges,+ totalSolved,+ totalChallenges,+ percentage,+ };+}diff --git a/apps/web/src/app/[locale]/(profile)/[username]/_components/dashboard/challenges-progress.tsx b/apps/web/src/app/[locale]/(profile)/[username]/_components/dashboard/challenges-progress.tsxnew file mode 100644index 00000000..b28f308b--- /dev/null+++ b/apps/web/src/app/[locale]/(profile)/[username]/_components/dashboard/challenges-progress.tsx@@ -0,0 +1,63 @@+import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '@repo/ui/components/card';+import { DifficultyBadge } from '@repo/ui/components/difficulty-badge';+import { Progress } from '@repo/ui/components/progress';+import { getSolvedChallenges } from './_actions';++export const DIFFICULTIES = ['BEGINNER', 'EASY', 'MEDIUM', 'HARD', 'EXTREME'] as const;++export async function ChallengesProgress() {+ const { challenges, percentage, totalChallenges, totalSolved } = await getSolvedChallenges();+ return (+ <Card className="flex-grow">+ <CardHeader>+ <CardTitle>Challenges</CardTitle>+ </CardHeader>+ <CardContent>+ <div className="flex flex-grow flex-col gap-2 text-xl">+ {DIFFICULTIES.map((difficulty) => (+ <div key={difficulty} className="flex items-center gap-4 md:gap-6">+ <DifficultyBadge+ className="w-full max-w-[80px] justify-center"+ difficulty={difficulty}+ />+ <Progress+ indicatorClassName={`bg-opacity-75 ${getProgressBarColor(difficulty)}`}+ className="h-1"+ value={(challenges[difficulty].solved / challenges[difficulty].total) * 100}+ />+ <div className="w-16 text-center md:w-20">+ {challenges[difficulty].solved}+ <span className="text-muted-foreground text-sm">+ /{challenges[difficulty].total}+ </span>+ </div>+ </div>+ ))}+ </div>+ </CardContent>+ <CardFooter>+ <div className="text-muted-foreground text-sm">+ Solved: <span className="text-foreground text-xl">{totalSolved}</span>/{totalChallenges} (+ {percentage}%)+ </div>+ </CardFooter>+ </Card>+ );+}++const getProgressBarColor = (difficulty: string) => {+ switch (difficulty) {+ case 'BEGINNER':+ return 'dark:bg-blue-300 bg-blue-700';+ case 'EASY':+ return 'dark:bg-green-300 bg-green-700';+ case 'MEDIUM':+ return 'dark:bg-yellow-300 bg-yellow-700';+ case 'HARD':+ return 'dark:bg-red-300 bg-red-700';+ case 'EXTREME':+ return 'dark:bg-purple-300 bg-purple-700';+ default:+ return '';+ }+};diff --git a/apps/web/src/app/[locale]/(profile)/[username]/_components/dashboard/overview-tab.tsx b/apps/web/src/app/[locale]/(profile)/[username]/_components/dashboard/overview-tab.tsxindex 97f88a8f..a6edff96 100644--- a/apps/web/src/app/[locale]/(profile)/[username]/_components/dashboard/overview-tab.tsx+++ b/apps/web/src/app/[locale]/(profile)/[username]/_components/dashboard/overview-tab.tsx@@ -1,6 +1,7 @@import type { User } from '@repo/db/types';import { Card, CardContent, CardHeader, CardTitle } from '@repo/ui/components/card';import { Markdown } from '@repo/ui/components/markdown';+import { ChallengesProgress } from './challenges-progress';interface Props {// TODO: how do do this union type with just letting prisma halp@@ -13,18 +14,26 @@ export async function OverviewTab({ user }: Props) {const hasBio = Boolean(user.bio) && user.bio.trim().length > 0;return (- <Card className="col-span-4 md:min-h-[calc(100vh_-_56px_-_6rem)]">- <CardHeader>- <CardTitle>Overview</CardTitle>- </CardHeader>- <CardContent>- <div className="w-full text-sm">- {Boolean(hasBio) && <Markdown>{user.bio}</Markdown>}- {Boolean(!hasBio) && (- <p className="text-muted-foreground">{user.name} does not have a bio.</p>- )}- </div>- </CardContent>- </Card>+ <div className="col-span-4 flex flex-col gap-6 md:min-h-[calc(100vh_-_56px_-_6rem)]">+ <div className="flex flex-col md:flex-row md:gap-6">+ <ChallengesProgress />+ {/* //Todo: Filling with void for now, may put contributions / something else */}+ <div className="max-w-sm flex-grow" />+ </div>+ <Card className="flex-grow">+ <CardHeader>+ <CardTitle>Bio</CardTitle>+ </CardHeader>+ <CardContent>+ <div className="w-full text-sm">+ {hasBio ? (+ <Markdown>{user.bio}</Markdown>+ ) : (+ <p className="text-muted-foreground">{user.name} does not have a bio.</p>+ )}+ </div>+ </CardContent>+ </Card>+ </div>);}diff --git a/packages/ui/src/components/difficulty-badge.tsx b/packages/ui/src/components/difficulty-badge.tsxindex b1db30bc..e0f69884 100644--- a/packages/ui/src/components/difficulty-badge.tsx+++ b/packages/ui/src/components/difficulty-badge.tsx@@ -1,8 +1,10 @@import { type Difficulty } from '@repo/db/types';import { Badge } from './badge';+import { cn } from '../cn';interface Props {difficulty: Difficulty;+ className?: string;}const COLORS_BY_DIFFICULTY = {@@ -13,10 +15,13 @@ const COLORS_BY_DIFFICULTY = {EXTREME: 'dark:bg-difficulty-extreme-dark bg-difficulty-extreme',};-export function DifficultyBadge({ difficulty }: Props) {+export function DifficultyBadge({ className, difficulty }: Props) {return (<Badge- className={`duration-300 ${COLORS_BY_DIFFICULTY[difficulty]} text-white dark:text-black`}+ className={cn(+ `duration-300 ${COLORS_BY_DIFFICULTY[difficulty]} text-white dark:text-black`,+ className,+ )}>{difficulty}</Badge>diff --git a/packages/ui/src/components/progress.tsx b/packages/ui/src/components/progress.tsxindex 853595f0..c314b8ef 100644--- a/packages/ui/src/components/progress.tsx+++ b/packages/ui/src/components/progress.tsx@@ -4,17 +4,21 @@ import * as ProgressPrimitive from '@radix-ui/react-progress';import * as React from 'react';import { cn } from '../cn';+interface ProgressIndicator {+ indicatorClassName?: string;+}+const Progress = React.forwardRef<- React.ElementRef<typeof ProgressPrimitive.Root>,- React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>->(({ className, value, ...props }, ref) => (+ ProgressIndicator & React.ElementRef<typeof ProgressPrimitive.Root>,+ ProgressIndicator & React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>+>(({ indicatorClassName, className, value, ...props }, ref) => (<ProgressPrimitive.Rootref={ref}className={cn('bg-secondary relative h-4 w-full overflow-hidden rounded-full', className)}{...props}><ProgressPrimitive.Indicator- className="bg-primary h-full w-full flex-1 transition-all"+ className={cn('bg-primary h-full w-full flex-1 transition-all', indicatorClassName)}style={{ transform: `translateX(-${100 - (value || 0)}%)` }}/></ProgressPrimitive.Root>