feat(accounts): add consent settings and organization management

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 13:00:39 +03:00
1 parent 24638d46d2
commit 391af7a1ef
83 files changed
+10198 -613

No files matched your search

@@ -0,0 +1,22 @@
package organization
import "errors"
var (
// ErrForbidden reports an account that cannot create or manage an
// organization.
ErrForbidden = errors.New("organization operation forbidden")
// ErrEmailNotVerified reports an account whose current email is not
// confirmed.
ErrEmailNotVerified = errors.New("organization requires a confirmed email")
// ErrIdempotencyKeyReused reports a live key first used with another body.
ErrIdempotencyKeyReused = errors.New("idempotency key reused with a different request")
// ErrInvalidIdempotencyKey reports a key outside the public contract bound.
ErrInvalidIdempotencyKey = errors.New("invalid idempotency key")
// ErrInvalidCreateRequest reports an oversized canonical request body.
ErrInvalidCreateRequest = errors.New("invalid organization create request")
)
@@ -0,0 +1,376 @@
// Package organization creates organizations and lets their owners edit the
// company profile.
package organization
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const (
createOperation = "organization.create"
createLocation = "organization.Service.Create"
maxIdempotencyKeySize = 255
maxCanonicalBodySize = 1 << 20
purgeExpiredBatch = 100
)
// Keyring computes scoped idempotency digests. identity.Keyring implements
// this interface so the feature uses the existing server secret and storage.
type Keyring interface {
IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte
Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte
}
// Dependencies are the collaborators of Service.
type Dependencies struct {
Transactor outbound.Transactor
Keyring Keyring
Clock func() time.Time
}
// Service applies organization commands. It stores no request state.
type Service struct {
transactor outbound.Transactor
keyring Keyring
clock func() time.Time
}
// NewService fails at startup when a required dependency is missing.
func NewService(deps Dependencies) (*Service, error) {
if deps.Transactor == nil || deps.Keyring == nil || deps.Clock == nil {
return nil, errors.New("organization.NewService - every dependency must be set")
}
return &Service{transactor: deps.Transactor, keyring: deps.Keyring, clock: deps.Clock}, nil
}
// CreateCommand is the caller and profile content of one create request.
type CreateCommand struct {
ActorID uuid.UUID
IdempotencyKey string
CanonicalBody []byte
Profile domain.OrganizationProfileInput
}
// CreateResult is the organization and owner membership created by a request.
// Replayed marks an identical request answered from the immutable result
// snapshot; it does not change the public status or body.
type CreateResult struct {
Organization domain.Organization
Owner domain.Membership
Replayed bool
}
type createRequest struct {
command CreateCommand
fingerprint [outbound.IdempotencyDigestSize]byte
scope [outbound.IdempotencyDigestSize]byte
record outbound.IdempotencyRecord
now time.Time
}
// Create creates a company and its active owner membership in one
// transaction. An identical key and body returns the original creation
// snapshot, even if the live profile has since changed.
func (service *Service) Create(ctx context.Context, command CreateCommand) (CreateResult, error) {
request, err := service.prepareCreateRequest(command)
if err != nil {
return CreateResult{}, err
}
var result CreateResult
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
created, err := service.createInTransaction(ctx, unit, request)
if err != nil {
return err
}
result = created
return nil
})
if err != nil {
return CreateResult{}, fmt.Errorf("%s - run transaction: %w", createLocation, err)
}
return result, nil
}
func (service *Service) prepareCreateRequest(command CreateCommand) (createRequest, error) {
switch {
case command.ActorID == uuid.Nil:
return createRequest{}, fmt.Errorf("%s - actor ID must be set: %w", createLocation, ErrForbidden)
case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize:
return createRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", createLocation, ErrInvalidIdempotencyKey)
}
canonical := command.CanonicalBody
if len(canonical) == 0 {
var err error
canonical, err = canonicalCreateBody(command.Profile)
if err != nil {
return createRequest{}, fmt.Errorf("%s - encode canonical profile", createLocation)
}
}
if len(canonical) > maxCanonicalBodySize {
return createRequest{}, fmt.Errorf("%s - request body exceeds its bound: %w", createLocation, ErrInvalidCreateRequest)
}
fingerprint := service.keyring.Fingerprint(canonical)
scope := service.keyring.IdempotencyScope(createOperation, command.IdempotencyKey, command.ActorID.String())
now := service.clock()
if now.IsZero() {
return createRequest{}, fmt.Errorf("%s - application time must be set", createLocation)
}
record := outbound.IdempotencyRecord{
Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention),
}
return createRequest{command: command, fingerprint: fingerprint, scope: scope, record: record, now: now}, nil
}
func (service *Service) createInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
request createRequest,
) (CreateResult, error) {
if err := requireEmployer(ctx, unit, request.command.ActorID, createLocation); err != nil {
return CreateResult{}, fmt.Errorf("%s - authorize creator: %w", createLocation, err)
}
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
if err != nil {
return CreateResult{}, fmt.Errorf("%s - reserve idempotency record: %w", createLocation, err)
}
if !created {
return replayCreation(ctx, unit, request, stored)
}
return service.createOrganization(ctx, unit, request)
}
func replayCreation(
ctx context.Context,
unit outbound.UnitOfWork,
request createRequest,
stored outbound.IdempotencyRecord,
) (CreateResult, error) {
if stored.Fingerprint != request.fingerprint {
return CreateResult{}, ErrIdempotencyKeyReused
}
snapshot, err := unit.Organizations().GetCreationResult(ctx, request.scope)
if err != nil {
return CreateResult{}, fmt.Errorf("%s - read creation snapshot: %w", createLocation, err)
}
if !validCreationSnapshot(snapshot, request.command.ActorID) {
return CreateResult{}, fmt.Errorf("%s - stored creation snapshot does not match the actor: %w", createLocation, domain.ErrInvalidMembership)
}
return CreateResult{Organization: snapshot.Organization, Owner: snapshot.Owner, Replayed: true}, nil
}
func validCreationSnapshot(snapshot outbound.OrganizationCreationResult, actorID uuid.UUID) bool {
if snapshot.Organization.IsZero() || snapshot.Owner.IsZero() {
return false
}
return snapshot.Owner.UserID() == actorID &&
snapshot.Owner.OrganizationID() == snapshot.Organization.ID() &&
snapshot.Owner.Role() == domain.OrganizationRoleOwner && snapshot.Owner.GrantsAccess()
}
func (service *Service) createOrganization(
ctx context.Context,
unit outbound.UnitOfWork,
request createRequest,
) (CreateResult, error) {
profile, err := domain.NewOrganizationProfile(request.command.Profile)
if err != nil {
return CreateResult{}, fmt.Errorf("%s - validate profile: %w", createLocation, err)
}
company, err := domain.NewOrganization(profile, request.now)
if err != nil {
return CreateResult{}, fmt.Errorf("%s - build organization: %w", createLocation, err)
}
owner, err := domain.NewOwnerMembership(company.ID(), request.command.ActorID, request.now)
if err != nil {
return CreateResult{}, fmt.Errorf("%s - build owner membership: %w", createLocation, err)
}
if err := unit.Organizations().CreateWithOwner(ctx, company, owner); err != nil {
return CreateResult{}, fmt.Errorf("%s - store organization and owner: %w", createLocation, err)
}
creation := outbound.OrganizationCreationResult{Organization: company, Owner: owner}
if err := unit.Organizations().SaveCreationResult(ctx, request.scope, creation); err != nil {
return CreateResult{}, fmt.Errorf("%s - store creation snapshot: %w", createLocation, err)
}
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
return CreateResult{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err)
}
return CreateResult{Organization: company, Owner: owner}, nil
}
func canonicalCreateBody(profile domain.OrganizationProfileInput) ([]byte, error) {
// An ordered array makes the fingerprint stable for non-HTTP callers.
return json.Marshal([]any{
profile.Name,
profile.Description,
profile.Sphere,
profile.Contacts.Website,
profile.Contacts.Email,
profile.Contacts.Phone,
profile.Contacts.Telegram,
profile.Representatives,
})
}
// OptionalString distinguishes an absent field from a present value. An empty
// value clears nullable description and sphere fields.
type OptionalString struct {
Set bool
Value string
}
// ProfilePatch is the set of editable fields present in an update request.
// Contacts and representatives replace their complete value when set.
type ProfilePatch struct {
Name OptionalString
Description OptionalString
Sphere OptionalString
Contacts *domain.OrganizationContactsInput
Representatives *[]domain.OrganizationRepresentativeInput
}
// UpdateCommand describes a versioned profile edit.
type UpdateCommand struct {
ActorID uuid.UUID
OrganizationID uuid.UUID
ExpectedVersion int64
Patch ProfilePatch
}
// Update merges the patch over the current profile, preserves verification,
// and checks that the acting account is the active owner.
func (service *Service) Update(ctx context.Context, command UpdateCommand) (domain.Organization, error) {
const location = "organization.Service.Update"
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 command.ExpectedVersion < 1 {
return domain.Organization{}, fmt.Errorf("%s - expected version must be positive: %w", location, domain.ErrInvalidOrganization)
}
var result domain.Organization
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 editor: %w", location, err)
}
current, membership, err := unit.Organizations().GetForMember(ctx, command.OrganizationID, command.ActorID)
if err != nil {
return fmt.Errorf("%s - read organization for member: %w", location, err)
}
if !membership.CanManageOrganization() {
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
}
profile, err := applyPatch(current.Profile(), command.Patch)
if err != nil {
if command.ExpectedVersion != current.Version() {
return fmt.Errorf("%s - expected version %d, current version %d: %w", location,
command.ExpectedVersion, current.Version(), outbound.ErrOrganizationVersionConflict)
}
return fmt.Errorf("%s - validate profile: %w", location, err)
}
if current.Profile().Equal(profile) {
result = current
return nil
}
if command.ExpectedVersion != current.Version() {
return fmt.Errorf("%s - expected version %d, current version %d: %w", location,
command.ExpectedVersion, current.Version(), outbound.ErrOrganizationVersionConflict)
}
updated, err := current.ApplyProfile(profile, service.clock())
if err != nil {
return fmt.Errorf("%s - apply profile: %w", location, err)
}
result, err = unit.Organizations().UpdateProfile(ctx, command.ActorID, updated)
if err != nil {
return fmt.Errorf("%s - store profile: %w", location, err)
}
return nil
})
if err != nil {
return domain.Organization{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
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.
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)
}
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 {
return fmt.Errorf("%s - authorize reader: %w", location, err)
}
organization, membership, err := unit.Organizations().GetForMember(ctx, organizationID, actorID)
if err != nil {
return fmt.Errorf("%s - read organization for member: %w", location, err)
}
if !membership.GrantsAccess() {
return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound)
}
result = organization
return nil
})
if err != nil {
return domain.Organization{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
func applyPatch(current domain.OrganizationProfile, patch ProfilePatch) (domain.OrganizationProfile, error) {
contacts := current.Contacts()
input := domain.OrganizationProfileInput{
Name: current.Name(), Description: current.Description(), Sphere: current.Sphere(),
Contacts: domain.OrganizationContactsInput{
Website: contacts.Website(), Email: contacts.Email(), Phone: contacts.Phone(), Telegram: contacts.Telegram(),
},
}
for _, representative := range current.Representatives() {
input.Representatives = append(input.Representatives, domain.OrganizationRepresentativeInput{
Name: representative.Name(), JobTitle: representative.JobTitle(),
})
}
if patch.Name.Set {
input.Name = patch.Name.Value
}
if patch.Description.Set {
input.Description = patch.Description.Value
}
if patch.Sphere.Set {
input.Sphere = patch.Sphere.Value
}
if patch.Contacts != nil {
input.Contacts = *patch.Contacts
}
if patch.Representatives != nil {
input.Representatives = append([]domain.OrganizationRepresentativeInput(nil), (*patch.Representatives)...)
}
return domain.NewOrganizationProfile(input)
}
func requireEmployer(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID, location string) error {
user, err := unit.Users().GetByID(ctx, actorID)
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.ScenarioEmployer {
return ErrForbidden
}
return nil
}
@@ -0,0 +1,628 @@
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
}