feat(profile): persist candidate edits and enforce company access
This commit is contained in:
1 parent
3ab6bd91a3
commit
73c7caa225
67 files changed
+5286
-229
No files matched your search
@@ -0,0 +1,44 @@
|
||||
package organization
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// CompanyAccess is a request-scoped capability issued after the current
|
||||
// account has been checked as an active owner. Business operations still
|
||||
// repeat authorization inside their transaction before reading or writing.
|
||||
type CompanyAccess struct {
|
||||
actorID uuid.UUID
|
||||
organizationID uuid.UUID
|
||||
membershipID uuid.UUID
|
||||
}
|
||||
|
||||
// Matches reports whether this capability was issued for actorID and
|
||||
// organizationID.
|
||||
func (access CompanyAccess) Matches(actorID, organizationID uuid.UUID) bool {
|
||||
return access.actorID != uuid.Nil && access.organizationID != uuid.Nil && access.membershipID != uuid.Nil &&
|
||||
access.actorID == actorID && access.organizationID == organizationID
|
||||
}
|
||||
|
||||
type companyAccessContextKey struct{}
|
||||
|
||||
// WithCompanyAccess attaches a validated company capability to a request
|
||||
// context. An empty capability is ignored.
|
||||
func WithCompanyAccess(ctx context.Context, access CompanyAccess) context.Context {
|
||||
if !access.Matches(access.actorID, access.organizationID) {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, companyAccessContextKey{}, access)
|
||||
}
|
||||
|
||||
// CompanyAccessFromContext returns the capability attached by the HTTP
|
||||
// boundary, if one is present and valid.
|
||||
func CompanyAccessFromContext(ctx context.Context) (CompanyAccess, bool) {
|
||||
access, ok := ctx.Value(companyAccessContextKey{}).(CompanyAccess)
|
||||
if !ok || !access.Matches(access.actorID, access.organizationID) {
|
||||
return CompanyAccess{}, false
|
||||
}
|
||||
return access, true
|
||||
}
|
||||
@@ -252,6 +252,9 @@ func (service *Service) Update(ctx context.Context, command UpdateCommand) (doma
|
||||
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil {
|
||||
return domain.Organization{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
|
||||
}
|
||||
if err := matchCompanyContext(ctx, command.ActorID, command.OrganizationID, location); err != nil {
|
||||
return domain.Organization{}, err
|
||||
}
|
||||
if command.ExpectedVersion < 1 {
|
||||
return domain.Organization{}, fmt.Errorf("%s - expected version must be positive: %w", location, domain.ErrInvalidOrganization)
|
||||
}
|
||||
@@ -299,13 +302,16 @@ func (service *Service) Update(ctx context.Context, command UpdateCommand) (doma
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Get reads an organization only for an active member of the employer
|
||||
// account. The membership is checked in the same transaction as the account.
|
||||
// Get reads an organization only for its active owner. The membership is
|
||||
// checked in the same transaction as the account.
|
||||
func (service *Service) Get(ctx context.Context, actorID, organizationID uuid.UUID) (domain.Organization, error) {
|
||||
const location = "organization.Service.Get"
|
||||
if actorID == uuid.Nil || organizationID == uuid.Nil {
|
||||
return domain.Organization{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
|
||||
}
|
||||
if err := matchCompanyContext(ctx, actorID, organizationID, location); err != nil {
|
||||
return domain.Organization{}, err
|
||||
}
|
||||
var result domain.Organization
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireEmployer(ctx, unit, actorID, location); err != nil {
|
||||
@@ -318,6 +324,9 @@ func (service *Service) Get(ctx context.Context, actorID, organizationID uuid.UU
|
||||
if !membership.GrantsAccess() {
|
||||
return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound)
|
||||
}
|
||||
if membership.Role() != domain.OrganizationRoleOwner {
|
||||
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
|
||||
}
|
||||
result = organization
|
||||
return nil
|
||||
})
|
||||
@@ -327,6 +336,82 @@ func (service *Service) Get(ctx context.Context, actorID, organizationID uuid.UU
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// AuthorizeCompany verifies the current verified employer account, active
|
||||
// membership, and owner role before issuing a request-scoped capability.
|
||||
func (service *Service) AuthorizeCompany(ctx context.Context, actorID, organizationID uuid.UUID) (CompanyAccess, error) {
|
||||
const location = "organization.Service.AuthorizeCompany"
|
||||
if actorID == uuid.Nil || organizationID == uuid.Nil {
|
||||
return CompanyAccess{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
|
||||
}
|
||||
var access CompanyAccess
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireEmployer(ctx, unit, actorID, location); err != nil {
|
||||
return fmt.Errorf("%s - authorize company actor: %w", location, err)
|
||||
}
|
||||
_, membership, err := unit.Organizations().GetForMember(ctx, organizationID, actorID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read active company membership: %w", location, err)
|
||||
}
|
||||
if !membership.GrantsAccess() {
|
||||
return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound)
|
||||
}
|
||||
if membership.Role() != domain.OrganizationRoleOwner {
|
||||
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
|
||||
}
|
||||
access = CompanyAccess{actorID: actorID, organizationID: organizationID, membershipID: membership.ID()}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return CompanyAccess{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return access, nil
|
||||
}
|
||||
|
||||
// ListMyOrganizations returns active organization memberships for one
|
||||
// verified employer. The actor always comes from the authenticated session.
|
||||
func (service *Service) ListMyOrganizations(ctx context.Context, command OrganizationListCommand) (outbound.OrganizationPage, error) {
|
||||
const location = "organization.Service.ListMyOrganizations"
|
||||
if command.ActorID == uuid.Nil {
|
||||
return outbound.OrganizationPage{}, fmt.Errorf("%s - actor ID must be set: %w", location, ErrForbidden)
|
||||
}
|
||||
if command.Limit < 1 || command.Limit > outbound.MaxOrganizationPageSize {
|
||||
return outbound.OrganizationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxOrganizationPageSize, domain.ErrInvalidMembership)
|
||||
}
|
||||
var result outbound.OrganizationPage
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireEmployer(ctx, unit, command.ActorID, location); err != nil {
|
||||
return fmt.Errorf("%s - authorize list actor: %w", location, err)
|
||||
}
|
||||
page, err := unit.Organizations().ListForUser(ctx, outbound.OrganizationListQuery{
|
||||
UserID: command.ActorID, After: command.After, Limit: command.Limit,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - list active memberships: %w", location, err)
|
||||
}
|
||||
result = page
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.OrganizationPage{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// OrganizationListCommand selects a page of the actor's own memberships.
|
||||
type OrganizationListCommand struct {
|
||||
ActorID uuid.UUID
|
||||
After *outbound.OrganizationListPosition
|
||||
Limit int32
|
||||
}
|
||||
|
||||
func matchCompanyContext(ctx context.Context, actorID, organizationID uuid.UUID, location string) error {
|
||||
access, ok := CompanyAccessFromContext(ctx)
|
||||
if ok && !access.Matches(actorID, organizationID) {
|
||||
return fmt.Errorf("%s - company context does not match the operation: %w", location, ErrForbidden)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyPatch(current domain.OrganizationProfile, patch ProfilePatch) (domain.OrganizationProfile, error) {
|
||||
contacts := current.Contacts()
|
||||
input := domain.OrganizationProfileInput{
|
||||
|
||||
@@ -22,6 +22,7 @@ type organizationTestState struct {
|
||||
memberships map[organizationTestMembershipKey]domain.Membership
|
||||
idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord
|
||||
results map[[outbound.IdempotencyDigestSize]byte]outbound.OrganizationCreationResult
|
||||
lastListQuery *outbound.OrganizationListQuery
|
||||
}
|
||||
|
||||
type organizationTestMembershipKey struct {
|
||||
@@ -56,6 +57,14 @@ func (state organizationTestState) clone() organizationTestState {
|
||||
for scope, result := range state.results {
|
||||
cloned.results[scope] = result
|
||||
}
|
||||
if state.lastListQuery != nil {
|
||||
query := *state.lastListQuery
|
||||
if query.After != nil {
|
||||
position := *query.After
|
||||
query.After = &position
|
||||
}
|
||||
cloned.lastListQuery = &query
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
|
||||
@@ -227,9 +236,10 @@ func (repository organizationTestOrganizations) GetForMember(
|
||||
}
|
||||
|
||||
func (repository organizationTestOrganizations) ListForUser(
|
||||
context.Context,
|
||||
outbound.OrganizationListQuery,
|
||||
_ context.Context,
|
||||
query outbound.OrganizationListQuery,
|
||||
) (outbound.OrganizationPage, error) {
|
||||
repository.state.lastListQuery = &query
|
||||
return outbound.OrganizationPage{}, nil
|
||||
}
|
||||
|
||||
@@ -550,6 +560,93 @@ func TestUpdateRequiresOwnerAndPreservesVerification(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeCompanyIssuesContextCapabilityOnlyToActiveOwner(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
|
||||
tx := newOrganizationTestTransactor()
|
||||
ownerID, recruiterID, candidateID, unverifiedID, foreignID := uuid.New(), uuid.New(), uuid.New(), uuid.New(), uuid.New()
|
||||
tx.state.users[ownerID] = verifiedEmployer(ownerID, now)
|
||||
tx.state.users[recruiterID] = verifiedEmployer(recruiterID, now)
|
||||
tx.state.users[candidateID] = domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
|
||||
tx.state.users[unverifiedID] = domain.User{ID: unverifiedID, Scenario: domain.ScenarioEmployer}
|
||||
tx.state.users[foreignID] = verifiedEmployer(foreignID, now)
|
||||
service := newOrganizationTestService(t, tx, func() time.Time { return now })
|
||||
profile := organizationProfile("ООО Пример", "Данные")
|
||||
created, err := service.Create(ctx, CreateCommand{
|
||||
ActorID: ownerID, IdempotencyKey: "company-access-01", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Create() error = %v", err)
|
||||
}
|
||||
organizationID := created.Organization.ID()
|
||||
for _, input := range []domain.MembershipInput{
|
||||
{OrganizationID: organizationID, UserID: recruiterID, Role: domain.OrganizationRoleRecruiter, At: now.Add(time.Second)},
|
||||
{OrganizationID: organizationID, UserID: candidateID, Role: domain.OrganizationRoleOwner, At: now.Add(time.Second)},
|
||||
{OrganizationID: organizationID, UserID: unverifiedID, Role: domain.OrganizationRoleOwner, At: now.Add(time.Second)},
|
||||
} {
|
||||
membership, err := domain.NewMembership(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewMembership() error = %v", err)
|
||||
}
|
||||
tx.state.memberships[organizationTestMembershipKey{organizationID, input.UserID}] = membership
|
||||
}
|
||||
|
||||
access, err := service.AuthorizeCompany(ctx, ownerID, organizationID)
|
||||
if err != nil || !access.Matches(ownerID, organizationID) {
|
||||
t.Fatalf("AuthorizeCompany(owner) = %+v, %v; want matching capability", access, err)
|
||||
}
|
||||
if access.Matches(foreignID, organizationID) || access.Matches(ownerID, uuid.New()) {
|
||||
t.Fatal("CompanyAccess matched a different actor or organization")
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
user uuid.UUID
|
||||
want error
|
||||
}{
|
||||
{name: "recruiter role", user: recruiterID, want: outbound.ErrOrganizationManagerRequired},
|
||||
{name: "candidate even with owner membership", user: candidateID, want: ErrForbidden},
|
||||
{name: "unverified employer", user: unverifiedID, want: ErrEmailNotVerified},
|
||||
{name: "no membership", user: foreignID, want: outbound.ErrOrganizationNotFound},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if _, err := service.AuthorizeCompany(ctx, test.user, organizationID); !errors.Is(err, test.want) {
|
||||
t.Fatalf("AuthorizeCompany() error = %v, want %v", err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
if _, err := service.Get(ctx, recruiterID, organizationID); !errors.Is(err, outbound.ErrOrganizationManagerRequired) {
|
||||
t.Fatalf("Get(recruiter) error = %v, want ErrOrganizationManagerRequired", err)
|
||||
}
|
||||
if _, err := service.Get(WithCompanyAccess(ctx, access), ownerID, uuid.New()); !errors.Is(err, ErrForbidden) {
|
||||
t.Fatalf("Get(mismatched company context) error = %v, want ErrForbidden", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListMyOrganizationsUsesOnlyVerifiedEmployerActorAndBoundedPage(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
|
||||
tx := newOrganizationTestTransactor()
|
||||
employerID, candidateID := uuid.New(), uuid.New()
|
||||
tx.state.users[employerID] = verifiedEmployer(employerID, now)
|
||||
tx.state.users[candidateID] = domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
|
||||
service := newOrganizationTestService(t, tx, func() time.Time { return now })
|
||||
position := outbound.OrganizationListPosition{JoinedAt: now.Add(-time.Minute), OrganizationID: uuid.New()}
|
||||
page, err := service.ListMyOrganizations(ctx, OrganizationListCommand{ActorID: employerID, After: &position, Limit: 8})
|
||||
if err != nil || len(page.Items) != 0 || page.HasMore {
|
||||
t.Fatalf("ListMyOrganizations() = %+v, %v; want empty page", page, err)
|
||||
}
|
||||
query := tx.snapshot().lastListQuery
|
||||
if query == nil || query.UserID != employerID || query.Limit != 8 || query.After == nil || *query.After != position {
|
||||
t.Fatalf("ListForUser query = %+v, want principal-scoped cursor and limit", query)
|
||||
}
|
||||
if _, err := service.ListMyOrganizations(ctx, OrganizationListCommand{ActorID: candidateID, Limit: 8}); !errors.Is(err, ErrForbidden) {
|
||||
t.Fatalf("ListMyOrganizations(candidate) error = %v, want ErrForbidden", err)
|
||||
}
|
||||
if _, err := service.ListMyOrganizations(ctx, OrganizationListCommand{ActorID: employerID, Limit: outbound.MaxOrganizationPageSize + 1}); !errors.Is(err, domain.ErrInvalidMembership) {
|
||||
t.Fatalf("ListMyOrganizations(oversized limit) error = %v, want ErrInvalidMembership", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentCreateWithSameKeyReturnsOneCompany(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
// Package profile reads and version-saves a candidate's private manual profile.
|
||||
package profile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrForbidden reports an account that cannot use the candidate profile.
|
||||
ErrForbidden = errors.New("candidate profile operation forbidden")
|
||||
|
||||
// ErrEmailNotVerified reports an account whose current email is not confirmed.
|
||||
ErrEmailNotVerified = errors.New("candidate profile requires a confirmed email")
|
||||
)
|
||||
|
||||
// Service is stateless between calls. Profile data, its history, and onboarding
|
||||
// movement are written through one transaction.
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
// NewService takes the transaction boundary and application clock. A nil
|
||||
// dependency is a wiring error and panics at construction.
|
||||
func NewService(transactor outbound.Transactor, clock func() time.Time) *Service {
|
||||
if transactor == nil {
|
||||
panic("profile.NewService - transactor must not be nil")
|
||||
}
|
||||
if clock == nil {
|
||||
panic("profile.NewService - clock must not be nil")
|
||||
}
|
||||
return &Service{transactor: transactor, clock: clock}
|
||||
}
|
||||
|
||||
// GetMyProfile reads only the profile owned by userID. Version zero means the
|
||||
// candidate has not saved a profile yet.
|
||||
func (service *Service) GetMyProfile(ctx context.Context, userID uuid.UUID) (domain.CandidateProfile, error) {
|
||||
const location = "Service.GetMyProfile"
|
||||
if userID == uuid.Nil {
|
||||
return domain.CandidateProfile{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile)
|
||||
}
|
||||
var result domain.CandidateProfile
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireCandidate(ctx, unit, userID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
result, err = unit.CandidateProfiles().Get(ctx, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read profile: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.CandidateProfile{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// SaveMyProfile replaces the candidate's manual profile when expectedVersion
|
||||
// is current. Identical retries remain no-ops, while every successful request
|
||||
// advances onboarding only from candidate_profile.
|
||||
func (service *Service) SaveMyProfile(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
expectedVersion int64,
|
||||
input domain.CandidateProfileInput,
|
||||
) (domain.CandidateProfile, error) {
|
||||
const location = "Service.SaveMyProfile"
|
||||
if userID == uuid.Nil {
|
||||
return domain.CandidateProfile{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile)
|
||||
}
|
||||
at := service.clock().UTC()
|
||||
if at.IsZero() {
|
||||
return domain.CandidateProfile{}, fmt.Errorf("%s - application clock returned zero: %w", location, domain.ErrInvalidCandidateProfile)
|
||||
}
|
||||
var result domain.CandidateProfile
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireCandidate(ctx, unit, userID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
repository := unit.CandidateProfiles()
|
||||
current, err := repository.Get(ctx, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read profile: %w", location, err)
|
||||
}
|
||||
updated, changed, err := current.Replace(input, expectedVersion, at)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - apply profile: %w", location, err)
|
||||
}
|
||||
if changed {
|
||||
updated, err = repository.Save(ctx, expectedVersion, updated)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - save profile: %w", location, err)
|
||||
}
|
||||
}
|
||||
if err := repository.AdvanceOnboarding(ctx, userID, at); err != nil {
|
||||
return fmt.Errorf("%s - advance onboarding: %w", location, err)
|
||||
}
|
||||
result = updated
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrCandidateProfileVersionConflict) || errors.Is(err, domain.ErrCandidateProfileVersionConflict) {
|
||||
return domain.CandidateProfile{}, fmt.Errorf("%s - transaction: %w", location, domain.ErrCandidateProfileVersionConflict)
|
||||
}
|
||||
return domain.CandidateProfile{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func requireCandidate(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, location string) error {
|
||||
user, err := unit.Users().GetByID(ctx, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return ErrForbidden
|
||||
}
|
||||
return fmt.Errorf("%s - read account: %w", location, err)
|
||||
}
|
||||
if !user.EmailVerified() {
|
||||
return ErrEmailNotVerified
|
||||
}
|
||||
if user.Scenario != domain.ScenarioCandidate {
|
||||
return ErrForbidden
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package profile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type profileTestTransactor struct {
|
||||
unit outbound.UnitOfWork
|
||||
}
|
||||
|
||||
func (transactor profileTestTransactor) WithinTransaction(
|
||||
ctx context.Context,
|
||||
fn func(context.Context, outbound.UnitOfWork) error,
|
||||
) error {
|
||||
return fn(ctx, transactor.unit)
|
||||
}
|
||||
|
||||
type profileTestUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
users outbound.UserRepository
|
||||
profiles outbound.CandidateProfileRepository
|
||||
}
|
||||
|
||||
func (unit profileTestUnit) Users() outbound.UserRepository { return unit.users }
|
||||
|
||||
func (unit profileTestUnit) CandidateProfiles() outbound.CandidateProfileRepository {
|
||||
return unit.profiles
|
||||
}
|
||||
|
||||
type profileTestUsers struct {
|
||||
outbound.UserRepository
|
||||
|
||||
user domain.User
|
||||
err error
|
||||
getCalls int
|
||||
}
|
||||
|
||||
func (users *profileTestUsers) GetByID(_ context.Context, userID uuid.UUID) (domain.User, error) {
|
||||
users.getCalls++
|
||||
if users.err != nil {
|
||||
return domain.User{}, users.err
|
||||
}
|
||||
if userID != users.user.ID {
|
||||
return domain.User{}, outbound.ErrUserNotFound
|
||||
}
|
||||
return users.user, nil
|
||||
}
|
||||
|
||||
type profileTestRepository struct {
|
||||
profile domain.CandidateProfile
|
||||
getCalls int
|
||||
saveCalls int
|
||||
advanceCalls int
|
||||
saveErr error
|
||||
advanceErr error
|
||||
}
|
||||
|
||||
func (repository *profileTestRepository) Get(_ context.Context, _ uuid.UUID) (domain.CandidateProfile, error) {
|
||||
repository.getCalls++
|
||||
return repository.profile, nil
|
||||
}
|
||||
|
||||
func (repository *profileTestRepository) Save(
|
||||
_ context.Context,
|
||||
expectedVersion int64,
|
||||
profile domain.CandidateProfile,
|
||||
) (domain.CandidateProfile, error) {
|
||||
repository.saveCalls++
|
||||
if repository.saveErr != nil {
|
||||
return domain.CandidateProfile{}, repository.saveErr
|
||||
}
|
||||
claims, err := profile.Content().StoredClaims()
|
||||
if err != nil {
|
||||
return domain.CandidateProfile{}, err
|
||||
}
|
||||
repository.profile, err = domain.RestoreCandidateProfile(domain.StoredCandidateProfile{
|
||||
UserID: profile.UserID(), Version: expectedVersion + 1,
|
||||
CreatedAt: profile.CreatedAt(), UpdatedAt: profile.UpdatedAt(), Claims: claims,
|
||||
ParallelPeriodAcknowledgements: profile.Content().ParallelPeriodAcknowledgements(),
|
||||
})
|
||||
return repository.profile, err
|
||||
}
|
||||
|
||||
func (repository *profileTestRepository) AdvanceOnboarding(_ context.Context, _ uuid.UUID, _ time.Time) error {
|
||||
repository.advanceCalls++
|
||||
return repository.advanceErr
|
||||
}
|
||||
|
||||
func TestServiceRequiresVerifiedCandidateBeforeReadingOrWritingProfile(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
tests := []struct {
|
||||
name string
|
||||
scenario domain.Scenario
|
||||
verified bool
|
||||
wantErr error
|
||||
}{
|
||||
{name: "verified candidate", scenario: domain.ScenarioCandidate, verified: true},
|
||||
{name: "unverified candidate", scenario: domain.ScenarioCandidate, wantErr: ErrEmailNotVerified},
|
||||
{name: "verified employer", scenario: domain.ScenarioEmployer, verified: true, wantErr: ErrForbidden},
|
||||
{name: "unverified employer", scenario: domain.ScenarioEmployer, wantErr: ErrEmailNotVerified},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
id := uuid.Must(uuid.NewV7())
|
||||
user := domain.User{ID: id, Scenario: test.scenario}
|
||||
if test.verified {
|
||||
user.EmailVerifiedAt = &now
|
||||
}
|
||||
users := &profileTestUsers{user: user}
|
||||
profiles := &profileTestRepository{}
|
||||
profiles.profile, _ = domain.EmptyCandidateProfile(id)
|
||||
service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles}}, func() time.Time { return now })
|
||||
|
||||
_, readErr := service.GetMyProfile(context.Background(), id)
|
||||
if !errors.Is(readErr, test.wantErr) {
|
||||
t.Fatalf("GetMyProfile() error = %v, want %v", readErr, test.wantErr)
|
||||
}
|
||||
_, saveErr := service.SaveMyProfile(context.Background(), id, 0, domain.CandidateProfileInput{})
|
||||
if !errors.Is(saveErr, test.wantErr) {
|
||||
t.Fatalf("SaveMyProfile() error = %v, want %v", saveErr, test.wantErr)
|
||||
}
|
||||
wantProfileReads := 0
|
||||
wantAdvances := 0
|
||||
if test.wantErr == nil {
|
||||
wantProfileReads = 2
|
||||
wantAdvances = 1
|
||||
}
|
||||
if profiles.getCalls != wantProfileReads || profiles.saveCalls != 0 || profiles.advanceCalls != wantAdvances {
|
||||
t.Fatalf("profile calls = get %d, save %d, advance %d; want %d, 0, %d", profiles.getCalls, profiles.saveCalls, profiles.advanceCalls, wantProfileReads, wantAdvances)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveMyProfileWritesOnlyChangedVersionsAndAdvancesOnNoOp(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
id := uuid.Must(uuid.NewV7())
|
||||
user := domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
|
||||
users := &profileTestUsers{user: user}
|
||||
profiles := &profileTestRepository{}
|
||||
profiles.profile, _ = domain.EmptyCandidateProfile(id)
|
||||
service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles}}, func() time.Time { return now })
|
||||
input := domain.CandidateProfileInput{FullName: &domain.ProfileClaimInput[string]{Value: "Anna Sokolova", Status: domain.ProfileClaimConfirmed}}
|
||||
|
||||
if _, err := service.SaveMyProfile(context.Background(), id, 0, input); err != nil {
|
||||
t.Fatalf("SaveMyProfile(first save) error = %v", err)
|
||||
}
|
||||
if profiles.saveCalls != 1 || profiles.advanceCalls != 1 || profiles.profile.Version() != 1 {
|
||||
t.Fatalf("first save calls = save %d, advance %d, version %d", profiles.saveCalls, profiles.advanceCalls, profiles.profile.Version())
|
||||
}
|
||||
if _, err := service.SaveMyProfile(context.Background(), id, 1, input); err != nil {
|
||||
t.Fatalf("SaveMyProfile(no-op retry) error = %v", err)
|
||||
}
|
||||
if profiles.saveCalls != 1 || profiles.advanceCalls != 2 {
|
||||
t.Fatalf("no-op calls = save %d, advance %d, want one saved version and two onboarding checks", profiles.saveCalls, profiles.advanceCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveMyProfileDoesNotAdvanceAfterProfileWriteFailure(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
id := uuid.Must(uuid.NewV7())
|
||||
user := domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
|
||||
users := &profileTestUsers{user: user}
|
||||
profiles := &profileTestRepository{saveErr: outbound.ErrTransactionConflict}
|
||||
profiles.profile, _ = domain.EmptyCandidateProfile(id)
|
||||
service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles}}, func() time.Time { return now })
|
||||
input := domain.CandidateProfileInput{FullName: &domain.ProfileClaimInput[string]{Value: "Anna Sokolova", Status: domain.ProfileClaimConfirmed}}
|
||||
|
||||
if _, err := service.SaveMyProfile(context.Background(), id, 0, input); !errors.Is(err, outbound.ErrTransactionConflict) {
|
||||
t.Fatalf("SaveMyProfile() error = %v, want transaction conflict", err)
|
||||
}
|
||||
if profiles.advanceCalls != 0 {
|
||||
t.Fatalf("onboarding advances %d times after a failed write, want 0", profiles.advanceCalls)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user