feat(org): add organization and membership contract and storage

This commit is contained in:
shira committed 2026-10-06 15:55:29 +03:00
1 parent a0551a34b8
commit bdc5855001
90 files changed
+17545 -480

No files matched your search

@@ -0,0 +1,979 @@
//go:build integration
package integration_test
import (
"context"
"errors"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const (
organizationTestTimeout = 3 * time.Minute
// concurrentOrganizationUpdates change one organization at once from the
// same version, each on its own connection.
concurrentOrganizationUpdates = 8
organizationUniqueViolation = "23505"
organizationCheckViolation = "23514"
organizationRestrictViolation = "23001"
)
var (
organizationsTable = pgx.Identifier{"organizations"}
organizationRepresentativesTable = pgx.Identifier{"organization_representatives"}
membershipsTable = pgx.Identifier{"memberships"}
// organizationTables are emptied together: memberships reference both
// users and organizations.
organizationTables = []pgx.Identifier{membershipsTable, organizationRepresentativesTable, organizationsTable}
// usersDependentTables is every table that references users, directly or
// through another table of the list. A TRUNCATE of users must name all of
// them, so a migration that adds such a table adds it here.
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables)
)
// organizationFixture works on the bootstrap database. The tables are
// truncated between subtests.
type organizationFixture struct {
ctx context.Context
pool *pgxpool.Pool
identity identityFixture
transactor *postgresadapter.Transactor
// now is truncated to microseconds, the precision PostgreSQL stores.
now time.Time
}
func TestOrganizationsAndMemberships(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), organizationTestTimeout)
defer cancel()
pool := env.newPool(ctx, t)
now := time.Now().UTC().Truncate(time.Microsecond)
fixture := organizationFixture{
ctx: ctx,
pool: pool,
identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now},
transactor: postgresadapter.NewTransactor(pool),
now: now,
}
reset := func(t *testing.T) {
t.Helper()
truncateTables(ctx, t, pool, usersDependentTables...)
}
t.Run("stores an organization with its owner and reads it back for the member", func(t *testing.T) {
reset(t)
owner := fixture.employer(t, "owner@example.com")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример Платежи"), now)
read, membership, err := fixture.read(owner.ID, organization.ID())
if err != nil {
t.Fatalf("GetForMember() error = %v", err)
}
if !read.Profile().Equal(organization.Profile()) || read.Version() != 1 || !read.CreatedAt().Equal(now) || !read.UpdatedAt().Equal(now) {
t.Fatalf("stored organization = %v, want the created profile at version 1", read)
}
if verification := read.Verification(); verification.Level() != domain.OrganizationVerificationE0 ||
verification.Basis() != domain.OrganizationBasisConfirmedEmail || !verification.ChangedAt().Equal(now) {
t.Fatalf("verification = %s %s, want e0 on the confirmed email", verification.Level(), verification.Basis())
}
if membership.Role() != domain.OrganizationRoleOwner || membership.State() != domain.MembershipStateActive ||
membership.UserID() != owner.ID || membership.OrganizationID() != organization.ID() {
t.Fatalf("membership = %+v, want the active owner membership of the creator", membership)
}
if got := read.Profile().Representatives(); len(got) != 2 || got[0].Name() != "Анна Тестова" || got[1].Name() != "Борис Образцов" {
t.Fatalf("representatives = %v, want two in the given order", got)
}
// The stored values are NULL for a field that is not set, not an
// empty string.
minimal := fixture.create(t, owner, mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Только имя"}), now.Add(time.Minute))
var description, website *string
if err := pool.QueryRow(ctx, `SELECT description, contact_website FROM organizations WHERE id = $1`, minimal.ID()).Scan(&description, &website); err != nil {
t.Fatalf("select the minimal organization: %v", err)
}
if description != nil || website != nil {
t.Fatalf("description = %v, website = %v, want NULL for fields that are not set", description, website)
}
bare, _, err := fixture.read(owner.ID, minimal.ID())
if err != nil || len(bare.Profile().Representatives()) != 0 {
t.Fatalf("GetForMember(organization without representatives) = %v, %v, want an empty list", bare, err)
}
})
t.Run("a repeated membership of the same pair violates the unique constraint in any state", func(t *testing.T) {
reset(t)
owner := fixture.employer(t, "owner@example.com")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now)
for _, role := range domain.OrganizationRoles() {
repeated, err := domain.NewMembership(domain.MembershipInput{OrganizationID: organization.ID(), UserID: owner.ID, Role: role, At: now.Add(time.Hour)})
if err != nil {
t.Fatalf("NewMembership(%s) error = %v", role, err)
}
err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Memberships().Insert(ctx, repeated)
})
if !errors.Is(err, outbound.ErrMembershipExists) || !strings.Contains(err.Error(), "memberships_user_id_organization_id_key") {
t.Fatalf("Insert(repeated %s) error = %v, want ErrMembershipExists naming the constraint", role, err)
}
}
// A membership that ended keeps its row, so the pair stays taken.
fixture.setMembershipState(t, organization.ID(), owner.ID, domain.MembershipStateLeft)
repeated, err := domain.NewOwnerMembership(organization.ID(), owner.ID, now.Add(time.Hour))
if err != nil {
t.Fatalf("NewOwnerMembership() error = %v", err)
}
err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Memberships().Insert(ctx, repeated)
})
if !errors.Is(err, outbound.ErrMembershipExists) {
t.Fatalf("Insert(after the member left) error = %v, want ErrMembershipExists", err)
}
// The database refuses it without the adapter, too.
_, err = pool.Exec(ctx, `
INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at)
VALUES ($1, $2, $3, 'recruiter', 'active', $4, $4)`, uuid.New(), organization.ID(), owner.ID, now)
assertSQLError(t, "raw duplicate membership", err, organizationUniqueViolation, "memberships_user_id_organization_id_key")
assertRowCount(ctx, t, pool, membershipsTable, 1)
// Another account, or another organization, is another pair.
second := fixture.employer(t, "second@example.com")
fixture.addMember(t, organization, second, domain.OrganizationRoleRecruiter, now.Add(2*time.Hour))
other := fixture.create(t, owner, fixture.completeProfile(t, "ООО Другое"), now.Add(3*time.Hour))
if _, _, err := fixture.read(owner.ID, other.ID()); err != nil {
t.Fatalf("GetForMember(second organization of the same account) error = %v", err)
}
assertRowCount(ctx, t, pool, membershipsTable, 3)
if _, err := fixture.getMembership(organization.ID(), second.ID); err != nil {
t.Fatalf("Get(membership) error = %v", err)
}
if _, err := fixture.getMembership(organization.ID(), uuid.New()); !errors.Is(err, outbound.ErrMembershipNotFound) {
t.Fatalf("Get(unknown account) error = %v, want ErrMembershipNotFound", err)
}
})
t.Run("an organization and its owner are stored atomically", func(t *testing.T) {
reset(t)
creator := fixture.employer(t, "creator@example.com")
// The owner row fails on a foreign key: the organization, its
// representatives, and the membership are all rolled back.
organization := fixture.newOrganization(t, fixture.completeProfile(t, "ООО Пример"), now)
unknownOwner, err := domain.NewOwnerMembership(organization.ID(), uuid.New(), now)
if err != nil {
t.Fatalf("NewOwnerMembership() error = %v", err)
}
err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Organizations().CreateWithOwner(ctx, organization, unknownOwner)
})
if !errors.Is(err, outbound.ErrUserNotFound) {
t.Fatalf("CreateWithOwner(unknown account) error = %v, want ErrUserNotFound", err)
}
fixture.assertNothingStored(t)
// A later failure of the same transaction removes the organization.
owner, err := domain.NewOwnerMembership(organization.ID(), creator.ID, now)
if err != nil {
t.Fatalf("NewOwnerMembership() error = %v", err)
}
failure := errors.New("the usecase failed after the organization was stored")
err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := unit.Organizations().CreateWithOwner(ctx, organization, owner); err != nil {
return err
}
return failure
})
if !errors.Is(err, failure) {
t.Fatalf("transaction error = %v, want the usecase failure", err)
}
fixture.assertNothingStored(t)
// The adapter refuses an owner that is not the active owner of the
// organization before it writes anything.
recruiter, err := domain.NewMembership(domain.MembershipInput{OrganizationID: organization.ID(), UserID: creator.ID, Role: domain.OrganizationRoleRecruiter, At: now})
if err != nil {
t.Fatalf("NewMembership() error = %v", err)
}
foreign, err := domain.NewOwnerMembership(uuid.New(), creator.ID, now)
if err != nil {
t.Fatalf("NewOwnerMembership() error = %v", err)
}
for name, membership := range map[string]domain.Membership{"recruiter": recruiter, "owner of another organization": foreign, "zero": {}} {
err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Organizations().CreateWithOwner(ctx, organization, membership)
})
if !errors.Is(err, domain.ErrInvalidMembership) {
t.Fatalf("CreateWithOwner(%s) error = %v, want ErrInvalidMembership", name, err)
}
}
fixture.assertNothingStored(t)
// Success stores all three.
fixture.create(t, creator, fixture.completeProfile(t, "ООО Пример"), now)
assertRowCount(ctx, t, pool, organizationsTable, 1)
assertRowCount(ctx, t, pool, organizationRepresentativesTable, 2)
assertRowCount(ctx, t, pool, membershipsTable, 1)
})
t.Run("the database refuses to commit an organization without an active owner", func(t *testing.T) {
reset(t)
member := fixture.employer(t, "member@example.com")
insertOrganization := func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error {
_, err := tx.Exec(ctx, `
INSERT INTO organizations (
id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at
) VALUES ($1, 'ООО Без владельца', 'e0', 'confirmed_email', $2, 1, $2, $2)`, id, now)
return err
}
insertMember := func(ctx context.Context, tx pgx.Tx, organizationID uuid.UUID, role, state string) error {
_, err := tx.Exec(ctx, `
INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $6)`, uuid.New(), organizationID, member.ID, role, state, now)
return err
}
for _, test := range []struct {
name string
work func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error
}{
{"no membership at all", func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error { return insertOrganization(ctx, tx, id) }},
{"only a recruiter", func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error {
if err := insertOrganization(ctx, tx, id); err != nil {
return err
}
return insertMember(ctx, tx, id, "recruiter", "active")
}},
{"an owner that is removed in the same transaction", func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error {
if err := insertOrganization(ctx, tx, id); err != nil {
return err
}
if err := insertMember(ctx, tx, id, "owner", "active"); err != nil {
return err
}
_, err := tx.Exec(ctx, `UPDATE memberships SET state = 'removed' WHERE organization_id = $1`, id)
return err
}},
{"only a suspended owner", func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error {
if err := insertOrganization(ctx, tx, id); err != nil {
return err
}
return insertMember(ctx, tx, id, "owner", "suspended")
}},
} {
t.Run(test.name, func(t *testing.T) {
err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
tx, ok := postgresadapter.TransactionForIntegrationTest(unit)
if !ok {
t.Fatal("the unit of work has no PostgreSQL transaction")
}
return test.work(ctx, tx, uuid.New())
})
var pgError *pgconn.PgError
if !errors.As(err, &pgError) || pgError.Code != organizationCheckViolation || pgError.ConstraintName != "organizations_owner_required" {
t.Fatalf("commit error = %v, want SQLSTATE %s on organizations_owner_required", err, organizationCheckViolation)
}
fixture.assertNothingStored(t)
})
}
// An active owner inserted after the organization, in the same
// transaction, satisfies the deferred check.
err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
tx, _ := postgresadapter.TransactionForIntegrationTest(unit)
id := uuid.New()
if err := insertOrganization(ctx, tx, id); err != nil {
return err
}
return insertMember(ctx, tx, id, "owner", "active")
})
if err != nil {
t.Fatalf("organization with an owner in one transaction error = %v", err)
}
assertRowCount(ctx, t, pool, organizationsTable, 1)
})
t.Run("lists only the active organizations of the caller", func(t *testing.T) {
reset(t)
alice := fixture.employer(t, "alice@example.com")
bob := fixture.employer(t, "bob@example.com")
carol := fixture.employer(t, "carol@example.com")
at := func(minutes int) time.Time { return now.Add(time.Duration(minutes) * time.Minute) }
first := fixture.create(t, alice, fixture.completeProfile(t, "Первая Алисы"), at(1))
bobs := fixture.create(t, bob, fixture.completeProfile(t, "Бобова"), at(2))
third := fixture.create(t, alice, fixture.completeProfile(t, "Третья Алисы"), at(3))
shared := fixture.create(t, bob, fixture.completeProfile(t, "Общая"), at(4))
fixture.addMember(t, shared, alice, domain.OrganizationRoleRecruiter, at(5))
suspended := fixture.create(t, bob, fixture.completeProfile(t, "Приостановленная"), at(6))
fixture.addMember(t, suspended, alice, domain.OrganizationRoleHiringManager, at(7))
fixture.setMembershipState(t, suspended.ID(), alice.ID, domain.MembershipStateSuspended)
left := fixture.create(t, bob, fixture.completeProfile(t, "Покинутая"), at(8))
fixture.addMember(t, left, alice, domain.OrganizationRoleTechnicalExpert, at(9))
fixture.setMembershipState(t, left.ID(), alice.ID, domain.MembershipStateLeft)
removed := fixture.create(t, bob, fixture.completeProfile(t, "Удаленная"), at(10))
fixture.addMember(t, removed, alice, domain.OrganizationRoleRecruiter, at(11))
fixture.setMembershipState(t, removed.ID(), alice.ID, domain.MembershipStateRemoved)
page := fixture.list(t, outbound.OrganizationListQuery{UserID: alice.ID, Limit: 10})
wantOrder := []uuid.UUID{shared.ID(), third.ID(), first.ID()}
if got := organizationIDs(page); !slices.Equal(got, wantOrder) || page.HasMore {
t.Fatalf("Alice's organizations = %v (more %v), want %v newest membership first", got, page.HasMore, wantOrder)
}
if page.Items[0].Membership.Role() != domain.OrganizationRoleRecruiter || page.Items[1].Membership.Role() != domain.OrganizationRoleOwner ||
page.Items[0].Organization.Name() != "Общая" || page.Items[0].Organization.VerificationLevel() != domain.OrganizationVerificationE0 ||
page.Items[0].Membership.UserID() != alice.ID {
t.Fatalf("items = %+v, want each organization with Alice's own membership", page.Items)
}
bobPage := fixture.list(t, outbound.OrganizationListQuery{UserID: bob.ID, Limit: 10})
if got := organizationIDs(bobPage); len(got) != 5 || slices.Contains(got, first.ID()) || slices.Contains(got, third.ID()) || !slices.Contains(got, bobs.ID()) {
t.Fatalf("Bob's organizations = %v, want his five and none of Alice's own", got)
}
if got := organizationIDs(fixture.list(t, outbound.OrganizationListQuery{UserID: carol.ID, Limit: 10})); len(got) != 0 {
t.Fatalf("Carol's organizations = %v, want none", got)
}
if got := organizationIDs(fixture.list(t, outbound.OrganizationListQuery{UserID: uuid.New(), Limit: 10})); len(got) != 0 {
t.Fatalf("an unknown account's organizations = %v, want none", got)
}
// Paging follows the same order without a gap or a repeat.
firstPage := fixture.list(t, outbound.OrganizationListQuery{UserID: alice.ID, Limit: 2})
if !firstPage.HasMore || len(firstPage.Items) != 2 {
t.Fatalf("first page = %d items (more %v), want 2 and more", len(firstPage.Items), firstPage.HasMore)
}
last := outbound.OrganizationPositionOf(firstPage.Items[1])
secondPage := fixture.list(t, outbound.OrganizationListQuery{UserID: alice.ID, Limit: 2, After: &last})
if got := append(organizationIDs(firstPage), organizationIDs(secondPage)...); !slices.Equal(got, wantOrder) || secondPage.HasMore {
t.Fatalf("pages = %v (more %v), want %v and the end", got, secondPage.HasMore, wantOrder)
}
// Memberships created at the same instant order by the organization.
tie := fixture.create(t, carol, fixture.completeProfile(t, "Ничья А"), at(20))
tieB := fixture.create(t, carol, fixture.completeProfile(t, "Ничья Б"), at(20))
wantTie := []uuid.UUID{tie.ID(), tieB.ID()}
slices.SortFunc(wantTie, func(left, right uuid.UUID) int { return strings.Compare(right.String(), left.String()) })
if got := organizationIDs(fixture.list(t, outbound.OrganizationListQuery{UserID: carol.ID, Limit: 10})); !slices.Equal(got, wantTie) {
t.Fatalf("tied memberships = %v, want %v by organization ID descending", got, wantTie)
}
for name, query := range map[string]outbound.OrganizationListQuery{
"nil user": {Limit: 10},
"zero limit": {UserID: alice.ID},
"limit too large": {UserID: alice.ID, Limit: outbound.MaxOrganizationPageSize + 1},
"zero position": {UserID: alice.ID, Limit: 10, After: &outbound.OrganizationListPosition{}},
"position without an organization": {UserID: alice.ID, Limit: 10, After: &outbound.OrganizationListPosition{JoinedAt: now}},
} {
err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
_, err := unit.Organizations().ListForUser(ctx, query)
return err
})
if !errors.Is(err, domain.ErrInvalidMembership) {
t.Fatalf("ListForUser(%s) error = %v, want ErrInvalidMembership", name, err)
}
}
})
t.Run("only an active member reads an organization, and a revoked membership closes the next read", func(t *testing.T) {
reset(t)
owner := fixture.employer(t, "owner@example.com")
outsider := fixture.employer(t, "outsider@example.com")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now)
stored := fixture.employer(t, "former@example.com")
fixture.addMember(t, organization, stored, domain.OrganizationRoleRecruiter, now.Add(time.Minute))
for name, userID := range map[string]uuid.UUID{"an account that is no member": outsider.ID, "an unknown account": uuid.New()} {
if _, _, err := fixture.read(userID, organization.ID()); !errors.Is(err, outbound.ErrOrganizationNotFound) {
t.Fatalf("GetForMember(%s) error = %v, want ErrOrganizationNotFound", name, err)
}
}
if _, _, err := fixture.read(owner.ID, uuid.New()); !errors.Is(err, outbound.ErrOrganizationNotFound) {
t.Fatalf("GetForMember(unknown organization) error = %v, want ErrOrganizationNotFound", err)
}
if _, membership, err := fixture.read(stored.ID, organization.ID()); err != nil || membership.Role() != domain.OrganizationRoleRecruiter {
t.Fatalf("GetForMember(recruiter) = %+v, %v, want the recruiter membership", membership, err)
}
for _, state := range []domain.MembershipState{domain.MembershipStateSuspended, domain.MembershipStateRemoved, domain.MembershipStateLeft} {
fixture.setMembershipState(t, organization.ID(), stored.ID, state)
if _, _, err := fixture.read(stored.ID, organization.ID()); !errors.Is(err, outbound.ErrOrganizationNotFound) {
t.Fatalf("GetForMember(%s member) error = %v, want ErrOrganizationNotFound", state, err)
}
// The membership row is still readable in any state for the
// application that manages members.
membership, err := fixture.getMembership(organization.ID(), stored.ID)
if err != nil || membership.State() != state || membership.GrantsAccess() {
t.Fatalf("Get(%s membership) = %+v, %v, want the stored state without access", state, membership, err)
}
}
fixture.setMembershipState(t, organization.ID(), stored.ID, domain.MembershipStateActive)
if _, _, err := fixture.read(stored.ID, organization.ID()); err != nil {
t.Fatalf("GetForMember(restored member) error = %v", err)
}
})
t.Run("updates the profile over the version read and never touches the verification", func(t *testing.T) {
reset(t)
owner := fixture.employer(t, "owner@example.com")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Старое Имя"), now)
later := now.Add(time.Hour)
changed := mustOrganizationProfile(t, domain.OrganizationProfileInput{
Name: "ООО Новое Имя",
Contacts: domain.OrganizationContactsInput{Telegram: "@new_careers"},
Representatives: []domain.OrganizationRepresentativeInput{
{Name: "Виктор Новый", JobTitle: "Директор"},
},
})
updated := fixture.update(t, owner.ID, organization, changed, later)
if updated.Version() != 2 || updated.Profile().Name() != "ООО Новое Имя" || !updated.UpdatedAt().Equal(later) || !updated.CreatedAt().Equal(now) {
t.Fatalf("updated = %v, want version 2 with the new name at the new time", updated)
}
read, _, err := fixture.read(owner.ID, organization.ID())
if err != nil {
t.Fatalf("GetForMember() error = %v", err)
}
profile := read.Profile()
if !profile.Equal(changed) || profile.Description() != "" || profile.Sphere() != "" || profile.Contacts().Website() != "" ||
profile.Contacts().Telegram() != "@new_careers" || len(profile.Representatives()) != 1 {
t.Fatalf("stored profile = %+v, want the replaced profile with the cleared fields unset", profile)
}
if read.Version() != 2 || !sameVerification(read.Verification(), organization.Verification()) {
t.Fatalf("stored organization = %v, want version 2 and the unchanged verification", read)
}
// A level that a verification process set stays through profile edits.
if _, err := pool.Exec(ctx, `
UPDATE organizations
SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2
WHERE id = $1`, organization.ID(), later); err != nil {
t.Fatalf("simulate a verification process: %v", err)
}
again := fixture.update(t, owner.ID, read, mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "ООО Третье Имя"}), later.Add(time.Hour))
if again.Version() != 3 || again.Verification().Level() != domain.OrganizationVerificationE1 ||
again.Verification().Basis() != domain.OrganizationBasisCorporateDomain || !again.Verification().ChangedAt().Equal(later) {
t.Fatalf("after the profile edit = %v, want version 3 and the level e1 set by the process", again)
}
var level, basis string
if err := pool.QueryRow(ctx, `SELECT verification_level, verification_basis FROM organizations WHERE id = $1`, organization.ID()).Scan(&level, &basis); err != nil ||
level != "e1" || basis != "corporate_domain" {
t.Fatalf("stored verification = %s %s, %v, want e1 corporate_domain", level, basis, err)
}
})
t.Run("a stale version, a non-manager, and a non-member change nothing", func(t *testing.T) {
reset(t)
owner := fixture.employer(t, "owner@example.com")
recruiter := fixture.employer(t, "recruiter@example.com")
suspendedOwner := fixture.employer(t, "suspended@example.com")
outsider := fixture.employer(t, "outsider@example.com")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now)
fixture.addMember(t, organization, recruiter, domain.OrganizationRoleRecruiter, now.Add(time.Minute))
fixture.addMember(t, organization, suspendedOwner, domain.OrganizationRoleOwner, now.Add(time.Minute))
fixture.setMembershipState(t, organization.ID(), suspendedOwner.ID, domain.MembershipStateSuspended)
changed, err := organization.ApplyProfile(mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Чужая правка"}), now.Add(time.Hour))
if err != nil {
t.Fatalf("ApplyProfile() error = %v", err)
}
for _, test := range []struct {
name string
actorID uuid.UUID
want error
}{
{"a recruiter", recruiter.ID, outbound.ErrOrganizationManagerRequired},
{"a suspended owner", suspendedOwner.ID, outbound.ErrOrganizationNotFound},
{"an account that is no member", outsider.ID, outbound.ErrOrganizationNotFound},
{"an unknown account", uuid.New(), outbound.ErrOrganizationNotFound},
} {
_, err := fixture.tryUpdate(test.actorID, changed)
if !errors.Is(err, test.want) {
t.Fatalf("UpdateProfile(%s) error = %v, want %v", test.name, err, test.want)
}
}
// Two owners read version 1; the second write is stale.
first := fixture.update(t, owner.ID, organization, mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Первая правка"}), now.Add(time.Hour))
if first.Version() != 2 {
t.Fatalf("first update version = %d, want 2", first.Version())
}
if _, err := fixture.tryUpdate(owner.ID, changed); !errors.Is(err, outbound.ErrOrganizationVersionConflict) {
t.Fatalf("UpdateProfile(stale version) error = %v, want ErrOrganizationVersionConflict", err)
}
// The order of the checks: an outsider with a stale version learns
// nothing about the version.
if _, err := fixture.tryUpdate(outsider.ID, changed); !errors.Is(err, outbound.ErrOrganizationNotFound) {
t.Fatalf("UpdateProfile(outsider, stale version) error = %v, want ErrOrganizationNotFound", err)
}
read, _, err := fixture.read(owner.ID, organization.ID())
if err != nil {
t.Fatalf("GetForMember() error = %v", err)
}
if read.Profile().Name() != "Первая правка" || read.Version() != 2 || len(read.Profile().Representatives()) != 0 {
t.Fatalf("stored organization = %v, want only the first update", read)
}
for name, build := range map[string]func() (domain.Organization, uuid.UUID){
"a zero organization": func() (domain.Organization, uuid.UUID) { return domain.Organization{}, owner.ID },
"a nil actor": func() (domain.Organization, uuid.UUID) { return read, uuid.Nil },
} {
organization, actor := build()
if _, err := fixture.tryUpdate(actor, organization); !errors.Is(err, domain.ErrInvalidOrganization) {
t.Fatalf("UpdateProfile(%s) error = %v, want ErrInvalidOrganization", name, err)
}
}
})
t.Run("of concurrent updates from one version exactly one wins", func(t *testing.T) {
reset(t)
owner := fixture.employer(t, "owner@example.com")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now)
concurrent := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, concurrentOrganizationUpdates+1))
errs := make([]error, concurrentOrganizationUpdates)
start := make(chan struct{})
var group sync.WaitGroup
for index := range concurrentOrganizationUpdates {
group.Go(func() {
<-start
profile, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{
Name: "Правка " + string(rune('А'+index)),
Representatives: []domain.OrganizationRepresentativeInput{
{Name: "Автор " + string(rune('А'+index)), JobTitle: "Должность"},
},
})
if err != nil {
errs[index] = err
return
}
changed, err := organization.ApplyProfile(profile, now.Add(time.Hour))
if err != nil {
errs[index] = err
return
}
errs[index] = concurrent.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
_, err := unit.Organizations().UpdateProfile(ctx, owner.ID, changed)
return err
})
})
}
close(start)
group.Wait()
successes := 0
for index, err := range errs {
switch {
case err == nil:
successes++
case errors.Is(err, outbound.ErrOrganizationVersionConflict):
default:
t.Fatalf("update %d error = %v, want nil or ErrOrganizationVersionConflict", index, err)
}
}
if successes != 1 {
t.Fatalf("%d updates succeeded, want exactly 1", successes)
}
read, _, err := fixture.read(owner.ID, organization.ID())
if err != nil {
t.Fatalf("GetForMember() error = %v", err)
}
// The winner's name and representative belong together.
winner := strings.TrimPrefix(read.Profile().Name(), "Правка ")
if read.Version() != 2 || len(read.Profile().Representatives()) != 1 || read.Profile().Representatives()[0].Name() != "Автор "+winner {
t.Fatalf("stored organization = %v, want one winner's name and representative at version 2", read)
}
})
t.Run("a revocation that commits while an update waits stops the update", func(t *testing.T) {
reset(t)
owner := fixture.employer(t, "owner@example.com")
second := fixture.employer(t, "second@example.com")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now)
fixture.addMember(t, organization, second, domain.OrganizationRoleOwner, now.Add(time.Minute))
changed, err := organization.ApplyProfile(mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Правка отозванного"}), now.Add(time.Hour))
if err != nil {
t.Fatalf("ApplyProfile() error = %v", err)
}
// A transaction revokes the second owner and stays open, holding the
// row lock of the membership.
revoker := startHeldTransaction(ctx, t, fixture.transactor, func(ctx context.Context, unit outbound.UnitOfWork) error {
tx, _ := postgresadapter.TransactionForIntegrationTest(unit)
_, err := tx.Exec(ctx, `UPDATE memberships SET state = 'removed' WHERE organization_id = $1 AND user_id = $2`, organization.ID(), second.ID)
return err
}, true)
revoker.awaitHeld(ctx, t)
const applicationName = "organization-update-waiter"
waiting := postgresadapter.NewTransactor(env.newPoolWithApplicationName(ctx, t, applicationName))
result := make(chan error, 1)
go func() {
result <- waiting.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
_, err := unit.Organizations().UpdateProfile(ctx, second.ID, changed)
return err
})
}()
if event, ok := waitForLockWait(ctx, pool, applicationName); !ok {
t.Fatalf("the update did not wait for the membership lock, last wait event %q", event)
}
if err := revoker.finish(); err != nil {
t.Fatalf("revoking transaction error = %v", err)
}
// The update saw the committed revocation and wrote nothing.
if err := <-result; !errors.Is(err, outbound.ErrOrganizationNotFound) {
t.Fatalf("UpdateProfile(revoked while waiting) error = %v, want ErrOrganizationNotFound", err)
}
read, _, err := fixture.read(owner.ID, organization.ID())
if err != nil || read.Version() != 1 || read.Profile().Name() != "ООО Пример" {
t.Fatalf("stored organization = %v, %v, want it unchanged at version 1", read, err)
}
})
t.Run("keeps the role off the organization and refuses malformed rows", func(t *testing.T) {
reset(t)
// The role and the members live only in memberships.
var columns []string
rows, err := pool.Query(ctx, `
SELECT column_name FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'organizations' ORDER BY ordinal_position`)
if err != nil {
t.Fatalf("list organization columns: %v", err)
}
columns, err = pgx.CollectRows(rows, pgx.RowTo[string])
if err != nil {
t.Fatalf("read organization columns: %v", err)
}
for _, column := range columns {
if strings.Contains(column, "role") || strings.Contains(column, "owner") || strings.Contains(column, "member") || strings.Contains(column, "user") {
t.Fatalf("organizations has the column %q; roles and members belong to memberships", column)
}
}
user := fixture.employer(t, "owner@example.com")
organization := fixture.create(t, user, fixture.completeProfile(t, "ООО Пример"), now)
insertOrganization := func(name, verificationLevel, basis string, version int) error {
_, err := pool.Exec(ctx, `
INSERT INTO organizations (
id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at
) VALUES ($1, $2, $3, $4, $5, $6, $5, $5)`, uuid.New(), name, verificationLevel, basis, now, version)
return err
}
for _, test := range []struct {
name string
err error
constraint string
}{
{"empty name", insertOrganization("", "e0", "confirmed_email", 1), "organizations_name_format"},
{"padded name", insertOrganization(" ООО", "e0", "confirmed_email", 1), "organizations_name_format"},
{"name with a line break", insertOrganization("ООО\nПример", "e0", "confirmed_email", 1), "organizations_name_format"},
{"name over 200 characters", insertOrganization(strings.Repeat("я", 201), "e0", "confirmed_email", 1), "organizations_name_format"},
{"unknown level", insertOrganization("ООО", "e4", "confirmed_email", 1), "organizations_verification_known"},
{"level with the basis of another", insertOrganization("ООО", "e0", "corporate_domain", 1), "organizations_verification_known"},
{"version zero", insertOrganization("ООО", "e0", "confirmed_email", 0), "organizations_version_positive"},
} {
assertSQLError(t, test.name, test.err, organizationCheckViolation, test.constraint)
}
for _, test := range []struct {
name string
column string
value string
constraint string
}{
{"description with a padded end", "description", "текст ", "organizations_description_format"},
{"description with a control character", "description", "текст\x07", "organizations_description_format"},
{"sphere with a line break", "sphere", "а\nб", "organizations_sphere_format"},
{"website over http", "contact_website", "http://example.com", "organizations_contact_website_format"},
{"website with credentials", "contact_website", "https://user@example.com", "organizations_contact_website_format"},
{"email with a space", "contact_email", "a b@example.com", "organizations_contact_email_format"},
{"phone without a plus", "contact_phone", "74950000000", "organizations_contact_phone_format"},
{"telegram without an at sign", "contact_telegram", "careers_team", "organizations_contact_telegram_format"},
} {
_, err := pool.Exec(ctx, `UPDATE organizations SET `+test.column+` = $2 WHERE id = $1`, organization.ID(), test.value)
assertSQLError(t, test.name, err, organizationCheckViolation, test.constraint)
}
// Each level takes its own bases, and the composite key of the
// memberships can be the target of a later foreign key.
for _, test := range []struct {
level, basis string
ok bool
}{
{"e1", "corporate_domain", true},
{"e2", "requisites_and_authority", true},
{"e3", "manual_review", true},
{"e3", "partner_status", true},
{"e2", "manual_review", false},
{"e2", "corporate_domain", false},
{"e3", "requisites_and_authority", false},
{"e3", "confirmed_email", false},
{"e1", "partner_status", false},
} {
_, err := pool.Exec(ctx, `UPDATE organizations SET verification_level = $2, verification_basis = $3 WHERE id = $1`, organization.ID(), test.level, test.basis)
if test.ok && err != nil {
t.Fatalf("level %s with basis %s error = %v, want it accepted", test.level, test.basis, err)
}
if !test.ok {
assertSQLError(t, "level "+test.level+" with basis "+test.basis, err, organizationCheckViolation, "organizations_verification_known")
}
}
if _, err := pool.Exec(ctx, `UPDATE organizations SET verification_level = 'e0', verification_basis = 'confirmed_email' WHERE id = $1`, organization.ID()); err != nil {
t.Fatalf("reset the level: %v", err)
}
composite, err := pool.Begin(ctx)
if err != nil {
t.Fatalf("begin: %v", err)
}
defer func() { _ = composite.Rollback(ctx) }()
if _, err := composite.Exec(ctx, `
CREATE TABLE membership_reference (
organization_id uuid NOT NULL,
membership_id uuid NOT NULL,
FOREIGN KEY (organization_id, membership_id) REFERENCES memberships (organization_id, id)
)`); err != nil {
t.Fatalf("composite foreign key on memberships: %v", err)
}
if _, err := composite.Exec(ctx, `
INSERT INTO membership_reference SELECT organization_id, id FROM memberships WHERE organization_id = $1`, organization.ID()); err != nil {
t.Fatalf("reference a membership of its own organization: %v", err)
}
if _, err := composite.Exec(ctx, `
INSERT INTO membership_reference SELECT $1::uuid, id FROM memberships WHERE organization_id = $2`, uuid.New(), organization.ID()); err == nil {
t.Fatal("a membership was referenced under another organization")
}
_ = composite.Rollback(ctx)
// A value in the contract format passes.
if _, err := pool.Exec(ctx, `UPDATE organizations SET contact_website = 'https://example.com/path?q=1', contact_phone = '+74950000000' WHERE id = $1`, organization.ID()); err != nil {
t.Fatalf("update with valid contacts: %v", err)
}
_, err = pool.Exec(ctx, `UPDATE organizations SET updated_at = created_at - interval '1 second' WHERE id = $1`, organization.ID())
assertSQLError(t, "update before creation", err, organizationCheckViolation, "organizations_timestamps_after_creation")
for _, test := range []struct {
name string
role string
state string
constraint string
}{
{"unknown role", "admin", "active", "memberships_role_known"},
{"manager as a role of the PRD wording", "manager", "active", "memberships_role_known"},
{"unknown state", "recruiter", "invited", "memberships_state_known"},
} {
second := fixture.employer(t, test.role+test.state+"@example.com")
_, err := pool.Exec(ctx, `
INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $6)`, uuid.New(), organization.ID(), second.ID, test.role, test.state, now)
assertSQLError(t, test.name, err, organizationCheckViolation, test.constraint)
}
_, err = pool.Exec(ctx, `
INSERT INTO organization_representatives (organization_id, ordinal, name, job_title)
VALUES ($1, 10, 'Имя', 'Должность')`, organization.ID())
assertSQLError(t, "eleventh representative", err, organizationCheckViolation, "organization_representatives_ordinal_range")
_, err = pool.Exec(ctx, `
INSERT INTO organization_representatives (organization_id, ordinal, name, job_title)
VALUES ($1, 5, 'Имя', ' Должность')`, organization.ID())
assertSQLError(t, "padded job title", err, organizationCheckViolation, "organization_representatives_job_title_format")
})
t.Run("an account and an organization with memberships cannot be deleted", func(t *testing.T) {
reset(t)
owner := fixture.employer(t, "owner@example.com")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now)
_, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, owner.ID)
assertSQLError(t, "delete of an account with a membership", err, organizationRestrictViolation, "memberships_user_id_fkey")
_, err = pool.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, organization.ID())
assertSQLError(t, "delete of an organization with a member", err, organizationRestrictViolation, "memberships_organization_id_fkey")
assertRowCount(ctx, t, pool, organizationsTable, 1)
assertRowCount(ctx, t, pool, membershipsTable, 1)
// Once the memberships are gone the representatives go with the
// organization.
if _, err := pool.Exec(ctx, `DELETE FROM memberships WHERE organization_id = $1`, organization.ID()); err != nil {
t.Fatalf("delete the memberships: %v", err)
}
if _, err := pool.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, organization.ID()); err != nil {
t.Fatalf("delete the organization: %v", err)
}
assertRowCount(ctx, t, pool, organizationRepresentativesTable, 0)
})
}
func (fixture organizationFixture) employer(t *testing.T, email string) domain.User {
t.Helper()
return fixture.identity.createUser(t, email, domain.ScenarioEmployer, fixture.now.Add(-time.Hour))
}
func mustOrganizationProfile(t *testing.T, input domain.OrganizationProfileInput) domain.OrganizationProfile {
t.Helper()
profile, err := domain.NewOrganizationProfile(input)
if err != nil {
t.Fatalf("NewOrganizationProfile() error = %v", err)
}
return profile
}
func (fixture organizationFixture) completeProfile(t *testing.T, name string) domain.OrganizationProfile {
t.Helper()
return mustOrganizationProfile(t, domain.OrganizationProfileInput{
Name: name,
Description: "Платежный сервис для малого бизнеса.\nСобственное ядро платежей.",
Sphere: "Платежи и финансовые сервисы",
Contacts: domain.OrganizationContactsInput{
Website: "https://payments.example.com", Email: "careers@payments.example.com", Phone: "+74950000000", Telegram: "@payments_careers",
},
Representatives: []domain.OrganizationRepresentativeInput{
{Name: "Анна Тестова", JobTitle: "Руководитель по подбору"},
{Name: "Борис Образцов", JobTitle: "Технический директор"},
},
})
}
func (fixture organizationFixture) newOrganization(t *testing.T, profile domain.OrganizationProfile, at time.Time) domain.Organization {
t.Helper()
organization, err := domain.NewOrganization(profile, at)
if err != nil {
t.Fatalf("NewOrganization() error = %v", err)
}
return organization
}
// create stores an organization with its owner in one transaction.
func (fixture organizationFixture) create(t *testing.T, owner domain.User, profile domain.OrganizationProfile, at time.Time) domain.Organization {
t.Helper()
organization := fixture.newOrganization(t, profile, at)
membership, err := domain.NewOwnerMembership(organization.ID(), owner.ID, at)
if err != nil {
t.Fatalf("NewOwnerMembership() error = %v", err)
}
err = fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Organizations().CreateWithOwner(ctx, organization, membership)
})
if err != nil {
t.Fatalf("CreateWithOwner(%q) error = %v", profile.Name(), err)
}
return organization
}
func (fixture organizationFixture) addMember(t *testing.T, organization domain.Organization, user domain.User, role domain.OrganizationRole, at time.Time) {
t.Helper()
membership, err := domain.NewMembership(domain.MembershipInput{OrganizationID: organization.ID(), UserID: user.ID, Role: role, At: at})
if err != nil {
t.Fatalf("NewMembership() error = %v", err)
}
err = fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Memberships().Insert(ctx, membership)
})
if err != nil {
t.Fatalf("Insert(%s membership) error = %v", role, err)
}
}
// setMembershipState ends or restores a membership the way the planned
// member management will; the repository has no such method yet.
func (fixture organizationFixture) setMembershipState(t *testing.T, organizationID, userID uuid.UUID, state domain.MembershipState) {
t.Helper()
if _, err := fixture.pool.Exec(fixture.ctx, `UPDATE memberships SET state = $3 WHERE organization_id = $1 AND user_id = $2`, organizationID, userID, string(state)); err != nil {
t.Fatalf("set the membership state to %s: %v", state, err)
}
}
func (fixture organizationFixture) read(userID, organizationID uuid.UUID) (domain.Organization, domain.Membership, error) {
var (
organization domain.Organization
membership domain.Membership
)
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
organization, membership, err = unit.Organizations().GetForMember(ctx, organizationID, userID)
return err
})
return organization, membership, err
}
func (fixture organizationFixture) getMembership(organizationID, userID uuid.UUID) (domain.Membership, error) {
var membership domain.Membership
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
membership, err = unit.Memberships().Get(ctx, organizationID, userID)
return err
})
return membership, err
}
func (fixture organizationFixture) list(t *testing.T, query outbound.OrganizationListQuery) outbound.OrganizationPage {
t.Helper()
var page outbound.OrganizationPage
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
page, err = unit.Organizations().ListForUser(ctx, query)
return err
})
if err != nil {
t.Fatalf("ListForUser() error = %v", err)
}
return page
}
// update applies profile to organization as of its version and stores it.
func (fixture organizationFixture) update(
t *testing.T,
actorID uuid.UUID,
organization domain.Organization,
profile domain.OrganizationProfile,
at time.Time,
) domain.Organization {
t.Helper()
changed, err := organization.ApplyProfile(profile, at)
if err != nil {
t.Fatalf("ApplyProfile() error = %v", err)
}
updated, err := fixture.tryUpdate(actorID, changed)
if err != nil {
t.Fatalf("UpdateProfile() error = %v", err)
}
return updated
}
func (fixture organizationFixture) tryUpdate(actorID uuid.UUID, organization domain.Organization) (domain.Organization, error) {
var updated domain.Organization
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
updated, err = unit.Organizations().UpdateProfile(ctx, actorID, organization)
return err
})
return updated, err
}
func (fixture organizationFixture) assertNothingStored(t *testing.T) {
t.Helper()
for _, table := range organizationTables {
assertRowCount(fixture.ctx, t, fixture.pool, table, 0)
}
}
func organizationIDs(page outbound.OrganizationPage) []uuid.UUID {
ids := make([]uuid.UUID, 0, len(page.Items))
for _, item := range page.Items {
ids = append(ids, item.Organization.ID())
}
return ids
}
// sameVerification compares the instants, because a stored time carries
// another location than the application clock that wrote it.
func sameVerification(left, right domain.OrganizationVerification) bool {
return left.Level() == right.Level() && left.Basis() == right.Basis() && left.ChangedAt().Equal(right.ChangedAt())
}