Files
lincodex/frontend/src/pages/candidate-home/ui/candidate-home-invitations.tsx
T

465 lines
16 KiB
TypeScript

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 (
<div className={styles.outcome} data-state={invitation.state}>
{invitation.state === "accepted" ? (
<>
<p role="status">
Вы приняли приглашение. Компания получила доступ только к контактам, отмеченным в
согласии C4.
</p>
{invitation.contact_grant ? (
<ul className={styles.granted}>
{orderedContactKinds(invitation.contact_grant.fields).map((kind) => (
<li key={kind}>{contactKindLabels[kind]}</li>
))}
</ul>
) : null}
</>
) : invitation.state === "declined" ? (
<>
<p role="status">Вы отклонили приглашение. Контакты компании не переданы.</p>
{decline ? (
<p>
Причина отказа: {declineReasonLabels[decline.reason]}.
{decline.comment ? ` Ваш комментарий: ${decline.comment}` : ""}
</p>
) : null}
</>
) : (
<p role="status">{candidateStatusLabel(invitation, serverNow)}</p>
)}
</div>
);
}
const offer = invitation.contact_consent;
return (
<div className={styles.answer}>
{notice ? (
<p className={styles.notice} role="status">
{notice}
</p>
) : null}
{offer ? (
<AcceptContactConsentForm
key={acceptDraftResetKey(invitation.id, invitation.terms_version, offer)}
invitation={invitation}
offer={offer}
organizationName={invitation.organization.name}
csrfToken={csrfToken}
onAccepted={onAnswered}
onFailure={onFailure}
/>
) : (
<Card tone="raised">
<h4 className={styles.title}>Принять приглашение нельзя</h4>
<p className={styles.text}>
Компании передаются только контакты из профиля. Добавьте хотя бы один контакт, чтобы
принять приглашение.
</p>
<ButtonLink to={paths.candidate.profile} variant="secondary">
Открыть профиль
</ButtonLink>
</Card>
)}
<DeclineInvitationForm
key={invitation.id}
invitation={invitation}
csrfToken={csrfToken}
onDeclined={onAnswered}
onFailure={onFailure}
/>
</div>
);
}
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<string | null>(null);
const [answeredInvitation, setAnsweredInvitation] = useState<CandidateInvitation | null>(null);
const viewedId = useRef<string | null>(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<CandidateInvitation>(detailKey, (current) =>
newerInvitation(current, viewed),
);
},
() => undefined,
);
}, [expanded, detail.data, item.id, actor, queryClient, detailKey]);
function handleAnswered(updated: CandidateInvitation) {
setAnsweredInvitation(updated);
onAnsweredInHome(updated);
queryClient.setQueryData<CandidateInvitation>(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 (
<li>
<article className={styles.card}>
<header className={styles.head}>
<div>
<p className={styles.label}>Компания</p>
<h3 className={styles.company}>{item.organization.name}</h3>
</div>
<Tag tone={answerable ? "accent" : "neutral"} dot>
{candidateStatusLabel(displayedInvitation, serverNow)}
</Tag>
</header>
<p className={styles.role}>{item.role_title}</p>
<p className={styles.facts}>{formatSalaryRange(item.salary)}</p>
<p className={styles.facts}>
Срок ответа: до {formatServerMoment(item.response_deadline_at)}
</p>
<div className={styles.actions}>
<Button
variant="secondary"
aria-expanded={expanded}
aria-controls={cardId}
onClick={() => setExpanded((current) => !current)}
>
{expanded ? "Скрыть условия" : answerable ? "Ответить на приглашение" : "Показать итог"}
</Button>
</div>
{expanded ? (
<div id={cardId} className={styles.details}>
{detail.isPending ? <LoadingState label="Загружаем условия приглашения..." /> : null}
{detail.isError ? (
isAccessDenied(detail.error) ? (
<ForbiddenState error={detail.error} />
) : (
<ErrorState
error={detail.error}
isRetrying={detail.isFetching}
onRetry={() => void detail.refetch()}
title="Не удалось загрузить условия"
/>
)
) : null}
{detail.data ? (
<>
<section aria-label="Условия приглашения">
<InvitationTermsArticle
terms={detail.data.terms}
responsePeriodDays={null}
responseDeadlineAt={detail.data.response_deadline_at}
headingLevel={4}
/>
</section>
<InvitationAnswer
invitation={detail.data}
csrfToken={actor.csrf_token}
serverNow={serverNow}
notice={notice}
onAnswered={handleAnswered}
onFailure={handleFailure}
/>
</>
) : null}
</div>
) : null}
</article>
</li>
);
}
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 (
<Section title="Приглашения">
{isAccessDenied(session.error) ? (
<ForbiddenState error={session.error} />
) : (
<ErrorState
error={session.error}
isRetrying={session.isRefetching}
onRetry={() => void session.refetch()}
title="Не удалось проверить вход"
/>
)}
</Section>
);
}
if (session.isPending || session.isFetching) {
return (
<Section title="Приглашения" description="Проверяем новые предложения от компаний.">
<LoadingState label="Проверяем текущий вход..." />
</Section>
);
}
if (!actor) {
return (
<Section title="Приглашения">
<ForbiddenState
title="Приглашения недоступны"
description="Откройте кабинет кандидата и повторите проверку входа."
/>
</Section>
);
}
if (!isCandidate) return null;
if (!sessionCanRead) {
return (
<Section title="Приглашения">
<ForbiddenState
title="Приглашения недоступны"
description="Откройте кабинет кандидата и повторите проверку входа."
/>
</Section>
);
}
if (inbox.isPending) {
return (
<Section title="Приглашения" description="Проверяем новые предложения от компаний.">
<LoadingState label="Загружаем приглашения..." />
<Skeleton shape="card" lines={3} />
</Section>
);
}
if (inbox.isError) {
return (
<Section title="Приглашения">
{isAccessDenied(inbox.error) ? (
<ForbiddenState error={inbox.error} />
) : (
<ErrorState
error={inbox.error}
isRetrying={inbox.isFetching}
onRetry={() => void inbox.refetch()}
title="Не удалось загрузить приглашения"
/>
)}
</Section>
);
}
if (answerable.length === 0 && !inbox.hasNextPage && !visibleResponseNotice) return null;
return (
<Section
title="Приглашения"
description="Откройте условия здесь. Контакты передаются только после вашего отдельного выбора и подтверждения согласия C4."
>
{visibleResponseNotice ? (
<div className={styles["response-notice"]} role="status" aria-live="polite">
{visibleResponseNotice.state === "accepted" ? (
<>
<p>Приглашение принято. Компании открыты только выбранные вами контакты:</p>
<ul>
{orderedContactKinds(visibleResponseNotice.contact_grant?.fields ?? []).map(
(kind) => (
<li key={kind}>{contactKindLabels[kind]}</li>
),
)}
</ul>
</>
) : (
<p>Приглашение отклонено. Контакты компании не переданы.</p>
)}
</div>
) : null}
{answerable.length > 0 ? (
<ul className={styles.list}>
{answerable.map((item) => (
<HomeInvitationCard
key={`${accountId}:${item.id}`}
item={item}
accountId={accountId}
actor={actor}
serverNow={serverNow}
onAnsweredInHome={(invitation) => setResponseNotice({ accountId, invitation })}
/>
))}
</ul>
) : (
<EmptyState
title="Открытых приглашений пока нет"
description="Новые предложения от компаний будут появляться здесь."
/>
)}
{inbox.hasNextPage ? (
<div className={styles.more}>
<Button
variant="secondary"
isBusy={inbox.isFetchingNextPage}
onClick={() => void inbox.fetchNextPage()}
>
{inbox.isFetchingNextPage ? "Загружаем..." : "Показать еще приглашения"}
</Button>
</div>
) : null}
</Section>
);
}