package invitation import ( "context" "crypto/sha256" "errors" "fmt" "slices" "strings" "sync" "testing" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/candidateview" ) type testKeyring struct{} func (testKeyring) IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte { return sha256.Sum256([]byte(operation + "\x00" + key + "\x00" + principal)) } func (testKeyring) Fingerprint(body []byte) [outbound.IdempotencyDigestSize]byte { return sha256.Sum256(body) } type termsKey struct { invitationID uuid.UUID version int64 } type testState struct { users map[uuid.UUID]domain.User memberships map[[2]uuid.UUID]domain.Membership invitations map[uuid.UUID]domain.Invitation terms map[termsKey]domain.InvitationTerms events []domain.InvitationEvent idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord results map[[outbound.IdempotencyDigestSize]byte]domain.OrganizationInvitationView sendResults map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationSendResult needVersions map[[3]string]bool // declines holds the stored declines by invitation, and declineResults // the decline outcomes kept under a key. declines map[uuid.UUID]domain.InvitationDecline declineResults map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationDeclineResult // charged lists the invitations charged against the organization quota, // and notified the delivered invitations that were notified. charged []uuid.UUID notified []uuid.UUID } func newTestState() testState { return testState{ users: map[uuid.UUID]domain.User{}, memberships: map[[2]uuid.UUID]domain.Membership{}, invitations: map[uuid.UUID]domain.Invitation{}, terms: map[termsKey]domain.InvitationTerms{}, idempotency: map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord{}, results: map[[outbound.IdempotencyDigestSize]byte]domain.OrganizationInvitationView{}, sendResults: map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationSendResult{}, needVersions: map[[3]string]bool{}, declines: map[uuid.UUID]domain.InvitationDecline{}, declineResults: map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationDeclineResult{}, } } func (state testState) clone() testState { cloned := newTestState() for id, user := range state.users { cloned.users[id] = user } for key, membership := range state.memberships { cloned.memberships[key] = membership } for id, invitation := range state.invitations { cloned.invitations[id] = invitation } for key, terms := range state.terms { cloned.terms[key] = terms.Clone() } cloned.events = slices.Clone(state.events) for scope, record := range state.idempotency { cloned.idempotency[scope] = record } for scope, result := range state.results { cloned.results[scope] = result } for scope, result := range state.sendResults { cloned.sendResults[scope] = result } for key, found := range state.needVersions { cloned.needVersions[key] = found } for id, decline := range state.declines { cloned.declines[id] = decline } for scope, result := range state.declineResults { cloned.declineResults[scope] = result } cloned.charged = slices.Clone(state.charged) cloned.notified = slices.Clone(state.notified) return cloned } type testTransactor struct { mu sync.Mutex state testState policy domain.PolicyVersion failResultSave bool } func (transactor *testTransactor) WithinTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error { transactor.mu.Lock() defer transactor.mu.Unlock() working := transactor.state.clone() unit := &testUnit{state: &working, policy: transactor.policy, failResultSave: transactor.failResultSave} if err := work(ctx, unit); err != nil { return err } transactor.state = working return nil } func (transactor *testTransactor) snapshot() testState { transactor.mu.Lock() defer transactor.mu.Unlock() return transactor.state.clone() } type testUnit struct { outbound.UnitOfWork state *testState policy domain.PolicyVersion failResultSave bool } func (unit *testUnit) Users() outbound.UserRepository { return testUsers{state: unit.state} } func (unit *testUnit) Organizations() outbound.OrganizationRepository { return testOrganizations{state: unit.state} } func (unit *testUnit) IdempotencyRecords() outbound.IdempotencyRepository { return testIdempotency{state: unit.state} } func (unit *testUnit) CompanyQuotas() outbound.CompanyQuotaRepository { return testQuotas{} } func (unit *testUnit) Policies() outbound.PolicyRepository { return testPolicies{version: unit.policy} } func (unit *testUnit) Invitations() outbound.InvitationRepository { return testInvitations{state: unit.state} } func (unit *testUnit) InvitationCreationResults() outbound.InvitationCreationResultRepository { return testInvitations{state: unit.state, failResultSave: unit.failResultSave} } func (unit *testUnit) InvitationSendResults() outbound.InvitationSendResultRepository { return testInvitations{state: unit.state} } func (unit *testUnit) InvitationDeclineResults() outbound.InvitationDeclineResultRepository { return testInvitations{state: unit.state} } type testUsers struct { outbound.UserRepository state *testState } func (repository testUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) { user, ok := repository.state.users[id] if !ok { return domain.User{}, outbound.ErrUserNotFound } return user, nil } type testOrganizations struct { outbound.OrganizationRepository state *testState } func (repository testOrganizations) LockActiveMembership(_ context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) { membership, ok := repository.state.memberships[[2]uuid.UUID{organizationID, userID}] if !ok || !membership.GrantsAccess() { return domain.Membership{}, outbound.ErrOrganizationNotFound } return membership, nil } func (repository testOrganizations) GetForMember(_ context.Context, organizationID, userID uuid.UUID) (domain.Organization, domain.Membership, error) { membership, ok := repository.state.memberships[[2]uuid.UUID{organizationID, userID}] if !ok || !membership.GrantsAccess() { return domain.Organization{}, domain.Membership{}, outbound.ErrOrganizationNotFound } return domain.Organization{}, membership, nil } type testQuotas struct { outbound.CompanyQuotaRepository } func (testQuotas) LockOrganization(context.Context, uuid.UUID) error { return nil } type testPolicies struct { outbound.PolicyRepository version domain.PolicyVersion } func (policies testPolicies) GetEffective(context.Context, domain.PolicyKey, time.Time) (domain.PolicyVersion, error) { return policies.version, nil } type testIdempotency struct { outbound.IdempotencyRepository state *testState } func (repository testIdempotency) Reserve(_ context.Context, record outbound.IdempotencyRecord) (outbound.IdempotencyRecord, bool, error) { if existing, ok := repository.state.idempotency[record.Scope]; ok && existing.ExpiresAt.After(record.CreatedAt) { return existing, false, nil } repository.state.idempotency[record.Scope] = record return record, true, nil } func (repository testIdempotency) PurgeExpired(_ context.Context, at time.Time, _ int32) (int64, error) { var deleted int64 for scope, record := range repository.state.idempotency { if !record.ExpiresAt.After(at) { delete(repository.state.idempotency, scope) delete(repository.state.results, scope) delete(repository.state.sendResults, scope) delete(repository.state.declineResults, scope) deleted++ } } return deleted, nil } type testInvitations struct { state *testState failResultSave bool } func (repository testInvitations) Create(_ context.Context, invitation domain.Invitation, event domain.InvitationEvent) error { repository.state.invitations[invitation.ID()] = invitation repository.state.terms[termsKey{invitation.ID(), 1}] = invitation.Snapshot().Terms repository.state.events = append(repository.state.events, event) return nil } func (repository testInvitations) Get(_ context.Context, organizationID, invitationID uuid.UUID) (domain.Invitation, error) { invitation, ok := repository.state.invitations[invitationID] if !ok || invitation.OrganizationID() != organizationID { return domain.Invitation{}, outbound.ErrInvitationNotFound } return invitation, nil } func (repository testInvitations) GetForUpdate(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.Invitation, error) { return repository.Get(ctx, organizationID, invitationID) } func (repository testInvitations) List(_ context.Context, query outbound.InvitationListQuery) (outbound.InvitationPage, error) { var items []domain.Invitation for _, invitation := range repository.state.invitations { if invitation.OrganizationID() == query.OrganizationID { items = append(items, invitation) } } slices.SortFunc(items, func(left, right domain.Invitation) int { return strings.Compare(right.ID().String(), left.ID().String()) }) page := outbound.InvitationPage{HasMore: len(items) > int(query.Limit)} if page.HasMore { items = items[:query.Limit] } page.Items = items return page, nil } func (repository testInvitations) SaveDraft(_ context.Context, expectedVersion int64, next domain.Invitation, termsChanged bool, event domain.InvitationEvent) error { current, ok := repository.state.invitations[next.ID()] if !ok || current.Version() != expectedVersion || current.State() != domain.InvitationDraft { return outbound.ErrInvitationVersionConflict } repository.state.invitations[next.ID()] = next if termsChanged { repository.state.terms[termsKey{next.ID(), next.TermsVersion()}] = next.Snapshot().Terms } repository.state.events = append(repository.state.events, event) return nil } func (repository testInvitations) Deliver(_ context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error { current, ok := repository.state.invitations[next.ID()] if !ok || current.Version() != expectedVersion || current.State() != domain.InvitationDraft { return outbound.ErrInvitationVersionConflict } repository.state.invitations[next.ID()] = next repository.state.events = append(repository.state.events, event) return nil } func (repository testInvitations) ListForCandidate(_ context.Context, query outbound.CandidateInvitationListQuery) (outbound.CandidateInvitationPage, error) { var items []outbound.CandidateInvitationEntry for _, invitation := range repository.state.invitations { if invitation.CandidateID() == query.CandidateID && invitation.IsDelivered() { items = append(items, outbound.CandidateInvitationEntry{Invitation: invitation, OrganizationName: "Test organization"}) } } page := outbound.CandidateInvitationPage{HasMore: len(items) > int(query.Limit)} if page.HasMore { items = items[:query.Limit] } page.Items = items return page, nil } func (repository testInvitations) GetForCandidate(_ context.Context, candidateID, invitationID uuid.UUID) (domain.Invitation, error) { invitation, ok := repository.state.invitations[invitationID] if !ok || invitation.CandidateID() != candidateID || !invitation.IsDelivered() { return domain.Invitation{}, outbound.ErrInvitationNotFound } return invitation, nil } func (repository testInvitations) SaveSendResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, result outbound.InvitationSendResult) error { repository.state.sendResults[scope] = result return nil } func (repository testInvitations) GetSendResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (outbound.InvitationSendResult, error) { result, ok := repository.state.sendResults[scope] if !ok { return outbound.InvitationSendResult{}, outbound.ErrInvitationSendResultNotFound } return result, nil } func (repository testInvitations) NeedVersionExists(_ context.Context, organizationID, needID uuid.UUID, version int64) (bool, error) { return repository.state.needVersions[[3]string{organizationID.String(), needID.String(), fmt.Sprint(version)}], nil } func (repository testInvitations) SaveCreationResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, result domain.OrganizationInvitationView) error { if repository.failResultSave { return errors.New("result store failed") } repository.state.results[scope] = result return nil } func (repository testInvitations) GetCreationResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (domain.OrganizationInvitationView, error) { result, ok := repository.state.results[scope] if !ok { return domain.OrganizationInvitationView{}, outbound.ErrInvitationCreationResultNotFound } return result, nil } type harness struct { service *Service transactor *testTransactor // quotaLeft is the number of new invitations the organization quota // still allows. quotaLeft int key domain.CandidateViewPseudonymKey actorID uuid.UUID organizationID uuid.UUID // visible maps a handle of the organization to its candidate. visible map[string]uuid.UUID setTime func(time.Time) } func newHarness(t *testing.T) *harness { t.Helper() now := time.Date(2026, time.October, 9, 10, 0, 0, 0, time.UTC) current := now actorID, organizationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()) verifiedAt := now.Add(-time.Hour) state := newTestState() state.users[actorID] = domain.User{ID: actorID, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verifiedAt} owner, err := domain.NewOwnerMembership(organizationID, actorID, now) if err != nil { t.Fatalf("NewOwnerMembership() error = %v", err) } state.memberships[[2]uuid.UUID{organizationID, actorID}] = owner key, err := domain.NewCandidateViewPseudonymKey([]byte(strings.Repeat("invitation-test-key-", 3))) if err != nil { t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err) } test := &harness{ transactor: &testTransactor{state: state, policy: testPolicyVersion(t, now)}, key: key, actorID: actorID, organizationID: organizationID, visible: map[string]uuid.UUID{}, quotaLeft: 10, setTime: func(value time.Time) { current = value }, } test.service, err = NewService(Dependencies{ Transactor: test.transactor, Keyring: testKeyring{}, PseudonymKey: key, Clock: func() time.Time { return current }, Candidates: func(_ context.Context, _ outbound.UnitOfWork, _, organizationID uuid.UUID, handle string) (uuid.UUID, error) { candidateID, ok := test.visible[handle] if !ok || organizationID != test.organizationID { return uuid.Nil, candidateview.ErrCandidateCardNotFound } return candidateID, nil }, Quota: func(_ context.Context, unit outbound.UnitOfWork, _ domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) { state := unit.(*testUnit).state if slices.Contains(state.charged, invitationID) { return outbound.CompanyQuotaDecision{Allowed: true, Reused: true}, nil } if len(state.charged) >= test.quotaLeft { return outbound.CompanyQuotaDecision{RetryAt: current.Add(time.Hour)}, nil } state.charged = append(state.charged, invitationID) return outbound.CompanyQuotaDecision{Allowed: true}, nil }, Notifier: testNotifier{}, }) if err != nil { t.Fatalf("NewService() error = %v", err) } return test } // showCandidate makes a new candidate visible to the organization and returns // the handle of the card. func (test *harness) showCandidate(t *testing.T) (string, uuid.UUID) { t.Helper() candidateID := uuid.Must(uuid.NewV7()) handle, err := test.key.ForOrganization(test.organizationID, candidateID) if err != nil { t.Fatalf("ForOrganization() error = %v", err) } test.visible[handle] = candidateID return handle, candidateID } type testNotifier struct{} func (testNotifier) InvitationDelivered(_ context.Context, unit outbound.UnitOfWork, invitation domain.Invitation) error { state := unit.(*testUnit).state state.notified = append(state.notified, invitation.ID()) return nil } func testPolicyVersion(t *testing.T, at time.Time) domain.PolicyVersion { t.Helper() draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV1(), }) if err != nil { t.Fatalf("NewPolicyVersionDraft() error = %v", err) } numbered, err := draft.WithVersion(1) if err != nil { t.Fatalf("WithVersion() error = %v", err) } hash := numbered.DocumentHash() version, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{ ID: numbered.ID(), Key: string(numbered.Key()), Version: numbered.Version(), Kind: string(numbered.Kind()), Author: string(numbered.Author()), EffectiveAt: at, CreatedAt: at, Document: numbered.Document(), DocumentHash: hash[:], }) if err != nil { t.Fatalf("RestorePolicyVersion() error = %v", err) } return version } func testTerms() domain.InvitationTerms { none := domain.InvitationPackageItem{Status: domain.InvitationPackageNotProvided} return domain.InvitationTerms{ RoleTitle: "Middle Go developer", Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle, OfferType: domain.InvitationOfferFullTime, Tasks: []string{"Build the payout service"}, Team: "Six engineers", TechStack: []string{"Go"}, WorkFormats: []domain.NeedWorkFormat{domain.NeedWorkFormatRemote}, CommunicationMethod: domain.InvitationCommunicationMethod{Channel: domain.InvitationChannelEmail}, Salary: domain.SalaryRange{SalaryFrom: 100_000, SalaryTo: 140_000, Currency: "RUB", Period: "month", TaxBasis: "net"}, Package: domain.InvitationPackage{Bonus: none, Equipment: none, Training: none, HealthInsurance: none}, } } func (test *harness) createCommand(handle, key string) CreateCommand { return CreateCommand{ ActorID: test.actorID, OrganizationID: test.organizationID, IdempotencyKey: key, CanonicalBody: []byte(fmt.Sprintf(`{"candidate_handle":%q,"key":%q}`, handle, key)), CandidateHandle: handle, Terms: testTerms(), } } func fieldPointer(t *testing.T, err error) string { t.Helper() field, ok := errors.AsType[*domain.InvitationFieldError](err) if !ok { t.Fatalf("error = %v, want a field error", err) } return field.Pointer } func TestCreateStoresADraftForAVisibleCandidateWithTheDefaultPeriod(t *testing.T) { test := newHarness(t) handle, candidateID := test.showCandidate(t) view, err := test.service.Create(t.Context(), test.createCommand(handle, "key-1")) if err != nil { t.Fatalf("Create() error = %v", err) } if view.State != domain.InvitationDraft || view.Version != 1 || view.TermsVersion != 1 || view.ResponsePeriodDays != 7 || view.CandidateHandle != handle || view.SalaryFit != domain.InvitationSalaryNotAvailable || view.ContactAccess != domain.InvitationContactAccessNone || view.ResponseDeadlineAt != nil { t.Fatalf("created view = %+v, want an unsent version 1 with the default period for the card handle", view.InvitationSnapshot) } state := test.transactor.snapshot() stored := state.invitations[view.ID] if stored.CandidateID() != candidateID || len(state.events) != 1 || state.events[0].Kind != domain.InvitationEventDraftCreated || state.events[0].ActorID != test.actorID { t.Fatalf("stored candidate/events = %v/%+v, want the resolved candidate and one creation event", stored.CandidateID() == candidateID, state.events) } } func TestCreateRefusesEveryCandidateTheOrganizationCannotUseWithTheSamePointer(t *testing.T) { test := newHarness(t) otherOrganization := uuid.Must(uuid.NewV7()) foreign, err := test.key.ForOrganization(otherOrganization, uuid.Must(uuid.NewV7())) if err != nil { t.Fatalf("ForOrganization() error = %v", err) } unknown := "cv1_" + strings.Repeat("Z", 43) for name, handle := range map[string]string{"another organization": foreign, "unknown": unknown, "malformed": "not-a-handle"} { command := test.createCommand(handle, "key-"+name) _, err := test.service.Create(t.Context(), command) if pointer := fieldPointer(t, err); pointer != "/candidate_handle" { t.Errorf("%s: pointer = %s, want /candidate_handle", name, pointer) } } state := test.transactor.snapshot() if len(state.invitations) != 0 || len(state.events) != 0 || len(state.idempotency) != 0 || len(state.results) != 0 { t.Fatalf("refused creates left state: %d invitations, %d events, %d keys, %d results", len(state.invitations), len(state.events), len(state.idempotency), len(state.results)) } } func TestCreateAppliesTheDomainRulesInTheContractOrderAndStoresNothingOnFailure(t *testing.T) { test := newHarness(t) handle, _ := test.showCandidate(t) needID := uuid.Must(uuid.NewV7()) command := test.createCommand(handle, "key-need") command.Need = &domain.InvitationNeedRef{NeedID: needID, RequirementsVersion: 1} command.Terms.Salary.SalaryTo = 500_000 _, err := test.service.Create(t.Context(), command) if pointer := fieldPointer(t, err); pointer != "/need" { t.Fatalf("pointer = %s, want /need before the terms", pointer) } test.transactor.state.needVersions[[3]string{test.organizationID.String(), needID.String(), "1"}] = true _, err = test.service.Create(t.Context(), command) if pointer := fieldPointer(t, err); pointer != "/terms/salary/salary_to" { t.Fatalf("pointer = %s, want the salary range", pointer) } command = test.createCommand(handle, "key-period") period := int32(5) command.ResponsePeriodDays = &period _, err = test.service.Create(t.Context(), command) if pointer := fieldPointer(t, err); pointer != "/response_period_days" { t.Fatalf("pointer = %s, want /response_period_days", pointer) } if state := test.transactor.snapshot(); len(state.invitations) != 0 || len(state.idempotency) != 0 { t.Fatalf("failed creates stored %d invitations and %d keys", len(state.invitations), len(state.idempotency)) } } func TestCreateReplaysTheOriginalResponseAndRejectsAChangedRequest(t *testing.T) { test := newHarness(t) handle, _ := test.showCandidate(t) command := test.createCommand(handle, "key-replay") first, err := test.service.Create(t.Context(), command) if err != nil { t.Fatalf("Create() error = %v", err) } // The candidate stops being visible; the replay still returns the stored // response and creates nothing. delete(test.visible, handle) replay, err := test.service.Create(t.Context(), command) if err != nil || replay.ID != first.ID || replay.Version != 1 { t.Fatalf("replay = %v, %v; want the original draft", replay.ID, err) } changed := command changed.CanonicalBody = []byte(`{"different":true}`) if _, err := test.service.Create(t.Context(), changed); !errors.Is(err, ErrIdempotencyKeyReused) { t.Fatalf("Create(changed body) error = %v, want ErrIdempotencyKeyReused", err) } if state := test.transactor.snapshot(); len(state.invitations) != 1 || len(state.events) != 1 { t.Fatalf("replay stored %d invitations and %d events, want one each", len(state.invitations), len(state.events)) } } func TestCreateRollbackLeavesNoDraftWhenTheResponseCannotBeStored(t *testing.T) { test := newHarness(t) handle, _ := test.showCandidate(t) test.transactor.failResultSave = true if _, err := test.service.Create(t.Context(), test.createCommand(handle, "key-fail")); err == nil { t.Fatal("Create() succeeded although the response could not be stored") } if state := test.transactor.snapshot(); len(state.invitations) != 0 || len(state.events) != 0 || len(state.idempotency) != 0 { t.Fatalf("failed create left %d invitations, %d events, %d keys", len(state.invitations), len(state.events), len(state.idempotency)) } } func TestOnlyTheActiveOwnerOfAnEmployerAccountMayWorkWithInvitations(t *testing.T) { test := newHarness(t) handle, _ := test.showCandidate(t) verified := time.Date(2026, time.October, 9, 9, 0, 0, 0, time.UTC) addAccount := func(scenario domain.Scenario) uuid.UUID { id := uuid.Must(uuid.NewV7()) test.transactor.state.users[id] = domain.User{ID: id, Scenario: scenario, EmailVerifiedAt: &verified} return id } recruiter := addAccount(domain.ScenarioEmployer) membership, err := domain.NewMembership(domain.MembershipInput{ OrganizationID: test.organizationID, UserID: recruiter, Role: domain.OrganizationRoleRecruiter, At: verified, }) if err != nil { t.Fatalf("NewMembership() error = %v", err) } test.transactor.state.memberships[[2]uuid.UUID{test.organizationID, recruiter}] = membership unverified := uuid.Must(uuid.NewV7()) test.transactor.state.users[unverified] = domain.User{ID: unverified, Scenario: domain.ScenarioEmployer} ownerMembership, _ := domain.NewOwnerMembership(test.organizationID, unverified, verified) test.transactor.state.memberships[[2]uuid.UUID{test.organizationID, unverified}] = ownerMembership tests := []struct { name string actor uuid.UUID want error }{ {"recruiter", recruiter, outbound.ErrOrganizationManagerRequired}, {"candidate account", addAccount(domain.ScenarioCandidate), ErrForbidden}, {"employer outside the organization", addAccount(domain.ScenarioEmployer), outbound.ErrOrganizationNotFound}, {"owner without a confirmed email", unverified, ErrEmailNotVerified}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { command := test.createCommand(handle, "key-"+tt.name) command.ActorID = tt.actor if _, err := test.service.Create(t.Context(), command); !errors.Is(err, tt.want) { t.Errorf("Create() error = %v, want %v", err, tt.want) } if _, err := test.service.List(t.Context(), ListCommand{ActorID: tt.actor, OrganizationID: test.organizationID, Limit: 10}); !errors.Is(err, tt.want) { t.Errorf("List() error = %v, want %v", err, tt.want) } if _, err := test.service.Get(t.Context(), tt.actor, test.organizationID, uuid.New()); !errors.Is(err, tt.want) { t.Errorf("Get() error = %v, want %v", err, tt.want) } send := SendCommand{ActorID: tt.actor, OrganizationID: test.organizationID, InvitationID: uuid.New(), IdempotencyKey: "send-" + tt.name, ExpectedVersion: 1} if _, err := test.service.Send(t.Context(), send); !errors.Is(err, tt.want) { t.Errorf("Send() error = %v, want %v", err, tt.want) } }) } if state := test.transactor.snapshot(); len(state.invitations) != 0 { t.Fatalf("a refused actor created %d invitations", len(state.invitations)) } } func (test *harness) createDraft(t *testing.T, key string) domain.OrganizationInvitationView { t.Helper() handle, _ := test.showCandidate(t) view, err := test.service.Create(t.Context(), test.createCommand(handle, key)) if err != nil { t.Fatalf("Create() error = %v", err) } return view } func (test *harness) update(command UpdateCommand) (domain.OrganizationInvitationView, error) { command.ActorID, command.OrganizationID = test.actorID, test.organizationID return test.service.Update(context.Background(), command) } func TestUpdateFollowsTheDocumentedOrderOfChecks(t *testing.T) { test := newHarness(t) draft := test.createDraft(t, "key-order") test.setTime(time.Date(2026, time.October, 9, 10, 5, 0, 0, time.UTC)) changedTerms := testTerms() changedTerms.Salary.SalaryTo = 150_000 updated, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 1, Terms: &changedTerms}) if err != nil || updated.Version != 2 || updated.TermsVersion != 2 || updated.Terms.Salary.SalaryTo != 150_000 { t.Fatalf("Update(terms) = version %d/%d, %v; want 2/2", updated.Version, updated.TermsVersion, err) } state := test.transactor.snapshot() if first := state.terms[termsKey{draft.ID, 1}]; first.Salary.SalaryTo != 140_000 { t.Fatalf("terms version 1 changed to %d", first.Salary.SalaryTo) } if len(state.events) != 2 || state.events[1].Kind != domain.InvitationEventDraftUpdated || fmt.Sprint(state.events[1].ChangedFields) != "[terms]" { t.Fatalf("events = %+v, want a draft_updated event for the terms", state.events) } // 1. A body that changes nothing answers with the current invitation even // when the version it names is stale. repeated, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 1, Terms: &changedTerms}) if err != nil || repeated.Version != 2 { t.Fatalf("Update(retry) = version %d, %v; want the current version 2", repeated.Version, err) } // 2. A stale version beats the domain rules. invalid := testTerms() invalid.Salary.SalaryTo = 500_000 if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 1, Terms: &invalid}); !errors.Is(err, domain.ErrInvitationVersionConflict) { t.Fatalf("Update(stale, invalid) error = %v, want a version conflict", err) } // 3. A rule violation of a current version is a field error and changes nothing. _, err = test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 2, Terms: &invalid}) if pointer := fieldPointer(t, err); pointer != "/terms/salary/salary_to" { t.Fatalf("pointer = %s, want the salary range", pointer) } // 4. A period outside the policy and an unknown need are field errors. period := int32(5) if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 2, ResponsePeriodDays: &period}); fieldPointer(t, err) != "/response_period_days" { t.Fatalf("Update(period 5) error = %v", err) } need := Field[domain.InvitationNeedRef]{Set: true, Value: domain.InvitationNeedRef{NeedID: uuid.New(), RequirementsVersion: 1}} if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 2, Need: need}); fieldPointer(t, err) != "/need" { t.Fatalf("Update(unknown need) error = %v", err) } if after := test.transactor.snapshot(); after.invitations[draft.ID].Version() != 2 || len(after.events) != 2 { t.Fatalf("rejected updates changed the draft: version %d, %d events", after.invitations[draft.ID].Version(), len(after.events)) } } func TestUpdateKeepsTheTermsVersionWhenOnlyThePeriodOrTheNeedChanges(t *testing.T) { test := newHarness(t) draft := test.createDraft(t, "key-parts") needID := uuid.Must(uuid.NewV7()) test.transactor.state.needVersions[[3]string{test.organizationID.String(), needID.String(), "2"}] = true period := int32(14) linked, err := test.update(UpdateCommand{ InvitationID: draft.ID, ExpectedVersion: 1, ResponsePeriodDays: &period, Need: Field[domain.InvitationNeedRef]{Set: true, Value: domain.InvitationNeedRef{NeedID: needID, RequirementsVersion: 2}}, }) if err != nil || linked.Version != 2 || linked.TermsVersion != 1 || linked.ResponsePeriodDays != 14 || linked.Need == nil || linked.Need.NeedID != needID { t.Fatalf("Update(period, need) = version %d/%d period %d, %v; want 2/1 with the link", linked.Version, linked.TermsVersion, linked.ResponsePeriodDays, err) } unlinked, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 2, Need: Field[domain.InvitationNeedRef]{Set: true, Null: true}}) if err != nil || unlinked.Version != 3 || unlinked.Need != nil || unlinked.TermsVersion != 1 { t.Fatalf("Update(unlink) = version %d need %v, %v; want version 3 without a need", unlinked.Version, unlinked.Need, err) } if state := test.transactor.snapshot(); len(state.terms) != 1 { t.Fatalf("stored %d terms versions, want only the first", len(state.terms)) } } func TestUpdateRefusesAnInvitationThatLeftTheDraftState(t *testing.T) { test := newHarness(t) draft := test.createDraft(t, "key-state") stored := test.transactor.state.invitations[draft.ID].Stored() stored.State = string(domain.InvitationWithdrawn) withdrawn, err := domain.RestoreInvitation(stored) if err != nil { t.Fatalf("RestoreInvitation() error = %v", err) } test.transactor.state.invitations[draft.ID] = withdrawn changed := testTerms() changed.RoleTitle = "Senior Go developer" if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 1, Terms: &changed}); !errors.Is(err, domain.ErrInvitationNotDraft) { t.Fatalf("Update(withdrawn) error = %v, want ErrInvitationNotDraft", err) } // A stale version of a withdrawn invitation is still reported as the state. if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 7, Terms: &changed}); !errors.Is(err, domain.ErrInvitationVersionConflict) { t.Fatalf("Update(stale, withdrawn) error = %v, want the version comparison first", err) } } func TestReadsAreScopedToTheOrganizationAndPaged(t *testing.T) { test := newHarness(t) first := test.createDraft(t, "key-1") second := test.createDraft(t, "key-2") third := test.createDraft(t, "key-3") if got, err := test.service.Get(t.Context(), test.actorID, test.organizationID, second.ID); err != nil || got.ID != second.ID { t.Fatalf("Get() = %v, %v; want the draft", got.ID, err) } if _, err := test.service.Get(t.Context(), test.actorID, uuid.Must(uuid.NewV7()), second.ID); !errors.Is(err, outbound.ErrOrganizationNotFound) { t.Fatalf("Get(other organization) error = %v, want not found", err) } if _, err := test.service.Get(t.Context(), test.actorID, test.organizationID, uuid.New()); !errors.Is(err, outbound.ErrInvitationNotFound) { t.Fatalf("Get(unknown) error = %v, want not found", err) } page, err := test.service.List(t.Context(), ListCommand{ActorID: test.actorID, OrganizationID: test.organizationID, Limit: 2}) if err != nil || len(page.Items) != 2 || !page.HasMore { t.Fatalf("List(2) = %d items more=%t, %v; want a first page of two", len(page.Items), page.HasMore, err) } ids := map[uuid.UUID]bool{first.ID: true, second.ID: true, third.ID: true} for _, item := range page.Items { if !ids[item.ID] || item.CandidateHandle == "" { t.Fatalf("listed item %v is unknown or has no alias", item.ID) } } if _, err := test.service.List(t.Context(), ListCommand{ActorID: test.actorID, OrganizationID: test.organizationID, Limit: 0}); !errors.Is(err, ErrInvalidRequest) { t.Fatalf("List(0) error = %v, want ErrInvalidRequest", err) } } func (repository testInvitations) GetTermsVersion(_ context.Context, _, invitationID uuid.UUID, version int64) (domain.InvitationTerms, error) { terms, ok := repository.state.terms[termsKey{invitationID, version}] if !ok { return domain.InvitationTerms{}, outbound.ErrInvitationNotFound } return terms, nil }