feat(platform): add the notification inbox and deterministic match search

This commit is contained in:
shira committed 2026-10-09 13:14:46 +03:00
1 parent 5edff21d2d
commit 0b11021b16
169 files changed
+17083 -443

No files matched your search

@@ -0,0 +1,3 @@
export { NotificationInbox } from "./ui/notification-inbox";
export { OrganizationNotificationInbox } from "./ui/organization-notification-inbox";
export type { NotificationScope } from "./model/scope";
@@ -0,0 +1,61 @@
import { describe, expect, it, vi } from "vitest";
import { ApiRequestError } from "../../../shared/api";
import { isMarkAccessLoss, markWithSessionRetry } from "./mark-read";
function failure(
status: number,
code: "csrf_check_failed" | "not_found" | "unauthenticated" | "internal",
) {
return new ApiRequestError({ status, code, title: "problem" });
}
describe("isMarkAccessLoss", () => {
it("counts only a lost session or a gone item, not a refusal", () => {
expect(isMarkAccessLoss(failure(401, "unauthenticated"))).toBe(true);
expect(isMarkAccessLoss(failure(404, "not_found"))).toBe(true);
expect(isMarkAccessLoss(failure(403, "csrf_check_failed"))).toBe(false);
expect(isMarkAccessLoss(failure(500, "internal"))).toBe(false);
expect(isMarkAccessLoss(new Error("network"))).toBe(false);
});
});
describe("markWithSessionRetry", () => {
it("sends once when the first request succeeds", async () => {
const attempt = vi.fn().mockResolvedValue("ok");
const refresh = vi.fn().mockResolvedValue(undefined);
await expect(markWithSessionRetry(attempt, refresh)).resolves.toBe("ok");
expect(attempt).toHaveBeenCalledTimes(1);
expect(refresh).not.toHaveBeenCalled();
});
it("reads the session again and retries once after a 403", async () => {
const attempt = vi
.fn()
.mockRejectedValueOnce(failure(403, "csrf_check_failed"))
.mockResolvedValueOnce("ok");
const refresh = vi.fn().mockResolvedValue(undefined);
await expect(markWithSessionRetry(attempt, refresh)).resolves.toBe("ok");
expect(refresh).toHaveBeenCalledTimes(1);
expect(attempt).toHaveBeenCalledTimes(2);
});
it("gives up after the second refusal and does not loop", async () => {
const refusal = failure(403, "csrf_check_failed");
const attempt = vi.fn().mockRejectedValue(refusal);
const refresh = vi.fn().mockResolvedValue(undefined);
await expect(markWithSessionRetry(attempt, refresh)).rejects.toBe(refusal);
expect(attempt).toHaveBeenCalledTimes(2);
expect(refresh).toHaveBeenCalledTimes(1);
});
it.each([failure(401, "unauthenticated"), failure(404, "not_found"), failure(500, "internal")])(
"does not retry a $status",
async (error) => {
const attempt = vi.fn().mockRejectedValue(error);
const refresh = vi.fn().mockResolvedValue(undefined);
await expect(markWithSessionRetry(attempt, refresh)).rejects.toBe(error);
expect(attempt).toHaveBeenCalledTimes(1);
expect(refresh).not.toHaveBeenCalled();
},
);
});
@@ -0,0 +1,35 @@
import { ApiRequestError } from "../../../shared/api";
/**
* A mark loses access only when the session ended (401) or the item or the
* organization is gone for this account (404). A 403 is different: after a
* sign-in in another tab the CSRF token of this tab is stale, and that must
* not be reported as lost access.
*/
export function isMarkAccessLoss(error: unknown): error is ApiRequestError {
return error instanceof ApiRequestError && (error.status === 401 || error.status === 404);
}
/** True for a refusal that a fresh session may fix, such as a stale CSRF token. */
export function isRetryableMarkRefusal(error: unknown): error is ApiRequestError {
return error instanceof ApiRequestError && error.status === 403;
}
/**
* Sends a mark and, after a 403, reads the session again and sends it once
* more with whatever the session now holds. `attempt` must take its CSRF
* token from the session at call time. A second refusal, or any other error,
* is returned to the caller as it is.
*/
export async function markWithSessionRetry<T>(
attempt: () => Promise<T>,
refreshSession: () => Promise<void>,
): Promise<T> {
try {
return await attempt();
} catch (error: unknown) {
if (!isRetryableMarkRefusal(error)) throw error;
await refreshSession();
return attempt();
}
}
@@ -0,0 +1,57 @@
import { describe, expect, it } from "vitest";
import {
formatDeliveredAt,
notificationKindLabel,
safeNotificationPath,
unavailableContentText,
} from "./presentation";
const candidate = { kind: "candidate" } as const;
const organization = { kind: "organization", organizationId: "org" } as const;
describe("safeNotificationPath", () => {
it("opens only a same-origin path of the cabinet that shows it", () => {
expect(safeNotificationPath("/candidate/invitations", candidate)).toBe(
"/candidate/invitations",
);
expect(safeNotificationPath("/employer/invitations", organization)).toBe(
"/employer/invitations",
);
expect(safeNotificationPath("/employer/invitations", candidate)).toBeNull();
expect(safeNotificationPath("/candidate/invitations", organization)).toBeNull();
expect(safeNotificationPath("/candidatex", candidate)).toBeNull();
});
it.each([
"https://evil.example/candidate",
"//evil.example/candidate",
"/candidate/../employer",
"/candidate/a?token=1",
"/candidate/a#b",
"/candidate/%2e%2e",
"/candidate\\a",
"javascript:alert(1)",
"",
null,
undefined,
])("refuses %s", (path) => {
expect(safeNotificationPath(path, candidate)).toBeNull();
});
});
describe("notification wording", () => {
it("labels known kinds and keeps an unknown kind generic", () => {
expect(notificationKindLabel("invitation_delivered")).toBe("Приглашение");
expect(notificationKindLabel("synthetic")).toContain("Тестовое");
expect(notificationKindLabel("something_new")).toBe("Уведомление");
});
it("says plainly that the content is gone and shows no earlier copy", () => {
expect(unavailableContentText).toContain("больше недоступно");
});
it("formats a delivery time in a given zone and ignores an invalid value", () => {
expect(formatDeliveredAt("2026-10-09T08:30:00Z", "UTC")).toMatch(/9 октября.*08:30/);
expect(formatDeliveredAt("not a date")).toBe("");
});
});
@@ -0,0 +1,56 @@
import type { Notification } from "../../../shared/api/schemas";
import type { NotificationScope } from "./scope";
const kindLabels: Readonly<Record<Notification["kind"], string>> = {
invitation_delivered: "Приглашение",
synthetic: "Тестовое уведомление платформы",
};
/** Label of the event that produced a notification; unknown kinds stay generic. */
export function notificationKindLabel(kind: string): string {
return (kindLabels as Readonly<Record<string, string>>)[kind] ?? "Уведомление";
}
/**
* Shown when the server returned no content: the source is gone or the
* recipient may not see it now. The client never keeps an earlier copy.
*/
export const unavailableContentText =
"Содержимое больше недоступно. Уведомление осталось в списке, но его текст не показывается.";
const linkPathPattern = /^\/[A-Za-z0-9/_-]{0,255}$/;
const cabinetRoots: Readonly<Record<NotificationScope["kind"], string>> = {
candidate: "/candidate",
organization: "/employer",
};
/**
* A content link is opened only when it is a same-origin path of the cabinet
* that shows it. The server already restricts the shape; the client repeats
* the check so a malformed value can never become an external navigation.
*/
export function safeNotificationPath(
path: string | null | undefined,
scope: NotificationScope,
): string | null {
if (!path || path.startsWith("//") || !linkPathPattern.test(path)) return null;
const root = cabinetRoots[scope.kind];
return path === root || path.startsWith(`${root}/`) ? path : null;
}
function dateFormat(timeZone?: string): Intl.DateTimeFormat {
return new Intl.DateTimeFormat("ru-RU", {
day: "numeric",
month: "long",
hour: "2-digit",
minute: "2-digit",
...(timeZone ? { timeZone } : {}),
});
}
/** Date and time of a delivery in the browser zone; empty for an invalid value. */
export function formatDeliveredAt(value: string, timeZone?: string): string {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? "" : dateFormat(timeZone).format(date);
}
@@ -0,0 +1,40 @@
import { QueryClient } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import {
notificationListQueryKey,
notificationOrganizationsQueryKey,
notificationScopeKey,
removeNotificationQueries,
} from "./scope";
describe("notification query keys", () => {
it("separate accounts and cabinets", () => {
const candidate = notificationListQueryKey("a", { kind: "candidate" });
const first = notificationListQueryKey("a", { kind: "organization", organizationId: "o1" });
const second = notificationListQueryKey("a", { kind: "organization", organizationId: "o2" });
const other = notificationListQueryKey("b", { kind: "candidate" });
expect(new Set([candidate, first, second, other].map((key) => key.join("/"))).size).toBe(4);
expect(notificationScopeKey({ kind: "organization", organizationId: "o1" })).toBe(
"organization:o1",
);
});
it("drops the cached inbox of one account or of every account, and nothing else", () => {
const queryClient = new QueryClient();
const a = notificationListQueryKey("a", { kind: "candidate" });
const b = notificationListQueryKey("b", { kind: "candidate" });
const directory = notificationOrganizationsQueryKey("a");
const unrelated = ["account", "a", "support-cases", "list"] as const;
for (const key of [a, b, directory, unrelated]) queryClient.setQueryData(key, { value: 1 });
removeNotificationQueries(queryClient, "a");
expect(queryClient.getQueryData(a)).toBeUndefined();
expect(queryClient.getQueryData(directory)).toBeUndefined();
expect(queryClient.getQueryData(b)).toBeDefined();
expect(queryClient.getQueryData(unrelated)).toBeDefined();
removeNotificationQueries(queryClient);
expect(queryClient.getQueryData(b)).toBeUndefined();
expect(queryClient.getQueryData(unrelated)).toBeDefined();
});
});
@@ -0,0 +1,40 @@
import type { QueryClient } from "@tanstack/react-query";
/**
* Which inbox a screen reads. The candidate cabinet spans every organization
* that sent to the account; an employer cabinet is always one organization.
* The scope selects the operation only: the server derives the recipient from
* the session and re-checks the membership on every request.
*/
export type NotificationScope =
| { readonly kind: "candidate" }
| { readonly kind: "organization"; readonly organizationId: string };
export const notificationPageSize = 20;
export function notificationScopeKey(scope: NotificationScope): string {
return scope.kind === "candidate" ? "candidate" : `organization:${scope.organizationId}`;
}
/**
* Cached inbox pages belong to one account and one cabinet, so the account
* comes first and a query can be dropped by account or by cabinet.
*/
export function notificationListQueryKey(accountId: string, scope: NotificationScope) {
return ["account", accountId, "notifications", notificationScopeKey(scope), "list"] as const;
}
/** The organizations of an employer account that the organization inbox can show. */
export function notificationOrganizationsQueryKey(accountId: string) {
return ["account", accountId, "notifications", "organizations"] as const;
}
/** Drops every cached inbox page of an account, or of all accounts. */
export function removeNotificationQueries(queryClient: QueryClient, accountId?: string): void {
queryClient.removeQueries({
predicate: (query) =>
query.queryKey[0] === "account" &&
query.queryKey[2] === "notifications" &&
(accountId === undefined || query.queryKey[1] === accountId),
});
}
@@ -0,0 +1,19 @@
import type { QueryClient } from "@tanstack/react-query";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import type { Session } from "../../../shared/api/schemas";
/**
* True while the cached session is the successful session of the same
* account and the same sign-in as the actor a request was made for, so a
* response is never applied to another account.
*/
export function isCurrentNotificationSession(queryClient: QueryClient, actor: Session): boolean {
const state = queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey());
return Boolean(
state &&
state.status === "success" &&
state.data &&
state.data.account.id === actor.account.id &&
state.data.csrf_token === actor.csrf_token,
);
}
@@ -0,0 +1,107 @@
.root {
display: grid;
gap: var(--space-4);
min-width: 0;
}
.live {
margin: 0;
}
.list {
display: grid;
gap: var(--space-4);
margin: 0;
padding: 0;
list-style: none;
}
.item {
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
}
/* Unread is a heavier edge and the word "Не прочитано", never color alone. */
.item[data-unread] {
border-color: var(--color-border-strong);
border-inline-start-width: var(--space-2);
}
.item article {
display: grid;
gap: var(--space-3);
}
.item p,
.item h2 {
margin: 0;
overflow-wrap: anywhere;
}
.meta {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-4);
align-items: baseline;
color: var(--color-text-secondary);
font-size: var(--font-size-xs);
}
.kind {
letter-spacing: var(--letter-spacing-label);
text-transform: uppercase;
}
.unread {
color: var(--color-text);
font-weight: var(--font-weight-bold);
}
.read {
font-weight: var(--font-weight-regular);
}
.title {
font-size: var(--font-size-l);
line-height: var(--line-height-snug);
}
.title:focus-visible {
outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset);
}
.summary {
color: var(--color-text);
}
.unavailable {
color: var(--color-text-secondary);
font-style: italic;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3) var(--space-5);
align-items: center;
}
.failure {
color: var(--color-danger);
font-weight: var(--font-weight-bold);
}
.more {
display: flex;
justify-content: center;
}
@media (width < 42rem) {
.item {
padding: var(--space-3);
}
}
@@ -0,0 +1,130 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderToString } from "react-dom/server";
import { MemoryRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import type { NotificationList, Session } from "../../../shared/api/schemas";
import { notificationListQueryKey, type NotificationScope } from "../model/scope";
import { NotificationInbox } from "./notification-inbox";
const accountId = "11111111-1111-4111-8111-111111111111";
const organizationId = "22222222-2222-4222-8222-222222222222";
function session(scenario: "candidate" | "employer"): Session {
return {
account: {
id: accountId,
email: "person@example.test",
email_verified: true,
scenario,
onboarding_step: "completed",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: "A".repeat(43),
};
}
const page: NotificationList = {
items: [
{
id: "33333333-3333-4333-8333-333333333333",
kind: "synthetic",
organization_id: organizationId,
delivered_at: "2026-10-09T08:30:00Z",
read_at: null,
content: {
title: "Тестовое уведомление",
summary: "Организация «Север» отправила проверочное уведомление.",
link_path: "/candidate/invitations",
},
},
{
id: "44444444-4444-4444-8444-444444444444",
kind: "synthetic",
organization_id: organizationId,
delivered_at: "2026-10-08T17:05:00Z",
read_at: "2026-10-08T17:10:00Z",
content: null,
},
{
id: "55555555-5555-4555-8555-555555555555",
kind: "invitation_delivered",
organization_id: organizationId,
delivered_at: "2026-10-07T10:00:00Z",
read_at: null,
content: {
title: "Внешняя ссылка",
summary: "Ссылка не должна открываться.",
link_path: "//evil.example/x",
},
},
],
page: { has_more: true, next_cursor: "cursor" },
};
function render(options: {
scope?: NotificationScope;
scenario?: "candidate" | "employer";
data?: NotificationList | null;
}): string {
const scope = options.scope ?? { kind: "candidate" };
const queryClient = new QueryClient();
queryClient.setQueryData(
getGetCurrentSessionQueryKey(),
session(options.scenario ?? "candidate"),
);
if (options.data !== null) {
queryClient.setQueryData(notificationListQueryKey(accountId, scope), {
pages: [options.data ?? page],
pageParams: [undefined],
});
}
return renderToString(
<QueryClientProvider client={queryClient}>
<MemoryRouter>
<NotificationInbox scope={scope} />
</MemoryRouter>
</QueryClientProvider>,
);
}
describe("NotificationInbox", () => {
it("lists items with a visible read state and a mark button only for unread ones", () => {
const html = render({});
expect(html).toContain("Тестовое уведомление");
expect(html).toContain("Не прочитано");
expect(html).toContain("Прочитано");
expect(html.match(/Отметить прочитанным/g)).toHaveLength(2);
expect(html).toContain('<time dateTime="2026-10-09T08:30:00Z">');
expect(html).toContain("Показать еще");
});
it("shows a generic line, not an earlier copy, for an item without content", () => {
const html = render({});
expect(html).toContain("Содержимое больше недоступно");
expect(html).toContain("Тестовое уведомление платформы");
});
it("opens only a safe link of the cabinet", () => {
const html = render({});
expect(html).toContain('href="/candidate/invitations"');
expect(html).not.toContain("evil.example");
});
it("shows the empty state", () => {
const html = render({ data: { items: [], page: { has_more: false, next_cursor: null } } });
expect(html).toContain("Уведомлений пока нет");
expect(html).not.toContain("Показать еще");
});
it("refuses an account of the other scenario instead of requesting its inbox", () => {
const html = render({ scenario: "employer", data: null });
expect(html).toContain("Уведомления недоступны");
expect(html).toContain("кабинету другого типа");
});
it("waits for the list while the session is known", () => {
const html = render({ data: null });
expect(html).toContain("Загружаем уведомления");
});
});
@@ -0,0 +1,360 @@
import { useEffect, useRef, useState } from "react";
import { useInfiniteQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import type { InfiniteData } from "@tanstack/react-query";
import { ApiRequestError } from "../../../shared/api";
import {
getGetCurrentSessionQueryKey,
useGetCurrentSession,
} from "../../../shared/api/endpoints/identity/identity";
import {
listMyNotifications,
listOrganizationNotifications,
markMyNotificationRead,
markOrganizationNotificationRead,
} from "../../../shared/api/endpoints/notification/notification";
import type { Notification, NotificationList, Session } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config/paths";
import {
Button,
ButtonLink,
EmptyState,
ErrorState,
ForbiddenState,
LoadingState,
TextLink,
VisuallyHidden,
} from "../../../shared/ui";
import { isMarkAccessLoss, markWithSessionRetry } from "../model/mark-read";
import {
formatDeliveredAt,
notificationKindLabel,
safeNotificationPath,
unavailableContentText,
} from "../model/presentation";
import {
notificationListQueryKey,
notificationPageSize,
removeNotificationQueries,
type NotificationScope,
} from "../model/scope";
import { isCurrentNotificationSession } from "../model/session";
import styles from "./notification-inbox.module.css";
type NotificationInboxProps = {
scope: NotificationScope;
};
type InboxData = InfiniteData<NotificationList, string | undefined>;
const markFailureText = "Не удалось отметить уведомление прочитанным. Повторите попытку.";
function isAccessLoss(error: unknown): error is ApiRequestError {
return (
error instanceof ApiRequestError &&
(error.status === 401 || error.status === 403 || error.status === 404)
);
}
function setReadTime(
data: InboxData | undefined,
id: string,
readAt: string,
): InboxData | undefined {
if (!data) return data;
return {
...data,
pages: data.pages.map((page) => ({
...page,
items: page.items.map((item) => (item.id === id ? { ...item, read_at: readAt } : item)),
})),
};
}
/**
* The inbox of the signed-in account in one cabinet. The list is read from
* the server on every visit and never kept between visits: the text of an
* item is resolved by the server from its current source, so a hiding or a
* revoked membership removes it from the next read. The server decides
* access; a refused read becomes a forbidden state, and the cached pages are
* dropped.
*/
export function NotificationInbox({ scope }: NotificationInboxProps) {
const queryClient = useQueryClient();
const session = useGetCurrentSession({ query: { retry: false } });
const actor = session.data;
const expectedScenario = scope.kind === "candidate" ? "candidate" : "employer";
const actorReady = Boolean(
actor &&
actor.account.scenario === expectedScenario &&
isCurrentNotificationSession(queryClient, actor),
);
const accountId = actor?.account.id;
const csrfToken = actor?.csrf_token;
const queryKey = notificationListQueryKey(accountId ?? "no-session", scope);
const [failedId, setFailedId] = useState<string | null>(null);
const [announcement, setAnnouncement] = useState("");
// Focus moves to the heading of the item that was just marked: its button is
// gone after the mark, and focus must not fall back to the page.
const focusAfterRender = useRef<string | null>(null);
const headings = useRef(new Map<string, HTMLElement>());
const previousIdentity = useRef<{ accountId: string; csrfToken: string } | null>(null);
useEffect(() => {
const next = actorReady && accountId && csrfToken ? { accountId, csrfToken } : null;
const before = previousIdentity.current;
if (
before &&
(!next || before.accountId !== next.accountId || before.csrfToken !== next.csrfToken)
) {
removeNotificationQueries(queryClient);
}
previousIdentity.current = next;
}, [accountId, actorReady, csrfToken, queryClient]);
const list = useInfiniteQuery({
queryKey,
initialPageParam: undefined as string | undefined,
queryFn: async ({ pageParam, signal }) => {
if (!actor || !isCurrentNotificationSession(queryClient, actor)) {
throw new Error("The session changed before the inbox request.");
}
const params = { limit: notificationPageSize, ...(pageParam ? { cursor: pageParam } : {}) };
const page =
scope.kind === "candidate"
? await listMyNotifications(params, { signal })
: await listOrganizationNotifications(scope.organizationId, params, { signal });
if (!isCurrentNotificationSession(queryClient, actor)) {
throw new Error("The session changed during the inbox request.");
}
return page;
},
getNextPageParam: (lastPage) =>
lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined,
enabled: actorReady,
staleTime: 0,
gcTime: 0,
refetchOnMount: "always",
refetchOnWindowFocus: "always",
retry: false,
});
const mark = useMutation({
mutationFn: (id: string) => {
const sessionKey = getGetCurrentSessionQueryKey();
// The CSRF token is read from the session at call time, so a retry after
// a sign-in in another tab uses the fresh one. A different account stops
// the mark: it must never be sent for another session.
const attempt = () => {
const current = queryClient.getQueryData<Session>(sessionKey);
if (!current || current.account.id !== accountId) {
throw new Error("The session changed before the mark.");
}
const request = { headers: { "X-CSRF-Token": current.csrf_token } };
return scope.kind === "candidate"
? markMyNotificationRead(id, request)
: markOrganizationNotificationRead(scope.organizationId, id, request);
};
return markWithSessionRetry(attempt, async () => {
await queryClient.refetchQueries({ queryKey: sessionKey });
});
},
onMutate: () => {
setFailedId(null);
setAnnouncement("");
},
onSuccess: (receipt) => {
queryClient.setQueryData<InboxData>(queryKey, (data) =>
setReadTime(data, receipt.id, receipt.read_at),
);
setAnnouncement("Уведомление отмечено прочитанным.");
focusAfterRender.current = receipt.id;
},
onError: (error, id) => {
if (isMarkAccessLoss(error)) {
// The access changed since the list was read. Read it again: the
// server answers with the current state, and nothing stale stays.
removeNotificationQueries(queryClient);
void list.refetch();
return;
}
setFailedId(id);
},
});
useEffect(() => {
const id = focusAfterRender.current;
if (!id) return;
focusAfterRender.current = null;
headings.current.get(id)?.focus();
});
const accessError = list.isError && isAccessLoss(list.error) ? list.error : null;
useEffect(() => {
if (accessError) removeNotificationQueries(queryClient);
}, [accessError, queryClient]);
if (session.isError) {
return isAccessLoss(session.error) ? (
<ForbiddenState
error={session.error}
title="Уведомления недоступны"
description="Войдите в аккаунт, чтобы открыть уведомления."
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
/>
) : (
<ErrorState
error={session.error}
title="Не удалось проверить вход"
isRetrying={session.isRefetching}
onRetry={() => void session.refetch()}
/>
);
}
if (session.isPending || !actor) return <LoadingState label="Проверяем вход..." />;
if (actor.account.scenario !== expectedScenario) {
return (
<ForbiddenState
title="Уведомления недоступны"
description="Эти уведомления относятся к кабинету другого типа."
/>
);
}
if (!actorReady) return <LoadingState label="Подтверждаем текущий вход..." />;
if (accessError) {
return (
<ForbiddenState
error={accessError}
title="Уведомления недоступны"
description={
scope.kind === "organization"
? "Сервер не подтвердил доступ к уведомлениям этой компании. Возможно, ваше членство в ней завершено."
: "Сервер не подтвердил доступ к уведомлениям этого аккаунта."
}
/>
);
}
if (list.isError && !list.data) {
return (
<ErrorState
error={list.error}
title="Не удалось загрузить уведомления"
isRetrying={list.isRefetching}
onRetry={() => void list.refetch()}
/>
);
}
if (list.isPending || !list.data) return <LoadingState label="Загружаем уведомления..." />;
const items = list.data.pages.flatMap((page) => page.items);
if (items.length === 0) {
return (
<EmptyState
title="Уведомлений пока нет"
description="Здесь появятся приглашения и сообщения платформы. Письмо на почту для этого не нужно: список в кабинете - основной источник."
/>
);
}
return (
<div className={styles.root}>
<p className={styles.live} role="status">
<VisuallyHidden>{announcement}</VisuallyHidden>
</p>
<ul className={styles.list} aria-label="Уведомления">
{items.map((item) => (
<NotificationItem
key={item.id}
item={item}
scope={scope}
isMarking={mark.isPending && mark.variables === item.id}
failed={failedId === item.id}
onMark={() => mark.mutate(item.id)}
registerHeading={(element) => {
if (element) headings.current.set(item.id, element);
else headings.current.delete(item.id);
}}
/>
))}
</ul>
{list.isError ? (
<ErrorState
error={list.error}
title="Не удалось обновить список"
isRetrying={list.isRefetching}
onRetry={() => void list.refetch()}
/>
) : null}
{list.hasNextPage ? (
<div className={styles.more}>
<Button
variant="secondary"
isBusy={list.isFetchingNextPage}
onClick={() => void list.fetchNextPage()}
>
{list.isFetchingNextPage ? "Загружаем..." : "Показать еще"}
</Button>
</div>
) : null}
</div>
);
}
type NotificationItemProps = {
item: Notification;
scope: NotificationScope;
isMarking: boolean;
failed: boolean;
onMark: () => void;
registerHeading: (element: HTMLElement | null) => void;
};
function NotificationItem({
item,
scope,
isMarking,
failed,
onMark,
registerHeading,
}: NotificationItemProps) {
const unread = item.read_at === null;
const content = item.content;
const title = content ? content.title : notificationKindLabel(item.kind);
const link = content ? safeNotificationPath(content.link_path, scope) : null;
const headingId = `notification-${item.id}`;
return (
<li className={styles.item} data-unread={unread || undefined}>
<article aria-labelledby={headingId}>
<p className={styles.meta}>
<span className={styles.kind}>{notificationKindLabel(item.kind)}</span>
<time dateTime={item.delivered_at}>{formatDeliveredAt(item.delivered_at)}</time>
<span className={unread ? styles.unread : styles.read}>
{unread ? "Не прочитано" : "Прочитано"}
</span>
</p>
<h2 id={headingId} className={styles.title} tabIndex={-1} ref={registerHeading}>
{title}
</h2>
<p className={content ? styles.summary : styles.unavailable}>
{content ? content.summary : unavailableContentText}
</p>
{link || unread ? (
<div className={styles.actions}>
{link ? <TextLink to={link}>Открыть: {title}</TextLink> : null}
{unread ? (
<Button variant="secondary" isBusy={isMarking} onClick={onMark}>
{isMarking ? "Отмечаем..." : "Отметить прочитанным"}
<VisuallyHidden>: {title}</VisuallyHidden>
</Button>
) : null}
</div>
) : null}
{failed ? (
<p className={styles.failure} role="alert">
{markFailureText}
</p>
) : null}
</article>
</li>
);
}
@@ -0,0 +1,30 @@
.root {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.selector {
display: grid;
gap: var(--space-2);
max-width: 24rem;
}
.selector label {
font-weight: var(--font-weight-bold);
}
.selector select {
min-height: 2.75rem;
padding: var(--space-2) var(--space-3);
border: var(--line-strong) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
font: inherit;
}
.selector select:focus-visible {
outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset);
}
@@ -0,0 +1,144 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useSearchParams } from "react-router-dom";
import { ApiRequestError } from "../../../shared/api";
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
import { listMyOrganizations } from "../../../shared/api/endpoints/organization/organization";
import { paths } from "../../../shared/config/paths";
import {
ButtonLink,
EmptyState,
ErrorState,
ForbiddenState,
LoadingState,
} from "../../../shared/ui";
import { notificationOrganizationsQueryKey } from "../model/scope";
import { isCurrentNotificationSession } from "../model/session";
import { NotificationInbox } from "./notification-inbox";
import styles from "./organization-notification-inbox.module.css";
const organizationParam = "organization_id";
const organizationPageSize = 100;
function isAccessLoss(error: unknown): error is ApiRequestError {
return error instanceof ApiRequestError && (error.status === 401 || error.status === 403);
}
/**
* The inbox of an employer in one of the organizations where the account has
* an active membership. The organization is chosen in the address
* (`organization_id`), so a reload or a shared link keeps it; the server
* checks the membership again on every read, so a chosen organization that the
* account no longer belongs to is refused there and not hidden here.
*/
export function OrganizationNotificationInbox() {
const queryClient = useQueryClient();
const session = useGetCurrentSession({ query: { retry: false } });
const actor = session.data;
const actorReady = Boolean(
actor &&
actor.account.scenario === "employer" &&
isCurrentNotificationSession(queryClient, actor),
);
const [searchParams, setSearchParams] = useSearchParams();
const requested = searchParams.get(organizationParam);
const directory = useQuery({
queryKey: notificationOrganizationsQueryKey(actor?.account.id ?? "no-session"),
queryFn: ({ signal }) => listMyOrganizations({ limit: organizationPageSize }, { signal }),
enabled: actorReady,
staleTime: 0,
gcTime: 0,
refetchOnMount: "always",
retry: false,
});
if (session.isError) {
return isAccessLoss(session.error) ? (
<ForbiddenState
error={session.error}
title="Уведомления недоступны"
description="Войдите в аккаунт, чтобы открыть уведомления."
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
/>
) : (
<ErrorState
error={session.error}
title="Не удалось проверить вход"
isRetrying={session.isRefetching}
onRetry={() => void session.refetch()}
/>
);
}
if (session.isPending || !actor) return <LoadingState label="Проверяем вход..." />;
if (actor.account.scenario !== "employer") {
return (
<ForbiddenState
title="Уведомления недоступны"
description="Уведомления компании открываются из кабинета работодателя."
/>
);
}
if (directory.isError) {
return isAccessLoss(directory.error) ? (
<ForbiddenState error={directory.error} title="Компании недоступны" />
) : (
<ErrorState
error={directory.error}
title="Не удалось загрузить компании"
isRetrying={directory.isRefetching}
onRetry={() => void directory.refetch()}
/>
);
}
if (!actorReady || directory.isPending) return <LoadingState label="Проверяем компании..." />;
const organizations = directory.data.items.filter((item) => item.membership.state === "active");
if (organizations.length === 0) {
return (
<EmptyState
title="Компаний пока нет"
description="Уведомления компании появятся после создания компании или присоединения к ней."
action={<ButtonLink to={paths.employer.company}>Перейти к компании</ButtonLink>}
/>
);
}
const selected = requested
? organizations.find((item) => item.organization.id === requested)
: organizations[0];
return (
<div className={styles.root}>
{organizations.length > 1 || (requested && !selected) ? (
<div className={styles.selector}>
<label htmlFor="notification-organization">Компания</label>
<select
id="notification-organization"
value={selected?.organization.id ?? ""}
onChange={(event) => {
const next = new URLSearchParams(searchParams);
next.set(organizationParam, event.currentTarget.value);
setSearchParams(next);
}}
>
{!selected ? <option value="">Выберите компанию</option> : null}
{organizations.map((item) => (
<option key={item.organization.id} value={item.organization.id}>
{item.organization.name}
</option>
))}
</select>
</div>
) : null}
{selected ? (
<NotificationInbox
key={selected.organization.id}
scope={{ kind: "organization", organizationId: selected.organization.id }}
/>
) : (
<ForbiddenState
title="Компания недоступна"
description="Эта компания не найдена среди ваших активных компаний. Выберите другую компанию в списке."
/>
)}
</div>
);
}