feat(sprint-6): Phase 6 — Notifications (WebSocket) + PWA
Deploy to Production / test (push) Has been cancelled
Deploy to Production / deploy (push) Has been cancelled

- 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:
Patrick Plate
2026-06-12 23:02:44 +02:00
parent 076fd6f9b3
commit 599514c0db
39 changed files with 6684 additions and 3217 deletions
+5
View File
@@ -123,6 +123,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- WebSocket (STOMP + SockJS for notifications) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
<build>
@@ -0,0 +1,34 @@
package de.cannamanage.api.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
/**
* WebSocket configuration — enables STOMP messaging over SockJS.
* Clients connect to /ws, subscribe to /user/queue/notifications for personal notifications.
*/
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// Enable simple in-memory broker for /topic (broadcast) and /queue (user-specific)
config.enableSimpleBroker("/topic", "/queue");
// Prefix for @MessageMapping methods
config.setApplicationDestinationPrefixes("/app");
// User-specific destination prefix
config.setUserDestinationPrefix("/user");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// WebSocket endpoint with SockJS fallback
registry.addEndpoint("/ws")
.setAllowedOriginPatterns("*")
.withSockJS();
}
}
@@ -0,0 +1,68 @@
package de.cannamanage.api.controller;
import de.cannamanage.domain.entity.Notification;
import de.cannamanage.service.NotificationService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* REST endpoints for notification management.
*/
@RestController
@RequestMapping("/api/v1/notifications")
@RequiredArgsConstructor
public class NotificationController {
private final NotificationService notificationService;
/**
* Get current user's notifications (last 10, unread first).
*/
@GetMapping
public ResponseEntity<Map<String, Object>> getNotifications(@AuthenticationPrincipal UserDetails user) {
UUID userId = UUID.fromString(user.getUsername());
List<Notification> notifications = notificationService.getRecentNotifications(userId);
long unreadCount = notificationService.getUnreadCount(userId);
var items = notifications.stream().map(n -> Map.of(
"id", (Object) n.getId(),
"type", n.getType().name(),
"title", n.getTitle(),
"message", n.getMessage(),
"link", n.getLink() != null ? n.getLink() : "",
"read", n.isRead(),
"createdAt", n.getCreatedAt().toString()
)).toList();
return ResponseEntity.ok(Map.of(
"notifications", items,
"unreadCount", unreadCount
));
}
/**
* Mark a single notification as read.
*/
@PutMapping("/{id}/read")
public ResponseEntity<Void> markAsRead(@PathVariable UUID id) {
notificationService.markAsRead(id);
return ResponseEntity.noContent().build();
}
/**
* Mark all notifications as read.
*/
@PutMapping("/read-all")
public ResponseEntity<Map<String, Object>> markAllAsRead(@AuthenticationPrincipal UserDetails user) {
UUID userId = UUID.fromString(user.getUsername());
int updated = notificationService.markAllAsRead(userId);
return ResponseEntity.ok(Map.of("updated", updated));
}
}
@@ -0,0 +1,15 @@
-- V10: Notifications table for real-time + persistent notification system
CREATE TABLE IF NOT EXISTS notifications (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL,
type VARCHAR(50) NOT NULL,
title VARCHAR(255) NOT NULL,
message TEXT NOT NULL,
link VARCHAR(500),
read BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
tenant_id UUID NOT NULL
);
CREATE INDEX idx_notifications_user ON notifications(user_id, read, created_at DESC);
CREATE INDEX idx_notifications_tenant ON notifications(tenant_id);
@@ -0,0 +1,64 @@
package de.cannamanage.domain.entity;
import de.cannamanage.domain.enums.NotificationType;
import jakarta.persistence.*;
import java.util.UUID;
/**
* Persistent notification entity — survives page refresh.
* Delivered in real-time via WebSocket, but also queryable via REST.
*/
@Entity
@Table(name = "notifications", indexes = {
@Index(name = "idx_notifications_user", columnList = "user_id, read, created_at DESC")
})
public class Notification extends AbstractTenantEntity {
@Column(name = "user_id", nullable = false)
private UUID userId;
@Enumerated(EnumType.STRING)
@Column(name = "type", nullable = false, length = 50)
private NotificationType type;
@Column(name = "title", nullable = false)
private String title;
@Column(name = "message", nullable = false, columnDefinition = "TEXT")
private String message;
@Column(name = "link", length = 500)
private String link;
@Column(name = "read", nullable = false)
private boolean read = false;
public Notification() {}
public Notification(UUID userId, NotificationType type, String title, String message, String link) {
this.userId = userId;
this.type = type;
this.title = title;
this.message = message;
this.link = link;
}
public UUID getUserId() { return userId; }
public void setUserId(UUID userId) { this.userId = userId; }
public NotificationType getType() { return type; }
public void setType(NotificationType type) { this.type = type; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
public String getLink() { return link; }
public void setLink(String link) { this.link = link; }
public boolean isRead() { return read; }
public void setRead(boolean read) { this.read = read; }
}
@@ -0,0 +1,11 @@
package de.cannamanage.domain.enums;
/**
* Types of notifications sent to users.
*/
public enum NotificationType {
QUOTA_WARNING,
BATCH_RECALLED,
DISTRIBUTION_RECORDED,
SUBSCRIPTION_EXPIRING
}
+24 -25
View File
@@ -6,73 +6,72 @@
## Admin Login
| Dark Mode | Light Mode |
|-----------|------------|
| Dark Mode | Light Mode |
| -------------------------------------------------- | ---------------------------------------------------- |
| ![Admin Login Dark](screenshots/01-login-dark.png) | ![Admin Login Light](screenshots/01-login-light.png) |
## Member Portal Login
| Dark Mode | Light Mode |
|-----------|------------|
| Dark Mode | Light Mode |
| ----------------------------------------------------------------- | ------------------------------------------------------------------- |
| ![Member Portal Login Dark](screenshots/02-portal-login-dark.png) | ![Member Portal Login Light](screenshots/02-portal-login-light.png) |
## Club Dashboard (auth required)
| Dark Mode | Light Mode |
|-----------|------------|
| Dark Mode | Light Mode |
| ------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| ![Club Dashboard (auth required) Dark](screenshots/03-dashboard-dark.png) | ![Club Dashboard (auth required) Light](screenshots/03-dashboard-dark.png) |
## Member Management (auth required)
| Dark Mode | Light Mode |
|-----------|------------|
| Dark Mode | Light Mode |
| -------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| ![Member Management (auth required) Dark](screenshots/04-members-dark.png) | ![Member Management (auth required) Light](screenshots/04-members-dark.png) |
## Distribution History (auth required)
| Dark Mode | Light Mode |
|-----------|------------|
| Dark Mode | Light Mode |
| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| ![Distribution History (auth required) Dark](screenshots/05-distributions-dark.png) | ![Distribution History (auth required) Light](screenshots/05-distributions-dark.png) |
## New Distribution (Multi-Step) (auth required)
| Dark Mode | Light Mode |
|-----------|------------|
| Dark Mode | Light Mode |
| ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| ![New Distribution (Multi-Step) (auth required) Dark](screenshots/06-distribution-new-dark.png) | ![New Distribution (Multi-Step) (auth required) Light](screenshots/06-distribution-new-dark.png) |
## Stock & Batch Management (auth required)
| Dark Mode | Light Mode |
|-----------|------------|
| Dark Mode | Light Mode |
| ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| ![Stock & Batch Management (auth required) Dark](screenshots/07-stock-dark.png) | ![Stock & Batch Management (auth required) Light](screenshots/07-stock-dark.png) |
## Add New Batch (auth required)
| Dark Mode | Light Mode |
|-----------|------------|
| Dark Mode | Light Mode |
| ------------------------------------------------------------------------ | ------------------------------------------------------------------------- |
| ![Add New Batch (auth required) Dark](screenshots/08-stock-new-dark.png) | ![Add New Batch (auth required) Light](screenshots/08-stock-new-dark.png) |
## Compliance Reports (auth required)
| Dark Mode | Light Mode |
|-----------|------------|
| Dark Mode | Light Mode |
| --------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| ![Compliance Reports (auth required) Dark](screenshots/09-reports-dark.png) | ![Compliance Reports (auth required) Light](screenshots/09-reports-dark.png) |
## Member Quota Overview
| Dark Mode | Light Mode |
|-----------|------------|
| Dark Mode | Light Mode |
| ----------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| ![Member Quota Overview Dark](screenshots/10-portal-dashboard-dark.png) | ![Member Quota Overview Light](screenshots/10-portal-dashboard-light.png) |
## My Distribution History
| Dark Mode | Light Mode |
|-----------|------------|
| Dark Mode | Light Mode |
| ----------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| ![My Distribution History Dark](screenshots/11-portal-history-dark.png) | ![My Distribution History Light](screenshots/11-portal-history-light.png) |
## Profile & Settings
| Dark Mode | Light Mode |
|-----------|------------|
| Dark Mode | Light Mode |
| ------------------------------------------------------------------ | -------------------------------------------------------------------- |
| ![Profile & Settings Dark](screenshots/12-portal-profile-dark.png) | ![Profile & Settings Light](screenshots/12-portal-profile-light.png) |
@@ -23,13 +23,41 @@ const SCREENSHOT_DIR = path.join(__dirname, "..", "docs", "screenshots")
// Admin pages to visit after login
const ADMIN_PAGES = [
{ route: "/dashboard", name: "03-dashboard-dark", waitFor: "h1, h2, [data-testid]" },
{ route: "/members", name: "04-members-dark", waitFor: "h1, h2, table, [data-testid]" },
{ route: "/distributions", name: "05-distributions-dark", waitFor: "h1, h2, table, [data-testid]" },
{ route: "/distributions/new", name: "06-distribution-new-dark", waitFor: "h1, h2, form, [data-testid]" },
{ route: "/stock", name: "07-stock-dark", waitFor: "h1, h2, table, [data-testid]" },
{ route: "/stock/new", name: "08-stock-new-dark", waitFor: "h1, h2, form, [data-testid]" },
{ route: "/reports", name: "09-reports-dark", waitFor: "h1, h2, [data-testid]" },
{
route: "/dashboard",
name: "03-dashboard-dark",
waitFor: "h1, h2, [data-testid]",
},
{
route: "/members",
name: "04-members-dark",
waitFor: "h1, h2, table, [data-testid]",
},
{
route: "/distributions",
name: "05-distributions-dark",
waitFor: "h1, h2, table, [data-testid]",
},
{
route: "/distributions/new",
name: "06-distribution-new-dark",
waitFor: "h1, h2, form, [data-testid]",
},
{
route: "/stock",
name: "07-stock-dark",
waitFor: "h1, h2, table, [data-testid]",
},
{
route: "/stock/new",
name: "08-stock-new-dark",
waitFor: "h1, h2, form, [data-testid]",
},
{
route: "/reports",
name: "09-reports-dark",
waitFor: "h1, h2, [data-testid]",
},
]
// Error patterns to check for on each page
@@ -129,8 +157,14 @@ test.describe("Authenticated Admin Tour", () => {
console.log(" ⚠️ Form login didn't redirect. Checking for errors...")
const pageText = await page.locator("body").innerText()
if (pageText.includes("Ungültige") || pageText.includes("invalid") || pageText.includes("Fehler")) {
console.log(" ❌ Auth error on page. Trying cookie-based session bypass...")
if (
pageText.includes("Ungültige") ||
pageText.includes("invalid") ||
pageText.includes("Fehler")
) {
console.log(
" ❌ Auth error on page. Trying cookie-based session bypass..."
)
}
// Alternative: directly inject a NextAuth session token cookie
@@ -146,15 +180,18 @@ test.describe("Authenticated Admin Tour", () => {
console.log(` Using CSRF token: ${csrfToken?.substring(0, 20)}...`)
const signInResponse = await page.request.post("/api/auth/callback/credentials", {
form: {
email: "admin@gruener-daumen.de",
password: "test123",
csrfToken: csrfToken,
callbackUrl: "/dashboard",
json: "true",
},
})
const signInResponse = await page.request.post(
"/api/auth/callback/credentials",
{
form: {
email: "admin@gruener-daumen.de",
password: "test123",
csrfToken: csrfToken,
callbackUrl: "/dashboard",
json: "true",
},
}
)
// The response sets cookies — apply them
const cookies = signInResponse.headers()["set-cookie"]
@@ -171,7 +208,9 @@ test.describe("Authenticated Admin Tour", () => {
if (afterDirectUrl.includes("/login")) {
// Still redirected to login — one more approach: use page.request to get the session
console.log(" ⚠️ Still on login. Trying page.context().storageState approach...")
console.log(
" ⚠️ Still on login. Trying page.context().storageState approach..."
)
// Last resort: go through the full browser-based flow with longer waits
await page.goto("/login", { waitUntil: "domcontentloaded" })
@@ -181,7 +220,9 @@ test.describe("Authenticated Admin Tour", () => {
// Click and immediately wait for URL change
await Promise.all([
page.waitForURL("**/dashboard**", { timeout: 15_000 }).catch(() => null),
page
.waitForURL("**/dashboard**", { timeout: 15_000 })
.catch(() => null),
submitButton.click(),
])
@@ -190,7 +231,9 @@ test.describe("Authenticated Admin Tour", () => {
console.log(` Final URL: ${finalUrl}`)
if (finalUrl.includes("/login")) {
console.log(" ❌ All login attempts failed. Test will capture login-state screenshots.")
console.log(
" ❌ All login attempts failed. Test will capture login-state screenshots."
)
// We'll still screenshot whatever renders
}
}
@@ -215,14 +258,23 @@ test.describe("Authenticated Admin Tour", () => {
// Check if we were redirected to login (auth failed)
if (page.url().includes("/login")) {
console.log(` ⚠️ Redirected to /login — no session for ${adminPage.route}`)
allErrors.push(`${adminPage.name}: Redirected to login (no valid session)`)
console.log(
` ⚠️ Redirected to /login no session for ${adminPage.route}`
)
allErrors.push(
`${adminPage.name}: Redirected to login (no valid session)`
)
} else {
// Wait for content to appear
try {
await page.locator(adminPage.waitFor).first().waitFor({ timeout: 8000 })
await page
.locator(adminPage.waitFor)
.first()
.waitFor({ timeout: 8000 })
} catch {
console.log(` ⚠️ Content selector "${adminPage.waitFor}" not found within timeout`)
console.log(
` ⚠️ Content selector "${adminPage.waitFor}" not found within timeout`
)
}
// Check for errors
@@ -241,7 +293,9 @@ test.describe("Authenticated Admin Tour", () => {
// STEP 3: Summary
// ============================================
console.log("\n📊 Results:")
console.log(` Screenshots captured: ${captured.length}/${ADMIN_PAGES.length}`)
console.log(
` Screenshots captured: ${captured.length}/${ADMIN_PAGES.length}`
)
console.log(` Errors found: ${allErrors.length}`)
if (allErrors.length > 0) {
@@ -254,7 +308,9 @@ test.describe("Authenticated Admin Tour", () => {
// The test passes as long as screenshots were taken (even with login issues)
// but we assert no ERROR patterns on the actual rendered pages
const criticalErrors = allErrors.filter(
(e) => !e.includes("Redirected to login") && !e.includes("not found within timeout")
(e) =>
!e.includes("Redirected to login") &&
!e.includes("not found within timeout")
)
if (criticalErrors.length > 0) {
@@ -59,9 +59,9 @@ test.describe("Group 1: Login Form Interactions", () => {
expect(page.url()).toContain("/login")
// The email input should fail native HTML5 validation
const isInvalid = await page.locator('input[id="email"]').evaluate(
(el: HTMLInputElement) => !el.checkValidity()
)
const isInvalid = await page
.locator('input[id="email"]')
.evaluate((el: HTMLInputElement) => !el.checkValidity())
expect(isInvalid).toBe(true)
})
@@ -192,7 +192,9 @@ test.describe("Group 3: Navigation & Layout", () => {
const url = page.url()
// If redirected to login — that's also acceptable behavior for protected routes
const is404OrLogin = url.includes("/login") || url.includes("not-found")
expect(is404OrLogin || (await page.locator("body").textContent()) !== "").toBe(true)
expect(
is404OrLogin || (await page.locator("body").textContent()) !== ""
).toBe(true)
})
test("3.3 - Responsive: mobile viewport (375px)", async ({ page }) => {
@@ -611,9 +613,7 @@ test.describe("Group 11: Accessibility Basics", () => {
await expect(emailInput).toHaveAttribute("autoComplete", "email")
})
test("11.5 - Form submit button is keyboard-accessible", async ({
page,
}) => {
test("11.5 - Form submit button is keyboard-accessible", async ({ page }) => {
await page.goto("/login", { waitUntil: "domcontentloaded" })
await page.waitForSelector('input[id="email"]', { timeout: 15000 })
@@ -683,7 +683,8 @@ test.describe("Group 12: Error States & Edge Cases", () => {
// Page should not crash — wait and verify it's still functional
await page.waitForTimeout(3000)
const isStillOnLogin = page.url().includes("/login") || page.url().includes("/dashboard")
const isStillOnLogin =
page.url().includes("/login") || page.url().includes("/dashboard")
expect(isStillOnLogin).toBe(true)
})
+4 -1
View File
@@ -16,7 +16,10 @@ const MOCK_USER = {
const server = http.createServer((req, res) => {
// CORS headers
res.setHeader("Access-Control-Allow-Origin", "*")
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS"
)
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization")
if (req.method === "OPTIONS") {
@@ -20,15 +20,27 @@ const SCREENSHOT_DIR = path.join(__dirname, "..", "docs", "screenshots")
// Pages accessible without auth
const PUBLIC_PAGES = [
{ route: "/login", name: "01-login", title: "Admin Login" },
{ route: "/portal-login", name: "02-portal-login", title: "Member Portal Login" },
{
route: "/portal-login",
name: "02-portal-login",
title: "Member Portal Login",
},
]
// Admin pages (require auth session)
const ADMIN_PAGES = [
{ route: "/dashboard", name: "03-dashboard", title: "Club Dashboard" },
{ route: "/members", name: "04-members", title: "Member Management" },
{ route: "/distributions", name: "05-distributions", title: "Distribution History" },
{ route: "/distributions/new", name: "06-distribution-new", title: "New Distribution (Multi-Step)" },
{
route: "/distributions",
name: "05-distributions",
title: "Distribution History",
},
{
route: "/distributions/new",
name: "06-distribution-new",
title: "New Distribution (Multi-Step)",
},
{ route: "/stock", name: "07-stock", title: "Stock & Batch Management" },
{ route: "/stock/new", name: "08-stock-new", title: "Add New Batch" },
{ route: "/reports", name: "09-reports", title: "Compliance Reports" },
@@ -36,9 +48,21 @@ const ADMIN_PAGES = [
// Portal pages (no admin auth needed per middleware)
const PORTAL_PAGES = [
{ route: "/portal/dashboard", name: "10-portal-dashboard", title: "Member Quota Overview" },
{ route: "/portal/history", name: "11-portal-history", title: "My Distribution History" },
{ route: "/portal/profile", name: "12-portal-profile", title: "Profile & Settings" },
{
route: "/portal/dashboard",
name: "10-portal-dashboard",
title: "Member Quota Overview",
},
{
route: "/portal/history",
name: "11-portal-history",
title: "My Distribution History",
},
{
route: "/portal/profile",
name: "12-portal-profile",
title: "Profile & Settings",
},
]
async function setTheme(page: Page, theme: "dark" | "light") {
@@ -76,7 +100,12 @@ test.describe("CannaManage Screenshot Tour", () => {
test.setTimeout(120_000)
test("capture all pages in dark and light mode", async ({ page }) => {
const results: { name: string; title: string; dark: string; light: string }[] = []
const results: {
name: string
title: string
dark: string
light: string
}[] = []
// --- PUBLIC PAGES ---
for (const p of PUBLIC_PAGES) {
@@ -102,13 +131,19 @@ test.describe("CannaManage Screenshot Tour", () => {
}
// Check if we got authenticated (redirected to dashboard)
const isAuthenticated = page.url().includes("/dashboard") || page.url().includes("/login")
const isAuthenticated =
page.url().includes("/dashboard") || page.url().includes("/login")
if (page.url().includes("/dashboard")) {
// --- ADMIN PAGES (authenticated) ---
for (const p of ADMIN_PAGES) {
const dark = await capturePageScreenshot(page, p.route, p.name, "dark")
const light = await capturePageScreenshot(page, p.route, p.name, "light")
const light = await capturePageScreenshot(
page,
p.route,
p.name,
"light"
)
results.push({ name: p.name, title: p.title, dark, light })
}
} else {
@@ -116,7 +151,12 @@ test.describe("CannaManage Screenshot Tour", () => {
console.log("⚠️ Auth failed — admin pages will show login redirect")
for (const p of ADMIN_PAGES) {
const dark = await capturePageScreenshot(page, p.route, p.name, "dark")
results.push({ name: p.name, title: `${p.title} (auth required)`, dark, light: dark })
results.push({
name: p.name,
title: `${p.title} (auth required)`,
dark,
light: dark,
})
}
}
@@ -147,7 +187,9 @@ test.describe("CannaManage Screenshot Tour", () => {
}
fs.writeFileSync(path.join(docsDir, "visual-tour.md"), md)
console.log(`\n✅ Screenshot tour complete! ${results.length} pages captured.`)
console.log(
`\n✅ Screenshot tour complete! ${results.length} pages captured.`
)
console.log(`📄 Markdown: docs/visual-tour.md`)
console.log(`📸 Screenshots: docs/screenshots/`)
})
@@ -26,7 +26,9 @@ test.describe("Staff Management", () => {
// If redirected to login, that's expected without a running backend
if (page.url().includes("/login")) {
console.log(" ️ Redirected to login (no session) — expected without backend")
console.log(
" ️ Redirected to login (no session) — expected without backend"
)
return
}
@@ -53,7 +55,9 @@ test.describe("Staff Management", () => {
// Sheet/dialog should open with form fields
const hasEmailField =
(await page.locator('input[type="email"], input[name="email"]').count()) > 0
(await page
.locator('input[type="email"], input[name="email"]')
.count()) > 0
expect(hasEmailField).toBe(true)
}
})
@@ -69,7 +73,8 @@ test.describe("Staff Management", () => {
// Check for table or list structure
const hasTable = (await page.locator("table").count()) > 0
const hasList = (await page.locator('[role="list"], [data-testid*="staff"]').count()) > 0
const hasList =
(await page.locator('[role="list"], [data-testid*="staff"]').count()) > 0
expect(hasTable || hasList).toBe(true)
})
@@ -1,4 +1,4 @@
{
"status": "passed",
"failedTests": []
}
}
+20 -1
View File
@@ -489,5 +489,24 @@
"created": "Anbau gestartet.",
"stageAdvanced": "Phase gewechselt zu {stage}.",
"harvestComplete": "Ernte abgeschlossen — {grams}g verknüpft mit Charge."
},
"notifications": {
"title": "Benachrichtigungen",
"markAllRead": "Alle als gelesen markieren",
"noNotifications": "Keine Benachrichtigungen",
"unread": "{count} ungelesen",
"types": {
"QUOTA_WARNING": "Kontingent-Warnung",
"BATCH_RECALLED": "Chargen-Rückruf",
"DISTRIBUTION_RECORDED": "Ausgabe erfasst",
"SUBSCRIPTION_EXPIRING": "Abo läuft bald ab"
}
},
"pwa": {
"install": "Als App installieren",
"installDesc": "Für schnelleren Zugriff CannaManage auf dem Startbildschirm hinzufügen.",
"offline": "Keine Internetverbindung",
"offlineDesc": "Die App funktioniert eingeschränkt im Offline-Modus.",
"retry": "Erneut verbinden"
}
}
}
+20 -1
View File
@@ -489,5 +489,24 @@
"created": "Grow started.",
"stageAdvanced": "Stage advanced to {stage}.",
"harvestComplete": "Harvest completed — {grams}g linked to batch."
},
"notifications": {
"title": "Notifications",
"markAllRead": "Mark all as read",
"noNotifications": "No notifications",
"unread": "{count} unread",
"types": {
"QUOTA_WARNING": "Quota Warning",
"BATCH_RECALLED": "Batch Recalled",
"DISTRIBUTION_RECORDED": "Distribution Recorded",
"SUBSCRIPTION_EXPIRING": "Subscription Expiring"
}
},
"pwa": {
"install": "Install as App",
"installDesc": "Add CannaManage to your home screen for faster access.",
"offline": "No Internet Connection",
"offlineDesc": "The app has limited functionality in offline mode.",
"retry": "Reconnect"
}
}
}
+5575 -3091
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 69 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 B

+24
View File
@@ -0,0 +1,24 @@
{
"name": "CannaManage",
"short_name": "CannaManage",
"description": "Cannabis-Club Verwaltung",
"start_url": "/",
"display": "standalone",
"background_color": "#0D1117",
"theme_color": "#2ECC71",
"orientation": "portrait-primary",
"icons": [
{
"src": "/icons/icon-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any maskable"
},
{
"src": "/icons/icon-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any maskable"
}
]
}
+72
View File
@@ -0,0 +1,72 @@
/// <reference lib="webworker" />
const CACHE_NAME = "cannamanage-v1"
const OFFLINE_URL = "/offline"
// Assets to pre-cache
const PRECACHE_ASSETS = [
"/offline",
"/manifest.json",
"/icons/icon-192.png",
"/icons/icon-512.png",
]
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(PRECACHE_ASSETS)
})
)
self.skipWaiting()
})
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames
.filter((name) => name !== CACHE_NAME)
.map((name) => caches.delete(name))
)
})
)
self.clients.claim()
})
self.addEventListener("fetch", (event) => {
// Only handle GET requests
if (event.request.method !== "GET") return
// Skip API requests — let them fail naturally
if (event.request.url.includes("/api/")) return
// Network-first for navigation requests
if (event.request.mode === "navigate") {
event.respondWith(
fetch(event.request).catch(() => {
return caches.match(OFFLINE_URL)
})
)
return
}
// Stale-while-revalidate for static assets
if (
event.request.destination === "style" ||
event.request.destination === "script" ||
event.request.destination === "image"
) {
event.respondWith(
caches.match(event.request).then((cachedResponse) => {
const fetchPromise = fetch(event.request).then((networkResponse) => {
if (networkResponse && networkResponse.status === 200) {
const cache = caches.open(CACHE_NAME)
cache.then((c) => c.put(event.request, networkResponse.clone()))
}
return networkResponse
})
return cachedResponse || fetchPromise
})
)
}
})
@@ -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
View File
@@ -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",
})
}
@@ -0,0 +1,88 @@
package de.cannamanage.service;
import de.cannamanage.domain.entity.Notification;
import de.cannamanage.domain.enums.NotificationType;
import de.cannamanage.service.repository.NotificationRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Notification service — persists notifications and delivers in real-time via WebSocket.
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class NotificationService {
private final NotificationRepository notificationRepository;
private final SimpMessagingTemplate messagingTemplate;
/**
* Send a notification: persist to DB + push via WebSocket.
*/
@Transactional
public Notification sendNotification(UUID userId, NotificationType type, String title, String message, String link) {
var notification = new Notification(userId, type, title, message, link);
notification = notificationRepository.save(notification);
// Push to user's WebSocket queue
messagingTemplate.convertAndSendToUser(
userId.toString(),
"/queue/notifications",
Map.of(
"id", notification.getId(),
"type", notification.getType().name(),
"title", notification.getTitle(),
"message", notification.getMessage(),
"link", notification.getLink() != null ? notification.getLink() : "",
"read", notification.isRead(),
"createdAt", notification.getCreatedAt().toString()
)
);
log.debug("Notification sent to user {}: {} - {}", userId, type, title);
return notification;
}
/**
* Get the last 10 notifications for a user (unread first).
*/
@Transactional(readOnly = true)
public List<Notification> getRecentNotifications(UUID userId) {
return notificationRepository.findTop10ByUserIdOrderByReadAscCreatedAtDesc(userId);
}
/**
* Get unread count for badge display.
*/
@Transactional(readOnly = true)
public long getUnreadCount(UUID userId) {
return notificationRepository.countByUserIdAndReadFalse(userId);
}
/**
* Mark a single notification as read.
*/
@Transactional
public void markAsRead(UUID notificationId) {
notificationRepository.findById(notificationId).ifPresent(n -> {
n.setRead(true);
notificationRepository.save(n);
});
}
/**
* Mark all notifications as read for a user.
*/
@Transactional
public int markAllAsRead(UUID userId) {
return notificationRepository.markAllAsRead(userId);
}
}
@@ -0,0 +1,25 @@
package de.cannamanage.service.repository;
import de.cannamanage.domain.entity.Notification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.UUID;
@Repository
public interface NotificationRepository extends JpaRepository<Notification, UUID> {
List<Notification> findByUserIdOrderByReadAscCreatedAtDesc(UUID userId);
List<Notification> findTop10ByUserIdOrderByReadAscCreatedAtDesc(UUID userId);
long countByUserIdAndReadFalse(UUID userId);
@Modifying
@Query("UPDATE Notification n SET n.read = true WHERE n.userId = :userId AND n.read = false")
int markAllAsRead(@Param("userId") UUID userId);
}