Your favorite shift management application!
chore: Switch to React Query polling & optimistic updates from SSE (#123)
panteLdfee67d419a0
diff --git a/.env.example b/.env.exampleindex 2a181bf..adf5ce5 100644--- a/.env.example+++ b/.env.example@@ -119,10 +119,6 @@ GITHUB_REPO_NAME=BetterShift# RATE_LIMIT_UPLOAD_AVATAR_REQUESTS=5 # Per user# RATE_LIMIT_UPLOAD_AVATAR_WINDOW=300 # 5 minutes-# Real-Time Features-# RATE_LIMIT_SSE_CONNECTIONS=10 # Per user-# RATE_LIMIT_SSE_WINDOW=10 # 10 seconds-# Calendar Operations# RATE_LIMIT_CALENDAR_CREATE_REQUESTS=10 # Per user# RATE_LIMIT_CALENDAR_CREATE_WINDOW=3600 # 1 hourdiff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.mdindex 4b62dcb..1672b68 100644--- a/.github/copilot-instructions.md+++ b/.github/copilot-instructions.md@@ -11,6 +11,7 @@- **Database**: SQLite (via better-sqlite3) + Drizzle ORM 0.44- **Auth**: Better Auth 1.4 (enabled by default) - email/password + OAuth (Google/GitHub/Discord) + custom OIDC- **i18n**: next-intl 4.5 - Supported locales: `en`, `de`, `it`+- **Data Fetching**: @tanstack/react-query 5 - Polling, caching, optimistic updates- **Key Libraries**: date-fns, ical.js, jsPDF, @dnd-kit, recharts, sonner (toasts)## Architecture Patterns@@ -37,7 +38,6 @@```bashnpm run db:generate # Generate SQL from schema changesnpm run db:migrate # Apply migrations to database-npm run db:studio # Open Drizzle Studio GUI```### 3. Authentication & Permissions@@ -181,27 +181,94 @@ ALLOW_GUEST_ACCESS=false- `useAuthFeatures()` - Client: Convenience hook for auth-related flags- Feature flags in [`lib/auth/feature-flags.ts`](lib/auth/feature-flags.ts) are SERVER-ONLY now-### 5. Real-Time Updates (SSE)+### 5. Real-Time Updates (React Query Polling)-**Event stream**: [`app/api/events/stream/route.ts`](app/api/events/stream/route.ts) - Server-Sent Events endpoint+**Architecture**: All data fetching uses `@tanstack/react-query` with automatic polling for live updates across all pages and components.-**Event emitter**: [`lib/event-emitter.ts`](lib/event-emitter.ts) - Singleton pattern with HMR support+**Configuration**: [`lib/query-client.ts`](lib/query-client.ts) - Global query client settings-**Emit events after mutations**:+```typescript+// Centralized refetch interval constant+export const REFETCH_INTERVAL = 5000; // 5s polling for live updates++// Default settings+{+ staleTime: 3000, // Data fresh for 3s+ gcTime: 300000, // Cache for 5min+ refetchInterval: REFETCH_INTERVAL,+ refetchOnWindowFocus: true,+ refetchOnReconnect: true,+}+```++**Using custom polling intervals**: Import and use `REFETCH_INTERVAL` from [`lib/query-client.ts`](lib/query-client.ts) in all queries that need polling:++**Query Keys**: [`lib/query-keys.ts`](lib/query-keys.ts) - Consistent key management++```typescript+import { queryKeys } from "@/lib/query-keys";++// Examples+queryKeys.shifts.byCalendar(calendarId); // ['shifts', calendarId]+queryKeys.admin.users({ filters, sort }); // ['admin', 'users', { filters, sort }]+```++**Data fetching with useQuery**:```typescript-import { eventEmitter } from "@/lib/event-emitter";--// After creating/updating/deleting-eventEmitter.emit("calendar-change", {- type: "shift" | "preset" | "note" | "calendar" | "sync-log",- action: "create" | "update" | "delete" | "reorder",- calendarId: string,- data: unknown,+import { useQuery } from "@tanstack/react-query";+import { queryKeys } from "@/lib/query-keys";+import { REFETCH_INTERVAL } from "@/lib/query-client";++const { data: shifts = [], isLoading } = useQuery({+ queryKey: queryKeys.shifts.byCalendar(calendarId!),+ queryFn: () => fetchShiftsApi(calendarId!),+ enabled: !!calendarId,+ refetchInterval: REFETCH_INTERVAL, // Use centralized constant});```-**Client connection**: Use `useSSEConnection` hook in [`hooks/useSSEConnection.ts`](hooks/useSSEConnection.ts) - automatically reconnects, handles visibility changes, and triggers data refreshes.+**Mutations with optimistic updates**:++```typescript+import { useMutation, useQueryClient } from "@tanstack/react-query";++const queryClient = useQueryClient();++const createMutation = useMutation({+ mutationFn: createShiftApi,+ onMutate: async (newShift) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.shifts.byCalendar(calendarId!),+ });+ const previous = queryClient.getQueryData(+ queryKeys.shifts.byCalendar(calendarId!)+ );+ queryClient.setQueryData(+ queryKeys.shifts.byCalendar(calendarId!),+ (old: Shift[] = []) => [...old, optimisticShift]+ );+ return { previous };+ },+ onError: (err, variables, context) => {+ queryClient.setQueryData(+ queryKeys.shifts.byCalendar(calendarId!),+ context?.previous+ );+ toast.error(t("common.createError", { item: t("shift.shift_one") }));+ },+ onSuccess: () => {+ toast.success(t("common.created", { item: t("shift.shift_one") }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.shifts.byCalendar(calendarId!),+ });+ },+});+```++**Cache invalidation**: After mutations, use `queryClient.invalidateQueries()` to refetch related data.### 6. Component Architecture@@ -220,7 +287,7 @@ eventEmitter.emit("calendar-change", {- Data fetching: `useShifts`, `usePresets`, `useNotes`, `useCalendars` (in `/hooks`)- Actions: `useShiftActions`, `useNoteActions` (handle CRUD + optimistic updates)-- Forms: `useShiftForm`, `usePresetManagement` (form state + validation)+- Forms: `useShiftForm` (form state + validation)### 7. Internationalization@@ -303,7 +370,6 @@ import { NextRequest, NextResponse } from "next/server";import { db } from "@/lib/db";import { getSessionUser } from "@/lib/auth/sessions";import { checkPermission } from "@/lib/auth/permissions";-import { eventEmitter } from "@/lib/event-emitter";export async function POST(request: NextRequest) {const user = await getSessionUser(request.headers);@@ -324,27 +390,35 @@ export async function POST(request: NextRequest) {.values({ ...data, calendarId }).returning();- // Emit SSE event- eventEmitter.emit("calendar-change", {- type: "shift",- action: "create",- calendarId,- data: result,- });-+ // No event emission needed - React Query polling handles syncreturn NextResponse.json(result, { status: 201 });}```### Optimistic Updates-See [`hooks/useShifts.ts`](hooks/useShifts.ts) `createShift` function:+All mutations use React Query's optimistic update pattern. See [`hooks/useShifts.ts`](hooks/useShifts.ts):++1. **onMutate**: Cancel queries, save previous state, apply optimistic update+2. **onError**: Rollback to previous state, show error toast+3. **onSuccess**: Show success toast+4. **onSettled**: Invalidate queries to refetch real data-1. Generate temp ID: `temp-${Date.now()}`-2. Add optimistic item to state immediately-3. Make API call-4. On error: Remove temp item, show toast-5. On success: Replace temp item with real data from API+```typescript+const mutation = useMutation({+ mutationFn: createShiftApi,+ onMutate: async (newData) => {+ await queryClient.cancelQueries({ queryKey });+ const previous = queryClient.getQueryData(queryKey);+ queryClient.setQueryData(queryKey, (old) => [...old, optimisticItem]);+ return { previous };+ },+ onError: (err, vars, context) => {+ queryClient.setQueryData(queryKey, context?.previous);+ },+ onSettled: () => queryClient.invalidateQueries({ queryKey }),+});+```### Date Handling@@ -371,14 +445,18 @@ See [`hooks/useShifts.ts`](hooks/useShifts.ts) `createShift` function:- [`hooks/usePublicConfig.ts`](hooks/usePublicConfig.ts) - Client-side config access hook- [`hooks/useAuthFeatures.ts`](hooks/useAuthFeatures.ts) - Auth-specific feature flags hook- [`components/calendar-grid.tsx`](components/calendar-grid.tsx) - Core calendar rendering with shift display-- [`hooks/useSSEConnection.ts`](hooks/useSSEConnection.ts) - Real-time sync connection management+- [`lib/query-client.ts`](lib/query-client.ts) - React Query client configuration+- [`lib/query-keys.ts`](lib/query-keys.ts) - Query key factory for consistent cache management+- [`components/query-provider.tsx`](components/query-provider.tsx) - React Query provider- [`MIGRATION_PLAN.md`](MIGRATION_PLAN.md) - Detailed auth migration plan with phases and todos## Important Notes- **No NEXT*PUBLIC***: Use `getPublicConfig()` on server, `usePublicConfig()` hook on client - never `process.env.NEXT_PUBLIC_*`- **Better Auth first**: Always check [Better Auth docs](https://www.better-auth.com/docs) before implementing auth features - use built-in methods, don't reinvent-- **SSE is required**: All mutations must emit events to keep clients in sync+- **React Query for data**: All data fetching uses `useQuery`/`useMutation` with polling - no manual fetch/refetch logic+- **Query keys from factory**: Always use `queryKeys` from `lib/query-keys.ts` for cache consistency+- **Optimistic updates**: All mutations should implement optimistic updates for instant UI feedback- **Permission checks everywhere**: Check permissions in both API routes (server) and UI (client) for security + UX- **Strict TypeScript**: No `any` types, use Drizzle-inferred types from schema- **Translations required**: All user-facing strings must use `t()` functiondiff --git a/app/admin/calendars/page.tsx b/app/admin/calendars/page.tsxindex 364629e..0c86fd8 100644--- a/app/admin/calendars/page.tsx+++ b/app/admin/calendars/page.tsx@@ -1,16 +1,8 @@"use client";-import { useState, useEffect } from "react";+import { useState } from "react";import { useTranslations } from "next-intl";-import {- Search,- Filter,- AlertCircle,- Send,- Trash2,- X,- RefreshCw,-} from "lucide-react";+import { Search, Filter, AlertCircle, Send, Trash2, X } from "lucide-react";import { Input } from "@/components/ui/input";import { Button } from "@/components/ui/button";import {@@ -37,15 +29,9 @@ import { useAdminLevel } from "@/hooks/useAdminAccess";export default function AdminCalendarsPage() {const t = useTranslations();- const { fetchCalendars, deleteCalendar, bulkDeleteCalendars, isLoading } =- useAdminCalendars();const adminLevel = useAdminLevel();const isSuperAdmin = adminLevel === "superadmin";- // State- const [calendars, setCalendars] = useState<AdminCalendar[]>([]);- const [orphanedCount, setOrphanedCount] = useState(0);-// Filters & Sortconst [searchQuery, setSearchQuery] = useState("");const [statusFilter, setStatusFilter] = useState<@@ -54,6 +40,26 @@ export default function AdminCalendarsPage() {const sortField = "createdAt" as const;const sortDirection = "desc" as const;+ // Build filters and sort+ const filters: CalendarFilters = {+ search: searchQuery || undefined,+ status: statusFilter,+ };++ const sort: CalendarSort = {+ field: sortField,+ direction: sortDirection,+ };++ // Use hook with filters+ const {+ calendars,+ orphanedCount,+ isLoading,+ deleteCalendar,+ bulkDeleteCalendars,+ } = useAdminCalendars(filters, sort);+// Selectionconst [selectedIds, setSelectedIds] = useState<string[]>([]);@@ -72,50 +78,6 @@ export default function AdminCalendarsPage() {AdminCalendar[]>([]);- // Load calendars- const loadCalendars = async () => {- const filters: CalendarFilters = {- search: searchQuery || undefined,- status: statusFilter,- };-- const sort: CalendarSort = {- field: sortField,- direction: sortDirection,- };-- const result = await fetchCalendars(filters, sort);-- if (result) {- setCalendars(result.calendars);- setOrphanedCount(result.orphanedCount);- }- };-- // Initial load- useEffect(() => {- const filters: CalendarFilters = {- search: searchQuery || undefined,- status: statusFilter,- };-- const sort: CalendarSort = {- field: sortField,- direction: sortDirection,- };-- const loadData = async () => {- const result = await fetchCalendars(filters, sort);-- if (result) {- setCalendars(result.calendars);- setOrphanedCount(result.orphanedCount);- }- };-- loadData();- }, [searchQuery, statusFilter, sortField, sortDirection, fetchCalendars]);-// Selection handlersconst handleToggleSelect = (calendarId: string) => {setSelectedIds((prev) =>@@ -177,7 +139,6 @@ export default function AdminCalendarsPage() {const success = await bulkDeleteCalendars(selectedIds);if (success) {setSelectedIds([]);- await loadCalendars();}};@@ -187,18 +148,16 @@ export default function AdminCalendarsPage() {if (success) {setShowDeleteDialog(false);setSelectedCalendar(null);- await loadCalendars();}};- const handleSuccess = async () => {+ const handleSuccess = () => {setShowEditSheet(false);setShowTransferSheet(false);setShowBulkTransferSheet(false);setSelectedCalendar(null);setCalendarsForBulkTransfer([]);setSelectedIds([]);- await loadCalendars();};const handleEditFromDetails = () => {@@ -239,14 +198,6 @@ export default function AdminCalendarsPage() {{t("admin.calendars.description")}</p></div>- <Button- variant="outline"- size="icon"- onClick={() => loadCalendars()}- disabled={isLoading}- >- <RefreshCw className={isLoading ? "animate-spin" : ""} />- </Button></div>{/* Orphaned Calendars Warning Banner */}diff --git a/app/admin/logs/page.tsx b/app/admin/logs/page.tsxindex cde728a..bf0839c 100644--- a/app/admin/logs/page.tsx+++ b/app/admin/logs/page.tsx@@ -1,8 +1,8 @@"use client";-import React, { useState, useEffect, useMemo, useTransition } from "react";+import React, { useState, useEffect, useMemo } from "react";import { useTranslations, useLocale } from "next-intl";-import { useAuditLogs, type AuditLog } from "@/hooks/useAuditLogs";+import { useAdminAuditLogs, type AuditLog } from "@/hooks/useAdminAuditLogs";import { FullscreenLoader } from "@/components/fullscreen-loader";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";@@ -28,7 +28,6 @@ import { AuditLogDeleteDialog } from "@/components/admin/audit-log-delete-dialogimport {ChevronLeft,ChevronRight,- RefreshCw,Trash2,Search,ChevronDown,@@ -57,16 +56,11 @@ export default function AdminAuditLogsPage() {const t = useTranslations();const locale = useLocale();const dateLocale = getDateLocale(locale);- const { fetchAuditLogs, isLoading } = useAuditLogs();const isSuperAdmin = useIsSuperAdmin();- // Data State- const [logs, setLogs] = useState<AuditLog[]>([]);- const [total, setTotal] = useState(0);+ // Filter Stateconst [page, setPage] = useState(0);const limit = 25;-- // Filter Stateconst [actionFilter, setActionFilter] = useState<string>("all");const [severityFilter, setSeverityFilter] = useState<string>("all");const [searchQuery, setSearchQuery] = useState("");@@ -74,14 +68,53 @@ export default function AdminAuditLogsPage() {const [startDate, setStartDate] = useState("");const [endDate, setEndDate] = useState("");- // UI State- const [isPending, startTransition] = useTransition();- const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());- const [selectedLogIds, setSelectedLogIds] = useState<string[]>([]);+ // Sort Stateconst [sortColumn, setSortColumn] = useState<- "timestamp" | "action" | "severity" | "user" | "ipAddress" | null+ "timestamp" | "action" | "severity" | "user" | "ipAddress">("timestamp");const [sortDirection, setSortDirection] = useState<"asc" | "desc">("desc");++ // Build filters and sort for hook+ const filters = useMemo(+ () => ({+ action: actionFilter !== "all" ? actionFilter : undefined,+ severity:+ severityFilter !== "all"+ ? (severityFilter as "info" | "warning" | "error" | "critical")+ : undefined,+ search: debouncedSearch || undefined,+ startDate: startDate || undefined,+ endDate: endDate || undefined,+ }),+ [actionFilter, severityFilter, debouncedSearch, startDate, endDate]+ );++ const sort = useMemo(+ () => ({+ field: sortColumn,+ direction: sortDirection,+ }),+ [sortColumn, sortDirection]+ );++ const pagination = useMemo(+ () => ({+ limit,+ offset: page * limit,+ }),+ [page, limit]+ );++ // Use hook with live updates+ const { logs, total, isLoading } = useAdminAuditLogs(+ filters,+ sort,+ pagination+ );++ // UI State+ const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());+ const [selectedLogIds, setSelectedLogIds] = useState<string[]>([]);const [selectedLog, setSelectedLog] = useState<AuditLog | null>(null);const [showDetailsDialog, setShowDetailsDialog] = useState(false);const [showDeleteDialog, setShowDeleteDialog] = useState(false);@@ -137,62 +170,51 @@ export default function AdminAuditLogsPage() {[]);+ // Handler functions that combine filter changes with page reset+ const handleActionFilterChange = (value: string) => {+ setActionFilter(value);+ setPage(0);+ setSelectedLogIds([]);+ setExpandedRows(new Set());+ };++ const handleSeverityFilterChange = (value: string) => {+ setSeverityFilter(value);+ setPage(0);+ setSelectedLogIds([]);+ setExpandedRows(new Set());+ };++ const handleStartDateChange = (value: string) => {+ setStartDate(value);+ setPage(0);+ setSelectedLogIds([]);+ setExpandedRows(new Set());+ };++ const handleEndDateChange = (value: string) => {+ setEndDate(value);+ setPage(0);+ setSelectedLogIds([]);+ setExpandedRows(new Set());+ };++ const handleDebouncedSearchChange = (value: string) => {+ setDebouncedSearch(value);+ setPage(0);+ setSelectedLogIds([]);+ setExpandedRows(new Set());+ };+// Debounce search queryuseEffect(() => {const timer = setTimeout(() => {- setDebouncedSearch(searchQuery);+ handleDebouncedSearchChange(searchQuery);}, 500);return () => clearTimeout(timer);}, [searchQuery]);- // Load logs- const loadLogs = async () => {- startTransition(async () => {- const filters = {- action: actionFilter !== "all" ? actionFilter : undefined,- severity:- severityFilter !== "all"- ? (severityFilter as "info" | "warning" | "error" | "critical")- : undefined,- search: debouncedSearch || undefined,- startDate: startDate || undefined,- endDate: endDate || undefined,- };-- // Backend now supports all sort columns including user and ipAddress- const sort = {- sortBy: sortColumn || "timestamp",- sortOrder: sortDirection,- };-- const result = await fetchAuditLogs(filters, sort, {- limit,- offset: page * limit,- });-- if (result) {- setLogs(result.logs);- setTotal(result.pagination.total);- }- });- };-- // Initial load and reload on filter/page/sort change- useEffect(() => {- loadLogs();- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [- page,- actionFilter,- severityFilter,- debouncedSearch,- startDate,- endDate,- sortColumn,- sortDirection,- ]);-// Toggle row expansionconst toggleRow = (logId: string) => {setExpandedRows((prev) => {@@ -239,6 +261,8 @@ export default function AdminAuditLogsPage() {setStartDate("");setEndDate("");setPage(0);+ // Immediately clear debouncedSearch to prevent stale value+ handleDebouncedSearchChange("");};// Checkbox selection handlers@@ -265,7 +289,8 @@ export default function AdminAuditLogsPage() {const isAllSelected =logs.length > 0 && selectedLogIds.length === logs.length;- if (isLoading && !isPending) {+ // Show loader only on initial load+ if (isLoading && logs.length === 0) {return <FullscreenLoader />;}@@ -282,16 +307,6 @@ export default function AdminAuditLogsPage() {</p></div><div className="flex items-center gap-2">- <Button- variant="outline"- size="sm"- onClick={loadLogs}- disabled={isLoading}- >- <RefreshCw- className={isLoading ? "animate-spin h-4 w-4" : "h-4 w-4"}- />- </Button>{isSuperAdmin && (<Buttonvariant="outline"@@ -322,7 +337,7 @@ export default function AdminAuditLogsPage() {</div>{/* Action Type Filter */}- <Select value={actionFilter} onValueChange={setActionFilter}>+ <Select value={actionFilter} onValueChange={handleActionFilterChange}><SelectTrigger className="w-full sm:w-[200px]"><Filter className="h-4 w-4 mr-2" /><SelectValue />@@ -341,7 +356,10 @@ export default function AdminAuditLogsPage() {</Select>{/* Severity Filter */}- <Select value={severityFilter} onValueChange={setSeverityFilter}>+ <Select+ value={severityFilter}+ onValueChange={handleSeverityFilterChange}+ ><SelectTrigger className="w-full sm:w-[180px]"><Filter className="h-4 w-4 mr-2" /><SelectValue />@@ -373,7 +391,7 @@ export default function AdminAuditLogsPage() {<Inputtype="date"value={startDate}- onChange={(e) => setStartDate(e.target.value)}+ onChange={(e) => handleStartDateChange(e.target.value)}/></div>@@ -384,7 +402,7 @@ export default function AdminAuditLogsPage() {<Inputtype="date"value={endDate}- onChange={(e) => setEndDate(e.target.value)}+ onChange={(e) => handleEndDateChange(e.target.value)}/></div>@@ -440,219 +458,217 @@ export default function AdminAuditLogsPage() {{/* Table */}<div className="rounded-md border bg-card">- <div className={isPending ? "opacity-50 pointer-events-none" : ""}>- <Table>- <TableHeader>- <TableRow>- {isSuperAdmin && (- <TableHead className="w-[50px]">- <Checkbox- checked={isAllSelected}- onCheckedChange={toggleSelectAll}- />- </TableHead>- )}- <TableHead className="w-[50px]"></TableHead>- <TableHead- className="cursor-pointer select-none"- onClick={() => handleSort("timestamp")}- >- <div className="flex items-center gap-2">- {t("admin.timestamp")}- {sortColumn === "timestamp" &&- (sortDirection === "asc" ? (- <ChevronUp className="h-4 w-4" />- ) : (- <ChevronDown className="h-4 w-4" />- ))}- </div>- </TableHead>- <TableHead- className="cursor-pointer select-none"- onClick={() => handleSort("action")}- >- <div className="flex items-center gap-2">- {t("common.labels.action")}- {sortColumn === "action" &&- (sortDirection === "asc" ? (- <ChevronUp className="h-4 w-4" />- ) : (- <ChevronDown className="h-4 w-4" />- ))}- </div>+ <Table>+ <TableHeader>+ <TableRow>+ {isSuperAdmin && (+ <TableHead className="w-[50px]">+ <Checkbox+ checked={isAllSelected}+ onCheckedChange={toggleSelectAll}+ /></TableHead>- <TableHead- className="cursor-pointer select-none"- onClick={() => handleSort("user")}+ )}+ <TableHead className="w-[50px]"></TableHead>+ <TableHead+ className="cursor-pointer select-none"+ onClick={() => handleSort("timestamp")}+ >+ <div className="flex items-center gap-2">+ {t("admin.timestamp")}+ {sortColumn === "timestamp" &&+ (sortDirection === "asc" ? (+ <ChevronUp className="h-4 w-4" />+ ) : (+ <ChevronDown className="h-4 w-4" />+ ))}+ </div>+ </TableHead>+ <TableHead+ className="cursor-pointer select-none"+ onClick={() => handleSort("action")}+ >+ <div className="flex items-center gap-2">+ {t("common.labels.action")}+ {sortColumn === "action" &&+ (sortDirection === "asc" ? (+ <ChevronUp className="h-4 w-4" />+ ) : (+ <ChevronDown className="h-4 w-4" />+ ))}+ </div>+ </TableHead>+ <TableHead+ className="cursor-pointer select-none"+ onClick={() => handleSort("user")}+ >+ <div className="flex items-center gap-2">+ {t("common.labels.user")}+ {sortColumn === "user" &&+ (sortDirection === "asc" ? (+ <ChevronUp className="h-4 w-4" />+ ) : (+ <ChevronDown className="h-4 w-4" />+ ))}+ </div>+ </TableHead>+ <TableHead+ className="cursor-pointer select-none"+ onClick={() => handleSort("severity")}+ >+ <div className="flex items-center gap-2">+ {t("common.labels.severity")}+ {sortColumn === "severity" &&+ (sortDirection === "asc" ? (+ <ChevronUp className="h-4 w-4" />+ ) : (+ <ChevronDown className="h-4 w-4" />+ ))}+ </div>+ </TableHead>+ <TableHead+ className="cursor-pointer select-none"+ onClick={() => handleSort("ipAddress")}+ >+ <div className="flex items-center gap-2">+ {t("common.labels.ipAddress")}+ {sortColumn === "ipAddress" &&+ (sortDirection === "asc" ? (+ <ChevronUp className="h-4 w-4" />+ ) : (+ <ChevronDown className="h-4 w-4" />+ ))}+ </div>+ </TableHead>+ <TableHead className="w-[100px]"></TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {logs.length === 0 ? (+ <TableRow>+ <TableCell+ colSpan={isSuperAdmin ? 8 : 7}+ className="text-center py-8 text-muted-foreground">- <div className="flex items-center gap-2">- {t("common.labels.user")}- {sortColumn === "user" &&- (sortDirection === "asc" ? (- <ChevronUp className="h-4 w-4" />- ) : (+ {isLoading ? t("common.loading") : t("admin.noLogsFound")}+ </TableCell>+ </TableRow>+ ) : (+ logs.map((log) => (+ <React.Fragment key={log.id}>+ <TableRow+ className="cursor-pointer hover:bg-muted/50"+ onClick={() => toggleRow(log.id)}+ >+ {isSuperAdmin && (+ <TableCell onClick={(e) => e.stopPropagation()}>+ <Checkbox+ checked={selectedLogIds.includes(log.id)}+ onCheckedChange={() => toggleLogSelection(log.id)}+ />+ </TableCell>+ )}+ <TableCell>+ {expandedRows.has(log.id) ? (<ChevronDown className="h-4 w-4" />- ))}- </div>- </TableHead>- <TableHead- className="cursor-pointer select-none"- onClick={() => handleSort("severity")}- >- <div className="flex items-center gap-2">- {t("common.labels.severity")}- {sortColumn === "severity" &&- (sortDirection === "asc" ? (- <ChevronUp className="h-4 w-4" />) : (- <ChevronDown className="h-4 w-4" />- ))}- </div>- </TableHead>- <TableHead- className="cursor-pointer select-none"- onClick={() => handleSort("ipAddress")}- >- <div className="flex items-center gap-2">- {t("common.labels.ipAddress")}- {sortColumn === "ipAddress" &&- (sortDirection === "asc" ? (- <ChevronUp className="h-4 w-4" />+ <ChevronRight className="h-4 w-4" />+ )}+ </TableCell>+ <TableCell className="whitespace-nowrap">+ {format(new Date(log.timestamp), "PPp", {+ locale: dateLocale,+ })}+ </TableCell>+ <TableCell>+ <Badge+ variant="outline"+ className={getActionColor(log.action)}+ >+ {log.action}+ </Badge>+ </TableCell>+ <TableCell>+ {log.userId ? (+ <div className="flex items-center gap-2">+ <Avatar className="h-6 w-6">+ {log.userImage && (+ <AvatarImage+ src={log.userImage}+ alt={log.userName || ""}+ />+ )}+ <AvatarFallback className="text-xs">+ {getUserInitials(log.userName)}+ </AvatarFallback>+ </Avatar>+ <span className="text-sm">+ {log.userName ||+ log.userEmail ||+ t("admin.unknownUser")}+ </span>+ </div>) : (- <ChevronDown className="h-4 w-4" />- ))}- </div>- </TableHead>- <TableHead className="w-[100px]"></TableHead>- </TableRow>- </TableHeader>- <TableBody>- {logs.length === 0 ? (- <TableRow>- <TableCell- colSpan={isSuperAdmin ? 8 : 7}- className="text-center py-8 text-muted-foreground"- >- {isPending ? t("common.loading") : t("admin.noLogsFound")}- </TableCell>- </TableRow>- ) : (- logs.map((log) => (- <React.Fragment key={log.id}>- <TableRow- className="cursor-pointer hover:bg-muted/50"- onClick={() => toggleRow(log.id)}- >- {isSuperAdmin && (- <TableCell onClick={(e) => e.stopPropagation()}>- <Checkbox- checked={selectedLogIds.includes(log.id)}- onCheckedChange={() => toggleLogSelection(log.id)}- />- </TableCell>+ <span className="text-sm text-muted-foreground">+ {t("admin.systemAction")}+ </span>)}- <TableCell>- {expandedRows.has(log.id) ? (- <ChevronDown className="h-4 w-4" />- ) : (- <ChevronRight className="h-4 w-4" />- )}- </TableCell>- <TableCell className="whitespace-nowrap">- {format(new Date(log.timestamp), "PPp", {- locale: dateLocale,- })}- </TableCell>- <TableCell>- <Badge- variant="outline"- className={getActionColor(log.action)}- >- {log.action}- </Badge>- </TableCell>- <TableCell>- {log.userId ? (- <div className="flex items-center gap-2">- <Avatar className="h-6 w-6">- {log.userImage && (- <AvatarImage- src={log.userImage}- alt={log.userName || ""}- />- )}- <AvatarFallback className="text-xs">- {getUserInitials(log.userName)}- </AvatarFallback>- </Avatar>- <span className="text-sm">- {log.userName ||- log.userEmail ||- t("admin.unknownUser")}- </span>+ </TableCell>+ <TableCell>+ <Badge+ variant="outline"+ className={getSeverityColor(log.severity)}+ >+ {log.severity}+ </Badge>+ </TableCell>+ <TableCell className="text-sm text-muted-foreground">+ {log.ipAddress || "—"}+ </TableCell>+ <TableCell>+ <Button+ variant="ghost"+ size="sm"+ onClick={(e) => {+ e.stopPropagation();+ setSelectedLog(log);+ setShowDetailsDialog(true);+ }}+ >+ {t("common.viewDetails")}+ </Button>+ </TableCell>+ </TableRow>+ {expandedRows.has(log.id) && (+ <TableRow>+ <TableCell+ colSpan={isSuperAdmin ? 8 : 7}+ className="bg-muted/50"+ >+ <div className="p-4 space-y-2">+ <div className="text-sm font-medium">+ {t("admin.metadata")}:</div>- ) : (- <span className="text-sm text-muted-foreground">- {t("admin.systemAction")}- </span>- )}- </TableCell>- <TableCell>- <Badge- variant="outline"- className={getSeverityColor(log.severity)}- >- {log.severity}- </Badge>- </TableCell>- <TableCell className="text-sm text-muted-foreground">- {log.ipAddress || "—"}- </TableCell>- <TableCell>- <Button- variant="ghost"- size="sm"- onClick={(e) => {- e.stopPropagation();- setSelectedLog(log);- setShowDetailsDialog(true);- }}- >- {t("common.viewDetails")}- </Button>+ <pre className="text-xs bg-background p-3 rounded border overflow-x-auto">+ {JSON.stringify(log.metadata, null, 2)}+ </pre>+ {log.userAgent && (+ <div className="text-xs text-muted-foreground">+ <span className="font-medium">+ {t("admin.userAgent")}:+ </span>{" "}+ {log.userAgent}+ </div>+ )}+ </div></TableCell></TableRow>- {expandedRows.has(log.id) && (- <TableRow>- <TableCell- colSpan={isSuperAdmin ? 8 : 7}- className="bg-muted/50"- >- <div className="p-4 space-y-2">- <div className="text-sm font-medium">- {t("admin.metadata")}:- </div>- <pre className="text-xs bg-background p-3 rounded border overflow-x-auto">- {JSON.stringify(log.metadata, null, 2)}- </pre>- {log.userAgent && (- <div className="text-xs text-muted-foreground">- <span className="font-medium">- {t("admin.userAgent")}:- </span>{" "}- {log.userAgent}- </div>- )}- </div>- </TableCell>- </TableRow>- )}- </React.Fragment>- ))- )}- </TableBody>- </Table>- </div>+ )}+ </React.Fragment>+ ))+ )}+ </TableBody>+ </Table></div>{/* Pagination */}@@ -701,7 +717,7 @@ export default function AdminAuditLogsPage() {onSuccess={() => {setPage(0);clearSelection();- loadLogs();+ // No manual refetch needed - React Query will auto-update}}/></div>diff --git a/app/admin/page.tsx b/app/admin/page.tsxindex ade96e2..f9c72be 100644--- a/app/admin/page.tsx+++ b/app/admin/page.tsx@@ -53,7 +53,7 @@ export default function AdminDashboardPage() {const locale = useLocale();const dateLocale = getDateLocale(locale);- const { stats, isLoading: isLoadingStats, refetch } = useAdminStats();+ const { stats, isLoading: isLoadingStats } = useAdminStats();const [versionInfo, setVersionInfo] = useState<VersionInfo | null>(null);const [isLoadingVersion, setIsLoadingVersion] = useState(true);@@ -93,14 +93,6 @@ export default function AdminDashboardPage() {{t("admin.dashboardDescription")}</p></div>- <Button- variant="outline"- size="icon"- onClick={() => refetch()}- disabled={isLoadingStats}- >- <RefreshCw className={isLoadingStats ? "animate-spin" : ""} />- </Button></div>{/* System Information */}diff --git a/app/admin/users/page.tsx b/app/admin/users/page.tsxindex ce09821..a866e58 100644--- a/app/admin/users/page.tsx+++ b/app/admin/users/page.tsx@@ -1,10 +1,9 @@"use client";-import { useState, useEffect } from "react";+import { useState } from "react";import { useTranslations } from "next-intl";-import { Search, Filter, RefreshCw } from "lucide-react";+import { Search, Filter } from "lucide-react";import { Input } from "@/components/ui/input";-import { Button } from "@/components/ui/button";import {Select,SelectContent,@@ -29,18 +28,6 @@ import {export default function AdminUsersPage() {const t = useTranslations();- const {- fetchUsers,- banUser,- unbanUser,- deleteUser,- resetPassword,- isLoading,- } = useAdminUsers();-- // State- const [users, setUsers] = useState<AdminUser[]>([]);- const [totalUsers, setTotalUsers] = useState(0);// Filters & Sortconst [searchQuery, setSearchQuery] = useState("");@@ -53,6 +40,31 @@ export default function AdminUsersPage() {const sortField = "createdAt" as const;const sortDirection = "desc" as const;+ // Build filters, sort, and pagination+ const filters: UserFilters = {+ search: searchQuery || undefined,+ role: roleFilter,+ status: statusFilter,+ };++ const sort: UserSort = {+ field: sortField,+ direction: sortDirection,+ };++ const pagination = { page: 1, limit: 1000 };++ // Use hook with filters+ const {+ users,+ total: totalUsers,+ isLoading,+ banUser,+ unbanUser,+ deleteUser,+ resetPassword,+ } = useAdminUsers(filters, sort, pagination);+// Dialogs & Sheetsconst [selectedUser, setSelectedUser] = useState<AdminUser | null>(null);const [showEditSheet, setShowEditSheet] = useState(false);@@ -62,65 +74,6 @@ export default function AdminUsersPage() {const [showDeleteDialog, setShowDeleteDialog] = useState(false);const [showPasswordDialog, setShowPasswordDialog] = useState(false);- // Load users- const loadUsers = async () => {- const filters: UserFilters = {- search: searchQuery || undefined,- role: roleFilter,- status: statusFilter,- };-- const sort: UserSort = {- field: sortField,- direction: sortDirection,- };-- const result = await fetchUsers(filters, sort, {- page: 1,- limit: 1000,- });-- if (result) {- setUsers(result.users);- setTotalUsers(result.total);- }- };-- // Initial load- useEffect(() => {- const filters: UserFilters = {- search: searchQuery || undefined,- role: roleFilter,- status: statusFilter,- };-- const sort: UserSort = {- field: sortField,- direction: sortDirection,- };-- const loadData = async () => {- const result = await fetchUsers(filters, sort, {- page: 1,- limit: 1000,- });-- if (result) {- setUsers(result.users);- setTotalUsers(result.total);- }- };-- loadData();- }, [- searchQuery,- roleFilter,- statusFilter,- sortField,- sortDirection,- fetchUsers,- ]);-// Handlersconst handleUserClick = (user: AdminUser) => {setSelectedUser(user);@@ -156,7 +109,6 @@ export default function AdminUsersPage() {if (!selectedUser) return;const success = await banUser(selectedUser.id, reason, expiresAt);if (success) {- loadUsers();setShowBanDialog(false);}};@@ -165,7 +117,6 @@ export default function AdminUsersPage() {if (!selectedUser) return;const success = await unbanUser(selectedUser.id);if (success) {- loadUsers();setShowUnbanDialog(false);}};@@ -174,7 +125,6 @@ export default function AdminUsersPage() {if (!selectedUser) return;const success = await deleteUser(selectedUser.id);if (success) {- loadUsers();setShowDeleteDialog(false);}};@@ -187,10 +137,6 @@ export default function AdminUsersPage() {}};- const handleRefresh = () => {- loadUsers();- };-if (isLoading && users.length === 0) {return <FullscreenLoader />;}@@ -208,14 +154,6 @@ export default function AdminUsersPage() {{t("admin.userManagementDescription")}</p></div>- <Button- variant="outline"- size="icon"- onClick={handleRefresh}- disabled={isLoading}- >- <RefreshCw className={isLoading ? "animate-spin" : ""} />- </Button></div>{/* Filters */}@@ -298,7 +236,7 @@ export default function AdminUsersPage() {open={showEditSheet}onOpenChange={setShowEditSheet}user={selectedUser}- onSuccess={loadUsers}+ onSuccess={() => {}}/>)}diff --git a/app/api/activity-logs/route.ts b/app/api/activity-logs/route.tsindex 089b6b9..86b21d2 100644--- a/app/api/activity-logs/route.ts+++ b/app/api/activity-logs/route.ts@@ -39,9 +39,10 @@ export async function GET(request: NextRequest) {const type = searchParams.get("type"); // e.g., "auth", "calendar", "sync", "security"const startDate = searchParams.get("startDate");const endDate = searchParams.get("endDate");- const page = parseInt(searchParams.get("page") || "0", 10);+ const severity = searchParams.get("severity"); // e.g., "info", "warning", "error", "critical"+ const search = searchParams.get("search"); // search text for action/metadataconst limit = Math.min(parseInt(searchParams.get("limit") || "50", 10), 100);- const offset = page * limit;+ const offset = parseInt(searchParams.get("offset") || "0", 10);try {// Fetch all logs and merge them before pagination@@ -61,6 +62,11 @@ export async function GET(request: NextRequest) {auditConditions.push(sql`${auditLogs.action} LIKE ${type + ".%"}`);}+ // Filter by severity+ if (severity) {+ auditConditions.push(eq(auditLogs.severity, severity));+ }+// Filter by date rangeif (startDate) {const start = new Date(startDate);@@ -159,20 +165,48 @@ export async function GET(request: NextRequest) {}// ============================================- // 3. Sort merged logs by timestamp (descending)+ // 3. Apply severity filter after merging (sync logs derive severity from status)+ // ============================================+ let filteredLogs = allLogs;+ if (severity) {+ filteredLogs = filteredLogs.filter((log) => log.severity === severity);+ }++ // ============================================+ // 4. Apply search filter (search in action and metadata)+ // ============================================+ if (search) {+ const searchLower = search.toLowerCase();+ filteredLogs = filteredLogs.filter((log) => {+ // Search in action+ if (log.action.toLowerCase().includes(searchLower)) return true;+ // Search in metadata+ if (log.metadata) {+ const metadataStr = JSON.stringify(log.metadata).toLowerCase();+ if (metadataStr.includes(searchLower)) return true;+ }+ // Search in resourceType or resourceId+ if (log.resourceType?.toLowerCase().includes(searchLower)) return true;+ if (log.resourceId?.toLowerCase().includes(searchLower)) return true;+ return false;+ });+ }++ // ============================================+ // 5. Sort merged logs by timestamp (descending)// ============================================- allLogs.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());+ filteredLogs.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());// ============================================- // 4. Apply pagination to merged results+ // 6. Apply pagination to filtered results// ============================================- const paginatedLogs = allLogs.slice(offset, offset + limit);- const total = allLogs.length;+ const paginatedLogs = filteredLogs.slice(offset, offset + limit);+ const total = filteredLogs.length;return NextResponse.json({logs: paginatedLogs,total,- page,+ offset,limit,hasMore: offset + paginatedLogs.length < total,});diff --git a/app/api/admin/calendars/[id]/route.ts b/app/api/admin/calendars/[id]/route.tsindex 93bbcac..50c9ee3 100644--- a/app/api/admin/calendars/[id]/route.ts+++ b/app/api/admin/calendars/[id]/route.ts@@ -25,7 +25,6 @@ import {getValidatedAdminUser,isErrorResponse,} from "@/lib/auth/admin-helpers";-import { eventEmitter } from "@/lib/event-emitter";/*** Admin Calendar Detail API@@ -348,14 +347,6 @@ export async function PATCH(},});- // Emit SSE event- eventEmitter.emit("calendar-change", {- type: "calendar",- action: "update",- calendarId,- data: updatedCalendar,- });-return NextResponse.json(updatedCalendar);} catch (error) {console.error("[Admin Calendar Update API] Error:", error);@@ -477,14 +468,6 @@ export async function DELETE(},});- // Emit SSE event- eventEmitter.emit("calendar-change", {- type: "calendar",- action: "delete",- calendarId,- data: { id: calendarId },- });-return NextResponse.json({message: "Calendar deleted successfully",calendarId,diff --git a/app/api/admin/calendars/[id]/transfer/route.ts b/app/api/admin/calendars/[id]/transfer/route.tsindex 6505194..95d1a47 100644--- a/app/api/admin/calendars/[id]/transfer/route.ts+++ b/app/api/admin/calendars/[id]/transfer/route.ts@@ -12,7 +12,6 @@ import {getValidatedAdminUser,isErrorResponse,} from "@/lib/auth/admin-helpers";-import { eventEmitter } from "@/lib/event-emitter";/*** Admin Calendar Transfer API@@ -128,14 +127,6 @@ export async function POST(},});- // Emit SSE event- eventEmitter.emit("calendar-change", {- type: "calendar",- action: "update",- calendarId,- data: updatedCalendar,- });-return NextResponse.json({message: "Calendar ownership transferred successfully",calendar: updatedCalendar,diff --git a/app/api/admin/calendars/bulk-delete/route.ts b/app/api/admin/calendars/bulk-delete/route.tsindex 7248c37..752ffce 100644--- a/app/api/admin/calendars/bulk-delete/route.ts+++ b/app/api/admin/calendars/bulk-delete/route.ts@@ -19,7 +19,6 @@ import {getValidatedAdminUser,isErrorResponse,} from "@/lib/auth/admin-helpers";-import { eventEmitter } from "@/lib/event-emitter";/*** Admin Calendar Bulk Delete API@@ -136,16 +135,6 @@ export async function POST(request: NextRequest): Promise<NextResponse> {},});- // Emit SSE events for each deleted calendar- for (const calendarId of calendarIds) {- eventEmitter.emit("calendar-change", {- type: "calendar",- action: "delete",- calendarId,- data: { id: calendarId },- });- }-return NextResponse.json({message: `${calendars.length} calendar(s) deleted successfully`,deletedCount: calendars.length,diff --git a/app/api/admin/calendars/bulk-transfer/route.ts b/app/api/admin/calendars/bulk-transfer/route.tsindex 4ffd0a6..e93e1e9 100644--- a/app/api/admin/calendars/bulk-transfer/route.ts+++ b/app/api/admin/calendars/bulk-transfer/route.ts@@ -12,7 +12,6 @@ import {getValidatedAdminUser,isErrorResponse,} from "@/lib/auth/admin-helpers";-import { eventEmitter } from "@/lib/event-emitter";/*** Admin Calendar Bulk Transfer API@@ -120,16 +119,6 @@ export async function POST(request: NextRequest): Promise<NextResponse> {},});- // Emit SSE events for each transferred calendar- for (const calendarId of calendarIds) {- eventEmitter.emit("calendar-change", {- type: "calendar",- action: "update",- calendarId,- data: { id: calendarId, ownerId: newOwnerId },- });- }-return NextResponse.json({message: `${calendars.length} calendar(s) transferred successfully`,transferredCount: calendars.length,diff --git a/app/api/calendars/subscriptions/[calendarId]/route.ts b/app/api/calendars/subscriptions/[calendarId]/route.tsindex 38239c6..623d1e8 100644--- a/app/api/calendars/subscriptions/[calendarId]/route.ts+++ b/app/api/calendars/subscriptions/[calendarId]/route.ts@@ -1,7 +1,6 @@import { NextRequest, NextResponse } from "next/server";import { getSessionUser } from "@/lib/auth/sessions";import { dismissCalendar } from "@/lib/auth/permissions";-import { eventEmitter } from "@/lib/event-emitter";/*** DELETE /api/calendars/subscriptions/[calendarId]@@ -26,14 +25,6 @@ export async function DELETE(// Use the helper function to handle dismissal/unsubscribeawait dismissCalendar(user.id, calendarId);- // Emit SSE event to trigger calendar list refresh- eventEmitter.emit("calendar-change", {- type: "calendar",- action: "update",- calendarId,- data: { dismissed: true },- });-return NextResponse.json({ success: true }, { status: 200 });} catch (error) {console.error("Error dismissing calendar:", error);diff --git a/app/api/calendars/subscriptions/route.ts b/app/api/calendars/subscriptions/route.tsindex 652acf7..1e047cb 100644--- a/app/api/calendars/subscriptions/route.ts+++ b/app/api/calendars/subscriptions/route.ts@@ -8,7 +8,6 @@ import {import { getSessionUser } from "@/lib/auth/sessions";import { eq, and, or, ne, isNull } from "drizzle-orm";import { undismissCalendar } from "@/lib/auth/permissions";-import { eventEmitter } from "@/lib/event-emitter";/*** GET /api/calendars/subscriptions@@ -205,14 +204,6 @@ export async function POST(request: NextRequest) {// Use the helper function to handle both scenariosawait undismissCalendar(user.id, calendarId);- // Emit SSE event to trigger calendar list refresh- eventEmitter.emit("calendar-change", {- type: "calendar",- action: "update",- calendarId,- data: { subscribed: true },- });-return NextResponse.json({ success: true }, { status: 200 });} catch (error) {console.error("Error subscribing to calendar:", error);diff --git a/app/api/events/stream/route.ts b/app/api/events/stream/route.tsdeleted file mode 100644index bb5db48..0000000--- a/app/api/events/stream/route.ts+++ /dev/null@@ -1,90 +0,0 @@-import { NextRequest } from "next/server";-import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";-import { getSessionUser } from "@/lib/auth/sessions";-import { canViewCalendar } from "@/lib/auth/permissions";-import { rateLimit } from "@/lib/rate-limiter";--// Disable default body parsing-export const dynamic = "force-dynamic";--export async function GET(request: NextRequest) {- const searchParams = request.nextUrl.searchParams;- const calendarId = searchParams.get("calendarId");-- if (!calendarId) {- return new Response(JSON.stringify({ error: "Calendar ID is required" }), {- status: 400,- headers: { "Content-Type": "application/json" },- });- }-- // Check read permission for calendar (works for both authenticated users and guests)- const user = await getSessionUser(request.headers);- const hasAccess = await canViewCalendar(user?.id, calendarId);- if (!hasAccess) {- return new Response(JSON.stringify({ error: "Insufficient permissions" }), {- status: 403,- headers: { "Content-Type": "application/json" },- });- }-- // Rate limiting check for SSE connections (1 per user per minute)- const rateLimitResponse = rateLimit(request, user?.id, "sse");- if (rateLimitResponse) return rateLimitResponse;-- // Create a readable stream for SSE- const encoder = new TextEncoder();- const stream = new ReadableStream({- start(controller) {- // Send initial connection message- const connectMessage = `data: ${JSON.stringify({- type: "connected",- calendarId,- })}\n\n`;- controller.enqueue(encoder.encode(connectMessage));-- // Event handler for calendar changes- const handleCalendarChange = (data: unknown) => {- const event = data as CalendarChangeEvent;- // Only send events for the subscribed calendar- if (event.calendarId === calendarId) {- const message = `data: ${JSON.stringify(event)}\n\n`;- try {- controller.enqueue(encoder.encode(message));- } catch (error) {- console.error("Error sending SSE message:", error);- // Client likely disconnected, will be cleaned up below- }- }- };-- // Subscribe to calendar changes- eventEmitter.on("calendar-change", handleCalendarChange);-- // Send keepalive ping every 30 seconds to prevent timeout- const keepAliveInterval = setInterval(() => {- try {- controller.enqueue(encoder.encode(": keepalive\n\n"));- } catch {- // Client disconnected- clearInterval(keepAliveInterval);- }- }, 30000);-- // Clean up on disconnect- request.signal.addEventListener("abort", () => {- clearInterval(keepAliveInterval);- eventEmitter.off("calendar-change", handleCalendarChange);- controller.close();- });- },- });-- return new Response(stream, {- headers: {- "Content-Type": "text/event-stream",- "Cache-Control": "no-cache, no-transform",- Connection: "keep-alive",- },- });-}diff --git a/app/api/external-syncs/[id]/route.ts b/app/api/external-syncs/[id]/route.tsindex aae291b..480845b 100644--- a/app/api/external-syncs/[id]/route.ts+++ b/app/api/external-syncs/[id]/route.ts@@ -2,7 +2,6 @@ import { NextRequest, NextResponse } from "next/server";import { db } from "@/lib/db";import { externalSyncs, shifts, calendars } from "@/lib/db/schema";import { eq } from "drizzle-orm";-import { eventEmitter } from "@/lib/event-emitter";import { getSessionUser } from "@/lib/auth/sessions";import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";import {@@ -190,24 +189,6 @@ export async function PATCH(updatedAt: new Date(),}).where(eq(shifts.externalSyncId, id));-- // Emit event to notify clients about shift updates- eventEmitter.emit("calendar-change", {- type: "shift",- action: "update",- calendarId: updated.calendarId,- data: { externalSyncId: id, colorUpdated: true },- });- }-- // Emit event to notify clients about visibility changes- if (isHidden !== undefined || hideFromStats !== undefined) {- eventEmitter.emit("calendar-change", {- type: "shift",- action: "update",- calendarId: updated.calendarId,- data: { externalSyncId: id, visibilityUpdated: true },- });}return NextResponse.json(updated);diff --git a/app/api/external-syncs/[id]/sync/route.ts b/app/api/external-syncs/[id]/sync/route.tsindex e5b5d9f..3c7f047 100644--- a/app/api/external-syncs/[id]/sync/route.ts+++ b/app/api/external-syncs/[id]/sync/route.ts@@ -11,7 +11,6 @@ import {createEventFingerprint,needsUpdate,} from "@/lib/external-calendar-utils";-import { eventEmitter } from "@/lib/event-emitter";import { rateLimit } from "@/lib/rate-limiter";import {logUserAction,@@ -328,13 +327,6 @@ export async function syncExternalCalendar(},request,});-- // Emit event for sync log creation after successful transaction- eventEmitter.emit("calendar-change", {- type: "sync-log",- action: "create",- calendarId: externalSync.calendarId,- });} catch (error) {errorMessage =error instanceof Error ? error.message : "Unknown sync error";@@ -373,13 +365,6 @@ export async function syncExternalCalendar(request,});- // Emit event for sync log creation- eventEmitter.emit("calendar-change", {- type: "sync-log",- action: "create",- calendarId: externalSync.calendarId,- });-throw error;}diff --git a/app/api/notes/[id]/route.ts b/app/api/notes/[id]/route.tsindex 1c0725e..c49ea67 100644--- a/app/api/notes/[id]/route.ts+++ b/app/api/notes/[id]/route.ts@@ -2,7 +2,6 @@ import { NextResponse } from "next/server";import { db } from "@/lib/db";import { calendarNotes, calendars } from "@/lib/db/schema";import { eq } from "drizzle-orm";-import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";import { getSessionUser } from "@/lib/auth/sessions";import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";@@ -147,14 +146,6 @@ export async function PUT();}- // Emit event for SSE- eventEmitter.emit("calendar-change", {- type: "note",- action: "update",- calendarId: updated.calendarId,- data: updated,- } as CalendarChangeEvent);-return NextResponse.json(updated);} catch (error) {console.error("Failed to update calendar note:", error);@@ -221,14 +212,6 @@ export async function DELETE();}- // Emit event for SSE- eventEmitter.emit("calendar-change", {- type: "note",- action: "delete",- calendarId: result[0].calendarId,- data: { id },- } as CalendarChangeEvent);-return NextResponse.json({ success: true });} catch (error) {console.error("Failed to delete calendar note:", error);diff --git a/app/api/notes/route.ts b/app/api/notes/route.tsindex e565d88..1f5dc6e 100644--- a/app/api/notes/route.ts+++ b/app/api/notes/route.ts@@ -2,7 +2,6 @@ import { NextResponse } from "next/server";import { db } from "@/lib/db";import { calendarNotes, calendars } from "@/lib/db/schema";import { eq, and, gte, lte } from "drizzle-orm";-import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";import { getSessionUser } from "@/lib/auth/sessions";import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";import { parseLocalDate } from "@/lib/date-utils";@@ -163,14 +162,6 @@ export async function POST(request: Request) {}).returning();- // Emit event for SSE- eventEmitter.emit("calendar-change", {- type: "note",- action: "create",- calendarId,- data: calendarNote,- } as CalendarChangeEvent);-return NextResponse.json(calendarNote);} catch (error) {console.error("Failed to create calendar note:", error);diff --git a/app/api/presets/[id]/route.ts b/app/api/presets/[id]/route.tsindex 5d74a0a..5cb6642 100644--- a/app/api/presets/[id]/route.ts+++ b/app/api/presets/[id]/route.ts@@ -2,7 +2,6 @@ import { NextRequest, NextResponse } from "next/server";import { db } from "@/lib/db";import { shiftPresets, shifts, calendars } from "@/lib/db/schema";import { eq } from "drizzle-orm";-import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";import { getSessionUser } from "@/lib/auth/sessions";import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";@@ -142,14 +141,6 @@ export async function PATCH(}).where(eq(shifts.presetId, id));- // Emit event for SSE- eventEmitter.emit("calendar-change", {- type: "preset",- action: "update",- calendarId: existingPreset.calendarId,- data: updatedPreset,- } as CalendarChangeEvent);-return NextResponse.json(updatedPreset);} catch (error) {console.error("Error updating preset:", error);@@ -207,14 +198,6 @@ export async function DELETE(// Delete the presetawait db.delete(shiftPresets).where(eq(shiftPresets.id, id));- // Emit event for SSE- eventEmitter.emit("calendar-change", {- type: "preset",- action: "delete",- calendarId: preset.calendarId,- data: { id },- } as CalendarChangeEvent);-return NextResponse.json({ success: true });} catch (error) {console.error("Error deleting preset:", error);diff --git a/app/api/presets/reorder/route.ts b/app/api/presets/reorder/route.tsindex eeec2a2..b5ebbb8 100644--- a/app/api/presets/reorder/route.ts+++ b/app/api/presets/reorder/route.ts@@ -2,7 +2,6 @@ import { NextRequest, NextResponse } from "next/server";import { db } from "@/lib/db";import { shiftPresets, calendars } from "@/lib/db/schema";import { eq } from "drizzle-orm";-import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";import { getSessionUser } from "@/lib/auth/sessions";import { canEditCalendar } from "@/lib/auth/permissions";@@ -91,14 +90,6 @@ export async function PATCH(request: NextRequest) {);await Promise.all(updatePromises);- // Emit event for SSE- eventEmitter.emit("calendar-change", {- type: "preset",- action: "reorder",- calendarId,- data: { presetOrders },- } as CalendarChangeEvent);-return NextResponse.json({ success: true });} catch (error) {console.error("Error reordering presets:", error);diff --git a/app/api/presets/route.ts b/app/api/presets/route.tsindex ae994c3..5c13ccc 100644--- a/app/api/presets/route.ts+++ b/app/api/presets/route.ts@@ -2,7 +2,6 @@ import { NextRequest, NextResponse } from "next/server";import { db } from "@/lib/db";import { shiftPresets, calendars } from "@/lib/db/schema";import { eq, asc } from "drizzle-orm";-import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";import { getSessionUser } from "@/lib/auth/sessions";import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";@@ -132,14 +131,6 @@ export async function POST(request: NextRequest) {}).returning();- // Emit event for SSE- eventEmitter.emit("calendar-change", {- type: "preset",- action: "create",- calendarId,- data: preset,- } as CalendarChangeEvent);-return NextResponse.json(preset);} catch (error) {console.error("Error creating preset:", error);diff --git a/app/api/shifts/[id]/route.ts b/app/api/shifts/[id]/route.tsindex ebab39c..397f340 100644--- a/app/api/shifts/[id]/route.ts+++ b/app/api/shifts/[id]/route.ts@@ -2,10 +2,8 @@ import { NextResponse } from "next/server";import { db } from "@/lib/db";import { calendars, shifts } from "@/lib/db/schema";import { eq } from "drizzle-orm";-import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";import { getSessionUser } from "@/lib/auth/sessions";import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";-import { parseLocalDate } from "@/lib/date-utils";// GET single shiftexport async function GET(@@ -63,93 +61,6 @@ export async function GET(}}-// PATCH update shift (requires write permission)-export async function PATCH(- request: Request,- { params }: { params: Promise<{ id: string }> }-) {- try {- const { id } = await params;- const body = await request.json();- const {- date,- startTime,- endTime,- title,- color,- notes,- isAllDay,- isSecondary,- } = body;-- const user = await getSessionUser(request.headers);-- // Fetch shift to get calendar ID- const [existingShift] = await db- .select()- .from(shifts)- .where(eq(shifts.id, id));-- if (!existingShift) {- return NextResponse.json({ error: "Shift not found" }, { status: 404 });- }-- // Fetch calendar- const [calendar] = await db- .select()- .from(calendars)- .where(eq(calendars.id, existingShift.calendarId));-- if (!calendar) {- return NextResponse.json(- { error: "Calendar not found" },- { status: 404 }- );- }-- // Check write permission (works for both authenticated users and guests)- const hasAccess = await canEditCalendar(user?.id, existingShift.calendarId);- if (!hasAccess) {- return NextResponse.json(- { error: "Insufficient permissions. Write access required." },- { status: 403 }- );- }-- const updateData: Partial<typeof shifts.$inferInsert> = {};- if (date) updateData.date = parseLocalDate(date);- if (startTime !== undefined) updateData.startTime = startTime;- if (endTime !== undefined) updateData.endTime = endTime;- if (title) updateData.title = title;- if (color) updateData.color = color;- if (notes !== undefined) updateData.notes = notes;- if (isAllDay !== undefined) updateData.isAllDay = isAllDay;- if (isSecondary !== undefined) updateData.isSecondary = isSecondary;-- const [shift] = await db- .update(shifts)- .set(updateData)- .where(eq(shifts.id, id))- .returning();-- // Emit event for SSE- eventEmitter.emit("calendar-change", {- type: "shift",- action: "update",- calendarId: existingShift.calendarId,- data: { ...shift, calendar },- } as CalendarChangeEvent);-- return NextResponse.json({ ...shift, calendar });- } catch (error) {- console.error("Failed to update shift:", error);- return NextResponse.json(- { error: "Failed to update shift" },- { status: 500 }- );- }-}-// DELETE shift (requires write permission)export async function DELETE(request: Request,@@ -177,14 +88,6 @@ export async function DELETE(await db.delete(shifts).where(eq(shifts.id, id));- // Emit event for SSE- eventEmitter.emit("calendar-change", {- type: "shift",- action: "delete",- calendarId: shift.calendarId,- data: { id },- } as CalendarChangeEvent);-return NextResponse.json({ success: true });} catch (error) {console.error("Failed to delete shift:", error);diff --git a/app/api/shifts/route.ts b/app/api/shifts/route.tsindex 115e9ec..4292fd0 100644--- a/app/api/shifts/route.ts+++ b/app/api/shifts/route.ts@@ -2,7 +2,6 @@ import { NextResponse } from "next/server";import { db } from "@/lib/db";import { calendars, shifts, externalSyncs } from "@/lib/db/schema";import { eq, and, gte, lte, or, isNull } from "drizzle-orm";-import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";import { getSessionUser } from "@/lib/auth/sessions";import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";import { parseLocalDate } from "@/lib/date-utils";@@ -191,14 +190,6 @@ export async function POST(request: Request) {}).returning();- // Emit event for SSE- eventEmitter.emit("calendar-change", {- type: "shift",- action: "create",- calendarId,- data: { ...shift, calendar },- } as CalendarChangeEvent);-return NextResponse.json({ ...shift, calendar }, { status: 201 });} catch (error) {console.error("Failed to create shift:", error);diff --git a/app/layout.tsx b/app/layout.tsxindex 7e9e4df..d2854a6 100644--- a/app/layout.tsx+++ b/app/layout.tsx@@ -6,6 +6,7 @@ import { ThemeProvider } from "@/components/theme-provider";import { ThemedToaster } from "@/components/themed-toaster";import { AuthProvider } from "@/components/auth-provider";import { PublicConfigProvider } from "@/components/public-config-provider";+import { QueryProvider } from "@/components/query-provider";import { getPublicConfig } from "@/lib/public-config";import "./globals.css";@@ -87,9 +88,11 @@ export default async function RootLayout({disableTransitionOnChange={false}><NextIntlClientProvider messages={messages} locale={locale}>- <PublicConfigProvider initialConfig={publicConfig}>- <AuthProvider>{children}</AuthProvider>- </PublicConfigProvider>+ <QueryProvider>+ <PublicConfigProvider initialConfig={publicConfig}>+ <AuthProvider>{children}</AuthProvider>+ </PublicConfigProvider>+ </QueryProvider><ThemedToaster /></NextIntlClientProvider></ThemeProvider>diff --git a/app/page.tsx b/app/page.tsxindex cfe233f..a5b5df4 100644--- a/app/page.tsx+++ b/app/page.tsx@@ -9,18 +9,15 @@ import { Plus } from "lucide-react";import { getDateLocale } from "@/lib/locales";import { motion, AnimatePresence } from "motion/react";import { ShiftWithCalendar } from "@/lib/types";-import {- ShiftPreset,- CalendarNote,- ExternalSync,- Shift,-} from "@/lib/db/schema";+import { CalendarNote } from "@/lib/db/schema";import { useCalendars } from "@/hooks/useCalendars";-import { useShifts, normalizeShift } from "@/hooks/useShifts";+import { useShifts } from "@/hooks/useShifts";import { usePresets } from "@/hooks/usePresets";-import { useNotes, normalizeNote } from "@/hooks/useNotes";-import { useSSEConnection } from "@/hooks/useSSEConnection";+import { useNotes } from "@/hooks/useNotes";+import { useCompareData } from "@/hooks/useCompareData";import { useViewSettings } from "@/hooks/useViewSettings";+import { useQueryClient } from "@tanstack/react-query";+import { queryKeys } from "@/lib/query-keys";import { useShiftActions } from "@/hooks/useShiftActions";import { useNoteActions } from "@/hooks/useNoteActions";import { useExternalSync } from "@/hooks/useExternalSync";@@ -66,11 +63,9 @@ function HomeContent() {const {shifts,- setShifts,loading: shiftsLoading,hasLoadedOnce: shiftsLoadedOnce,createShift: createShiftHook,- updateShift: updateShiftHook,deleteShift: deleteShiftHook,refetchShifts,} = useShifts(selectedCalendar);@@ -79,7 +74,6 @@ function HomeContent() {presets,loading: presetsLoading,hasLoadedOnce: presetsLoadedOnce,- refetchPresets,} = usePresets(selectedCalendar);// Local state@@ -88,8 +82,6 @@ function HomeContent() {>();const [currentDate, setCurrentDate] = useState(new Date());const [selectedDate, setSelectedDate] = useState<Date | undefined>();- const [statsRefreshTrigger, setStatsRefreshTrigger] = useState(0);- const [isConnected, setIsConnected] = useState(true);const [compareNoteCalendarId, setCompareNoteCalendarId] = useState<string | undefined>();@@ -98,23 +90,30 @@ function HomeContent() {const [isCompareMode, setIsCompareMode] = useState(false);const [showCompareSelector, setShowCompareSelector] = useState(false);const [selectedCompareIds, setSelectedCompareIds] = useState<string[]>([]);- const [compareDataLoading, setCompareDataLoading] = useState(false);++ // Local UI state for toggling dates in compare mode (shows spinner during API call)+ const [compareTogglingDates, setCompareTogglingDates] = useState<+ Map<string, Set<string>>+ >(new Map());++ // Query client for cache invalidation+ const queryClient = useQueryClient();++ // Compare mode data using React Query+ const compareData = useCompareData({+ calendarIds: selectedCompareIds,+ enabled: isCompareMode,+ });const {notes,createNote: createNoteHook,updateNote: updateNoteHook,deleteNote: deleteNoteHook,- refetchNotes,} = useNotes(isCompareMode ? compareNoteCalendarId : selectedCalendar);- const {- externalSyncs,- hasSyncErrors,- syncLogRefreshTrigger,- setSyncLogRefreshTrigger,- fetchExternalSyncs,- fetchSyncErrorStatus,- } = useExternalSync(selectedCalendar || null);+ const { externalSyncs, hasSyncErrors } = useExternalSync(+ selectedCalendar || null+ );// View settingsconst viewSettings = useViewSettings();@@ -145,24 +144,9 @@ function HomeContent() {recurringInterval);- // Reload notes for the specific calendar in compare mode+ // Invalidate notes cache for the specific calendar in compare modeif (isCompareMode && compareNoteCalendarId) {- try {- const notesRes = await fetch(- `/api/notes?calendarId=${compareNoteCalendarId}`- );- const notesData = notesRes.ok ? await notesRes.json() : [];- setCompareCalendarData((prev) => {- const updated = new Map(prev);- const data = updated.get(compareNoteCalendarId);- if (data) {- updated.set(compareNoteCalendarId, { ...data, notes: notesData });- }- return updated;- });- } catch (error) {- console.error("Failed to reload notes:", error);- }+ compareData.invalidateNotes(compareNoteCalendarId);}};@@ -170,24 +154,9 @@ function HomeContent() {const handleNoteDelete = async () => {await noteActions.handleNoteDelete();- // Reload notes for the specific calendar in compare mode+ // Invalidate notes cache for the specific calendar in compare modeif (isCompareMode && compareNoteCalendarId) {- try {- const notesRes = await fetch(- `/api/notes?calendarId=${compareNoteCalendarId}`- );- const notesData = notesRes.ok ? await notesRes.json() : [];- setCompareCalendarData((prev) => {- const updated = new Map(prev);- const data = updated.get(compareNoteCalendarId);- if (data) {- updated.set(compareNoteCalendarId, { ...data, notes: notesData });- }- return updated;- });- } catch (error) {- console.error("Failed to reload notes:", error);- }+ compareData.invalidateNotes(compareNoteCalendarId);}};@@ -215,24 +184,9 @@ function HomeContent() {dialogStates.setShowNotesListDialog(false);}- // Reload compare mode data if needed+ // Invalidate compare mode data if neededif (isCompareMode && compareNoteCalendarId) {- try {- const notesRes = await fetch(- `/api/notes?calendarId=${compareNoteCalendarId}`- );- const notesData = notesRes.ok ? await notesRes.json() : [];- setCompareCalendarData((prev) => {- const updated = new Map(prev);- const data = updated.get(compareNoteCalendarId);- if (data) {- updated.set(compareNoteCalendarId, { ...data, notes: notesData });- }- return updated;- });- } catch (error) {- console.error("Failed to reload notes:", error);- }+ compareData.invalidateNotes(compareNoteCalendarId);}}};@@ -242,109 +196,17 @@ function HomeContent() {noteActions.openNoteDialog(date, undefined);};- // External sync management- const [compareCalendarData, setCompareCalendarData] = useState<- Map<- string,- {- shifts: ShiftWithCalendar[];- notes: CalendarNote[];- externalSyncs: ExternalSync[];- presets: ShiftPreset[];- togglingDates: Set<string>;- }- >- >(new Map());-// Version infoconst versionInfo = useVersionInfo();// Shift actionsconst shiftActions = useShiftActions({shifts,- setShifts,presets,createShift: createShiftHook,- updateShift: updateShiftHook,deleteShift: deleteShiftHook,- onStatsRefresh: () => setStatsRefreshTrigger((prev) => prev + 1),- });-- // SSE Connection- useSSEConnection({- calendarId: selectedCalendar,- onShiftUpdate: refetchShifts,- onPresetUpdate: refetchPresets,- onNoteUpdate: refetchNotes,- onCalendarUpdate: refetchCalendars,- onStatsRefresh: () => setStatsRefreshTrigger((prev) => prev + 1),- onSyncLogUpdate: () => {- fetchSyncErrorStatus();- setSyncLogRefreshTrigger((prev) => prev + 1);- },- isConnected,- setIsConnected,});- // Load data for compare mode- useEffect(() => {- if (!isCompareMode || selectedCompareIds.length === 0) return;-- const loadCompareData = async () => {- setCompareDataLoading(true);- const dataMap = new Map();-- // Load all calendars in parallel- await Promise.all(- selectedCompareIds.map(async (calendarId) => {- try {- // Fetch all data for this calendar in parallel- const [shiftsRes, notesRes, syncsRes, presetsRes] =- await Promise.all([- fetch(`/api/shifts?calendarId=${calendarId}`),- fetch(`/api/notes?calendarId=${calendarId}`),- fetch(`/api/external-syncs?calendarId=${calendarId}`),- fetch(`/api/presets?calendarId=${calendarId}`),- ]);-- const [shiftsData, notesData, syncsData, presetsData] =- await Promise.all([- shiftsRes.ok ? shiftsRes.json() : [],- notesRes.ok ? notesRes.json() : [],- syncsRes.ok ? syncsRes.json() : [],- presetsRes.ok ? presetsRes.json() : [],- ]);-- dataMap.set(calendarId, {- shifts: shiftsData.map(normalizeShift),- notes: notesData.map(normalizeNote),- externalSyncs: syncsData,- presets: presetsData,- togglingDates: new Set<string>(),- });- } catch (error) {- console.error(- `Error loading data for calendar ${calendarId}:`,- error- );- dataMap.set(calendarId, {- shifts: [],- notes: [],- externalSyncs: [],- presets: [],- togglingDates: new Set<string>(),- });- }- })- );-- setCompareCalendarData(dataMap);- setCompareDataLoading(false);- };-- loadCompareData();- }, [isCompareMode, selectedCompareIds]);-// Load compare mode from URL on initial loaduseEffect(() => {const compareParam = searchParams.get("compare");@@ -364,7 +226,7 @@ function HomeContent() {// If compare param is removed from URL, exit compare modesetIsCompareMode(false);setSelectedCompareIds([]);- setCompareCalendarData(new Map());+ setCompareTogglingDates(new Map());}// eslint-disable-next-line react-hooks/exhaustive-deps}, [searchParams, calendars]);@@ -385,10 +247,8 @@ function HomeContent() {// Calendar operationsconst handleDeleteCalendar = async () => {if (!selectedCalendar) return;- const success = await deleteCalendarHook(selectedCalendar);- if (success) {- dialogStates.setShowCalendarSettingsDialog(false);- }+ await deleteCalendarHook(selectedCalendar);+ dialogStates.setShowCalendarSettingsDialog(false);};// External sync operations@@ -397,11 +257,11 @@ function HomeContent() {};const handleSyncComplete = () => {- refetchShifts();- refetchCalendars();- setStatsRefreshTrigger((prev) => prev + 1);- fetchExternalSyncs();- fetchSyncErrorStatus();+ // Invalidate caches - React Query will refetch automatically+ queryClient.invalidateQueries({+ queryKey: queryKeys.shifts.byCalendar(selectedCalendar!),+ });+ queryClient.invalidateQueries({ queryKey: queryKeys.calendars.all });};// Manual shift creation@@ -519,7 +379,7 @@ function HomeContent() {const handleExitCompare = () => {setIsCompareMode(false);setSelectedCompareIds([]);- setCompareCalendarData(new Map());+ setCompareTogglingDates(new Map());// Immediately update URL to prevent re-loading from URL parameterif (selectedCalendar) {router.replace(`/?id=${selectedCalendar}`, { scroll: false });@@ -541,10 +401,9 @@ function HomeContent() {if (!selectedPresetId) {// No preset selected, just show existing shifts if any- const calendarData = compareCalendarData.get(calendarId);- if (!calendarData) return;+ const shifts = compareData.shiftsMap.get(calendarId) || [];- const dayShifts = calendarData.shifts.filter(+ const dayShifts = shifts.filter((shift) => shift.date && isSameDay(shift.date as Date, targetDate));@@ -557,32 +416,30 @@ function HomeContent() {}// Preset selected, add or remove shift- const calendarData = compareCalendarData.get(calendarId);- if (!calendarData) return;-- const preset = calendarData.presets.find((p) => p.id === selectedPresetId);+ const presets = compareData.presetsMap.get(calendarId) || [];+ const shifts = compareData.shiftsMap.get(calendarId) || [];+ const preset = presets.find((p) => p.id === selectedPresetId);if (!preset) return;const dateKey = formatDateToLocal(targetDate);// Check if already toggling- if (calendarData.togglingDates.has(dateKey)) return;+ const togglingDates = compareTogglingDates.get(calendarId) || new Set();+ if (togglingDates.has(dateKey)) return;// Mark as toggling- const newTogglingDates = new Set(calendarData.togglingDates);- newTogglingDates.add(dateKey);- setCompareCalendarData((prev) => {+ setCompareTogglingDates((prev) => {const updated = new Map(prev);- const data = updated.get(calendarId);- if (data) {- updated.set(calendarId, { ...data, togglingDates: newTogglingDates });- }+ const current = updated.get(calendarId) || new Set();+ const newSet = new Set(current);+ newSet.add(dateKey);+ updated.set(calendarId, newSet);return updated;});try {// Check if shift already exists- const existingShift = calendarData.shifts.find(+ const existingShift = shifts.find((shift) =>shift.date &&isSameDay(shift.date as Date, targetDate) &&@@ -592,36 +449,14 @@ function HomeContent() {);if (existingShift) {- // Delete existing shift- const response = await fetch(`/api/shifts/${existingShift.id}`, {- method: "DELETE",- headers: { "Content-Type": "application/json" },+ // Delete existing shift using mutation+ await compareData.deleteShift({+ calendarId,+ shiftId: existingShift.id,});-- if (!response.ok) {- toast.error(t("common.deleteError", { item: t("shift.shift_one") }));- } else {- toast.success(t("common.deleted", { item: t("shift.shift_one") }));- // Reload shifts for this calendar- const shiftsRes = await fetch(`/api/shifts?calendarId=${calendarId}`);- const shiftsData = shiftsRes.ok ? await shiftsRes.json() : [];- setCompareCalendarData((prev) => {- const updated = new Map(prev);- const data = updated.get(calendarId);- if (data) {- updated.set(calendarId, {- ...data,- shifts: shiftsData.map(normalizeShift),- });- }- return updated;- });- setStatsRefreshTrigger((prev) => prev + 1);- }} else {- // Create new shift+ // Create new shift using mutationconst shiftData = {- calendarId,date: dateKey,startTime: preset.startTime,endTime: preset.endTime,@@ -632,46 +467,19 @@ function HomeContent() {isAllDay: preset.isAllDay || false,};- const response = await fetch("/api/shifts", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(shiftData),- });-- if (!response.ok) {- toast.error(t("common.createError", { item: t("shift.shift_one") }));- } else {- toast.success(t("common.created", { item: t("shift.shift_one") }));- // Reload shifts for this calendar- const shiftsRes = await fetch(`/api/shifts?calendarId=${calendarId}`);- const shiftsData = shiftsRes.ok ? await shiftsRes.json() : [];- setCompareCalendarData((prev) => {- const updated = new Map(prev);- const data = updated.get(calendarId);- if (data) {- updated.set(calendarId, {- ...data,- shifts: shiftsData.map(normalizeShift),- });- }- return updated;- });- setStatsRefreshTrigger((prev) => prev + 1);- }+ await compareData.createShift({ calendarId, formData: shiftData });}} catch (error) {console.error("Failed to toggle shift:", error);toast.error(t("common.error"));} finally {// Remove toggling state- setCompareCalendarData((prev) => {+ setCompareTogglingDates((prev) => {const updated = new Map(prev);- const data = updated.get(calendarId);- if (data) {- const newTogglingDates = new Set(data.togglingDates);- newTogglingDates.delete(dateKey);- updated.set(calendarId, { ...data, togglingDates: newTogglingDates });- }+ const current = updated.get(calendarId) || new Set();+ const newSet = new Set(current);+ newSet.delete(dateKey);+ updated.set(calendarId, newSet);return updated;});}@@ -683,11 +491,10 @@ function HomeContent() {date: Date) => {e.preventDefault();- const calendarData = compareCalendarData.get(calendarId);- if (!calendarData) return;+ const calendarNotes = compareData.notesMap.get(calendarId) || [];// Get all notes/events for this date (including recurring)- const allDayNotes = findNotesForDate(calendarData.notes, date);+ const allDayNotes = findNotesForDate(calendarNotes, date);// Always show list dialog when notes exist (to allow adding more)if (allDayNotes.length >= 1) {@@ -708,11 +515,10 @@ function HomeContent() {date: Date) => {e.stopPropagation();- const calendarData = compareCalendarData.get(calendarId);- if (!calendarData) return;+ const calendarNotes = compareData.notesMap.get(calendarId) || [];// Get all notes/events for this date (including recurring)- const allDayNotes = findNotesForDate(calendarData.notes, date);+ const allDayNotes = findNotesForDate(calendarNotes, date);// Always show list dialog when notes exist (to allow adding more)if (allDayNotes.length >= 1) {@@ -728,11 +534,10 @@ function HomeContent() {};const handleCompareLongPress = (calendarId: string, date: Date) => {- const calendarData = compareCalendarData.get(calendarId);- if (!calendarData) return;+ const calendarNotes = compareData.notesMap.get(calendarId) || [];// Get all notes/events for this date (including recurring)- const allDayNotes = findNotesForDate(calendarData.notes, date);+ const allDayNotes = findNotesForDate(calendarNotes, date);// Always show list dialog when notes exist (to allow adding more)if (allDayNotes.length >= 1) {@@ -783,10 +588,16 @@ function HomeContent() {// If in compare mode, render compare viewif (isCompareMode) {// Show loader while loading compare data- if (compareDataLoading) {+ if (compareData.isLoading) {return <FullscreenLoader message={t("common.loading")} />;}+ // Build togglingDatesMap from local state+ const togglingDatesMap = new Map<string, Set<string>>();+ selectedCompareIds.forEach((id) => {+ togglingDatesMap.set(id, compareTogglingDates.get(id) || new Set());+ });+return (<><CalendarCompareView@@ -796,48 +607,13 @@ function HomeContent() {calendarDays={calendarDays}currentDate={currentDate}onDateChange={setCurrentDate}- shiftsMap={- new Map(- Array.from(compareCalendarData.entries()).map(([id, data]) => [- id,- data.shifts,- ])- )- }- notesMap={- new Map(- Array.from(compareCalendarData.entries()).map(([id, data]) => [- id,- data.notes,- ])- )- }- externalSyncsMap={- new Map(- Array.from(compareCalendarData.entries()).map(([id, data]) => [- id,- data.externalSyncs,- ])- )- }- presetsMap={- new Map(- Array.from(compareCalendarData.entries()).map(([id, data]) => [- id,- data.presets || [],- ])- )- }+ shiftsMap={compareData.shiftsMap}+ notesMap={compareData.notesMap}+ externalSyncsMap={compareData.externalSyncsMap}+ presetsMap={compareData.presetsMap}selectedPresetId={selectedPresetId}onSelectPreset={setSelectedPresetId}- togglingDatesMap={- new Map(- Array.from(compareCalendarData.entries()).map(([id, data]) => [- id,- data.togglingDates,- ])- )- }+ togglingDatesMap={togglingDatesMap}maxShiftsToShow={viewSettings.shiftsPerDay === null? undefined@@ -855,7 +631,6 @@ function HomeContent() {combinedSortMode={viewSettings.combinedSortMode}highlightedWeekdays={viewSettings.highlightedWeekdays}highlightColor={viewSettings.highlightColor}- statsRefreshTrigger={statsRefreshTrigger}locale={dateLocale}onDayClick={handleCompareDayClick}onDayRightClick={handleCompareDayRightClick}@@ -869,80 +644,22 @@ function HomeContent() {onExit={handleExitCompare}hidePresetHeader={viewSettings.hidePresetHeader}onHidePresetHeaderChange={viewSettings.handleHidePresetHeaderChange}- onPresetsChange={async (calendarId: string) => {- // Reload presets and shifts for specific calendar- try {- const [presetsRes, shiftsRes] = await Promise.all([- fetch(`/api/presets?calendarId=${calendarId}`),- fetch(`/api/shifts?calendarId=${calendarId}`),- ]);-- const [presetsData, shiftsData] = await Promise.all([- presetsRes.ok ? presetsRes.json() : [],- shiftsRes.ok ? shiftsRes.json() : [],- ]);-- setCompareCalendarData((prev) => {- const updated = new Map(prev);- const data = updated.get(calendarId);- if (data) {- updated.set(calendarId, {- ...data,- presets: presetsData,- shifts: shiftsData.map(normalizeShift),- });- }- return updated;- });- setStatsRefreshTrigger((prev) => prev + 1);- } catch (error) {- console.error(- `Error reloading presets for calendar ${calendarId}:`,- error- );- }+ onPresetsChange={(calendarId: string) => {+ // Invalidate presets and shifts cache for this calendar+ compareData.invalidatePresets(calendarId);+ queryClient.invalidateQueries({+ queryKey: queryKeys.shifts.byCalendar(calendarId),+ });}}onShiftsChange={() => {- // Reload shifts for all calendars- const loadShifts = async () => {- // Build updates for each calendar in parallel- const updates = new Map<string, Shift[]>();- await Promise.all(- selectedCompareIds.map(async (calendarId) => {- try {- const shiftsRes = await fetch(- `/api/shifts?calendarId=${calendarId}`- );- const shiftsData = shiftsRes.ok- ? await shiftsRes.json()- : [];- updates.set(calendarId, shiftsData);- } catch (error) {- console.error(- `Error loading shifts for calendar ${calendarId}:`,- error- );- }- })- );- // Apply updates using functional state updater- setCompareCalendarData((prev) => {- const dataMap = new Map(prev);- for (const [calendarId, shiftsData] of updates.entries()) {- const currentData = dataMap.get(calendarId);- if (currentData) {- dataMap.set(calendarId, {- ...currentData,- shifts: shiftsData.map(normalizeShift),- });- }- }- return dataMap;+ // Invalidate shifts cache for all compare calendars+ selectedCompareIds.forEach((calendarId) => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.shifts.byCalendar(calendarId),});- };- loadShifts();+ });}}- onStatsRefresh={() => setStatsRefreshTrigger((prev) => prev + 1)}+ presetsLoadingMap={compareData.presetsLoadingMap}/>{/* Dialogs still work in compare mode */}@@ -955,7 +672,6 @@ function HomeContent() {onShiftSubmit={shiftActions.handleShiftSubmit}selectedDate={selectedDate}selectedCalendar={selectedCalendar || null}- onPresetsChange={refetchPresets}calendars={calendars}showCalendarSettingsDialog={dialogStates.showCalendarSettingsDialog}onCalendarSettingsDialogChange={@@ -968,14 +684,11 @@ function HomeContent() {}showExternalSyncDialog={dialogStates.showExternalSyncDialog}onExternalSyncDialogChange={dialogStates.setShowExternalSyncDialog}- syncErrorRefreshTrigger={syncLogRefreshTrigger}onSyncComplete={handleSyncComplete}showSyncNotificationDialog={dialogStates.showSyncNotificationDialog}onSyncNotificationDialogChange={dialogStates.setShowSyncNotificationDialog}- onErrorsMarkedRead={fetchSyncErrorStatus}- onSyncLogUpdate={() => setSyncLogRefreshTrigger((prev) => prev + 1)}showDayShiftsDialog={dialogStates.showDayShiftsDialog}onDayShiftsDialogChange={dialogStates.setShowDayShiftsDialog}selectedDayDate={dialogStates.selectedDayDate}@@ -1046,7 +759,6 @@ function HomeContent() {onShiftSubmit={shiftActions.handleShiftSubmit}selectedDate={selectedDate}selectedCalendar={selectedCalendar || null}- onPresetsChange={refetchPresets}calendars={calendars}showCalendarSettingsDialog={dialogStates.showCalendarSettingsDialog}onCalendarSettingsDialogChange={@@ -1059,14 +771,11 @@ function HomeContent() {}showExternalSyncDialog={dialogStates.showExternalSyncDialog}onExternalSyncDialogChange={dialogStates.setShowExternalSyncDialog}- syncErrorRefreshTrigger={syncLogRefreshTrigger}onSyncComplete={handleSyncComplete}showSyncNotificationDialog={dialogStates.showSyncNotificationDialog}onSyncNotificationDialogChange={dialogStates.setShowSyncNotificationDialog}- onErrorsMarkedRead={fetchSyncErrorStatus}- onSyncLogUpdate={() => setSyncLogRefreshTrigger((prev) => prev + 1)}showDayShiftsDialog={dialogStates.showDayShiftsDialog}onDayShiftsDialogChange={dialogStates.setShowDayShiftsDialog}selectedDayDate={dialogStates.selectedDayDate}@@ -1135,7 +844,6 @@ function HomeContent() {selectedCalendar={selectedCalendar}presets={presets}selectedPresetId={selectedPresetId}- isConnected={isConnected}showMobileCalendarDialog={dialogStates.showMobileCalendarDialog}hasSyncErrors={hasSyncErrors}onSelectCalendar={setSelectedCalendar}@@ -1144,9 +852,7 @@ function HomeContent() {onSettings={() => dialogStates.setShowCalendarSettingsDialog(true)}onSyncNotifications={handleSyncNotifications}onCompare={handleCompareClick}- onPresetsChange={refetchPresets}onShiftsChange={refetchShifts}- onStatsRefresh={() => setStatsRefreshTrigger((prev) => prev + 1)}onManualShiftCreation={handleManualShiftCreation}onMobileCalendarDialogChange={dialogStates.setShowMobileCalendarDialog}onViewSettingsClick={() => dialogStates.setShowViewSettingsDialog(true)}@@ -1183,7 +889,6 @@ function HomeContent() {highlightedWeekdays={viewSettings.highlightedWeekdays}highlightColor={viewSettings.highlightColor}selectedCalendar={selectedCalendar || null}- statsRefreshTrigger={statsRefreshTrigger}locale={dateLocale}onDayClick={handleDayClick}onDayRightClick={handleDayRightClick}@@ -1223,7 +928,6 @@ function HomeContent() {onShiftSubmit={shiftActions.handleShiftSubmit}selectedDate={selectedDate}selectedCalendar={selectedCalendar || null}- onPresetsChange={refetchPresets}calendars={calendars}showCalendarSettingsDialog={dialogStates.showCalendarSettingsDialog}onCalendarSettingsDialogChange={@@ -1236,14 +940,11 @@ function HomeContent() {}showExternalSyncDialog={dialogStates.showExternalSyncDialog}onExternalSyncDialogChange={dialogStates.setShowExternalSyncDialog}- syncErrorRefreshTrigger={syncLogRefreshTrigger}onSyncComplete={handleSyncComplete}showSyncNotificationDialog={dialogStates.showSyncNotificationDialog}onSyncNotificationDialogChange={dialogStates.setShowSyncNotificationDialog}- onErrorsMarkedRead={fetchSyncErrorStatus}- onSyncLogUpdate={() => setSyncLogRefreshTrigger((prev) => prev + 1)}showDayShiftsDialog={dialogStates.showDayShiftsDialog}onDayShiftsDialogChange={dialogStates.setShowDayShiftsDialog}selectedDayDate={dialogStates.selectedDayDate}diff --git a/app/profile/activity/page.tsx b/app/profile/activity/page.tsxindex cfeacdf..6d32885 100644--- a/app/profile/activity/page.tsx+++ b/app/profile/activity/page.tsx@@ -1,6 +1,6 @@"use client";-import React, { useState, useEffect } from "react";+import React, { useState, useEffect, useMemo, useCallback } from "react";import { useRouter } from "next/navigation";import { useTranslations, useLocale } from "next-intl";import { useAuth } from "@/hooks/useAuth";@@ -31,7 +31,6 @@ import { AppFooter } from "@/components/app-footer";import {ChevronLeft,ChevronRight,- RefreshCw,Trash2,Search,ChevronDown,@@ -40,7 +39,6 @@ import {import { format } from "date-fns";import { getDateLocale } from "@/lib/locales";import { cn } from "@/lib/utils";-import { toast } from "sonner";/*** Activity Log Page - Full-screen table view for user activity logs@@ -61,32 +59,96 @@ export default function ActivityLogPage() {const router = useRouter();const { isLoading: authLoading, isAuthenticated } = useAuth();const versionInfo = useVersionInfo();- const {- logs,- total,- page,- limit,- hasMore,- loading,- error,- filters,- updateFilters,- clearFilters,- fetchLogs,- clearLogs,- goToNextPage,- goToPreviousPage,- } = useActivityLogs();- // UI State (must be defined before any early returns)- const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());+ // Filter State (managed locally like admin audit log page)+ const [page, setPage] = useState(0);+ const limit = 50;+ const [typeFilter, setTypeFilter] = useState<string>("all");+ const [severityFilter, setSeverityFilter] = useState<string>("all");+ const [searchQuery, setSearchQuery] = useState("");+ const [debouncedSearch, setDebouncedSearch] = useState("");+ const [startDate, setStartDate] = useState("");+ const [endDate, setEndDate] = useState("");++ // Sort Stateconst [sortColumn, setSortColumn] = useState<"timestamp" | "type" | "severity" | null>("timestamp");const [sortDirection, setSortDirection] = useState<"asc" | "desc">("desc");++ // Build filters and pagination with useMemo (like admin audit log page)+ const filters = useMemo(+ () => ({+ type:+ typeFilter !== "all"+ ? (typeFilter as "sync" | "auth" | "calendar" | "security")+ : undefined,+ severity:+ severityFilter !== "all"+ ? (severityFilter as "info" | "warning" | "error" | "critical")+ : undefined,+ search: debouncedSearch || undefined,+ startDate: startDate || undefined,+ endDate: endDate || undefined,+ }),+ [typeFilter, severityFilter, debouncedSearch, startDate, endDate]+ );++ const pagination = useMemo(+ () => ({+ limit,+ offset: page * limit,+ }),+ [page, limit]+ );++ // Use hook with filters and pagination+ const { logs, total, isLoading, error, clearLogs } = useActivityLogs(+ filters,+ pagination+ );++ // Calculate pagination info+ const hasMore = (page + 1) * limit < total;++ // UI State (must be defined before any early returns)+ const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());const [clearDialogOpen, setClearDialogOpen] = useState(false);- const [startDate, setStartDate] = useState<string>("");- const [endDate, setEndDate] = useState<string>("");++ // Handler functions that combine filter changes with page reset+ const handleTypeFilterChange = (value: string) => {+ setTypeFilter(value);+ setPage(0);+ };++ const handleSeverityFilterChange = (value: string) => {+ setSeverityFilter(value);+ setPage(0);+ };++ const handleStartDateChange = (value: string) => {+ setStartDate(value);+ setPage(0);+ };++ const handleEndDateChange = (value: string) => {+ setEndDate(value);+ setPage(0);+ };++ const handleDebouncedSearchChange = useCallback((value: string) => {+ setDebouncedSearch(value);+ setPage(0);+ }, []);++ // Debounce search query+ useEffect(() => {+ const timer = setTimeout(() => {+ handleDebouncedSearchChange(searchQuery);+ }, 500);++ return () => clearTimeout(timer);+ }, [searchQuery, handleDebouncedSearchChange]);// Redirect to login if not authenticateduseEffect(() => {@@ -95,8 +157,9 @@ export default function ActivityLogPage() {}}, [authLoading, isAuthenticated, router]);- // Show fullscreen loader during initial data fetch- if (authLoading || loading) {+ // Show fullscreen loader only during initial auth check+ // Don't show loader during data refetches to prevent UI flashing+ if (authLoading) {return <FullscreenLoader />;}@@ -179,29 +242,35 @@ export default function ActivityLogPage() {}};- // Handle date changes- const handleStartDateChange = (value: string) => {- setStartDate(value);- updateFilters({- startDate: value ? new Date(value) : undefined,- endDate: endDate ? new Date(endDate) : undefined,- });- };-- const handleEndDateChange = (value: string) => {- setEndDate(value);- updateFilters({- startDate: startDate ? new Date(startDate) : undefined,- endDate: value ? new Date(value) : undefined,- });- };-// Clear all logs with confirmationconst handleClearAll = async () => {setClearDialogOpen(false);await clearLogs();};+ // Clear all filters+ const clearFilters = () => {+ setTypeFilter("all");+ setSeverityFilter("all");+ setSearchQuery("");+ setDebouncedSearch("");+ setStartDate("");+ setEndDate("");+ setPage(0);+ };++ // Check if any filters are active+ const hasActiveFilters =+ typeFilter !== "all" ||+ severityFilter !== "all" ||+ startDate ||+ endDate ||+ searchQuery;++ // Pagination handlers+ const goToNextPage = () => setPage((prev) => prev + 1);+ const goToPreviousPage = () => setPage((prev) => Math.max(0, prev - 1));+return (<div className="flex min-h-screen flex-col"><AuthHeader showUserMenu />@@ -209,30 +278,35 @@ export default function ActivityLogPage() {<div className="flex-1 bg-gradient-to-br from-background via-background to-primary/5"><main className="container py-4 sm:py-8 max-w-full sm:max-w-6xl mx-auto px-2 sm:px-4">{/* Header */}- <div className="mb-6 sm:mb-8">- <h1 className="text-2xl sm:text-4xl font-bold tracking-tight bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text text-transparent mb-2">- {t("activityLog.title")}- </h1>- <p className="text-sm text-muted-foreground">- {t("activityLog.description")}- </p>+ <div className="mb-6 sm:mb-8 flex items-center justify-between">+ <div>+ <h1 className="text-2xl sm:text-4xl font-bold tracking-tight bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text text-transparent mb-2">+ {t("activityLog.title")}+ </h1>+ <p className="text-sm text-muted-foreground">+ {t("activityLog.description")}+ </p>+ </div>+ <div className="flex items-center gap-2">+ <Button+ variant="outline"+ size="sm"+ onClick={() => setClearDialogOpen(true)}+ disabled={total === 0}+ >+ <Trash2 className="h-4 w-4" />+ <span className="hidden sm:inline ml-2">+ {t("activityLog.clearAll")}+ </span>+ </Button>+ </div></div>{/* Filters Bar */}<div className="mb-6 space-y-4"><div className="flex flex-col sm:flex-row gap-4">{/* Type Filter */}- <Select- value={filters.type || "all"}- onValueChange={(value) =>- updateFilters({- type:- value === "all"- ? undefined- : (value as "auth" | "calendar" | "sync" | "security"),- })- }- >+ <Select value={typeFilter} onValueChange={handleTypeFilterChange}><SelectTrigger className="w-full sm:w-[200px]"><SelectValue placeholder={t("activityLog.allTypes")} /></SelectTrigger>@@ -253,15 +327,8 @@ export default function ActivityLogPage() {{/* Severity Filter */}<Select- value={filters.severity || "all"}- onValueChange={(value) =>- updateFilters({- severity:- value === "all"- ? undefined- : (value as "info" | "warning" | "error" | "critical"),- })- }+ value={severityFilter}+ onValueChange={handleSeverityFilterChange}><SelectTrigger className="w-full sm:w-[200px]"><SelectValue@@ -310,75 +377,34 @@ export default function ActivityLogPage() {<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /><Inputplaceholder={t("activityLog.searchPlaceholder")}- value={filters.search || ""}- onChange={(e) => updateFilters({ search: e.target.value })}+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}className="pl-9"/></div>{/* Clear Filters */}- {(filters.type ||- filters.severity ||- startDate ||- endDate ||- filters.search) && (- <Button- variant="outline"- onClick={() => {- clearFilters();- setStartDate("");- setEndDate("");- }}- >+ {hasActiveFilters && (+ <Button variant="outline" onClick={clearFilters}>{t("common.filters.clearFilters")}</Button>)}</div>- {/* Actions Row */}- <div className="flex items-center justify-between">- <div className="text-sm text-muted-foreground">- {t("activityLog.totalLogs", { count: total })}- </div>-- <div className="flex gap-2 flex-wrap">- <Button- variant="outline"- size="sm"- onClick={async () => {- await fetchLogs();- toast.success(t("activityLog.refreshed"));- }}- >- <RefreshCw className="h-4 w-4 mr-1" />- <span className="hidden sm:inline">- {t("activityLog.refresh")}- </span>- </Button>-- <Button- variant="outline"- size="sm"- onClick={() => setClearDialogOpen(true)}- disabled={total === 0}- >- <Trash2 className="h-4 w-4 mr-1" />- <span className="hidden sm:inline">- {t("activityLog.clearAll")}- </span>- </Button>- </div>+ {/* Stats */}+ <div className="text-sm text-muted-foreground">+ {t("activityLog.totalLogs", { count: total })}</div></div>{/* Table */}- {loading && logs.length === 0 ? (+ {isLoading && logs.length === 0 && !authLoading ? (<div className="text-center py-12 text-muted-foreground">{t("common.loading")}</div>) : error ? (<div className="text-center py-12 text-red-500">- {t("common.error")}: {error}+ {t("common.error")}: {error?.message || String(error)}</div>) : logs.length === 0 ? (<div className="text-center py-12 text-muted-foreground">diff --git a/components/admin/admin-header.tsx b/components/admin/admin-header.tsxindex ea83801..31b2537 100644--- a/components/admin/admin-header.tsx+++ b/components/admin/admin-header.tsx@@ -4,6 +4,7 @@ import { useTranslations } from "next-intl";import Link from "next/link";import { usePathname } from "next/navigation";import { Menu } from "lucide-react";+import { useConnectionStatus } from "@/hooks/useConnectionStatus";import {Breadcrumb,BreadcrumbItem,@@ -36,6 +37,7 @@ interface AdminHeaderProps {export function AdminHeader({ onMenuClick }: AdminHeaderProps) {const t = useTranslations();const pathname = usePathname();+ const { isOnline } = useConnectionStatus();// Generate breadcrumbs from pathnameconst generateBreadcrumbs = (): BreadcrumbSegment[] => {@@ -124,8 +126,20 @@ export function AdminHeader({ onMenuClick }: AdminHeaderProps) {</BreadcrumbList></Breadcrumb>- {/* Controls: Theme + Language */}+ {/* Controls: Connection Status + Theme + Language */}<div className="flex items-center gap-2">+ {/* Connection Status Indicator */}+ <div+ title={isOnline ? t("sync.connected") : t("sync.disconnected")}+ >+ <div+ className={`w-2.5 h-2.5 rounded-full transition-all ${+ isOnline+ ? "bg-green-500 animate-pulse shadow-[0_0_8px_rgba(34,197,94,0.6)]"+ : "bg-red-500 shadow-[0_0_8px_rgba(239,68,68,0.6)]"+ }`}+ ></div>+ </div><LanguageSwitcher /><ThemeSwitcher /></div>diff --git a/components/admin/audit-log-delete-dialog.tsx b/components/admin/audit-log-delete-dialog.tsxindex 5a34b4f..4b2f462 100644--- a/components/admin/audit-log-delete-dialog.tsx+++ b/components/admin/audit-log-delete-dialog.tsx@@ -14,7 +14,7 @@ import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Checkbox } from "@/components/ui/checkbox";import { AlertTriangle, Trash2, X } from "lucide-react";-import { useAuditLogs } from "@/hooks/useAuditLogs";+import { useAdminAuditLogs } from "@/hooks/useAdminAuditLogs";import { toast } from "sonner";interface AuditLogDeleteDialogProps {@@ -31,7 +31,7 @@ export function AuditLogDeleteDialog({onSuccess,}: AuditLogDeleteDialogProps) {const t = useTranslations();- const { deleteLogsByDate, deleteLogsByIds, isLoading } = useAuditLogs();+ const { deleteLogsByDate, deleteLogsByIds, isLoading } = useAdminAuditLogs();const [beforeDate, setBeforeDate] = useState("");const [confirmed, setConfirmed] = useState(false);diff --git a/components/admin/audit-log-details-dialog.tsx b/components/admin/audit-log-details-dialog.tsxindex 267d0a8..0476f73 100644--- a/components/admin/audit-log-details-dialog.tsx+++ b/components/admin/audit-log-details-dialog.tsx@@ -15,7 +15,7 @@ import { Badge } from "@/components/ui/badge";import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";import { Copy, X } from "lucide-react";import { toast } from "sonner";-import type { AuditLog } from "@/hooks/useAuditLogs";+import type { AuditLog } from "@/hooks/useAdminAuditLogs";interface AuditLogDetailsDialogProps {open: boolean;diff --git a/components/app-header.tsx b/components/app-header.tsxindex 2a5a376..5a61303 100644--- a/components/app-header.tsx+++ b/components/app-header.tsx@@ -25,6 +25,7 @@ import {} from "lucide-react";import { ShiftPreset } from "@/lib/db/schema";import { useVersionUpdateCheck } from "@/hooks/useVersionUpdate";+import { useConnectionStatus } from "@/hooks/useConnectionStatus";import { ChangelogDialog } from "@/components/changelog-dialog";import { useLocale } from "next-intl";@@ -33,7 +34,6 @@ interface AppHeaderProps {selectedCalendar: string | undefined;presets: ShiftPreset[];selectedPresetId: string | undefined;- isConnected: boolean;showMobileCalendarDialog: boolean;hasSyncErrors?: boolean;onSelectCalendar: (id: string) => void;@@ -42,9 +42,8 @@ interface AppHeaderProps {onSettings: () => void;onSyncNotifications: () => void;onCompare?: () => void;- onPresetsChange: () => void;+ onPresetsChange?: () => void;onShiftsChange: () => void;- onStatsRefresh: () => void;onManualShiftCreation: () => void;onMobileCalendarDialogChange: (open: boolean) => void;onViewSettingsClick: () => void;@@ -58,7 +57,6 @@ export function AppHeader({selectedCalendar,presets,selectedPresetId,- isConnected,showMobileCalendarDialog,hasSyncErrors = false,onSelectCalendar,@@ -69,7 +67,6 @@ export function AppHeader({onCompare,onPresetsChange,onShiftsChange,- onStatsRefresh,onManualShiftCreation,onMobileCalendarDialogChange,onViewSettingsClick,@@ -82,6 +79,7 @@ export function AppHeader({const { isGuest } = useAuth();const { isAuthEnabled } = useAuthFeatures();const { versionInfo } = useVersionUpdateCheck();+ const { isOnline } = useConnectionStatus();const [showChangelog, setShowChangelog] = useState(false);return (@@ -106,14 +104,10 @@ export function AppHeader({{/* Connection Status Indicator */}<divclassName={`absolute -bottom-0.5 -right-0.5 w-4 h-4 rounded-full border-2 border-background transition-colors ${- isConnected- ? "bg-green-500 animate-pulse"- : "bg-red-500"+ isOnline ? "bg-green-500 animate-pulse" : "bg-red-500"}`}title={- isConnected- ? t("sync.reconnected")- : t("sync.disconnected")+ isOnline ? t("sync.connected") : t("sync.disconnected")}></div></div>@@ -251,10 +245,10 @@ export function AppHeader({{/* Connection Status Indicator - Top Right of Card */}<divclassName={`absolute top-2 right-2 w-2 h-2 rounded-full transition-colors ${- isConnected ? "bg-green-500 animate-pulse" : "bg-red-500"+ isOnline ? "bg-green-500 animate-pulse" : "bg-red-500"}`}title={- isConnected ? t("sync.reconnected") : t("sync.disconnected")+ isOnline ? t("sync.connected") : t("sync.disconnected")}></div>@@ -319,7 +313,6 @@ export function AppHeader({onSelectPreset={onSelectPreset}onPresetsChange={onPresetsChange}onShiftsChange={onShiftsChange}- onStatsRefresh={onStatsRefresh}calendarId={selectedCalendar}onViewSettingsClick={onViewSettingsClick}loading={presetsLoading}diff --git a/components/auth-header.tsx b/components/auth-header.tsxindex f0e99c6..8f9283e 100644--- a/components/auth-header.tsx+++ b/components/auth-header.tsx@@ -8,6 +8,7 @@ import { UserMenu } from "@/components/user-menu";import { Calendar as CalendarIcon, Bell, ExternalLink } from "lucide-react";import { useVersionUpdateCheck } from "@/hooks/useVersionUpdate";import { ChangelogDialog } from "@/components/changelog-dialog";+import { useConnectionStatus } from "@/hooks/useConnectionStatus";/*** Simplified header for authentication pages@@ -22,6 +23,7 @@ export function AuthHeader({ showUserMenu = false }: AuthHeaderProps) {const t = useTranslations();const locale = useLocale();const { versionInfo } = useVersionUpdateCheck();+ const { isOnline } = useConnectionStatus();const [showChangelog, setShowChangelog] = useState(false);return (@@ -43,6 +45,15 @@ export function AuthHeader({ showUserMenu = false }: AuthHeaderProps) {<div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-slate-900 via-slate-800 to-slate-700 dark:from-slate-800 dark:via-slate-700 dark:to-slate-600 flex items-center justify-center shadow-xl shadow-slate-900/50 dark:shadow-slate-950/70 ring-2 ring-slate-700/50 dark:ring-slate-600/50 transition-transform group-hover:scale-105"><CalendarIcon className="h-6 w-6 text-white" /></div>+ {/* Connection Status Indicator */}+ <div+ className={`absolute -bottom-0.5 -right-0.5 w-4 h-4 rounded-full border-2 border-background transition-colors ${+ isOnline ? "bg-green-500 animate-pulse" : "bg-red-500"+ }`}+ title={+ isOnline ? t("sync.connected") : t("sync.disconnected")+ }+ ></div></div><div><h1 className="text-xl font-bold bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text transition-all group-hover:from-primary group-hover:via-primary group-hover:to-primary/70">diff --git a/components/calendar-compare-view.tsx b/components/calendar-compare-view.tsxindex 0e5d651..6737472 100644--- a/components/calendar-compare-view.tsx+++ b/components/calendar-compare-view.tsx@@ -36,7 +36,6 @@ interface CalendarCompareViewProps {combinedSortMode: boolean;highlightedWeekdays?: number[];highlightColor?: string;- statsRefreshTrigger: number;locale?: Locale;onDayClick: (calendarId: string, date: Date) => void;onDayRightClick?: (@@ -67,7 +66,6 @@ interface CalendarCompareViewProps {onHidePresetHeaderChange?: (hide: boolean) => void;onPresetsChange: (calendarId: string) => void;onShiftsChange?: () => void;- onStatsRefresh?: () => void;presetsLoadingMap?: Map<string, boolean>;}@@ -241,7 +239,6 @@ export function CalendarCompareView(props: CalendarCompareViewProps) {onSelectPreset={props.onSelectPreset}onPresetsChange={() => props.onPresetsChange(calendar.id)}onShiftsChange={props.onShiftsChange}- onStatsRefresh={props.onStatsRefresh}calendarId={calendar.id}onViewSettingsClick={props.onViewSettingsClick}loading={presetsLoading}@@ -283,7 +280,6 @@ export function CalendarCompareView(props: CalendarCompareViewProps) {highlightedWeekdays={props.highlightedWeekdays}highlightColor={props.highlightColor}selectedCalendar={calendar.id}- statsRefreshTrigger={props.statsRefreshTrigger}locale={props.locale}onDayClick={isDisableddiff --git a/components/calendar-content.tsx b/components/calendar-content.tsxindex 89872ea..9348678 100644--- a/components/calendar-content.tsx+++ b/components/calendar-content.tsx@@ -30,7 +30,6 @@ interface CalendarContentProps {highlightedWeekdays?: number[];highlightColor?: string;selectedCalendar: string | null;- statsRefreshTrigger: number;locale?: Locale;onDayClick: (date: Date) => void;onDayRightClick?: (e: React.MouseEvent, date: Date) => void;@@ -123,7 +122,6 @@ export function CalendarContent(props: CalendarContentProps) {<ShiftStatscalendarId={props.selectedCalendar || undefined}currentDate={props.currentDate}- refreshTrigger={props.statsRefreshTrigger}/><ShiftsListdiff --git a/components/calendar-settings-sheet.tsx b/components/calendar-settings-sheet.tsxindex 81d7867..c038d94 100644--- a/components/calendar-settings-sheet.tsx+++ b/components/calendar-settings-sheet.tsx@@ -116,14 +116,11 @@ export function CalendarSettingsSheet({color: selectedColor !== calendarColor ? selectedColor : undefined,};- const result = await updateCalendar(calendarId, updates);+ await updateCalendar(calendarId, updates);setLoading(false);-- if (result.success) {- onSuccess();- onOpenChange(false);- }+ onSuccess();+ onOpenChange(false);};const handleDelete = () => {diff --git a/components/calendar-share-list.tsx b/components/calendar-share-list.tsxindex b6c6a9f..79299ac 100644--- a/components/calendar-share-list.tsx+++ b/components/calendar-share-list.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useState } from "react";+import { useState } from "react";import { useTranslations } from "next-intl";import { format } from "date-fns";import { UserPlus, MoreVertical, Trash2, Shield } from "lucide-react";@@ -51,18 +51,13 @@ export function CalendarShareList({const locale = useLocale();const { user: currentUser } = useAuth();const { isOwner } = useCalendarPermission(calendarId);- const { shares, fetchShares, updateShare, removeShare } =- useCalendarShares(calendarId);+ const { shares, updateShare, removeShare } = useCalendarShares(calendarId);const [showAddUser, setShowAddUser] = useState(false);const [shareToDelete, setShareToDelete] = useState<CalendarShare | null>(null);- useEffect(() => {- fetchShares();- }, [fetchShares]);-const getUserInitials = (share: CalendarShare) => {if (share.user.name) {return share.user.name@@ -285,7 +280,6 @@ export function CalendarShareList({open={showAddUser}onOpenChange={setShowAddUser}calendarId={calendarId}- onSuccess={fetchShares}/>{/* Remove Confirmation */}diff --git a/components/calendar-share-management-sheet.tsx b/components/calendar-share-management-sheet.tsxindex 90da5f6..f16294e 100644--- a/components/calendar-share-management-sheet.tsx+++ b/components/calendar-share-management-sheet.tsx@@ -41,11 +41,15 @@ export function CalendarShareManagementSheet({const { isAuthEnabled } = useAuthFeatures();const [activeTab, setActiveTab] = useState("users");- const [guestPermission, setGuestPermission] = useState<- "none" | "read" | "write"- >(calendarGuestPermission);+ const [optimisticGuestPermission, setOptimisticGuestPermission] = useState<+ "none" | "read" | "write" | null+ >(null);const [saving, setSaving] = useState(false);+ // Use optimistic value during save, otherwise use prop value+ // This avoids calling setState in an effect and potential cascading renders+ const guestPermission = optimisticGuestPermission ?? calendarGuestPermission;+// Show public access tab when auth is enabled (allows sharing with authenticated users via guestPermission)// This is separate from allowGuest which controls unauthenticated accessconst showGuestTab = isAuthEnabled;@@ -55,7 +59,7 @@ export function CalendarShareManagementSheet({) => {if (!canManageShares) return;- setGuestPermission(value);+ setOptimisticGuestPermission(value);setSaving(true);await updateCalendar(calendarId, {@@ -63,6 +67,7 @@ export function CalendarShareManagementSheet({});setSaving(false);+ setOptimisticGuestPermission(null);};return (diff --git a/components/calendar-share-user-search.tsx b/components/calendar-share-user-search.tsxindex 610e711..71608dc 100644--- a/components/calendar-share-user-search.tsx+++ b/components/calendar-share-user-search.tsx@@ -29,7 +29,7 @@ interface CalendarShareUserSearchProps {open: boolean;onOpenChange: (open: boolean) => void;calendarId: string;- onSuccess: () => void;+ onSuccess?: () => void;}export function CalendarShareUserSearch({@@ -79,7 +79,7 @@ export function CalendarShareUserSearch({setQuery("");setSelectedUser(null);setPermission("read");- onSuccess();+ onSuccess?.();onOpenChange(false);}};diff --git a/components/calendar-token-list.tsx b/components/calendar-token-list.tsxindex 0b6dad3..98e6b90 100644--- a/components/calendar-token-list.tsx+++ b/components/calendar-token-list.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useState } from "react";+import { useState } from "react";import { useTranslations } from "next-intl";import {useCalendarTokens,@@ -55,19 +55,16 @@ export function CalendarTokenList({ calendarId }: CalendarTokenListProps) {const locale = useLocale();const dateLocale = getDateLocale(locale);- const { tokens, fetchTokens, deleteToken, updateToken } =- useCalendarTokens(calendarId);+ const { tokens, updateToken, deleteToken } = useCalendarTokens(calendarId);const [createDialogOpen, setCreateDialogOpen] = useState(false);const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);const [tokenToDelete, setTokenToDelete] =useState<CalendarAccessToken | null>(null);- useEffect(() => {- if (calendarId) {- void fetchTokens();- }- }, [calendarId, fetchTokens]);+ const handleToggleActive = async (token: CalendarAccessToken) => {+ await updateToken(token.id, { isActive: !token.isActive });+ };const handleDelete = async () => {if (!tokenToDelete) return;@@ -79,12 +76,6 @@ export function CalendarTokenList({ calendarId }: CalendarTokenListProps) {}};- const handleToggleActive = async (token: CalendarAccessToken) => {- await updateToken(token.id, {- isActive: !token.isActive,- });- };-return (<div className="space-y-4">{/* Header */}@@ -273,7 +264,6 @@ export function CalendarTokenList({ calendarId }: CalendarTokenListProps) {open={createDialogOpen}onOpenChange={setCreateDialogOpen}calendarId={calendarId}- onSuccess={fetchTokens}/>{/* Delete Confirmation */}diff --git a/components/dialog-manager.tsx b/components/dialog-manager.tsxindex 979595d..04b161d 100644--- a/components/dialog-manager.tsx+++ b/components/dialog-manager.tsx@@ -22,7 +22,7 @@ interface DialogManagerProps {onShiftSubmit: (data: ShiftFormData) => void;selectedDate?: Date;selectedCalendar: string | null;- onPresetsChange: () => void;+ onPresetsChange?: () => void;calendars: CalendarWithCount[];// Calendar Settings Dialog@@ -35,14 +35,11 @@ interface DialogManagerProps {// External Sync SheetshowExternalSyncDialog: boolean;onExternalSyncDialogChange: (open: boolean) => void;- syncErrorRefreshTrigger: number;onSyncComplete: () => void;// Sync Notification DialogshowSyncNotificationDialog: boolean;onSyncNotificationDialogChange: (open: boolean) => void;- onErrorsMarkedRead: () => void;- onSyncLogUpdate: () => void;// Shifts Overview Dialog (for day shifts and synced shifts)showDayShiftsDialog: boolean;@@ -157,7 +154,6 @@ export function DialogManager(props: DialogManagerProps) {open={props.showExternalSyncDialog}onOpenChange={props.onExternalSyncDialogChange}calendarId={props.selectedCalendar}- syncErrorRefreshTrigger={props.syncErrorRefreshTrigger}onSyncComplete={props.onSyncComplete}/>@@ -165,9 +161,6 @@ export function DialogManager(props: DialogManagerProps) {open={props.showSyncNotificationDialog}onOpenChange={props.onSyncNotificationDialogChange}calendarId={props.selectedCalendar}- onErrorsMarkedRead={props.onErrorsMarkedRead}- onSyncLogUpdate={props.onSyncLogUpdate}- syncLogRefreshTrigger={props.syncErrorRefreshTrigger}/></>)}diff --git a/components/external-sync-manage-sheet.tsx b/components/external-sync-manage-sheet.tsxindex 0e75150..386b9f8 100644--- a/components/external-sync-manage-sheet.tsx+++ b/components/external-sync-manage-sheet.tsx@@ -1,6 +1,7 @@"use client";-import { useState, useEffect, useCallback, useRef } from "react";+import { useState, useEffect, useCallback, useRef, useMemo } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";import {Sheet,SheetContent,@@ -24,6 +25,7 @@ import {import { ColorPicker } from "@/components/ui/color-picker";import { Slider } from "@/components/ui/slider";import { useTranslations } from "next-intl";+import { REFETCH_INTERVAL } from "@/lib/query-client";import {Trash2,RefreshCw,@@ -45,6 +47,7 @@ import {} from "@/lib/external-calendar-utils";import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";import { useDirtyState } from "@/hooks/useDirtyState";+import { queryKeys } from "@/lib/query-keys";interface ExternalSyncManageSheetProps {open: boolean;@@ -59,18 +62,16 @@ export function ExternalSyncManageSheet({onOpenChange,calendarId,onSyncComplete,- syncErrorRefreshTrigger,-}: ExternalSyncManageSheetProps) {+}: // syncErrorRefreshTrigger is no longer needed - React Query polls automatically+ExternalSyncManageSheetProps) {const t = useTranslations();- const [syncs, setSyncs] = useState<ExternalSync[]>([]);- const [syncErrors, setSyncErrors] = useState<Record<string, string>>({});- const [isLoading, setIsLoading] = useState(false);const [isSyncing, setIsSyncing] = useState<string | null>(null);const [isDeleting, setIsDeleting] = useState<string | null>(null);const [showAddForm, setShowAddForm] = useState(false);const [editingSync, setEditingSync] = useState<ExternalSync | null>(null);const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);+ const [isSubmitting, setIsSubmitting] = useState(false); // For form submission loading// Form stateconst [formName, setFormName] = useState("");@@ -94,81 +95,76 @@ export function ExternalSyncManageSheet({autoSyncInterval: number;} | null>(null);const [isSavingEdit, setIsSavingEdit] = useState(false);+ const queryClient = useQueryClient();++ // Fetch external syncs with React Query for live updates+ const { data: syncsData = [] } = useQuery({+ queryKey: queryKeys.externalSyncs.byCalendar(calendarId!),+ queryFn: async () => {+ const params = new URLSearchParams({ calendarId: calendarId! });+ const response = await fetch(`/api/external-syncs?${params}`);+ if (!response.ok) throw new Error("Failed to fetch syncs");+ return (await response.json()) as ExternalSync[];+ },+ enabled: !!calendarId && open,+ refetchInterval: REFETCH_INTERVAL,+ refetchIntervalInBackground: true,+ });- const fetchSyncs = useCallback(- async (showLoadingState = true) => {- if (!calendarId) return;-- if (showLoadingState) {- setIsLoading(true);- }- try {- const params = new URLSearchParams({ calendarId });-- const response = await fetch(`/api/external-syncs?${params}`);- if (response.ok) {- const data = await response.json();- setSyncs(data);-- // Fetch last sync logs to check for errors- const logsParams = new URLSearchParams({ calendarId, limit: "50" });-- const logsResponse = await fetch(`/api/sync-logs?${logsParams}`);- if (logsResponse.ok) {- const logs = await logsResponse.json();- const errors: Record<string, string> = {};-- // Get the latest error for each external sync- data.forEach((sync: ExternalSync) => {- const syncLogs = logs.filter(- (log: SyncLog) => log.externalSyncId === sync.id- );- // Only show unread errors- const latestError = syncLogs.find(- (log: SyncLog) => log.status === "error" && !log.isRead- );- if (latestError) {- errors[sync.id] =- latestError.errorMessage ||- t("syncNotifications.statusError");- }- });-- setSyncErrors(errors);- }- }- } catch (error) {- console.error("Failed to fetch syncs:", error);- } finally {- if (showLoadingState) {- setIsLoading(false);- }- }+ // Fetch sync logs with React Query for live updates+ const { data: syncLogsData = [] } = useQuery({+ queryKey: queryKeys.externalSyncs.logs(calendarId!),+ queryFn: async () => {+ const params = new URLSearchParams({+ calendarId: calendarId!,+ limit: "50",+ });+ const response = await fetch(`/api/sync-logs?${params}`);+ if (!response.ok) throw new Error("Failed to fetch sync logs");+ return (await response.json()) as SyncLog[];},- [calendarId, t]- );+ enabled: !!calendarId && open,+ refetchInterval: REFETCH_INTERVAL,+ refetchIntervalInBackground: true,+ });- // Silent refresh for sync error updates (triggered by SSE)- useEffect(() => {- if (- open &&- calendarId &&- syncErrorRefreshTrigger &&- syncErrorRefreshTrigger > 0- ) {- // Silently refresh sync errors without loading state- fetchSyncs(false);+ // Compute sync errors from logs+ const syncErrors = useMemo(() => {+ const errors: Record<string, string> = {};+ syncsData.forEach((sync: ExternalSync) => {+ const syncLogs = syncLogsData.filter(+ (log: SyncLog) => log.externalSyncId === sync.id+ );+ const latestError = syncLogs.find(+ (log: SyncLog) => log.status === "error" && !log.isRead+ );+ if (latestError) {+ errors[sync.id] =+ latestError.errorMessage || t("syncNotifications.statusError");+ }+ });+ return errors;+ }, [syncsData, syncLogsData, t]);++ // Use syncsData from React Query+ const syncs = syncsData;++ // Invalidate queries function to refetch data+ const invalidateSyncs = useCallback(() => {+ if (calendarId) {+ queryClient.invalidateQueries({+ queryKey: queryKeys.externalSyncs.byCalendar(calendarId),+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.externalSyncs.logs(calendarId),+ });}- }, [syncErrorRefreshTrigger, open, calendarId, fetchSyncs]);+ }, [calendarId, queryClient]);- // Load syncs when dialog opens, reset state when it closes+ // Reset form state when dialog closesuseEffect(() => {- if (open && calendarId) {- fetchSyncs();- } else {- // Reset all internal state when dialog closes or calendarId becomes falsy- setSyncs([]);- setIsLoading(false);+ if (!open) {+ // Reset all internal state when dialog closessetIsSyncing(null);setIsDeleting(null);setShowAddForm(false);@@ -182,8 +178,9 @@ export function ExternalSyncManageSheet({setImportType("url");setFormIsHidden(false);setFormHideFromStats(false);+ setIsSubmitting(false);}- }, [open, calendarId, fetchSyncs]);+ }, [open]);const handleAddSync = async () => {if (!calendarId || !formName.trim()) return;@@ -222,7 +219,7 @@ export function ExternalSyncManageSheet({}}- setIsLoading(true);+ setIsSubmitting(true);try {let icsContent: string | undefined;@@ -232,7 +229,7 @@ export function ExternalSyncManageSheet({const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MBif (icsFile.size > MAX_FILE_SIZE) {toast.error(t("validation.fileTooLarge", { maxSize: "5MB" }));- setIsLoading(false);+ setIsSubmitting(false);return;}icsContent = await icsFile.text();@@ -266,7 +263,7 @@ export function ExternalSyncManageSheet({setFormIsHidden(false);setFormHideFromStats(false);setShowAddForm(false);- await fetchSyncs();+ invalidateSyncs();onSyncComplete?.(); // Trigger refresh to update parent statetoast.success(t("common.created", { item: t("externalSync.syncTypeCustom") })@@ -286,7 +283,7 @@ export function ExternalSyncManageSheet({t("common.createError", { item: t("externalSync.syncTypeCustom") }));} finally {- setIsLoading(false);+ setIsSubmitting(false);}};@@ -310,7 +307,7 @@ export function ExternalSyncManageSheet({throw new Error(data.error || "Failed to sync calendar");}- await fetchSyncs();+ invalidateSyncs();onSyncComplete?.();// Show sync statistics@@ -347,7 +344,7 @@ export function ExternalSyncManageSheet({});if (response.ok) {- await fetchSyncs();+ invalidateSyncs();onSyncComplete?.();toast.success(t("common.deleted", { item: t("externalSync.syncTypeCustom") })@@ -425,7 +422,7 @@ export function ExternalSyncManageSheet({});if (response.ok) {- await fetchSyncs();+ invalidateSyncs();onSyncComplete?.(); // Trigger refreshtoast.success(t("common.updated", { item: t("externalSync.syncTypeCustom") })@@ -538,7 +535,7 @@ export function ExternalSyncManageSheet({});if (response.ok) {- await fetchSyncs();+ invalidateSyncs();onSyncComplete?.();// Update initial data ref after successful saveinitialFormDataRef.current = {@@ -578,7 +575,7 @@ export function ExternalSyncManageSheet({formColor,formDisplayMode,formAutoSyncInterval,- fetchSyncs,+ invalidateSyncs,onSyncComplete,t,]);@@ -783,7 +780,7 @@ export function ExternalSyncManageSheet({})}value={formName}onChange={(e) => setFormName(e.target.value)}- disabled={isLoading}+ disabled={isSubmitting}/></div>@@ -836,7 +833,7 @@ export function ExternalSyncManageSheet({const file = e.target.files?.[0];setIcsFile(file || null);}}- disabled={isLoading}+ disabled={isSubmitting}className="cursor-pointer"value=""/>@@ -857,7 +854,7 @@ export function ExternalSyncManageSheet({placeholder={getUrlPlaceholder()}value={formUrl || ""}onChange={(e) => setFormUrl(e.target.value)}- disabled={isLoading}+ disabled={isSubmitting}readOnly={!!editingSync}className={editingSync@@ -1187,7 +1184,7 @@ export function ExternalSyncManageSheet({setFormIsHidden(false);setFormHideFromStats(false);}}- disabled={isLoading}+ disabled={isSubmitting}className="flex-1 h-11 border-border/50 hover:bg-muted/50">{t("common.cancel")}@@ -1196,13 +1193,13 @@ export function ExternalSyncManageSheet({type="button"onClick={handleAddSync}disabled={- isLoading ||+ isSubmitting ||!formName.trim() ||(importType === "file" ? !icsFile : !formUrl.trim())}className="flex-1 h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25 disabled:opacity-50 disabled:shadow-none">- {isLoading ? (+ {isSubmitting ? (<><Loader2 className="mr-2 h-4 w-4 animate-spin" />{t("common.saving")}diff --git a/components/preset-manage-sheet.tsx b/components/preset-manage-sheet.tsxindex 45dc0cd..9411285 100644--- a/components/preset-manage-sheet.tsx+++ b/components/preset-manage-sheet.tsx@@ -39,7 +39,7 @@ import { Plus, Trash2, Edit2, Loader2, GripVertical } from "lucide-react";import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";import { ReadOnlyBanner } from "@/components/read-only-banner";import { useDirtyState } from "@/hooks/useDirtyState";-import { usePresetManagement } from "@/hooks/usePresetManagement";+import { usePresets } from "@/hooks/usePresets";import { useCalendarPermission } from "@/hooks/useCalendarPermission";interface PresetFormData {@@ -58,7 +58,7 @@ interface PresetManageSheetProps {onOpenChange: (open: boolean) => void;calendarId: string;presets: ShiftPreset[];- onPresetsChange: () => void;+ onPresetsChange?: () => void; // Now optional - React Query handles refetchingreadOnly?: boolean;}@@ -183,7 +183,6 @@ export function PresetManageSheet({onOpenChange,calendarId,presets,- onPresetsChange,readOnly = false,}: PresetManageSheetProps) {const t = useTranslations();@@ -217,11 +216,13 @@ export function PresetManageSheet({>([]);const initialFormDataRef = useRef<PresetFormData | null>(null);- const { createPreset, updatePreset, deletePreset, reorderPresets } =- usePresetManagement({- calendarId,- onSuccess: onPresetsChange,- });+ // Use the unified usePresets hook with mutations+ const {+ createPreset: createPresetMutation,+ updatePreset: updatePresetMutation,+ deletePreset: deletePresetMutation,+ reorderPresets: reorderPresetsMutation,+ } = usePresets(calendarId);// Initialize ordered presetsuseEffect(() => {@@ -288,7 +289,7 @@ export function PresetManageSheet({order: index,}));- const success = await reorderPresets(presetOrders);+ const success = await reorderPresetsMutation(presetOrders);if (!success) {// Revert order on errorsetOrderedPrimaryPresets(presets.filter((p) => !p.isSecondary));@@ -324,9 +325,9 @@ export function PresetManageSheet({let success = false;if (editingPreset) {- success = await updatePreset(editingPreset.id, formData);+ success = await updatePresetMutation(editingPreset.id, formData);} else {- success = await createPreset(formData);+ success = await createPresetMutation(formData);}if (success) {@@ -360,7 +361,7 @@ export function PresetManageSheet({setShowDeleteConfirm(false);try {- const success = await deletePreset(deleteTargetId);+ const success = await deletePresetMutation(deleteTargetId);if (success) {// If we're editing the deleted preset, close the edit formif (editingPreset?.id === deleteTargetId) {diff --git a/components/preset-selector.tsx b/components/preset-selector.tsxindex 0a5f4a7..3b66030 100644--- a/components/preset-selector.tsx+++ b/components/preset-selector.tsx@@ -11,9 +11,8 @@ interface PresetSelectorProps {presets: ShiftPreset[];selectedPresetId?: string;onSelectPreset: (presetId: string | undefined) => void;- onPresetsChange: () => void;+ onPresetsChange?: () => void;onShiftsChange?: () => void;- onStatsRefresh?: () => void;calendarId: string;onViewSettingsClick?: () => void;loading?: boolean;@@ -29,7 +28,6 @@ export function PresetSelector({onSelectPreset,onPresetsChange,onShiftsChange,- onStatsRefresh,calendarId,onViewSettingsClick,hidePresetHeader = false,@@ -43,9 +41,8 @@ export function PresetSelector({};const handlePresetsChange = () => {- onPresetsChange();+ if (onPresetsChange) onPresetsChange();if (onShiftsChange) onShiftsChange();- if (onStatsRefresh) onStatsRefresh();};return (diff --git a/components/query-provider.tsx b/components/query-provider.tsxnew file mode 100644index 0000000..cc58f9b--- /dev/null+++ b/components/query-provider.tsx@@ -0,0 +1,13 @@+"use client";++import { QueryClientProvider } from "@tanstack/react-query";+import { useState } from "react";+import { createQueryClient } from "@/lib/query-client";++export function QueryProvider({ children }: { children: React.ReactNode }) {+ const [queryClient] = useState(() => createQueryClient());++ return (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+}diff --git a/components/shift-stats.tsx b/components/shift-stats.tsxindex 585d568..238dabc 100644--- a/components/shift-stats.tsx+++ b/components/shift-stats.tsx@@ -91,7 +91,6 @@ const CustomTooltip = ({interface ShiftStatsProps {calendarId: string | undefined;currentDate: Date;- refreshTrigger?: number;}type ViewMode = "overview" | "pie" | "bar" | "radar";@@ -111,11 +110,7 @@ const CHART_COLORS = ["#22c55e", // lime];-export function ShiftStats({- calendarId,- currentDate,- refreshTrigger,-}: ShiftStatsProps) {+export function ShiftStats({ calendarId, currentDate }: ShiftStatsProps) {const t = useTranslations();const [period, setPeriod] = useState<"week" | "month" | "year">("month");const [viewMode, setViewMode] = useState<ViewMode>("overview");@@ -126,7 +121,6 @@ export function ShiftStats({calendarId,currentDate,period,- refreshTrigger,});if (!calendarId) return null;diff --git a/components/sync-notification-dialog.tsx b/components/sync-notification-dialog.tsxindex b64ca96..6a5838f 100644--- a/components/sync-notification-dialog.tsx+++ b/components/sync-notification-dialog.tsx@@ -1,7 +1,8 @@"use client";-import { useCallback, useEffect, useState } from "react";+import { useState } from "react";import { useLocale, useTranslations } from "next-intl";+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import {Dialog,DialogContent,@@ -10,6 +11,7 @@ import {} from "@/components/ui/dialog";import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";import { Button } from "@/components/ui/button";+import { REFETCH_INTERVAL } from "@/lib/query-client";import {Select,SelectContent,@@ -18,6 +20,7 @@ import {SelectValue,} from "@/components/ui/select";import { SyncLog } from "@/lib/db/schema";+import { queryKeys } from "@/lib/query-keys";import {CheckCircle2,XCircle,@@ -29,13 +32,25 @@ import {} from "lucide-react";import { toast } from "sonner";+/**+ * Fetch sync logs from API+ */+async function fetchSyncLogsApi(calendarId: string): Promise<SyncLog[]> {+ const params = new URLSearchParams({ calendarId, limit: "20" });+ const response = await fetch(`/api/sync-logs?${params}`);++ if (!response.ok) {+ throw new Error("Failed to fetch sync logs");+ }++ return await response.json();+}+interface SyncNotificationDialogProps {open: boolean;onOpenChange: (open: boolean) => void;calendarId: string | null;onErrorsMarkedRead?: () => void;- onSyncLogUpdate?: () => void;- syncLogRefreshTrigger?: number;}export function SyncNotificationDialog({@@ -43,60 +58,77 @@ export function SyncNotificationDialog({onOpenChange,calendarId,onErrorsMarkedRead,- syncLogRefreshTrigger,}: SyncNotificationDialogProps) {const t = useTranslations();const locale = useLocale();- const [logs, setLogs] = useState<SyncLog[]>([]);- const [loading, setLoading] = useState(false);+ const queryClient = useQueryClient();const [filter, setFilter] = useState<"all" | "success" | "error">("all");- const [isDeleting, setIsDeleting] = useState(false);- const [isMarkingRead, setIsMarkingRead] = useState(false);const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);- const fetchLogs = useCallback(- async (showLoadingState = true) => {- if (!calendarId) return;+ // Fetch sync logs with React Query polling+ const { data: logs = [], isLoading: loading } = useQuery({+ queryKey: queryKeys.externalSyncs.logs(calendarId!),+ queryFn: () => fetchSyncLogsApi(calendarId!),+ enabled: !!calendarId && open,+ refetchInterval: REFETCH_INTERVAL,+ refetchIntervalInBackground: false, // Only poll when dialog is open+ });- if (showLoadingState) {- setLoading(true);+ // Delete all logs mutation+ const deleteMutation = useMutation({+ mutationFn: async () => {+ const response = await fetch(`/api/sync-logs?calendarId=${calendarId}`, {+ method: "DELETE",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({}),+ });+ if (!response.ok) {+ throw new Error("Failed to delete sync logs");}- try {- const params = new URLSearchParams({ calendarId, limit: "20" });+ },+ onSuccess: () => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.externalSyncs.logs(calendarId!),+ });+ toast.success(+ t("common.deleted", { item: t("syncNotifications.title") })+ );+ },+ onError: () => {+ toast.error(+ t("common.deleteError", { item: t("syncNotifications.title") })+ );+ },+ });- const response = await fetch(`/api/sync-logs?${params}`);- if (response.ok) {- const data = await response.json();- setLogs(data);- }- } catch (error) {- console.error("Failed to fetch sync logs:", error);- } finally {- if (showLoadingState) {- setLoading(false);+ // Mark errors as read mutation+ const markReadMutation = useMutation({+ mutationFn: async () => {+ const response = await fetch(+ `/api/sync-logs?calendarId=${calendarId}&action=markErrorsAsRead`,+ {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({}),}+ );+ if (!response.ok) {+ throw new Error("Failed to mark errors as read");}},- [calendarId]- );-- useEffect(() => {- if (open && calendarId) {- fetchLogs();- }- }, [open, calendarId, fetchLogs]);-- // Silent refresh when SSE triggers update (syncLogRefreshTrigger changes)- useEffect(() => {- if (- open &&- calendarId &&- syncLogRefreshTrigger &&- syncLogRefreshTrigger > 0- ) {- fetchLogs(false);- }- }, [open, calendarId, syncLogRefreshTrigger, fetchLogs]);+ onSuccess: () => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.externalSyncs.logs(calendarId!),+ });+ toast.success(t("syncNotifications.markedAsRead"));+ onErrorsMarkedRead?.();+ },+ onError: () => {+ toast.error(+ t("common.updateError", { item: t("syncNotifications.title") })+ );+ },+ });const formatDateTime = (date: Date) => {return new Intl.DateTimeFormat(locale, {@@ -128,71 +160,13 @@ export function SyncNotificationDialog({);};- const handleDeleteLogs = async () => {- if (!calendarId) return;-- setIsDeleting(true);+ const handleDeleteLogs = () => {setShowDeleteConfirm(false);-- try {- const response = await fetch(`/api/sync-logs?calendarId=${calendarId}`, {- method: "DELETE",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({}),- });-- if (response.ok) {- setLogs([]);- toast.success(- t("common.deleted", { item: t("syncNotifications.title") })- );- } else {- toast.error(- t("common.deleteError", { item: t("syncNotifications.title") })- );- }- } catch (error) {- console.error("Failed to delete sync logs:", error);- toast.error(- t("common.deleteError", { item: t("syncNotifications.title") })- );- } finally {- setIsDeleting(false);- }+ deleteMutation.mutate();};- const handleMarkErrorsAsRead = async () => {- if (!calendarId) return;-- setIsMarkingRead(true);- try {- const response = await fetch(- `/api/sync-logs?calendarId=${calendarId}&action=markErrorsAsRead`,- {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({}),- }- );-- if (response.ok) {- await fetchLogs();- toast.success(t("syncNotifications.markedAsRead"));- // Notify parent to refresh error status- onErrorsMarkedRead?.();- } else {- toast.error(- t("common.updateError", { item: t("syncNotifications.title") })- );- }- } catch (error) {- console.error("Failed to mark errors as read:", error);- toast.error(- t("common.updateError", { item: t("syncNotifications.title") })- );- } finally {- setIsMarkingRead(false);- }+ const handleMarkErrorsAsRead = () => {+ markReadMutation.mutate();};const filteredLogs = logs.filter((log) => {@@ -237,7 +211,7 @@ export function SyncNotificationDialog({variant="outline"size="sm"onClick={handleMarkErrorsAsRead}- disabled={isMarkingRead}+ disabled={markReadMutation.isPending}><CheckCheck className="h-4 w-4 mr-2" />{t("syncNotifications.markAsRead")}@@ -247,7 +221,7 @@ export function SyncNotificationDialog({variant="outline"size="sm"onClick={() => setShowDeleteConfirm(true)}- disabled={isDeleting || logs.length === 0}+ disabled={deleteMutation.isPending || logs.length === 0}><Trash2 className="h-4 w-4 mr-2" />{t("syncNotifications.deleteAll")}diff --git a/eslint.config.mjs b/eslint.config.mjsindex 05e726d..1c01a22 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -1,10 +1,12 @@import { defineConfig, globalIgnores } from "eslint/config";import nextVitals from "eslint-config-next/core-web-vitals";import nextTs from "eslint-config-next/typescript";+import pluginQuery from "@tanstack/eslint-plugin-query";const eslintConfig = defineConfig([...nextVitals,...nextTs,+ ...pluginQuery.configs["flat/recommended"],// Override default ignores of eslint-config-next.globalIgnores([// Default ignores of eslint-config-next:diff --git a/hooks/useActivityLogs.ts b/hooks/useActivityLogs.tsindex a361b78..9a40095 100644--- a/hooks/useActivityLogs.ts+++ b/hooks/useActivityLogs.ts@@ -1,215 +1,178 @@"use client";-import { useState, useEffect, useCallback } from "react";+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { toast } from "sonner";+import { useTranslations } from "next-intl";+import { queryKeys } from "@/lib/query-keys";+import { REFETCH_INTERVAL } from "@/lib/query-client";-// Unified activity log format (matches API response)+/**+ * Activity Log Types+ */export interface UnifiedActivityLog {id: string;type: "sync" | "auth" | "calendar" | "security";action: string;timestamp: Date;- severity: string;+ severity: "info" | "warning" | "error" | "critical";metadata: object | null;resourceType?: string;resourceId?: string;}-interface ActivityLogsFilters {+export interface ActivityLogsFilters {type?: "sync" | "auth" | "calendar" | "security";- startDate?: Date;- endDate?: Date;+ startDate?: string;+ endDate?: string;severity?: "info" | "warning" | "error" | "critical";search?: string;}-interface ActivityLogsResponse {+export interface ActivityLogsPagination {+ limit: number;+ offset: number;+}++export interface ActivityLogsResponse {logs: UnifiedActivityLog[];total: number;- page: number;limit: number;- hasMore: boolean;+ offset: number;}-export function useActivityLogs() {- const [logs, setLogs] = useState<UnifiedActivityLog[]>([]);- const [filteredLogs, setFilteredLogs] = useState<UnifiedActivityLog[]>([]);- const [total, setTotal] = useState(0);- const [page, setPage] = useState(0);- const [limit] = useState(50); // Fixed page size- const [hasMore, setHasMore] = useState(false);- const [loading, setLoading] = useState(false);- const [error, setError] = useState<string | null>(null);-- // Filters- const [filters, setFilters] = useState<ActivityLogsFilters>({});-- // Fetch logs from API- const fetchLogs = useCallback(- async (pageNum = 0) => {- setLoading(true);- setError(null);-- try {- const params = new URLSearchParams();- if (filters.type) params.set("type", filters.type);- if (filters.startDate)- params.set("startDate", filters.startDate.toISOString());- if (filters.endDate)- params.set("endDate", filters.endDate.toISOString());- params.set("page", pageNum.toString());- params.set("limit", limit.toString());-- const response = await fetch(`/api/activity-logs?${params}`);-- if (!response.ok) {- throw new Error("Failed to fetch activity logs");- }-- const data: ActivityLogsResponse = await response.json();-- // Parse timestamps- const parsedLogs = data.logs.map((log) => ({- ...log,- timestamp: new Date(log.timestamp),- }));-- // Apply client-side filters (severity, search)- let filtered = parsedLogs;-- if (filters.severity) {- filtered = filtered.filter(- (log) => log.severity === filters.severity- );- }-- if (filters.search && filters.search.trim()) {- const searchLower = filters.search.toLowerCase();- filtered = filtered.filter(- (log) =>- log.action.toLowerCase().includes(searchLower) ||- (log.resourceType &&- log.resourceType.toLowerCase().includes(searchLower)) ||- (log.resourceId &&- log.resourceId.toLowerCase().includes(searchLower))- );- }-- setLogs(parsedLogs);- setFilteredLogs(filtered);- setTotal(data.total);- setPage(pageNum);- setHasMore(data.hasMore);- } catch (err) {- console.error("Error fetching activity logs:", err);- setError(- err instanceof Error ? err.message : "Failed to fetch activity logs"- );- } finally {- setLoading(false);- }+/**+ * Fetch activity logs from API+ */+async function fetchActivityLogsApi(+ filters: ActivityLogsFilters,+ pagination: ActivityLogsPagination,+ t: ReturnType<typeof useTranslations>+): Promise<ActivityLogsResponse> {+ const params = new URLSearchParams();++ if (filters.type) params.set("type", filters.type);+ if (filters.startDate) params.set("startDate", filters.startDate);+ if (filters.endDate) params.set("endDate", filters.endDate);+ if (filters.severity) params.set("severity", filters.severity);+ if (filters.search) params.set("search", filters.search);++ params.set("limit", pagination.limit.toString());+ params.set("offset", pagination.offset.toString());++ const response = await fetch(`/api/activity-logs?${params.toString()}`, {+ method: "GET",+ headers: {+ "Content-Type": "application/json",},- [filters, limit]- );-- // Clear all logs- const clearLogs = useCallback(async () => {- try {- const response = await fetch("/api/activity-logs", {- method: "DELETE",- });-- if (!response.ok) {- throw new Error("Failed to clear activity logs");- }+ });- toast.success("Activity logs cleared");- await fetchLogs(0); // Refresh logs- } catch (err) {- console.error("Error clearing logs:", err);+ if (!response.ok) {+ throw new Error(t("common.fetchError", { item: t("activityLog.title") }));+ }++ const data = await response.json();++ // Parse date strings to Date objects+ const logs = data.logs.map((log: Record<string, unknown>) => ({+ ...log,+ timestamp: new Date(log.timestamp as string),+ }));++ return {+ logs,+ total: data.total,+ limit: data.limit,+ offset: data.offset,+ };+}++/**+ * Clear all activity logs via API+ */+async function clearLogsApi(+ t: ReturnType<typeof useTranslations>+): Promise<void> {+ const response = await fetch("/api/activity-logs", {+ method: "DELETE",+ });++ if (!response.ok) {+ throw new Error(t("common.deleteError", { item: t("activityLog.title") }));+ }+}++/**+ * Activity Logs Hook+ *+ * Provides user activity logs with automatic polling.+ * Uses React Query for automatic cache management and live updates.+ *+ * Features:+ * - Fetch activity logs with filtering and pagination+ * - Clear all logs+ * - Automatic polling every 5 seconds+ * - Error handling with toast notifications+ * - Automatic cache invalidation+ *+ * @param filters - Activity log filters (pass as memoized object)+ * @param pagination - Pagination options (limit, offset) (pass as memoized object)+ * @returns Object with activity log data and management functions+ */+export function useActivityLogs(+ filters: ActivityLogsFilters = {},+ pagination: ActivityLogsPagination = { limit: 50, offset: 0 }+) {+ const t = useTranslations();+ const queryClient = useQueryClient();++ // Fetch activity logs with polling+ const {+ data: logsData,+ isLoading,+ error,+ refetch,+ } = useQuery({+ /* eslint-disable-next-line @tanstack/query/exhaustive-deps */+ queryKey: queryKeys.activityLogs({ filters, pagination }),+ queryFn: () => fetchActivityLogsApi(filters, pagination, t),+ refetchInterval: REFETCH_INTERVAL,+ refetchIntervalInBackground: true, // Continue polling in background+ });++ // Clear logs mutation+ const clearLogsMutation = useMutation({+ mutationFn: () => clearLogsApi(t),+ onSuccess: () => {+ toast.success(t("common.deleted", { item: t("activityLog.title") }));+ queryClient.invalidateQueries({ queryKey: ["activity-logs"] });+ },+ onError: (err) => {toast.error(- err instanceof Error ? err.message : "Failed to clear activity logs"+ err instanceof Error+ ? err.message+ : t("common.deleteError", { item: t("activityLog.title") }));- }- }, [fetchLogs]);-- // Mark specific logs as read- // Update filters- const updateFilters = useCallback(- (newFilters: Partial<ActivityLogsFilters>) => {- setFilters((prev) => ({ ...prev, ...newFilters }));- setPage(0); // Reset to first page when filters change},- []- );-- // Clear filters- const clearFilters = useCallback(() => {- setFilters({});- setPage(0);- }, []);-- // Pagination- const goToNextPage = useCallback(() => {- if (hasMore) {- setPage((prev) => prev + 1);- }- }, [hasMore]);-- const goToPreviousPage = useCallback(() => {- if (page > 0) {- setPage((prev) => prev - 1);- }- }, [page]);-- // Initial fetch + fetch on filter/page change- useEffect(() => {- fetchLogs(page);- }, [page, filters.type, filters.startDate, filters.endDate, fetchLogs]); // Re-fetch on server-side filter changes-- // Apply client-side filters when they change- useEffect(() => {- let filtered = logs;-- if (filters.severity) {- filtered = filtered.filter((log) => log.severity === filters.severity);- }-- if (filters.search && filters.search.trim()) {- const searchLower = filters.search.toLowerCase();- filtered = filtered.filter(- (log) =>- log.action.toLowerCase().includes(searchLower) ||- (log.resourceType &&- log.resourceType.toLowerCase().includes(searchLower)) ||- (log.resourceId && log.resourceId.toLowerCase().includes(searchLower))- );- }-- setFilteredLogs(filtered);- }, [logs, filters.severity, filters.search]);+ });return {// Data- logs: filteredLogs,- total,- page,- limit,- hasMore,- loading,+ logs: logsData?.logs || [],+ total: logsData?.total || 0,+ limit: logsData?.limit || pagination.limit,+ offset: logsData?.offset || pagination.offset,+ isLoading,error,- // Filters- filters,- updateFilters,- clearFilters,-- // Actions- fetchLogs: () => fetchLogs(page),- clearLogs,-- // Pagination- goToNextPage,- goToPreviousPage,+ // Functions+ refetch,+ clearLogs: async (): Promise<boolean> => {+ try {+ await clearLogsMutation.mutateAsync();+ return true;+ } catch {+ return false;+ }+ },};}diff --git a/hooks/useAdminAuditLogs.ts b/hooks/useAdminAuditLogs.tsnew file mode 100644index 0000000..8d2eefd--- /dev/null+++ b/hooks/useAdminAuditLogs.ts@@ -0,0 +1,312 @@+"use client";++import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import { useTranslations } from "next-intl";+import { queryKeys } from "@/lib/query-keys";+import { REFETCH_INTERVAL } from "@/lib/query-client";++/**+ * Audit Log Types+ */+export interface AuditLog {+ id: string;+ userId: string | null;+ action: string;+ resourceType: string | null;+ resourceId: string | null;+ metadata: unknown;+ ipAddress: string | null;+ userAgent: string | null;+ severity: "info" | "warning" | "error" | "critical";+ isUserVisible: boolean;+ timestamp: Date;+ userName: string | null;+ userEmail: string | null;+ userImage: string | null;+}++export interface AuditLogFilters {+ action?: string;+ userId?: string;+ resourceType?: string;+ resourceId?: string;+ severity?: "info" | "warning" | "error" | "critical";+ search?: string;+ startDate?: string;+ endDate?: string;+}++export interface AuditLogSort {+ field: "timestamp" | "action" | "severity" | "user" | "ipAddress";+ direction: "asc" | "desc";+}++export interface AuditLogPagination {+ limit: number;+ offset: number;+}++export interface AuditLogsResponse {+ logs: AuditLog[];+ total: number;+ limit: number;+ offset: number;+}++/**+ * Fetch audit logs from API+ */+async function fetchAuditLogsApi(+ filters: AuditLogFilters,+ sort: AuditLogSort,+ pagination: AuditLogPagination,+ t: ReturnType<typeof useTranslations>+): Promise<AuditLogsResponse> {+ const params = new URLSearchParams();++ if (filters.action) params.set("action", filters.action);+ if (filters.userId) params.set("userId", filters.userId);+ if (filters.resourceType) params.set("resourceType", filters.resourceType);+ if (filters.resourceId) params.set("resourceId", filters.resourceId);+ if (filters.severity) params.set("severity", filters.severity);+ if (filters.search) params.set("search", filters.search);+ if (filters.startDate) params.set("startDate", filters.startDate);+ if (filters.endDate) params.set("endDate", filters.endDate);++ params.set("sortBy", sort.field);+ params.set("sortOrder", sort.direction);+ params.set("limit", pagination.limit.toString());+ params.set("offset", pagination.offset.toString());++ const response = await fetch(`/api/admin/audit-logs?${params.toString()}`, {+ method: "GET",+ headers: {+ "Content-Type": "application/json",+ },+ });++ if (!response.ok) {+ if (response.status === 403) {+ throw new Error(t("admin.accessDenied"));+ }+ throw new Error(t("common.fetchError", { item: t("admin.auditLogs") }));+ }++ const data = await response.json();++ // Parse date strings to Date objects+ const logs = data.logs.map((log: Record<string, unknown>) => ({+ ...log,+ timestamp: new Date(log.timestamp as string),+ }));++ return {+ logs,+ total: data.pagination.total,+ limit: data.pagination.limit,+ offset: data.pagination.offset,+ };+}++/**+ * Delete audit logs by IDs via API+ */+async function deleteLogsByIdsApi(+ logIds: string[],+ t: ReturnType<typeof useTranslations>+): Promise<{ deletedCount: number }> {+ const response = await fetch("/api/admin/audit-logs", {+ method: "DELETE",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ logIds }),+ });++ if (!response.ok) {+ if (response.status === 403) {+ throw new Error(t("admin.accessDenied"));+ }+ throw new Error(t("common.deleteError", { item: t("admin.auditLogs") }));+ }++ return await response.json();+}++/**+ * Delete audit logs by date via API+ */+async function deleteLogsByDateApi(+ beforeDate: string,+ t: ReturnType<typeof useTranslations>+): Promise<{ deletedCount: number }> {+ const response = await fetch(+ `/api/admin/audit-logs?before=${encodeURIComponent(beforeDate)}`,+ {+ method: "DELETE",+ }+ );++ if (!response.ok) {+ if (response.status === 403) {+ throw new Error(t("admin.accessDenied"));+ }+ throw new Error(t("common.deleteError", { item: t("admin.auditLogs") }));+ }++ return await response.json();+}++/**+ * Admin Audit Logs Hook+ *+ * Provides functions for managing audit logs in the admin panel.+ * Uses React Query for automatic polling and cache management.+ *+ * Features:+ * - Fetch audit logs with filtering, sorting, and pagination+ * - Delete audit logs by IDs (superadmin only)+ * - Delete audit logs by date (superadmin only)+ * - Optimistic updates for instant UI feedback+ * - Error handling with toast notifications+ * - Automatic cache invalidation+ *+ * @param filters - Audit log filters+ * @param sort - Sort options (field, direction)+ * @param pagination - Pagination options (limit, offset)+ * @returns Object with audit log data and management functions+ */+export function useAdminAuditLogs(+ filters: AuditLogFilters = {},+ sort: AuditLogSort = { field: "timestamp", direction: "desc" },+ pagination: AuditLogPagination = { limit: 25, offset: 0 }+) {+ const t = useTranslations();+ const queryClient = useQueryClient();++ // Fetch audit logs list with polling+ const {+ data: logsData,+ isLoading,+ error,+ refetch,+ } = useQuery({+ // eslint-disable-next-line @tanstack/query/exhaustive-deps+ queryKey: queryKeys.admin.auditLogs({ filters, sort, pagination }),+ queryFn: () => fetchAuditLogsApi(filters, sort, pagination, t),+ refetchInterval: REFETCH_INTERVAL,+ refetchIntervalInBackground: true, // Continue polling in background+ });++ // Delete audit logs by IDs mutation+ const deleteByIdsMutation = useMutation({+ mutationFn: (logIds: string[]) => deleteLogsByIdsApi(logIds, t),+ onMutate: async (logIds) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.admin.auditLogs({ filters, sort, pagination }),+ });+ const previous = queryClient.getQueryData(+ queryKeys.admin.auditLogs({ filters, sort, pagination })+ );++ // Optimistic update+ queryClient.setQueryData(+ queryKeys.admin.auditLogs({ filters, sort, pagination }),+ (old: AuditLogsResponse | undefined) => {+ if (!old) return old;+ return {+ ...old,+ logs: old.logs.filter((log) => !logIds.includes(log.id)),+ total: old.total - logIds.length,+ };+ }+ );++ return { previous };+ },+ onError: (err, logIds, context) => {+ queryClient.setQueryData(+ queryKeys.admin.auditLogs({ filters, sort, pagination }),+ context?.previous+ );+ toast.error(+ err instanceof Error+ ? err.message+ : t("common.deleteError", { item: t("admin.auditLogs") })+ );+ },+ onSuccess: (data) => {+ toast.success(t("common.deletedCount", { count: data.deletedCount }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: ["admin", "audit-logs"] });+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats });+ },+ });++ // Delete audit logs by date mutation+ const deleteByDateMutation = useMutation({+ mutationFn: (beforeDate: string) => deleteLogsByDateApi(beforeDate, t),+ onError: (err) => {+ toast.error(+ err instanceof Error+ ? err.message+ : t("common.deleteError", { item: t("admin.auditLogs") })+ );+ },+ onSuccess: (data) => {+ toast.success(t("common.deletedCount", { count: data.deletedCount }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: ["admin", "audit-logs"] });+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats });+ },+ });++ return {+ // Data+ logs: logsData?.logs || [],+ total: logsData?.total || 0,+ limit: logsData?.limit || pagination.limit,+ offset: logsData?.offset || pagination.offset,+ isLoading,+ error,++ // Functions+ refetch,+ deleteLogsByIds: async (logIds: string[]): Promise<boolean> => {+ if (logIds.length === 0) {+ return false;+ }+ try {+ await deleteByIdsMutation.mutateAsync(logIds);+ return true;+ } catch {+ return false;+ }+ },+ deleteLogsByDate: async (beforeDate: string): Promise<boolean> => {+ try {+ await deleteByDateMutation.mutateAsync(beforeDate);+ return true;+ } catch {+ return false;+ }+ },+ fetchAuditLogs: async (+ searchFilters: AuditLogFilters,+ searchSort: AuditLogSort,+ searchPagination: AuditLogPagination+ ): Promise<AuditLogsResponse | null> => {+ try {+ return await fetchAuditLogsApi(+ searchFilters,+ searchSort,+ searchPagination,+ t+ );+ } catch {+ return null;+ }+ },+ };+}diff --git a/hooks/useAdminCalendars.ts b/hooks/useAdminCalendars.tsindex 7e7487e..c11ca45 100644--- a/hooks/useAdminCalendars.ts+++ b/hooks/useAdminCalendars.ts@@ -1,8 +1,10 @@"use client";-import { useState, useCallback } from "react";+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { toast } from "sonner";import { useTranslations } from "next-intl";+import { queryKeys } from "@/lib/query-keys";+import { REFETCH_INTERVAL } from "@/lib/query-client";/*** Calendar Owner Info@@ -82,10 +84,181 @@ export interface CalendarsListResponse {orphanedCount: number;}+/**+ * Fetch calendars list from API+ */+async function fetchCalendarsApi(+ filters: CalendarFilters | undefined,+ sort: CalendarSort | undefined,+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ t: ReturnType<typeof useTranslations>+): Promise<CalendarsListResponse> {+ const params = new URLSearchParams();++ if (filters?.search) {+ params.set("search", filters.search);+ }+ if (filters?.status && filters.status !== "all") {+ params.set("status", filters.status);+ }++ if (sort?.field) {+ params.set("sortBy", sort.field);+ }+ if (sort?.direction) {+ params.set("sortDirection", sort.direction);+ }++ const response = await fetch(`/api/admin/calendars?${params}`);++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.error || "Failed to fetch calendars");+ }++ const data = await response.json();++ // Parse dates+ const calendars = data.calendars.map((cal: AdminCalendar) => ({+ ...cal,+ createdAt: new Date(cal.createdAt),+ updatedAt: new Date(cal.updatedAt),+ }));++ return {+ calendars,+ total: data.total,+ orphanedCount: data.orphanedCount,+ };+}++/**+ * Fetch calendar details from API+ */+async function fetchCalendarDetailsApi(+ calendarId: string+): Promise<CalendarDetails> {+ const response = await fetch(`/api/admin/calendars/${calendarId}`);++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.error || "Failed to fetch calendar details");+ }++ const data = await response.json();++ // Parse dates+ return {+ ...data,+ createdAt: new Date(data.createdAt),+ updatedAt: new Date(data.updatedAt),+ externalSyncs: data.externalSyncs.map(+ (sync: CalendarDetails["externalSyncs"][number]) => ({+ ...sync,+ lastSyncedAt: sync.lastSyncedAt ? new Date(sync.lastSyncedAt) : null,+ })+ ),+ };+}++/**+ * Update calendar via API+ */+async function updateCalendarApi(+ calendarId: string,+ updates: { name?: string; color?: string; guestPermission?: string }+): Promise<void> {+ const response = await fetch(`/api/admin/calendars/${calendarId}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(updates),+ });++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.error || "Failed to update calendar");+ }+}++/**+ * Delete calendar via API+ */+async function deleteCalendarApi(calendarId: string): Promise<void> {+ const response = await fetch(`/api/admin/calendars/${calendarId}`, {+ method: "DELETE",+ });++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.error || "Failed to delete calendar");+ }+}++/**+ * Transfer calendar ownership via API+ */+async function transferCalendarApi(+ calendarId: string,+ newOwnerId: string+): Promise<void> {+ const response = await fetch(`/api/admin/calendars/${calendarId}/transfer`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ newOwnerId }),+ });++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.error || "Failed to transfer calendar");+ }+}++/**+ * Bulk delete calendars via API+ */+async function bulkDeleteCalendarsApi(+ calendarIds: string[]+): Promise<{ deletedCount: number }> {+ const response = await fetch("/api/admin/calendars/bulk-delete", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ calendarIds }),+ });++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.error || "Failed to delete calendars");+ }++ return await response.json();+}++/**+ * Bulk transfer calendars via API+ */+async function bulkTransferCalendarsApi(+ calendarIds: string[],+ newOwnerId: string+): Promise<{ transferredCount: number }> {+ const response = await fetch("/api/admin/calendars/bulk-transfer", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ calendarIds, newOwnerId }),+ });++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.error || "Failed to transfer calendars");+ }++ return await response.json();+}+/*** Admin Calendars Management Hook** Provides functions for managing calendars in the admin panel.+ * Uses React Query for automatic polling and cache management.** Features:* - Fetch calendars with filtering and sorting@@ -93,310 +266,289 @@ export interface CalendarsListResponse {* - Update calendar information* - Delete calendars (single and bulk)* - Transfer calendar ownership (single and bulk)+ * - Optimistic updates for instant UI feedback* - Error handling with toast notifications+ * - Automatic cache invalidation*- * @returns Object with calendar management functions and state+ * @param filters - Calendar filters (search, status)+ * @param sort - Sort options (field, direction)+ * @returns Object with calendar data and management functions*/-export function useAdminCalendars() {+export function useAdminCalendars(+ filters?: CalendarFilters,+ sort?: CalendarSort+) {const t = useTranslations();- const [isLoading, setIsLoading] = useState(false);-- /**- * Fetch calendars list with filters and sort- */- const fetchCalendars = useCallback(- async (- filters?: CalendarFilters,- sort?: CalendarSort- ): Promise<CalendarsListResponse | null> => {- setIsLoading(true);- try {- const params = new URLSearchParams();+ const queryClient = useQueryClient();- // Add filters- if (filters?.search) {- params.set("search", filters.search);- }- if (filters?.status && filters.status !== "all") {- params.set("status", filters.status);+ // Fetch calendars list with polling+ const {+ data: calendarsData,+ isLoading,+ error,+ refetch,+ } = useQuery({+ // eslint-disable-next-line @tanstack/query/exhaustive-deps+ queryKey: queryKeys.admin.calendars({ filters, sort }),+ queryFn: () => fetchCalendarsApi(filters, sort, t),+ refetchInterval: REFETCH_INTERVAL,+ });++ // Update calendar mutation+ const updateMutation = useMutation({+ mutationFn: ({+ calendarId,+ updates,+ }: {+ calendarId: string;+ updates: { name?: string; color?: string; guestPermission?: string };+ }) => updateCalendarApi(calendarId, updates),+ onMutate: async ({ calendarId, updates }) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.admin.calendars({ filters, sort }),+ });+ const previous = queryClient.getQueryData(+ queryKeys.admin.calendars({ filters, sort })+ );++ // Optimistic update+ queryClient.setQueryData(+ queryKeys.admin.calendars({ filters, sort }),+ (old: CalendarsListResponse | undefined) => {+ if (!old) return old;+ return {+ ...old,+ calendars: old.calendars.map((cal) =>+ cal.id === calendarId ? { ...cal, ...updates } : cal+ ),+ };}+ );- // Add sort- if (sort?.field) {- params.set("sortBy", sort.field);- }- if (sort?.direction) {- params.set("sortDirection", sort.direction);+ return { previous };+ },+ onError: (err, variables, context) => {+ queryClient.setQueryData(+ queryKeys.admin.calendars({ filters, sort }),+ context?.previous+ );+ toast.error(+ t("common.updateError", { item: t("common.labels.calendar") })+ );+ },+ onSuccess: () => {+ toast.success(t("common.updated", { item: t("common.labels.calendar") }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: ["admin", "calendars"] });+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats });+ },+ });++ // Delete calendar mutation+ const deleteMutation = useMutation({+ mutationFn: (calendarId: string) => deleteCalendarApi(calendarId),+ onMutate: async (calendarId) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.admin.calendars({ filters, sort }),+ });+ const previous = queryClient.getQueryData(+ queryKeys.admin.calendars({ filters, sort })+ );++ // Optimistic update+ queryClient.setQueryData(+ queryKeys.admin.calendars({ filters, sort }),+ (old: CalendarsListResponse | undefined) => {+ if (!old) return old;+ return {+ ...old,+ calendars: old.calendars.filter((cal) => cal.id !== calendarId),+ total: old.total - 1,+ };}+ );- const response = await fetch(`/api/admin/calendars?${params}`);-- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || "Failed to fetch calendars");+ return { previous };+ },+ onError: (err, calendarId, context) => {+ queryClient.setQueryData(+ queryKeys.admin.calendars({ filters, sort }),+ context?.previous+ );+ toast.error(+ t("common.deleteError", { item: t("common.labels.calendar") })+ );+ },+ onSuccess: () => {+ toast.success(t("common.deleted", { item: t("common.labels.calendar") }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: ["admin", "calendars"] });+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats });+ },+ });++ // Transfer calendar mutation+ const transferMutation = useMutation({+ mutationFn: ({+ calendarId,+ newOwnerId,+ }: {+ calendarId: string;+ newOwnerId: string;+ }) => transferCalendarApi(calendarId, newOwnerId),+ onError: () => {+ toast.error(+ t("common.transferError", { item: t("common.labels.calendar") })+ );+ },+ onSuccess: () => {+ toast.success(+ t("common.transferred", { item: t("common.labels.calendar") })+ );+ },+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: ["admin", "calendars"] });+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats });+ },+ });++ // Bulk delete mutation+ const bulkDeleteMutation = useMutation({+ mutationFn: (calendarIds: string[]) => bulkDeleteCalendarsApi(calendarIds),+ onMutate: async (calendarIds) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.admin.calendars({ filters, sort }),+ });+ const previous = queryClient.getQueryData(+ queryKeys.admin.calendars({ filters, sort })+ );++ // Optimistic update+ queryClient.setQueryData(+ queryKeys.admin.calendars({ filters, sort }),+ (old: CalendarsListResponse | undefined) => {+ if (!old) return old;+ return {+ ...old,+ calendars: old.calendars.filter(+ (cal) => !calendarIds.includes(cal.id)+ ),+ total: old.total - calendarIds.length,+ };}+ );- const data = await response.json();-- // Parse dates- const calendars = data.calendars.map((cal: AdminCalendar) => ({- ...cal,- createdAt: new Date(cal.createdAt),- updatedAt: new Date(cal.updatedAt),- }));-- return {- calendars,- total: data.total,- orphanedCount: data.orphanedCount,- };- } catch (error) {- console.error("Failed to fetch calendars:", error);- toast.error(- t("common.fetchError", { item: t("common.labels.calendar") })- );- return null;- } finally {- setIsLoading(false);- }+ return { previous };},- [t]- );-- /**- * Get calendar details by ID- */- const fetchCalendarDetails = useCallback(- async (calendarId: string): Promise<CalendarDetails | null> => {- setIsLoading(true);- try {- const response = await fetch(`/api/admin/calendars/${calendarId}`);+ onError: (err, calendarIds, context) => {+ queryClient.setQueryData(+ queryKeys.admin.calendars({ filters, sort }),+ context?.previous+ );+ toast.error(+ t("common.deleteError", { item: t("common.labels.calendar") })+ );+ },+ onSuccess: (data) => {+ toast.success(+ t("admin.calendars.calendarsDeleted", { count: data.deletedCount })+ );+ },+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: ["admin", "calendars"] });+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats });+ },+ });++ // Bulk transfer mutation+ const bulkTransferMutation = useMutation({+ mutationFn: ({+ calendarIds,+ newOwnerId,+ }: {+ calendarIds: string[];+ newOwnerId: string;+ }) => bulkTransferCalendarsApi(calendarIds, newOwnerId),+ onError: () => {+ toast.error(+ t("common.transferError", { item: t("common.labels.calendar") })+ );+ },+ onSuccess: (data) => {+ toast.success(+ t("admin.calendars.calendarsTransferred", {+ count: data.transferredCount,+ })+ );+ },+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: ["admin", "calendars"] });+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats });+ },+ });- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || "Failed to fetch calendar details");- }+ return {+ // Data+ calendars: calendarsData?.calendars || [],+ total: calendarsData?.total || 0,+ orphanedCount: calendarsData?.orphanedCount || 0,+ isLoading,+ error,- const data = await response.json();-- // Parse dates- return {- ...data,- createdAt: new Date(data.createdAt),- updatedAt: new Date(data.updatedAt),- externalSyncs: data.externalSyncs.map(- (sync: CalendarDetails["externalSyncs"][number]) => ({- ...sync,- lastSyncedAt: sync.lastSyncedAt- ? new Date(sync.lastSyncedAt)- : null,- })- ),- };- } catch (error) {- console.error("Failed to fetch calendar details:", error);- toast.error(- t("common.fetchError", { item: t("admin.calendars.calendarDetails") })- );- return null;- } finally {- setIsLoading(false);- }- },- [t]- );-- /**- * Update calendar- */- const updateCalendar = useCallback(- async (+ // Functions+ refetch,+ fetchCalendarDetails: (calendarId: string) =>+ fetchCalendarDetailsApi(calendarId),+ updateCalendar: async (calendarId: string,updates: { name?: string; color?: string; guestPermission?: string }): Promise<boolean> => {- setIsLoading(true);try {- const response = await fetch(`/api/admin/calendars/${calendarId}`, {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(updates),- });-- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || "Failed to update calendar");- }-- toast.success(- t("common.updated", { item: t("common.labels.calendar") })- );+ await updateMutation.mutateAsync({ calendarId, updates });return true;- } catch (error) {- console.error("Failed to update calendar:", error);- toast.error(- t("common.updateError", { item: t("common.labels.calendar") })- );+ } catch {return false;- } finally {- setIsLoading(false);}},- [t]- );-- /**- * Delete calendar- */- const deleteCalendar = useCallback(- async (calendarId: string): Promise<boolean> => {- setIsLoading(true);+ deleteCalendar: async (calendarId: string): Promise<boolean> => {try {- const response = await fetch(`/api/admin/calendars/${calendarId}`, {- method: "DELETE",- });-- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || "Failed to delete calendar");- }-- toast.success(- t("common.deleted", { item: t("common.labels.calendar") })- );+ await deleteMutation.mutateAsync(calendarId);return true;- } catch (error) {- console.error("Failed to delete calendar:", error);- toast.error(- t("common.deleteError", { item: t("common.labels.calendar") })- );+ } catch {return false;- } finally {- setIsLoading(false);}},- [t]- );-- /**- * Transfer calendar ownership- */- const transferCalendar = useCallback(- async (calendarId: string, newOwnerId: string): Promise<boolean> => {- setIsLoading(true);+ transferCalendar: async (+ calendarId: string,+ newOwnerId: string+ ): Promise<boolean> => {try {- const response = await fetch(- `/api/admin/calendars/${calendarId}/transfer`,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ newOwnerId }),- }- );-- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || "Failed to transfer calendar");- }-- toast.success(- t("common.transferred", { item: t("common.labels.calendar") })- );+ await transferMutation.mutateAsync({ calendarId, newOwnerId });return true;- } catch (error) {- console.error("Failed to transfer calendar:", error);- toast.error(- t("common.transferError", { item: t("common.labels.calendar") })- );+ } catch {return false;- } finally {- setIsLoading(false);}},- [t]- );-- /**- * Bulk delete calendars- */- const bulkDeleteCalendars = useCallback(- async (calendarIds: string[]): Promise<boolean> => {- setIsLoading(true);+ bulkDeleteCalendars: async (calendarIds: string[]): Promise<boolean> => {try {- const response = await fetch("/api/admin/calendars/bulk-delete", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ calendarIds }),- });-- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || "Failed to delete calendars");- }-- const data = await response.json();- toast.success(- t("admin.calendars.calendarsDeleted", { count: data.deletedCount })- );+ await bulkDeleteMutation.mutateAsync(calendarIds);return true;- } catch (error) {- console.error("Failed to bulk delete calendars:", error);- toast.error(- t("common.deleteError", { item: t("common.labels.calendar") })- );+ } catch {return false;- } finally {- setIsLoading(false);}},- [t]- );-- /**- * Bulk transfer calendars- */- const bulkTransferCalendars = useCallback(- async (calendarIds: string[], newOwnerId: string): Promise<boolean> => {- setIsLoading(true);+ bulkTransferCalendars: async (+ calendarIds: string[],+ newOwnerId: string+ ): Promise<boolean> => {try {- const response = await fetch("/api/admin/calendars/bulk-transfer", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ calendarIds, newOwnerId }),- });-- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || "Failed to transfer calendars");- }-- const data = await response.json();- toast.success(- t("admin.calendars.calendarsTransferred", {- count: data.transferredCount,- })- );+ await bulkTransferMutation.mutateAsync({ calendarIds, newOwnerId });return true;- } catch (error) {- console.error("Failed to bulk transfer calendars:", error);- toast.error(- t("common.transferError", { item: t("common.labels.calendar") })- );+ } catch {return false;- } finally {- setIsLoading(false);}},- [t]- );-- return {- fetchCalendars,- fetchCalendarDetails,- updateCalendar,- deleteCalendar,- transferCalendar,- bulkDeleteCalendars,- bulkTransferCalendars,- isLoading,};}diff --git a/hooks/useAdminStats.ts b/hooks/useAdminStats.tsindex 05abc73..31bbd34 100644--- a/hooks/useAdminStats.ts+++ b/hooks/useAdminStats.ts@@ -1,8 +1,11 @@"use client";-import { useState, useEffect, useCallback } from "react";+import { useQuery } from "@tanstack/react-query";+import { useEffect, useRef } from "react";import { toast } from "sonner";import { useTranslations } from "next-intl";+import { queryKeys } from "@/lib/query-keys";+import { REFETCH_INTERVAL } from "@/lib/query-client";/*** Admin Stats Type Definitions@@ -50,94 +53,87 @@ interface AuditLogResponse {timestamp: string | Date;}+/**+ * Fetch admin stats from API+ */+async function fetchAdminStatsApi(+ t: ReturnType<typeof useTranslations>+): Promise<AdminStats> {+ const response = await fetch("/api/admin/stats", {+ method: "GET",+ headers: {+ "Content-Type": "application/json",+ },+ });++ if (!response.ok) {+ if (response.status === 403) {+ throw new Error(t("admin.accessDenied"));+ }+ throw new Error(t("admin.statsFetchError"));+ }++ const data = await response.json();++ // Parse timestamp strings to Date objects+ if (data.activity?.logs) {+ data.activity.logs = data.activity.logs.map((log: AuditLogResponse) => ({+ ...log,+ timestamp: new Date(log.timestamp),+ }));+ }++ return data;+}+/*** Admin Statistics Hook** Fetches and manages system-wide statistics for admin dashboard.+ * Uses React Query for automatic polling and cache management.** Features:- * - Automatic data fetching on mount- * - Optional auto-refresh (configurable interval)+ * - Automatic 5-second polling for live updates* - Error handling with toast notifications+ * - Smart caching and background refetching* - Loading state management*- * @param autoRefresh - Enable auto-refresh (default: false)- * @param refreshInterval - Refresh interval in milliseconds (default: 60000 = 1 minute)+ * @returns Object with stats data, loading state, error, and refetch function*/-export function useAdminStats(- autoRefresh = false,- refreshInterval = 60000-): {+export function useAdminStats(): {stats: AdminStats | null;isLoading: boolean;error: Error | null;- refetch: () => Promise<void>;+ refetch: () => void;} {const t = useTranslations();- const [stats, setStats] = useState<AdminStats | null>(null);- const [isLoading, setIsLoading] = useState(true);- const [error, setError] = useState<Error | null>(null);-- const fetchStats = useCallback(async () => {- try {- setError(null);-- const response = await fetch("/api/admin/stats", {- method: "GET",- headers: {- "Content-Type": "application/json",- },- });-- if (!response.ok) {- if (response.status === 403) {- throw new Error(t("admin.accessDenied"));- }- throw new Error(t("admin.statsFetchError"));- }+ const lastErrorMessage = useRef<string | null>(null);- const data = await response.json();-- // Parse timestamp strings to Date objects- if (data.activity?.logs) {- data.activity.logs = data.activity.logs.map(- (log: AuditLogResponse) => ({- ...log,- timestamp: new Date(log.timestamp),- })- );- }+ const {+ data: stats = null,+ isLoading,+ error,+ refetch,+ } = useQuery({+ // eslint-disable-next-line @tanstack/query/exhaustive-deps+ queryKey: queryKeys.admin.stats,+ queryFn: () => fetchAdminStatsApi(t),+ refetchInterval: REFETCH_INTERVAL,+ });- setStats(data);- } catch (err) {- const error = err instanceof Error ? err : new Error("Unknown error");- setError(error);+ useEffect(() => {+ if (error && error.message !== lastErrorMessage.current) {toast.error(error.message);- } finally {- setIsLoading(false);+ lastErrorMessage.current = error.message;+ } else if (!error) {+ lastErrorMessage.current = null;}- }, [t]);-- // Initial fetch on mount- useEffect(() => {- fetchStats();- }, [fetchStats]);-- // Auto-refresh setup- useEffect(() => {- if (!autoRefresh) return;-- const interval = setInterval(() => {- fetchStats();- }, refreshInterval);-- return () => clearInterval(interval);- }, [autoRefresh, refreshInterval, fetchStats]);+ }, [error]);return {stats,isLoading,- error,- refetch: fetchStats,+ error: error as Error | null,+ refetch,};}diff --git a/hooks/useAdminUsers.ts b/hooks/useAdminUsers.tsindex f6ba286..4413c7b 100644--- a/hooks/useAdminUsers.ts+++ b/hooks/useAdminUsers.ts@@ -1,9 +1,11 @@"use client";-import { useState, useCallback } from "react";+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { toast } from "sonner";import { useTranslations } from "next-intl";+import { queryKeys } from "@/lib/query-keys";import type { User } from "@/lib/auth";+import { REFETCH_INTERVAL } from "@/lib/query-client";/*** Extended User Type with Admin-specific fields@@ -76,10 +78,248 @@ export interface UsersListResponse {totalPages: number;}+/**+ * Fetch users list from API+ */+async function fetchUsersApi(+ filters: UserFilters,+ sort: UserSort,+ pagination: Pagination,+ t: ReturnType<typeof useTranslations>+): Promise<UsersListResponse> {+ const params = new URLSearchParams();+ if (filters.search) params.set("search", filters.search);+ if (filters.role && filters.role !== "all") params.set("role", filters.role);+ if (filters.status && filters.status !== "all") {+ params.set("banned", filters.status === "banned" ? "true" : "false");+ }+ params.set("sortBy", sort.field);+ params.set("sortDir", sort.direction);+ params.set("page", pagination.page.toString());+ params.set("limit", pagination.limit.toString());++ const response = await fetch(`/api/admin/users?${params.toString()}`, {+ method: "GET",+ headers: {+ "Content-Type": "application/json",+ },+ });++ if (!response.ok) {+ if (response.status === 403) {+ throw new Error(t("admin.accessDenied"));+ }+ throw new Error(t("common.fetchError", { item: t("common.labels.users") }));+ }++ const data = await response.json();++ // Parse date strings to Date objects+ const users = data.users.map((user: Record<string, unknown>) => ({+ ...user,+ createdAt: new Date(user.createdAt as string),+ updatedAt: new Date(user.updatedAt as string),+ lastActivity: user.lastActivity+ ? new Date(user.lastActivity as string)+ : null,+ banExpires: user.banExpires ? new Date(user.banExpires as string) : null,+ }));++ return {+ ...data,+ users,+ };+}++/**+ * Fetch user details from API+ */+async function fetchUserDetailsApi(+ userId: string,+ t: ReturnType<typeof useTranslations>+): Promise<UserDetails> {+ const response = await fetch(`/api/admin/users/${userId}`, {+ method: "GET",+ headers: {+ "Content-Type": "application/json",+ },+ });++ if (!response.ok) {+ if (response.status === 403) {+ throw new Error(t("admin.accessDenied"));+ }+ if (response.status === 404) {+ throw new Error(t("admin.userNotFound"));+ }+ throw new Error(t("common.fetchError", { item: t("admin.userDetails") }));+ }++ const data = await response.json();++ // Parse date strings to Date objects+ return {+ ...data.user,+ createdAt: new Date(data.user.createdAt as string),+ updatedAt: new Date(data.user.updatedAt as string),+ lastActivity: data.lastActivity+ ? new Date(data.lastActivity as string)+ : null,+ banExpires: data.user.banExpires+ ? new Date(data.user.banExpires as string)+ : null,+ ownedCalendars: data.calendars || [],+ sharedCalendars: data.sharedCalendars || [],+ sharesCount: data.sharesCount,+ calendarCount: (data.calendars?.length || 0) + data.sharesCount,+ accounts: data.accounts.map((account: Record<string, unknown>) => ({+ ...account,+ createdAt: new Date(account.createdAt as string),+ })),+ sessionsCount: data.sessionsCount,+ };+}++/**+ * Update user via API+ */+async function updateUserApi(+ userId: string,+ data: { name?: string; email?: string; role?: string },+ t: ReturnType<typeof useTranslations>+): Promise<void> {+ const response = await fetch(`/api/admin/users/${userId}`, {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(data),+ });++ if (!response.ok) {+ if (response.status === 403) {+ throw new Error(t("admin.accessDenied"));+ }+ if (response.status === 404) {+ throw new Error(t("admin.userNotFound"));+ }+ throw new Error(t("common.updateError", { item: t("common.labels.user") }));+ }+}++/**+ * Ban user via API+ */+async function banUserApi(+ userId: string,+ reason: string,+ expiresAt: Date | undefined,+ t: ReturnType<typeof useTranslations>+): Promise<void> {+ const response = await fetch(`/api/admin/users/${userId}/ban`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ reason,+ expiresAt: expiresAt?.toISOString(),+ }),+ });++ if (!response.ok) {+ if (response.status === 403) {+ throw new Error(t("admin.accessDenied"));+ }+ if (response.status === 404) {+ throw new Error(t("admin.userNotFound"));+ }+ throw new Error(t("common.banError", { item: t("common.labels.user") }));+ }+}++/**+ * Unban user via API+ */+async function unbanUserApi(+ userId: string,+ t: ReturnType<typeof useTranslations>+): Promise<void> {+ const response = await fetch(`/api/admin/users/${userId}/unban`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ });++ if (!response.ok) {+ if (response.status === 403) {+ throw new Error(t("admin.accessDenied"));+ }+ if (response.status === 404) {+ throw new Error(t("admin.userNotFound"));+ }+ throw new Error(t("common.unbanError", { item: t("common.labels.user") }));+ }+}++/**+ * Delete user via API+ */+async function deleteUserApi(+ userId: string,+ t: ReturnType<typeof useTranslations>+): Promise<void> {+ const response = await fetch(`/api/admin/users/${userId}`, {+ method: "DELETE",+ headers: {+ "Content-Type": "application/json",+ },+ });++ if (!response.ok) {+ if (response.status === 403) {+ throw new Error(t("admin.accessDenied"));+ }+ if (response.status === 404) {+ throw new Error(t("admin.userNotFound"));+ }+ throw new Error(t("common.deleteError", { item: t("common.labels.user") }));+ }+}++/**+ * Reset user password via API+ */+async function resetPasswordApi(+ userId: string,+ newPassword: string,+ t: ReturnType<typeof useTranslations>+): Promise<void> {+ const response = await fetch(`/api/admin/users/${userId}/password`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ password: newPassword }),+ });++ if (!response.ok) {+ if (response.status === 403) {+ throw new Error(t("admin.accessDenied"));+ }+ if (response.status === 404) {+ throw new Error(t("admin.userNotFound"));+ }+ throw new Error(t("common.passwordResetError"));+ }+}+/*** Admin Users Management Hook** Provides functions for managing users in the admin panel.+ * Uses React Query for automatic polling and cache management.** Features:* - Fetch users with filtering, sorting, and pagination@@ -88,393 +328,344 @@ export interface UsersListResponse {* - Ban/Unban users* - Delete users* - Reset user passwords+ * - Optimistic updates for instant UI feedback* - Error handling with toast notifications+ * - Automatic cache invalidation*- * @returns Object with user management functions and state+ * @param filters - User filters (search, role, status)+ * @param sort - Sort options (field, direction)+ * @param pagination - Pagination options (page, limit)+ * @returns Object with user data and management functions*/-export function useAdminUsers() {+export function useAdminUsers(+ filters: UserFilters = {},+ sort: UserSort = { field: "createdAt", direction: "desc" },+ pagination: Pagination = { page: 1, limit: 25 }+) {const t = useTranslations();- const [isLoading, setIsLoading] = useState(false);-- /**- * Fetch users list with filters, sort, and pagination- */- const fetchUsers = useCallback(- async (- filters: UserFilters = {},- sort: UserSort = { field: "createdAt", direction: "desc" },- pagination: Pagination = { page: 1, limit: 25 }- ): Promise<UsersListResponse | null> => {- try {- setIsLoading(true);-- const params = new URLSearchParams();- if (filters.search) params.set("search", filters.search);- if (filters.role && filters.role !== "all")- params.set("role", filters.role);- if (filters.status && filters.status !== "all") {- // Map 'active'/'banned' to boolean for API- params.set("banned", filters.status === "banned" ? "true" : "false");+ const queryClient = useQueryClient();++ // Fetch users list with polling+ const {+ data: usersData,+ isLoading,+ error,+ refetch,+ } = useQuery({+ // eslint-disable-next-line @tanstack/query/exhaustive-deps+ queryKey: queryKeys.admin.users({ filters, sort, pagination }),+ queryFn: () => fetchUsersApi(filters, sort, pagination, t),+ refetchInterval: REFETCH_INTERVAL,+ });++ // Update user mutation+ const updateMutation = useMutation({+ mutationFn: ({+ userId,+ data,+ }: {+ userId: string;+ data: { name?: string; email?: string; role?: string };+ }) => updateUserApi(userId, data, t),+ onMutate: async ({ userId, data }) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.admin.users({ filters, sort, pagination }),+ });+ const previous = queryClient.getQueryData(+ queryKeys.admin.users({ filters, sort, pagination })+ );++ // Optimistic update+ queryClient.setQueryData(+ queryKeys.admin.users({ filters, sort, pagination }),+ (old: UsersListResponse | undefined) => {+ if (!old) return old;+ return {+ ...old,+ users: old.users.map((user) =>+ user.id === userId ? { ...user, ...data } : user+ ),+ };}- params.set("sortBy", sort.field);- params.set("sortDir", sort.direction);- params.set("page", pagination.page.toString());- params.set("limit", pagination.limit.toString());-- const response = await fetch(`/api/admin/users?${params.toString()}`, {- method: "GET",- headers: {- "Content-Type": "application/json",- },- });-- if (!response.ok) {- if (response.status === 403) {- throw new Error(t("admin.accessDenied"));- }- throw new Error(- t("common.fetchError", { item: t("common.labels.users") })- );+ );++ return { previous };+ },+ onError: (err, variables, context) => {+ queryClient.setQueryData(+ queryKeys.admin.users({ filters, sort, pagination }),+ context?.previous+ );+ toast.error(+ err instanceof Error+ ? err.message+ : t("common.updateError", { item: t("common.labels.user") })+ );+ },+ onSuccess: () => {+ toast.success(t("common.updated", { item: t("common.labels.user") }));+ },+ onSettled: () => {+ // Invalidate all user queries+ queryClient.invalidateQueries({ queryKey: ["admin", "users"] });+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats });+ },+ });++ // Ban user mutation+ const banMutation = useMutation({+ mutationFn: ({+ userId,+ reason,+ expiresAt,+ }: {+ userId: string;+ reason: string;+ expiresAt?: Date;+ }) => banUserApi(userId, reason, expiresAt, t),+ onMutate: async ({ userId, reason, expiresAt }) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.admin.users({ filters, sort, pagination }),+ });+ const previous = queryClient.getQueryData(+ queryKeys.admin.users({ filters, sort, pagination })+ );++ // Optimistic update+ queryClient.setQueryData(+ queryKeys.admin.users({ filters, sort, pagination }),+ (old: UsersListResponse | undefined) => {+ if (!old) return old;+ return {+ ...old,+ users: old.users.map((user) =>+ user.id === userId+ ? {+ ...user,+ banned: true,+ banReason: reason,+ banExpires: expiresAt || null,+ }+ : user+ ),+ };}+ );- const data = await response.json();-- // Parse date strings to Date objects- const users = data.users.map((user: Record<string, unknown>) => ({- ...user,- createdAt: new Date(user.createdAt as string),- updatedAt: new Date(user.updatedAt as string),- lastActivity: user.lastActivity- ? new Date(user.lastActivity as string)- : null,- banExpires: user.banExpires- ? new Date(user.banExpires as string)- : null,- }));-- return {- ...data,- users,- };- } catch (error) {- console.error("Failed to fetch users:", error);- toast.error(- error instanceof Error- ? error.message- : t("common.fetchError", { item: t("common.labels.users") })- );- return null;- } finally {- setIsLoading(false);- }+ return { previous };},- [t]- );-- /**- * Fetch detailed user information- */- const fetchUserDetails = useCallback(- async (userId: string): Promise<UserDetails | null> => {- try {- setIsLoading(true);-- const response = await fetch(`/api/admin/users/${userId}`, {- method: "GET",- headers: {- "Content-Type": "application/json",- },- });-- if (!response.ok) {- if (response.status === 403) {- throw new Error(t("admin.accessDenied"));- }- if (response.status === 404) {- throw new Error(t("admin.userNotFound"));- }- throw new Error(- t("common.fetchError", { item: t("admin.userDetails") })- );+ onError: (err, variables, context) => {+ queryClient.setQueryData(+ queryKeys.admin.users({ filters, sort, pagination }),+ context?.previous+ );+ toast.error(+ err instanceof Error+ ? err.message+ : t("common.banError", { item: t("common.labels.user") })+ );+ },+ onSuccess: () => {+ toast.success(t("common.banned", { item: t("common.labels.user") }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: ["admin", "users"] });+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats });+ },+ });++ // Unban user mutation+ const unbanMutation = useMutation({+ mutationFn: (userId: string) => unbanUserApi(userId, t),+ onMutate: async (userId) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.admin.users({ filters, sort, pagination }),+ });+ const previous = queryClient.getQueryData(+ queryKeys.admin.users({ filters, sort, pagination })+ );++ // Optimistic update+ queryClient.setQueryData(+ queryKeys.admin.users({ filters, sort, pagination }),+ (old: UsersListResponse | undefined) => {+ if (!old) return old;+ return {+ ...old,+ users: old.users.map((user) =>+ user.id === userId+ ? { ...user, banned: false, banReason: null, banExpires: null }+ : user+ ),+ };}+ );- const data = await response.json();-- // Parse date strings to Date objects- return {- ...data.user,- createdAt: new Date(data.user.createdAt as string),- updatedAt: new Date(data.user.updatedAt as string),- lastActivity: data.lastActivity- ? new Date(data.lastActivity as string)- : null,- banExpires: data.user.banExpires- ? new Date(data.user.banExpires as string)- : null,- ownedCalendars: data.calendars || [],- sharedCalendars: data.sharedCalendars || [],- sharesCount: data.sharesCount,- calendarCount: (data.calendars?.length || 0) + data.sharesCount,- accounts: data.accounts.map((account: Record<string, unknown>) => ({- ...account,- createdAt: new Date(account.createdAt as string),- })),- sessionsCount: data.sessionsCount,- };- } catch (error) {- console.error("Failed to fetch user details:", error);- toast.error(- error instanceof Error- ? error.message- : t("common.fetchError", { item: t("admin.userDetails") })- );- return null;- } finally {- setIsLoading(false);- }+ return { previous };+ },+ onError: (err, userId, context) => {+ queryClient.setQueryData(+ queryKeys.admin.users({ filters, sort, pagination }),+ context?.previous+ );+ toast.error(+ err instanceof Error+ ? err.message+ : t("common.unbanError", { item: t("common.labels.user") })+ );+ },+ onSuccess: () => {+ toast.success(t("common.unbanned", { item: t("common.labels.user") }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: ["admin", "users"] });+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats });},- [t]- );-- /**- * Update user information- */- const updateUser = useCallback(- async (+ });++ // Delete user mutation+ const deleteMutation = useMutation({+ mutationFn: (userId: string) => deleteUserApi(userId, t),+ onMutate: async (userId) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.admin.users({ filters, sort, pagination }),+ });+ const previous = queryClient.getQueryData(+ queryKeys.admin.users({ filters, sort, pagination })+ );++ // Optimistic update+ queryClient.setQueryData(+ queryKeys.admin.users({ filters, sort, pagination }),+ (old: UsersListResponse | undefined) => {+ if (!old) return old;+ return {+ ...old,+ users: old.users.filter((user) => user.id !== userId),+ total: old.total - 1,+ };+ }+ );++ return { previous };+ },+ onError: (err, userId, context) => {+ queryClient.setQueryData(+ queryKeys.admin.users({ filters, sort, pagination }),+ context?.previous+ );+ toast.error(+ err instanceof Error+ ? err.message+ : t("common.deleteError", { item: t("common.labels.user") })+ );+ },+ onSuccess: () => {+ toast.success(t("common.deleted", { item: t("common.labels.user") }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: ["admin", "users"] });+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats });+ },+ });++ // Reset password mutation (no optimistic update needed)+ const resetPasswordMutation = useMutation({+ mutationFn: ({+ userId,+ newPassword,+ }: {+ userId: string;+ newPassword: string;+ }) => resetPasswordApi(userId, newPassword, t),+ onError: (err) => {+ toast.error(+ err instanceof Error ? err.message : t("common.passwordResetError")+ );+ },+ onSuccess: () => {+ toast.success(t("common.passwordReset"));+ },+ });++ return {+ // Data+ users: usersData?.users || [],+ total: usersData?.total || 0,+ page: usersData?.page || pagination.page,+ limit: usersData?.limit || pagination.limit,+ totalPages: usersData?.totalPages || 1,+ isLoading,+ error,++ // Functions+ refetch,+ fetchUserDetails: (userId: string) => fetchUserDetailsApi(userId, t),+ updateUser: async (userId: string,data: { name?: string; email?: string; role?: string }): Promise<boolean> => {try {- setIsLoading(true);-- const response = await fetch(`/api/admin/users/${userId}`, {- method: "PATCH",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(data),- });-- if (!response.ok) {- if (response.status === 403) {- throw new Error(t("admin.accessDenied"));- }- if (response.status === 404) {- throw new Error(t("admin.userNotFound"));- }- throw new Error(- t("common.updateError", { item: t("common.labels.user") })- );- }-- toast.success(t("common.updated", { item: t("common.labels.user") }));+ await updateMutation.mutateAsync({ userId, data });return true;- } catch (error) {- console.error("Failed to update user:", error);- toast.error(- error instanceof Error- ? error.message- : t("common.updateError", { item: t("common.labels.user") })- );+ } catch {return false;- } finally {- setIsLoading(false);}},- [t]- );-- /**- * Ban user- */- const banUser = useCallback(- async (+ banUser: async (userId: string,reason: string,expiresAt?: Date): Promise<boolean> => {try {- setIsLoading(true);-- const response = await fetch(`/api/admin/users/${userId}/ban`, {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- reason,- expiresAt: expiresAt?.toISOString(),- }),- });-- if (!response.ok) {- if (response.status === 403) {- throw new Error(t("admin.accessDenied"));- }- if (response.status === 404) {- throw new Error(t("admin.userNotFound"));- }- throw new Error(- t("common.banError", { item: t("common.labels.user") })- );- }-- toast.success(t("common.banned", { item: t("common.labels.user") }));+ await banMutation.mutateAsync({ userId, reason, expiresAt });return true;- } catch (error) {- console.error("Failed to ban user:", error);- toast.error(- error instanceof Error- ? error.message- : t("common.banError", { item: t("common.labels.user") })- );+ } catch {return false;- } finally {- setIsLoading(false);}},- [t]- );-- /**- * Unban user- */- const unbanUser = useCallback(- async (userId: string): Promise<boolean> => {+ unbanUser: async (userId: string): Promise<boolean> => {try {- setIsLoading(true);-- const response = await fetch(`/api/admin/users/${userId}/unban`, {- method: "POST",- headers: {- "Content-Type": "application/json",- },- });-- if (!response.ok) {- if (response.status === 403) {- throw new Error(t("admin.accessDenied"));- }- if (response.status === 404) {- throw new Error(t("admin.userNotFound"));- }- throw new Error(- t("common.unbanError", { item: t("common.labels.user") })- );- }-- toast.success(t("common.unbanned", { item: t("common.labels.user") }));+ await unbanMutation.mutateAsync(userId);return true;- } catch (error) {- console.error("Failed to unban user:", error);- toast.error(- error instanceof Error- ? error.message- : t("common.unbanError", { item: t("common.labels.user") })- );+ } catch {return false;- } finally {- setIsLoading(false);}},- [t]- );-- /**- * Delete user- */- const deleteUser = useCallback(- async (userId: string): Promise<boolean> => {+ deleteUser: async (userId: string): Promise<boolean> => {try {- setIsLoading(true);-- const response = await fetch(`/api/admin/users/${userId}`, {- method: "DELETE",- headers: {- "Content-Type": "application/json",- },- });-- if (!response.ok) {- if (response.status === 403) {- throw new Error(t("admin.accessDenied"));- }- if (response.status === 404) {- throw new Error(t("admin.userNotFound"));- }- throw new Error(- t("common.deleteError", { item: t("common.labels.user") })- );- }-- toast.success(t("common.deleted", { item: t("common.labels.user") }));+ await deleteMutation.mutateAsync(userId);return true;- } catch (error) {- console.error("Failed to delete user:", error);- toast.error(- error instanceof Error- ? error.message- : t("common.deleteError", { item: t("common.labels.user") })- );+ } catch {return false;- } finally {- setIsLoading(false);}},- [t]- );-- /**- * Reset user password- */- const resetPassword = useCallback(- async (userId: string, newPassword: string): Promise<boolean> => {+ resetPassword: async (+ userId: string,+ newPassword: string+ ): Promise<boolean> => {try {- setIsLoading(true);-- const response = await fetch(`/api/admin/users/${userId}/password`, {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({ password: newPassword }),- });-- if (!response.ok) {- if (response.status === 403) {- throw new Error(t("admin.accessDenied"));- }- if (response.status === 404) {- throw new Error(t("admin.userNotFound"));- }- throw new Error(t("common.passwordResetError"));- }-- toast.success(t("common.passwordReset"));+ await resetPasswordMutation.mutateAsync({ userId, newPassword });return true;- } catch (error) {- console.error("Failed to reset password:", error);- toast.error(- error instanceof Error- ? error.message- : t("common.passwordResetError")- );+ } catch {return false;- } finally {- setIsLoading(false);}},- [t]- );-- return {- isLoading,- fetchUsers,- fetchUserDetails,- updateUser,- banUser,- unbanUser,- deleteUser,- resetPassword,+ fetchUsers: async (+ searchFilters: UserFilters,+ searchSort: UserSort,+ searchPagination: Pagination+ ): Promise<UsersListResponse | null> => {+ try {+ return await fetchUsersApi(+ searchFilters,+ searchSort,+ searchPagination,+ t+ );+ } catch {+ return null;+ }+ },};}diff --git a/hooks/useAuditLogs.ts b/hooks/useAuditLogs.tsdeleted file mode 100644index fbc3542..0000000--- a/hooks/useAuditLogs.ts+++ /dev/null@@ -1,220 +0,0 @@-import { useState, useCallback } from "react";-import { toast } from "sonner";-import { useTranslations } from "next-intl";--/**- * Audit Log Types- */-export interface AuditLog {- id: string;- userId: string | null;- action: string;- resourceType: string | null;- resourceId: string | null;- metadata: unknown;- ipAddress: string | null;- userAgent: string | null;- severity: "info" | "warning" | "error" | "critical";- isUserVisible: boolean;- timestamp: string;- userName: string | null;- userEmail: string | null;- userImage: string | null;-}--export interface AuditLogFilters {- action?: string;- userId?: string;- resourceType?: string;- resourceId?: string;- severity?: "info" | "warning" | "error" | "critical";- search?: string;- startDate?: string;- endDate?: string;-}--export interface AuditLogSort {- sortBy?: "timestamp" | "action" | "severity" | "user" | "ipAddress";- sortOrder?: "asc" | "desc";-}--export interface AuditLogPagination {- limit?: number;- offset?: number;-}--export interface AuditLogsResponse {- logs: AuditLog[];- pagination: {- total: number;- limit: number;- offset: number;- hasMore: boolean;- };-}--/**- * Hook for managing audit logs (admin only)- *- * Provides functions to:- * - Fetch audit logs with filtering, sorting, and pagination- * - Delete logs by date range- * - Delete specific logs by IDs- * - Export logs (future feature)- */-export function useAuditLogs() {- const t = useTranslations();- const [isLoading, setIsLoading] = useState(false);-- /**- * Fetch audit logs with filters, sorting, and pagination- */- const fetchAuditLogs = useCallback(- async (- filters: AuditLogFilters = {},- sort: AuditLogSort = {},- pagination: AuditLogPagination = {}- ): Promise<AuditLogsResponse | null> => {- setIsLoading(true);-- try {- const params = new URLSearchParams();-- // Add filters- if (filters.action) params.append("action", filters.action);- if (filters.userId) params.append("userId", filters.userId);- if (filters.resourceType)- params.append("resourceType", filters.resourceType);- if (filters.resourceId) params.append("resourceId", filters.resourceId);- if (filters.severity) params.append("severity", filters.severity);- if (filters.search) params.append("search", filters.search);- if (filters.startDate) params.append("startDate", filters.startDate);- if (filters.endDate) params.append("endDate", filters.endDate);-- // Add sorting- if (sort.sortBy) params.append("sortBy", sort.sortBy);- if (sort.sortOrder) params.append("sortOrder", sort.sortOrder);-- // Add pagination- if (pagination.limit)- params.append("limit", pagination.limit.toString());- if (pagination.offset !== undefined)- params.append("offset", pagination.offset.toString());-- const response = await fetch(`/api/admin/audit-logs?${params}`, {- credentials: "include",- });-- if (!response.ok) {- const error = await response.json().catch(() => ({}));- throw new Error(error.error || "Failed to fetch audit logs");- }-- const data = await response.json();- return data;- } catch (error) {- console.error("[useAuditLogs] Fetch error:", error);- toast.error(- error instanceof Error- ? error.message- : t("admin.auditLogs.fetchError")- );- return null;- } finally {- setIsLoading(false);- }- },- [t]- );-- /**- * Delete audit logs older than a specific date- * (Superadmin only)- */- const deleteLogsByDate = useCallback(- async (beforeDate: string): Promise<boolean> => {- setIsLoading(true);-- try {- const response = await fetch(- `/api/admin/audit-logs?before=${encodeURIComponent(beforeDate)}`,- {- method: "DELETE",- credentials: "include",- }- );-- if (!response.ok) {- const error = await response.json().catch(() => ({}));- throw new Error(error.error || "Failed to delete audit logs");- }-- const data = await response.json();- toast.success(t("common.deletedCount", { count: data.deletedCount }));- return true;- } catch (error) {- console.error("[useAuditLogs] Delete by date error:", error);- toast.error(- error instanceof Error- ? error.message- : t("admin.auditLogs.deleteError")- );- return false;- } finally {- setIsLoading(false);- }- },- [t]- );-- /**- * Delete specific audit logs by IDs- * (Superadmin only)- */- const deleteLogsByIds = useCallback(- async (logIds: string[]): Promise<boolean> => {- if (logIds.length === 0) {- toast.error(t("admin.auditLogs.noLogsSelected"));- return false;- }-- setIsLoading(true);-- try {- const response = await fetch("/api/admin/audit-logs", {- method: "DELETE",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify({ logIds }),- });-- if (!response.ok) {- const error = await response.json().catch(() => ({}));- throw new Error(error.error || "Failed to delete audit logs");- }-- const data = await response.json();- toast.success(t("common.deletedCount", { count: data.deletedCount }));- return true;- } catch (error) {- console.error("[useAuditLogs] Delete by IDs error:", error);- toast.error(- error instanceof Error- ? error.message- : t("admin.auditLogs.deleteError")- );- return false;- } finally {- setIsLoading(false);- }- },- [t]- );-- return {- isLoading,- fetchAuditLogs,- deleteLogsByDate,- deleteLogsByIds,- };-}diff --git a/hooks/useCalendarShares.ts b/hooks/useCalendarShares.tsindex 1d85804..349bc04 100644--- a/hooks/useCalendarShares.ts+++ b/hooks/useCalendarShares.ts@@ -1,6 +1,10 @@+"use client";+import { useState, useCallback } from "react";+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { toast } from "sonner";import { useTranslations } from "next-intl";+import { queryKeys } from "@/lib/query-keys";export interface CalendarShare {id: string;@@ -29,120 +33,277 @@ export interface SearchUser {image: string | null;}+/**+ * Fetch calendar shares from API+ */+async function fetchSharesApi(calendarId: string): Promise<CalendarShare[]> {+ const response = await fetch(`/api/calendars/${calendarId}/shares`);++ if (!response.ok) {+ throw new Error("Failed to fetch shares");+ }++ const data = await response.json();++ // Parse date strings to Date objects+ return data.map((share: Record<string, unknown>) => ({+ ...share,+ createdAt: new Date(share.createdAt as string),+ }));+}++/**+ * Add a new share via API+ */+async function addShareApi(+ calendarId: string,+ userId: string,+ permission: "admin" | "write" | "read"+): Promise<CalendarShare> {+ const response = await fetch(`/api/calendars/${calendarId}/shares`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ userId, permission }),+ });++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.error || "Failed to add share");+ }++ const data = await response.json();++ return {+ ...data,+ createdAt: new Date(data.createdAt),+ };+}++/**+ * Update a share's permission via API+ */+async function updateShareApi(+ calendarId: string,+ shareId: string,+ permission: "admin" | "write" | "read"+): Promise<CalendarShare> {+ const response = await fetch(+ `/api/calendars/${calendarId}/shares/${shareId}`,+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ permission }),+ }+ );++ if (!response.ok) {+ throw new Error("Failed to update share");+ }++ const data = await response.json();++ return {+ ...data,+ createdAt: new Date(data.createdAt),+ };+}++/**+ * Remove a share via API+ */+async function removeShareApi(+ calendarId: string,+ shareId: string+): Promise<void> {+ const response = await fetch(+ `/api/calendars/${calendarId}/shares/${shareId}`,+ {+ method: "DELETE",+ }+ );++ if (!response.ok) {+ throw new Error("Failed to remove share");+ }+}++/**+ * Calendar Shares Hook+ *+ * Provides calendar share management with automatic polling.+ * Uses React Query for automatic cache management and live updates.+ *+ * Features:+ * - Fetch shares for a calendar+ * - Add, update, and remove shares+ * - Optimistic updates for instant UI feedback+ * - User search functionality (local state)+ * - Automatic polling every 5 seconds+ *+ * @param calendarId - Calendar ID to manage shares for+ * @returns Object with shares data and management functions+ */export function useCalendarShares(calendarId: string) {const t = useTranslations();- const [shares, setShares] = useState<CalendarShare[]>([]);- const [loading, setLoading] = useState(false);+ const queryClient = useQueryClient();++ // User search state (not server data)const [searchResults, setSearchResults] = useState<SearchUser[]>([]);const [searchLoading, setSearchLoading] = useState(false);- const fetchShares = useCallback(async () => {- if (!calendarId) return;+ // Fetch shares+ const { data: shares = [], isLoading: loading } = useQuery({+ queryKey: queryKeys.shares.byCalendar(calendarId),+ queryFn: () => fetchSharesApi(calendarId),+ enabled: !!calendarId,+ });- setLoading(true);- try {- const response = await fetch(`/api/calendars/${calendarId}/shares`);- if (!response.ok) {- throw new Error("Failed to fetch shares");- }- const data = await response.json();- setShares(data);- } catch (error) {- console.error("Failed to fetch shares:", error);- toast.error(t("common.fetchError", { item: t("common.labels.shares") }));- } finally {- setLoading(false);- }- }, [calendarId, t]);+ // Add share mutation+ const addShareMutation = useMutation({+ mutationFn: ({+ userId,+ permission,+ }: {+ userId: string;+ permission: "admin" | "write" | "read";+ }) => addShareApi(calendarId, userId, permission),+ onMutate: async ({ userId, permission }) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.shares.byCalendar(calendarId),+ });+ const previous = queryClient.getQueryData(+ queryKeys.shares.byCalendar(calendarId)+ );- const addShare = useCallback(- async (userId: string, permission: "admin" | "write" | "read") => {- try {- const response = await fetch(`/api/calendars/${calendarId}/shares`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ userId, permission }),- });+ // Optimistic update+ const optimisticShare: CalendarShare = {+ id: `temp-${Date.now()}`,+ calendarId,+ userId,+ permission,+ sharedBy: "current-user",+ createdAt: new Date(),+ user: {+ id: userId,+ name: null,+ email: "",+ image: null,+ },+ sharedByUser: {+ id: "current-user",+ name: null,+ email: "",+ },+ };- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || "Failed to add share");- }+ queryClient.setQueryData(+ queryKeys.shares.byCalendar(calendarId),+ (old: CalendarShare[] = []) => [optimisticShare, ...old]+ );- const newShare = await response.json();- setShares((prev) => [newShare, ...prev]);- toast.success(t("share.shareAdded"));- return { success: true };- } catch (error) {- console.error("Failed to add share:", error);- toast.error(- error instanceof Error- ? error.message- : t("common.createError", { item: t("share.share") })- );- return { success: false };- }+ return { previous };},- [calendarId, t]- );+ onError: (err, variables, context) => {+ queryClient.setQueryData(+ queryKeys.shares.byCalendar(calendarId),+ context?.previous+ );+ toast.error(+ err instanceof Error+ ? err.message+ : t("common.createError", { item: t("share.share") })+ );+ },+ onSuccess: () => {+ toast.success(t("share.shareAdded"));+ },+ onSettled: () => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.shares.byCalendar(calendarId),+ });+ },+ });- const updateShare = useCallback(- async (shareId: string, permission: "admin" | "write" | "read") => {- try {- const response = await fetch(- `/api/calendars/${calendarId}/shares/${shareId}`,- {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ permission }),- }- );+ // Update share mutation+ const updateShareMutation = useMutation({+ mutationFn: ({+ shareId,+ permission,+ }: {+ shareId: string;+ permission: "admin" | "write" | "read";+ }) => updateShareApi(calendarId, shareId, permission),+ onMutate: async ({ shareId, permission }) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.shares.byCalendar(calendarId),+ });+ const previous = queryClient.getQueryData(+ queryKeys.shares.byCalendar(calendarId)+ );- if (!response.ok) {- throw new Error("Failed to update share");- }+ // Optimistic update+ queryClient.setQueryData(+ queryKeys.shares.byCalendar(calendarId),+ (old: CalendarShare[] = []) =>+ old.map((s) => (s.id === shareId ? { ...s, permission } : s))+ );- const updatedShare = await response.json();- setShares((prev) =>- prev.map((s) => (s.id === shareId ? updatedShare : s))- );- toast.success(t("share.shareUpdated"));- return { success: true };- } catch (error) {- console.error("Failed to update share:", error);- toast.error(t("common.updateError", { item: t("share.share") }));- return { success: false };- }+ return { previous };},- [calendarId, t]- );+ onError: (err, variables, context) => {+ queryClient.setQueryData(+ queryKeys.shares.byCalendar(calendarId),+ context?.previous+ );+ toast.error(t("common.updateError", { item: t("share.share") }));+ },+ onSuccess: () => {+ toast.success(t("share.shareUpdated"));+ },+ onSettled: () => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.shares.byCalendar(calendarId),+ });+ },+ });- const removeShare = useCallback(- async (shareId: string) => {- try {- const response = await fetch(- `/api/calendars/${calendarId}/shares/${shareId}`,- {- method: "DELETE",- }- );+ // Remove share mutation+ const removeShareMutation = useMutation({+ mutationFn: (shareId: string) => removeShareApi(calendarId, shareId),+ onMutate: async (shareId) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.shares.byCalendar(calendarId),+ });+ const previous = queryClient.getQueryData(+ queryKeys.shares.byCalendar(calendarId)+ );- if (!response.ok) {- throw new Error("Failed to remove share");- }+ // Optimistic update+ queryClient.setQueryData(+ queryKeys.shares.byCalendar(calendarId),+ (old: CalendarShare[] = []) => old.filter((s) => s.id !== shareId)+ );- setShares((prev) => prev.filter((s) => s.id !== shareId));- toast.success(t("share.shareRemoved"));- return { success: true };- } catch (error) {- console.error("Failed to remove share:", error);- toast.error(t("common.deleteError", { item: t("share.share") }));- return { success: false };- }+ return { previous };},- [calendarId, t]- );+ onError: (err, shareId, context) => {+ queryClient.setQueryData(+ queryKeys.shares.byCalendar(calendarId),+ context?.previous+ );+ toast.error(t("common.deleteError", { item: t("share.share") }));+ },+ onSuccess: () => {+ toast.success(t("share.shareRemoved"));+ },+ onSettled: () => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.shares.byCalendar(calendarId),+ });+ },+ });+ // User search (local state, not server state)const searchUsers = useCallback(async (query: string) => {if (!query || query.length < 2) {@@ -179,10 +340,36 @@ export function useCalendarShares(calendarId: string) {loading,searchResults,searchLoading,- fetchShares,- addShare,- updateShare,- removeShare,+ addShare: async (+ userId: string,+ permission: "admin" | "write" | "read"+ ): Promise<{ success: boolean }> => {+ try {+ await addShareMutation.mutateAsync({ userId, permission });+ return { success: true };+ } catch {+ return { success: false };+ }+ },+ updateShare: async (+ shareId: string,+ permission: "admin" | "write" | "read"+ ): Promise<{ success: boolean }> => {+ try {+ await updateShareMutation.mutateAsync({ shareId, permission });+ return { success: true };+ } catch {+ return { success: false };+ }+ },+ removeShare: async (shareId: string): Promise<{ success: boolean }> => {+ try {+ await removeShareMutation.mutateAsync(shareId);+ return { success: true };+ } catch {+ return { success: false };+ }+ },searchUsers,};}diff --git a/hooks/useCalendarSubscriptions.ts b/hooks/useCalendarSubscriptions.tsindex 66dbfa4..7c54edd 100644--- a/hooks/useCalendarSubscriptions.ts+++ b/hooks/useCalendarSubscriptions.ts@@ -1,8 +1,10 @@"use client";-import { useState, useEffect, useCallback } from "react";+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { toast } from "sonner";import { useTranslations } from "next-intl";+import { queryKeys } from "@/lib/query-keys";+import { REFETCH_INTERVAL } from "@/lib/query-client";type CalendarSource = "guest" | "shared";@@ -38,195 +40,249 @@ type SubscriptionResponse = {};/**- * Hook for managing calendar subscriptions and dismissals+ * Fetch calendar subscriptions from API*/-export function useCalendarSubscriptions() {- const t = useTranslations();- const [availableCalendars, setAvailableCalendars] = useState<- AvailableCalendar[]- >([]);- const [dismissedCalendars, setDismissedCalendars] = useState<- DismissedCalendar[]- >([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);-- const fetchCalendars = useCallback(async () => {- setLoading(true);- setError(null);-- try {- const response = await fetch("/api/calendars/subscriptions");-- if (!response.ok) {- throw new Error("Failed to fetch calendars");- }+async function fetchSubscriptionsApi(): Promise<SubscriptionResponse> {+ const response = await fetch("/api/calendars/subscriptions");- const data: SubscriptionResponse = await response.json();- setAvailableCalendars(data.available);- setDismissedCalendars(data.dismissed);- } catch (err) {- const message =- err instanceof Error ? err.message : "Failed to load calendars";- setError(message);- toast.error(message);- } finally {- setLoading(false);- }- }, []);-- useEffect(() => {- fetchCalendars();- }, [fetchCalendars]);-- /**- * Subscribe to a public calendar or re-subscribe to a dismissed calendar- */- const subscribe = useCallback(- async (calendarId: string, calendarName: string) => {- // Find calendar in either list- const dismissedCal = dismissedCalendars.find(- (cal) => cal.id === calendarId- );- const availableCal = availableCalendars.find(- (cal) => cal.id === calendarId- );+ if (!response.ok) {+ throw new Error("Failed to fetch calendars");+ }- // Optimistic update: Remove from dismissed and add/update in available- if (dismissedCal) {- setDismissedCalendars((prev) =>- prev.filter((cal) => cal.id !== calendarId)- );- setAvailableCalendars((prev) => [- ...prev,- {- id: dismissedCal.id,- name: dismissedCal.name,- color: dismissedCal.color,- guestPermission: dismissedCal.permission,- permission: dismissedCal.permission, // Preserve original permission- owner: dismissedCal.owner,- source: dismissedCal.source,- isSubscribed: true,- },- ]);- } else if (availableCal) {- setAvailableCalendars((prev) =>- prev.map((cal) =>- cal.id === calendarId ? { ...cal, isSubscribed: true } : cal- )- );- }+ return await response.json();+}- try {- const response = await fetch("/api/calendars/subscriptions", {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({ calendarId }),- });-- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || "Failed to subscribe");- }+/**+ * Subscribe to a calendar via API+ */+async function subscribeApi(calendarId: string): Promise<void> {+ const response = await fetch("/api/calendars/subscriptions", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ calendarId }),+ });++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.error || "Failed to subscribe");+ }+}++/**+ * Dismiss/Unsubscribe from a calendar via API+ */+async function dismissApi(calendarId: string): Promise<void> {+ const response = await fetch(`/api/calendars/subscriptions/${calendarId}`, {+ method: "DELETE",+ });- toast.success(- t("calendar.subscriptionSuccess", { name: calendarName })- );+ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.error || "Failed to unsubscribe");+ }+}- // Dispatch custom event to trigger calendar list refresh- window.dispatchEvent(- new CustomEvent("calendar-list-change", {- detail: { action: "subscribe", calendarId },- })- );+/**+ * Calendar Subscriptions Hook+ *+ * Provides calendar subscription management with automatic polling.+ * Uses React Query for automatic cache management and live updates.+ *+ * Features:+ * - Fetch available and dismissed calendars+ * - Subscribe to public calendars+ * - Dismiss/unsubscribe from calendars+ * - Optimistic updates for instant UI feedback+ * - Automatic polling every 5 seconds+ * - Automatic cache invalidation (no window events needed!)+ *+ * @returns Object with calendar subscription data and management functions+ */+export function useCalendarSubscriptions() {+ const t = useTranslations();+ const queryClient = useQueryClient();- return true;- } catch (err) {- const message =- err instanceof Error ? err.message : "Failed to subscribe";- toast.error(message);+ // Fetch subscriptions+ const {+ data,+ isLoading: loading,+ error: errorMessage,+ } = useQuery({+ queryKey: queryKeys.subscriptions.all,+ queryFn: fetchSubscriptionsApi,+ refetchInterval: REFETCH_INTERVAL,+ });- // Revert optimistic update- await fetchCalendars();- return false;- }- },- [t, fetchCalendars, dismissedCalendars, availableCalendars]- );-- /**- * Dismiss/Unsubscribe from a calendar- */- const dismiss = useCallback(- async (calendarId: string, calendarName: string) => {- // Find calendar in available list- const calendar = availableCalendars.find((cal) => cal.id === calendarId);-- if (!calendar) return false;-- // Optimistic update: Remove from available and add to dismissed- setAvailableCalendars((prev) =>- prev.filter((cal) => cal.id !== calendarId)- );+ const availableCalendars = data?.available ?? [];+ const dismissedCalendars = data?.dismissed ?? [];- setDismissedCalendars((prev) => [- ...prev,- {- id: calendar.id,- name: calendar.name,- color: calendar.color,- permission: calendar.permission || calendar.guestPermission, // Use share permission if available, fallback to guest- owner: calendar.owner,- source: calendar.source,- },- ]);+ // Subscribe mutation+ const subscribeMutation = useMutation({+ mutationFn: (variables: { calendarId: string; name: string }) =>+ subscribeApi(variables.calendarId),+ onMutate: async (variables) => {+ const { calendarId } = variables;+ await queryClient.cancelQueries({+ queryKey: queryKeys.subscriptions.all,+ });+ const previous = queryClient.getQueryData(queryKeys.subscriptions.all);- try {- const response = await fetch(- `/api/calendars/subscriptions/${calendarId}`,- {- method: "DELETE",+ // Optimistic update+ queryClient.setQueryData(+ queryKeys.subscriptions.all,+ (old: SubscriptionResponse | undefined) => {+ if (!old) return old;++ const dismissedCal = old.dismissed.find(+ (cal) => cal.id === calendarId+ );+ const availableCal = old.available.find(+ (cal) => cal.id === calendarId+ );++ if (dismissedCal) {+ // Move from dismissed to available+ return {+ available: [+ ...old.available,+ {+ id: dismissedCal.id,+ name: dismissedCal.name,+ color: dismissedCal.color,+ guestPermission: dismissedCal.permission,+ permission: dismissedCal.permission,+ owner: dismissedCal.owner,+ source: dismissedCal.source,+ isSubscribed: true,+ },+ ],+ dismissed: old.dismissed.filter((cal) => cal.id !== calendarId),+ };+ } else if (availableCal) {+ // Mark as subscribed+ return {+ ...old,+ available: old.available.map((cal) =>+ cal.id === calendarId ? { ...cal, isSubscribed: true } : cal+ ),+ };}- );- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || "Failed to unsubscribe");+ return old;}+ );- toast.success(t("calendar.unsubscribeSuccess", { name: calendarName }));+ return { previous };+ },+ onError: (err, variables, context) => {+ queryClient.setQueryData(queryKeys.subscriptions.all, context?.previous);+ toast.error(err instanceof Error ? err.message : "Failed to subscribe");+ },+ onSuccess: (_, variables) => {+ toast.success(+ t("calendar.subscriptionSuccess", {+ name: variables.name || "Calendar",+ })+ );+ },+ onSettled: () => {+ // Invalidate both subscriptions and main calendar list+ queryClient.invalidateQueries({ queryKey: queryKeys.subscriptions.all });+ queryClient.invalidateQueries({ queryKey: queryKeys.calendars.all });+ },+ });- // Dispatch custom event to trigger calendar list refresh- window.dispatchEvent(- new CustomEvent("calendar-list-change", {- detail: { action: "dismiss", calendarId },- })- );+ // Dismiss mutation+ const dismissMutation = useMutation({+ mutationFn: dismissApi,+ onMutate: async (calendarId) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.subscriptions.all,+ });+ const previous = queryClient.getQueryData(queryKeys.subscriptions.all);- return true;- } catch (err) {- const message =- err instanceof Error ? err.message : "Failed to unsubscribe";- toast.error(message);+ // Optimistic update+ queryClient.setQueryData(+ queryKeys.subscriptions.all,+ (old: SubscriptionResponse | undefined) => {+ if (!old) return old;- // Revert optimistic update- await fetchCalendars();- return false;- }+ const calendar = old.available.find((cal) => cal.id === calendarId);+ if (!calendar) return old;++ return {+ available: old.available.filter((cal) => cal.id !== calendarId),+ dismissed: [+ ...old.dismissed,+ {+ id: calendar.id,+ name: calendar.name,+ color: calendar.color,+ permission: calendar.permission || calendar.guestPermission,+ owner: calendar.owner,+ source: calendar.source,+ },+ ],+ };+ }+ );++ return { previous };+ },+ onError: (err, calendarId, context) => {+ queryClient.setQueryData(queryKeys.subscriptions.all, context?.previous);+ toast.error(err instanceof Error ? err.message : "Failed to unsubscribe");},- [t, fetchCalendars, availableCalendars]- );+ onSuccess: (_, calendarId) => {+ const data = queryClient.getQueryData<SubscriptionResponse>(+ queryKeys.subscriptions.all+ );+ const calendar =+ data?.available.find((cal) => cal.id === calendarId) ||+ data?.dismissed.find((cal) => cal.id === calendarId);+ toast.success(+ t("calendar.unsubscribeSuccess", { name: calendar?.name || "Calendar" })+ );+ },+ onSettled: () => {+ // Invalidate both subscriptions and main calendar list+ queryClient.invalidateQueries({ queryKey: queryKeys.subscriptions.all });+ queryClient.invalidateQueries({ queryKey: queryKeys.calendars.all });+ },+ });return {availableCalendars,dismissedCalendars,loading,- error,- subscribe,- dismiss,- refetch: fetchCalendars,+ error: errorMessage ? errorMessage.message : null,+ subscribe: async (+ calendarId: string,+ calendarName: string+ ): Promise<boolean> => {+ try {+ await subscribeMutation.mutateAsync({ calendarId, name: calendarName });+ return true;+ } catch {+ return false;+ }+ },+ dismiss: async (+ calendarId: string,+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ _calendarName: string+ ): Promise<boolean> => {+ try {+ await dismissMutation.mutateAsync(calendarId);+ return true;+ } catch {+ return false;+ }+ },+ refetch: () => {+ queryClient.invalidateQueries({ queryKey: queryKeys.subscriptions.all });+ },};}diff --git a/hooks/useCalendarTokens.ts b/hooks/useCalendarTokens.tsindex e9ee211..a863776 100644--- a/hooks/useCalendarTokens.ts+++ b/hooks/useCalendarTokens.ts@@ -1,6 +1,11 @@-import { useState, useCallback } from "react";+"use client";++import { useCallback } from "react";+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { toast } from "sonner";import { useTranslations } from "next-intl";+import { queryKeys } from "@/lib/query-keys";+import { REFETCH_INTERVAL } from "@/lib/query-client";export interface CalendarAccessToken {id: string;@@ -22,170 +27,256 @@ export interface CreateTokenParams {expiresAt?: string | null;}-export interface UpdateTokenParams {- name?: string;- permission?: "read" | "write";- expiresAt?: string | null;- isActive?: boolean;-}--export function useCalendarTokens(calendarId: string | null) {- const [tokens, setTokens] = useState<CalendarAccessToken[]>([]);- const [isLoading, setIsLoading] = useState(false);- const [error, setError] = useState<string | null>(null);- const t = useTranslations();-- /**- * Fetch all tokens for calendar- */- const fetchTokens = useCallback(async () => {- if (!calendarId) {- setTokens([]);- return;+/**+ * Safe error extraction helper+ * Handles non-JSON responses gracefully+ */+async function parseErrorResponse(response: Response): Promise<string> {+ try {+ const text = await response.text();+ if (!text) {+ return response.statusText || `HTTP ${response.status}`;}-- setIsLoading(true);- setError(null);-try {- const response = await fetch(`/api/calendars/${calendarId}/tokens`);-- if (!response.ok) {- throw new Error(`HTTP ${response.status}`);- }-- const data = await response.json();- setTokens(data);+ const json = JSON.parse(text);+ return json.error || json.message || text;} catch {- const message = t("common.fetchError", { item: t("token.accessLinks") });- setError(message);- toast.error(message);- } finally {- setIsLoading(false);+ // Not JSON, return the text or fallback+ return text.includes("<")+ ? response.statusText || `HTTP ${response.status}`+ : text;}- }, [calendarId, t]);-- /**- * Create a new access token- * Returns full token (only time it's visible!)- */- const createToken = useCallback(- async (params: CreateTokenParams): Promise<CalendarAccessToken | null> => {- if (!calendarId) return null;-- try {- const response = await fetch(`/api/calendars/${calendarId}/tokens`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(params),- });-- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || `HTTP ${response.status}`);- }-- const newToken = await response.json();-- // Add to local state- setTokens((prev) => [newToken, ...prev]);-- toast.success(t("common.created", { item: t("token.accessLinks") }));-- return newToken; // Includes full token!- } catch (err) {- toast.error(- err instanceof Error- ? err.message- : t("common.createError", { item: t("token.accessLinks") })- );- return null;- }- },- [calendarId, t]- );-- /**- * Update an existing token- */- const updateToken = useCallback(- async (tokenId: string, updates: UpdateTokenParams): Promise<boolean> => {- if (!calendarId) return false;-- try {- const response = await fetch(- `/api/calendars/${calendarId}/tokens/${tokenId}`,- {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(updates),- }- );+ } catch {+ return response.statusText || `HTTP ${response.status}`;+ }+}- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || `HTTP ${response.status}`);- }+/**+ * Fetch calendar access tokens from API+ */+async function fetchTokensApi(+ calendarId: string+): Promise<CalendarAccessToken[]> {+ const response = await fetch(`/api/calendars/${calendarId}/tokens`);- const updatedToken = await response.json();+ if (!response.ok) {+ throw new Error(`HTTP ${response.status}`);+ }- // Update local state- setTokens((prev) =>- prev.map((token) => (token.id === tokenId ? updatedToken : token))- );+ return await response.json();+}- toast.success(t("common.updated", { item: t("token.accessLinks") }));+/**+ * Create a new access token via API+ * Returns full token (only time it's visible!)+ */+async function createTokenApi(+ calendarId: string,+ params: CreateTokenParams+): Promise<CalendarAccessToken> {+ const response = await fetch(`/api/calendars/${calendarId}/tokens`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(params),+ });++ if (!response.ok) {+ const errorMessage = await parseErrorResponse(response);+ throw new Error(errorMessage);+ }++ return await response.json();+}- return true;- } catch (err) {- toast.error(- err instanceof Error- ? err.message- : t("common.updateError", { item: t("token.accessLinks") })- );- return false;- }- },- [calendarId, t]+/**+ * Update a token via API+ */+async function updateTokenApi(+ calendarId: string,+ tokenId: string,+ updates: { isActive?: boolean }+): Promise<CalendarAccessToken> {+ const response = await fetch(+ `/api/calendars/${calendarId}/tokens/${tokenId}`,+ {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(updates),+ });- /**- * Delete (revoke) a token- */- const deleteToken = useCallback(- async (tokenId: string): Promise<boolean> => {- if (!calendarId) return false;+ if (!response.ok) {+ const errorMessage = await parseErrorResponse(response);+ throw new Error(errorMessage);+ }- try {- const response = await fetch(- `/api/calendars/${calendarId}/tokens/${tokenId}`,- {- method: "DELETE",- }- );+ return await response.json();+}- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || `HTTP ${response.status}`);- }+/**+ * Delete (revoke) a token via API+ */+async function deleteTokenApi(+ calendarId: string,+ tokenId: string+): Promise<void> {+ const response = await fetch(+ `/api/calendars/${calendarId}/tokens/${tokenId}`,+ {+ method: "DELETE",+ }+ );- // Remove from local state- setTokens((prev) => prev.filter((token) => token.id !== tokenId));+ if (!response.ok) {+ const errorMessage = await parseErrorResponse(response);+ throw new Error(errorMessage);+ }+}- toast.success(t("common.revoked", { item: t("token.accessLinks") }));+/**+ * Calendar Access Tokens Hook+ *+ * Provides calendar access token management with automatic polling.+ * Uses React Query for automatic cache management and live updates.+ *+ * Features:+ * - Fetch access tokens for a calendar+ * - Create new tokens (returns full token only once!)+ * - Delete (revoke) tokens+ * - Optimistic updates for instant UI feedback+ * - Automatic polling every 5 seconds+ * - Helper functions for share links+ *+ * Note: Token update and regenerate are not supported in the UI.+ *+ * @param calendarId - Calendar ID to manage tokens for+ * @returns Object with tokens data and management functions+ */+export function useCalendarTokens(calendarId: string | null) {+ const t = useTranslations();+ const queryClient = useQueryClient();- return true;- } catch (err) {- toast.error(- err instanceof Error- ? err.message- : t("common.revokeError", { item: t("token.accessLinks") })- );- return false;- }+ // Fetch tokens+ const {+ data: tokens = [],+ isLoading,+ error,+ } = useQuery({+ queryKey: queryKeys.tokens.byCalendar(calendarId!),+ queryFn: () => fetchTokensApi(calendarId!),+ enabled: !!calendarId,+ refetchInterval: REFETCH_INTERVAL,+ });++ // Create token mutation (NO optimistic update - need real token!)+ const createTokenMutation = useMutation({+ mutationFn: (params: CreateTokenParams) =>+ createTokenApi(calendarId!, params),+ onSuccess: () => {+ toast.success(t("common.created", { item: t("token.accessLinks") }));+ // Invalidate to refetch and get updated list+ queryClient.invalidateQueries({+ queryKey: queryKeys.tokens.byCalendar(calendarId!),+ });},- [calendarId, t]- );+ onError: (err) => {+ toast.error(+ err instanceof Error+ ? err.message+ : t("common.createError", { item: t("token.accessLinks") })+ );+ },+ });++ // Update token mutation+ const updateTokenMutation = useMutation({+ mutationFn: ({+ tokenId,+ updates,+ }: {+ tokenId: string;+ updates: { isActive?: boolean };+ }) => updateTokenApi(calendarId!, tokenId, updates),+ onMutate: async ({ tokenId, updates }) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.tokens.byCalendar(calendarId!),+ });+ const previous = queryClient.getQueryData(+ queryKeys.tokens.byCalendar(calendarId!)+ );++ // Optimistic update+ queryClient.setQueryData(+ queryKeys.tokens.byCalendar(calendarId!),+ (old: CalendarAccessToken[] = []) =>+ old.map((token) =>+ token.id === tokenId ? { ...token, ...updates } : token+ )+ );++ return { previous };+ },+ onError: (err, variables, context) => {+ queryClient.setQueryData(+ queryKeys.tokens.byCalendar(calendarId!),+ context?.previous+ );+ toast.error(+ err instanceof Error+ ? err.message+ : t("common.updateError", { item: t("token.accessLinks") })+ );+ },+ onSuccess: () => {+ toast.success(t("common.updated", { item: t("token.accessLinks") }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.tokens.byCalendar(calendarId!),+ });+ },+ });++ // Delete token mutation+ const deleteTokenMutation = useMutation({+ mutationFn: (tokenId: string) => deleteTokenApi(calendarId!, tokenId),+ onMutate: async (tokenId) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.tokens.byCalendar(calendarId!),+ });+ const previous = queryClient.getQueryData(+ queryKeys.tokens.byCalendar(calendarId!)+ );++ // Optimistic update+ queryClient.setQueryData(+ queryKeys.tokens.byCalendar(calendarId!),+ (old: CalendarAccessToken[] = []) =>+ old.filter((token) => token.id !== tokenId)+ );++ return { previous };+ },+ onError: (err, tokenId, context) => {+ queryClient.setQueryData(+ queryKeys.tokens.byCalendar(calendarId!),+ context?.previous+ );+ toast.error(+ err instanceof Error+ ? err.message+ : t("common.revokeError", { item: t("token.accessLinks") })+ );+ },+ onSuccess: () => {+ toast.success(t("common.revoked", { item: t("token.accessLinks") }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.tokens.byCalendar(calendarId!),+ });+ },+ });/*** Generate a shareable link from token@@ -219,10 +310,37 @@ export function useCalendarTokens(calendarId: string | null) {tokens,isLoading,error,- fetchTokens,- createToken,- updateToken,- deleteToken,+ createToken: async (+ params: CreateTokenParams+ ): Promise<CalendarAccessToken | null> => {+ if (!calendarId) return null;+ try {+ return await createTokenMutation.mutateAsync(params);+ } catch {+ return null;+ }+ },+ updateToken: async (+ tokenId: string,+ updates: { isActive?: boolean }+ ): Promise<boolean> => {+ if (!calendarId) return false;+ try {+ await updateTokenMutation.mutateAsync({ tokenId, updates });+ return true;+ } catch {+ return false;+ }+ },+ deleteToken: async (tokenId: string): Promise<boolean> => {+ if (!calendarId) return false;+ try {+ await deleteTokenMutation.mutateAsync(tokenId);+ return true;+ } catch {+ return false;+ }+ },getShareLink,copyShareLink,};diff --git a/hooks/useCalendars.ts b/hooks/useCalendars.tsindex a9f6f87..d6412ff 100644--- a/hooks/useCalendars.ts+++ b/hooks/useCalendars.ts@@ -1,4 +1,5 @@-import { useState, useEffect, useCallback, useRef } from "react";+import { useState, useEffect, useRef } from "react";+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { CalendarWithCount } from "@/lib/types";import { toast } from "sonner";import { useTranslations } from "next-intl";@@ -6,97 +7,333 @@ import {isRateLimitError,handleRateLimitError,} from "@/lib/rate-limit-client";+import { queryKeys } from "@/lib/query-keys";+import { REFETCH_INTERVAL } from "@/lib/query-client";++// API functions+async function fetchCalendarsApi(): Promise<CalendarWithCount[]> {+ const response = await fetch("/api/calendars");++ if (!response.ok) {+ throw new Error(`Failed to fetch calendars: ${response.statusText}`);+ }++ const data = await response.json();+ return Array.isArray(data) ? data : [];+}++// Custom error class for rate-limit errors+class RateLimitError extends Error {+ constructor(public response: Response) {+ super("Rate limit exceeded");+ this.name = "RateLimitError";+ }+}++async function createCalendarApi(+ name: string,+ color: string+): Promise<CalendarWithCount> {+ const response = await fetch("/api/calendars", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ name,+ color,+ guestPermission: "none",+ }),+ });++ // Check for rate-limit error first+ if (isRateLimitError(response)) {+ throw new RateLimitError(response);+ }++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(+ `Failed to create calendar: ${response.status} ${response.statusText} - ${errorText}`+ );+ }++ return response.json();+}++async function updateCalendarApi(+ calendarId: string,+ updates: {+ name?: string;+ color?: string;+ guestPermission?: "none" | "read" | "write";+ }+): Promise<CalendarWithCount> {+ const response = await fetch(`/api/calendars/${calendarId}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(updates),+ });++ // Check for rate-limit error first+ if (isRateLimitError(response)) {+ throw new RateLimitError(response);+ }++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(errorData.error || "Failed to update calendar");+ }++ return response.json();+}++async function deleteCalendarApi(calendarId: string): Promise<void> {+ const response = await fetch(`/api/calendars/${calendarId}`, {+ method: "DELETE",+ headers: { "Content-Type": "application/json" },+ });++ // Check for rate-limit error first+ if (isRateLimitError(response)) {+ throw new RateLimitError(response);+ }++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(+ `Failed to delete calendar: ${response.status} ${response.statusText} - ${errorText}`+ );+ }+}++// Context types for optimistic updates+interface CreateCalendarContext {+ previous: CalendarWithCount[] | undefined;+}++interface UpdateCalendarContext {+ previous: CalendarWithCount[] | undefined;+}++interface DeleteCalendarContext {+ previous: CalendarWithCount[] | undefined;+ previousSelected: string | undefined;+}export function useCalendars(initialCalendarId?: string | null) {const t = useTranslations();- const [calendars, setCalendars] = useState<CalendarWithCount[]>([]);+ const queryClient = useQueryClient();const [selectedCalendar, setSelectedCalendar] = useState<string | undefined>();- const [loading, setLoading] = useState(true);- const [hasLoadedOnce, setHasLoadedOnce] = useState(false);// Capture initialCalendarId on mount to prevent dependency changesconst initialCalendarIdRef = useRef(initialCalendarId);- const fetchCalendars = useCallback(async () => {- try {- const response = await fetch("/api/calendars");- const data = await response.json();-- // Ensure data is an array- const calendarsData = Array.isArray(data) ? data : [];- setCalendars(calendarsData);- setHasLoadedOnce(true);-- // Only auto-select on initial load- setSelectedCalendar((current) => {- // If a calendar is already selected and still exists, keep it- if (- current &&- calendarsData.some((cal: CalendarWithCount) => cal.id === current)- ) {- return current;- }- // Otherwise, try initialCalendarId or fallback to first calendar- if (- initialCalendarIdRef.current &&- calendarsData.some(- (cal: CalendarWithCount) => cal.id === initialCalendarIdRef.current- )- ) {- return initialCalendarIdRef.current;- } else if (calendarsData.length > 0) {- return calendarsData[0].id;- }- return undefined;- });- } catch (error) {- console.error("Failed to fetch calendars:", error);- setCalendars([]);- } finally {- setLoading(false);+ // Data fetching with React Query+ const {+ data: calendars = [],+ isLoading,+ isFetched,+ } = useQuery({+ queryKey: queryKeys.calendars.all,+ queryFn: fetchCalendarsApi,+ refetchInterval: REFETCH_INTERVAL,+ });++ // Auto-select calendar when data loads+ useEffect(() => {+ if (calendars.length > 0 && !selectedCalendar) {+ const initial = initialCalendarIdRef.current;+ const found = calendars.find((c) => c.id === initial);+ const initialId = found?.id || calendars[0].id;+ queueMicrotask(() => setSelectedCalendar(initialId));}- }, []);+ }, [calendars, selectedCalendar]);- const createCalendar = async (name: string, color: string) => {- try {- const response = await fetch("/api/calendars", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- name,- color,- guestPermission: "none", // Always default to "none" on creation- }),- });-- if (isRateLimitError(response)) {- await handleRateLimitError(response, t);+ // Create mutation with optimistic update+ const createMutation = useMutation<+ CalendarWithCount,+ Error,+ { name: string; color: string },+ CreateCalendarContext+ >({+ mutationFn: ({ name, color }) => createCalendarApi(name, color),+ onMutate: async ({ name, color }) => {+ await queryClient.cancelQueries({ queryKey: queryKeys.calendars.all });++ const previous = queryClient.getQueryData<CalendarWithCount[]>(+ queryKeys.calendars.all+ );++ const optimisticCalendar: CalendarWithCount = {+ id: `temp-${Date.now()}`,+ name,+ color,+ guestPermission: "none",+ ownerId: null,+ createdAt: new Date(),+ updatedAt: new Date(),+ _count: 0,+ };++ queryClient.setQueryData<CalendarWithCount[]>(+ queryKeys.calendars.all,+ (old = []) => [...old, optimisticCalendar]+ );++ // Auto-select new calendar+ setSelectedCalendar(optimisticCalendar.id);++ return { previous };+ },+ onError: (err, variables, context) => {+ if (context?.previous) {+ queryClient.setQueryData(queryKeys.calendars.all, context.previous);+ }+ // Skip duplicate notifications for rate limit errors (already handled by wrapper)+ if (err instanceof RateLimitError) {return;}+ console.error("Failed to create calendar:", err);+ toast.error(t("common.createError", { item: t("calendar.title") }));+ },+ onSuccess: (newCalendar) => {+ // Update selection with real ID+ setSelectedCalendar(newCalendar.id);+ toast.success(t("common.created", { item: t("calendar.title") }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: queryKeys.calendars.all });+ },+ });++ // Update mutation with optimistic update+ const updateMutation = useMutation<+ CalendarWithCount,+ Error,+ {+ calendarId: string;+ updates: {+ name?: string;+ color?: string;+ guestPermission?: "none" | "read" | "write";+ };+ },+ UpdateCalendarContext+ >({+ mutationFn: ({ calendarId, updates }) =>+ updateCalendarApi(calendarId, updates),+ onMutate: async ({ calendarId, updates }) => {+ await queryClient.cancelQueries({ queryKey: queryKeys.calendars.all });++ const previous = queryClient.getQueryData<CalendarWithCount[]>(+ queryKeys.calendars.all+ );++ queryClient.setQueryData<CalendarWithCount[]>(+ queryKeys.calendars.all,+ (old = []) =>+ old.map((cal) =>+ cal.id === calendarId ? { ...cal, ...updates } : cal+ )+ );- if (!response.ok) {- const errorText = await response.text();- console.error(- `Failed to create calendar: ${response.status} ${response.statusText}`,- errorText- );- toast.error(t("common.createError", { item: t("calendar.title") }));+ return { previous };+ },+ onError: (err, variables, context) => {+ if (context?.previous) {+ queryClient.setQueryData(queryKeys.calendars.all, context.previous);+ }+ // Skip duplicate notifications for rate limit errors (already handled by wrapper)+ if (err instanceof RateLimitError) {return;}+ console.error("Failed to update calendar:", err);+ const errorMessage =+ err instanceof Error+ ? err.message+ : t("common.updateError", { item: t("calendar.title") });+ toast.error(errorMessage);+ },+ onSuccess: () => {+ toast.success(t("common.updated", { item: t("calendar.title") }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: queryKeys.calendars.all });+ },+ });- const newCalendar = await response.json();- setCalendars((prev) => [...prev, newCalendar]);- setSelectedCalendar(newCalendar.id);+ // Delete mutation with optimistic update+ const deleteMutation = useMutation<+ void,+ Error,+ string,+ DeleteCalendarContext+ >({+ mutationFn: (calendarId) => deleteCalendarApi(calendarId),+ onMutate: async (calendarId) => {+ await queryClient.cancelQueries({ queryKey: queryKeys.calendars.all });- toast.success(t("common.created", { item: t("calendar.title") }));+ const previous = queryClient.getQueryData<CalendarWithCount[]>(+ queryKeys.calendars.all+ );+ const previousSelected = selectedCalendar;++ queryClient.setQueryData<CalendarWithCount[]>(+ queryKeys.calendars.all,+ (old = []) => {+ const remaining = old.filter((c) => c.id !== calendarId);++ // Update selected calendar if deleted+ if (selectedCalendar === calendarId) {+ setSelectedCalendar(+ remaining.length > 0 ? remaining[0].id : undefined+ );+ }++ return remaining;+ }+ );++ return { previous, previousSelected };+ },+ onError: (err, calendarId, context) => {+ if (context?.previous) {+ queryClient.setQueryData(queryKeys.calendars.all, context.previous);+ }+ if (context?.previousSelected) {+ setSelectedCalendar(context.previousSelected);+ }+ // Skip duplicate notifications for rate limit errors (already handled by wrapper)+ if (err instanceof RateLimitError) {+ return;+ }+ console.error("Failed to delete calendar:", err);+ toast.error(t("common.deleteError", { item: t("calendar.title") }));+ },+ onSuccess: () => {+ toast.success(t("common.deleted", { item: t("calendar.title") }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: queryKeys.calendars.all });+ },+ });++ // Wrapper for createCalendar to handle rate limiting+ const createCalendar = async (name: string, color: string) => {+ try {+ // Call mutation once - it handles optimistic updates, toasts, and cache invalidation+ await createMutation.mutateAsync({ name, color });} catch (error) {- console.error("Failed to create calendar:", error);- toast.error(t("common.createError", { item: t("calendar.title") }));+ // Handle rate-limit errors specifically+ if (error instanceof RateLimitError) {+ await handleRateLimitError(error.response, t);+ }+ // Other errors are already handled by createMutation's onError handler}};+ // Wrapper for updateCalendar to maintain original signatureconst updateCalendar = async (calendarId: string,updates: {@@ -106,134 +343,39 @@ export function useCalendars(initialCalendarId?: string | null) {}) => {try {- const response = await fetch(`/api/calendars/${calendarId}`, {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(updates),- });-- 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))- );-- toast.success(t("common.updated", { item: t("calendar.title") }));- return { success: true };+ return await updateMutation.mutateAsync({ calendarId, updates });} 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 };+ // Handle rate-limit errors specifically+ if (error instanceof RateLimitError) {+ await handleRateLimitError(error.response, t);+ }+ throw error;}};+ // Wrapper for deleteCalendar to maintain original signatureconst deleteCalendar = async (calendarId: string) => {try {- const response = await fetch(`/api/calendars/${calendarId}`, {- method: "DELETE",- headers: {- "Content-Type": "application/json",- },- });-- if (response.ok) {- setCalendars((prev) => {- const remainingCalendars = prev.filter((c) => c.id !== calendarId);-- if (selectedCalendar === calendarId) {- setSelectedCalendar(- remainingCalendars.length > 0- ? remainingCalendars[0].id- : undefined- );- }-- return remainingCalendars;- });-- toast.success(t("common.deleted", { item: t("calendar.title") }));- return true;- } else {- const errorText = await response.text();- console.error(- `Failed to delete calendar: ${response.status} ${response.statusText}`,- errorText- );- toast.error(t("common.deleteError", { item: t("calendar.title") }));- return false;- }+ return await deleteMutation.mutateAsync(calendarId);} catch (error) {- console.error("Failed to delete calendar:", error);- toast.error(t("common.deleteError", { item: t("calendar.title") }));+ // Handle rate-limit errors specifically+ if (error instanceof RateLimitError) {+ await handleRateLimitError(error.response, t);+ }+ throw error;}- return false;};- // Initial calendar fetch- useEffect(() => {- fetchCalendars();- }, [fetchCalendars]);-- // Listen for calendar subscription changes (SSE events + custom events)- useEffect(() => {- const handleCalendarChange = (event: Event) => {- const customEvent = event as CustomEvent;- const { type, action } = customEvent.detail || {};-- // Refetch calendars when subscriptions change- if (type === "calendar" && (action === "update" || action === "delete")) {- fetchCalendars();- }- };-- const handleCalendarListChange = () => {- // Triggered by calendar subscription/dismissal actions- fetchCalendars();- };-- // Listen to SSE calendar-change events- window.addEventListener("calendar-change" as never, handleCalendarChange);- // Listen to direct calendar list changes (subscriptions/dismissals)- window.addEventListener(- "calendar-list-change" as never,- handleCalendarListChange- );-- return () => {- window.removeEventListener(- "calendar-change" as never,- handleCalendarChange- );- window.removeEventListener(- "calendar-list-change" as never,- handleCalendarListChange- );- };- }, [fetchCalendars]);-return {calendars,selectedCalendar,setSelectedCalendar,- loading,- hasLoadedOnce,+ loading: isLoading,+ hasLoadedOnce: isFetched,createCalendar,updateCalendar,deleteCalendar,- refetchCalendars: fetchCalendars,+ refetchCalendars: () =>+ queryClient.invalidateQueries({ queryKey: queryKeys.calendars.all }),};}diff --git a/hooks/useCompareData.ts b/hooks/useCompareData.tsnew file mode 100644index 0000000..5ef6ad4--- /dev/null+++ b/hooks/useCompareData.ts@@ -0,0 +1,250 @@+"use client";++import { useMemo } from "react";+import { useQueries, useQueryClient, useMutation } from "@tanstack/react-query";+import { queryKeys } from "@/lib/query-keys";+import { ShiftWithCalendar } from "@/lib/types";+import { CalendarNote, ExternalSync, ShiftPreset } from "@/lib/db/schema";+import { normalizeShift } from "@/hooks/useShifts";+import { normalizeNote } from "@/hooks/useNotes";+import { ShiftFormData } from "@/components/shift-sheet";+import { toast } from "sonner";+import { useTranslations } from "next-intl";++// API functions+async function fetchShiftsApi(+ calendarId: string+): Promise<ShiftWithCalendar[]> {+ const response = await fetch(`/api/shifts?calendarId=${calendarId}`);+ if (!response.ok) return [];+ const data = await response.json();+ return data.map(normalizeShift);+}++async function fetchNotesApi(calendarId: string): Promise<CalendarNote[]> {+ const response = await fetch(`/api/notes?calendarId=${calendarId}`);+ if (!response.ok) return [];+ const data = await response.json();+ return data.map(normalizeNote);+}++async function fetchExternalSyncsApi(+ calendarId: string+): Promise<ExternalSync[]> {+ const response = await fetch(`/api/external-syncs?calendarId=${calendarId}`);+ if (!response.ok) return [];+ return await response.json();+}++async function fetchPresetsApi(calendarId: string): Promise<ShiftPreset[]> {+ const response = await fetch(`/api/presets?calendarId=${calendarId}`);+ if (!response.ok) return [];+ return await response.json();+}++async function createShiftApi(+ calendarId: string,+ formData: ShiftFormData+): Promise<ShiftWithCalendar> {+ const response = await fetch("/api/shifts", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ...formData, calendarId }),+ });++ if (!response.ok) {+ throw new Error("Failed to create shift");+ }++ const data = await response.json();+ return normalizeShift(data);+}++async function deleteShiftApi(shiftId: string): Promise<void> {+ const response = await fetch(`/api/shifts/${shiftId}`, {+ method: "DELETE",+ headers: { "Content-Type": "application/json" },+ });++ if (!response.ok) {+ throw new Error("Failed to delete shift");+ }+}++interface UseCompareDataOptions {+ calendarIds: string[];+ enabled: boolean;+}++/**+ * Hook for loading and managing Compare Mode data using React Query.+ * Uses useQueries to fetch data for multiple calendars in parallel.+ * All data is cached and shared with single-calendar views.+ */+export function useCompareData({+ calendarIds,+ enabled,+}: UseCompareDataOptions) {+ const t = useTranslations();+ const queryClient = useQueryClient();++ // Fetch shifts for all calendars+ const shiftsQueries = useQueries({+ queries: calendarIds.map((id) => ({+ queryKey: queryKeys.shifts.byCalendar(id),+ queryFn: () => fetchShiftsApi(id),+ enabled: enabled && !!id,+ })),+ });++ // Fetch notes for all calendars+ const notesQueries = useQueries({+ queries: calendarIds.map((id) => ({+ queryKey: queryKeys.notes.byCalendar(id),+ queryFn: () => fetchNotesApi(id),+ enabled: enabled && !!id,+ })),+ });++ // Fetch external syncs for all calendars+ const externalSyncsQueries = useQueries({+ queries: calendarIds.map((id) => ({+ queryKey: queryKeys.externalSyncs.byCalendar(id),+ queryFn: () => fetchExternalSyncsApi(id),+ enabled: enabled && !!id,+ })),+ });++ // Fetch presets for all calendars+ const presetsQueries = useQueries({+ queries: calendarIds.map((id) => ({+ queryKey: queryKeys.presets.byCalendar(id),+ queryFn: () => fetchPresetsApi(id),+ enabled: enabled && !!id,+ })),+ });++ // Build maps from query results+ // Extract data arrays to use as stable dependencies+ const shiftsDataArray = shiftsQueries.map((q) => q.data);+ const notesDataArray = notesQueries.map((q) => q.data);+ const externalSyncsDataArray = externalSyncsQueries.map((q) => q.data);+ const presetsDataArray = presetsQueries.map((q) => q.data);+ const presetsLoadingArray = presetsQueries.map((q) => q.isLoading);++ const shiftsMap = useMemo(() => {+ const map = new Map<string, ShiftWithCalendar[]>();+ calendarIds.forEach((id, index) => {+ map.set(id, shiftsDataArray[index] || []);+ });+ return map;+ }, [calendarIds, shiftsDataArray]);++ const notesMap = useMemo(() => {+ const map = new Map<string, CalendarNote[]>();+ calendarIds.forEach((id, index) => {+ map.set(id, notesDataArray[index] || []);+ });+ return map;+ }, [calendarIds, notesDataArray]);++ const externalSyncsMap = useMemo(() => {+ const map = new Map<string, ExternalSync[]>();+ calendarIds.forEach((id, index) => {+ map.set(id, externalSyncsDataArray[index] || []);+ });+ return map;+ }, [calendarIds, externalSyncsDataArray]);++ const presetsMap = useMemo(() => {+ const map = new Map<string, ShiftPreset[]>();+ calendarIds.forEach((id, index) => {+ map.set(id, presetsDataArray[index] || []);+ });+ return map;+ }, [calendarIds, presetsDataArray]);++ const presetsLoadingMap = useMemo(() => {+ const map = new Map<string, boolean>();+ calendarIds.forEach((id, index) => {+ map.set(id, presetsLoadingArray[index] || false);+ });+ return map;+ }, [calendarIds, presetsLoadingArray]);++ // Check if any data is still loading+ const isLoading =+ shiftsQueries.some((q) => q.isLoading) ||+ notesQueries.some((q) => q.isLoading) ||+ externalSyncsQueries.some((q) => q.isLoading) ||+ presetsQueries.some((q) => q.isLoading);++ // Create shift mutation (for toggle functionality)+ const createShiftMutation = useMutation({+ mutationFn: ({+ calendarId,+ formData,+ }: {+ calendarId: string;+ formData: ShiftFormData;+ }) => createShiftApi(calendarId, formData),+ onSuccess: (_, { calendarId }) => {+ toast.success(t("common.created", { item: t("shift.shift_one") }));+ queryClient.invalidateQueries({+ queryKey: queryKeys.shifts.byCalendar(calendarId),+ });+ },+ onError: () => {+ toast.error(t("common.createError", { item: t("shift.shift_one") }));+ },+ });++ // Delete shift mutation (for toggle functionality)+ const deleteShiftMutation = useMutation({+ mutationFn: ({ shiftId }: { calendarId: string; shiftId: string }) =>+ deleteShiftApi(shiftId),+ onSuccess: (_, { calendarId }) => {+ toast.success(t("common.deleted", { item: t("shift.shift_one") }));+ queryClient.invalidateQueries({+ queryKey: queryKeys.shifts.byCalendar(calendarId),+ });+ },+ onError: () => {+ toast.error(t("common.deleteError", { item: t("shift.shift_one") }));+ },+ });++ // Invalidate notes for a specific calendar (used after note mutations)+ const invalidateNotes = (calendarId: string) => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.notes.byCalendar(calendarId),+ });+ };++ // Invalidate presets for a specific calendar+ const invalidatePresets = (calendarId: string) => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.presets.byCalendar(calendarId),+ });+ };++ return {+ // Data maps+ shiftsMap,+ notesMap,+ externalSyncsMap,+ presetsMap,+ presetsLoadingMap,++ // Loading state+ isLoading,++ // Mutations+ createShift: createShiftMutation.mutateAsync,+ deleteShift: deleteShiftMutation.mutateAsync,++ // Invalidation helpers+ invalidateNotes,+ invalidatePresets,+ };+}diff --git a/hooks/useConnectionStatus.ts b/hooks/useConnectionStatus.tsnew file mode 100644index 0000000..67a79f4--- /dev/null+++ b/hooks/useConnectionStatus.ts@@ -0,0 +1,69 @@+"use client";++import { useEffect, useState, useRef } from "react";+import { onlineManager } from "@tanstack/react-query";+import { toast } from "sonner";+import { useTranslations } from "next-intl";++// Toast ID for persistent disconnect toast+const DISCONNECT_TOAST_ID = "connection-status-disconnected";++/**+ * Hook to track connection/polling status for React Query.+ * Shows toast notifications on status changes.+ * Returns true if the browser is online and React Query can poll.+ */+export function useConnectionStatus() {+ const t = useTranslations();+ const [isOnline, setIsOnline] = useState(() => onlineManager.isOnline());+ const hasInitialized = useRef(false);+ const previousOnline = useRef(isOnline);++ useEffect(() => {+ // Subscribe to online status changes from React Query+ const unsubscribe = onlineManager.subscribe((online) => {+ setIsOnline(online);+ });++ return () => {+ unsubscribe();+ };+ }, []);++ // Show toast notifications on status changes+ useEffect(() => {+ // Skip initial render - don't show toast on page load+ if (!hasInitialized.current) {+ hasInitialized.current = true;+ previousOnline.current = isOnline;+ return;+ }++ // Only show toast if status actually changed+ if (previousOnline.current === isOnline) {+ return;+ }++ previousOnline.current = isOnline;++ if (isOnline) {+ // Dismiss any existing disconnect toast+ toast.dismiss(DISCONNECT_TOAST_ID);+ // Show connected toast for a few seconds+ toast.success(t("sync.connected"), {+ duration: 3000,+ });+ } else {+ // Show permanent disconnect toast+ toast.error(t("sync.disconnected"), {+ id: DISCONNECT_TOAST_ID,+ duration: Infinity,+ });+ }+ }, [isOnline, t]);++ return {+ isOnline,+ isPolling: isOnline, // Polling works when online+ };+}diff --git a/hooks/useExternalSync.ts b/hooks/useExternalSync.tsindex 826930f..85c39ba 100644--- a/hooks/useExternalSync.ts+++ b/hooks/useExternalSync.ts@@ -1,72 +1,103 @@-import { useState, useEffect, useCallback } from "react";+"use client";++import { useMemo } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";import { ExternalSync, SyncLog } from "@/lib/db/schema";+import { queryKeys } from "@/lib/query-keys";+import { REFETCH_INTERVAL } from "@/lib/query-client";-export function useExternalSync(selectedCalendar: string | null) {- const [externalSyncs, setExternalSyncs] = useState<ExternalSync[]>([]);- const [hasSyncErrors, setHasSyncErrors] = useState(false);- const [syncLogRefreshTrigger, setSyncLogRefreshTrigger] = useState(0);+/**+ * Fetch external syncs from API+ */+async function fetchExternalSyncsApi(+ calendarId: string+): Promise<ExternalSync[]> {+ const params = new URLSearchParams({ calendarId });+ const response = await fetch(`/api/external-syncs?${params}`);- const fetchExternalSyncs = useCallback(async () => {- if (!selectedCalendar) {- setExternalSyncs([]);- setHasSyncErrors(false);- return;- }+ if (!response.ok) {+ throw new Error("Failed to fetch external syncs");+ }- try {- const params = new URLSearchParams({ calendarId: selectedCalendar });+ return await response.json();+}- const response = await fetch(`/api/external-syncs?${params}`);- if (response.ok) {- const data = await response.json();- setExternalSyncs(data);- }- } catch (error) {- console.error("Failed to fetch external syncs:", error);- }- }, [selectedCalendar]);+/**+ * Fetch sync logs from API+ */+async function fetchSyncLogsApi(calendarId: string): Promise<SyncLog[]> {+ const params = new URLSearchParams({+ calendarId,+ limit: "50",+ });- const fetchSyncErrorStatus = useCallback(async () => {- if (!selectedCalendar) {- setHasSyncErrors(false);- return;- }+ const response = await fetch(`/api/sync-logs?${params}`);- try {- const params = new URLSearchParams({- calendarId: selectedCalendar,- limit: "50",- });+ if (!response.ok) {+ throw new Error("Failed to fetch sync logs");+ }- const response = await fetch(`/api/sync-logs?${params}`);- if (response.ok) {- const logs: SyncLog[] = await response.json();- const hasErrors = logs.some(- (log: SyncLog) => log.status === "error" && !log.isRead- );- setHasSyncErrors(hasErrors);- }- } catch (error) {- console.error("Failed to fetch sync logs:", error);- }- }, [selectedCalendar]);+ return await response.json();+}- // Fetch syncs and error status when calendar changes- useEffect(() => {+/**+ * External Sync Hook+ *+ * Provides external calendar sync data with automatic polling.+ * Uses React Query for automatic cache management and live updates.+ *+ * Features:+ * - Fetch external syncs for a calendar+ * - Monitor sync error status from logs+ * - Automatic polling every 5 seconds+ * - Manual refetch available if needed+ *+ * @param selectedCalendar - Calendar ID to fetch syncs for+ * @returns Object with syncs data, error status, and loading state+ */+export function useExternalSync(selectedCalendar: string | null) {+ const queryClient = useQueryClient();++ // Fetch external syncs+ const { data: externalSyncs = [], isLoading: syncsLoading } = useQuery({+ queryKey: queryKeys.externalSyncs.byCalendar(selectedCalendar!),+ queryFn: () => fetchExternalSyncsApi(selectedCalendar!),+ enabled: !!selectedCalendar,+ refetchInterval: REFETCH_INTERVAL,+ refetchIntervalInBackground: true, // Continue polling in background+ });++ // Fetch sync logs+ const { data: syncLogs = [], isLoading: logsLoading } = useQuery({+ queryKey: queryKeys.externalSyncs.logs(selectedCalendar!),+ queryFn: () => fetchSyncLogsApi(selectedCalendar!),+ enabled: !!selectedCalendar,+ refetchInterval: REFETCH_INTERVAL,+ refetchIntervalInBackground: true, // Continue polling in background+ });++ // Compute error status from logs+ const hasSyncErrors = useMemo(+ () => syncLogs.some((log) => log.status === "error" && !log.isRead),+ [syncLogs]+ );++ // Combined refetch function+ const refetch = () => {if (selectedCalendar) {- const initializeData = async () => {- await Promise.all([fetchExternalSyncs(), fetchSyncErrorStatus()]);- };- initializeData();+ queryClient.invalidateQueries({+ queryKey: queryKeys.externalSyncs.byCalendar(selectedCalendar),+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.externalSyncs.logs(selectedCalendar),+ });}- }, [selectedCalendar, fetchExternalSyncs, fetchSyncErrorStatus]);+ };return {externalSyncs,hasSyncErrors,- syncLogRefreshTrigger,- setSyncLogRefreshTrigger,- fetchExternalSyncs,- fetchSyncErrorStatus,+ loading: syncsLoading || logsLoading,+ refetch,};}diff --git a/hooks/useNotes.ts b/hooks/useNotes.tsindex a2b1df3..524b038 100644--- a/hooks/useNotes.ts+++ b/hooks/useNotes.ts@@ -1,8 +1,9 @@-import { useState, useEffect, useCallback } from "react";+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { useTranslations } from "next-intl";import { CalendarNote } from "@/lib/db/schema";import { formatDateToLocal, parseLocalDate } from "@/lib/date-utils";import { toast } from "sonner";+import { queryKeys } from "@/lib/query-keys";// Helper to convert API response timestamps to Date objectsexport function normalizeNote(note: Record<string, unknown>): CalendarNote {@@ -20,176 +21,351 @@ export function normalizeNote(note: Record<string, unknown>): CalendarNote {};}+// Form data interface+export interface NoteFormData {+ date: string;+ note: string;+ type?: "note" | "event";+ color?: string;+ recurringPattern?: string;+ recurringInterval?: number;+}++// API functions+async function fetchNotesApi(calendarId: string): Promise<CalendarNote[]> {+ const params = new URLSearchParams({ calendarId });+ const response = await fetch(`/api/notes?${params}`);++ if (!response.ok) {+ throw new Error(`Failed to fetch notes: ${response.statusText}`);+ }++ const data = await response.json();+ return data.map(normalizeNote);+}++async function createNoteApi(+ calendarId: string,+ formData: NoteFormData+): Promise<CalendarNote> {+ const response = await fetch("/api/notes", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ...formData, calendarId }),+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(+ `Failed to create note: ${response.status} ${response.statusText} - ${errorText}`+ );+ }++ const data = await response.json();+ return normalizeNote(data);+}++async function updateNoteApi(+ id: string,+ formData: Omit<NoteFormData, "date">+): Promise<CalendarNote> {+ const response = await fetch(`/api/notes/${id}`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(formData),+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(+ `Failed to update note: ${response.status} ${response.statusText} - ${errorText}`+ );+ }++ const data = await response.json();+ return normalizeNote(data);+}++async function deleteNoteApi(id: string): Promise<void> {+ const response = await fetch(`/api/notes/${id}`, {+ method: "DELETE",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({}),+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(+ `Failed to delete note: ${response.status} ${response.statusText} - ${errorText}`+ );+ }+}++// Context types for optimistic updates+interface CreateNoteContext {+ previous: CalendarNote[] | undefined;+}++interface UpdateNoteContext {+ previous: CalendarNote[] | undefined;+}++interface DeleteNoteContext {+ previous: CalendarNote[] | undefined;+}+export function useNotes(calendarId: string | undefined) {const t = useTranslations();- const [notes, setNotes] = useState<CalendarNote[]>([]);-- const fetchNotes = useCallback(async () => {- if (!calendarId) return;-- try {- const params = new URLSearchParams({ calendarId });-- const response = await fetch(`/api/notes?${params}`);- if (!response.ok) {- // Only clear notes for unauthorized responses (locked calendar)- if (response.status === 401 || response.status === 403) {- setNotes([]);- } else {- // For other errors (server errors, etc.), log but don't clear existing notes- console.error(- `Failed to fetch notes: ${response.status} ${response.statusText}`- );- }- return;- }- const data = await response.json();- setNotes(data.map(normalizeNote));- } catch (error) {- // Network errors or other exceptions - don't clear existing notes- console.error("Failed to fetch notes:", error);- }- }, [calendarId]);-- const createNote = async (- noteText: string,- date: Date,- type?: "note" | "event",- color?: string,- recurringPattern?: string,- recurringInterval?: number- ) => {- if (!calendarId) return false;-- try {- const response = await fetch("/api/notes", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- calendarId: calendarId,- date: formatDateToLocal(date),- note: noteText,- type: type,- color: color,- recurringPattern: recurringPattern,- recurringInterval: recurringInterval,- }),+ const queryClient = useQueryClient();++ // Data fetching with React Query+ const {+ data: notes = [],+ isLoading,+ isFetched,+ } = useQuery({+ queryKey: queryKeys.notes.byCalendar(calendarId!),+ queryFn: () => fetchNotesApi(calendarId!),+ enabled: !!calendarId,+ });++ // Create mutation with optimistic update+ const createMutation = useMutation<+ CalendarNote,+ Error,+ NoteFormData,+ CreateNoteContext+ >({+ mutationFn: (formData) => createNoteApi(calendarId!, formData),+ onMutate: async (formData) => {+ // Cancel outgoing refetches+ await queryClient.cancelQueries({+ queryKey: queryKeys.notes.byCalendar(calendarId!),});- if (!response.ok) {- const errorText = await response.text();- console.error(- `Failed to create note: ${response.status} ${response.statusText}`,- errorText+ // Snapshot previous value+ const previous = queryClient.getQueryData<CalendarNote[]>(+ queryKeys.notes.byCalendar(calendarId!)+ );++ // Create optimistic note+ const optimisticNote: CalendarNote = {+ id: `temp-${Date.now()}`,+ date: parseLocalDate(formData.date),+ note: formData.note,+ type: formData.type || "note",+ color: formData.color ?? null,+ recurringPattern: formData.recurringPattern || "none",+ recurringInterval: formData.recurringInterval ?? null,+ calendarId: calendarId!,+ createdAt: new Date(),+ updatedAt: new Date(),+ };++ // Optimistically update cache+ queryClient.setQueryData<CalendarNote[]>(+ queryKeys.notes.byCalendar(calendarId!),+ (old = []) => [...old, optimisticNote]+ );++ return { previous };+ },+ onError: (err, formData, context) => {+ // Rollback on error+ if (context?.previous) {+ queryClient.setQueryData(+ queryKeys.notes.byCalendar(calendarId!),+ context.previous);- toast.error(t("common.createError", { item: t("note.note") }));- return false;}-- const newNote = await response.json();- setNotes((prev) => [...prev, newNote]);- const itemType = type === "event" ? t("note.typeEvent") : t("note.note");- toast.success(t("common.created", { item: itemType }));- return true;- } catch (error) {- console.error("Failed to create note:", error);- const itemType = type === "event" ? t("note.typeEvent") : t("note.note");+ console.error("Failed to create note:", err);+ const itemType =+ formData.type === "event" ? t("note.typeEvent") : t("note.note");toast.error(t("common.createError", { item: itemType }));- return false;- }- };+ },+ onSuccess: (data, formData) => {+ const itemType =+ formData.type === "event" ? t("note.typeEvent") : t("note.note");+ toast.success(t("common.created", { item: itemType }));+ },+ onSettled: () => {+ // Refetch to get real data from server+ queryClient.invalidateQueries({+ queryKey: queryKeys.notes.byCalendar(calendarId!),+ });+ },+ });- const updateNote = async (- noteId: string,- noteText: string,- type?: "note" | "event",- color?: string,- recurringPattern?: string,- recurringInterval?: number- ) => {- try {- const response = await fetch(`/api/notes/${noteId}`, {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- note: noteText,- type: type,- color: color,- recurringPattern: recurringPattern,- recurringInterval: recurringInterval,- }),+ // Update mutation with optimistic update+ const updateMutation = useMutation<+ CalendarNote,+ Error,+ { id: string; formData: Omit<NoteFormData, "date"> },+ UpdateNoteContext+ >({+ mutationFn: ({ id, formData }) => updateNoteApi(id, formData),+ onMutate: async ({ id, formData }) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.notes.byCalendar(calendarId!),});- if (!response.ok) {- const errorText = await response.text();- console.error(- `Failed to update note: ${response.status} ${response.statusText}`,- errorText+ const previous = queryClient.getQueryData<CalendarNote[]>(+ queryKeys.notes.byCalendar(calendarId!)+ );++ // Optimistically update+ queryClient.setQueryData<CalendarNote[]>(+ queryKeys.notes.byCalendar(calendarId!),+ (old = []) =>+ old.map((n) =>+ n.id === id+ ? {+ ...n,+ note: formData.note,+ type: formData.type || n.type,+ color: formData.color ?? n.color,+ recurringPattern:+ formData.recurringPattern ?? n.recurringPattern,+ recurringInterval:+ formData.recurringInterval ?? n.recurringInterval,+ updatedAt: new Date(),+ }+ : n+ )+ );++ return { previous };+ },+ onError: (err, variables, context) => {+ if (context?.previous) {+ queryClient.setQueryData(+ queryKeys.notes.byCalendar(calendarId!),+ context.previous);- toast.error(t("common.updateError", { item: t("note.note") }));- return false;}-- const updatedNote = await response.json();- setNotes((prev) => prev.map((n) => (n.id === noteId ? updatedNote : n)));- const itemType = type === "event" ? t("note.typeEvent") : t("note.note");- toast.success(t("common.updated", { item: itemType }));- return true;- } catch (error) {- console.error("Failed to update note:", error);- const itemType = type === "event" ? t("note.typeEvent") : t("note.note");+ console.error("Failed to update note:", err);+ const itemType =+ variables.formData.type === "event"+ ? t("note.typeEvent")+ : t("note.note");toast.error(t("common.updateError", { item: itemType }));- return false;- }- };+ },+ onSuccess: (data, variables) => {+ const itemType =+ variables.formData.type === "event"+ ? t("note.typeEvent")+ : t("note.note");+ toast.success(t("common.updated", { item: itemType }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.notes.byCalendar(calendarId!),+ });+ },+ });- const deleteNote = async (noteId: string) => {- try {- const response = await fetch(`/api/notes/${noteId}`, {- method: "DELETE",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({}),+ // Delete mutation with optimistic update+ const deleteMutation = useMutation<void, Error, string, DeleteNoteContext>({+ mutationFn: (id) => deleteNoteApi(id),+ onMutate: async (id) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.notes.byCalendar(calendarId!),});- if (!response.ok) {- const errorText = await response.text();- console.error(- `Failed to delete note: ${response.status} ${response.statusText}`,- errorText+ const previous = queryClient.getQueryData<CalendarNote[]>(+ queryKeys.notes.byCalendar(calendarId!)+ );++ // Optimistically remove+ queryClient.setQueryData<CalendarNote[]>(+ queryKeys.notes.byCalendar(calendarId!),+ (old = []) => old.filter((n) => n.id !== id)+ );++ return { previous };+ },+ onError: (err, id, context) => {+ if (context?.previous) {+ queryClient.setQueryData(+ queryKeys.notes.byCalendar(calendarId!),+ context.previous);- toast.error(t("common.deleteError", { item: t("note.note") }));- return false;}-- setNotes((prev) => prev.filter((n) => n.id !== noteId));- toast.success(t("common.deleted", { item: t("note.note") }));- return true;- } catch (error) {- console.error("Failed to delete note:", error);+ console.error("Failed to delete note:", err);toast.error(t("common.deleteError", { item: t("note.note") }));- return false;- }- };-- // Fetch notes when calendar changes-- useEffect(() => {- if (!calendarId) {- // Data fetching on mount/calendar change is a valid effect use case- // eslint-disable-next-line react-hooks/set-state-in-effect- setNotes([]);- return;- }- fetchNotes();- }, [calendarId, fetchNotes]);+ },+ onSuccess: () => {+ toast.success(t("common.deleted", { item: t("note.note") }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.notes.byCalendar(calendarId!),+ });+ },+ });+ // Return API-compatible interface with backward compatibilityreturn {notes,- createNote,- updateNote,- deleteNote,- refetchNotes: fetchNotes,+ loading: isLoading,+ hasLoadedOnce: isFetched,+ createNote: async (+ noteText: string,+ date: Date,+ type?: "note" | "event",+ color?: string,+ recurringPattern?: string,+ recurringInterval?: number+ ) => {+ try {+ await createMutation.mutateAsync({+ date: formatDateToLocal(date),+ note: noteText,+ type,+ color,+ recurringPattern,+ recurringInterval,+ });+ return true;+ } catch {+ return false;+ }+ },+ updateNote: async (+ noteId: string,+ noteText: string,+ type?: "note" | "event",+ color?: string,+ recurringPattern?: string,+ recurringInterval?: number+ ) => {+ try {+ await updateMutation.mutateAsync({+ id: noteId,+ formData: {+ note: noteText,+ type,+ color,+ recurringPattern,+ recurringInterval,+ },+ });+ return true;+ } catch {+ return false;+ }+ },+ deleteNote: async (noteId: string) => {+ try {+ await deleteMutation.mutateAsync(noteId);+ return true;+ } catch {+ return false;+ }+ },+ refetchNotes: () =>+ queryClient.invalidateQueries({+ queryKey: queryKeys.notes.byCalendar(calendarId!),+ }),};}diff --git a/hooks/usePresetManagement.ts b/hooks/usePresetManagement.tsdeleted file mode 100644index 8942b33..0000000--- a/hooks/usePresetManagement.ts+++ /dev/null@@ -1,156 +0,0 @@-import { useCallback } from "react";-import { toast } from "sonner";-import { useTranslations } from "next-intl";--interface PresetFormData {- title: string;- startTime: string;- endTime: string;- color: string;- notes: string;- isSecondary: boolean;- isAllDay: boolean;- hideFromStats: boolean;-}--interface UsePresetManagementOptions {- calendarId: string;- onSuccess: () => void;-}--export function usePresetManagement({- calendarId,- onSuccess,-}: UsePresetManagementOptions) {- const t = useTranslations();-- const createPreset = useCallback(- async (formData: PresetFormData) => {- try {- const response = await fetch("/api/presets", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- calendarId,- ...formData,- }),- });-- if (response.ok) {- onSuccess();- toast.success(t("common.created", { item: t("preset.preset") }));- return true;- } else {- const data = await response.json();- toast.error(- data.error || t("common.createError", { item: t("preset.preset") })- );- return false;- }- } catch (error) {- console.error("Failed to create preset:", error);- toast.error(t("common.createError", { item: t("preset.preset") }));- return false;- }- },- [calendarId, onSuccess, t]- );-- const updatePreset = useCallback(- async (presetId: string, formData: PresetFormData) => {- try {- const response = await fetch(`/api/presets/${presetId}`, {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- ...formData,- }),- });-- if (response.ok) {- onSuccess();- toast.success(t("common.updated", { item: t("preset.preset") }));- return true;- } else {- const data = await response.json();- toast.error(- data.error || t("common.updateError", { item: t("preset.preset") })- );- return false;- }- } catch (error) {- console.error("Failed to update preset:", error);- toast.error(t("common.updateError", { item: t("preset.preset") }));- return false;- }- },- [onSuccess, t]- );-- const deletePreset = useCallback(- async (presetId: string) => {- try {- const response = await fetch(`/api/presets/${presetId}`, {- method: "DELETE",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({}),- });-- if (response.ok) {- onSuccess();- toast.success(t("common.deleted", { item: t("preset.preset") }));- return true;- } else {- const data = await response.json();- toast.error(- data.error || t("common.deleteError", { item: t("preset.preset") })- );- return false;- }- } catch (error) {- console.error("Failed to delete preset:", error);- toast.error(t("common.deleteError", { item: t("preset.preset") }));- return false;- }- },- [onSuccess, t]- );-- const reorderPresets = useCallback(- async (presetOrders: Array<{ id: string; order: number }>) => {- try {- const response = await fetch("/api/presets/reorder", {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- calendarId,- presetOrders,- }),- });-- if (response.ok) {- onSuccess();- return true;- } else {- const data = await response.json();- toast.error(- data.error || t("common.updateError", { item: t("preset.preset") })- );- return false;- }- } catch (error) {- console.error("Failed to reorder presets:", error);- toast.error(t("common.updateError", { item: t("preset.preset") }));- return false;- }- },- [calendarId, onSuccess, t]- );-- return {- createPreset,- updatePreset,- deletePreset,- reorderPresets,- };-}diff --git a/hooks/usePresets.ts b/hooks/usePresets.tsindex e477c0a..e3a9868 100644--- a/hooks/usePresets.ts+++ b/hooks/usePresets.ts@@ -1,59 +1,348 @@-import { useState, useEffect, useCallback } from "react";+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";+import { useTranslations } from "next-intl";import { ShiftPreset } from "@/lib/db/schema";+import { toast } from "sonner";+import { queryKeys } from "@/lib/query-keys";+// Form data interface+export interface PresetFormData {+ title: string;+ startTime: string;+ endTime: string;+ color: string;+ notes: string;+ isSecondary: boolean;+ isAllDay: boolean;+ hideFromStats: boolean;+}++// API functions+async function fetchPresetsApi(calendarId: string): Promise<ShiftPreset[]> {+ const params = new URLSearchParams({ calendarId });+ const response = await fetch(`/api/presets?${params}`);++ if (!response.ok) {+ throw new Error(`Failed to fetch presets: ${response.statusText}`);+ }++ return await response.json();+}++async function createPresetApi(+ calendarId: string,+ formData: PresetFormData+): Promise<ShiftPreset> {+ const response = await fetch("/api/presets", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ...formData, calendarId }),+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.error || "Failed to create preset");+ }++ return await response.json();+}++async function updatePresetApi(+ presetId: string,+ formData: PresetFormData+): Promise<ShiftPreset> {+ const response = await fetch(`/api/presets/${presetId}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(formData),+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.error || "Failed to update preset");+ }++ return await response.json();+}++async function deletePresetApi(presetId: string): Promise<void> {+ const response = await fetch(`/api/presets/${presetId}`, {+ method: "DELETE",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({}),+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.error || "Failed to delete preset");+ }+}++async function reorderPresetsApi(+ calendarId: string,+ presetOrders: Array<{ id: string; order: number }>+): Promise<void> {+ const response = await fetch("/api/presets/reorder", {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ calendarId, presetOrders }),+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.error || "Failed to reorder presets");+ }+}++// Helper to create optimistic preset+function createOptimisticPreset(+ calendarId: string,+ formData: PresetFormData+): ShiftPreset {+ return {+ id: `temp-${Date.now()}`,+ calendarId,+ title: formData.title,+ startTime: formData.startTime,+ endTime: formData.endTime,+ color: formData.color,+ notes: formData.notes,+ isSecondary: formData.isSecondary,+ isAllDay: formData.isAllDay,+ hideFromStats: formData.hideFromStats,+ order: 999, // Will be corrected by server+ createdAt: new Date(),+ updatedAt: new Date(),+ };+}++// Main hookexport function usePresets(calendarId: string | undefined) {- const [presets, setPresets] = useState<ShiftPreset[]>([]);- const [loading, setLoading] = useState(true);- const [hasLoadedOnce, setHasLoadedOnce] = useState(false);-- const fetchPresets = useCallback(- async (silent = false) => {- if (!calendarId) {- setPresets([]);- setLoading(false);- return;- }+ const queryClient = useQueryClient();+ const t = useTranslations();- if (!silent) {- setLoading(true);- }- try {- const params = new URLSearchParams({ calendarId });+ // Query for fetching presets+ const {+ data: presets = [],+ isLoading,+ isFetched,+ } = useQuery({+ queryKey: queryKeys.presets.byCalendar(calendarId!),+ queryFn: () => fetchPresetsApi(calendarId!),+ enabled: !!calendarId,+ });- const response = await fetch(`/api/presets?${params}`);- if (!response.ok) {- setPresets([]);- setLoading(false);- return;- }- const data = await response.json();- setPresets(data);- setHasLoadedOnce(true);- } catch (error) {- console.error("Failed to fetch presets:", error);- setPresets([]);- } finally {- if (!silent) {- setLoading(false);- }- }+ // Create preset mutation+ const createMutation = useMutation({+ mutationFn: (formData: PresetFormData) =>+ createPresetApi(calendarId!, formData),+ onMutate: async (formData) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.presets.byCalendar(calendarId!),+ });+ const previous = queryClient.getQueryData(+ queryKeys.presets.byCalendar(calendarId!)+ );+ const optimisticPreset = createOptimisticPreset(calendarId!, formData);+ queryClient.setQueryData(+ queryKeys.presets.byCalendar(calendarId!),+ (old: ShiftPreset[] = []) => [...old, optimisticPreset]+ );+ return { previous };},- [calendarId]- );+ onError: (error, formData, context) => {+ queryClient.setQueryData(+ queryKeys.presets.byCalendar(calendarId!),+ context?.previous+ );+ toast.error(+ error instanceof Error+ ? error.message+ : t("common.createError", { item: t("preset.preset") })+ );+ },+ onSuccess: () => {+ toast.success(t("common.created", { item: t("preset.preset") }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.presets.byCalendar(calendarId!),+ });+ },+ });++ // Update preset mutation+ const updateMutation = useMutation({+ mutationFn: ({+ presetId,+ formData,+ }: {+ presetId: string;+ formData: PresetFormData;+ }) => updatePresetApi(presetId, formData),+ onMutate: async ({ presetId, formData }) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.presets.byCalendar(calendarId!),+ });+ const previous = queryClient.getQueryData(+ queryKeys.presets.byCalendar(calendarId!)+ );+ queryClient.setQueryData(+ queryKeys.presets.byCalendar(calendarId!),+ (old: ShiftPreset[] = []) =>+ old.map((p) =>+ p.id === presetId+ ? {+ ...p,+ ...formData,+ updatedAt: new Date(),+ }+ : p+ )+ );+ return { previous };+ },+ onError: (error, variables, context) => {+ queryClient.setQueryData(+ queryKeys.presets.byCalendar(calendarId!),+ context?.previous+ );+ toast.error(+ error instanceof Error+ ? error.message+ : t("common.updateError", { item: t("preset.preset") })+ );+ },+ onSuccess: () => {+ toast.success(t("common.updated", { item: t("preset.preset") }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.presets.byCalendar(calendarId!),+ });+ },+ });- useEffect(() => {- if (calendarId) {- fetchPresets();- } else {- setPresets([]);- setLoading(false);- }- }, [calendarId, fetchPresets]);+ // Delete preset mutation+ const deleteMutation = useMutation({+ mutationFn: (presetId: string) => deletePresetApi(presetId),+ onMutate: async (presetId) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.presets.byCalendar(calendarId!),+ });+ const previous = queryClient.getQueryData(+ queryKeys.presets.byCalendar(calendarId!)+ );+ queryClient.setQueryData(+ queryKeys.presets.byCalendar(calendarId!),+ (old: ShiftPreset[] = []) => old.filter((p) => p.id !== presetId)+ );+ return { previous };+ },+ onError: (error, presetId, context) => {+ queryClient.setQueryData(+ queryKeys.presets.byCalendar(calendarId!),+ context?.previous+ );+ toast.error(+ error instanceof Error+ ? error.message+ : t("common.deleteError", { item: t("preset.preset") })+ );+ },+ onSuccess: () => {+ toast.success(t("common.deleted", { item: t("preset.preset") }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.presets.byCalendar(calendarId!),+ });+ },+ });++ // Reorder presets mutation+ const reorderMutation = useMutation({+ mutationFn: (presetOrders: Array<{ id: string; order: number }>) =>+ reorderPresetsApi(calendarId!, presetOrders),+ onMutate: async (presetOrders) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.presets.byCalendar(calendarId!),+ });+ const previous = queryClient.getQueryData(+ queryKeys.presets.byCalendar(calendarId!)+ );+ // Optimistically reorder+ queryClient.setQueryData(+ queryKeys.presets.byCalendar(calendarId!),+ (old: ShiftPreset[] = []) => {+ const orderMap = new Map(presetOrders.map((po) => [po.id, po.order]));+ return [...old].sort((a, b) => {+ const orderA = orderMap.get(a.id) ?? a.order;+ const orderB = orderMap.get(b.id) ?? b.order;+ return orderA - orderB;+ });+ }+ );+ return { previous };+ },+ onError: (error, variables, context) => {+ queryClient.setQueryData(+ queryKeys.presets.byCalendar(calendarId!),+ context?.previous+ );+ toast.error(+ error instanceof Error+ ? error.message+ : t("common.updateError", { item: t("preset.preset") })+ );+ },+ onSettled: () => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.presets.byCalendar(calendarId!),+ });+ },+ });+ // Return interfacereturn {+ // Datapresets,- loading,- hasLoadedOnce,- refetchPresets: fetchPresets,+ loading: isLoading,+ hasLoadedOnce: isFetched,++ // Mutations+ createPreset: async (formData: PresetFormData) => {+ try {+ await createMutation.mutateAsync(formData);+ return true;+ } catch {+ return false;+ }+ },+ updatePreset: async (presetId: string, formData: PresetFormData) => {+ try {+ await updateMutation.mutateAsync({ presetId, formData });+ return true;+ } catch {+ return false;+ }+ },+ deletePreset: async (presetId: string) => {+ try {+ await deleteMutation.mutateAsync(presetId);+ return true;+ } catch {+ return false;+ }+ },+ reorderPresets: async (+ presetOrders: Array<{ id: string; order: number }>+ ) => {+ try {+ await reorderMutation.mutateAsync(presetOrders);+ return true;+ } catch {+ return false;+ }+ },};}diff --git a/hooks/useSSEConnection.ts b/hooks/useSSEConnection.tsdeleted file mode 100644index 06c4a20..0000000--- a/hooks/useSSEConnection.ts+++ /dev/null@@ -1,302 +0,0 @@-import { useEffect, useRef } from "react";-import { toast } from "sonner";-import { useTranslations } from "next-intl";-import {- isRateLimitError,- handleRateLimitError,-} from "@/lib/rate-limit-client";--interface SSEConnectionOptions {- calendarId: string | undefined;- onShiftUpdate: () => void;- onPresetUpdate: () => void;- onNoteUpdate: () => void;- onStatsRefresh: () => void;- onSyncLogUpdate?: () => void;- onCalendarUpdate?: () => void;- isConnected: boolean;- setIsConnected: (connected: boolean) => void;-}--export function useSSEConnection({- calendarId,- onShiftUpdate,- onPresetUpdate,- onNoteUpdate,- onStatsRefresh,- onSyncLogUpdate,- onCalendarUpdate,- setIsConnected,-}: SSEConnectionOptions) {- const t = useTranslations();- const eventSourceRef = useRef<EventSource | null>(null);- const lastSyncTimeRef = useRef<number>(0);- const disconnectTimeRef = useRef<number | null>(null);- const errorTimeoutRef = useRef<NodeJS.Timeout | null>(null);- const resyncTimeoutRef = useRef<NodeJS.Timeout | null>(null);-- // Initialize lastSyncTimeRef on mount- useEffect(() => {- if (lastSyncTimeRef.current === 0) {- lastSyncTimeRef.current = Date.now();- }- }, []);-- // Refs to avoid stale closures in SSE handlers- const shiftUpdateRef = useRef(onShiftUpdate);- const presetUpdateRef = useRef(onPresetUpdate);- const noteUpdateRef = useRef(onNoteUpdate);- const statsRefreshRef = useRef(onStatsRefresh);- const syncLogUpdateRef = useRef(onSyncLogUpdate);- const calendarUpdateRef = useRef(onCalendarUpdate);- const setIsConnectedRef = useRef(setIsConnected);- const tRef = useRef(t);-- // Update refs when callbacks or translations change- useEffect(() => {- shiftUpdateRef.current = onShiftUpdate;- presetUpdateRef.current = onPresetUpdate;- noteUpdateRef.current = onNoteUpdate;- statsRefreshRef.current = onStatsRefresh;- syncLogUpdateRef.current = onSyncLogUpdate;- calendarUpdateRef.current = onCalendarUpdate;- setIsConnectedRef.current = setIsConnected;- tRef.current = t;- }, [- onShiftUpdate,- onPresetUpdate,- onNoteUpdate,- onStatsRefresh,- onSyncLogUpdate,- onCalendarUpdate,- setIsConnected,- t,- ]);-- // Handle page visibility changes- useEffect(() => {- const handleVisibilityChange = () => {- if (document.visibilityState === "visible" && calendarId) {- const now = Date.now();- const timeSinceLastSync = now - lastSyncTimeRef.current;-- if (timeSinceLastSync > 30000 || disconnectTimeRef.current) {- console.log("Tab became visible, resyncing data...");- toast.info(tRef.current("sync.refreshing"), { duration: Infinity });- shiftUpdateRef.current();- presetUpdateRef.current();- noteUpdateRef.current();- statsRefreshRef.current();- calendarUpdateRef.current?.();- lastSyncTimeRef.current = now;- disconnectTimeRef.current = null;- setTimeout(() => toast.dismiss(), 1000);- }- }- };-- const handleOnline = () => {- console.log("Network connection restored");- toast.dismiss();- toast.success(tRef.current("sync.reconnected"));- setIsConnectedRef.current(true);- if (calendarId) {- shiftUpdateRef.current();- presetUpdateRef.current();- noteUpdateRef.current();- statsRefreshRef.current();- lastSyncTimeRef.current = Date.now();- disconnectTimeRef.current = null;- }- };-- const handleOffline = () => {- console.log("Network connection lost");- toast.error(tRef.current("sync.offline"), { duration: Infinity });- setIsConnectedRef.current(false);- disconnectTimeRef.current = Date.now();- };-- document.addEventListener("visibilitychange", handleVisibilityChange);- window.addEventListener("online", handleOnline);- window.addEventListener("offline", handleOffline);-- return () => {- document.removeEventListener("visibilitychange", handleVisibilityChange);- window.removeEventListener("online", handleOnline);- window.removeEventListener("offline", handleOffline);- };- }, [calendarId]);-- // Setup SSE connection- useEffect(() => {- if (!calendarId) {- if (eventSourceRef.current) {- eventSourceRef.current.close();- }- return;- }-- if (eventSourceRef.current) {- eventSourceRef.current.close();- }-- // Test connection first to check for rate limiting- const testConnection = async () => {- try {- const response = await fetch(- `/api/events/stream?calendarId=${calendarId}`,- {- method: "HEAD", // Just check headers, don't establish connection yet- }- );-- // Check for rate limit before establishing SSE connection- if (isRateLimitError(response)) {- await handleRateLimitError(response, t);- setIsConnectedRef.current(false);- return false;- }-- return true;- } catch {- // If HEAD fails, try regular connection anyway- return true;- }- };-- testConnection().then((canConnect) => {- if (!canConnect) return;-- const eventSource = new EventSource(- `/api/events/stream?calendarId=${calendarId}`- );-- eventSource.onopen = () => {- setIsConnectedRef.current(true);- toast.dismiss();-- if (disconnectTimeRef.current) {- const disconnectDuration = Date.now() - disconnectTimeRef.current;- if (disconnectDuration > 10000) {- console.log("Reconnected after long disconnect, resyncing...");- toast.info(tRef.current("sync.resyncing"), { duration: Infinity });- shiftUpdateRef.current();- presetUpdateRef.current();- noteUpdateRef.current();- statsRefreshRef.current();- }- disconnectTimeRef.current = null;- }- lastSyncTimeRef.current = Date.now();- };-- eventSource.onmessage = (event) => {- try {- const data = JSON.parse(event.data);-- if (data.type === "connected") {- console.log("SSE connected for calendar:", data.calendarId);- return;- }-- if (data.type === "shift") {- shiftUpdateRef.current();- statsRefreshRef.current();- } else if (data.type === "preset") {- presetUpdateRef.current();- } else if (data.type === "note") {- noteUpdateRef.current();- } else if (data.type === "calendar") {- calendarUpdateRef.current?.();- } else if (data.type === "sync-log") {- syncLogUpdateRef.current?.();- }-- lastSyncTimeRef.current = Date.now();- } catch (error) {- console.error("Error parsing SSE message:", error);- }- };-- eventSource.onerror = (error) => {- console.error("SSE connection error:", error);- setIsConnectedRef.current(false);- disconnectTimeRef.current = Date.now();-- // Check if error is due to rate limiting- // EventSource doesn't provide status codes, but we can detect it by rapid reconnection failures- const timeSinceStart = Date.now() - lastSyncTimeRef.current;- if (timeSinceStart < 5000) {- // Connection failed within 5 seconds - likely rate limited- fetch(`/api/events/stream?calendarId=${calendarId}`, {- method: "HEAD",- }).then(async (response) => {- if (isRateLimitError(response)) {- await handleRateLimitError(response, t);- // Close the EventSource to prevent auto-reconnect- eventSource.close();- return;- }- });- }-- // Clear any existing timeouts- if (errorTimeoutRef.current) {- clearTimeout(errorTimeoutRef.current);- errorTimeoutRef.current = null;- }- if (resyncTimeoutRef.current) {- clearTimeout(resyncTimeoutRef.current);- resyncTimeoutRef.current = null;- }-- // Show error toast after delay if offline- errorTimeoutRef.current = setTimeout(() => {- if (!navigator.onLine) {- toast.error(tRef.current("sync.disconnected"), {- duration: Infinity,- });- }- errorTimeoutRef.current = null;- }, 5000);-- // Attempt resync after delay (EventSource will auto-reconnect)- resyncTimeoutRef.current = setTimeout(() => {- if (errorTimeoutRef.current) {- clearTimeout(errorTimeoutRef.current);- errorTimeoutRef.current = null;- }- if (calendarId && navigator.onLine) {- console.log("Attempting to resync data...");- shiftUpdateRef.current();- presetUpdateRef.current();- noteUpdateRef.current();- }- resyncTimeoutRef.current = null;- }, 3000);- };-- eventSourceRef.current = eventSource;-- return () => {- // Clear all timeouts on cleanup- if (errorTimeoutRef.current) {- clearTimeout(errorTimeoutRef.current);- errorTimeoutRef.current = null;- }- if (resyncTimeoutRef.current) {- clearTimeout(resyncTimeoutRef.current);- resyncTimeoutRef.current = null;- }- // Close EventSource on unmount or calendarId change- eventSource.close();- };- }); // End of testConnection().then()- }, [calendarId, t]);-- return {- lastSyncTimeRef,- disconnectTimeRef,- };-}diff --git a/hooks/useShiftActions.ts b/hooks/useShiftActions.tsindex 1b86ec8..8b71f71 100644--- a/hooks/useShiftActions.ts+++ b/hooks/useShiftActions.ts@@ -1,6 +1,4 @@import { useState, useCallback, useRef, useEffect } from "react";-import { toast } from "sonner";-import { useTranslations } from "next-intl";import { isSameDay } from "date-fns";import { ShiftFormData } from "@/components/shift-sheet";import { ShiftWithCalendar } from "@/lib/types";@@ -9,24 +7,18 @@ import { formatDateToLocal, parseLocalDate } from "@/lib/date-utils";interface UseShiftActionsProps {shifts: ShiftWithCalendar[];- setShifts: (shifts: ShiftWithCalendar[]) => void;presets: ShiftPreset[];- createShift: (data: ShiftFormData) => Promise<ShiftWithCalendar | null>;- updateShift: (id: string, data: ShiftFormData) => Promise<boolean>;- deleteShift: (id: string) => Promise<boolean>;- onStatsRefresh: () => void;+ createShift: (data: ShiftFormData) => Promise<ShiftWithCalendar>;+ deleteShift: (id: string) => Promise<void>;+ onStatsRefresh?: () => void;}export function useShiftActions({shifts,- setShifts,presets,createShift,- updateShift,deleteShift,- onStatsRefresh,}: UseShiftActionsProps) {- const t = useTranslations();const [togglingDates, setTogglingDates] = useState<Set<string>>(new Set());const togglingDatesRef = useRef(togglingDates);@@ -38,35 +30,23 @@ export function useShiftActions({const handleShiftSubmit = useCallback(async (formData: ShiftFormData) => {try {- const result = await createShift(formData);- if (result) {- onStatsRefresh();- }+ await createShift(formData);} catch (error) {console.error("Failed to create shift:", error);}},- [createShift, onStatsRefresh]- );-- const handleUpdateShift = useCallback(- async (id: string, formData: ShiftFormData) => {- const success = await updateShift(id, formData);- if (success) {- onStatsRefresh();- }- },- [updateShift, onStatsRefresh]+ [createShift]);const handleDeleteShift = useCallback(async (id: string) => {- const success = await deleteShift(id);- if (success) {- onStatsRefresh();+ try {+ await deleteShift(id);+ } catch (error) {+ console.error("Failed to delete shift:", error);}},- [deleteShift, onStatsRefresh]+ [deleteShift]);const handleAddShift = useCallback(@@ -97,37 +77,10 @@ export function useShiftActions({);if (existingShift) {- const previousShifts = [...shifts];- setShifts(shifts.filter((s) => s.id !== existingShift.id));- onStatsRefresh();-try {- const response = await fetch(`/api/shifts/${existingShift.id}`, {- method: "DELETE",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({}),- });-- if (!response.ok) {- setShifts(previousShifts);- onStatsRefresh();- toast.error(- t("common.deleteError", { item: t("shift.shift_one") })- );- } else {- toast.success(- t("common.deleted", { item: t("shift.shift_one") })- );- }+ await deleteShift(existingShift.id);} catch (error) {console.error("Failed to delete shift:", error);- setShifts(previousShifts);- onStatsRefresh();- toast.error(- t("common.deleteError", { item: t("shift.shift_one") })- );}} else {const shiftData: ShiftFormData = {@@ -141,9 +94,10 @@ export function useShiftActions({isAllDay: preset.isAllDay || false,};- const newShift = await createShift(shiftData);- if (newShift) {- onStatsRefresh();+ try {+ await createShift(shiftData);+ } catch (error) {+ console.error("Failed to create shift:", error);}}} finally {@@ -154,13 +108,12 @@ export function useShiftActions({});}},- [shifts, setShifts, presets, createShift, onStatsRefresh, t]+ [shifts, presets, createShift, deleteShift]);return {togglingDates,handleShiftSubmit,- handleUpdateShift,handleDeleteShift,handleAddShift,};diff --git a/hooks/useShiftForm.ts b/hooks/useShiftForm.tsindex e1ed1fe..2b6df12 100644--- a/hooks/useShiftForm.ts+++ b/hooks/useShiftForm.ts@@ -33,44 +33,26 @@ export function useShiftForm({isAllDay: false,});- const { presets, refetchPresets } = usePresets(calendarId);+ const { presets, createPreset } = usePresets(calendarId);const [saveAsPreset, setSaveAsPreset] = useState(false);const [presetName, setPresetName] = useState("");const saveAsPresetHandler = async (shiftData: ShiftFormData) => {if (!presetName.trim() || !calendarId) return false;- try {- const response = await fetch("/api/presets", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- calendarId,- title: presetName,- startTime: shiftData.startTime,- endTime: shiftData.endTime,- color: shiftData.color,- notes: shiftData.notes,- isAllDay: shiftData.isAllDay,- }),- });-- if (!response.ok) {- const errorText = await response.text();- console.error(- `Failed to save preset: ${response.status} ${response.statusText}`,- errorText- );- return false;- }+ // Use the new createPreset mutation from usePresets+ const success = await createPreset({+ title: presetName,+ startTime: shiftData.startTime,+ endTime: shiftData.endTime,+ color: shiftData.color || "#3b82f6",+ notes: shiftData.notes || "",+ isAllDay: shiftData.isAllDay || false,+ isSecondary: false,+ hideFromStats: false,+ });- await response.json();- await refetchPresets();- return true;- } catch (error) {- console.error("Failed to save preset:", error);- return false;- }+ return success;};const applyPreset = (preset: ShiftPreset) => {@@ -153,6 +135,5 @@ export function useShiftForm({applyPreset,saveAsPresetHandler,resetForm,- refetchPresets,};}diff --git a/hooks/useShiftStats.ts b/hooks/useShiftStats.tsindex 97a3038..45d62cc 100644--- a/hooks/useShiftStats.ts+++ b/hooks/useShiftStats.ts@@ -1,4 +1,9 @@-import { useState, useEffect, useCallback, useRef } from "react";+"use client";++import { useQuery } from "@tanstack/react-query";+import { queryKeys } from "@/lib/query-keys";+import { REFETCH_INTERVAL } from "@/lib/query-client";+import { formatDateToLocal } from "@/lib/date-utils";export interface ShiftStatsData {period: string;@@ -20,62 +25,70 @@ interface UseShiftStatsOptions {calendarId: string | undefined;currentDate: Date;period: "week" | "month" | "year";- refreshTrigger?: number;}+/**+ * Fetch shift statistics from API+ */+async function fetchShiftStatsApi(+ calendarId: string,+ period: string,+ currentDate: Date+): Promise<ShiftStatsData> {+ const params = new URLSearchParams({+ calendarId,+ period,+ date: formatDateToLocal(currentDate),+ });++ const response = await fetch(`/api/shifts/stats?${params}`);++ if (!response.ok) {+ throw new Error("Failed to fetch shift statistics");+ }++ return await response.json();+}++/**+ * Shift Statistics Hook+ *+ * Provides shift statistics for a calendar with automatic polling.+ * Uses React Query for automatic cache management and live updates.+ *+ * Features:+ * - Automatic polling every 5 seconds+ * - Statistics by calendar, period, and date+ * - Manual refetch available if needed+ *+ * @param calendarId - Calendar ID to fetch stats for+ * @param currentDate - Current date for stats calculation+ * @param period - Time period (week, month, year)+ * @returns Object with stats data and loading state+ */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 params = new URLSearchParams({- calendarId,- period,- date: currentDate.toISOString(),- });-- const response = await fetch(`/api/shifts/stats?${params}`);- if (!response.ok) {- return;- }- 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 {+ data: stats = null,+ isLoading: loading,+ refetch,+ } = useQuery({+ queryKey: queryKeys.stats.shifts(+ calendarId!,+ period,+ formatDateToLocal(currentDate)+ ),+ queryFn: () => fetchShiftStatsApi(calendarId!, period, currentDate),+ enabled: !!calendarId,+ refetchInterval: REFETCH_INTERVAL,+ });return {stats,loading,- refetch: fetchStats,+ refetch,};}diff --git a/hooks/useShifts.ts b/hooks/useShifts.tsindex 96ac6f0..150ad1f 100644--- a/hooks/useShifts.ts+++ b/hooks/useShifts.ts@@ -1,9 +1,10 @@-import { useState, useEffect, useCallback } from "react";+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { ShiftWithCalendar } from "@/lib/types";import { ShiftFormData } from "@/components/shift-sheet";import { toast } from "sonner";import { useTranslations } from "next-intl";import { parseLocalDate } from "@/lib/date-utils";+import { queryKeys } from "@/lib/query-keys";// Helper to convert API response timestamps to Date objectsexport function normalizeShift(@@ -23,174 +24,227 @@ export function normalizeShift(};}-export function useShifts(calendarId: string | undefined) {- const t = useTranslations();- const [shifts, setShifts] = useState<ShiftWithCalendar[]>([]);- const [loading, setLoading] = useState(false);- const [hasLoadedOnce, setHasLoadedOnce] = useState(false);+// API functions+async function fetchShiftsApi(+ calendarId: string+): Promise<ShiftWithCalendar[]> {+ const params = new URLSearchParams({ calendarId });+ const response = await fetch(`/api/shifts?${params}`);- const fetchShifts = useCallback(- async (showLoading = true) => {- if (!calendarId) return;+ if (!response.ok) {+ throw new Error(`Failed to fetch shifts: ${response.statusText}`);+ }- if (showLoading) {- setLoading(true);- }- try {- const params = new URLSearchParams({ calendarId });-- const response = await fetch(`/api/shifts?${params}`);- if (!response.ok) {- setShifts([]);- return;- }- const data = await response.json();- setShifts(data.map(normalizeShift));- setHasLoadedOnce(true);- } catch (error) {- console.error("Failed to fetch shifts:", error);- setShifts([]);- } finally {- if (showLoading) {- setLoading(false);- }- }- },- [calendarId]- );-- const createShift = async (formData: ShiftFormData) => {- if (!calendarId) return null;-- const tempId = `temp-${Date.now()}`;- const optimisticShift: ShiftWithCalendar = {- id: tempId,- date: parseLocalDate(formData.date),- startTime: formData.startTime,- endTime: formData.endTime,- title: formData.title,- color: formData.color || "#000000",- notes: formData.notes || null,- isAllDay: formData.isAllDay || false,- calendarId: calendarId,- createdAt: new Date(),- updatedAt: new Date(),- };-- setShifts((prev) => [...prev, optimisticShift]);-- try {- const response = await fetch("/api/shifts", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- ...formData,- calendarId: calendarId,- }),- });+ const data = await response.json();+ return data.map(normalizeShift);+}- if (!response.ok) {- const errorText = await response.text();- console.error(- `Failed to create shift: ${response.status} ${response.statusText}`,- errorText- );- setShifts((shifts) => shifts.filter((s) => s.id !== tempId));- toast.error(t("common.createError", { item: t("shift.shift_one") }));- return null;- }+async function createShiftApi(+ calendarId: string,+ formData: ShiftFormData+): Promise<ShiftWithCalendar> {+ const response = await fetch("/api/shifts", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ...formData, calendarId }),+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(+ `Failed to create shift: ${response.status} ${response.statusText} - ${errorText}`+ );+ }++ const data = await response.json();+ return normalizeShift(data);+}- const newShift = await response.json();- setShifts((shifts) =>- shifts.map((s) => (s.id === tempId ? normalizeShift(newShift) : s))- );- toast.success(t("common.created", { item: t("shift.shift_one") }));- return normalizeShift(newShift);- } catch (error) {- console.error("Failed to create shift:", error);- setShifts((shifts) => shifts.filter((s) => s.id !== tempId));- toast.error(t("common.createError", { item: t("shift.shift_one") }));- return null;- }- };+async function deleteShiftApi(id: string): Promise<void> {+ const response = await fetch(`/api/shifts/${id}`, {+ method: "DELETE",+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(+ `Failed to delete shift: ${response.status} ${response.statusText} - ${errorText}`+ );+ }+}- const updateShift = async (id: string, formData: ShiftFormData) => {- try {- const response = await fetch(`/api/shifts/${id}`, {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ ...formData }),+// Context type for optimistic updates+interface CreateShiftContext {+ previous: ShiftWithCalendar[] | undefined;+}++interface DeleteShiftContext {+ previous: ShiftWithCalendar[] | undefined;+}++export function useShifts(calendarId: string | undefined) {+ const t = useTranslations();+ const queryClient = useQueryClient();++ // Data fetching with React Query+ const {+ data: shifts = [],+ isLoading,+ isFetched,+ } = useQuery({+ queryKey: queryKeys.shifts.byCalendar(calendarId!),+ queryFn: () => fetchShiftsApi(calendarId!),+ enabled: !!calendarId,+ });++ // Create mutation with optimistic update+ const createMutation = useMutation<+ ShiftWithCalendar,+ Error,+ ShiftFormData,+ CreateShiftContext+ >({+ mutationFn: (formData) => createShiftApi(calendarId!, formData),+ onMutate: async (formData) => {+ // Cancel outgoing refetches+ await queryClient.cancelQueries({+ queryKey: queryKeys.shifts.byCalendar(calendarId!),});- if (!response.ok) {- const errorText = await response.text();- console.error(- `Failed to update shift: ${response.status} ${response.statusText}`,- errorText+ // Snapshot previous value+ const previous = queryClient.getQueryData<ShiftWithCalendar[]>(+ queryKeys.shifts.byCalendar(calendarId!)+ );++ // Create optimistic shift+ const optimisticShift: ShiftWithCalendar = {+ id: `temp-${Date.now()}`,+ date: parseLocalDate(formData.date),+ startTime: formData.startTime,+ endTime: formData.endTime,+ title: formData.title,+ color: formData.color || "#3b82f6",+ notes: formData.notes || null,+ isAllDay: formData.isAllDay || false,+ presetId: formData.presetId || null,+ calendarId: calendarId!,+ createdAt: new Date(),+ updatedAt: new Date(),+ };++ // Optimistically update cache+ queryClient.setQueryData<ShiftWithCalendar[]>(+ queryKeys.shifts.byCalendar(calendarId!),+ (old = []) => [...old, optimisticShift]+ );++ return { previous };+ },+ onError: (err, formData, context) => {+ // Rollback on error+ if (context?.previous) {+ queryClient.setQueryData(+ queryKeys.shifts.byCalendar(calendarId!),+ context.previous);- toast.error(t("common.updateError", { item: t("shift.shift_one") }));- return false;}+ console.error("Failed to create shift:", err);+ toast.error(t("common.createError", { item: t("shift.shift_one") }));+ },+ onSuccess: () => {+ toast.success(t("common.created", { item: t("shift.shift_one") }));+ },+ onSettled: () => {+ // Refetch to get real data from server+ queryClient.invalidateQueries({+ queryKey: queryKeys.shifts.byCalendar(calendarId!),+ });+ },+ });++ // Delete mutation with optimistic update+ const deleteMutation = useMutation<void, Error, string, DeleteShiftContext>({+ mutationFn: (id) => deleteShiftApi(id),+ onMutate: async (id) => {+ await queryClient.cancelQueries({+ queryKey: queryKeys.shifts.byCalendar(calendarId!),+ });- const updatedShift = await response.json();- setShifts((prev) => prev.map((s) => (s.id === id ? updatedShift : s)));- toast.success(t("common.updated", { item: t("shift.shift_one") }));- return true;- } catch (error) {- console.error("Failed to update shift:", error);- toast.error(t("common.updateError", { item: t("shift.shift_one") }));- return false;- }- };+ const previous = queryClient.getQueryData<ShiftWithCalendar[]>(+ queryKeys.shifts.byCalendar(calendarId!)+ );- const deleteShift = async (id: string) => {- try {- const response = await fetch(`/api/shifts/${id}`, {- method: "DELETE",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({}),- });+ // Optimistically remove+ queryClient.setQueryData<ShiftWithCalendar[]>(+ queryKeys.shifts.byCalendar(calendarId!),+ (old = []) => old.filter((s) => s.id !== id)+ );- if (!response.ok) {- const errorText = await response.text();- console.error(- `Failed to delete shift: ${response.status} ${response.statusText}`,- errorText+ return { previous };+ },+ onError: (err, id, context) => {+ if (context?.previous) {+ queryClient.setQueryData(+ queryKeys.shifts.byCalendar(calendarId!),+ context.previous);- toast.error(t("common.deleteError", { item: t("shift.shift_one") }));- return false;}-- setShifts((prev) => prev.filter((s) => s.id !== id));- toast.success(t("common.deleted", { item: t("shift.shift_one") }));- return true;- } catch (error) {- console.error("Failed to delete shift:", error);+ console.error("Failed to delete shift:", err);toast.error(t("common.deleteError", { item: t("shift.shift_one") }));- return false;- }- };-- // Fetch shifts when calendar changes-- useEffect(() => {- if (!calendarId) {- setShifts([]);- return;- }- fetchShifts();- }, [calendarId, fetchShifts]);+ },+ onSuccess: () => {+ toast.success(t("common.deleted", { item: t("shift.shift_one") }));+ },+ onSettled: () => {+ queryClient.invalidateQueries({+ queryKey: queryKeys.shifts.byCalendar(calendarId!),+ });+ },+ });+ // Return API-compatible interfacereturn {shifts,- setShifts,- loading,- hasLoadedOnce,- createShift,- updateShift,- deleteShift,- refetchShifts: () => fetchShifts(false), // Silent refresh for live updates+ setShifts: (+ newShifts:+ | ShiftWithCalendar[]+ | ((prev: ShiftWithCalendar[]) => ShiftWithCalendar[])+ ) => {+ if (!calendarId) return;+ queryClient.setQueryData(+ queryKeys.shifts.byCalendar(calendarId),+ newShifts+ );+ },+ loading: isLoading,+ hasLoadedOnce: isFetched,+ createShift: async (shift: ShiftFormData) => {+ if (!calendarId) {+ throw new Error("Calendar ID is required to create a shift");+ }+ return createMutation.mutateAsync(shift);+ },+ deleteShift: async (shiftId: string) => {+ if (!calendarId) {+ throw new Error("Calendar ID is required to delete a shift");+ }+ // Check if shift is externally synced (read-only)+ const cachedShifts = queryClient.getQueryData<ShiftWithCalendar[]>(+ queryKeys.shifts.byCalendar(calendarId)+ );+ const shift = cachedShifts?.find((s) => s.id === shiftId);+ if (shift?.syncedFromExternal) {+ throw new Error(+ t("common.deleteError", { item: t("shift.shift_one") })+ );+ }+ return deleteMutation.mutateAsync(shiftId);+ },+ refetchShifts: () => {+ if (!calendarId) return;+ queryClient.invalidateQueries({+ queryKey: queryKeys.shifts.byCalendar(calendarId),+ });+ },};}diff --git a/lib/auto-sync-service.ts b/lib/auto-sync-service.tsindex 61dfda8..4d6eac1 100644--- a/lib/auto-sync-service.ts+++ b/lib/auto-sync-service.ts@@ -7,7 +7,6 @@import { db } from "@/lib/db";import { externalSyncs, calendars } from "@/lib/db/schema";import { gt, eq } from "drizzle-orm";-import { eventEmitter } from "@/lib/event-emitter";import { syncExternalCalendar } from "@/app/api/external-syncs/[id]/sync/route";import { isAuthEnabled } from "@/lib/auth/feature-flags";@@ -195,16 +194,6 @@ class AutoSyncService {if (stats) {console.log(`Auto-sync completed for ${syncId}:`, stats);-- // Emit event to notify connected clients only if changes were made- if (stats.created > 0 || stats.updated > 0 || stats.deleted > 0) {- eventEmitter.emit("calendar-change", {- type: "shift",- action: "update",- calendarId: stats.calendarId,- data: { autoSync: true, syncId, stats },- });- }}} catch (error) {console.error(`Auto-sync error for ${syncId}:`, error);diff --git a/lib/event-emitter.ts b/lib/event-emitter.tsdeleted file mode 100644index 59fe11f..0000000--- a/lib/event-emitter.ts+++ /dev/null@@ -1,56 +0,0 @@-/**- * Simple event emitter for server-sent events- * Allows broadcasting changes across API routes to connected SSE clients- */--type EventCallback = (data: unknown) => void;--class EventEmitter {- private listeners: Map<string, Set<EventCallback>> = new Map();-- on(event: string, callback: EventCallback) {- if (!this.listeners.has(event)) {- this.listeners.set(event, new Set());- }- this.listeners.get(event)!.add(callback);- }-- off(event: string, callback: EventCallback) {- const callbacks = this.listeners.get(event);- if (callbacks) {- callbacks.delete(callback);- }- }-- emit(event: string, data: unknown) {- const callbacks = this.listeners.get(event);- if (callbacks) {- callbacks.forEach((callback) => callback(data));- }- }-- listenerCount(event: string): number {- return this.listeners.get(event)?.size || 0;- }-}--// Global singleton instance with HMR support-// Use globalThis to persist across hot reloads in development-const globalForEventEmitter = globalThis as unknown as {- eventEmitter: EventEmitter | undefined;-};--export const eventEmitter =- globalForEventEmitter.eventEmitter ?? new EventEmitter();--if (process.env.NODE_ENV !== "production") {- globalForEventEmitter.eventEmitter = eventEmitter;-}--// Event types-export type CalendarChangeEvent = {- type: "shift" | "preset" | "note" | "calendar" | "sync-log";- action: "create" | "update" | "delete" | "reorder";- calendarId: string;- data?: unknown;-};diff --git a/lib/query-client.ts b/lib/query-client.tsnew file mode 100644index 0000000..0b80e7c--- /dev/null+++ b/lib/query-client.ts@@ -0,0 +1,22 @@+import { QueryClient } from "@tanstack/react-query";++export const REFETCH_INTERVAL = 5000; // 5s polling for live updates++export const queryClientConfig = {+ defaultOptions: {+ queries: {+ staleTime: 3000, // 3s - data considered fresh+ gcTime: 300000, // 5min - cache retention+ refetchInterval: REFETCH_INTERVAL,+ refetchOnWindowFocus: true,+ refetchOnReconnect: true,+ retry: 3,+ retryDelay: (attemptIndex: number) =>+ Math.min(1000 * 2 ** attemptIndex, 30000),+ },+ },+};++export function createQueryClient() {+ return new QueryClient(queryClientConfig);+}diff --git a/lib/query-keys.ts b/lib/query-keys.tsnew file mode 100644index 0000000..a27e953--- /dev/null+++ b/lib/query-keys.ts@@ -0,0 +1,61 @@+/**+ * Query Key Factory for TanStack Query+ *+ * Provides consistent, type-safe query keys for all data fetching operations.+ * Follow the structure: [entity, ...params] for proper cache invalidation.+ *+ * @see https://tanstack.com/query/latest/docs/framework/react/guides/query-keys+ */++export const queryKeys = {+ // Calendar Data+ calendars: {+ all: ["calendars"] as const,+ byId: (id: string) => ["calendars", id] as const,+ },+ shifts: {+ all: ["shifts"] as const,+ byCalendar: (calendarId: string) => ["shifts", calendarId] as const,+ },+ presets: {+ all: ["presets"] as const,+ byCalendar: (calendarId: string) => ["presets", calendarId] as const,+ },+ notes: {+ all: ["notes"] as const,+ byCalendar: (calendarId: string) => ["notes", calendarId] as const,+ },+ stats: {+ shifts: (calendarId: string, period: string, date: string) =>+ ["stats", "shifts", calendarId, period, date] as const,+ },+ externalSyncs: {+ byCalendar: (calendarId: string) => ["external-syncs", calendarId] as const,+ logs: (calendarId: string) => ["sync-logs", calendarId] as const,+ },++ // Admin Data+ admin: {+ stats: ["admin", "stats"] as const,+ users: (filters?: object) => ["admin", "users", filters] as const,+ userDetails: (userId: string) => ["admin", "users", userId] as const,+ calendars: (filters?: object) => ["admin", "calendars", filters] as const,+ calendarDetails: (calendarId: string) =>+ ["admin", "calendars", calendarId] as const,+ auditLogs: (filters?: object) => ["admin", "audit-logs", filters] as const,+ },++ // Calendar Features+ shares: {+ byCalendar: (calendarId: string) => ["shares", calendarId] as const,+ },+ tokens: {+ byCalendar: (calendarId: string) => ["tokens", calendarId] as const,+ },+ subscriptions: {+ all: ["subscriptions"] as const,+ },++ // User Activity Logs+ activityLogs: (filters?: object) => ["activity-logs", filters] as const,+} as const;diff --git a/lib/rate-limiter.ts b/lib/rate-limiter.tsindex 0b4622a..fceb091 100644--- a/lib/rate-limiter.ts+++ b/lib/rate-limiter.ts@@ -15,8 +15,6 @@* - RATE_LIMIT_ACCOUNT_DELETE_WINDOW* - RATE_LIMIT_UPLOAD_AVATAR_REQUESTS - Avatar upload endpoint* - RATE_LIMIT_UPLOAD_AVATAR_WINDOW- * - RATE_LIMIT_SSE_CONNECTIONS - SSE connection limit per user- * - RATE_LIMIT_SSE_WINDOW* - RATE_LIMIT_CALENDAR_CREATE_REQUESTS - Calendar creation* - RATE_LIMIT_CALENDAR_CREATE_WINDOW* - RATE_LIMIT_EXTERNAL_SYNC_REQUESTS - External sync execution (per calendar)@@ -72,10 +70,6 @@ const config = {windowMs:parseInt(process.env.RATE_LIMIT_UPLOAD_AVATAR_WINDOW || "300", 10) * 1000,},- sseConnection: {- requests: parseInt(process.env.RATE_LIMIT_SSE_CONNECTIONS || "10", 10),- windowMs: parseInt(process.env.RATE_LIMIT_SSE_WINDOW || "10", 10) * 1000,- },calendarCreate: {requests: parseInt(process.env.RATE_LIMIT_CALENDAR_CREATE_REQUESTS || "10",@@ -320,7 +314,6 @@ export function rateLimit(| "password-change"| "account-delete"| "upload-avatar"- | "sse"| "calendar-create"| "external-sync"| "export-pdf"@@ -361,9 +354,6 @@ export function rateLimit(case "upload-avatar":options = config.uploadAvatar;break;- case "sse":- options = config.sseConnection;- break;case "calendar-create":options = config.calendarCreate;break;@@ -447,7 +437,6 @@ export function getRateLimitStatus(| "password-change"| "account-delete"| "upload-avatar"- | "sse"| "calendar-create"| "external-sync"| "export-pdf"@@ -472,9 +461,6 @@ export function getRateLimitStatus(case "upload-avatar":options = config.uploadAvatar;break;- case "sse":- options = config.sseConnection;- break;case "calendar-create":options = config.calendarCreate;break;diff --git a/messages/de.json b/messages/de.jsonindex f2c8a33..5b245c7 100644--- a/messages/de.json+++ b/messages/de.json@@ -323,11 +323,8 @@"radarDescription": "Vergleiche Top-Schichttypen nach Gesamtstunden und Durchschnitt"},"sync": {- "reconnected": "Verbindung wiederhergestellt",- "disconnected": "Verbindung zum Server verloren",- "offline": "Keine Internetverbindung",- "refreshing": "Daten werden aktualisiert...",- "resyncing": "Daten werden synchronisiert..."+ "connected": "Server Verbindung hergestellt",+ "disconnected": "Server Verbindung verloren"},"onboarding": {"welcome": "Willkommen bei BetterShift",@@ -621,7 +618,8 @@"allTypes": "Alle Typen","auth": "Authentifizierung","sync": "Synchronisation",- "security": "Sicherheit"+ "security": "Sicherheit",+ "calendar": "Kalender"},"admin": {"title": "Admin-Panel",diff --git a/messages/en.json b/messages/en.jsonindex 87922af..58d76b2 100644--- a/messages/en.json+++ b/messages/en.json@@ -323,11 +323,8 @@"radarDescription": "Compare top shift types by total hours and average"},"sync": {- "reconnected": "Connection restored",- "disconnected": "Connection to server lost",- "offline": "No internet connection",- "refreshing": "Refreshing data...",- "resyncing": "Syncing data..."+ "connected": "Connected to server",+ "disconnected": "Connection to server lost"},"onboarding": {"welcome": "Welcome to BetterShift",@@ -621,7 +618,8 @@"allTypes": "All Types","auth": "Authentication","sync": "Sync",- "security": "Security"+ "security": "Security",+ "calendar": "Calendar"},"admin": {"title": "Admin Panel",diff --git a/messages/it.json b/messages/it.jsonindex 9f43abe..2692566 100644--- a/messages/it.json+++ b/messages/it.json@@ -323,11 +323,8 @@"radarDescription": "Confronta i tipi di turno principali per ore totali e media"},"sync": {- "reconnected": "Connessione ripristinata",- "disconnected": "Connessione al server persa",- "offline": "Nessuna connessione internet",- "refreshing": "Aggiornamento dati...",- "resyncing": "Sincronizzazione dati..."+ "connected": "Connesso al server",+ "disconnected": "Connessione al server persa"},"onboarding": {"welcome": "Benvenuto in BetterShift",@@ -621,7 +618,8 @@"allTypes": "Tutti i Tipi","auth": "Autenticazione","sync": "Sincronizzazione",- "security": "Sicurezza"+ "security": "Sicurezza",+ "calendar": "Calendario"},"admin": {"title": "Pannello Admin",diff --git a/package-lock.json b/package-lock.jsonindex 06ed1f5..a680182 100644--- a/package-lock.json+++ b/package-lock.json@@ -28,16 +28,17 @@"@radix-ui/react-tabs": "^1.1.13","@radix-ui/react-tooltip": "^1.2.8","@supercharge/request-ip": "^1.2.0",+ "@tanstack/react-query": "^5.90.17","better-auth": "^1.4.7","better-sqlite3": "^12.5.0","class-variance-authority": "^0.7.1","clsx": "^2.1.1","date-fns": "^4.1.0","dotenv": "^17.2.3",- "drizzle-kit": "^0.31.7",- "drizzle-orm": "^0.44.7",+ "drizzle-kit": "^0.31.8",+ "drizzle-orm": "^0.45.0","ical.js": "^2.2.1",- "jspdf": "^3.0.4",+ "jspdf": "^4.0.0","lucide-react": "^0.555.0","motion": "^12.23.25","next": "16.0.10",@@ -55,6 +56,7 @@},"devDependencies": {"@tailwindcss/postcss": "^4",+ "@tanstack/eslint-plugin-query": "^5.91.2","@types/better-sqlite3": "^7.6.13","@types/node": "^24.10.1","@types/react": "^19.2.7",@@ -4459,6 +4461,49 @@"tailwindcss": "4.1.18"}},+ "node_modules/@tanstack/eslint-plugin-query": {+ "version": "5.91.2",+ "resolved": "https://registry.npmjs.org/@tanstack/eslint-plugin-query/-/eslint-plugin-query-5.91.2.tgz",+ "integrity": "sha512-UPeWKl/Acu1IuuHJlsN+eITUHqAaa9/04geHHPedY8siVarSaWprY0SVMKrkpKfk5ehRT7+/MZ5QwWuEtkWrFw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/utils": "^8.44.1"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/tannerlinsley"+ },+ "peerDependencies": {+ "eslint": "^8.57.0 || ^9.0.0"+ }+ },+ "node_modules/@tanstack/query-core": {+ "version": "5.90.17",+ "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.90.17.tgz",+ "integrity": "sha512-hDww+RyyYhjhUfoYQ4es6pbgxY7LNiPWxt4l1nJqhByjndxJ7HIjDxTBtfvMr5HwjYavMrd+ids5g4Rfev3lVQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/tannerlinsley"+ }+ },+ "node_modules/@tanstack/react-query": {+ "version": "5.90.17",+ "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.90.17.tgz",+ "integrity": "sha512-PGc2u9KLwohDUSchjW9MZqeDQJfJDON7y4W7REdNBgiFKxQy+Pf7eGjiFWEj5xPqKzAeHYdAb62IWI1a9UJyGQ==",+ "license": "MIT",+ "dependencies": {+ "@tanstack/query-core": "5.90.17"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/tannerlinsley"+ },+ "peerDependencies": {+ "react": "^18 || ^19"+ }+ },"node_modules/@tybys/wasm-util": {"version": "0.10.1","resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz",@@ -6354,9 +6399,9 @@}},"node_modules/drizzle-orm": {- "version": "0.44.7",- "resolved": "https://registry.npmjs.org/drizzle-orm/-/drizzle-orm-0.44.7.tgz",- "integrity": "sha512-quIpnYznjU9lHshEOAYLoZ9s3jweleHlZIAWR/jX9gAWNg/JhQ1wj0KGRf7/Zm+obRrYd9GjPVJg790QY9N5AQ==",+ "version": "0.45.1",+ "resolved": "https://registry.npmjs.org/drizzle-orm/-/drizzle-orm-0.45.1.tgz",+ "integrity": "sha512-Te0FOdKIistGNPMq2jscdqngBRfBpC8uMFVwqjf6gtTVJHIQ/dosgV/CLBU2N4ZJBsXL5savCba9b0YJskKdcA==","license": "Apache-2.0","peerDependencies": {"@aws-sdk/client-rds-data": ">=3",@@ -8454,9 +8499,9 @@}},"node_modules/jspdf": {- "version": "3.0.4",- "resolved": "https://registry.npmjs.org/jspdf/-/jspdf-3.0.4.tgz",- "integrity": "sha512-dc6oQ8y37rRcHn316s4ngz/nOjayLF/FFxBF4V9zamQKRqXxyiH1zagkCdktdWhtoQId5K20xt1lB90XzkB+hQ==",+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/jspdf/-/jspdf-4.0.0.tgz",+ "integrity": "sha512-w12U97Z6edKd2tXDn3LzTLg7C7QLJlx0BPfM3ecjK2BckUl9/81vZ+r5gK4/3KQdhAcEZhENUxRhtgYBj75MqQ==","license": "MIT","dependencies": {"@babel/runtime": "^7.28.4",diff --git a/package.json b/package.jsonindex da61401..8115804 100644--- a/package.json+++ b/package.json@@ -39,16 +39,17 @@"@radix-ui/react-tabs": "^1.1.13","@radix-ui/react-tooltip": "^1.2.8","@supercharge/request-ip": "^1.2.0",+ "@tanstack/react-query": "^5.90.17","better-auth": "^1.4.7","better-sqlite3": "^12.5.0","class-variance-authority": "^0.7.1","clsx": "^2.1.1","date-fns": "^4.1.0","dotenv": "^17.2.3",- "drizzle-kit": "^0.31.7",- "drizzle-orm": "^0.44.7",+ "drizzle-kit": "^0.31.8",+ "drizzle-orm": "^0.45.0","ical.js": "^2.2.1",- "jspdf": "^3.0.4",+ "jspdf": "^4.0.0","lucide-react": "^0.555.0","motion": "^12.23.25","next": "16.0.10",@@ -66,6 +67,7 @@},"devDependencies": {"@tailwindcss/postcss": "^4",+ "@tanstack/eslint-plugin-query": "^5.91.2","@types/better-sqlite3": "^7.6.13","@types/node": "^24.10.1","@types/react": "^19.2.7",diff --git a/scripts/i18n-checks.ts b/scripts/i18n-checks.tsindex f927976..e2beca0 100644--- a/scripts/i18n-checks.ts+++ b/scripts/i18n-checks.ts@@ -396,9 +396,51 @@ function main() {const usedKeys = findUsedKeys(files);const staticKeys = Array.from(usedKeys).filter((k) => !k.endsWith(".*"));const wildcardPatterns = Array.from(usedKeys).filter((k) => k.endsWith(".*"));- console.log(- ` Found ${staticKeys.length} static keys + ${wildcardPatterns.length} dynamic patterns\n`- );++ // Identify phantom keys (used in code but don't exist in de.json)+ const allKeysSet = new Set(allKeys);+ const phantomKeys = staticKeys.filter((key) => !allKeysSet.has(key));+ const realStaticKeys = staticKeys.filter((key) => allKeysSet.has(key));++ // Count how many actual keys are matched by wildcards+ let wildcardMatchedKeysCount = 0;+ for (const wildcardKey of wildcardPatterns) {+ const prefix = wildcardKey.slice(0, -2); // Remove ".*"+ const matchingKeys = allKeys.filter((key) => {+ if (key.startsWith(prefix + ".")) return true;+ if (key.startsWith(prefix) && key.length > prefix.length) {+ const afterPrefix = key.substring(prefix.length);+ return !afterPrefix.includes(".");+ }+ return false;+ });+ wildcardMatchedKeysCount += matchingKeys.length;+ }++ // Keys that are used via both static AND wildcard (avoid double counting)+ const keysInBoth = realStaticKeys.filter((key) => {+ for (const wildcardKey of wildcardPatterns) {+ const prefix = wildcardKey.slice(0, -2);+ if (+ key.startsWith(prefix + ".") ||+ (key.startsWith(prefix) &&+ key.length > prefix.length &&+ !key.substring(prefix.length).includes("."))+ ) {+ return true;+ }+ }+ return false;+ });++ const totalUniqueKeysUsed =+ realStaticKeys.length + wildcardMatchedKeysCount - keysInBoth.length;++ console.log(` Found ${totalUniqueKeysUsed} keys used in code`);+ if (phantomKeys.length > 0) {+ console.log(` ⚠️ ${phantomKeys.length} missing in de.json`);+ }+ console.log();// 1. Find unused keysconsole.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");@@ -440,11 +482,22 @@ function main() {const missingKeys = findMissingKeys(usedKeys, allKeys);- if (missingKeys.length === 0) {- console.log("✅ No missing translation keys found!\n");- } else {+ // Show phantom keys first (static keys that don't exist)+ if (phantomKeys.length > 0) {hasIssues = true;- console.log(`❌ Found ${missingKeys.length} missing translation keys:\n`);+ console.log(`❌ Found ${phantomKeys.length} missing static keys:\n`);+ for (const key of phantomKeys.sort()) {+ console.log(` - ${key}`);+ }+ console.log();+ }++ // Show missing dynamic pattern keys+ if (missingKeys.length > 0) {+ hasIssues = true;+ console.log(+ `❌ Found ${missingKeys.length} missing dynamic pattern keys:\n`+ );for (const item of missingKeys) {if (item.pattern) {// Dynamic pattern@@ -464,6 +517,11 @@ function main() {console.log();}+ // If no missing keys at all+ if (phantomKeys.length === 0 && missingKeys.length === 0) {+ console.log("✅ No missing translation keys found!\n");+ }+// 3. Compare translation filesconsole.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");console.log("3️⃣ FILE SYNCHRONIZATION (de.json vs en.json vs it.json)");@@ -524,21 +582,62 @@ function main() {console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");console.log("📊 SUMMARY");console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");- console.log(` Total keys in de.json: ${allKeys.length}`);- console.log(` Static keys used in code: ${staticKeys.length}`);- console.log(` Dynamic patterns (wildcards): ${wildcardPatterns.length}`);- console.log(` Unused keys: ${unusedKeys.length}`);- console.log(` Missing keys: ${missingKeys.length}`);++ // Calculate overall health+ const totalIssues =+ unusedKeys.length ++ phantomKeys.length ++ missingKeys.length ++ missingInEn.length ++ missingInIt.length ++ extraInEn.length ++ extraInIt.length;+ const healthScore =+ totalIssues === 0 ? 100 : Math.max(0, 100 - totalIssues * 2);+ const healthIcon =+ healthScore === 100 ? "✅" : healthScore >= 80 ? "⚠️" : "❌";++ console.log(`${healthIcon} Overall Health: ${healthScore}%\n`);++ // Main stats+ console.log("📊 Translation Keys:");+ console.log(` Keys in de.json: ${allKeys.length}`);+ console.log(` Keys used in code: ${totalUniqueKeysUsed}`);+ console.log(` Unused keys: ${unusedKeys.length}`);+ const missingTotal = phantomKeys.length + missingKeys.length;+ if (missingTotal > 0) {+ console.log(` Missing keys: ${missingTotal}`);+ }++ const matchRate = ((totalUniqueKeysUsed / allKeys.length) * 100).toFixed(1);+ console.log(` Match rate: ${matchRate}%`);+ console.log();++ if (phantomKeys.length > 0 || missingKeys.length > 0) {+ console.log("⚠️ Issues:");+ console.log(+ ` Missing in de.json: ${phantomKeys.length + missingKeys.length}`+ );+ console.log();+ }++ console.log("🌍 File Synchronization:");+ const enIssues = missingInEn.length + extraInEn.length;+ const itIssues = missingInIt.length + extraInIt.length;console.log(- ` Usage rate: ${((1 - unusedKeys.length / allKeys.length) * 100).toFixed(- 1- )}%`+ ` en.json: ${+ enIssues === 0+ ? "✅ Synced"+ : `⚠️ ${missingInEn.length} missing, ${extraInEn.length} extra`+ }`+ );+ console.log(+ ` it.json: ${+ itIssues === 0+ ? "✅ Synced"+ : `⚠️ ${missingInIt.length} missing, ${extraInIt.length} extra`+ }`);- console.log();- console.log(` en.json missing: ${missingInEn.length}`);- console.log(` en.json extra: ${extraInEn.length}`);- console.log(` it.json missing: ${missingInIt.length}`);- console.log(` it.json extra: ${extraInIt.length}`);console.log();if (!hasIssues) {