package organization import ( "context" "errors" "fmt" "strings" "sync" "testing" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/identity" ) type organizationTestState struct { users map[uuid.UUID]domain.User organizations map[uuid.UUID]domain.Organization memberships map[organizationTestMembershipKey]domain.Membership idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord results map[[outbound.IdempotencyDigestSize]byte]outbound.OrganizationCreationResult } type organizationTestMembershipKey struct { organizationID uuid.UUID userID uuid.UUID } func newOrganizationTestState() organizationTestState { return organizationTestState{ users: map[uuid.UUID]domain.User{}, organizations: map[uuid.UUID]domain.Organization{}, memberships: map[organizationTestMembershipKey]domain.Membership{}, idempotency: map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord{}, results: map[[outbound.IdempotencyDigestSize]byte]outbound.OrganizationCreationResult{}, } } func (state organizationTestState) clone() organizationTestState { cloned := newOrganizationTestState() for id, user := range state.users { cloned.users[id] = user } for id, company := range state.organizations { cloned.organizations[id] = company } for key, membership := range state.memberships { cloned.memberships[key] = membership } for scope, record := range state.idempotency { cloned.idempotency[scope] = record } for scope, result := range state.results { cloned.results[scope] = result } return cloned } type organizationTestTransactor struct { mu sync.Mutex state organizationTestState failOwnerInsert bool } func newOrganizationTestTransactor() *organizationTestTransactor { return &organizationTestTransactor{state: newOrganizationTestState()} } func (transactor *organizationTestTransactor) WithinTransaction( ctx context.Context, work func(context.Context, outbound.UnitOfWork) error, ) error { transactor.mu.Lock() defer transactor.mu.Unlock() working := transactor.state.clone() unit := &organizationTestUnit{state: &working, failOwnerInsert: transactor.failOwnerInsert} if err := work(ctx, unit); err != nil { return err } transactor.state = working return nil } func (transactor *organizationTestTransactor) snapshot() organizationTestState { transactor.mu.Lock() defer transactor.mu.Unlock() return transactor.state.clone() } type organizationTestUnit struct { outbound.UnitOfWork state *organizationTestState failOwnerInsert bool } func (unit *organizationTestUnit) Users() outbound.UserRepository { return organizationTestUsers{state: unit.state} } func (unit *organizationTestUnit) IdempotencyRecords() outbound.IdempotencyRepository { return organizationTestIdempotency{state: unit.state} } func (unit *organizationTestUnit) Organizations() outbound.OrganizationRepository { return organizationTestOrganizations{state: unit.state, failOwnerInsert: unit.failOwnerInsert} } type organizationTestUsers struct { outbound.UserRepository state *organizationTestState } func (repository organizationTestUsers) 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 organizationTestIdempotency struct { outbound.IdempotencyRepository state *organizationTestState } func (repository organizationTestIdempotency) Reserve( _ context.Context, record outbound.IdempotencyRecord, ) (outbound.IdempotencyRecord, bool, error) { if stored, ok := repository.state.idempotency[record.Scope]; ok && stored.ExpiresAt.After(record.CreatedAt) { return stored, false, nil } repository.state.idempotency[record.Scope] = record return record, true, nil } func (repository organizationTestIdempotency) Find( _ context.Context, scope [outbound.IdempotencyDigestSize]byte, at time.Time, ) (outbound.IdempotencyRecord, error) { record, ok := repository.state.idempotency[scope] if !ok || !record.ExpiresAt.After(at) { return outbound.IdempotencyRecord{}, outbound.ErrIdempotencyRecordNotFound } return record, nil } func (repository organizationTestIdempotency) PurgeExpired( _ context.Context, at time.Time, limit int32, ) (int64, error) { var deleted int64 for scope, record := range repository.state.idempotency { if deleted >= int64(limit) { break } if !record.ExpiresAt.After(at) { delete(repository.state.idempotency, scope) delete(repository.state.results, scope) deleted++ } } return deleted, nil } type organizationTestOrganizations struct { outbound.OrganizationRepository state *organizationTestState failOwnerInsert bool } func (repository organizationTestOrganizations) CreateWithOwner( _ context.Context, company domain.Organization, owner domain.Membership, ) error { repository.state.organizations[company.ID()] = company if repository.failOwnerInsert { return errors.New("simulated owner membership insert failure") } repository.state.memberships[organizationTestMembershipKey{company.ID(), owner.UserID()}] = owner return nil } func (repository organizationTestOrganizations) SaveCreationResult( _ context.Context, scope [outbound.IdempotencyDigestSize]byte, result outbound.OrganizationCreationResult, ) error { if _, ok := repository.state.idempotency[scope]; !ok { return outbound.ErrIdempotencyRecordNotFound } repository.state.results[scope] = result return nil } func (repository organizationTestOrganizations) GetCreationResult( _ context.Context, scope [outbound.IdempotencyDigestSize]byte, ) (outbound.OrganizationCreationResult, error) { result, ok := repository.state.results[scope] if !ok { return outbound.OrganizationCreationResult{}, outbound.ErrOrganizationCreationResultNotFound } return result, nil } func (repository organizationTestOrganizations) GetForMember( _ context.Context, organizationID, userID uuid.UUID, ) (domain.Organization, domain.Membership, error) { company, companyOK := repository.state.organizations[organizationID] membership, memberOK := repository.state.memberships[organizationTestMembershipKey{organizationID, userID}] if !companyOK || !memberOK || !membership.GrantsAccess() { return domain.Organization{}, domain.Membership{}, outbound.ErrOrganizationNotFound } return company, membership, nil } func (repository organizationTestOrganizations) ListForUser( context.Context, outbound.OrganizationListQuery, ) (outbound.OrganizationPage, error) { return outbound.OrganizationPage{}, nil } func (repository organizationTestOrganizations) UpdateProfile( _ context.Context, actorID uuid.UUID, updated domain.Organization, ) (domain.Organization, error) { current, ok := repository.state.organizations[updated.ID()] if !ok { return domain.Organization{}, outbound.ErrOrganizationNotFound } membership, ok := repository.state.memberships[organizationTestMembershipKey{updated.ID(), actorID}] if !ok || !membership.GrantsAccess() { return domain.Organization{}, outbound.ErrOrganizationNotFound } if !membership.CanManageOrganization() { return domain.Organization{}, outbound.ErrOrganizationManagerRequired } if current.Version() != updated.Version() { return domain.Organization{}, outbound.ErrOrganizationVersionConflict } company, err := restoreOrganizationVersion(updated, current.Version()+1) if err != nil { return domain.Organization{}, err } repository.state.organizations[updated.ID()] = company return company, nil } func restoreOrganizationVersion(company domain.Organization, version int64) (domain.Organization, error) { profile := company.Profile() contacts := profile.Contacts() representatives := profile.Representatives() storedRepresentatives := make([]domain.StoredRepresentative, 0, len(representatives)) for _, representative := range representatives { storedRepresentatives = append(storedRepresentatives, domain.StoredRepresentative{ Name: representative.Name(), JobTitle: representative.JobTitle(), }) } verification := company.Verification() return domain.RestoreOrganization(domain.StoredOrganization{ ID: company.ID(), Name: profile.Name(), Description: profile.Description(), Sphere: profile.Sphere(), Website: contacts.Website(), Email: contacts.Email(), Phone: contacts.Phone(), Telegram: contacts.Telegram(), Representatives: storedRepresentatives, VerificationLevel: string(verification.Level()), VerificationBasis: string(verification.Basis()), VerificationChangedAt: verification.ChangedAt(), Version: version, CreatedAt: company.CreatedAt(), UpdatedAt: company.UpdatedAt(), }) } func newOrganizationTestService(t *testing.T, tx *organizationTestTransactor, clock func() time.Time) *Service { t.Helper() keyring, err := identity.NewKeyring([]byte(strings.Repeat("k", identity.MinKeySecretBytes))) if err != nil { t.Fatalf("NewKeyring() error = %v", err) } service, err := NewService(Dependencies{Transactor: tx, Keyring: keyring, Clock: clock}) if err != nil { t.Fatalf("NewService() error = %v", err) } return service } func verifiedEmployer(id uuid.UUID, at time.Time) domain.User { verifiedAt := at return domain.User{ID: id, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verifiedAt} } func organizationProfile(name, description string) domain.OrganizationProfileInput { return domain.OrganizationProfileInput{ Name: name, Description: description, Sphere: "Payments", Contacts: domain.OrganizationContactsInput{ Website: "https://example.com", Email: "careers@example.com", Phone: "+74951234567", Telegram: "@example", }, Representatives: []domain.OrganizationRepresentativeInput{{Name: "Анна Тестова", JobTitle: "Директор"}}, } } func canonicalBodyForTest(t *testing.T, profile domain.OrganizationProfileInput) []byte { t.Helper() body, err := canonicalCreateBody(profile) if err != nil { t.Fatalf("canonicalCreateBody() error = %v", err) } return body } func TestCreateStoresOwnerAtE0AndReplaysOriginalSnapshotAfterEdit(t *testing.T) { ctx := t.Context() now := time.Date(2026, 8, 15, 10, 30, 0, 123456000, time.UTC) currentTime := now tx := newOrganizationTestTransactor() ownerID := uuid.New() tx.state.users[ownerID] = verifiedEmployer(ownerID, now) service := newOrganizationTestService(t, tx, func() time.Time { return currentTime }) profile := organizationProfile("ООО Пример", "Первоначальные данные") command := CreateCommand{ ActorID: ownerID, IdempotencyKey: "company-create-01", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile, } created, err := service.Create(ctx, command) if err != nil { t.Fatalf("Create() error = %v", err) } if created.Replayed || created.Organization.Version() != 1 || created.Owner.UserID() != ownerID || created.Owner.Role() != domain.OrganizationRoleOwner || !created.Owner.GrantsAccess() { t.Fatalf("Create() = %+v, want a new version 1 organization and its active owner", created) } verification := created.Organization.Verification() if verification.Level() != domain.OrganizationVerificationE0 || verification.Basis() != domain.OrganizationBasisConfirmedEmail { t.Fatalf("verification = %s %s, want e0 from confirmed email", verification.Level(), verification.Basis()) } if card := created.Organization.CandidateCard(); card.ID() != created.Organization.ID() || card.VerificationLevel() != domain.OrganizationVerificationE0 { t.Fatalf("CandidateCard() = %+v, want the safe organization card", card) } currentTime = now.Add(time.Minute) updated, err := service.Update(ctx, UpdateCommand{ ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1, Patch: ProfilePatch{Description: OptionalString{Set: true, Value: "Измененные данные"}}, }) if err != nil { t.Fatalf("Update() error = %v", err) } if updated.Profile().Description() != "Измененные данные" || updated.Version() != 2 || updated.Verification().Level() != domain.OrganizationVerificationE0 { t.Fatalf("Update() = %+v, want version 2 with the edited profile and e0", updated) } replayed, err := service.Create(ctx, command) if err != nil { t.Fatalf("Create(retry) error = %v", err) } if !replayed.Replayed || replayed.Organization.ID() != created.Organization.ID() || !replayed.Organization.Profile().Equal(created.Organization.Profile()) || replayed.Organization.Version() != 1 || replayed.Owner.ID() != created.Owner.ID() { t.Fatalf("Create(retry) = %+v, want the original immutable result", replayed) } state := tx.snapshot() if len(state.organizations) != 1 || len(state.memberships) != 1 || len(state.results) != 1 { t.Fatalf("stored organizations/memberships/results = %d/%d/%d, want 1/1/1", len(state.organizations), len(state.memberships), len(state.results)) } } func TestCreateRejectsChangedBodyAndAllowsReuseAfterExpiration(t *testing.T) { ctx := t.Context() now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC) currentTime := now tx := newOrganizationTestTransactor() ownerID := uuid.New() tx.state.users[ownerID] = verifiedEmployer(ownerID, now) service := newOrganizationTestService(t, tx, func() time.Time { return currentTime }) firstProfile := organizationProfile("ООО Пример", "Первоначальные данные") first := CreateCommand{ ActorID: ownerID, IdempotencyKey: "company-create-02", CanonicalBody: canonicalBodyForTest(t, firstProfile), Profile: firstProfile, } created, err := service.Create(ctx, first) if err != nil { t.Fatalf("Create() error = %v", err) } changedProfile := organizationProfile("ООО Другое", "Первоначальные данные") changed := CreateCommand{ ActorID: ownerID, IdempotencyKey: first.IdempotencyKey, CanonicalBody: canonicalBodyForTest(t, changedProfile), Profile: changedProfile, } if _, err := service.Create(ctx, changed); !errors.Is(err, ErrIdempotencyKeyReused) { t.Fatalf("Create(changed body) error = %v, want ErrIdempotencyKeyReused", err) } if count := len(tx.snapshot().organizations); count != 1 { t.Fatalf("organization count after changed-body retry = %d, want 1", count) } currentTime = now.Add(outbound.IdempotencyRetention + time.Second) reused, err := service.Create(ctx, first) if err != nil { t.Fatalf("Create(expired key) error = %v", err) } if reused.Replayed || reused.Organization.ID() == created.Organization.ID() { t.Fatalf("Create(expired key) = %+v, want a new organization", reused) } state := tx.snapshot() if len(state.organizations) != 2 || len(state.memberships) != 2 || len(state.results) != 1 { t.Fatalf("stored organizations/memberships/results = %d/%d/%d, want 2/2/1", len(state.organizations), len(state.memberships), len(state.results)) } } func TestCreateRollsBackOrganizationOwnerIdempotencyAndSnapshot(t *testing.T) { ctx := t.Context() now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC) tx := newOrganizationTestTransactor() tx.failOwnerInsert = true ownerID := uuid.New() tx.state.users[ownerID] = verifiedEmployer(ownerID, now) service := newOrganizationTestService(t, tx, func() time.Time { return now }) profile := organizationProfile("ООО Пример", "Данные") _, err := service.Create(ctx, CreateCommand{ ActorID: ownerID, IdempotencyKey: "company-create-03", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile, }) if err == nil || !strings.Contains(err.Error(), "run transaction") { t.Fatalf("Create(owner insert failure) error = %v, want transaction failure", err) } state := tx.snapshot() if len(state.organizations) != 0 || len(state.memberships) != 0 || len(state.idempotency) != 0 || len(state.results) != 0 { t.Fatalf("state after failed transaction = companies:%d memberships:%d idempotency:%d results:%d, want all zero", len(state.organizations), len(state.memberships), len(state.idempotency), len(state.results)) } } func TestCreateRequiresVerifiedEmployer(t *testing.T) { now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC) for _, test := range []struct { name string user domain.User want error }{ {name: "candidate", user: domain.User{ID: uuid.New(), Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}, want: ErrForbidden}, {name: "unverified employer", user: domain.User{ID: uuid.New(), Scenario: domain.ScenarioEmployer}, want: ErrEmailNotVerified}, } { t.Run(test.name, func(t *testing.T) { tx := newOrganizationTestTransactor() tx.state.users[test.user.ID] = test.user service := newOrganizationTestService(t, tx, func() time.Time { return now }) profile := organizationProfile("ООО Пример", "Данные") _, err := service.Create(t.Context(), CreateCommand{ ActorID: test.user.ID, IdempotencyKey: "company-create-04", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile, }) if !errors.Is(err, test.want) { t.Fatalf("Create() error = %v, want %v", err, test.want) } if state := tx.snapshot(); len(state.organizations) != 0 || len(state.idempotency) != 0 { t.Fatalf("state after denied create = companies:%d idempotency:%d, want both zero", len(state.organizations), len(state.idempotency)) } }) } } func TestUpdateRequiresOwnerAndPreservesVerification(t *testing.T) { ctx := t.Context() now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC) currentTime := now tx := newOrganizationTestTransactor() ownerID := uuid.New() foreignID := uuid.New() memberID := uuid.New() tx.state.users[ownerID] = verifiedEmployer(ownerID, now) tx.state.users[foreignID] = verifiedEmployer(foreignID, now) tx.state.users[memberID] = verifiedEmployer(memberID, now) service := newOrganizationTestService(t, tx, func() time.Time { return currentTime }) profile := organizationProfile("ООО Пример", "Данные") created, err := service.Create(ctx, CreateCommand{ ActorID: ownerID, IdempotencyKey: "company-create-05", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile, }) if err != nil { t.Fatalf("Create() error = %v", err) } if _, err := service.Update(ctx, UpdateCommand{ ActorID: foreignID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1, Patch: ProfilePatch{Name: OptionalString{Set: true, Value: "Чужое изменение"}}, }); !errors.Is(err, outbound.ErrOrganizationNotFound) { t.Fatalf("Update(foreign user) error = %v, want ErrOrganizationNotFound", err) } member, err := domain.NewMembership(domain.MembershipInput{ OrganizationID: created.Organization.ID(), UserID: memberID, Role: domain.OrganizationRoleRecruiter, At: now.Add(time.Second), }) if err != nil { t.Fatalf("NewMembership() error = %v", err) } tx.mu.Lock() tx.state.memberships[organizationTestMembershipKey{created.Organization.ID(), memberID}] = member tx.mu.Unlock() if _, err := service.Update(ctx, UpdateCommand{ ActorID: memberID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1, Patch: ProfilePatch{Name: OptionalString{Set: true, Value: "Чужое изменение"}}, }); !errors.Is(err, outbound.ErrOrganizationManagerRequired) { t.Fatalf("Update(non-owner member) error = %v, want ErrOrganizationManagerRequired", err) } currentTime = now.Add(time.Minute) updated, err := service.Update(ctx, UpdateCommand{ ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1, Patch: ProfilePatch{Description: OptionalString{Set: true, Value: "Новый текст"}}, }) if err != nil { t.Fatalf("Update(owner) error = %v", err) } if updated.Version() != 2 || updated.Profile().Description() != "Новый текст" || updated.Verification().Level() != domain.OrganizationVerificationE0 || updated.Verification().Basis() != domain.OrganizationBasisConfirmedEmail { t.Fatalf("Update(owner) = %+v, want profile version 2 with unchanged e0 verification", updated) } if _, err := service.Update(ctx, UpdateCommand{ ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1, Patch: ProfilePatch{Description: OptionalString{Set: true, Value: "Другая версия"}}, }); !errors.Is(err, outbound.ErrOrganizationVersionConflict) { t.Fatalf("Update(stale version) error = %v, want ErrOrganizationVersionConflict", err) } noOp, err := service.Update(ctx, UpdateCommand{ ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1, Patch: ProfilePatch{Description: OptionalString{Set: true, Value: "Новый текст"}}, }) if err != nil || noOp.Version() != 2 { t.Fatalf("Update(stale no-op) = %v, %v, want current version 2", noOp, err) } invalidContacts := domain.OrganizationContactsInput{Website: "http://invalid.example"} if _, err := service.Update(ctx, UpdateCommand{ ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1, Patch: ProfilePatch{Contacts: &invalidContacts}, }); !errors.Is(err, outbound.ErrOrganizationVersionConflict) { t.Fatalf("Update(stale invalid website) error = %v, want version conflict", err) } if _, err := service.Update(ctx, UpdateCommand{ ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 2, Patch: ProfilePatch{Contacts: &invalidContacts}, }); !errors.Is(err, domain.ErrInvalidOrganization) { t.Fatalf("Update(current invalid website) error = %v, want domain validation error", err) } } func TestConcurrentCreateWithSameKeyReturnsOneCompany(t *testing.T) { ctx := t.Context() now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC) tx := newOrganizationTestTransactor() ownerID := uuid.New() tx.state.users[ownerID] = verifiedEmployer(ownerID, now) service := newOrganizationTestService(t, tx, func() time.Time { return now }) profile := organizationProfile("ООО Пример", "Данные") command := CreateCommand{ ActorID: ownerID, IdempotencyKey: "company-create-06", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile, } const requests = 12 results := make(chan CreateResult, requests) errorsFound := make(chan error, requests) var wait sync.WaitGroup for range requests { wait.Add(1) go func() { defer wait.Done() result, err := service.Create(ctx, command) if err != nil { errorsFound <- err return } results <- result }() } wait.Wait() close(results) close(errorsFound) for err := range errorsFound { t.Fatalf("Create(concurrent) error = %v", err) } var organizationID uuid.UUID createdCount := 0 for result := range results { if organizationID == uuid.Nil { organizationID = result.Organization.ID() } if result.Organization.ID() != organizationID || result.Owner.UserID() != ownerID { t.Fatalf("concurrent result = %+v, want the same company and owner", result) } if !result.Replayed { createdCount++ } } if createdCount != 1 { t.Fatalf("non-replayed results = %d, want one", createdCount) } state := tx.snapshot() if len(state.organizations) != 1 || len(state.memberships) != 1 || len(state.results) != 1 { t.Fatalf("stored organizations/memberships/results = %d/%d/%d, want 1/1/1", len(state.organizations), len(state.memberships), len(state.results)) } } func TestCreateInputCanonicalizationIsStable(t *testing.T) { profile := organizationProfile("ООО Пример", "Данные") one := canonicalBodyForTest(t, profile) two := canonicalBodyForTest(t, profile) if string(one) != string(two) { t.Fatalf("canonical bodies differ: %q and %q", one, two) } changed := profile changed.Representatives = append([]domain.OrganizationRepresentativeInput(nil), profile.Representatives...) changed.Representatives[0].Name = "Другой человек" three := canonicalBodyForTest(t, changed) if string(one) == string(three) { t.Fatalf("canonical body did not change with representative name: %q", one) } } func ExampleOptionalString() { patch := ProfilePatch{Description: OptionalString{Set: true, Value: ""}} fmt.Println(patch.Description.Set, patch.Description.Value == "") // Output: true true }