feat: add candidate profile, questionnaire and company forms
This commit is contained in:
1 parent
3a61a8e8bb
commit
f81cd0ae09
68 files changed
+9517
-54
No files matched your search
@@ -0,0 +1 @@
|
||||
export { CompanyEditor } from "./ui/company-editor";
|
||||
@@ -0,0 +1,110 @@
|
||||
.form {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: var(--font-size-l);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.field,
|
||||
.group {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.field label,
|
||||
.group legend {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.field input,
|
||||
.field textarea {
|
||||
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;
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.field textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.field input:focus-visible,
|
||||
.field textarea:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.field input[aria-invalid="true"],
|
||||
.field textarea[aria-invalid="true"] {
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.group {
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
}
|
||||
|
||||
.hint {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.representative {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto;
|
||||
gap: var(--space-3);
|
||||
align-items: end;
|
||||
padding-block: var(--space-3);
|
||||
border-bottom: var(--line-thin) solid var(--color-divider);
|
||||
}
|
||||
|
||||
.field-error,
|
||||
.action-error {
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
.action-error,
|
||||
.notice,
|
||||
.conflict {
|
||||
padding: var(--space-3);
|
||||
border-left: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.conflict {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.conflict h3 {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
@media (width < 42rem) {
|
||||
.representative {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (width < 30rem) {
|
||||
.group {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,528 @@
|
||||
import { useId, useMemo, useState, type FormEvent } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
getOrganization,
|
||||
useCreateOrganization,
|
||||
useUpdateOrganization,
|
||||
} from "../../../shared/api/endpoints/organization/organization";
|
||||
import {
|
||||
getGetCurrentSessionQueryKey,
|
||||
useGetCurrentSession,
|
||||
} from "../../../shared/api/endpoints/identity/identity";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import type { Organization, OrganizationCreate, Session } from "../../../shared/api/schemas";
|
||||
import { Button, SavingStatus } from "../../../shared/ui";
|
||||
import {
|
||||
buildCompanyCreateBody,
|
||||
buildCompanyUpdateBody,
|
||||
draftFromOrganization,
|
||||
emptyCompanyDraft,
|
||||
rebaseCompanyDraft,
|
||||
type CompanyDraft,
|
||||
} from "../../../entities/company";
|
||||
import styles from "./company-editor.module.css";
|
||||
|
||||
type CompanyEditorProps = {
|
||||
organization?: Organization | undefined;
|
||||
onSaved: (organization: Organization) => void | Promise<void>;
|
||||
onAccessLost: (error: ApiRequestError) => void;
|
||||
};
|
||||
|
||||
type CreateAttempt = {
|
||||
body: OrganizationCreate;
|
||||
key: string;
|
||||
};
|
||||
|
||||
type FieldErrors = Partial<Record<string, string>>;
|
||||
|
||||
function fieldNameForPointer(pointer: string): string | undefined {
|
||||
const fields: Readonly<Record<string, string>> = {
|
||||
"/name": "name",
|
||||
"/description": "description",
|
||||
"/sphere": "sphere",
|
||||
"/contacts/website": "website",
|
||||
"/contacts/email": "email",
|
||||
"/contacts/phone": "phone",
|
||||
"/contacts/telegram": "telegram",
|
||||
};
|
||||
const direct = fields[pointer];
|
||||
if (direct) return direct;
|
||||
if (pointer.startsWith("/representatives/")) return "representatives";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function fieldErrorsFor(error: unknown): FieldErrors {
|
||||
if (!(error instanceof ApiRequestError)) return {};
|
||||
return Object.fromEntries(
|
||||
error.fieldErrors.flatMap((field) => {
|
||||
const name = fieldNameForPointer(field.pointer);
|
||||
return name ? [[name, "Проверьте это поле и сохраните изменения снова."]] : [];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function hasDraftChanges(draft: CompanyDraft, baseline: Organization): boolean {
|
||||
return Object.keys(buildCompanyUpdateBody(draft, baseline)).some(
|
||||
(key) => key !== "expected_version",
|
||||
);
|
||||
}
|
||||
|
||||
function accessLost(error: unknown): error is ApiRequestError {
|
||||
return (
|
||||
error instanceof ApiRequestError &&
|
||||
(error.status === 401 ||
|
||||
(error.status === 403 && error.code !== "csrf_check_failed") ||
|
||||
error.status === 404)
|
||||
);
|
||||
}
|
||||
|
||||
function csrfCheckFailed(error: unknown): error is ApiRequestError {
|
||||
return (
|
||||
error instanceof ApiRequestError && error.status === 403 && error.code === "csrf_check_failed"
|
||||
);
|
||||
}
|
||||
|
||||
export function CompanyEditor({ organization, onSaved, onAccessLost }: CompanyEditorProps) {
|
||||
const id = useId();
|
||||
const queryClient = useQueryClient();
|
||||
const session = useGetCurrentSession({ query: { retry: false } });
|
||||
const sessionReady = Boolean(session.data) && !session.isFetching && !session.isError;
|
||||
const requestHeaders = session.data ? { "X-CSRF-Token": session.data.csrf_token } : {};
|
||||
const createOrganization = useCreateOrganization({
|
||||
request: { headers: requestHeaders },
|
||||
mutation: { gcTime: 0 },
|
||||
});
|
||||
const updateOrganization = useUpdateOrganization({
|
||||
request: { headers: requestHeaders },
|
||||
mutation: { gcTime: 0 },
|
||||
});
|
||||
const [baseline, setBaseline] = useState<Organization | null>(organization ?? null);
|
||||
const [draft, setDraft] = useState<CompanyDraft>(() =>
|
||||
organization ? draftFromOrganization(organization) : emptyCompanyDraft(),
|
||||
);
|
||||
const [attempt, setAttempt] = useState<CreateAttempt | null>(null);
|
||||
const [createRetryRequired, setCreateRetryRequired] = useState(false);
|
||||
const [actionError, setActionError] = useState<unknown>(null);
|
||||
const [csrfRetryMessage, setCsrfRetryMessage] = useState<string | null>(null);
|
||||
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
|
||||
const [conflict, setConflict] = useState(false);
|
||||
const [reviewRequired, setReviewRequired] = useState(false);
|
||||
const [status, setStatus] = useState<"idle" | "saving" | "saved" | "failed">("idle");
|
||||
|
||||
const creating = organization === undefined;
|
||||
const isSaving = createOrganization.isPending || updateOrganization.isPending;
|
||||
const createRequestIsFrozen = creating && attempt !== null && createRetryRequired;
|
||||
const formLocked = !sessionReady || isSaving || status === "saving" || createRequestIsFrozen;
|
||||
const hasChanges = useMemo(
|
||||
() => (baseline ? hasDraftChanges(draft, baseline) : draft.name.trim() !== ""),
|
||||
[baseline, draft],
|
||||
);
|
||||
|
||||
function updateDraft<K extends keyof CompanyDraft>(key: K, value: CompanyDraft[K]): void {
|
||||
setDraft((current) => ({ ...current, [key]: value }));
|
||||
setFieldErrors((current) => ({ ...current, [key]: undefined }));
|
||||
setActionError(null);
|
||||
setCsrfRetryMessage(null);
|
||||
setStatus("idle");
|
||||
}
|
||||
|
||||
function updateRepresentative(index: number, key: "name" | "job_title", value: string): void {
|
||||
setDraft((current) => ({
|
||||
...current,
|
||||
representatives: current.representatives.map((representative, itemIndex) =>
|
||||
itemIndex === index ? { ...representative, [key]: value } : representative,
|
||||
),
|
||||
}));
|
||||
setFieldErrors((current) => ({ ...current, representatives: undefined }));
|
||||
setActionError(null);
|
||||
setCsrfRetryMessage(null);
|
||||
setStatus("idle");
|
||||
}
|
||||
|
||||
function isSubmittingSessionCurrent(expected: Session): boolean {
|
||||
const current = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
|
||||
const state = queryClient.getQueryState(getGetCurrentSessionQueryKey());
|
||||
return Boolean(
|
||||
current &&
|
||||
state?.status === "success" &&
|
||||
current.account.id === expected.account.id &&
|
||||
current.csrf_token === expected.csrf_token,
|
||||
);
|
||||
}
|
||||
|
||||
function isSubmittingAccountCurrent(expected: Session): boolean {
|
||||
const current = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
|
||||
return current?.account.id === expected.account.id;
|
||||
}
|
||||
|
||||
async function refreshAfterCsrfFailure(expected: Session): Promise<void> {
|
||||
if (!isSubmittingAccountCurrent(expected)) return;
|
||||
setActionError(null);
|
||||
setCsrfRetryMessage("Проверяем текущий вход...");
|
||||
setStatus("failed");
|
||||
const refreshed = await session.refetch();
|
||||
if (refreshed.data?.account.id !== expected.account.id) return;
|
||||
setCsrfRetryMessage(
|
||||
refreshed.isError
|
||||
? "Не удалось проверить вход. Данные формы сохранены; повторите проверку и отправьте их снова."
|
||||
: "Проверка входа обновлена. Данные формы сохранены, повторите сохранение.",
|
||||
);
|
||||
}
|
||||
|
||||
async function saveCreate(): Promise<void> {
|
||||
const submittingSession = session.data;
|
||||
if (!sessionReady || !submittingSession || !isSubmittingSessionCurrent(submittingSession))
|
||||
return;
|
||||
let request = attempt;
|
||||
if (!request) {
|
||||
request = { body: buildCompanyCreateBody(draft), key: crypto.randomUUID() };
|
||||
setAttempt(request);
|
||||
}
|
||||
setCreateRetryRequired(true);
|
||||
setActionError(null);
|
||||
setCsrfRetryMessage(null);
|
||||
setFieldErrors({});
|
||||
setStatus("saving");
|
||||
let saved: Organization;
|
||||
try {
|
||||
saved = await createOrganization.mutateAsync({
|
||||
data: request.body,
|
||||
headers: { "Idempotency-Key": request.key },
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
if (csrfCheckFailed(error)) {
|
||||
await refreshAfterCsrfFailure(submittingSession);
|
||||
return;
|
||||
}
|
||||
if (!isSubmittingSessionCurrent(submittingSession)) return;
|
||||
if (accessLost(error)) onAccessLost(error);
|
||||
setActionError(error);
|
||||
setFieldErrors(fieldErrorsFor(error));
|
||||
setStatus("failed");
|
||||
if (error instanceof ApiRequestError && error.status === 400) {
|
||||
setAttempt(null);
|
||||
setCreateRetryRequired(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isSubmittingSessionCurrent(submittingSession)) return;
|
||||
|
||||
try {
|
||||
await onSaved(saved);
|
||||
if (!isSubmittingSessionCurrent(submittingSession)) return;
|
||||
setAttempt(null);
|
||||
setCreateRetryRequired(false);
|
||||
setStatus("saved");
|
||||
} catch (error: unknown) {
|
||||
setActionError(error);
|
||||
setStatus("failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function saveUpdate(): Promise<void> {
|
||||
if (!baseline) return;
|
||||
const submittingSession = session.data;
|
||||
if (!sessionReady || !submittingSession || !isSubmittingSessionCurrent(submittingSession))
|
||||
return;
|
||||
const body = buildCompanyUpdateBody(draft, baseline);
|
||||
if (!Object.keys(body).some((key) => key !== "expected_version")) return;
|
||||
setActionError(null);
|
||||
setCsrfRetryMessage(null);
|
||||
setFieldErrors({});
|
||||
setStatus("saving");
|
||||
try {
|
||||
const saved = await updateOrganization.mutateAsync({ orgId: baseline.id, data: body });
|
||||
if (!isSubmittingSessionCurrent(submittingSession)) return;
|
||||
setBaseline(saved);
|
||||
setDraft(draftFromOrganization(saved));
|
||||
setConflict(false);
|
||||
setReviewRequired(false);
|
||||
await onSaved(saved);
|
||||
if (!isSubmittingSessionCurrent(submittingSession)) return;
|
||||
setStatus("saved");
|
||||
} catch (error: unknown) {
|
||||
if (csrfCheckFailed(error)) {
|
||||
await refreshAfterCsrfFailure(submittingSession);
|
||||
return;
|
||||
}
|
||||
if (!isSubmittingSessionCurrent(submittingSession)) return;
|
||||
if (accessLost(error)) onAccessLost(error);
|
||||
setActionError(error);
|
||||
setFieldErrors(fieldErrorsFor(error));
|
||||
setStatus("failed");
|
||||
if (error instanceof ApiRequestError && error.status === 412) {
|
||||
setConflict(true);
|
||||
setReviewRequired(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function reloadCurrentVersion(): Promise<void> {
|
||||
if (!baseline) return;
|
||||
const submittingSession = session.data;
|
||||
if (!sessionReady || !submittingSession || !isSubmittingSessionCurrent(submittingSession))
|
||||
return;
|
||||
setActionError(null);
|
||||
try {
|
||||
const latest = await getOrganization(baseline.id);
|
||||
if (!isSubmittingSessionCurrent(submittingSession)) return;
|
||||
const rebased = rebaseCompanyDraft(draft, baseline, latest);
|
||||
setBaseline(latest);
|
||||
setDraft(rebased);
|
||||
setFieldErrors({});
|
||||
setConflict(false);
|
||||
setReviewRequired(true);
|
||||
setStatus("idle");
|
||||
} catch (error: unknown) {
|
||||
if (!isSubmittingSessionCurrent(submittingSession)) return;
|
||||
if (accessLost(error)) onAccessLost(error);
|
||||
setActionError(error);
|
||||
setStatus("failed");
|
||||
}
|
||||
}
|
||||
|
||||
function submit(event: FormEvent<HTMLFormElement>): void {
|
||||
event.preventDefault();
|
||||
if (!sessionReady || isSaving || !hasChanges || conflict || reviewRequired) return;
|
||||
if (creating) {
|
||||
void saveCreate();
|
||||
} else {
|
||||
void saveUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
const errorMessage =
|
||||
csrfRetryMessage ??
|
||||
(createRequestIsFrozen
|
||||
? "Ответ о создании не подтвержден. Повторите запрос с теми же данными, чтобы сервер вернул исходный результат."
|
||||
: actionError instanceof ApiRequestError
|
||||
? actionError.status === 412
|
||||
? "Компания изменилась в другом запросе. Черновик сохранен; прочитайте текущую версию перед повторным сохранением."
|
||||
: "Не удалось сохранить изменения. Проверьте поля и повторите попытку."
|
||||
: actionError
|
||||
? "Не удалось сохранить изменения. Проверьте подключение и повторите попытку."
|
||||
: null);
|
||||
|
||||
const nameErrorId = `${id}-name-error`;
|
||||
const descriptionErrorId = `${id}-description-error`;
|
||||
const sphereErrorId = `${id}-sphere-error`;
|
||||
const websiteErrorId = `${id}-website-error`;
|
||||
const emailErrorId = `${id}-email-error`;
|
||||
const phoneErrorId = `${id}-phone-error`;
|
||||
const telegramErrorId = `${id}-telegram-error`;
|
||||
|
||||
return (
|
||||
<form className={styles.form} onSubmit={submit} noValidate>
|
||||
{creating ? <h2 className={styles.title}>Основные данные компании</h2> : null}
|
||||
{createRequestIsFrozen ? (
|
||||
<p className={styles.notice} role="status">
|
||||
Запрос создания хранится только на этой странице. Не меняйте данные до подтверждения
|
||||
ответа.
|
||||
</p>
|
||||
) : null}
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={`${id}-name`}>Название компании</label>
|
||||
<input
|
||||
id={`${id}-name`}
|
||||
autoComplete="organization"
|
||||
required
|
||||
maxLength={200}
|
||||
value={draft.name}
|
||||
readOnly={formLocked}
|
||||
aria-invalid={Boolean(fieldErrors.name)}
|
||||
aria-describedby={fieldErrors.name ? nameErrorId : undefined}
|
||||
onChange={(event) => updateDraft("name", event.currentTarget.value)}
|
||||
/>
|
||||
{fieldErrors.name ? (
|
||||
<p className={styles["field-error"]} id={nameErrorId}>
|
||||
{fieldErrors.name}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={`${id}-description`}>Чем занимается компания</label>
|
||||
<textarea
|
||||
id={`${id}-description`}
|
||||
rows={5}
|
||||
maxLength={2000}
|
||||
value={draft.description}
|
||||
readOnly={formLocked}
|
||||
aria-invalid={Boolean(fieldErrors.description)}
|
||||
aria-describedby={fieldErrors.description ? descriptionErrorId : undefined}
|
||||
onChange={(event) => updateDraft("description", event.currentTarget.value)}
|
||||
/>
|
||||
{fieldErrors.description ? (
|
||||
<p className={styles["field-error"]} id={descriptionErrorId}>
|
||||
{fieldErrors.description}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={`${id}-sphere`}>Сфера деятельности</label>
|
||||
<input
|
||||
id={`${id}-sphere`}
|
||||
maxLength={100}
|
||||
value={draft.sphere}
|
||||
readOnly={formLocked}
|
||||
aria-invalid={Boolean(fieldErrors.sphere)}
|
||||
aria-describedby={fieldErrors.sphere ? sphereErrorId : undefined}
|
||||
onChange={(event) => updateDraft("sphere", event.currentTarget.value)}
|
||||
/>
|
||||
{fieldErrors.sphere ? (
|
||||
<p className={styles["field-error"]} id={sphereErrorId}>
|
||||
{fieldErrors.sphere}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Публичные контакты компании</legend>
|
||||
<p className={styles.hint}>
|
||||
Чтобы удалить контакт из карточки компании, оставьте соответствующее поле пустым.
|
||||
</p>
|
||||
{(
|
||||
[
|
||||
["website", "Сайт компании", "url", "https://example.com", websiteErrorId],
|
||||
["email", "Почта для связи", "email", "jobs@example.com", emailErrorId],
|
||||
["phone", "Телефон компании", "tel", "+70000000000", phoneErrorId],
|
||||
["telegram", "Telegram компании", "text", "@company", telegramErrorId],
|
||||
] as const
|
||||
).map(([key, label, type, placeholder, errorId]) => (
|
||||
<div className={styles.field} key={key}>
|
||||
<label htmlFor={`${id}-${key}`}>{label}</label>
|
||||
<input
|
||||
id={`${id}-${key}`}
|
||||
type={type}
|
||||
placeholder={placeholder}
|
||||
value={draft[key]}
|
||||
readOnly={formLocked}
|
||||
aria-invalid={Boolean(fieldErrors[key])}
|
||||
aria-describedby={fieldErrors[key] ? errorId : undefined}
|
||||
onChange={(event) => updateDraft(key, event.currentTarget.value)}
|
||||
/>
|
||||
{fieldErrors[key] ? (
|
||||
<p className={styles["field-error"]} id={errorId}>
|
||||
{fieldErrors[key]}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Представители компании</legend>
|
||||
<p className={styles.hint}>
|
||||
Добавляйте только представителей, которых компания вправе представить кандидатам.
|
||||
</p>
|
||||
{draft.representatives.map((representative, index) => (
|
||||
<div className={styles.representative} key={`representative-${index}`}>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={`${id}-representative-${index}-name`}>Имя представителя</label>
|
||||
<input
|
||||
id={`${id}-representative-${index}-name`}
|
||||
maxLength={100}
|
||||
value={representative.name}
|
||||
readOnly={formLocked}
|
||||
onChange={(event) => updateRepresentative(index, "name", event.currentTarget.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={`${id}-representative-${index}-title`}>Должность</label>
|
||||
<input
|
||||
id={`${id}-representative-${index}-title`}
|
||||
maxLength={100}
|
||||
value={representative.job_title}
|
||||
readOnly={formLocked}
|
||||
onChange={(event) =>
|
||||
updateRepresentative(index, "job_title", event.currentTarget.value)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="quiet"
|
||||
aria-label={`Удалить представителя ${index + 1}`}
|
||||
aria-disabled={formLocked || undefined}
|
||||
onClick={() =>
|
||||
updateDraft(
|
||||
"representatives",
|
||||
formLocked
|
||||
? draft.representatives
|
||||
: draft.representatives.filter((_, itemIndex) => itemIndex !== index),
|
||||
)
|
||||
}
|
||||
>
|
||||
Удалить
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
{fieldErrors.representatives ? (
|
||||
<p className={styles["field-error"]} role="alert">
|
||||
{fieldErrors.representatives}
|
||||
</p>
|
||||
) : null}
|
||||
<Button
|
||||
variant="secondary"
|
||||
aria-disabled={formLocked || draft.representatives.length >= 10 || undefined}
|
||||
onClick={() => {
|
||||
if (!formLocked && draft.representatives.length < 10) {
|
||||
updateDraft("representatives", [
|
||||
...draft.representatives,
|
||||
{ name: "", job_title: "" },
|
||||
]);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Добавить представителя
|
||||
</Button>
|
||||
</fieldset>
|
||||
|
||||
{conflict ? (
|
||||
<div className={styles.conflict} role="status">
|
||||
<h3>Компания изменилась</h3>
|
||||
<p>
|
||||
Черновик оставлен. Прочитайте текущие данные, проверьте изменения и подтвердите
|
||||
повторное сохранение.
|
||||
</p>
|
||||
<Button variant="secondary" isBusy={isSaving} onClick={() => void reloadCurrentVersion()}>
|
||||
Прочитать текущую версию
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
{reviewRequired ? (
|
||||
<div className={styles.conflict} role="status">
|
||||
<p>
|
||||
Текущая версия загружена. Ваши измененные поля сохранены в черновике; проверьте их перед
|
||||
повторной отправкой.
|
||||
</p>
|
||||
<Button variant="secondary" onClick={() => setReviewRequired(false)}>
|
||||
Я проверил черновик
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
{errorMessage ? (
|
||||
<p className={styles["action-error"]} role="alert">
|
||||
{errorMessage}
|
||||
</p>
|
||||
) : null}
|
||||
<div className={styles.actions}>
|
||||
<Button
|
||||
type="submit"
|
||||
isBusy={isSaving}
|
||||
aria-disabled={!sessionReady || !hasChanges || conflict || reviewRequired || undefined}
|
||||
>
|
||||
{isSaving
|
||||
? "Сохраняем..."
|
||||
: createRequestIsFrozen
|
||||
? "Повторить создание с теми же данными"
|
||||
: creating
|
||||
? "Создать компанию"
|
||||
: reviewRequired
|
||||
? "Сначала проверьте черновик"
|
||||
: "Сохранить изменения"}
|
||||
</Button>
|
||||
</div>
|
||||
<SavingStatus state={status} />
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { EditProfile } from "./ui/edit-profile";
|
||||
@@ -0,0 +1,61 @@
|
||||
.root {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.root > section {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.server-step,
|
||||
.form-error,
|
||||
.conflict,
|
||||
.continuation {
|
||||
min-width: 0;
|
||||
margin: 0 0 var(--space-4);
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.server-step {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.form-error,
|
||||
.conflict {
|
||||
border-width: var(--line-strong);
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.form-error {
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
|
||||
.conflict h2 {
|
||||
margin: 0 0 var(--space-2);
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.conflict p,
|
||||
.continuation p {
|
||||
margin: 0 0 var(--space-3);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.continuation {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin: var(--space-5) 0 0;
|
||||
}
|
||||
|
||||
.continuation p {
|
||||
flex: 1 1 16rem;
|
||||
margin: 0;
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useQueryClient, type UseQueryResult } from "@tanstack/react-query";
|
||||
import {
|
||||
buildCandidateProfileUpdate,
|
||||
mapProfileServerErrors,
|
||||
toCandidateProfileDraft,
|
||||
type CandidateProfileDraft,
|
||||
type ProfileFormIssue,
|
||||
} from "../../../entities/candidate";
|
||||
import { getOnboardingDestination } from "../../../entities/session";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import {
|
||||
type GetMyProfileQueryError,
|
||||
type GetMyProfileQueryResult,
|
||||
getGetMyProfileQueryKey,
|
||||
useGetMyProfile,
|
||||
useSaveMyProfile,
|
||||
} from "../../../shared/api/endpoints/candidate/candidate";
|
||||
import {
|
||||
getGetCurrentSessionQueryKey,
|
||||
useGetCurrentSession,
|
||||
} from "../../../shared/api/endpoints/identity/identity";
|
||||
import type { Account, CandidateProfile, Session } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Section,
|
||||
} from "../../../shared/ui";
|
||||
import { ProfileForm } from "./profile-form";
|
||||
import styles from "./edit-profile.module.css";
|
||||
|
||||
type OnboardingStep = Account["onboarding_step"];
|
||||
|
||||
function stepLabel(step: OnboardingStep): string {
|
||||
switch (step) {
|
||||
case "candidate_consents":
|
||||
return "Согласия";
|
||||
case "candidate_profile":
|
||||
return "Профиль";
|
||||
case "candidate_questionnaire":
|
||||
return "Анкета";
|
||||
case "candidate_assessment":
|
||||
return "Оценка навыков";
|
||||
case "employer_company":
|
||||
return "Компания";
|
||||
case "completed":
|
||||
return "Завершено";
|
||||
}
|
||||
}
|
||||
|
||||
function ProfileAccessDenied({ error }: { error: unknown }) {
|
||||
return (
|
||||
<ForbiddenState
|
||||
error={error}
|
||||
title="Профиль недоступен"
|
||||
description="Сервер не подтвердил доступ к профилю кандидата. Обновите вход или откройте подходящий кабинет."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function EditProfile() {
|
||||
const queryClient = useQueryClient();
|
||||
const profile = useGetMyProfile({
|
||||
query: {
|
||||
gcTime: 0,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
retry: false,
|
||||
},
|
||||
});
|
||||
const session = useGetCurrentSession();
|
||||
const profileAccessError =
|
||||
profile.isError &&
|
||||
profile.error instanceof ApiRequestError &&
|
||||
(profile.error.status === 401 || profile.error.status === 403)
|
||||
? profile.error
|
||||
: null;
|
||||
const sessionAccessError =
|
||||
session.isError &&
|
||||
session.error instanceof ApiRequestError &&
|
||||
(session.error.status === 401 || session.error.status === 403)
|
||||
? session.error
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!profileAccessError && !sessionAccessError) return;
|
||||
queryClient.removeQueries({ queryKey: getGetMyProfileQueryKey(), exact: true });
|
||||
}, [profileAccessError, queryClient, sessionAccessError]);
|
||||
|
||||
if (profile.isPending && !profile.data) {
|
||||
return <LoadingState label="Загружаем профиль кандидата..." />;
|
||||
}
|
||||
if (profileAccessError) {
|
||||
return <ProfileAccessDenied error={profileAccessError} />;
|
||||
}
|
||||
if (sessionAccessError) {
|
||||
return <ProfileAccessDenied error={sessionAccessError} />;
|
||||
}
|
||||
if (!profile.data) {
|
||||
if (profile.error instanceof ApiRequestError && profile.error.status === 403) {
|
||||
return <ProfileAccessDenied error={profile.error} />;
|
||||
}
|
||||
if (profile.error instanceof ApiRequestError && profile.error.status === 401) {
|
||||
return <ProfileAccessDenied error={profile.error} />;
|
||||
}
|
||||
return (
|
||||
<ErrorState
|
||||
error={profile.error}
|
||||
isRetrying={profile.isRefetching}
|
||||
onRetry={() => void profile.refetch()}
|
||||
title="Не удалось загрузить профиль"
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (!session.data) {
|
||||
if (session.error instanceof ApiRequestError && session.error.status === 403) {
|
||||
return <ProfileAccessDenied error={session.error} />;
|
||||
}
|
||||
if (session.error && !session.isFetching) {
|
||||
return (
|
||||
<ErrorState
|
||||
error={session.error}
|
||||
isRetrying={session.isRefetching}
|
||||
onRetry={() => void session.refetch()}
|
||||
title="Не удалось проверить текущий вход"
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <LoadingState label="Проверяем текущий вход..." />;
|
||||
}
|
||||
if (session.data.account.scenario !== "candidate") {
|
||||
return (
|
||||
<ForbiddenState
|
||||
title="Профиль кандидата недоступен"
|
||||
description="Войдите в кабинет, связанный со сценарием кандидата."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ProfileEditor key={session.data.account.id} profile={profile.data} profileQuery={profile} />
|
||||
);
|
||||
}
|
||||
|
||||
type ProfileQueryResult = UseQueryResult<GetMyProfileQueryResult, GetMyProfileQueryError>;
|
||||
|
||||
type ProfileEditorProps = {
|
||||
profile: CandidateProfile;
|
||||
profileQuery: ProfileQueryResult;
|
||||
};
|
||||
|
||||
function ProfileEditor({ profile, profileQuery }: ProfileEditorProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const session = useGetCurrentSession();
|
||||
const saveInFlight = useRef(false);
|
||||
const [draft, setDraft] = useState<CandidateProfileDraft>(() => toCandidateProfileDraft(profile));
|
||||
const [issues, setIssues] = useState<ProfileFormIssue[]>([]);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [savingState, setSavingState] = useState<"idle" | "saving" | "saved" | "failed">("idle");
|
||||
const [conflict, setConflict] = useState(false);
|
||||
const [latestLoadError, setLatestLoadError] = useState(false);
|
||||
const [forbidden, setForbidden] = useState(false);
|
||||
const [savedStep, setSavedStep] = useState<OnboardingStep | null>(null);
|
||||
const saveMutation = useSaveMyProfile({
|
||||
request: {
|
||||
headers: session.data ? { "X-CSRF-Token": session.data.csrf_token } : {},
|
||||
},
|
||||
mutation: { gcTime: 0 },
|
||||
});
|
||||
|
||||
const changeDraft = (next: CandidateProfileDraft) => {
|
||||
setDraft(next);
|
||||
setIssues([]);
|
||||
setFormError(null);
|
||||
setSavingState("idle");
|
||||
setSavedStep(null);
|
||||
};
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!session.data || conflict || forbidden || saveInFlight.current) return;
|
||||
const result = buildCandidateProfileUpdate(draft);
|
||||
setIssues(result.issues);
|
||||
setFormError(null);
|
||||
setSavedStep(null);
|
||||
if (!result.data) {
|
||||
setSavingState("failed");
|
||||
return;
|
||||
}
|
||||
|
||||
const submittingSession = session.data;
|
||||
const isSubmittingSessionCurrent = () => {
|
||||
const current = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
|
||||
return Boolean(
|
||||
current &&
|
||||
current.account.id === submittingSession.account.id &&
|
||||
current.csrf_token === submittingSession.csrf_token,
|
||||
);
|
||||
};
|
||||
saveInFlight.current = true;
|
||||
setSavingState("saving");
|
||||
try {
|
||||
const saved = await saveMutation.mutateAsync({ data: result.data });
|
||||
if (!isSubmittingSessionCurrent()) return;
|
||||
queryClient.setQueryData(getGetMyProfileQueryKey(), saved);
|
||||
setDraft(toCandidateProfileDraft(saved));
|
||||
setIssues([]);
|
||||
setConflict(false);
|
||||
setLatestLoadError(false);
|
||||
setSavingState("saved");
|
||||
const refreshedSession = await session.refetch();
|
||||
if (
|
||||
refreshedSession.data &&
|
||||
!refreshedSession.isError &&
|
||||
refreshedSession.data.account.id === submittingSession.account.id
|
||||
) {
|
||||
setSavedStep(refreshedSession.data.account.onboarding_step);
|
||||
} else {
|
||||
setFormError("Профиль сохранен. Не удалось проверить следующий шаг на сервере.");
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (!isSubmittingSessionCurrent()) return;
|
||||
setSavingState("failed");
|
||||
if (error instanceof ApiRequestError && error.status === 412) {
|
||||
setConflict(true);
|
||||
setLatestLoadError(false);
|
||||
const refreshed = await profileQuery.refetch();
|
||||
if (!refreshed.data || refreshed.isError) setLatestLoadError(true);
|
||||
return;
|
||||
}
|
||||
if (error instanceof ApiRequestError && error.status === 400) {
|
||||
const serverIssues = mapProfileServerErrors(error.fieldErrors);
|
||||
setIssues(serverIssues);
|
||||
setFormError(
|
||||
serverIssues.length === 0
|
||||
? "Сервер не сохранил изменения. Проверьте формат данных и повторите попытку."
|
||||
: null,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (error instanceof ApiRequestError && error.status === 403) {
|
||||
if (error.code === "csrf_check_failed") {
|
||||
const refreshed = await session.refetch();
|
||||
setFormError(
|
||||
refreshed.data
|
||||
? "Проверка входа обновлена. Данные формы сохранены, повторите сохранение."
|
||||
: "Вход больше не подтвержден. Войдите снова, чтобы продолжить работу с профилем.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
setForbidden(true);
|
||||
setFormError(
|
||||
"Сервер больше не подтверждает доступ к профилю. Изменения не были отправлены.",
|
||||
);
|
||||
void session.refetch();
|
||||
return;
|
||||
}
|
||||
if (error instanceof ApiRequestError && error.status === 401) {
|
||||
setFormError(
|
||||
"Вход больше не подтвержден. Войдите снова, чтобы продолжить работу с профилем.",
|
||||
);
|
||||
void session.refetch();
|
||||
return;
|
||||
}
|
||||
setFormError("Не удалось сохранить профиль. Проверьте подключение и повторите попытку.");
|
||||
} finally {
|
||||
saveInFlight.current = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadCurrentVersion() {
|
||||
setLatestLoadError(false);
|
||||
const refreshed = await profileQuery.refetch();
|
||||
if (!refreshed.data || refreshed.isError) {
|
||||
setLatestLoadError(true);
|
||||
return;
|
||||
}
|
||||
setDraft(toCandidateProfileDraft(refreshed.data));
|
||||
setIssues([]);
|
||||
setFormError(null);
|
||||
setConflict(false);
|
||||
setLatestLoadError(false);
|
||||
setSavedStep(null);
|
||||
setSavingState("idle");
|
||||
}
|
||||
|
||||
const currentStep = session.data?.account.onboarding_step;
|
||||
const continuation = savedStep
|
||||
? getOnboardingDestination({ scenario: "candidate", onboarding_step: savedStep })
|
||||
: null;
|
||||
const continuationLabel = savedStep ? stepLabel(savedStep) : null;
|
||||
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<Section
|
||||
title="Личные сведения"
|
||||
description="Заполните только то, что готовы указать. Профиль сохраняется на сервере и не требует резюме или внешнего аккаунта."
|
||||
>
|
||||
{currentStep ? (
|
||||
<p className={styles["server-step"]}>
|
||||
Сохраненный шаг аккаунта: <strong>{stepLabel(currentStep)}</strong>.
|
||||
</p>
|
||||
) : null}
|
||||
{conflict ? (
|
||||
<div className={styles.conflict} role="alert" aria-labelledby="profile-conflict-title">
|
||||
<h2 id="profile-conflict-title">Профиль обновлен в другом окне</h2>
|
||||
<p>
|
||||
Введенные здесь изменения не отправлены. Сравнение и автоматическое объединение не
|
||||
выполняются. При замене черновика данные из этой формы будут удалены.
|
||||
</p>
|
||||
{latestLoadError ? (
|
||||
<p>Не удалось получить текущую версию. Черновик сохранен в памяти формы.</p>
|
||||
) : null}
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={profileQuery.isRefetching}
|
||||
aria-describedby="profile-conflict-title"
|
||||
onClick={() => void loadCurrentVersion()}
|
||||
>
|
||||
{profileQuery.isRefetching
|
||||
? "Загружаем текущую версию..."
|
||||
: "Заменить черновик актуальной версией"}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
{forbidden ? (
|
||||
<div className={styles["form-error"]} role="alert">
|
||||
Профиль больше недоступен. Данные формы останутся до ухода со страницы.
|
||||
</div>
|
||||
) : null}
|
||||
{formError ? (
|
||||
<div className={styles["form-error"]} role="alert">
|
||||
{formError}
|
||||
</div>
|
||||
) : null}
|
||||
<ProfileForm
|
||||
draft={draft}
|
||||
issues={issues}
|
||||
isSaving={savingState === "saving"}
|
||||
savingState={savingState}
|
||||
onDraftChange={changeDraft}
|
||||
onSubmit={() => void handleSubmit()}
|
||||
/>
|
||||
{savedStep && continuation ? (
|
||||
<div className={styles.continuation} role="status">
|
||||
<p>Профиль сохранен. Сервер подтвердил шаг аккаунта: {continuationLabel}.</p>
|
||||
{continuation !== paths.candidate.profile ? (
|
||||
<ButtonLink to={continuation} variant="secondary">
|
||||
Открыть сохраненный шаг
|
||||
</ButtonLink>
|
||||
) : (
|
||||
<p>Серверный шаг остается «Профиль».</p>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
.form {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.editor-fields {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.editor-legend {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.issue-summary {
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-strong) solid var(--color-danger);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.issue-summary h2,
|
||||
.categories h2 {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.issue-summary ul,
|
||||
.categories ul {
|
||||
margin: var(--space-3) 0 0;
|
||||
padding-left: var(--space-5);
|
||||
}
|
||||
|
||||
.group {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
}
|
||||
|
||||
.group legend {
|
||||
max-width: 100%;
|
||||
padding-inline: var(--space-2);
|
||||
font-size: var(--font-size-l);
|
||||
font-weight: var(--font-weight-bold);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.group-description,
|
||||
.hint,
|
||||
.categories p {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.field > label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.field input,
|
||||
.field select,
|
||||
.field textarea {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
min-height: 2.75rem;
|
||||
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 textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.field input[aria-invalid="true"],
|
||||
.field select[aria-invalid="true"],
|
||||
.field textarea[aria-invalid="true"] {
|
||||
border-width: var(--line-strong);
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.overlap input {
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
margin: 0.125rem 0 0;
|
||||
}
|
||||
|
||||
.overlap input:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.field input:focus-visible,
|
||||
.field select:focus-visible,
|
||||
.field textarea:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.hint,
|
||||
.error,
|
||||
.claim-status {
|
||||
font-size: var(--font-size-s);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: var(--color-text);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.claim-status {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.suggestion {
|
||||
min-width: 0;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.suggestion summary {
|
||||
cursor: pointer;
|
||||
font-size: var(--font-size-s);
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
|
||||
.suggestion blockquote,
|
||||
.suggestion p {
|
||||
margin: var(--space-2) 0 0;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.item {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
}
|
||||
|
||||
.item-header,
|
||||
.item-actions,
|
||||
.list-row,
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.item-header {
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.item-header h3,
|
||||
.list h3,
|
||||
.overlap-list h3 {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-m);
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.list,
|
||||
.overlap-list {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.list-row {
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
.list-row > .field {
|
||||
flex: 1 1 14rem;
|
||||
}
|
||||
|
||||
.overlap {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
gap: var(--space-3);
|
||||
align-items: start;
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
}
|
||||
|
||||
.overlap label,
|
||||
.overlap p {
|
||||
margin: 0;
|
||||
line-height: var(--line-height-body);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.categories {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
}
|
||||
|
||||
.actions {
|
||||
justify-content: space-between;
|
||||
padding-top: var(--space-2);
|
||||
}
|
||||
|
||||
.actions > :first-child {
|
||||
flex: 1 1 12rem;
|
||||
}
|
||||
|
||||
@media (width < 48rem) {
|
||||
.grid {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (width < 30rem) {
|
||||
.group {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
|
||||
.item {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
|
||||
.actions {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.item-actions {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { renderToString } from "react-dom/server";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { toCandidateProfileDraft } from "../../../entities/candidate";
|
||||
import type { CandidateProfile } from "../../../shared/api/schemas";
|
||||
import { ProfileForm } from "./profile-form";
|
||||
|
||||
const emptyProfile: CandidateProfile = {
|
||||
version: 0,
|
||||
full_name: { status: "unknown", value: null, source: null },
|
||||
contacts: {
|
||||
email: { status: "unknown", value: null, source: null },
|
||||
phone: { status: "unknown", value: null, source: null },
|
||||
telegram: { status: "unknown", value: null, source: null },
|
||||
},
|
||||
stack: [],
|
||||
roles: [],
|
||||
experience: [],
|
||||
experience_overlaps: [],
|
||||
soft_skills: [],
|
||||
terms: {
|
||||
location: { status: "unknown", value: null, source: null },
|
||||
relocation: { status: "unknown", value: null, source: null },
|
||||
salary_minimum: { status: "unknown", value: null, source: null },
|
||||
},
|
||||
confirmed_categories: [],
|
||||
updated_at: null,
|
||||
};
|
||||
|
||||
function profileWithOverlap(status: "confirmed" | "needs_confirmation"): CandidateProfile {
|
||||
const source = {
|
||||
origin: "manual" as const,
|
||||
trust_level: 0 as const,
|
||||
quote: null,
|
||||
extraction_version: null,
|
||||
confirmed_at: null,
|
||||
};
|
||||
return {
|
||||
...emptyProfile,
|
||||
experience: [
|
||||
{
|
||||
employer_name: "Первая компания",
|
||||
specialization: "backend",
|
||||
started_on: "2024-01",
|
||||
ended_on: "2024-12",
|
||||
summary: null,
|
||||
status: "confirmed",
|
||||
source,
|
||||
},
|
||||
{
|
||||
employer_name: "Вторая компания",
|
||||
specialization: "frontend",
|
||||
started_on: "2024-06",
|
||||
ended_on: "2025-01",
|
||||
summary: null,
|
||||
status: "confirmed",
|
||||
source,
|
||||
},
|
||||
],
|
||||
experience_overlaps: [{ first_index: 0, second_index: 1, status }],
|
||||
};
|
||||
}
|
||||
|
||||
describe("ProfileForm", () => {
|
||||
it("renders an empty profile as editable controls without inventing claims or categories", () => {
|
||||
const html = renderToString(
|
||||
<ProfileForm
|
||||
draft={toCandidateProfileDraft(emptyProfile)}
|
||||
issues={[]}
|
||||
isSaving={false}
|
||||
savingState="idle"
|
||||
onDraftChange={vi.fn()}
|
||||
onSubmit={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain('name="full_name"');
|
||||
expect(html).toContain('name="contact_email"');
|
||||
expect(html).toContain("Добавить место работы");
|
||||
expect(html).toContain("Добавить специализацию");
|
||||
expect(html).toContain("Подтвержденных категорий пока нет.");
|
||||
expect(html).not.toContain("резюме обязательно");
|
||||
const describedIds = [...html.matchAll(/aria-describedby="([^"]+)"/g)].flatMap((match) =>
|
||||
(match[1] ?? "").split(" "),
|
||||
);
|
||||
expect(describedIds.length).toBeGreaterThan(0);
|
||||
expect(describedIds.every((id) => html.includes(`id="${id}"`))).toBe(true);
|
||||
});
|
||||
|
||||
it("renders confirmed overlap copy with a separating space and keeps new overlap confirmation explicit", () => {
|
||||
const props = {
|
||||
issues: [],
|
||||
isSaving: false,
|
||||
savingState: "idle" as const,
|
||||
onDraftChange: vi.fn(),
|
||||
onSubmit: vi.fn(),
|
||||
};
|
||||
const confirmedHtml = renderToString(
|
||||
<ProfileForm draft={toCandidateProfileDraft(profileWithOverlap("confirmed"))} {...props} />,
|
||||
);
|
||||
const unconfirmedHtml = renderToString(
|
||||
<ProfileForm
|
||||
draft={toCandidateProfileDraft(profileWithOverlap("needs_confirmation"))}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
const confirmedText = confirmedHtml.replaceAll("<!-- -->", "").replace(/\s+/g, " ");
|
||||
const unconfirmedText = unconfirmedHtml.replaceAll("<!-- -->", "").replace(/\s+/g, " ");
|
||||
|
||||
expect(confirmedText).toContain("Параллельная работа в местах 1 и 2 подтверждена ранее:");
|
||||
expect(confirmedText).not.toContain("2подтверждена ранее");
|
||||
expect(unconfirmedText).toContain(
|
||||
"Подтверждаю, что места работы 1 и 2 действительно шли параллельно:",
|
||||
);
|
||||
expect(unconfirmedText).not.toContain("подтверждена ранее");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,895 @@
|
||||
import { useId, useRef, type FormEvent, type ReactNode } from "react";
|
||||
import {
|
||||
addExperience,
|
||||
addRole,
|
||||
addSoftSkill,
|
||||
addStack,
|
||||
moveExperience,
|
||||
removeExperience,
|
||||
removeItem,
|
||||
reviewExperienceOverlaps,
|
||||
setParallelAcknowledgement,
|
||||
updateExperienceDraft,
|
||||
updateFieldDraft,
|
||||
updateRoleDraft,
|
||||
updateSalaryDraft,
|
||||
updateSoftSkillDraft,
|
||||
updateStackDraft,
|
||||
type CandidateProfileDraft,
|
||||
type ProfileFormIssue,
|
||||
} from "../../../entities/candidate";
|
||||
import type { CandidateProfile } from "../../../shared/api/schemas";
|
||||
import { Button, SavingStatus } from "../../../shared/ui";
|
||||
import styles from "./profile-form.module.css";
|
||||
|
||||
type Specialization = CandidateProfile["roles"][number]["specialization"];
|
||||
type Grade = NonNullable<CandidateProfile["roles"][number]["self_assessed_grade"]>;
|
||||
|
||||
const specializations: ReadonlyArray<{ value: Specialization; label: string }> = [
|
||||
{ value: "backend", label: "Backend" },
|
||||
{ value: "frontend", label: "Frontend" },
|
||||
{ value: "mobile", label: "Mobile" },
|
||||
{ value: "network_engineer", label: "Сетевой инженер" },
|
||||
{ value: "devops_sre", label: "DevOps / SRE" },
|
||||
{ value: "data_analyst", label: "Аналитик данных" },
|
||||
{ value: "ds_ml", label: "DS / ML" },
|
||||
{ value: "information_security", label: "Информационная безопасность" },
|
||||
{ value: "qa", label: "QA" },
|
||||
];
|
||||
|
||||
const grades: ReadonlyArray<{ value: Grade; label: string }> = [
|
||||
{ value: "intern", label: "Стажер" },
|
||||
{ value: "junior", label: "Junior" },
|
||||
{ value: "middle", label: "Middle" },
|
||||
{ value: "senior", label: "Senior" },
|
||||
];
|
||||
|
||||
type ProfileFormProps = {
|
||||
draft: CandidateProfileDraft;
|
||||
issues: readonly ProfileFormIssue[];
|
||||
isSaving: boolean;
|
||||
savingState: "idle" | "saving" | "saved" | "failed";
|
||||
onDraftChange: (draft: CandidateProfileDraft) => void;
|
||||
onSubmit: () => void;
|
||||
};
|
||||
|
||||
function errorFor(issues: readonly ProfileFormIssue[], field: string): string | undefined {
|
||||
return issues.find((issue) => issue.field === field)?.message;
|
||||
}
|
||||
|
||||
function ErrorText({ id, children }: { id: string; children?: string | undefined }) {
|
||||
return children ? (
|
||||
<p className={styles.error} id={id}>
|
||||
{children}
|
||||
</p>
|
||||
) : null;
|
||||
}
|
||||
|
||||
function Suggestion({ source }: { source: { quote: string | null; origin: string } | null }) {
|
||||
if (!source || source.origin === "manual") return null;
|
||||
const origin = source.origin === "imported" ? "Импортировано" : "Предложено из документа";
|
||||
return (
|
||||
<details className={styles.suggestion}>
|
||||
<summary>{origin}. Значение пока не подтверждено.</summary>
|
||||
{source.quote ? <blockquote>{source.quote}</blockquote> : <p>Цитата не сохранена.</p>}
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
type FieldProps = {
|
||||
id: string;
|
||||
label: string;
|
||||
error?: string | undefined;
|
||||
description?: ReactNode | undefined;
|
||||
suggestion?: { quote: string | null; origin: string } | null | undefined;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
function Field({ id, label, error, description, suggestion, children }: FieldProps) {
|
||||
return (
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={id}>{label}</label>
|
||||
{description ? (
|
||||
<p className={styles.hint} id={`${id}-hint`}>
|
||||
{description}
|
||||
</p>
|
||||
) : null}
|
||||
{children}
|
||||
{suggestion ? (
|
||||
<div id={`${id}-suggestion`}>
|
||||
<Suggestion source={suggestion} />
|
||||
</div>
|
||||
) : null}
|
||||
<ErrorText id={`${id}-error`}>{error}</ErrorText>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function describedBy(
|
||||
id: string,
|
||||
error?: string,
|
||||
suggestion?: boolean,
|
||||
hint?: boolean,
|
||||
): string | undefined {
|
||||
const values = [
|
||||
hint ? `${id}-hint` : "",
|
||||
suggestion ? `${id}-suggestion` : "",
|
||||
error ? `${id}-error` : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ");
|
||||
return values || undefined;
|
||||
}
|
||||
|
||||
function SourceLabel({ status }: { status: "confirmed" | "extracted" | "unknown" }) {
|
||||
if (status === "extracted")
|
||||
return <span className={styles["claim-status"]}>Нужно проверить</span>;
|
||||
if (status === "unknown") return <span className={styles["claim-status"]}>Не указано</span>;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function ProfileForm({
|
||||
draft,
|
||||
issues,
|
||||
isSaving,
|
||||
savingState,
|
||||
onDraftChange,
|
||||
onSubmit,
|
||||
}: ProfileFormProps) {
|
||||
const prefix = `profile-${useId().replaceAll(":", "")}`;
|
||||
const rowSequence = useRef(0);
|
||||
const newRowId = (kind: string) => `${kind}-draft-${++rowSequence.current}`;
|
||||
const fieldId = (field: string) => `${prefix}-${field.replaceAll(".", "-")}`;
|
||||
const issue = (field: string) => errorFor(issues, field);
|
||||
const setDraft = (next: CandidateProfileDraft) => onDraftChange(next);
|
||||
|
||||
function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
event.currentTarget.querySelector<HTMLButtonElement>('button[type="submit"]')?.focus();
|
||||
onSubmit();
|
||||
}
|
||||
|
||||
const overlaps = reviewExperienceOverlaps(draft);
|
||||
|
||||
return (
|
||||
<form className={styles.form} onSubmit={handleSubmit} noValidate>
|
||||
{issues.length > 0 ? (
|
||||
<div
|
||||
className={styles["issue-summary"]}
|
||||
role="alert"
|
||||
aria-labelledby={`${prefix}-issues-title`}
|
||||
>
|
||||
<h2 id={`${prefix}-issues-title`}>Проверьте профиль</h2>
|
||||
<ul>
|
||||
{issues.map((item, index) => (
|
||||
<li key={`${item.field}-${index}`}>{item.message}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<fieldset className={styles["editor-fields"]} disabled={isSaving}>
|
||||
<legend className={styles["editor-legend"]}>Данные профиля</legend>
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Имя и контакты</legend>
|
||||
<Field
|
||||
id={fieldId("fullName")}
|
||||
label="Имя и фамилия"
|
||||
error={issue("fullName")}
|
||||
suggestion={draft.fullName.source}
|
||||
>
|
||||
<input
|
||||
id={fieldId("fullName")}
|
||||
name="full_name"
|
||||
autoComplete="name"
|
||||
maxLength={200}
|
||||
value={draft.fullName.value}
|
||||
aria-invalid={Boolean(issue("fullName"))}
|
||||
aria-describedby={describedBy(
|
||||
fieldId("fullName"),
|
||||
issue("fullName"),
|
||||
Boolean(draft.fullName.source),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
setDraft({
|
||||
...draft,
|
||||
fullName: updateFieldDraft(draft.fullName, event.currentTarget.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
<SourceLabel status={draft.fullName.status} />
|
||||
</Field>
|
||||
<Field
|
||||
id={fieldId("contacts.email")}
|
||||
label="Контактный email"
|
||||
error={issue("contacts.email")}
|
||||
suggestion={draft.contacts.email.source}
|
||||
description="Это контакт профиля. Он может отличаться от адреса входа."
|
||||
>
|
||||
<input
|
||||
id={fieldId("contacts.email")}
|
||||
name="contact_email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
maxLength={254}
|
||||
value={draft.contacts.email.value}
|
||||
aria-invalid={Boolean(issue("contacts.email"))}
|
||||
aria-describedby={describedBy(
|
||||
fieldId("contacts.email"),
|
||||
issue("contacts.email"),
|
||||
Boolean(draft.contacts.email.source),
|
||||
true,
|
||||
)}
|
||||
onChange={(event) =>
|
||||
setDraft({
|
||||
...draft,
|
||||
contacts: {
|
||||
...draft.contacts,
|
||||
email: updateFieldDraft(draft.contacts.email, event.currentTarget.value),
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
<SourceLabel status={draft.contacts.email.status} />
|
||||
</Field>
|
||||
<Field
|
||||
id={fieldId("contacts.phone")}
|
||||
label="Телефон"
|
||||
error={issue("contacts.phone")}
|
||||
suggestion={draft.contacts.phone.source}
|
||||
description="Международный формат E.164, например +70000000000."
|
||||
>
|
||||
<input
|
||||
id={fieldId("contacts.phone")}
|
||||
name="contact_phone"
|
||||
type="tel"
|
||||
autoComplete="tel"
|
||||
inputMode="tel"
|
||||
maxLength={16}
|
||||
value={draft.contacts.phone.value}
|
||||
aria-invalid={Boolean(issue("contacts.phone"))}
|
||||
aria-describedby={describedBy(
|
||||
fieldId("contacts.phone"),
|
||||
issue("contacts.phone"),
|
||||
Boolean(draft.contacts.phone.source),
|
||||
true,
|
||||
)}
|
||||
onChange={(event) =>
|
||||
setDraft({
|
||||
...draft,
|
||||
contacts: {
|
||||
...draft.contacts,
|
||||
phone: updateFieldDraft(draft.contacts.phone, event.currentTarget.value),
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
<SourceLabel status={draft.contacts.phone.status} />
|
||||
</Field>
|
||||
<Field
|
||||
id={fieldId("contacts.telegram")}
|
||||
label="Telegram"
|
||||
error={issue("contacts.telegram")}
|
||||
suggestion={draft.contacts.telegram.source}
|
||||
description="Укажите имя пользователя с символом @."
|
||||
>
|
||||
<input
|
||||
id={fieldId("contacts.telegram")}
|
||||
name="contact_telegram"
|
||||
autoComplete="off"
|
||||
maxLength={33}
|
||||
value={draft.contacts.telegram.value}
|
||||
aria-invalid={Boolean(issue("contacts.telegram"))}
|
||||
aria-describedby={describedBy(
|
||||
fieldId("contacts.telegram"),
|
||||
issue("contacts.telegram"),
|
||||
Boolean(draft.contacts.telegram.source),
|
||||
true,
|
||||
)}
|
||||
onChange={(event) =>
|
||||
setDraft({
|
||||
...draft,
|
||||
contacts: {
|
||||
...draft.contacts,
|
||||
telegram: updateFieldDraft(draft.contacts.telegram, event.currentTarget.value),
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
<SourceLabel status={draft.contacts.telegram.status} />
|
||||
</Field>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Опыт работы</legend>
|
||||
<p className={styles["group-description"]}>
|
||||
Укажите специализацию и месяцы работы. Пустая дата окончания означает, что работа
|
||||
продолжается.
|
||||
</p>
|
||||
{draft.experience.map((item, index) => {
|
||||
const base = `experience.${index}`;
|
||||
const specialId = fieldId(`${base}.specialization`);
|
||||
const startId = fieldId(`${base}.started_on`);
|
||||
const endId = fieldId(`${base}.ended_on`);
|
||||
const employerId = fieldId(`${base}.employer_name`);
|
||||
const summaryId = fieldId(`${base}.summary`);
|
||||
return (
|
||||
<section
|
||||
className={styles.item}
|
||||
key={item.id}
|
||||
aria-labelledby={`${prefix}-experience-${index}-title`}
|
||||
>
|
||||
<div className={styles["item-header"]}>
|
||||
<h3 id={`${prefix}-experience-${index}-title`}>Место работы {index + 1}</h3>
|
||||
<div className={styles["item-actions"]}>
|
||||
<Button
|
||||
variant="quiet"
|
||||
aria-label={`Переместить место работы ${index + 1} выше`}
|
||||
disabled={index === 0 || isSaving}
|
||||
onClick={() => setDraft(moveExperience(draft, index, -1))}
|
||||
>
|
||||
Выше
|
||||
</Button>
|
||||
<Button
|
||||
variant="quiet"
|
||||
aria-label={`Переместить место работы ${index + 1} ниже`}
|
||||
disabled={index === draft.experience.length - 1 || isSaving}
|
||||
onClick={() => setDraft(moveExperience(draft, index, 1))}
|
||||
>
|
||||
Ниже
|
||||
</Button>
|
||||
<Button
|
||||
variant="quiet"
|
||||
aria-label={`Удалить место работы ${index + 1}`}
|
||||
disabled={isSaving}
|
||||
onClick={() => setDraft(removeExperience(draft, item.id))}
|
||||
>
|
||||
Удалить
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.grid}>
|
||||
<Field
|
||||
id={employerId}
|
||||
label="Компания"
|
||||
error={issue(`${base}.employer_name`)}
|
||||
suggestion={item.source}
|
||||
>
|
||||
<input
|
||||
id={employerId}
|
||||
value={item.employer_name ?? ""}
|
||||
maxLength={200}
|
||||
aria-invalid={Boolean(issue(`${base}.employer_name`))}
|
||||
aria-describedby={describedBy(
|
||||
employerId,
|
||||
issue(`${base}.employer_name`),
|
||||
Boolean(item.source),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
setDraft(
|
||||
updateExperienceDraft(draft, item.id, {
|
||||
employer_name: event.currentTarget.value || null,
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
id={specialId}
|
||||
label="Специализация"
|
||||
error={issue(`${base}.specialization`)}
|
||||
suggestion={item.source}
|
||||
>
|
||||
<select
|
||||
id={specialId}
|
||||
value={item.specialization}
|
||||
aria-invalid={Boolean(issue(`${base}.specialization`))}
|
||||
aria-describedby={describedBy(
|
||||
specialId,
|
||||
issue(`${base}.specialization`),
|
||||
Boolean(item.source),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
setDraft(
|
||||
updateExperienceDraft(draft, item.id, {
|
||||
specialization: event.currentTarget.value as Specialization | "",
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Выберите специализацию</option>
|
||||
{specializations.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
id={startId}
|
||||
label="Начало работы"
|
||||
error={issue(`${base}.started_on`)}
|
||||
description="Месяц и год."
|
||||
suggestion={item.source}
|
||||
>
|
||||
<input
|
||||
id={startId}
|
||||
type="month"
|
||||
value={item.started_on}
|
||||
aria-invalid={Boolean(issue(`${base}.started_on`))}
|
||||
aria-describedby={describedBy(
|
||||
startId,
|
||||
issue(`${base}.started_on`),
|
||||
Boolean(item.source),
|
||||
true,
|
||||
)}
|
||||
onChange={(event) =>
|
||||
setDraft(
|
||||
updateExperienceDraft(draft, item.id, {
|
||||
started_on: event.currentTarget.value,
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
id={endId}
|
||||
label="Окончание работы"
|
||||
error={issue(`${base}.ended_on`)}
|
||||
description="Оставьте пустым, если работаете здесь сейчас."
|
||||
suggestion={item.source}
|
||||
>
|
||||
<input
|
||||
id={endId}
|
||||
type="month"
|
||||
value={item.ended_on ?? ""}
|
||||
aria-invalid={Boolean(issue(`${base}.ended_on`))}
|
||||
aria-describedby={describedBy(
|
||||
endId,
|
||||
issue(`${base}.ended_on`),
|
||||
Boolean(item.source),
|
||||
true,
|
||||
)}
|
||||
onChange={(event) =>
|
||||
setDraft(
|
||||
updateExperienceDraft(draft, item.id, {
|
||||
ended_on: event.currentTarget.value || null,
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field id={summaryId} label="Чем занимались" error={issue(`${base}.summary`)}>
|
||||
<textarea
|
||||
id={summaryId}
|
||||
rows={3}
|
||||
maxLength={1000}
|
||||
value={item.summary ?? ""}
|
||||
aria-invalid={Boolean(issue(`${base}.summary`))}
|
||||
aria-describedby={describedBy(summaryId, issue(`${base}.summary`))}
|
||||
onChange={(event) =>
|
||||
setDraft(
|
||||
updateExperienceDraft(draft, item.id, {
|
||||
summary: event.currentTarget.value || null,
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={draft.experience.length >= 20 || isSaving}
|
||||
onClick={() => setDraft(addExperience(draft, newRowId("experience")))}
|
||||
>
|
||||
Добавить место работы
|
||||
</Button>
|
||||
{overlaps.length > 0 ? (
|
||||
<div className={styles["overlap-list"]}>
|
||||
<h3>Параллельные периоды</h3>
|
||||
<p>Совпадающие месяцы нужно подтвердить отдельно для каждой пары мест работы.</p>
|
||||
{overlaps.map((overlap) => {
|
||||
const id = `${prefix}-overlap-${overlap.key.replace(":", "-")}`;
|
||||
return (
|
||||
<div className={styles.overlap} key={overlap.key}>
|
||||
{overlap.requiresAcknowledgement ? (
|
||||
<>
|
||||
<input
|
||||
id={id}
|
||||
type="checkbox"
|
||||
checked={overlap.acknowledged}
|
||||
disabled={isSaving}
|
||||
aria-describedby={
|
||||
issue("experience.overlaps") ? `${id}-error` : undefined
|
||||
}
|
||||
onChange={(event) =>
|
||||
setDraft(
|
||||
setParallelAcknowledgement(
|
||||
draft,
|
||||
overlap.key,
|
||||
event.currentTarget.checked,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<label htmlFor={id}>
|
||||
Подтверждаю, что места работы {overlap.firstIndex + 1} и{" "}
|
||||
{overlap.secondIndex + 1} действительно шли параллельно:{" "}
|
||||
{formatPeriod(overlap.firstPeriod)} и {formatPeriod(overlap.secondPeriod)}
|
||||
.
|
||||
</label>
|
||||
</>
|
||||
) : (
|
||||
<p>
|
||||
Параллельная работа в местах {overlap.firstIndex + 1} и{" "}
|
||||
{overlap.secondIndex + 1} подтверждена ранее:{" "}
|
||||
{formatPeriod(overlap.firstPeriod)} и {formatPeriod(overlap.secondPeriod)}.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<ErrorText id={`${prefix}-experience-overlaps-error`}>
|
||||
{issue("experience.overlaps")}
|
||||
</ErrorText>
|
||||
</div>
|
||||
) : null}
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Специализация и навыки</legend>
|
||||
<p className={styles["group-description"]}>
|
||||
Самооценка остается заявлением кандидата. Подтвержденная категория появляется только
|
||||
после оценки.
|
||||
</p>
|
||||
{draft.roles.map((item, index) => {
|
||||
const base = `roles.${index}`;
|
||||
const specializationId = fieldId(`${base}.specialization`);
|
||||
const gradeId = fieldId(`${base}.self_assessed_grade`);
|
||||
return (
|
||||
<div className={styles.item} key={item.id}>
|
||||
<div className={styles["item-header"]}>
|
||||
<h3>Роль {index + 1}</h3>
|
||||
<Button
|
||||
variant="quiet"
|
||||
aria-label={`Удалить роль ${index + 1}`}
|
||||
disabled={isSaving}
|
||||
onClick={() => setDraft(removeItem(draft, "roles", item.id))}
|
||||
>
|
||||
Удалить
|
||||
</Button>
|
||||
</div>
|
||||
<div className={styles.grid}>
|
||||
<Field
|
||||
id={specializationId}
|
||||
label="Специализация"
|
||||
error={issue(`${base}.specialization`)}
|
||||
suggestion={item.source}
|
||||
>
|
||||
<select
|
||||
id={specializationId}
|
||||
value={item.specialization}
|
||||
aria-invalid={Boolean(issue(`${base}.specialization`))}
|
||||
aria-describedby={describedBy(
|
||||
specializationId,
|
||||
issue(`${base}.specialization`),
|
||||
Boolean(item.source),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
setDraft(
|
||||
updateRoleDraft(draft, item.id, {
|
||||
specialization: event.currentTarget.value as Specialization | "",
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Выберите специализацию</option>
|
||||
{specializations.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
id={gradeId}
|
||||
label="Моя оценка уровня"
|
||||
error={issue(`${base}.self_assessed_grade`)}
|
||||
suggestion={item.source}
|
||||
>
|
||||
<select
|
||||
id={gradeId}
|
||||
value={item.self_assessed_grade ?? ""}
|
||||
aria-invalid={Boolean(issue(`${base}.self_assessed_grade`))}
|
||||
aria-describedby={describedBy(
|
||||
gradeId,
|
||||
issue(`${base}.self_assessed_grade`),
|
||||
Boolean(item.source),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
setDraft(
|
||||
updateRoleDraft(draft, item.id, {
|
||||
self_assessed_grade: (event.currentTarget.value ||
|
||||
null) as Grade | null,
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Не указывать</option>
|
||||
{grades.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={draft.roles.length >= 9 || isSaving}
|
||||
onClick={() => setDraft(addRole(draft, newRowId("role")))}
|
||||
>
|
||||
Добавить специализацию
|
||||
</Button>
|
||||
|
||||
<div className={styles.list}>
|
||||
<h3>Технологии и инструменты</h3>
|
||||
{draft.stack.map((item, index) => {
|
||||
const field = `stack.${index}.tag`;
|
||||
const id = fieldId(field);
|
||||
return (
|
||||
<div className={styles["list-row"]} key={item.id}>
|
||||
<Field
|
||||
id={id}
|
||||
label={`Навык ${index + 1}`}
|
||||
error={issue(field)}
|
||||
suggestion={item.source}
|
||||
>
|
||||
<input
|
||||
id={id}
|
||||
value={item.tag}
|
||||
maxLength={50}
|
||||
aria-invalid={Boolean(issue(field))}
|
||||
aria-describedby={describedBy(id, issue(field), Boolean(item.source))}
|
||||
onChange={(event) =>
|
||||
setDraft(
|
||||
updateStackDraft(draft, item.id, { tag: event.currentTarget.value }),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Button
|
||||
variant="quiet"
|
||||
aria-label={`Удалить навык ${index + 1}`}
|
||||
disabled={isSaving}
|
||||
onClick={() => setDraft(removeItem(draft, "stack", item.id))}
|
||||
>
|
||||
Удалить
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={draft.stack.length >= 30 || isSaving}
|
||||
onClick={() => setDraft(addStack(draft, newRowId("stack")))}
|
||||
>
|
||||
Добавить навык
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className={styles.list}>
|
||||
<h3>Гибкие навыки</h3>
|
||||
{draft.softSkills.map((item, index) => {
|
||||
const field = `softSkills.${index}.skill`;
|
||||
const id = fieldId(field);
|
||||
return (
|
||||
<div className={styles["list-row"]} key={item.id}>
|
||||
<Field
|
||||
id={id}
|
||||
label={`Гибкий навык ${index + 1}`}
|
||||
error={issue(field)}
|
||||
suggestion={item.source}
|
||||
>
|
||||
<input
|
||||
id={id}
|
||||
value={item.skill}
|
||||
maxLength={50}
|
||||
aria-invalid={Boolean(issue(field))}
|
||||
aria-describedby={describedBy(id, issue(field), Boolean(item.source))}
|
||||
onChange={(event) =>
|
||||
setDraft(
|
||||
updateSoftSkillDraft(draft, item.id, {
|
||||
skill: event.currentTarget.value,
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Button
|
||||
variant="quiet"
|
||||
aria-label={`Удалить гибкий навык ${index + 1}`}
|
||||
disabled={isSaving}
|
||||
onClick={() => setDraft(removeItem(draft, "softSkills", item.id))}
|
||||
>
|
||||
Удалить
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={draft.softSkills.length >= 10 || isSaving}
|
||||
onClick={() => setDraft(addSoftSkill(draft, newRowId("soft-skill")))}
|
||||
>
|
||||
Добавить гибкий навык
|
||||
</Button>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Условия работы</legend>
|
||||
<Field
|
||||
id={fieldId("terms.location")}
|
||||
label="Желаемое место работы"
|
||||
error={issue("terms.location")}
|
||||
suggestion={draft.terms.location.source}
|
||||
>
|
||||
<input
|
||||
id={fieldId("terms.location")}
|
||||
maxLength={100}
|
||||
value={draft.terms.location.value}
|
||||
aria-invalid={Boolean(issue("terms.location"))}
|
||||
aria-describedby={describedBy(
|
||||
fieldId("terms.location"),
|
||||
issue("terms.location"),
|
||||
Boolean(draft.terms.location.source),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
setDraft({
|
||||
...draft,
|
||||
terms: {
|
||||
...draft.terms,
|
||||
location: updateFieldDraft(draft.terms.location, event.currentTarget.value),
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
id={fieldId("terms.relocation")}
|
||||
label="Готовность к переезду"
|
||||
error={issue("terms.relocation")}
|
||||
suggestion={draft.terms.relocation.source}
|
||||
>
|
||||
<select
|
||||
id={fieldId("terms.relocation")}
|
||||
value={
|
||||
draft.terms.relocation.value === null ? "" : String(draft.terms.relocation.value)
|
||||
}
|
||||
aria-invalid={Boolean(issue("terms.relocation"))}
|
||||
aria-describedby={describedBy(
|
||||
fieldId("terms.relocation"),
|
||||
issue("terms.relocation"),
|
||||
Boolean(draft.terms.relocation.source),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
setDraft({
|
||||
...draft,
|
||||
terms: {
|
||||
...draft.terms,
|
||||
relocation: updateFieldDraft(
|
||||
draft.terms.relocation,
|
||||
event.currentTarget.value === ""
|
||||
? null
|
||||
: event.currentTarget.value === "true",
|
||||
),
|
||||
},
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Не указывать</option>
|
||||
<option value="true">Да</option>
|
||||
<option value="false">Нет</option>
|
||||
</select>
|
||||
</Field>
|
||||
<div className={styles.grid}>
|
||||
<Field
|
||||
id={fieldId("terms.salaryMinimum.amount")}
|
||||
label="Минимальная зарплата, рублей в месяц"
|
||||
error={issue("terms.salaryMinimum.amount")}
|
||||
suggestion={draft.terms.salaryMinimum.source}
|
||||
description="Сумма должна быть кратна 1000."
|
||||
>
|
||||
<input
|
||||
id={fieldId("terms.salaryMinimum.amount")}
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={1000}
|
||||
max={100000000}
|
||||
step={1000}
|
||||
value={draft.terms.salaryMinimum.amount}
|
||||
aria-invalid={Boolean(issue("terms.salaryMinimum.amount"))}
|
||||
aria-describedby={describedBy(
|
||||
fieldId("terms.salaryMinimum.amount"),
|
||||
issue("terms.salaryMinimum.amount"),
|
||||
Boolean(draft.terms.salaryMinimum.source),
|
||||
true,
|
||||
)}
|
||||
onChange={(event) =>
|
||||
setDraft(updateSalaryDraft(draft, { amount: event.currentTarget.value }))
|
||||
}
|
||||
/>
|
||||
<SourceLabel status={draft.terms.salaryMinimum.status} />
|
||||
</Field>
|
||||
<Field
|
||||
id={fieldId("terms.salaryMinimum.tax_basis")}
|
||||
label="Сумма до или после налога"
|
||||
error={issue("terms.salaryMinimum.tax_basis")}
|
||||
suggestion={draft.terms.salaryMinimum.source}
|
||||
>
|
||||
<select
|
||||
id={fieldId("terms.salaryMinimum.tax_basis")}
|
||||
value={draft.terms.salaryMinimum.tax_basis}
|
||||
aria-invalid={Boolean(issue("terms.salaryMinimum.tax_basis"))}
|
||||
aria-describedby={describedBy(
|
||||
fieldId("terms.salaryMinimum.tax_basis"),
|
||||
issue("terms.salaryMinimum.tax_basis"),
|
||||
Boolean(draft.terms.salaryMinimum.source),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
setDraft(
|
||||
updateSalaryDraft(draft, {
|
||||
tax_basis: event.currentTarget.value as "net" | "gross" | "",
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Выберите</option>
|
||||
<option value="gross">До налога</option>
|
||||
<option value="net">После налога</option>
|
||||
</select>
|
||||
</Field>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<section className={styles.categories} aria-labelledby={`${prefix}-categories-title`}>
|
||||
<h2 id={`${prefix}-categories-title`}>Подтвержденные категории</h2>
|
||||
<p>Эти результаты устанавливает оценка. Их нельзя изменить в профиле.</p>
|
||||
{draft.confirmedCategories.length > 0 ? (
|
||||
<ul>
|
||||
{draft.confirmedCategories.map((category) => (
|
||||
<li key={`${category.specialization}-${category.grade}-${category.attempt_id}`}>
|
||||
{specializations.find((option) => option.value === category.specialization)
|
||||
?.label ?? category.specialization}
|
||||
,{" "}
|
||||
{grades.find((option) => option.value === category.grade)?.label ??
|
||||
category.grade}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>Подтвержденных категорий пока нет.</p>
|
||||
)}
|
||||
</section>
|
||||
</fieldset>
|
||||
|
||||
<div className={styles.actions}>
|
||||
<SavingStatus state={savingState} />
|
||||
<Button type="submit" isBusy={isSaving}>
|
||||
{isSaving ? "Сохраняем профиль..." : "Сохранить профиль"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function formatPeriod(period: { started_on: string; ended_on: string | null }): string {
|
||||
return `${period.started_on} - ${period.ended_on ?? "сейчас"}`;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { FillQuestionnaire } from "./ui/fill-questionnaire";
|
||||
@@ -0,0 +1,274 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type {
|
||||
CandidateQuestionnaire,
|
||||
ProblemFieldError,
|
||||
SpecializationCatalog,
|
||||
} from "../../../shared/api/schemas";
|
||||
import {
|
||||
addQuestionnaireSpecialization,
|
||||
addQuestionnaireStackTag,
|
||||
buildCandidateQuestionnaireUpdate,
|
||||
changeQuestionnaireSpecialization,
|
||||
mapQuestionnaireServerErrors,
|
||||
patchQuestionnaireSpecialization,
|
||||
removeQuestionnaireSpecialization,
|
||||
toQuestionnaireDraft,
|
||||
toggleQuestionnaireWorkFormat,
|
||||
} from "./questionnaire-form";
|
||||
|
||||
const catalog: SpecializationCatalog = {
|
||||
directions: [
|
||||
{
|
||||
code: "development",
|
||||
title: "Разработка",
|
||||
specializations: [
|
||||
{
|
||||
code: "backend",
|
||||
title: "Backend",
|
||||
test_availability: {
|
||||
status: "available",
|
||||
grades: ["junior"],
|
||||
task_languages: ["python", "go"],
|
||||
note: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
code: "data",
|
||||
title: "Данные",
|
||||
specializations: [
|
||||
{
|
||||
code: "ds_ml",
|
||||
title: "DS/ML",
|
||||
test_availability: {
|
||||
status: "in_development",
|
||||
grades: [],
|
||||
task_languages: [],
|
||||
note: "Банк заданий готовится.",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
grades: [
|
||||
{ code: "intern", title: "Стажер" },
|
||||
{ code: "junior", title: "Junior" },
|
||||
{ code: "middle", title: "Middle" },
|
||||
{ code: "senior", title: "Senior" },
|
||||
],
|
||||
};
|
||||
|
||||
const emptyQuestionnaire: CandidateQuestionnaire = {
|
||||
version: 0,
|
||||
specializations: [],
|
||||
work_context: null,
|
||||
updated_at: null,
|
||||
};
|
||||
|
||||
function completedDraft() {
|
||||
const base = toQuestionnaireDraft(emptyQuestionnaire);
|
||||
const item = base.specializations[0];
|
||||
if (!item) throw new Error("The empty questionnaire draft should include one editing row.");
|
||||
const selected = changeQuestionnaireSpecialization(base, item.id, "backend");
|
||||
return {
|
||||
...patchQuestionnaireSpecialization(selected, item.id, {
|
||||
selfAssessedGrade: "junior",
|
||||
taskLanguages: ["go"],
|
||||
}),
|
||||
workFormats: ["remote" as const],
|
||||
};
|
||||
}
|
||||
|
||||
describe("questionnaire form model", () => {
|
||||
it("restores server fields and the first unsaved form starts at version zero", () => {
|
||||
const empty = toQuestionnaireDraft(emptyQuestionnaire);
|
||||
expect(empty.expectedVersion).toBe(0);
|
||||
expect(empty.specializations).toHaveLength(1);
|
||||
expect(empty.specializations[0]?.specialization).toBe("");
|
||||
|
||||
const stored: CandidateQuestionnaire = {
|
||||
version: 3,
|
||||
specializations: [
|
||||
{
|
||||
specialization: "backend",
|
||||
self_assessed_grade: "junior",
|
||||
task_languages: ["go"],
|
||||
stack: ["PostgreSQL"],
|
||||
experience: { commercial_months: 12, academic_months: 6 },
|
||||
},
|
||||
],
|
||||
work_context: { work_formats: ["remote", "hybrid"] },
|
||||
updated_at: "2026-10-07T12:00:00Z",
|
||||
};
|
||||
expect(toQuestionnaireDraft(stored)).toMatchObject({
|
||||
expectedVersion: 3,
|
||||
workFormats: ["remote", "hybrid"],
|
||||
specializations: [
|
||||
{
|
||||
specialization: "backend",
|
||||
selfAssessedGrade: "junior",
|
||||
taskLanguages: ["go"],
|
||||
stack: ["PostgreSQL"],
|
||||
hasExperience: true,
|
||||
commercialMonths: "12",
|
||||
academicMonths: "6",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("builds the full Backend/Junior/Go questionnaire without requiring an FSP", () => {
|
||||
const result = buildCandidateQuestionnaireUpdate(completedDraft(), catalog);
|
||||
expect(result.issues).toEqual([]);
|
||||
expect(result.data).toEqual({
|
||||
expected_version: 0,
|
||||
specializations: [
|
||||
{
|
||||
specialization: "backend",
|
||||
self_assessed_grade: "junior",
|
||||
task_languages: ["go"],
|
||||
stack: [],
|
||||
experience: null,
|
||||
},
|
||||
],
|
||||
work_context: { work_formats: ["remote"] },
|
||||
});
|
||||
});
|
||||
|
||||
it("allows an in-development specialization as a self-assessed claim", () => {
|
||||
const base = completedDraft();
|
||||
const item = base.specializations[0];
|
||||
if (!item) throw new Error("Expected one specialization row.");
|
||||
const selected = changeQuestionnaireSpecialization(base, item.id, "ds_ml");
|
||||
const developmentDraft = patchQuestionnaireSpecialization(selected, item.id, {
|
||||
selfAssessedGrade: "senior",
|
||||
taskLanguages: [],
|
||||
});
|
||||
const result = buildCandidateQuestionnaireUpdate(developmentDraft, catalog);
|
||||
expect(result.issues).toEqual([]);
|
||||
expect(result.data?.specializations[0]).toMatchObject({
|
||||
specialization: "ds_ml",
|
||||
self_assessed_grade: "senior",
|
||||
task_languages: [],
|
||||
});
|
||||
expect(result.data?.specializations[0]).not.toHaveProperty("confirmed_grade");
|
||||
});
|
||||
|
||||
it("rejects duplicate specializations, unavailable languages, and invalid months", () => {
|
||||
const base = completedDraft();
|
||||
const first = base.specializations[0];
|
||||
if (!first) throw new Error("Expected one specialization row.");
|
||||
let draft = addQuestionnaireSpecialization(base, "new-second");
|
||||
draft = changeQuestionnaireSpecialization(draft, "new-second", "backend");
|
||||
draft = patchQuestionnaireSpecialization(draft, "new-second", {
|
||||
selfAssessedGrade: "junior",
|
||||
});
|
||||
draft = patchQuestionnaireSpecialization(draft, first.id, {
|
||||
hasExperience: true,
|
||||
commercialMonths: "601",
|
||||
academicMonths: "-1",
|
||||
taskLanguages: ["python"],
|
||||
});
|
||||
const restrictedCatalog: SpecializationCatalog = {
|
||||
...catalog,
|
||||
directions: catalog.directions.map((direction) => ({
|
||||
...direction,
|
||||
specializations: direction.specializations.map((specialization) =>
|
||||
specialization.code === "backend"
|
||||
? {
|
||||
...specialization,
|
||||
test_availability: {
|
||||
...specialization.test_availability,
|
||||
task_languages: ["go"],
|
||||
},
|
||||
}
|
||||
: specialization,
|
||||
),
|
||||
})),
|
||||
};
|
||||
const result = buildCandidateQuestionnaireUpdate(draft, restrictedCatalog);
|
||||
expect(result.data).toBeNull();
|
||||
expect(result.issues.map((issue) => issue.field)).toContain("specializations.1.specialization");
|
||||
expect(result.issues.map((issue) => issue.field)).toContain(
|
||||
"specializations.0.commercialMonths",
|
||||
);
|
||||
expect(result.issues.map((issue) => issue.field)).toContain("specializations.0.academicMonths");
|
||||
expect(result.issues.map((issue) => issue.field)).toContain("specializations.0.taskLanguages");
|
||||
});
|
||||
|
||||
it("resets specialization-specific answers when the candidate changes the selected discipline", () => {
|
||||
const base = completedDraft();
|
||||
const item = base.specializations[0];
|
||||
if (!item) throw new Error("Expected one specialization row.");
|
||||
const changed = patchQuestionnaireSpecialization(base, item.id, {
|
||||
stack: ["Go"],
|
||||
hasExperience: true,
|
||||
commercialMonths: "15",
|
||||
academicMonths: "0",
|
||||
});
|
||||
const changedSpecialization = changeQuestionnaireSpecialization(changed, item.id, "ds_ml");
|
||||
expect(changedSpecialization.specializations[0]).toMatchObject({
|
||||
specialization: "ds_ml",
|
||||
stack: [],
|
||||
hasExperience: false,
|
||||
commercialMonths: "",
|
||||
academicMonths: "",
|
||||
selfAssessedGrade: "",
|
||||
taskLanguages: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps one or two specialization rows and at most three work formats", () => {
|
||||
let draft = toQuestionnaireDraft(emptyQuestionnaire);
|
||||
draft = addQuestionnaireSpecialization(draft, "second");
|
||||
expect(draft.specializations).toHaveLength(2);
|
||||
expect(addQuestionnaireSpecialization(draft, "third")).toBe(draft);
|
||||
draft = removeQuestionnaireSpecialization(draft, "second");
|
||||
expect(draft.specializations).toHaveLength(1);
|
||||
expect(removeQuestionnaireSpecialization(draft, draft.specializations[0]?.id ?? "")).toBe(
|
||||
draft,
|
||||
);
|
||||
|
||||
draft = toggleQuestionnaireWorkFormat(draft, "remote");
|
||||
draft = toggleQuestionnaireWorkFormat(draft, "office");
|
||||
draft = toggleQuestionnaireWorkFormat(draft, "hybrid");
|
||||
expect(toggleQuestionnaireWorkFormat(draft, "remote").workFormats).toEqual([
|
||||
"office",
|
||||
"hybrid",
|
||||
]);
|
||||
expect(toggleQuestionnaireWorkFormat(draft, "office").workFormats).toEqual([
|
||||
"remote",
|
||||
"hybrid",
|
||||
]);
|
||||
});
|
||||
|
||||
it("adds normalized stack tags and maps server pointers to the matching form field", () => {
|
||||
const base = completedDraft();
|
||||
const item = base.specializations[0];
|
||||
if (!item) throw new Error("Expected one specialization row.");
|
||||
const withInput = patchQuestionnaireSpecialization(base, item.id, { stackInput: " Go " });
|
||||
const added = addQuestionnaireStackTag(withInput, item.id);
|
||||
expect(added.issue).toBeNull();
|
||||
expect(added.draft.specializations[0]?.stack).toEqual(["Go"]);
|
||||
|
||||
const serverErrors: ProblemFieldError[] = [
|
||||
{
|
||||
in: "body",
|
||||
pointer: "/specializations/0/task_languages/0",
|
||||
code: "invalid",
|
||||
message: "invalid",
|
||||
},
|
||||
{
|
||||
in: "body",
|
||||
pointer: "/work_context/work_formats/0",
|
||||
code: "invalid",
|
||||
message: "invalid",
|
||||
},
|
||||
];
|
||||
expect(mapQuestionnaireServerErrors(serverErrors).map((issue) => issue.field)).toEqual([
|
||||
"specializations.0.taskLanguages",
|
||||
"workFormats",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,361 @@
|
||||
import {
|
||||
CandidateQuestionnaireUpdate as CandidateQuestionnaireUpdateSchema,
|
||||
type CandidateQuestionnaire,
|
||||
type CandidateQuestionnaireUpdate,
|
||||
type ProblemFieldError,
|
||||
type SpecializationCatalog,
|
||||
type SpecializationCode,
|
||||
type TaskLanguage,
|
||||
type WorkFormat,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { findSpecializationOption } from "../../../entities/specialization";
|
||||
|
||||
type QuestionnaireAnswer = CandidateQuestionnaireUpdate["specializations"][number];
|
||||
type GradeCode = QuestionnaireAnswer["self_assessed_grade"];
|
||||
|
||||
export type QuestionnaireSpecializationDraft = {
|
||||
id: string;
|
||||
specialization: SpecializationCode | "";
|
||||
selfAssessedGrade: GradeCode | "";
|
||||
taskLanguages: TaskLanguage[];
|
||||
stack: string[];
|
||||
stackInput: string;
|
||||
hasExperience: boolean;
|
||||
commercialMonths: string;
|
||||
academicMonths: string;
|
||||
};
|
||||
|
||||
export type QuestionnaireDraft = {
|
||||
expectedVersion: number;
|
||||
specializations: QuestionnaireSpecializationDraft[];
|
||||
workFormats: WorkFormat[];
|
||||
};
|
||||
|
||||
export type QuestionnaireFormIssue = { field: string; message: string };
|
||||
|
||||
export type QuestionnaireBuildResult = {
|
||||
data: CandidateQuestionnaireUpdate | null;
|
||||
issues: QuestionnaireFormIssue[];
|
||||
};
|
||||
|
||||
export function createQuestionnaireSpecializationDraft(
|
||||
id: string,
|
||||
): QuestionnaireSpecializationDraft {
|
||||
return {
|
||||
id,
|
||||
specialization: "",
|
||||
selfAssessedGrade: "",
|
||||
taskLanguages: [],
|
||||
stack: [],
|
||||
stackInput: "",
|
||||
hasExperience: false,
|
||||
commercialMonths: "",
|
||||
academicMonths: "",
|
||||
};
|
||||
}
|
||||
|
||||
export function toQuestionnaireDraft(questionnaire: CandidateQuestionnaire): QuestionnaireDraft {
|
||||
const specializations = questionnaire.specializations.map((answer, index) => ({
|
||||
id: `saved-${index}-${answer.specialization}`,
|
||||
specialization: answer.specialization,
|
||||
selfAssessedGrade: answer.self_assessed_grade,
|
||||
taskLanguages: [...answer.task_languages],
|
||||
stack: [...answer.stack],
|
||||
stackInput: "",
|
||||
hasExperience: answer.experience !== null,
|
||||
commercialMonths: answer.experience === null ? "" : String(answer.experience.commercial_months),
|
||||
academicMonths: answer.experience === null ? "" : String(answer.experience.academic_months),
|
||||
}));
|
||||
|
||||
return {
|
||||
expectedVersion: questionnaire.version,
|
||||
specializations:
|
||||
specializations.length > 0
|
||||
? specializations
|
||||
: [createQuestionnaireSpecializationDraft("new-0")],
|
||||
workFormats: questionnaire.work_context ? [...questionnaire.work_context.work_formats] : [],
|
||||
};
|
||||
}
|
||||
|
||||
export function changeQuestionnaireSpecialization(
|
||||
draft: QuestionnaireDraft,
|
||||
id: string,
|
||||
specialization: SpecializationCode | "",
|
||||
): QuestionnaireDraft {
|
||||
return {
|
||||
...draft,
|
||||
specializations: draft.specializations.map((item) =>
|
||||
item.id === id ? { ...createQuestionnaireSpecializationDraft(id), specialization } : item,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function patchQuestionnaireSpecialization(
|
||||
draft: QuestionnaireDraft,
|
||||
id: string,
|
||||
patch: Partial<Omit<QuestionnaireSpecializationDraft, "id" | "specialization">>,
|
||||
): QuestionnaireDraft {
|
||||
return {
|
||||
...draft,
|
||||
specializations: draft.specializations.map((item) =>
|
||||
item.id === id ? { ...item, ...patch } : item,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function addQuestionnaireSpecialization(
|
||||
draft: QuestionnaireDraft,
|
||||
id: string,
|
||||
): QuestionnaireDraft {
|
||||
if (draft.specializations.length >= 2) return draft;
|
||||
return {
|
||||
...draft,
|
||||
specializations: [...draft.specializations, createQuestionnaireSpecializationDraft(id)],
|
||||
};
|
||||
}
|
||||
|
||||
export function removeQuestionnaireSpecialization(
|
||||
draft: QuestionnaireDraft,
|
||||
id: string,
|
||||
): QuestionnaireDraft {
|
||||
if (draft.specializations.length <= 1) return draft;
|
||||
return {
|
||||
...draft,
|
||||
specializations: draft.specializations.filter((item) => item.id !== id),
|
||||
};
|
||||
}
|
||||
|
||||
export function toggleQuestionnaireWorkFormat(
|
||||
draft: QuestionnaireDraft,
|
||||
format: WorkFormat,
|
||||
): QuestionnaireDraft {
|
||||
const selected = draft.workFormats.includes(format);
|
||||
if (selected) {
|
||||
return { ...draft, workFormats: draft.workFormats.filter((item) => item !== format) };
|
||||
}
|
||||
if (draft.workFormats.length >= 3) return draft;
|
||||
return { ...draft, workFormats: [...draft.workFormats, format] };
|
||||
}
|
||||
|
||||
export function addQuestionnaireStackTag(
|
||||
draft: QuestionnaireDraft,
|
||||
id: string,
|
||||
): { draft: QuestionnaireDraft; issue: QuestionnaireFormIssue | null } {
|
||||
const item = draft.specializations.find((specialization) => specialization.id === id);
|
||||
if (!item) return { draft, issue: null };
|
||||
const tag = item.stackInput.trim();
|
||||
const field = `specializations.${draft.specializations.indexOf(item)}.stack`;
|
||||
if (!tag) return { draft, issue: { field, message: "Введите название технологии." } };
|
||||
if (Array.from(tag).length > 50) {
|
||||
return {
|
||||
draft,
|
||||
issue: { field, message: "Название технологии должно быть не длиннее 50 символов." },
|
||||
};
|
||||
}
|
||||
if (/[\r\n]/.test(tag)) {
|
||||
return { draft, issue: { field, message: "Укажите одну технологию в одной строке." } };
|
||||
}
|
||||
if (item.stack.some((existing) => existing.toLowerCase() === tag.toLowerCase())) {
|
||||
return { draft, issue: { field, message: "Эта технология уже добавлена." } };
|
||||
}
|
||||
if (item.stack.length >= 20) {
|
||||
return { draft, issue: { field, message: "Можно добавить не больше 20 технологий." } };
|
||||
}
|
||||
return {
|
||||
draft: patchQuestionnaireSpecialization(draft, id, {
|
||||
stack: [...item.stack, tag],
|
||||
stackInput: "",
|
||||
}),
|
||||
issue: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function removeQuestionnaireStackTag(
|
||||
draft: QuestionnaireDraft,
|
||||
id: string,
|
||||
tag: string,
|
||||
): QuestionnaireDraft {
|
||||
const item = draft.specializations.find((specialization) => specialization.id === id);
|
||||
if (!item) return draft;
|
||||
return patchQuestionnaireSpecialization(draft, id, {
|
||||
stack: item.stack.filter((value) => value !== tag),
|
||||
});
|
||||
}
|
||||
|
||||
function parseMonths(
|
||||
value: string,
|
||||
field: string,
|
||||
issues: QuestionnaireFormIssue[],
|
||||
): number | null {
|
||||
if (!/^\d+$/.test(value)) {
|
||||
issues.push({ field, message: "Укажите целое число месяцев от 0 до 600." });
|
||||
return null;
|
||||
}
|
||||
const months = Number(value);
|
||||
if (!Number.isSafeInteger(months) || months > 600) {
|
||||
issues.push({ field, message: "Укажите целое число месяцев от 0 до 600." });
|
||||
return null;
|
||||
}
|
||||
return months;
|
||||
}
|
||||
|
||||
export function buildCandidateQuestionnaireUpdate(
|
||||
draft: QuestionnaireDraft,
|
||||
catalog: SpecializationCatalog,
|
||||
expectedVersion = draft.expectedVersion,
|
||||
): QuestionnaireBuildResult {
|
||||
const issues: QuestionnaireFormIssue[] = [];
|
||||
const specializations: QuestionnaireAnswer[] = [];
|
||||
const seenSpecializations = new Set<SpecializationCode>();
|
||||
|
||||
if (draft.specializations.length < 1 || draft.specializations.length > 2) {
|
||||
issues.push({ field: "specializations", message: "Выберите одну или две специализации." });
|
||||
}
|
||||
|
||||
draft.specializations.forEach((item, index) => {
|
||||
const base = `specializations.${index}`;
|
||||
if (!item.specialization) {
|
||||
issues.push({ field: `${base}.specialization`, message: "Выберите специализацию." });
|
||||
return;
|
||||
}
|
||||
if (seenSpecializations.has(item.specialization)) {
|
||||
issues.push({ field: `${base}.specialization`, message: "Эта специализация уже выбрана." });
|
||||
return;
|
||||
}
|
||||
seenSpecializations.add(item.specialization);
|
||||
|
||||
const option = findSpecializationOption(catalog, item.specialization);
|
||||
if (!option) {
|
||||
issues.push({
|
||||
field: `${base}.specialization`,
|
||||
message: "Выберите специализацию из каталога.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!item.selfAssessedGrade) {
|
||||
issues.push({ field: `${base}.selfAssessedGrade`, message: "Укажите свою оценку уровня." });
|
||||
return;
|
||||
}
|
||||
|
||||
const languagesAllowed = new Set(option.test_availability.task_languages);
|
||||
item.taskLanguages.forEach((language, languageIndex) => {
|
||||
if (!languagesAllowed.has(language)) {
|
||||
issues.push({
|
||||
field: `${base}.taskLanguages`,
|
||||
message:
|
||||
"Выбранный язык заданий больше не предлагается. Снимите этот выбор перед сохранением.",
|
||||
});
|
||||
}
|
||||
if (item.taskLanguages.indexOf(language) !== languageIndex) {
|
||||
issues.push({
|
||||
field: `${base}.taskLanguages`,
|
||||
message: "Не выбирайте язык заданий повторно.",
|
||||
});
|
||||
}
|
||||
});
|
||||
if (item.taskLanguages.length > 2) {
|
||||
issues.push({
|
||||
field: `${base}.taskLanguages`,
|
||||
message: "Выберите не больше двух языков заданий.",
|
||||
});
|
||||
}
|
||||
|
||||
const seenStack = new Set<string>();
|
||||
item.stack.forEach((tag, tagIndex) => {
|
||||
const tagField = `${base}.stack.${tagIndex}`;
|
||||
if (!tag || tag !== tag.trim() || /[\r\n]/.test(tag) || Array.from(tag).length > 50) {
|
||||
issues.push({
|
||||
field: tagField,
|
||||
message: "Проверьте название технологии: до 50 символов, без пробелов по краям.",
|
||||
});
|
||||
}
|
||||
const normalized = tag.toLowerCase();
|
||||
if (seenStack.has(normalized)) {
|
||||
issues.push({ field: tagField, message: "Эта технология уже добавлена." });
|
||||
}
|
||||
seenStack.add(normalized);
|
||||
});
|
||||
if (item.stack.length > 20) {
|
||||
issues.push({ field: `${base}.stack`, message: "Можно добавить не больше 20 технологий." });
|
||||
}
|
||||
|
||||
let experience: QuestionnaireAnswer["experience"] = null;
|
||||
if (item.hasExperience) {
|
||||
const commercialMonths = parseMonths(
|
||||
item.commercialMonths,
|
||||
`${base}.commercialMonths`,
|
||||
issues,
|
||||
);
|
||||
const academicMonths = parseMonths(item.academicMonths, `${base}.academicMonths`, issues);
|
||||
if (commercialMonths !== null && academicMonths !== null) {
|
||||
experience = { commercial_months: commercialMonths, academic_months: academicMonths };
|
||||
}
|
||||
}
|
||||
|
||||
specializations.push({
|
||||
specialization: item.specialization,
|
||||
self_assessed_grade: item.selfAssessedGrade,
|
||||
task_languages: [...item.taskLanguages],
|
||||
stack: [...item.stack],
|
||||
experience,
|
||||
});
|
||||
});
|
||||
|
||||
if (draft.workFormats.length < 1 || draft.workFormats.length > 3) {
|
||||
issues.push({ field: "workFormats", message: "Выберите от одного до трех форматов работы." });
|
||||
}
|
||||
if (new Set(draft.workFormats).size !== draft.workFormats.length) {
|
||||
issues.push({ field: "workFormats", message: "Не выбирайте формат работы повторно." });
|
||||
}
|
||||
|
||||
if (issues.length > 0) return { data: null, issues };
|
||||
|
||||
const candidate: CandidateQuestionnaireUpdate = {
|
||||
expected_version: expectedVersion,
|
||||
specializations,
|
||||
work_context: { work_formats: [...draft.workFormats] },
|
||||
};
|
||||
const parsed = CandidateQuestionnaireUpdateSchema.safeParse(candidate);
|
||||
if (!parsed.success) {
|
||||
return {
|
||||
data: null,
|
||||
issues: parsed.error.issues.map((issue) => ({
|
||||
field: issue.path.join("."),
|
||||
message: "Проверьте это значение.",
|
||||
})),
|
||||
};
|
||||
}
|
||||
return { data: parsed.data, issues: [] };
|
||||
}
|
||||
|
||||
function fieldForPointer(pointer: string): string {
|
||||
const match = /^\/specializations\/(\d+)(?:\/([^/]+))?/.exec(pointer);
|
||||
if (match) {
|
||||
const [, index, property] = match;
|
||||
switch (property) {
|
||||
case "specialization":
|
||||
return `specializations.${index}.specialization`;
|
||||
case "self_assessed_grade":
|
||||
return `specializations.${index}.selfAssessedGrade`;
|
||||
case "task_languages":
|
||||
return `specializations.${index}.taskLanguages`;
|
||||
case "stack":
|
||||
return `specializations.${index}.stack`;
|
||||
case "experience":
|
||||
return `specializations.${index}.experience`;
|
||||
default:
|
||||
return `specializations.${index}`;
|
||||
}
|
||||
}
|
||||
if (pointer.startsWith("/work_context/work_formats")) return "workFormats";
|
||||
return "form";
|
||||
}
|
||||
|
||||
export function mapQuestionnaireServerErrors(
|
||||
errors: readonly ProblemFieldError[],
|
||||
): QuestionnaireFormIssue[] {
|
||||
return errors.map((error) => ({
|
||||
field: fieldForPointer(error.pointer),
|
||||
message: "Сервер не принял это значение. Проверьте выбор и повторите сохранение.",
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { CandidateQuestionnaire, Session } from "../../../shared/api/schemas";
|
||||
import { activeSessionMatches, storeQuestionnaireForActiveSession } from "./session-guard";
|
||||
|
||||
const session: Session = {
|
||||
account: {
|
||||
id: "22b209a8-8715-4ad5-a9b0-d93a18fc70a4",
|
||||
email: "candidate@example.test",
|
||||
email_verified: true,
|
||||
scenario: "candidate",
|
||||
onboarding_step: "candidate_questionnaire",
|
||||
created_at: "2026-10-07T12:00:00Z",
|
||||
},
|
||||
csrf_token: "a".repeat(32),
|
||||
};
|
||||
|
||||
const otherSession: Session = {
|
||||
...session,
|
||||
account: {
|
||||
...session.account,
|
||||
id: "36acbba3-d786-4c3a-95b2-4c374ab3206e",
|
||||
email: "other@example.test",
|
||||
},
|
||||
csrf_token: "b".repeat(32),
|
||||
};
|
||||
|
||||
const questionnaire: CandidateQuestionnaire = {
|
||||
version: 1,
|
||||
specializations: [],
|
||||
work_context: null,
|
||||
updated_at: "2026-10-07T12:00:00Z",
|
||||
};
|
||||
|
||||
describe("questionnaire session guard", () => {
|
||||
it("rejects cached session data after its query enters an error state", () => {
|
||||
expect(
|
||||
activeSessionMatches(
|
||||
{
|
||||
data: session,
|
||||
status: "error",
|
||||
},
|
||||
session,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not write a late save response after the active account changes", () => {
|
||||
const queryClient = new QueryClient();
|
||||
const sessionKey = ["/api/v1/identity/sessions/current"];
|
||||
const firstQuestionnaireKey = ["/api/v1/me/questionnaire", session.account.id];
|
||||
const currentQuestionnaireKey = ["/api/v1/me/questionnaire", otherSession.account.id];
|
||||
queryClient.setQueryData(sessionKey, session);
|
||||
queryClient.setQueryData(currentQuestionnaireKey, questionnaire);
|
||||
|
||||
queryClient.setQueryData(sessionKey, otherSession);
|
||||
const stored = storeQuestionnaireForActiveSession(
|
||||
queryClient,
|
||||
sessionKey,
|
||||
session,
|
||||
firstQuestionnaireKey,
|
||||
questionnaire,
|
||||
);
|
||||
|
||||
expect(stored).toBe(false);
|
||||
expect(queryClient.getQueryData(firstQuestionnaireKey)).toBeUndefined();
|
||||
expect(queryClient.getQueryData(currentQuestionnaireKey)).toEqual(questionnaire);
|
||||
});
|
||||
|
||||
it("accepts the same actor during a background session refetch", () => {
|
||||
const state = {
|
||||
data: session,
|
||||
status: "success",
|
||||
fetchStatus: "fetching",
|
||||
isInvalidated: true,
|
||||
} as const;
|
||||
|
||||
expect(activeSessionMatches(state, session)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a different actor or a rotated CSRF token", () => {
|
||||
const state = {
|
||||
data: session,
|
||||
status: "success",
|
||||
fetchStatus: "fetching",
|
||||
isInvalidated: true,
|
||||
} as const;
|
||||
|
||||
expect(activeSessionMatches(state, otherSession)).toBe(false);
|
||||
expect(
|
||||
activeSessionMatches({ ...state, data: { ...session, csrf_token: "c".repeat(32) } }, session),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { QueryClient, QueryKey, QueryState } from "@tanstack/react-query";
|
||||
import type { CandidateQuestionnaire, Session } from "../../../shared/api/schemas";
|
||||
|
||||
type SessionQuerySnapshot = Pick<QueryState<Session, Error>, "data" | "status">;
|
||||
|
||||
export function activeSessionMatches(
|
||||
snapshot: SessionQuerySnapshot | undefined,
|
||||
actor: Session,
|
||||
): boolean {
|
||||
return Boolean(
|
||||
snapshot &&
|
||||
snapshot.status === "success" &&
|
||||
snapshot.data &&
|
||||
snapshot.data.account.id === actor.account.id &&
|
||||
snapshot.data.csrf_token === actor.csrf_token,
|
||||
);
|
||||
}
|
||||
|
||||
export function storeQuestionnaireForActiveSession(
|
||||
queryClient: QueryClient,
|
||||
sessionQueryKey: QueryKey,
|
||||
actor: Session,
|
||||
questionnaireQueryKey: QueryKey,
|
||||
questionnaire: CandidateQuestionnaire,
|
||||
): boolean {
|
||||
if (!activeSessionMatches(queryClient.getQueryState<Session>(sessionQueryKey), actor)) {
|
||||
return false;
|
||||
}
|
||||
queryClient.setQueryData(questionnaireQueryKey, questionnaire);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
.root {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.root > section {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.server-step,
|
||||
.warning,
|
||||
.form-error,
|
||||
.conflict,
|
||||
.continuation {
|
||||
min-width: 0;
|
||||
margin: 0 0 var(--space-4);
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.server-step {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.warning,
|
||||
.form-error,
|
||||
.conflict {
|
||||
border-width: var(--line-strong);
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.warning,
|
||||
.conflict {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.warning p,
|
||||
.conflict p,
|
||||
.continuation p {
|
||||
margin: 0;
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.conflict h2 {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.conflict-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.continuation {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin: var(--space-5) 0 0;
|
||||
}
|
||||
|
||||
.continuation p {
|
||||
flex: 1 1 16rem;
|
||||
}
|
||||
@@ -0,0 +1,547 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useQueryClient, type QueryKey, type UseQueryResult } from "@tanstack/react-query";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import {
|
||||
type GetMyQuestionnaireQueryError,
|
||||
type GetMyQuestionnaireQueryResult,
|
||||
getGetMyQuestionnaireQueryKey,
|
||||
useGetMyQuestionnaire,
|
||||
useSaveMyQuestionnaire,
|
||||
} from "../../../shared/api/endpoints/candidate/candidate";
|
||||
import {
|
||||
type GetSpecializationCatalogQueryError,
|
||||
type GetSpecializationCatalogQueryResult,
|
||||
useGetSpecializationCatalog,
|
||||
} from "../../../shared/api/endpoints/catalog/catalog";
|
||||
import {
|
||||
type GetCurrentSessionQueryError,
|
||||
type GetCurrentSessionQueryResult,
|
||||
getGetCurrentSessionQueryKey,
|
||||
useGetCurrentSession,
|
||||
} from "../../../shared/api/endpoints/identity/identity";
|
||||
import type {
|
||||
Account,
|
||||
CandidateQuestionnaire,
|
||||
Session,
|
||||
SpecializationCatalog,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Section,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
buildCandidateQuestionnaireUpdate,
|
||||
mapQuestionnaireServerErrors,
|
||||
toQuestionnaireDraft,
|
||||
type QuestionnaireDraft,
|
||||
type QuestionnaireFormIssue,
|
||||
} from "../model/questionnaire-form";
|
||||
import { activeSessionMatches, storeQuestionnaireForActiveSession } from "../model/session-guard";
|
||||
import { QuestionnaireForm } from "./questionnaire-form";
|
||||
import styles from "./fill-questionnaire.module.css";
|
||||
|
||||
type QuestionnaireQuery = UseQueryResult<
|
||||
GetMyQuestionnaireQueryResult,
|
||||
GetMyQuestionnaireQueryError
|
||||
>;
|
||||
type CatalogQuery = UseQueryResult<
|
||||
GetSpecializationCatalogQueryResult,
|
||||
GetSpecializationCatalogQueryError
|
||||
>;
|
||||
type SessionQuery = UseQueryResult<GetCurrentSessionQueryResult, GetCurrentSessionQueryError>;
|
||||
type OnboardingStep = Account["onboarding_step"];
|
||||
|
||||
function stepLabel(step: OnboardingStep): string {
|
||||
switch (step) {
|
||||
case "candidate_consents":
|
||||
return "Согласия";
|
||||
case "candidate_profile":
|
||||
return "Профиль";
|
||||
case "candidate_questionnaire":
|
||||
return "Анкета";
|
||||
case "candidate_assessment":
|
||||
return "Оценка навыков";
|
||||
case "employer_company":
|
||||
return "Компания";
|
||||
case "completed":
|
||||
return "Завершено";
|
||||
}
|
||||
}
|
||||
|
||||
function isAccessError(error: unknown): error is ApiRequestError {
|
||||
return error instanceof ApiRequestError && (error.status === 401 || error.status === 403);
|
||||
}
|
||||
|
||||
function actorMatches(queryClient: ReturnType<typeof useQueryClient>, actor: Session): boolean {
|
||||
return activeSessionMatches(
|
||||
queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey()),
|
||||
actor,
|
||||
);
|
||||
}
|
||||
|
||||
export function FillQuestionnaire() {
|
||||
const queryClient = useQueryClient();
|
||||
const session = useGetCurrentSession();
|
||||
const accountId = session.data?.account.id ?? null;
|
||||
const accountIsCandidate = session.data?.account.scenario === "candidate";
|
||||
const [deniedActor, setDeniedActor] = useState<{ accountId: string; csrfToken: string } | null>(
|
||||
null,
|
||||
);
|
||||
const actorIsDenied = Boolean(
|
||||
session.data &&
|
||||
deniedActor?.accountId === session.data.account.id &&
|
||||
deniedActor.csrfToken === session.data.csrf_token,
|
||||
);
|
||||
const questionnaireQueryKey: QueryKey = accountId
|
||||
? [...getGetMyQuestionnaireQueryKey(), accountId]
|
||||
: [...getGetMyQuestionnaireQueryKey(), "anonymous"];
|
||||
const questionnaire = useGetMyQuestionnaire({
|
||||
query: {
|
||||
queryKey: questionnaireQueryKey,
|
||||
enabled: Boolean(accountId && accountIsCandidate && !session.isError && !actorIsDenied),
|
||||
gcTime: 0,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
retry: false,
|
||||
},
|
||||
});
|
||||
const catalog = useGetSpecializationCatalog({
|
||||
query: {
|
||||
staleTime: 5 * 60 * 1000,
|
||||
retry: false,
|
||||
},
|
||||
});
|
||||
const questionnaireAccessError = questionnaire.isError && isAccessError(questionnaire.error);
|
||||
const sessionAccessError = session.isError && isAccessError(session.error);
|
||||
const refetchSession = session.refetch;
|
||||
|
||||
useEffect(() => {
|
||||
if (sessionAccessError) {
|
||||
queryClient.removeQueries({ queryKey: questionnaire.queryKey, exact: true });
|
||||
}
|
||||
if (
|
||||
questionnaireAccessError &&
|
||||
questionnaire.error instanceof ApiRequestError &&
|
||||
questionnaire.error.status === 401
|
||||
) {
|
||||
void refetchSession();
|
||||
}
|
||||
}, [
|
||||
questionnaireAccessError,
|
||||
questionnaire.error,
|
||||
questionnaire.queryKey,
|
||||
queryClient,
|
||||
refetchSession,
|
||||
sessionAccessError,
|
||||
]);
|
||||
|
||||
if (sessionAccessError) {
|
||||
return (
|
||||
<ForbiddenState
|
||||
error={session.error}
|
||||
title="Анкета недоступна"
|
||||
description="Не удалось проверить текущий вход. Войдите снова, чтобы продолжить."
|
||||
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (session.isError) {
|
||||
return (
|
||||
<ErrorState
|
||||
error={session.error}
|
||||
isRetrying={session.isRefetching}
|
||||
onRetry={() => void session.refetch()}
|
||||
title="Не удалось проверить текущий вход"
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (session.isPending || !session.data) {
|
||||
return <LoadingState label="Проверяем вход и загружаем анкету..." />;
|
||||
}
|
||||
if (session.data.account.scenario !== "candidate") {
|
||||
return (
|
||||
<ForbiddenState
|
||||
title="Анкета кандидата недоступна"
|
||||
description="Войдите в кабинет, связанный со сценарием кандидата."
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (actorIsDenied) {
|
||||
return (
|
||||
<ForbiddenState
|
||||
title="Анкета недоступна"
|
||||
description="Сервер запретил доступ к анкете. Войдите снова, чтобы проверить права."
|
||||
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (questionnaire.isPending && !questionnaire.data) {
|
||||
return <LoadingState label="Загружаем сохраненные ответы..." />;
|
||||
}
|
||||
if (questionnaireAccessError) {
|
||||
return (
|
||||
<ForbiddenState
|
||||
error={questionnaire.error}
|
||||
title="Анкета недоступна"
|
||||
description="Сервер не подтвердил доступ к анкете кандидата. Войдите снова или повторите проверку входа."
|
||||
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (!questionnaire.data) {
|
||||
return (
|
||||
<ErrorState
|
||||
error={questionnaire.error}
|
||||
isRetrying={questionnaire.isRefetching}
|
||||
onRetry={() => void questionnaire.refetch()}
|
||||
title="Не удалось загрузить ответы"
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (catalog.isPending && !catalog.data) {
|
||||
return <LoadingState label="Загружаем каталог специализаций..." />;
|
||||
}
|
||||
if (!catalog.data) {
|
||||
return (
|
||||
<ErrorState
|
||||
error={catalog.error}
|
||||
isRetrying={catalog.isRefetching}
|
||||
onRetry={() => void catalog.refetch()}
|
||||
title="Не удалось загрузить каталог специализаций"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<QuestionnaireEditor
|
||||
key={session.data.account.id}
|
||||
actor={session.data}
|
||||
questionnaire={questionnaire}
|
||||
questionnaireQueryKey={questionnaireQueryKey}
|
||||
catalog={catalog.data}
|
||||
catalogQuery={catalog}
|
||||
sessionQuery={session}
|
||||
queryClient={queryClient}
|
||||
onAccessDenied={() =>
|
||||
setDeniedActor({
|
||||
accountId: session.data.account.id,
|
||||
csrfToken: session.data.csrf_token,
|
||||
})
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
type QuestionnaireEditorProps = {
|
||||
actor: Session;
|
||||
questionnaire: QuestionnaireQuery;
|
||||
questionnaireQueryKey: QueryKey;
|
||||
catalog: SpecializationCatalog;
|
||||
catalogQuery: CatalogQuery;
|
||||
sessionQuery: SessionQuery;
|
||||
queryClient: ReturnType<typeof useQueryClient>;
|
||||
onAccessDenied: () => void;
|
||||
};
|
||||
|
||||
function QuestionnaireEditor({
|
||||
actor,
|
||||
questionnaire,
|
||||
questionnaireQueryKey,
|
||||
catalog,
|
||||
catalogQuery,
|
||||
sessionQuery,
|
||||
queryClient,
|
||||
onAccessDenied,
|
||||
}: QuestionnaireEditorProps) {
|
||||
const [draft, setDraft] = useState<QuestionnaireDraft>(() =>
|
||||
toQuestionnaireDraft(questionnaire.data as CandidateQuestionnaire),
|
||||
);
|
||||
const [issues, setIssues] = useState<QuestionnaireFormIssue[]>([]);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [saveState, setSaveState] = useState<"idle" | "saving" | "saved" | "failed">("idle");
|
||||
const [canRetry, setCanRetry] = useState(false);
|
||||
const [conflict, setConflict] = useState(false);
|
||||
const [latest, setLatest] = useState<CandidateQuestionnaire | null>(null);
|
||||
const [latestLoadError, setLatestLoadError] = useState(false);
|
||||
const [savedStep, setSavedStep] = useState<OnboardingStep | null>(null);
|
||||
const saveInFlight = useRef(false);
|
||||
const saveMutation = useSaveMyQuestionnaire({
|
||||
request: { headers: { "X-CSRF-Token": actor.csrf_token } },
|
||||
mutation: { gcTime: 0 },
|
||||
});
|
||||
const currentStep = sessionQuery.data?.account.onboarding_step;
|
||||
const catalogUnavailable = catalogQuery.isError;
|
||||
|
||||
function changeDraft(next: QuestionnaireDraft) {
|
||||
setDraft(next);
|
||||
setIssues([]);
|
||||
setFormError(null);
|
||||
setCanRetry(false);
|
||||
setSaveState("idle");
|
||||
setSavedStep(null);
|
||||
}
|
||||
|
||||
async function refreshLatest(): Promise<CandidateQuestionnaire | null> {
|
||||
setLatestLoadError(false);
|
||||
const refreshed = await questionnaire.refetch();
|
||||
if (!actorMatches(queryClient, actor)) return null;
|
||||
if (!refreshed.data || refreshed.isError) {
|
||||
setLatestLoadError(true);
|
||||
return null;
|
||||
}
|
||||
setLatest(refreshed.data);
|
||||
return refreshed.data;
|
||||
}
|
||||
|
||||
async function submit(expectedVersion = draft.expectedVersion) {
|
||||
if (
|
||||
!sessionQuery.data ||
|
||||
!actorMatches(queryClient, actor) ||
|
||||
catalogUnavailable ||
|
||||
saveInFlight.current
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const result = buildCandidateQuestionnaireUpdate(draft, catalog, expectedVersion);
|
||||
setIssues(result.issues);
|
||||
setFormError(null);
|
||||
setSavedStep(null);
|
||||
setCanRetry(false);
|
||||
if (!result.data) {
|
||||
setSaveState("failed");
|
||||
return;
|
||||
}
|
||||
|
||||
saveInFlight.current = true;
|
||||
setSaveState("saving");
|
||||
try {
|
||||
const saved = await saveMutation.mutateAsync({ data: result.data });
|
||||
const savedForCurrentActor = storeQuestionnaireForActiveSession(
|
||||
queryClient,
|
||||
getGetCurrentSessionQueryKey(),
|
||||
actor,
|
||||
questionnaireQueryKey,
|
||||
saved,
|
||||
);
|
||||
if (!savedForCurrentActor) {
|
||||
setSaveState("failed");
|
||||
if (
|
||||
queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey())?.account.id ===
|
||||
actor.account.id
|
||||
) {
|
||||
setFormError("Не удалось подтвердить текущий вход. Повторите проверку и сохранение.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
setDraft(toQuestionnaireDraft(saved));
|
||||
setIssues([]);
|
||||
setConflict(false);
|
||||
setLatest(null);
|
||||
setLatestLoadError(false);
|
||||
setSaveState("saved");
|
||||
const refreshedSession = await sessionQuery.refetch();
|
||||
if (
|
||||
refreshedSession.data &&
|
||||
!refreshedSession.isError &&
|
||||
refreshedSession.data.account.id === actor.account.id &&
|
||||
activeSessionMatches(
|
||||
queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey()),
|
||||
refreshedSession.data,
|
||||
)
|
||||
) {
|
||||
setSavedStep(refreshedSession.data.account.onboarding_step);
|
||||
} else if (!refreshedSession.isError && actorMatches(queryClient, actor)) {
|
||||
setFormError("Анкета сохранена. Не удалось проверить сохраненный шаг аккаунта.");
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (!actorMatches(queryClient, actor)) {
|
||||
setSaveState("failed");
|
||||
if (
|
||||
queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey())?.account.id ===
|
||||
actor.account.id
|
||||
) {
|
||||
setFormError("Не удалось подтвердить текущий вход. Повторите проверку и сохранение.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
setSaveState("failed");
|
||||
if (error instanceof ApiRequestError && error.status === 412) {
|
||||
setConflict(true);
|
||||
setLatest(null);
|
||||
setLatestLoadError(false);
|
||||
setFormError(null);
|
||||
await refreshLatest();
|
||||
return;
|
||||
}
|
||||
if (error instanceof ApiRequestError && error.status === 400) {
|
||||
const serverIssues = mapQuestionnaireServerErrors(error.fieldErrors);
|
||||
setIssues(serverIssues);
|
||||
setFormError(
|
||||
serverIssues.length === 0
|
||||
? "Сервер не сохранил изменения. Проверьте ответы и повторите попытку."
|
||||
: null,
|
||||
);
|
||||
void catalogQuery.refetch();
|
||||
return;
|
||||
}
|
||||
if (error instanceof ApiRequestError && error.status === 403) {
|
||||
if (error.code === "csrf_check_failed") {
|
||||
const refreshed = await sessionQuery.refetch();
|
||||
if (
|
||||
!refreshed.isError &&
|
||||
refreshed.data?.account.id === actor.account.id &&
|
||||
activeSessionMatches(
|
||||
queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey()),
|
||||
refreshed.data,
|
||||
)
|
||||
) {
|
||||
setFormError(
|
||||
"Проверка входа обновлена. Ответы остались в форме, повторите сохранение.",
|
||||
);
|
||||
} else if (!refreshed.isError && actorMatches(queryClient, actor)) {
|
||||
setFormError("Не удалось подтвердить текущий вход. Повторите проверку.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
queryClient.removeQueries({ queryKey: questionnaireQueryKey, exact: true });
|
||||
onAccessDenied();
|
||||
return;
|
||||
}
|
||||
if (error instanceof ApiRequestError && error.status === 401) {
|
||||
setFormError("Вход больше не подтвержден. Войдите снова, чтобы продолжить.");
|
||||
void sessionQuery.refetch();
|
||||
return;
|
||||
}
|
||||
setCanRetry(true);
|
||||
setFormError("Не удалось сохранить анкету. Проверьте подключение и повторите попытку.");
|
||||
} finally {
|
||||
saveInFlight.current = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleDraftIssue(issue: QuestionnaireFormIssue) {
|
||||
setIssues([issue]);
|
||||
setFormError(null);
|
||||
setSaveState("failed");
|
||||
setCanRetry(false);
|
||||
}
|
||||
|
||||
function loadLatestAndDiscardDraft() {
|
||||
if (!latest) return;
|
||||
changeDraft(toQuestionnaireDraft(latest));
|
||||
setConflict(false);
|
||||
setLatest(null);
|
||||
setLatestLoadError(false);
|
||||
setFormError(null);
|
||||
}
|
||||
|
||||
const onboardingDestination =
|
||||
savedStep === "candidate_assessment" ? paths.candidate.assessment : null;
|
||||
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<Section
|
||||
title="Ответы кандидата"
|
||||
description="Выберите специализации, укажите самооценку и подходящие форматы работы. Эти ответы не подтверждают грейд и не требуют ФСП."
|
||||
>
|
||||
{currentStep ? (
|
||||
<p className={styles["server-step"]}>
|
||||
Шаг аккаунта на сервере: <strong>{stepLabel(currentStep)}</strong>.
|
||||
</p>
|
||||
) : null}
|
||||
{catalogUnavailable ? (
|
||||
<div className={styles.warning} role="alert">
|
||||
<p>Не удалось обновить каталог. Показаны последние загруженные сведения.</p>
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={catalogQuery.isRefetching}
|
||||
onClick={() => void catalogQuery.refetch()}
|
||||
>
|
||||
{catalogQuery.isRefetching ? "Обновляем каталог..." : "Повторить загрузку каталога"}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
{formError ? (
|
||||
<div className={styles["form-error"]} role="alert">
|
||||
{formError}
|
||||
</div>
|
||||
) : null}
|
||||
{conflict ? (
|
||||
<div
|
||||
className={styles.conflict}
|
||||
role="alert"
|
||||
aria-labelledby="questionnaire-conflict-title"
|
||||
>
|
||||
<h2 id="questionnaire-conflict-title">Анкета изменилась в другом окне</h2>
|
||||
<p>
|
||||
Черновик этой формы сохранен в памяти и не отправлен повторно. Выберите, какие ответы
|
||||
оставить. Перезапись отправит весь черновик поверх актуальной анкеты.
|
||||
</p>
|
||||
{latestLoadError ? (
|
||||
<p>Не удалось загрузить актуальные ответы. Ваш черновик остается в форме.</p>
|
||||
) : null}
|
||||
{latest ? <p>Последняя прочитанная серверная версия: {latest.version}.</p> : null}
|
||||
<div className={styles["conflict-actions"]}>
|
||||
<Button
|
||||
variant="primary"
|
||||
isBusy={saveState === "saving" || questionnaire.isRefetching}
|
||||
disabled={!latest || latestLoadError}
|
||||
onClick={() => void submit(latest?.version ?? draft.expectedVersion)}
|
||||
>
|
||||
Записать этот черновик поверх актуальной анкеты
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={questionnaire.isRefetching}
|
||||
onClick={() => void refreshLatest()}
|
||||
>
|
||||
{questionnaire.isRefetching ? "Загружаем ответы..." : "Загрузить актуальные ответы"}
|
||||
</Button>
|
||||
<Button
|
||||
variant="quiet"
|
||||
disabled={!latest || questionnaire.isRefetching || saveState === "saving"}
|
||||
onClick={loadLatestAndDiscardDraft}
|
||||
aria-describedby="questionnaire-conflict-discard-hint"
|
||||
>
|
||||
Заменить черновик актуальными ответами
|
||||
</Button>
|
||||
</div>
|
||||
<p id="questionnaire-conflict-discard-hint">
|
||||
Замена удалит введенные в этой форме изменения.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
<QuestionnaireForm
|
||||
draft={draft}
|
||||
catalog={catalog}
|
||||
issues={issues}
|
||||
isSaving={saveState === "saving"}
|
||||
isForbidden={false}
|
||||
isConflict={conflict}
|
||||
canRetry={canRetry}
|
||||
onDraftChange={changeDraft}
|
||||
onIssue={handleDraftIssue}
|
||||
onSubmit={() => void submit()}
|
||||
/>
|
||||
{saveState === "saved" ? (
|
||||
<div className={styles.continuation} role="status">
|
||||
<p>
|
||||
Анкета сохранена. Сервер подтвердил шаг аккаунта:{" "}
|
||||
{savedStep ? stepLabel(savedStep) : "не удалось прочитать"}.
|
||||
</p>
|
||||
{onboardingDestination ? (
|
||||
<ButtonLink to={onboardingDestination} variant="secondary">
|
||||
Перейти к следующему шагу
|
||||
</ButtonLink>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
.form {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.editor-fields {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.visually-hidden {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.issue-summary {
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-strong) solid var(--color-danger);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.issue-summary:focus {
|
||||
outline: var(--line-strong) solid var(--color-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.issue-summary h2 {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.issue-summary ul {
|
||||
margin: var(--space-3) 0 0;
|
||||
padding-left: var(--space-5);
|
||||
}
|
||||
|
||||
.group,
|
||||
.specialization,
|
||||
.option-group {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
}
|
||||
|
||||
.group legend,
|
||||
.specialization legend,
|
||||
.option-group legend {
|
||||
max-width: 100%;
|
||||
padding-inline: var(--space-2);
|
||||
font-size: var(--font-size-l);
|
||||
font-weight: var(--font-weight-bold);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.hint,
|
||||
.availability p {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.field > label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.field input,
|
||||
.field select {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
min-height: 2.75rem;
|
||||
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;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: var(--color-text);
|
||||
font-size: var(--font-size-s);
|
||||
font-weight: var(--font-weight-bold);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.availability {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.availability-title {
|
||||
color: var(--color-text);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.check-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3) var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.check-item {
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
align-items: flex-start;
|
||||
min-width: 0;
|
||||
line-height: var(--line-height-body);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.check-item input {
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
margin: 0.125rem 0 0;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.month-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.stack-input {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: flex-end;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.stack-input input {
|
||||
flex: 1 1 15rem;
|
||||
}
|
||||
|
||||
.field input:focus-visible,
|
||||
.field select:focus-visible,
|
||||
.check-item input:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.field input[aria-invalid="true"],
|
||||
.field select[aria-invalid="true"] {
|
||||
border-width: var(--line-strong);
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.tag-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.tag {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
align-items: center;
|
||||
max-width: 100%;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-s);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.actions > .hint {
|
||||
flex: 1 1 18rem;
|
||||
}
|
||||
|
||||
.form-error {
|
||||
margin: 0;
|
||||
padding: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-danger);
|
||||
background: var(--color-canvas);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
@media (width < 48rem) {
|
||||
.month-grid {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (width < 30rem) {
|
||||
.group,
|
||||
.specialization,
|
||||
.option-group {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
|
||||
.actions {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { CandidateQuestionnaire, SpecializationCatalog } from "../../../shared/api/schemas";
|
||||
import {
|
||||
changeQuestionnaireSpecialization,
|
||||
patchQuestionnaireSpecialization,
|
||||
toQuestionnaireDraft,
|
||||
} from "../model/questionnaire-form";
|
||||
import { QuestionnaireForm } from "./questionnaire-form";
|
||||
|
||||
const catalog: SpecializationCatalog = {
|
||||
directions: [
|
||||
{
|
||||
code: "development",
|
||||
title: "Разработка",
|
||||
specializations: [
|
||||
{
|
||||
code: "backend",
|
||||
title: "Backend",
|
||||
test_availability: {
|
||||
status: "available",
|
||||
grades: ["junior"],
|
||||
task_languages: ["python", "go"],
|
||||
note: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
code: "data",
|
||||
title: "Данные",
|
||||
specializations: [
|
||||
{
|
||||
code: "ds_ml",
|
||||
title: "DS/ML",
|
||||
test_availability: {
|
||||
status: "in_development",
|
||||
grades: [],
|
||||
task_languages: [],
|
||||
note: "Банк заданий готовится.",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
grades: [
|
||||
{ code: "intern", title: "Стажер" },
|
||||
{ code: "junior", title: "Junior" },
|
||||
{ code: "middle", title: "Middle" },
|
||||
{ code: "senior", title: "Senior" },
|
||||
],
|
||||
};
|
||||
|
||||
const emptyQuestionnaire: CandidateQuestionnaire = {
|
||||
version: 0,
|
||||
specializations: [],
|
||||
work_context: null,
|
||||
updated_at: null,
|
||||
};
|
||||
|
||||
function renderQuestionnaireForm(specialization: "backend" | "ds_ml"): string {
|
||||
const base = toQuestionnaireDraft(emptyQuestionnaire);
|
||||
const first = base.specializations[0];
|
||||
if (!first) throw new Error("Expected the questionnaire to have one editing row.");
|
||||
const selected = changeQuestionnaireSpecialization(base, first.id, specialization);
|
||||
const draft = patchQuestionnaireSpecialization(selected, first.id, {
|
||||
selfAssessedGrade: specialization === "backend" ? "junior" : "senior",
|
||||
taskLanguages: specialization === "backend" ? ["go"] : [],
|
||||
});
|
||||
|
||||
return renderToStaticMarkup(
|
||||
<QuestionnaireForm
|
||||
draft={draft}
|
||||
catalog={catalog}
|
||||
issues={[]}
|
||||
isSaving={false}
|
||||
isForbidden={false}
|
||||
isConflict={false}
|
||||
canRetry={false}
|
||||
onDraftChange={() => undefined}
|
||||
onIssue={() => undefined}
|
||||
onSubmit={() => undefined}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("questionnaire form", () => {
|
||||
it("renders current Backend task language and grade options with associated hints", () => {
|
||||
const markup = renderQuestionnaireForm("backend");
|
||||
const ids = new Set([...markup.matchAll(/\sid="([^"]+)"/g)].map((match) => match[1]));
|
||||
const descriptions = [...markup.matchAll(/aria-describedby="([^"]+)"/g)].flatMap((match) =>
|
||||
(match[1] ?? "").split(/\s+/),
|
||||
);
|
||||
|
||||
expect(markup).toContain("Проверка опубликована для уровней: Junior.");
|
||||
expect(markup).toContain("Python");
|
||||
expect(markup).toContain("Go");
|
||||
expect(markup).toContain("При смене выбора самооценка");
|
||||
expect(descriptions.length).toBeGreaterThan(0);
|
||||
expect(descriptions.every((id) => ids.has(id))).toBe(true);
|
||||
expect(markup).not.toMatch(/ФСП|confirmed_grade|подтвержденный грейд/i);
|
||||
});
|
||||
|
||||
it("allows an in-development specialization as a self-assessed claim without an assessment action", () => {
|
||||
const markup = renderQuestionnaireForm("ds_ml");
|
||||
|
||||
expect(markup).toContain("Проверка: в разработке");
|
||||
expect(markup).toContain(
|
||||
"Эту специализацию можно сохранить. Начать проверку по ней пока нельзя.",
|
||||
);
|
||||
expect(markup).toContain("Банк заданий готовится.");
|
||||
expect(markup).toContain('value="senior" selected=""');
|
||||
expect(markup).not.toMatch(/<button\b[^>]*>[^<]*(?:Перейти|Начать) проверку/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,634 @@
|
||||
import { useEffect, useId, useRef, type FormEvent, type ReactNode } from "react";
|
||||
import {
|
||||
addQuestionnaireSpecialization,
|
||||
addQuestionnaireStackTag,
|
||||
changeQuestionnaireSpecialization,
|
||||
patchQuestionnaireSpecialization,
|
||||
removeQuestionnaireSpecialization,
|
||||
removeQuestionnaireStackTag,
|
||||
toggleQuestionnaireWorkFormat,
|
||||
type QuestionnaireDraft,
|
||||
type QuestionnaireFormIssue,
|
||||
type QuestionnaireSpecializationDraft,
|
||||
} from "../model/questionnaire-form";
|
||||
import { findGradeTitle, findSpecializationOption } from "../../../entities/specialization";
|
||||
import type {
|
||||
SpecializationCatalog,
|
||||
SpecializationCode,
|
||||
TaskLanguage,
|
||||
WorkFormat,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { Button } from "../../../shared/ui";
|
||||
import styles from "./questionnaire-form.module.css";
|
||||
|
||||
const workFormats: ReadonlyArray<{ value: WorkFormat; label: string }> = [
|
||||
{ value: "remote", label: "Удаленно" },
|
||||
{ value: "office", label: "В офисе" },
|
||||
{ value: "hybrid", label: "Гибридно" },
|
||||
];
|
||||
|
||||
const taskLanguageLabels: Record<TaskLanguage, string> = {
|
||||
python: "Python",
|
||||
go: "Go",
|
||||
};
|
||||
|
||||
type QuestionnaireFormProps = {
|
||||
draft: QuestionnaireDraft;
|
||||
catalog: SpecializationCatalog;
|
||||
issues: readonly QuestionnaireFormIssue[];
|
||||
isSaving: boolean;
|
||||
isForbidden: boolean;
|
||||
isConflict: boolean;
|
||||
canRetry: boolean;
|
||||
onDraftChange: (draft: QuestionnaireDraft) => void;
|
||||
onIssue: (issue: QuestionnaireFormIssue) => void;
|
||||
onSubmit: () => void;
|
||||
};
|
||||
|
||||
function issueFor(issues: readonly QuestionnaireFormIssue[], field: string): string | undefined {
|
||||
return issues.find((issue) => issue.field === field)?.message;
|
||||
}
|
||||
|
||||
function describeIds(id: string, hint: boolean, error: boolean): string | undefined {
|
||||
const ids = [hint ? `${id}-hint` : "", error ? `${id}-error` : ""].filter(Boolean);
|
||||
return ids.length > 0 ? ids.join(" ") : undefined;
|
||||
}
|
||||
|
||||
function ErrorText({ id, children }: { id: string; children?: string | undefined }) {
|
||||
return children ? (
|
||||
<p className={styles.error} id={id}>
|
||||
{children}
|
||||
</p>
|
||||
) : null;
|
||||
}
|
||||
|
||||
function Field({
|
||||
id,
|
||||
label,
|
||||
hint,
|
||||
error,
|
||||
children,
|
||||
}: {
|
||||
id: string;
|
||||
label: string;
|
||||
hint?: string | undefined;
|
||||
error?: string | undefined;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={id}>{label}</label>
|
||||
{hint ? (
|
||||
<p className={styles.hint} id={`${id}-hint`}>
|
||||
{hint}
|
||||
</p>
|
||||
) : null}
|
||||
{children}
|
||||
<ErrorText id={`${id}-error`}>{error}</ErrorText>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StackTags({
|
||||
draft,
|
||||
item,
|
||||
index,
|
||||
error,
|
||||
disabled,
|
||||
prefix,
|
||||
onDraftChange,
|
||||
onIssue,
|
||||
}: {
|
||||
draft: QuestionnaireDraft;
|
||||
item: QuestionnaireSpecializationDraft;
|
||||
index: number;
|
||||
error?: string | undefined;
|
||||
disabled: boolean;
|
||||
prefix: string;
|
||||
onDraftChange: (draft: QuestionnaireDraft) => void;
|
||||
onIssue: (issue: QuestionnaireFormIssue) => void;
|
||||
}) {
|
||||
const inputId = `${prefix}-stack-input`;
|
||||
const helpId = `${inputId}-hint`;
|
||||
const addTag = () => {
|
||||
const result = addQuestionnaireStackTag(draft, item.id);
|
||||
if (result.issue) {
|
||||
onIssue(result.issue);
|
||||
return;
|
||||
}
|
||||
onDraftChange(result.draft);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={inputId}>Стек технологий</label>
|
||||
<p className={styles.hint} id={helpId}>
|
||||
Например, PostgreSQL или Kubernetes. Это не язык заданий и не уровень оценки.
|
||||
</p>
|
||||
<div className={styles["stack-input"]}>
|
||||
<input
|
||||
id={inputId}
|
||||
value={item.stackInput}
|
||||
maxLength={50}
|
||||
disabled={disabled}
|
||||
aria-invalid={Boolean(error)}
|
||||
aria-describedby={describeIds(inputId, true, Boolean(error))}
|
||||
onChange={(event) =>
|
||||
onDraftChange(
|
||||
patchQuestionnaireSpecialization(draft, item.id, {
|
||||
stackInput: event.currentTarget.value,
|
||||
}),
|
||||
)
|
||||
}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
addTag();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button variant="secondary" disabled={disabled || item.stack.length >= 20} onClick={addTag}>
|
||||
Добавить технологию
|
||||
</Button>
|
||||
</div>
|
||||
{item.stack.length > 0 ? (
|
||||
<ul className={styles["tag-list"]} aria-label={`Технологии по специализации ${index + 1}`}>
|
||||
{item.stack.map((tag) => (
|
||||
<li className={styles.tag} key={`${tag}-${index}`}>
|
||||
<span>{tag}</span>
|
||||
<Button
|
||||
variant="quiet"
|
||||
disabled={disabled}
|
||||
aria-label={`Удалить технологию ${tag}`}
|
||||
onClick={() => onDraftChange(removeQuestionnaireStackTag(draft, item.id, tag))}
|
||||
>
|
||||
Удалить
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
<ErrorText id={`${inputId}-error`}>{error}</ErrorText>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SpecializationCard({
|
||||
draft,
|
||||
item,
|
||||
index,
|
||||
catalog,
|
||||
issues,
|
||||
disabled,
|
||||
prefix,
|
||||
onDraftChange,
|
||||
onIssue,
|
||||
}: {
|
||||
draft: QuestionnaireDraft;
|
||||
item: QuestionnaireSpecializationDraft;
|
||||
index: number;
|
||||
catalog: SpecializationCatalog;
|
||||
issues: readonly QuestionnaireFormIssue[];
|
||||
disabled: boolean;
|
||||
prefix: string;
|
||||
onDraftChange: (draft: QuestionnaireDraft) => void;
|
||||
onIssue: (issue: QuestionnaireFormIssue) => void;
|
||||
}) {
|
||||
const cardId = `${prefix}-specialization-${index}`;
|
||||
const selectionId = `${cardId}-selection`;
|
||||
const gradeId = `${cardId}-grade`;
|
||||
const experienceToggleId = `${cardId}-experience-enabled`;
|
||||
const commercialId = `${cardId}-commercial-months`;
|
||||
const academicId = `${cardId}-academic-months`;
|
||||
const taskLanguagesId = `${cardId}-task-languages`;
|
||||
const selectedOption = findSpecializationOption(catalog, item.specialization);
|
||||
const selectedElsewhere = new Set(
|
||||
draft.specializations
|
||||
.filter((candidate) => candidate.id !== item.id)
|
||||
.map((candidate) => candidate.specialization)
|
||||
.filter(Boolean),
|
||||
);
|
||||
const specialtyField = `specializations.${index}.specialization`;
|
||||
const gradeField = `specializations.${index}.selfAssessedGrade`;
|
||||
const languagesField = `specializations.${index}.taskLanguages`;
|
||||
const stackError = issues.find((issue) =>
|
||||
issue.field.startsWith(`specializations.${index}.stack`),
|
||||
)?.message;
|
||||
const offeredLanguages = selectedOption?.test_availability.task_languages ?? [];
|
||||
const oldLanguages = item.taskLanguages.filter(
|
||||
(language) => !offeredLanguages.includes(language),
|
||||
);
|
||||
const shownLanguages = [...new Set([...offeredLanguages, ...oldLanguages])];
|
||||
|
||||
function changeLanguage(language: TaskLanguage, selected: boolean) {
|
||||
const next = selected
|
||||
? [...item.taskLanguages, language]
|
||||
: item.taskLanguages.filter((current) => current !== language);
|
||||
onDraftChange(patchQuestionnaireSpecialization(draft, item.id, { taskLanguages: next }));
|
||||
}
|
||||
|
||||
return (
|
||||
<fieldset className={styles.specialization}>
|
||||
<legend>Специализация {index + 1}</legend>
|
||||
<p className={styles.hint}>
|
||||
Самооценка описывает ваш выбор и не подтверждает грейд. Подтвержденную категорию определяет
|
||||
только результат проверки.
|
||||
</p>
|
||||
<Field
|
||||
id={selectionId}
|
||||
label="Специализация"
|
||||
hint="Выберите направление из актуального каталога. При смене выбора самооценка, языки заданий, стек и опыт для этой строки будут очищены."
|
||||
error={issueFor(issues, specialtyField)}
|
||||
>
|
||||
<select
|
||||
id={selectionId}
|
||||
value={item.specialization}
|
||||
aria-invalid={Boolean(issueFor(issues, specialtyField))}
|
||||
aria-describedby={describeIds(
|
||||
selectionId,
|
||||
true,
|
||||
Boolean(issueFor(issues, specialtyField)),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
onDraftChange(
|
||||
changeQuestionnaireSpecialization(
|
||||
draft,
|
||||
item.id,
|
||||
event.currentTarget.value as SpecializationCode | "",
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Выберите специализацию</option>
|
||||
{item.specialization && !selectedOption ? (
|
||||
<option value={item.specialization}>
|
||||
{item.specialization} (нет в текущем каталоге)
|
||||
</option>
|
||||
) : null}
|
||||
{catalog.directions.map((direction) => (
|
||||
<optgroup key={direction.code} label={direction.title}>
|
||||
{direction.specializations.map((option) => (
|
||||
<option
|
||||
key={option.code}
|
||||
value={option.code}
|
||||
disabled={selectedElsewhere.has(option.code)}
|
||||
>
|
||||
{option.title}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
|
||||
{selectedOption ? (
|
||||
<div className={styles.availability} role="status">
|
||||
{selectedOption.test_availability.status === "in_development" ? (
|
||||
<>
|
||||
<p className={styles["availability-title"]}>Проверка: в разработке</p>
|
||||
<p>Эту специализацию можно сохранить. Начать проверку по ней пока нельзя.</p>
|
||||
{selectedOption.test_availability.note ? (
|
||||
<p>{selectedOption.test_availability.note}</p>
|
||||
) : null}
|
||||
</>
|
||||
) : selectedOption.test_availability.grades.length > 0 ? (
|
||||
<p>
|
||||
Проверка опубликована для уровней:{" "}
|
||||
{selectedOption.test_availability.grades
|
||||
.map((grade) => findGradeTitle(catalog, grade))
|
||||
.join(", ")}
|
||||
.
|
||||
</p>
|
||||
) : (
|
||||
<p>Сейчас нет опубликованных уровней проверки для этой специализации.</p>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<Field
|
||||
id={gradeId}
|
||||
label="Моя оценка уровня"
|
||||
hint="Это самооценка. Она не присваивает подтвержденную категорию."
|
||||
error={issueFor(issues, gradeField)}
|
||||
>
|
||||
<select
|
||||
id={gradeId}
|
||||
value={item.selfAssessedGrade}
|
||||
disabled={!selectedOption}
|
||||
aria-invalid={Boolean(issueFor(issues, gradeField))}
|
||||
aria-describedby={describeIds(gradeId, true, Boolean(issueFor(issues, gradeField)))}
|
||||
onChange={(event) =>
|
||||
onDraftChange(
|
||||
patchQuestionnaireSpecialization(draft, item.id, {
|
||||
selfAssessedGrade: event.currentTarget
|
||||
.value as QuestionnaireSpecializationDraft["selfAssessedGrade"],
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Выберите уровень</option>
|
||||
{catalog.grades.map((grade) => (
|
||||
<option key={grade.code} value={grade.code}>
|
||||
{grade.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
|
||||
<fieldset className={styles["option-group"]}>
|
||||
<legend id={taskLanguagesId}>Язык заданий</legend>
|
||||
<p className={styles.hint} id={`${taskLanguagesId}-hint`}>
|
||||
Этот выбор относится к языку заданий проверки, а не к вашему стеку технологий.
|
||||
</p>
|
||||
{!selectedOption ? (
|
||||
<p>Сначала выберите специализацию.</p>
|
||||
) : shownLanguages.length > 0 ? (
|
||||
<div className={styles["check-list"]}>
|
||||
{shownLanguages.map((language) => {
|
||||
const isOld = oldLanguages.includes(language);
|
||||
const languageId = `${taskLanguagesId}-${language}`;
|
||||
return (
|
||||
<label className={styles["check-item"]} htmlFor={languageId} key={language}>
|
||||
<input
|
||||
id={languageId}
|
||||
type="checkbox"
|
||||
checked={item.taskLanguages.includes(language)}
|
||||
disabled={!selectedOption}
|
||||
aria-describedby={describeIds(
|
||||
taskLanguagesId,
|
||||
true,
|
||||
Boolean(issueFor(issues, languagesField)),
|
||||
)}
|
||||
onChange={(event) => changeLanguage(language, event.currentTarget.checked)}
|
||||
/>
|
||||
<span>
|
||||
{taskLanguageLabels[language]}
|
||||
{isOld ? " (сейчас не предлагается)" : ""}
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<p>Для этой специализации сейчас не предлагаются варианты языка заданий.</p>
|
||||
)}
|
||||
<ErrorText id={`${taskLanguagesId}-error`}>{issueFor(issues, languagesField)}</ErrorText>
|
||||
</fieldset>
|
||||
|
||||
<StackTags
|
||||
draft={draft}
|
||||
item={item}
|
||||
index={index}
|
||||
error={stackError}
|
||||
disabled={disabled || !selectedOption}
|
||||
prefix={cardId}
|
||||
onDraftChange={onDraftChange}
|
||||
onIssue={onIssue}
|
||||
/>
|
||||
|
||||
<fieldset className={styles["option-group"]}>
|
||||
<legend>Опыт в этой специализации</legend>
|
||||
<label className={styles["check-item"]} htmlFor={experienceToggleId}>
|
||||
<input
|
||||
id={experienceToggleId}
|
||||
type="checkbox"
|
||||
checked={item.hasExperience}
|
||||
disabled={!selectedOption}
|
||||
onChange={(event) =>
|
||||
onDraftChange(
|
||||
patchQuestionnaireSpecialization(draft, item.id, {
|
||||
hasExperience: event.currentTarget.checked,
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<span>Указать опыт в месяцах</span>
|
||||
</label>
|
||||
{item.hasExperience ? (
|
||||
<div className={styles["month-grid"]}>
|
||||
<Field
|
||||
id={commercialId}
|
||||
label="Коммерческий опыт, месяцев"
|
||||
hint="Допустимое значение: от 0 до 600."
|
||||
error={issueFor(issues, `specializations.${index}.commercialMonths`)}
|
||||
>
|
||||
<input
|
||||
id={commercialId}
|
||||
type="number"
|
||||
min={0}
|
||||
max={600}
|
||||
step={1}
|
||||
inputMode="numeric"
|
||||
value={item.commercialMonths}
|
||||
disabled={!selectedOption}
|
||||
aria-invalid={Boolean(
|
||||
issueFor(issues, `specializations.${index}.commercialMonths`),
|
||||
)}
|
||||
aria-describedby={describeIds(
|
||||
commercialId,
|
||||
true,
|
||||
Boolean(issueFor(issues, `specializations.${index}.commercialMonths`)),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
onDraftChange(
|
||||
patchQuestionnaireSpecialization(draft, item.id, {
|
||||
commercialMonths: event.currentTarget.value,
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
id={academicId}
|
||||
label="Учебный и академический опыт, месяцев"
|
||||
hint="Допустимое значение: от 0 до 600."
|
||||
error={issueFor(issues, `specializations.${index}.academicMonths`)}
|
||||
>
|
||||
<input
|
||||
id={academicId}
|
||||
type="number"
|
||||
min={0}
|
||||
max={600}
|
||||
step={1}
|
||||
inputMode="numeric"
|
||||
value={item.academicMonths}
|
||||
disabled={!selectedOption}
|
||||
aria-invalid={Boolean(issueFor(issues, `specializations.${index}.academicMonths`))}
|
||||
aria-describedby={describeIds(
|
||||
academicId,
|
||||
true,
|
||||
Boolean(issueFor(issues, `specializations.${index}.academicMonths`)),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
onDraftChange(
|
||||
patchQuestionnaireSpecialization(draft, item.id, {
|
||||
academicMonths: event.currentTarget.value,
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
) : (
|
||||
<p className={styles.hint}>Можно оставить без указания.</p>
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
{draft.specializations.length > 1 ? (
|
||||
<Button
|
||||
variant="quiet"
|
||||
disabled={disabled}
|
||||
onClick={() => onDraftChange(removeQuestionnaireSpecialization(draft, item.id))}
|
||||
aria-label={`Удалить специализацию ${index + 1}`}
|
||||
>
|
||||
Удалить специализацию
|
||||
</Button>
|
||||
) : null}
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
|
||||
export function QuestionnaireForm({
|
||||
draft,
|
||||
catalog,
|
||||
issues,
|
||||
isSaving,
|
||||
isForbidden,
|
||||
isConflict,
|
||||
canRetry,
|
||||
onDraftChange,
|
||||
onIssue,
|
||||
onSubmit,
|
||||
}: QuestionnaireFormProps) {
|
||||
const prefix = `questionnaire-${useId().replaceAll(":", "")}`;
|
||||
const rowSequence = useRef(0);
|
||||
const issueSummary = useRef<HTMLDivElement>(null);
|
||||
const formDisabled = isSaving || isForbidden;
|
||||
const generalIssue = issueFor(issues, "form");
|
||||
|
||||
useEffect(() => {
|
||||
if (issues.length > 0) issueSummary.current?.focus();
|
||||
}, [issues.length]);
|
||||
|
||||
function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (issues.length > 0) issueSummary.current?.focus();
|
||||
else event.currentTarget.querySelector<HTMLButtonElement>('button[type="submit"]')?.focus();
|
||||
onSubmit();
|
||||
}
|
||||
|
||||
return (
|
||||
<form className={styles.form} onSubmit={handleSubmit} noValidate>
|
||||
{issues.length > 0 ? (
|
||||
<div
|
||||
className={styles["issue-summary"]}
|
||||
ref={issueSummary}
|
||||
role="alert"
|
||||
aria-labelledby={`${prefix}-issues-title`}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<h2 id={`${prefix}-issues-title`}>Проверьте анкету</h2>
|
||||
<ul>
|
||||
{issues.map((item, index) => (
|
||||
<li key={`${item.field}-${index}`}>{item.message}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<fieldset className={styles["editor-fields"]} disabled={formDisabled}>
|
||||
<legend className={styles["visually-hidden"]}>Ответы анкеты</legend>
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Специализации</legend>
|
||||
<p className={styles.hint}>
|
||||
Выберите одну или две специализации. Самооценка и опыт сохраняются отдельно для каждой.
|
||||
</p>
|
||||
{draft.specializations.map((item, index) => (
|
||||
<SpecializationCard
|
||||
key={item.id}
|
||||
draft={draft}
|
||||
item={item}
|
||||
index={index}
|
||||
catalog={catalog}
|
||||
issues={issues}
|
||||
disabled={formDisabled}
|
||||
prefix={prefix}
|
||||
onDraftChange={onDraftChange}
|
||||
onIssue={onIssue}
|
||||
/>
|
||||
))}
|
||||
<ErrorText id={`${prefix}-specializations-error`}>
|
||||
{issueFor(issues, "specializations")}
|
||||
</ErrorText>
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={formDisabled || draft.specializations.length >= 2}
|
||||
aria-describedby={`${prefix}-specialization-limit`}
|
||||
onClick={() => {
|
||||
const id = `${prefix}-row-${++rowSequence.current}`;
|
||||
onDraftChange(addQuestionnaireSpecialization(draft, id));
|
||||
}}
|
||||
>
|
||||
Добавить специализацию
|
||||
</Button>
|
||||
<p className={styles.hint} id={`${prefix}-specialization-limit`}>
|
||||
Можно указать не больше двух специализаций.
|
||||
</p>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Подходящий формат работы</legend>
|
||||
<p className={styles.hint}>
|
||||
Укажите от одного до трех вариантов. Город, переезд и зарплата относятся к профилю.
|
||||
</p>
|
||||
<div className={styles["check-list"]}>
|
||||
{workFormats.map((format) => {
|
||||
const id = `${prefix}-format-${format.value}`;
|
||||
return (
|
||||
<label className={styles["check-item"]} htmlFor={id} key={format.value}>
|
||||
<input
|
||||
id={id}
|
||||
type="checkbox"
|
||||
checked={draft.workFormats.includes(format.value)}
|
||||
onChange={() =>
|
||||
onDraftChange(toggleQuestionnaireWorkFormat(draft, format.value))
|
||||
}
|
||||
/>
|
||||
<span>{format.label}</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<ErrorText id={`${prefix}-work-formats-error`}>
|
||||
{issueFor(issues, "workFormats")}
|
||||
</ErrorText>
|
||||
</fieldset>
|
||||
</fieldset>
|
||||
|
||||
{generalIssue ? (
|
||||
<p className={styles["form-error"]} role="alert">
|
||||
{generalIssue}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className={styles.actions}>
|
||||
<p className={styles.hint}>
|
||||
Сохраненные ответы можно изменить. Данные черновика не записываются в браузерное
|
||||
хранилище.
|
||||
</p>
|
||||
<Button
|
||||
type="submit"
|
||||
isBusy={isSaving}
|
||||
disabled={isForbidden || isConflict}
|
||||
aria-disabled={isForbidden || isConflict || undefined}
|
||||
>
|
||||
{isSaving
|
||||
? "Сохраняем анкету..."
|
||||
: canRetry
|
||||
? "Повторить сохранение"
|
||||
: "Сохранить анкету"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user