feat: add candidate profile, questionnaire and company forms

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 16:07:02 +03:00
1 parent 3a61a8e8bb
commit f81cd0ae09
68 files changed
+9517 -54

No files matched your search

+2
View File
@@ -68,6 +68,8 @@ linters:
list-mode: lax
files:
- "!$test"
# This command is compiled only by the local E2E mail image.
- "!**/cmd/mail-fixture/main.go"
deny:
- pkg: lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture
desc: the Resend fixture is for tests only
+4
View File
@@ -14,6 +14,8 @@ RUN go mod download
COPY . ./
RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/app ./cmd/app
RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/consent-fixture ./cmd/consent-fixture
RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/company-fixture ./cmd/company-fixture
RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/questionnaire-fixture ./cmd/questionnaire-fixture
FROM ${RUNTIME_IMAGE}
@@ -23,6 +25,8 @@ LABEL org.opencontainers.image.title="Lincodex local E2E backend" \
WORKDIR /
COPY --from=build /out/app /app
COPY --from=build /out/consent-fixture /consent-fixture
COPY --from=build /out/company-fixture /company-fixture
COPY --from=build /out/questionnaire-fixture /questionnaire-fixture
EXPOSE 8080 9090
USER nonroot:nonroot
ENTRYPOINT ["/app"]
+278
View File
@@ -0,0 +1,278 @@
//go:build e2e
package main
import (
"context"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"io"
"log"
"mime"
"net/http"
"os"
"strings"
"sync/atomic"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/port/outbound"
)
const (
fixtureEnabledName = "E2E_COMPANY_FIXTURE"
fixtureAuthEnvName = "E2E_COMPANY_FIXTURE_TOKEN"
fixtureListenAddr = ":8081"
fixtureEndpoint = "/company/memberships/revoke"
fixtureHealthPath = "/healthcheck"
maxRequestBody = 1024
maxFixtureRequests = 32
requestTimeout = 5 * time.Second
readHeaderTimeout = 3 * time.Second
readTimeout = 5 * time.Second
writeTimeout = 5 * time.Second
idleTimeout = 15 * time.Second
)
type membershipRevoker func(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) error
type fixtureHandler struct {
token string
revoke membershipRevoker
requests atomic.Uint32
}
type revokeMembershipRequest struct {
OrganizationID string `json:"organization_id"`
UserID string `json:"user_id"`
SuccessorUserID string `json:"successor_user_id"`
}
func main() {
if len(os.Args) == 2 && os.Args[1] == "healthcheck" {
if err := checkHealth(); err != nil {
os.Exit(1)
}
return
}
if err := serve(); err != nil {
_, _ = io.WriteString(os.Stderr, "Company fixture could not start.\n")
os.Exit(1)
}
}
func serve() error {
if os.Getenv(fixtureEnabledName) != "1" {
return errors.New("company fixture requires the isolated e2e environment")
}
token := os.Getenv(fixtureAuthEnvName)
if !hasFixtureTokenStrength(token) {
return errors.New("company fixture token must contain at least 32 random bytes")
}
databaseURL := os.Getenv("DATABASE_URL")
if databaseURL == "" {
return errors.New("company fixture database is not configured")
}
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
pool, err := postgres.NewSizedPool(ctx, databaseURL, 4)
if err != nil {
return errors.New("company fixture could not open its database")
}
defer pool.Close()
if err := pool.Ping(ctx); err != nil {
return errors.New("company fixture database is unavailable")
}
server := &http.Server{
Addr: fixtureListenAddr,
Handler: &fixtureHandler{
token: token,
revoke: func(ctx context.Context, organizationID, userID, successorUserID uuid.UUID) error {
return postgres.RevokeCompanyFixtureMembership(ctx, pool, organizationID, userID, successorUserID)
},
},
ReadHeaderTimeout: readHeaderTimeout,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
IdleTimeout: idleTimeout,
MaxHeaderBytes: 4096,
ErrorLog: log.New(io.Discard, "", 0),
}
return server.ListenAndServe()
}
func checkHealth() error {
client := http.Client{Timeout: time.Second}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
request, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://127.0.0.1:8081"+fixtureHealthPath, nil)
if err != nil {
return errors.New("company fixture is not healthy")
}
response, err := client.Do(request)
if err != nil {
return errors.New("company fixture is not healthy")
}
defer func() { _ = response.Body.Close() }()
if response.StatusCode != http.StatusNoContent {
return errors.New("company fixture is not healthy")
}
return nil
}
func hasFixtureTokenStrength(token string) bool {
if decoded, err := hex.DecodeString(token); err == nil && len(decoded) >= 32 {
return true
}
decoded, err := base64.RawURLEncoding.Strict().DecodeString(token)
return err == nil && len(decoded) >= 32
}
func (handler *fixtureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case fixtureHealthPath:
handler.serveHealthcheck(w, r)
case fixtureEndpoint:
handler.serveMembershipRevocation(w, r)
default:
w.WriteHeader(http.StatusNotFound)
}
}
func (handler *fixtureHandler) serveHealthcheck(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.Header().Set("Allow", http.MethodGet)
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (handler *fixtureHandler) serveMembershipRevocation(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.Header().Set("Allow", http.MethodPost)
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if handler.requests.Add(1) > maxFixtureRequests {
w.WriteHeader(http.StatusTooManyRequests)
return
}
if !hasFixtureBearerToken(r.Header.Get("Authorization"), handler.token) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if !isJSONRequest(r) {
w.WriteHeader(http.StatusUnsupportedMediaType)
return
}
request, status := decodeRevokeMembershipRequest(w, r)
if status != 0 {
w.WriteHeader(status)
return
}
if handler.revoke == nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
ctx, cancel := context.WithTimeout(r.Context(), requestTimeout)
defer cancel()
if err := handler.revoke(ctx, request.organizationID, request.userID, request.successorUserID); err != nil {
w.WriteHeader(statusForFixtureError(err))
return
}
w.WriteHeader(http.StatusNoContent)
}
type parsedRevokeMembershipRequest struct {
organizationID uuid.UUID
userID uuid.UUID
successorUserID uuid.UUID
}
func decodeRevokeMembershipRequest(w http.ResponseWriter, r *http.Request) (parsedRevokeMembershipRequest, int) {
request, status := decodeRevokeRequest(w, r)
if status != 0 {
return parsedRevokeMembershipRequest{}, status
}
organizationID, err := uuid.Parse(request.OrganizationID)
if err != nil || organizationID == uuid.Nil {
return parsedRevokeMembershipRequest{}, http.StatusBadRequest
}
userID, err := uuid.Parse(request.UserID)
if err != nil || userID == uuid.Nil {
return parsedRevokeMembershipRequest{}, http.StatusBadRequest
}
successorUserID, err := uuid.Parse(request.SuccessorUserID)
if err != nil || successorUserID == uuid.Nil || successorUserID == userID {
return parsedRevokeMembershipRequest{}, http.StatusBadRequest
}
return parsedRevokeMembershipRequest{
organizationID: organizationID,
userID: userID,
successorUserID: successorUserID,
}, 0
}
func isJSONRequest(r *http.Request) bool {
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
return err == nil && strings.EqualFold(mediaType, "application/json")
}
func decodeRevokeRequest(w http.ResponseWriter, r *http.Request) (revokeMembershipRequest, int) {
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxRequestBody))
decoder.DisallowUnknownFields()
var request revokeMembershipRequest
if err := decoder.Decode(&request); err != nil {
return revokeMembershipRequest{}, statusForDecodeError(err)
}
var trailing any
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
return revokeMembershipRequest{}, statusForDecodeError(err)
}
if request.OrganizationID == "" || request.UserID == "" {
return revokeMembershipRequest{}, http.StatusBadRequest
}
return request, 0
}
func statusForDecodeError(err error) int {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return http.StatusRequestEntityTooLarge
}
return http.StatusBadRequest
}
func statusForFixtureError(err error) int {
switch {
case errors.Is(err, postgres.ErrCompanyFixtureScope),
errors.Is(err, outbound.ErrUserNotFound),
errors.Is(err, outbound.ErrMembershipNotFound),
errors.Is(err, outbound.ErrOrganizationNotFound):
return http.StatusNotFound
case errors.Is(err, outbound.ErrTransactionConflict):
return http.StatusConflict
default:
return http.StatusInternalServerError
}
}
func hasFixtureBearerToken(header, token string) bool {
prefix, supplied, ok := strings.Cut(header, " ")
if !ok || prefix != "Bearer" || supplied == "" {
return false
}
expectedDigest := sha256.Sum256([]byte(token))
suppliedDigest := sha256.Sum256([]byte(supplied))
return subtle.ConstantTimeCompare(expectedDigest[:], suppliedDigest[:]) == 1
}
+177
View File
@@ -0,0 +1,177 @@
//go:build e2e
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/hex"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/port/outbound"
)
func TestFixtureHandlerRevokesOnlyWithConfiguredBearer(t *testing.T) {
organizationID := uuid.New()
userID := uuid.New()
successorUserID := uuid.New()
called := false
handler := &fixtureHandler{
token: strings.Repeat("ab", 32),
revoke: func(_ context.Context, gotOrganizationID, gotUserID, gotSuccessorUserID uuid.UUID) error {
called = true
if gotOrganizationID != organizationID || gotUserID != userID || gotSuccessorUserID != successorUserID {
t.Fatalf("revoke IDs = %s/%s/%s, want %s/%s/%s", gotOrganizationID, gotUserID, gotSuccessorUserID, organizationID, userID, successorUserID)
}
return nil
},
}
body := `{"organization_id":"` + organizationID.String() + `","user_id":"` + userID.String() + `","successor_user_id":"` + successorUserID.String() + `"}`
unauthorized := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, body, "Bearer "+strings.Repeat("cd", 32), "application/json")
if unauthorized.Code != http.StatusUnauthorized || called {
t.Fatalf("unauthorized response = %d, revoke called = %t", unauthorized.Code, called)
}
if len(unauthorized.Body.Bytes()) != 0 {
t.Fatalf("unauthorized response exposed a body: %q", unauthorized.Body.String())
}
response := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, body, "Bearer "+handler.token, "application/json; charset=utf-8")
if response.Code != http.StatusNoContent || !called {
t.Fatalf("authorized response = %d, revoke called = %t", response.Code, called)
}
if len(response.Body.Bytes()) != 0 {
t.Fatalf("success response exposed a body: %q", response.Body.String())
}
}
func TestFixtureHandlerRejectsInvalidRequestsWithoutCallingRevoker(t *testing.T) {
called := false
handler := &fixtureHandler{
token: strings.Repeat("ab", 32),
revoke: func(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) error {
called = true
return nil
},
}
validBody := `{"organization_id":"` + uuid.NewString() + `","user_id":"` + uuid.NewString() + `","successor_user_id":"` + uuid.NewString() + `"}`
userID := uuid.NewString()
sameUserBody := `{"organization_id":"` + uuid.NewString() + `","user_id":"` + userID + `","successor_user_id":"` + userID + `"}`
largeBody := `{"organization_id":"` + uuid.NewString() + `","user_id":"` + uuid.NewString() + `","successor_user_id":"` + uuid.NewString() + `","padding":"` + strings.Repeat("x", maxRequestBody) + `"}`
tests := []struct {
name string
method string
path string
body string
authority string
contentType string
wantStatus int
}{
{name: "unknown path", method: http.MethodPost, path: "/other", wantStatus: http.StatusNotFound},
{name: "wrong method", method: http.MethodGet, path: fixtureEndpoint, wantStatus: http.StatusMethodNotAllowed},
{name: "wrong content type", method: http.MethodPost, path: fixtureEndpoint, body: validBody, authority: "Bearer " + handler.token, contentType: "text/plain", wantStatus: http.StatusUnsupportedMediaType},
{name: "unknown field", method: http.MethodPost, path: fixtureEndpoint, body: strings.TrimSuffix(validBody, "}") + `,"extra":"value"}`, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusBadRequest},
{name: "malformed UUID", method: http.MethodPost, path: fixtureEndpoint, body: `{"organization_id":"bad","user_id":"` + uuid.NewString() + `","successor_user_id":"` + uuid.NewString() + `"}`, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusBadRequest},
{name: "same owner and successor", method: http.MethodPost, path: fixtureEndpoint, body: sameUserBody, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusBadRequest},
{name: "trailing JSON", method: http.MethodPost, path: fixtureEndpoint, body: validBody + `{}`, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusBadRequest},
{name: "oversized body", method: http.MethodPost, path: fixtureEndpoint, body: largeBody, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusRequestEntityTooLarge},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
response := fixtureRequest(handler, test.method, test.path, test.body, test.authority, test.contentType)
if response.Code != test.wantStatus {
t.Fatalf("response status = %d, want %d", response.Code, test.wantStatus)
}
if len(response.Body.Bytes()) != 0 {
t.Fatalf("response exposed a body: %q", response.Body.String())
}
})
}
if called {
t.Fatal("revoker was called for an invalid request")
}
}
func TestFixtureHandlerBoundsControlRequests(t *testing.T) {
handler := &fixtureHandler{token: strings.Repeat("ab", 32)}
for range maxFixtureRequests {
response := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, "", "", "application/json")
if response.Code != http.StatusUnauthorized {
t.Fatalf("request before limit status = %d, want %d", response.Code, http.StatusUnauthorized)
}
}
response := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, "", "", "application/json")
if response.Code != http.StatusTooManyRequests {
t.Fatalf("request after limit status = %d, want %d", response.Code, http.StatusTooManyRequests)
}
}
func TestFixtureHandlerMapsStorageErrorsToEmptyResponses(t *testing.T) {
handler := &fixtureHandler{
token: strings.Repeat("ab", 32),
revoke: func(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) error {
return errors.Join(errors.New("private database detail"), outbound.ErrTransactionConflict)
},
}
body := `{"organization_id":"` + uuid.NewString() + `","user_id":"` + uuid.NewString() + `","successor_user_id":"` + uuid.NewString() + `"}`
response := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, body, "Bearer "+handler.token, "application/json")
if response.Code != http.StatusConflict {
t.Fatalf("response status = %d, want %d", response.Code, http.StatusConflict)
}
if len(response.Body.Bytes()) != 0 {
t.Fatalf("response exposed internal error: %q", response.Body.String())
}
if got := statusForFixtureError(postgres.ErrCompanyFixtureScope); got != http.StatusNotFound {
t.Fatalf("fixture scope status = %d, want %d", got, http.StatusNotFound)
}
}
func TestFixtureHealthIsMinimal(t *testing.T) {
handler := &fixtureHandler{}
response := fixtureRequest(handler, http.MethodGet, fixtureHealthPath, "", "", "")
if response.Code != http.StatusNoContent || len(response.Body.Bytes()) != 0 {
t.Fatalf("health response = %d %q, want empty %d", response.Code, response.Body.String(), http.StatusNoContent)
}
wrongMethod := fixtureRequest(handler, http.MethodPost, fixtureHealthPath, "", "", "")
if wrongMethod.Code != http.StatusMethodNotAllowed || wrongMethod.Header().Get("Allow") != http.MethodGet {
t.Fatalf("health wrong-method response = %d, Allow = %q", wrongMethod.Code, wrongMethod.Header().Get("Allow"))
}
}
func TestFixtureTokenStrengthAcceptsOnlyAtLeast32Bytes(t *testing.T) {
bytes32 := bytes.Repeat([]byte{0x4a}, 32)
for name, token := range map[string]string{
"hex": hex.EncodeToString(bytes32),
"base64": base64.RawURLEncoding.EncodeToString(bytes32),
"too short": hex.EncodeToString(bytes32[:31]),
"invalid": "not-a-token",
} {
t.Run(name, func(t *testing.T) {
want := name == "hex" || name == "base64"
if got := hasFixtureTokenStrength(token); got != want {
t.Fatalf("hasFixtureTokenStrength() = %t, want %t", got, want)
}
})
}
}
func fixtureRequest(handler http.Handler, method, path, body, authorization, contentType string) *httptest.ResponseRecorder {
request := httptest.NewRequest(method, path, strings.NewReader(body))
if authorization != "" {
request.Header.Set("Authorization", authorization)
}
if contentType != "" {
request.Header.Set("Content-Type", contentType)
}
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
return response
}
+3 -1
View File
@@ -34,7 +34,9 @@ func main() {
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Fprintln(os.Stdout, "Consent browser fixture seeded.")
if _, err := fmt.Fprintln(os.Stdout, "Consent browser fixture seeded."); err != nil {
os.Exit(1)
}
}
func run() error {
+1 -1
View File
@@ -76,7 +76,7 @@ func healthcheck() error {
if err != nil {
return errors.New("main.healthcheck - mail fixture is not ready")
}
defer response.Body.Close()
defer func() { _ = response.Body.Close() }()
if response.StatusCode != http.StatusNoContent {
return errors.New("main.healthcheck - mail fixture is not ready")
}
+211
View File
@@ -0,0 +1,211 @@
//go:build e2e
package main
import (
"context"
"errors"
"fmt"
"os"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/assessment"
)
const (
fixtureEnabledName = "E2E_QUESTIONNAIRE_FIXTURE"
fixtureTimeout = 90 * time.Second
maxFixtureFamilies = 200
fixtureBundleName = "e2e-questionnaire-bank"
fixtureAuthor = "operator:questionnaire-fixture-author"
fixtureReviewer = "operator:questionnaire-fixture-reviewer"
fixturePublisher = domain.AssessmentOperator("operator:questionnaire-fixture-publisher")
fixtureOpener = domain.AssessmentOperator("operator:questionnaire-fixture-opener")
fixtureFamilyStem = "e2e-questionnaire-family-"
fixtureCategory = domain.AssessmentCategory("backend")
)
func main() {
if err := run(context.Background(), os.Args[1:], os.LookupEnv); err != nil {
if _, writeErr := fmt.Fprintln(os.Stderr, err); writeErr != nil {
os.Exit(1)
}
os.Exit(1)
}
if _, err := fmt.Fprintln(os.Stdout, "Questionnaire bank fixture is ready."); err != nil {
os.Exit(1)
}
}
func run(
parent context.Context,
args []string,
lookupEnv func(string) (string, bool),
) error {
if len(args) != 0 {
return errors.New("questionnaire fixture accepts no arguments")
}
enabled, _ := lookupEnv(fixtureEnabledName)
if enabled != "1" {
return errors.New("questionnaire fixture requires E2E_QUESTIONNAIRE_FIXTURE=1")
}
databaseURL, _ := lookupEnv("DATABASE_URL")
if databaseURL == "" {
return errors.New("questionnaire fixture database is not configured")
}
ctx, cancel := context.WithTimeout(parent, fixtureTimeout)
defer cancel()
pool, err := postgres.NewSizedPool(ctx, databaseURL, 4)
if err != nil {
return errors.New("questionnaire fixture could not open its database")
}
defer pool.Close()
if err := pool.Ping(ctx); err != nil {
return errors.New("questionnaire fixture database is unavailable")
}
if err := seedQuestionnaireBank(ctx, pool); err != nil {
return err
}
return nil
}
func seedQuestionnaireBank(ctx context.Context, pool *pgxpool.Pool) error {
const location = "questionnaire fixture"
occupied, err := backendQuestionnaireBankOccupied(ctx, pool)
if err != nil {
return errors.New(location + " could not inspect backend bank state")
}
if occupied {
return errors.New(location + " refuses existing backend openings or published families")
}
transactor := postgres.NewTransactor(pool)
currentPolicy, err := currentProductPolicy(ctx, transactor)
if err != nil {
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
return errors.New(location + " requires a current product assessment policy")
}
return errors.New(location + " could not read the current product policy")
}
required, err := domain.RequiredPublishedAssessmentFamilies(currentPolicy.Policy())
if err != nil || required < 1 || required > maxFixtureFamilies {
return errors.New(location + " current policy has an unsupported family threshold")
}
bundle, err := reviewedQuestionnaireBundle(int(required))
if err != nil {
return errors.New(location + " reviewed family fixture is invalid")
}
bank := assessment.NewBank(transactor)
if _, err := bank.ImportBundle(ctx, bundle); err != nil {
return errors.New(location + " could not import reviewed families")
}
for _, family := range bundle.Families {
if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil {
return errors.New(location + " could not publish reviewed families")
}
}
metadata, err := questionnaireCatalogMetadata()
if err != nil {
return errors.New(location + " public catalog mapping is invalid")
}
if _, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{
Category: fixtureCategory, GradingPolicyID: currentPolicy.ID(), OpenedBy: fixtureOpener,
CatalogMetadata: &metadata,
}); err != nil {
return errors.New(location + " could not open the reviewed catalog mapping")
}
return nil
}
func questionnaireCatalogMetadata() (domain.AssessmentCategoryCatalogMetadata, error) {
return domain.NewAssessmentCategoryCatalogMetadata(
domain.SpecializationBackend,
domain.GradeJunior,
[]domain.TaskLanguageCode{domain.TaskLanguageGo},
)
}
func backendQuestionnaireBankOccupied(ctx context.Context, pool *pgxpool.Pool) (bool, error) {
var occupied bool
err := pool.QueryRow(ctx, `
SELECT
EXISTS (SELECT 1 FROM assessment_category_openings WHERE category = $1)
OR EXISTS (
SELECT 1 FROM assessment_families
WHERE category = $1 AND lifecycle = 'published'
)
OR EXISTS (
SELECT 1 FROM assessment_families
WHERE category = $1 AND family_key LIKE $2
)`, string(fixtureCategory), fixtureFamilyStem+"%").Scan(&occupied)
return occupied, err
}
func currentProductPolicy(ctx context.Context, transactor outbound.Transactor) (domain.PolicyVersion, error) {
var version domain.PolicyVersion
err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
if err != nil {
return err
}
version, err = unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, databaseTime)
return err
})
return version, err
}
func reviewedQuestionnaireBundle(count int) (assessment.Bundle, error) {
if count < 1 || count > maxFixtureFamilies {
return assessment.Bundle{}, errors.New("questionnaire fixture family count is outside the supported range")
}
bundle := assessment.Bundle{
Name: fixtureBundleName, Category: string(fixtureCategory), Author: fixtureAuthor,
Review: assessment.BundleReview{Status: string(domain.AssessmentReviewApproved), Reviewer: fixtureReviewer},
Families: make([]assessment.BundleFamily, 0, count),
}
requestsMinimum := int32(12)
for index := range count {
familyNumber := index + 1
family := assessment.BundleFamily{
Key: fmt.Sprintf("%s%03d", fixtureFamilyStem, familyNumber), Version: 1,
Specialization: "rate-limiting", Title: fmt.Sprintf("Sliding-window fixture case %03d", familyNumber),
SeedGenerator: domain.AssessmentSeedGenerator{
Algorithm: "rate_limit_window.v1",
Parameters: map[string]domain.AssessmentParameterRange{
"requests": {Min: requestsMinimum, Max: requestsMinimum + 8},
"window": {Min: 3, Max: 15},
"limit": {Min: 2, Max: 6},
"max_gap": {Min: 1, Max: 5},
},
StatementTemplate: "A gateway applies a sliding-window limiter. A request at second t is accepted only when fewer than {{.limit}} previously accepted requests arrived in (t - {{.window}}, t]. Rejected requests are not remembered. The gateway receives {{.requests}} requests at these non-decreasing arrival times: {{.timestamps}}. How many requests are rejected?",
},
AnswerKey: domain.AssessmentAnswerKey{
AnswerFormat: domain.AnswerFormatInteger,
ReferenceSolution: "Keep accepted arrival times in order. Before each request at t, remove accepted times at or before t - window. Accept and append t when fewer than limit times remain; otherwise count a rejection without appending it. Each request enters and leaves the queue at most once.",
},
Rubric: domain.AssessmentRubric{
Principle: "The answer is the exact number of rejected requests for the generated arrival sequence. The rubric has criteria but no points or pass mark.",
Criteria: []domain.AssessmentRubricCriterion{
{ID: "correct_answer", Description: "The submitted integer equals the generated reference answer."},
{ID: "window_boundary", Description: "A request exactly window seconds old is outside the half-open interval."},
{ID: "rejected_not_counted", Description: "Rejected requests do not occupy capacity in later windows."},
{ID: "queue_approach", Description: "The approach processes each arrival at most once when entering and once when leaving the queue."},
},
},
}
bundle.Families = append(bundle.Families, family)
requestsMinimum++
}
if _, err := bundle.Drafts(); err != nil {
return assessment.Bundle{}, err
}
return bundle, nil
}
@@ -0,0 +1,86 @@
//go:build e2e
package main
import (
"context"
"testing"
"lincodex/backend/internal/domain"
)
func TestRunRequiresExactE2EGuardBeforeDatabase(t *testing.T) {
lookup := func(name string) (string, bool) {
if name == "DATABASE_URL" {
return "postgres://fixture.invalid/test", true
}
return "true", true
}
err := run(context.Background(), nil, lookup)
if err == nil || err.Error() != "questionnaire fixture requires E2E_QUESTIONNAIRE_FIXTURE=1" {
t.Fatalf("run(disabled) error = %v, want exact E2E guard refusal", err)
}
}
func TestRunRejectsArgumentsAndMissingDatabase(t *testing.T) {
enabled := func(name string) (string, bool) {
if name == fixtureEnabledName {
return "1", true
}
return "", false
}
if err := run(context.Background(), []string{"seed"}, enabled); err == nil || err.Error() != "questionnaire fixture accepts no arguments" {
t.Fatalf("run(with argument) error = %v, want argument refusal", err)
}
if err := run(context.Background(), nil, enabled); err == nil || err.Error() != "questionnaire fixture database is not configured" {
t.Fatalf("run(without database) error = %v, want missing database refusal", err)
}
}
func TestReviewedQuestionnaireBundleValidatesIndependentFamilies(t *testing.T) {
const count = 13
bundle, err := reviewedQuestionnaireBundle(count)
if err != nil {
t.Fatalf("reviewedQuestionnaireBundle(%d) error = %v", count, err)
}
if bundle.Category != string(fixtureCategory) || bundle.Review.Status != string(domain.AssessmentReviewApproved) ||
bundle.Author == bundle.Review.Reviewer || len(bundle.Families) != count {
t.Fatalf("reviewed fixture bundle metadata = category %q, review %q by %q, author %q, families %d",
bundle.Category, bundle.Review.Status, bundle.Review.Reviewer, bundle.Author, len(bundle.Families))
}
drafts, err := bundle.Drafts()
if err != nil || len(drafts) != count {
t.Fatalf("Bundle.Drafts() = %d, %v; want %d valid reviewed families", len(drafts), err, count)
}
seen := make(map[domain.AssessmentFamilyKey]struct{}, count)
for _, draft := range drafts {
core := draft.Core()
if core.Category != fixtureCategory || core.Reviewer == "" || string(core.Reviewer) == string(core.Author) {
t.Fatalf("draft review identity/category is not independent: category %q reviewer %q author %q", core.Category, core.Reviewer, core.Author)
}
if _, exists := seen[core.Key]; exists {
t.Fatalf("duplicate synthetic family key %q", core.Key)
}
seen[core.Key] = struct{}{}
}
}
func TestReviewedQuestionnaireBundleRejectsUnsupportedThreshold(t *testing.T) {
for _, count := range []int{0, maxFixtureFamilies + 1} {
if _, err := reviewedQuestionnaireBundle(count); err == nil {
t.Fatalf("reviewedQuestionnaireBundle(%d) error = %v; want a fixture threshold error", count, err)
}
}
}
func TestQuestionnaireCatalogMetadataUsesTheReviewedE2EProjection(t *testing.T) {
metadata, err := questionnaireCatalogMetadata()
if err != nil {
t.Fatalf("questionnaireCatalogMetadata() error = %v", err)
}
if metadata.Specialization() != domain.SpecializationBackend || metadata.Grade() != domain.GradeJunior ||
len(metadata.TaskLanguages()) != 1 || metadata.TaskLanguages()[0] != domain.TaskLanguageGo {
t.Fatalf("questionnaire catalog metadata = %s/%s/%v; want Backend/Junior/Go",
metadata.Specialization(), metadata.Grade(), metadata.TaskLanguages())
}
}
@@ -0,0 +1,152 @@
//go:build e2e
package postgres
import (
"context"
"errors"
"fmt"
"regexp"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var (
ErrCompanyFixtureScope = errors.New("company fixture scope rejected")
companyFixtureEmail = regexp.MustCompile(`^company-[a-f0-9]{8}@example\.test$`)
)
func isCompanyFixtureEmployer(user domain.User) bool {
return user.Scenario == domain.ScenarioEmployer && user.EmailVerified() &&
companyFixtureEmail.MatchString(user.Email.Address())
}
// RevokeCompanyFixtureMembership removes the synthetic owner membership used
// by the isolated browser suite. It is available only in e2e-tagged builds.
func RevokeCompanyFixtureMembership(
ctx context.Context,
pool *pgxpool.Pool,
organizationID, userID, successorUserID uuid.UUID,
) error {
const location = "postgres.RevokeCompanyFixtureMembership"
if pool == nil || organizationID == uuid.Nil || userID == uuid.Nil || successorUserID == uuid.Nil ||
userID == successorUserID {
return fmt.Errorf("%s - invalid fixture identity: %w", location, ErrCompanyFixtureScope)
}
tx, err := pool.BeginTx(ctx, transactionOptions)
if err != nil {
return fmt.Errorf("%s - begin transaction: %w", location, sanitizeConnectError(err))
}
finished := false
defer func() {
if !finished {
_ = rollback(ctx, tx)
}
}()
unit := &UnitOfWork{tx: tx, queries: sqlc.New(tx)}
membership, err := validateCompanyFixtureAccounts(ctx, unit, location, organizationID, userID, successorUserID)
if err != nil {
return err
}
changedAt := time.Now().UTC().Truncate(time.Microsecond)
if changedAt.Before(membership.UpdatedAt()) {
changedAt = membership.UpdatedAt()
}
if err := addCompanyFixtureSuccessor(ctx, unit, location, organizationID, successorUserID, changedAt); err != nil {
return err
}
if err := removeCompanyFixtureMembership(ctx, tx, location, organizationID, userID, changedAt); err != nil {
return err
}
finished = true
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("%s - commit transaction: %w", location, markTransactionConflict(err))
}
return nil
}
func validateCompanyFixtureAccounts(
ctx context.Context,
unit *UnitOfWork,
location string,
organizationID, userID, successorUserID uuid.UUID,
) (domain.Membership, error) {
user, err := unit.Users().GetByID(ctx, userID)
if err != nil {
return domain.Membership{}, fmt.Errorf("%s - read fixture account: %w", location, err)
}
if !isCompanyFixtureEmployer(user) {
return domain.Membership{}, fmt.Errorf("%s - account is outside the fixture scope: %w", location, ErrCompanyFixtureScope)
}
successor, err := unit.Users().GetByID(ctx, successorUserID)
if err != nil {
return domain.Membership{}, fmt.Errorf("%s - read successor account: %w", location, err)
}
if !isCompanyFixtureEmployer(successor) {
return domain.Membership{}, fmt.Errorf("%s - successor account is outside the fixture scope: %w", location, ErrCompanyFixtureScope)
}
membership, err := unit.Memberships().Get(ctx, organizationID, userID)
if err != nil {
return domain.Membership{}, fmt.Errorf("%s - read fixture membership: %w", location, err)
}
if membership.Role() != domain.OrganizationRoleOwner || membership.State() != domain.MembershipStateActive {
return domain.Membership{}, fmt.Errorf("%s - membership is outside the fixture scope: %w", location, ErrCompanyFixtureScope)
}
if _, err := unit.Memberships().Get(ctx, organizationID, successorUserID); err == nil {
return domain.Membership{}, fmt.Errorf("%s - successor already belongs to the organization: %w", location, ErrCompanyFixtureScope)
} else if !errors.Is(err, outbound.ErrMembershipNotFound) {
return domain.Membership{}, fmt.Errorf("%s - check successor membership: %w", location, err)
}
return membership, nil
}
func addCompanyFixtureSuccessor(
ctx context.Context,
unit *UnitOfWork,
location string,
organizationID, successorUserID uuid.UUID,
changedAt time.Time,
) error {
successorMembership, err := domain.NewOwnerMembership(organizationID, successorUserID, changedAt)
if err != nil {
return fmt.Errorf("%s - create successor owner membership: %w", location, err)
}
if err := unit.Memberships().Insert(ctx, successorMembership); err != nil {
return fmt.Errorf("%s - add successor owner membership: %w", location, err)
}
return nil
}
func removeCompanyFixtureMembership(
ctx context.Context,
tx pgx.Tx,
location string,
organizationID, userID uuid.UUID,
changedAt time.Time,
) error {
tag, err := tx.Exec(ctx, `
UPDATE memberships
SET state = 'removed', updated_at = $3
WHERE organization_id = $1
AND user_id = $2
AND role = 'owner'
AND state = 'active'
`, organizationID, userID, changedAt)
if err != nil {
return fmt.Errorf("%s - remove fixture membership: %w", location, err)
}
if tag.RowsAffected() != 1 {
return fmt.Errorf("%s - membership changed concurrently: %w", location, outbound.ErrTransactionConflict)
}
return nil
}
@@ -0,0 +1,42 @@
//go:build e2e
package postgres
import (
"testing"
"time"
"lincodex/backend/internal/domain"
)
func TestIsCompanyFixtureEmployerRequiresVerifiedSyntheticEmployer(t *testing.T) {
verifiedAt := time.Date(2026, time.October, 7, 12, 0, 0, 0, time.UTC)
tests := []struct {
name string
email string
scenario domain.Scenario
verified bool
want bool
}{
{name: "verified fixture employer", email: "company-abcdef12@example.test", scenario: domain.ScenarioEmployer, verified: true, want: true},
{name: "unverified employer", email: "company-abcdef12@example.test", scenario: domain.ScenarioEmployer},
{name: "candidate account", email: "company-abcdef12@example.test", scenario: domain.ScenarioCandidate, verified: true},
{name: "ordinary employer", email: "employer@example.test", scenario: domain.ScenarioEmployer, verified: true},
{name: "fixture-like address with wrong suffix", email: "company-abcdef12@example.org", scenario: domain.ScenarioEmployer, verified: true},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
address, err := domain.NewEmailAddress(test.email)
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
user := domain.User{Email: address, Scenario: test.scenario}
if test.verified {
user.EmailVerifiedAt = &verifiedAt
}
if got := isCompanyFixtureEmployer(user); got != test.want {
t.Fatalf("isCompanyFixtureEmployer() = %t, want %t", got, test.want)
}
})
}
}
+1 -1
View File
@@ -53,7 +53,7 @@ config: ## Render all Compose files with safe example values
APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG=000000000000 IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" -f "$(RELEASE_FILE)" config --quiet
APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG=000000000000 IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" -f "$(ML_RELEASE_FILE)" config --quiet
APP_PROJECT=lincodex-e2e-config APP_NETWORK=lincodex-e2e-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" --profile e2e config --quiet
APP_PROJECT=lincodex-e2e-mail-config APP_NETWORK=lincodex-e2e-mail-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-mail-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" -f "$(E2E_MAIL_FILE)" --profile e2e config --quiet
E2E_COMPANY_FIXTURE_TOKEN=render-only-company-fixture-token-00000000000000000000000000000000 APP_PROJECT=lincodex-e2e-mail-config APP_NETWORK=lincodex-e2e-mail-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-mail-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" -f "$(E2E_MAIL_FILE)" --profile e2e config --quiet
build: ## Build local frontend and backend images
APP_PROJECT="$(APP_PROJECT)" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" build
+43
View File
@@ -6,6 +6,8 @@ services:
context: ../../backend
dockerfile: Dockerfile.e2e
environment:
# Browser scenarios share one proxy address in this isolated stand.
IDENTITY_CLIENT_HOURLY_LIMIT: "200"
EMAIL_PROVIDER: resend
EMAIL_ACCOUNT: e2e
EMAIL_FROM: no-reply@example.com
@@ -24,7 +26,48 @@ services:
E2E_MAILBOX_URL: http://mail-fixture:8025/__e2e/inbox
E2E_MAILBOX_TOKEN: local-e2e-mailbox-token
E2E_MAIL_FIXTURE: "1"
E2E_COMPANY_FIXTURE: "1"
E2E_QUESTIONNAIRE_FIXTURE: "1"
E2E_CONSENT_FIXTURE: "1"
E2E_COMPANY_FIXTURE_URL: http://company-fixture:8081/company/memberships/revoke
E2E_COMPANY_FIXTURE_TOKEN: ${E2E_COMPANY_FIXTURE_TOKEN:?Set the per-run company fixture token}
company-fixture:
build:
context: ../../backend
dockerfile: Dockerfile.e2e
entrypoint: ["/company-fixture"]
environment:
E2E_COMPANY_FIXTURE: "1"
E2E_COMPANY_FIXTURE_TOKEN: ${E2E_COMPANY_FIXTURE_TOKEN:?Set the per-run company fixture token}
DATABASE_URL: postgres://${POSTGRES_USER:?Set POSTGRES_USER}:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:?Set POSTGRES_DB}?sslmode=disable
expose:
- "8081"
read_only: true
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
depends_on:
postgres:
condition: service_healthy
healthcheck:
test: ["CMD", "/company-fixture", "healthcheck"]
interval: 2s
timeout: 3s
retries: 15
start_period: 2s
stop_grace_period: 5s
networks:
- default
logging:
driver: json-file
options:
max-size: 1m
max-file: "2"
deploy:
resources:
limits:
cpus: "0.25"
memory: 128M
mail-fixture:
build:
+3
View File
@@ -189,6 +189,7 @@ EMAIL_TIMEOUT=10s
APP_PUBLIC_URL=http://localhost:8080
PASSWORD_HASH_CONCURRENCY=1
IDENTITY_KEY_SECRET=$(random_secret)
E2E_COMPANY_FIXTURE_TOKEN=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')
POSTGRES_EXPORTER_USER=
POSTGRES_EXPORTER_PASSWORD=
EOF
@@ -263,6 +264,8 @@ try {
# Seed only synthetic consent scopes in this fresh, isolated database.
# The command exists only in the local E2E image and rejects other modes.
compose exec -T backend /consent-fixture
# Publish an explicitly reviewed synthetic bank for the questionnaire flow.
compose exec -T -e E2E_QUESTIONNAIRE_FIXTURE=1 backend /questionnaire-fixture
fi
playwright_command=(node node_modules/@playwright/test/cli.js test)
+38
View File
@@ -11,6 +11,7 @@ ROOT = Path(__file__).resolve().parents[2]
DEPLOY = ROOT / "deploy"
DOCKER = os.environ.get("DOCKER", "docker")
FIXTURE_TOKEN = "local-e2e-mailbox-token"
COMPANY_FIXTURE_TOKEN = "render-only-company-fixture-token-" + "0" * 32
class E2EUserSelectionTest(unittest.TestCase):
@@ -55,6 +56,7 @@ def render_compose(file_names, project, extra_env=None):
"E2E_SPEC_DIR": str(ROOT / "frontend" / "e2e"),
"E2E_ARTIFACTS_DIR": str(ROOT / "frontend" / "test-results" / "e2e"),
"IDENTITY_KEY_SECRET": "render-only-identity-key-secret",
"E2E_COMPANY_FIXTURE_TOKEN": COMPANY_FIXTURE_TOKEN,
}
environment.update(extra_env or {})
command = [DOCKER, "compose", "--env-file", str(ROOT / ".env.example"), "-p", project]
@@ -94,10 +96,12 @@ class ComposeMailFixtureTest(unittest.TestCase):
for rendered in (self.ordinary, self.release):
with self.subTest(project=rendered["name"]):
self.assertNotIn("mail-fixture", rendered["services"])
self.assertNotIn("company-fixture", rendered["services"])
backend = rendered["services"]["backend"]
self.assertEqual(backend["build"]["dockerfile"], "Dockerfile")
self.assertEqual(backend["environment"]["EMAIL_PROVIDER"], "disabled")
self.assertEqual(backend["environment"]["VERIFICATION_MAIL_MIN_INTERVAL"], "1m")
self.assertEqual(backend["environment"]["IDENTITY_CLIENT_HOURLY_LIMIT"], "30")
self.assertNotIn("RESEND_ENDPOINT", backend["environment"])
self.assertNotIn("E2E_CONSENT_FIXTURE", backend["environment"])
self.assertNotIn(
@@ -108,6 +112,11 @@ class ComposeMailFixtureTest(unittest.TestCase):
"E2E_MAIL_FIXTURE",
rendered["services"]["playwright"].get("environment", {}),
)
for name in ("E2E_COMPANY_FIXTURE", "E2E_COMPANY_FIXTURE_URL", "E2E_COMPANY_FIXTURE_TOKEN"):
self.assertNotIn(name, backend["environment"])
self.assertNotIn(name, rendered["services"]["playwright"].get("environment", {}))
self.assertNotIn("E2E_QUESTIONNAIRE_FIXTURE", backend["environment"])
self.assertNotIn("E2E_QUESTIONNAIRE_FIXTURE", rendered["services"]["playwright"].get("environment", {}))
def test_fixture_uses_an_e2e_build_and_fixed_synthetic_credentials(self):
services = self.fixture["services"]
@@ -116,6 +125,7 @@ class ComposeMailFixtureTest(unittest.TestCase):
self.assertEqual(backend["environment"]["EMAIL_PROVIDER"], "resend")
self.assertEqual(backend["environment"]["RESEND_API_KEY"], "re_fixture_key")
self.assertEqual(backend["environment"]["VERIFICATION_MAIL_MIN_INTERVAL"], "1s")
self.assertEqual(backend["environment"]["IDENTITY_CLIENT_HOURLY_LIMIT"], "200")
self.assertEqual(backend["environment"]["E2E_CONSENT_FIXTURE"], "1")
self.assertNotIn("RESEND_ENDPOINT", backend["environment"])
self.assertEqual(
@@ -125,6 +135,9 @@ class ComposeMailFixtureTest(unittest.TestCase):
self.assertEqual(services["playwright"]["environment"]["E2E_MAILBOX_TOKEN"], FIXTURE_TOKEN)
self.assertEqual(services["playwright"]["environment"]["E2E_MAIL_FIXTURE"], "1")
self.assertEqual(services["playwright"]["environment"]["E2E_CONSENT_FIXTURE"], "1")
self.assertEqual(services["playwright"]["environment"]["E2E_QUESTIONNAIRE_FIXTURE"], "1")
self.assertNotIn("E2E_QUESTIONNAIRE_FIXTURE", backend["environment"])
self.assertNotIn("questionnaire-fixture", (ROOT / "backend" / "Dockerfile").read_text())
self.assertNotIn("E2E_MAIL_FIXTURE", services["frontend"].get("environment", {}))
def test_fixture_has_no_host_port_storage_network_or_outbound_route(self):
@@ -142,6 +155,31 @@ class ComposeMailFixtureTest(unittest.TestCase):
self.assertIn("no-new-privileges:true", fixture["security_opt"])
self.assertEqual(fixture["deploy"]["resources"]["limits"]["memory"], str(128 * 1024 * 1024))
def test_company_control_is_private_and_only_built_for_local_e2e(self):
services = self.fixture["services"]
fixture = services["company-fixture"]
self.assertEqual(fixture["build"]["dockerfile"], "Dockerfile.e2e")
self.assertEqual(fixture["entrypoint"], ["/company-fixture"])
self.assertEqual(fixture["environment"]["E2E_COMPANY_FIXTURE"], "1")
self.assertEqual(services["playwright"]["environment"]["E2E_COMPANY_FIXTURE"], "1")
self.assertEqual(fixture["environment"]["E2E_COMPANY_FIXTURE_TOKEN"], COMPANY_FIXTURE_TOKEN)
self.assertEqual(
services["playwright"]["environment"]["E2E_COMPANY_FIXTURE_TOKEN"], COMPANY_FIXTURE_TOKEN
)
self.assertEqual(
services["playwright"]["environment"]["E2E_COMPANY_FIXTURE_URL"],
"http://company-fixture:8081/company/memberships/revoke",
)
self.assertFalse(fixture.get("ports"))
self.assertFalse(fixture.get("volumes"))
self.assertEqual(set(fixture["networks"]), {"default"})
self.assertTrue(self.fixture["networks"]["default"]["internal"])
self.assertTrue(fixture["read_only"])
self.assertEqual(fixture["cap_drop"], ["ALL"])
self.assertIn("no-new-privileges:true", fixture["security_opt"])
self.assertEqual(fixture["deploy"]["resources"]["limits"]["memory"], str(128 * 1024 * 1024))
self.assertNotIn("company-fixture", (ROOT / "backend" / "Dockerfile").read_text())
class E2ERunnerModeTest(unittest.TestCase):
def test_release_tag_cannot_enable_the_local_mail_fixture(self):
+17 -1
View File
@@ -75,6 +75,10 @@ The registration-mode suite additionally runs `frontend/e2e/auth-registration.sp
In the same mode, the runner invokes `/consent-fixture` from the test backend image before starting the browser. The command exists only with the Go `e2e` build tag, requires `E2E_CONSENT_FIXTURE=1`, and uses domain objects and transactional ports to create a synthetic verified candidate, C1/C2, and two C4 scopes for different companies. A collision with an existing test address stops the run. Ordinary and release images contain neither the command nor its enabled flag. `frontend/e2e/consent-management.spec.ts` uses normal sign-in and real consent APIs to grant C3 independently, revoke C2 and one C4, retain the other scope, reload, and submit a C1 request whose returned status is shown. A controlled 403 exercises the failure UI; successful mutations reach PostgreSQL. Synthetic invitation IDs in the fixture do not prove the invitation acceptance flow. Traces and automatic screenshots are disabled; the explicit review screenshot contains only synthetic data.
`frontend/e2e/profile-edit.spec.ts` fills the manual profile at 360px after real registration, acknowledges overlapping employment periods, saves, and reloads the data. A second context changes the version through the API; the first window keeps its draft on 412 and replaces it only through an explicit action. The test checks frozen fields during PUT, focus, no overflow at 360/768/1280px, and rejection of a late response after an account switch. Saving a profile does not count as completion of the consent step.
`frontend/e2e/company-management.spec.ts` creates a company, retries a lost response with the same key and body, edits the profile, and compares its preview with the API. Controlled responses check CSRF recovery, version conflict, and a delayed response. A separate `company-fixture` performs real revocation: Go build tag `e2e`, an explicit enable flag, a random bearer token per run, no published port, and only the internal network. It validates two synthetic verified employer accounts, adds a successor owner, and revokes the original owner in one transaction while preserving the mandatory-owner constraint. The browser with its original cookie checks real API denial and removal from its directory. The control endpoint is absent from the ordinary backend and release image; its URL and token reach only the test process through `E2E_COMPANY_FIXTURE_URL` and `E2E_COMPANY_FIXTURE_TOKEN`.
## Release manifest tests
`make -C deploy check-release` runs `deploy/scripts/test_release_manifest.py` with the Python standard library and without Docker. It fails when go.mod, the `GO_IMAGE` default, and `GOTOOLCHAIN=local` in backend/Dockerfile stop pinning Go 1.26.8, or when a service Dockerfile uses a base image that is not a pinnable `*_IMAGE` build argument, including an external image in `COPY --from` or `RUN --mount=from`. On fake image, Compose, and container data it checks that:
@@ -365,7 +369,9 @@ Unit tests (`make -C backend test`) cover the organization rules without a datab
- Constraints through raw SQL: an empty, padded, multi-line, or over-long name, an unknown level, a basis of another level, version zero, a description with a padded end or a control character, a sphere with a line break, an http website or one with credentials, an email with a space, a phone without `+`, a Telegram username without `@`, an update before the creation time, the level and basis pairs of `e1`, `e2`, and `e3` (the right ones accepted, the wrong ones refused), a composite foreign key onto `(organization_id, id)` of the memberships (accepted for the member's own organization, refused for another), an unknown role (including `manager`), an unknown state (including `invited`), an eleventh representative, and a padded job title are refused by constraint name; the organizations table has no column for a role, an owner, a member, or a user.
- Deletion: an account with a membership and an organization with a member cannot be deleted (SQLSTATE 23001); once the memberships are gone, the organization takes its representatives with it.
`TestPostgresMigrations` rolls migration 00010 back with the others, checks that its three tables and its function disappear while the identity tables stay, and checks them again after the second migration. The tests that truncate `users` name `usersDependentTables` (identity, delivery, consent, and organization tables), the one list to extend when a migration adds a table that references users. The suite does not cover the usecases, the handlers, the session and CSRF mapping, or the claim that the contract is enforced end to end, because none of them exists yet; the atomicity of the single-statement read of the organization with its representatives is not proven by a test, because the window between two statements cannot be reproduced deterministically.
`TestPostgresMigrations` rolls migration 00010 back with the others, checks that its three tables and its function disappear while the identity tables stay, and checks them again after the second migration. The tests that truncate `users` name `usersDependentTables` (identity, delivery, consent, and organization tables), the one list to extend when a migration adds a table that references users. This storage suite does not cover the usecases or HTTP; the separate tests below use real sessions and CSRF. The atomicity of the single-statement read of the organization with its representatives is not proven by a test, because the window between two statements cannot be reproduced deterministically.
`TestOrganizationCreationAndOwnerEditingOverHTTP` and `TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` exercise organization creation and editing, idempotent replay, the caller's paginated directory, owner-only actions, foreign organizations, and revoked membership over real HTTP and PostgreSQL. Revoking a second owner closes the profile and tenant operations for the same cookie while preserving another owner's access. Middleware tests enumerate every tenant operation in the contract.
## Candidate profile tests
@@ -385,6 +391,16 @@ Unit tests (`make -C backend test`) check the profile rules without a database:
`TestCandidateProfileMigrationRollsBack` rolls migration 00013 back on an isolated database and checks that both tables disappear while `users` stays.
`TestCandidateProfileOverHTTP` checks the caller's profile through a session and CSRF: an empty GET, complete save and API restart, specific date and overlap errors, parallel-work confirmation, 412, no history write on a no-op, foreign-profile isolation, and employer denial. History, data, and the conditional onboarding transition share one transaction; injected history and step-transition failures roll back the save. Changing self-assessment does not create a confirmed category.
## Candidate questionnaire tests
`TestCandidateQuestionnaireOverHTTP` uses real sessions, CSRF, and PostgreSQL. It checks an empty version-zero questionnaire, save and handler restart, account isolation, employer denial, rejection of unknown confirmed-grade fields, different concurrent writes returning 200/412, identical concurrent writes returning 200 with one version increment, conditional onboarding, rollback, paired experience constraints, and catalog invalidation after a policy change or family retirement. Self-assessment never creates a confirmed category. The canonical API uses 412 for version conflicts; older task wording mentions 409.
The isolated mail overlay sets `IDENTITY_CLIENT_HOURLY_LIMIT=200` because all browser scenarios share one proxy address. Ordinary and release configuration retain 30, and per-email limits remain unchanged.
`questionnaire.spec.ts` uses the local mail fixture and an explicitly published synthetic bank for Backend/Junior/Go. The test-only `questionnaire-fixture` command reads the existing effective policy and publishes the required number of reviewed families before binding the catalog. It refuses existing backend bank ownership and is absent from ordinary and release images. The browser scenario covers persistence, a DS/ML specialization marked in development, keyboard access and layout at 360/768/1280 px, and conflict handling between two real sessions. It is skipped when these isolated fixtures are not enabled.
## Candidate visibility tests
Unit tests (`make -C backend test`) check the visibility rules without a database:
+17 -1
View File
@@ -75,6 +75,10 @@ Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-f
В этом же режиме runner перед браузером запускает `/consent-fixture` из тестового backend-образа. Команда доступна только с Go build tag `e2e`, требует `E2E_CONSENT_FIXTURE=1` и через домен и транзакционные порты создает синтетического подтвержденного кандидата, C1/C2 и два C4 для разных компаний. Совпадение тестового адреса с существующим аккаунтом останавливает запуск. Обычный и release-образы не содержат команду и не включают этот флаг. Сценарий `frontend/e2e/consent-management.spec.ts` использует обычный вход и реальные API согласий: отдельную выдачу C3, отзыв C2 и одного C4, сохранение другого scope, перезагрузку и C1 request со статусом из ответа. Отказ сервера для проверки UI задается управляемым 403; успешные изменения идут в PostgreSQL. Синтетические invitation IDs в fixture не доказывают реализацию принятия приглашений. Трассы и автоматические снимки отключены; явный снимок показывает только синтетические данные.
`frontend/e2e/profile-edit.spec.ts` заполняет ручной профиль на 360 px после реальной регистрации, подтверждает пересечение периодов, сохраняет и перечитывает данные. Второй контекст меняет версию через API; первое окно сохраняет черновик при 412 и заменяет его только явным действием. Проверяются заморозка полей во время PUT, фокус, отсутствие переполнения на 360/768/1280 px и отбрасывание позднего ответа после смены аккаунта. Шаг согласий не считается завершенным сохранением профиля.
`frontend/e2e/company-management.spec.ts` создает компанию, повторяет запрос после потери ответа с тем же ключом и телом, изменяет профиль и сравнивает предпросмотр с API. Управляемые ответы проверяют восстановление после CSRF-ошибки, конфликт версии и задержанный ответ. Реальный отзыв выполняет отдельный `company-fixture`: Go build tag `e2e`, явный флаг, случайный bearer token на каждый прогон, без опубликованного порта и только во внутренней сети. Утилита проверяет два синтетических подтвержденных employer-аккаунта, добавляет владельца-преемника и отзывает исходного владельца в одной транзакции, сохраняя ограничение обязательного владельца. Браузер с прежней cookie проверяет отказ реального API и исчезновение компании из своей директории. Контрольный endpoint отсутствует в обычном backend и release-образе; его URL и токен передаются только тестовому процессу через `E2E_COMPANY_FIXTURE_URL` и `E2E_COMPANY_FIXTURE_TOKEN`.
## Тесты манифеста выпуска
`make -C deploy check-release` запускает `deploy/scripts/test_release_manifest.py` на стандартной библиотеке Python и без Docker. Тест падает, если go.mod, значение `GO_IMAGE` по умолчанию и `GOTOOLCHAIN=local` в backend/Dockerfile перестают закреплять Go 1.26.8 или если Dockerfile сервиса использует базовый образ не через закрепляемый build-аргумент `*_IMAGE`, в том числе внешний образ в `COPY --from` или `RUN --mount=from`. На подставных данных образов, Compose и контейнеров он проверяет, что:
@@ -365,7 +369,9 @@ Unit-тесты (`make -C backend test`) проверяют правила жу
- Ограничения через прямой SQL: пустое, с пробелами по краям, многострочное или слишком длинное название, неизвестный уровень, основание другого уровня, версия ноль, описание с пробелом на конце или управляющим символом, сфера с переводом строки, сайт по http или с учетными данными, email с пробелом, телефон без `+`, имя Telegram без `@`, обновление раньше создания, пары уровня и основания для `e1`, `e2` и `e3` (верные принимаются, неверные отвергаются), составной внешний ключ на `(organization_id, id)` членств (принимается для организации самого участника, отвергается для чужой), неизвестная роль (включая `manager`), неизвестное состояние (включая `invited`), одиннадцатый представитель и должность с пробелом по краю отвергаются по имени ограничения; в таблице организаций нет столбца роли, владельца, участника или пользователя.
- Удаление: аккаунт с членством и организацию с участником удалить нельзя (SQLSTATE 23001); когда членства удалены, организация забирает представителей с собой.
`TestPostgresMigrations` откатывает миграцию 00010 вместе с остальными, проверяет, что три ее таблицы и функция исчезают, а таблицы identity остаются, и проверяет их снова после второго применения. Тесты, очищающие `users`, называют `usersDependentTables` (таблицы identity, доставок, согласий и организаций) - единственный список, который нужно расширять, когда миграция добавляет таблицу со ссылкой на users. Набор не покрывает usecase, обработчики, сопоставление сессии и CSRF и утверждение, что контракт соблюдается сквозным путем, потому что ничего из этого еще нет; атомарность чтения организации с представителями одним оператором тестом не доказана, потому что окно между двумя операторами нельзя воспроизвести детерминированно.
`TestPostgresMigrations` откатывает миграцию 00010 вместе с остальными, проверяет, что три ее таблицы и функция исчезают, а таблицы identity остаются, и проверяет их снова после второго применения. Тесты, очищающие `users`, называют `usersDependentTables` (таблицы identity, доставок, согласий и организаций) - единственный список, который нужно расширять, когда миграция добавляет таблицу со ссылкой на users. Этот набор хранения не покрывает usecase и HTTP; отдельные проверки ниже используют реальную сессию и CSRF. Атомарность чтения организации с представителями одним оператором тестом не доказана, потому что окно между двумя операторами нельзя воспроизвести детерминированно.
`TestOrganizationCreationAndOwnerEditingOverHTTP` и `TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` проверяют создание и изменение организации, идемпотентный повтор, свою постраничную директорию, owner-only действия, чужие организации и прекращенное членство через настоящий HTTP и PostgreSQL. Отзыв второго владельца закрывает профиль и tenant-операции для той же cookie, не закрывая доступ другого владельца. Проверки middleware перечисляют все tenant operations контракта.
## Тесты профиля кандидата
@@ -385,6 +391,16 @@ Unit-тесты (`make -C backend test`) проверяют правила жу
`TestCandidateProfileMigrationRollsBack` откатывает миграцию 00013 на изолированной базе, проверяет, что обе таблицы исчезают, а `users` остается.
`TestCandidateProfileOverHTTP` проверяет собственный профиль через сессию и CSRF: пустой GET, полное сохранение и перезапуск API, конкретные ошибки дат и пересечений, подтверждение параллельной работы, 412, отсутствие записи истории при no-op, недоступность чужого профиля и отказ employer. История, данные и условный переход шага находятся в одной транзакции; ошибки вставки истории и перехода шага откатывают сохранение. Изменение самооценки не создает подтвержденную категорию.
## Тесты анкеты кандидата
`TestCandidateQuestionnaireOverHTTP` использует настоящие сессии, CSRF и PostgreSQL. Он проверяет пустую анкету версии 0, сохранение и перезапуск обработчика, изоляцию аккаунтов, отказ работодателю, отклонение неизвестных полей подтвержденного грейда, разные конкурентные записи с ответами 200/412, одинаковые конкурентные записи с ответами 200 и одним повышением версии, условный переход onboarding, откат, парность полей опыта и закрытие каталога после смены политики или отзыва семейства. Самооценка не создает подтвержденную категорию. Канонический API использует 412 для конфликта версий; прежняя формулировка задачи упоминает 409.
Изолированный почтовый overlay задает `IDENTITY_CLIENT_HOURLY_LIMIT=200`, поскольку все браузерные сценарии используют один адрес прокси. Обычная и релизная конфигурации сохраняют 30, лимиты отдельного email не меняются.
`questionnaire.spec.ts` использует локальный почтовый fixture и явно опубликованный синтетический банк Backend/Junior/Go. Тестовая команда `questionnaire-fixture` читает действующую политику и публикует необходимое число проверенных семейств перед привязкой каталога. Она отказывается работать поверх существующего backend-банка и отсутствует в обычном и релизном образах. Браузерный сценарий проверяет сохранность, специализацию DS/ML с пометкой о разработке, клавиатуру и верстку на 360/768/1280 px, а также конфликт между двумя настоящими сессиями. Без изолированных fixtures сценарий пропускается.
## Тесты видимости кандидата
Модульные тесты (`make -C backend test`) проверяют правила видимости без базы:
+31 -11
View File
@@ -2,12 +2,12 @@
[Русский](README.md) | English
A React and TypeScript SPA built with Vite and organized using FSD. The interface scaffold exists: public pages and the candidate and employer cabinet shells with navigation, shared screen states, and brand tokens. Every screen is a placeholder; business screens are separate tasks.
A React and TypeScript SPA built with Vite and organized using FSD. Registration, email confirmation, sign-in, consent settings, the manual candidate profile, and the company profile use the API. The cabinets share navigation and screen states; remaining business screens are connected as they are implemented.
- `src/app/` starts the application: the route tree (`router/`), the query client (`providers/`), global styles, and the route error page.
- `src/pages/` holds pages: `welcome` (start page), `placeholder` (screen placeholders and the screen map), `status` (technical status), `not-found`.
- `src/pages/` holds public pages, sign-in and registration, consents, the company page, technical status, and remaining screen placeholders.
- `src/widgets/` holds shells: `public-shell`, `candidate-shell`, `employer-shell`, plus the technical `system-status` widget.
- `src/entities/` holds entities: `need` (the form model of an employer need, see [Need entity](#need-entity)); `src/features/` is still empty.
- `src/entities/` holds entity models, including `need` (see [Need entity](#need-entity)) and `company`; `src/features/` holds user actions and forms.
- `src/shared/ui/` holds design tokens, fonts, logos, and primitives; `src/shared/config/` holds route paths; `src/shared/api/` holds the API client with generated endpoints, Zod schemas, and MSW mocks.
- `codegen/orval.config.ts` configures generation from the shared OpenAPI contract; `codegen/mock-patterns.ts` is the step after Orval that fixes MSW mocks of strings with a `pattern` (see [API client generation](#api-client-generation)).
- `scripts/` checks FSD boundaries and Orval compatibility with the OpenAPI 3.2 fixture.
@@ -17,13 +17,13 @@ From the repository root, `make -C frontend dev` starts development and `make -C
## Routes
| Group | Paths | Shell |
| --------- | -------------------------------------------------------------------------------------------------------------- | ---------------- |
| Public | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` |
| Candidate | `/candidate` and `/candidate/` + `onboarding`, `profile`, `assessment`, `results`, `invitations`, `privacy` | `CandidateShell` |
| Employer | `/employer` (redirects to `/employer/company`), `/employer/` + `company`, `needs`, `candidates`, `invitations` | `EmployerShell` |
| Group | Paths | Shell |
| --------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------- |
| Public | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` |
| Candidate | `/candidate` and `/candidate/` + `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `invitations`, `privacy` | `CandidateShell` |
| Employer | `/employer` (redirects to `/employer/company`), `/employer/` + `company`, `needs`, `candidates`, `invitations` | `EmployerShell` |
Each group has its own not-found page. Paths are defined once in `shared/config/paths.ts`. The router uses React Router data APIs (`createBrowserRouter`): a route-level error boundary, loader redirects, and later `lazy` code splitting for cabinets. Loaders do not fetch data; server data belongs to TanStack Query. Access control is not implemented in the interface; the server enforces it.
Each group has its own not-found page. Paths are defined once in `shared/config/paths.ts`. The router uses React Router data APIs (`createBrowserRouter`): a route-level error boundary, loader redirects, and later `lazy` code splitting for cabinets. Loaders do not fetch data; server data belongs to TanStack Query. Cabinet boundaries read the current session and direct guests to sign-in. The server checks authorization again for every operation.
`/status` is a service page: it checks `/api/v1/healthz` and is linked from the public footer only. It is not a product readiness indicator. In development mode the same page shows a gallery of states built from local fixtures (an error with retry, loading, empty, forbidden, saving, trust levels); production builds do not include it.
@@ -33,7 +33,27 @@ Generated Orval hooks call the shared same-origin `apiRequest` client, so the `Q
- retries: up to two, only for no response (status 0) and 5xx except 501; 4xx and `invalid_response` fail at once;
- `staleTime` of 30 s; window focus does not refetch, and screens that need fresh data opt in per query;
- mutations do not retry until the API supports `Idempotency-Key`.
- automatic mutation retries are disabled; company creation retries through an explicit action with the same body and `Idempotency-Key`.
## Candidate profile
`entities/candidate` holds the complete profile draft model and converts it to `CandidateProfileUpdate`. `features/edit-profile` owns the fields and saving, while `pages/profile` owns the page. Server data stays in React Query; contacts and drafts are not written to localStorage or sessionStorage.
The form preserves the provenance of untouched suggestions, displays overlapping employment periods, and requires explicit confirmation of parallel work. Confirmation is bound to the current indices and dates; reordering or changing periods requires another review. Confirmed categories are displayed separately and never enter the save body. A 412 version conflict preserves the draft and offers an explicit replacement with current data.
After saving, the form reloads the session and shows the account step returned by the server. Saving a profile does not complete the consent step; that transition is not implemented yet. Independent profile editing works without ML, a file, or FSP.
## Candidate questionnaire
`pages/questionnaire` reads the specialization catalog and the current candidate's private answers through Orval. The draft stays in component state, saved answers stay in React Query, and reload restores the server record. The form offers one or two specializations, self-assessed grades, currently available task languages, stack, experience, and work formats. A specialization without a published bank is marked in development and can be saved without FSP.
A 412 conflict retains the draft and offers explicit reload or replacement against the latest read version. Session errors hide private answers; responses from a previous account cannot repopulate the cache. Onboarding links follow the step returned by the server. `/candidate/questionnaire` is the destination for the saved questionnaire step.
## Company profile
`pages/company` selects a company from the paginated active memberships of the current account. Only an owner may read or edit its profile. The form keeps its draft in memory, displays the server verification level without a promotion action, and builds its preview only from `candidate_card`.
Creation uses one idempotency key for retries of the same body after a lost response. A 412 version conflict preserves the draft; the user explicitly loads current data, reviews the reapplied changes, and saves again. Background refresh does not reset the draft. A 401/403/404 response hides the profile and clears its cached query, then reloads the company directory. This complements server membership checks rather than replacing them.
## Need entity
@@ -98,7 +118,7 @@ Accessibility: every shell starts with a skip link to `main`, has landmarks and
## Tests
Vitest runs in the Node environment with no DOM library. Routes are rendered through React Router's static handler and checked as HTML: shells, landmarks, the skip link, the active item, redirects, and not-found pages. State tests render components to markup; the query-error test runs the real `QueryClient` with the generated health operation and a stubbed `fetch`. Clicks and focus movement are checked manually in a browser; automated interaction tests need a DOM environment, which is a separate dependency decision.
Vitest runs in the Node environment with no DOM library. Routes are rendered through React Router's static handler and checked as HTML: shells, landmarks, the skip link, the active item, redirects, and not-found pages. State tests render components to markup; the query-error test runs the real `QueryClient` with the generated health operation and a stubbed `fetch`. Playwright checks clicks, input, and focus movement in real Chromium; Vitest does not substitute a browser environment.
Playwright specs in `e2e/` run in a real Chromium against the built frontend and backend: `make -C deploy test-e2e` starts a throwaway Compose stack and runs them in the official Playwright image, so no browser is installed on the host. Vitest excludes `e2e/`; `make -C frontend typecheck` and lint cover the specs. Artifacts of the last run are in `test-results/e2e/`. Details: [TESTING.md](../docs/en/TESTING.md#browser-e2e-suite).
+31 -11
View File
@@ -2,12 +2,12 @@
Русский | [English](README.en.md)
SPA на React и TypeScript со сборкой Vite и структурой FSD. Готов каркас интерфейса: публичные страницы и оболочки кабинетов кандидата и работодателя с навигацией, общими состояниями экранов и токенами бренда. Все экраны - заготовки; бизнес-экраны делаются отдельными задачами.
SPA на React и TypeScript со сборкой Vite и структурой FSD. Регистрация, подтверждение почты, вход, настройки согласий, ручной профиль кандидата и профиль компании работают с API. Кабинеты имеют общую навигацию и состояния экранов; оставшиеся бизнес-экраны подключаются по мере реализации.
- `src/app/` - запуск приложения: дерево маршрутов (`router/`), клиент запросов (`providers/`), глобальные стили и страница ошибки маршрута.
- `src/pages/` - страницы: `welcome` (стартовая), `placeholder` (заготовки экранов и карта экранов), `status` (технический статус), `not-found`.
- `src/pages/` - публичные страницы, вход и регистрация, согласия, компания, технический статус и оставшиеся заготовки экранов.
- `src/widgets/` - оболочки: `public-shell`, `candidate-shell`, `employer-shell`, а также технический виджет `system-status`.
- `src/entities/` - сущности: `need` (модель формы потребности работодателя, см. [сущность потребности](#сущность-потребности)); `src/features/` пока пуст.
- `src/entities/` - модели сущностей, в том числе `need` (см. [сущность потребности](#сущность-потребности)) и `company`; `src/features/` - действия пользователя и формы.
- `src/shared/ui/` - токены дизайна, шрифты, логотипы и примитивы; `src/shared/config/` - пути маршрутов; `src/shared/api/` - API-клиент со сгенерированными endpoints, схемами Zod и MSW-моками.
- `codegen/orval.config.ts` - генерация из общего OpenAPI-контракта; `codegen/mock-patterns.ts` - шаг после Orval, который исправляет MSW-моки строк с `pattern` (см. [генерацию API-клиента](#генерация-api-клиента)).
- `scripts/` - проверки границ FSD и совместимости Orval с фикстурой OpenAPI 3.2.
@@ -17,13 +17,13 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
## Маршруты
| Группа | Пути | Оболочка |
| ------------ | ------------------------------------------------------------------------------------------------------------------- | ---------------- |
| Публичная | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` |
| Кандидат | `/candidate` и `/candidate/` + `onboarding`, `profile`, `assessment`, `results`, `invitations`, `privacy` | `CandidateShell` |
| Работодатель | `/employer` (перенаправляет на `/employer/company`), `/employer/` + `company`, `needs`, `candidates`, `invitations` | `EmployerShell` |
| Группа | Пути | Оболочка |
| ------------ | -------------------------------------------------------------------------------------------------------------------------- | ---------------- |
| Публичная | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` |
| Кандидат | `/candidate` и `/candidate/` + `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `invitations`, `privacy` | `CandidateShell` |
| Работодатель | `/employer` (перенаправляет на `/employer/company`), `/employer/` + `company`, `needs`, `candidates`, `invitations` | `EmployerShell` |
У каждой группы своя страница "не найдено". Пути заданы один раз в `shared/config/paths.ts`. Роутер использует data API React Router (`createBrowserRouter`): граница ошибок на уровне маршрута, перенаправления через loader и в будущем разделение кода кабинетов через `lazy`. Loader не загружает данные: серверные данные принадлежат TanStack Query. Контроль доступа в интерфейсе не реализован; его обеспечивает сервер.
У каждой группы своя страница "не найдено". Пути заданы один раз в `shared/config/paths.ts`. Роутер использует data API React Router (`createBrowserRouter`): граница ошибок на уровне маршрута, перенаправления через loader и в будущем разделение кода кабинетов через `lazy`. Loader не загружает данные: серверные данные принадлежат TanStack Query. Границы кабинетов читают текущую сессию и направляют гостя на вход. Сервер повторно проверяет полномочия для каждой операции.
`/status` - служебная страница: проверяет `/api/v1/healthz`, ссылка на нее есть только в подвале публичных страниц. Это не показатель готовности продукта. В режиме разработки та же страница показывает галерею состояний на локальных фикстурах (ошибка с повтором, загрузка, пусто, нет доступа, сохранение, уровни доверия); в production-сборку она не попадает.
@@ -33,7 +33,27 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
- повторы: не больше двух и только при отсутствии ответа (статус 0) и 5xx, кроме 501; 4xx и `invalid_response` завершаются сразу;
- `staleTime` 30 с; фокус окна не перезапрашивает данные, экраны со свежими данными включают это для своего запроса;
- мутации не повторяются, пока API не поддерживает `Idempotency-Key`.
- автоматические повторы мутаций выключены; создание компании повторяется явным действием с тем же телом и `Idempotency-Key`.
## Профиль кандидата
`entities/candidate` хранит модель полного черновика профиля и переводит ее в `CandidateProfileUpdate`. `features/edit-profile` отвечает за поля и сохранение, `pages/profile` - за страницу. Серверные данные остаются в React Query; контакты и черновик не записываются в localStorage или sessionStorage.
Форма сохраняет происхождение нетронутых предложений, показывает пересекающиеся периоды работы и требует явного подтверждения параллельной работы. Подтверждение связано с текущими индексами и датами; перестановка или изменение периодов требует проверки заново. Подтвержденные категории отображаются отдельно и не входят в тело сохранения. Ошибка версии 412 оставляет черновик и предлагает явно заменить его актуальными данными.
После сохранения форма перечитывает сессию и показывает шаг аккаунта, который вернул сервер. Сохранение профиля само по себе не завершает шаг согласий; переход от него пока не реализован. Независимое редактирование профиля доступно без ML, файла и ФСП.
## Анкета кандидата
`pages/questionnaire` получает каталог специализаций и приватные ответы текущего кандидата через Orval. Черновик остается в состоянии компонента, сохраненные ответы принадлежат React Query, а reload восстанавливает серверную запись. Форма предлагает одну или две специализации, самооценку грейда, доступные языки заданий, стек, опыт и форматы работы. Специализация без опубликованного банка отмечена как находящаяся в разработке; ее можно сохранить без ФСП.
Конфликт 412 сохраняет черновик и предлагает явное перечитывание или замену по последней прочитанной версии. Ошибки сессии скрывают приватные ответы; ответ прежнего аккаунта не заполняет кеш заново. Переходы onboarding следуют шагу, возвращенному сервером. Сохраненный шаг анкеты открывает `/candidate/questionnaire`.
## Профиль компании
`pages/company` выбирает компанию из постраничного списка действующих membership текущего аккаунта. Читать и менять профиль может только owner. Форма сохраняет черновик в памяти, показывает серверный уровень проверки без возможности повысить его и строит предпросмотр только из `candidate_card`.
Создание использует один ключ идемпотентности для повторов того же тела после потерянного ответа. При конфликте версии 412 черновик сохраняется; пользователь отдельно загружает текущие данные, проверяет перенесенные изменения и повторяет сохранение. Фоновое обновление не сбрасывает черновик. Ответ 401/403/404 скрывает профиль и очищает его запрос из кеша; список компаний перечитывается. Это дополняет серверную проверку membership, а не заменяет ее.
## Сущность потребности
@@ -98,7 +118,7 @@ JetBrains Mono 2.304 (SIL OFL 1.1) раздается с нашего серве
## Тесты
Vitest работает в окружении Node без DOM-библиотеки. Маршруты отрисовываются через статический обработчик React Router и проверяются как HTML: оболочки, ориентиры, ссылка пропуска, активный пункт, перенаправления и страницы "не найдено". Тесты состояний отрисовывают компоненты в разметку; тест ошибки запроса запускает настоящий `QueryClient` со сгенерированной операцией health и подмененным `fetch`. Нажатия и перемещение фокуса проверяются вручную в браузере; автоматические тесты взаимодействия требуют DOM-окружения, а это отдельное решение о зависимости.
Vitest работает в окружении Node без DOM-библиотеки. Маршруты отрисовываются через статический обработчик React Router и проверяются как HTML: оболочки, ориентиры, ссылка пропуска, активный пункт, перенаправления и страницы "не найдено". Тесты состояний отрисовывают компоненты в разметку; тест ошибки запроса запускает настоящий `QueryClient` со сгенерированной операцией health и подмененным `fetch`. Нажатия, ввод и перемещение фокуса проверяются Playwright в настоящем Chromium; Vitest не подменяет браузерное окружение.
Спецификации Playwright из `e2e/` выполняются в настоящем Chromium на собранных frontend и backend: `make -C deploy test-e2e` поднимает одноразовый Compose-стек и запускает их в официальном образе Playwright, поэтому браузер на хост не ставится. Vitest исключает `e2e/`; `make -C frontend typecheck` и lint проверяют спецификации. Артефакты последнего прогона лежат в `test-results/e2e/`. Подробнее: [TESTING.md](../docs/ru/TESTING.md#браузерный-e2e-набор).
+1 -1
View File
@@ -96,7 +96,7 @@ test.describe("registration, email confirmation, and onboarding", () => {
const email = `auth-${crypto.randomUUID()}@example.test`;
const password = "correct horse battery staple 2026";
const scenarioLabel = scenario === "candidate" ? "Кандидат" : "Работодатель";
const nextStep = scenario === "candidate" ? "Согласия" : "Компания и команда";
const nextStep = scenario === "candidate" ? "Согласия" : "Компания";
await page.goto("/register");
await expect(
+457
View File
@@ -0,0 +1,457 @@
import { expect, test, type Page } from "@playwright/test";
type InboxMessage = {
id: string;
text?: string;
html?: string;
};
type InboxResponse = {
messages: InboxMessage[];
};
type OrganizationResponse = {
id: string;
name: string;
version: number;
candidate_card: {
name: string;
description: string | null;
sphere: string | null;
contacts: Record<string, string | null>;
representatives?: { name: string; job_title: string }[] | null;
verification_level: string;
};
};
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
const companyFixtureEnabled = process.env.E2E_COMPANY_FIXTURE === "1";
type CurrentSessionResponse = {
account: { id: string };
};
async function readInbox(email: string): Promise<InboxMessage[]> {
const inboxUrl = process.env.E2E_MAILBOX_URL;
const token = process.env.E2E_MAILBOX_TOKEN;
if (!inboxUrl || !token)
throw new Error("The local registration mailbox fixture is not configured.");
const url = new URL(inboxUrl);
url.searchParams.set("to", email);
const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
if (!response.ok) throw new Error("Could not read the local registration mailbox.");
return ((await response.json()) as InboxResponse).messages;
}
async function waitForVerificationMessage(email: string): Promise<InboxMessage> {
const deadline = Date.now() + 20_000;
while (Date.now() < deadline) {
const message = (await readInbox(email)).at(-1);
if (message) return message;
await new Promise((resolve) => setTimeout(resolve, 250));
}
throw new Error("The local registration mailbox did not receive the expected message.");
}
function verificationToken(message: InboxMessage): string {
const content = `${message.text ?? ""}\n${message.html ?? ""}`;
const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1];
if (!token) throw new Error("The local registration message had no verification link.");
return token;
}
async function registerVerifiedEmployer(
page: Page,
): Promise<{ email: string; password: string; userId: string }> {
const suffix = crypto.randomUUID().slice(0, 8);
const email = `company-${suffix}@example.test`;
const password = "correct horse battery staple 2026";
await page.goto("/register");
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
await page.getByRole("radio", { name: /Работодатель/ }).check();
await page.getByRole("checkbox", { name: /принимаю его/ }).check();
await page.getByRole("button", { name: "Создать аккаунт" }).click();
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
const message = await waitForVerificationMessage(email);
const verificationUrl = new URL("/verify-email", process.env.E2E_BASE_URL);
verificationUrl.hash = `token=${verificationToken(message)}`;
await page.goto(verificationUrl.toString());
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
await page.goto("/employer/company");
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
const loginResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/identity/sessions" &&
response.status() === 201,
);
await page.getByRole("button", { name: "Войти" }).click();
await expect(page.getByRole("heading", { name: "Компания" })).toBeVisible();
const loginResponse = await loginResponsePromise;
const currentSession = (await loginResponse.json()) as CurrentSessionResponse;
return { email, password, userId: currentSession.account.id };
}
async function revokeCompanyMembership(
organizationId: string,
userId: string,
successorUserId: string,
): Promise<void> {
const fixtureURL = process.env.E2E_COMPANY_FIXTURE_URL;
const fixtureToken = process.env.E2E_COMPANY_FIXTURE_TOKEN;
if (!fixtureURL || !fixtureToken) {
throw new Error("The local company membership fixture is not configured.");
}
const response = await fetch(new URL(fixtureURL), {
method: "POST",
headers: {
Authorization: `Bearer ${fixtureToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
organization_id: organizationId,
user_id: userId,
successor_user_id: successorUserId,
}),
});
if (response.status !== 204) {
throw new Error("The local company membership fixture could not revoke the test membership.");
}
}
function isOrganizationRead(response: { url(): string; request(): { method(): string } }): boolean {
return (
response.request().method() === "GET" &&
/\/api\/v1\/organizations\/[0-9a-f-]+$/.test(new URL(response.url()).pathname)
);
}
test.use({ trace: "off", screenshot: "off", video: "off" });
test.describe("company cabinet", () => {
test.skip(
!mailFixtureEnabled || !companyFixtureEnabled,
"Requires the isolated mail and company fixtures.",
);
test("creates, retries, edits, reloads, previews, and hides data after membership revocation", async ({
browser,
page,
}) => {
const { email, userId } = await registerVerifiedEmployer(page);
const baseURL = process.env.E2E_BASE_URL;
if (!baseURL) throw new Error("The local browser test origin is not configured.");
const successorContext = await browser.newContext({
baseURL,
locale: "ru-RU",
});
let successorUserId: string;
try {
const successorPage = await successorContext.newPage();
successorUserId = (await registerVerifiedEmployer(successorPage)).userId;
} finally {
await successorContext.close();
}
const suffix = crypto.randomUUID().slice(0, 8);
const companyName = `North Star ${suffix}`;
const companyDescription = `Candidate-facing company profile ${suffix}`;
const companyMailbox = `careers-${suffix}@example.test`;
const createAttempts: { key: string | undefined; csrf: string | undefined; body: unknown }[] =
[];
const updateAttempts: { csrf: string | undefined; body: unknown }[] = [];
let firstResponseLost = false;
await page.route("**/api/v1/organizations", async (route) => {
if (route.request().method() !== "POST") {
await route.continue();
return;
}
createAttempts.push({
key: route.request().headers()["idempotency-key"],
csrf: route.request().headers()["x-csrf-token"],
body: route.request().postDataJSON(),
});
if (!firstResponseLost) {
const response = await route.fetch();
expect(response.status()).toBe(201);
firstResponseLost = true;
await route.fulfill({
status: 502,
contentType: "application/problem+json; charset=utf-8",
body: JSON.stringify({
type: "urn:lincodex:problem:upstream_unavailable",
title: "Temporary response failure",
status: 502,
code: "upstream_unavailable",
}),
});
return;
}
await route.continue();
});
await expect(page.getByText("Компаний пока нет", { exact: true })).toBeVisible();
await page.getByLabel("Название компании").fill(companyName);
await page.getByLabel("Чем занимается компания").fill(companyDescription);
await page.getByLabel("Сфера деятельности").fill("Платежные технологии");
await page.getByLabel("Сайт компании").fill(`https://north-${suffix}.example`);
await page.getByLabel("Почта для связи").fill(companyMailbox);
await page.getByRole("button", { name: "Добавить представителя" }).click();
await page.getByLabel("Имя представителя").fill("Анна Иванова");
await page.getByLabel("Должность").fill("Руководитель по подбору");
await page.getByRole("button", { name: "Создать компанию" }).click();
await expect(
page.getByRole("button", { name: "Повторить создание с теми же данными" }),
).toBeVisible();
const createdResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/organizations" &&
response.status() === 201,
);
const firstProfileResponsePromise = page.waitForResponse(
(response) => isOrganizationRead(response) && response.status() === 200,
);
await page.getByRole("button", { name: "Повторить создание с теми же данными" }).click();
const createdResponse = await createdResponsePromise;
expect(createAttempts).toHaveLength(2);
expect(createAttempts[0]?.key).toBeTruthy();
expect(createAttempts[0]?.csrf).toBeTruthy();
expect(createAttempts[1]).toEqual(createAttempts[0]);
const created = (await createdResponse.json()) as OrganizationResponse;
expect(created.name).toBe(companyName);
const firstProfileResponse = await firstProfileResponsePromise;
let firstProfile = (await firstProfileResponse.json()) as OrganizationResponse;
expect(firstProfile.id).toBe(created.id);
const draftName = `${companyName} draft`;
await page.getByLabel("Название компании").fill(draftName);
const revalidationResponsePromise = page.waitForResponse(
(response) => isOrganizationRead(response) && response.status() === 200,
);
await page.getByRole("button", { name: "Обновить профиль" }).click();
await revalidationResponsePromise;
await expect(page.getByLabel("Название компании")).toHaveValue(draftName);
await expect(page.getByText("E0 - подтверждена почта владельца")).toBeVisible();
await expect(page.getByText("Подтвержденная почта владельца")).toBeVisible();
await expect(
page.getByRole("button", { name: /повысить уровень|повысить доверие/i }),
).toHaveCount(0);
const updatedName = `${companyName} Labs`;
await page.getByLabel("Название компании").fill(updatedName);
let csrfFailureReturned = false;
let stalePatchReturned = false;
await page.route(`**/api/v1/organizations/${created.id}`, async (route) => {
if (route.request().method() === "PATCH") {
updateAttempts.push({
csrf: route.request().headers()["x-csrf-token"],
body: route.request().postDataJSON(),
});
}
if (route.request().method() === "PATCH" && !csrfFailureReturned) {
csrfFailureReturned = true;
await route.fulfill({
status: 403,
contentType: "application/problem+json; charset=utf-8",
body: JSON.stringify({
type: "urn:lincodex:problem:csrf_check_failed",
title: "CSRF check failed",
status: 403,
code: "csrf_check_failed",
}),
});
return;
}
if (route.request().method() === "PATCH" && !stalePatchReturned) {
stalePatchReturned = true;
await route.fulfill({
status: 412,
contentType: "application/problem+json; charset=utf-8",
body: JSON.stringify({
type: "urn:lincodex:problem:version_conflict",
title: "Version conflict",
status: 412,
code: "version_conflict",
}),
});
return;
}
await route.continue();
});
const conflictResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "PATCH" &&
new URL(response.url()).pathname === `/api/v1/organizations/${created.id}` &&
response.status() === 412,
);
const refreshedSessionPromise = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === "/api/v1/identity/sessions/current" &&
response.status() === 200,
);
await page.getByRole("button", { name: "Сохранить изменения" }).click();
await expect(page.getByRole("alert")).toContainText("Проверка входа обновлена");
await refreshedSessionPromise;
await expect(page.getByLabel("Название компании")).toHaveValue(updatedName);
expect(updateAttempts).toHaveLength(1);
expect(updateAttempts[0]?.csrf).toBeTruthy();
await page.getByRole("button", { name: "Сохранить изменения" }).click();
const conflictResponse = await conflictResponsePromise;
expect(conflictResponse.status()).toBe(412);
expect(updateAttempts).toHaveLength(2);
expect(updateAttempts[1]?.body).toEqual(updateAttempts[0]?.body);
await expect(page.getByLabel("Название компании")).toHaveValue(updatedName);
const latestProfileResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === `/api/v1/organizations/${created.id}` &&
response.status() === 200,
);
await page.getByRole("button", { name: "Прочитать текущую версию" }).click();
await latestProfileResponsePromise;
await expect(page.getByLabel("Название компании")).toHaveValue(updatedName);
await page.getByRole("button", { name: "Я проверил черновик" }).click();
const updateResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "PATCH" &&
new URL(response.url()).pathname === `/api/v1/organizations/${created.id}` &&
response.status() === 200,
);
await page.getByRole("button", { name: "Сохранить изменения" }).click();
const updateResponse = await updateResponsePromise;
expect(updateResponse.status()).toBe(200);
expect(updateAttempts[2]?.csrf).toBeTruthy();
firstProfile = (await updateResponse.json()) as OrganizationResponse;
expect(firstProfile.version).toBeGreaterThan(created.version);
await page.unroute(`**/api/v1/organizations/${created.id}`);
const preview = page.getByRole("article", { name: "Предпросмотр карточки компании" });
await expect(
preview.getByRole("heading", { name: firstProfile.candidate_card.name }),
).toBeVisible();
await expect(
preview.getByText(firstProfile.candidate_card.description ?? "", { exact: true }),
).toBeVisible();
await expect(preview.getByText(companyMailbox, { exact: true })).toBeVisible();
await expect(preview.getByText("Анна Иванова", { exact: true })).toBeVisible();
const previewText = await preview.innerText();
expect(previewText).not.toMatch(/membership|role|участник|владелец/i);
const reloadedProfileResponsePromise = page.waitForResponse(
(response) => isOrganizationRead(response) && response.status() === 200,
);
await page.reload();
const reloadedProfileResponse = await reloadedProfileResponsePromise;
const reloadedProfile = (await reloadedProfileResponse.json()) as OrganizationResponse;
expect(reloadedProfile.id).toBe(created.id);
expect(reloadedProfile.candidate_card).toEqual(firstProfile.candidate_card);
await expect(page.getByRole("heading", { name: updatedName })).toBeVisible();
await expect(
page.getByRole("article", { name: "Предпросмотр карточки компании" }),
).toContainText(reloadedProfile.candidate_card.name);
await expect(page.getByText(email, { exact: true })).toHaveCount(0);
await page.screenshot({
path: `${process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e"}/company-profile.png`,
animations: "disabled",
});
let releaseLateUpdate: (() => void) | undefined;
let notifyLateUpdateStarted: (() => void) | undefined;
const lateUpdateGate = new Promise<void>((resolve) => {
releaseLateUpdate = resolve;
});
const lateUpdateStarted = new Promise<void>((resolve) => {
notifyLateUpdateStarted = resolve;
});
let holdDirectoryRefresh = false;
let releaseDirectoryRefresh: (() => void) | undefined;
let notifyDirectoryRefreshStarted: (() => void) | undefined;
const directoryRefreshGate = new Promise<void>((resolve) => {
releaseDirectoryRefresh = resolve;
});
const directoryRefreshStarted = new Promise<void>((resolve) => {
notifyDirectoryRefreshStarted = resolve;
});
await page.route("**/api/v1/me/organizations**", async (route) => {
if (holdDirectoryRefresh && route.request().method() === "GET") {
holdDirectoryRefresh = false;
const response = await route.fetch();
expect(response.status()).toBe(200);
notifyDirectoryRefreshStarted?.();
await directoryRefreshGate;
await route.fulfill({ response });
return;
}
await route.continue();
});
await page.route(`**/api/v1/organizations/${created.id}`, async (route) => {
if (route.request().method() === "GET") {
await route.continue();
return;
}
if (route.request().method() === "PATCH") {
const response = await route.fetch();
expect(response.status()).toBe(200);
notifyLateUpdateStarted?.();
await lateUpdateGate;
await route.fulfill({ response });
return;
}
await route.continue();
});
const lateUpdatedName = `${updatedName} Review`;
await page.getByLabel("Название компании").fill(lateUpdatedName);
await page.getByRole("button", { name: "Сохранить изменения" }).click();
await lateUpdateStarted;
await revokeCompanyMembership(created.id, userId, successorUserId);
holdDirectoryRefresh = true;
const deniedProfileResponse = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === `/api/v1/organizations/${created.id}` &&
response.status() === 404,
);
await page.getByRole("button", { name: "Обновить профиль" }).click();
await deniedProfileResponse;
await directoryRefreshStarted;
const accessLossNotice = page.getByText("Профиль компании недоступен", { exact: true });
await expect(accessLossNotice).toHaveCount(1);
await expect(accessLossNotice).toBeVisible();
const directoryRefreshResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === "/api/v1/me/organizations" &&
response.status() === 200,
);
releaseDirectoryRefresh?.();
await directoryRefreshResponsePromise;
const lateUpdateResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "PATCH" &&
new URL(response.url()).pathname === `/api/v1/organizations/${created.id}` &&
response.status() === 200,
);
releaseLateUpdate?.();
await lateUpdateResponsePromise;
await expect(page.getByText("Компаний пока нет", { exact: true })).toBeVisible();
await expect(accessLossNotice).toHaveCount(1);
await expect(accessLossNotice).toBeVisible();
await expect(page.getByText(companyDescription, { exact: true })).toHaveCount(0);
await expect(page.getByText(companyMailbox, { exact: true })).toHaveCount(0);
await expect(page.getByRole("article", { name: "Предпросмотр карточки компании" })).toHaveCount(
0,
);
});
});
+349
View File
@@ -0,0 +1,349 @@
import { expect, test, type Page } from "@playwright/test";
type InboxMessage = {
id: string;
text?: string;
html?: string;
};
type InboxResponse = {
messages: InboxMessage[];
};
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
const password = "correct horse battery staple 2026";
function e2eBaseUrl(): string {
const value = process.env.E2E_BASE_URL;
if (!value) throw new Error("The local end-to-end base URL is not configured.");
return value;
}
test.use({ trace: "off", screenshot: "off", video: "off" });
test.describe("candidate profile", () => {
test.skip(!mailFixtureEnabled, "Requires the local mail fixture target.");
async function readInbox(email: string): Promise<InboxMessage[]> {
const inboxUrl = process.env.E2E_MAILBOX_URL;
const token = process.env.E2E_MAILBOX_TOKEN;
if (!inboxUrl || !token) {
throw new Error("The local registration mailbox fixture is not configured.");
}
const url = new URL(inboxUrl);
url.searchParams.set("to", email);
const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
if (!response.ok) throw new Error("Could not read the local registration mailbox.");
return ((await response.json()) as InboxResponse).messages;
}
async function waitForVerification(email: string): Promise<InboxMessage> {
const deadline = Date.now() + 20_000;
while (Date.now() < deadline) {
const message = (await readInbox(email)).at(-1);
if (message) return message;
await new Promise((resolve) => setTimeout(resolve, 250));
}
throw new Error("The local registration mailbox did not receive the verification message.");
}
function verificationToken(message: InboxMessage): string {
const content = `${message.text ?? ""}\n${message.html ?? ""}`;
const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1];
if (!token) throw new Error("The local registration message had no verification link.");
return token;
}
async function login(page: Page, email: string): Promise<void> {
await page.goto("/candidate/profile");
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
await page.getByRole("button", { name: "Войти" }).click();
await expect(page.getByRole("heading", { name: "Первые шаги" })).toBeVisible();
await page.goto("/candidate/profile");
await expect(page.getByRole("heading", { name: "Профиль" })).toBeVisible();
await expect(page.getByLabel("Имя и фамилия")).toBeVisible();
}
async function registerCandidate(page: Page): Promise<{ email: string }> {
const suffix = crypto.randomUUID().slice(0, 8);
const email = `profile-${suffix}@example.test`;
await page.goto("/register");
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
await page.getByRole("radio", { name: /Кандидат/ }).check();
await page.getByRole("checkbox", { name: /принимаю его/ }).check();
await page.getByRole("button", { name: "Создать аккаунт" }).click();
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
const message = await waitForVerification(email);
const verificationUrl = new URL("/verify-email", e2eBaseUrl());
verificationUrl.hash = `token=${verificationToken(message)}`;
await page.goto(verificationUrl.toString());
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
expect(await page.evaluate(() => window.location.hash)).toBe("");
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
await login(page, email);
return { email };
}
async function expectResponsiveKeyboardFlow(page: Page): Promise<void> {
for (const width of [360, 768, 1280]) {
await page.setViewportSize({ width, height: 900 });
await page.getByLabel("Имя и фамилия").focus();
await page.keyboard.press("Tab");
const focusedControlHasRing = await page.evaluate(() => {
const active = document.activeElement;
if (!(active instanceof HTMLElement) || !active.matches(":focus-visible")) return false;
const style = getComputedStyle(active);
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
});
const hasHorizontalOverflow = await page.evaluate(
() => document.documentElement.scrollWidth > window.innerWidth,
);
expect(focusedControlHasRing, `visible focus at ${width}px`).toBe(true);
expect(hasHorizontalOverflow, `no horizontal overflow at ${width}px`).toBe(false);
}
}
async function saveProfile(page: Page, expectedStatus = 200): Promise<void> {
const responsePromise = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/profile",
);
await page.getByRole("button", { name: "Сохранить профиль" }).click();
expect((await responsePromise).status()).toBe(expectedStatus);
}
async function pauseProfileSave(page: Page) {
let intercepted = false;
let cleanupStarted = false;
let markForwarded: () => void = () => {};
let releaseRequest: () => void = () => {};
let routeTask: Promise<void> = Promise.resolve();
const forwarded = new Promise<void>((resolve) => {
markForwarded = resolve;
});
const gate = new Promise<void>((resolve) => {
releaseRequest = resolve;
});
const response = page.waitForResponse(
(item) =>
item.request().method() === "PUT" && new URL(item.url()).pathname === "/api/v1/me/profile",
);
void response.catch(() => undefined);
await page.route("**/api/v1/me/profile", (route) => {
if (route.request().method() !== "PUT" || intercepted) {
return route.continue();
}
intercepted = true;
routeTask = (async () => {
const result = await route.fetch();
markForwarded();
await gate;
try {
await route.fulfill({ response: result });
} catch (error: unknown) {
if (!cleanupStarted) throw error;
}
})();
return routeTask;
});
return {
forwarded,
response,
release: releaseRequest,
cleanup: async () => {
cleanupStarted = true;
releaseRequest();
await routeTask.catch(() => undefined);
await page.unroute("**/api/v1/me/profile");
},
};
}
test("saves manual profile data, reloads it, and preserves a stale draft through a version conflict", async ({
browser,
page,
}) => {
const suffix = crypto.randomUUID().slice(0, 8);
const name = `Тестовый профиль ${suffix}`;
const contactEmail = `contact-${suffix}@example.test`;
const { email } = await registerCandidate(page);
await page.setViewportSize({ width: 360, height: 900 });
await expect(page.getByText("Сохраненный шаг аккаунта: Согласия.")).toBeVisible();
await page.getByLabel("Имя и фамилия").fill(name);
await page.getByLabel("Контактный email").fill(contactEmail);
await page.getByLabel("Телефон").fill("+79990000000");
await page.getByLabel("Telegram").fill("@candidate_123");
await page.getByRole("button", { name: "Добавить место работы" }).click();
await page.getByRole("button", { name: "Добавить место работы" }).click();
await page.getByLabel("Компания").nth(0).fill("Первая компания");
await page.getByLabel("Компания").nth(1).fill("Вторая компания");
await page.getByLabel("Специализация").nth(0).selectOption("backend");
await page.getByLabel("Специализация").nth(1).selectOption("frontend");
await page.getByLabel("Начало работы").nth(0).fill("2024-01");
await page.getByLabel("Окончание работы").nth(0).fill("2024-12");
await page.getByLabel("Начало работы").nth(1).fill("2024-06");
await page.getByLabel("Окончание работы").nth(1).fill("2025-01");
await page.getByRole("checkbox", { name: /Подтверждаю, что места работы 1 и 2/ }).check();
await page.getByRole("button", { name: "Добавить специализацию" }).click();
await page.getByLabel("Специализация").nth(2).selectOption("backend");
await page.getByLabel("Моя оценка уровня").selectOption("senior");
await page.getByRole("button", { name: "Добавить навык" }).click();
await page.getByLabel("Навык 1", { exact: true }).fill("Go");
await page.getByRole("button", { name: "Добавить гибкий навык" }).click();
await page.getByLabel("Гибкий навык 1", { exact: true }).fill("Коммуникация");
await page.getByLabel("Желаемое место работы").fill("Москва");
await page.getByLabel("Готовность к переезду").selectOption("true");
await page.getByLabel("Минимальная зарплата, рублей в месяц").fill("150000");
await page.getByLabel("Сумма до или после налога").selectOption("gross");
const pausedSave = await pauseProfileSave(page);
try {
const saveButton = page.getByRole("button", { name: /Сохранить профиль|Сохраняем профиль/ });
await saveButton.click();
await pausedSave.forwarded;
await expect(page.getByLabel("Имя и фамилия")).toBeDisabled();
await expect(saveButton).toBeFocused();
await expect(saveButton).toHaveAttribute("aria-disabled", "true");
pausedSave.release();
expect((await pausedSave.response).status()).toBe(200);
await expect(page.getByLabel("Имя и фамилия")).toBeEnabled();
} finally {
pausedSave.release();
await pausedSave.cleanup();
}
await expect(
page.getByText("Профиль сохранен. Сервер подтвердил шаг аккаунта: Согласия."),
).toBeVisible();
await expect(page.getByText("Сохраненный шаг аккаунта: Согласия.")).toBeVisible();
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(name);
await expect(
page.getByText(/Параллельная работа в местах 1 и 2 подтверждена ранее/),
).toBeVisible();
await page.screenshot({
path: `${process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e"}/candidate-profile-mobile.png`,
animations: "disabled",
});
const profileNotPersistedInBrowserStorage = await page.evaluate((needle) => {
const serialized = [localStorage, sessionStorage]
.flatMap((storage) =>
Array.from({ length: storage.length }, (_, index) => {
const key = storage.key(index);
return key === null ? "" : `${key}:${storage.getItem(key) ?? ""}`;
}),
)
.join("\n");
return !serialized.includes(needle);
}, name);
expect(profileNotPersistedInBrowserStorage).toBe(true);
await page.reload();
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(name);
await expect(page.getByLabel("Контактный email")).toHaveValue(contactEmail);
await expect(page.getByLabel("Телефон")).toHaveValue("+79990000000");
await expect(page.getByLabel("Telegram")).toHaveValue("@candidate_123");
await expect(page.getByLabel("Навык 1", { exact: true })).toHaveValue("Go");
await expect(page.getByLabel("Гибкий навык 1", { exact: true })).toHaveValue("Коммуникация");
await expect(page.getByLabel("Минимальная зарплата, рублей в месяц")).toHaveValue("150000");
await expect(page.getByText("Сохраненный шаг аккаунта: Согласия.")).toBeVisible();
await expectResponsiveKeyboardFlow(page);
const secondContext = await browser.newContext({
baseURL: e2eBaseUrl(),
locale: "ru-RU",
});
try {
const secondPage = await secondContext.newPage();
await login(secondPage, email);
const secondVersionName = `Изменение во втором окне ${suffix}`;
await secondPage.getByLabel("Имя и фамилия").fill(secondVersionName);
await saveProfile(secondPage);
const staleName = `Черновик первого окна ${suffix}`;
await page.getByLabel("Имя и фамилия").fill(staleName);
await saveProfile(page, 412);
await expect(
page.getByRole("heading", { name: "Профиль обновлен в другом окне" }),
).toBeVisible();
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(staleName);
const latestRead = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === "/api/v1/me/profile" &&
response.status() === 200,
);
await page.getByRole("button", { name: "Заменить черновик актуальной версией" }).click();
await latestRead;
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(secondVersionName);
await page.getByLabel("Имя и фамилия").fill(staleName);
await saveProfile(page);
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(staleName);
await expectResponsiveKeyboardFlow(page);
await page.reload();
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(staleName);
} finally {
await secondContext.close();
}
});
test("does not cache a pending save after the account changes", async ({ browser, page }) => {
const firstAccount = await registerCandidate(page);
const firstProfileName = `Первый профиль ${crypto.randomUUID().slice(0, 8)}`;
await page.getByLabel("Имя и фамилия").fill(firstProfileName);
const pausedSave = await pauseProfileSave(page);
try {
const saveButton = page.getByRole("button", { name: /Сохранить профиль|Сохраняем профиль/ });
await saveButton.click();
await pausedSave.forwarded;
await expect(page.getByLabel("Имя и фамилия")).toBeDisabled();
const secondContext = await browser.newContext({
baseURL: e2eBaseUrl(),
locale: "ru-RU",
});
let secondAccount: { email: string };
try {
const secondPage = await secondContext.newPage();
secondAccount = await registerCandidate(secondPage);
} finally {
await secondContext.close();
}
await page.evaluate(() => {
window.history.pushState({}, "", "/login");
window.dispatchEvent(new PopStateEvent("popstate"));
});
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await page.getByLabel("Электронная почта").fill(secondAccount.email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
await page.getByRole("button", { name: "Войти" }).click();
await expect(page.getByRole("heading", { name: "Первые шаги" })).toBeVisible();
await page.getByRole("link", { name: "Профиль" }).click();
await expect(page.getByRole("heading", { name: "Профиль" })).toBeVisible();
await expect(page.getByLabel("Имя и фамилия")).toHaveValue("");
pausedSave.release();
expect((await pausedSave.response).status()).toBe(200);
await expect(page.getByLabel("Имя и фамилия")).toHaveValue("");
await expect(page.getByText(firstProfileName)).toHaveCount(0);
expect(firstAccount.email).not.toBe(secondAccount.email);
} finally {
pausedSave.release();
await pausedSave.cleanup();
}
});
});
+529
View File
@@ -0,0 +1,529 @@
import { expect, test, type Browser, type Page, type Route } from "@playwright/test";
type InboxMessage = {
id: string;
text?: string;
html?: string;
};
type InboxResponse = {
messages: InboxMessage[];
};
type QuestionnaireResponse = {
version: number;
updated_at?: string | null;
specializations: {
specialization: string;
self_assessed_grade: string;
task_languages: string[];
stack: string[];
experience: { commercial_months: number; academic_months: number } | null;
}[];
work_context: { work_formats: string[] } | null;
};
const questionnaireFixtureEnabled = process.env.E2E_QUESTIONNAIRE_FIXTURE === "1";
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
const password = "correct horse battery staple 2026";
test.use({ trace: "off", screenshot: "off", video: "off" });
function baseUrl(): string {
const value = process.env.E2E_BASE_URL;
if (!value) throw new Error("The local end-to-end base URL is not configured.");
return value;
}
async function readInbox(email: string): Promise<InboxMessage[]> {
const inboxUrl = process.env.E2E_MAILBOX_URL;
const token = process.env.E2E_MAILBOX_TOKEN;
if (!inboxUrl || !token)
throw new Error("The local registration mailbox fixture is not configured.");
const url = new URL(inboxUrl);
url.searchParams.set("to", email);
const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
if (!response.ok) throw new Error("Could not read the local registration mailbox.");
return ((await response.json()) as InboxResponse).messages;
}
async function waitForVerificationMessage(email: string): Promise<InboxMessage> {
const deadline = Date.now() + 20_000;
while (Date.now() < deadline) {
const message = (await readInbox(email)).at(-1);
if (message) return message;
await new Promise((resolve) => setTimeout(resolve, 250));
}
throw new Error("The local registration mailbox did not receive the verification message.");
}
function verificationToken(message: InboxMessage): string {
const content = `${message.text ?? ""}\n${message.html ?? ""}`;
const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1];
if (!token) throw new Error("The local registration message had no verification link.");
return token;
}
async function registerVerifiedCandidate(page: Page): Promise<{ email: string }> {
const email = `questionnaire-${crypto.randomUUID()}@example.test`;
await page.goto("/register");
await expect(
page.getByRole("heading", { name: "Согласие C1 на обработку персональных данных" }),
).toBeVisible();
await expect(page.getByText(/C4/)).toHaveCount(0);
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
await page.getByRole("radio", { name: /Кандидат/ }).check();
await page.getByRole("checkbox", { name: /принимаю его/ }).check();
await page.getByRole("button", { name: "Создать аккаунт" }).click();
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
const message = await waitForVerificationMessage(email);
const verificationUrl = new URL("/verify-email", baseUrl());
verificationUrl.hash = `token=${verificationToken(message)}`;
await page.goto(verificationUrl.toString());
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
await expect.poll(() => page.evaluate(() => window.location.hash)).toBe("");
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
const confirmResponse = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/identity/email-verifications",
);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
expect((await confirmResponse).status()).toBe(200);
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
await signIn(page, email);
return { email };
}
async function signIn(page: Page, email: string): Promise<void> {
await page.goto("/candidate/questionnaire");
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
const loginResponse = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/identity/sessions",
);
await page.getByRole("button", { name: "Войти" }).click();
expect((await loginResponse).status()).toBe(201);
await page.goto("/candidate/questionnaire");
await expect(page.getByRole("heading", { name: "Анкета" })).toBeVisible();
await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible();
}
async function checkResponsiveLayout(page: Page): Promise<void> {
for (const width of [360, 768, 1280]) {
await page.setViewportSize({ width, height: 900 });
const hasHorizontalOverflow = await page.evaluate(
() => document.documentElement.scrollWidth > window.innerWidth,
);
expect(hasHorizontalOverflow, `no horizontal overflow at ${width}px`).toBe(false);
if (width === 360) continue;
await page.getByLabel("Специализация", { exact: true }).focus();
await page.keyboard.press("Tab");
const hasVisibleFocus = await page.evaluate(() => {
const active = document.activeElement;
if (!(active instanceof HTMLElement) || !active.matches(":focus-visible")) return false;
const style = getComputedStyle(active);
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
});
expect(hasVisibleFocus, `visible keyboard focus at ${width}px`).toBe(true);
}
await page.setViewportSize({ width: 360, height: 900 });
}
async function tabToSaveButton(page: Page): Promise<void> {
const saveButton = page.getByRole("button", { name: "Сохранить анкету" });
await page.evaluate(() => {
if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
});
let reached = false;
for (let index = 0; index < 50; index += 1) {
await page.keyboard.press("Tab");
if (await saveButton.evaluate((button) => document.activeElement === button)) {
reached = true;
break;
}
}
expect(reached, "keyboard can reach the questionnaire save action").toBe(true);
const hasVisibleFocus = await saveButton.evaluate((button) => {
if (!(button instanceof HTMLElement) || !button.matches(":focus-visible")) return false;
const style = getComputedStyle(button);
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
});
expect(hasVisibleFocus, "save action has a visible keyboard focus indicator").toBe(true);
}
async function saveFromKeyboard(page: Page, expectedStatus: number): Promise<void> {
const responsePromise = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await tabToSaveButton(page);
await page.keyboard.press("Enter");
expect((await responsePromise).status()).toBe(expectedStatus);
}
async function createSecondSession(browser: Browser, email: string): Promise<Page> {
const context = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
const page = await context.newPage();
await signIn(page, email);
return page;
}
async function navigateInApp(page: Page, path: string): Promise<void> {
await page.evaluate((target) => {
window.history.pushState(window.history.state, "", target);
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
}, path);
}
async function fulfillProblem(route: Route, status: number, code: string): Promise<void> {
await route.fulfill({
status,
headers: { "content-type": "application/problem+json" },
body: JSON.stringify({
type: `urn:lincodex:problem:${code}`,
title: code,
status,
code,
}),
});
}
test.describe("candidate questionnaire", () => {
test("saves real catalog answers, reloads them, and preserves a draft after 412", async ({
browser,
page,
}) => {
test.skip(
!questionnaireFixtureEnabled || !mailFixtureEnabled,
"Requires the local published Backend bank and mail fixtures.",
);
const { email } = await registerVerifiedCandidate(page);
await page.setViewportSize({ width: 360, height: 900 });
const catalogResponse = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === "/api/v1/specializations",
);
const questionnaireResponse = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page.goto("/candidate/questionnaire");
expect((await catalogResponse).status()).toBe(200);
const initialResponse = await questionnaireResponse;
expect(initialResponse.status()).toBe(200);
const initial = (await initialResponse.json()) as QuestionnaireResponse;
expect(initial.version).toBe(0);
const specialization = page.getByLabel("Специализация", { exact: true });
await specialization.selectOption("ds_ml");
await expect(page.getByText("Проверка: в разработке")).toBeVisible();
await expect(
page.getByText("Эту специализацию можно сохранить. Начать проверку по ней пока нельзя."),
).toBeVisible();
await expect(page.getByRole("button", { name: /проверку/i })).toHaveCount(0);
await page.getByLabel("Моя оценка уровня").selectOption("senior");
await page.getByLabel("Удаленно").check();
await saveFromKeyboard(page, 200);
await expect(
page.getByText(/Анкета сохранена\. Сервер подтвердил шаг аккаунта:/),
).toBeVisible();
await expect(page.getByText(/Шаг аккаунта на сервере: Согласия\./)).toBeVisible();
await specialization.selectOption("backend");
await page.getByLabel("Моя оценка уровня").selectOption("junior");
await page.getByRole("checkbox", { name: "Go", exact: true }).check();
await page.getByLabel("Стек технологий").fill("Go");
await page.getByRole("button", { name: "Добавить технологию" }).click();
const backendSave = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page.getByRole("button", { name: "Сохранить анкету" }).click();
const backendSaveResponse = await backendSave;
expect(backendSaveResponse.status()).toBe(200);
const savedBackend = (await backendSaveResponse.json()) as QuestionnaireResponse;
expect(savedBackend.specializations).toEqual([
{
specialization: "backend",
self_assessed_grade: "junior",
task_languages: ["go"],
stack: ["Go"],
experience: null,
},
]);
await expect(page.getByText(/Анкета сохранена/)).toBeVisible();
await page.reload();
await expect(page.getByLabel("Специализация", { exact: true })).toHaveValue("backend");
await expect(page.getByLabel("Моя оценка уровня")).toHaveValue("junior");
await expect(page.getByRole("checkbox", { name: "Go", exact: true })).toBeChecked();
await expect(page.getByLabel("Стек технологий")).toHaveValue("");
await expect(page.getByText(/Шаг аккаунта на сервере: Согласия\./)).toBeVisible();
await page.screenshot({
path: `${process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e"}/questionnaire-360.png`,
});
await checkResponsiveLayout(page);
const secondPage = await createSecondSession(browser, email);
try {
await secondPage.getByLabel("Специализация", { exact: true }).selectOption("ds_ml");
await secondPage.getByLabel("Моя оценка уровня").selectOption("senior");
const concurrentSave = secondPage.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await secondPage.getByRole("button", { name: "Сохранить анкету" }).click();
expect((await concurrentSave).status()).toBe(200);
await page.getByLabel("Удаленно").uncheck();
await page.getByLabel("В офисе").check();
const staleSave = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page.getByRole("button", { name: "Сохранить анкету" }).click();
expect((await staleSave).status()).toBe(412);
await expect(
page.getByRole("heading", { name: "Анкета изменилась в другом окне" }),
).toBeVisible();
await expect(page.getByLabel("Удаленно")).not.toBeChecked();
await expect(page.getByLabel("В офисе")).toBeChecked();
await expect(page.getByText(/Последняя прочитанная серверная версия:/)).toBeVisible();
const reapply = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page
.getByRole("button", { name: "Записать этот черновик поверх актуальной анкеты" })
.click();
expect((await reapply).status()).toBe(200);
await expect(page.getByText(/Анкета сохранена/)).toBeVisible();
await secondPage.reload();
await expect(secondPage.getByLabel("В офисе")).toBeChecked();
await expect(secondPage.getByLabel("Удаленно")).not.toBeChecked();
await checkResponsiveLayout(page);
} finally {
await secondPage.context().close();
}
});
test("blocks questionnaire reads after an API 401 with a cached session", async ({ page }) => {
test.skip(
!questionnaireFixtureEnabled || !mailFixtureEnabled,
"Requires the local questionnaire and mail fixtures.",
);
await registerVerifiedCandidate(page);
await page.getByRole("link", { name: "Профиль" }).click();
await expect(page.getByRole("heading", { name: "Профиль" })).toBeVisible();
await page.route("**/api/v1/me/questionnaire", async (route) => {
if (route.request().method() === "GET") {
await fulfillProblem(route, 401, "unauthenticated");
return;
}
await route.continue();
});
const failedRead = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page.getByRole("link", { name: "Анкета" }).click();
expect((await failedRead).status()).toBe(401);
await expect(page.getByText("Анкета недоступна", { exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "Сохранить анкету" })).toHaveCount(0);
await expect(page.getByLabel("Специализация", { exact: true })).toHaveCount(0);
});
test("clears the editor after a non-CSRF 403 response", async ({ page }) => {
test.skip(
!questionnaireFixtureEnabled || !mailFixtureEnabled,
"Requires the local questionnaire and mail fixtures.",
);
await registerVerifiedCandidate(page);
await page.getByLabel("Специализация", { exact: true }).selectOption("ds_ml");
await page.getByLabel("Моя оценка уровня").selectOption("senior");
await page.getByLabel("Удаленно").check();
await page.route("**/api/v1/me/questionnaire", async (route) => {
if (route.request().method() === "PUT") {
await fulfillProblem(route, 403, "forbidden");
return;
}
await route.continue();
});
const saveResponse = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page.getByRole("button", { name: "Сохранить анкету" }).click();
expect((await saveResponse).status()).toBe(403);
await expect(page.getByText("Анкета недоступна", { exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "Сохранить анкету" })).toHaveCount(0);
await expect(page.getByLabel("Специализация", { exact: true })).toHaveCount(0);
});
test("keeps a draft after a successful CSRF refresh and hides it when refresh fails", async ({
page,
}) => {
test.skip(
!questionnaireFixtureEnabled || !mailFixtureEnabled,
"Requires the local questionnaire and mail fixtures.",
);
await registerVerifiedCandidate(page);
await page.getByLabel("Специализация", { exact: true }).selectOption("ds_ml");
await page.getByLabel("Моя оценка уровня").selectOption("senior");
await page.getByLabel("Удаленно").check();
let rejectSessionRefresh = false;
await page.route("**/api/v1/identity/sessions/current", async (route) => {
if (rejectSessionRefresh) {
await fulfillProblem(route, 401, "unauthenticated");
return;
}
await route.continue();
});
await page.route("**/api/v1/me/questionnaire", async (route) => {
if (route.request().method() === "PUT") {
await fulfillProblem(route, 403, "csrf_check_failed");
return;
}
await route.continue();
});
const firstSave = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page.getByRole("button", { name: "Сохранить анкету" }).click();
expect((await firstSave).status()).toBe(403);
await expect(
page.getByText("Проверка входа обновлена. Ответы остались в форме, повторите сохранение."),
).toBeVisible();
await expect(page.getByLabel("Специализация", { exact: true })).toHaveValue("ds_ml");
rejectSessionRefresh = true;
const secondSave = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page.getByRole("button", { name: "Сохранить анкету" }).click();
expect((await secondSave).status()).toBe(403);
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await expect(page.getByRole("button", { name: "Сохранить анкету" })).toHaveCount(0);
});
test("ignores an old account save response after signing in to another account", async ({
browser,
page,
}) => {
test.skip(
!questionnaireFixtureEnabled || !mailFixtureEnabled,
"Requires the local questionnaire and mail fixtures.",
);
const secondContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
let secondEmail: string;
try {
const secondAccountPage = await secondContext.newPage();
({ email: secondEmail } = await registerVerifiedCandidate(secondAccountPage));
} finally {
await secondContext.close();
}
await registerVerifiedCandidate(page);
await page.getByLabel("Специализация", { exact: true }).selectOption("ds_ml");
await page.getByLabel("Моя оценка уровня").selectOption("senior");
await page.getByLabel("Удаленно").check();
let releaseOldResponse: () => void = () => undefined;
let markOldRequestHeld: () => void = () => undefined;
const oldResponseGate = new Promise<void>((resolve) => {
releaseOldResponse = resolve;
});
const oldRequestHeld = new Promise<void>((resolve) => {
markOldRequestHeld = resolve;
});
let held = false;
let cleanupStarted = false;
let requestForwarded = false;
await page.route("**/api/v1/me/questionnaire", (route) => {
if (route.request().method() === "PUT" && !held) {
held = true;
return (async () => {
const response = await route.fetch();
requestForwarded = true;
markOldRequestHeld();
await oldResponseGate;
try {
await route.fulfill({ response });
} catch (error: unknown) {
if (!cleanupStarted) throw error;
}
})();
}
return route.continue();
});
const oldSaveResponse = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
void oldSaveResponse.catch(() => undefined);
try {
await page.getByRole("button", { name: "Сохранить анкету" }).click();
await oldRequestHeld;
await navigateInApp(page, "/login");
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await page.getByLabel("Электронная почта").fill(secondEmail);
await page.getByLabel("Пароль", { exact: true }).fill(password);
const loginResponse = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/identity/sessions",
);
await page.getByRole("button", { name: "Войти" }).click();
expect((await loginResponse).status()).toBe(201);
await navigateInApp(page, "/candidate/questionnaire");
await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible();
await expect(page.getByLabel("Специализация", { exact: true })).toHaveValue("");
releaseOldResponse();
expect((await oldSaveResponse).status()).toBe(200);
await expect(page.getByLabel("Специализация", { exact: true })).toHaveValue("");
await expect(page.getByLabel("Моя оценка уровня")).toHaveValue("");
await expect(page.getByRole("button", { name: "Сохранить анкету" })).toBeEnabled();
await expect(page.getByRole("button", { name: "Сохраняем анкету..." })).toHaveCount(0);
} finally {
cleanupStarted = true;
releaseOldResponse();
if (requestForwarded) await oldSaveResponse.catch(() => undefined);
await page.unroute("**/api/v1/me/questionnaire");
}
});
});
+2 -1
View File
@@ -119,9 +119,10 @@ describe("route groups", () => {
["/support", "Поддержка", "Публичные разделы"],
["/candidate", "Главная", "Разделы кабинета кандидата"],
["/candidate/profile", "Профиль", "Разделы кабинета кандидата"],
["/candidate/questionnaire", "Анкета", "Разделы кабинета кандидата"],
["/candidate/onboarding", "Первые шаги", "Разделы кабинета кандидата"],
["/candidate/privacy", "Согласия и настройки приватности", "Разделы кабинета кандидата"],
["/employer/company", "Компания и команда", "Разделы кабинета работодателя"],
["/employer/company", "Компания", "Разделы кабинета работодателя"],
["/employer/candidates", "Кандидаты", "Разделы кабинета работодателя"],
])("renders %s in its shell with one h1 and landmarks", async (path, heading, navLabel) => {
const html = await renderHtml(path);
+9 -2
View File
@@ -1,10 +1,13 @@
import { redirect, type RouteObject } from "react-router-dom";
import { LoginPage, RegisterPage, VerifyEmailPage } from "../../pages/auth";
import { CandidateOnboardingPage } from "../../pages/candidate-onboarding";
import { CompanyPage } from "../../pages/company";
import { ConsentsPage } from "../../pages/consents";
import { SessionGate } from "../../entities/session";
import { NotFoundPage } from "../../pages/not-found";
import { PlaceholderPage } from "../../pages/placeholder";
import { ProfilePage } from "../../pages/profile";
import { QuestionnairePage } from "../../pages/questionnaire";
import { StatusPage } from "../../pages/status";
import { WelcomePage } from "../../pages/welcome";
import { paths } from "../../shared/config";
@@ -47,7 +50,11 @@ export const routes: RouteObject[] = [
{ path: paths.candidate.onboarding, element: <CandidateOnboardingPage /> },
{
path: paths.candidate.profile,
element: <PlaceholderPage screen="candidateProfile" />,
element: <ProfilePage />,
},
{
path: paths.candidate.questionnaire,
element: <QuestionnairePage />,
},
{
path: paths.candidate.assessment,
@@ -85,7 +92,7 @@ export const routes: RouteObject[] = [
{ index: true, loader: () => redirect(paths.employer.company) },
{
path: paths.employer.company,
element: <PlaceholderPage screen="employerCompany" />,
element: <CompanyPage />,
},
{ path: paths.employer.needs, element: <PlaceholderPage screen="employerNeeds" /> },
{
+28
View File
@@ -0,0 +1,28 @@
export {
addExperience,
addRole,
addSoftSkill,
addStack,
buildCandidateProfileUpdate,
mapProfileServerErrors,
moveExperience,
profilePointerField,
removeExperience,
removeItem,
reviewExperienceOverlaps,
setParallelAcknowledgement,
toCandidateProfileDraft,
updateExperienceDraft,
updateFieldDraft,
updateRoleDraft,
updateSalaryDraft,
updateSoftSkillDraft,
updateStackDraft,
type CandidateProfileDraft,
type ExperienceDraft,
type FieldDraft,
type ProfileFormIssue,
type RoleDraft,
type SoftSkillDraft,
type StackDraft,
} from "./model/profile-form";
@@ -0,0 +1,234 @@
import { describe, expect, it } from "vitest";
import type { CandidateProfile } from "../../../shared/api/schemas";
import {
addExperience,
buildCandidateProfileUpdate,
mapProfileServerErrors,
moveExperience,
reviewExperienceOverlaps,
setParallelAcknowledgement,
toCandidateProfileDraft,
updateExperienceDraft,
updateFieldDraft,
} from "./profile-form";
const unknownClaim = { status: "unknown", value: null, source: null } as const;
function blankProfile(): CandidateProfile {
return {
version: 0,
full_name: unknownClaim,
contacts: { email: unknownClaim, phone: unknownClaim, telegram: unknownClaim },
stack: [],
roles: [],
experience: [],
experience_overlaps: [],
soft_skills: [],
terms: {
location: unknownClaim,
relocation: unknownClaim,
salary_minimum: unknownClaim,
},
confirmed_categories: [],
updated_at: null,
};
}
const suggestion = {
origin: "extracted_from_resume",
trust_level: 0,
quote: "Работал с Go и PostgreSQL",
extraction_version: "resume-rules.2026-10.1",
confirmed_at: null,
} as const;
describe("candidate profile draft mapping", () => {
it("sends an empty first profile as unknown values at version zero", () => {
const draft = toCandidateProfileDraft(blankProfile());
const result = buildCandidateProfileUpdate(draft, new Date("2026-06-15T00:00:00Z"));
expect(result.issues).toEqual([]);
expect(result.data).toMatchObject({
expected_version: 0,
full_name: null,
contacts: { email: null, phone: null, telegram: null },
stack: [],
roles: [],
experience: [],
confirmed_parallel_periods: [],
soft_skills: [],
terms: { location: null, relocation: null, salary_minimum: null },
});
expect(result.data).not.toHaveProperty("confirmed_categories");
});
it("preserves untouched suggestions and confirms a changed suggestion", () => {
const profile: CandidateProfile = {
...blankProfile(),
version: 4,
full_name: { status: "extracted", value: "Анна Соколова", source: suggestion },
contacts: {
email: unknownClaim,
phone: { status: "extracted", value: "+79000000000", source: suggestion },
telegram: unknownClaim,
},
stack: [{ tag: "Go", status: "extracted", source: suggestion }],
experience: [
{
employer_name: "ООО Пример",
specialization: "backend",
started_on: "2022-01",
ended_on: null,
summary: "Разработка сервисов",
status: "extracted",
source: suggestion,
},
],
soft_skills: [{ skill: "Наставничество", status: "extracted", source: suggestion }],
terms: {
location: { status: "extracted", value: "Казань", source: suggestion },
relocation: unknownClaim,
salary_minimum: unknownClaim,
},
};
let draft = toCandidateProfileDraft(profile);
const stackId = draft.stack[0]?.id;
if (!stackId) throw new Error("Expected a stack suggestion in the fixture.");
let result = buildCandidateProfileUpdate(draft, new Date("2026-06-15T00:00:00Z"));
expect(result.data?.full_name).toEqual({ value: "Анна Соколова", status: "extracted" });
expect(result.data?.contacts.phone).toEqual({ value: "+79000000000", status: "extracted" });
expect(result.data?.stack).toEqual([{ tag: "Go", status: "extracted" }]);
expect(result.data?.experience[0]?.status).toBe("extracted");
expect(result.data?.soft_skills).toEqual([{ skill: "Наставничество", status: "extracted" }]);
expect(result.data?.terms.location).toEqual({ value: "Казань", status: "extracted" });
draft = {
...draft,
stack: draft.stack.map((item) =>
item.id === stackId ? { ...item, tag: "Go и PostgreSQL", status: "confirmed" } : item,
),
};
result = buildCandidateProfileUpdate(draft, new Date("2026-06-15T00:00:00Z"));
expect(result.data?.stack).toEqual([{ tag: "Go и PostgreSQL", status: "confirmed" }]);
const nameDraft = toCandidateProfileDraft(profile).fullName;
expect(updateFieldDraft(nameDraft, "Новое имя").status).toBe("confirmed");
expect(updateFieldDraft(nameDraft, "Анна Соколова").status).toBe("extracted");
});
it("requires an explicit range-bound acknowledgement and clears it after date edits or reorder", () => {
let draft = toCandidateProfileDraft(blankProfile());
draft = addExperience(draft, "first");
draft = updateExperienceDraft(draft, "first", {
employer_name: "Первая компания",
specialization: "backend",
started_on: "2023-01",
ended_on: "2024-12",
});
draft = addExperience(draft, "second");
draft = updateExperienceDraft(draft, "second", {
employer_name: "Вторая компания",
specialization: "frontend",
started_on: "2024-01",
ended_on: "2025-01",
});
const overlap = reviewExperienceOverlaps(draft, new Date("2026-06-15T00:00:00Z"))[0];
expect(overlap).toMatchObject({
key: "0:1",
requiresAcknowledgement: true,
acknowledged: false,
});
expect(buildCandidateProfileUpdate(draft, new Date("2026-06-15T00:00:00Z")).data).toBeNull();
draft = setParallelAcknowledgement(draft, "0:1", true);
const acknowledged = buildCandidateProfileUpdate(draft, new Date("2026-06-15T00:00:00Z"));
expect(acknowledged.data?.confirmed_parallel_periods).toEqual([
{
first_index: 0,
second_index: 1,
first_period: { started_on: "2023-01", ended_on: "2024-12" },
second_period: { started_on: "2024-01", ended_on: "2025-01" },
},
]);
const changed = updateExperienceDraft(draft, "second", { started_on: "2024-02" });
expect(changed.parallelAcknowledgements).toEqual({});
expect(
reviewExperienceOverlaps(changed, new Date("2026-06-15T00:00:00Z"))[0]?.acknowledged,
).toBe(false);
const reordered = moveExperience(draft, 1, -1);
expect(reordered.parallelAcknowledgements).toEqual({});
expect(
reviewExperienceOverlaps(reordered, new Date("2026-06-15T00:00:00Z"))[0]
?.requiresAcknowledgement,
).toBe(true);
});
it("carries a confirmed overlap only for the original indices and exact date ranges", () => {
const profile: CandidateProfile = {
...blankProfile(),
version: 2,
experience: [
{
employer_name: null,
specialization: "backend",
started_on: "2023-01",
ended_on: "2024-12",
summary: null,
status: "confirmed",
source: {
...suggestion,
origin: "manual",
quote: null,
extraction_version: null,
confirmed_at: "2026-01-01T00:00:00Z",
},
},
{
employer_name: null,
specialization: "frontend",
started_on: "2024-01",
ended_on: "2025-01",
summary: null,
status: "confirmed",
source: {
...suggestion,
origin: "manual",
quote: null,
extraction_version: null,
confirmed_at: "2026-01-01T00:00:00Z",
},
},
],
experience_overlaps: [{ first_index: 0, second_index: 1, status: "confirmed" }],
};
const draft = toCandidateProfileDraft(profile);
expect(
reviewExperienceOverlaps(draft, new Date("2026-06-15T00:00:00Z"))[0]?.requiresAcknowledgement,
).toBe(false);
const changed = updateExperienceDraft(draft, "experience-0", { started_on: "2023-02" });
expect(
reviewExperienceOverlaps(changed, new Date("2026-06-15T00:00:00Z"))[0]
?.requiresAcknowledgement,
).toBe(true);
});
it("maps server validation pointers to the corresponding form fields", () => {
expect(
mapProfileServerErrors([
{ pointer: "/contacts/phone/value" },
{ pointer: "/experience/2/ended_on" },
{ pointer: "/terms/salary_minimum/value/amount" },
{ pointer: "/confirmed_parallel_periods/0/first_period/started_on" },
]),
).toEqual([
{ field: "contacts.phone", message: "Проверьте значение и формат этого поля." },
{ field: "experience.2.ended_on", message: "Проверьте значение и формат этого поля." },
{ field: "terms.salaryMinimum.amount", message: "Проверьте значение и формат этого поля." },
{ field: "experience.overlaps", message: "Проверьте значение и формат этого поля." },
]);
});
});
@@ -0,0 +1,713 @@
import {
CandidateProfileUpdate as CandidateProfileUpdateSchema,
type CandidateProfile,
type CandidateProfileUpdate,
} from "../../../shared/api/schemas";
type ClaimStatus = CandidateProfile["full_name"]["status"];
type DecisionStatus = Exclude<ClaimStatus, "unknown">;
type ClaimSource = NonNullable<CandidateProfile["full_name"]["source"]>;
export type FieldDraft<Value> = {
value: Value;
status: ClaimStatus;
originalStatus: ClaimStatus;
originalValue: Value | null;
source: ClaimSource | null;
};
type ItemMetadata<Value> = {
id: string;
originalIndex: number | null;
status: DecisionStatus;
originalStatus: DecisionStatus | null;
originalValue: Value | null;
source: ClaimSource | null;
};
type StackValue = Pick<CandidateProfile["stack"][number], "tag">;
type RoleValue = Omit<
Pick<CandidateProfile["roles"][number], "specialization" | "self_assessed_grade">,
"specialization"
> & { specialization: CandidateProfile["roles"][number]["specialization"] | "" };
type ExperienceValue = Omit<
Pick<
CandidateProfile["experience"][number],
"employer_name" | "specialization" | "started_on" | "ended_on" | "summary"
>,
"specialization"
> & { specialization: CandidateProfile["experience"][number]["specialization"] | "" };
type SoftSkillValue = Pick<CandidateProfile["soft_skills"][number], "skill">;
type SalaryValue = CandidateProfile["terms"]["salary_minimum"]["value"];
export type StackDraft = StackValue & ItemMetadata<StackValue>;
export type RoleDraft = RoleValue & ItemMetadata<RoleValue>;
export type ExperienceDraft = ExperienceValue & ItemMetadata<ExperienceValue>;
export type SoftSkillDraft = SoftSkillValue & ItemMetadata<SoftSkillValue>;
export type SalaryDraft = {
amount: string;
tax_basis: "net" | "gross" | "";
status: ClaimStatus;
originalStatus: ClaimStatus;
originalValue: SalaryValue;
source: ClaimSource | null;
};
export type CandidateProfileDraft = {
expectedVersion: number;
fullName: FieldDraft<string>;
contacts: {
email: FieldDraft<string>;
phone: FieldDraft<string>;
telegram: FieldDraft<string>;
};
stack: StackDraft[];
roles: RoleDraft[];
experience: ExperienceDraft[];
softSkills: SoftSkillDraft[];
terms: {
location: FieldDraft<string>;
relocation: FieldDraft<boolean | null>;
salaryMinimum: SalaryDraft;
};
confirmedCategories: CandidateProfile["confirmed_categories"];
originalOverlaps: CandidateProfile["experience_overlaps"];
parallelAcknowledgements: Record<string, boolean>;
};
export type ExperienceOverlapReview = {
key: string;
firstIndex: number;
secondIndex: number;
firstPeriod: { started_on: string; ended_on: string | null };
secondPeriod: { started_on: string; ended_on: string | null };
requiresAcknowledgement: boolean;
acknowledged: boolean;
};
export type ProfileFormIssue = { field: string; message: string };
function textFieldDraft(claim: {
status: ClaimStatus;
value: string | null;
source: ClaimSource | null;
}): FieldDraft<string> {
return {
value: claim.value ?? "",
status: claim.status,
originalStatus: claim.status,
originalValue: claim.value,
source: claim.source,
};
}
function valueFieldDraft<Value>(claim: {
status: ClaimStatus;
value: Value | null;
source: ClaimSource | null;
}): FieldDraft<Value | null> {
return {
value: claim.value,
status: claim.status,
originalStatus: claim.status,
originalValue: claim.value,
source: claim.source,
};
}
function itemDraft<Value, Item extends { status: DecisionStatus; source: ClaimSource }>(
id: string,
index: number,
item: Item,
value: Value,
): Value & ItemMetadata<Value> {
return {
...value,
id,
originalIndex: index,
status: item.status,
originalStatus: item.status,
originalValue: value,
source: item.source,
};
}
export function toCandidateProfileDraft(profile: CandidateProfile): CandidateProfileDraft {
const salaryValue = profile.terms.salary_minimum.value;
return {
expectedVersion: profile.version,
fullName: textFieldDraft(profile.full_name),
contacts: {
email: textFieldDraft(profile.contacts.email),
phone: textFieldDraft(profile.contacts.phone),
telegram: textFieldDraft(profile.contacts.telegram),
},
stack: profile.stack.map((item, index) =>
itemDraft(`stack-${index}`, index, item, { tag: item.tag }),
),
roles: profile.roles.map((item, index) =>
itemDraft(`role-${index}`, index, item, {
specialization: item.specialization,
self_assessed_grade: item.self_assessed_grade,
}),
),
experience: profile.experience.map((item, index) =>
itemDraft(`experience-${index}`, index, item, {
employer_name: item.employer_name,
specialization: item.specialization,
started_on: item.started_on,
ended_on: item.ended_on,
summary: item.summary,
}),
),
softSkills: profile.soft_skills.map((item, index) =>
itemDraft(`soft-skill-${index}`, index, item, { skill: item.skill }),
),
terms: {
location: textFieldDraft(profile.terms.location),
relocation: valueFieldDraft(profile.terms.relocation),
salaryMinimum: {
amount: salaryValue ? String(salaryValue.amount) : "",
tax_basis: salaryValue?.tax_basis ?? "",
status: profile.terms.salary_minimum.status,
originalStatus: profile.terms.salary_minimum.status,
originalValue: salaryValue,
source: profile.terms.salary_minimum.source,
},
},
confirmedCategories: profile.confirmed_categories,
originalOverlaps: profile.experience_overlaps,
parallelAcknowledgements: {},
};
}
export function updateFieldDraft<Value>(draft: FieldDraft<Value>, value: Value): FieldDraft<Value> {
const keepSuggestion =
draft.originalStatus === "extracted" && sameValue(value, draft.originalValue);
const remainsUnknown = draft.originalStatus === "unknown" && isEmptyValue(value);
return {
...draft,
value,
status: keepSuggestion ? "extracted" : remainsUnknown ? "unknown" : "confirmed",
};
}
export function updateStackDraft(
draft: CandidateProfileDraft,
id: string,
patch: Partial<StackValue>,
): CandidateProfileDraft {
return updateItem(draft, "stack", id, patch);
}
export function updateRoleDraft(
draft: CandidateProfileDraft,
id: string,
patch: Partial<RoleValue>,
): CandidateProfileDraft {
return updateItem(draft, "roles", id, patch);
}
export function updateExperienceDraft(
draft: CandidateProfileDraft,
id: string,
patch: Partial<ExperienceValue>,
): CandidateProfileDraft {
const dateChanged = "started_on" in patch || "ended_on" in patch;
const updated = updateItem(draft, "experience", id, patch);
return dateChanged ? { ...updated, parallelAcknowledgements: {} } : updated;
}
export function updateSalaryDraft(
draft: CandidateProfileDraft,
patch: Partial<Pick<SalaryDraft, "amount" | "tax_basis">>,
): CandidateProfileDraft {
const next = { ...draft.terms.salaryMinimum, ...patch };
const sameOriginal = Boolean(
next.amount.trim() !== "" &&
next.tax_basis !== "" &&
next.originalValue &&
Number(next.amount) === next.originalValue.amount &&
next.tax_basis === next.originalValue.tax_basis,
);
const isEmpty = next.amount.trim() === "";
return {
...draft,
terms: {
...draft.terms,
salaryMinimum: {
...next,
status:
next.originalStatus === "extracted" && sameOriginal
? "extracted"
: next.originalStatus === "unknown" && isEmpty
? "unknown"
: "confirmed",
},
},
};
}
export function updateSoftSkillDraft(
draft: CandidateProfileDraft,
id: string,
patch: Partial<SoftSkillValue>,
): CandidateProfileDraft {
return updateItem(draft, "softSkills", id, patch);
}
function updateItem<
Key extends "stack" | "roles" | "experience" | "softSkills",
Item extends CandidateProfileDraft[Key][number],
Patch extends Partial<Omit<Item, keyof ItemMetadata<unknown>>>,
>(draft: CandidateProfileDraft, key: Key, id: string, patch: Patch): CandidateProfileDraft {
const items = draft[key] as Item[];
const updatedItems = items.map((item) => {
if (item.id !== id) return item;
const next = { ...item, ...patch };
const unchangedSuggestion =
item.originalStatus === "extracted" &&
item.originalValue !== null &&
sameValue(itemValue(next), item.originalValue);
return {
...next,
status: unchangedSuggestion ? "extracted" : "confirmed",
} as Item;
});
return { ...draft, [key]: updatedItems } as CandidateProfileDraft;
}
function itemValue(item: object): object {
const value: Record<string, unknown> = {};
for (const [key, itemValue] of Object.entries(item)) {
if (
key !== "id" &&
key !== "originalIndex" &&
key !== "status" &&
key !== "originalStatus" &&
key !== "originalValue" &&
key !== "source"
) {
value[key] = itemValue;
}
}
return value;
}
function sameValue(left: unknown, right: unknown): boolean {
return JSON.stringify(left) === JSON.stringify(right);
}
function isEmptyValue(value: unknown): boolean {
return value === "" || value === null;
}
function monthNumber(value: string): number | null {
if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(value)) return null;
const year = Number(value.slice(0, 4));
const month = Number(value.slice(5, 7));
return year * 12 + month - 1;
}
function rangesOverlap(
first: ExperienceDraft,
second: ExperienceDraft,
currentMonth: number,
): boolean {
const firstStart = monthNumber(first.started_on);
const secondStart = monthNumber(second.started_on);
const firstEnd = first.ended_on === null ? currentMonth : monthNumber(first.ended_on);
const secondEnd = second.ended_on === null ? currentMonth : monthNumber(second.ended_on);
if (firstStart === null || secondStart === null || firstEnd === null || secondEnd === null) {
return false;
}
if (firstStart > firstEnd || secondStart > secondEnd) return false;
return firstStart <= secondEnd && secondStart <= firstEnd;
}
function samePeriod(current: ExperienceDraft, original: ExperienceValue | null): boolean {
return Boolean(
original &&
current.started_on === original.started_on &&
current.ended_on === original.ended_on,
);
}
export function reviewExperienceOverlaps(
draft: CandidateProfileDraft,
now = new Date(),
): ExperienceOverlapReview[] {
const currentMonth = now.getUTCFullYear() * 12 + now.getUTCMonth();
const overlaps: ExperienceOverlapReview[] = [];
for (let firstIndex = 0; firstIndex < draft.experience.length; firstIndex += 1) {
const first = draft.experience[firstIndex];
if (!first) continue;
for (
let secondIndex = firstIndex + 1;
secondIndex < draft.experience.length;
secondIndex += 1
) {
const second = draft.experience[secondIndex];
if (!second || !rangesOverlap(first, second, currentMonth)) continue;
const key = `${firstIndex}:${secondIndex}`;
const prior = draft.originalOverlaps.find(
(overlap) => overlap.first_index === firstIndex && overlap.second_index === secondIndex,
);
const unchangedConfirmed = Boolean(
prior?.status === "confirmed" &&
first.originalIndex === firstIndex &&
second.originalIndex === secondIndex &&
samePeriod(first, first.originalValue) &&
samePeriod(second, second.originalValue),
);
overlaps.push({
key,
firstIndex,
secondIndex,
firstPeriod: { started_on: first.started_on, ended_on: first.ended_on },
secondPeriod: { started_on: second.started_on, ended_on: second.ended_on },
requiresAcknowledgement: !unchangedConfirmed,
acknowledged: draft.parallelAcknowledgements[key] === true,
});
}
}
return overlaps;
}
export function setParallelAcknowledgement(
draft: CandidateProfileDraft,
key: string,
acknowledged: boolean,
): CandidateProfileDraft {
return {
...draft,
parallelAcknowledgements: { ...draft.parallelAcknowledgements, [key]: acknowledged },
};
}
export function addExperience(draft: CandidateProfileDraft, id: string): CandidateProfileDraft {
return {
...draft,
experience: [
...draft.experience,
{
id,
originalIndex: null,
employer_name: null,
specialization: "",
started_on: "",
ended_on: null,
summary: null,
status: "confirmed",
originalStatus: null,
originalValue: null,
source: null,
},
],
parallelAcknowledgements: {},
};
}
export function removeExperience(draft: CandidateProfileDraft, id: string): CandidateProfileDraft {
return {
...draft,
experience: draft.experience.filter((item) => item.id !== id),
parallelAcknowledgements: {},
};
}
export function moveExperience(
draft: CandidateProfileDraft,
index: number,
direction: -1 | 1,
): CandidateProfileDraft {
const targetIndex = index + direction;
if (targetIndex < 0 || targetIndex >= draft.experience.length) return draft;
const experience = [...draft.experience];
[experience[index], experience[targetIndex]] = [experience[targetIndex]!, experience[index]!];
return { ...draft, experience, parallelAcknowledgements: {} };
}
export function addStack(draft: CandidateProfileDraft, id: string): CandidateProfileDraft {
return {
...draft,
stack: [
...draft.stack,
{
id,
originalIndex: null,
tag: "",
status: "confirmed",
originalStatus: null,
originalValue: null,
source: null,
},
],
};
}
export function addRole(draft: CandidateProfileDraft, id: string): CandidateProfileDraft {
return {
...draft,
roles: [
...draft.roles,
{
id,
originalIndex: null,
specialization: "",
self_assessed_grade: null,
status: "confirmed",
originalStatus: null,
originalValue: null,
source: null,
},
],
};
}
export function addSoftSkill(draft: CandidateProfileDraft, id: string): CandidateProfileDraft {
return {
...draft,
softSkills: [
...draft.softSkills,
{
id,
originalIndex: null,
skill: "",
status: "confirmed",
originalStatus: null,
originalValue: null,
source: null,
},
],
};
}
export function removeItem<Key extends "stack" | "roles" | "softSkills">(
draft: CandidateProfileDraft,
key: Key,
id: string,
): CandidateProfileDraft {
return { ...draft, [key]: draft[key].filter((item) => item.id !== id) } as CandidateProfileDraft;
}
function fieldDecision<Value>(
draft: FieldDraft<Value>,
value = draft.value,
): { value: Exclude<Value, null | "">; status: DecisionStatus } | null {
if (isEmptyValue(value)) return null;
const extracted = draft.status === "extracted" && sameValue(value, draft.originalValue);
return {
value: value as Exclude<Value, null | "">,
status: extracted ? "extracted" : "confirmed",
};
}
function itemDecision<Value>(
item: Value & ItemMetadata<Value>,
): Value & { status: DecisionStatus } {
const extracted =
item.status === "extracted" &&
item.originalValue !== null &&
sameValue(itemValue(item), item.originalValue);
return { ...itemValue(item), status: extracted ? "extracted" : "confirmed" } as Value & {
status: DecisionStatus;
};
}
function escapePointerSegment(value: string | number): string {
return String(value).replaceAll("~", "~0").replaceAll("/", "~1");
}
function fieldForPointer(pointer: string): string {
const parts = pointer
.split("/")
.slice(1)
.map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
const [root, index, property, detail] = parts;
if (root === "full_name") return "fullName";
if (root === "contacts" && index) return `contacts.${index}`;
if (root === "stack" && index !== undefined) return `stack.${index}.${property ?? "tag"}`;
if (root === "roles" && index !== undefined)
return `roles.${index}.${property ?? "specialization"}`;
if (root === "experience" && index !== undefined)
return `experience.${index}.${property ?? "started_on"}`;
if (root === "soft_skills" && index !== undefined) return `softSkills.${index}.skill`;
if (root === "terms" && index) {
if (index === "salary_minimum") {
return property === "value"
? `terms.salaryMinimum.${detail ?? "amount"}`
: "terms.salaryMinimum";
}
return `terms.${index}`;
}
if (root === "confirmed_parallel_periods") return "experience.overlaps";
if (root === "expected_version" || !root) return "form";
return "form";
}
function zodPointer(path: readonly PropertyKey[]): string {
return `/${path.map((part) => escapePointerSegment(String(part))).join("/")}`;
}
function monthIsFuture(value: string, now: Date): boolean {
const month = monthNumber(value);
if (month === null) return false;
const current = now.getUTCFullYear() * 12 + now.getUTCMonth();
return month > current;
}
function customValidationIssues(draft: CandidateProfileDraft, now: Date): ProfileFormIssue[] {
const issues: ProfileFormIssue[] = [];
const duplicates = <Value>(
items: Value[],
valueOf: (value: Value) => string,
fieldOfIndex: (index: number) => string,
) => {
const seen = new Set<string>();
items.forEach((item, index) => {
const value = valueOf(item).trim().toLocaleLowerCase("ru");
if (!value) return;
if (seen.has(value)) {
issues.push({ field: fieldOfIndex(index), message: "Повторяющееся значение." });
}
seen.add(value);
});
};
duplicates(
draft.stack,
(item) => item.tag,
(index) => `stack.${index}.tag`,
);
duplicates(
draft.roles,
(item) => item.specialization,
(index) => `roles.${index}.specialization`,
);
duplicates(
draft.softSkills,
(item) => item.skill,
(index) => `softSkills.${index}.skill`,
);
draft.experience.forEach((item, index) => {
const start = monthNumber(item.started_on);
const end = item.ended_on === null ? null : monthNumber(item.ended_on);
if (start !== null && monthIsFuture(item.started_on, now)) {
issues.push({
field: `experience.${index}.started_on`,
message: "Месяц не может быть в будущем.",
});
}
if (item.ended_on !== null && end !== null && monthIsFuture(item.ended_on, now)) {
issues.push({
field: `experience.${index}.ended_on`,
message: "Месяц не может быть в будущем.",
});
}
if (start !== null && end !== null && end < start) {
issues.push({
field: `experience.${index}.ended_on`,
message: "Месяц окончания должен быть не раньше начала.",
});
}
});
if (draft.terms.salaryMinimum.amount.trim() && !draft.terms.salaryMinimum.tax_basis) {
issues.push({
field: "terms.salaryMinimum.tax_basis",
message: "Выберите, указана сумма до или после налога.",
});
}
for (const overlap of reviewExperienceOverlaps(draft, now)) {
if (overlap.requiresAcknowledgement && !overlap.acknowledged) {
issues.push({
field: "experience.overlaps",
message: `Подтвердите отдельно, что периоды ${overlap.firstIndex + 1} и ${overlap.secondIndex + 1} действительно шли параллельно.`,
});
}
}
return issues;
}
export function profilePointerField(pointer: string): string {
return fieldForPointer(pointer);
}
export function buildCandidateProfileUpdate(
draft: CandidateProfileDraft,
now = new Date(),
): { data: CandidateProfileUpdate | null; issues: ProfileFormIssue[] } {
const salaryAmount = draft.terms.salaryMinimum.amount.trim();
const salaryValue: SalaryValue =
salaryAmount && draft.terms.salaryMinimum.tax_basis
? {
amount: Number(salaryAmount),
currency: "RUB",
period: "month",
tax_basis: draft.terms.salaryMinimum.tax_basis,
}
: null;
const data: unknown = {
expected_version: draft.expectedVersion,
full_name: fieldDecision(draft.fullName, draft.fullName.value.trim()),
contacts: {
email: fieldDecision(draft.contacts.email, draft.contacts.email.value.trim()),
phone: fieldDecision(draft.contacts.phone, draft.contacts.phone.value.trim()),
telegram: fieldDecision(draft.contacts.telegram, draft.contacts.telegram.value.trim()),
},
stack: draft.stack.filter((item) => item.tag.trim()).map(itemDecision),
roles: draft.roles.map(itemDecision),
experience: draft.experience.map((item) =>
itemDecision({
...item,
employer_name: item.employer_name?.trim() || null,
summary: item.summary?.trim() || null,
}),
),
confirmed_parallel_periods: reviewExperienceOverlaps(draft, now)
.filter((overlap) => overlap.requiresAcknowledgement && overlap.acknowledged)
.map((overlap) => ({
first_index: overlap.firstIndex,
second_index: overlap.secondIndex,
first_period: overlap.firstPeriod,
second_period: overlap.secondPeriod,
})),
soft_skills: draft.softSkills.filter((item) => item.skill.trim()).map(itemDecision),
terms: {
location: fieldDecision(draft.terms.location, draft.terms.location.value.trim()),
relocation: fieldDecision(draft.terms.relocation),
salary_minimum: salaryValue
? {
value: salaryValue,
status:
draft.terms.salaryMinimum.status === "extracted" &&
sameValue(salaryValue, draft.terms.salaryMinimum.originalValue)
? "extracted"
: "confirmed",
}
: null,
},
};
const issues = customValidationIssues(draft, now);
const parsed = CandidateProfileUpdateSchema.safeParse(data);
if (!parsed.success) {
issues.push(
...parsed.error.issues.map((issue) => ({
field: fieldForPointer(zodPointer(issue.path)),
message: "Проверьте значение и формат этого поля.",
})),
);
}
return {
data: issues.length === 0 && parsed.success ? (parsed.data as CandidateProfileUpdate) : null,
issues,
};
}
export function mapProfileServerErrors(errors: readonly { pointer: string }[]): ProfileFormIssue[] {
return errors.map((error) => ({
field: fieldForPointer(error.pointer),
message: "Проверьте значение и формат этого поля.",
}));
}
+16
View File
@@ -0,0 +1,16 @@
export {
buildCompanyCreateBody,
buildCompanyUpdateBody,
draftFromOrganization,
emptyCompanyDraft,
rebaseCompanyDraft,
type CompanyDraft,
type CompanyRepresentativeDraft,
} from "./model/company-form";
export {
organizationBasisLabels,
organizationLevelLabels,
organizationTrustLevel,
candidateCardLevelLabels,
} from "./model/verification-labels";
export { CandidateCardPreview } from "./ui/candidate-card-preview";
@@ -0,0 +1,103 @@
import { describe, expect, it } from "vitest";
import {
buildCompanyCreateBody,
buildCompanyUpdateBody,
draftFromOrganization,
emptyCompanyDraft,
rebaseCompanyDraft,
} from "./company-form";
import type { Organization } from "../../../shared/api/schemas";
const organization: Organization = {
id: "9869e1e3-02b2-460e-9b36-ef82e970bb77",
version: 4,
name: "North Star",
description: "Hiring tools",
sphere: "Software",
contacts: {
website: "https://north.example",
email: "jobs@north.example",
phone: null,
telegram: null,
},
representatives: [{ name: "Ada Lovelace", job_title: "Founder" }],
verification: {
level: "e0",
basis: "confirmed_email",
changed_at: "2026-10-01T10:00:00Z",
},
candidate_card: {
id: "9869e1e3-02b2-460e-9b36-ef82e970bb77",
name: "North Star",
description: "Hiring tools",
sphere: "Software",
contacts: {
website: "https://north.example",
email: "jobs@north.example",
phone: null,
telegram: null,
},
representatives: [{ name: "Ada Lovelace", job_title: "Founder" }],
verification_level: "e0",
},
created_at: "2026-10-01T10:00:00Z",
updated_at: "2026-10-01T10:00:00Z",
};
describe("company form mapping", () => {
it("keeps an empty create body limited to the required name", () => {
expect(buildCompanyCreateBody({ ...emptyCompanyDraft(), name: "North Star" })).toEqual({
name: "North Star",
});
});
it("sends contacts as a complete replacement when any contact changes", () => {
const draft = draftFromOrganization(organization);
draft.email = "people@north.example";
draft.website = "";
expect(buildCompanyUpdateBody(draft, organization)).toEqual({
expected_version: 4,
contacts: {
website: null,
email: "people@north.example",
phone: null,
telegram: null,
},
});
});
it("uses null to clear optional text and replaces representatives as a whole", () => {
const draft = draftFromOrganization(organization);
draft.description = "";
draft.representatives = [];
expect(buildCompanyUpdateBody(draft, organization)).toEqual({
expected_version: 4,
description: null,
representatives: [],
});
});
it("rebases untouched fields while preserving the user draft after a version conflict", () => {
const draft = draftFromOrganization(organization);
draft.name = "North Star Labs";
const latest: Organization = {
...organization,
version: 5,
sphere: "Financial software",
candidate_card: { ...organization.candidate_card, sphere: "Financial software" },
};
expect(rebaseCompanyDraft(draft, organization, latest)).toEqual({
...draft,
sphere: "Financial software",
});
expect(buildCompanyUpdateBody(rebaseCompanyDraft(draft, organization, latest), latest)).toEqual(
{
expected_version: 5,
name: "North Star Labs",
},
);
});
});
@@ -0,0 +1,157 @@
import type {
Organization,
OrganizationCreate,
OrganizationUpdate,
} from "../../../shared/api/schemas";
export type CompanyRepresentativeDraft = {
name: string;
job_title: string;
};
export type CompanyDraft = {
name: string;
description: string;
sphere: string;
website: string;
email: string;
phone: string;
telegram: string;
representatives: CompanyRepresentativeDraft[];
};
const emptyDraft: CompanyDraft = {
name: "",
description: "",
sphere: "",
website: "",
email: "",
phone: "",
telegram: "",
representatives: [],
};
export function draftFromOrganization(organization: Organization): CompanyDraft {
return {
name: organization.name,
description: organization.description ?? "",
sphere: organization.sphere ?? "",
website: organization.contacts.website ?? "",
email: organization.contacts.email ?? "",
phone: organization.contacts.phone ?? "",
telegram: organization.contacts.telegram ?? "",
representatives: organization.representatives.map((representative) => ({ ...representative })),
};
}
function contactValues(draft: CompanyDraft) {
return {
website: draft.website === "" ? null : draft.website,
email: draft.email === "" ? null : draft.email,
phone: draft.phone === "" ? null : draft.phone,
telegram: draft.telegram === "" ? null : draft.telegram,
};
}
function hasPublicContacts(draft: CompanyDraft): boolean {
return [draft.website, draft.email, draft.phone, draft.telegram].some((value) => value !== "");
}
function sameRepresentatives(
left: readonly CompanyRepresentativeDraft[],
right: readonly CompanyRepresentativeDraft[],
): boolean {
return (
left.length === right.length &&
left.every(
(representative, index) =>
representative.name === right[index]?.name &&
representative.job_title === right[index]?.job_title,
)
);
}
function contactsChanged(draft: CompanyDraft, organization: Organization): boolean {
const values = contactValues(draft);
return (
values.website !== organization.contacts.website ||
values.email !== organization.contacts.email ||
values.phone !== organization.contacts.phone ||
values.telegram !== organization.contacts.telegram
);
}
export function buildCompanyCreateBody(draft: CompanyDraft): OrganizationCreate {
const body: OrganizationCreate = { name: draft.name };
if (draft.description !== "") body.description = draft.description;
if (draft.sphere !== "") body.sphere = draft.sphere;
if (hasPublicContacts(draft)) body.contacts = contactValues(draft);
if (draft.representatives.length > 0) {
body.representatives = draft.representatives.map((representative) => ({ ...representative }));
}
return body;
}
export function buildCompanyUpdateBody(
draft: CompanyDraft,
organization: Organization,
): OrganizationUpdate {
const body: OrganizationUpdate = { expected_version: organization.version };
if (draft.name !== organization.name) body.name = draft.name;
if ((draft.description || null) !== organization.description) {
body.description = draft.description === "" ? null : draft.description;
}
if ((draft.sphere || null) !== organization.sphere) {
body.sphere = draft.sphere === "" ? null : draft.sphere;
}
if (contactsChanged(draft, organization)) body.contacts = contactValues(draft);
if (!sameRepresentatives(draft.representatives, organization.representatives)) {
body.representatives = draft.representatives.map((representative) => ({ ...representative }));
}
return body;
}
export function rebaseCompanyDraft(
previousDraft: CompanyDraft,
previousOrganization: Organization,
latestOrganization: Organization,
): CompanyDraft {
const latestDraft = draftFromOrganization(latestOrganization);
const previousBaseline = draftFromOrganization(previousOrganization);
return {
...latestDraft,
name: previousDraft.name !== previousBaseline.name ? previousDraft.name : latestDraft.name,
description:
previousDraft.description !== previousBaseline.description
? previousDraft.description
: latestDraft.description,
sphere:
previousDraft.sphere !== previousBaseline.sphere ? previousDraft.sphere : latestDraft.sphere,
...(contactsChanged(previousDraft, previousOrganization)
? {
website: previousDraft.website,
email: previousDraft.email,
phone: previousDraft.phone,
telegram: previousDraft.telegram,
}
: {}),
representatives: sameRepresentatives(
previousDraft.representatives,
previousBaseline.representatives,
)
? latestDraft.representatives
: previousDraft.representatives.map((representative) => ({ ...representative })),
};
}
export function emptyCompanyDraft(): CompanyDraft {
return {
...emptyDraft,
representatives: [],
};
}
@@ -0,0 +1,39 @@
import type { Organization } from "../../../shared/api/schemas";
import type { TrustLevelValue } from "../../../shared/ui";
export const organizationLevelLabels: Readonly<
Record<Organization["verification"]["level"], string>
> = {
e0: "E0 - подтверждена почта владельца",
e1: "E1 - подтверждены домен и связь с компанией",
e2: "E2 - проверены реквизиты и полномочия",
e3: "E3 - дополнительная проверка платформы",
};
export const candidateCardLevelLabels: Readonly<
Record<Organization["candidate_card"]["verification_level"], string>
> = {
e0: "Уровень E0",
e1: "Уровень E1",
e2: "Уровень E2",
e3: "Уровень E3",
};
export const organizationBasisLabels: Readonly<
Record<Organization["verification"]["basis"], string>
> = {
confirmed_email: "Подтвержденная почта владельца",
corporate_domain: "Корпоративный домен и связь с компанией",
requisites_and_authority: "Проверка реквизитов и полномочий",
manual_review: "Ручная проверка платформы",
partner_status: "Статус партнера",
};
export const organizationTrustLevel: Readonly<
Record<Organization["verification"]["level"], TrustLevelValue>
> = {
e0: "claimed",
e1: "partial",
e2: "confirmed",
e3: "confirmed",
};
@@ -0,0 +1,95 @@
.card {
display: grid;
gap: var(--space-4);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.header {
display: flex;
flex-wrap: wrap;
gap: var(--space-3) var(--space-5);
align-items: flex-start;
justify-content: space-between;
}
.name {
overflow-wrap: anywhere;
font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
}
.level,
.sphere,
.description {
overflow-wrap: anywhere;
}
.sphere {
max-width: 24rem;
color: var(--color-text-secondary);
}
.description {
white-space: pre-wrap;
}
.contacts {
display: grid;
gap: var(--space-2);
min-width: 0;
}
.contact {
display: grid;
grid-template-columns: minmax(8rem, max-content) minmax(0, 1fr);
gap: var(--space-2) var(--space-4);
}
.contact dt {
color: var(--color-text-secondary);
}
.contact dd {
min-width: 0;
overflow-wrap: anywhere;
}
.representatives {
display: grid;
gap: var(--space-2);
}
.representatives h4 {
font-weight: var(--font-weight-bold);
}
.representatives ul {
display: grid;
gap: var(--space-2);
padding: 0;
list-style: none;
}
.representatives li {
display: grid;
gap: var(--space-1);
}
.representatives li span + span {
color: var(--color-text-secondary);
}
@media (width < 30rem) {
.card {
padding: var(--space-3);
}
.contact {
grid-template-columns: minmax(0, 1fr);
gap: var(--space-1);
}
}
@@ -0,0 +1,34 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { CandidateCardPreview } from "./candidate-card-preview";
import type { Organization } from "../../../shared/api/schemas";
const card: Organization["candidate_card"] = {
id: "9869e1e3-02b2-460e-9b36-ef82e970bb77",
name: "North Star",
description: "Candidate-facing profile",
sphere: "Software",
contacts: {
website: "https://north.example",
email: "careers@north.example",
phone: null,
telegram: null,
},
representatives: [{ name: "Ada Lovelace", job_title: "Founder" }],
verification_level: "e0",
};
describe("candidate card preview", () => {
it("renders the card fields and omits membership, account, and verification basis", () => {
const markup = renderToStaticMarkup(<CandidateCardPreview card={card} />);
const preview = /<article[^>]*>(.*?)<\/article>/.exec(markup)?.[1];
expect(preview).toContain("North Star");
expect(preview).toContain("Candidate-facing profile");
expect(preview).toContain("Software");
expect(preview).toContain("careers@north.example");
expect(preview).toContain("Ada Lovelace");
expect(preview).toContain("Уровень E0");
expect(preview).not.toMatch(/membership|role|account|version|basis|владелец/i);
});
});
@@ -0,0 +1,70 @@
import type { Organization } from "../../../shared/api/schemas";
import { Section, TrustLevel } from "../../../shared/ui";
import { candidateCardLevelLabels, organizationTrustLevel } from "../model/verification-labels";
import styles from "./candidate-card-preview.module.css";
type CandidateCard = Organization["candidate_card"];
type CandidateCardPreviewProps = {
card: CandidateCard;
};
const contactLabels = {
website: "Сайт",
email: "Почта для связи",
phone: "Телефон компании",
telegram: "Telegram компании",
} as const;
export function CandidateCardPreview({ card }: CandidateCardPreviewProps) {
const contacts = (Object.keys(contactLabels) as (keyof typeof contactLabels)[]).flatMap((key) => {
const value = card.contacts[key];
return value ? [{ label: contactLabels[key], value }] : [];
});
return (
<Section
title="Так карточку увидит кандидат"
description="Проверьте описание и контакты, которые увидит кандидат."
>
<article className={styles.card} aria-label="Предпросмотр карточки компании">
<header className={styles.header}>
<div>
<h3 className={styles.name}>{card.name}</h3>
<p className={styles.level}>
<TrustLevel
level={organizationTrustLevel[card.verification_level]}
label={candidateCardLevelLabels[card.verification_level]}
/>
</p>
</div>
{card.sphere ? <p className={styles.sphere}>{card.sphere}</p> : null}
</header>
{card.description ? <p className={styles.description}>{card.description}</p> : null}
{contacts.length > 0 ? (
<dl className={styles.contacts}>
{contacts.map(({ label, value }) => (
<div className={styles.contact} key={label}>
<dt>{label}</dt>
<dd>{value}</dd>
</div>
))}
</dl>
) : null}
{card.representatives && card.representatives.length > 0 ? (
<div className={styles.representatives}>
<h4>Представители компании</h4>
<ul>
{card.representatives.map((representative, index) => (
<li key={`${representative.name}-${index}`}>
<span>{representative.name}</span>
<span>{representative.job_title}</span>
</li>
))}
</ul>
</div>
) : null}
</article>
</Section>
);
}
@@ -14,7 +14,7 @@ describe("getOnboardingDestination", () => {
it.each([
["candidate", "candidate_consents", paths.candidate.onboarding],
["candidate", "candidate_profile", paths.candidate.profile],
["candidate", "candidate_questionnaire", paths.candidate.onboarding],
["candidate", "candidate_questionnaire", paths.candidate.questionnaire],
["candidate", "candidate_assessment", paths.candidate.assessment],
["candidate", "completed", paths.candidate.root],
["employer", "employer_company", paths.employer.company],
@@ -11,8 +11,9 @@ export function getOnboardingDestination(
switch (account.onboarding_step) {
case "candidate_consents":
case "candidate_questionnaire":
return paths.candidate.onboarding;
case "candidate_questionnaire":
return paths.candidate.questionnaire;
case "candidate_profile":
return paths.candidate.profile;
case "candidate_assessment":
@@ -0,0 +1,6 @@
export {
findGradeTitle,
findSpecializationOption,
listSpecializationOptions,
type CatalogSpecializationOption,
} from "./model/catalog";
@@ -0,0 +1,71 @@
import { describe, expect, it } from "vitest";
import type { SpecializationCatalog } from "../../../shared/api/schemas";
import { findGradeTitle, findSpecializationOption, listSpecializationOptions } from "./catalog";
const catalog: SpecializationCatalog = {
directions: [
{
code: "development",
title: "Разработка",
specializations: [
{
code: "backend",
title: "Backend",
test_availability: {
status: "available",
grades: ["junior"],
task_languages: ["go"],
note: null,
},
},
],
},
{
code: "data",
title: "Данные",
specializations: [
{
code: "ds_ml",
title: "DS/ML",
test_availability: {
status: "in_development",
grades: [],
task_languages: [],
note: "Банк заданий готовится.",
},
},
],
},
],
grades: [
{ code: "intern", title: "Стажер" },
{ code: "junior", title: "Junior" },
{ code: "middle", title: "Middle" },
{ code: "senior", title: "Senior" },
],
};
describe("specialization catalog helpers", () => {
it("keeps the server's direction and specialization order", () => {
expect(
listSpecializationOptions(catalog).map((option) => [option.directionTitle, option.code]),
).toEqual([
["Разработка", "backend"],
["Данные", "ds_ml"],
]);
});
it("returns current availability without inferring it from a code", () => {
expect(findSpecializationOption(catalog, "ds_ml")?.test_availability).toEqual({
status: "in_development",
grades: [],
task_languages: [],
note: "Банк заданий готовится.",
});
expect(findSpecializationOption(catalog, "")).toBeNull();
});
it("uses grade titles from the public catalog", () => {
expect(findGradeTitle(catalog, "junior")).toBe("Junior");
});
});
@@ -0,0 +1,35 @@
import type {
CatalogGrade,
CatalogSpecialization,
SpecializationCatalog,
SpecializationCode,
} from "../../../shared/api/schemas";
export type CatalogSpecializationOption = CatalogSpecialization & {
directionCode: SpecializationCatalog["directions"][number]["code"];
directionTitle: string;
};
export function listSpecializationOptions(
catalog: SpecializationCatalog,
): CatalogSpecializationOption[] {
return catalog.directions.flatMap((direction) =>
direction.specializations.map((specialization) => ({
...specialization,
directionCode: direction.code,
directionTitle: direction.title,
})),
);
}
export function findSpecializationOption(
catalog: SpecializationCatalog,
code: SpecializationCode | "",
): CatalogSpecializationOption | null {
if (!code) return null;
return listSpecializationOptions(catalog).find((option) => option.code === code) ?? null;
}
export function findGradeTitle(catalog: SpecializationCatalog, code: CatalogGrade["code"]): string {
return catalog.grades.find((grade) => grade.code === code)?.title ?? code;
}
@@ -0,0 +1 @@
export { CompanyEditor } from "./ui/company-editor";
@@ -0,0 +1,110 @@
.form {
display: grid;
gap: var(--space-4);
min-width: 0;
}
.title {
font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
}
.field,
.group {
display: grid;
gap: var(--space-2);
min-width: 0;
}
.field label,
.group legend {
font-weight: var(--font-weight-bold);
}
.field input,
.field textarea {
width: 100%;
min-width: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
font: inherit;
line-height: var(--line-height-body);
}
.field textarea {
resize: vertical;
}
.field input:focus-visible,
.field textarea:focus-visible {
outline: var(--line-strong) solid var(--color-accent);
outline-offset: 2px;
}
.field input[aria-invalid="true"],
.field textarea[aria-invalid="true"] {
border-color: var(--color-danger);
}
.group {
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
}
.hint {
color: var(--color-text-secondary);
}
.representative {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto;
gap: var(--space-3);
align-items: end;
padding-block: var(--space-3);
border-bottom: var(--line-thin) solid var(--color-divider);
}
.field-error,
.action-error {
color: var(--color-danger);
}
.action-error,
.notice,
.conflict {
padding: var(--space-3);
border-left: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
}
.conflict {
display: grid;
gap: var(--space-2);
}
.conflict h3 {
font-weight: var(--font-weight-bold);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
align-items: center;
}
@media (width < 42rem) {
.representative {
grid-template-columns: minmax(0, 1fr);
}
}
@media (width < 30rem) {
.group {
padding: var(--space-3);
}
}
@@ -0,0 +1,528 @@
import { useId, useMemo, useState, type FormEvent } from "react";
import { useQueryClient } from "@tanstack/react-query";
import {
getOrganization,
useCreateOrganization,
useUpdateOrganization,
} from "../../../shared/api/endpoints/organization/organization";
import {
getGetCurrentSessionQueryKey,
useGetCurrentSession,
} from "../../../shared/api/endpoints/identity/identity";
import { ApiRequestError } from "../../../shared/api";
import type { Organization, OrganizationCreate, Session } from "../../../shared/api/schemas";
import { Button, SavingStatus } from "../../../shared/ui";
import {
buildCompanyCreateBody,
buildCompanyUpdateBody,
draftFromOrganization,
emptyCompanyDraft,
rebaseCompanyDraft,
type CompanyDraft,
} from "../../../entities/company";
import styles from "./company-editor.module.css";
type CompanyEditorProps = {
organization?: Organization | undefined;
onSaved: (organization: Organization) => void | Promise<void>;
onAccessLost: (error: ApiRequestError) => void;
};
type CreateAttempt = {
body: OrganizationCreate;
key: string;
};
type FieldErrors = Partial<Record<string, string>>;
function fieldNameForPointer(pointer: string): string | undefined {
const fields: Readonly<Record<string, string>> = {
"/name": "name",
"/description": "description",
"/sphere": "sphere",
"/contacts/website": "website",
"/contacts/email": "email",
"/contacts/phone": "phone",
"/contacts/telegram": "telegram",
};
const direct = fields[pointer];
if (direct) return direct;
if (pointer.startsWith("/representatives/")) return "representatives";
return undefined;
}
function fieldErrorsFor(error: unknown): FieldErrors {
if (!(error instanceof ApiRequestError)) return {};
return Object.fromEntries(
error.fieldErrors.flatMap((field) => {
const name = fieldNameForPointer(field.pointer);
return name ? [[name, "Проверьте это поле и сохраните изменения снова."]] : [];
}),
);
}
function hasDraftChanges(draft: CompanyDraft, baseline: Organization): boolean {
return Object.keys(buildCompanyUpdateBody(draft, baseline)).some(
(key) => key !== "expected_version",
);
}
function accessLost(error: unknown): error is ApiRequestError {
return (
error instanceof ApiRequestError &&
(error.status === 401 ||
(error.status === 403 && error.code !== "csrf_check_failed") ||
error.status === 404)
);
}
function csrfCheckFailed(error: unknown): error is ApiRequestError {
return (
error instanceof ApiRequestError && error.status === 403 && error.code === "csrf_check_failed"
);
}
export function CompanyEditor({ organization, onSaved, onAccessLost }: CompanyEditorProps) {
const id = useId();
const queryClient = useQueryClient();
const session = useGetCurrentSession({ query: { retry: false } });
const sessionReady = Boolean(session.data) && !session.isFetching && !session.isError;
const requestHeaders = session.data ? { "X-CSRF-Token": session.data.csrf_token } : {};
const createOrganization = useCreateOrganization({
request: { headers: requestHeaders },
mutation: { gcTime: 0 },
});
const updateOrganization = useUpdateOrganization({
request: { headers: requestHeaders },
mutation: { gcTime: 0 },
});
const [baseline, setBaseline] = useState<Organization | null>(organization ?? null);
const [draft, setDraft] = useState<CompanyDraft>(() =>
organization ? draftFromOrganization(organization) : emptyCompanyDraft(),
);
const [attempt, setAttempt] = useState<CreateAttempt | null>(null);
const [createRetryRequired, setCreateRetryRequired] = useState(false);
const [actionError, setActionError] = useState<unknown>(null);
const [csrfRetryMessage, setCsrfRetryMessage] = useState<string | null>(null);
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
const [conflict, setConflict] = useState(false);
const [reviewRequired, setReviewRequired] = useState(false);
const [status, setStatus] = useState<"idle" | "saving" | "saved" | "failed">("idle");
const creating = organization === undefined;
const isSaving = createOrganization.isPending || updateOrganization.isPending;
const createRequestIsFrozen = creating && attempt !== null && createRetryRequired;
const formLocked = !sessionReady || isSaving || status === "saving" || createRequestIsFrozen;
const hasChanges = useMemo(
() => (baseline ? hasDraftChanges(draft, baseline) : draft.name.trim() !== ""),
[baseline, draft],
);
function updateDraft<K extends keyof CompanyDraft>(key: K, value: CompanyDraft[K]): void {
setDraft((current) => ({ ...current, [key]: value }));
setFieldErrors((current) => ({ ...current, [key]: undefined }));
setActionError(null);
setCsrfRetryMessage(null);
setStatus("idle");
}
function updateRepresentative(index: number, key: "name" | "job_title", value: string): void {
setDraft((current) => ({
...current,
representatives: current.representatives.map((representative, itemIndex) =>
itemIndex === index ? { ...representative, [key]: value } : representative,
),
}));
setFieldErrors((current) => ({ ...current, representatives: undefined }));
setActionError(null);
setCsrfRetryMessage(null);
setStatus("idle");
}
function isSubmittingSessionCurrent(expected: Session): boolean {
const current = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
const state = queryClient.getQueryState(getGetCurrentSessionQueryKey());
return Boolean(
current &&
state?.status === "success" &&
current.account.id === expected.account.id &&
current.csrf_token === expected.csrf_token,
);
}
function isSubmittingAccountCurrent(expected: Session): boolean {
const current = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
return current?.account.id === expected.account.id;
}
async function refreshAfterCsrfFailure(expected: Session): Promise<void> {
if (!isSubmittingAccountCurrent(expected)) return;
setActionError(null);
setCsrfRetryMessage("Проверяем текущий вход...");
setStatus("failed");
const refreshed = await session.refetch();
if (refreshed.data?.account.id !== expected.account.id) return;
setCsrfRetryMessage(
refreshed.isError
? "Не удалось проверить вход. Данные формы сохранены; повторите проверку и отправьте их снова."
: "Проверка входа обновлена. Данные формы сохранены, повторите сохранение.",
);
}
async function saveCreate(): Promise<void> {
const submittingSession = session.data;
if (!sessionReady || !submittingSession || !isSubmittingSessionCurrent(submittingSession))
return;
let request = attempt;
if (!request) {
request = { body: buildCompanyCreateBody(draft), key: crypto.randomUUID() };
setAttempt(request);
}
setCreateRetryRequired(true);
setActionError(null);
setCsrfRetryMessage(null);
setFieldErrors({});
setStatus("saving");
let saved: Organization;
try {
saved = await createOrganization.mutateAsync({
data: request.body,
headers: { "Idempotency-Key": request.key },
});
} catch (error: unknown) {
if (csrfCheckFailed(error)) {
await refreshAfterCsrfFailure(submittingSession);
return;
}
if (!isSubmittingSessionCurrent(submittingSession)) return;
if (accessLost(error)) onAccessLost(error);
setActionError(error);
setFieldErrors(fieldErrorsFor(error));
setStatus("failed");
if (error instanceof ApiRequestError && error.status === 400) {
setAttempt(null);
setCreateRetryRequired(false);
}
return;
}
if (!isSubmittingSessionCurrent(submittingSession)) return;
try {
await onSaved(saved);
if (!isSubmittingSessionCurrent(submittingSession)) return;
setAttempt(null);
setCreateRetryRequired(false);
setStatus("saved");
} catch (error: unknown) {
setActionError(error);
setStatus("failed");
}
}
async function saveUpdate(): Promise<void> {
if (!baseline) return;
const submittingSession = session.data;
if (!sessionReady || !submittingSession || !isSubmittingSessionCurrent(submittingSession))
return;
const body = buildCompanyUpdateBody(draft, baseline);
if (!Object.keys(body).some((key) => key !== "expected_version")) return;
setActionError(null);
setCsrfRetryMessage(null);
setFieldErrors({});
setStatus("saving");
try {
const saved = await updateOrganization.mutateAsync({ orgId: baseline.id, data: body });
if (!isSubmittingSessionCurrent(submittingSession)) return;
setBaseline(saved);
setDraft(draftFromOrganization(saved));
setConflict(false);
setReviewRequired(false);
await onSaved(saved);
if (!isSubmittingSessionCurrent(submittingSession)) return;
setStatus("saved");
} catch (error: unknown) {
if (csrfCheckFailed(error)) {
await refreshAfterCsrfFailure(submittingSession);
return;
}
if (!isSubmittingSessionCurrent(submittingSession)) return;
if (accessLost(error)) onAccessLost(error);
setActionError(error);
setFieldErrors(fieldErrorsFor(error));
setStatus("failed");
if (error instanceof ApiRequestError && error.status === 412) {
setConflict(true);
setReviewRequired(false);
}
}
}
async function reloadCurrentVersion(): Promise<void> {
if (!baseline) return;
const submittingSession = session.data;
if (!sessionReady || !submittingSession || !isSubmittingSessionCurrent(submittingSession))
return;
setActionError(null);
try {
const latest = await getOrganization(baseline.id);
if (!isSubmittingSessionCurrent(submittingSession)) return;
const rebased = rebaseCompanyDraft(draft, baseline, latest);
setBaseline(latest);
setDraft(rebased);
setFieldErrors({});
setConflict(false);
setReviewRequired(true);
setStatus("idle");
} catch (error: unknown) {
if (!isSubmittingSessionCurrent(submittingSession)) return;
if (accessLost(error)) onAccessLost(error);
setActionError(error);
setStatus("failed");
}
}
function submit(event: FormEvent<HTMLFormElement>): void {
event.preventDefault();
if (!sessionReady || isSaving || !hasChanges || conflict || reviewRequired) return;
if (creating) {
void saveCreate();
} else {
void saveUpdate();
}
}
const errorMessage =
csrfRetryMessage ??
(createRequestIsFrozen
? "Ответ о создании не подтвержден. Повторите запрос с теми же данными, чтобы сервер вернул исходный результат."
: actionError instanceof ApiRequestError
? actionError.status === 412
? "Компания изменилась в другом запросе. Черновик сохранен; прочитайте текущую версию перед повторным сохранением."
: "Не удалось сохранить изменения. Проверьте поля и повторите попытку."
: actionError
? "Не удалось сохранить изменения. Проверьте подключение и повторите попытку."
: null);
const nameErrorId = `${id}-name-error`;
const descriptionErrorId = `${id}-description-error`;
const sphereErrorId = `${id}-sphere-error`;
const websiteErrorId = `${id}-website-error`;
const emailErrorId = `${id}-email-error`;
const phoneErrorId = `${id}-phone-error`;
const telegramErrorId = `${id}-telegram-error`;
return (
<form className={styles.form} onSubmit={submit} noValidate>
{creating ? <h2 className={styles.title}>Основные данные компании</h2> : null}
{createRequestIsFrozen ? (
<p className={styles.notice} role="status">
Запрос создания хранится только на этой странице. Не меняйте данные до подтверждения
ответа.
</p>
) : null}
<div className={styles.field}>
<label htmlFor={`${id}-name`}>Название компании</label>
<input
id={`${id}-name`}
autoComplete="organization"
required
maxLength={200}
value={draft.name}
readOnly={formLocked}
aria-invalid={Boolean(fieldErrors.name)}
aria-describedby={fieldErrors.name ? nameErrorId : undefined}
onChange={(event) => updateDraft("name", event.currentTarget.value)}
/>
{fieldErrors.name ? (
<p className={styles["field-error"]} id={nameErrorId}>
{fieldErrors.name}
</p>
) : null}
</div>
<div className={styles.field}>
<label htmlFor={`${id}-description`}>Чем занимается компания</label>
<textarea
id={`${id}-description`}
rows={5}
maxLength={2000}
value={draft.description}
readOnly={formLocked}
aria-invalid={Boolean(fieldErrors.description)}
aria-describedby={fieldErrors.description ? descriptionErrorId : undefined}
onChange={(event) => updateDraft("description", event.currentTarget.value)}
/>
{fieldErrors.description ? (
<p className={styles["field-error"]} id={descriptionErrorId}>
{fieldErrors.description}
</p>
) : null}
</div>
<div className={styles.field}>
<label htmlFor={`${id}-sphere`}>Сфера деятельности</label>
<input
id={`${id}-sphere`}
maxLength={100}
value={draft.sphere}
readOnly={formLocked}
aria-invalid={Boolean(fieldErrors.sphere)}
aria-describedby={fieldErrors.sphere ? sphereErrorId : undefined}
onChange={(event) => updateDraft("sphere", event.currentTarget.value)}
/>
{fieldErrors.sphere ? (
<p className={styles["field-error"]} id={sphereErrorId}>
{fieldErrors.sphere}
</p>
) : null}
</div>
<fieldset className={styles.group}>
<legend>Публичные контакты компании</legend>
<p className={styles.hint}>
Чтобы удалить контакт из карточки компании, оставьте соответствующее поле пустым.
</p>
{(
[
["website", "Сайт компании", "url", "https://example.com", websiteErrorId],
["email", "Почта для связи", "email", "jobs@example.com", emailErrorId],
["phone", "Телефон компании", "tel", "+70000000000", phoneErrorId],
["telegram", "Telegram компании", "text", "@company", telegramErrorId],
] as const
).map(([key, label, type, placeholder, errorId]) => (
<div className={styles.field} key={key}>
<label htmlFor={`${id}-${key}`}>{label}</label>
<input
id={`${id}-${key}`}
type={type}
placeholder={placeholder}
value={draft[key]}
readOnly={formLocked}
aria-invalid={Boolean(fieldErrors[key])}
aria-describedby={fieldErrors[key] ? errorId : undefined}
onChange={(event) => updateDraft(key, event.currentTarget.value)}
/>
{fieldErrors[key] ? (
<p className={styles["field-error"]} id={errorId}>
{fieldErrors[key]}
</p>
) : null}
</div>
))}
</fieldset>
<fieldset className={styles.group}>
<legend>Представители компании</legend>
<p className={styles.hint}>
Добавляйте только представителей, которых компания вправе представить кандидатам.
</p>
{draft.representatives.map((representative, index) => (
<div className={styles.representative} key={`representative-${index}`}>
<div className={styles.field}>
<label htmlFor={`${id}-representative-${index}-name`}>Имя представителя</label>
<input
id={`${id}-representative-${index}-name`}
maxLength={100}
value={representative.name}
readOnly={formLocked}
onChange={(event) => updateRepresentative(index, "name", event.currentTarget.value)}
/>
</div>
<div className={styles.field}>
<label htmlFor={`${id}-representative-${index}-title`}>Должность</label>
<input
id={`${id}-representative-${index}-title`}
maxLength={100}
value={representative.job_title}
readOnly={formLocked}
onChange={(event) =>
updateRepresentative(index, "job_title", event.currentTarget.value)
}
/>
</div>
<Button
variant="quiet"
aria-label={`Удалить представителя ${index + 1}`}
aria-disabled={formLocked || undefined}
onClick={() =>
updateDraft(
"representatives",
formLocked
? draft.representatives
: draft.representatives.filter((_, itemIndex) => itemIndex !== index),
)
}
>
Удалить
</Button>
</div>
))}
{fieldErrors.representatives ? (
<p className={styles["field-error"]} role="alert">
{fieldErrors.representatives}
</p>
) : null}
<Button
variant="secondary"
aria-disabled={formLocked || draft.representatives.length >= 10 || undefined}
onClick={() => {
if (!formLocked && draft.representatives.length < 10) {
updateDraft("representatives", [
...draft.representatives,
{ name: "", job_title: "" },
]);
}
}}
>
Добавить представителя
</Button>
</fieldset>
{conflict ? (
<div className={styles.conflict} role="status">
<h3>Компания изменилась</h3>
<p>
Черновик оставлен. Прочитайте текущие данные, проверьте изменения и подтвердите
повторное сохранение.
</p>
<Button variant="secondary" isBusy={isSaving} onClick={() => void reloadCurrentVersion()}>
Прочитать текущую версию
</Button>
</div>
) : null}
{reviewRequired ? (
<div className={styles.conflict} role="status">
<p>
Текущая версия загружена. Ваши измененные поля сохранены в черновике; проверьте их перед
повторной отправкой.
</p>
<Button variant="secondary" onClick={() => setReviewRequired(false)}>
Я проверил черновик
</Button>
</div>
) : null}
{errorMessage ? (
<p className={styles["action-error"]} role="alert">
{errorMessage}
</p>
) : null}
<div className={styles.actions}>
<Button
type="submit"
isBusy={isSaving}
aria-disabled={!sessionReady || !hasChanges || conflict || reviewRequired || undefined}
>
{isSaving
? "Сохраняем..."
: createRequestIsFrozen
? "Повторить создание с теми же данными"
: creating
? "Создать компанию"
: reviewRequired
? "Сначала проверьте черновик"
: "Сохранить изменения"}
</Button>
</div>
<SavingStatus state={status} />
</form>
);
}
@@ -0,0 +1 @@
export { EditProfile } from "./ui/edit-profile";
@@ -0,0 +1,61 @@
.root {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.root > section {
min-width: 0;
}
.server-step,
.form-error,
.conflict,
.continuation {
min-width: 0;
margin: 0 0 var(--space-4);
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
overflow-wrap: anywhere;
}
.server-step {
color: var(--color-text-secondary);
}
.form-error,
.conflict {
border-width: var(--line-strong);
border-color: var(--color-danger);
}
.form-error {
font-weight: var(--font-weight-medium);
}
.conflict h2 {
margin: 0 0 var(--space-2);
font-size: var(--font-size-l);
}
.conflict p,
.continuation p {
margin: 0 0 var(--space-3);
line-height: var(--line-height-body);
}
.continuation {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
align-items: center;
justify-content: space-between;
margin: var(--space-5) 0 0;
}
.continuation p {
flex: 1 1 16rem;
margin: 0;
}
@@ -0,0 +1,362 @@
import { useEffect, useRef, useState } from "react";
import { useQueryClient, type UseQueryResult } from "@tanstack/react-query";
import {
buildCandidateProfileUpdate,
mapProfileServerErrors,
toCandidateProfileDraft,
type CandidateProfileDraft,
type ProfileFormIssue,
} from "../../../entities/candidate";
import { getOnboardingDestination } from "../../../entities/session";
import { ApiRequestError } from "../../../shared/api";
import {
type GetMyProfileQueryError,
type GetMyProfileQueryResult,
getGetMyProfileQueryKey,
useGetMyProfile,
useSaveMyProfile,
} from "../../../shared/api/endpoints/candidate/candidate";
import {
getGetCurrentSessionQueryKey,
useGetCurrentSession,
} from "../../../shared/api/endpoints/identity/identity";
import type { Account, CandidateProfile, Session } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import {
Button,
ButtonLink,
ErrorState,
ForbiddenState,
LoadingState,
Section,
} from "../../../shared/ui";
import { ProfileForm } from "./profile-form";
import styles from "./edit-profile.module.css";
type OnboardingStep = Account["onboarding_step"];
function stepLabel(step: OnboardingStep): string {
switch (step) {
case "candidate_consents":
return "Согласия";
case "candidate_profile":
return "Профиль";
case "candidate_questionnaire":
return "Анкета";
case "candidate_assessment":
return "Оценка навыков";
case "employer_company":
return "Компания";
case "completed":
return "Завершено";
}
}
function ProfileAccessDenied({ error }: { error: unknown }) {
return (
<ForbiddenState
error={error}
title="Профиль недоступен"
description="Сервер не подтвердил доступ к профилю кандидата. Обновите вход или откройте подходящий кабинет."
/>
);
}
export function EditProfile() {
const queryClient = useQueryClient();
const profile = useGetMyProfile({
query: {
gcTime: 0,
staleTime: 0,
refetchOnMount: "always",
retry: false,
},
});
const session = useGetCurrentSession();
const profileAccessError =
profile.isError &&
profile.error instanceof ApiRequestError &&
(profile.error.status === 401 || profile.error.status === 403)
? profile.error
: null;
const sessionAccessError =
session.isError &&
session.error instanceof ApiRequestError &&
(session.error.status === 401 || session.error.status === 403)
? session.error
: null;
useEffect(() => {
if (!profileAccessError && !sessionAccessError) return;
queryClient.removeQueries({ queryKey: getGetMyProfileQueryKey(), exact: true });
}, [profileAccessError, queryClient, sessionAccessError]);
if (profile.isPending && !profile.data) {
return <LoadingState label="Загружаем профиль кандидата..." />;
}
if (profileAccessError) {
return <ProfileAccessDenied error={profileAccessError} />;
}
if (sessionAccessError) {
return <ProfileAccessDenied error={sessionAccessError} />;
}
if (!profile.data) {
if (profile.error instanceof ApiRequestError && profile.error.status === 403) {
return <ProfileAccessDenied error={profile.error} />;
}
if (profile.error instanceof ApiRequestError && profile.error.status === 401) {
return <ProfileAccessDenied error={profile.error} />;
}
return (
<ErrorState
error={profile.error}
isRetrying={profile.isRefetching}
onRetry={() => void profile.refetch()}
title="Не удалось загрузить профиль"
/>
);
}
if (!session.data) {
if (session.error instanceof ApiRequestError && session.error.status === 403) {
return <ProfileAccessDenied error={session.error} />;
}
if (session.error && !session.isFetching) {
return (
<ErrorState
error={session.error}
isRetrying={session.isRefetching}
onRetry={() => void session.refetch()}
title="Не удалось проверить текущий вход"
/>
);
}
return <LoadingState label="Проверяем текущий вход..." />;
}
if (session.data.account.scenario !== "candidate") {
return (
<ForbiddenState
title="Профиль кандидата недоступен"
description="Войдите в кабинет, связанный со сценарием кандидата."
/>
);
}
return (
<ProfileEditor key={session.data.account.id} profile={profile.data} profileQuery={profile} />
);
}
type ProfileQueryResult = UseQueryResult<GetMyProfileQueryResult, GetMyProfileQueryError>;
type ProfileEditorProps = {
profile: CandidateProfile;
profileQuery: ProfileQueryResult;
};
function ProfileEditor({ profile, profileQuery }: ProfileEditorProps) {
const queryClient = useQueryClient();
const session = useGetCurrentSession();
const saveInFlight = useRef(false);
const [draft, setDraft] = useState<CandidateProfileDraft>(() => toCandidateProfileDraft(profile));
const [issues, setIssues] = useState<ProfileFormIssue[]>([]);
const [formError, setFormError] = useState<string | null>(null);
const [savingState, setSavingState] = useState<"idle" | "saving" | "saved" | "failed">("idle");
const [conflict, setConflict] = useState(false);
const [latestLoadError, setLatestLoadError] = useState(false);
const [forbidden, setForbidden] = useState(false);
const [savedStep, setSavedStep] = useState<OnboardingStep | null>(null);
const saveMutation = useSaveMyProfile({
request: {
headers: session.data ? { "X-CSRF-Token": session.data.csrf_token } : {},
},
mutation: { gcTime: 0 },
});
const changeDraft = (next: CandidateProfileDraft) => {
setDraft(next);
setIssues([]);
setFormError(null);
setSavingState("idle");
setSavedStep(null);
};
async function handleSubmit() {
if (!session.data || conflict || forbidden || saveInFlight.current) return;
const result = buildCandidateProfileUpdate(draft);
setIssues(result.issues);
setFormError(null);
setSavedStep(null);
if (!result.data) {
setSavingState("failed");
return;
}
const submittingSession = session.data;
const isSubmittingSessionCurrent = () => {
const current = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
return Boolean(
current &&
current.account.id === submittingSession.account.id &&
current.csrf_token === submittingSession.csrf_token,
);
};
saveInFlight.current = true;
setSavingState("saving");
try {
const saved = await saveMutation.mutateAsync({ data: result.data });
if (!isSubmittingSessionCurrent()) return;
queryClient.setQueryData(getGetMyProfileQueryKey(), saved);
setDraft(toCandidateProfileDraft(saved));
setIssues([]);
setConflict(false);
setLatestLoadError(false);
setSavingState("saved");
const refreshedSession = await session.refetch();
if (
refreshedSession.data &&
!refreshedSession.isError &&
refreshedSession.data.account.id === submittingSession.account.id
) {
setSavedStep(refreshedSession.data.account.onboarding_step);
} else {
setFormError("Профиль сохранен. Не удалось проверить следующий шаг на сервере.");
}
} catch (error: unknown) {
if (!isSubmittingSessionCurrent()) return;
setSavingState("failed");
if (error instanceof ApiRequestError && error.status === 412) {
setConflict(true);
setLatestLoadError(false);
const refreshed = await profileQuery.refetch();
if (!refreshed.data || refreshed.isError) setLatestLoadError(true);
return;
}
if (error instanceof ApiRequestError && error.status === 400) {
const serverIssues = mapProfileServerErrors(error.fieldErrors);
setIssues(serverIssues);
setFormError(
serverIssues.length === 0
? "Сервер не сохранил изменения. Проверьте формат данных и повторите попытку."
: null,
);
return;
}
if (error instanceof ApiRequestError && error.status === 403) {
if (error.code === "csrf_check_failed") {
const refreshed = await session.refetch();
setFormError(
refreshed.data
? "Проверка входа обновлена. Данные формы сохранены, повторите сохранение."
: "Вход больше не подтвержден. Войдите снова, чтобы продолжить работу с профилем.",
);
return;
}
setForbidden(true);
setFormError(
"Сервер больше не подтверждает доступ к профилю. Изменения не были отправлены.",
);
void session.refetch();
return;
}
if (error instanceof ApiRequestError && error.status === 401) {
setFormError(
"Вход больше не подтвержден. Войдите снова, чтобы продолжить работу с профилем.",
);
void session.refetch();
return;
}
setFormError("Не удалось сохранить профиль. Проверьте подключение и повторите попытку.");
} finally {
saveInFlight.current = false;
}
}
async function loadCurrentVersion() {
setLatestLoadError(false);
const refreshed = await profileQuery.refetch();
if (!refreshed.data || refreshed.isError) {
setLatestLoadError(true);
return;
}
setDraft(toCandidateProfileDraft(refreshed.data));
setIssues([]);
setFormError(null);
setConflict(false);
setLatestLoadError(false);
setSavedStep(null);
setSavingState("idle");
}
const currentStep = session.data?.account.onboarding_step;
const continuation = savedStep
? getOnboardingDestination({ scenario: "candidate", onboarding_step: savedStep })
: null;
const continuationLabel = savedStep ? stepLabel(savedStep) : null;
return (
<div className={styles.root}>
<Section
title="Личные сведения"
description="Заполните только то, что готовы указать. Профиль сохраняется на сервере и не требует резюме или внешнего аккаунта."
>
{currentStep ? (
<p className={styles["server-step"]}>
Сохраненный шаг аккаунта: <strong>{stepLabel(currentStep)}</strong>.
</p>
) : null}
{conflict ? (
<div className={styles.conflict} role="alert" aria-labelledby="profile-conflict-title">
<h2 id="profile-conflict-title">Профиль обновлен в другом окне</h2>
<p>
Введенные здесь изменения не отправлены. Сравнение и автоматическое объединение не
выполняются. При замене черновика данные из этой формы будут удалены.
</p>
{latestLoadError ? (
<p>Не удалось получить текущую версию. Черновик сохранен в памяти формы.</p>
) : null}
<Button
variant="secondary"
isBusy={profileQuery.isRefetching}
aria-describedby="profile-conflict-title"
onClick={() => void loadCurrentVersion()}
>
{profileQuery.isRefetching
? "Загружаем текущую версию..."
: "Заменить черновик актуальной версией"}
</Button>
</div>
) : null}
{forbidden ? (
<div className={styles["form-error"]} role="alert">
Профиль больше недоступен. Данные формы останутся до ухода со страницы.
</div>
) : null}
{formError ? (
<div className={styles["form-error"]} role="alert">
{formError}
</div>
) : null}
<ProfileForm
draft={draft}
issues={issues}
isSaving={savingState === "saving"}
savingState={savingState}
onDraftChange={changeDraft}
onSubmit={() => void handleSubmit()}
/>
{savedStep && continuation ? (
<div className={styles.continuation} role="status">
<p>Профиль сохранен. Сервер подтвердил шаг аккаунта: {continuationLabel}.</p>
{continuation !== paths.candidate.profile ? (
<ButtonLink to={continuation} variant="secondary">
Открыть сохраненный шаг
</ButtonLink>
) : (
<p>Серверный шаг остается «Профиль».</p>
)}
</div>
) : null}
</Section>
</div>
);
}
@@ -0,0 +1,276 @@
.form {
display: grid;
gap: var(--space-6);
min-width: 0;
}
.editor-fields {
display: grid;
gap: var(--space-6);
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}
.editor-legend {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.issue-summary {
min-width: 0;
padding: var(--space-4);
border: var(--line-strong) solid var(--color-danger);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.issue-summary h2,
.categories h2 {
margin: 0;
font-size: var(--font-size-l);
}
.issue-summary ul,
.categories ul {
margin: var(--space-3) 0 0;
padding-left: var(--space-5);
}
.group {
display: grid;
gap: var(--space-4);
min-width: 0;
margin: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
}
.group legend {
max-width: 100%;
padding-inline: var(--space-2);
font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
overflow-wrap: anywhere;
}
.group-description,
.hint,
.categories p {
margin: 0;
color: var(--color-text-secondary);
line-height: var(--line-height-body);
}
.field {
display: grid;
gap: var(--space-2);
min-width: 0;
}
.field > label {
font-weight: var(--font-weight-bold);
}
.field input,
.field select,
.field textarea {
box-sizing: border-box;
width: 100%;
min-width: 0;
max-width: 100%;
min-height: 2.75rem;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
font: inherit;
}
.field textarea {
resize: vertical;
}
.field input[aria-invalid="true"],
.field select[aria-invalid="true"],
.field textarea[aria-invalid="true"] {
border-width: var(--line-strong);
border-color: var(--color-danger);
}
.overlap input {
width: 1.25rem;
height: 1.25rem;
margin: 0.125rem 0 0;
}
.overlap input:focus-visible {
outline: var(--line-strong) solid var(--color-focus-ring);
outline-offset: 2px;
}
.field input:focus-visible,
.field select:focus-visible,
.field textarea:focus-visible {
outline: var(--line-strong) solid var(--color-focus-ring);
outline-offset: 2px;
}
.hint,
.error,
.claim-status {
font-size: var(--font-size-s);
line-height: var(--line-height-body);
}
.error {
margin: 0;
color: var(--color-text);
font-weight: var(--font-weight-bold);
}
.claim-status {
color: var(--color-text-secondary);
}
.suggestion {
min-width: 0;
padding: var(--space-2) var(--space-3);
border-inline-start: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
overflow-wrap: anywhere;
}
.suggestion summary {
cursor: pointer;
font-size: var(--font-size-s);
font-weight: var(--font-weight-medium);
}
.suggestion blockquote,
.suggestion p {
margin: var(--space-2) 0 0;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.item {
display: grid;
gap: var(--space-4);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
}
.item-header,
.item-actions,
.list-row,
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
align-items: center;
min-width: 0;
}
.item-header {
justify-content: space-between;
}
.item-header h3,
.list h3,
.overlap-list h3 {
margin: 0;
font-size: var(--font-size-m);
}
.grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--space-4);
min-width: 0;
}
.list,
.overlap-list {
display: grid;
gap: var(--space-3);
min-width: 0;
}
.list-row {
align-items: flex-end;
}
.list-row > .field {
flex: 1 1 14rem;
}
.overlap {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: var(--space-3);
align-items: start;
min-width: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
}
.overlap label,
.overlap p {
margin: 0;
line-height: var(--line-height-body);
overflow-wrap: anywhere;
}
.categories {
display: grid;
gap: var(--space-2);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
}
.actions {
justify-content: space-between;
padding-top: var(--space-2);
}
.actions > :first-child {
flex: 1 1 12rem;
}
@media (width < 48rem) {
.grid {
grid-template-columns: minmax(0, 1fr);
}
}
@media (width < 30rem) {
.group {
padding: var(--space-3);
}
.item {
padding: var(--space-3);
}
.actions {
align-items: stretch;
flex-direction: column;
}
.item-actions {
width: 100%;
}
}
@@ -0,0 +1,116 @@
import { renderToString } from "react-dom/server";
import { describe, expect, it, vi } from "vitest";
import { toCandidateProfileDraft } from "../../../entities/candidate";
import type { CandidateProfile } from "../../../shared/api/schemas";
import { ProfileForm } from "./profile-form";
const emptyProfile: CandidateProfile = {
version: 0,
full_name: { status: "unknown", value: null, source: null },
contacts: {
email: { status: "unknown", value: null, source: null },
phone: { status: "unknown", value: null, source: null },
telegram: { status: "unknown", value: null, source: null },
},
stack: [],
roles: [],
experience: [],
experience_overlaps: [],
soft_skills: [],
terms: {
location: { status: "unknown", value: null, source: null },
relocation: { status: "unknown", value: null, source: null },
salary_minimum: { status: "unknown", value: null, source: null },
},
confirmed_categories: [],
updated_at: null,
};
function profileWithOverlap(status: "confirmed" | "needs_confirmation"): CandidateProfile {
const source = {
origin: "manual" as const,
trust_level: 0 as const,
quote: null,
extraction_version: null,
confirmed_at: null,
};
return {
...emptyProfile,
experience: [
{
employer_name: "Первая компания",
specialization: "backend",
started_on: "2024-01",
ended_on: "2024-12",
summary: null,
status: "confirmed",
source,
},
{
employer_name: "Вторая компания",
specialization: "frontend",
started_on: "2024-06",
ended_on: "2025-01",
summary: null,
status: "confirmed",
source,
},
],
experience_overlaps: [{ first_index: 0, second_index: 1, status }],
};
}
describe("ProfileForm", () => {
it("renders an empty profile as editable controls without inventing claims or categories", () => {
const html = renderToString(
<ProfileForm
draft={toCandidateProfileDraft(emptyProfile)}
issues={[]}
isSaving={false}
savingState="idle"
onDraftChange={vi.fn()}
onSubmit={vi.fn()}
/>,
);
expect(html).toContain('name="full_name"');
expect(html).toContain('name="contact_email"');
expect(html).toContain("Добавить место работы");
expect(html).toContain("Добавить специализацию");
expect(html).toContain("Подтвержденных категорий пока нет.");
expect(html).not.toContain("резюме обязательно");
const describedIds = [...html.matchAll(/aria-describedby="([^"]+)"/g)].flatMap((match) =>
(match[1] ?? "").split(" "),
);
expect(describedIds.length).toBeGreaterThan(0);
expect(describedIds.every((id) => html.includes(`id="${id}"`))).toBe(true);
});
it("renders confirmed overlap copy with a separating space and keeps new overlap confirmation explicit", () => {
const props = {
issues: [],
isSaving: false,
savingState: "idle" as const,
onDraftChange: vi.fn(),
onSubmit: vi.fn(),
};
const confirmedHtml = renderToString(
<ProfileForm draft={toCandidateProfileDraft(profileWithOverlap("confirmed"))} {...props} />,
);
const unconfirmedHtml = renderToString(
<ProfileForm
draft={toCandidateProfileDraft(profileWithOverlap("needs_confirmation"))}
{...props}
/>,
);
const confirmedText = confirmedHtml.replaceAll("<!-- -->", "").replace(/\s+/g, " ");
const unconfirmedText = unconfirmedHtml.replaceAll("<!-- -->", "").replace(/\s+/g, " ");
expect(confirmedText).toContain("Параллельная работа в местах 1 и 2 подтверждена ранее:");
expect(confirmedText).not.toContain("2подтверждена ранее");
expect(unconfirmedText).toContain(
"Подтверждаю, что места работы 1 и 2 действительно шли параллельно:",
);
expect(unconfirmedText).not.toContain("подтверждена ранее");
});
});
@@ -0,0 +1,895 @@
import { useId, useRef, type FormEvent, type ReactNode } from "react";
import {
addExperience,
addRole,
addSoftSkill,
addStack,
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, SavingStatus } from "../../../shared/ui";
import styles from "./profile-form.module.css";
type Specialization = CandidateProfile["roles"][number]["specialization"];
type Grade = NonNullable<CandidateProfile["roles"][number]["self_assessed_grade"]>;
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 ? (
<p className={styles.error} id={id}>
{children}
</p>
) : null;
}
function Suggestion({ source }: { source: { quote: string | null; origin: string } | null }) {
if (!source || source.origin === "manual") return null;
const origin = source.origin === "imported" ? "Импортировано" : "Предложено из документа";
return (
<details className={styles.suggestion}>
<summary>{origin}. Значение пока не подтверждено.</summary>
{source.quote ? <blockquote>{source.quote}</blockquote> : <p>Цитата не сохранена.</p>}
</details>
);
}
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 (
<div className={styles.field}>
<label htmlFor={id}>{label}</label>
{description ? (
<p className={styles.hint} id={`${id}-hint`}>
{description}
</p>
) : null}
{children}
{suggestion ? (
<div id={`${id}-suggestion`}>
<Suggestion source={suggestion} />
</div>
) : null}
<ErrorText id={`${id}-error`}>{error}</ErrorText>
</div>
);
}
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;
}
function SourceLabel({ status }: { status: "confirmed" | "extracted" | "unknown" }) {
if (status === "extracted")
return <span className={styles["claim-status"]}>Нужно проверить</span>;
if (status === "unknown") return <span className={styles["claim-status"]}>Не указано</span>;
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 issue = (field: string) => errorFor(issues, field);
const setDraft = (next: CandidateProfileDraft) => onDraftChange(next);
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
event.currentTarget.querySelector<HTMLButtonElement>('button[type="submit"]')?.focus();
onSubmit();
}
const overlaps = reviewExperienceOverlaps(draft);
return (
<form className={styles.form} onSubmit={handleSubmit} noValidate>
{issues.length > 0 ? (
<div
className={styles["issue-summary"]}
role="alert"
aria-labelledby={`${prefix}-issues-title`}
>
<h2 id={`${prefix}-issues-title`}>Проверьте профиль</h2>
<ul>
{issues.map((item, index) => (
<li key={`${item.field}-${index}`}>{item.message}</li>
))}
</ul>
</div>
) : null}
<fieldset className={styles["editor-fields"]} disabled={isSaving}>
<legend className={styles["editor-legend"]}>Данные профиля</legend>
<fieldset className={styles.group}>
<legend>Имя и контакты</legend>
<Field
id={fieldId("fullName")}
label="Имя и фамилия"
error={issue("fullName")}
suggestion={draft.fullName.source}
>
<input
id={fieldId("fullName")}
name="full_name"
autoComplete="name"
maxLength={200}
value={draft.fullName.value}
aria-invalid={Boolean(issue("fullName"))}
aria-describedby={describedBy(
fieldId("fullName"),
issue("fullName"),
Boolean(draft.fullName.source),
)}
onChange={(event) =>
setDraft({
...draft,
fullName: updateFieldDraft(draft.fullName, event.currentTarget.value),
})
}
/>
<SourceLabel status={draft.fullName.status} />
</Field>
<Field
id={fieldId("contacts.email")}
label="Контактный email"
error={issue("contacts.email")}
suggestion={draft.contacts.email.source}
description="Это контакт профиля. Он может отличаться от адреса входа."
>
<input
id={fieldId("contacts.email")}
name="contact_email"
type="email"
autoComplete="email"
maxLength={254}
value={draft.contacts.email.value}
aria-invalid={Boolean(issue("contacts.email"))}
aria-describedby={describedBy(
fieldId("contacts.email"),
issue("contacts.email"),
Boolean(draft.contacts.email.source),
true,
)}
onChange={(event) =>
setDraft({
...draft,
contacts: {
...draft.contacts,
email: updateFieldDraft(draft.contacts.email, event.currentTarget.value),
},
})
}
/>
<SourceLabel status={draft.contacts.email.status} />
</Field>
<Field
id={fieldId("contacts.phone")}
label="Телефон"
error={issue("contacts.phone")}
suggestion={draft.contacts.phone.source}
description="Международный формат E.164, например +70000000000."
>
<input
id={fieldId("contacts.phone")}
name="contact_phone"
type="tel"
autoComplete="tel"
inputMode="tel"
maxLength={16}
value={draft.contacts.phone.value}
aria-invalid={Boolean(issue("contacts.phone"))}
aria-describedby={describedBy(
fieldId("contacts.phone"),
issue("contacts.phone"),
Boolean(draft.contacts.phone.source),
true,
)}
onChange={(event) =>
setDraft({
...draft,
contacts: {
...draft.contacts,
phone: updateFieldDraft(draft.contacts.phone, event.currentTarget.value),
},
})
}
/>
<SourceLabel status={draft.contacts.phone.status} />
</Field>
<Field
id={fieldId("contacts.telegram")}
label="Telegram"
error={issue("contacts.telegram")}
suggestion={draft.contacts.telegram.source}
description="Укажите имя пользователя с символом @."
>
<input
id={fieldId("contacts.telegram")}
name="contact_telegram"
autoComplete="off"
maxLength={33}
value={draft.contacts.telegram.value}
aria-invalid={Boolean(issue("contacts.telegram"))}
aria-describedby={describedBy(
fieldId("contacts.telegram"),
issue("contacts.telegram"),
Boolean(draft.contacts.telegram.source),
true,
)}
onChange={(event) =>
setDraft({
...draft,
contacts: {
...draft.contacts,
telegram: updateFieldDraft(draft.contacts.telegram, event.currentTarget.value),
},
})
}
/>
<SourceLabel status={draft.contacts.telegram.status} />
</Field>
</fieldset>
<fieldset className={styles.group}>
<legend>Опыт работы</legend>
<p className={styles["group-description"]}>
Укажите специализацию и месяцы работы. Пустая дата окончания означает, что работа
продолжается.
</p>
{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 (
<section
className={styles.item}
key={item.id}
aria-labelledby={`${prefix}-experience-${index}-title`}
>
<div className={styles["item-header"]}>
<h3 id={`${prefix}-experience-${index}-title`}>Место работы {index + 1}</h3>
<div className={styles["item-actions"]}>
<Button
variant="quiet"
aria-label={`Переместить место работы ${index + 1} выше`}
disabled={index === 0 || isSaving}
onClick={() => setDraft(moveExperience(draft, index, -1))}
>
Выше
</Button>
<Button
variant="quiet"
aria-label={`Переместить место работы ${index + 1} ниже`}
disabled={index === draft.experience.length - 1 || isSaving}
onClick={() => setDraft(moveExperience(draft, index, 1))}
>
Ниже
</Button>
<Button
variant="quiet"
aria-label={`Удалить место работы ${index + 1}`}
disabled={isSaving}
onClick={() => setDraft(removeExperience(draft, item.id))}
>
Удалить
</Button>
</div>
</div>
<div className={styles.grid}>
<Field
id={employerId}
label="Компания"
error={issue(`${base}.employer_name`)}
suggestion={item.source}
>
<input
id={employerId}
value={item.employer_name ?? ""}
maxLength={200}
aria-invalid={Boolean(issue(`${base}.employer_name`))}
aria-describedby={describedBy(
employerId,
issue(`${base}.employer_name`),
Boolean(item.source),
)}
onChange={(event) =>
setDraft(
updateExperienceDraft(draft, item.id, {
employer_name: event.currentTarget.value || null,
}),
)
}
/>
</Field>
<Field
id={specialId}
label="Специализация"
error={issue(`${base}.specialization`)}
suggestion={item.source}
>
<select
id={specialId}
value={item.specialization}
aria-invalid={Boolean(issue(`${base}.specialization`))}
aria-describedby={describedBy(
specialId,
issue(`${base}.specialization`),
Boolean(item.source),
)}
onChange={(event) =>
setDraft(
updateExperienceDraft(draft, item.id, {
specialization: event.currentTarget.value as Specialization | "",
}),
)
}
>
<option value="">Выберите специализацию</option>
{specializations.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</Field>
<Field
id={startId}
label="Начало работы"
error={issue(`${base}.started_on`)}
description="Месяц и год."
suggestion={item.source}
>
<input
id={startId}
type="month"
value={item.started_on}
aria-invalid={Boolean(issue(`${base}.started_on`))}
aria-describedby={describedBy(
startId,
issue(`${base}.started_on`),
Boolean(item.source),
true,
)}
onChange={(event) =>
setDraft(
updateExperienceDraft(draft, item.id, {
started_on: event.currentTarget.value,
}),
)
}
/>
</Field>
<Field
id={endId}
label="Окончание работы"
error={issue(`${base}.ended_on`)}
description="Оставьте пустым, если работаете здесь сейчас."
suggestion={item.source}
>
<input
id={endId}
type="month"
value={item.ended_on ?? ""}
aria-invalid={Boolean(issue(`${base}.ended_on`))}
aria-describedby={describedBy(
endId,
issue(`${base}.ended_on`),
Boolean(item.source),
true,
)}
onChange={(event) =>
setDraft(
updateExperienceDraft(draft, item.id, {
ended_on: event.currentTarget.value || null,
}),
)
}
/>
</Field>
<Field id={summaryId} label="Чем занимались" error={issue(`${base}.summary`)}>
<textarea
id={summaryId}
rows={3}
maxLength={1000}
value={item.summary ?? ""}
aria-invalid={Boolean(issue(`${base}.summary`))}
aria-describedby={describedBy(summaryId, issue(`${base}.summary`))}
onChange={(event) =>
setDraft(
updateExperienceDraft(draft, item.id, {
summary: event.currentTarget.value || null,
}),
)
}
/>
</Field>
</div>
</section>
);
})}
<Button
variant="secondary"
disabled={draft.experience.length >= 20 || isSaving}
onClick={() => setDraft(addExperience(draft, newRowId("experience")))}
>
Добавить место работы
</Button>
{overlaps.length > 0 ? (
<div className={styles["overlap-list"]}>
<h3>Параллельные периоды</h3>
<p>Совпадающие месяцы нужно подтвердить отдельно для каждой пары мест работы.</p>
{overlaps.map((overlap) => {
const id = `${prefix}-overlap-${overlap.key.replace(":", "-")}`;
return (
<div className={styles.overlap} key={overlap.key}>
{overlap.requiresAcknowledgement ? (
<>
<input
id={id}
type="checkbox"
checked={overlap.acknowledged}
disabled={isSaving}
aria-describedby={
issue("experience.overlaps") ? `${id}-error` : undefined
}
onChange={(event) =>
setDraft(
setParallelAcknowledgement(
draft,
overlap.key,
event.currentTarget.checked,
),
)
}
/>
<label htmlFor={id}>
Подтверждаю, что места работы {overlap.firstIndex + 1} и{" "}
{overlap.secondIndex + 1} действительно шли параллельно:{" "}
{formatPeriod(overlap.firstPeriod)} и {formatPeriod(overlap.secondPeriod)}
.
</label>
</>
) : (
<p>
Параллельная работа в местах {overlap.firstIndex + 1} и{" "}
{overlap.secondIndex + 1} подтверждена ранее:{" "}
{formatPeriod(overlap.firstPeriod)} и {formatPeriod(overlap.secondPeriod)}.
</p>
)}
</div>
);
})}
<ErrorText id={`${prefix}-experience-overlaps-error`}>
{issue("experience.overlaps")}
</ErrorText>
</div>
) : null}
</fieldset>
<fieldset className={styles.group}>
<legend>Специализация и навыки</legend>
<p className={styles["group-description"]}>
Самооценка остается заявлением кандидата. Подтвержденная категория появляется только
после оценки.
</p>
{draft.roles.map((item, index) => {
const base = `roles.${index}`;
const specializationId = fieldId(`${base}.specialization`);
const gradeId = fieldId(`${base}.self_assessed_grade`);
return (
<div className={styles.item} key={item.id}>
<div className={styles["item-header"]}>
<h3>Роль {index + 1}</h3>
<Button
variant="quiet"
aria-label={`Удалить роль ${index + 1}`}
disabled={isSaving}
onClick={() => setDraft(removeItem(draft, "roles", item.id))}
>
Удалить
</Button>
</div>
<div className={styles.grid}>
<Field
id={specializationId}
label="Специализация"
error={issue(`${base}.specialization`)}
suggestion={item.source}
>
<select
id={specializationId}
value={item.specialization}
aria-invalid={Boolean(issue(`${base}.specialization`))}
aria-describedby={describedBy(
specializationId,
issue(`${base}.specialization`),
Boolean(item.source),
)}
onChange={(event) =>
setDraft(
updateRoleDraft(draft, item.id, {
specialization: event.currentTarget.value as Specialization | "",
}),
)
}
>
<option value="">Выберите специализацию</option>
{specializations.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</Field>
<Field
id={gradeId}
label="Моя оценка уровня"
error={issue(`${base}.self_assessed_grade`)}
suggestion={item.source}
>
<select
id={gradeId}
value={item.self_assessed_grade ?? ""}
aria-invalid={Boolean(issue(`${base}.self_assessed_grade`))}
aria-describedby={describedBy(
gradeId,
issue(`${base}.self_assessed_grade`),
Boolean(item.source),
)}
onChange={(event) =>
setDraft(
updateRoleDraft(draft, item.id, {
self_assessed_grade: (event.currentTarget.value ||
null) as Grade | null,
}),
)
}
>
<option value="">Не указывать</option>
{grades.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</Field>
</div>
</div>
);
})}
<Button
variant="secondary"
disabled={draft.roles.length >= 9 || isSaving}
onClick={() => setDraft(addRole(draft, newRowId("role")))}
>
Добавить специализацию
</Button>
<div className={styles.list}>
<h3>Технологии и инструменты</h3>
{draft.stack.map((item, index) => {
const field = `stack.${index}.tag`;
const id = fieldId(field);
return (
<div className={styles["list-row"]} key={item.id}>
<Field
id={id}
label={`Навык ${index + 1}`}
error={issue(field)}
suggestion={item.source}
>
<input
id={id}
value={item.tag}
maxLength={50}
aria-invalid={Boolean(issue(field))}
aria-describedby={describedBy(id, issue(field), Boolean(item.source))}
onChange={(event) =>
setDraft(
updateStackDraft(draft, item.id, { tag: event.currentTarget.value }),
)
}
/>
</Field>
<Button
variant="quiet"
aria-label={`Удалить навык ${index + 1}`}
disabled={isSaving}
onClick={() => setDraft(removeItem(draft, "stack", item.id))}
>
Удалить
</Button>
</div>
);
})}
<Button
variant="secondary"
disabled={draft.stack.length >= 30 || isSaving}
onClick={() => setDraft(addStack(draft, newRowId("stack")))}
>
Добавить навык
</Button>
</div>
<div className={styles.list}>
<h3>Гибкие навыки</h3>
{draft.softSkills.map((item, index) => {
const field = `softSkills.${index}.skill`;
const id = fieldId(field);
return (
<div className={styles["list-row"]} key={item.id}>
<Field
id={id}
label={`Гибкий навык ${index + 1}`}
error={issue(field)}
suggestion={item.source}
>
<input
id={id}
value={item.skill}
maxLength={50}
aria-invalid={Boolean(issue(field))}
aria-describedby={describedBy(id, issue(field), Boolean(item.source))}
onChange={(event) =>
setDraft(
updateSoftSkillDraft(draft, item.id, {
skill: event.currentTarget.value,
}),
)
}
/>
</Field>
<Button
variant="quiet"
aria-label={`Удалить гибкий навык ${index + 1}`}
disabled={isSaving}
onClick={() => setDraft(removeItem(draft, "softSkills", item.id))}
>
Удалить
</Button>
</div>
);
})}
<Button
variant="secondary"
disabled={draft.softSkills.length >= 10 || isSaving}
onClick={() => setDraft(addSoftSkill(draft, newRowId("soft-skill")))}
>
Добавить гибкий навык
</Button>
</div>
</fieldset>
<fieldset className={styles.group}>
<legend>Условия работы</legend>
<Field
id={fieldId("terms.location")}
label="Желаемое место работы"
error={issue("terms.location")}
suggestion={draft.terms.location.source}
>
<input
id={fieldId("terms.location")}
maxLength={100}
value={draft.terms.location.value}
aria-invalid={Boolean(issue("terms.location"))}
aria-describedby={describedBy(
fieldId("terms.location"),
issue("terms.location"),
Boolean(draft.terms.location.source),
)}
onChange={(event) =>
setDraft({
...draft,
terms: {
...draft.terms,
location: updateFieldDraft(draft.terms.location, event.currentTarget.value),
},
})
}
/>
</Field>
<Field
id={fieldId("terms.relocation")}
label="Готовность к переезду"
error={issue("terms.relocation")}
suggestion={draft.terms.relocation.source}
>
<select
id={fieldId("terms.relocation")}
value={
draft.terms.relocation.value === null ? "" : String(draft.terms.relocation.value)
}
aria-invalid={Boolean(issue("terms.relocation"))}
aria-describedby={describedBy(
fieldId("terms.relocation"),
issue("terms.relocation"),
Boolean(draft.terms.relocation.source),
)}
onChange={(event) =>
setDraft({
...draft,
terms: {
...draft.terms,
relocation: updateFieldDraft(
draft.terms.relocation,
event.currentTarget.value === ""
? null
: event.currentTarget.value === "true",
),
},
})
}
>
<option value="">Не указывать</option>
<option value="true">Да</option>
<option value="false">Нет</option>
</select>
</Field>
<div className={styles.grid}>
<Field
id={fieldId("terms.salaryMinimum.amount")}
label="Минимальная зарплата, рублей в месяц"
error={issue("terms.salaryMinimum.amount")}
suggestion={draft.terms.salaryMinimum.source}
description="Сумма должна быть кратна 1000."
>
<input
id={fieldId("terms.salaryMinimum.amount")}
type="number"
inputMode="numeric"
min={1000}
max={100000000}
step={1000}
value={draft.terms.salaryMinimum.amount}
aria-invalid={Boolean(issue("terms.salaryMinimum.amount"))}
aria-describedby={describedBy(
fieldId("terms.salaryMinimum.amount"),
issue("terms.salaryMinimum.amount"),
Boolean(draft.terms.salaryMinimum.source),
true,
)}
onChange={(event) =>
setDraft(updateSalaryDraft(draft, { amount: event.currentTarget.value }))
}
/>
<SourceLabel status={draft.terms.salaryMinimum.status} />
</Field>
<Field
id={fieldId("terms.salaryMinimum.tax_basis")}
label="Сумма до или после налога"
error={issue("terms.salaryMinimum.tax_basis")}
suggestion={draft.terms.salaryMinimum.source}
>
<select
id={fieldId("terms.salaryMinimum.tax_basis")}
value={draft.terms.salaryMinimum.tax_basis}
aria-invalid={Boolean(issue("terms.salaryMinimum.tax_basis"))}
aria-describedby={describedBy(
fieldId("terms.salaryMinimum.tax_basis"),
issue("terms.salaryMinimum.tax_basis"),
Boolean(draft.terms.salaryMinimum.source),
)}
onChange={(event) =>
setDraft(
updateSalaryDraft(draft, {
tax_basis: event.currentTarget.value as "net" | "gross" | "",
}),
)
}
>
<option value="">Выберите</option>
<option value="gross">До налога</option>
<option value="net">После налога</option>
</select>
</Field>
</div>
</fieldset>
<section className={styles.categories} aria-labelledby={`${prefix}-categories-title`}>
<h2 id={`${prefix}-categories-title`}>Подтвержденные категории</h2>
<p>Эти результаты устанавливает оценка. Их нельзя изменить в профиле.</p>
{draft.confirmedCategories.length > 0 ? (
<ul>
{draft.confirmedCategories.map((category) => (
<li key={`${category.specialization}-${category.grade}-${category.attempt_id}`}>
{specializations.find((option) => option.value === category.specialization)
?.label ?? category.specialization}
,{" "}
{grades.find((option) => option.value === category.grade)?.label ??
category.grade}
</li>
))}
</ul>
) : (
<p>Подтвержденных категорий пока нет.</p>
)}
</section>
</fieldset>
<div className={styles.actions}>
<SavingStatus state={savingState} />
<Button type="submit" isBusy={isSaving}>
{isSaving ? "Сохраняем профиль..." : "Сохранить профиль"}
</Button>
</div>
</form>
);
}
function formatPeriod(period: { started_on: string; ended_on: string | null }): string {
return `${period.started_on} - ${period.ended_on ?? "сейчас"}`;
}
@@ -0,0 +1 @@
export { FillQuestionnaire } from "./ui/fill-questionnaire";
@@ -0,0 +1,274 @@
import { describe, expect, it } from "vitest";
import type {
CandidateQuestionnaire,
ProblemFieldError,
SpecializationCatalog,
} from "../../../shared/api/schemas";
import {
addQuestionnaireSpecialization,
addQuestionnaireStackTag,
buildCandidateQuestionnaireUpdate,
changeQuestionnaireSpecialization,
mapQuestionnaireServerErrors,
patchQuestionnaireSpecialization,
removeQuestionnaireSpecialization,
toQuestionnaireDraft,
toggleQuestionnaireWorkFormat,
} from "./questionnaire-form";
const catalog: SpecializationCatalog = {
directions: [
{
code: "development",
title: "Разработка",
specializations: [
{
code: "backend",
title: "Backend",
test_availability: {
status: "available",
grades: ["junior"],
task_languages: ["python", "go"],
note: null,
},
},
],
},
{
code: "data",
title: "Данные",
specializations: [
{
code: "ds_ml",
title: "DS/ML",
test_availability: {
status: "in_development",
grades: [],
task_languages: [],
note: "Банк заданий готовится.",
},
},
],
},
],
grades: [
{ code: "intern", title: "Стажер" },
{ code: "junior", title: "Junior" },
{ code: "middle", title: "Middle" },
{ code: "senior", title: "Senior" },
],
};
const emptyQuestionnaire: CandidateQuestionnaire = {
version: 0,
specializations: [],
work_context: null,
updated_at: null,
};
function completedDraft() {
const base = toQuestionnaireDraft(emptyQuestionnaire);
const item = base.specializations[0];
if (!item) throw new Error("The empty questionnaire draft should include one editing row.");
const selected = changeQuestionnaireSpecialization(base, item.id, "backend");
return {
...patchQuestionnaireSpecialization(selected, item.id, {
selfAssessedGrade: "junior",
taskLanguages: ["go"],
}),
workFormats: ["remote" as const],
};
}
describe("questionnaire form model", () => {
it("restores server fields and the first unsaved form starts at version zero", () => {
const empty = toQuestionnaireDraft(emptyQuestionnaire);
expect(empty.expectedVersion).toBe(0);
expect(empty.specializations).toHaveLength(1);
expect(empty.specializations[0]?.specialization).toBe("");
const stored: CandidateQuestionnaire = {
version: 3,
specializations: [
{
specialization: "backend",
self_assessed_grade: "junior",
task_languages: ["go"],
stack: ["PostgreSQL"],
experience: { commercial_months: 12, academic_months: 6 },
},
],
work_context: { work_formats: ["remote", "hybrid"] },
updated_at: "2026-10-07T12:00:00Z",
};
expect(toQuestionnaireDraft(stored)).toMatchObject({
expectedVersion: 3,
workFormats: ["remote", "hybrid"],
specializations: [
{
specialization: "backend",
selfAssessedGrade: "junior",
taskLanguages: ["go"],
stack: ["PostgreSQL"],
hasExperience: true,
commercialMonths: "12",
academicMonths: "6",
},
],
});
});
it("builds the full Backend/Junior/Go questionnaire without requiring an FSP", () => {
const result = buildCandidateQuestionnaireUpdate(completedDraft(), catalog);
expect(result.issues).toEqual([]);
expect(result.data).toEqual({
expected_version: 0,
specializations: [
{
specialization: "backend",
self_assessed_grade: "junior",
task_languages: ["go"],
stack: [],
experience: null,
},
],
work_context: { work_formats: ["remote"] },
});
});
it("allows an in-development specialization as a self-assessed claim", () => {
const base = completedDraft();
const item = base.specializations[0];
if (!item) throw new Error("Expected one specialization row.");
const selected = changeQuestionnaireSpecialization(base, item.id, "ds_ml");
const developmentDraft = patchQuestionnaireSpecialization(selected, item.id, {
selfAssessedGrade: "senior",
taskLanguages: [],
});
const result = buildCandidateQuestionnaireUpdate(developmentDraft, catalog);
expect(result.issues).toEqual([]);
expect(result.data?.specializations[0]).toMatchObject({
specialization: "ds_ml",
self_assessed_grade: "senior",
task_languages: [],
});
expect(result.data?.specializations[0]).not.toHaveProperty("confirmed_grade");
});
it("rejects duplicate specializations, unavailable languages, and invalid months", () => {
const base = completedDraft();
const first = base.specializations[0];
if (!first) throw new Error("Expected one specialization row.");
let draft = addQuestionnaireSpecialization(base, "new-second");
draft = changeQuestionnaireSpecialization(draft, "new-second", "backend");
draft = patchQuestionnaireSpecialization(draft, "new-second", {
selfAssessedGrade: "junior",
});
draft = patchQuestionnaireSpecialization(draft, first.id, {
hasExperience: true,
commercialMonths: "601",
academicMonths: "-1",
taskLanguages: ["python"],
});
const restrictedCatalog: SpecializationCatalog = {
...catalog,
directions: catalog.directions.map((direction) => ({
...direction,
specializations: direction.specializations.map((specialization) =>
specialization.code === "backend"
? {
...specialization,
test_availability: {
...specialization.test_availability,
task_languages: ["go"],
},
}
: specialization,
),
})),
};
const result = buildCandidateQuestionnaireUpdate(draft, restrictedCatalog);
expect(result.data).toBeNull();
expect(result.issues.map((issue) => issue.field)).toContain("specializations.1.specialization");
expect(result.issues.map((issue) => issue.field)).toContain(
"specializations.0.commercialMonths",
);
expect(result.issues.map((issue) => issue.field)).toContain("specializations.0.academicMonths");
expect(result.issues.map((issue) => issue.field)).toContain("specializations.0.taskLanguages");
});
it("resets specialization-specific answers when the candidate changes the selected discipline", () => {
const base = completedDraft();
const item = base.specializations[0];
if (!item) throw new Error("Expected one specialization row.");
const changed = patchQuestionnaireSpecialization(base, item.id, {
stack: ["Go"],
hasExperience: true,
commercialMonths: "15",
academicMonths: "0",
});
const changedSpecialization = changeQuestionnaireSpecialization(changed, item.id, "ds_ml");
expect(changedSpecialization.specializations[0]).toMatchObject({
specialization: "ds_ml",
stack: [],
hasExperience: false,
commercialMonths: "",
academicMonths: "",
selfAssessedGrade: "",
taskLanguages: [],
});
});
it("keeps one or two specialization rows and at most three work formats", () => {
let draft = toQuestionnaireDraft(emptyQuestionnaire);
draft = addQuestionnaireSpecialization(draft, "second");
expect(draft.specializations).toHaveLength(2);
expect(addQuestionnaireSpecialization(draft, "third")).toBe(draft);
draft = removeQuestionnaireSpecialization(draft, "second");
expect(draft.specializations).toHaveLength(1);
expect(removeQuestionnaireSpecialization(draft, draft.specializations[0]?.id ?? "")).toBe(
draft,
);
draft = toggleQuestionnaireWorkFormat(draft, "remote");
draft = toggleQuestionnaireWorkFormat(draft, "office");
draft = toggleQuestionnaireWorkFormat(draft, "hybrid");
expect(toggleQuestionnaireWorkFormat(draft, "remote").workFormats).toEqual([
"office",
"hybrid",
]);
expect(toggleQuestionnaireWorkFormat(draft, "office").workFormats).toEqual([
"remote",
"hybrid",
]);
});
it("adds normalized stack tags and maps server pointers to the matching form field", () => {
const base = completedDraft();
const item = base.specializations[0];
if (!item) throw new Error("Expected one specialization row.");
const withInput = patchQuestionnaireSpecialization(base, item.id, { stackInput: " Go " });
const added = addQuestionnaireStackTag(withInput, item.id);
expect(added.issue).toBeNull();
expect(added.draft.specializations[0]?.stack).toEqual(["Go"]);
const serverErrors: ProblemFieldError[] = [
{
in: "body",
pointer: "/specializations/0/task_languages/0",
code: "invalid",
message: "invalid",
},
{
in: "body",
pointer: "/work_context/work_formats/0",
code: "invalid",
message: "invalid",
},
];
expect(mapQuestionnaireServerErrors(serverErrors).map((issue) => issue.field)).toEqual([
"specializations.0.taskLanguages",
"workFormats",
]);
});
});
@@ -0,0 +1,361 @@
import {
CandidateQuestionnaireUpdate as CandidateQuestionnaireUpdateSchema,
type CandidateQuestionnaire,
type CandidateQuestionnaireUpdate,
type ProblemFieldError,
type SpecializationCatalog,
type SpecializationCode,
type TaskLanguage,
type WorkFormat,
} from "../../../shared/api/schemas";
import { findSpecializationOption } from "../../../entities/specialization";
type QuestionnaireAnswer = CandidateQuestionnaireUpdate["specializations"][number];
type GradeCode = QuestionnaireAnswer["self_assessed_grade"];
export type QuestionnaireSpecializationDraft = {
id: string;
specialization: SpecializationCode | "";
selfAssessedGrade: GradeCode | "";
taskLanguages: TaskLanguage[];
stack: string[];
stackInput: string;
hasExperience: boolean;
commercialMonths: string;
academicMonths: string;
};
export type QuestionnaireDraft = {
expectedVersion: number;
specializations: QuestionnaireSpecializationDraft[];
workFormats: WorkFormat[];
};
export type QuestionnaireFormIssue = { field: string; message: string };
export type QuestionnaireBuildResult = {
data: CandidateQuestionnaireUpdate | null;
issues: QuestionnaireFormIssue[];
};
export function createQuestionnaireSpecializationDraft(
id: string,
): QuestionnaireSpecializationDraft {
return {
id,
specialization: "",
selfAssessedGrade: "",
taskLanguages: [],
stack: [],
stackInput: "",
hasExperience: false,
commercialMonths: "",
academicMonths: "",
};
}
export function toQuestionnaireDraft(questionnaire: CandidateQuestionnaire): QuestionnaireDraft {
const specializations = questionnaire.specializations.map((answer, index) => ({
id: `saved-${index}-${answer.specialization}`,
specialization: answer.specialization,
selfAssessedGrade: answer.self_assessed_grade,
taskLanguages: [...answer.task_languages],
stack: [...answer.stack],
stackInput: "",
hasExperience: answer.experience !== null,
commercialMonths: answer.experience === null ? "" : String(answer.experience.commercial_months),
academicMonths: answer.experience === null ? "" : String(answer.experience.academic_months),
}));
return {
expectedVersion: questionnaire.version,
specializations:
specializations.length > 0
? specializations
: [createQuestionnaireSpecializationDraft("new-0")],
workFormats: questionnaire.work_context ? [...questionnaire.work_context.work_formats] : [],
};
}
export function changeQuestionnaireSpecialization(
draft: QuestionnaireDraft,
id: string,
specialization: SpecializationCode | "",
): QuestionnaireDraft {
return {
...draft,
specializations: draft.specializations.map((item) =>
item.id === id ? { ...createQuestionnaireSpecializationDraft(id), specialization } : item,
),
};
}
export function patchQuestionnaireSpecialization(
draft: QuestionnaireDraft,
id: string,
patch: Partial<Omit<QuestionnaireSpecializationDraft, "id" | "specialization">>,
): QuestionnaireDraft {
return {
...draft,
specializations: draft.specializations.map((item) =>
item.id === id ? { ...item, ...patch } : item,
),
};
}
export function addQuestionnaireSpecialization(
draft: QuestionnaireDraft,
id: string,
): QuestionnaireDraft {
if (draft.specializations.length >= 2) return draft;
return {
...draft,
specializations: [...draft.specializations, createQuestionnaireSpecializationDraft(id)],
};
}
export function removeQuestionnaireSpecialization(
draft: QuestionnaireDraft,
id: string,
): QuestionnaireDraft {
if (draft.specializations.length <= 1) return draft;
return {
...draft,
specializations: draft.specializations.filter((item) => item.id !== id),
};
}
export function toggleQuestionnaireWorkFormat(
draft: QuestionnaireDraft,
format: WorkFormat,
): QuestionnaireDraft {
const selected = draft.workFormats.includes(format);
if (selected) {
return { ...draft, workFormats: draft.workFormats.filter((item) => item !== format) };
}
if (draft.workFormats.length >= 3) return draft;
return { ...draft, workFormats: [...draft.workFormats, format] };
}
export function addQuestionnaireStackTag(
draft: QuestionnaireDraft,
id: string,
): { draft: QuestionnaireDraft; issue: QuestionnaireFormIssue | null } {
const item = draft.specializations.find((specialization) => specialization.id === id);
if (!item) return { draft, issue: null };
const tag = item.stackInput.trim();
const field = `specializations.${draft.specializations.indexOf(item)}.stack`;
if (!tag) return { draft, issue: { field, message: "Введите название технологии." } };
if (Array.from(tag).length > 50) {
return {
draft,
issue: { field, message: "Название технологии должно быть не длиннее 50 символов." },
};
}
if (/[\r\n]/.test(tag)) {
return { draft, issue: { field, message: "Укажите одну технологию в одной строке." } };
}
if (item.stack.some((existing) => existing.toLowerCase() === tag.toLowerCase())) {
return { draft, issue: { field, message: "Эта технология уже добавлена." } };
}
if (item.stack.length >= 20) {
return { draft, issue: { field, message: "Можно добавить не больше 20 технологий." } };
}
return {
draft: patchQuestionnaireSpecialization(draft, id, {
stack: [...item.stack, tag],
stackInput: "",
}),
issue: null,
};
}
export function removeQuestionnaireStackTag(
draft: QuestionnaireDraft,
id: string,
tag: string,
): QuestionnaireDraft {
const item = draft.specializations.find((specialization) => specialization.id === id);
if (!item) return draft;
return patchQuestionnaireSpecialization(draft, id, {
stack: item.stack.filter((value) => value !== tag),
});
}
function parseMonths(
value: string,
field: string,
issues: QuestionnaireFormIssue[],
): number | null {
if (!/^\d+$/.test(value)) {
issues.push({ field, message: "Укажите целое число месяцев от 0 до 600." });
return null;
}
const months = Number(value);
if (!Number.isSafeInteger(months) || months > 600) {
issues.push({ field, message: "Укажите целое число месяцев от 0 до 600." });
return null;
}
return months;
}
export function buildCandidateQuestionnaireUpdate(
draft: QuestionnaireDraft,
catalog: SpecializationCatalog,
expectedVersion = draft.expectedVersion,
): QuestionnaireBuildResult {
const issues: QuestionnaireFormIssue[] = [];
const specializations: QuestionnaireAnswer[] = [];
const seenSpecializations = new Set<SpecializationCode>();
if (draft.specializations.length < 1 || draft.specializations.length > 2) {
issues.push({ field: "specializations", message: "Выберите одну или две специализации." });
}
draft.specializations.forEach((item, index) => {
const base = `specializations.${index}`;
if (!item.specialization) {
issues.push({ field: `${base}.specialization`, message: "Выберите специализацию." });
return;
}
if (seenSpecializations.has(item.specialization)) {
issues.push({ field: `${base}.specialization`, message: "Эта специализация уже выбрана." });
return;
}
seenSpecializations.add(item.specialization);
const option = findSpecializationOption(catalog, item.specialization);
if (!option) {
issues.push({
field: `${base}.specialization`,
message: "Выберите специализацию из каталога.",
});
return;
}
if (!item.selfAssessedGrade) {
issues.push({ field: `${base}.selfAssessedGrade`, message: "Укажите свою оценку уровня." });
return;
}
const languagesAllowed = new Set(option.test_availability.task_languages);
item.taskLanguages.forEach((language, languageIndex) => {
if (!languagesAllowed.has(language)) {
issues.push({
field: `${base}.taskLanguages`,
message:
"Выбранный язык заданий больше не предлагается. Снимите этот выбор перед сохранением.",
});
}
if (item.taskLanguages.indexOf(language) !== languageIndex) {
issues.push({
field: `${base}.taskLanguages`,
message: "Не выбирайте язык заданий повторно.",
});
}
});
if (item.taskLanguages.length > 2) {
issues.push({
field: `${base}.taskLanguages`,
message: "Выберите не больше двух языков заданий.",
});
}
const seenStack = new Set<string>();
item.stack.forEach((tag, tagIndex) => {
const tagField = `${base}.stack.${tagIndex}`;
if (!tag || tag !== tag.trim() || /[\r\n]/.test(tag) || Array.from(tag).length > 50) {
issues.push({
field: tagField,
message: "Проверьте название технологии: до 50 символов, без пробелов по краям.",
});
}
const normalized = tag.toLowerCase();
if (seenStack.has(normalized)) {
issues.push({ field: tagField, message: "Эта технология уже добавлена." });
}
seenStack.add(normalized);
});
if (item.stack.length > 20) {
issues.push({ field: `${base}.stack`, message: "Можно добавить не больше 20 технологий." });
}
let experience: QuestionnaireAnswer["experience"] = null;
if (item.hasExperience) {
const commercialMonths = parseMonths(
item.commercialMonths,
`${base}.commercialMonths`,
issues,
);
const academicMonths = parseMonths(item.academicMonths, `${base}.academicMonths`, issues);
if (commercialMonths !== null && academicMonths !== null) {
experience = { commercial_months: commercialMonths, academic_months: academicMonths };
}
}
specializations.push({
specialization: item.specialization,
self_assessed_grade: item.selfAssessedGrade,
task_languages: [...item.taskLanguages],
stack: [...item.stack],
experience,
});
});
if (draft.workFormats.length < 1 || draft.workFormats.length > 3) {
issues.push({ field: "workFormats", message: "Выберите от одного до трех форматов работы." });
}
if (new Set(draft.workFormats).size !== draft.workFormats.length) {
issues.push({ field: "workFormats", message: "Не выбирайте формат работы повторно." });
}
if (issues.length > 0) return { data: null, issues };
const candidate: CandidateQuestionnaireUpdate = {
expected_version: expectedVersion,
specializations,
work_context: { work_formats: [...draft.workFormats] },
};
const parsed = CandidateQuestionnaireUpdateSchema.safeParse(candidate);
if (!parsed.success) {
return {
data: null,
issues: parsed.error.issues.map((issue) => ({
field: issue.path.join("."),
message: "Проверьте это значение.",
})),
};
}
return { data: parsed.data, issues: [] };
}
function fieldForPointer(pointer: string): string {
const match = /^\/specializations\/(\d+)(?:\/([^/]+))?/.exec(pointer);
if (match) {
const [, index, property] = match;
switch (property) {
case "specialization":
return `specializations.${index}.specialization`;
case "self_assessed_grade":
return `specializations.${index}.selfAssessedGrade`;
case "task_languages":
return `specializations.${index}.taskLanguages`;
case "stack":
return `specializations.${index}.stack`;
case "experience":
return `specializations.${index}.experience`;
default:
return `specializations.${index}`;
}
}
if (pointer.startsWith("/work_context/work_formats")) return "workFormats";
return "form";
}
export function mapQuestionnaireServerErrors(
errors: readonly ProblemFieldError[],
): QuestionnaireFormIssue[] {
return errors.map((error) => ({
field: fieldForPointer(error.pointer),
message: "Сервер не принял это значение. Проверьте выбор и повторите сохранение.",
}));
}
@@ -0,0 +1,94 @@
import { QueryClient } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import type { CandidateQuestionnaire, Session } from "../../../shared/api/schemas";
import { activeSessionMatches, storeQuestionnaireForActiveSession } from "./session-guard";
const session: Session = {
account: {
id: "22b209a8-8715-4ad5-a9b0-d93a18fc70a4",
email: "candidate@example.test",
email_verified: true,
scenario: "candidate",
onboarding_step: "candidate_questionnaire",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: "a".repeat(32),
};
const otherSession: Session = {
...session,
account: {
...session.account,
id: "36acbba3-d786-4c3a-95b2-4c374ab3206e",
email: "other@example.test",
},
csrf_token: "b".repeat(32),
};
const questionnaire: CandidateQuestionnaire = {
version: 1,
specializations: [],
work_context: null,
updated_at: "2026-10-07T12:00:00Z",
};
describe("questionnaire session guard", () => {
it("rejects cached session data after its query enters an error state", () => {
expect(
activeSessionMatches(
{
data: session,
status: "error",
},
session,
),
).toBe(false);
});
it("does not write a late save response after the active account changes", () => {
const queryClient = new QueryClient();
const sessionKey = ["/api/v1/identity/sessions/current"];
const firstQuestionnaireKey = ["/api/v1/me/questionnaire", session.account.id];
const currentQuestionnaireKey = ["/api/v1/me/questionnaire", otherSession.account.id];
queryClient.setQueryData(sessionKey, session);
queryClient.setQueryData(currentQuestionnaireKey, questionnaire);
queryClient.setQueryData(sessionKey, otherSession);
const stored = storeQuestionnaireForActiveSession(
queryClient,
sessionKey,
session,
firstQuestionnaireKey,
questionnaire,
);
expect(stored).toBe(false);
expect(queryClient.getQueryData(firstQuestionnaireKey)).toBeUndefined();
expect(queryClient.getQueryData(currentQuestionnaireKey)).toEqual(questionnaire);
});
it("accepts the same actor during a background session refetch", () => {
const state = {
data: session,
status: "success",
fetchStatus: "fetching",
isInvalidated: true,
} as const;
expect(activeSessionMatches(state, session)).toBe(true);
});
it("rejects a different actor or a rotated CSRF token", () => {
const state = {
data: session,
status: "success",
fetchStatus: "fetching",
isInvalidated: true,
} as const;
expect(activeSessionMatches(state, otherSession)).toBe(false);
expect(
activeSessionMatches({ ...state, data: { ...session, csrf_token: "c".repeat(32) } }, session),
).toBe(false);
});
});
@@ -0,0 +1,31 @@
import type { QueryClient, QueryKey, QueryState } from "@tanstack/react-query";
import type { CandidateQuestionnaire, Session } from "../../../shared/api/schemas";
type SessionQuerySnapshot = Pick<QueryState<Session, Error>, "data" | "status">;
export function activeSessionMatches(
snapshot: SessionQuerySnapshot | undefined,
actor: Session,
): boolean {
return Boolean(
snapshot &&
snapshot.status === "success" &&
snapshot.data &&
snapshot.data.account.id === actor.account.id &&
snapshot.data.csrf_token === actor.csrf_token,
);
}
export function storeQuestionnaireForActiveSession(
queryClient: QueryClient,
sessionQueryKey: QueryKey,
actor: Session,
questionnaireQueryKey: QueryKey,
questionnaire: CandidateQuestionnaire,
): boolean {
if (!activeSessionMatches(queryClient.getQueryState<Session>(sessionQueryKey), actor)) {
return false;
}
queryClient.setQueryData(questionnaireQueryKey, questionnaire);
return true;
}
@@ -0,0 +1,72 @@
.root {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.root > section {
min-width: 0;
}
.server-step,
.warning,
.form-error,
.conflict,
.continuation {
min-width: 0;
margin: 0 0 var(--space-4);
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
overflow-wrap: anywhere;
}
.server-step {
color: var(--color-text-secondary);
}
.warning,
.form-error,
.conflict {
border-width: var(--line-strong);
border-color: var(--color-danger);
}
.warning,
.conflict {
display: grid;
gap: var(--space-3);
}
.warning p,
.conflict p,
.continuation p {
margin: 0;
line-height: var(--line-height-body);
}
.conflict h2 {
margin: 0;
font-size: var(--font-size-l);
}
.conflict-actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
min-width: 0;
}
.continuation {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
align-items: center;
justify-content: space-between;
margin: var(--space-5) 0 0;
}
.continuation p {
flex: 1 1 16rem;
}
@@ -0,0 +1,547 @@
import { useEffect, useRef, useState } from "react";
import { useQueryClient, type QueryKey, type UseQueryResult } from "@tanstack/react-query";
import { ApiRequestError } from "../../../shared/api";
import {
type GetMyQuestionnaireQueryError,
type GetMyQuestionnaireQueryResult,
getGetMyQuestionnaireQueryKey,
useGetMyQuestionnaire,
useSaveMyQuestionnaire,
} from "../../../shared/api/endpoints/candidate/candidate";
import {
type GetSpecializationCatalogQueryError,
type GetSpecializationCatalogQueryResult,
useGetSpecializationCatalog,
} from "../../../shared/api/endpoints/catalog/catalog";
import {
type GetCurrentSessionQueryError,
type GetCurrentSessionQueryResult,
getGetCurrentSessionQueryKey,
useGetCurrentSession,
} from "../../../shared/api/endpoints/identity/identity";
import type {
Account,
CandidateQuestionnaire,
Session,
SpecializationCatalog,
} from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import {
Button,
ButtonLink,
ErrorState,
ForbiddenState,
LoadingState,
Section,
} from "../../../shared/ui";
import {
buildCandidateQuestionnaireUpdate,
mapQuestionnaireServerErrors,
toQuestionnaireDraft,
type QuestionnaireDraft,
type QuestionnaireFormIssue,
} from "../model/questionnaire-form";
import { activeSessionMatches, storeQuestionnaireForActiveSession } from "../model/session-guard";
import { QuestionnaireForm } from "./questionnaire-form";
import styles from "./fill-questionnaire.module.css";
type QuestionnaireQuery = UseQueryResult<
GetMyQuestionnaireQueryResult,
GetMyQuestionnaireQueryError
>;
type CatalogQuery = UseQueryResult<
GetSpecializationCatalogQueryResult,
GetSpecializationCatalogQueryError
>;
type SessionQuery = UseQueryResult<GetCurrentSessionQueryResult, GetCurrentSessionQueryError>;
type OnboardingStep = Account["onboarding_step"];
function stepLabel(step: OnboardingStep): string {
switch (step) {
case "candidate_consents":
return "Согласия";
case "candidate_profile":
return "Профиль";
case "candidate_questionnaire":
return "Анкета";
case "candidate_assessment":
return "Оценка навыков";
case "employer_company":
return "Компания";
case "completed":
return "Завершено";
}
}
function isAccessError(error: unknown): error is ApiRequestError {
return error instanceof ApiRequestError && (error.status === 401 || error.status === 403);
}
function actorMatches(queryClient: ReturnType<typeof useQueryClient>, actor: Session): boolean {
return activeSessionMatches(
queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey()),
actor,
);
}
export function FillQuestionnaire() {
const queryClient = useQueryClient();
const session = useGetCurrentSession();
const accountId = session.data?.account.id ?? null;
const accountIsCandidate = session.data?.account.scenario === "candidate";
const [deniedActor, setDeniedActor] = useState<{ accountId: string; csrfToken: string } | null>(
null,
);
const actorIsDenied = Boolean(
session.data &&
deniedActor?.accountId === session.data.account.id &&
deniedActor.csrfToken === session.data.csrf_token,
);
const questionnaireQueryKey: QueryKey = accountId
? [...getGetMyQuestionnaireQueryKey(), accountId]
: [...getGetMyQuestionnaireQueryKey(), "anonymous"];
const questionnaire = useGetMyQuestionnaire({
query: {
queryKey: questionnaireQueryKey,
enabled: Boolean(accountId && accountIsCandidate && !session.isError && !actorIsDenied),
gcTime: 0,
staleTime: 0,
refetchOnMount: "always",
retry: false,
},
});
const catalog = useGetSpecializationCatalog({
query: {
staleTime: 5 * 60 * 1000,
retry: false,
},
});
const questionnaireAccessError = questionnaire.isError && isAccessError(questionnaire.error);
const sessionAccessError = session.isError && isAccessError(session.error);
const refetchSession = session.refetch;
useEffect(() => {
if (sessionAccessError) {
queryClient.removeQueries({ queryKey: questionnaire.queryKey, exact: true });
}
if (
questionnaireAccessError &&
questionnaire.error instanceof ApiRequestError &&
questionnaire.error.status === 401
) {
void refetchSession();
}
}, [
questionnaireAccessError,
questionnaire.error,
questionnaire.queryKey,
queryClient,
refetchSession,
sessionAccessError,
]);
if (sessionAccessError) {
return (
<ForbiddenState
error={session.error}
title="Анкета недоступна"
description="Не удалось проверить текущий вход. Войдите снова, чтобы продолжить."
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
/>
);
}
if (session.isError) {
return (
<ErrorState
error={session.error}
isRetrying={session.isRefetching}
onRetry={() => void session.refetch()}
title="Не удалось проверить текущий вход"
/>
);
}
if (session.isPending || !session.data) {
return <LoadingState label="Проверяем вход и загружаем анкету..." />;
}
if (session.data.account.scenario !== "candidate") {
return (
<ForbiddenState
title="Анкета кандидата недоступна"
description="Войдите в кабинет, связанный со сценарием кандидата."
/>
);
}
if (actorIsDenied) {
return (
<ForbiddenState
title="Анкета недоступна"
description="Сервер запретил доступ к анкете. Войдите снова, чтобы проверить права."
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
/>
);
}
if (questionnaire.isPending && !questionnaire.data) {
return <LoadingState label="Загружаем сохраненные ответы..." />;
}
if (questionnaireAccessError) {
return (
<ForbiddenState
error={questionnaire.error}
title="Анкета недоступна"
description="Сервер не подтвердил доступ к анкете кандидата. Войдите снова или повторите проверку входа."
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
/>
);
}
if (!questionnaire.data) {
return (
<ErrorState
error={questionnaire.error}
isRetrying={questionnaire.isRefetching}
onRetry={() => void questionnaire.refetch()}
title="Не удалось загрузить ответы"
/>
);
}
if (catalog.isPending && !catalog.data) {
return <LoadingState label="Загружаем каталог специализаций..." />;
}
if (!catalog.data) {
return (
<ErrorState
error={catalog.error}
isRetrying={catalog.isRefetching}
onRetry={() => void catalog.refetch()}
title="Не удалось загрузить каталог специализаций"
/>
);
}
return (
<QuestionnaireEditor
key={session.data.account.id}
actor={session.data}
questionnaire={questionnaire}
questionnaireQueryKey={questionnaireQueryKey}
catalog={catalog.data}
catalogQuery={catalog}
sessionQuery={session}
queryClient={queryClient}
onAccessDenied={() =>
setDeniedActor({
accountId: session.data.account.id,
csrfToken: session.data.csrf_token,
})
}
/>
);
}
type QuestionnaireEditorProps = {
actor: Session;
questionnaire: QuestionnaireQuery;
questionnaireQueryKey: QueryKey;
catalog: SpecializationCatalog;
catalogQuery: CatalogQuery;
sessionQuery: SessionQuery;
queryClient: ReturnType<typeof useQueryClient>;
onAccessDenied: () => void;
};
function QuestionnaireEditor({
actor,
questionnaire,
questionnaireQueryKey,
catalog,
catalogQuery,
sessionQuery,
queryClient,
onAccessDenied,
}: QuestionnaireEditorProps) {
const [draft, setDraft] = useState<QuestionnaireDraft>(() =>
toQuestionnaireDraft(questionnaire.data as CandidateQuestionnaire),
);
const [issues, setIssues] = useState<QuestionnaireFormIssue[]>([]);
const [formError, setFormError] = useState<string | null>(null);
const [saveState, setSaveState] = useState<"idle" | "saving" | "saved" | "failed">("idle");
const [canRetry, setCanRetry] = useState(false);
const [conflict, setConflict] = useState(false);
const [latest, setLatest] = useState<CandidateQuestionnaire | null>(null);
const [latestLoadError, setLatestLoadError] = useState(false);
const [savedStep, setSavedStep] = useState<OnboardingStep | null>(null);
const saveInFlight = useRef(false);
const saveMutation = useSaveMyQuestionnaire({
request: { headers: { "X-CSRF-Token": actor.csrf_token } },
mutation: { gcTime: 0 },
});
const currentStep = sessionQuery.data?.account.onboarding_step;
const catalogUnavailable = catalogQuery.isError;
function changeDraft(next: QuestionnaireDraft) {
setDraft(next);
setIssues([]);
setFormError(null);
setCanRetry(false);
setSaveState("idle");
setSavedStep(null);
}
async function refreshLatest(): Promise<CandidateQuestionnaire | null> {
setLatestLoadError(false);
const refreshed = await questionnaire.refetch();
if (!actorMatches(queryClient, actor)) return null;
if (!refreshed.data || refreshed.isError) {
setLatestLoadError(true);
return null;
}
setLatest(refreshed.data);
return refreshed.data;
}
async function submit(expectedVersion = draft.expectedVersion) {
if (
!sessionQuery.data ||
!actorMatches(queryClient, actor) ||
catalogUnavailable ||
saveInFlight.current
) {
return;
}
const result = buildCandidateQuestionnaireUpdate(draft, catalog, expectedVersion);
setIssues(result.issues);
setFormError(null);
setSavedStep(null);
setCanRetry(false);
if (!result.data) {
setSaveState("failed");
return;
}
saveInFlight.current = true;
setSaveState("saving");
try {
const saved = await saveMutation.mutateAsync({ data: result.data });
const savedForCurrentActor = storeQuestionnaireForActiveSession(
queryClient,
getGetCurrentSessionQueryKey(),
actor,
questionnaireQueryKey,
saved,
);
if (!savedForCurrentActor) {
setSaveState("failed");
if (
queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey())?.account.id ===
actor.account.id
) {
setFormError("Не удалось подтвердить текущий вход. Повторите проверку и сохранение.");
}
return;
}
setDraft(toQuestionnaireDraft(saved));
setIssues([]);
setConflict(false);
setLatest(null);
setLatestLoadError(false);
setSaveState("saved");
const refreshedSession = await sessionQuery.refetch();
if (
refreshedSession.data &&
!refreshedSession.isError &&
refreshedSession.data.account.id === actor.account.id &&
activeSessionMatches(
queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey()),
refreshedSession.data,
)
) {
setSavedStep(refreshedSession.data.account.onboarding_step);
} else if (!refreshedSession.isError && actorMatches(queryClient, actor)) {
setFormError("Анкета сохранена. Не удалось проверить сохраненный шаг аккаунта.");
}
} catch (error: unknown) {
if (!actorMatches(queryClient, actor)) {
setSaveState("failed");
if (
queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey())?.account.id ===
actor.account.id
) {
setFormError("Не удалось подтвердить текущий вход. Повторите проверку и сохранение.");
}
return;
}
setSaveState("failed");
if (error instanceof ApiRequestError && error.status === 412) {
setConflict(true);
setLatest(null);
setLatestLoadError(false);
setFormError(null);
await refreshLatest();
return;
}
if (error instanceof ApiRequestError && error.status === 400) {
const serverIssues = mapQuestionnaireServerErrors(error.fieldErrors);
setIssues(serverIssues);
setFormError(
serverIssues.length === 0
? "Сервер не сохранил изменения. Проверьте ответы и повторите попытку."
: null,
);
void catalogQuery.refetch();
return;
}
if (error instanceof ApiRequestError && error.status === 403) {
if (error.code === "csrf_check_failed") {
const refreshed = await sessionQuery.refetch();
if (
!refreshed.isError &&
refreshed.data?.account.id === actor.account.id &&
activeSessionMatches(
queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey()),
refreshed.data,
)
) {
setFormError(
"Проверка входа обновлена. Ответы остались в форме, повторите сохранение.",
);
} else if (!refreshed.isError && actorMatches(queryClient, actor)) {
setFormError("Не удалось подтвердить текущий вход. Повторите проверку.");
}
return;
}
queryClient.removeQueries({ queryKey: questionnaireQueryKey, exact: true });
onAccessDenied();
return;
}
if (error instanceof ApiRequestError && error.status === 401) {
setFormError("Вход больше не подтвержден. Войдите снова, чтобы продолжить.");
void sessionQuery.refetch();
return;
}
setCanRetry(true);
setFormError("Не удалось сохранить анкету. Проверьте подключение и повторите попытку.");
} finally {
saveInFlight.current = false;
}
}
function handleDraftIssue(issue: QuestionnaireFormIssue) {
setIssues([issue]);
setFormError(null);
setSaveState("failed");
setCanRetry(false);
}
function loadLatestAndDiscardDraft() {
if (!latest) return;
changeDraft(toQuestionnaireDraft(latest));
setConflict(false);
setLatest(null);
setLatestLoadError(false);
setFormError(null);
}
const onboardingDestination =
savedStep === "candidate_assessment" ? paths.candidate.assessment : null;
return (
<div className={styles.root}>
<Section
title="Ответы кандидата"
description="Выберите специализации, укажите самооценку и подходящие форматы работы. Эти ответы не подтверждают грейд и не требуют ФСП."
>
{currentStep ? (
<p className={styles["server-step"]}>
Шаг аккаунта на сервере: <strong>{stepLabel(currentStep)}</strong>.
</p>
) : null}
{catalogUnavailable ? (
<div className={styles.warning} role="alert">
<p>Не удалось обновить каталог. Показаны последние загруженные сведения.</p>
<Button
variant="secondary"
isBusy={catalogQuery.isRefetching}
onClick={() => void catalogQuery.refetch()}
>
{catalogQuery.isRefetching ? "Обновляем каталог..." : "Повторить загрузку каталога"}
</Button>
</div>
) : null}
{formError ? (
<div className={styles["form-error"]} role="alert">
{formError}
</div>
) : null}
{conflict ? (
<div
className={styles.conflict}
role="alert"
aria-labelledby="questionnaire-conflict-title"
>
<h2 id="questionnaire-conflict-title">Анкета изменилась в другом окне</h2>
<p>
Черновик этой формы сохранен в памяти и не отправлен повторно. Выберите, какие ответы
оставить. Перезапись отправит весь черновик поверх актуальной анкеты.
</p>
{latestLoadError ? (
<p>Не удалось загрузить актуальные ответы. Ваш черновик остается в форме.</p>
) : null}
{latest ? <p>Последняя прочитанная серверная версия: {latest.version}.</p> : null}
<div className={styles["conflict-actions"]}>
<Button
variant="primary"
isBusy={saveState === "saving" || questionnaire.isRefetching}
disabled={!latest || latestLoadError}
onClick={() => void submit(latest?.version ?? draft.expectedVersion)}
>
Записать этот черновик поверх актуальной анкеты
</Button>
<Button
variant="secondary"
isBusy={questionnaire.isRefetching}
onClick={() => void refreshLatest()}
>
{questionnaire.isRefetching ? "Загружаем ответы..." : "Загрузить актуальные ответы"}
</Button>
<Button
variant="quiet"
disabled={!latest || questionnaire.isRefetching || saveState === "saving"}
onClick={loadLatestAndDiscardDraft}
aria-describedby="questionnaire-conflict-discard-hint"
>
Заменить черновик актуальными ответами
</Button>
</div>
<p id="questionnaire-conflict-discard-hint">
Замена удалит введенные в этой форме изменения.
</p>
</div>
) : null}
<QuestionnaireForm
draft={draft}
catalog={catalog}
issues={issues}
isSaving={saveState === "saving"}
isForbidden={false}
isConflict={conflict}
canRetry={canRetry}
onDraftChange={changeDraft}
onIssue={handleDraftIssue}
onSubmit={() => void submit()}
/>
{saveState === "saved" ? (
<div className={styles.continuation} role="status">
<p>
Анкета сохранена. Сервер подтвердил шаг аккаунта:{" "}
{savedStep ? stepLabel(savedStep) : "не удалось прочитать"}.
</p>
{onboardingDestination ? (
<ButtonLink to={onboardingDestination} variant="secondary">
Перейти к следующему шагу
</ButtonLink>
) : null}
</div>
) : null}
</Section>
</div>
);
}
@@ -0,0 +1,239 @@
.form {
display: grid;
gap: var(--space-6);
min-width: 0;
}
.editor-fields {
display: grid;
gap: var(--space-6);
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.issue-summary {
min-width: 0;
padding: var(--space-4);
border: var(--line-strong) solid var(--color-danger);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.issue-summary:focus {
outline: var(--line-strong) solid var(--color-focus-ring);
outline-offset: 2px;
}
.issue-summary h2 {
margin: 0;
font-size: var(--font-size-l);
}
.issue-summary ul {
margin: var(--space-3) 0 0;
padding-left: var(--space-5);
}
.group,
.specialization,
.option-group {
display: grid;
gap: var(--space-4);
min-width: 0;
margin: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
}
.group legend,
.specialization legend,
.option-group legend {
max-width: 100%;
padding-inline: var(--space-2);
font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
overflow-wrap: anywhere;
}
.hint,
.availability p {
margin: 0;
color: var(--color-text-secondary);
line-height: var(--line-height-body);
}
.field {
display: grid;
gap: var(--space-2);
min-width: 0;
}
.field > label {
font-weight: var(--font-weight-bold);
}
.field input,
.field select {
box-sizing: border-box;
width: 100%;
min-width: 0;
max-width: 100%;
min-height: 2.75rem;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
font: inherit;
}
.error {
margin: 0;
color: var(--color-text);
font-size: var(--font-size-s);
font-weight: var(--font-weight-bold);
line-height: var(--line-height-body);
}
.availability {
display: grid;
gap: var(--space-2);
min-width: 0;
padding: var(--space-3);
border-inline-start: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
overflow-wrap: anywhere;
}
.availability-title {
color: var(--color-text);
font-weight: var(--font-weight-bold);
}
.check-list {
display: flex;
flex-wrap: wrap;
gap: var(--space-3) var(--space-5);
min-width: 0;
}
.check-item {
display: flex;
gap: var(--space-2);
align-items: flex-start;
min-width: 0;
line-height: var(--line-height-body);
overflow-wrap: anywhere;
}
.check-item input {
width: 1.25rem;
height: 1.25rem;
margin: 0.125rem 0 0;
flex: 0 0 auto;
}
.month-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--space-4);
min-width: 0;
}
.stack-input {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
align-items: flex-end;
min-width: 0;
}
.stack-input input {
flex: 1 1 15rem;
}
.field input:focus-visible,
.field select:focus-visible,
.check-item input:focus-visible {
outline: var(--line-strong) solid var(--color-focus-ring);
outline-offset: 2px;
}
.field input[aria-invalid="true"],
.field select[aria-invalid="true"] {
border-width: var(--line-strong);
border-color: var(--color-danger);
}
.tag-list {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
margin: 0;
padding: 0;
list-style: none;
}
.tag {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
align-items: center;
max-width: 100%;
padding: var(--space-2) var(--space-3);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-s);
overflow-wrap: anywhere;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
align-items: center;
justify-content: space-between;
min-width: 0;
}
.actions > .hint {
flex: 1 1 18rem;
}
.form-error {
margin: 0;
padding: var(--space-3);
border-inline-start: var(--line-strong) solid var(--color-danger);
background: var(--color-canvas);
line-height: var(--line-height-body);
}
@media (width < 48rem) {
.month-grid {
grid-template-columns: minmax(0, 1fr);
}
}
@media (width < 30rem) {
.group,
.specialization,
.option-group {
padding: var(--space-3);
}
.actions {
align-items: stretch;
flex-direction: column;
}
}
@@ -0,0 +1,115 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import type { CandidateQuestionnaire, SpecializationCatalog } from "../../../shared/api/schemas";
import {
changeQuestionnaireSpecialization,
patchQuestionnaireSpecialization,
toQuestionnaireDraft,
} from "../model/questionnaire-form";
import { QuestionnaireForm } from "./questionnaire-form";
const catalog: SpecializationCatalog = {
directions: [
{
code: "development",
title: "Разработка",
specializations: [
{
code: "backend",
title: "Backend",
test_availability: {
status: "available",
grades: ["junior"],
task_languages: ["python", "go"],
note: null,
},
},
],
},
{
code: "data",
title: "Данные",
specializations: [
{
code: "ds_ml",
title: "DS/ML",
test_availability: {
status: "in_development",
grades: [],
task_languages: [],
note: "Банк заданий готовится.",
},
},
],
},
],
grades: [
{ code: "intern", title: "Стажер" },
{ code: "junior", title: "Junior" },
{ code: "middle", title: "Middle" },
{ code: "senior", title: "Senior" },
],
};
const emptyQuestionnaire: CandidateQuestionnaire = {
version: 0,
specializations: [],
work_context: null,
updated_at: null,
};
function renderQuestionnaireForm(specialization: "backend" | "ds_ml"): string {
const base = toQuestionnaireDraft(emptyQuestionnaire);
const first = base.specializations[0];
if (!first) throw new Error("Expected the questionnaire to have one editing row.");
const selected = changeQuestionnaireSpecialization(base, first.id, specialization);
const draft = patchQuestionnaireSpecialization(selected, first.id, {
selfAssessedGrade: specialization === "backend" ? "junior" : "senior",
taskLanguages: specialization === "backend" ? ["go"] : [],
});
return renderToStaticMarkup(
<QuestionnaireForm
draft={draft}
catalog={catalog}
issues={[]}
isSaving={false}
isForbidden={false}
isConflict={false}
canRetry={false}
onDraftChange={() => undefined}
onIssue={() => undefined}
onSubmit={() => undefined}
/>,
);
}
describe("questionnaire form", () => {
it("renders current Backend task language and grade options with associated hints", () => {
const markup = renderQuestionnaireForm("backend");
const ids = new Set([...markup.matchAll(/\sid="([^"]+)"/g)].map((match) => match[1]));
const descriptions = [...markup.matchAll(/aria-describedby="([^"]+)"/g)].flatMap((match) =>
(match[1] ?? "").split(/\s+/),
);
expect(markup).toContain("Проверка опубликована для уровней: Junior.");
expect(markup).toContain("Python");
expect(markup).toContain("Go");
expect(markup).toContain("При смене выбора самооценка");
expect(descriptions.length).toBeGreaterThan(0);
expect(descriptions.every((id) => ids.has(id))).toBe(true);
expect(markup).not.toMatch(/ФСП|confirmed_grade|подтвержденный грейд/i);
});
it("allows an in-development specialization as a self-assessed claim without an assessment action", () => {
const markup = renderQuestionnaireForm("ds_ml");
expect(markup).toContain("Проверка: в разработке");
expect(markup).toContain(
"Эту специализацию можно сохранить. Начать проверку по ней пока нельзя.",
);
expect(markup).toContain("Банк заданий готовится.");
expect(markup).toContain('value="senior" selected=""');
expect(markup).not.toMatch(/<button\b[^>]*>[^<]*(?:Перейти|Начать) проверку/);
});
});
@@ -0,0 +1,634 @@
import { useEffect, useId, useRef, type FormEvent, type ReactNode } from "react";
import {
addQuestionnaireSpecialization,
addQuestionnaireStackTag,
changeQuestionnaireSpecialization,
patchQuestionnaireSpecialization,
removeQuestionnaireSpecialization,
removeQuestionnaireStackTag,
toggleQuestionnaireWorkFormat,
type QuestionnaireDraft,
type QuestionnaireFormIssue,
type QuestionnaireSpecializationDraft,
} from "../model/questionnaire-form";
import { findGradeTitle, findSpecializationOption } from "../../../entities/specialization";
import type {
SpecializationCatalog,
SpecializationCode,
TaskLanguage,
WorkFormat,
} from "../../../shared/api/schemas";
import { Button } from "../../../shared/ui";
import styles from "./questionnaire-form.module.css";
const workFormats: ReadonlyArray<{ value: WorkFormat; label: string }> = [
{ value: "remote", label: "Удаленно" },
{ value: "office", label: "В офисе" },
{ value: "hybrid", label: "Гибридно" },
];
const taskLanguageLabels: Record<TaskLanguage, string> = {
python: "Python",
go: "Go",
};
type QuestionnaireFormProps = {
draft: QuestionnaireDraft;
catalog: SpecializationCatalog;
issues: readonly QuestionnaireFormIssue[];
isSaving: boolean;
isForbidden: boolean;
isConflict: boolean;
canRetry: boolean;
onDraftChange: (draft: QuestionnaireDraft) => void;
onIssue: (issue: QuestionnaireFormIssue) => void;
onSubmit: () => void;
};
function issueFor(issues: readonly QuestionnaireFormIssue[], field: string): string | undefined {
return issues.find((issue) => issue.field === field)?.message;
}
function describeIds(id: string, hint: boolean, error: boolean): string | undefined {
const ids = [hint ? `${id}-hint` : "", error ? `${id}-error` : ""].filter(Boolean);
return ids.length > 0 ? ids.join(" ") : undefined;
}
function ErrorText({ id, children }: { id: string; children?: string | undefined }) {
return children ? (
<p className={styles.error} id={id}>
{children}
</p>
) : null;
}
function Field({
id,
label,
hint,
error,
children,
}: {
id: string;
label: string;
hint?: string | undefined;
error?: string | undefined;
children: ReactNode;
}) {
return (
<div className={styles.field}>
<label htmlFor={id}>{label}</label>
{hint ? (
<p className={styles.hint} id={`${id}-hint`}>
{hint}
</p>
) : null}
{children}
<ErrorText id={`${id}-error`}>{error}</ErrorText>
</div>
);
}
function StackTags({
draft,
item,
index,
error,
disabled,
prefix,
onDraftChange,
onIssue,
}: {
draft: QuestionnaireDraft;
item: QuestionnaireSpecializationDraft;
index: number;
error?: string | undefined;
disabled: boolean;
prefix: string;
onDraftChange: (draft: QuestionnaireDraft) => void;
onIssue: (issue: QuestionnaireFormIssue) => void;
}) {
const inputId = `${prefix}-stack-input`;
const helpId = `${inputId}-hint`;
const addTag = () => {
const result = addQuestionnaireStackTag(draft, item.id);
if (result.issue) {
onIssue(result.issue);
return;
}
onDraftChange(result.draft);
};
return (
<div className={styles.field}>
<label htmlFor={inputId}>Стек технологий</label>
<p className={styles.hint} id={helpId}>
Например, PostgreSQL или Kubernetes. Это не язык заданий и не уровень оценки.
</p>
<div className={styles["stack-input"]}>
<input
id={inputId}
value={item.stackInput}
maxLength={50}
disabled={disabled}
aria-invalid={Boolean(error)}
aria-describedby={describeIds(inputId, true, Boolean(error))}
onChange={(event) =>
onDraftChange(
patchQuestionnaireSpecialization(draft, item.id, {
stackInput: event.currentTarget.value,
}),
)
}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
addTag();
}
}}
/>
<Button variant="secondary" disabled={disabled || item.stack.length >= 20} onClick={addTag}>
Добавить технологию
</Button>
</div>
{item.stack.length > 0 ? (
<ul className={styles["tag-list"]} aria-label={`Технологии по специализации ${index + 1}`}>
{item.stack.map((tag) => (
<li className={styles.tag} key={`${tag}-${index}`}>
<span>{tag}</span>
<Button
variant="quiet"
disabled={disabled}
aria-label={`Удалить технологию ${tag}`}
onClick={() => onDraftChange(removeQuestionnaireStackTag(draft, item.id, tag))}
>
Удалить
</Button>
</li>
))}
</ul>
) : null}
<ErrorText id={`${inputId}-error`}>{error}</ErrorText>
</div>
);
}
function SpecializationCard({
draft,
item,
index,
catalog,
issues,
disabled,
prefix,
onDraftChange,
onIssue,
}: {
draft: QuestionnaireDraft;
item: QuestionnaireSpecializationDraft;
index: number;
catalog: SpecializationCatalog;
issues: readonly QuestionnaireFormIssue[];
disabled: boolean;
prefix: string;
onDraftChange: (draft: QuestionnaireDraft) => void;
onIssue: (issue: QuestionnaireFormIssue) => void;
}) {
const cardId = `${prefix}-specialization-${index}`;
const selectionId = `${cardId}-selection`;
const gradeId = `${cardId}-grade`;
const experienceToggleId = `${cardId}-experience-enabled`;
const commercialId = `${cardId}-commercial-months`;
const academicId = `${cardId}-academic-months`;
const taskLanguagesId = `${cardId}-task-languages`;
const selectedOption = findSpecializationOption(catalog, item.specialization);
const selectedElsewhere = new Set(
draft.specializations
.filter((candidate) => candidate.id !== item.id)
.map((candidate) => candidate.specialization)
.filter(Boolean),
);
const specialtyField = `specializations.${index}.specialization`;
const gradeField = `specializations.${index}.selfAssessedGrade`;
const languagesField = `specializations.${index}.taskLanguages`;
const stackError = issues.find((issue) =>
issue.field.startsWith(`specializations.${index}.stack`),
)?.message;
const offeredLanguages = selectedOption?.test_availability.task_languages ?? [];
const oldLanguages = item.taskLanguages.filter(
(language) => !offeredLanguages.includes(language),
);
const shownLanguages = [...new Set([...offeredLanguages, ...oldLanguages])];
function changeLanguage(language: TaskLanguage, selected: boolean) {
const next = selected
? [...item.taskLanguages, language]
: item.taskLanguages.filter((current) => current !== language);
onDraftChange(patchQuestionnaireSpecialization(draft, item.id, { taskLanguages: next }));
}
return (
<fieldset className={styles.specialization}>
<legend>Специализация {index + 1}</legend>
<p className={styles.hint}>
Самооценка описывает ваш выбор и не подтверждает грейд. Подтвержденную категорию определяет
только результат проверки.
</p>
<Field
id={selectionId}
label="Специализация"
hint="Выберите направление из актуального каталога. При смене выбора самооценка, языки заданий, стек и опыт для этой строки будут очищены."
error={issueFor(issues, specialtyField)}
>
<select
id={selectionId}
value={item.specialization}
aria-invalid={Boolean(issueFor(issues, specialtyField))}
aria-describedby={describeIds(
selectionId,
true,
Boolean(issueFor(issues, specialtyField)),
)}
onChange={(event) =>
onDraftChange(
changeQuestionnaireSpecialization(
draft,
item.id,
event.currentTarget.value as SpecializationCode | "",
),
)
}
>
<option value="">Выберите специализацию</option>
{item.specialization && !selectedOption ? (
<option value={item.specialization}>
{item.specialization} (нет в текущем каталоге)
</option>
) : null}
{catalog.directions.map((direction) => (
<optgroup key={direction.code} label={direction.title}>
{direction.specializations.map((option) => (
<option
key={option.code}
value={option.code}
disabled={selectedElsewhere.has(option.code)}
>
{option.title}
</option>
))}
</optgroup>
))}
</select>
</Field>
{selectedOption ? (
<div className={styles.availability} role="status">
{selectedOption.test_availability.status === "in_development" ? (
<>
<p className={styles["availability-title"]}>Проверка: в разработке</p>
<p>Эту специализацию можно сохранить. Начать проверку по ней пока нельзя.</p>
{selectedOption.test_availability.note ? (
<p>{selectedOption.test_availability.note}</p>
) : null}
</>
) : selectedOption.test_availability.grades.length > 0 ? (
<p>
Проверка опубликована для уровней:{" "}
{selectedOption.test_availability.grades
.map((grade) => findGradeTitle(catalog, grade))
.join(", ")}
.
</p>
) : (
<p>Сейчас нет опубликованных уровней проверки для этой специализации.</p>
)}
</div>
) : null}
<Field
id={gradeId}
label="Моя оценка уровня"
hint="Это самооценка. Она не присваивает подтвержденную категорию."
error={issueFor(issues, gradeField)}
>
<select
id={gradeId}
value={item.selfAssessedGrade}
disabled={!selectedOption}
aria-invalid={Boolean(issueFor(issues, gradeField))}
aria-describedby={describeIds(gradeId, true, Boolean(issueFor(issues, gradeField)))}
onChange={(event) =>
onDraftChange(
patchQuestionnaireSpecialization(draft, item.id, {
selfAssessedGrade: event.currentTarget
.value as QuestionnaireSpecializationDraft["selfAssessedGrade"],
}),
)
}
>
<option value="">Выберите уровень</option>
{catalog.grades.map((grade) => (
<option key={grade.code} value={grade.code}>
{grade.title}
</option>
))}
</select>
</Field>
<fieldset className={styles["option-group"]}>
<legend id={taskLanguagesId}>Язык заданий</legend>
<p className={styles.hint} id={`${taskLanguagesId}-hint`}>
Этот выбор относится к языку заданий проверки, а не к вашему стеку технологий.
</p>
{!selectedOption ? (
<p>Сначала выберите специализацию.</p>
) : shownLanguages.length > 0 ? (
<div className={styles["check-list"]}>
{shownLanguages.map((language) => {
const isOld = oldLanguages.includes(language);
const languageId = `${taskLanguagesId}-${language}`;
return (
<label className={styles["check-item"]} htmlFor={languageId} key={language}>
<input
id={languageId}
type="checkbox"
checked={item.taskLanguages.includes(language)}
disabled={!selectedOption}
aria-describedby={describeIds(
taskLanguagesId,
true,
Boolean(issueFor(issues, languagesField)),
)}
onChange={(event) => changeLanguage(language, event.currentTarget.checked)}
/>
<span>
{taskLanguageLabels[language]}
{isOld ? " (сейчас не предлагается)" : ""}
</span>
</label>
);
})}
</div>
) : (
<p>Для этой специализации сейчас не предлагаются варианты языка заданий.</p>
)}
<ErrorText id={`${taskLanguagesId}-error`}>{issueFor(issues, languagesField)}</ErrorText>
</fieldset>
<StackTags
draft={draft}
item={item}
index={index}
error={stackError}
disabled={disabled || !selectedOption}
prefix={cardId}
onDraftChange={onDraftChange}
onIssue={onIssue}
/>
<fieldset className={styles["option-group"]}>
<legend>Опыт в этой специализации</legend>
<label className={styles["check-item"]} htmlFor={experienceToggleId}>
<input
id={experienceToggleId}
type="checkbox"
checked={item.hasExperience}
disabled={!selectedOption}
onChange={(event) =>
onDraftChange(
patchQuestionnaireSpecialization(draft, item.id, {
hasExperience: event.currentTarget.checked,
}),
)
}
/>
<span>Указать опыт в месяцах</span>
</label>
{item.hasExperience ? (
<div className={styles["month-grid"]}>
<Field
id={commercialId}
label="Коммерческий опыт, месяцев"
hint="Допустимое значение: от 0 до 600."
error={issueFor(issues, `specializations.${index}.commercialMonths`)}
>
<input
id={commercialId}
type="number"
min={0}
max={600}
step={1}
inputMode="numeric"
value={item.commercialMonths}
disabled={!selectedOption}
aria-invalid={Boolean(
issueFor(issues, `specializations.${index}.commercialMonths`),
)}
aria-describedby={describeIds(
commercialId,
true,
Boolean(issueFor(issues, `specializations.${index}.commercialMonths`)),
)}
onChange={(event) =>
onDraftChange(
patchQuestionnaireSpecialization(draft, item.id, {
commercialMonths: event.currentTarget.value,
}),
)
}
/>
</Field>
<Field
id={academicId}
label="Учебный и академический опыт, месяцев"
hint="Допустимое значение: от 0 до 600."
error={issueFor(issues, `specializations.${index}.academicMonths`)}
>
<input
id={academicId}
type="number"
min={0}
max={600}
step={1}
inputMode="numeric"
value={item.academicMonths}
disabled={!selectedOption}
aria-invalid={Boolean(issueFor(issues, `specializations.${index}.academicMonths`))}
aria-describedby={describeIds(
academicId,
true,
Boolean(issueFor(issues, `specializations.${index}.academicMonths`)),
)}
onChange={(event) =>
onDraftChange(
patchQuestionnaireSpecialization(draft, item.id, {
academicMonths: event.currentTarget.value,
}),
)
}
/>
</Field>
</div>
) : (
<p className={styles.hint}>Можно оставить без указания.</p>
)}
</fieldset>
{draft.specializations.length > 1 ? (
<Button
variant="quiet"
disabled={disabled}
onClick={() => onDraftChange(removeQuestionnaireSpecialization(draft, item.id))}
aria-label={`Удалить специализацию ${index + 1}`}
>
Удалить специализацию
</Button>
) : null}
</fieldset>
);
}
export function QuestionnaireForm({
draft,
catalog,
issues,
isSaving,
isForbidden,
isConflict,
canRetry,
onDraftChange,
onIssue,
onSubmit,
}: QuestionnaireFormProps) {
const prefix = `questionnaire-${useId().replaceAll(":", "")}`;
const rowSequence = useRef(0);
const issueSummary = useRef<HTMLDivElement>(null);
const formDisabled = isSaving || isForbidden;
const generalIssue = issueFor(issues, "form");
useEffect(() => {
if (issues.length > 0) issueSummary.current?.focus();
}, [issues.length]);
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (issues.length > 0) issueSummary.current?.focus();
else event.currentTarget.querySelector<HTMLButtonElement>('button[type="submit"]')?.focus();
onSubmit();
}
return (
<form className={styles.form} onSubmit={handleSubmit} noValidate>
{issues.length > 0 ? (
<div
className={styles["issue-summary"]}
ref={issueSummary}
role="alert"
aria-labelledby={`${prefix}-issues-title`}
tabIndex={-1}
>
<h2 id={`${prefix}-issues-title`}>Проверьте анкету</h2>
<ul>
{issues.map((item, index) => (
<li key={`${item.field}-${index}`}>{item.message}</li>
))}
</ul>
</div>
) : null}
<fieldset className={styles["editor-fields"]} disabled={formDisabled}>
<legend className={styles["visually-hidden"]}>Ответы анкеты</legend>
<fieldset className={styles.group}>
<legend>Специализации</legend>
<p className={styles.hint}>
Выберите одну или две специализации. Самооценка и опыт сохраняются отдельно для каждой.
</p>
{draft.specializations.map((item, index) => (
<SpecializationCard
key={item.id}
draft={draft}
item={item}
index={index}
catalog={catalog}
issues={issues}
disabled={formDisabled}
prefix={prefix}
onDraftChange={onDraftChange}
onIssue={onIssue}
/>
))}
<ErrorText id={`${prefix}-specializations-error`}>
{issueFor(issues, "specializations")}
</ErrorText>
<Button
variant="secondary"
disabled={formDisabled || draft.specializations.length >= 2}
aria-describedby={`${prefix}-specialization-limit`}
onClick={() => {
const id = `${prefix}-row-${++rowSequence.current}`;
onDraftChange(addQuestionnaireSpecialization(draft, id));
}}
>
Добавить специализацию
</Button>
<p className={styles.hint} id={`${prefix}-specialization-limit`}>
Можно указать не больше двух специализаций.
</p>
</fieldset>
<fieldset className={styles.group}>
<legend>Подходящий формат работы</legend>
<p className={styles.hint}>
Укажите от одного до трех вариантов. Город, переезд и зарплата относятся к профилю.
</p>
<div className={styles["check-list"]}>
{workFormats.map((format) => {
const id = `${prefix}-format-${format.value}`;
return (
<label className={styles["check-item"]} htmlFor={id} key={format.value}>
<input
id={id}
type="checkbox"
checked={draft.workFormats.includes(format.value)}
onChange={() =>
onDraftChange(toggleQuestionnaireWorkFormat(draft, format.value))
}
/>
<span>{format.label}</span>
</label>
);
})}
</div>
<ErrorText id={`${prefix}-work-formats-error`}>
{issueFor(issues, "workFormats")}
</ErrorText>
</fieldset>
</fieldset>
{generalIssue ? (
<p className={styles["form-error"]} role="alert">
{generalIssue}
</p>
) : null}
<div className={styles.actions}>
<p className={styles.hint}>
Сохраненные ответы можно изменить. Данные черновика не записываются в браузерное
хранилище.
</p>
<Button
type="submit"
isBusy={isSaving}
disabled={isForbidden || isConflict}
aria-disabled={isForbidden || isConflict || undefined}
>
{isSaving
? "Сохраняем анкету..."
: canRetry
? "Повторить сохранение"
: "Сохранить анкету"}
</Button>
</div>
</form>
);
}
@@ -18,7 +18,7 @@ export function CandidateOnboardingPage() {
/>
);
}
if (step !== "candidate_consents" && step !== "candidate_questionnaire") {
if (step !== "candidate_consents") {
const destination = getOnboardingDestination(session.data.account);
if (destination === paths.candidate.onboarding) {
return (
@@ -32,28 +32,19 @@ export function CandidateOnboardingPage() {
return <Navigate to={destination} replace />;
}
const stepTitle = step === "candidate_consents" ? "Согласия" : "Анкета";
const description =
step === "candidate_consents"
? "Следующий сохраненный шаг - согласия кандидата. Согласие C1 уже было показано отдельно при регистрации."
: "Следующий сохраненный шаг - анкета кандидата. После ее сохранения сервер откроет следующий этап.";
return (
<Page title="Первые шаги" eyebrow="Кабинет кандидата">
<Section title={stepTitle} description={description}>
{step === "candidate_consents" ? (
<>
<p>
Состояние шага хранится на сервере. Просмотрите согласия и выберите каждое действие
отдельно.
</p>
<ButtonLink to={paths.candidate.privacy}>
Открыть согласия и настройки приватности
</ButtonLink>
</>
) : (
<p>Этот шаг сохранен в аккаунте и будет открыт после следующего входа.</p>
)}
<Section
title="Согласия"
description="Следующий сохраненный шаг - согласия кандидата. Согласие C1 уже было показано отдельно при регистрации."
>
<p>
Состояние шага хранится на сервере. Просмотрите согласия и выберите каждое действие
отдельно.
</p>
<ButtonLink to={paths.candidate.privacy}>
Открыть согласия и настройки приватности
</ButtonLink>
</Section>
</Page>
);
+1
View File
@@ -0,0 +1 @@
export { CompanyPage } from "./ui/company-page";
@@ -0,0 +1,106 @@
.directory-content {
display: grid;
gap: var(--space-6);
min-width: 0;
}
.directory-content[hidden] {
display: none;
}
.selector {
display: grid;
gap: var(--space-2);
max-width: 38rem;
}
.selector label {
font-weight: var(--font-weight-bold);
}
.selector select {
width: 100%;
min-width: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
font: inherit;
}
.selector select:focus-visible {
outline: var(--line-strong) solid var(--color-accent);
outline-offset: 2px;
}
.workspace {
display: grid;
gap: var(--space-6);
min-width: 0;
}
.workspace-state {
display: grid;
gap: var(--space-4);
min-width: 0;
}
.refresh-row {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-4);
align-items: center;
justify-content: space-between;
color: var(--color-text-secondary);
}
.verification {
display: grid;
gap: var(--space-3);
}
.facts {
display: grid;
grid-template-columns: minmax(8rem, max-content) minmax(0, 1fr);
gap: var(--space-2) var(--space-4);
}
.facts dt {
color: var(--color-text-secondary);
}
.facts dd {
overflow-wrap: anywhere;
}
.next-step {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
align-items: center;
justify-content: space-between;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
}
.load-more {
display: flex;
justify-content: center;
}
@media (width < 30rem) {
.facts {
grid-template-columns: minmax(0, 1fr);
}
.facts dd + dt {
padding-top: var(--space-2);
}
.next-step {
align-items: flex-start;
flex-direction: column;
}
}
@@ -0,0 +1,558 @@
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
getGetOrganizationQueryKey,
getListMyOrganizationsQueryKey,
listMyOrganizations,
useGetOrganization,
} from "../../../shared/api/endpoints/organization/organization";
import {
getGetCurrentSessionQueryKey,
useGetCurrentSession,
} from "../../../shared/api/endpoints/identity/identity";
import { ApiRequestError } from "../../../shared/api";
import type { MyOrganizationList, Organization, Session } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config/paths";
import {
Button,
ButtonLink,
EmptyState,
ErrorState,
ForbiddenState,
LoadingState,
Page,
Section,
TrustLevel,
} from "../../../shared/ui";
import {
CandidateCardPreview,
organizationBasisLabels,
organizationLevelLabels,
organizationTrustLevel,
} from "../../../entities/company";
import { CompanyEditor } from "../../../features/edit-company";
import styles from "./company-page.module.css";
const pageSize = 100;
const directoryBaseKey = getListMyOrganizationsQueryKey({ limit: pageSize });
type OrganizationDirectoryItem = MyOrganizationList["items"][number];
function isAccessLoss(error: unknown): error is ApiRequestError {
return (
error instanceof ApiRequestError &&
(error.status === 401 || error.status === 403 || error.status === 404)
);
}
function roleLabel(role: OrganizationDirectoryItem["membership"]["role"]): string {
switch (role) {
case "owner":
return "Владелец";
case "recruiter":
return "Рекрутер";
case "hiring_manager":
return "Менеджер по найму";
case "technical_expert":
return "Технический эксперт";
}
}
function formatDate(value: string): string {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
return new Intl.DateTimeFormat("ru-RU", {
dateStyle: "medium",
timeStyle: "short",
timeZone: "UTC",
}).format(date);
}
type CompanyWorkspaceProps = {
item: OrganizationDirectoryItem;
isAccessDenied: boolean;
isDirectoryFresh: boolean;
onAccessLost: (organizationId: string, error: ApiRequestError) => void;
onSaved: (organization: Organization) => Promise<void> | void;
};
function CompanyWorkspace({
item,
isAccessDenied,
isDirectoryFresh,
onAccessLost,
onSaved,
}: CompanyWorkspaceProps) {
const reportedAccessError = useRef(false);
const owner = item.membership.role === "owner" && item.membership.state === "active";
const organization = useGetOrganization(item.organization.id, {
query: {
enabled: owner && isDirectoryFresh && !isAccessDenied,
gcTime: 0,
staleTime: 0,
refetchOnMount: "always",
refetchOnWindowFocus: "always",
retry: false,
},
});
useEffect(() => {
if (!organization.isError || !isAccessLoss(organization.error)) {
if (!organization.isError) reportedAccessError.current = false;
return;
}
if (reportedAccessError.current) return;
reportedAccessError.current = true;
onAccessLost(item.organization.id, organization.error);
}, [item.organization.id, onAccessLost, organization.error, organization.isError]);
if (!owner) {
return (
<ForbiddenState
title="Действия владельца недоступны"
description="В этой версии профиль компании может открывать и менять только владелец."
/>
);
}
if (isAccessDenied) return null;
if (organization.isError && isAccessLoss(organization.error)) {
return <ForbiddenState error={organization.error} title="Профиль компании недоступен" />;
}
const requestIsPending = !isDirectoryFresh || organization.isLoading || organization.isFetching;
const accessError = organization.isError ? organization.error : null;
return (
<div className={styles["workspace-state"]}>
{accessError ? (
<ErrorState
error={accessError}
isRetrying={organization.isFetching}
onRetry={() => void organization.refetch()}
/>
) : null}
{requestIsPending ? (
<LoadingState
label={
isDirectoryFresh
? "Проверяем доступ и загружаем профиль..."
: "Проверяем доступ к компании..."
}
/>
) : null}
{organization.data ? (
<div hidden={requestIsPending || organization.isError}>
<CompanyDetails
organization={organization.data}
isRefreshing={organization.isFetching}
onRefresh={() => void organization.refetch()}
onSaved={onSaved}
onAccessLost={onAccessLostFor(item.organization.id, onAccessLost)}
/>
</div>
) : null}
{!requestIsPending && !organization.isError && !organization.data ? (
<EmptyState
title="Профиль компании не найден"
description="Обновите список компаний и выберите доступный контекст."
/>
) : null}
</div>
);
}
function onAccessLostFor(
organizationId: string,
onAccessLost: CompanyWorkspaceProps["onAccessLost"],
) {
return (error: ApiRequestError) => onAccessLost(organizationId, error);
}
type CompanyDetailsProps = {
organization: Organization;
isRefreshing: boolean;
onRefresh: () => void;
onSaved: CompanyWorkspaceProps["onSaved"];
onAccessLost: (error: ApiRequestError) => void;
};
function CompanyDetails({
organization,
isRefreshing,
onRefresh,
onSaved,
onAccessLost,
}: CompanyDetailsProps) {
return (
<div className={styles.workspace}>
<div className={styles["refresh-row"]}>
<p>Данные профиля регулярно сверяются с сервером.</p>
<Button variant="quiet" isBusy={isRefreshing} onClick={onRefresh}>
Обновить профиль
</Button>
</div>
<Section
title="Статус проверки"
description="Уровень и основание устанавливает сервер. Их нельзя изменить через форму компании."
>
<div className={styles.verification}>
<TrustLevel
level={organizationTrustLevel[organization.verification.level]}
label={organizationLevelLabels[organization.verification.level]}
/>
<dl className={styles.facts}>
<dt>Основание</dt>
<dd>{organizationBasisLabels[organization.verification.basis]}</dd>
<dt>Установлено</dt>
<dd>{formatDate(organization.verification.changed_at)}</dd>
</dl>
</div>
</Section>
<Section title="Данные компании">
<CompanyEditor
key={organization.id}
organization={organization}
onSaved={onSaved}
onAccessLost={onAccessLost}
/>
</Section>
<CandidateCardPreview card={organization.candidate_card} />
<div className={styles["next-step"]}>
<p>Профиль компании сохранен. Можно перейти к разделу потребностей.</p>
<ButtonLink to={paths.employer.needs} variant="secondary">
Перейти к потребностям
</ButtonLink>
</div>
</div>
);
}
export function CompanyPage() {
const queryClient = useQueryClient();
const session = useGetCurrentSession({ query: { retry: false } });
const sessionAccountId = session.data?.account.id ?? null;
const sessionCsrfToken = session.data?.csrf_token ?? null;
const sessionReady = Boolean(session.data) && !session.isFetching && !session.isError;
const directoryKey = useMemo(
() => [...directoryBaseKey, sessionAccountId ?? "no-session"] as const,
[sessionAccountId],
);
const deniedOrganizationIdsRef = useRef<ReadonlySet<string>>(new Set());
const previousAccountIdRef = useRef<string | null>(sessionAccountId);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [createMode, setCreateMode] = useState(false);
const [accessRefreshing, setAccessRefreshing] = useState(false);
const [savedTransition, setSavedTransition] = useState(false);
const [accessDeniedOrganizationId, setAccessDeniedOrganizationId] = useState<string | null>(null);
const [deniedOrganizationIds, setDeniedOrganizationIds] = useState<ReadonlySet<string>>(
() => new Set(),
);
const isCurrentSession = useCallback(() => {
if (!sessionAccountId || !sessionCsrfToken) return false;
const current = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
const state = queryClient.getQueryState(getGetCurrentSessionQueryKey());
return Boolean(
current &&
state?.status === "success" &&
current.account.id === sessionAccountId &&
current.csrf_token === sessionCsrfToken,
);
}, [queryClient, sessionAccountId, sessionCsrfToken]);
useEffect(() => {
if (previousAccountIdRef.current === sessionAccountId) return;
previousAccountIdRef.current = sessionAccountId;
deniedOrganizationIdsRef.current = new Set();
setDeniedOrganizationIds(new Set());
setSelectedId(null);
setCreateMode(false);
setAccessRefreshing(false);
setSavedTransition(false);
setAccessDeniedOrganizationId(null);
}, [sessionAccountId]);
const directory = useInfiniteQuery({
queryKey: directoryKey,
initialPageParam: undefined as string | undefined,
queryFn: ({ pageParam, signal }) =>
listMyOrganizations(
{ limit: pageSize, ...(pageParam ? { cursor: pageParam } : {}) },
{ signal },
),
getNextPageParam: (lastPage) =>
lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined,
gcTime: 0,
staleTime: 0,
refetchOnMount: "always",
refetchOnWindowFocus: "always",
retry: false,
enabled: sessionReady,
});
const refetchDirectory = directory.refetch;
const items = useMemo(
() => directory.data?.pages.flatMap((page) => page.items) ?? [],
[directory.data],
);
const selectedItem =
items.find((item) => item.organization.id === selectedId) ??
items.find((item) => item.membership.role === "owner") ??
items[0];
const selectedOrganizationDenied =
selectedItem !== undefined && deniedOrganizationIds.has(selectedItem.organization.id);
const isRefreshingDirectory = directory.isFetching && !directory.isFetchingNextPage;
const directoryFresh =
sessionReady &&
Boolean(directory.data) &&
!directory.isError &&
!isRefreshingDirectory &&
!accessRefreshing &&
!savedTransition;
const handleAccessLost = useCallback(
async (organizationId: string, error: ApiRequestError) => {
if (error.status !== 401 && error.status !== 403 && error.status !== 404) return;
if (!isCurrentSession()) return;
const denied = new Set(deniedOrganizationIdsRef.current);
denied.add(organizationId);
deniedOrganizationIdsRef.current = denied;
setDeniedOrganizationIds(denied);
setAccessDeniedOrganizationId(organizationId);
setAccessRefreshing(true);
try {
if (organizationId !== "") {
await queryClient.removeQueries({
queryKey: getGetOrganizationQueryKey(organizationId),
exact: true,
});
}
if (!isCurrentSession()) return;
const refreshed = await refetchDirectory();
if (!isCurrentSession()) return;
const refreshedItems = refreshed.data?.pages.flatMap((page) => page.items) ?? [];
if (!refreshedItems.some((item) => item.organization.id === organizationId)) {
setSelectedId(null);
}
} finally {
if (isCurrentSession()) setAccessRefreshing(false);
}
},
[isCurrentSession, queryClient, refetchDirectory],
);
const handleCreateAccessLost = useCallback(
async (error: ApiRequestError) => {
if (error.status !== 401 && error.status !== 403 && error.status !== 404) return;
if (!isCurrentSession()) return;
setAccessRefreshing(true);
try {
await refetchDirectory();
if (!isCurrentSession()) return;
} finally {
if (isCurrentSession()) setAccessRefreshing(false);
}
},
[isCurrentSession, refetchDirectory],
);
const handleRetryAccess = useCallback(
(organizationId: string) => {
if (!isCurrentSession()) return;
const denied = new Set(deniedOrganizationIdsRef.current);
denied.delete(organizationId);
deniedOrganizationIdsRef.current = denied;
setDeniedOrganizationIds(denied);
if (accessDeniedOrganizationId === organizationId) setAccessDeniedOrganizationId(null);
void queryClient.removeQueries({
queryKey: getGetOrganizationQueryKey(organizationId),
exact: true,
});
void queryClient.invalidateQueries({ queryKey: directoryKey, exact: true });
},
[accessDeniedOrganizationId, directoryKey, isCurrentSession, queryClient],
);
const handleSaved = useCallback(
async (organization: Organization) => {
if (!isCurrentSession()) return;
if (deniedOrganizationIdsRef.current.has(organization.id)) return;
const organizationQueryKey = getGetOrganizationQueryKey(organization.id);
const currentOrganizationQuery = queryClient.getQueryState(organizationQueryKey);
if (
currentOrganizationQuery?.status === "error" &&
isAccessLoss(currentOrganizationQuery.error)
) {
return;
}
queryClient.setQueryData(organizationQueryKey, organization);
const alreadyInDirectory = items.some((item) => item.organization.id === organization.id);
if (alreadyInDirectory) {
await refetchDirectory();
return;
}
setSavedTransition(true);
try {
const refreshed = await refetchDirectory();
if (!isCurrentSession()) return;
if (deniedOrganizationIdsRef.current.has(organization.id)) return;
if (refreshed.isError) throw refreshed.error;
const refreshedItems = refreshed.data?.pages.flatMap((page) => page.items) ?? [];
if (!refreshedItems.some((item) => item.organization.id === organization.id)) {
throw new Error("The saved company is not available in the refreshed directory.");
}
setSelectedId(organization.id);
setCreateMode(false);
} finally {
if (isCurrentSession()) setSavedTransition(false);
}
},
[isCurrentSession, items, queryClient, refetchDirectory],
);
const isDirectoryError = sessionReady && directory.isError;
const directoryErrorIsAccessLoss = isDirectoryError && isAccessLoss(directory.error);
const showLoading =
!session.isError &&
(!session.data ||
session.isFetching ||
directory.isLoading ||
isRefreshingDirectory ||
accessRefreshing ||
savedTransition ||
!directory.data);
return (
<Page
title="Компания"
eyebrow="Кабинет работодателя"
lead="Выберите компанию, управляйте ее карточкой и проверьте, как ее увидит кандидат."
width="wide"
>
{session.isError && !session.isFetching ? (
isAccessLoss(session.error) ? (
<ForbiddenState error={session.error} title="Текущий вход не подтвержден" />
) : (
<ErrorState
error={session.error}
isRetrying={session.isRefetching}
onRetry={() => void session.refetch()}
title="Не удалось проверить текущий вход"
/>
)
) : null}
{accessDeniedOrganizationId ? (
<ForbiddenState
title="Профиль компании недоступен"
description="Доступ к выбранной компании закрыт. Выберите другую компанию или создайте новую."
action={
<Button
variant="secondary"
onClick={() => handleRetryAccess(accessDeniedOrganizationId)}
>
Проверить доступ снова
</Button>
}
/>
) : null}
{showLoading ? (
<LoadingState label="Загружаем список компаний и проверяем доступ..." />
) : null}
{isDirectoryError ? (
directoryErrorIsAccessLoss ? (
<ForbiddenState error={directory.error} />
) : (
<ErrorState
error={directory.error}
isRetrying={directory.isFetching}
onRetry={() => void directory.refetch()}
/>
)
) : null}
{!directoryErrorIsAccessLoss && directory.data ? (
<div
className={styles["directory-content"]}
hidden={!directoryFresh || selectedOrganizationDenied}
>
{items.length > 0 ? (
<Section
title="Ваши компании"
description="Выбирайте только компании, в которых у вас есть активное членство."
>
<div className={styles.selector}>
<label htmlFor="company-directory">Компания</label>
<select
id="company-directory"
value={createMode ? "__create__" : (selectedItem?.organization.id ?? "")}
onChange={(event) => {
setAccessDeniedOrganizationId(null);
if (event.currentTarget.value === "__create__") {
setCreateMode(true);
} else {
setCreateMode(false);
setSelectedId(event.currentTarget.value);
}
}}
>
{items.map((item) => (
<option key={item.organization.id} value={item.organization.id}>
{item.organization.name} - {roleLabel(item.membership.role)}
</option>
))}
{items.some((item) => item.membership.role === "owner") ? (
<option value="__create__">Создать еще одну компанию</option>
) : null}
</select>
</div>
{createMode ? (
<Section title="Создать компанию">
<CompanyEditor
key={`create:${sessionAccountId ?? "no-session"}`}
onSaved={handleSaved}
onAccessLost={handleCreateAccessLost}
/>
<Button variant="quiet" onClick={() => setCreateMode(false)}>
Вернуться к выбранной компании
</Button>
</Section>
) : selectedItem ? (
<CompanyWorkspace
key={`${sessionAccountId ?? "no-session"}:${selectedItem.organization.id}`}
item={selectedItem}
isAccessDenied={deniedOrganizationIds.has(selectedItem.organization.id)}
isDirectoryFresh={directoryFresh}
onAccessLost={handleAccessLost}
onSaved={handleSaved}
/>
) : null}
</Section>
) : (
<Section title="Создать компанию">
<EmptyState
title="Компаний пока нет"
description="Создайте компанию, чтобы заполнить карточку и показать кандидатам основные сведения."
/>
<CompanyEditor
key={`create:${sessionAccountId ?? "no-session"}`}
onSaved={handleSaved}
onAccessLost={handleCreateAccessLost}
/>
</Section>
)}
{directory.hasNextPage ? (
<div className={styles["load-more"]}>
<Button
variant="secondary"
isBusy={directory.isFetchingNextPage}
onClick={() => void directory.fetchNextPage()}
>
{directory.isFetchingNextPage ? "Загружаем компании..." : "Показать еще компании"}
</Button>
</div>
) : null}
</div>
) : null}
</Page>
);
}
+1
View File
@@ -0,0 +1 @@
export { ProfilePage } from "./ui/profile-page";
@@ -0,0 +1,15 @@
import { EditProfile } from "../../../features/edit-profile";
import { Page } from "../../../shared/ui";
export function ProfilePage() {
return (
<Page
title="Профиль"
eyebrow="Кабинет кандидата"
lead="Управляйте своими сведениями и проверяйте, какие данные подтверждены оценкой."
width="wide"
>
<EditProfile />
</Page>
);
}
@@ -0,0 +1 @@
export { QuestionnairePage } from "./ui/questionnaire-page";
@@ -0,0 +1,15 @@
import { FillQuestionnaire } from "../../../features/fill-questionnaire";
import { Page } from "../../../shared/ui";
export function QuestionnairePage() {
return (
<Page
title="Анкета"
eyebrow="Кабинет кандидата"
lead="Укажите специализации и условия поиска. Самооценка не становится подтвержденной категорией."
width="wide"
>
<FillQuestionnaire />
</Page>
);
}
+1
View File
@@ -13,6 +13,7 @@ export const paths = {
root: "/candidate",
onboarding: "/candidate/onboarding",
profile: "/candidate/profile",
questionnaire: "/candidate/questionnaire",
assessment: "/candidate/assessment",
results: "/candidate/results",
invitations: "/candidate/invitations",
@@ -6,6 +6,7 @@ import styles from "./candidate-shell.module.css";
const navigation = [
{ to: paths.candidate.root, label: "Главная", end: true },
{ to: paths.candidate.profile, label: "Профиль", end: false },
{ to: paths.candidate.questionnaire, label: "Анкета", end: false },
{ to: paths.candidate.assessment, label: "Тест", end: false },
{ to: paths.candidate.results, label: "Результаты", end: false },
{ to: paths.candidate.invitations, label: "Приглашения", end: false },