413 lines
16 KiB
TypeScript
413 lines
16 KiB
TypeScript
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
|
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
import { useSearchParams } from "react-router-dom";
|
|
import { listOrganizationNeeds } from "../../../shared/api/endpoints/need/need";
|
|
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
|
|
import { ApiRequestError } from "../../../shared/api";
|
|
import type { MyOrganizationList, NeedList } from "../../../shared/api/schemas";
|
|
import { paths } from "../../../shared/config/paths";
|
|
import {
|
|
Button,
|
|
ButtonLink,
|
|
EmptyState,
|
|
ErrorState,
|
|
ForbiddenState,
|
|
LoadingState,
|
|
Page,
|
|
Section,
|
|
} from "../../../shared/ui";
|
|
import {
|
|
activeNeedOrganizations,
|
|
isNeedSessionCurrent,
|
|
needListPageSize,
|
|
needQueryKeys,
|
|
removeAllNeedQueries,
|
|
removeNeedQueriesForOrganization,
|
|
removeNeedQueriesForSessionChange,
|
|
useNeedOrganizationDirectory,
|
|
} from "../../../entities/need";
|
|
import styles from "./need-list-page.module.css";
|
|
|
|
type NeedSummary = NeedList["items"][number];
|
|
const emptyDirectoryPages: readonly MyOrganizationList[] = [];
|
|
|
|
const specializationLabels: Readonly<Record<string, string>> = {
|
|
backend: "Backend",
|
|
frontend: "Frontend",
|
|
mobile: "Мобильная разработка",
|
|
network_engineer: "Сетевые технологии",
|
|
devops_sre: "DevOps/SRE",
|
|
data_analyst: "Аналитика данных",
|
|
ds_ml: "DS/ML",
|
|
information_security: "Информационная безопасность",
|
|
qa: "QA",
|
|
};
|
|
|
|
const gradeLabels: Readonly<Record<string, string>> = {
|
|
intern: "Стажер",
|
|
junior: "Junior",
|
|
middle: "Middle",
|
|
senior: "Senior",
|
|
};
|
|
|
|
function isAccessLoss(error: unknown): error is ApiRequestError {
|
|
return (
|
|
error instanceof ApiRequestError &&
|
|
(error.status === 401 || error.status === 403 || error.status === 404)
|
|
);
|
|
}
|
|
|
|
function displayDecision<T extends string>(
|
|
state: { status: "confirmed" | "extracted" | "unknown"; value: T | null },
|
|
labels: Readonly<Record<string, string>>,
|
|
): string {
|
|
if (state.status === "unknown" || state.value === null) return "Не указано";
|
|
const label = labels[state.value] ?? state.value;
|
|
return state.status === "extracted" ? `Предложено: ${label}` : label;
|
|
}
|
|
|
|
function NeedCard({ item, organizationId }: { item: NeedSummary; organizationId: string }) {
|
|
const missingCount = item.readiness.missing_fields.length;
|
|
return (
|
|
<article className={styles.card}>
|
|
<div className={styles["card-heading"]}>
|
|
<h3>{item.title}</h3>
|
|
<span
|
|
className={item.readiness.status === "complete" ? styles.complete : styles.incomplete}
|
|
>
|
|
{item.readiness.status === "complete"
|
|
? "Данные заполнены"
|
|
: `Не хватает данных: ${missingCount}`}
|
|
</span>
|
|
</div>
|
|
<dl className={styles.facts}>
|
|
<dt>Специализация</dt>
|
|
<dd>{displayDecision(item.specialization, specializationLabels)}</dd>
|
|
<dt>Грейд</dt>
|
|
<dd>{displayDecision(item.grade, gradeLabels)}</dd>
|
|
<dt>Версия</dt>
|
|
<dd>{item.version}</dd>
|
|
</dl>
|
|
{missingCount > 0 ? (
|
|
<ul className={styles.missing}>
|
|
{item.readiness.missing_fields.map((field) => (
|
|
<li key={field.field}>{field.question}</li>
|
|
))}
|
|
</ul>
|
|
) : null}
|
|
<div className={styles.actions}>
|
|
<ButtonLink to={paths.employer.need(item.id, organizationId)} variant="secondary">
|
|
Открыть потребность
|
|
</ButtonLink>
|
|
<ButtonLink to={paths.employer.candidatesForNeed(item.id, organizationId)} variant="quiet">
|
|
Подобрать кандидатов
|
|
</ButtonLink>
|
|
</div>
|
|
</article>
|
|
);
|
|
}
|
|
|
|
export function NeedListPage() {
|
|
const queryClient = useQueryClient();
|
|
const sessionQuery = useGetCurrentSession({ query: { retry: false } });
|
|
const session = sessionQuery.data;
|
|
const accountId = session?.account.id;
|
|
const sessionReady =
|
|
Boolean(session && session.account.scenario === "employer") &&
|
|
isNeedSessionCurrent(queryClient, session);
|
|
const directory = useNeedOrganizationDirectory(session, sessionReady);
|
|
const directoryData = directory.data;
|
|
const directoryIsError = directory.isError;
|
|
const directoryError = directory.error;
|
|
const directoryIsFetching = directory.isFetching;
|
|
const directoryIsFetchingNextPage = directory.isFetchingNextPage;
|
|
const directoryIsLoading = directory.isLoading;
|
|
const hasMoreOrganizations = directory.hasNextPage;
|
|
const fetchNextOrganizationPage = directory.fetchNextPage;
|
|
const refetchDirectory = directory.refetch;
|
|
const [searchParams, setSearchParams] = useSearchParams();
|
|
const selectedOrganizationId = searchParams.get("organization_id");
|
|
const [deniedContext, setDeniedContext] = useState<string | null>(null);
|
|
const reportedAccessError = useRef(false);
|
|
const previousSessionRef = useRef<{ accountId: string; csrfToken: string } | null>(null);
|
|
const pages = directoryData?.pages ?? emptyDirectoryPages;
|
|
const organizations = useMemo(() => activeNeedOrganizations(pages), [pages]);
|
|
const selectedOrganization = organizations.find(
|
|
(item) => item.organization.id === selectedOrganizationId,
|
|
);
|
|
const directoryRefreshing = directoryIsFetching && !directoryIsFetchingNextPage;
|
|
const directoryFresh =
|
|
sessionReady && Boolean(directoryData) && !directoryIsError && !directoryRefreshing;
|
|
const deniedKey =
|
|
accountId && selectedOrganizationId ? `${accountId}:${selectedOrganizationId}` : null;
|
|
const denied = deniedContext !== null && deniedContext === deniedKey;
|
|
const membershipDenied =
|
|
Boolean(selectedOrganizationId) &&
|
|
!selectedOrganization &&
|
|
directoryFresh &&
|
|
!hasMoreOrganizations;
|
|
|
|
useEffect(() => {
|
|
const next =
|
|
session && sessionReady
|
|
? { accountId: session.account.id, csrfToken: session.csrf_token }
|
|
: null;
|
|
const previous = previousSessionRef.current;
|
|
if (
|
|
previous &&
|
|
(!next || previous.accountId !== next.accountId || previous.csrfToken !== next.csrfToken)
|
|
) {
|
|
removeNeedQueriesForSessionChange(queryClient);
|
|
}
|
|
previousSessionRef.current = next;
|
|
}, [queryClient, session, sessionReady]);
|
|
|
|
useEffect(() => {
|
|
if (directoryIsError && isAccessLoss(directoryError)) {
|
|
removeAllNeedQueries(queryClient);
|
|
}
|
|
}, [directoryError, directoryIsError, queryClient]);
|
|
|
|
useEffect(() => {
|
|
if (!sessionReady || !directoryData || directoryIsError || directoryIsFetchingNextPage) return;
|
|
if (selectedOrganizationId) {
|
|
if (!selectedOrganization && hasMoreOrganizations) void fetchNextOrganizationPage();
|
|
return;
|
|
}
|
|
if (organizations[0]) {
|
|
setSearchParams({ organization_id: organizations[0].organization.id }, { replace: true });
|
|
} else if (hasMoreOrganizations) {
|
|
void fetchNextOrganizationPage();
|
|
}
|
|
}, [
|
|
directoryData,
|
|
directoryIsError,
|
|
directoryIsFetchingNextPage,
|
|
fetchNextOrganizationPage,
|
|
hasMoreOrganizations,
|
|
organizations,
|
|
selectedOrganization,
|
|
selectedOrganizationId,
|
|
sessionReady,
|
|
setSearchParams,
|
|
]);
|
|
|
|
const needs = useInfiniteQuery({
|
|
queryKey: needQueryKeys.list(
|
|
accountId ?? "no-session",
|
|
selectedOrganizationId ?? "no-organization",
|
|
),
|
|
initialPageParam: undefined as string | undefined,
|
|
queryFn: async ({ pageParam, signal }) => {
|
|
if (!isNeedSessionCurrent(queryClient, session))
|
|
throw new Error("The session changed before the need-list request.");
|
|
const result = await listOrganizationNeeds(
|
|
selectedOrganizationId ?? "",
|
|
{ limit: needListPageSize, ...(pageParam ? { cursor: pageParam } : {}) },
|
|
{ signal },
|
|
);
|
|
if (!isNeedSessionCurrent(queryClient, session))
|
|
throw new Error("The session changed during the need-list request.");
|
|
return result;
|
|
},
|
|
getNextPageParam: (lastPage) =>
|
|
lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined,
|
|
enabled: directoryFresh && selectedOrganization !== undefined && !denied && !membershipDenied,
|
|
gcTime: 0,
|
|
staleTime: 0,
|
|
refetchOnMount: "always",
|
|
refetchOnWindowFocus: "always",
|
|
retry: false,
|
|
});
|
|
|
|
const handleAccessLoss = useCallback(
|
|
async (error: ApiRequestError, deniedOrganizationId: string | null) => {
|
|
if (
|
|
!isAccessLoss(error) ||
|
|
!deniedOrganizationId ||
|
|
!isNeedSessionCurrent(queryClient, session)
|
|
)
|
|
return;
|
|
if (!accountId) return;
|
|
setDeniedContext(`${accountId}:${deniedOrganizationId}`);
|
|
removeNeedQueriesForOrganization(queryClient, deniedOrganizationId);
|
|
await refetchDirectory();
|
|
},
|
|
[accountId, queryClient, refetchDirectory, session, setDeniedContext],
|
|
);
|
|
|
|
useEffect(() => {
|
|
if (!needs.isError || !isAccessLoss(needs.error)) {
|
|
if (!needs.isError) reportedAccessError.current = false;
|
|
return;
|
|
}
|
|
if (reportedAccessError.current) return;
|
|
reportedAccessError.current = true;
|
|
void handleAccessLoss(needs.error, selectedOrganizationId);
|
|
}, [handleAccessLoss, needs.error, needs.isError, selectedOrganizationId]);
|
|
|
|
useEffect(() => {
|
|
if (!membershipDenied || !selectedOrganizationId) return;
|
|
removeNeedQueriesForOrganization(queryClient, selectedOrganizationId);
|
|
}, [membershipDenied, queryClient, selectedOrganizationId]);
|
|
|
|
const listItems = needs.data?.pages.flatMap((page) => page.items) ?? [];
|
|
const hasAccessError = sessionQuery.isError || directoryIsError;
|
|
const loading =
|
|
!sessionQuery.isError &&
|
|
(!sessionReady ||
|
|
directoryIsLoading ||
|
|
directoryRefreshing ||
|
|
!directoryData ||
|
|
(!selectedOrganization && hasMoreOrganizations));
|
|
|
|
return (
|
|
<Page
|
|
title="Потребности"
|
|
eyebrow="Кабинет работодателя"
|
|
lead="Описывайте потребности команды, подтверждайте предложения из текста и проверяйте готовность данных."
|
|
width="wide"
|
|
>
|
|
{sessionQuery.isError ? (
|
|
isAccessLoss(sessionQuery.error) ? (
|
|
<ForbiddenState error={sessionQuery.error} title="Текущий вход не подтвержден" />
|
|
) : (
|
|
<ErrorState
|
|
error={sessionQuery.error}
|
|
isRetrying={sessionQuery.isFetching}
|
|
onRetry={() => void sessionQuery.refetch()}
|
|
/>
|
|
)
|
|
) : null}
|
|
{directoryIsError ? (
|
|
isAccessLoss(directoryError) ? (
|
|
<ForbiddenState error={directoryError} />
|
|
) : (
|
|
<ErrorState
|
|
error={directoryError}
|
|
isRetrying={directoryIsFetching}
|
|
onRetry={() => void refetchDirectory()}
|
|
/>
|
|
)
|
|
) : null}
|
|
{loading ? <LoadingState label="Проверяем компанию и загружаем потребности..." /> : null}
|
|
{!hasAccessError && directoryData && directoryFresh ? (
|
|
<div className={styles.content}>
|
|
{organizations.length > 0 ? (
|
|
<Section title="Список потребностей">
|
|
<div className={styles.toolbar}>
|
|
<div className={styles.selector}>
|
|
<label htmlFor="need-organization">Компания</label>
|
|
<select
|
|
id="need-organization"
|
|
value={selectedOrganization?.organization.id ?? ""}
|
|
onChange={(event) => {
|
|
const next = new URLSearchParams(searchParams);
|
|
next.set("organization_id", event.currentTarget.value);
|
|
setDeniedContext(null);
|
|
reportedAccessError.current = false;
|
|
setSearchParams(next);
|
|
}}
|
|
>
|
|
{!selectedOrganization ? <option value="">Выберите компанию</option> : null}
|
|
{organizations.map((item) => (
|
|
<option key={item.organization.id} value={item.organization.id}>
|
|
{item.organization.name}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
{selectedOrganization ? (
|
|
<ButtonLink to={paths.employer.needNew(selectedOrganization.organization.id)}>
|
|
Создать потребность
|
|
</ButtonLink>
|
|
) : null}
|
|
</div>
|
|
{denied || membershipDenied ? (
|
|
<ForbiddenState
|
|
title="Потребности компании недоступны"
|
|
description="Доступ владельца не подтвержден. Выберите компанию с активным членством владельца."
|
|
action={
|
|
<Button
|
|
variant="secondary"
|
|
onClick={() => {
|
|
setDeniedContext(null);
|
|
reportedAccessError.current = false;
|
|
void refetchDirectory();
|
|
}}
|
|
>
|
|
Проверить доступ снова
|
|
</Button>
|
|
}
|
|
/>
|
|
) : null}
|
|
{needs.isError && !isAccessLoss(needs.error) ? (
|
|
<ErrorState
|
|
error={needs.error}
|
|
isRetrying={needs.isFetching}
|
|
onRetry={() => void needs.refetch()}
|
|
/>
|
|
) : null}
|
|
{needs.isLoading ? <LoadingState label="Загружаем потребности..." /> : null}
|
|
{needs.data && !needs.isError && !denied && !membershipDenied ? (
|
|
listItems.length === 0 ? (
|
|
<EmptyState
|
|
title="Потребностей пока нет"
|
|
description="Создайте первую потребность. Связанная вакансия для этого не нужна."
|
|
action={
|
|
selectedOrganization ? (
|
|
<ButtonLink
|
|
to={paths.employer.needNew(selectedOrganization.organization.id)}
|
|
>
|
|
Создать потребность
|
|
</ButtonLink>
|
|
) : null
|
|
}
|
|
/>
|
|
) : (
|
|
<div className={styles.list}>
|
|
{listItems.map((item) => (
|
|
<NeedCard
|
|
key={item.id}
|
|
item={item}
|
|
organizationId={selectedOrganizationId ?? ""}
|
|
/>
|
|
))}
|
|
</div>
|
|
)
|
|
) : null}
|
|
{needs.hasNextPage && !denied && !membershipDenied ? (
|
|
<div className={styles["load-more"]}>
|
|
<Button
|
|
variant="secondary"
|
|
isBusy={needs.isFetchingNextPage}
|
|
onClick={() => void needs.fetchNextPage()}
|
|
>
|
|
{needs.isFetchingNextPage ? "Загружаем..." : "Показать еще"}
|
|
</Button>
|
|
</div>
|
|
) : null}
|
|
</Section>
|
|
) : (
|
|
<ForbiddenState
|
|
title="Нужны права владельца компании"
|
|
description="Потребностями в этой версии может управлять только владелец."
|
|
/>
|
|
)}
|
|
{hasMoreOrganizations ? (
|
|
<div className={styles["load-more"]}>
|
|
<Button
|
|
variant="secondary"
|
|
isBusy={directoryIsFetchingNextPage}
|
|
onClick={() => void fetchNextOrganizationPage()}
|
|
>
|
|
{directoryIsFetchingNextPage ? "Загружаем компании..." : "Показать еще компании"}
|
|
</Button>
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
) : null}
|
|
</Page>
|
|
);
|
|
}
|