fix(api): fix api endpoint logic #5

chore(env): obscure api url in env

feat(ui): render subjects according to user preparation unit
This commit is contained in:
Dacca Retro
2025-08-18 15:06:50 +06:00
parent e3673951c6
commit 58d4d14a51
15 changed files with 3853 additions and 577 deletions

1
.env.example Normal file
View File

@ -0,0 +1 @@
NEXT_PUBLIC_EXAMJAM_API_URL=api_url_here

2
.gitignore vendored
View File

@ -31,7 +31,7 @@ yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
.env
# vercel
.vercel

View File

@ -9,7 +9,7 @@ import { House, LayoutGrid, Bookmark, Settings } from "lucide-react";
const tabs = [
{ name: "Home", href: "/home", component: <House size={30} /> },
{ name: "Unit", href: "/unit", component: <LayoutGrid size={30} /> },
{ name: "Subjects", href: "/subjects", component: <LayoutGrid size={30} /> },
{ name: "Bookmark", href: "/bookmark", component: <Bookmark size={30} /> },
{ name: "Settings", href: "/settings", component: <Settings size={30} /> },
];

View File

@ -8,49 +8,15 @@ import { API_URL, getToken } from "@/lib/auth";
import { BoardData, getLeaderboard } from "@/lib/leaderboard";
import { UserData } from "@/types/auth";
import React, { useEffect, useState } from "react";
import { useAuth } from "@/context/AuthContext";
const LeaderboardPage = () => {
const [boardError, setBoardError] = useState<string | null>(null);
const [boardData, setBoardData] = useState<BoardData[]>([]);
const [userData, setUserData] = useState<UserData>({
name: "",
institution: "",
sscRoll: "",
hscRoll: "",
email: "",
phone: "",
});
const {user, isLoading} = useAuth()
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchUser() {
try {
const token = await getToken();
if (!token) throw new Error("User is not authenticated");
const response = await fetch(`${API_URL}/me`, {
method: "get",
headers: { Authorization: `Bearer ${token}` },
});
if (!response.ok) throw new Error("Failed to fetch user data");
const fetchedUserData = await response.json();
setLoading(false);
setUserData(fetchedUserData);
} catch (error) {
console.error(error);
setUserData({
name: "",
institution: "",
sscRoll: "",
hscRoll: "",
email: "",
phone: "",
});
}
}
async function fetchBoardData() {
try {
@ -75,10 +41,8 @@ const LeaderboardPage = () => {
setBoardData([]);
}
}
fetchUser();
fetchBoardData();
}, []);
}
const getTopThree = (boardData: BoardData[]) => {
if (!boardData || !Array.isArray(boardData)) return [];

View File

@ -1,122 +0,0 @@
"use client";
import { useSearchParams } from "next/navigation";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import Header from "@/components/Header";
import DestructibleAlert from "@/components/DestructibleAlert";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { API_URL } from "@/lib/auth";
import { Loader, RefreshCw } from "lucide-react";
interface Mock {
id: string;
title: string;
rating: number;
}
export default function PaperScreen() {
const router = useRouter();
const searchParams = useSearchParams();
const name = searchParams.get("name") || "";
const [questions, setQuestions] = useState<Mock[] | null>(null);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState<boolean>(false);
const [componentKey, setComponentKey] = useState<number>(0);
async function fetchMocks() {
try {
const questionResponse = await fetch(`${API_URL}/mocks`, {
method: "GET",
});
const fetchedQuestionData: Mock[] = await questionResponse.json();
setQuestions(fetchedQuestionData);
} catch (error) {
setErrorMsg(error instanceof Error ? error.message : "An error occurred");
}
}
useEffect(() => {
if (name) {
fetchMocks();
}
}, [name]);
const onRefresh = async () => {
setRefreshing(true);
await fetchMocks();
setComponentKey((prevKey) => prevKey + 1);
setTimeout(() => {
setRefreshing(false);
}, 1000);
};
if (errorMsg) {
return (
<BackgroundWrapper>
<Header displayTabTitle={name} />
<div className="overflow-y-auto">
<div className="mt-5 px-5">
<DestructibleAlert text={errorMsg} extraStyles="" />
</div>
<div className="flex justify-center mt-4">
<button
onClick={onRefresh}
disabled={refreshing}
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50"
>
{refreshing ? <Loader /> : <RefreshCw />}
</button>
</div>
</div>
</BackgroundWrapper>
);
}
return (
<BackgroundWrapper>
<div>
<Header displayTabTitle={name} />
<div className="mx-10 pt-10 overflow-y-auto">
<div className="border border-[#c0dafc] flex flex-col gap-4 w-full rounded-[25px] p-4">
{questions ? (
questions.map((mock) => (
<div key={mock.id}>
<button
onClick={() =>
router.push(
`/exam/pretest?unitname=${name}&id=${mock.id}&title=${mock.title}&rating=${mock.rating}`
)
}
className="w-full border-2 border-[#B0C2DA] py-4 rounded-[10px] px-6 gap-2 text-left hover:bg-gray-50 transition-colors"
>
<h3 className="text-xl font-medium">{mock.title}</h3>
<p className="text-md font-normal">
Rating: {mock.rating} / 10
</p>
</button>
</div>
))
) : (
<div className="flex flex-col items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
<p className="text-xl font-medium text-center">Loading...</p>
</div>
)}
</div>
<div className="flex justify-center mt-4">
<button
onClick={onRefresh}
disabled={refreshing}
className="p-2 bg-blue-500 text-white hover:bg-blue-600 disabled:opacity-50 rounded-full"
>
{refreshing ? <Loader /> : <RefreshCw />}
</button>
</div>
</div>
</div>
{/* <CustomBackHandler fallbackRoute="unit" useCustomHandler={false} /> */}
</BackgroundWrapper>
);
}

View File

@ -0,0 +1,228 @@
"use client";
import { useSearchParams } from "next/navigation";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import Header from "@/components/Header";
import DestructibleAlert from "@/components/DestructibleAlert";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { API_URL } from "@/lib/auth";
import { Loader, RefreshCw } from "lucide-react";
import { v4 as uuidv4 } from "uuid";
import { useAuth } from "@/context/AuthContext";
interface Mock {
id: string;
title: string;
rating: number;
}
export default function PaperScreen() {
const router = useRouter();
const searchParams = useSearchParams();
const name = searchParams.get("name") || "";
const {user} = useAuth()
const [questions, setQuestions] = useState<Mock[] | null>(null);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState<boolean>(false);
const [componentKey, setComponentKey] = useState<number>(0);
interface Subject {
subject_id: string;
name: string;
unit: string;
}
const [subjects, setSubjects] = useState<Subject[]>([
{
subject_id: uuidv4(),
name: "Biology",
unit: "Science"
},
{
subject_id: uuidv4(),
name: "Chemistry",
unit: "Science"
},
{
subject_id: uuidv4(),
name: "Physics",
unit: "Science"
},
{
subject_id: uuidv4(),
name: "Accounting",
unit: "Business"
},
{
subject_id: uuidv4(),
name: "Finance",
unit: "Business"
},
{
subject_id: uuidv4(),
name: "Marketing",
unit: "Business"
},
{
subject_id: uuidv4(),
name: "History",
unit: "Humanities"
},
{
subject_id: uuidv4(),
name: "Geography",
unit: "Humanities"
},
{
subject_id: uuidv4(),
name: "Sociology",
unit: "Humanities"
},
]);
// async function fetchMocks() {
// try {
// const questionResponse = await fetch(`${API_URL}/mocks`, {
// method: "GET",
// });
// const fetchedQuestionData: Mock[] = await questionResponse.json();
// setQuestions(fetchedQuestionData);
// } catch (error) {
// setErrorMsg(error instanceof Error ? error.message : "An error occurred");
// }
// }
// useEffect(() => {
// if (name) {
// fetchMocks();
// }
// }, [name]);
const onRefresh = async () => {
setRefreshing(true);
setSubjects([{
subject_id: uuidv4(),
name: "Biology",
unit: "Science"
},
{
subject_id: uuidv4(),
name: "Chemistry",
unit: "Science"
},
{
subject_id: uuidv4(),
name: "Physics",
unit: "Science"
},
{
subject_id: uuidv4(),
name: "Accounting",
unit: "Business Studies"
},
{
subject_id: uuidv4(),
name: "Finance",
unit: "Business Studies"
},
{
subject_id: uuidv4(),
name: "Marketing",
unit: "Business Studies"
},
{
subject_id: uuidv4(),
name: "History",
unit: "Humanities"
},
{
subject_id: uuidv4(),
name: "Geography",
unit: "Humanities"
},
{
subject_id: uuidv4(),
name: "Sociology",
unit: "Humanities"
}])
setComponentKey((prevKey) => prevKey + 1);
setTimeout(() => {
setRefreshing(false);
}, 1000);
};
if (errorMsg) {
return (
<BackgroundWrapper>
<Header displayTabTitle={name} />
<div className="overflow-y-auto">
<div className="mt-5 px-5">
<DestructibleAlert text={errorMsg} extraStyles="" />
</div>
<div className="flex justify-center mt-4">
<button
onClick={onRefresh}
disabled={refreshing}
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50"
>
{refreshing ? <Loader /> : <RefreshCw />}
</button>
</div>
</div>
</BackgroundWrapper>
);
}
return (
<BackgroundWrapper>
<div>
<Header displayTabTitle="Subjects" />
<div className="mx-10 pt-10 overflow-y-auto">
<h1 className="text-2xl font-semibold mb-5">{user?.preparation_unit}</h1>
<div className="border border-[#c0dafc] flex flex-col gap-4 w-full rounded-[25px] p-4 mb-20">
{subjects ? (
subjects
.filter(subject => subject.unit === user?.preparation_unit)
.map((subject) => (
<div key={subject.subject_id}>
<button
onClick={() =>
router.push(
`/exam/pretest?unitname=${name}&id=${subject.subject_id}&title=${subject.name}`
)
}
className="w-full border-2 border-[#B0C2DA] py-4 rounded-[10px] px-6 space-y-2 text-left hover:bg-gray-50 transition-colors"
>
<h3 className="text-xl font-medium">{subject.name}</h3>
<p className="text-md font-normal">
Rating: 8/10
</p>
</button>
</div>
))
) : (
<div className="flex flex-col items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
<p className="text-xl font-medium text-center">Loading...</p>
</div>
)}
</div>
<div className="flex justify-center mt-4">
<button
onClick={onRefresh}
disabled={refreshing}
className="p-2 bg-blue-500 text-white hover:bg-blue-600 disabled:opacity-50 rounded-full"
>
{refreshing ? <Loader /> : <RefreshCw />}
</button>
</div>
</div>
</div>
{/* <CustomBackHandler fallbackRoute="unit" useCustomHandler={false} /> */}
</BackgroundWrapper>
);
}

View File

@ -4,11 +4,22 @@ import React from "react";
import { useRouter } from "next/navigation";
import Header from "@/components/Header";
import BackgroundWrapper from "@/components/BackgroundWrapper";
import { v4 as uuidv4 } from "uuid";
const units = [
{
id: 3,
name: "C Unit (Business Studies)",
id: uuidv4(),
name: "Science",
rating: 8,
},
{
id: uuidv4(),
name: "Business Studies",
rating: 8,
},
{
id: uuidv4(),
name: "Humanities",
rating: 9,
},
];
@ -17,7 +28,7 @@ const Unit = () => {
const router = useRouter();
const handleUnitPress = (unit: {
id?: number;
id: string;
name: string;
rating?: number;
}) => {
@ -27,10 +38,10 @@ const Unit = () => {
return (
<BackgroundWrapper>
<div className="flex flex-col min-h-screen">
<Header displayTabTitle="Units" />
<Header displayTabTitle="Subjects" />
<div className="flex-1">
<div className="overflow-y-auto">
<div className="border border-blue-200 gap-4 rounded-3xl p-4 mx-10 mt-10">
<div className="border border-blue-200 flex flex-col gap-4 rounded-3xl p-4 mx-10 mt-10">
{units ? (
units.map((unit) => (
<button

View File

@ -32,7 +32,6 @@ function PretestPageContent() {
const [metadata, setMetadata] = useState<Metadata | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string>();
console.log(loading);
useEffect(() => {
async function fetchQuestions() {

BIN
bun.lockb

Binary file not shown.

View File

@ -19,8 +19,6 @@ export default function ProfileManager({
setUserData((prev) => (prev ? { ...prev, [field]: value } : prev));
};
console.log(userData);
return (
<div className="mx-auto">
<div className="space-y-4">

View File

@ -72,7 +72,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
if (!res.ok) {
throw new Error("Failed to fetch user info");
}
console.log(API_URL)
const data: UserData = await res.json();
setUser(data);
} catch (error) {

View File

@ -1,6 +1,6 @@
import { LoginForm, RegisterForm } from "@/types/auth";
export const API_URL = "https://examjam-backend.omukk.dev";
export const API_URL = process.env.NEXT_PUBLIC_EXAMJAM_API_URL;
// Cookie utility function
const setCookie = (name: string, value: string | null, days: number = 7) => {

4001
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -19,7 +19,9 @@
"lucide-react": "^0.523.0",
"next": "15.3.2",
"react": "^19.0.0",
"react-dom": "^19.0.0"
"react-dom": "^19.0.0",
"tailwind-merge": "^3.3.1",
"uuid": "^11.1.0"
},
"devDependencies": {
"@capacitor/cli": "^7.4.2",

View File