Your favorite shift management application!
chore: Centralize calendar update and stats fetching into hooks (#89)
panteL8e3e75974c76
diff --git a/components/calendar-settings-sheet.tsx b/components/calendar-settings-sheet.tsxindex 3a6627a..712060d 100644--- a/components/calendar-settings-sheet.tsx+++ b/components/calendar-settings-sheet.tsx@@ -15,11 +15,8 @@ import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { Checkbox } from "@/components/ui/checkbox";-import {- removeCachedPassword,- setCachedPassword,- getCachedPassword,-} from "@/lib/password-cache";+import { getCachedPassword } from "@/lib/password-cache";+import { useCalendars } from "@/hooks/useCalendars";import { PRESET_COLORS } from "@/lib/constants";import { AlertTriangle, Trash2, Download } from "lucide-react";import { ExportDialog } from "@/components/export-dialog";@@ -58,6 +55,9 @@ export function CalendarSettingsSheet({onDelete,}: CalendarSettingsSheetProps) {const t = useTranslations();+ const { updateCalendar } = useCalendars();++ // Use props directly as initial state, controlled by key prop on componentconst [name, setName] = useState(calendarName);const [selectedColor, setSelectedColor] = useState(calendarColor);const [currentPassword, setCurrentPassword] = useState("");@@ -68,43 +68,28 @@ export function CalendarSettingsSheet({const [loading, setLoading] = useState(false);const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);const [showExportDialog, setShowExportDialog] = useState(false);- const [canExport, setCanExport] = useState(false);const [passwordError, setPasswordError] = useState(false);const initialFormStateRef = useRef<FormState | null>(null);const currentPasswordRef = useRef<HTMLInputElement>(null);+ // Calculate export permission based on password state (no useEffect needed)+ const canExport =+ !hasPassword || !isLocked || !!getCachedPassword(calendarId);++ // Initialize form state reference when openinguseEffect(() => {- if (open) {- setName(calendarName);- setSelectedColor(calendarColor);- setCurrentPassword("");- setNewPassword("");- setConfirmPassword("");- setRemovePassword(false);- setLockCalendar(isLocked);- setPasswordError(false);- setShowDeleteConfirm(false);- setShowExportDialog(false);-- // Store initial form state for change detection+ if (open && !initialFormStateRef.current) {initialFormStateRef.current = {name: calendarName,selectedColor: calendarColor,lockCalendar: isLocked,removePassword: false,};-- // Check if export is allowed (no password or password is cached)- if (!hasPassword || !isLocked) {- setCanExport(true);- } else {- const cachedPassword = getCachedPassword(calendarId);- setCanExport(!!cachedPassword);- }- } else {+ }+ if (!open) {initialFormStateRef.current = null;}- }, [open, calendarName, calendarColor, isLocked, hasPassword, calendarId]);+ }, [open, calendarName, calendarColor, isLocked]);const hasChanges = () => {if (!initialFormStateRef.current) return false;@@ -164,74 +149,28 @@ export function CalendarSettingsSheet({setLoading(true);- try {- const requestBody: {- name?: string;- color?: string;- currentPassword?: string;- isLocked: boolean;- password?: string | null;- } = {- name: name !== calendarName ? name : undefined,- color: selectedColor !== calendarColor ? selectedColor : undefined,- currentPassword: hasPassword ? currentPassword : undefined,- isLocked: lockCalendar,- };-- // Include password fields if changing password- if (removePassword) {- requestBody.password = null;- } else if (newPassword) {- requestBody.password = newPassword;- }-- const response = await fetch(`/api/calendars/${calendarId}`, {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(requestBody),- });-- if (response.status === 401) {- toast.error(t("validation.passwordIncorrect"));- setPasswordError(true);- currentPasswordRef.current?.focus();- setLoading(false);- return;- }+ const updates = {+ name: name !== calendarName ? name : undefined,+ color: selectedColor !== calendarColor ? selectedColor : undefined,+ currentPassword: hasPassword ? currentPassword : undefined,+ isLocked: lockCalendar,+ password: removePassword+ ? (null as null)+ : newPassword+ ? newPassword+ : undefined,+ };- if (!response.ok) {- const errorData = await response.json().catch(() => ({}));- toast.error(- errorData.error ||- t("common.updateError", { item: t("calendar.title") })- );- setLoading(false);- return;- }+ const result = await updateCalendar(calendarId, updates);- // Handle localStorage based on what changed- if (removePassword) {- // Only remove from localStorage if password was actually removed- removeCachedPassword(calendarId);- } else if (newPassword) {- // New password was set, update localStorage- setCachedPassword(calendarId, newPassword);- } else if (hasPassword && currentPassword) {- // Only isLocked changed, keep the current password cached- setCachedPassword(calendarId, currentPassword);- }+ setLoading(false);+ if (result.success) {onSuccess();onOpenChange(false);- } catch (error) {- console.error("Failed to update calendar:", error);- toast.error(- error instanceof Error- ? error.message- : t("common.updateError", { item: t("calendar.title") })- );- } finally {- setLoading(false);+ } else if (result.error === "unauthorized") {+ setPasswordError(true);+ currentPasswordRef.current?.focus();}};diff --git a/components/dialog-manager.tsx b/components/dialog-manager.tsxindex 0e946a0..25846f3 100644--- a/components/dialog-manager.tsx+++ b/components/dialog-manager.tsx@@ -130,6 +130,7 @@ export function DialogManager(props: DialogManagerProps) {/><CalendarSettingsSheet+ key={`settings-${props.selectedCalendar}-${props.showCalendarSettingsDialog}`}open={props.showCalendarSettingsDialog}onOpenChange={props.onCalendarSettingsDialogChange}calendarId={props.selectedCalendar}diff --git a/components/shift-stats.tsx b/components/shift-stats.tsxindex 5d24d66..8845f4e 100644--- a/components/shift-stats.tsx+++ b/components/shift-stats.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useEffect, useCallback, useRef } from "react";+import { useState, useEffect } from "react";import { useTranslations } from "next-intl";import { Button } from "@/components/ui/button";import {@@ -10,9 +10,27 @@ import {PieChart,Radar as RadarIcon,} from "lucide-react";-import { getCachedPassword } from "@/lib/password-cache";import { formatDuration } from "@/lib/date-utils";import { Skeleton } from "@/components/ui/skeleton";+import { useShiftStats } from "@/hooks/useShiftStats";+import {+ PieChart as RechartsPieChart,+ Pie,+ Cell,+ ResponsiveContainer,+ Tooltip,+ BarChart,+ Bar,+ XAxis,+ YAxis,+ CartesianGrid,+ Legend,+ RadarChart,+ PolarGrid,+ PolarAngleAxis,+ PolarRadiusAxis,+ Radar,+} from "recharts";// Hook for responsive radius that's SSR-safefunction useResponsiveRadius() {@@ -38,40 +56,38 @@ function useResponsiveRadius() {return radius;}-import {- PieChart as RechartsPieChart,- Pie,- Cell,- ResponsiveContainer,- Tooltip,- BarChart,- Bar,- XAxis,- YAxis,- CartesianGrid,- Legend,- RadarChart,- PolarGrid,- PolarAngleAxis,- PolarRadiusAxis,- Radar,-} from "recharts";--interface ShiftStats {- period: string;- startDate: string;- endDate: string;- stats: Record<string, { count: number; totalMinutes: number }>;- totalMinutes: number;- totalShifts: number;- avgMinutesPerShift: number;- avgShiftsPerDay: number;- avgMinutesPerDay: number;- minDuration: number;- maxDuration: number;- daysWithShifts: number;- trendData: Array<{ date: string; count: number; totalMinutes: number }>;-}+// CustomTooltip component - declared outside to avoid recreation on each render+const CustomTooltip = ({+ active,+ payload,+}: {+ active?: boolean;+ payload?: Array<{+ name: string;+ value: number;+ color: string;+ dataKey?: string;+ payload: { fullName?: string; name?: string };+ }>;+}) => {+ if (active && payload && payload.length) {+ return (+ <div className="bg-card/95 backdrop-blur-sm border border-border rounded-lg p-3 shadow-lg">+ <p className="font-semibold text-sm mb-1">+ {payload[0].payload.fullName || payload[0].name}+ </p>+ {payload.map((entry) => (+ <p key={entry.name} className="text-xs text-muted-foreground">+ <span style={{ color: entry.color }}>{entry.name}:</span>{" "}+ {entry.value}+ {entry.name === "hours" || entry.dataKey === "hours" ? "h" : ""}+ </p>+ ))}+ </div>+ );+ }+ return null;+};interface ShiftStatsProps {calendarId: string | undefined;@@ -104,55 +120,15 @@ export function ShiftStats({const t = useTranslations();const [period, setPeriod] = useState<"week" | "month" | "year">("month");const [viewMode, setViewMode] = useState<ViewMode>("overview");- const [stats, setStats] = useState<ShiftStats | null>(null);- const [loading, setLoading] = useState(false);const [isExpanded, setIsExpanded] = useState(true);- const isInitialLoadRef = useRef(true);const outerRadius = useResponsiveRadius();- const fetchStats = useCallback(- async (silent = false) => {- if (!calendarId) return;-- if (!silent) {- setLoading(true);- }-- try {- const password = getCachedPassword(calendarId);- const params = new URLSearchParams({- calendarId,- period,- date: currentDate.toISOString(),- });- if (password) {- params.append("password", password);- }-- const response = await fetch(`/api/shifts/stats?${params}`);- if (!response.ok) {- return; // Calendar is locked and no valid password- }- const data = await response.json();- setStats(data);- } catch (error) {- console.error("Failed to fetch shift statistics:", error);- } finally {- if (!silent) {- setLoading(false);- }- }- },- [calendarId, period, currentDate]- );-- // Fetch stats when dependencies change- useEffect(() => {- if (calendarId) {- fetchStats(!isInitialLoadRef.current);- isInitialLoadRef.current = false;- }- }, [calendarId, refreshTrigger, fetchStats]);+ const { stats, loading } = useShiftStats({+ calendarId,+ currentDate,+ period,+ refreshTrigger,+ });if (!calendarId) return null;@@ -195,38 +171,6 @@ export function ShiftStats({})): [];- const CustomTooltip = ({- active,- payload,- }: {- active?: boolean;- payload?: Array<{- name: string;- value: number;- color: string;- dataKey?: string;- payload: { fullName?: string; name?: string };- }>;- }) => {- if (active && payload && payload.length) {- return (- <div className="bg-card/95 backdrop-blur-sm border border-border rounded-lg p-3 shadow-lg">- <p className="font-semibold text-sm mb-1">- {payload[0].payload.fullName || payload[0].name}- </p>- {payload.map((entry) => (- <p key={entry.name} className="text-xs text-muted-foreground">- <span style={{ color: entry.color }}>{entry.name}:</span>{" "}- {entry.value}- {entry.name === "hours" || entry.dataKey === "hours" ? "h" : ""}- </p>- ))}- </div>- );- }- return null;- };-return (<div className="border border-border/50 rounded-xl bg-gradient-to-b from-card/80 via-card/60 to-card/40 backdrop-blur-sm overflow-hidden shadow-lg">{/* Header */}diff --git a/hooks/useCalendars.ts b/hooks/useCalendars.tsindex 155160f..98bfdb4 100644--- a/hooks/useCalendars.ts+++ b/hooks/useCalendars.ts@@ -94,6 +94,66 @@ export function useCalendars(initialCalendarId?: string | null) {}};+ const updateCalendar = async (+ calendarId: string,+ updates: {+ name?: string;+ color?: string;+ currentPassword?: string;+ isLocked: boolean;+ password?: string | null;+ }+ ) => {+ try {+ const response = await fetch(`/api/calendars/${calendarId}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(updates),+ });++ if (response.status === 401) {+ toast.error(t("validation.passwordIncorrect"));+ return { success: false, error: "unauthorized" as const };+ }++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ const errorMessage =+ errorData.error ||+ t("common.updateError", { item: t("calendar.title") });+ toast.error(errorMessage);+ return { success: false, error: "failed" as const };+ }++ const updatedCalendar = await response.json();++ // Update local state+ setCalendars((prev) =>+ prev.map((cal) => (cal.id === calendarId ? updatedCalendar : cal))+ );++ // Handle password caching+ if (updates.password === null) {+ removeCachedPassword(calendarId);+ } else if (updates.password) {+ setCachedPassword(calendarId, updates.password);+ } else if (updates.currentPassword) {+ setCachedPassword(calendarId, updates.currentPassword);+ }++ toast.success(t("common.updated", { item: t("calendar.title") }));+ return { success: true };+ } catch (error) {+ console.error("Failed to update calendar:", error);+ toast.error(+ error instanceof Error+ ? error.message+ : t("common.updateError", { item: t("calendar.title") })+ );+ return { success: false, error: "failed" as const };+ }+ };+const deleteCalendar = async (calendarId: string, password?: string) => {try {const response = await fetch(`/api/calendars/${calendarId}`, {@@ -154,6 +214,7 @@ export function useCalendars(initialCalendarId?: string | null) {setSelectedCalendar,loading,createCalendar,+ updateCalendar,deleteCalendar,refetchCalendars: fetchCalendars,};diff --git a/hooks/useShiftStats.ts b/hooks/useShiftStats.tsnew file mode 100644index 0000000..5072a43--- /dev/null+++ b/hooks/useShiftStats.ts@@ -0,0 +1,86 @@+import { useState, useEffect, useCallback, useRef } from "react";+import { getCachedPassword } from "@/lib/password-cache";++export interface ShiftStatsData {+ period: string;+ startDate: string;+ endDate: string;+ stats: Record<string, { count: number; totalMinutes: number }>;+ totalMinutes: number;+ totalShifts: number;+ avgMinutesPerShift: number;+ avgShiftsPerDay: number;+ avgMinutesPerDay: number;+ minDuration: number;+ maxDuration: number;+ daysWithShifts: number;+ trendData: Array<{ date: string; count: number; totalMinutes: number }>;+}++interface UseShiftStatsOptions {+ calendarId: string | undefined;+ currentDate: Date;+ period: "week" | "month" | "year";+ refreshTrigger?: number;+}++export function useShiftStats({+ calendarId,+ currentDate,+ period,+ refreshTrigger,+}: UseShiftStatsOptions) {+ const [stats, setStats] = useState<ShiftStatsData | null>(null);+ const [loading, setLoading] = useState(false);+ const isInitialLoadRef = useRef(true);++ const fetchStats = useCallback(+ async (silent = false) => {+ if (!calendarId) return;++ if (!silent) {+ setLoading(true);+ }++ try {+ const password = getCachedPassword(calendarId);+ const params = new URLSearchParams({+ calendarId,+ period,+ date: currentDate.toISOString(),+ });+ if (password) {+ params.append("password", password);+ }++ const response = await fetch(`/api/shifts/stats?${params}`);+ if (!response.ok) {+ return; // Calendar is locked and no valid password+ }+ const data = await response.json();+ setStats(data);+ } catch (error) {+ console.error("Failed to fetch shift statistics:", error);+ } finally {+ if (!silent) {+ setLoading(false);+ }+ }+ },+ [calendarId, period, currentDate]+ );++ // Fetch stats when dependencies change+ useEffect(() => {+ if (calendarId) {+ fetchStats(!isInitialLoadRef.current);+ isInitialLoadRef.current = false;+ }+ }, [calendarId, refreshTrigger, fetchStats]);++ return {+ stats,+ loading,+ refetch: fetchStats,+ };+}