From f81cd0ae099e94ba7eec4945f8a5c351a4b57102 Mon Sep 17 00:00:00 2001 From: TakuyaYagam1 Date: Wed, 7 Oct 2026 16:07:02 +0300 Subject: [PATCH] feat: add candidate profile, questionnaire and company forms --- backend/.golangci.yml | 2 + backend/Dockerfile.e2e | 4 + backend/cmd/company-fixture/main.go | 278 ++++++ backend/cmd/company-fixture/main_test.go | 177 ++++ backend/cmd/consent-fixture/main.go | 4 +- backend/cmd/mail-fixture/main.go | 2 +- backend/cmd/questionnaire-fixture/main.go | 211 +++++ .../cmd/questionnaire-fixture/main_test.go | 86 ++ .../secondary/postgres/company_fixture.go | 152 +++ .../postgres/company_fixture_test.go | 42 + deploy/Makefile | 2 +- deploy/docker/docker-compose.e2e-mail.yml | 43 + deploy/scripts/e2e.sh | 3 + deploy/scripts/test_e2e_mail.py | 38 + docs/en/TESTING.md | 18 +- docs/ru/TESTING.md | 18 +- frontend/README.en.md | 42 +- frontend/README.md | 42 +- frontend/e2e/auth-registration.spec.ts | 2 +- frontend/e2e/company-management.spec.ts | 457 +++++++++ frontend/e2e/profile-edit.spec.ts | 349 +++++++ frontend/e2e/questionnaire.spec.ts | 529 +++++++++++ frontend/src/app/router/routes.test.tsx | 3 +- frontend/src/app/router/routes.tsx | 11 +- frontend/src/entities/candidate/index.ts | 28 + .../candidate/model/profile-form.test.ts | 234 +++++ .../entities/candidate/model/profile-form.ts | 713 ++++++++++++++ frontend/src/entities/company/index.ts | 16 + .../company/model/company-form.test.ts | 103 ++ .../entities/company/model/company-form.ts | 157 +++ .../company/model/verification-labels.ts | 39 + .../ui/candidate-card-preview.module.css | 95 ++ .../ui/candidate-card-preview.test.tsx | 34 + .../company/ui/candidate-card-preview.tsx | 70 ++ .../model/onboarding-destination.test.ts | 2 +- .../session/model/onboarding-destination.ts | 3 +- frontend/src/entities/specialization/index.ts | 6 + .../specialization/model/catalog.test.ts | 71 ++ .../entities/specialization/model/catalog.ts | 35 + frontend/src/features/edit-company/index.ts | 1 + .../edit-company/ui/company-editor.module.css | 110 +++ .../edit-company/ui/company-editor.tsx | 528 +++++++++++ frontend/src/features/edit-profile/index.ts | 1 + .../edit-profile/ui/edit-profile.module.css | 61 ++ .../features/edit-profile/ui/edit-profile.tsx | 362 +++++++ .../edit-profile/ui/profile-form.module.css | 276 ++++++ .../edit-profile/ui/profile-form.test.tsx | 116 +++ .../features/edit-profile/ui/profile-form.tsx | 895 ++++++++++++++++++ .../src/features/fill-questionnaire/index.ts | 1 + .../model/questionnaire-form.test.ts | 274 ++++++ .../model/questionnaire-form.ts | 361 +++++++ .../model/session-guard.test.ts | 94 ++ .../fill-questionnaire/model/session-guard.ts | 31 + .../ui/fill-questionnaire.module.css | 72 ++ .../ui/fill-questionnaire.tsx | 547 +++++++++++ .../ui/questionnaire-form.module.css | 239 +++++ .../ui/questionnaire-form.test.tsx | 115 +++ .../ui/questionnaire-form.tsx | 634 +++++++++++++ .../ui/candidate-onboarding-page.tsx | 33 +- frontend/src/pages/company/index.ts | 1 + .../pages/company/ui/company-page.module.css | 106 +++ .../src/pages/company/ui/company-page.tsx | 558 +++++++++++ frontend/src/pages/profile/index.ts | 1 + .../src/pages/profile/ui/profile-page.tsx | 15 + frontend/src/pages/questionnaire/index.ts | 1 + .../questionnaire/ui/questionnaire-page.tsx | 15 + frontend/src/shared/config/paths.ts | 1 + .../candidate-shell/ui/candidate-shell.tsx | 1 + 68 files changed, 9517 insertions(+), 54 deletions(-) create mode 100644 backend/cmd/company-fixture/main.go create mode 100644 backend/cmd/company-fixture/main_test.go create mode 100644 backend/cmd/questionnaire-fixture/main.go create mode 100644 backend/cmd/questionnaire-fixture/main_test.go create mode 100644 backend/internal/adapter/secondary/postgres/company_fixture.go create mode 100644 backend/internal/adapter/secondary/postgres/company_fixture_test.go create mode 100644 frontend/e2e/company-management.spec.ts create mode 100644 frontend/e2e/profile-edit.spec.ts create mode 100644 frontend/e2e/questionnaire.spec.ts create mode 100644 frontend/src/entities/candidate/index.ts create mode 100644 frontend/src/entities/candidate/model/profile-form.test.ts create mode 100644 frontend/src/entities/candidate/model/profile-form.ts create mode 100644 frontend/src/entities/company/index.ts create mode 100644 frontend/src/entities/company/model/company-form.test.ts create mode 100644 frontend/src/entities/company/model/company-form.ts create mode 100644 frontend/src/entities/company/model/verification-labels.ts create mode 100644 frontend/src/entities/company/ui/candidate-card-preview.module.css create mode 100644 frontend/src/entities/company/ui/candidate-card-preview.test.tsx create mode 100644 frontend/src/entities/company/ui/candidate-card-preview.tsx create mode 100644 frontend/src/entities/specialization/index.ts create mode 100644 frontend/src/entities/specialization/model/catalog.test.ts create mode 100644 frontend/src/entities/specialization/model/catalog.ts create mode 100644 frontend/src/features/edit-company/index.ts create mode 100644 frontend/src/features/edit-company/ui/company-editor.module.css create mode 100644 frontend/src/features/edit-company/ui/company-editor.tsx create mode 100644 frontend/src/features/edit-profile/index.ts create mode 100644 frontend/src/features/edit-profile/ui/edit-profile.module.css create mode 100644 frontend/src/features/edit-profile/ui/edit-profile.tsx create mode 100644 frontend/src/features/edit-profile/ui/profile-form.module.css create mode 100644 frontend/src/features/edit-profile/ui/profile-form.test.tsx create mode 100644 frontend/src/features/edit-profile/ui/profile-form.tsx create mode 100644 frontend/src/features/fill-questionnaire/index.ts create mode 100644 frontend/src/features/fill-questionnaire/model/questionnaire-form.test.ts create mode 100644 frontend/src/features/fill-questionnaire/model/questionnaire-form.ts create mode 100644 frontend/src/features/fill-questionnaire/model/session-guard.test.ts create mode 100644 frontend/src/features/fill-questionnaire/model/session-guard.ts create mode 100644 frontend/src/features/fill-questionnaire/ui/fill-questionnaire.module.css create mode 100644 frontend/src/features/fill-questionnaire/ui/fill-questionnaire.tsx create mode 100644 frontend/src/features/fill-questionnaire/ui/questionnaire-form.module.css create mode 100644 frontend/src/features/fill-questionnaire/ui/questionnaire-form.test.tsx create mode 100644 frontend/src/features/fill-questionnaire/ui/questionnaire-form.tsx create mode 100644 frontend/src/pages/company/index.ts create mode 100644 frontend/src/pages/company/ui/company-page.module.css create mode 100644 frontend/src/pages/company/ui/company-page.tsx create mode 100644 frontend/src/pages/profile/index.ts create mode 100644 frontend/src/pages/profile/ui/profile-page.tsx create mode 100644 frontend/src/pages/questionnaire/index.ts create mode 100644 frontend/src/pages/questionnaire/ui/questionnaire-page.tsx diff --git a/backend/.golangci.yml b/backend/.golangci.yml index 653e596..50f4c64 100644 --- a/backend/.golangci.yml +++ b/backend/.golangci.yml @@ -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 diff --git a/backend/Dockerfile.e2e b/backend/Dockerfile.e2e index c3758f2..fdffc99 100644 --- a/backend/Dockerfile.e2e +++ b/backend/Dockerfile.e2e @@ -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"] diff --git a/backend/cmd/company-fixture/main.go b/backend/cmd/company-fixture/main.go new file mode 100644 index 0000000..76aceda --- /dev/null +++ b/backend/cmd/company-fixture/main.go @@ -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 +} diff --git a/backend/cmd/company-fixture/main_test.go b/backend/cmd/company-fixture/main_test.go new file mode 100644 index 0000000..6fcf440 --- /dev/null +++ b/backend/cmd/company-fixture/main_test.go @@ -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 +} diff --git a/backend/cmd/consent-fixture/main.go b/backend/cmd/consent-fixture/main.go index cf5d38b..d2e1333 100644 --- a/backend/cmd/consent-fixture/main.go +++ b/backend/cmd/consent-fixture/main.go @@ -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 { diff --git a/backend/cmd/mail-fixture/main.go b/backend/cmd/mail-fixture/main.go index b5e0c81..7158905 100644 --- a/backend/cmd/mail-fixture/main.go +++ b/backend/cmd/mail-fixture/main.go @@ -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") } diff --git a/backend/cmd/questionnaire-fixture/main.go b/backend/cmd/questionnaire-fixture/main.go new file mode 100644 index 0000000..a11ca8c --- /dev/null +++ b/backend/cmd/questionnaire-fixture/main.go @@ -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 +} diff --git a/backend/cmd/questionnaire-fixture/main_test.go b/backend/cmd/questionnaire-fixture/main_test.go new file mode 100644 index 0000000..b398994 --- /dev/null +++ b/backend/cmd/questionnaire-fixture/main_test.go @@ -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()) + } +} diff --git a/backend/internal/adapter/secondary/postgres/company_fixture.go b/backend/internal/adapter/secondary/postgres/company_fixture.go new file mode 100644 index 0000000..ff49ef2 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/company_fixture.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/company_fixture_test.go b/backend/internal/adapter/secondary/postgres/company_fixture_test.go new file mode 100644 index 0000000..ab87185 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/company_fixture_test.go @@ -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) + } + }) + } +} diff --git a/deploy/Makefile b/deploy/Makefile index f4d7424..d8a462c 100644 --- a/deploy/Makefile +++ b/deploy/Makefile @@ -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 diff --git a/deploy/docker/docker-compose.e2e-mail.yml b/deploy/docker/docker-compose.e2e-mail.yml index f76f5d5..8ca7d4b 100644 --- a/deploy/docker/docker-compose.e2e-mail.yml +++ b/deploy/docker/docker-compose.e2e-mail.yml @@ -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: diff --git a/deploy/scripts/e2e.sh b/deploy/scripts/e2e.sh index 858c4a7..0ac78a6 100644 --- a/deploy/scripts/e2e.sh +++ b/deploy/scripts/e2e.sh @@ -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) diff --git a/deploy/scripts/test_e2e_mail.py b/deploy/scripts/test_e2e_mail.py index d936667..ab8b258 100644 --- a/deploy/scripts/test_e2e_mail.py +++ b/deploy/scripts/test_e2e_mail.py @@ -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): diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 772cdb9..f0d2ca1 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -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: diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 371e5ac..4f979fd 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -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`) ΠΏΡ€ΠΎΠ²Π΅Ρ€ΡΡŽΡ‚ ΠΏΡ€Π°Π²ΠΈΠ»Π° видимости Π±Π΅Π· Π±Π°Π·Ρ‹: diff --git a/frontend/README.en.md b/frontend/README.en.md index 9761893..f27c1b1 100644 --- a/frontend/README.en.md +++ b/frontend/README.en.md @@ -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). diff --git a/frontend/README.md b/frontend/README.md index db80af2..8ebf3d7 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -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-Π½Π°Π±ΠΎΡ€). diff --git a/frontend/e2e/auth-registration.spec.ts b/frontend/e2e/auth-registration.spec.ts index f001bb3..66cf8ad 100644 --- a/frontend/e2e/auth-registration.spec.ts +++ b/frontend/e2e/auth-registration.spec.ts @@ -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( diff --git a/frontend/e2e/company-management.spec.ts b/frontend/e2e/company-management.spec.ts new file mode 100644 index 0000000..d1673ab --- /dev/null +++ b/frontend/e2e/company-management.spec.ts @@ -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; + 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 { + 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 { + 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 { + 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((resolve) => { + releaseLateUpdate = resolve; + }); + const lateUpdateStarted = new Promise((resolve) => { + notifyLateUpdateStarted = resolve; + }); + let holdDirectoryRefresh = false; + let releaseDirectoryRefresh: (() => void) | undefined; + let notifyDirectoryRefreshStarted: (() => void) | undefined; + const directoryRefreshGate = new Promise((resolve) => { + releaseDirectoryRefresh = resolve; + }); + const directoryRefreshStarted = new Promise((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, + ); + }); +}); diff --git a/frontend/e2e/profile-edit.spec.ts b/frontend/e2e/profile-edit.spec.ts new file mode 100644 index 0000000..6471e10 --- /dev/null +++ b/frontend/e2e/profile-edit.spec.ts @@ -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 { + 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 { + 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 { + 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 { + 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 { + 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 = Promise.resolve(); + const forwarded = new Promise((resolve) => { + markForwarded = resolve; + }); + const gate = new Promise((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(); + } + }); +}); diff --git a/frontend/e2e/questionnaire.spec.ts b/frontend/e2e/questionnaire.spec.ts new file mode 100644 index 0000000..7ca3f98 --- /dev/null +++ b/frontend/e2e/questionnaire.spec.ts @@ -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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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((resolve) => { + releaseOldResponse = resolve; + }); + const oldRequestHeld = new Promise((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"); + } + }); +}); diff --git a/frontend/src/app/router/routes.test.tsx b/frontend/src/app/router/routes.test.tsx index 4c3bf3d..e537ddb 100644 --- a/frontend/src/app/router/routes.test.tsx +++ b/frontend/src/app/router/routes.test.tsx @@ -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); diff --git a/frontend/src/app/router/routes.tsx b/frontend/src/app/router/routes.tsx index 98d70f7..2307839 100644 --- a/frontend/src/app/router/routes.tsx +++ b/frontend/src/app/router/routes.tsx @@ -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: }, { path: paths.candidate.profile, - element: , + element: , + }, + { + path: paths.candidate.questionnaire, + element: , }, { path: paths.candidate.assessment, @@ -85,7 +92,7 @@ export const routes: RouteObject[] = [ { index: true, loader: () => redirect(paths.employer.company) }, { path: paths.employer.company, - element: , + element: , }, { path: paths.employer.needs, element: }, { diff --git a/frontend/src/entities/candidate/index.ts b/frontend/src/entities/candidate/index.ts new file mode 100644 index 0000000..926adb9 --- /dev/null +++ b/frontend/src/entities/candidate/index.ts @@ -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"; diff --git a/frontend/src/entities/candidate/model/profile-form.test.ts b/frontend/src/entities/candidate/model/profile-form.test.ts new file mode 100644 index 0000000..cf5e8e7 --- /dev/null +++ b/frontend/src/entities/candidate/model/profile-form.test.ts @@ -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: "ΠŸΡ€ΠΎΠ²Π΅Ρ€ΡŒΡ‚Π΅ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ ΠΈ Ρ„ΠΎΡ€ΠΌΠ°Ρ‚ этого поля." }, + ]); + }); +}); diff --git a/frontend/src/entities/candidate/model/profile-form.ts b/frontend/src/entities/candidate/model/profile-form.ts new file mode 100644 index 0000000..0d26860 --- /dev/null +++ b/frontend/src/entities/candidate/model/profile-form.ts @@ -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; +type ClaimSource = NonNullable; + +export type FieldDraft = { + value: Value; + status: ClaimStatus; + originalStatus: ClaimStatus; + originalValue: Value | null; + source: ClaimSource | null; +}; + +type ItemMetadata = { + id: string; + originalIndex: number | null; + status: DecisionStatus; + originalStatus: DecisionStatus | null; + originalValue: Value | null; + source: ClaimSource | null; +}; + +type StackValue = Pick; +type RoleValue = Omit< + Pick, + "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; +type SalaryValue = CandidateProfile["terms"]["salary_minimum"]["value"]; + +export type StackDraft = StackValue & ItemMetadata; +export type RoleDraft = RoleValue & ItemMetadata; +export type ExperienceDraft = ExperienceValue & ItemMetadata; +export type SoftSkillDraft = SoftSkillValue & ItemMetadata; + +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; + contacts: { + email: FieldDraft; + phone: FieldDraft; + telegram: FieldDraft; + }; + stack: StackDraft[]; + roles: RoleDraft[]; + experience: ExperienceDraft[]; + softSkills: SoftSkillDraft[]; + terms: { + location: FieldDraft; + relocation: FieldDraft; + salaryMinimum: SalaryDraft; + }; + confirmedCategories: CandidateProfile["confirmed_categories"]; + originalOverlaps: CandidateProfile["experience_overlaps"]; + parallelAcknowledgements: Record; +}; + +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 { + return { + value: claim.value ?? "", + status: claim.status, + originalStatus: claim.status, + originalValue: claim.value, + source: claim.source, + }; +} + +function valueFieldDraft(claim: { + status: ClaimStatus; + value: Value | null; + source: ClaimSource | null; +}): FieldDraft { + return { + value: claim.value, + status: claim.status, + originalStatus: claim.status, + originalValue: claim.value, + source: claim.source, + }; +} + +function itemDraft( + id: string, + index: number, + item: Item, + value: Value, +): Value & ItemMetadata { + 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(draft: FieldDraft, value: Value): FieldDraft { + 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, +): CandidateProfileDraft { + return updateItem(draft, "stack", id, patch); +} + +export function updateRoleDraft( + draft: CandidateProfileDraft, + id: string, + patch: Partial, +): CandidateProfileDraft { + return updateItem(draft, "roles", id, patch); +} + +export function updateExperienceDraft( + draft: CandidateProfileDraft, + id: string, + patch: Partial, +): 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>, +): 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, +): CandidateProfileDraft { + return updateItem(draft, "softSkills", id, patch); +} + +function updateItem< + Key extends "stack" | "roles" | "experience" | "softSkills", + Item extends CandidateProfileDraft[Key][number], + Patch extends Partial>>, +>(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 = {}; + 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( + draft: CandidateProfileDraft, + key: Key, + id: string, +): CandidateProfileDraft { + return { ...draft, [key]: draft[key].filter((item) => item.id !== id) } as CandidateProfileDraft; +} + +function fieldDecision( + draft: FieldDraft, + value = draft.value, +): { value: Exclude; status: DecisionStatus } | null { + if (isEmptyValue(value)) return null; + const extracted = draft.status === "extracted" && sameValue(value, draft.originalValue); + return { + value: value as Exclude, + status: extracted ? "extracted" : "confirmed", + }; +} + +function itemDecision( + item: Value & ItemMetadata, +): 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 = ( + items: Value[], + valueOf: (value: Value) => string, + fieldOfIndex: (index: number) => string, + ) => { + const seen = new Set(); + 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: "ΠŸΡ€ΠΎΠ²Π΅Ρ€ΡŒΡ‚Π΅ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ ΠΈ Ρ„ΠΎΡ€ΠΌΠ°Ρ‚ этого поля.", + })); +} diff --git a/frontend/src/entities/company/index.ts b/frontend/src/entities/company/index.ts new file mode 100644 index 0000000..488b611 --- /dev/null +++ b/frontend/src/entities/company/index.ts @@ -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"; diff --git a/frontend/src/entities/company/model/company-form.test.ts b/frontend/src/entities/company/model/company-form.test.ts new file mode 100644 index 0000000..12d6a03 --- /dev/null +++ b/frontend/src/entities/company/model/company-form.test.ts @@ -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", + }, + ); + }); +}); diff --git a/frontend/src/entities/company/model/company-form.ts b/frontend/src/entities/company/model/company-form.ts new file mode 100644 index 0000000..3887856 --- /dev/null +++ b/frontend/src/entities/company/model/company-form.ts @@ -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: [], + }; +} diff --git a/frontend/src/entities/company/model/verification-labels.ts b/frontend/src/entities/company/model/verification-labels.ts new file mode 100644 index 0000000..3d67522 --- /dev/null +++ b/frontend/src/entities/company/model/verification-labels.ts @@ -0,0 +1,39 @@ +import type { Organization } from "../../../shared/api/schemas"; +import type { TrustLevelValue } from "../../../shared/ui"; + +export const organizationLevelLabels: Readonly< + Record +> = { + e0: "E0 - ΠΏΠΎΠ΄Ρ‚Π²Π΅Ρ€ΠΆΠ΄Π΅Π½Π° ΠΏΠΎΡ‡Ρ‚Π° Π²Π»Π°Π΄Π΅Π»ΡŒΡ†Π°", + e1: "E1 - ΠΏΠΎΠ΄Ρ‚Π²Π΅Ρ€ΠΆΠ΄Π΅Π½Ρ‹ Π΄ΠΎΠΌΠ΅Π½ ΠΈ связь с ΠΊΠΎΠΌΠΏΠ°Π½ΠΈΠ΅ΠΉ", + e2: "E2 - ΠΏΡ€ΠΎΠ²Π΅Ρ€Π΅Π½Ρ‹ Ρ€Π΅ΠΊΠ²ΠΈΠ·ΠΈΡ‚Ρ‹ ΠΈ полномочия", + e3: "E3 - Π΄ΠΎΠΏΠΎΠ»Π½ΠΈΡ‚Π΅Π»ΡŒΠ½Π°Ρ ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ° ΠΏΠ»Π°Ρ‚Ρ„ΠΎΡ€ΠΌΡ‹", +}; + +export const candidateCardLevelLabels: Readonly< + Record +> = { + e0: "Π£Ρ€ΠΎΠ²Π΅Π½ΡŒ E0", + e1: "Π£Ρ€ΠΎΠ²Π΅Π½ΡŒ E1", + e2: "Π£Ρ€ΠΎΠ²Π΅Π½ΡŒ E2", + e3: "Π£Ρ€ΠΎΠ²Π΅Π½ΡŒ E3", +}; + +export const organizationBasisLabels: Readonly< + Record +> = { + confirmed_email: "ΠŸΠΎΠ΄Ρ‚Π²Π΅Ρ€ΠΆΠ΄Π΅Π½Π½Π°Ρ ΠΏΠΎΡ‡Ρ‚Π° Π²Π»Π°Π΄Π΅Π»ΡŒΡ†Π°", + corporate_domain: "ΠšΠΎΡ€ΠΏΠΎΡ€Π°Ρ‚ΠΈΠ²Π½Ρ‹ΠΉ Π΄ΠΎΠΌΠ΅Π½ ΠΈ связь с ΠΊΠΎΠΌΠΏΠ°Π½ΠΈΠ΅ΠΉ", + requisites_and_authority: "ΠŸΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ° Ρ€Π΅ΠΊΠ²ΠΈΠ·ΠΈΡ‚ΠΎΠ² ΠΈ ΠΏΠΎΠ»Π½ΠΎΠΌΠΎΡ‡ΠΈΠΉ", + manual_review: "Ручная ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ° ΠΏΠ»Π°Ρ‚Ρ„ΠΎΡ€ΠΌΡ‹", + partner_status: "Бтатус ΠΏΠ°Ρ€Ρ‚Π½Π΅Ρ€Π°", +}; + +export const organizationTrustLevel: Readonly< + Record +> = { + e0: "claimed", + e1: "partial", + e2: "confirmed", + e3: "confirmed", +}; diff --git a/frontend/src/entities/company/ui/candidate-card-preview.module.css b/frontend/src/entities/company/ui/candidate-card-preview.module.css new file mode 100644 index 0000000..1e374e2 --- /dev/null +++ b/frontend/src/entities/company/ui/candidate-card-preview.module.css @@ -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); + } +} diff --git a/frontend/src/entities/company/ui/candidate-card-preview.test.tsx b/frontend/src/entities/company/ui/candidate-card-preview.test.tsx new file mode 100644 index 0000000..cf9c03b --- /dev/null +++ b/frontend/src/entities/company/ui/candidate-card-preview.test.tsx @@ -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(); + const preview = /]*>(.*?)<\/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); + }); +}); diff --git a/frontend/src/entities/company/ui/candidate-card-preview.tsx b/frontend/src/entities/company/ui/candidate-card-preview.tsx new file mode 100644 index 0000000..901147f --- /dev/null +++ b/frontend/src/entities/company/ui/candidate-card-preview.tsx @@ -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 ( +
+
+
+
+

{card.name}

+

+ +

+
+ {card.sphere ?

{card.sphere}

: null} +
+ {card.description ?

{card.description}

: null} + {contacts.length > 0 ? ( +
+ {contacts.map(({ label, value }) => ( +
+
{label}
+
{value}
+
+ ))} +
+ ) : null} + {card.representatives && card.representatives.length > 0 ? ( +
+

ΠŸΡ€Π΅Π΄ΡΡ‚Π°Π²ΠΈΡ‚Π΅Π»ΠΈ ΠΊΠΎΠΌΠΏΠ°Π½ΠΈΠΈ

+
    + {card.representatives.map((representative, index) => ( +
  • + {representative.name} + {representative.job_title} +
  • + ))} +
+
+ ) : null} +
+
+ ); +} diff --git a/frontend/src/entities/session/model/onboarding-destination.test.ts b/frontend/src/entities/session/model/onboarding-destination.test.ts index b76d806..b8109ec 100644 --- a/frontend/src/entities/session/model/onboarding-destination.test.ts +++ b/frontend/src/entities/session/model/onboarding-destination.test.ts @@ -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], diff --git a/frontend/src/entities/session/model/onboarding-destination.ts b/frontend/src/entities/session/model/onboarding-destination.ts index 264a5e0..338db5e 100644 --- a/frontend/src/entities/session/model/onboarding-destination.ts +++ b/frontend/src/entities/session/model/onboarding-destination.ts @@ -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": diff --git a/frontend/src/entities/specialization/index.ts b/frontend/src/entities/specialization/index.ts new file mode 100644 index 0000000..4df2309 --- /dev/null +++ b/frontend/src/entities/specialization/index.ts @@ -0,0 +1,6 @@ +export { + findGradeTitle, + findSpecializationOption, + listSpecializationOptions, + type CatalogSpecializationOption, +} from "./model/catalog"; diff --git a/frontend/src/entities/specialization/model/catalog.test.ts b/frontend/src/entities/specialization/model/catalog.test.ts new file mode 100644 index 0000000..3bf0187 --- /dev/null +++ b/frontend/src/entities/specialization/model/catalog.test.ts @@ -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"); + }); +}); diff --git a/frontend/src/entities/specialization/model/catalog.ts b/frontend/src/entities/specialization/model/catalog.ts new file mode 100644 index 0000000..074447d --- /dev/null +++ b/frontend/src/entities/specialization/model/catalog.ts @@ -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; +} diff --git a/frontend/src/features/edit-company/index.ts b/frontend/src/features/edit-company/index.ts new file mode 100644 index 0000000..366259e --- /dev/null +++ b/frontend/src/features/edit-company/index.ts @@ -0,0 +1 @@ +export { CompanyEditor } from "./ui/company-editor"; diff --git a/frontend/src/features/edit-company/ui/company-editor.module.css b/frontend/src/features/edit-company/ui/company-editor.module.css new file mode 100644 index 0000000..383ccdc --- /dev/null +++ b/frontend/src/features/edit-company/ui/company-editor.module.css @@ -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); + } +} diff --git a/frontend/src/features/edit-company/ui/company-editor.tsx b/frontend/src/features/edit-company/ui/company-editor.tsx new file mode 100644 index 0000000..1177a6f --- /dev/null +++ b/frontend/src/features/edit-company/ui/company-editor.tsx @@ -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; + onAccessLost: (error: ApiRequestError) => void; +}; + +type CreateAttempt = { + body: OrganizationCreate; + key: string; +}; + +type FieldErrors = Partial>; + +function fieldNameForPointer(pointer: string): string | undefined { + const fields: Readonly> = { + "/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); + const [draft, setDraft] = useState(() => + organization ? draftFromOrganization(organization) : emptyCompanyDraft(), + ); + const [attempt, setAttempt] = useState(null); + const [createRetryRequired, setCreateRetryRequired] = useState(false); + const [actionError, setActionError] = useState(null); + const [csrfRetryMessage, setCsrfRetryMessage] = useState(null); + const [fieldErrors, setFieldErrors] = useState({}); + 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(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(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(getGetCurrentSessionQueryKey()); + return current?.account.id === expected.account.id; + } + + async function refreshAfterCsrfFailure(expected: Session): Promise { + 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 { + 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 { + 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 { + 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): 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 ( +
+ {creating ?

ΠžΡΠ½ΠΎΠ²Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅ ΠΊΠΎΠΌΠΏΠ°Π½ΠΈΠΈ

: null} + {createRequestIsFrozen ? ( +

+ Запрос создания хранится Ρ‚ΠΎΠ»ΡŒΠΊΠΎ Π½Π° этой страницС. НС мСняйтС Π΄Π°Π½Π½Ρ‹Π΅ Π΄ΠΎ подтвСрТдСния + ΠΎΡ‚Π²Π΅Ρ‚Π°. +

+ ) : null} +
+ + updateDraft("name", event.currentTarget.value)} + /> + {fieldErrors.name ? ( +

+ {fieldErrors.name} +

+ ) : null} +
+
+ +