import { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from "react"; import { addExperience, addRole, addSoftSkill, addStack, buildCandidateProfileUpdate, 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, Mono, Notice, SavingStatus, Tag, TrustLevel } from "../../../shared/ui"; import { profileStepOfField, type ProfileStepId } from "../model/profile-steps"; import { FormProgress, FormStepFooter, FormStepPanel, ReviewBlock, type FormStep, } from "./form-steps"; import { useFormSteps } from "./use-form-steps"; import styles from "./profile-form.module.css"; const profileSteps: readonly FormStep[] = [ { id: "contacts", label: "Контакты" }, { id: "roles", label: "Роли" }, { id: "experience", label: "Опыт" }, { id: "skills", label: "Навыки" }, { id: "terms", label: "Условия" }, { id: "review", label: "Проверка" }, ]; type Specialization = CandidateProfile["roles"][number]["specialization"]; type Grade = NonNullable; 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 ? (

{children}

) : null; } function Suggestion({ source }: { source: { quote: string | null; origin: string } | null }) { if (!source || source.origin === "manual") return null; const origin = source.origin === "imported" ? "Импортировано" : "Предложено из документа"; return (
{origin}. Значение пока не подтверждено. {source.quote ?
{source.quote}
:

Цитата не сохранена.

}
); } 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 (
{description ? (

{description}

) : null} {children} {suggestion ? (
) : null} {error}
); } 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; } const fieldLabels: Readonly> = { fullName: "имя и фамилия", "contacts.email": "контактный email", "contacts.phone": "телефон", "contacts.telegram": "Telegram", "terms.location": "место работы", "terms.relocation": "переезд", "terms.salaryMinimum.amount": "минимальная зарплата", "terms.salaryMinimum.tax_basis": "до или после налога", }; /** The field named in an issue of the summary, when it has a short name. */ function fieldLabel(field: string): string | null { if (fieldLabels[field]) return fieldLabels[field]; const row = /^(experience|roles|stack|softSkills)\.(\d+)/.exec(field); if (!row) return null; const position = Number(row[2]) + 1; switch (row[1]) { case "experience": return `место работы ${position}`; case "roles": return `роль ${position}`; case "stack": return `навык ${position}`; default: return `гибкий навык ${position}`; } } /** One line per field and message: a schema error can repeat for a field. */ function uniqueIssues(issues: readonly ProfileFormIssue[]): ProfileFormIssue[] { const seen = new Set(); return issues.filter((item) => { const key = `${item.field}\u0000${item.message}`; if (seen.has(key)) return false; seen.add(key); return true; }); } function SourceLabel({ status }: { status: "confirmed" | "extracted" | "unknown" }) { if (status === "extracted") return Нужно проверить; if (status === "unknown") return Не указано; 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 issueSummary = useRef(null); const steps = useFormSteps(profileSteps); const { goTo } = steps; const [stepIssues, setStepIssues] = useState([]); const shownIssues = issues.length > 0 ? issues : stepIssues; const listedIssues = uniqueIssues(shownIssues); const issue = (field: string) => errorFor(shownIssues, field); const setDraft = (next: CandidateProfileDraft) => { setStepIssues([]); onDraftChange(next); }; // Issues from a save (client or server) open the first step that owns one. const [seenIssues, setSeenIssues] = useState(issues); if (seenIssues !== issues) { setSeenIssues(issues); const first = issues[0]; if (first) steps.show(profileStepOfField(first.field)); } useEffect(() => { if (shownIssues.length > 0) issueSummary.current?.focus(); }, [shownIssues]); function goForward() { const step = steps.current.id; const found = buildCandidateProfileUpdate(draft).issues.filter( (item) => profileStepOfField(item.field) === step, ); if (found.length > 0) { setStepIssues(found); return; } setStepIssues([]); steps.next(); } function handleSubmit(event: FormEvent) { event.preventDefault(); if (!steps.isLast) { goForward(); return; } event.currentTarget.querySelector('button[type="submit"]')?.focus(); onSubmit(); } const stepLabel = (field: string) => profileSteps.find((step) => step.id === profileStepOfField(field))?.label ?? ""; const panel = (id: ProfileStepId) => { const position = profileSteps.findIndex((step) => step.id === id); return { step: profileSteps[position] as FormStep, position: position + 1, total: profileSteps.length, active: steps.current.id === id, headingRef: steps.headingRef(id), }; }; const overlaps = reviewExperienceOverlaps(draft); return (
{shownIssues.length > 0 ? (
Проверьте профиль} >
    {listedIssues.map((item, index) => (
  • {stepLabel(item.field)} {fieldLabel(item.field) ? `, ${fieldLabel(item.field)}` : ""}: {" "} {item.message}
  • ))}
) : null}
Данные профиля
setDraft({ ...draft, fullName: updateFieldDraft(draft.fullName, event.currentTarget.value), }) } /> setDraft({ ...draft, contacts: { ...draft.contacts, email: updateFieldDraft(draft.contacts.email, event.currentTarget.value), }, }) } /> setDraft({ ...draft, contacts: { ...draft.contacts, phone: updateFieldDraft(draft.contacts.phone, event.currentTarget.value), }, }) } /> setDraft({ ...draft, contacts: { ...draft.contacts, telegram: updateFieldDraft( draft.contacts.telegram, event.currentTarget.value, ), }, }) } />
{draft.roles.map((item, index) => { const base = `roles.${index}`; const specializationId = fieldId(`${base}.specialization`); const gradeId = fieldId(`${base}.self_assessed_grade`); return (

Роль {index + 1}

); })}

Подтвержденные категории

Эти результаты устанавливает оценка. Их нельзя изменить в профиле.

{draft.confirmedCategories.length > 0 ? (
    {draft.confirmedCategories.map((category) => (
  • {`${specializationLabel(category.specialization)} · ${gradeLabel(category.grade)}`}
  • ))}
) : (

Подтвержденных категорий пока нет.

)}
{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 (

Место работы {index + 1}

setDraft( updateExperienceDraft(draft, item.id, { employer_name: event.currentTarget.value || null, }), ) } /> setDraft( updateExperienceDraft(draft, item.id, { started_on: event.currentTarget.value, }), ) } /> setDraft( updateExperienceDraft(draft, item.id, { ended_on: event.currentTarget.value || null, }), ) } />