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

+3
View File
@@ -9,6 +9,7 @@ import { SessionGate } from "../../entities/session";
import { NotFoundPage } from "../../pages/not-found";
import { NeedEditorPage } from "../../pages/need-editor";
import { NeedListPage } from "../../pages/needs";
import { CandidateNotificationsPage, EmployerNotificationsPage } from "../../pages/notifications";
import { PlaceholderPage } from "../../pages/placeholder";
import { ProfilePage } from "../../pages/profile";
import { QuestionnairePage } from "../../pages/questionnaire";
@@ -81,6 +82,7 @@ export const routes: RouteObject[] = [
path: paths.candidate.invitations,
element: <PlaceholderPage screen="candidateInvitations" />,
},
{ path: paths.candidate.notifications, element: <CandidateNotificationsPage /> },
{
path: paths.candidate.privacy,
element: <PrivacyPage />,
@@ -131,6 +133,7 @@ export const routes: RouteObject[] = [
path: paths.employer.invitations,
element: <PlaceholderPage screen="employerInvitations" />,
},
{ path: paths.employer.notifications, element: <EmployerNotificationsPage /> },
{
path: "*",
element: (
@@ -111,6 +111,7 @@ function matchResponseFixture(): MatchSearchResponseOutput {
},
],
},
truncated: false,
});
}
@@ -195,6 +196,15 @@ describe("match response adapter", () => {
expect(matchSearchFromTransport(roundTrip)).toEqual(model);
});
it("keeps the truncation flag, which carries no count", () => {
const response = { ...matchResponseFixture(), truncated: true };
const model = matchSearchFromTransport(response);
expect(model.truncated).toBe(true);
expect(matchSearchToTransport(model)).toEqual(response);
expect(() => matchSearchFromTransport({ ...response, truncated: undefined })).toThrow();
});
it("round-trips a need source using its requirements version", () => {
const response = matchResponseFixture();
const needResponse = {
@@ -84,6 +84,8 @@ export type MatchCardModel = MatchConfirmedCardModel | MatchUnconfirmedCardModel
export type MatchSearchModel = {
readonly source: MatchSearchSourceModel;
readonly cards: readonly MatchCardModel[];
/** True when the output is not the whole ranked result; it carries no count. */
readonly truncated: boolean;
};
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -258,6 +260,7 @@ export function matchSearchFromTransport(value: unknown, status = 200): MatchSea
...response.groups.near.map((candidate) => confirmedFromTransport("near", candidate)),
...response.groups.unconfirmed.map(unconfirmedFromTransport),
],
truncated: response.truncated,
};
}
@@ -316,5 +319,6 @@ export function matchSearchToTransport(model: MatchSearchModel): MatchSearchResp
return matchSearchResponseSchema.parse({
source: sourceToTransport(model.source),
groups,
truncated: model.truncated,
});
}
@@ -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>
);
}
@@ -0,0 +1 @@
export { CandidateNotificationsPage, EmployerNotificationsPage } from "./ui/notifications-pages";
@@ -0,0 +1,44 @@
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 { Session } from "../../../shared/api/schemas";
import { CandidateNotificationsPage, EmployerNotificationsPage } from "./notifications-pages";
function render(scenario: "candidate" | "employer", element: React.ReactElement): string {
const queryClient = new QueryClient();
const session: Session = {
account: {
id: "11111111-1111-4111-8111-111111111111",
email: "person@example.test",
email_verified: true,
scenario,
onboarding_step: "completed",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: "A".repeat(43),
};
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
return renderToString(
<QueryClientProvider client={queryClient}>
<MemoryRouter>{element}</MemoryRouter>
</QueryClientProvider>,
);
}
describe("notification pages", () => {
it("name the cabinet and carry the single h1", () => {
const candidate = render("candidate", <CandidateNotificationsPage />);
expect(candidate).toContain("Кабинет кандидата");
expect(candidate.match(/<h1/g)).toHaveLength(1);
const employer = render("employer", <EmployerNotificationsPage />);
expect(employer).toContain("Кабинет работодателя");
expect(employer.match(/<h1/g)).toHaveLength(1);
});
it("refuse the other cabinet's account instead of loading its inbox", () => {
expect(render("employer", <CandidateNotificationsPage />)).toContain("кабинету другого типа");
expect(render("candidate", <EmployerNotificationsPage />)).toContain("кабинета работодателя");
});
});
@@ -0,0 +1,21 @@
import { NotificationInbox, OrganizationNotificationInbox } from "../../../features/notifications";
import { Page } from "../../../shared/ui";
const lead =
"Платформа сообщает здесь о событиях в вашем кабинете. Письмо на почту ничего не заменяет и ничему не мешает: список здесь - основной источник. Текст берется из текущих данных, поэтому после смены доступа он может исчезнуть.";
export function CandidateNotificationsPage() {
return (
<Page title="Уведомления" eyebrow="Кабинет кандидата" lead={lead}>
<NotificationInbox scope={{ kind: "candidate" }} />
</Page>
);
}
export function EmployerNotificationsPage() {
return (
<Page title="Уведомления" eyebrow="Кабинет работодателя" lead={lead} width="wide">
<OrganizationNotificationInbox />
</Page>
);
}
@@ -7,6 +7,7 @@ export { getHealthMock } from './health/health.msw'
export { getIdentityMock } from './identity/identity.msw'
export { getInvitationMock } from './invitation/invitation.msw'
export { getNeedMock } from './need/need.msw'
export { getNotificationMock } from './notification/notification.msw'
export { getOrganizationMock } from './organization/organization.msw'
export { getPrivacyMock } from './privacy/privacy.msw'
export { getSupportMock } from './support/support.msw'
@@ -7,6 +7,7 @@ export * from './health/health';
export * from './identity/identity';
export * from './invitation/invitation';
export * from './need/need';
export * from './notification/notification';
export * from './organization/organization';
export * from './privacy/privacy';
export * from './support/support';
@@ -0,0 +1,95 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import {
faker
} from '@faker-js/faker';
import {
fakeFromPattern
} from '../../mock-pattern';
import {
HttpResponse,
http
} from 'msw';
import type {
RequestHandlerOptions
} from 'msw';
import type {
NotificationContent,
NotificationList,
NotificationReadReceipt
} from '../../schemas';
export const getListMyNotificationsResponseNotificationContentMock = (overrideResponse: Partial<NotificationContent> = {}): NotificationContent => ({...{title: faker.string.alpha({length: {min: 1, max: 120}}), summary: faker.string.alpha({length: {min: 1, max: 500}}), link_path: faker.helpers.arrayElement([fakeFromPattern("^/[A-Za-z0-9/_-]{0,255}$", {maxLength: 256}), null])}, ...overrideResponse});
export const getListMyNotificationsResponseMock = (overrideResponse: Partial<Extract<NotificationList, object>> = {}): NotificationList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), kind: faker.helpers.arrayElement(['invitation_delivered','synthetic'] as const), organization_id: faker.string.uuid(), delivered_at: faker.date.past().toISOString().slice(0, 19) + 'Z', read_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), content: faker.helpers.arrayElement([{...getListMyNotificationsResponseNotificationContentMock()},null,])})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
export const getMarkMyNotificationReadResponseMock = (overrideResponse: Partial<Extract<NotificationReadReceipt, object>> = {}): NotificationReadReceipt => ({id: faker.string.uuid(), read_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse})
export const getListOrganizationNotificationsResponseNotificationContentMock = (overrideResponse: Partial<NotificationContent> = {}): NotificationContent => ({...{title: faker.string.alpha({length: {min: 1, max: 120}}), summary: faker.string.alpha({length: {min: 1, max: 500}}), link_path: faker.helpers.arrayElement([fakeFromPattern("^/[A-Za-z0-9/_-]{0,255}$", {maxLength: 256}), null])}, ...overrideResponse});
export const getListOrganizationNotificationsResponseMock = (overrideResponse: Partial<Extract<NotificationList, object>> = {}): NotificationList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), kind: faker.helpers.arrayElement(['invitation_delivered','synthetic'] as const), organization_id: faker.string.uuid(), delivered_at: faker.date.past().toISOString().slice(0, 19) + 'Z', read_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), content: faker.helpers.arrayElement([{...getListOrganizationNotificationsResponseNotificationContentMock()},null,])})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
export const getMarkOrganizationNotificationReadResponseMock = (overrideResponse: Partial<Extract<NotificationReadReceipt, object>> = {}): NotificationReadReceipt => ({id: faker.string.uuid(), read_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse})
export const getListMyNotificationsMockHandler = (overrideResponse?: NotificationList | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<NotificationList> | NotificationList), options?: RequestHandlerOptions) => {
return http.get('*/api/v1/me/notifications', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getListMyNotificationsResponseMock(),
{ status: 200
})
}, options)
}
export const getMarkMyNotificationReadMockHandler = (overrideResponse?: NotificationReadReceipt | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<NotificationReadReceipt> | NotificationReadReceipt), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/me/notifications/:notificationId/read', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getMarkMyNotificationReadResponseMock(),
{ status: 200
})
}, options)
}
export const getListOrganizationNotificationsMockHandler = (overrideResponse?: NotificationList | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<NotificationList> | NotificationList), options?: RequestHandlerOptions) => {
return http.get('*/api/v1/organizations/:orgId/notifications', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getListOrganizationNotificationsResponseMock(),
{ status: 200
})
}, options)
}
export const getMarkOrganizationNotificationReadMockHandler = (overrideResponse?: NotificationReadReceipt | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<NotificationReadReceipt> | NotificationReadReceipt), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/organizations/:orgId/notifications/:notificationId/read', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getMarkOrganizationNotificationReadResponseMock(),
{ status: 200
})
}, options)
}
export const getNotificationMock = () => [
getListMyNotificationsMockHandler(),
getMarkMyNotificationReadMockHandler(),
getListOrganizationNotificationsMockHandler(),
getMarkOrganizationNotificationReadMockHandler()
]
@@ -0,0 +1,450 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import {
useMutation,
useQuery
} from '@tanstack/react-query';
import type {
DataTag,
DefinedInitialDataOptions,
DefinedUseQueryResult,
MutationFunction,
QueryClient,
QueryFunction,
QueryKey,
UndefinedInitialDataOptions,
UseMutationOptions,
UseMutationResult,
UseQueryOptions,
UseQueryResult
} from '@tanstack/react-query';
import type {
ListMyNotificationsParams,
ListOrganizationNotificationsParams,
NotificationList,
NotificationReadReceipt,
Problem
} from '../../schemas';
import { apiRequest } from '../../client';
import type { ErrorType } from '../../client';
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
const withQueryKey = <T extends object, K>(query: T, queryKey: K): T & { queryKey: K } => {
const result = { queryKey } as T & { queryKey: K };
for (const key of Object.keys(query)) {
// The explicit queryKey always wins, matching the previous
// `{ ...query, queryKey }` spread where it was set last.
if (key === 'queryKey') continue;
Object.defineProperty(result, key, {
enumerable: true,
configurable: true,
get: () => (query as Record<string, unknown>)[key],
});
}
return result;
};
export const getListMyNotificationsUrl = (params?: ListMyNotificationsParams,) => {
const normalizedParams = new URLSearchParams();
Object.entries(params || {}).forEach(([key, value]) => {
if (value !== undefined) {
normalizedParams.append(key, value === null ? 'null' : String(value))
}
});
const stringifiedParams = normalizedParams.toString();
return stringifiedParams.length > 0 ? `/api/v1/me/notifications?${stringifiedParams}` : `/api/v1/me/notifications`
}
/**
* Requires the session cookie of a candidate account with a confirmed email. The recipient comes from the session, never from a request parameter, so the response holds only the caller's own items. Returns a page, newest delivery first with the identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`.
*
* The inbox is the in-platform delivery state of a notification. An item exists as soon as the event reached the platform, whether or not any email was sent, and an email that failed or was never sent does not block it. The inbox stores a reference to the event, not its text: the `content` of every item is resolved from the current source for this recipient on this read. When the source is gone or the recipient may not see it now (for example the candidate hid the organization), the item stays in the list with `content` null, and no earlier text is shown. An event that is delivered twice is one item.
*
* Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another account, answers 400 validation_failed.
* @summary List the inbox of the current candidate.
*/
export const listMyNotifications = async (params?: ListMyNotificationsParams, options?: Parameters<typeof apiRequest>[1]): Promise<NotificationList> => {
return apiRequest<NotificationList>(getListMyNotificationsUrl(params),
{
...options,
method: 'GET'
}
);}
export const getListMyNotificationsQueryKey = (params?: ListMyNotificationsParams,) => {
return [
`/api/v1/me/notifications`, ...(params ? [params] : [])
] as const;
}
export const getListMyNotificationsQueryOptions = <TData = Awaited<ReturnType<typeof listMyNotifications>>, TError = ErrorType<Problem>>(params?: ListMyNotificationsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyNotifications>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
) => {
const {query: queryOptions, request: requestOptions} = options ?? {};
const queryKey = queryOptions?.queryKey ?? getListMyNotificationsQueryKey(params);
const queryFn: QueryFunction<Awaited<ReturnType<typeof listMyNotifications>>> = ({ signal }) => listMyNotifications(params, { signal, ...requestOptions });
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof listMyNotifications>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
}
export type ListMyNotificationsQueryResult = NonNullable<Awaited<ReturnType<typeof listMyNotifications>>>
export type ListMyNotificationsQueryError = ErrorType<Problem>
export function useListMyNotifications<TData = Awaited<ReturnType<typeof listMyNotifications>>, TError = ErrorType<Problem>>(
params: undefined | ListMyNotificationsParams, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyNotifications>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof listMyNotifications>>,
TError,
Awaited<ReturnType<typeof listMyNotifications>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useListMyNotifications<TData = Awaited<ReturnType<typeof listMyNotifications>>, TError = ErrorType<Problem>>(
params?: ListMyNotificationsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyNotifications>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof listMyNotifications>>,
TError,
Awaited<ReturnType<typeof listMyNotifications>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useListMyNotifications<TData = Awaited<ReturnType<typeof listMyNotifications>>, TError = ErrorType<Problem>>(
params?: ListMyNotificationsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyNotifications>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary List the inbox of the current candidate.
*/
export function useListMyNotifications<TData = Awaited<ReturnType<typeof listMyNotifications>>, TError = ErrorType<Problem>>(
params?: ListMyNotificationsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyNotifications>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
const queryOptions = getListMyNotificationsQueryOptions(params,options)
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
return withQueryKey(query, queryOptions.queryKey);
}
export const getMarkMyNotificationReadUrl = (notificationId: string,) => {
return `/api/v1/me/notifications/${notificationId}/read`
}
/**
* Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session. The request has no body.
*
* The command is idempotent by its effect: the first mark stores the read time and every repeat returns that first time, so it needs no Idempotency-Key. It never reads the source and returns no content, so marking an item whose content is no longer available still works. It changes no other item.
*
* The general rate limit can answer 429 with Retry-After before any check.
*
* Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers 403 forbidden; an item of another account and an unknown identifier both answer 404 not_found, so identifiers cannot be enumerated. A `notification_id` that is not a UUID answers 400 validation_failed with the path pointer.
* @summary Mark an item of the inbox of the current candidate as read.
*/
export const markMyNotificationRead = async (notificationId: string, options?: Parameters<typeof apiRequest>[1]): Promise<NotificationReadReceipt> => {
return apiRequest<NotificationReadReceipt>(getMarkMyNotificationReadUrl(notificationId),
{
...options,
method: 'POST'
}
);}
export const getMarkMyNotificationReadMutationKey = () => ['markMyNotificationRead'] as const;
export const getMarkMyNotificationReadMutationOptions = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof markMyNotificationRead>>, TError,MarkMyNotificationReadMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof markMyNotificationRead>>, TError,MarkMyNotificationReadMutationVariables, TContext> => {
const mutationKey = getMarkMyNotificationReadMutationKey();
const {mutation: mutationOptions, request: requestOptions} = options ?
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
options
: {...options, mutation: {...options.mutation, mutationKey}}
: {mutation: { mutationKey, }, request: undefined};
const mutationFn: MutationFunction<Awaited<ReturnType<typeof markMyNotificationRead>>, MarkMyNotificationReadMutationVariables> = (props) => {
const {notificationId} = props ?? {};
return markMyNotificationRead(notificationId,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type MarkMyNotificationReadMutationResult = NonNullable<Awaited<ReturnType<typeof markMyNotificationRead>>>
export type MarkMyNotificationReadMutationError = ErrorType<Problem>
export type MarkMyNotificationReadMutationVariables = {notificationId: string}
/**
* @summary Mark an item of the inbox of the current candidate as read.
*/
export const useMarkMyNotificationRead = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof markMyNotificationRead>>, TError,MarkMyNotificationReadMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof markMyNotificationRead>>,
TError,
MarkMyNotificationReadMutationVariables,
TContext
> => {
return useMutation(getMarkMyNotificationReadMutationOptions(options), queryClient);
}
export const getListOrganizationNotificationsUrl = (orgId: string,
params?: ListOrganizationNotificationsParams,) => {
const normalizedParams = new URLSearchParams();
Object.entries(params || {}).forEach(([key, value]) => {
if (value !== undefined) {
normalizedParams.append(key, value === null ? 'null' : String(value))
}
});
const stringifiedParams = normalizedParams.toString();
return stringifiedParams.length > 0 ? `/api/v1/organizations/${orgId}/notifications?${stringifiedParams}` : `/api/v1/organizations/${orgId}/notifications`
}
/**
* Requires the session cookie of an employer account with a confirmed email and an active membership in `org_id`, whatever its role. The recipient comes from the session and the organization from the path and the membership that the server holds, never from the request. Returns only the items addressed to the caller in this organization, newest delivery first with the identifier as the tie-breaker, with cursor pagination. An item of the same account in another organization, and an item of another member, are never listed. The response is `Cache-Control: no-store`.
*
* Items follow the rules of ListMyNotifications: the inbox stores a reference to the event, an email never blocks an item, and the `content` of every item is resolved from the current source for this recipient on this read. An employer sees content only while the membership is active.
*
* Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an account without an active membership in the organization and an unknown organization both answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id`, `limit`, or `cursor`, or a cursor of another account or organization, answers 400 validation_failed.
* @summary List the inbox of the current employer in one organization.
*/
export const listOrganizationNotifications = async (orgId: string,
params?: ListOrganizationNotificationsParams, options?: Parameters<typeof apiRequest>[1]): Promise<NotificationList> => {
return apiRequest<NotificationList>(getListOrganizationNotificationsUrl(orgId,params),
{
...options,
method: 'GET'
}
);}
export const getListOrganizationNotificationsQueryKey = (orgId: string,
params?: ListOrganizationNotificationsParams,) => {
return [
`/api/v1/organizations/${orgId}/notifications`, ...(params ? [params] : [])
] as const;
}
export const getListOrganizationNotificationsQueryOptions = <TData = Awaited<ReturnType<typeof listOrganizationNotifications>>, TError = ErrorType<Problem>>(orgId: string,
params?: ListOrganizationNotificationsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listOrganizationNotifications>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
) => {
const {query: queryOptions, request: requestOptions} = options ?? {};
const queryKey = queryOptions?.queryKey ?? getListOrganizationNotificationsQueryKey(orgId,params);
const queryFn: QueryFunction<Awaited<ReturnType<typeof listOrganizationNotifications>>> = ({ signal }) => listOrganizationNotifications(orgId,params, { signal, ...requestOptions });
return { queryKey, queryFn, enabled: orgId !== null && orgId !== undefined, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof listOrganizationNotifications>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
}
export type ListOrganizationNotificationsQueryResult = NonNullable<Awaited<ReturnType<typeof listOrganizationNotifications>>>
export type ListOrganizationNotificationsQueryError = ErrorType<Problem>
export function useListOrganizationNotifications<TData = Awaited<ReturnType<typeof listOrganizationNotifications>>, TError = ErrorType<Problem>>(
orgId: string,
params: undefined | ListOrganizationNotificationsParams, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof listOrganizationNotifications>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof listOrganizationNotifications>>,
TError,
Awaited<ReturnType<typeof listOrganizationNotifications>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useListOrganizationNotifications<TData = Awaited<ReturnType<typeof listOrganizationNotifications>>, TError = ErrorType<Problem>>(
orgId: string,
params?: ListOrganizationNotificationsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listOrganizationNotifications>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof listOrganizationNotifications>>,
TError,
Awaited<ReturnType<typeof listOrganizationNotifications>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useListOrganizationNotifications<TData = Awaited<ReturnType<typeof listOrganizationNotifications>>, TError = ErrorType<Problem>>(
orgId: string,
params?: ListOrganizationNotificationsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listOrganizationNotifications>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary List the inbox of the current employer in one organization.
*/
export function useListOrganizationNotifications<TData = Awaited<ReturnType<typeof listOrganizationNotifications>>, TError = ErrorType<Problem>>(
orgId: string,
params?: ListOrganizationNotificationsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listOrganizationNotifications>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
const queryOptions = getListOrganizationNotificationsQueryOptions(orgId,params,options)
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
return withQueryKey(query, queryOptions.queryKey);
}
export const getMarkOrganizationNotificationReadUrl = (orgId: string,
notificationId: string,) => {
return `/api/v1/organizations/${orgId}/notifications/${notificationId}/read`
}
/**
* Requires the session cookie of an employer account with a confirmed email and an active membership in `org_id`, whatever its role, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session and the organization from the path and the server-side membership. The request has no body.
*
* The command is idempotent by its effect and returns no content, like MarkMyNotificationRead. The item must belong to the caller in this organization.
*
* The general rate limit can answer 429 with Retry-After before any check.
*
* Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; a candidate account answers 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an account without an active membership in the organization, an unknown organization, an item of another account, an item of another organization, and an unknown identifier all answer 404 not_found. A malformed `org_id` or `notification_id` answers 400 validation_failed with the path pointer.
* @summary Mark an item of the inbox of the current employer in one organization as read.
*/
export const markOrganizationNotificationRead = async (orgId: string,
notificationId: string, options?: Parameters<typeof apiRequest>[1]): Promise<NotificationReadReceipt> => {
return apiRequest<NotificationReadReceipt>(getMarkOrganizationNotificationReadUrl(orgId,notificationId),
{
...options,
method: 'POST'
}
);}
export const getMarkOrganizationNotificationReadMutationKey = () => ['markOrganizationNotificationRead'] as const;
export const getMarkOrganizationNotificationReadMutationOptions = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof markOrganizationNotificationRead>>, TError,MarkOrganizationNotificationReadMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof markOrganizationNotificationRead>>, TError,MarkOrganizationNotificationReadMutationVariables, TContext> => {
const mutationKey = getMarkOrganizationNotificationReadMutationKey();
const {mutation: mutationOptions, request: requestOptions} = options ?
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
options
: {...options, mutation: {...options.mutation, mutationKey}}
: {mutation: { mutationKey, }, request: undefined};
const mutationFn: MutationFunction<Awaited<ReturnType<typeof markOrganizationNotificationRead>>, MarkOrganizationNotificationReadMutationVariables> = (props) => {
const {orgId,notificationId} = props ?? {};
return markOrganizationNotificationRead(orgId,notificationId,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type MarkOrganizationNotificationReadMutationResult = NonNullable<Awaited<ReturnType<typeof markOrganizationNotificationRead>>>
export type MarkOrganizationNotificationReadMutationError = ErrorType<Problem>
export type MarkOrganizationNotificationReadMutationVariables = {orgId: string;notificationId: string}
/**
* @summary Mark an item of the inbox of the current employer in one organization as read.
*/
export const useMarkOrganizationNotificationRead = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof markOrganizationNotificationRead>>, TError,MarkOrganizationNotificationReadMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof markOrganizationNotificationRead>>,
TError,
MarkOrganizationNotificationReadMutationVariables,
TContext
> => {
return useMutation(getMarkOrganizationNotificationReadMutationOptions(options), queryClient);
}
@@ -47,7 +47,7 @@ export const getSearchOrganizationMatchesResponseMatchAppliedConditionsMock = (o
export const getSearchOrganizationMatchesResponseMatchSearchBankSourceMock = (overrideResponse: Partial<MatchSearchBankSource> = {}): MatchSearchBankSource => ({...{kind: faker.helpers.arrayElement(['bank'] as const), filters: {specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), confirmed_category: faker.helpers.arrayElement([{...getSearchOrganizationMatchesResponseMatchGradeFilterMock()},null,]), confirmation_status: faker.helpers.arrayElement([faker.helpers.arrayElement(['confirmed','unconfirmed'] as const),null,]), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const),null,]), conditions: faker.helpers.arrayElement([{...getSearchOrganizationMatchesResponseMatchAppliedConditionsMock()},null,])}}, ...overrideResponse});
export const getSearchOrganizationMatchesResponseMock = (overrideResponse: Partial<Extract<MatchSearchResponse, object>> = {}): MatchSearchResponse => ({source: faker.helpers.arrayElement([{...getSearchOrganizationMatchesResponseMatchSearchNeedSourceMock()},{...getSearchOrganizationMatchesResponseMatchSearchBankSourceMock()},]), groups: {main: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), category: {specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const)}, strength: faker.helpers.arrayElement(['standard','strong'] as const), public_context: {stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const),null,]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const),null,]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,])}, evidence_summary: Array.from({ length: faker.number.int({min: 1, max: 12}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(['confirmed_category','required_skill_evidence','desired_skill_evidence','domain_alignment','task_alignment','work_conditions_match','salary_compatibility','declared_grade'] as const), state: faker.helpers.arrayElement(['supports','partial','gap','declared_only'] as const)})), components: {fit: faker.number.float({min: 0, max: 1, fractionDigits: 2}), coverage: faker.number.float({min: 0, max: 1, fractionDigits: 2}), domain: faker.number.float({min: 0, max: 1, fractionDigits: 2}), semantics: faker.number.float({min: 0, max: 1, fractionDigits: 2}), percentile: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}),null,]), competition: faker.number.float({min: 0, max: 1, fractionDigits: 2}), freshness: faker.number.float({min: 0, max: 1, fractionDigits: 2}), responsiveness: faker.number.float({min: 0, max: 1, fractionDigits: 2}), rank_score: faker.number.float({min: 0, max: 1, fractionDigits: 2})}, unknown_flags: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({component: faker.helpers.arrayElement(['semantics','percentile','assessment','freshness','responsiveness','experience_band','work_formats','salary_compatibility','domain'] as const), reason: faker.helpers.arrayElement(['ml_unavailable','cohort_below_30','no_confirmation_for_specialization','not_in_public_card','need_field_unconfirmed','no_freshness_history','no_response_history'] as const)}))})), near: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), category: {specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const)}, strength: faker.helpers.arrayElement(['standard','strong'] as const), public_context: {stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const),null,]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const),null,]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,])}, evidence_summary: Array.from({ length: faker.number.int({min: 1, max: 12}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(['confirmed_category','required_skill_evidence','desired_skill_evidence','domain_alignment','task_alignment','work_Line truncated
export const getSearchOrganizationMatchesResponseMock = (overrideResponse: Partial<Extract<MatchSearchResponse, object>> = {}): MatchSearchResponse => ({source: faker.helpers.arrayElement([{...getSearchOrganizationMatchesResponseMatchSearchNeedSourceMock()},{...getSearchOrganizationMatchesResponseMatchSearchBankSourceMock()},]), groups: {main: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), category: {specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const)}, strength: faker.helpers.arrayElement(['standard','strong'] as const), public_context: {stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const),null,]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const),null,]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,])}, evidence_summary: Array.from({ length: faker.number.int({min: 1, max: 12}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(['confirmed_category','required_skill_evidence','desired_skill_evidence','domain_alignment','task_alignment','work_conditions_match','salary_compatibility','declared_grade'] as const), state: faker.helpers.arrayElement(['supports','partial','gap','declared_only'] as const)})), components: {fit: faker.number.float({min: 0, max: 1, fractionDigits: 2}), coverage: faker.number.float({min: 0, max: 1, fractionDigits: 2}), domain: faker.number.float({min: 0, max: 1, fractionDigits: 2}), semantics: faker.number.float({min: 0, max: 1, fractionDigits: 2}), percentile: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}),null,]), competition: faker.number.float({min: 0, max: 1, fractionDigits: 2}), freshness: faker.number.float({min: 0, max: 1, fractionDigits: 2}), responsiveness: faker.number.float({min: 0, max: 1, fractionDigits: 2}), rank_score: faker.number.float({min: 0, max: 1, fractionDigits: 2})}, unknown_flags: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({component: faker.helpers.arrayElement(['semantics','percentile','assessment','freshness','responsiveness','experience_band','work_formats','salary_compatibility','domain'] as const), reason: faker.helpers.arrayElement(['ml_unavailable','cohort_below_30','no_confirmation_for_specialization','not_in_public_card','need_field_unconfirmed','no_freshness_history','no_response_history','percentile_not_computed'] as const)}))})), near: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), category: {specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const)}, strength: faker.helpers.arrayElement(['standard','strong'] as const), public_context: {stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const),null,]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const),null,]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,])}, evidence_summary: Array.from({ length: faker.number.int({min: 1, max: 12}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(['confirmed_category','required_skill_evidence','desired_skill_evidence','domain_alignmenLine truncated
export const getListMyOrganizationsMockHandler = (overrideResponse?: MyOrganizationList | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<MyOrganizationList> | MyOrganizationList), options?: RequestHandlerOptions) => {
@@ -482,9 +482,11 @@ export const useUpdateOrganization = <TError = ErrorType<Problem>,
*
* The body selects either a Need's `requirements_version` snapshot or the current organization-visible bank with explicit filters. A need reference uses `Need.requirements_version`, not the general `Need.version`; title or suggestion-only edits do not change the confirmed-requirements snapshot. An empty bank filter searches all otherwise eligible specializations, returning each specialization separately.
*
* A search reveals card content, so it is charged like card reads. The whole visible bank is ranked, but each group returns at most the versioned per-group limit and no total is returned. In the order `main`, `near`, `unconfirmed`, each newly revealed candidate is counted as a distinct card view of the organization (a candidate it already viewed inside the window costs nothing again, so repeating the search or opening the card afterwards does not charge twice) and appears in the candidate's access history with the fields actually returned. When the allowance ends, the entries already counted are returned and `truncated` is true; the flag is also true when a group exceeded its limit, and it carries no count. No new error is returned for an exhausted allowance.
*
* Every entry is one candidate specialization. A confirmed result in Backend never confirms Networks for the same candidate. The `main`, `near`, and `unconfirmed` arrays are separate groups. A confirmed category with required-skill coverage below 0.25 belongs to `near`; other confirmed entries belong to `main` (FR09). Entries in `unconfirmed` are ordered by Fit, then coverage, then a stable internal tie-breaker that is never returned. Their category and strength remain null, and they have no theta, T, P, or test percentile. The search result uses the organization-scoped opaque `candidate_handle` as its display pseudonym and invitation reference, never a candidate account or profile identifier.
*
* The card context is limited to safe public fields: recognized stack tags, coarse experience, accepted work formats, and coarse salary compatibility. It contains no contact, candidate location, salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data. Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30 comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names `cohort_below_30`.
* The card context is limited to safe public fields: recognized stack tags, coarse experience, accepted work formats, and coarse salary compatibility. It contains no contact, candidate location, salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data. Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30 comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5, the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not fail.
*
* A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without active membership answers 404 not_found. The response is `Cache-Control: no-store`.
* @summary Search the current organization-visible candidate bank.
+1
View File
@@ -52,6 +52,7 @@ export * from './health';
export * from './identity';
export * from './invitation';
export * from './need';
export * from './notification';
export * from './organization';
export * from './privacy';
export * from './support';
@@ -0,0 +1,14 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
export * from './listMyNotificationsParams.zod';
export * from './listOrganizationNotificationsParams.zod';
export * from './notification.zod';
export * from './notificationContent.zod';
export * from './notificationKind.zod';
export * from './notificationList.zod';
export * from './notificationReadReceipt.zod';
@@ -0,0 +1,23 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const listMyNotificationsParamsLimitDefault = 20;
export const listMyNotificationsParamsLimitMax = 100;
export const listMyNotificationsParamsCursorMax = 512;
export const listMyNotificationsParamsCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const ListMyNotificationsParams = zod.object({
"limit": zod.int().min(1).max(listMyNotificationsParamsLimitMax).default(listMyNotificationsParamsLimitDefault),
"cursor": zod.string().min(1).max(listMyNotificationsParamsCursorMax).regex(listMyNotificationsParamsCursorRegExp).exactOptional()
})
export type ListMyNotificationsParams = zod.input<typeof ListMyNotificationsParams>;
export type ListMyNotificationsParamsOutput = zod.output<typeof ListMyNotificationsParams>;
@@ -0,0 +1,23 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const listOrganizationNotificationsParamsLimitDefault = 20;
export const listOrganizationNotificationsParamsLimitMax = 100;
export const listOrganizationNotificationsParamsCursorMax = 512;
export const listOrganizationNotificationsParamsCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const ListOrganizationNotificationsParams = zod.object({
"limit": zod.int().min(1).max(listOrganizationNotificationsParamsLimitMax).default(listOrganizationNotificationsParamsLimitDefault),
"cursor": zod.string().min(1).max(listOrganizationNotificationsParamsCursorMax).regex(listOrganizationNotificationsParamsCursorRegExp).exactOptional()
})
export type ListOrganizationNotificationsParams = zod.input<typeof ListOrganizationNotificationsParams>;
export type ListOrganizationNotificationsParamsOutput = zod.output<typeof ListOrganizationNotificationsParams>;
@@ -0,0 +1,32 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const notificationContentOneTitleMax = 120;
export const notificationContentOneSummaryMax = 500;
export const notificationContentOneLinkPathMax = 256;
export const notificationContentOneLinkPathRegExp = new RegExp('^/[A-Za-z0-9/_-]{0,255}$');
export const Notification = zod.object({
"id": zod.uuid().describe('Identifier of the item. It equals the identifier of the event that produced it, so a repeated delivery of the same event is the same item.'),
"kind": zod.enum(['invitation_delivered', 'synthetic']).describe('Which event put the notification into the inbox. The inbox stores a reference to the event, never its text.\n\n- invitation_delivered: an invitation reached the candidate\'s inbox. This is the in-platform delivery state of the invitation: it does not depend on any email, and a failed or missing email never blocks it. The invitation operations are planned; no invitation produces a notification yet.\n- synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action.\n\nAdding a value is a contract change; a client shows an unknown kind with the generic text of an item without content.'),
"organization_id": zod.uuid().describe('The organization context of the item: the organization that sent it to a candidate, or the organization whose cabinet holds it for an employer. The identifier is not a right to read the organization.'),
"delivered_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"read_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('When the recipient first marked the item read, or null while it is unread. A repeated mark keeps the first time.'),
"content": zod.union([zod.object({
"title": zod.string().min(1).max(notificationContentOneTitleMax).describe('Short heading in Russian.'),
"summary": zod.string().min(1).max(notificationContentOneSummaryMax).describe('One or two sentences in Russian. Plain text, never markup.'),
"link_path": zod.string().max(notificationContentOneLinkPathMax).regex(notificationContentOneLinkPathRegExp).nullable().describe('Same-origin absolute path of the screen that the notification opens, or null when there is none. It has no origin, query, fragment, or escape; a client opens it only as a path of its own router.')
}).describe('The text of a notification as the current source shows it to the recipient now. It is computed on every read and never stored, so a hiding, a revoked membership, or a withdrawn source removes it from the next read. It holds no contact, no score, and no result of an assessment.'),zod.null()]).describe('The current content, or null when the source is gone or the recipient may not see it now. A client then shows a generic line such as "The content is no longer available" and never an old copy. The item stays in the list and can be marked read.')
}).describe('One item of the inbox of the current account. Its identity, kind, organization, delivery time, and read state are stored; its content is resolved from the current source on every read.')
export type Notification = zod.input<typeof Notification>;
export type NotificationOutput = zod.output<typeof Notification>;
@@ -0,0 +1,25 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const notificationContentTitleMax = 120;
export const notificationContentSummaryMax = 500;
export const notificationContentLinkPathMax = 256;
export const notificationContentLinkPathRegExp = new RegExp('^/[A-Za-z0-9/_-]{0,255}$');
export const NotificationContent = zod.object({
"title": zod.string().min(1).max(notificationContentTitleMax).describe('Short heading in Russian.'),
"summary": zod.string().min(1).max(notificationContentSummaryMax).describe('One or two sentences in Russian. Plain text, never markup.'),
"link_path": zod.string().max(notificationContentLinkPathMax).regex(notificationContentLinkPathRegExp).nullable().describe('Same-origin absolute path of the screen that the notification opens, or null when there is none. It has no origin, query, fragment, or escape; a client opens it only as a path of its own router.')
}).describe('The text of a notification as the current source shows it to the recipient now. It is computed on every read and never stored, so a hiding, a revoked membership, or a withdrawn source removes it from the next read. It holds no contact, no score, and no result of an assessment.')
export type NotificationContent = zod.input<typeof NotificationContent>;
export type NotificationContentOutput = zod.output<typeof NotificationContent>;
@@ -0,0 +1,12 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const NotificationKind = zod.enum(['invitation_delivered', 'synthetic']).describe('Which event put the notification into the inbox. The inbox stores a reference to the event, never its text.\n\n- invitation_delivered: an invitation reached the candidate\'s inbox. This is the in-platform delivery state of the invitation: it does not depend on any email, and a failed or missing email never blocks it. The invitation operations are planned; no invitation produces a notification yet.\n- synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action.\n\nAdding a value is a contract change; a client shows an unknown kind with the generic text of an item without content.')
export type NotificationKind = zod.input<typeof NotificationKind>;
export type NotificationKindOutput = zod.output<typeof NotificationKind>;
@@ -0,0 +1,44 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const notificationListItemsItemContentOneTitleMax = 120;
export const notificationListItemsItemContentOneSummaryMax = 500;
export const notificationListItemsItemContentOneLinkPathMax = 256;
export const notificationListItemsItemContentOneLinkPathRegExp = new RegExp('^/[A-Za-z0-9/_-]{0,255}$');
export const notificationListItemsMax = 100;
export const notificationListPageNextCursorMax = 512;
export const notificationListPageNextCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const NotificationList = zod.object({
"items": zod.array(zod.object({
"id": zod.uuid().describe('Identifier of the item. It equals the identifier of the event that produced it, so a repeated delivery of the same event is the same item.'),
"kind": zod.enum(['invitation_delivered', 'synthetic']).describe('Which event put the notification into the inbox. The inbox stores a reference to the event, never its text.\n\n- invitation_delivered: an invitation reached the candidate\'s inbox. This is the in-platform delivery state of the invitation: it does not depend on any email, and a failed or missing email never blocks it. The invitation operations are planned; no invitation produces a notification yet.\n- synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action.\n\nAdding a value is a contract change; a client shows an unknown kind with the generic text of an item without content.'),
"organization_id": zod.uuid().describe('The organization context of the item: the organization that sent it to a candidate, or the organization whose cabinet holds it for an employer. The identifier is not a right to read the organization.'),
"delivered_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"read_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('When the recipient first marked the item read, or null while it is unread. A repeated mark keeps the first time.'),
"content": zod.union([zod.object({
"title": zod.string().min(1).max(notificationListItemsItemContentOneTitleMax).describe('Short heading in Russian.'),
"summary": zod.string().min(1).max(notificationListItemsItemContentOneSummaryMax).describe('One or two sentences in Russian. Plain text, never markup.'),
"link_path": zod.string().max(notificationListItemsItemContentOneLinkPathMax).regex(notificationListItemsItemContentOneLinkPathRegExp).nullable().describe('Same-origin absolute path of the screen that the notification opens, or null when there is none. It has no origin, query, fragment, or escape; a client opens it only as a path of its own router.')
}).describe('The text of a notification as the current source shows it to the recipient now. It is computed on every read and never stored, so a hiding, a revoked membership, or a withdrawn source removes it from the next read. It holds no contact, no score, and no result of an assessment.'),zod.null()]).describe('The current content, or null when the source is gone or the recipient may not see it now. A client then shows a generic line such as "The content is no longer available" and never an old copy. The item stays in the list and can be marked read.')
}).describe('One item of the inbox of the current account. Its identity, kind, organization, delivery time, and read state are stored; its content is resolved from the current source on every read.')).max(notificationListItemsMax).describe('Items of the page.'),
"page": zod.object({
"has_more": zod.boolean().describe('Whether another page follows this one.'),
"next_cursor": zod.string().min(1).max(notificationListPageNextCursorMax).regex(notificationListPageNextCursorRegExp).nullable().describe('Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing.')
}).describe('Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`.')
}).describe('One page of the inbox, newest delivery first.')
export type NotificationList = zod.input<typeof NotificationList>;
export type NotificationListOutput = zod.output<typeof NotificationList>;
@@ -0,0 +1,15 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const NotificationReadReceipt = zod.object({
"id": zod.uuid().describe('Identifier of the marked item.'),
"read_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
}).describe('The read state of one item after a mark. It carries no content, so marking never reads the source.')
export type NotificationReadReceipt = zod.input<typeof NotificationReadReceipt>;
export type NotificationReadReceiptOutput = zod.output<typeof NotificationReadReceipt>;
@@ -80,7 +80,7 @@ export const MatchConfirmedCandidate = zod.object({
}).describe('Components from the FR09 ranking model for a confirmed category. `percentile` is null when fewer than 30 comparable real candidates are available; the ranking uses neutral T = 0.5 and does not publish a percentile. If ML is unavailable, `semantics` uses neutral 0.5 and the reason appears in `unknown_flags`.'),
"unknown_flags": zod.array(zod.object({
"component": zod.enum(['semantics', 'percentile', 'assessment', 'freshness', 'responsiveness', 'experience_band', 'work_formats', 'salary_compatibility', 'domain']).describe('Ranking or public-card component whose value is unknown.'),
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history']).describe('Bounded explanation for an unknown component, not a hiding reason.')
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history', 'percentile_not_computed']).describe('Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported only while the comparable real cohort of the category is smaller than the versioned minimum; once the cohort reaches the minimum but the percentile is still not computed, the reason is `percentile_not_computed`. In both cases T is the neutral 0.5.')
}).describe('A safe, bounded explanation for one unavailable component.')).max(matchConfirmedCandidateUnknownFlagsMax)
}).describe('One confirmed specialization entry in the `main` or `near` group. The group containing it supplies the group label. A candidate may have a separate entry for another specialization.')
@@ -140,7 +140,7 @@ export const MatchSearchGroups = zod.object({
}).describe('Components from the FR09 ranking model for a confirmed category. `percentile` is null when fewer than 30 comparable real candidates are available; the ranking uses neutral T = 0.5 and does not publish a percentile. If ML is unavailable, `semantics` uses neutral 0.5 and the reason appears in `unknown_flags`.'),
"unknown_flags": zod.array(zod.object({
"component": zod.enum(['semantics', 'percentile', 'assessment', 'freshness', 'responsiveness', 'experience_band', 'work_formats', 'salary_compatibility', 'domain']).describe('Ranking or public-card component whose value is unknown.'),
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history']).describe('Bounded explanation for an unknown component, not a hiding reason.')
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history', 'percentile_not_computed']).describe('Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported only while the comparable real cohort of the category is smaller than the versioned minimum; once the cohort reaches the minimum but the percentile is still not computed, the reason is `percentile_not_computed`. In both cases T is the neutral 0.5.')
}).describe('A safe, bounded explanation for one unavailable component.')).max(matchSearchGroupsMainItemUnknownFlagsMax)
}).describe('One confirmed specialization entry in the `main` or `near` group. The group containing it supplies the group label. A candidate may have a separate entry for another specialization.')),
"near": zod.array(zod.object({
@@ -176,7 +176,7 @@ export const MatchSearchGroups = zod.object({
}).describe('Components from the FR09 ranking model for a confirmed category. `percentile` is null when fewer than 30 comparable real candidates are available; the ranking uses neutral T = 0.5 and does not publish a percentile. If ML is unavailable, `semantics` uses neutral 0.5 and the reason appears in `unknown_flags`.'),
"unknown_flags": zod.array(zod.object({
"component": zod.enum(['semantics', 'percentile', 'assessment', 'freshness', 'responsiveness', 'experience_band', 'work_formats', 'salary_compatibility', 'domain']).describe('Ranking or public-card component whose value is unknown.'),
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history']).describe('Bounded explanation for an unknown component, not a hiding reason.')
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history', 'percentile_not_computed']).describe('Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported only while the comparable real cohort of the category is smaller than the versioned minimum; once the cohort reaches the minimum but the percentile is still not computed, the reason is `percentile_not_computed`. In both cases T is the neutral 0.5.')
}).describe('A safe, bounded explanation for one unavailable component.')).max(matchSearchGroupsNearItemUnknownFlagsMax)
}).describe('One confirmed specialization entry in the `main` or `near` group. The group containing it supplies the group label. A candidate may have a separate entry for another specialization.')),
"unconfirmed": zod.array(zod.object({
@@ -202,7 +202,7 @@ export const MatchSearchGroups = zod.object({
}).describe('Unconfirmed entries are ordered only by Fit and coverage. This strict component object has no theta, T, P, test percentile, or confirmed assessment score.'),
"unknown_flags": zod.array(zod.object({
"component": zod.enum(['semantics', 'percentile', 'assessment', 'freshness', 'responsiveness', 'experience_band', 'work_formats', 'salary_compatibility', 'domain']).describe('Ranking or public-card component whose value is unknown.'),
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history']).describe('Bounded explanation for an unknown component, not a hiding reason.')
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history', 'percentile_not_computed']).describe('Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported only while the comparable real cohort of the category is smaller than the versioned minimum; once the cohort reaches the minimum but the percentile is still not computed, the reason is `percentile_not_computed`. In both cases T is the neutral 0.5.')
}).describe('A safe, bounded explanation for one unavailable component.')).max(matchSearchGroupsUnconfirmedItemUnknownFlagsMax)
}).describe('One specialization with no confirmed category. `category` and `strength` remain present and null. A confirmation in another specialization never changes this entry. The schema intentionally has no assessment measurement fields.'))
}).describe('Separate ranking groups. Confirmed categories appear in main and near; unconfirmed specializations appear only in the lower unconfirmed group.')
@@ -168,7 +168,7 @@ export const MatchSearchResponse = zod.object({
}).describe('Components from the FR09 ranking model for a confirmed category. `percentile` is null when fewer than 30 comparable real candidates are available; the ranking uses neutral T = 0.5 and does not publish a percentile. If ML is unavailable, `semantics` uses neutral 0.5 and the reason appears in `unknown_flags`.'),
"unknown_flags": zod.array(zod.object({
"component": zod.enum(['semantics', 'percentile', 'assessment', 'freshness', 'responsiveness', 'experience_band', 'work_formats', 'salary_compatibility', 'domain']).describe('Ranking or public-card component whose value is unknown.'),
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history']).describe('Bounded explanation for an unknown component, not a hiding reason.')
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history', 'percentile_not_computed']).describe('Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported only while the comparable real cohort of the category is smaller than the versioned minimum; once the cohort reaches the minimum but the percentile is still not computed, the reason is `percentile_not_computed`. In both cases T is the neutral 0.5.')
}).describe('A safe, bounded explanation for one unavailable component.')).max(matchSearchResponseGroupsMainItemUnknownFlagsMax)
}).describe('One confirmed specialization entry in the `main` or `near` group. The group containing it supplies the group label. A candidate may have a separate entry for another specialization.')),
"near": zod.array(zod.object({
@@ -204,7 +204,7 @@ export const MatchSearchResponse = zod.object({
}).describe('Components from the FR09 ranking model for a confirmed category. `percentile` is null when fewer than 30 comparable real candidates are available; the ranking uses neutral T = 0.5 and does not publish a percentile. If ML is unavailable, `semantics` uses neutral 0.5 and the reason appears in `unknown_flags`.'),
"unknown_flags": zod.array(zod.object({
"component": zod.enum(['semantics', 'percentile', 'assessment', 'freshness', 'responsiveness', 'experience_band', 'work_formats', 'salary_compatibility', 'domain']).describe('Ranking or public-card component whose value is unknown.'),
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history']).describe('Bounded explanation for an unknown component, not a hiding reason.')
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history', 'percentile_not_computed']).describe('Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported only while the comparable real cohort of the category is smaller than the versioned minimum; once the cohort reaches the minimum but the percentile is still not computed, the reason is `percentile_not_computed`. In both cases T is the neutral 0.5.')
}).describe('A safe, bounded explanation for one unavailable component.')).max(matchSearchResponseGroupsNearItemUnknownFlagsMax)
}).describe('One confirmed specialization entry in the `main` or `near` group. The group containing it supplies the group label. A candidate may have a separate entry for another specialization.')),
"unconfirmed": zod.array(zod.object({
@@ -230,10 +230,11 @@ export const MatchSearchResponse = zod.object({
}).describe('Unconfirmed entries are ordered only by Fit and coverage. This strict component object has no theta, T, P, test percentile, or confirmed assessment score.'),
"unknown_flags": zod.array(zod.object({
"component": zod.enum(['semantics', 'percentile', 'assessment', 'freshness', 'responsiveness', 'experience_band', 'work_formats', 'salary_compatibility', 'domain']).describe('Ranking or public-card component whose value is unknown.'),
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history']).describe('Bounded explanation for an unknown component, not a hiding reason.')
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history', 'percentile_not_computed']).describe('Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported only while the comparable real cohort of the category is smaller than the versioned minimum; once the cohort reaches the minimum but the percentile is still not computed, the reason is `percentile_not_computed`. In both cases T is the neutral 0.5.')
}).describe('A safe, bounded explanation for one unavailable component.')).max(matchSearchResponseGroupsUnconfirmedItemUnknownFlagsMax)
}).describe('One specialization with no confirmed category. `category` and `strength` remain present and null. A confirmation in another specialization never changes this entry. The schema intentionally has no assessment measurement fields.'))
}).describe('Separate ranking groups. Confirmed categories appear in main and near; unconfirmed specializations appear only in the lower unconfirmed group.')
}).describe('Separate ranking groups. Confirmed categories appear in main and near; unconfirmed specializations appear only in the lower unconfirmed group.'),
"truncated": zod.boolean().describe('True when the groups are not the whole ranked result: a group exceeded the versioned per-group limit, or the organization\'s card-view allowance ended while the entries were being revealed. The entries returned are in rank order and already counted as card views. It carries no total, so it does not reveal how many candidates match.')
}).describe('Anonymous search result grouped by specialization state. Repeated organization-scoped handles are allowed when the same candidate has different specialization entries; entries never transfer confirmation between specializations.')
export type MatchSearchResponse = zod.input<typeof MatchSearchResponse>;
@@ -49,7 +49,7 @@ export const MatchUnconfirmedCandidate = zod.object({
}).describe('Unconfirmed entries are ordered only by Fit and coverage. This strict component object has no theta, T, P, test percentile, or confirmed assessment score.'),
"unknown_flags": zod.array(zod.object({
"component": zod.enum(['semantics', 'percentile', 'assessment', 'freshness', 'responsiveness', 'experience_band', 'work_formats', 'salary_compatibility', 'domain']).describe('Ranking or public-card component whose value is unknown.'),
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history']).describe('Bounded explanation for an unknown component, not a hiding reason.')
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history', 'percentile_not_computed']).describe('Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported only while the comparable real cohort of the category is smaller than the versioned minimum; once the cohort reaches the minimum but the percentile is still not computed, the reason is `percentile_not_computed`. In both cases T is the neutral 0.5.')
}).describe('A safe, bounded explanation for one unavailable component.')).max(matchUnconfirmedCandidateUnknownFlagsMax)
}).describe('One specialization with no confirmed category. `category` and `strength` remain present and null. A confirmation in another specialization never changes this entry. The schema intentionally has no assessment measurement fields.')
@@ -8,7 +8,7 @@ import * as zod from 'zod';
export const MatchUnknownFlag = zod.object({
"component": zod.enum(['semantics', 'percentile', 'assessment', 'freshness', 'responsiveness', 'experience_band', 'work_formats', 'salary_compatibility', 'domain']).describe('Ranking or public-card component whose value is unknown.'),
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history']).describe('Bounded explanation for an unknown component, not a hiding reason.')
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history', 'percentile_not_computed']).describe('Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported only while the comparable real cohort of the category is smaller than the versioned minimum; once the cohort reaches the minimum but the percentile is still not computed, the reason is `percentile_not_computed`. In both cases T is the neutral 0.5.')
}).describe('A safe, bounded explanation for one unavailable component.')
export type MatchUnknownFlag = zod.input<typeof MatchUnknownFlag>;
@@ -11,7 +11,7 @@ export const MatchUnknownFlagsMax = 9;
export const MatchUnknownFlags = zod.array(zod.object({
"component": zod.enum(['semantics', 'percentile', 'assessment', 'freshness', 'responsiveness', 'experience_band', 'work_formats', 'salary_compatibility', 'domain']).describe('Ranking or public-card component whose value is unknown.'),
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history']).describe('Bounded explanation for an unknown component, not a hiding reason.')
"reason": zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history', 'percentile_not_computed']).describe('Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported only while the comparable real cohort of the category is smaller than the versioned minimum; once the cohort reaches the minimum but the percentile is still not computed, the reason is `percentile_not_computed`. In both cases T is the neutral 0.5.')
}).describe('A safe, bounded explanation for one unavailable component.')).max(MatchUnknownFlagsMax)
export type MatchUnknownFlags = zod.input<typeof MatchUnknownFlags>;
@@ -6,7 +6,7 @@
*/
import * as zod from 'zod';
export const MatchUnknownReason = zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history']).describe('Bounded explanation for an unknown component, not a hiding reason.')
export const MatchUnknownReason = zod.enum(['ml_unavailable', 'cohort_below_30', 'no_confirmation_for_specialization', 'not_in_public_card', 'need_field_unconfirmed', 'no_freshness_history', 'no_response_history', 'percentile_not_computed']).describe('Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported only while the comparable real cohort of the category is smaller than the versioned minimum; once the cohort reaches the minimum but the percentile is still not computed, the reason is `percentile_not_computed`. In both cases T is the neutral 0.5.')
export type MatchUnknownReason = zod.input<typeof MatchUnknownReason>;
export type MatchUnknownReasonOutput = zod.output<typeof MatchUnknownReason>;
+2
View File
@@ -20,6 +20,7 @@ export const paths = {
results: "/candidate/results",
result: (attemptId: string) => `/candidate/results/${encodeURIComponent(attemptId)}`,
invitations: "/candidate/invitations",
notifications: "/candidate/notifications",
privacy: "/candidate/privacy",
supportCases: "/candidate/support/cases",
supportNew: "/candidate/support/cases/new",
@@ -38,6 +39,7 @@ export const paths = {
`/employer/needs/${encodeURIComponent(needId)}?organization_id=${encodeURIComponent(organizationId)}`,
candidates: "/employer/candidates",
invitations: "/employer/invitations",
notifications: "/employer/notifications",
supportCases: "/employer/support/cases",
supportNew: "/employer/support/cases/new",
supportCase: (caseId: string) => `/employer/support/cases/${encodeURIComponent(caseId)}`,
@@ -10,6 +10,7 @@ const navigation = [
{ to: paths.candidate.assessment, label: "Тест", end: false },
{ to: paths.candidate.results, label: "Результаты", end: false },
{ to: paths.candidate.invitations, label: "Приглашения", end: false },
{ to: paths.candidate.notifications, label: "Уведомления", end: false },
{ to: paths.candidate.privacy, label: "Приватность", end: false },
{ to: paths.support, label: "Поддержка", end: false },
] as const;
@@ -8,6 +8,7 @@ const navigation = [
{ to: paths.employer.needs, label: "Потребности" },
{ to: paths.employer.candidates, label: "Кандидаты" },
{ to: paths.employer.invitations, label: "Приглашения" },
{ to: paths.employer.notifications, label: "Уведомления" },
{ to: paths.support, label: "Поддержка" },
] as const;