import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query"; import { useEffect, useId, useRef, useState } from "react"; import { candidateInvitationQueryKeys, candidateStatusLabel, contactKindLabels, declineReasonLabels, formatSalaryRange, formatServerMoment, isAnswerable, newerInvitation, orderedContactKinds, readCandidateInvitation, viewCandidateInvitation, useServerNow, type ResponseFailure, listCandidateInvitations, } from "../../../entities/invitation"; import { DeclineInvitationForm } from "../../../features/respond-invitation"; import { acceptDraftResetKey, AcceptContactConsentForm, } from "../../../features/accept-contact-consent"; import { isCurrentCandidateSession, runForCurrentCandidate, } from "../../../features/profile-visibility"; import { getGetCurrentSessionQueryKey, useGetCurrentSession, } from "../../../shared/api/endpoints/identity/identity"; import type { CandidateInvitation, CandidateInvitationSummary, Session, } from "../../../shared/api/schemas"; import { paths } from "../../../shared/config"; import { Button, ButtonLink, Card, EmptyState, ErrorState, ForbiddenState, isAccessDenied, LoadingState, Section, Skeleton, Tag, } from "../../../shared/ui"; import { InvitationTermsArticle } from "../../../widgets/invitation-preview"; import styles from "./candidate-home-invitations.module.css"; const staleAcceptNotice = "Приглашение изменилось после вашего прочтения. Мы загрузили актуальную версию: проверьте условия и подтвердите выбор контактов заново."; const privateQueryOptions = { gcTime: 0, staleTime: 0, retry: false, refetchOnMount: "always" as const, refetchOnWindowFocus: "always" as const, }; function InvitationAnswer({ invitation, csrfToken, serverNow, notice, onAnswered, onFailure, }: { invitation: CandidateInvitation; csrfToken: string; serverNow: number; notice: string | null; onAnswered: (invitation: CandidateInvitation) => void; onFailure: (failure: ResponseFailure) => void; }) { if (!isAnswerable(invitation, serverNow)) { const decline = invitation.decline; return (
{invitation.state === "accepted" ? ( <>

Вы приняли приглашение. Компания получила доступ только к контактам, отмеченным в согласии C4.

{invitation.contact_grant ? ( ) : null} ) : invitation.state === "declined" ? ( <>

Вы отклонили приглашение. Контакты компании не переданы.

{decline ? (

Причина отказа: {declineReasonLabels[decline.reason]}. {decline.comment ? ` Ваш комментарий: ${decline.comment}` : ""}

) : null} ) : (

{candidateStatusLabel(invitation, serverNow)}

)}
); } const offer = invitation.contact_consent; return (
{notice ? (

{notice}

) : null} {offer ? ( ) : (

Принять приглашение нельзя

Компании передаются только контакты из профиля. Добавьте хотя бы один контакт, чтобы принять приглашение.

Открыть профиль
)}
); } function HomeInvitationCard({ item, accountId, actor, serverNow, onAnsweredInHome, }: { item: CandidateInvitationSummary; accountId: string; actor: Session; serverNow: number; onAnsweredInHome: (invitation: CandidateInvitation) => void; }) { const queryClient = useQueryClient(); const cardId = useId(); const [expanded, setExpanded] = useState(false); const [notice, setNotice] = useState(null); const [answeredInvitation, setAnsweredInvitation] = useState(null); const viewedId = useRef(null); const detailKey = candidateInvitationQueryKeys.detail(accountId, item.id); const detail = useQuery({ queryKey: detailKey, queryFn: ({ signal }) => runForCurrentCandidate(queryClient, actor, () => readCandidateInvitation(item.id, signal)), enabled: expanded, ...privateQueryOptions, }); useEffect(() => { if ( !expanded || detail.data?.id !== item.id || actor.csrf_token === "" || viewedId.current === item.id ) { return; } viewedId.current = item.id; void runForCurrentCandidate(queryClient, actor, () => viewCandidateInvitation(item.id, { csrfToken: actor.csrf_token }), ).then( (viewed) => { queryClient.setQueryData(detailKey, (current) => newerInvitation(current, viewed), ); }, () => undefined, ); }, [expanded, detail.data, item.id, actor, queryClient, detailKey]); function handleAnswered(updated: CandidateInvitation) { setAnsweredInvitation(updated); onAnsweredInHome(updated); queryClient.setQueryData(detailKey, (current) => newerInvitation(current, updated), ); setNotice(null); void queryClient.invalidateQueries({ queryKey: candidateInvitationQueryKeys.inbox(accountId), }); } function handleFailure(failure: ResponseFailure) { if (failure.kind === "stale-terms") setNotice(staleAcceptNotice); if (failure.kind === "csrf") { void queryClient.invalidateQueries({ queryKey: getGetCurrentSessionQueryKey() }); } if (failure.refresh) void detail.refetch(); } const displayedInvitation = answeredInvitation ?? item; const answerable = isAnswerable(displayedInvitation, serverNow); return (
  • Компания

    {item.organization.name}

    {candidateStatusLabel(displayedInvitation, serverNow)}

    {item.role_title}

    {formatSalaryRange(item.salary)}

    Срок ответа: до {formatServerMoment(item.response_deadline_at)}

    {expanded ? (
    {detail.isPending ? : null} {detail.isError ? ( isAccessDenied(detail.error) ? ( ) : ( void detail.refetch()} title="Не удалось загрузить условия" /> ) ) : null} {detail.data ? ( <>
    ) : null}
    ) : null}
  • ); } export function CandidateHomeInvitations() { const queryClient = useQueryClient(); const session = useGetCurrentSession(); const actor = session.data; const accountId = actor?.account.id ?? ""; const isCandidate = actor?.account.scenario === "candidate"; const sessionCanRead = Boolean( actor && isCandidate && !session.isPending && !session.isFetching && !session.isError && isCurrentCandidateSession(queryClient, actor), ); const inboxKey = [...candidateInvitationQueryKeys.inbox(accountId), "home"] as const; const inbox = useInfiniteQuery({ queryKey: inboxKey, queryFn: ({ pageParam, signal }) => { if (!actor || actor.account.scenario !== "candidate") { throw new Error("A candidate session is required."); } return runForCurrentCandidate(queryClient, actor, () => listCandidateInvitations({ cursor: pageParam, signal }), ); }, initialPageParam: undefined as string | undefined, getNextPageParam: (lastPage) => lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined, enabled: sessionCanRead, ...privateQueryOptions, }); const serverNow = useServerNow(); const items = inbox.data?.pages.flatMap((page) => page.items) ?? []; const answerable = items.filter((item) => isAnswerable(item, serverNow)); const [responseNotice, setResponseNotice] = useState<{ accountId: string; invitation: CandidateInvitation; } | null>(null); const visibleResponseNotice = responseNotice?.accountId === accountId ? responseNotice.invitation : null; if (session.isError) { return (
    {isAccessDenied(session.error) ? ( ) : ( void session.refetch()} title="Не удалось проверить вход" /> )}
    ); } if (session.isPending || session.isFetching) { return (
    ); } if (!actor) { return (
    ); } if (!isCandidate) return null; if (!sessionCanRead) { return (
    ); } if (inbox.isPending) { return (
    ); } if (inbox.isError) { return (
    {isAccessDenied(inbox.error) ? ( ) : ( void inbox.refetch()} title="Не удалось загрузить приглашения" /> )}
    ); } if (answerable.length === 0 && !inbox.hasNextPage && !visibleResponseNotice) return null; return (
    {visibleResponseNotice ? (
    {visibleResponseNotice.state === "accepted" ? ( <>

    Приглашение принято. Компании открыты только выбранные вами контакты:

      {orderedContactKinds(visibleResponseNotice.contact_grant?.fields ?? []).map( (kind) => (
    • {contactKindLabels[kind]}
    • ), )}
    ) : (

    Приглашение отклонено. Контакты компании не переданы.

    )}
    ) : null} {answerable.length > 0 ? (
      {answerable.map((item) => ( setResponseNotice({ accountId, invitation })} /> ))}
    ) : ( )} {inbox.hasNextPage ? (
    ) : null}
    ); }