Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 37 additions & 90 deletions src/pages-desktop/dashboard/academic-calendar.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { useState, useEffect, useMemo } from "react";
import { useState, useEffect, useMemo, useCallback } from "react";
import { useAuth } from "@/hooks/useAuth";
import {
getAcademicCalendarOptions,
getAcademicCalendarView,
CalendarMonthOption,
MonthlySchedule,
} from "@/lib/features";
import { useOfflineData } from "@/hooks/use-offline-data";

import { ErrorDisplay } from "@/components/error-display";
import {
Expand Down Expand Up @@ -104,101 +105,47 @@ type CalendarCell = {

export default function AcademicCalendarPage() {
const { loading: authLoading } = useAuth();
const [options, setOptions] = useState<CalendarMonthOption[] | null>(null);
const {
data: optionsData,
loading: optionsLoading,
error: optionsError,
retry: fetchOptions,
} = useOfflineData<CalendarMonthOption[]>({
cacheKey: "deskly::cache::calendar_options",
fetcher: getAcademicCalendarOptions,
});

const options = optionsData;
const [selectedOption, setSelectedOption] = useState<CalendarMonthOption | null>(null);
const [schedule, setSchedule] = useState<MonthlySchedule | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);

// Selected cell details in side panel
const [selectedCell, setSelectedCell] = useState<CalendarCell | null>(null);

// Load options from cache first
useEffect(() => {
const cachedOptions = localStorage.getItem("deskly::cache::calendar_options");
if (cachedOptions) {
try {
const parsed = JSON.parse(cachedOptions);
if (parsed && parsed.length > 0) {
setOptions(parsed);
setSelectedOption(parsed[0]);
}
} catch (e) {
console.error("Failed to parse cached academic calendar options", e);
}
if (optionsData && optionsData.length > 0 && !selectedOption) {
setSelectedOption(optionsData[0]);
}
}, []);
}, [optionsData, selectedOption]);

const {
data: scheduleData,
loading: viewLoading,
error: viewError,
retry: retryView,
} = useOfflineData<MonthlySchedule>({
cacheKey: selectedOption ? `deskly::cache::calendar_view_${selectedOption.dateValue}` : "",
fetcher: () => getAcademicCalendarView(selectedOption!.dateValue),
enabled: !!selectedOption,
});

const schedule = scheduleData;
const loading = optionsLoading || viewLoading;
const error = optionsError || viewError;

// Load monthly view from cache first when selectedOption changes
useEffect(() => {
if (selectedOption) {
const cachedView = localStorage.getItem(`deskly::cache::calendar_view_${selectedOption.dateValue}`);
if (cachedView) {
try {
const parsed = JSON.parse(cachedView);
if (parsed && parsed.days && parsed.days.length > 0) {
setSchedule(parsed);
setLoading(false);
return;
}
} catch (e) {
console.error("Failed to parse cached calendar view", e);
}
}
setSchedule(null);
setLoading(true);
}
}, [selectedOption]);

const fetchOptions = async () => {
setLoading(options && options.length > 0 ? false : true);
setError(null);
try {
const res = await getAcademicCalendarOptions();
if (res.success && res.data && res.data.length > 0) {
setOptions(res.data);
localStorage.setItem("deskly::cache::calendar_options", JSON.stringify(res.data));
if (!selectedOption) {
setSelectedOption(res.data[0]);
}
} else {
setError(res.error ?? "No academic calendar semesters found.");
setLoading(false);
}
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
setLoading(false);
}
};

const fetchView = async (dateVal: string) => {
setLoading(schedule ? false : true);
setError(null);
try {
const res = await getAcademicCalendarView(dateVal);
if (res.success && res.data) {
setSchedule(res.data);
localStorage.setItem(`deskly::cache::calendar_view_${dateVal}`, JSON.stringify(res.data));
setSelectedCell(null); // Reset day details view on month change
} else {
setError(res.error ?? "Failed to load academic calendar view.");
}
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setLoading(false);
}
};

useEffect(() => {
fetchOptions();
}, []);
// Selected cell details in side panel
const [selectedCell, setSelectedCell] = useState<CalendarCell | null>(null);

useEffect(() => {
if (selectedOption) {
fetchView(selectedOption.dateValue);
}
}, [selectedOption]);
const fetchView = useCallback((_dateVal?: string) => {
setSelectedCell(null);
retryView();
}, [retryView]);

// Calendar Math: construct 35-42 grid cells based on loaded schedule and options
const calendarCells = useMemo(() => {
Expand Down
67 changes: 22 additions & 45 deletions src/pages-desktop/dashboard/attendance.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { useState, useEffect, useMemo } from "react";
import { useState, useMemo } from "react";
import { useAuth } from "@/hooks/useAuth";
import { getCurrentAttendance, AttendanceRecord } from "@/lib/attendance";
import { isNetworkError, fetchWithTimeout } from "@/lib/utils";
import { isNetworkError } from "@/lib/utils";
import { ErrorDisplay } from "@/components/error-display";
import { useOnlineStatus } from "@/hooks/use-online-status";
import { OfflineDisplay } from "@/components/offline-display";
import { Outlet, useMatch, useNavigate } from "react-router-dom";
import { useOfflineData } from "@/hooks/use-offline-data";
import {
UserCheck,
CalendarDays,
Expand Down Expand Up @@ -247,49 +248,25 @@ export default function AttendancePage() {
const isDetailRoute = useMatch("/dashboard/attendance/:classId");
const isOnline = useOnlineStatus();

const [attendance, setAttendance] = useState<AttendanceRecord[]>(() => {
try {
const cached = localStorage.getItem("deskly::cache::attendance");
if (cached) {
const parsed = JSON.parse(cached) as AttendanceRecord[];
if (Array.isArray(parsed) && parsed.length > 0) return parsed;
const {
data: attendanceRaw,
loading,
error,
retry,
} = useOfflineData<AttendanceRecord[]>({
cacheKey: "deskly::cache::attendance",
fetcher: async () => {
const res = await getCurrentAttendance();
if (res.success && res.semesterId) {
localStorage.setItem("deskly::cache::attendance_semester", res.semesterId);
}
} catch {}
return [];
return res;
},
enabled: isLoggedIn && !authLoading,
});
const [loading, setLoading] = useState(attendance.length === 0);
const [error, setError] = useState<string | null>(null);
const [filterType, setFilterType] = useState("all");

async function load() {
if (authLoading || !isLoggedIn) return;
setError(null);
const hasCache = attendance.length > 0;
setLoading(!hasCache);
try {
const res = await fetchWithTimeout(getCurrentAttendance(), 15000);
if (res.success && res.data) {
setAttendance(res.data);
const sem = res.semesterId ?? "";
localStorage.setItem("deskly::cache::attendance", JSON.stringify(res.data));
localStorage.setItem("deskly::cache::attendance_semester", sem);
} else {
if (!hasCache) {
setError(res.error ?? "Failed to fetch attendance.");
}
}
} catch (e) {
if (!hasCache) {
setError(e instanceof Error ? e.message : String(e));
}
} finally {
setLoading(false);
}
}

useEffect(() => {
if (isLoggedIn) load();
}, [isLoggedIn, authLoading]);
const attendance = useMemo(() => attendanceRaw || [], [attendanceRaw]);
const [filterType, setFilterType] = useState("all");

const stats = useMemo(() => {
let totalAttended = 0;
Expand Down Expand Up @@ -326,7 +303,7 @@ export default function AttendancePage() {
const showOffline = attendance.length === 0 && (isOnline === false || isNetworkError(error, isOnline));

if (showOffline) {
return <OfflineDisplay onRetry={load} />;
return <OfflineDisplay onRetry={retry} />;
}

if (authLoading || (loading && attendance.length === 0)) {
Expand All @@ -336,7 +313,7 @@ export default function AttendancePage() {
if (error && attendance.length === 0) {
return (
<div className="flex h-full items-center justify-center font-saira">
<ErrorDisplay message={error} onRetry={load} />
<ErrorDisplay message={error} onRetry={retry} />
</div>
);
}
Expand All @@ -349,7 +326,7 @@ export default function AttendancePage() {
{error && !isNetworkError(error, isOnline) && (
<div className="flex items-center justify-between gap-4 px-4 py-3 bg-destructive/10 border border-destructive/20 text-destructive rounded-lg">
<p className="text-xs font-semibold truncate">Sync failed — {error}</p>
<button onClick={load} className="text-xs font-bold uppercase tracking-wider shrink-0 border-0 bg-transparent text-destructive cursor-pointer">
<button onClick={retry} className="text-xs font-bold uppercase tracking-wider shrink-0 border-0 bg-transparent text-destructive cursor-pointer">
Retry
</button>
</div>
Expand Down
Loading
Loading