feat(candidate): add the candidate home, results and result history screens
This commit is contained in:
1 parent
8277133712
commit
4761508f13
52 files changed
+5334
-81
No files matched your search
@@ -0,0 +1,104 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { ApiRequestError, networkErrorCode } from "../../../shared/api";
|
||||
import type {
|
||||
AssessmentAvailability,
|
||||
CandidateProfile,
|
||||
CandidateQuestionnaire,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { combineJourneyReads } from "./home-queries";
|
||||
|
||||
function read<T>(
|
||||
status: "pending" | "error" | "success",
|
||||
data?: T,
|
||||
error: Error | null = null,
|
||||
refetch: () => unknown = () => undefined,
|
||||
) {
|
||||
return { status, data, error, isRefetching: false, refetch };
|
||||
}
|
||||
|
||||
const profile = { version: 1 } as CandidateProfile;
|
||||
const questionnaire = {
|
||||
version: 1,
|
||||
specializations: [
|
||||
{
|
||||
specialization: "backend",
|
||||
self_assessed_grade: "junior",
|
||||
task_languages: [],
|
||||
stack: [],
|
||||
experience: null,
|
||||
},
|
||||
],
|
||||
work_context: null,
|
||||
updated_at: null,
|
||||
} as CandidateQuestionnaire;
|
||||
const availability = {
|
||||
specializations: [
|
||||
{ specialization: "backend", confirmed_grade: null, active_attempt_id: null, grades: [] },
|
||||
],
|
||||
} as AssessmentAvailability;
|
||||
|
||||
function apiError(status: number) {
|
||||
return new ApiRequestError({ status, code: networkErrorCode, title: "Failed." });
|
||||
}
|
||||
|
||||
describe("combineJourneyReads", () => {
|
||||
it("stays pending until all three reads arrive", () => {
|
||||
const state = combineJourneyReads(
|
||||
"candidate_profile",
|
||||
read("success", profile),
|
||||
read("pending"),
|
||||
read("success", availability),
|
||||
);
|
||||
|
||||
expect(state).toEqual({ status: "pending" });
|
||||
});
|
||||
|
||||
it("builds the journey from the three reads", () => {
|
||||
const state = combineJourneyReads(
|
||||
"candidate_assessment",
|
||||
read("success", profile),
|
||||
read("success", questionnaire),
|
||||
read("success", availability),
|
||||
);
|
||||
|
||||
expect(state.status).toBe("success");
|
||||
if (state.status === "success") {
|
||||
expect(state.journey.savedStep).toBe("candidate_assessment");
|
||||
expect(state.journey.nextStep).toEqual({ kind: "assessment" });
|
||||
}
|
||||
});
|
||||
|
||||
it("fails as a whole instead of guessing a step from partial data", () => {
|
||||
const failure = apiError(500);
|
||||
const state = combineJourneyReads(
|
||||
"candidate_profile",
|
||||
read("error", undefined, failure),
|
||||
read("success", questionnaire),
|
||||
read("success", availability),
|
||||
);
|
||||
|
||||
expect(state).toMatchObject({ status: "error", error: failure });
|
||||
});
|
||||
|
||||
it("shows a denied read before other failures and retries only failed reads", () => {
|
||||
const denied = apiError(403);
|
||||
const failedProfile = vi.fn();
|
||||
const failedAvailability = vi.fn();
|
||||
const okQuestionnaire = vi.fn();
|
||||
const state = combineJourneyReads(
|
||||
"candidate_profile",
|
||||
read("error", undefined, apiError(500), failedProfile),
|
||||
read("success", questionnaire, null, okQuestionnaire),
|
||||
read("error", undefined, denied, failedAvailability),
|
||||
);
|
||||
|
||||
expect(state.status).toBe("error");
|
||||
if (state.status === "error") {
|
||||
expect(state.error).toBe(denied);
|
||||
state.retry();
|
||||
}
|
||||
expect(failedProfile).toHaveBeenCalledOnce();
|
||||
expect(failedAvailability).toHaveBeenCalledOnce();
|
||||
expect(okQuestionnaire).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";
|
||||
import type { z } from "zod";
|
||||
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
|
||||
import {
|
||||
getMyAssessmentAvailability,
|
||||
listMyAssessmentResults,
|
||||
} from "../../../shared/api/endpoints/assessment/assessment";
|
||||
import {
|
||||
getMyProfile,
|
||||
getMyQuestionnaire,
|
||||
} from "../../../shared/api/endpoints/candidate/candidate";
|
||||
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
|
||||
import { getMyPrivacySettings } from "../../../shared/api/endpoints/privacy/privacy";
|
||||
import {
|
||||
AssessmentAvailability,
|
||||
AssessmentResultHistoryPage,
|
||||
CandidateProfile,
|
||||
CandidateQuestionnaire,
|
||||
PrivacySettings,
|
||||
type Session,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { buildCandidateJourney, type CandidateJourney } from "../model/home";
|
||||
|
||||
// The home needs only the version of the profile: 0 means it was never saved.
|
||||
// The profile form validates the rest of the document itself.
|
||||
const profileVersionSchema = CandidateProfile.pick({ version: true });
|
||||
type CandidateProfileVersion = Pick<CandidateProfile, "version">;
|
||||
|
||||
const homeQueryPrefix = ["candidate-home"] as const;
|
||||
|
||||
/** Account-scoped keys: a response for one account never fills another's cache. */
|
||||
export const candidateHomeQueryKeys = {
|
||||
root: homeQueryPrefix,
|
||||
profile: (accountId: string) => [...homeQueryPrefix, accountId, "profile"] as const,
|
||||
questionnaire: (accountId: string) => [...homeQueryPrefix, accountId, "questionnaire"] as const,
|
||||
availability: (accountId: string) => [...homeQueryPrefix, accountId, "availability"] as const,
|
||||
latestResult: (accountId: string) => [...homeQueryPrefix, accountId, "latest-result"] as const,
|
||||
privacy: (accountId: string) => [...homeQueryPrefix, accountId, "privacy"] as const,
|
||||
};
|
||||
|
||||
// Personal data is not kept after the screen closes, and every visit reads the
|
||||
// current state: the home screen must match the API after a refresh.
|
||||
const privateQueryOptions = {
|
||||
gcTime: 0,
|
||||
staleTime: 0,
|
||||
retry: false,
|
||||
refetchOnMount: "always" as const,
|
||||
refetchOnWindowFocus: "always" as const,
|
||||
};
|
||||
|
||||
function parseResponse(schema: z.ZodType, value: unknown): unknown {
|
||||
const parsed = schema.safeParse(value);
|
||||
if (!parsed.success) {
|
||||
throw new ApiRequestError({
|
||||
status: 200,
|
||||
code: invalidResponseCode,
|
||||
title: "The response does not match the API contract.",
|
||||
});
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
function assertSameAccount(queryClient: QueryClient, accountId: string): void {
|
||||
const current = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
|
||||
if (current?.account.id !== accountId) {
|
||||
throw new Error("The candidate session changed during the home request.");
|
||||
}
|
||||
}
|
||||
|
||||
function useHomeQuery<T>(
|
||||
session: Session | undefined,
|
||||
key: (accountId: string) => readonly unknown[],
|
||||
read: (signal: AbortSignal) => Promise<unknown>,
|
||||
schema: z.ZodType,
|
||||
) {
|
||||
const queryClient = useQueryClient();
|
||||
const accountId = session?.account.id;
|
||||
const enabled = session?.account.scenario === "candidate";
|
||||
return useQuery<T, Error>({
|
||||
queryKey: key(accountId ?? "no-session"),
|
||||
enabled,
|
||||
...privateQueryOptions,
|
||||
queryFn: async ({ signal }) => {
|
||||
if (!accountId) throw new Error("A candidate session is required.");
|
||||
assertSameAccount(queryClient, accountId);
|
||||
const response = await read(signal);
|
||||
assertSameAccount(queryClient, accountId);
|
||||
return parseResponse(schema, response) as T;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useCandidateProfileRead(session: Session | undefined) {
|
||||
return useHomeQuery<CandidateProfileVersion>(
|
||||
session,
|
||||
candidateHomeQueryKeys.profile,
|
||||
(signal) => getMyProfile({ signal }),
|
||||
profileVersionSchema,
|
||||
);
|
||||
}
|
||||
|
||||
export function useCandidateQuestionnaireRead(session: Session | undefined) {
|
||||
return useHomeQuery<CandidateQuestionnaire>(
|
||||
session,
|
||||
candidateHomeQueryKeys.questionnaire,
|
||||
(signal) => getMyQuestionnaire({ signal }),
|
||||
CandidateQuestionnaire,
|
||||
);
|
||||
}
|
||||
|
||||
export function useCandidateAvailabilityRead(session: Session | undefined) {
|
||||
return useHomeQuery<AssessmentAvailability>(
|
||||
session,
|
||||
candidateHomeQueryKeys.availability,
|
||||
(signal) => getMyAssessmentAvailability({ signal }),
|
||||
AssessmentAvailability,
|
||||
);
|
||||
}
|
||||
|
||||
/** Newest real result only: the home screen links to the full history. */
|
||||
export function useCandidateLatestResultRead(session: Session | undefined) {
|
||||
return useHomeQuery<AssessmentResultHistoryPage>(
|
||||
session,
|
||||
candidateHomeQueryKeys.latestResult,
|
||||
(signal) => listMyAssessmentResults({ limit: 1 }, { signal }),
|
||||
AssessmentResultHistoryPage,
|
||||
);
|
||||
}
|
||||
|
||||
export function useCandidatePrivacyRead(session: Session | undefined) {
|
||||
return useHomeQuery<PrivacySettings>(
|
||||
session,
|
||||
candidateHomeQueryKeys.privacy,
|
||||
(signal) => getMyPrivacySettings({ signal }),
|
||||
PrivacySettings,
|
||||
);
|
||||
}
|
||||
|
||||
type ReadResult<T> = {
|
||||
status: "pending" | "error" | "success";
|
||||
data: T | undefined;
|
||||
error: Error | null;
|
||||
isRefetching: boolean;
|
||||
refetch: () => unknown;
|
||||
};
|
||||
|
||||
export type CandidateJourneyState =
|
||||
| { status: "pending" }
|
||||
| { status: "error"; error: unknown; isRetrying: boolean; retry: () => void }
|
||||
| { status: "success"; journey: CandidateJourney };
|
||||
|
||||
function isAccessError(error: unknown): boolean {
|
||||
return error instanceof ApiRequestError && (error.status === 401 || error.status === 403);
|
||||
}
|
||||
|
||||
/**
|
||||
* Joins the three reads that the next step depends on. One failed read fails
|
||||
* the whole state, because a step chosen from partial data could send the
|
||||
* candidate to a form they already completed. A denied read wins over other
|
||||
* failures so that the forbidden state is shown instead of a retry.
|
||||
*/
|
||||
export function combineJourneyReads(
|
||||
savedStep: CandidateJourney["savedStep"],
|
||||
profile: ReadResult<CandidateProfileVersion>,
|
||||
questionnaire: ReadResult<CandidateQuestionnaire>,
|
||||
availability: ReadResult<AssessmentAvailability>,
|
||||
): CandidateJourneyState {
|
||||
const reads = [profile, questionnaire, availability];
|
||||
const failed = reads.filter((read) => read.status === "error");
|
||||
if (failed.length > 0) {
|
||||
const denied = failed.find((read) => isAccessError(read.error));
|
||||
return {
|
||||
status: "error",
|
||||
error: (denied ?? failed[0])?.error,
|
||||
isRetrying: failed.some((read) => read.isRefetching),
|
||||
retry: () => {
|
||||
for (const read of failed) void read.refetch();
|
||||
},
|
||||
};
|
||||
}
|
||||
if (profile.data === undefined || questionnaire.data === undefined || !availability.data) {
|
||||
return { status: "pending" };
|
||||
}
|
||||
return {
|
||||
status: "success",
|
||||
journey: buildCandidateJourney({
|
||||
savedStep,
|
||||
profileVersion: profile.data.version,
|
||||
questionnaire: questionnaire.data,
|
||||
availability: availability.data,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Next-step state of the signed-in candidate, read from the current API state. */
|
||||
export function useCandidateJourney(session: Session | undefined): CandidateJourneyState {
|
||||
const profile = useCandidateProfileRead(session);
|
||||
const questionnaire = useCandidateQuestionnaireRead(session);
|
||||
const availability = useCandidateAvailabilityRead(session);
|
||||
if (!session) return { status: "pending" };
|
||||
return combineJourneyReads(session.account.onboarding_step, profile, questionnaire, availability);
|
||||
}
|
||||
@@ -26,3 +26,21 @@ export {
|
||||
type SoftSkillDraft,
|
||||
type StackDraft,
|
||||
} from "./model/profile-form";
|
||||
export {
|
||||
buildCandidateJourney,
|
||||
onboardingStepLabels,
|
||||
summarizeVisibility,
|
||||
type CandidateJourney,
|
||||
type CandidateJourneyInput,
|
||||
type CandidateNextStep,
|
||||
type SpecializationStanding,
|
||||
type VisibilitySummary,
|
||||
} from "./model/home";
|
||||
export {
|
||||
candidateHomeQueryKeys,
|
||||
combineJourneyReads,
|
||||
useCandidateJourney,
|
||||
useCandidateLatestResultRead,
|
||||
useCandidatePrivacyRead,
|
||||
type CandidateJourneyState,
|
||||
} from "./api/home-queries";
|
||||
@@ -0,0 +1,277 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type {
|
||||
AssessmentAvailability,
|
||||
GradeCode,
|
||||
PrivacySettings,
|
||||
SpecializationCode,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { buildCandidateJourney, summarizeVisibility, type CandidateJourneyInput } from "./home";
|
||||
|
||||
type Availability = AssessmentAvailability["specializations"][number];
|
||||
|
||||
function gradeRows(status: "available" | "cooldown"): Availability["grades"] {
|
||||
return (["intern", "junior", "middle", "senior"] as const).map((grade) => ({
|
||||
grade,
|
||||
status,
|
||||
mode: null,
|
||||
available_at: null,
|
||||
time_limit_seconds: null,
|
||||
max_sessions: null,
|
||||
max_items: null,
|
||||
practice_required: null,
|
||||
}));
|
||||
}
|
||||
|
||||
function availabilityRow(
|
||||
specialization: SpecializationCode,
|
||||
options: {
|
||||
confirmed?: GradeCode | null;
|
||||
attemptId?: string | null;
|
||||
status?: "available" | "cooldown";
|
||||
} = {},
|
||||
): Availability {
|
||||
return {
|
||||
specialization,
|
||||
confirmed_grade: options.confirmed ?? null,
|
||||
active_attempt_id: options.attemptId ?? null,
|
||||
grades: gradeRows(options.status ?? "available"),
|
||||
};
|
||||
}
|
||||
|
||||
function questionnaire(
|
||||
declared: [SpecializationCode, GradeCode][],
|
||||
version = declared.length > 0 ? 1 : 0,
|
||||
): CandidateJourneyInput["questionnaire"] {
|
||||
return {
|
||||
version,
|
||||
specializations: declared.map(([specialization, grade]) => ({
|
||||
specialization,
|
||||
self_assessed_grade: grade,
|
||||
task_languages: [],
|
||||
stack: [],
|
||||
experience: null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function input(overrides: Partial<CandidateJourneyInput> = {}): CandidateJourneyInput {
|
||||
return {
|
||||
savedStep: "candidate_consents",
|
||||
profileVersion: 0,
|
||||
questionnaire: questionnaire([]),
|
||||
availability: { specializations: [] },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildCandidateJourney next step", () => {
|
||||
it("leads an empty profile to the profile form", () => {
|
||||
expect(buildCandidateJourney(input()).nextStep).toEqual({ kind: "profile" });
|
||||
});
|
||||
|
||||
it("leads a saved profile without a questionnaire to the questionnaire", () => {
|
||||
const journey = buildCandidateJourney(input({ profileVersion: 3 }));
|
||||
|
||||
expect(journey.profileSaved).toBe(true);
|
||||
expect(journey.nextStep).toEqual({ kind: "questionnaire" });
|
||||
});
|
||||
|
||||
it("does not wait for the stored step to advance past the consents step", () => {
|
||||
// The server advances the stored step only from the matching step, so a
|
||||
// saved profile can coexist with the stored consents step.
|
||||
const journey = buildCandidateJourney(
|
||||
input({ savedStep: "candidate_consents", profileVersion: 1 }),
|
||||
);
|
||||
|
||||
expect(journey.savedStep).toBe("candidate_consents");
|
||||
expect(journey.nextStep).toEqual({ kind: "questionnaire" });
|
||||
});
|
||||
|
||||
it("leads a saved questionnaire to the test and keeps the declared grade", () => {
|
||||
const journey = buildCandidateJourney(
|
||||
input({
|
||||
savedStep: "candidate_assessment",
|
||||
profileVersion: 1,
|
||||
questionnaire: questionnaire([["backend", "middle"]]),
|
||||
availability: { specializations: [availabilityRow("backend")] },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(journey.nextStep).toEqual({ kind: "assessment" });
|
||||
expect(journey.confirmed).toEqual([]);
|
||||
expect(journey.standings).toEqual([
|
||||
{
|
||||
specialization: "backend",
|
||||
declaredGrade: "middle",
|
||||
confirmedGrade: null,
|
||||
activeAttemptId: null,
|
||||
canStartAttempt: true,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("treats a questionnaire version without specializations as not saved", () => {
|
||||
const journey = buildCandidateJourney(
|
||||
input({ profileVersion: 1, questionnaire: questionnaire([], 2) }),
|
||||
);
|
||||
|
||||
expect(journey.questionnaireSaved).toBe(false);
|
||||
expect(journey.nextStep).toEqual({ kind: "questionnaire" });
|
||||
});
|
||||
|
||||
it("resumes the active attempt instead of offering a new test", () => {
|
||||
const attemptId = "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80";
|
||||
const journey = buildCandidateJourney(
|
||||
input({
|
||||
profileVersion: 1,
|
||||
questionnaire: questionnaire([["backend", "junior"]]),
|
||||
availability: { specializations: [availabilityRow("backend", { attemptId })] },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(journey.nextStep).toEqual({
|
||||
kind: "resume_attempt",
|
||||
attemptId,
|
||||
specialization: "backend",
|
||||
});
|
||||
});
|
||||
|
||||
it("leads an obtained category to the result and keeps declared and confirmed apart", () => {
|
||||
const journey = buildCandidateJourney(
|
||||
input({
|
||||
savedStep: "candidate_assessment",
|
||||
profileVersion: 1,
|
||||
questionnaire: questionnaire([["backend", "middle"]]),
|
||||
availability: { specializations: [availabilityRow("backend", { confirmed: "junior" })] },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(journey.nextStep).toEqual({ kind: "result" });
|
||||
expect(journey.confirmed).toHaveLength(1);
|
||||
expect(journey.standings[0]).toMatchObject({
|
||||
declaredGrade: "middle",
|
||||
confirmedGrade: "junior",
|
||||
});
|
||||
});
|
||||
|
||||
it("offers the result even when the profile is still empty", () => {
|
||||
const journey = buildCandidateJourney(
|
||||
input({
|
||||
questionnaire: questionnaire([["qa", "junior"]]),
|
||||
availability: { specializations: [availabilityRow("qa", { confirmed: "junior" })] },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(journey.nextStep).toEqual({ kind: "result" });
|
||||
});
|
||||
|
||||
it("reports that no test can start when every grade is blocked", () => {
|
||||
const journey = buildCandidateJourney(
|
||||
input({
|
||||
profileVersion: 1,
|
||||
questionnaire: questionnaire([["backend", "junior"]]),
|
||||
availability: { specializations: [availabilityRow("backend", { status: "cooldown" })] },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(journey.standings[0]?.canStartAttempt).toBe(false);
|
||||
expect(journey.nextStep).toEqual({ kind: "assessment" });
|
||||
});
|
||||
|
||||
it("never turns a declared grade into a confirmed one", () => {
|
||||
const journey = buildCandidateJourney(
|
||||
input({
|
||||
savedStep: "completed",
|
||||
profileVersion: 1,
|
||||
questionnaire: questionnaire([["frontend", "senior"]]),
|
||||
availability: { specializations: [] },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(journey.confirmed).toEqual([]);
|
||||
expect(journey.standings[0]).toMatchObject({
|
||||
declaredGrade: "senior",
|
||||
confirmedGrade: null,
|
||||
});
|
||||
expect(journey.nextStep).toEqual({ kind: "assessment" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("summarizeVisibility", () => {
|
||||
function settings(overrides: {
|
||||
publication?: Partial<PrivacySettings["publication"]>;
|
||||
search?: Partial<PrivacySettings["search_status"]>;
|
||||
}): PrivacySettings {
|
||||
return {
|
||||
publication: {
|
||||
state: "closed",
|
||||
closed_reason: "never_published",
|
||||
fields: [],
|
||||
consent_id: null,
|
||||
published_at: null,
|
||||
version: 0,
|
||||
...overrides.publication,
|
||||
},
|
||||
search_status: {
|
||||
value: "not_looking",
|
||||
lapsed: false,
|
||||
confirmed_at: null,
|
||||
lapses_at: null,
|
||||
version: 0,
|
||||
...overrides.search,
|
||||
},
|
||||
hidden_organizations_total: 0,
|
||||
};
|
||||
}
|
||||
|
||||
it("restates a closed card with its reason", () => {
|
||||
expect(summarizeVisibility(settings({}))).toEqual({
|
||||
published: false,
|
||||
closedReason: "never_published",
|
||||
showsCategory: false,
|
||||
searchStatus: { looking: false, lapsed: false, lapsesAt: null },
|
||||
});
|
||||
});
|
||||
|
||||
it("reports whether a published card includes the category", () => {
|
||||
const published = { state: "published", closed_reason: null } as const;
|
||||
|
||||
expect(
|
||||
summarizeVisibility(
|
||||
settings({ publication: { ...published, fields: ["categories", "stack"] } }),
|
||||
),
|
||||
).toMatchObject({ published: true, showsCategory: true });
|
||||
expect(
|
||||
summarizeVisibility(settings({ publication: { ...published, fields: ["stack"] } })),
|
||||
).toMatchObject({ published: true, showsCategory: false });
|
||||
});
|
||||
|
||||
it("keeps the lapse moment only for a status that holds now", () => {
|
||||
expect(
|
||||
summarizeVisibility(
|
||||
settings({
|
||||
search: {
|
||||
value: "looking",
|
||||
confirmed_at: "2026-10-01T10:00:00Z",
|
||||
lapses_at: "2026-10-31T10:00:00Z",
|
||||
},
|
||||
}),
|
||||
).searchStatus,
|
||||
).toEqual({ looking: true, lapsed: false, lapsesAt: "2026-10-31T10:00:00Z" });
|
||||
});
|
||||
|
||||
it("marks a lapsed search status", () => {
|
||||
expect(
|
||||
summarizeVisibility(
|
||||
settings({
|
||||
search: {
|
||||
lapsed: true,
|
||||
confirmed_at: "2026-09-01T10:00:00Z",
|
||||
lapses_at: "2026-10-01T10:00:00Z",
|
||||
version: 4,
|
||||
},
|
||||
}),
|
||||
).searchStatus,
|
||||
).toEqual({ looking: false, lapsed: true, lapsesAt: null });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,170 @@
|
||||
import type {
|
||||
Account,
|
||||
AssessmentAvailability,
|
||||
CandidateQuestionnaire,
|
||||
GradeCode,
|
||||
PrivacySettings,
|
||||
SpecializationCode,
|
||||
} from "../../../shared/api/schemas";
|
||||
|
||||
type OnboardingStep = Account["onboarding_step"];
|
||||
|
||||
/** Plain names of the stored onboarding steps, for the saved-step line. */
|
||||
export const onboardingStepLabels: Readonly<Record<OnboardingStep, string>> = {
|
||||
candidate_consents: "Согласия",
|
||||
candidate_profile: "Профиль",
|
||||
candidate_questionnaire: "Анкета",
|
||||
candidate_assessment: "Тест",
|
||||
employer_company: "Компания",
|
||||
completed: "Онбординг завершен",
|
||||
};
|
||||
|
||||
/**
|
||||
* One questionnaire specialization with the two facts that must never be
|
||||
* merged: what the candidate declared and what an assessment confirmed.
|
||||
*/
|
||||
export type SpecializationStanding = {
|
||||
specialization: SpecializationCode;
|
||||
/** Self-assessed grade from the questionnaire; a claim, not a category. */
|
||||
declaredGrade: GradeCode | null;
|
||||
/** Grade that an assessment result confirmed, or null. */
|
||||
confirmedGrade: GradeCode | null;
|
||||
/** Active attempt of this specialization that can be resumed. */
|
||||
activeAttemptId: string | null;
|
||||
/** True when at least one grade can start a new attempt now. */
|
||||
canStartAttempt: boolean;
|
||||
};
|
||||
|
||||
/** The single main action offered on the home screen. */
|
||||
export type CandidateNextStep =
|
||||
| { kind: "profile" }
|
||||
| { kind: "questionnaire" }
|
||||
| { kind: "assessment" }
|
||||
| { kind: "resume_attempt"; attemptId: string; specialization: SpecializationCode }
|
||||
| { kind: "result" };
|
||||
|
||||
export type CandidateJourneyInput = {
|
||||
/** `onboarding_step` of the current session account. */
|
||||
savedStep: OnboardingStep;
|
||||
/** `version` of the profile read; 0 means it was never saved. */
|
||||
profileVersion: number;
|
||||
questionnaire: Pick<CandidateQuestionnaire, "version" | "specializations">;
|
||||
availability: Pick<AssessmentAvailability, "specializations">;
|
||||
};
|
||||
|
||||
export type CandidateJourney = {
|
||||
savedStep: OnboardingStep;
|
||||
profileSaved: boolean;
|
||||
questionnaireSaved: boolean;
|
||||
standings: readonly SpecializationStanding[];
|
||||
/** Standings whose grade an assessment confirmed. */
|
||||
confirmed: readonly SpecializationStanding[];
|
||||
nextStep: CandidateNextStep;
|
||||
};
|
||||
|
||||
function buildStandings(input: CandidateJourneyInput): SpecializationStanding[] {
|
||||
const standings = new Map<SpecializationCode, SpecializationStanding>();
|
||||
|
||||
// The availability list is the server's view of the questionnaire
|
||||
// specializations; the questionnaire adds the declared grade.
|
||||
for (const item of input.availability.specializations) {
|
||||
standings.set(item.specialization, {
|
||||
specialization: item.specialization,
|
||||
declaredGrade: null,
|
||||
confirmedGrade: item.confirmed_grade,
|
||||
activeAttemptId: item.active_attempt_id,
|
||||
canStartAttempt: item.grades.some((grade) => grade.status === "available"),
|
||||
});
|
||||
}
|
||||
for (const item of input.questionnaire.specializations) {
|
||||
const existing = standings.get(item.specialization);
|
||||
standings.set(item.specialization, {
|
||||
specialization: item.specialization,
|
||||
declaredGrade: item.self_assessed_grade,
|
||||
confirmedGrade: existing?.confirmedGrade ?? null,
|
||||
activeAttemptId: existing?.activeAttemptId ?? null,
|
||||
canStartAttempt: existing?.canStartAttempt ?? false,
|
||||
});
|
||||
}
|
||||
return [...standings.values()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Chooses the main action from what the server returned. The stored
|
||||
* onboarding step is kept for display and is never overridden; it is not the
|
||||
* only input because the server advances it only when the profile or the
|
||||
* questionnaire is saved from the matching step, so a saved profile can sit
|
||||
* behind an earlier stored step. Presence of saved data therefore decides
|
||||
* between the profile, the questionnaire, and the test.
|
||||
*
|
||||
* The client invents no category, grade, or threshold: a category exists only
|
||||
* when the availability read returns a confirmed grade.
|
||||
*/
|
||||
export function buildCandidateJourney(input: CandidateJourneyInput): CandidateJourney {
|
||||
const standings = buildStandings(input);
|
||||
const confirmed = standings.filter((standing) => standing.confirmedGrade !== null);
|
||||
const profileSaved = input.profileVersion > 0;
|
||||
const questionnaireSaved =
|
||||
input.questionnaire.version > 0 && input.questionnaire.specializations.length > 0;
|
||||
|
||||
return {
|
||||
savedStep: input.savedStep,
|
||||
profileSaved,
|
||||
questionnaireSaved,
|
||||
standings,
|
||||
confirmed,
|
||||
nextStep: chooseNextStep({ profileSaved, questionnaireSaved, standings, confirmed }),
|
||||
};
|
||||
}
|
||||
|
||||
function chooseNextStep(state: {
|
||||
profileSaved: boolean;
|
||||
questionnaireSaved: boolean;
|
||||
standings: readonly SpecializationStanding[];
|
||||
confirmed: readonly SpecializationStanding[];
|
||||
}): CandidateNextStep {
|
||||
if (state.confirmed.length > 0) return { kind: "result" };
|
||||
if (!state.profileSaved) return { kind: "profile" };
|
||||
if (!state.questionnaireSaved) return { kind: "questionnaire" };
|
||||
const resumable = state.standings.find((standing) => standing.activeAttemptId !== null);
|
||||
if (resumable?.activeAttemptId) {
|
||||
return {
|
||||
kind: "resume_attempt",
|
||||
attemptId: resumable.activeAttemptId,
|
||||
specialization: resumable.specialization,
|
||||
};
|
||||
}
|
||||
return { kind: "assessment" };
|
||||
}
|
||||
|
||||
export type VisibilitySummary = {
|
||||
/** True while organizations can read the card. */
|
||||
published: boolean;
|
||||
/** Why the card is closed, or null while it is published. */
|
||||
closedReason: PrivacySettings["publication"]["closed_reason"];
|
||||
/** True only for a published card that includes the confirmed category. */
|
||||
showsCategory: boolean;
|
||||
searchStatus: {
|
||||
looking: boolean;
|
||||
/** True when "looking" ran out because it was not confirmed again. */
|
||||
lapsed: boolean;
|
||||
/** Moment the confirmed status lapses, for a status that holds now. */
|
||||
lapsesAt: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
/** Restates the privacy settings read without adding rules of its own. */
|
||||
export function summarizeVisibility(settings: PrivacySettings): VisibilitySummary {
|
||||
const published = settings.publication.state === "published";
|
||||
return {
|
||||
published,
|
||||
closedReason: published ? null : settings.publication.closed_reason,
|
||||
showsCategory: published && settings.publication.fields.includes("categories"),
|
||||
searchStatus: {
|
||||
looking: settings.search_status.value === "looking",
|
||||
lapsed: settings.search_status.lapsed,
|
||||
lapsesAt:
|
||||
settings.search_status.value === "looking" ? settings.search_status.lapses_at : null,
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user