feat(notifications): open bell popover
CI and Deploy / test (pull_request) Failing after 2m55s
CI and Deploy / deploy (pull_request) Has been skipped

This commit is contained in:
cesnimda
2026-08-15 13:37:29 +02:00
parent 109745edb0
commit 998ee07a9a
13 changed files with 321 additions and 32 deletions
+10 -1
View File
@@ -23,6 +23,7 @@ import { ConfirmProvider } from "./confirm";
import { PromptProvider } from "./prompt";
import JobTable from "./components/JobTable";
import NotificationsPopover from "./components/NotificationsPopover";
import type { JobTableColumns } from "./components/JobTable";
import { I18nProvider, useI18n } from "./i18n/I18nProvider";
import LoginPage from "./views/LoginPage";
@@ -164,6 +165,7 @@ function Shell({ jobPageSize, setJobPageSize, jobColumns, setJobColumns, themeMo
const [mobileDrawerOpen, setMobileDrawerOpen] = useState(false);
const [reminderCount, setReminderCount] = useState(0);
const [notificationCount, setNotificationCount] = useState(0);
const [notificationAnchor, setNotificationAnchor] = useState<HTMLElement | null>(null);
const path = location.pathname;
const isJobs = path.startsWith("/jobs");
@@ -347,7 +349,7 @@ function Shell({ jobPageSize, setJobPageSize, jobColumns, setJobColumns, themeMo
onNavigate={(to) => { setMobileDrawerOpen(false); navigate(to); }}
user={{ email: me?.email, userName: me?.userName, displayName: me?.displayName || fullName || undefined, avatarImageDataUrl: me?.avatarImageDataUrl, roleLabel: isAdmin ? t("superAdmin") : t("user") }}
notificationsCount={notificationCount}
onOpenNotifications={() => navigate("/operations")}
onOpenNotifications={(anchor) => setNotificationAnchor(anchor)}
onOpenSettings={() => navigate("/settings")}
onOpenProfile={() => navigate("/profile")}
onSignOut={() => { void api.post("/auth/logout").catch(() => undefined).finally(() => { clearAuthClientState(); navigate("/login"); }); }}
@@ -382,6 +384,13 @@ function Shell({ jobPageSize, setJobPageSize, jobColumns, setJobColumns, themeMo
</Suspense>
</AppShell>
<NotificationsPopover
anchorEl={notificationAnchor}
onClose={() => setNotificationAnchor(null)}
onNavigate={(to) => navigate(to)}
onChanged={() => window.dispatchEvent(new Event("notifications-changed"))}
/>
<Suspense fallback={null}>
<AddJobModal open={addOpen} initialUrl={captureUrl} onClose={() => { setAddOpen(false); setCaptureUrl(undefined); }} onCreated={() => { setRefreshToken((t) => t + 1); }} />
<QuickCommandDialog open={quickOpen} onClose={() => setQuickOpen(false)} onNavigate={(to) => navigate(to)} onOpenAddJob={() => setAddOpen(true)} />
@@ -34,4 +34,5 @@ test("notification bell exposes its unread count and keyboard-accessible action"
expect(screen.getByText("3")).toBeInTheDocument();
fireEvent.click(bell);
expect(open).toHaveBeenCalledTimes(1);
expect(open.mock.calls[0][0]).toBeInstanceOf(HTMLElement);
});
@@ -0,0 +1,167 @@
import React, { useCallback, useEffect, useState } from "react";
import {
Alert,
Box,
Button,
CircularProgress,
Divider,
IconButton,
Popover,
Stack,
Tooltip,
Typography,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import DoneIcon from "@mui/icons-material/Done";
import { api, getApiErrorMessage } from "../api";
import { useI18n } from "../i18n/I18nProvider";
import { notificationDateLabel, UserNotification } from "../notifications";
type Props = {
anchorEl: HTMLElement | null;
onClose: () => void;
onNavigate: (path: string) => void;
onChanged: () => void;
};
export default function NotificationsPopover({ anchorEl, onClose, onNavigate, onChanged }: Props) {
const { t } = useI18n();
const open = Boolean(anchorEl);
const [notifications, setNotifications] = useState<UserNotification[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [busyId, setBusyId] = useState<string | null>(null);
const load = useCallback(async () => {
setLoading(true);
try {
const response = await api.get<UserNotification[]>("/notifications?limit=10");
setNotifications(response.data ?? []);
setError(null);
} catch (requestError) {
setError(getApiErrorMessage(requestError, t("notificationsLoadFailed")));
} finally {
setLoading(false);
}
}, [t]);
useEffect(() => {
if (open) void load();
}, [load, open]);
const markRead = async (notification: UserNotification) => {
if (notification.readAtUtc || busyId) return;
setBusyId(notification.id);
try {
await api.post(`/notifications/${notification.id}/read`);
setNotifications((items) => items.map((item) => item.id === notification.id
? { ...item, readAtUtc: new Date().toISOString() }
: item));
setError(null);
onChanged();
} catch (requestError) {
setError(getApiErrorMessage(requestError, t("notificationsActionFailed")));
} finally {
setBusyId(null);
}
};
const dismiss = async (notification: UserNotification) => {
if (busyId) return;
setBusyId(notification.id);
try {
await api.delete(`/notifications/${notification.id}`);
setNotifications((items) => items.filter((item) => item.id !== notification.id));
setError(null);
onChanged();
} catch (requestError) {
setError(getApiErrorMessage(requestError, t("notificationsActionFailed")));
} finally {
setBusyId(null);
}
};
const openNotification = async (notification: UserNotification) => {
if (!notification.linkPath) return;
if (!notification.readAtUtc) await markRead(notification);
onClose();
onNavigate(notification.linkPath);
};
return (
<Popover
open={open}
anchorEl={anchorEl}
onClose={onClose}
anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
transformOrigin={{ vertical: "top", horizontal: "right" }}
slotProps={{
paper: {
"aria-label": t("notificationsPanel"),
sx: {
mt: 1,
width: "min(420px, calc(100vw - 24px))",
maxHeight: "min(70vh, 600px)",
borderRadius: 3,
overflow: "hidden",
},
},
}}
>
<Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ px: 2, py: 1.5 }}>
<Box>
<Typography sx={{ fontWeight: 900 }}>{t("notifications")}</Typography>
<Typography variant="caption" color="text.secondary">{t("notificationsRecent")}</Typography>
</Box>
<Tooltip title={t("close")}>
<IconButton size="small" aria-label={t("close")} onClick={onClose}><CloseIcon fontSize="small" /></IconButton>
</Tooltip>
</Stack>
<Divider />
<Box sx={{ overflowY: "auto", maxHeight: "min(52vh, 450px)", p: 1 }}>
{loading ? <Box sx={{ py: 4, display: "grid", placeItems: "center" }}><CircularProgress size={28} aria-label={t("loading")} /></Box> : null}
{error ? <Alert severity="error" action={<Button color="inherit" size="small" onClick={() => void load()}>{t("retry")}</Button>} sx={{ m: 0.5 }}>{error}</Alert> : null}
{!loading && !error && notifications.length === 0 ? (
<Box sx={{ py: 4, px: 2, textAlign: "center" }}>
<Typography sx={{ fontWeight: 800 }}>{t("notificationsEmptyTitle")}</Typography>
<Typography variant="body2" color="text.secondary">{t("notificationsEmptyBody")}</Typography>
</Box>
) : null}
{!loading ? notifications.map((notification) => (
<Box
key={notification.id}
sx={{
p: 1.5,
mb: 0.75,
borderRadius: 2.5,
border: "1px solid",
borderColor: "divider",
bgcolor: notification.readAtUtc ? "transparent" : "action.selected",
opacity: notification.readAtUtc ? 0.82 : 1,
}}
>
<Typography sx={{ fontWeight: notification.readAtUtc ? 700 : 900, overflowWrap: "anywhere" }}>{notification.title}</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mt: 0.25, overflowWrap: "anywhere" }}>{notification.message}</Typography>
<Typography variant="caption" color="text.secondary">{notificationDateLabel(notification.createdAtUtc)}</Typography>
<Stack direction="row" spacing={0.5} alignItems="center" sx={{ mt: 0.75, flexWrap: "wrap" }}>
{notification.linkPath ? <Button size="small" onClick={() => void openNotification(notification)}>{t("notificationsOpen")}</Button> : null}
{!notification.readAtUtc ? (
<Button size="small" startIcon={<DoneIcon />} disabled={busyId !== null} onClick={() => void markRead(notification)}>{t("notificationsMarkRead")}</Button>
) : null}
<Button size="small" color="inherit" startIcon={<DeleteOutlineIcon />} disabled={busyId !== null} onClick={() => void dismiss(notification)}>{t("notificationsDismiss")}</Button>
</Stack>
</Box>
)) : null}
</Box>
<Divider />
<Box sx={{ p: 1 }}>
<Button fullWidth onClick={() => { onClose(); onNavigate("/operations"); }}>{t("notificationsViewAll")}</Button>
</Box>
</Popover>
);
}
+22
View File
@@ -33,6 +33,17 @@ export const translations = {
systemStatus: "System status",
manage: "Manage",
notifications: "Notifications",
notificationsPanel: "Notifications panel",
notificationsRecent: "Recent updates and background work",
notificationsLoadFailed: "Notifications could not be loaded.",
notificationsActionFailed: "The notification could not be updated.",
notificationsEmptyTitle: "You're all caught up",
notificationsEmptyBody: "New alerts and completed background work will appear here.",
notificationsOpen: "Open",
notificationsMarkRead: "Mark read",
notificationsDismiss: "Dismiss",
notificationsViewAll: "View all activity",
retry: "Retry",
quickSearch: "Quick Search",
searchPlaceholder: "Search jobs, companies, or actions",
noMatchingCommands: "No matching commands or records.",
@@ -1174,6 +1185,17 @@ export const translations = {
systemStatus: "Systemstatus",
manage: "Administrer",
notifications: "Varsler",
notificationsPanel: "Varslingspanel",
notificationsRecent: "Nylige oppdateringer og bakgrunnsarbeid",
notificationsLoadFailed: "Varslene kunne ikke lastes.",
notificationsActionFailed: "Varslet kunne ikke oppdateres.",
notificationsEmptyTitle: "Du er ajour",
notificationsEmptyBody: "Nye varsler og fullført bakgrunnsarbeid vises her.",
notificationsOpen: "Åpne",
notificationsMarkRead: "Marker som lest",
notificationsDismiss: "Fjern",
notificationsViewAll: "Vis all aktivitet",
retry: "Prøv igjen",
quickSearch: "Hurtigsøk",
searchPlaceholder: "Søk etter jobber, selskaper eller handlinger",
noMatchingCommands: "Ingen treff på kommandoer eller poster.",
+3 -3
View File
@@ -101,7 +101,7 @@ export default function AppShell({
drawerOpen: boolean;
user?: { email?: string; userName?: string; displayName?: string; avatarImageDataUrl?: string; roleLabel?: string };
notificationsCount?: number;
onOpenNotifications?: () => void;
onOpenNotifications?: (anchorEl: HTMLElement) => void;
onOpenSettings?: () => void;
onOpenProfile?: () => void;
onSignOut?: () => void;
@@ -301,7 +301,7 @@ export default function AppShell({
size="small"
title={t("notifications")}
aria-label={t("notifications")}
onClick={onOpenNotifications}
onClick={(event) => onOpenNotifications?.(event.currentTarget)}
sx={{ border: "1px solid", borderColor: "divider", borderRadius: 2.5, width: 42, height: 42 }}
>
<Badge color="primary" badgeContent={notificationsCount || 0} max={99}>
@@ -363,7 +363,7 @@ export default function AppShell({
size="small"
title={t("notifications")}
aria-label={t("notifications")}
onClick={onOpenNotifications}
onClick={(event) => onOpenNotifications?.(event.currentTarget)}
sx={{ border: "1px solid", borderColor: "divider", borderRadius: 2 }}
>
<Badge color="primary" badgeContent={notificationsCount || 0} max={99}>
@@ -0,0 +1,84 @@
import React from "react";
import "@testing-library/jest-dom";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { api } from "./api";
import NotificationsPopover from "./components/NotificationsPopover";
import { I18nProvider } from "./i18n/I18nProvider";
jest.mock("./api", () => ({
api: {
get: jest.fn(),
post: jest.fn(),
delete: jest.fn(),
interceptors: { request: { use: jest.fn() }, response: { use: jest.fn() } },
},
getApiErrorMessage: (_error: unknown, fallback?: string) => fallback || "Request failed.",
}));
const mockedApi = api as jest.Mocked<typeof api>;
const notification = {
id: "22222222-2222-2222-2222-222222222222",
operationId: null,
kind: "operation_failed",
title: "CV export failed",
message: "Review the operation and try again.",
linkPath: "/operations",
createdAtUtc: "2026-08-15T12:00:00Z",
readAtUtc: null,
};
function renderPopover(overrides: Partial<React.ComponentProps<typeof NotificationsPopover>> = {}) {
const anchor = document.createElement("button");
document.body.appendChild(anchor);
const props = {
anchorEl: anchor,
onClose: jest.fn(),
onNavigate: jest.fn(),
onChanged: jest.fn(),
...overrides,
};
const result = render(<I18nProvider><NotificationsPopover {...props} /></I18nProvider>);
return { ...result, props, anchor };
}
beforeEach(() => {
jest.clearAllMocks();
mockedApi.get.mockResolvedValue({ data: [notification] } as any);
mockedApi.post.mockResolvedValue({ data: {} } as any);
mockedApi.delete.mockResolvedValue({ data: {} } as any);
});
test("shows notifications and updates read and dismissed state in place", async () => {
const { props } = renderPopover();
expect(await screen.findByText("CV export failed")).toBeInTheDocument();
expect(mockedApi.get).toHaveBeenCalledWith("/notifications?limit=10");
fireEvent.click(screen.getByRole("button", { name: "Mark read" }));
await waitFor(() => expect(mockedApi.post).toHaveBeenCalledWith(`/notifications/${notification.id}/read`));
expect(props.onChanged).toHaveBeenCalledTimes(1);
await waitFor(() => expect(screen.queryByRole("button", { name: "Mark read" })).not.toBeInTheDocument());
fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));
await waitFor(() => expect(mockedApi.delete).toHaveBeenCalledWith(`/notifications/${notification.id}`));
await waitFor(() => expect(screen.queryByText("CV export failed")).not.toBeInTheDocument());
expect(props.onChanged).toHaveBeenCalledTimes(2);
});
test("opens a notification destination instead of routing the bell itself", async () => {
const { props } = renderPopover();
fireEvent.click(await screen.findByRole("button", { name: "Open" }));
await waitFor(() => expect(props.onNavigate).toHaveBeenCalledWith("/operations"));
expect(mockedApi.post).toHaveBeenCalledWith(`/notifications/${notification.id}/read`);
expect(props.onClose).toHaveBeenCalledTimes(1);
});
test("shows an honest empty state", async () => {
mockedApi.get.mockResolvedValue({ data: [] } as any);
renderPopover();
expect(await screen.findByText("You're all caught up")).toBeInTheDocument();
});
+15
View File
@@ -0,0 +1,15 @@
export type UserNotification = {
id: string;
operationId?: string | null;
kind: string;
title: string;
message: string;
linkPath?: string | null;
createdAtUtc: string;
readAtUtc?: string | null;
};
export function notificationDateLabel(value: string): string {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? "" : date.toLocaleString();
}
+4 -16
View File
@@ -12,6 +12,7 @@ import {
} from "@mui/material";
import { api, getApiErrorMessage } from "../api";
import { notificationDateLabel, UserNotification } from "../notifications";
type Operation = {
id: string;
@@ -28,25 +29,12 @@ type Operation = {
canRetry: boolean;
};
type Notification = {
id: string;
operationId?: string | null;
kind: string;
title: string;
message: string;
createdAtUtc: string;
readAtUtc?: string | null;
};
const statusLabel = (value: string) => value.replaceAll("_", " ");
const dateLabel = (value: string) => {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? "" : date.toLocaleString();
};
const dateLabel = notificationDateLabel;
export default function OperationsPage() {
const [operations, setOperations] = useState<Operation[]>([]);
const [notifications, setNotifications] = useState<Notification[]>([]);
const [notifications, setNotifications] = useState<UserNotification[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [busyKey, setBusyKey] = useState<string | null>(null);
@@ -56,7 +44,7 @@ export default function OperationsPage() {
try {
const [operationResponse, notificationResponse] = await Promise.all([
api.get<Operation[]>("/operations?limit=50"),
api.get<Notification[]>("/notifications?limit=50"),
api.get<UserNotification[]>("/notifications?limit=50"),
]);
setOperations(operationResponse.data ?? []);
setNotifications(notificationResponse.data ?? []);