feat(sprint-6): Phase 6 — Notifications (WebSocket) + PWA
- WebSocket: Spring STOMP + SockJS, NotificationService, persistent notifications table - NotificationController: GET/PUT endpoints for notification management - Frontend: notification bell with unread badge, dropdown panel, real-time via STOMP - PWA: manifest.json, service worker (manual sw.js), offline page, install prompt - PWA icons (192+512), dark theme colors, standalone display - Full i18n (de/en) for notifications and PWA - Flyway V10 migration for notifications table - spring-boot-starter-websocket dependency added
This commit is contained in:
@@ -1,13 +1,16 @@
|
||||
import React from "react"
|
||||
import { fireEvent, render, screen } from "@testing-library/react"
|
||||
import { describe, expect, it, vi } from "vitest"
|
||||
import React from "react"
|
||||
|
||||
// Error Boundary component for testing
|
||||
class ApiErrorBoundary extends React.Component<
|
||||
{ children: React.ReactNode; fallback?: React.ReactNode },
|
||||
{ hasError: boolean; error: Error | null }
|
||||
> {
|
||||
constructor(props: { children: React.ReactNode; fallback?: React.ReactNode }) {
|
||||
constructor(props: {
|
||||
children: React.ReactNode
|
||||
fallback?: React.ReactNode
|
||||
}) {
|
||||
super(props)
|
||||
this.state = { hasError: false, error: null }
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from "react"
|
||||
import { render, screen } from "@testing-library/react"
|
||||
import { describe, expect, it, vi } from "vitest"
|
||||
import React from "react"
|
||||
|
||||
// Since there's no existing offline banner component, we'll create and test a minimal one
|
||||
// This tests the pattern that would be used for an offline banner
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"
|
||||
import {
|
||||
afterAll,
|
||||
afterEach,
|
||||
beforeAll,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
vi,
|
||||
} from "vitest"
|
||||
|
||||
import { ApiError, apiClient, apiDownload } from "@/lib/api-client"
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { http, HttpResponse } from "msw"
|
||||
import { HttpResponse, http } from "msw"
|
||||
|
||||
// --- Mock Data ---
|
||||
|
||||
@@ -224,14 +224,17 @@ export const handlers = [
|
||||
})
|
||||
}),
|
||||
|
||||
http.put("/api/backend/staff/:id/permissions", async ({ request, params }) => {
|
||||
const body = (await request.json()) as Record<string, unknown>
|
||||
return HttpResponse.json({
|
||||
id: params.id,
|
||||
...body,
|
||||
status: "ACTIVE",
|
||||
})
|
||||
}),
|
||||
http.put(
|
||||
"/api/backend/staff/:id/permissions",
|
||||
async ({ request, params }) => {
|
||||
const body = (await request.json()) as Record<string, unknown>
|
||||
return HttpResponse.json({
|
||||
id: params.id,
|
||||
...body,
|
||||
status: "ACTIVE",
|
||||
})
|
||||
}
|
||||
),
|
||||
|
||||
http.post("/api/backend/staff/:id/revoke", ({ params }) => {
|
||||
return new HttpResponse(null, { status: 204 })
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import React from "react"
|
||||
import {
|
||||
useClubStatsQuery,
|
||||
useRecentDistributionsQuery,
|
||||
} from "@/services/dashboard"
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
|
||||
import { renderHook, waitFor } from "@testing-library/react"
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
|
||||
import React from "react"
|
||||
|
||||
import { useClubStatsQuery, useRecentDistributionsQuery } from "@/services/dashboard"
|
||||
|
||||
import { server } from "../mocks/server"
|
||||
import { mockClubStats, mockRecentDistributions } from "../mocks/handlers"
|
||||
import { server } from "../mocks/server"
|
||||
|
||||
beforeAll(() => server.listen({ onUnhandledRequest: "error" }))
|
||||
afterEach(() => server.resetHandlers())
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
import { renderHook, waitFor } from "@testing-library/react"
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
|
||||
import React from "react"
|
||||
|
||||
import {
|
||||
useCreateDistributionMutation,
|
||||
useDistributionsQuery,
|
||||
useQuotaQuery,
|
||||
useCreateDistributionMutation,
|
||||
} from "@/services/distributions"
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
|
||||
import { renderHook, waitFor } from "@testing-library/react"
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"
|
||||
|
||||
import { server } from "../mocks/server"
|
||||
import { mockDistributionsPage, mockQuotaStatus } from "../mocks/handlers"
|
||||
import { server } from "../mocks/server"
|
||||
|
||||
beforeAll(() => server.listen({ onUnhandledRequest: "error" }))
|
||||
afterEach(() => server.resetHandlers())
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
import { renderHook, waitFor } from "@testing-library/react"
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
|
||||
import React from "react"
|
||||
|
||||
import {
|
||||
useMembersQuery,
|
||||
useCreateMemberMutation,
|
||||
useMemberQuery,
|
||||
useMemberQuotaQuery,
|
||||
useCreateMemberMutation,
|
||||
useMembersQuery,
|
||||
useUpdateMemberMutation,
|
||||
} from "@/services/members"
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
|
||||
import { renderHook, waitFor } from "@testing-library/react"
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"
|
||||
|
||||
import { server } from "../mocks/server"
|
||||
import { mockMembersPage, mockQuotaStatus } from "../mocks/handlers"
|
||||
import { server } from "../mocks/server"
|
||||
|
||||
beforeAll(() => server.listen({ onUnhandledRequest: "error" }))
|
||||
afterEach(() => server.resetHandlers())
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
import React from "react"
|
||||
import {
|
||||
useInviteStaffMutation,
|
||||
useRevokeStaffMutation,
|
||||
useStaffListQuery,
|
||||
useUpdateStaffPermissionsMutation,
|
||||
} from "@/services/staff"
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
|
||||
import { renderHook, waitFor } from "@testing-library/react"
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
|
||||
import React from "react"
|
||||
|
||||
import {
|
||||
useStaffListQuery,
|
||||
useInviteStaffMutation,
|
||||
useUpdateStaffPermissionsMutation,
|
||||
useRevokeStaffMutation,
|
||||
} from "@/services/staff"
|
||||
|
||||
import { server } from "../mocks/server"
|
||||
import { mockStaffList } from "../mocks/handlers"
|
||||
import { server } from "../mocks/server"
|
||||
|
||||
beforeAll(() => server.listen({ onUnhandledRequest: "error" }))
|
||||
afterEach(() => server.resetHandlers())
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
import { renderHook, waitFor } from "@testing-library/react"
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
|
||||
import React from "react"
|
||||
|
||||
import {
|
||||
useBatchesQuery,
|
||||
useCreateBatchMutation,
|
||||
useRecallBatchMutation,
|
||||
useStrainsQuery,
|
||||
} from "@/services/stock"
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
|
||||
import { renderHook, waitFor } from "@testing-library/react"
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"
|
||||
|
||||
import { server } from "../mocks/server"
|
||||
import { mockBatchesPage } from "../mocks/handlers"
|
||||
import { server } from "../mocks/server"
|
||||
|
||||
beforeAll(() => server.listen({ onUnhandledRequest: "error" }))
|
||||
afterEach(() => server.resetHandlers())
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import React from "react"
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
|
||||
import { render, type RenderOptions } from "@testing-library/react"
|
||||
import React, { type ReactElement } from "react"
|
||||
import { render } from "@testing-library/react"
|
||||
|
||||
import type { RenderOptions } from "@testing-library/react"
|
||||
import type { ReactElement } from "react"
|
||||
|
||||
/**
|
||||
* Creates a fresh QueryClient for each test to avoid shared state.
|
||||
|
||||
@@ -11,6 +11,8 @@ import type { ReactNode } from "react"
|
||||
|
||||
import { Toaster as Sonner } from "@/components/ui/sonner"
|
||||
import { Toaster } from "@/components/ui/toaster"
|
||||
import { PwaInstallPrompt } from "@/components/pwa-install-prompt"
|
||||
import { ServiceWorkerRegistration as SwRegistration } from "@/components/sw-registration"
|
||||
|
||||
// Define metadata for the application
|
||||
// More info: https://nextjs.org/docs/app/building-your-application/optimizing/metadata
|
||||
@@ -21,6 +23,13 @@ export const metadata: Metadata = {
|
||||
},
|
||||
description: "Cannabis club management platform — CannaManage",
|
||||
metadataBase: new URL(process.env.BASE_URL as string),
|
||||
manifest: "/manifest.json",
|
||||
themeColor: "#2ECC71",
|
||||
appleWebApp: {
|
||||
capable: true,
|
||||
statusBarStyle: "default",
|
||||
title: "CannaManage",
|
||||
},
|
||||
}
|
||||
|
||||
// Define fonts for the application
|
||||
@@ -55,6 +64,8 @@ export default function RootLayout(props: { children: ReactNode }) {
|
||||
{children}
|
||||
<Toaster />
|
||||
<Sonner />
|
||||
<SwRegistration />
|
||||
<PwaInstallPrompt />
|
||||
</Providers>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"use client"
|
||||
|
||||
import { useTranslations } from "next-intl"
|
||||
import { RefreshCw, WifiOff } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
export default function OfflinePage() {
|
||||
const t = useTranslations("pwa")
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center gap-6 bg-background px-4 text-center">
|
||||
<div className="flex h-20 w-20 items-center justify-center rounded-full bg-muted">
|
||||
<WifiOff className="h-10 w-10 text-muted-foreground" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold">{t("offline")}</h1>
|
||||
<p className="max-w-sm text-muted-foreground">{t("offlineDesc")}</p>
|
||||
<Button onClick={() => window.location.reload()} className="gap-2">
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
{t("retry")}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import {
|
||||
getNotifications,
|
||||
markAllNotificationsAsRead,
|
||||
markNotificationAsRead,
|
||||
} from "@/services/notifications"
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { Bell, Check, CheckCheck } from "lucide-react"
|
||||
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
|
||||
export function NotificationBell() {
|
||||
const t = useTranslations("notifications")
|
||||
const queryClient = useQueryClient()
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const { data } = useQuery({
|
||||
queryKey: ["notifications"],
|
||||
queryFn: getNotifications,
|
||||
refetchInterval: 30000, // Poll every 30s as fallback
|
||||
})
|
||||
|
||||
const markReadMutation = useMutation({
|
||||
mutationFn: markNotificationAsRead,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["notifications"] })
|
||||
},
|
||||
})
|
||||
|
||||
const markAllReadMutation = useMutation({
|
||||
mutationFn: markAllNotificationsAsRead,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["notifications"] })
|
||||
},
|
||||
})
|
||||
|
||||
const notifications = data?.notifications ?? []
|
||||
const unreadCount = data?.unreadCount ?? 0
|
||||
|
||||
const handleNotificationClick = (id: string, link: string) => {
|
||||
markReadMutation.mutate(id)
|
||||
setOpen(false)
|
||||
if (link) {
|
||||
window.location.href = link
|
||||
}
|
||||
}
|
||||
|
||||
const getTypeIcon = (type: string) => {
|
||||
switch (type) {
|
||||
case "QUOTA_WARNING":
|
||||
return "⚠️"
|
||||
case "BATCH_RECALLED":
|
||||
return "🔴"
|
||||
case "DISTRIBUTION_RECORDED":
|
||||
return "✅"
|
||||
case "SUBSCRIPTION_EXPIRING":
|
||||
return "⏰"
|
||||
default:
|
||||
return "🔔"
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu open={open} onOpenChange={setOpen}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="relative"
|
||||
aria-label={t("title")}
|
||||
>
|
||||
<Bell className="h-5 w-5" />
|
||||
{unreadCount > 0 && (
|
||||
<Badge
|
||||
variant="destructive"
|
||||
className="absolute -right-1 -top-1 flex h-5 w-5 items-center justify-center rounded-full p-0 text-xs"
|
||||
>
|
||||
{unreadCount > 9 ? "9+" : unreadCount}
|
||||
</Badge>
|
||||
)}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-80">
|
||||
<DropdownMenuLabel className="flex items-center justify-between">
|
||||
<span>{t("title")}</span>
|
||||
{unreadCount > 0 && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-auto p-1 text-xs"
|
||||
onClick={() => markAllReadMutation.mutate()}
|
||||
>
|
||||
<CheckCheck className="mr-1 h-3 w-3" />
|
||||
{t("markAllRead")}
|
||||
</Button>
|
||||
)}
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{notifications.length === 0 ? (
|
||||
<div className="px-4 py-6 text-center text-sm text-muted-foreground">
|
||||
{t("noNotifications")}
|
||||
</div>
|
||||
) : (
|
||||
notifications.map((notification) => (
|
||||
<DropdownMenuItem
|
||||
key={notification.id}
|
||||
className={`flex cursor-pointer flex-col items-start gap-1 p-3 ${
|
||||
!notification.read ? "bg-muted/50" : ""
|
||||
}`}
|
||||
onClick={() =>
|
||||
handleNotificationClick(notification.id, notification.link)
|
||||
}
|
||||
>
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<span className="text-sm">
|
||||
{getTypeIcon(notification.type)}
|
||||
</span>
|
||||
<span className="flex-1 text-sm font-medium">
|
||||
{notification.title}
|
||||
</span>
|
||||
{!notification.read && (
|
||||
<Check className="h-3 w-3 text-primary" />
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground line-clamp-2 pl-6">
|
||||
{notification.message}
|
||||
</p>
|
||||
<span className="text-xs text-muted-foreground pl-6">
|
||||
{new Date(notification.createdAt).toLocaleDateString("de-DE", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
))
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { Download, X } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
interface BeforeInstallPromptEvent extends Event {
|
||||
prompt: () => Promise<void>
|
||||
userChoice: Promise<{ outcome: "accepted" | "dismissed" }>
|
||||
}
|
||||
|
||||
export function PwaInstallPrompt() {
|
||||
const t = useTranslations("pwa")
|
||||
const [deferredPrompt, setDeferredPrompt] =
|
||||
useState<BeforeInstallPromptEvent | null>(null)
|
||||
const [dismissed, setDismissed] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
// Check if already dismissed permanently
|
||||
if (localStorage.getItem("pwa-install-dismissed") === "true") {
|
||||
setDismissed(true)
|
||||
return
|
||||
}
|
||||
|
||||
const handler = (e: Event) => {
|
||||
e.preventDefault()
|
||||
setDeferredPrompt(e as BeforeInstallPromptEvent)
|
||||
}
|
||||
|
||||
window.addEventListener("beforeinstallprompt", handler)
|
||||
return () => window.removeEventListener("beforeinstallprompt", handler)
|
||||
}, [])
|
||||
|
||||
const handleInstall = async () => {
|
||||
if (!deferredPrompt) return
|
||||
await deferredPrompt.prompt()
|
||||
const { outcome } = await deferredPrompt.userChoice
|
||||
if (outcome === "accepted") {
|
||||
setDeferredPrompt(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDismiss = () => {
|
||||
setDismissed(true)
|
||||
localStorage.setItem("pwa-install-dismissed", "true")
|
||||
setDeferredPrompt(null)
|
||||
}
|
||||
|
||||
if (!deferredPrompt || dismissed) return null
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-4 left-4 right-4 z-50 mx-auto max-w-md animate-in slide-in-from-bottom-4 rounded-lg border bg-card p-4 shadow-lg">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-primary/10">
|
||||
<Download className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<p className="text-sm font-medium">{t("install")}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{t("installDesc")}
|
||||
</p>
|
||||
<div className="mt-3 flex gap-2">
|
||||
<Button size="sm" onClick={handleInstall}>
|
||||
{t("install")}
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={handleDismiss}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect } from "react"
|
||||
|
||||
/**
|
||||
* Registers the service worker on mount.
|
||||
* Must be rendered as a client component in the root layout.
|
||||
*/
|
||||
export function ServiceWorkerRegistration() {
|
||||
useEffect(() => {
|
||||
if ("serviceWorker" in navigator && process.env.NODE_ENV === "production") {
|
||||
navigator.serviceWorker.register("/sw.js").catch((err) => {
|
||||
console.warn("SW registration failed:", err)
|
||||
})
|
||||
}
|
||||
}, [])
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
"use client"
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react"
|
||||
import { useQueryClient } from "@tanstack/react-query"
|
||||
|
||||
export interface WsNotification {
|
||||
id: string
|
||||
type: string
|
||||
title: string
|
||||
message: string
|
||||
link: string
|
||||
read: boolean
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
interface UseNotificationsOptions {
|
||||
userId?: string
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* WebSocket hook for real-time notifications via STOMP over SockJS.
|
||||
* Connects to /ws, subscribes to /user/queue/notifications.
|
||||
* Falls back gracefully if WebSocket is unavailable.
|
||||
*/
|
||||
export function useNotifications({
|
||||
userId,
|
||||
enabled = true,
|
||||
}: UseNotificationsOptions) {
|
||||
const [connected, setConnected] = useState(false)
|
||||
const [lastNotification, setLastNotification] =
|
||||
useState<WsNotification | null>(null)
|
||||
const stompClientRef = useRef<unknown>(null)
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const connect = useCallback(async () => {
|
||||
if (!userId || !enabled) return
|
||||
|
||||
try {
|
||||
// Dynamic import to avoid SSR issues
|
||||
const { Client } = await import("@stomp/stompjs")
|
||||
const SockJS = (await import("sockjs-client")).default
|
||||
|
||||
const backendUrl =
|
||||
process.env.NEXT_PUBLIC_WS_URL || "http://localhost:8080"
|
||||
|
||||
const client = new Client({
|
||||
webSocketFactory: () => new SockJS(`${backendUrl}/ws`),
|
||||
reconnectDelay: 5000,
|
||||
heartbeatIncoming: 10000,
|
||||
heartbeatOutgoing: 10000,
|
||||
onConnect: () => {
|
||||
setConnected(true)
|
||||
|
||||
client.subscribe(`/user/${userId}/queue/notifications`, (message) => {
|
||||
try {
|
||||
const notification: WsNotification = JSON.parse(message.body)
|
||||
setLastNotification(notification)
|
||||
// Invalidate notifications query to refresh badge count
|
||||
queryClient.invalidateQueries({ queryKey: ["notifications"] })
|
||||
} catch {
|
||||
console.error("Failed to parse notification message")
|
||||
}
|
||||
})
|
||||
},
|
||||
onDisconnect: () => {
|
||||
setConnected(false)
|
||||
},
|
||||
onStompError: (frame) => {
|
||||
console.error("STOMP error:", frame.headers["message"])
|
||||
setConnected(false)
|
||||
},
|
||||
})
|
||||
|
||||
client.activate()
|
||||
stompClientRef.current = client
|
||||
} catch {
|
||||
// WebSocket libraries not available (SSR or missing deps) — fail silently
|
||||
console.warn("WebSocket connection unavailable, falling back to polling")
|
||||
}
|
||||
}, [userId, enabled, queryClient])
|
||||
|
||||
const disconnect = useCallback(() => {
|
||||
const client = stompClientRef.current as { deactivate?: () => void } | null
|
||||
if (client?.deactivate) {
|
||||
client.deactivate()
|
||||
}
|
||||
stompClientRef.current = null
|
||||
setConnected(false)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
connect()
|
||||
return () => disconnect()
|
||||
}, [connect, disconnect])
|
||||
|
||||
return {
|
||||
connected,
|
||||
lastNotification,
|
||||
disconnect,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { apiClient } from "@/lib/api-client"
|
||||
|
||||
export interface Notification {
|
||||
id: string
|
||||
type: string
|
||||
title: string
|
||||
message: string
|
||||
link: string
|
||||
read: boolean
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface NotificationsResponse {
|
||||
notifications: Notification[]
|
||||
unreadCount: number
|
||||
}
|
||||
|
||||
export async function getNotifications(): Promise<NotificationsResponse> {
|
||||
return apiClient<NotificationsResponse>("/notifications")
|
||||
}
|
||||
|
||||
export async function markNotificationAsRead(id: string): Promise<void> {
|
||||
await apiClient<void>(`/notifications/${id}/read`, { method: "PUT" })
|
||||
}
|
||||
|
||||
export async function markAllNotificationsAsRead(): Promise<{
|
||||
updated: number
|
||||
}> {
|
||||
return apiClient<{ updated: number }>("/notifications/read-all", {
|
||||
method: "PUT",
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user