feat: add assessment, privacy and support flows
This commit is contained in:
1 parent
ee3738ee73
commit
e4f24fa202
339 files changed
+56454
-1126
No files matched your search
@@ -0,0 +1,2 @@
|
||||
export { AssessmentAttemptPage } from "./ui/assessment-attempt-page";
|
||||
export { AssessmentPage } from "./ui/assessment-page";
|
||||
@@ -0,0 +1,102 @@
|
||||
.layout {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.resume,
|
||||
.finalize,
|
||||
.info,
|
||||
.result,
|
||||
.item {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
}
|
||||
|
||||
.resume p,
|
||||
.finalize p,
|
||||
.info p,
|
||||
.result p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.item {
|
||||
gap: var(--space-4);
|
||||
border-color: var(--color-border-strong);
|
||||
}
|
||||
|
||||
.item-heading {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.item-heading h2,
|
||||
.result h2 {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.item-heading span {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.prompt {
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.info {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
.result {
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.demo-label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.result-error {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.back-link {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
@media (width < 42rem) {
|
||||
.resume,
|
||||
.finalize,
|
||||
.info,
|
||||
.result,
|
||||
.item {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,678 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import {
|
||||
finalizeMyAssessmentAttempt,
|
||||
startMyAssessmentAttemptSession,
|
||||
} from "../../../shared/api/endpoints/assessment/assessment";
|
||||
import {
|
||||
getGetCurrentSessionQueryKey,
|
||||
useGetCurrentSession,
|
||||
} from "../../../shared/api/endpoints/identity/identity";
|
||||
import type {
|
||||
AssessmentAttempt,
|
||||
AssessmentFinalization,
|
||||
Session,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config/paths";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Page,
|
||||
Section,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
assessmentQueryKeys,
|
||||
assessmentResultSummary,
|
||||
assessmentSessionMatches,
|
||||
gradeLabels,
|
||||
isOutcomeAmbiguous,
|
||||
isCurrentAssessmentSession,
|
||||
methodLabel,
|
||||
parseAssessmentAttemptResponse,
|
||||
removeAssessmentQueries,
|
||||
removeAssessmentQueriesForSessionChange,
|
||||
useAssessmentAttempt,
|
||||
useAssessmentResult,
|
||||
} from "../../../entities/assessment";
|
||||
import {
|
||||
AnswerForm,
|
||||
buildAnswerSubmission,
|
||||
newIdempotencyKey,
|
||||
submitPendingAnswerCommand,
|
||||
} from "../../../features/answer-assessment";
|
||||
import type { AnswerDraft, PendingAnswerCommand } from "../../../features/answer-assessment";
|
||||
import attemptStyles from "./assessment-attempt-page.module.css";
|
||||
|
||||
type PendingFinalize = { key: string; body: AssessmentFinalization };
|
||||
|
||||
function isAccessLoss(error: unknown): error is ApiRequestError {
|
||||
return error instanceof ApiRequestError && [401, 403, 404].includes(error.status);
|
||||
}
|
||||
|
||||
function isTerminal(attempt: AssessmentAttempt): boolean {
|
||||
return ["completed", "expired", "insufficient_bank"].includes(attempt.state);
|
||||
}
|
||||
|
||||
function attemptName(attempt: AssessmentAttempt): string {
|
||||
if (attempt.kind === "demo_express") return "Демонстрационный экспресс-запуск";
|
||||
return `${attempt.specialization ? attempt.specialization : "Проверка"} - ${attempt.target_grade ? gradeLabels[attempt.target_grade] : ""}`;
|
||||
}
|
||||
|
||||
function answerErrorMessage(error: unknown): string {
|
||||
if (error instanceof ApiRequestError && error.status === 0) {
|
||||
return "Не удалось связаться с сервером. Повторите отправку того же ответа.";
|
||||
}
|
||||
if (error instanceof ApiRequestError && error.status >= 500) {
|
||||
return "Сервер не подтвердил ответ. Повторите отправку того же ответа.";
|
||||
}
|
||||
if (error instanceof ApiRequestError && error.status === 429) {
|
||||
return error.retryAfterSeconds
|
||||
? `Слишком много запросов. Повторите через ${error.retryAfterSeconds} сек.`
|
||||
: "Слишком много запросов. Повторите позже.";
|
||||
}
|
||||
if (error instanceof ApiRequestError && error.status === 412) {
|
||||
return "Попытка изменилась в другом окне. Проверьте актуальное задание и отправьте ответ еще раз.";
|
||||
}
|
||||
if (error instanceof ApiRequestError && error.status === 400) {
|
||||
return "Сервер не принял этот формат ответа. Проверьте введенные данные.";
|
||||
}
|
||||
return "Не удалось отправить ответ. Проверьте соединение и повторите попытку.";
|
||||
}
|
||||
|
||||
export function AssessmentAttemptPage() {
|
||||
const { attemptId = "" } = useParams();
|
||||
return <AssessmentAttemptContent key={attemptId} attemptId={attemptId} />;
|
||||
}
|
||||
|
||||
function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
const queryClient = useQueryClient();
|
||||
const session = useGetCurrentSession({ query: { retry: false } });
|
||||
const actor = session.data;
|
||||
const actorReady = Boolean(
|
||||
actor &&
|
||||
actor.account.scenario === "candidate" &&
|
||||
isCurrentAssessmentSession(queryClient, actor),
|
||||
);
|
||||
const attemptQuery = useAssessmentAttempt({ actor, attemptId, enabled: actorReady, queryClient });
|
||||
const attempt = attemptQuery.data;
|
||||
const resultQuery = useAssessmentResult({
|
||||
actor,
|
||||
attemptId,
|
||||
enabled: actorReady && Boolean(attempt && isTerminal(attempt)),
|
||||
queryClient,
|
||||
});
|
||||
const [workReady, setWorkReady] = useState(false);
|
||||
const [resumeBusy, setResumeBusy] = useState(false);
|
||||
const [pendingResume, setPendingResume] = useState<{ key: string; version: number } | null>(null);
|
||||
const [pendingAnswer, setPendingAnswer] = useState<PendingAnswerCommand | null>(null);
|
||||
const [answerBusy, setAnswerBusy] = useState(false);
|
||||
const [answerError, setAnswerError] = useState<string | null>(null);
|
||||
const [answerNeedsReview, setAnswerNeedsReview] = useState(false);
|
||||
const [pendingFinalize, setPendingFinalize] = useState<PendingFinalize | null>(null);
|
||||
const [finalizeBusy, setFinalizeBusy] = useState(false);
|
||||
const [pageError, setPageError] = useState<string | null>(null);
|
||||
const [accessDenied, setAccessDenied] = useState(false);
|
||||
const previousActor = useRef<{ accountId: string; csrfToken: string } | null>(null);
|
||||
const requestInFlight = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
const next =
|
||||
actor && actorReady ? { accountId: actor.account.id, csrfToken: actor.csrf_token } : null;
|
||||
const previous = previousActor.current;
|
||||
if (previous && (!next || previous.accountId !== next.accountId)) {
|
||||
removeAssessmentQueriesForSessionChange(queryClient);
|
||||
setPendingResume(null);
|
||||
setPendingAnswer(null);
|
||||
setPendingFinalize(null);
|
||||
setWorkReady(false);
|
||||
setPageError(null);
|
||||
setAnswerError(null);
|
||||
setAccessDenied(false);
|
||||
} else if (previous && next && previous.csrfToken !== next.csrfToken) {
|
||||
removeAssessmentQueriesForSessionChange(queryClient);
|
||||
setWorkReady(false);
|
||||
setPageError("Проверка входа обновлена. Продолжите попытку еще раз.");
|
||||
}
|
||||
previousActor.current = next;
|
||||
}, [actor, actorReady, queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (attemptQuery.isError && isAccessLoss(attemptQuery.error)) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
queueMicrotask(() => {
|
||||
if (!actor || !isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
setAccessDenied(true);
|
||||
setWorkReady(false);
|
||||
});
|
||||
}
|
||||
if (resultQuery.isError && isAccessLoss(resultQuery.error)) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
queueMicrotask(() => {
|
||||
if (!actor || !isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
setAccessDenied(true);
|
||||
setWorkReady(false);
|
||||
});
|
||||
}
|
||||
}, [
|
||||
actor,
|
||||
attemptQuery.error,
|
||||
attemptQuery.isError,
|
||||
queryClient,
|
||||
resultQuery.error,
|
||||
resultQuery.isError,
|
||||
]);
|
||||
|
||||
async function refreshSessionForActor(currentActor: Session): Promise<boolean> {
|
||||
const key = getGetCurrentSessionQueryKey();
|
||||
const captured = queryClient.getQueryData<Session>(key);
|
||||
if (!assessmentSessionMatches(queryClient.getQueryState<Session>(key), currentActor))
|
||||
return false;
|
||||
const refreshed = await session.refetch();
|
||||
const latest = queryClient.getQueryData<Session>(key);
|
||||
const state = queryClient.getQueryState<Session>(key);
|
||||
if (
|
||||
!captured ||
|
||||
refreshed.isError ||
|
||||
!refreshed.data ||
|
||||
state?.status !== "success" ||
|
||||
latest?.account.id !== currentActor.account.id ||
|
||||
latest.csrf_token !== refreshed.data.csrf_token
|
||||
) {
|
||||
if (refreshed.isError || refreshed.data?.account.id !== currentActor.account.id) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
setAccessDenied(true);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (captured.csrf_token !== currentActor.csrf_token) return false;
|
||||
setAnswerError("Проверка входа обновлена. Черновик сохранен, повторите отправку.");
|
||||
return true;
|
||||
}
|
||||
|
||||
async function resumeWork() {
|
||||
if (
|
||||
!actor ||
|
||||
!attempt ||
|
||||
!isCurrentAssessmentSession(queryClient, actor) ||
|
||||
requestInFlight.current
|
||||
)
|
||||
return;
|
||||
const command = pendingResume ?? { key: newIdempotencyKey(), version: attempt.version };
|
||||
if (!pendingResume) setPendingResume(command);
|
||||
requestInFlight.current = true;
|
||||
setResumeBusy(true);
|
||||
setPageError(null);
|
||||
try {
|
||||
const resumedResponse = await startMyAssessmentAttemptSession(
|
||||
attempt.id,
|
||||
{ expected_version: command.version },
|
||||
{ "Idempotency-Key": command.key },
|
||||
{ headers: { "X-CSRF-Token": actor.csrf_token } },
|
||||
);
|
||||
const resumed = parseAssessmentAttemptResponse(resumedResponse);
|
||||
if (!isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
queryClient.setQueryData(assessmentQueryKeys.attempt(actor, attempt.id), resumed);
|
||||
setPendingResume(null);
|
||||
setWorkReady(true);
|
||||
} catch (error: unknown) {
|
||||
if (!isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
if (
|
||||
error instanceof ApiRequestError &&
|
||||
error.status === 403 &&
|
||||
error.code === "csrf_check_failed"
|
||||
) {
|
||||
await refreshSessionForActor(actor);
|
||||
} else if (isAccessLoss(error)) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
setAccessDenied(true);
|
||||
} else if (isOutcomeAmbiguous(error)) {
|
||||
setPageError("Не удалось подтвердить продолжение. Повторите запрос с тем же ключом.");
|
||||
} else {
|
||||
setPendingResume(null);
|
||||
setPageError("Не удалось продолжить попытку. Обновите состояние и повторите действие.");
|
||||
await attemptQuery.refetch();
|
||||
}
|
||||
} finally {
|
||||
requestInFlight.current = false;
|
||||
setResumeBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function refetchAttempt(): Promise<AssessmentAttempt | null> {
|
||||
const refreshed = await attemptQuery.refetch();
|
||||
if (!actor || !isCurrentAssessmentSession(queryClient, actor) || refreshed.isError) return null;
|
||||
return refreshed.data ?? null;
|
||||
}
|
||||
|
||||
async function sendAnswer(draft: AnswerDraft) {
|
||||
if (!actor || !attempt || !attempt.current_item || !workReady || requestInFlight.current)
|
||||
return;
|
||||
const built = buildAnswerSubmission(attempt, attempt.current_item, draft);
|
||||
if (!built.ok) {
|
||||
setAnswerError(built.message);
|
||||
return;
|
||||
}
|
||||
const command: PendingAnswerCommand = {
|
||||
key: newIdempotencyKey(),
|
||||
body: built.body,
|
||||
itemId: attempt.current_item.id,
|
||||
};
|
||||
await sendPendingAnswer(command, actor, attempt.id);
|
||||
}
|
||||
|
||||
async function retryAnswer() {
|
||||
if (!actor || !attempt || !pendingAnswer || requestInFlight.current) return;
|
||||
await sendPendingAnswer(pendingAnswer, actor, attempt.id);
|
||||
}
|
||||
|
||||
async function sendPendingAnswer(
|
||||
command: PendingAnswerCommand,
|
||||
currentActor: Session,
|
||||
currentAttemptId: string,
|
||||
) {
|
||||
if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
|
||||
setPendingAnswer(command);
|
||||
requestInFlight.current = true;
|
||||
setAnswerBusy(true);
|
||||
setAnswerError(null);
|
||||
setAnswerNeedsReview(false);
|
||||
try {
|
||||
const outcome = await submitPendingAnswerCommand(
|
||||
command,
|
||||
currentAttemptId,
|
||||
currentActor.csrf_token,
|
||||
);
|
||||
if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
|
||||
if (outcome.kind === "retry") {
|
||||
setPendingAnswer(outcome.command);
|
||||
setAnswerError(answerErrorMessage(outcome.error));
|
||||
return;
|
||||
}
|
||||
if (outcome.kind === "rejected") throw outcome.error;
|
||||
const saved = outcome.attempt;
|
||||
const key = assessmentQueryKeys.attempt(currentActor, currentAttemptId);
|
||||
queryClient.setQueryData<AssessmentAttempt>(key, (current) =>
|
||||
current && current.version > saved.version ? current : saved,
|
||||
);
|
||||
void queryClient.invalidateQueries({ queryKey: key });
|
||||
setPendingAnswer(null);
|
||||
setAnswerError(null);
|
||||
setAnswerNeedsReview(false);
|
||||
setWorkReady(true);
|
||||
} catch (error: unknown) {
|
||||
if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
|
||||
if (
|
||||
error instanceof ApiRequestError &&
|
||||
error.status === 403 &&
|
||||
error.code === "csrf_check_failed"
|
||||
) {
|
||||
await refreshSessionForActor(currentActor);
|
||||
return;
|
||||
}
|
||||
if (isAccessLoss(error)) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
setPendingAnswer(null);
|
||||
setAccessDenied(true);
|
||||
setWorkReady(false);
|
||||
return;
|
||||
}
|
||||
if (isOutcomeAmbiguous(error)) {
|
||||
setAnswerError(answerErrorMessage(error));
|
||||
return;
|
||||
}
|
||||
setPendingAnswer(null);
|
||||
setAnswerError(answerErrorMessage(error));
|
||||
if (error instanceof ApiRequestError && error.status === 412) {
|
||||
const latest = await refetchAttempt();
|
||||
setAnswerNeedsReview(Boolean(latest?.current_item?.id === command.itemId));
|
||||
if (latest?.current_item?.id !== command.itemId) {
|
||||
setAnswerError("Попытка изменилась в другом окне. Показано текущее задание с сервера.");
|
||||
}
|
||||
} else if (error instanceof ApiRequestError && error.status === 409) {
|
||||
const latest = await refetchAttempt();
|
||||
if (latest) {
|
||||
queryClient.setQueryData(
|
||||
assessmentQueryKeys.attempt(currentActor, currentAttemptId),
|
||||
latest,
|
||||
);
|
||||
}
|
||||
setWorkReady(false);
|
||||
setPageError(
|
||||
"Сеанс работы завершился или состояние попытки изменилось. Продолжите попытку заново.",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
requestInFlight.current = false;
|
||||
setAnswerBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function finalizeAttempt() {
|
||||
if (!actor || !attempt || !workReady || requestInFlight.current) return;
|
||||
const body: AssessmentFinalization = { expected_version: attempt.version };
|
||||
const command = pendingFinalize ?? { key: newIdempotencyKey(), body };
|
||||
if (!pendingFinalize) setPendingFinalize(command);
|
||||
requestInFlight.current = true;
|
||||
setFinalizeBusy(true);
|
||||
setPageError(null);
|
||||
try {
|
||||
const finalizedResponse = await finalizeMyAssessmentAttempt(
|
||||
attempt.id,
|
||||
command.body,
|
||||
{ "Idempotency-Key": command.key },
|
||||
{ headers: { "X-CSRF-Token": actor.csrf_token } },
|
||||
);
|
||||
const finalized = parseAssessmentAttemptResponse(finalizedResponse);
|
||||
if (!isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
queryClient.setQueryData(assessmentQueryKeys.attempt(actor, attempt.id), finalized);
|
||||
setPendingFinalize(null);
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: assessmentQueryKeys.result(actor, attempt.id),
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
if (!isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
if (
|
||||
error instanceof ApiRequestError &&
|
||||
error.status === 403 &&
|
||||
error.code === "csrf_check_failed"
|
||||
) {
|
||||
await refreshSessionForActor(actor);
|
||||
} else if (isAccessLoss(error)) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
setAccessDenied(true);
|
||||
setWorkReady(false);
|
||||
} else if (isOutcomeAmbiguous(error)) {
|
||||
setPageError("Сервер не подтвердил завершение. Повторите запрос с тем же ключом.");
|
||||
} else {
|
||||
setPendingFinalize(null);
|
||||
setPageError("Сервер пока не завершил попытку. Обновите состояние и повторите действие.");
|
||||
const latest = await refetchAttempt();
|
||||
if (latest)
|
||||
queryClient.setQueryData(assessmentQueryKeys.attempt(actor, attempt.id), latest);
|
||||
}
|
||||
} finally {
|
||||
requestInFlight.current = false;
|
||||
setFinalizeBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<ForbiddenState
|
||||
error={session.error}
|
||||
title="Попытка недоступна"
|
||||
description="Сервер не подтвердил доступ к этой попытке. Проверьте вход в кабинет кандидата."
|
||||
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (session.isPending || !actor) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<LoadingState label="Проверяем вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!actorReady) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<LoadingState label="Подтверждаем текущий вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!attemptId) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<ErrorState
|
||||
error={new Error("The attempt identifier is missing.")}
|
||||
title="Не удалось открыть попытку"
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (attemptQuery.isPending && !attempt) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<LoadingState label="Загружаем сохраненную попытку..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (attemptQuery.isError || !attempt) {
|
||||
if (isAccessLoss(attemptQuery.error)) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<ForbiddenState
|
||||
error={attemptQuery.error}
|
||||
title="Попытка недоступна"
|
||||
description="Сервер не подтвердил доступ к этой попытке."
|
||||
action={<ButtonLink to={paths.candidate.assessment}>К списку проверок</ButtonLink>}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<ErrorState
|
||||
error={attemptQuery.error}
|
||||
isRetrying={attemptQuery.isRefetching}
|
||||
onRetry={() => void attemptQuery.refetch()}
|
||||
title="Не удалось загрузить попытку"
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
const currentItem = attempt.current_item;
|
||||
const practicePending = attempt.practices.some((practice) => practice.status === "pending");
|
||||
const pendingAnswerNeedsReplay = Boolean(
|
||||
pendingAnswer && pendingAnswer.itemId !== currentItem?.id,
|
||||
);
|
||||
const canFinalize =
|
||||
attempt.state === "ready_to_finalize" ||
|
||||
(attempt.state === "additional_practice_pending" &&
|
||||
!currentItem &&
|
||||
attempt.practices.some(
|
||||
(practice) =>
|
||||
practice.kind === "additional" && ["not_started", "failed"].includes(practice.status),
|
||||
));
|
||||
const terminal = isTerminal(attempt);
|
||||
|
||||
return (
|
||||
<Page
|
||||
title={attempt.kind === "demo_express" ? "Демонстрационная проверка" : "Полная проверка"}
|
||||
eyebrow="Кабинет кандидата"
|
||||
lead={
|
||||
attempt.kind === "demo_express"
|
||||
? "Учебный режим на 3-5 минут. Он не подтверждает квалификацию и не присваивает грейд."
|
||||
: undefined
|
||||
}
|
||||
width="wide"
|
||||
>
|
||||
<div className={attemptStyles.layout}>
|
||||
<Section
|
||||
title={attemptName(attempt)}
|
||||
description={`${methodLabel(attempt.mode)}. Сервер хранит состояние и результат попытки.`}
|
||||
>
|
||||
<div className={attemptStyles.meta}>
|
||||
<span>
|
||||
Заданий: {attempt.progress.answered_items} из {attempt.progress.max_items}
|
||||
</span>
|
||||
<span>
|
||||
Срок до:{" "}
|
||||
{new Intl.DateTimeFormat("ru-RU", { dateStyle: "medium", timeStyle: "short" }).format(
|
||||
new Date(attempt.expires_at),
|
||||
)}
|
||||
</span>
|
||||
{attempt.sessions ? (
|
||||
<span>
|
||||
Сеанс {attempt.sessions.used} из {attempt.sessions.max}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{pageError ? (
|
||||
<p className={attemptStyles.error} role="alert">
|
||||
{pageError}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{!workReady && !terminal ? (
|
||||
<div className={attemptStyles.resume}>
|
||||
<p>
|
||||
Продолжение сверит актуальную версию с сервером. При перезагрузке задания не
|
||||
меняются, а ответ не отправляется повторно автоматически.
|
||||
</p>
|
||||
<Button isBusy={resumeBusy} onClick={() => void resumeWork()}>
|
||||
{resumeBusy
|
||||
? "Проверяем попытку..."
|
||||
: pendingResume
|
||||
? "Повторить продолжение"
|
||||
: "Начать или продолжить"}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{workReady && pendingAnswerNeedsReplay && !terminal ? (
|
||||
<div className={attemptStyles.info} role="status">
|
||||
<p>Предыдущий ответ еще не подтвержден. Сначала повторите отправку того же ответа.</p>
|
||||
<Button isBusy={answerBusy} onClick={() => void retryAnswer()}>
|
||||
{answerBusy ? "Повторяем отправку..." : "Повторить отправку того же ответа"}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{workReady &&
|
||||
currentItem &&
|
||||
!terminal &&
|
||||
(!pendingAnswer || pendingAnswer.itemId === currentItem.id) ? (
|
||||
<article className={attemptStyles.item} aria-labelledby="assessment-item-title">
|
||||
<div className={attemptStyles["item-heading"]}>
|
||||
<h2 id="assessment-item-title">Задание {currentItem.sequence}</h2>
|
||||
<span>
|
||||
{currentItem.sequence} из {attempt.progress.max_items}
|
||||
</span>
|
||||
</div>
|
||||
<p className={attemptStyles.prompt}>{currentItem.prompt}</p>
|
||||
<AnswerForm
|
||||
key={currentItem.id}
|
||||
item={currentItem}
|
||||
isSaving={answerBusy}
|
||||
retryable={Boolean(pendingAnswer && pendingAnswer.itemId === currentItem.id)}
|
||||
errorMessage={answerError}
|
||||
onSubmit={(draft) => void sendAnswer(draft)}
|
||||
onRetry={() => void retryAnswer()}
|
||||
/>
|
||||
{answerNeedsReview ? (
|
||||
<p className={attemptStyles.info} role="status">
|
||||
Черновик остался в форме. Проверьте его и отправьте для актуальной версии попытки.
|
||||
</p>
|
||||
) : null}
|
||||
</article>
|
||||
) : null}
|
||||
|
||||
{workReady && practicePending && !currentItem && !pendingAnswerNeedsReplay ? (
|
||||
<p className={attemptStyles.info} role="status">
|
||||
Решение передано на проверку. Результат появится после ответа сервера; страница
|
||||
обновляет статус автоматически.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{workReady &&
|
||||
!currentItem &&
|
||||
!practicePending &&
|
||||
canFinalize &&
|
||||
!terminal &&
|
||||
!pendingAnswerNeedsReplay ? (
|
||||
<div className={attemptStyles.finalize}>
|
||||
<p>
|
||||
Обязательные задания завершены. Решение по уровню примет сервер после подтверждения.
|
||||
</p>
|
||||
<Button isBusy={finalizeBusy} onClick={() => void finalizeAttempt()}>
|
||||
{finalizeBusy
|
||||
? "Запрашиваем решение..."
|
||||
: pendingFinalize
|
||||
? "Повторить завершение"
|
||||
: "Завершить проверку"}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{workReady &&
|
||||
!currentItem &&
|
||||
!practicePending &&
|
||||
!canFinalize &&
|
||||
!terminal &&
|
||||
!pendingAnswerNeedsReplay ? (
|
||||
<div className={attemptStyles.info} role="status">
|
||||
<p>Сервер не вернул следующее задание. Обновите состояние попытки.</p>
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={attemptQuery.isRefetching}
|
||||
onClick={() => void attemptQuery.refetch()}
|
||||
>
|
||||
Обновить попытку
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{terminal ? <ResultView resultQuery={resultQuery} /> : null}
|
||||
</Section>
|
||||
<div className={attemptStyles["back-link"]}>
|
||||
<ButtonLink variant="secondary" to={paths.candidate.assessment}>
|
||||
К доступным проверкам
|
||||
</ButtonLink>
|
||||
</div>
|
||||
</div>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
function ResultView({ resultQuery }: { resultQuery: ReturnType<typeof useAssessmentResult> }) {
|
||||
if (resultQuery.isPending && !resultQuery.data) {
|
||||
return <LoadingState label="Загружаем сохраненный результат..." />;
|
||||
}
|
||||
if (resultQuery.isError || !resultQuery.data) {
|
||||
return (
|
||||
<div className={attemptStyles["result-error"]}>
|
||||
{resultQuery.error instanceof ApiRequestError && resultQuery.error.status === 409 ? (
|
||||
<p role="status">Сервер еще завершает обработку результата. Повторите проверку позже.</p>
|
||||
) : (
|
||||
<ErrorState
|
||||
error={resultQuery.error}
|
||||
isRetrying={resultQuery.isRefetching}
|
||||
onRetry={() => void resultQuery.refetch()}
|
||||
title="Не удалось загрузить результат"
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={resultQuery.isRefetching}
|
||||
onClick={() => void resultQuery.refetch()}
|
||||
>
|
||||
Обновить результат
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const result = resultQuery.data;
|
||||
const summary = assessmentResultSummary(result);
|
||||
return (
|
||||
<div className={attemptStyles.result} role="status" aria-live="polite">
|
||||
<h2>Результат с сервера</h2>
|
||||
<p>{summary.text}</p>
|
||||
{summary.reason ? <p>{summary.reason}</p> : null}
|
||||
{summary.isDemonstration ? (
|
||||
<p className={attemptStyles["demo-label"]}>
|
||||
Только демонстрация. Подтвержденный грейд не присваивается.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import type {
|
||||
AssessmentAttemptCreate,
|
||||
GradeCode,
|
||||
SpecializationCode,
|
||||
TaskLanguage,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { createMyAssessmentAttempt } from "../../../shared/api/endpoints/assessment/assessment";
|
||||
import { parseAssessmentAttemptResponse } from "../../../entities/assessment";
|
||||
|
||||
export type PendingCreate = { key: string; body: AssessmentAttemptCreate };
|
||||
|
||||
export function buildRootAttemptCreate(
|
||||
specialization: SpecializationCode,
|
||||
grade: GradeCode,
|
||||
savedLanguages: readonly TaskLanguage[],
|
||||
selectedLanguage: TaskLanguage | "",
|
||||
): AssessmentAttemptCreate | null {
|
||||
let taskLanguage: TaskLanguage | null = null;
|
||||
|
||||
if (savedLanguages.length === 1) {
|
||||
taskLanguage = savedLanguages[0] ?? null;
|
||||
} else if (savedLanguages.length > 1) {
|
||||
if (!selectedLanguage || !savedLanguages.includes(selectedLanguage)) return null;
|
||||
taskLanguage = selectedLanguage;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "root",
|
||||
specialization,
|
||||
target_grade: grade,
|
||||
task_language: taskLanguage,
|
||||
};
|
||||
}
|
||||
|
||||
export function preservePendingCreate(
|
||||
pending: PendingCreate | null,
|
||||
body: AssessmentAttemptCreate | null,
|
||||
keyFactory: () => string,
|
||||
): PendingCreate | null {
|
||||
return pending ?? (body ? { key: keyFactory(), body } : null);
|
||||
}
|
||||
|
||||
export function submitPendingAttempt(command: PendingCreate, csrfToken: string) {
|
||||
return createMyAssessmentAttempt(
|
||||
command.body,
|
||||
{ "Idempotency-Key": command.key },
|
||||
{ headers: { "X-CSRF-Token": csrfToken } },
|
||||
).then((response) => parseAssessmentAttemptResponse(response, 201));
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
.layout {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.field select {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
color: var(--color-text);
|
||||
background: var(--color-surface);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.field select:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.language-note,
|
||||
.language-availability {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.language-note {
|
||||
padding: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-divider);
|
||||
}
|
||||
|
||||
.language-availability {
|
||||
max-width: 72ch;
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.availability,
|
||||
.express,
|
||||
.notice {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
}
|
||||
|
||||
.availability p,
|
||||
.express p,
|
||||
.notice p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.status-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.status-row [data-state="available"] {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.limits {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: var(--space-3);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.limits div {
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
background: var(--color-canvas);
|
||||
border-radius: var(--radius-s);
|
||||
}
|
||||
|
||||
.limits dt {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.limits dd {
|
||||
margin: var(--space-1) 0 0;
|
||||
font-weight: var(--font-weight-bold);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.notice {
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.notice h3 {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-m);
|
||||
}
|
||||
|
||||
.notice p,
|
||||
.express p,
|
||||
.pending {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.pending {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
@media (width < 42rem) {
|
||||
.controls,
|
||||
.limits {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.availability,
|
||||
.express,
|
||||
.notice {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { setupServer } from "msw/node";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { AssessmentPolicyParameters, TaskLanguageControl } from "./assessment-page";
|
||||
import {
|
||||
buildRootAttemptCreate,
|
||||
preservePendingCreate,
|
||||
submitPendingAttempt,
|
||||
} from "./assessment-page.model";
|
||||
|
||||
const server = setupServer();
|
||||
|
||||
beforeAll(() => server.listen());
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
server.resetHandlers();
|
||||
});
|
||||
afterAll(() => server.close());
|
||||
|
||||
describe("assessment task language selection", () => {
|
||||
it("sends null when the saved questionnaire has no language", () => {
|
||||
expect(buildRootAttemptCreate("backend", "junior", [], "")).toEqual({
|
||||
kind: "root",
|
||||
specialization: "backend",
|
||||
target_grade: "junior",
|
||||
task_language: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the only saved language without an ambiguous default", () => {
|
||||
expect(buildRootAttemptCreate("backend", "junior", ["python"], "")).toEqual({
|
||||
kind: "root",
|
||||
specialization: "backend",
|
||||
target_grade: "junior",
|
||||
task_language: "python",
|
||||
});
|
||||
});
|
||||
|
||||
it("requires an explicit choice when the questionnaire has multiple languages", () => {
|
||||
expect(buildRootAttemptCreate("backend", "junior", ["python", "go"], "")).toBeNull();
|
||||
expect(buildRootAttemptCreate("backend", "junior", ["python", "go"], "go")).toEqual({
|
||||
kind: "root",
|
||||
specialization: "backend",
|
||||
target_grade: "junior",
|
||||
task_language: "go",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the selected second language and idempotency key on an exact retry", () => {
|
||||
const body = buildRootAttemptCreate("backend", "junior", ["python", "go"], "go");
|
||||
expect(body).not.toBeNull();
|
||||
const keyFactory = vi.fn(() => "original-key");
|
||||
const pending = preservePendingCreate(null, body, keyFactory);
|
||||
const retryBody = buildRootAttemptCreate("backend", "junior", ["python", "go"], "python");
|
||||
const retried = preservePendingCreate(pending, retryBody, () => "new-key");
|
||||
|
||||
expect(pending?.body).toMatchObject({ kind: "root", task_language: "go" });
|
||||
expect(retried).toBe(pending);
|
||||
expect(retried?.key).toBe("original-key");
|
||||
expect(retried?.body).toEqual(body);
|
||||
expect(keyFactory).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("posts the selected second language and replays the same request after an ambiguous response", async () => {
|
||||
const interceptedFetch = globalThis.fetch;
|
||||
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
|
||||
interceptedFetch(new URL(input, "http://localhost"), init),
|
||||
);
|
||||
const requests: Array<{ body: unknown; key: string | null; csrf: string | null }> = [];
|
||||
server.use(
|
||||
http.post("http://localhost/api/v1/me/assessment-attempts", async ({ request }) => {
|
||||
requests.push({
|
||||
body: await request.json(),
|
||||
key: request.headers.get("Idempotency-Key"),
|
||||
csrf: request.headers.get("X-CSRF-Token"),
|
||||
});
|
||||
return HttpResponse.json(
|
||||
{
|
||||
type: "urn:lincodex:problem:internal",
|
||||
title: "Internal error",
|
||||
status: 500,
|
||||
code: "internal",
|
||||
},
|
||||
{ status: 500, headers: { "Content-Type": "application/problem+json" } },
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const keyFactory = vi.fn(() => "retry-key");
|
||||
const firstBody = buildRootAttemptCreate("backend", "junior", ["python", "go"], "go");
|
||||
const pending = preservePendingCreate(null, firstBody, keyFactory);
|
||||
expect(pending).not.toBeNull();
|
||||
await expect(submitPendingAttempt(pending!, "csrf-token")).rejects.toMatchObject({
|
||||
status: 500,
|
||||
});
|
||||
|
||||
const changedSelection = buildRootAttemptCreate(
|
||||
"backend",
|
||||
"junior",
|
||||
["python", "go"],
|
||||
"python",
|
||||
);
|
||||
const retry = preservePendingCreate(pending, changedSelection, keyFactory);
|
||||
await expect(submitPendingAttempt(retry!, "csrf-token")).rejects.toMatchObject({
|
||||
status: 500,
|
||||
});
|
||||
|
||||
expect(requests).toEqual([
|
||||
{
|
||||
body: {
|
||||
kind: "root",
|
||||
specialization: "backend",
|
||||
target_grade: "junior",
|
||||
task_language: "go",
|
||||
},
|
||||
key: "retry-key",
|
||||
csrf: "csrf-token",
|
||||
},
|
||||
{
|
||||
body: {
|
||||
kind: "root",
|
||||
specialization: "backend",
|
||||
target_grade: "junior",
|
||||
task_language: "go",
|
||||
},
|
||||
key: "retry-key",
|
||||
csrf: "csrf-token",
|
||||
},
|
||||
]);
|
||||
expect(retry).toBe(pending);
|
||||
expect(keyFactory).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe("TaskLanguageControl", () => {
|
||||
it("shows the single saved language without requiring another choice", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<TaskLanguageControl languages={["go"]} value="" disabled={false} onChange={() => {}} />,
|
||||
);
|
||||
|
||||
expect(html).toContain("Язык задания из анкеты:");
|
||||
expect(html).toContain("Go");
|
||||
expect(html).not.toContain("<select");
|
||||
});
|
||||
|
||||
it("requires a visible choice when both languages are saved", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<TaskLanguageControl
|
||||
languages={["python", "go"]}
|
||||
value="go"
|
||||
disabled={false}
|
||||
onChange={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Язык задания");
|
||||
expect(html).toContain('value="python"');
|
||||
expect(html).toContain('value="go" selected');
|
||||
});
|
||||
});
|
||||
|
||||
describe("AssessmentPolicyParameters", () => {
|
||||
const grade = {
|
||||
grade: "junior",
|
||||
status: "active_attempt",
|
||||
mode: "adaptive",
|
||||
available_at: null,
|
||||
time_limit_seconds: 900,
|
||||
max_sessions: 1,
|
||||
max_items: 12,
|
||||
practice_required: true,
|
||||
} as const;
|
||||
|
||||
it("does not present today's policy limits as settings for a pinned attempt", () => {
|
||||
const html = renderToStaticMarkup(<AssessmentPolicyParameters grade={grade} />);
|
||||
|
||||
expect(html).toBe("");
|
||||
});
|
||||
|
||||
it("shows current policy parameters before a new attempt", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<AssessmentPolicyParameters grade={{ ...grade, status: "available" }} />,
|
||||
);
|
||||
|
||||
expect(html).toContain("Метод:");
|
||||
expect(html).toContain("Лимит времени");
|
||||
expect(html).toContain("Заданий");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,568 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import {
|
||||
getGetCurrentSessionQueryKey,
|
||||
useGetCurrentSession,
|
||||
} from "../../../shared/api/endpoints/identity/identity";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import type {
|
||||
AssessmentAttemptCreate,
|
||||
AssessmentGradeAvailability,
|
||||
GradeCode,
|
||||
Session,
|
||||
SpecializationCode,
|
||||
TaskLanguage,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config/paths";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Page,
|
||||
Section,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
assessmentSessionMatches,
|
||||
gradeLabels,
|
||||
isOutcomeAmbiguous,
|
||||
isCurrentAssessmentSession,
|
||||
methodLabel,
|
||||
removeAssessmentQueries,
|
||||
removeAssessmentQueriesForSessionChange,
|
||||
selectedSpecialization,
|
||||
specializationLabels,
|
||||
useAssessmentAvailability,
|
||||
useAssessmentQuestionnaire,
|
||||
} from "../../../entities/assessment";
|
||||
import { newIdempotencyKey } from "../../../features/answer-assessment";
|
||||
import {
|
||||
buildRootAttemptCreate,
|
||||
preservePendingCreate,
|
||||
submitPendingAttempt,
|
||||
type PendingCreate,
|
||||
} from "./assessment-page.model";
|
||||
import styles from "./assessment-page.module.css";
|
||||
|
||||
function isAccessLoss(error: unknown): error is ApiRequestError {
|
||||
return error instanceof ApiRequestError && [401, 403, 404].includes(error.status);
|
||||
}
|
||||
|
||||
function requiresC3(error: ApiRequestError): boolean {
|
||||
return (
|
||||
error.code === "state_conflict" &&
|
||||
error.fieldErrors.some((field) => field.code === "consent_required")
|
||||
);
|
||||
}
|
||||
|
||||
function gradeStatusDescription(grade: AssessmentGradeAvailability): string {
|
||||
switch (grade.status) {
|
||||
case "available":
|
||||
return "Уровень открыт для начала. Список доступности не разделяет варианты по языку; сервер проверит задания выбранного языка при создании попытки.";
|
||||
case "active_attempt":
|
||||
return "Продолжите сохраненную попытку по ссылке ниже. Ее язык и параметры закреплены и отображаются внутри попытки.";
|
||||
case "cooldown":
|
||||
return grade.available_at
|
||||
? `Следующая попытка будет доступна ${formatDate(grade.available_at)}.`
|
||||
: "Следующая попытка пока недоступна.";
|
||||
case "insufficient_bank":
|
||||
return "Набор заданий пока не подготовлен. Система не будет повторять уже пройденные задания.";
|
||||
}
|
||||
}
|
||||
|
||||
function formatDate(value: string): string {
|
||||
return new Intl.DateTimeFormat("ru-RU", {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
function formatTimeLimit(seconds: number | null): string {
|
||||
if (seconds === null) return "не задано";
|
||||
const minutes = Math.ceil(seconds / 60);
|
||||
return `${minutes} мин.`;
|
||||
}
|
||||
|
||||
function taskLanguageLabel(language: TaskLanguage): string {
|
||||
return language === "go" ? "Go" : "Python";
|
||||
}
|
||||
|
||||
export function TaskLanguageControl({
|
||||
languages,
|
||||
value,
|
||||
disabled,
|
||||
onChange,
|
||||
}: {
|
||||
languages: readonly TaskLanguage[];
|
||||
value: TaskLanguage | "";
|
||||
disabled: boolean;
|
||||
onChange: (language: TaskLanguage | "") => void;
|
||||
}) {
|
||||
if (languages.length === 0) {
|
||||
return (
|
||||
<p className={styles["language-note"]}>
|
||||
В сохраненной анкете нет выбранного языка. Попытка отправится без языка, а сервер проверит
|
||||
доступность заданий при создании.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
if (languages.length === 1) {
|
||||
return (
|
||||
<p className={styles["language-note"]}>
|
||||
Язык задания из анкеты: <strong>{taskLanguageLabel(languages[0]!)}</strong>.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<label className={styles.field}>
|
||||
<span>Язык задания</span>
|
||||
<select
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
onChange={(event) => onChange(event.currentTarget.value as TaskLanguage | "")}
|
||||
>
|
||||
<option value="">Выберите язык</option>
|
||||
{languages.map((language) => (
|
||||
<option key={language} value={language}>
|
||||
{taskLanguageLabel(language)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
export function AssessmentPolicyParameters({ grade }: { grade: AssessmentGradeAvailability }) {
|
||||
if (grade.status === "active_attempt") return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{grade.mode ? <p>Метод: {methodLabel(grade.mode)}.</p> : null}
|
||||
<dl className={styles.limits}>
|
||||
<div>
|
||||
<dt>Лимит времени</dt>
|
||||
<dd>{formatTimeLimit(grade.time_limit_seconds)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Попыток работы</dt>
|
||||
<dd>{grade.max_sessions ?? "не задано"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Заданий</dt>
|
||||
<dd>{grade.max_items ?? "не задано"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Практика кода</dt>
|
||||
<dd>
|
||||
{grade.practice_required === null
|
||||
? "не задано"
|
||||
: grade.practice_required
|
||||
? "включена"
|
||||
: "не требуется"}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function AssessmentSignalsNotice() {
|
||||
return (
|
||||
<aside className={styles.notice} aria-labelledby="assessment-signals-title">
|
||||
<h3 id="assessment-signals-title">Какие данные фиксируются во время проверки</h3>
|
||||
<p>
|
||||
Сохраняются время ответов и технические события: смена вкладки, выход из полноэкранного
|
||||
режима и размер операций копирования или вставки. Содержимое ответов и буфера не
|
||||
отправляется как сигнал. Камера, микрофон и запись экрана не используются.
|
||||
</p>
|
||||
<p>Сигналы помогают назначить ручную перепроверку и сами по себе не меняют результат.</p>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
export function AssessmentPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const session = useGetCurrentSession({ query: { retry: false } });
|
||||
const actor = session.data;
|
||||
const actorReady = Boolean(
|
||||
actor &&
|
||||
actor.account.scenario === "candidate" &&
|
||||
isCurrentAssessmentSession(queryClient, actor),
|
||||
);
|
||||
const availability = useAssessmentAvailability({ actor, enabled: actorReady, queryClient });
|
||||
const questionnaire = useAssessmentQuestionnaire({ actor, enabled: actorReady, queryClient });
|
||||
const [selection, setSelection] = useState<{
|
||||
specialization: SpecializationCode | "";
|
||||
grade: GradeCode | "";
|
||||
}>({ specialization: "", grade: "" });
|
||||
const [selectedTaskLanguage, setSelectedTaskLanguage] = useState<TaskLanguage | "">("");
|
||||
const [pendingCreate, setPendingCreate] = useState<PendingCreate | null>(null);
|
||||
const [createBusy, setCreateBusy] = useState(false);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [c3Required, setC3Required] = useState(false);
|
||||
const [accessDenied, setAccessDenied] = useState(false);
|
||||
const previousActor = useRef<{ accountId: string; csrfToken: string } | null>(null);
|
||||
const requestInFlight = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
const next =
|
||||
actor && actorReady ? { accountId: actor.account.id, csrfToken: actor.csrf_token } : null;
|
||||
const previous = previousActor.current;
|
||||
if (previous && (!next || previous.accountId !== next.accountId)) {
|
||||
removeAssessmentQueriesForSessionChange(queryClient);
|
||||
setPendingCreate(null);
|
||||
setSelectedTaskLanguage("");
|
||||
setFormError(null);
|
||||
setC3Required(false);
|
||||
setAccessDenied(false);
|
||||
} else if (previous && next && previous.csrfToken !== next.csrfToken) {
|
||||
removeAssessmentQueriesForSessionChange(queryClient);
|
||||
setFormError("Проверка входа обновлена. Повторите отправку теми же данными.");
|
||||
}
|
||||
previousActor.current = next;
|
||||
}, [actor, actorReady, queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
(availability.isError && isAccessLoss(availability.error)) ||
|
||||
(questionnaire.isError && isAccessLoss(questionnaire.error))
|
||||
) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
queueMicrotask(() => {
|
||||
if (isCurrentAssessmentSession(queryClient, actor)) setAccessDenied(true);
|
||||
});
|
||||
}
|
||||
}, [
|
||||
actor,
|
||||
availability.error,
|
||||
availability.isError,
|
||||
queryClient,
|
||||
questionnaire.error,
|
||||
questionnaire.isError,
|
||||
]);
|
||||
|
||||
const data = availability.data;
|
||||
const firstSpecialization = data?.specializations[0]?.specialization ?? "";
|
||||
const selectedCode = data?.specializations.some(
|
||||
(item) => item.specialization === selection.specialization,
|
||||
)
|
||||
? selection.specialization
|
||||
: firstSpecialization;
|
||||
const specialization = data ? selectedSpecialization(data, selectedCode || undefined) : undefined;
|
||||
const questionnaireSpecialization = questionnaire.data?.specializations.find(
|
||||
(item) => item.specialization === selectedCode,
|
||||
);
|
||||
const selfGrade = questionnaireSpecialization?.self_assessed_grade ?? "";
|
||||
const firstAvailableGrade =
|
||||
specialization?.grades.find((grade) => grade.status === "available")?.grade ?? "";
|
||||
const selectedGradeCode = specialization?.grades.some((grade) => grade.grade === selection.grade)
|
||||
? selection.grade
|
||||
: selfGrade || firstAvailableGrade || specialization?.grades[0]?.grade || "";
|
||||
const grade = specialization?.grades.find((item) => item.grade === selectedGradeCode);
|
||||
const activeAttemptId = specialization?.active_attempt_id;
|
||||
const savedTaskLanguages = questionnaireSpecialization?.task_languages ?? [];
|
||||
const selectedLanguageIsValid = savedTaskLanguages.includes(selectedTaskLanguage as TaskLanguage);
|
||||
const taskLanguageReady = savedTaskLanguages.length < 2 || selectedLanguageIsValid;
|
||||
|
||||
async function refreshSessionForActor(currentActor: Session): Promise<boolean> {
|
||||
const captured = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
|
||||
if (
|
||||
!assessmentSessionMatches(
|
||||
queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey()),
|
||||
currentActor,
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const refreshed = await session.refetch();
|
||||
const latest = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
|
||||
const queryState = queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey());
|
||||
if (
|
||||
!captured ||
|
||||
refreshed.isError ||
|
||||
!refreshed.data ||
|
||||
!latest ||
|
||||
latest.account.id !== currentActor.account.id ||
|
||||
latest.csrf_token !== refreshed.data.csrf_token ||
|
||||
queryState?.status !== "success"
|
||||
) {
|
||||
if (refreshed.isError || refreshed.data?.account.id !== currentActor.account.id) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
setAccessDenied(true);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (captured.csrf_token !== currentActor.csrf_token) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
async function startAttempt(body?: AssessmentAttemptCreate) {
|
||||
if (!actor || !isCurrentAssessmentSession(queryClient, actor) || requestInFlight.current)
|
||||
return;
|
||||
const command = preservePendingCreate(pendingCreate, body ?? null, newIdempotencyKey);
|
||||
if (!command) return;
|
||||
if (!pendingCreate) setPendingCreate(command);
|
||||
requestInFlight.current = true;
|
||||
setCreateBusy(true);
|
||||
setFormError(null);
|
||||
setC3Required(false);
|
||||
try {
|
||||
const created = await submitPendingAttempt(command, actor.csrf_token);
|
||||
if (!isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
setPendingCreate(null);
|
||||
navigate(paths.candidate.assessmentAttempt(created.id));
|
||||
} catch (error: unknown) {
|
||||
if (!isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
if (
|
||||
error instanceof ApiRequestError &&
|
||||
error.status === 403 &&
|
||||
error.code === "csrf_check_failed"
|
||||
) {
|
||||
const refreshed = await refreshSessionForActor(actor);
|
||||
if (refreshed) {
|
||||
setFormError("Проверка входа обновлена. Повторите отправку теми же данными.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (error instanceof ApiRequestError && [401, 403, 404].includes(error.status)) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
setAccessDenied(true);
|
||||
return;
|
||||
}
|
||||
if (error instanceof ApiRequestError && error.status === 409) {
|
||||
setPendingCreate(null);
|
||||
if (requiresC3(error)) {
|
||||
setC3Required(true);
|
||||
setFormError("Для полной проверки нужно активное согласие C3.");
|
||||
return;
|
||||
}
|
||||
setFormError("Доступность изменилась. Обновите состояние перед началом новой попытки.");
|
||||
await availability.refetch();
|
||||
return;
|
||||
}
|
||||
if (isOutcomeAmbiguous(error)) {
|
||||
setFormError(
|
||||
"Не удалось подтвердить создание попытки. Повторная отправка использует тот же ключ.",
|
||||
);
|
||||
} else {
|
||||
setPendingCreate(null);
|
||||
setFormError(
|
||||
"Сервер отклонил создание попытки. Проверьте доступность и повторите действие.",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
requestInFlight.current = false;
|
||||
setCreateBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const handleStartReal = () => {
|
||||
if (!specialization || !grade || !questionnaireSpecialization) return;
|
||||
const body = buildRootAttemptCreate(
|
||||
specialization.specialization,
|
||||
grade.grade,
|
||||
questionnaireSpecialization.task_languages,
|
||||
selectedTaskLanguage,
|
||||
);
|
||||
if (!body) {
|
||||
setFormError("Выберите язык задания перед началом проверки.");
|
||||
return;
|
||||
}
|
||||
void startAttempt(body);
|
||||
};
|
||||
|
||||
const handleStartExpress = () => {
|
||||
void startAttempt({ kind: "demo_express" });
|
||||
};
|
||||
|
||||
if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) {
|
||||
return (
|
||||
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
|
||||
<ForbiddenState
|
||||
error={session.error}
|
||||
title="Проверка недоступна"
|
||||
description="Войдите в кабинет кандидата и повторите проверку доступа."
|
||||
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (session.isPending || !actor) {
|
||||
return (
|
||||
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
|
||||
<LoadingState label="Проверяем вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!actorReady) {
|
||||
return (
|
||||
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
|
||||
<LoadingState label="Подтверждаем текущий вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Page
|
||||
title="Проверка знаний"
|
||||
eyebrow="Кабинет кандидата"
|
||||
lead="Выберите доступную проверку. Уровень из анкеты - это ваша самооценка; результат определяет только сервер после прохождения."
|
||||
width="wide"
|
||||
>
|
||||
<div className={styles.layout}>
|
||||
<Section
|
||||
title="Доступность проверки"
|
||||
description="Состояние и ограничения загружаются с сервера."
|
||||
>
|
||||
{(availability.isPending && !availability.data) ||
|
||||
(questionnaire.isPending && !questionnaire.data) ? (
|
||||
<LoadingState label="Загружаем доступность и сохраненные ответы..." />
|
||||
) : !data || !questionnaire.data ? (
|
||||
<ErrorState
|
||||
error={!data ? availability.error : questionnaire.error}
|
||||
isRetrying={!data ? availability.isRefetching : questionnaire.isRefetching}
|
||||
onRetry={() => void (!data ? availability.refetch() : questionnaire.refetch())}
|
||||
title="Не удалось загрузить состояние проверки"
|
||||
/>
|
||||
) : data.specializations.length === 0 ? (
|
||||
<EmptyState
|
||||
title="Сначала выберите специализацию"
|
||||
description="Сохраните специализацию в анкете кандидата, чтобы увидеть доступные проверки."
|
||||
action={<ButtonLink to={paths.candidate.questionnaire}>Открыть анкету</ButtonLink>}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div className={styles.controls}>
|
||||
<label className={styles.field}>
|
||||
<span>Специализация</span>
|
||||
<select
|
||||
value={selectedCode}
|
||||
disabled={Boolean(pendingCreate)}
|
||||
onChange={(event) => {
|
||||
setSelection({
|
||||
specialization: event.currentTarget.value as SpecializationCode,
|
||||
grade: "",
|
||||
});
|
||||
setSelectedTaskLanguage("");
|
||||
}}
|
||||
>
|
||||
{data.specializations.map((item) => (
|
||||
<option key={item.specialization} value={item.specialization}>
|
||||
{specializationLabels[item.specialization]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className={styles.field}>
|
||||
<span>Целевой уровень</span>
|
||||
<select
|
||||
value={selectedGradeCode}
|
||||
disabled={Boolean(pendingCreate)}
|
||||
onChange={(event) =>
|
||||
setSelection({
|
||||
specialization: selectedCode,
|
||||
grade: event.currentTarget.value as GradeCode,
|
||||
})
|
||||
}
|
||||
>
|
||||
{specialization?.grades.map((item) => (
|
||||
<option key={item.grade} value={item.grade}>
|
||||
{gradeLabels[item.grade]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
{questionnaireSpecialization && grade?.status !== "active_attempt" ? (
|
||||
<TaskLanguageControl
|
||||
languages={savedTaskLanguages}
|
||||
value={selectedLanguageIsValid ? selectedTaskLanguage : ""}
|
||||
disabled={Boolean(pendingCreate) || createBusy}
|
||||
onChange={setSelectedTaskLanguage}
|
||||
/>
|
||||
) : null}
|
||||
{grade?.status !== "active_attempt" ? (
|
||||
<p className={styles["language-availability"]}>
|
||||
Доступность уровня не зависит от выбранного языка. При создании сервер проверит,
|
||||
опубликованы ли подходящие задания.
|
||||
</p>
|
||||
) : null}
|
||||
{specialization && grade ? (
|
||||
<div className={styles.availability}>
|
||||
<div className={styles["status-row"]}>
|
||||
<strong>{gradeLabels[grade.grade]}</strong>
|
||||
<span data-state={grade.status}>
|
||||
{grade.status === "available"
|
||||
? "Доступна"
|
||||
: grade.status === "active_attempt"
|
||||
? "Есть попытка"
|
||||
: grade.status === "cooldown"
|
||||
? "Пауза"
|
||||
: "Банк не готов"}
|
||||
</span>
|
||||
</div>
|
||||
<p>{gradeStatusDescription(grade)}</p>
|
||||
<AssessmentPolicyParameters grade={grade} />
|
||||
{activeAttemptId && grade.status === "active_attempt" ? (
|
||||
<ButtonLink to={paths.candidate.assessmentAttempt(activeAttemptId)}>
|
||||
Продолжить текущую попытку
|
||||
</ButtonLink>
|
||||
) : grade.status === "available" ? (
|
||||
<Button
|
||||
isBusy={createBusy}
|
||||
disabled={!taskLanguageReady}
|
||||
onClick={() => {
|
||||
if (taskLanguageReady) handleStartReal();
|
||||
}}
|
||||
>
|
||||
{createBusy ? "Создаем попытку..." : "Начать полную проверку"}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{pendingCreate ? (
|
||||
<p className={styles.pending} role="status">
|
||||
Данные отправки зафиксированы до подтверждения. Если связь прервалась, повторите
|
||||
ее с тем же ключом.
|
||||
</p>
|
||||
) : null}
|
||||
{formError ? (
|
||||
<p className={styles.error} role="alert">
|
||||
{formError}{" "}
|
||||
{c3Required ? (
|
||||
<ButtonLink to={paths.candidate.privacy}>Открыть согласие C3</ButtonLink>
|
||||
) : null}
|
||||
</p>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
<AssessmentSignalsNotice />
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
title="Демонстрационный экспресс-запуск"
|
||||
description="Отдельный учебный режим для знакомства с заданиями."
|
||||
>
|
||||
<div className={styles.express}>
|
||||
<p>
|
||||
Это демонстрация на 3-5 минут. Она не подтверждает квалификацию, не присваивает грейд
|
||||
и не влияет на доступность полной проверки.
|
||||
</p>
|
||||
<Button
|
||||
isBusy={createBusy}
|
||||
disabled={Boolean(pendingCreate)}
|
||||
onClick={handleStartExpress}
|
||||
>
|
||||
{createBusy ? "Создаем запуск..." : "Начать демонстрацию"}
|
||||
</Button>
|
||||
</div>
|
||||
</Section>
|
||||
</div>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ConsentManagement } from "../../../features/consent-management";
|
||||
import { Page } from "../../../shared/ui";
|
||||
import { paths } from "../../../shared/config";
|
||||
import { ButtonLink, Page, Section } from "../../../shared/ui";
|
||||
|
||||
export function ConsentsPage() {
|
||||
return (
|
||||
@@ -10,6 +11,15 @@ export function ConsentsPage() {
|
||||
width="wide"
|
||||
>
|
||||
<ConsentManagement />
|
||||
<Section title="Ручная оценка">
|
||||
<p>
|
||||
Можно запросить оценку специалистом до первого теста или после отзыва согласия на
|
||||
автоматическую оценку. Запрос не включает согласие обратно.
|
||||
</p>
|
||||
<ButtonLink to={paths.candidate.supportManual} variant="secondary">
|
||||
Запросить ручную оценку
|
||||
</ButtonLink>
|
||||
</Section>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { NeedEditorPage } from "./ui/need-editor-page";
|
||||
@@ -0,0 +1,41 @@
|
||||
.content {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.content [hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.selector {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
max-width: 38rem;
|
||||
}
|
||||
|
||||
.selector label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.selector select {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) 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(--line-strong) solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
|
||||
import {
|
||||
getOrganizationNeed,
|
||||
useGetOrganizationNeed,
|
||||
} from "../../../shared/api/endpoints/need/need";
|
||||
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import type { MyOrganizationList, Need, Session } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config/paths";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Page,
|
||||
Section,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
activeNeedOrganizations,
|
||||
isNeedSessionCurrent,
|
||||
needQueryKeys,
|
||||
removeAllNeedQueries,
|
||||
removeNeedQueriesForOrganization,
|
||||
removeNeedQueriesForSessionChange,
|
||||
useNeedOrganizationDirectory,
|
||||
} from "../../../entities/need";
|
||||
import { NeedEditor } from "../../../features/edit-need";
|
||||
import styles from "./need-editor-page.module.css";
|
||||
|
||||
const emptyDirectoryPages: readonly MyOrganizationList[] = [];
|
||||
|
||||
function isAccessLoss(error: unknown): error is ApiRequestError {
|
||||
return (
|
||||
error instanceof ApiRequestError &&
|
||||
(error.status === 401 || error.status === 403 || error.status === 404)
|
||||
);
|
||||
}
|
||||
|
||||
function isOwnerContext(
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
session: Session | undefined,
|
||||
pages: readonly MyOrganizationList[],
|
||||
organizationId: string,
|
||||
): boolean {
|
||||
if (!isNeedSessionCurrent(queryClient, session)) return false;
|
||||
return activeNeedOrganizations(pages).some((item) => item.organization.id === organizationId);
|
||||
}
|
||||
|
||||
export function NeedEditorPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const { needId } = useParams();
|
||||
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 directoryIsFetching = directory.isFetching;
|
||||
const directoryIsFetchingNextPage = directory.isFetchingNextPage;
|
||||
const directoryIsLoading = directory.isLoading;
|
||||
const hasMoreOwnerPages = directory.hasNextPage;
|
||||
const fetchNextOwnerPage = directory.fetchNextPage;
|
||||
const refetchDirectory = directory.refetch;
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const organizationId = searchParams.get("organization_id");
|
||||
const [deniedOrganizationId, setDeniedOrganizationId] = 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 owner = organizations.find((item) => item.organization.id === organizationId);
|
||||
const directoryRefreshing = directoryIsFetching && !directoryIsFetchingNextPage;
|
||||
const directoryFresh =
|
||||
sessionReady && Boolean(directoryData) && !directoryIsError && !directoryRefreshing;
|
||||
const deniedKey = accountId && organizationId ? `${accountId}:${organizationId}` : null;
|
||||
const denied = deniedOrganizationId !== null && deniedOrganizationId === deniedKey;
|
||||
const membershipDenied =
|
||||
Boolean(organizationId) && !owner && directoryFresh && !hasMoreOwnerPages;
|
||||
const canReadNeed =
|
||||
needId !== undefined &&
|
||||
organizationId !== null &&
|
||||
directoryFresh &&
|
||||
owner !== undefined &&
|
||||
!denied;
|
||||
const needQuery = useGetOrganizationNeed(organizationId ?? "", needId ?? "", {
|
||||
query: {
|
||||
queryKey: needQueryKeys.detail(
|
||||
accountId ?? "no-session",
|
||||
organizationId ?? "no-organization",
|
||||
needId ?? "new",
|
||||
),
|
||||
queryFn: async ({ signal }) => {
|
||||
if (!isNeedSessionCurrent(queryClient, session)) {
|
||||
throw new Error("The session changed before the need request.");
|
||||
}
|
||||
const result = await getOrganizationNeed(organizationId ?? "", needId ?? "", { signal });
|
||||
if (!isNeedSessionCurrent(queryClient, session)) {
|
||||
throw new Error("The session changed during the need request.");
|
||||
}
|
||||
return result;
|
||||
},
|
||||
enabled: canReadNeed,
|
||||
gcTime: 0,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
refetchOnWindowFocus: "always",
|
||||
retry: false,
|
||||
},
|
||||
});
|
||||
|
||||
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(directory.error)) {
|
||||
removeAllNeedQueries(queryClient);
|
||||
}
|
||||
}, [directory.error, directoryIsError, queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!sessionReady || !directoryData || directoryIsError || directoryIsFetchingNextPage) return;
|
||||
if (organizationId) {
|
||||
if (!owner && hasMoreOwnerPages) void fetchNextOwnerPage();
|
||||
return;
|
||||
}
|
||||
if (organizations[0]) {
|
||||
const next = new URLSearchParams(searchParams);
|
||||
next.set("organization_id", organizations[0].organization.id);
|
||||
setSearchParams(next, { replace: true });
|
||||
} else if (hasMoreOwnerPages) {
|
||||
void fetchNextOwnerPage();
|
||||
}
|
||||
}, [
|
||||
directoryData,
|
||||
directoryIsError,
|
||||
directoryIsFetchingNextPage,
|
||||
fetchNextOwnerPage,
|
||||
hasMoreOwnerPages,
|
||||
organizations,
|
||||
organizationId,
|
||||
owner,
|
||||
searchParams,
|
||||
sessionReady,
|
||||
setSearchParams,
|
||||
]);
|
||||
|
||||
const markAccessLost = useCallback(
|
||||
async (error: ApiRequestError, deniedOrganizationId: string | null) => {
|
||||
if (
|
||||
!isAccessLoss(error) ||
|
||||
!deniedOrganizationId ||
|
||||
!isNeedSessionCurrent(queryClient, session) ||
|
||||
!accountId
|
||||
)
|
||||
return;
|
||||
setDeniedOrganizationId(`${accountId}:${deniedOrganizationId}`);
|
||||
removeNeedQueriesForOrganization(queryClient, deniedOrganizationId);
|
||||
await refetchDirectory();
|
||||
},
|
||||
[accountId, queryClient, refetchDirectory, session, setDeniedOrganizationId],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!needQuery.isError || !isAccessLoss(needQuery.error)) {
|
||||
if (!needQuery.isError) reportedAccessError.current = false;
|
||||
return;
|
||||
}
|
||||
if (reportedAccessError.current) return;
|
||||
reportedAccessError.current = true;
|
||||
void markAccessLost(needQuery.error, organizationId);
|
||||
}, [markAccessLost, needQuery.error, needQuery.isError, organizationId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!membershipDenied || !organizationId) return;
|
||||
removeNeedQueriesForOrganization(queryClient, organizationId);
|
||||
}, [membershipDenied, organizationId, queryClient]);
|
||||
|
||||
const isCurrentActor = useCallback(
|
||||
() => isNeedSessionCurrent(queryClient, session),
|
||||
[queryClient, session],
|
||||
);
|
||||
|
||||
const persistCreated = useCallback(
|
||||
async (saved: Need) => {
|
||||
const refreshed = await refetchDirectory();
|
||||
if (refreshed.isError) throw new Error("Could not confirm company access after saving.");
|
||||
const refreshedPages = refreshed.data?.pages ?? [];
|
||||
if (!isCurrentActor()) return;
|
||||
if (!isOwnerContext(queryClient, session, refreshedPages, organizationId ?? "")) {
|
||||
if (organizationId && accountId) setDeniedOrganizationId(`${accountId}:${organizationId}`);
|
||||
if (organizationId) removeNeedQueriesForOrganization(queryClient, organizationId);
|
||||
throw new Error("Owner access changed while saving the need.");
|
||||
}
|
||||
const key = needQueryKeys.detail(accountId ?? "no-session", organizationId ?? "", saved.id);
|
||||
queryClient.setQueryData(key, saved);
|
||||
navigate(paths.employer.need(saved.id, organizationId ?? ""), { replace: true });
|
||||
},
|
||||
[
|
||||
accountId,
|
||||
isCurrentActor,
|
||||
navigate,
|
||||
organizationId,
|
||||
queryClient,
|
||||
refetchDirectory,
|
||||
session,
|
||||
setDeniedOrganizationId,
|
||||
],
|
||||
);
|
||||
|
||||
const persistSaved = useCallback(
|
||||
async (saved: Need) => {
|
||||
const refreshed = await refetchDirectory();
|
||||
if (refreshed.isError) throw new Error("Could not confirm company access after saving.");
|
||||
const refreshedPages = refreshed.data?.pages ?? [];
|
||||
if (!isCurrentActor()) return;
|
||||
if (!isOwnerContext(queryClient, session, refreshedPages, organizationId ?? "")) {
|
||||
if (organizationId && accountId) setDeniedOrganizationId(`${accountId}:${organizationId}`);
|
||||
if (organizationId) removeNeedQueriesForOrganization(queryClient, organizationId);
|
||||
throw new Error("Owner access changed while saving the need.");
|
||||
}
|
||||
queryClient.setQueryData(
|
||||
needQueryKeys.detail(accountId ?? "no-session", organizationId ?? "", saved.id),
|
||||
saved,
|
||||
);
|
||||
},
|
||||
[
|
||||
accountId,
|
||||
isCurrentActor,
|
||||
organizationId,
|
||||
queryClient,
|
||||
refetchDirectory,
|
||||
session,
|
||||
setDeniedOrganizationId,
|
||||
],
|
||||
);
|
||||
|
||||
const selectedOrganizationDenied = denied || membershipDenied;
|
||||
const sessionFailure = sessionQuery.isError;
|
||||
const directoryAccessFailure = directory.isError && isAccessLoss(directory.error);
|
||||
const loading =
|
||||
!sessionFailure &&
|
||||
(!sessionReady ||
|
||||
directoryIsLoading ||
|
||||
directoryRefreshing ||
|
||||
!directoryData ||
|
||||
(!owner && hasMoreOwnerPages));
|
||||
const title = needId ? "Потребность" : "Новая потребность";
|
||||
|
||||
return (
|
||||
<Page
|
||||
title={title}
|
||||
eyebrow="Кабинет работодателя"
|
||||
lead={
|
||||
needId
|
||||
? "Подтверждайте требования и следите за полнотой данных."
|
||||
: "Опишите потребность команды без создания вакансии."
|
||||
}
|
||||
width="wide"
|
||||
>
|
||||
<div className={styles.content}>
|
||||
{sessionFailure ? (
|
||||
isAccessLoss(sessionQuery.error) ? (
|
||||
<ForbiddenState error={sessionQuery.error} title="Текущий вход не подтвержден" />
|
||||
) : (
|
||||
<ErrorState
|
||||
error={sessionQuery.error}
|
||||
isRetrying={sessionQuery.isFetching}
|
||||
onRetry={() => void sessionQuery.refetch()}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
{directory.isError ? (
|
||||
directoryAccessFailure ? (
|
||||
<ForbiddenState error={directory.error} />
|
||||
) : (
|
||||
<ErrorState
|
||||
error={directory.error}
|
||||
isRetrying={directory.isFetching}
|
||||
onRetry={() => void directory.refetch()}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
{loading ? <LoadingState label="Проверяем компанию и загружаем потребность..." /> : null}
|
||||
{!sessionFailure && !directory.isError && directory.data ? (
|
||||
<>
|
||||
{directoryRefreshing ? (
|
||||
<LoadingState label="Повторно проверяем права владельца..." />
|
||||
) : null}
|
||||
{organizations.length > 1 ? (
|
||||
<div className={styles.selector} hidden={!directoryFresh}>
|
||||
<label htmlFor="need-editor-organization">Компания</label>
|
||||
<select
|
||||
id="need-editor-organization"
|
||||
value={owner?.organization.id ?? ""}
|
||||
onChange={(event) => {
|
||||
const next = new URLSearchParams(searchParams);
|
||||
next.set("organization_id", event.currentTarget.value);
|
||||
reportedAccessError.current = false;
|
||||
setDeniedOrganizationId(null);
|
||||
setSearchParams(next);
|
||||
}}
|
||||
>
|
||||
{!owner ? <option value="">Выберите компанию</option> : null}
|
||||
{organizations.map((item) => (
|
||||
<option key={item.organization.id} value={item.organization.id}>
|
||||
{item.organization.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
) : null}
|
||||
{selectedOrganizationDenied ? (
|
||||
<ForbiddenState
|
||||
title="Потребность недоступна"
|
||||
description="Доступ владельца не подтвержден. Выберите компанию с активным членством владельца."
|
||||
action={
|
||||
<div className={styles.actions}>
|
||||
{needId ? (
|
||||
<ButtonLink to={paths.employer.needs}>К списку потребностей</ButtonLink>
|
||||
) : null}
|
||||
<Button variant="secondary" onClick={() => void directory.refetch()}>
|
||||
Проверить доступ снова
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{!organizationId && organizations.length === 0 && !directory.hasNextPage ? (
|
||||
<ForbiddenState
|
||||
title="Нужны права владельца компании"
|
||||
description="Потребностями в этой версии может управлять только владелец компании."
|
||||
action={
|
||||
<ButtonLink to={paths.employer.company}>Открыть профиль компании</ButtonLink>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{owner && !selectedOrganizationDenied ? (
|
||||
<Section title={needId ? "Редактирование" : "Создание потребности"}>
|
||||
{needId && needQuery.isError && isAccessLoss(needQuery.error) ? (
|
||||
<ForbiddenState
|
||||
title="Потребность недоступна"
|
||||
description="Проверьте права владельца и выбранную компанию."
|
||||
/>
|
||||
) : null}
|
||||
{needId && needQuery.isError && !isAccessLoss(needQuery.error) ? (
|
||||
<ErrorState
|
||||
error={needQuery.error}
|
||||
isRetrying={needQuery.isFetching}
|
||||
onRetry={() => void needQuery.refetch()}
|
||||
/>
|
||||
) : null}
|
||||
{needId && needQuery.isLoading ? (
|
||||
<LoadingState label="Загружаем данные потребности..." />
|
||||
) : null}
|
||||
{needId && needQuery.data && needQuery.isFetching ? (
|
||||
<LoadingState label="Проверяем, что доступ владельца действует..." />
|
||||
) : null}
|
||||
<div hidden={!directoryFresh || needQuery.isFetching || needQuery.isError}>
|
||||
{(!needId || needQuery.data) && !needQuery.isError ? (
|
||||
<NeedEditor
|
||||
key={`${accountId ?? "no-session"}:${organizationId}:${needId ?? "new"}`}
|
||||
accountId={accountId ?? "no-session"}
|
||||
organizationId={organizationId ?? ""}
|
||||
session={session!}
|
||||
need={needQuery.data}
|
||||
onCreated={persistCreated}
|
||||
onSaved={persistSaved}
|
||||
onAccessLost={(error) => void markAccessLost(error, organizationId)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</Section>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { NeedListPage } from "./ui/need-list-page";
|
||||
@@ -0,0 +1,139 @@
|
||||
.content {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: end;
|
||||
justify-content: space-between;
|
||||
margin-block-end: var(--space-5);
|
||||
}
|
||||
|
||||
.selector {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: min(100%, 20rem);
|
||||
}
|
||||
|
||||
.selector label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.selector select {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) 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(--line-strong) solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.list {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.card {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.card-heading {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.card-heading h3 {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.complete,
|
||||
.incomplete {
|
||||
max-width: 100%;
|
||||
overflow-wrap: anywhere;
|
||||
font-size: var(--font-size-s);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.complete {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.incomplete {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.facts {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(8rem, max-content) minmax(0, 1fr);
|
||||
gap: var(--space-2) var(--space-4);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.facts dt {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.facts dd {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.missing {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
padding-inline-start: var(--space-5);
|
||||
}
|
||||
|
||||
.load-more {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin-block-start: var(--space-4);
|
||||
}
|
||||
|
||||
@media (width < 30rem) {
|
||||
.toolbar {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.toolbar > a {
|
||||
width: fit-content;
|
||||
}
|
||||
|
||||
.facts {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.facts dd + dt {
|
||||
padding-block-start: var(--space-2);
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
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}
|
||||
<ButtonLink to={paths.employer.need(item.id, organizationId)} variant="secondary">
|
||||
Открыть потребность
|
||||
</ButtonLink>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export {
|
||||
CreateSupportCasePage,
|
||||
ManualAssessmentPage,
|
||||
SupportCaseDetailPage,
|
||||
SupportCasesPage,
|
||||
} from "./ui/support-cases-pages";
|
||||
@@ -0,0 +1,119 @@
|
||||
.root {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.case-list {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.case-card,
|
||||
.event,
|
||||
.decision {
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.card-heading,
|
||||
.event-heading {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
}
|
||||
|
||||
.card-heading h3,
|
||||
.event-heading h3,
|
||||
.decision h3 {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.card-heading > span {
|
||||
padding: var(--space-1) var(--space-2);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-pill);
|
||||
font-size: var(--font-size-s);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.case-card p,
|
||||
.event p,
|
||||
.decision p {
|
||||
margin: var(--space-3) 0 0;
|
||||
line-height: var(--line-height-body);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.target,
|
||||
.date,
|
||||
.event-heading time {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.more {
|
||||
margin-top: var(--space-4);
|
||||
}
|
||||
|
||||
.facts {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(9rem, 0.45fr) minmax(0, 1fr);
|
||||
gap: var(--space-2) var(--space-4);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.facts dt {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.facts dd {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.description,
|
||||
.message {
|
||||
overflow-wrap: anywhere;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.history {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.event-heading time {
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
@media (width <= 40rem) {
|
||||
.actions > * {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.facts {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.facts dd + dt {
|
||||
margin-top: var(--space-3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,548 @@
|
||||
import { useEffect } from "react";
|
||||
import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useParams } from "react-router-dom";
|
||||
import {
|
||||
formatSupportDate,
|
||||
isSupportSessionAccessError,
|
||||
supportCaseActorLabels,
|
||||
supportCaseDetailQueryKey,
|
||||
supportCaseEventKindLabels,
|
||||
supportCaseListQueryKey,
|
||||
supportCasePathFor,
|
||||
supportCaseStatusLabels,
|
||||
supportCaseTypeLabels,
|
||||
supportSessionMatches,
|
||||
supportTargetDescription,
|
||||
} from "../../../entities/support-case";
|
||||
import { CreateSupportCase } from "../../../features/create-support-case";
|
||||
import { RequestManualAssessment } from "../../../features/request-manual-assessment";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import {
|
||||
getGetCurrentSessionQueryKey,
|
||||
useGetCurrentSession,
|
||||
} from "../../../shared/api/endpoints/identity/identity";
|
||||
import {
|
||||
getMySupportCase,
|
||||
listMySupportCases,
|
||||
} from "../../../shared/api/endpoints/support/support";
|
||||
import type { Session, SupportCase } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Page,
|
||||
Section,
|
||||
TextLink,
|
||||
} from "../../../shared/ui";
|
||||
import styles from "./support-cases-pages.module.css";
|
||||
|
||||
const supportCasePageSize = 20;
|
||||
const caseIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
function isCaseAccessError(error: unknown): error is ApiRequestError {
|
||||
return (
|
||||
error instanceof ApiRequestError &&
|
||||
(error.status === 401 || error.status === 403 || error.status === 404)
|
||||
);
|
||||
}
|
||||
|
||||
function sessionErrorState(error: unknown, onRetry: () => void, isRetrying: boolean) {
|
||||
if (isSupportSessionAccessError(error)) {
|
||||
return (
|
||||
<ForbiddenState
|
||||
error={error}
|
||||
title="Войдите, чтобы открыть обращения"
|
||||
description="После входа поддержка откроется для вашего аккаунта."
|
||||
action={
|
||||
<ButtonLink to={paths.login} state={{ returnTo: "support" }}>
|
||||
Войти в поддержку
|
||||
</ButtonLink>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ErrorState
|
||||
error={error}
|
||||
title="Не удалось проверить вход"
|
||||
isRetrying={isRetrying}
|
||||
onRetry={onRetry}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function removeSupportAccountCache(
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
accountId: string,
|
||||
) {
|
||||
queryClient.removeQueries({
|
||||
predicate: (query) =>
|
||||
query.queryKey[0] === "account" &&
|
||||
query.queryKey[1] === accountId &&
|
||||
query.queryKey[2] === "support-cases",
|
||||
});
|
||||
}
|
||||
|
||||
function supportLandingPath(session: Session): string {
|
||||
return session.account.scenario === "candidate"
|
||||
? paths.candidate.supportCases
|
||||
: paths.employer.supportCases;
|
||||
}
|
||||
|
||||
export function SupportCasesPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const session = useGetCurrentSession({ query: { retry: false } });
|
||||
const actor = session.isSuccess ? session.data : null;
|
||||
const knownActor =
|
||||
session.data ?? queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
|
||||
const list = useInfiniteQuery({
|
||||
queryKey: actor
|
||||
? supportCaseListQueryKey(actor.account.id)
|
||||
: ["account", "anonymous", "support-cases", "list"],
|
||||
queryFn: async ({ pageParam, signal }) => {
|
||||
if (
|
||||
!actor ||
|
||||
!supportSessionMatches(queryClient.getQueryState(getGetCurrentSessionQueryKey()), actor)
|
||||
) {
|
||||
throw new Error("The active account changed before support history was loaded.");
|
||||
}
|
||||
const result = await listMySupportCases(
|
||||
pageParam
|
||||
? { limit: supportCasePageSize, cursor: pageParam }
|
||||
: { limit: supportCasePageSize },
|
||||
{ signal },
|
||||
);
|
||||
if (
|
||||
!supportSessionMatches(queryClient.getQueryState(getGetCurrentSessionQueryKey()), actor)
|
||||
) {
|
||||
throw new Error("The active account changed while support history was loading.");
|
||||
}
|
||||
return result;
|
||||
},
|
||||
initialPageParam: undefined as string | undefined,
|
||||
getNextPageParam: (lastPage) =>
|
||||
lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined,
|
||||
enabled: Boolean(actor),
|
||||
staleTime: 0,
|
||||
gcTime: 0,
|
||||
refetchOnMount: "always",
|
||||
retry: false,
|
||||
});
|
||||
const listAccessError = list.isError && isCaseAccessError(list.error) ? list.error : null;
|
||||
|
||||
useEffect(() => {
|
||||
const accountId = actor?.account.id ?? knownActor?.account.id;
|
||||
if (!accountId || (!isSupportSessionAccessError(session.error) && !listAccessError)) {
|
||||
return;
|
||||
}
|
||||
removeSupportAccountCache(queryClient, accountId);
|
||||
}, [actor, knownActor, listAccessError, queryClient, session.error]);
|
||||
|
||||
if (session.isPending && !session.data) {
|
||||
return (
|
||||
<Page title="Мои обращения">
|
||||
<LoadingState label="Проверяем вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (session.isError) {
|
||||
return (
|
||||
<Page title="Мои обращения">
|
||||
{sessionErrorState(session.error, () => void session.refetch(), session.isRefetching)}
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!actor || (actor.account.scenario !== "candidate" && actor.account.scenario !== "employer")) {
|
||||
return (
|
||||
<Page title="Мои обращения">
|
||||
<ForbiddenState title="Поддержка недоступна" />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (listAccessError) {
|
||||
return (
|
||||
<Page title="Мои обращения">
|
||||
<ForbiddenState
|
||||
error={listAccessError}
|
||||
title="Обращения недоступны"
|
||||
description="Сервер не подтвердил доступ к истории этого аккаунта."
|
||||
action={
|
||||
<ButtonLink to={paths.login} state={{ returnTo: "support" }}>
|
||||
Обновить вход
|
||||
</ButtonLink>
|
||||
}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (list.isPending && !list.data) {
|
||||
return (
|
||||
<Page title="Мои обращения">
|
||||
<LoadingState label="Загружаем историю обращений..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (list.isError && !list.data) {
|
||||
return (
|
||||
<Page title="Мои обращения">
|
||||
<ErrorState
|
||||
error={list.error}
|
||||
title="Не удалось загрузить обращения"
|
||||
isRetrying={list.isRefetching}
|
||||
onRetry={() => void list.refetch()}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
const cases = list.data?.pages.flatMap((page) => page.items) ?? [];
|
||||
return (
|
||||
<Page
|
||||
title="Мои обращения"
|
||||
eyebrow={
|
||||
actor.account.scenario === "candidate" ? "Кабинет кандидата" : "Кабинет работодателя"
|
||||
}
|
||||
lead="Здесь хранятся обращения этого аккаунта и ответы поддержки."
|
||||
width="wide"
|
||||
>
|
||||
<div className={styles.root}>
|
||||
<Section title="Новый запрос">
|
||||
<div className={styles.actions}>
|
||||
<ButtonLink
|
||||
to={
|
||||
actor.account.scenario === "candidate"
|
||||
? paths.candidate.supportNew
|
||||
: paths.employer.supportNew
|
||||
}
|
||||
>
|
||||
Написать в поддержку
|
||||
</ButtonLink>
|
||||
{actor.account.scenario === "candidate" ? (
|
||||
<ButtonLink to={paths.candidate.supportManual} variant="secondary">
|
||||
Запросить ручную оценку
|
||||
</ButtonLink>
|
||||
) : null}
|
||||
</div>
|
||||
</Section>
|
||||
<Section title="История">
|
||||
{list.isError ? (
|
||||
<ErrorState
|
||||
error={list.error}
|
||||
title="Не удалось обновить историю"
|
||||
isRetrying={list.isRefetching}
|
||||
onRetry={() => void list.refetch()}
|
||||
/>
|
||||
) : null}
|
||||
{cases.length === 0 ? (
|
||||
<EmptyState
|
||||
title="Обращений пока нет"
|
||||
description="После отправки новое дело появится здесь и останется доступным после повторного входа."
|
||||
action={
|
||||
<ButtonLink
|
||||
to={
|
||||
actor.account.scenario === "candidate"
|
||||
? paths.candidate.supportNew
|
||||
: paths.employer.supportNew
|
||||
}
|
||||
>
|
||||
Создать обращение
|
||||
</ButtonLink>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<div className={styles["case-list"]}>
|
||||
{cases.map((supportCase) => (
|
||||
<SupportCaseSummaryCard
|
||||
key={supportCase.id}
|
||||
supportCase={supportCase}
|
||||
href={supportCasePathFor(actor, supportCase.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{list.hasNextPage ? (
|
||||
<div className={styles.more}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={list.isFetchingNextPage}
|
||||
onClick={() => void list.fetchNextPage()}
|
||||
>
|
||||
{list.isFetchingNextPage ? "Загружаем..." : "Показать более ранние обращения"}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</Section>
|
||||
</div>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
function SupportCaseSummaryCard({
|
||||
supportCase,
|
||||
href,
|
||||
}: {
|
||||
supportCase: {
|
||||
id: string;
|
||||
number: string;
|
||||
type: SupportCase["type"];
|
||||
status: SupportCase["status"];
|
||||
response_target: SupportCase["response_target"];
|
||||
created_at: string;
|
||||
};
|
||||
href: string;
|
||||
}) {
|
||||
return (
|
||||
<article className={styles["case-card"]}>
|
||||
<div className={styles["card-heading"]}>
|
||||
<h3>
|
||||
<TextLink to={href}>{supportCase.number}</TextLink>
|
||||
</h3>
|
||||
<span>{supportCaseStatusLabels[supportCase.status]}</span>
|
||||
</div>
|
||||
<p>{supportCaseTypeLabels[supportCase.type]}</p>
|
||||
<p className={styles.target}>{supportTargetDescription(supportCase.response_target)}</p>
|
||||
<p className={styles.date}>Создано {formatSupportDate(supportCase.created_at)}</p>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
export function CreateSupportCasePage() {
|
||||
return (
|
||||
<Page
|
||||
title="Обратиться в поддержку"
|
||||
eyebrow="Мои обращения"
|
||||
lead="Отправьте вопрос или сообщите о проблеме."
|
||||
width="wide"
|
||||
>
|
||||
<CreateSupportCase />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
export function ManualAssessmentPage() {
|
||||
return (
|
||||
<Page
|
||||
title="Запросить ручную оценку"
|
||||
eyebrow="Поддержка"
|
||||
lead="Выберите категорию и расскажите, что важно учесть эксперту."
|
||||
width="wide"
|
||||
>
|
||||
<RequestManualAssessment />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
export function SupportCaseDetailPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const { caseId = "" } = useParams();
|
||||
const session = useGetCurrentSession({ query: { retry: false } });
|
||||
const actor = session.isSuccess ? session.data : null;
|
||||
const knownActor =
|
||||
session.data ?? queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
|
||||
const validId = caseIdPattern.test(caseId);
|
||||
const details = useQuery({
|
||||
queryKey:
|
||||
actor && validId
|
||||
? supportCaseDetailQueryKey(actor.account.id, caseId)
|
||||
: ["account", "anonymous", "support-cases", "detail", caseId],
|
||||
queryFn: async ({ signal }) => {
|
||||
if (
|
||||
!actor ||
|
||||
!supportSessionMatches(queryClient.getQueryState(getGetCurrentSessionQueryKey()), actor)
|
||||
) {
|
||||
throw new Error("The active account changed before the support request was loaded.");
|
||||
}
|
||||
const result = await getMySupportCase(caseId, { signal });
|
||||
if (
|
||||
!supportSessionMatches(queryClient.getQueryState(getGetCurrentSessionQueryKey()), actor)
|
||||
) {
|
||||
throw new Error("The active account changed while the support request was loading.");
|
||||
}
|
||||
return result;
|
||||
},
|
||||
enabled: Boolean(actor && validId),
|
||||
staleTime: 0,
|
||||
gcTime: 0,
|
||||
refetchOnMount: "always",
|
||||
retry: false,
|
||||
});
|
||||
const detailsAccessError =
|
||||
details.isError && isCaseAccessError(details.error) ? details.error : null;
|
||||
|
||||
useEffect(() => {
|
||||
const accountId = actor?.account.id ?? knownActor?.account.id;
|
||||
if (!accountId || (!isSupportSessionAccessError(session.error) && !detailsAccessError)) {
|
||||
return;
|
||||
}
|
||||
removeSupportAccountCache(queryClient, accountId);
|
||||
}, [actor, detailsAccessError, knownActor, queryClient, session.error]);
|
||||
|
||||
if (session.isPending && !session.data) {
|
||||
return (
|
||||
<Page title="Обращение">
|
||||
<LoadingState label="Проверяем вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (session.isError) {
|
||||
return (
|
||||
<Page title="Обращение">
|
||||
{sessionErrorState(session.error, () => void session.refetch(), session.isRefetching)}
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!actor)
|
||||
return (
|
||||
<Page title="Обращение">
|
||||
<ForbiddenState title="Войдите, чтобы открыть обращение" />
|
||||
</Page>
|
||||
);
|
||||
if (!validId) {
|
||||
return (
|
||||
<Page title="Обращение не найдено">
|
||||
<EmptyState
|
||||
title="Обращение не найдено или недоступно"
|
||||
description="Проверьте ссылку или вернитесь к истории своего аккаунта."
|
||||
action={<ButtonLink to={supportLandingPath(actor)}>Мои обращения</ButtonLink>}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (detailsAccessError) {
|
||||
if (detailsAccessError.status === 404) {
|
||||
return (
|
||||
<Page title="Обращение не найдено">
|
||||
<EmptyState
|
||||
title="Обращение не найдено или недоступно"
|
||||
description="Ссылка не дает доступ к истории другого аккаунта."
|
||||
action={<ButtonLink to={supportLandingPath(actor)}>Мои обращения</ButtonLink>}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Page title="Обращение недоступно">
|
||||
<ForbiddenState
|
||||
error={detailsAccessError}
|
||||
title="Обращение недоступно"
|
||||
description="Сервер не подтвердил доступ к этой истории."
|
||||
action={
|
||||
<ButtonLink to={paths.login} state={{ returnTo: "support" }}>
|
||||
Обновить вход
|
||||
</ButtonLink>
|
||||
}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (details.isPending && !details.data) {
|
||||
return (
|
||||
<Page title="Обращение">
|
||||
<LoadingState label="Загружаем обращение..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (details.isError && !details.data) {
|
||||
return (
|
||||
<Page title="Не удалось открыть обращение">
|
||||
<ErrorState
|
||||
error={details.error}
|
||||
title="Не удалось загрузить обращение"
|
||||
isRetrying={details.isRefetching}
|
||||
onRetry={() => void details.refetch()}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!details.data)
|
||||
return (
|
||||
<Page title="Обращение">
|
||||
<LoadingState label="Загружаем обращение..." />
|
||||
</Page>
|
||||
);
|
||||
|
||||
return (
|
||||
<Page
|
||||
title={details.data.number}
|
||||
eyebrow="Мои обращения"
|
||||
lead={supportCaseTypeLabels[details.data.type]}
|
||||
width="wide"
|
||||
>
|
||||
<SupportCaseDetails supportCase={details.data} session={actor} />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
function SupportCaseDetails({
|
||||
supportCase,
|
||||
session,
|
||||
}: {
|
||||
supportCase: SupportCase;
|
||||
session: Session;
|
||||
}) {
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<Section title="Состояние">
|
||||
<dl className={styles.facts}>
|
||||
<dt>Номер</dt>
|
||||
<dd>{supportCase.number}</dd>
|
||||
<dt>Статус</dt>
|
||||
<dd>{supportCaseStatusLabels[supportCase.status]}</dd>
|
||||
<dt>Создано</dt>
|
||||
<dd>{formatSupportDate(supportCase.created_at)}</dd>
|
||||
<dt>Операционная цель</dt>
|
||||
<dd>{supportTargetDescription(supportCase.response_target)}</dd>
|
||||
{supportCase.assessment_target ? (
|
||||
<>
|
||||
<dt>Специальность</dt>
|
||||
<dd>{supportCase.assessment_target.specialization}</dd>
|
||||
<dt>Желаемый грейд</dt>
|
||||
<dd>{supportCase.assessment_target.grade}</dd>
|
||||
</>
|
||||
) : null}
|
||||
{supportCase.type === "manual_assessment" ? (
|
||||
<>
|
||||
<dt>Рубрика</dt>
|
||||
<dd>
|
||||
{supportCase.rubric_version === null
|
||||
? "Опубликованной рубрики для этой категории пока нет. Запрос ожидает эксперта; автоматическая оценка не выполнялась."
|
||||
: `Зафиксирована версия ${supportCase.rubric_version}. Запрос ожидает эксперта.`}
|
||||
</dd>
|
||||
</>
|
||||
) : null}
|
||||
</dl>
|
||||
<p className={styles.description}>{supportCase.description}</p>
|
||||
{supportCase.decision ? (
|
||||
<div className={styles.decision}>
|
||||
<h3>Решение</h3>
|
||||
<p>{supportCase.decision.reason}</p>
|
||||
</div>
|
||||
) : null}
|
||||
</Section>
|
||||
<Section title="История">
|
||||
<ol className={styles.history}>
|
||||
{supportCase.history.map((event) => (
|
||||
<li key={event.sequence} className={styles.event}>
|
||||
<div className={styles["event-heading"]}>
|
||||
<h3>{supportCaseEventKindLabels[event.kind]}</h3>
|
||||
<time dateTime={event.occurred_at}>{formatSupportDate(event.occurred_at)}</time>
|
||||
</div>
|
||||
<p>{supportCaseActorLabels[event.actor]}</p>
|
||||
{event.status ? <p>Статус: {supportCaseStatusLabels[event.status]}</p> : null}
|
||||
{event.message ? <p className={styles.message}>{event.message}</p> : null}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</Section>
|
||||
<div className={styles.actions}>
|
||||
<ButtonLink to={supportLandingPath(session)} variant="secondary">
|
||||
Мои обращения
|
||||
</ButtonLink>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user