feat(demo): add the jury guide and demonstration markers to the demo stand build

This commit is contained in:
shira committed 2026-10-10 01:27:17 +03:00
1 parent d365a05c96
commit 41206abbcf
32 files changed
+1096 -141

No files matched your search

@@ -0,0 +1,58 @@
import { renderToString } from "react-dom/server";
import {
StaticRouterProvider,
createStaticHandler,
createStaticRouter,
matchRoutes,
} from "react-router-dom";
import { describe, expect, it } from "vitest";
import { guideRoles } from "../../pages/jury-guide";
import { createRoutes } from "./routes";
async function renderPath(path: string, demo: boolean): Promise<string> {
const handler = createStaticHandler(createRoutes({ demo }));
const context = await handler.query(new Request(`http://localhost${path}`));
if (context instanceof Response) throw new Error(`Unexpected response for ${path}`);
const router = createStaticRouter(handler.dataRoutes, context);
return renderToString(<StaticRouterProvider router={router} context={context} hydrate={false} />);
}
describe("demonstration stand routes", () => {
it("serves the jury guide and the banner only in a demo build", async () => {
expect(await renderPath("/demo", true)).toMatch(/<h1[^>]*>Гид для жюри<\/h1>/);
expect(await renderPath("/demo", false)).toMatch(/<h1[^>]*>Страница не найдена<\/h1>/);
expect(await renderPath("/", true)).toContain("Демонстрационный стенд.");
expect(await renderPath("/", false)).not.toContain("Демонстрационный стенд.");
});
it("links the jury guide from the landing page only in a demo build", async () => {
const demo = await renderPath("/", true);
const production = await renderPath("/", false);
expect(demo).toMatch(/<a[^>]*href="\/demo"[^>]*>Открыть гид для жюри<\/a>/);
expect(production).not.toContain("Открыть гид для жюри");
expect(production).not.toContain('href="/demo"');
});
it("keeps the skip link as the first link of a demo page", async () => {
const html = await renderPath("/", true);
const firstLink = html.match(/<a[^>]*>(.*?)<\/a>/);
expect(firstLink?.[0]).toContain('href="#main-content"');
});
it("resolves every link of the guide to a page of the router, not to not-found", () => {
const routes = createRoutes({ demo: true });
const links = guideRoles.flatMap((role) =>
role.steps.flatMap((step) => (step.link ? [step.link.to] : [])),
);
expect(links.length).toBeGreaterThan(0);
for (const to of links) {
const matches = matchRoutes(routes, to);
expect(matches, to).not.toBeNull();
expect(matches?.at(-1)?.route.path, to).not.toBe("*");
}
});
});
+128 -117
View File
@@ -12,6 +12,7 @@ import { PrivacyPage } from "../../pages/privacy";
import { SessionGate } from "../../entities/session";
import { MatchesPage } from "../../pages/matches";
import { InvitationComposePage } from "../../pages/invitation-compose";
import { JuryGuidePage } from "../../pages/jury-guide";
import { NotFoundPage } from "../../pages/not-found";
import { NeedEditorPage } from "../../pages/need-editor";
import { NeedListPage } from "../../pages/needs";
@@ -27,7 +28,7 @@ import {
SupportCasesPage,
} from "../../pages/support-cases";
import { WelcomePage } from "../../pages/welcome";
import { paths } from "../../shared/config";
import { paths, standMode, type StandMode } from "../../shared/config";
import { CandidateShell } from "../../widgets/candidate-shell";
import { EmployerShell } from "../../widgets/employer-shell";
import { PublicShell } from "../../widgets/public-shell";
@@ -38,120 +39,130 @@ import { SupportRoute } from "./support-route";
/**
* Route tree with public pages and role-specific cabinets. Protected shells
* restore the server session before they render any cabinet child.
* restore the server session before they render any cabinet child. The jury
* guide and the demonstration banner exist only in a demo build; elsewhere
* the guide path answers with the not-found page.
*/
export const routes: RouteObject[] = [
{
element: <RootLayout />,
errorElement: <RouteErrorPage />,
children: [
{
element: <PublicShell />,
children: [
{ index: true, element: <WelcomePage /> },
{ path: paths.login, element: <LoginPage /> },
{ path: paths.register, element: <RegisterPage /> },
{ path: paths.verifyEmail, element: <VerifyEmailPage /> },
{ path: paths.support, element: <SupportRoute /> },
{ path: paths.status, element: <StatusPage /> },
{ path: "*", element: <NotFoundPage /> },
],
},
{
path: paths.candidate.root,
element: <CandidateShell />,
children: [
{
element: <SessionGate scenario="candidate" />,
children: [
{ index: true, element: <CandidateHomeRoute /> },
{ path: paths.candidate.onboarding, element: <CandidateOnboardingPage /> },
{
path: paths.candidate.profile,
element: <ProfilePage />,
},
{
path: paths.candidate.questionnaire,
element: <QuestionnairePage />,
},
{
path: paths.candidate.assessment,
element: <AssessmentPage />,
},
{
path: `${paths.candidate.assessment}/:attemptId`,
element: <AssessmentAttemptPage />,
},
{ path: paths.candidate.results, element: <AssessmentResultsPage /> },
{ path: `${paths.candidate.results}/:attemptId`, element: <AssessmentResultPage /> },
{ path: paths.candidate.invitations, element: <CandidateInvitationsPage /> },
{
path: `${paths.candidate.invitations}/:invitationId`,
element: <CandidateInvitationPage />,
},
{ path: paths.candidate.notifications, element: <CandidateNotificationsPage /> },
{
path: paths.candidate.privacy,
element: <PrivacyPage />,
},
{ path: paths.candidate.supportCases, element: <SupportCasesPage /> },
{ path: paths.candidate.supportNew, element: <CreateSupportCasePage /> },
{ path: paths.candidate.supportManual, element: <ManualAssessmentPage /> },
{
path: `${paths.candidate.supportCases}/:caseId`,
element: <SupportCaseDetailPage />,
},
{
path: "*",
element: (
<NotFoundPage homePath={paths.candidate.root} homeLabel="В кабинет кандидата" />
),
},
],
},
],
},
{
path: paths.employer.root,
element: <EmployerShell />,
children: [
{
element: <SessionGate scenario="employer" />,
children: [
{ index: true, loader: () => redirect(paths.employer.company) },
{
path: paths.employer.company,
element: <CompanyPage />,
},
{ path: paths.employer.needs, element: <NeedListPage /> },
{ path: `${paths.employer.needs}/new`, element: <NeedEditorPage /> },
{ path: `${paths.employer.needs}/:needId`, element: <NeedEditorPage /> },
{ path: paths.employer.supportCases, element: <SupportCasesPage /> },
{ path: paths.employer.supportNew, element: <CreateSupportCasePage /> },
{
path: `${paths.employer.supportCases}/:caseId`,
element: <SupportCaseDetailPage />,
},
{ path: paths.employer.candidates, element: <MatchesPage /> },
{
path: paths.employer.invitations,
element: <PlaceholderPage screen="employerInvitations" />,
},
{ path: paths.employer.invitationNew, element: <InvitationComposePage /> },
{ path: paths.employer.notifications, element: <EmployerNotificationsPage /> },
{
path: "*",
element: (
<NotFoundPage
homePath={paths.employer.company}
homeLabel="В кабинет работодателя"
/>
),
},
],
},
],
},
],
},
];
export function createRoutes(stand: StandMode = standMode): RouteObject[] {
return [
{
element: <RootLayout demoStand={stand.demo} />,
errorElement: <RouteErrorPage />,
children: [
{
element: <PublicShell />,
children: [
{ index: true, element: <WelcomePage demoStand={stand.demo} /> },
{ path: paths.login, element: <LoginPage /> },
{ path: paths.register, element: <RegisterPage /> },
{ path: paths.verifyEmail, element: <VerifyEmailPage /> },
{ path: paths.support, element: <SupportRoute /> },
{ path: paths.status, element: <StatusPage /> },
...(stand.demo ? [{ path: paths.demoGuide, element: <JuryGuidePage /> }] : []),
{ path: "*", element: <NotFoundPage /> },
],
},
{
path: paths.candidate.root,
element: <CandidateShell />,
children: [
{
element: <SessionGate scenario="candidate" />,
children: [
{ index: true, element: <CandidateHomeRoute /> },
{ path: paths.candidate.onboarding, element: <CandidateOnboardingPage /> },
{
path: paths.candidate.profile,
element: <ProfilePage />,
},
{
path: paths.candidate.questionnaire,
element: <QuestionnairePage />,
},
{
path: paths.candidate.assessment,
element: <AssessmentPage />,
},
{
path: `${paths.candidate.assessment}/:attemptId`,
element: <AssessmentAttemptPage />,
},
{ path: paths.candidate.results, element: <AssessmentResultsPage /> },
{
path: `${paths.candidate.results}/:attemptId`,
element: <AssessmentResultPage />,
},
{ path: paths.candidate.invitations, element: <CandidateInvitationsPage /> },
{
path: `${paths.candidate.invitations}/:invitationId`,
element: <CandidateInvitationPage />,
},
{ path: paths.candidate.notifications, element: <CandidateNotificationsPage /> },
{
path: paths.candidate.privacy,
element: <PrivacyPage />,
},
{ path: paths.candidate.supportCases, element: <SupportCasesPage /> },
{ path: paths.candidate.supportNew, element: <CreateSupportCasePage /> },
{ path: paths.candidate.supportManual, element: <ManualAssessmentPage /> },
{
path: `${paths.candidate.supportCases}/:caseId`,
element: <SupportCaseDetailPage />,
},
{
path: "*",
element: (
<NotFoundPage homePath={paths.candidate.root} homeLabel="В кабинет кандидата" />
),
},
],
},
],
},
{
path: paths.employer.root,
element: <EmployerShell />,
children: [
{
element: <SessionGate scenario="employer" />,
children: [
{ index: true, loader: () => redirect(paths.employer.company) },
{
path: paths.employer.company,
element: <CompanyPage />,
},
{ path: paths.employer.needs, element: <NeedListPage /> },
{ path: `${paths.employer.needs}/new`, element: <NeedEditorPage /> },
{ path: `${paths.employer.needs}/:needId`, element: <NeedEditorPage /> },
{ path: paths.employer.supportCases, element: <SupportCasesPage /> },
{ path: paths.employer.supportNew, element: <CreateSupportCasePage /> },
{
path: `${paths.employer.supportCases}/:caseId`,
element: <SupportCaseDetailPage />,
},
{ path: paths.employer.candidates, element: <MatchesPage /> },
{
path: paths.employer.invitations,
element: <PlaceholderPage screen="employerInvitations" />,
},
{ path: paths.employer.invitationNew, element: <InvitationComposePage /> },
{ path: paths.employer.notifications, element: <EmployerNotificationsPage /> },
{
path: "*",
element: (
<NotFoundPage
homePath={paths.employer.company}
homeLabel="В кабинет работодателя"
/>
),
},
],
},
],
},
],
},
];
}
export const routes: RouteObject[] = createRoutes();
+8 -1
View File
@@ -1,10 +1,17 @@
import { Outlet, ScrollRestoration } from "react-router-dom";
import { DemoStandBanner } from "../../widgets/demo-stand-banner";
type RootLayoutProps = {
/** True only in a demo build; the banner marks synthetic data on every page. */
demoStand?: boolean;
};
/** Top route element shared by every route group. */
export function RootLayout() {
export function RootLayout({ demoStand = false }: RootLayoutProps) {
return (
<>
<ScrollRestoration />
{demoStand ? <DemoStandBanner /> : null}
<Outlet />
</>
);
@@ -1,13 +1,17 @@
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
import {
createOrganizationInvitation,
getGetOrganizationInvitationContactsQueryKey,
getGetOrganizationInvitationQueryKey,
getOrganizationInvitation,
getOrganizationInvitationContacts,
sendOrganizationInvitation,
updateOrganizationInvitation,
} from "../../../shared/api/endpoints/invitation/invitation";
import {
ContactDisclosure as contactDisclosureSchema,
OrganizationInvitation as organizationInvitationSchema,
type ContactDisclosure,
type OrganizationInvitation,
type OrganizationInvitationCreate,
type OrganizationInvitationUpdate,
@@ -100,8 +104,30 @@ export async function readOrganizationInvitation(
);
}
/**
* Reads the contacts that an active grant of an accepted invitation covers.
* The server answers 404 when no grant is readable, which the caller shows as
* "not available" without asking for a reason.
*/
export async function readInvitationContacts(
organizationId: string,
invitationId: string,
signal: AbortSignal | undefined = undefined,
): Promise<ContactDisclosure> {
const parsed = contactDisclosureSchema.safeParse(
await getOrganizationInvitationContacts(organizationId, invitationId, signal ? { signal } : {}),
);
if (!parsed.success) throw invalidResponse();
return parsed.data;
}
/** Invitation reads stay separate for each signed-in account. */
export const invitationQueryKeys = {
detail: (accountId: string, organizationId: string, invitationId: string) =>
[...getGetOrganizationInvitationQueryKey(organizationId, invitationId), accountId] as const,
contacts: (accountId: string, organizationId: string, invitationId: string) =>
[
...getGetOrganizationInvitationContactsQueryKey(organizationId, invitationId),
accountId,
] as const,
};
@@ -7,10 +7,12 @@
export {
createInvitationDraft,
invitationQueryKeys,
readInvitationContacts,
readOrganizationInvitation,
sendInvitationDraft,
updateInvitationDraft,
} from "./api/organization-invitations";
export { contactRows, type ContactRow } from "./model/contact-disclosure";
export {
acceptCandidateInvitation,
candidateInvitationQueryKeys,
@@ -0,0 +1,38 @@
import { describe, expect, it } from "vitest";
import type { ContactDisclosure } from "../../../shared/api/schemas";
import { contactRows } from "./contact-disclosure";
const base: ContactDisclosure = {
invitation_id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60",
grant_id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e61",
fields: ["email"],
granted_at: "2026-10-09T10:00:00Z",
full_name: null,
email: "candidate@example.test",
phone: null,
telegram: null,
};
describe("contactRows", () => {
it("lists only the kinds the grant covers", () => {
expect(contactRows(base)).toEqual([
{ kind: "email", label: "Электронная почта", value: "candidate@example.test" },
]);
});
it("keeps the contract order of the kinds whatever order the server sends them in", () => {
const rows = contactRows({ ...base, fields: ["telegram", "full_name", "email"] });
expect(rows.map((row) => row.kind)).toEqual(["full_name", "email", "telegram"]);
});
it("shows a covered kind with a null value when the profile no longer holds it", () => {
const rows = contactRows({ ...base, fields: ["phone"], phone: null });
expect(rows).toEqual([{ kind: "phone", label: "Телефон", value: null }]);
});
it("returns no rows for a grant that covers nothing", () => {
expect(contactRows({ ...base, fields: [] })).toEqual([]);
});
});
@@ -0,0 +1,30 @@
import type { ContactDisclosure, ContactFieldKind } from "../../../shared/api/schemas";
import { contactKindLabels, orderedContactKinds } from "./candidate-labels";
export type ContactRow = {
readonly kind: ContactFieldKind;
readonly label: string;
/** Null when the grant covers the kind but the profile no longer holds the value. */
readonly value: string | null;
};
const valueOf: Readonly<
Record<ContactFieldKind, (disclosure: ContactDisclosure) => string | null>
> = {
full_name: (disclosure) => disclosure.full_name,
email: (disclosure) => disclosure.email,
phone: (disclosure) => disclosure.phone,
telegram: (disclosure) => disclosure.telegram,
};
/**
* Rows for the kinds that the grant covers, in contract order. A kind outside
* the grant gets no row, so nothing reads as "not disclosed" by accident.
*/
export function contactRows(disclosure: ContactDisclosure): ContactRow[] {
return orderedContactKinds(disclosure.fields).map((kind) => ({
kind,
label: contactKindLabels[kind],
value: valueOf[kind](disclosure),
}));
}
@@ -67,6 +67,12 @@
line-height: var(--line-height-body);
}
.subtitle {
margin: 0;
font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
}
.notice {
margin: 0;
padding: var(--space-3);
@@ -53,6 +53,7 @@ import {
type InvitationPreviewSnapshot,
} from "../../../features/send-invitation";
import { InvitationPreview } from "../../../widgets/invitation-preview";
import { InvitationContacts } from "./invitation-contacts";
import styles from "./invitation-compose-page.module.css";
function isAccessLoss(error: unknown): error is ApiRequestError {
@@ -85,13 +86,23 @@ function cardFallbackOf(organization: OrganizationQuery) {
}
type SentInvitationProps = {
accountId: string;
invitation: OrganizationInvitation;
organization: OrganizationQuery;
organizationId: string;
};
/** The invitation after sending, with the state and the deadline the server stored. */
function SentInvitation({ invitation, organization, organizationId }: SentInvitationProps) {
/**
* The invitation after sending, with the state and the deadline the server
* stored. Once the candidate accepts, the contacts the grant covers are read
* here; before that the server has none to show.
*/
function SentInvitation({
accountId,
invitation,
organization,
organizationId,
}: SentInvitationProps) {
const headingRef = useRef<HTMLHeadingElement>(null);
useEffect(() => {
@@ -145,6 +156,13 @@ function SentInvitation({ invitation, organization, organizationId }: SentInvita
Срок ответа задал сервер при доставке; письмо кандидату его не сдвигает. Контакты кандидата
появятся только после принятия приглашения.
</p>
{invitation.state === "accepted" ? (
<InvitationContacts
accountId={accountId}
organizationId={organizationId}
invitationId={invitation.id}
/>
) : null}
<InvitationPreview
title="Отправленные условия"
card={organization.data?.candidate_card ?? null}
@@ -253,7 +271,12 @@ function InvitationWorkspace({
return (
<>
{header}
<SentInvitation invitation={sent} organization={company} organizationId={organizationId} />
<SentInvitation
accountId={accountId}
invitation={sent}
organization={company}
organizationId={organizationId}
/>
</>
);
}
@@ -300,6 +323,7 @@ function InvitationWorkspace({
<>
{header}
<SentInvitation
accountId={accountId}
invitation={resume.data}
organization={company}
organizationId={organizationId}
@@ -0,0 +1,76 @@
import { useQuery } from "@tanstack/react-query";
import { useId } from "react";
import { ApiRequestError } from "../../../shared/api";
import {
contactRows,
invitationQueryKeys,
readInvitationContacts,
} from "../../../entities/invitation";
import { ErrorState, LoadingState } from "../../../shared/ui";
import styles from "./invitation-compose-page.module.css";
type InvitationContactsProps = {
accountId: string;
organizationId: string;
invitationId: string;
};
/**
* Contacts that the candidate disclosed with an accepted invitation. The
* server answers 404 while no grant is readable, and it does not say why, so
* that answer is shown as "not available" with the possible reasons. Every
* open reads again, so a revoked grant closes on the next read.
*/
export function InvitationContacts({
accountId,
organizationId,
invitationId,
}: InvitationContactsProps) {
const headingId = useId();
const contacts = useQuery({
queryKey: invitationQueryKeys.contacts(accountId, organizationId, invitationId),
queryFn: ({ signal }) => readInvitationContacts(organizationId, invitationId, signal),
gcTime: 0,
staleTime: 0,
refetchOnWindowFocus: "always",
retry: false,
});
const error = contacts.error;
return (
<section className={styles.result} aria-labelledby={headingId}>
<h3 id={headingId} className={styles.subtitle}>
Контакты кандидата
</h3>
{contacts.isPending ? <LoadingState label="Читаем переданные контакты..." /> : null}
{contacts.isError && error instanceof ApiRequestError && error.status === 404 ? (
<p className={styles.hint} role="status">
Контакты пока недоступны. Кандидат может еще не принять приглашение, отозвать передачу
контактов или закрыть профиль для этой компании. Сервер не сообщает причину.
</p>
) : null}
{contacts.isError && !(error instanceof ApiRequestError && error.status === 404) ? (
<ErrorState
error={error}
title="Не удалось прочитать контакты"
isRetrying={contacts.isFetching}
onRetry={() => void contacts.refetch()}
/>
) : null}
{contacts.data ? (
contactRows(contacts.data).length === 0 ? (
<p className={styles.hint}>Кандидат не передал ни одного контакта.</p>
) : (
<dl className={styles.summary}>
{contactRows(contacts.data).map((row) => (
<div key={row.kind} className={styles.fact}>
<dt>{row.label}</dt>
<dd>{row.value ?? "Профиль больше не содержит это поле"}</dd>
</div>
))}
</dl>
)
) : null}
</section>
);
}
+2
View File
@@ -0,0 +1,2 @@
export { JuryGuidePage } from "./ui/jury-guide-page";
export { guideRoles } from "./model/guide";
@@ -0,0 +1,156 @@
import { paths } from "../../../shared/config";
/** One screen the jury opens from a step. `to` is a router path, never a query-bearing URL. */
export type GuideLink = {
readonly label: string;
readonly to: string;
};
export type GuideStep = {
readonly text: string;
/** Null when the step is done on a screen that has no stable address. */
readonly link: GuideLink | null;
};
/** A block of steps played with one account. */
export type GuideRole = {
readonly title: string;
readonly account: string;
readonly steps: readonly GuideStep[];
};
export const demoAccountDomain = "demo.lincodex.test";
/**
* The eight-minute route in the order a jury member plays it. Each block names
* the account to sign in with, so the two roles alternate without guidance.
*/
export const guideRoles: readonly GuideRole[] = [
{
title: "Кандидат: самостоятельная проверка",
account: `candidate@${demoAccountDomain}`,
steps: [
{
text: "Войдите под логином кандидата. Пароль указан в разделе «Логины» ниже. После входа откроется сохраненный шаг «Первые шаги» с согласиями: они уже выданы стендом, поэтому дальше переходите по ссылкам гида.",
link: { label: "Открыть вход", to: paths.login },
},
{
text: "На странице проверки нажмите «Начать демонстрацию». Экспресс-запуск занимает 3-5 минут и состоит из трех заданий. Итог не присваивает уровень: на экране есть пометка «Демонстрация без реального грейда», а результат не попадает в историю реальных проверок.",
link: { label: "Открыть проверку знаний", to: paths.candidate.assessment },
},
{
text: "На той же странице посмотрите полную проверку Backend, Junior, Go: 25 заданий, срок 72 часа, без практики. Кнопка «Начать полную проверку» видна, но ее можно не нажимать: запуск создает попытку на стенде.",
link: { label: "Открыть полную проверку", to: paths.candidate.assessment },
},
],
},
{
title: "Кандидат с подготовленным результатом",
account: `prepared-1@${demoAccountDomain}`,
steps: [
{
text: "Войдите как prepared-1. В профиле нет ФСП ID: профиль заполнен вручную, а строка опыта помечена как синтетический профиль.",
link: { label: "Открыть профиль", to: paths.candidate.profile },
},
{
text: "В результатах полный тест Backend, Junior, Go уже пройден. Категория помечена как демонстрационная: происхождение решения - синтетическая демонстрация стенда, пороги не калиброваны.",
link: { label: "Открыть результаты", to: paths.candidate.results },
},
{
text: "В настройках приватности карточка опубликована. Предпросмотр показывает доказательство навыка с пометкой «Демонстрационное подтверждение».",
link: { label: "Открыть настройки приватности", to: paths.candidate.privacy },
},
],
},
{
title: "Работодатель: потребность, подбор и приглашение",
account: `employer-alpha@${demoAccountDomain}`,
steps: [
{
text: "Войдите как employer-alpha. Организация «Альфа» выбирается сама: этот аккаунт ее владелец. Нажмите «Создать потребность» и заполните название, специализацию Backend, грейд Junior, обязательный навык Go и зарплатную вилку с базой суммы (до налога), затем нажмите «Создать потребность» внизу формы.",
link: { label: "Открыть потребности", to: paths.employer.needs },
},
{
text: "Откройте подбор кандидатов по этой потребности и нажмите «Найти кандидатов»: в основной группе шесть подготовленных карточек. Нажмите «Показать объяснение»: смысловая близость нейтральна (0,50) и помечена «смысловой анализ недоступен», потому что ML на стенде не работает. Остальные компоненты посчитал сервер.",
link: { label: "Открыть подбор", to: paths.employer.candidates },
},
{
text: "Нажмите «Пригласить» у одного из подготовленных кандидатов. Большая часть условий уже заполнена из потребности; выберите тип предложения и канал связи, отметьте хотя бы один формат работы и для каждого условия пакета укажите «Предусмотрено» с описанием. Затем нажмите «Отправить приглашение» и сохраните адрес страницы: в нем invitation_id, по нему открывается приглашение после ответа кандидата.",
link: null,
},
],
},
{
title: "Кандидат отвечает на приглашение",
account: `prepared-1@${demoAccountDomain}`,
steps: [
{
text: "Войдите как prepared-1 и откройте приглашения. Откройте приглашение от «Альфы», отметьте только электронную почту, подтвердите текст согласия C4 и нажмите «Принять и передать контакты».",
link: { label: "Открыть приглашения", to: paths.candidate.invitations },
},
],
},
{
title: "Работодатель читает переданный контакт",
account: `employer-alpha@${demoAccountDomain}`,
steps: [
{
text: "Войдите как employer-alpha и откройте сохраненный адрес приглашения. Блок «Контакты кандидата» показывает только то, что кандидат выбрал: электронную почту. Другие виды контактов в нем не выводятся.",
link: null,
},
],
},
];
export type GuideAccount = {
readonly login: string;
readonly role: string;
readonly purpose: string;
};
/** The synthetic accounts the seed creates; the password is shared by all of them. */
export const guideAccounts: readonly GuideAccount[] = [
{
login: `candidate@${demoAccountDomain}`,
role: "Кандидат без попыток",
purpose: "Экспресс-запуск и полная проверка",
},
{
login: `prepared-1@${demoAccountDomain} - prepared-6@${demoAccountDomain}`,
role: "Кандидат с подготовленным полным результатом и опубликованной карточкой",
purpose: "Результат, приватность, приглашение и ответ на него",
},
{
login: `employer-alpha@${demoAccountDomain}`,
role: "Владелец «Альфы», рекрутер «Беты»",
purpose: "Потребность, подбор, приглашение и чтение контакта",
},
{
login: `employer-beta@${demoAccountDomain}`,
role: "Владелец «Беты»",
purpose: "Второй работодатель для сравнения доступа",
},
];
/** Items that only simulate the product; each one is named as a simulation. */
export const demonstrationItems: readonly string[] = [
"Все люди на стенде синтетические: кандидаты, компании и их описания вымышлены. Адреса на домене demo.lincodex.test никогда не получают почту.",
"Подготовленные полные результаты созданы командой demo-seed обычными операциями попытки. Ответы выбраны заранее, а проходила их команда стенда, а не кандидат.",
"Категория «Демонстрационное подтверждение» (источник synthetic_demo) не калибрована и не измеряет навык. Банк заданий синтетический и предметной проверки не проходил.",
"Экспресс-запуск показывает механику проверки. Он не присваивает грейд, не создает категорию и не дает доказательства навыка.",
"ML на стенде не вызывается: смысловая близость нейтральна (0,50), а карточки помечены «смысловой анализ недоступен». ФСП не подключен ни в каком режиме, профиль заполняется вручную.",
"На стенде нет видеоматериалов: экран показывает работающий интерфейс на синтетических данных, а не запись.",
];
/** Behaviour that is real code on the stand, not a simulation. */
export const workingItems: readonly string[] = [
"Регистрация, вход, согласия C1-C5, профиль, анкета, настройки приватности и обращения в поддержку работают как в рабочей сборке.",
"Полный тест идет по серверным правилам: попытка, ответы, срок и завершение, а итог считает политика, без ручного вмешательства.",
"Подбор и объяснение позиции считает сервер детерминированно, без ML. Приглашения, принятие и отказ с согласием C4 и чтение раскрытых контактов работают на синтетических данных.",
];
export const guideLimits: readonly string[] = [
"Почта на стенде может быть отключена: новая регистрация не подтверждается, но маршрут на почту не опирается.",
"Список приглашений компании пока заготовка, поэтому приглашение открывается по сохраненному адресу страницы.",
"Не регистрируйте на стенде реальных людей и не вводите реальные данные.",
];
@@ -0,0 +1,80 @@
.roles,
.steps,
.list {
display: grid;
gap: var(--space-4);
margin: 0;
padding: 0;
list-style: none;
}
.role {
display: grid;
gap: var(--space-2);
padding: var(--space-4) 0 var(--space-4) var(--space-4);
border-left: var(--line-strong) solid var(--color-accent);
}
.role-title {
margin: 0;
font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
line-height: var(--line-height-snug);
}
.account {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
/* Continues the numbering from the previous block through the start attribute. */
.steps {
gap: var(--space-3);
padding-left: var(--space-5);
list-style: decimal;
}
.steps li {
padding-left: var(--space-1);
}
.steps p {
margin: 0 0 var(--space-1);
}
.list {
gap: var(--space-2);
padding-left: var(--space-4);
list-style: disc;
}
.table-wrap {
overflow-x: auto;
}
.table {
width: 100%;
border-collapse: collapse;
font-size: var(--font-size-s);
}
.table th,
.table td {
padding: var(--space-2);
border-bottom: var(--line-thin) solid var(--color-divider);
text-align: left;
vertical-align: top;
}
.table code {
overflow-wrap: anywhere;
font-family: var(--font-mono);
font-size: var(--font-size-xs);
}
.account code {
overflow-wrap: anywhere;
font-family: var(--font-mono);
font-size: var(--font-size-xs);
}
@@ -0,0 +1,98 @@
import { renderToString } from "react-dom/server";
import { StaticRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import { guideRoles } from "../model/guide";
import { JuryGuidePage } from "./jury-guide-page";
function render(): string {
return renderToString(
<StaticRouter location="/demo">
<JuryGuidePage />
</StaticRouter>,
);
}
function hrefs(html: string): string[] {
return [...html.matchAll(/<a[^>]*href="([^"]+)"/g)].map((match) => match[1] ?? "");
}
describe("jury guide page", () => {
it("renders one heading with the demonstration eyebrow and the memo title", () => {
const html = render();
expect(html.match(/<h1[\s>]/g)?.length).toBe(1);
expect(html).toMatch(/<h1[^>]*>Гид для жюри<\/h1>/);
expect(html).toContain("Демонстрационный стенд");
});
it("explains the product in the first section", () => {
const html = render();
expect(html).toContain("Что такое Lincodex");
expect(html).toContain("Заявленный уровень в анкете остается самооценкой");
});
it("separates the demonstration simulations from the working functionality", () => {
const html = render();
const simulations = html.indexOf("Что здесь демонстрационное");
const working = html.indexOf("Что работает без имитации");
expect(simulations).toBeGreaterThan(0);
expect(working).toBeGreaterThan(simulations);
expect(html).toContain("синтетические");
expect(html).toContain("не калибрована");
expect(html).toContain("смысловой анализ недоступен");
expect(html).toContain("ФСП не подключен");
expect(html).toContain("Экспресс-запуск показывает механику проверки");
});
it("numbers the route across the role blocks in one continuous sequence", () => {
const html = render();
const starts = [...html.matchAll(/<ol class="[^"]*" start="(\d+)">/g)].map((match) =>
Number(match[1]),
);
const lastBlock = guideRoles.at(-1)!;
expect(starts).toHaveLength(guideRoles.length);
expect(starts[0]).toBe(1);
expect(starts.at(-1)).toBe(
guideRoles.slice(0, -1).reduce((total, role) => total + role.steps.length, 0) + 1,
);
expect(lastBlock.steps.length).toBeGreaterThan(0);
});
it("names the account of every role block", () => {
const html = render();
expect(html).toContain("candidate@demo.lincodex.test");
expect(html).toContain("prepared-1@demo.lincodex.test");
expect(html).toContain("employer-alpha@demo.lincodex.test");
});
it("shows where the password comes from without printing its value", () => {
const html = render();
expect(html).toContain("DEMO_ACCOUNT_PASSWORD");
expect(html).toContain("deploy/demo/demo.env.example");
expect(html).not.toContain("synthetic demo stand only 2026");
});
it("renders every step link as a link of the guide", () => {
const html = render();
const links = guideRoles.flatMap((role) =>
role.steps.flatMap((step) => (step.link ? [step.link.to] : [])),
);
expect(links.length).toBeGreaterThan(0);
for (const to of links) {
expect(hrefs(html)).toContain(to);
}
});
it("states the limits: mail may be off and real people must not register", () => {
const html = render();
expect(html).toContain("Почта на стенде может быть отключена");
expect(html).toContain("Не регистрируйте на стенде реальных людей");
});
});
@@ -0,0 +1,128 @@
import { Page, Section, TextLink } from "../../../shared/ui";
import {
demonstrationItems,
guideAccounts,
guideLimits,
guideRoles,
workingItems,
} from "../model/guide";
import styles from "./jury-guide-page.module.css";
/** Step numbers run on across the role blocks, so the whole route reads as eight to thirteen steps. */
function firstStepNumbers(): number[] {
const starts: number[] = [];
let next = 1;
for (const role of guideRoles) {
starts.push(next);
next += role.steps.length;
}
return starts;
}
/**
* Memo for a jury member who opens the isolated demonstration stand without a
* briefing. It lists the route with the screens to open, the accounts, and the
* parts of the stand that are simulations. The route is shown only in a demo
* build (see routes), so nothing here reaches a production build.
*/
export function JuryGuidePage() {
const starts = firstStepNumbers();
return (
<Page
title="Гид для жюри"
eyebrow="Демонстрационный стенд"
lead="Короткий маршрут на синтетических данных: около восьми минут и две роли. Сначала прочитайте раздел «Что здесь демонстрационное»: он отделяет имитации от работающего функционала."
width="wide"
>
<Section title="Что такое Lincodex">
<p>
Lincodex помогает работодателям находить IT-специалистов по подтвержденным навыкам.
Заявленный уровень в анкете остается самооценкой, а категорию присваивает только результат
проверки.
</p>
</Section>
<Section
title="Маршрут за восемь минут"
description="Блоки идут по ролям. Перед каждым блоком войдите под указанным логином. Кнопки выхода в интерфейсе пока нет, поэтому роли удобнее вести в двух окнах: обычном и приватном."
>
<ol className={styles.roles}>
{guideRoles.map((role, index) => (
<li key={role.title} className={styles.role}>
<h3 className={styles["role-title"]}>{role.title}</h3>
<p className={styles.account}>
Логин: <code>{role.account}</code>
</p>
<ol className={styles.steps} start={starts[index]}>
{role.steps.map((step) => (
<li key={step.text}>
<p>{step.text}</p>
{step.link ? <TextLink to={step.link.to}>{step.link.label}</TextLink> : null}
</li>
))}
</ol>
</li>
))}
</ol>
</Section>
<Section
title="Что здесь демонстрационное"
description="Имитации и подготовленные данные. Они показывают механику, но не измеряют навык человека."
>
<ul className={styles.list}>
{demonstrationItems.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</Section>
<Section title="Что работает без имитации">
<ul className={styles.list}>
{workingItems.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</Section>
<Section title="Логины и пароль">
<p>
Пароль один для всех логинов ниже. Опубликованное значение по умолчанию - переменная
DEMO_ACCOUNT_PASSWORD из файла deploy/demo/demo.env.example. Если организатор задал свой
пароль, используйте его: он передается отдельно.
</p>
<div className={styles["table-wrap"]}>
<table className={styles.table}>
<thead>
<tr>
<th scope="col">Логин</th>
<th scope="col">Роль</th>
<th scope="col">Для чего</th>
</tr>
</thead>
<tbody>
{guideAccounts.map((account) => (
<tr key={account.login}>
<td>
<code>{account.login}</code>
</td>
<td>{account.role}</td>
<td>{account.purpose}</td>
</tr>
))}
</tbody>
</table>
</div>
</Section>
<Section title="Ограничения стенда">
<ul className={styles.list}>
{guideLimits.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</Section>
</Page>
);
}
@@ -0,0 +1,28 @@
import { renderToString } from "react-dom/server";
import { StaticRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import { WelcomePage } from "./welcome-page";
function render(demoStand: boolean): string {
return renderToString(
<StaticRouter location="/">
<WelcomePage demoStand={demoStand} />
</StaticRouter>,
);
}
describe("welcome page", () => {
it("omits the jury section outside a demonstration build", () => {
const html = render(false);
expect(html).not.toContain("Для жюри");
expect(html).not.toContain("гид для жюри");
});
it("offers the jury guide in a demonstration build", () => {
const html = render(true);
expect(html).toContain("Для жюри");
expect(html).toMatch(/<a[^>]*href="\/demo"[^>]*>Открыть гид для жюри<\/a>/);
});
});
+13 -2
View File
@@ -34,15 +34,26 @@ const cabinets = [
/**
* Public start page. It describes the cabinets that work now and names the
* screens that are still placeholders, so the page makes no promise the
* product does not keep.
* product does not keep. A demonstration stand adds the link to the jury guide.
*/
export function WelcomePage() {
export function WelcomePage({ demoStand = false }: { demoStand?: boolean }) {
return (
<Page
title="Протокол подтвержденных навыков"
eyebrow="Lincodex"
lead="Регистрация, вход и основные сценарии кабинетов уже работают. Заявленный уровень остается самооценкой: подтвержденную категорию присваивает только результат теста."
>
{demoStand ? (
<Section title="Для жюри">
<p>
Этот стенд показывает продукт на синтетических данных. Гид описывает маршрут на восемь
минут двумя ролями и отделяет имитации от работающего функционала.
</p>
<div className={styles.actions}>
<ButtonLink to={paths.demoGuide}>Открыть гид для жюри</ButtonLink>
</div>
</Section>
) : null}
<Section title="Кабинеты">
<ul className={styles.cabinets}>
{cabinets.map((cabinet) => (
+1
View File
@@ -1 +1,2 @@
export { paths } from "./paths";
export { standMode, standModeFrom, type StandMode } from "./stand";
+2
View File
@@ -9,6 +9,8 @@ export const paths = {
verifyEmail: "/verify-email",
support: "/support",
status: "/status",
/** Jury guide of the demonstration stand; the route exists only in a demo build. */
demoGuide: "/demo",
candidate: {
root: "/candidate",
onboarding: "/candidate/onboarding",
+16
View File
@@ -0,0 +1,16 @@
import { describe, expect, it } from "vitest";
import { standModeFrom } from "./stand";
describe("standModeFrom", () => {
it("turns the demonstration mode on only for the literal value true", () => {
expect(standModeFrom({ VITE_DEMO_STAND: "true" })).toEqual({ demo: true });
});
it("keeps the mode off when the build sets no flag", () => {
expect(standModeFrom({})).toEqual({ demo: false });
});
it.each(["false", "", "TRUE", "1", "yes"])("keeps the mode off for %j", (value) => {
expect(standModeFrom({ VITE_DEMO_STAND: value }).demo).toBe(false);
});
});
+18
View File
@@ -0,0 +1,18 @@
/**
* Mode of the running build. Builds that serve synthetic demonstration data
* set VITE_DEMO_STAND to "true": the isolated demonstration stand through
* deploy/docker/docker-compose.demo.yml, and the browser suite through
* deploy/docker/docker-compose.e2e.yml. Other builds leave it unset, so the
* jury guide and the demonstration banner are not part of them.
*/
export type StandMode = {
/** True only for a build that serves synthetic demonstration data. */
readonly demo: boolean;
};
/** Reads the mode from build-time environment values; testable without Vite. */
export function standModeFrom(env: Readonly<Record<string, unknown>>): StandMode {
return { demo: env.VITE_DEMO_STAND === "true" };
}
export const standMode: StandMode = standModeFrom(import.meta.env);
@@ -0,0 +1 @@
export { DemoStandBanner } from "./ui/demo-stand-banner";
@@ -0,0 +1,18 @@
.banner {
padding: var(--space-2) var(--space-4);
border-bottom: var(--line-strong) solid var(--color-border-strong);
color: var(--color-text);
background: var(--color-surface);
font-size: var(--font-size-s);
}
.banner p {
margin: 0;
max-width: 80rem;
margin-inline: auto;
}
.label {
color: var(--color-accent);
font-weight: var(--font-weight-bold);
}
@@ -0,0 +1,19 @@
import styles from "./demo-stand-banner.module.css";
/**
* Marks every page of the demonstration stand: the data is synthetic and the
* results are prepared for showing, not measured. It is rendered only by a
* demo build (see app routes), and it has no link, so the first link of a
* page stays the skip link.
*/
export function DemoStandBanner() {
return (
<aside className={styles.banner} aria-label="Статус стенда">
<p>
<strong className={styles.label}>Демонстрационный стенд.</strong> Все данные синтетические,
подготовленные результаты не подтверждают квалификацию. Гид для жюри есть на главной
странице.
</p>
</aside>
);
}