All files / src/app/student-page/page/dashboard/components AchievementsCard.jsx

97.72% Statements 43/44
94.11% Branches 48/51
100% Functions 6/6
100% Lines 36/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175                                              1x 25x 16x 13x 11x 2x 1x     1x 78x 78x 78x 78x   78x 26x 26x 26x 26x 26x 26x 24x 23x 26x   2x 2x 2x 2x   26x     26x 26x 26x       78x   78x                                                                               25x 25x   25x     25x                                                                                                                              
import { useEffect, useState } from "react";
import axios from "axios";
import {
    Box,
    Card,
    CardContent,
    Chip,
    CircularProgress,
    LinearProgress,
    Stack,
    Tooltip,
    Typography,
    useTheme,
} from "@mui/material";
import EmojiEventsIcon from "@mui/icons-material/EmojiEvents";
import RocketLaunchIcon from "@mui/icons-material/RocketLaunch";
import StarIcon from "@mui/icons-material/Star";
import LocalFireDepartmentIcon from "@mui/icons-material/LocalFireDepartment";
import MilitaryTechIcon from "@mui/icons-material/MilitaryTech";
import LockIcon from "@mui/icons-material/Lock";
import { API_ENDPOINTS } from "@/api/endpoints";
import { sortAchievements } from "./sortAchievements";
 
const _iconFor = (slug) => {
    if (slug === "rocket") return RocketLaunchIcon;
    if (slug === "star") return StarIcon;
    if (slug === "trophy") return EmojiEventsIcon;
    if (slug === "flame") return LocalFireDepartmentIcon;
    if (slug === "medal") return MilitaryTechIcon;
    return EmojiEventsIcon;
};
 
const AchievementsCard = ({ refreshKey }) => {
    const theme = useTheme();
    const [data, setData] = useState({ sorted: [], earnedCount: 0, lockedCount: 0 });
    const [isLoading, setIsLoading] = useState(false);
    const [hasError, setHasError] = useState(false);
 
    useEffect(() => {
        let cancelled = false;
        const fetchAchievements = async () => {
            setIsLoading(true);
            setHasError(false);
            try {
                const response = await axios.get(API_ENDPOINTS.student.dashboard.achievements);
                if (cancelled) return;
                const list = Array.isArray(response?.data?.achievements) ? response.data.achievements : [];
                setData(sortAchievements(list));
            } catch (error) {
                Iif (cancelled) return;
                console.error("EI-2966 achievements fetch error:", error?.response?.data || error?.message);
                setHasError(true);
                setData({ sorted: [], earnedCount: 0, lockedCount: 0 });
            } finally {
                if (!cancelled) setIsLoading(false);
            }
        };
        fetchAchievements();
        return () => {
            cancelled = true;
        };
    }, [refreshKey]);
 
    const { sorted, earnedCount, lockedCount } = data;
 
    return (
        <Card id="student-dashboard-achievements-card" sx={{ borderRadius: 2 }}>
            <CardContent>
                <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 2 }}>
                    <EmojiEventsIcon color="primary" />
                    <Typography variant="h6" sx={{ fontWeight: 600 }}>
                        Achievements
                    </Typography>
                    <Box sx={{ flexGrow: 1 }} />
                    <Chip
                        id="student-dashboard-achievements-earned-count"
                        label={`${earnedCount}/${earnedCount + lockedCount}`}
                        size="small"
                        color={earnedCount > 0 ? "primary" : "default"}
                    />
                </Stack>
 
                {isLoading ? (
                    <Box sx={{ py: 3, textAlign: "center" }}>
                        <CircularProgress size={24} />
                    </Box>
                ) : hasError ? (
                    <Typography
                        id="student-dashboard-achievements-error"
                        variant="body2"
                        color="error"
                    >
                        Unable to load achievements. Please try again later.
                    </Typography>
                ) : sorted.length === 0 ? (
                    <Typography
                        id="student-dashboard-achievements-empty"
                        variant="body2"
                        color="text.secondary"
                    >
                        No achievements yet — start submitting assignments to earn badges!
                    </Typography>
                ) : (
                    <Stack spacing={1.25}>
                        {sorted.map((a) => {
                            const IconCmp = _iconFor(a.icon);
                            const isEarned = !!a.earned;
                            const progressPct =
                                a.target && Number.isFinite(a.target)
                                    ? Math.min(100, Math.round(((a.progress || 0) / a.target) * 100))
                                    : null;
                            return (
                                <Tooltip key={a.id} title={a.description || ""} placement="top" arrow>
                                    <Stack
                                        direction="row"
                                        spacing={1.5}
                                        alignItems="center"
                                        data-achievement-id={a.id}
                                        data-achievement-earned={isEarned ? "true" : "false"}
                                        sx={{
                                            opacity: isEarned ? 1 : 0.55,
                                            transition: "opacity 0.2s",
                                        }}
                                    >
                                        <Box
                                            sx={{
                                                width: 40,
                                                height: 40,
                                                borderRadius: 1,
                                                bgcolor: isEarned ? "primary.lighter" : "action.hover",
                                                color: isEarned ? "primary.main" : "text.disabled",
                                                display: "flex",
                                                alignItems: "center",
                                                justifyContent: "center",
                                                flexShrink: 0,
                                            }}
                                        >
                                            {isEarned ? (
                                                <IconCmp fontSize="medium" />
                                            ) : (
                                                <LockIcon fontSize="small" />
                                            )}
                                        </Box>
                                        <Box sx={{ flexGrow: 1, minWidth: 0 }}>
                                            <Typography variant="body2" sx={{ fontWeight: 600 }} noWrap>
                                                {a.title}
                                            </Typography>
                                            {progressPct !== null && !isEarned && (
                                                <Stack direction="row" spacing={1} alignItems="center">
                                                    <Box sx={{ flexGrow: 1 }}>
                                                        <LinearProgress
                                                            variant="determinate"
                                                            value={progressPct}
                                                            sx={{ height: 4, borderRadius: 2 }}
                                                        />
                                                    </Box>
                                                    <Typography variant="caption" color="text.secondary">
                                                        {a.progress || 0}/{a.target}
                                                    </Typography>
                                                </Stack>
                                            )}
                                        </Box>
                                    </Stack>
                                </Tooltip>
                            );
                        })}
                    </Stack>
                )}
            </CardContent>
        </Card>
    );
};
 
export default AchievementsCard;