package invitation import ( "context" "errors" "strings" "testing" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) // testC4Version is the published C4 text of the fakes. const testC4Version = domain.ConsentTextVersion("c4-2026-10-01") func (unit *testUnit) ContactGrants() outbound.ContactGrantRepository { return testContactGrants{state: unit.state} } func (unit *testUnit) InvitationAcceptResults() outbound.InvitationAcceptResultRepository { return testInvitations{state: unit.state} } func (unit *testUnit) CandidateProfiles() outbound.CandidateProfileRepository { return testProfiles{state: unit.state} } func (unit *testUnit) ConsentTexts() outbound.ConsentTextRepository { return testConsentTexts{} } func (unit *testUnit) ConsentLedger() outbound.ConsentLedger { return testConsentLedger{state: unit.state} } func (unit *testUnit) PrivacySettings() outbound.PrivacySettingsRepository { return testPrivacySettings{state: unit.state} } // Accept applies the compare-and-swap of the acceptance like the database does: // the stored invitation must be answerable at the expected version. func (repository testInvitations) Accept(_ context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error { current, ok := repository.state.invitations[next.ID()] answerable := current.State() == domain.InvitationDelivered || current.State() == domain.InvitationViewed if !ok || current.Version() != expectedVersion || !answerable { return outbound.ErrInvitationVersionConflict } repository.state.invitations[next.ID()] = next repository.state.events = append(repository.state.events, event) return nil } func (repository testInvitations) SaveAcceptResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, result outbound.InvitationAcceptResult) error { repository.state.acceptResults[scope] = result return nil } func (repository testInvitations) GetAcceptResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (outbound.InvitationAcceptResult, error) { result, ok := repository.state.acceptResults[scope] if !ok { return outbound.InvitationAcceptResult{}, outbound.ErrInvitationAcceptResultNotFound } return result, nil } type testContactGrants struct { state *testState } func (repository testContactGrants) Create(_ context.Context, grant domain.ContactGrant) error { if _, exists := repository.state.grants[grant.InvitationID()]; exists { return errors.New("contact grant already exists") } repository.state.grants[grant.InvitationID()] = grant return nil } func (repository testContactGrants) GetByInvitation(_ context.Context, organizationID, invitationID uuid.UUID) (domain.ContactGrant, error) { grant, ok := repository.state.grants[invitationID] if !ok || grant.OrganizationID() != organizationID { return domain.ContactGrant{}, outbound.ErrContactGrantNotFound } return grant, nil } type testProfiles struct { outbound.CandidateProfileRepository state *testState } func (repository testProfiles) Get(_ context.Context, userID uuid.UUID) (domain.CandidateProfile, error) { if profile, ok := repository.state.profiles[userID]; ok { return profile, nil } return domain.EmptyCandidateProfile(userID) } // testConsentTexts publishes one C4 text that names the organization. type testConsentTexts struct { outbound.ConsentTextRepository } func (testConsentTexts) Current(_ context.Context, purpose domain.ConsentPurpose, _ time.Time) (domain.ConsentText, error) { if purpose != domain.ConsentPurposeContactDisclosure { return domain.ConsentText{}, outbound.ErrConsentTextNotFound } body := "I consent to the transfer of the contact data I select to {organization} for this invitation." hash := domain.HashConsentText(body) text, err := domain.RestoreConsentText(domain.StoredConsentText{ Purpose: string(purpose), Version: string(testC4Version), Body: body, Hash: hash[:], Kind: string(domain.ConsentTextKindDemo), PublishedAt: time.Date(2026, time.October, 1, 0, 0, 0, 0, time.UTC), }) if err != nil { return domain.ConsentText{}, err } return text, nil } // testConsentLedger stores the C4 record of an acceptance once per invitation, // as the ledger does. type testConsentLedger struct { outbound.ConsentLedger state *testState } func (ledger testConsentLedger) GrantContact(_ context.Context, grant domain.ContactConsentGrant) (domain.ConsentRecord, bool, error) { if existing, ok := ledger.state.consentRecords[grant.InvitationID()]; ok { return existing, false, nil } hash := grant.TextHash() fields := make([]string, 0, 4) for _, field := range grant.Fields().Fields() { fields = append(fields, string(field)) } record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{ ID: grant.ID(), SubjectID: grant.SubjectID(), Purpose: string(domain.ConsentPurposeContactDisclosure), TextVersion: string(grant.TextVersion()), TextHash: hash[:], Source: string(domain.ConsentSourceInvitationAcceptance), State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(), OrganizationID: grant.OrganizationID(), OrganizationName: grant.OrganizationName(), FieldSet: fields, InvitationID: grant.InvitationID(), InvitationTermsVersion: grant.InvitationTermsVersion(), }) if err != nil { return domain.ConsentRecord{}, false, err } ledger.state.consentRecords[grant.InvitationID()] = record return record, true, nil } // testPrivacySettings reads the publication and the hidings of the fakes. A // candidate who never published has the closed publication. type testPrivacySettings struct { outbound.PrivacySettingsRepository state *testState } func (repository testPrivacySettings) ReadSettings(_ context.Context, userID uuid.UUID) (outbound.CandidatePrivacySettings, error) { publication, ok := repository.state.publications[userID] if !ok { closed, err := domain.NewPublication(userID) if err != nil { return outbound.CandidatePrivacySettings{}, err } publication = closed } return outbound.CandidatePrivacySettings{Publication: publication}, nil } func (repository testPrivacySettings) GetHiddenOrganization(_ context.Context, userID, organizationID uuid.UUID) (outbound.HiddenOrganizationRecord, error) { if !repository.state.hidden[[2]uuid.UUID{userID, organizationID}] { return outbound.HiddenOrganizationRecord{}, outbound.ErrCandidatePrivacySettingsNotFound } return outbound.HiddenOrganizationRecord{OrganizationID: organizationID, OrganizationName: "Test organization"}, nil } // testProfile builds a candidate profile whose confirmed claims are the held // kinds, the way the profile service stores them. func testProfile(t *testing.T, candidateID uuid.UUID, held ...domain.ContactField) domain.CandidateProfile { t.Helper() confirmed := func(value string) *domain.ProfileClaimInput[string] { return &domain.ProfileClaimInput[string]{Value: value, Status: domain.ProfileClaimConfirmed} } var input domain.CandidateProfileInput for _, field := range held { switch field { case domain.ContactFieldFullName: input.FullName = confirmed("Test Candidate") case domain.ContactFieldEmail: input.Email = confirmed("candidate@example.test") case domain.ContactFieldPhone: input.Phone = confirmed("+70000000000") case domain.ContactFieldTelegram: input.Telegram = confirmed("@candidate_test") } } empty, err := domain.EmptyCandidateProfile(candidateID) if err != nil { t.Fatalf("EmptyCandidateProfile() error = %v", err) } profile, _, err := empty.Replace(input, 0, time.Date(2026, time.October, 9, 9, 0, 0, 0, time.UTC)) if err != nil { t.Fatalf("Replace() error = %v", err) } return profile } // setState changes the committed state of the fakes between commands. func (test *harness) setState(change func(state *testState)) { test.transactor.mu.Lock() defer test.transactor.mu.Unlock() change(&test.transactor.state) } func (test *harness) setProfile(t *testing.T, candidateID uuid.UUID, held ...domain.ContactField) { t.Helper() profile := testProfile(t, candidateID, held...) test.setState(func(state *testState) { state.profiles[candidateID] = profile }) } func (test *harness) publish(candidateID uuid.UUID, at time.Time) { publication, err := domain.RestorePublication(domain.StoredPublication{ UserID: candidateID, State: string(domain.PublicationPublished), Fields: []string{string(domain.CardFieldCategories)}, ConsentRecordID: uuid.Must(uuid.NewV7()), PublishedAt: at, Version: 1, }) if err != nil { panic(err) } test.setState(func(state *testState) { state.publications[candidateID] = publication }) } func acceptCommand(actorID, invitationID uuid.UUID, version, terms int64, key string, fields ...domain.ContactField) AcceptCommand { return AcceptCommand{ ActorID: actorID, InvitationID: invitationID, IdempotencyKey: key, ExpectedVersion: version, TermsVersion: terms, TextVersion: string(testC4Version), Fields: fields, } } func TestAcceptMineStoresTheAcceptanceAndTheGrantOfTheSelectedFieldsOnly(t *testing.T) { test := newHarness(t) sent, candidateID := test.deliveredTo(t) test.setProfile(t, candidateID, domain.ContactFieldEmail) test.setTime(sent.DeliveredAt.Add(time.Hour)) // The profile holds only the email, so a phone request is refused by its // pointer, and nothing is stored. _, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-phone", domain.ContactFieldPhone)) if got := fieldPointer(t, err); got != "/consent_c4/fields/0" { t.Fatalf("pointer = %s, want /consent_c4/fields/0", got) } if state := test.transactor.snapshot(); len(state.grants) != 0 || len(state.consentRecords) != 0 || len(state.acceptResults) != 0 { t.Fatalf("a refused acceptance stored grants %d, consents %d, outcomes %d", len(state.grants), len(state.consentRecords), len(state.acceptResults)) } view, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-email", domain.ContactFieldEmail)) if err != nil { t.Fatalf("AcceptMine() error = %v", err) } if view.State != domain.InvitationAccepted || view.Version != sent.Version+1 || view.TermsVersion != sent.TermsVersion || view.RespondedAt == nil || view.ContactConsent != nil || view.ContactGrant == nil { t.Fatalf("accepted = %+v, want the accepted invitation with its grant and no offer", view) } grant := view.ContactGrant if len(grant.Fields) != 1 || grant.Fields[0] != domain.ContactFieldEmail || grant.Status != domain.ContactGrantActive || grant.Readable || grant.BlockedBy == nil || *grant.BlockedBy != domain.ContactAccessBlockVisibility || grant.TermsVersion != sent.TermsVersion || grant.ConsentTextVersion != testC4Version { t.Fatalf("grant = %+v, want the email only, active, blocked by visibility while the profile is not published", grant) } state := test.transactor.snapshot() invitation := state.invitations[sent.ID] last := state.events[len(state.events)-1] if invitation.State() != domain.InvitationAccepted || len(state.grants) != 1 || len(state.consentRecords) != 1 || last.Kind != domain.InvitationEventAccepted || last.ActorID != candidateID || len(last.ChangedFields) != 0 { t.Fatalf("stored state = %s grants %d consents %d last event %s, want one acceptance, grant, and consent", invitation.State(), len(state.grants), len(state.consentRecords), last.Kind) } record := state.consentRecords[sent.ID] if record.InvitationTermsVersion() != sent.TermsVersion || record.OrganizationName() != "Test organization" || len(record.Fields().Fields()) != 1 || record.Fields().Fields()[0] != domain.ContactFieldEmail { t.Fatalf("C4 record = %s, want the organization, the terms version, and the email only", record) } } func TestAcceptMineRepeatsWithoutRecordingAgainAndRefusesAnotherChoice(t *testing.T) { test := newHarness(t) sent, candidateID := test.deliveredTo(t) test.setProfile(t, candidateID, domain.ContactFieldEmail, domain.ContactFieldPhone) test.setTime(sent.DeliveredAt.Add(time.Hour)) first, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-first", domain.ContactFieldEmail)) if err != nil { t.Fatalf("AcceptMine() error = %v", err) } before := test.transactor.snapshot() test.setTime(sent.DeliveredAt.Add(2 * time.Hour)) // A new key with the older expected version and the same terms and fields // answers the accepted invitation without a second grant or event. again, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-again", domain.ContactFieldEmail)) if err != nil || again.Version != first.Version || again.ContactGrant == nil || again.ContactGrant.ID != first.ContactGrant.ID { t.Fatalf("repeat = %+v, %v; want the first acceptance", again, err) } replay, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-first", domain.ContactFieldEmail)) if err != nil || replay.ContactGrant == nil || replay.ContactGrant.ID != first.ContactGrant.ID { t.Fatalf("replay = %+v, %v; want the stored response", replay, err) } after := test.transactor.snapshot() if len(after.events) != len(before.events) || len(after.grants) != 1 || len(after.consentRecords) != 1 { t.Fatalf("repeats stored events %d to %d, grants %d, consents %d", len(before.events), len(after.events), len(after.grants), len(after.consentRecords)) } // Another field set or a reused key with another body is refused, and the // refusal is stored under its key. if _, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-more", domain.ContactFieldEmail, domain.ContactFieldPhone)); !errors.Is(err, ErrAnswerBlocked) { t.Fatalf("another field set error = %v, want ErrAnswerBlocked", err) } if _, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-first", domain.ContactFieldPhone)); !errors.Is(err, ErrIdempotencyKeyReused) { t.Fatalf("reused key error = %v, want ErrIdempotencyKeyReused", err) } if got := test.transactor.snapshot().acceptResults; len(got) != 3 { t.Fatalf("stored outcomes = %d, want accepted, accepted again, and the refused field set", len(got)) } } func TestAcceptMineRefusesAStaleTermsVersionWithoutStoringAnything(t *testing.T) { test := newHarness(t) sent, candidateID := test.deliveredTo(t) test.setProfile(t, candidateID, domain.ContactFieldEmail) before := test.transactor.snapshot() // The terms the candidate read are not the current ones: 412, nothing // recorded, and no outcome under the key. for name, command := range map[string]AcceptCommand{ "stale terms": acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion+1, "stale-terms", domain.ContactFieldEmail), "stale version": acceptCommand(candidateID, sent.ID, sent.Version+1, sent.TermsVersion, "stale-version", domain.ContactFieldEmail), } { if _, err := test.service.AcceptMine(t.Context(), command); !errors.Is(err, domain.ErrInvitationVersionConflict) { t.Fatalf("%s error = %v, want ErrInvitationVersionConflict", name, err) } } after := test.transactor.snapshot() if len(after.grants) != 0 || len(after.consentRecords) != 0 || len(after.acceptResults) != 0 || len(after.events) != len(before.events) { t.Fatalf("a stale acceptance stored grants %d, consents %d, outcomes %d", len(after.grants), len(after.consentRecords), len(after.acceptResults)) } if after.invitations[sent.ID].State() != domain.InvitationDelivered { t.Fatalf("state = %s, want delivered", after.invitations[sent.ID].State()) } } func TestAcceptMineAtTheDeadlineStoresTheConflictAndGrantsNothing(t *testing.T) { test := newHarness(t) sent, candidateID := test.deliveredTo(t) test.setProfile(t, candidateID, domain.ContactFieldEmail) test.setTime(*sent.ResponseDeadlineAt) _, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version+5, sent.TermsVersion, "late", domain.ContactFieldEmail)) if !errors.Is(err, ErrAnswerBlocked) { t.Fatalf("late acceptance error = %v, want ErrAnswerBlocked whatever the version", err) } state := test.transactor.snapshot() if result := state.acceptResults[testKeyring{}.IdempotencyScope(acceptOperation, "late", candidateID.String())]; result.Outcome != outbound.InvitationAcceptStateConflict { t.Fatalf("stored outcome = %+v, want state_conflict under the key", result) } if len(state.grants) != 0 || len(state.consentRecords) != 0 || state.invitations[sent.ID].State() != domain.InvitationDelivered { t.Fatalf("a late acceptance changed the invitation: grants %d, consents %d", len(state.grants), len(state.consentRecords)) } } func TestAcceptMineChecksTheConsentTextAndTheHeldKinds(t *testing.T) { test := newHarness(t) sent, candidateID := test.deliveredTo(t) test.setProfile(t, candidateID, domain.ContactFieldFullName) test.setTime(sent.DeliveredAt.Add(time.Hour)) outdated := acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "outdated", domain.ContactFieldFullName) outdated.TextVersion = "c4-2025-01-01" if got := fieldPointer(t, mustFail(t, test, outdated)); got != "/consent_c4/text_version" { t.Fatalf("outdated text pointer = %s, want /consent_c4/text_version", got) } if got := fieldPointer(t, mustFail(t, test, acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "email", domain.ContactFieldFullName, domain.ContactFieldEmail))); got != "/consent_c4/fields/1" { t.Fatalf("unheld kind pointer = %s, want /consent_c4/fields/1", got) } if state := test.transactor.snapshot(); len(state.grants) != 0 || len(state.consentRecords) != 0 || len(state.acceptResults) != 0 { t.Fatalf("refused consent stored grants %d, consents %d, outcomes %d", len(state.grants), len(state.consentRecords), len(state.acceptResults)) } // The offer lists the held kinds in the order of the contract and shows the // text with the organization name. A profile without a kind has no offer. offered := decodeOffer(t, test, candidateID, sent.ID) if offered.Text.TextVersion != testC4Version || !strings.Contains(offered.Text.Text, "Test organization") || strings.Contains(offered.Text.Text, "{organization}") || len(offered.AvailableFields) != 1 || offered.AvailableFields[0] != domain.ContactFieldFullName { t.Fatalf("offer = %+v, want the rendered text and the held kind", offered) } test.setProfile(t, candidateID) read, err := test.service.GetMine(t.Context(), candidateID, sent.ID) if err != nil || read.ContactConsent != nil { t.Fatalf("GetMine without a held kind = %+v, %v; want no offer", read.ContactConsent, err) } } func TestAcceptedInvitationReadsTheGrantAndKeepsThePublicationAndTheHiding(t *testing.T) { test := newHarness(t) sent, candidateID := test.deliveredTo(t) test.setProfile(t, candidateID, domain.ContactFieldEmail) test.setTime(sent.DeliveredAt.Add(time.Hour)) test.publish(candidateID, *sent.DeliveredAt) test.setState(func(state *testState) { state.hidden[[2]uuid.UUID{candidateID, test.organizationID}] = true }) publications := test.transactor.snapshot().publications accepted, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "hidden", domain.ContactFieldEmail)) if err != nil { t.Fatalf("AcceptMine() while hidden error = %v", err) } if accepted.ContactGrant == nil || accepted.ContactGrant.Readable || accepted.ContactGrant.BlockedBy == nil { t.Fatalf("grant while hidden = %+v, want stored and blocked by visibility", accepted.ContactGrant) } state := test.transactor.snapshot() if len(state.publications) != len(publications) || state.publications[candidateID].State() != domain.PublicationPublished || !state.hidden[[2]uuid.UUID{candidateID, test.organizationID}] { t.Fatal("the acceptance changed the publication or lifted the hiding") } // Unhiding the organization makes the same grant readable; the grant // itself never changes. test.setState(func(state *testState) { delete(state.hidden, [2]uuid.UUID{candidateID, test.organizationID}) }) read, err := test.service.GetMine(t.Context(), candidateID, sent.ID) if err != nil || read.ContactGrant == nil || !read.ContactGrant.Readable || read.ContactGrant.BlockedBy != nil || read.ContactGrant.ID != accepted.ContactGrant.ID { t.Fatalf("read after unhiding = %+v, %v; want the same grant readable", read.ContactGrant, err) } } // decodeOffer reads the invitation of the candidate and returns its consent offer. func decodeOffer(t *testing.T, test *harness, candidateID, invitationID uuid.UUID) domain.ContactConsentOffer { t.Helper() read, err := test.service.GetMine(t.Context(), candidateID, invitationID) if err != nil { t.Fatalf("GetMine() error = %v", err) } if read.ContactConsent == nil { t.Fatal("GetMine() = no contact consent offer, want one") } return *read.ContactConsent } // mustFail returns the error of an acceptance that must be refused. func mustFail(t *testing.T, test *harness, command AcceptCommand) error { t.Helper() _, err := test.service.AcceptMine(t.Context(), command) if err == nil { t.Fatalf("AcceptMine(%s) succeeded, want a refusal", command.IdempotencyKey) } return err }