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,227 @@
-- +goose Up
-- Organizations, their public representatives, and the memberships that give
-- an account a role in an organization (PRD 2.2, FR07, and 6.4). Enum-like
-- columns are text with CHECK constraints, as in the identity tables.
--
-- The organization row holds the profile that the owner edits and the
-- verification level that only the server sets. The columns of the two are
-- separate on purpose: the profile update statement never names the
-- verification columns, so editing a profile cannot move the level. Every
-- time comes from the application clock.
--
-- The rows hold personal data of employees (representative names, the
-- membership of an account), so the application never copies them into
-- logs, metrics, or events beyond identifiers.
CREATE TABLE organizations (
-- UUIDv7 generated in Go. It is the org_id of every organization path.
id uuid NOT NULL,
-- The name consent records snapshot, so the bound equals the bound of
-- consent_records.organization_name.
name text NOT NULL,
description text,
-- Field of business as free text; the product has no sphere taxonomy.
sphere text,
-- Public company contacts only, never personal ones. Each is NULL or a
-- value in the format of the contract; the domain checks them in full.
contact_website text,
contact_email text,
contact_phone text,
contact_telegram text,
-- Trust level (PRD FR07). It starts at e0 and moves only by a
-- verification process of the server, which will record the change in
-- its own history table. No profile statement writes these columns.
verification_level text NOT NULL,
verification_basis text NOT NULL,
verification_changed_at timestamptz NOT NULL,
-- Optimistic concurrency version of the profile, advanced by every
-- profile update.
version bigint NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT organizations_pkey PRIMARY KEY (id),
CONSTRAINT organizations_name_format CHECK (
char_length(name) BETWEEN 1 AND 200
AND name !~ '^\s|\s$'
AND name !~ '[[:cntrl:]]'
),
-- Line breaks are allowed inside the text; every other control
-- character, and whitespace at the ends, are not.
CONSTRAINT organizations_description_format CHECK (
description IS NULL OR (
char_length(description) BETWEEN 1 AND 2000
AND description !~ '^\s|\s$'
AND translate(description, E'\n', '') !~ '[[:cntrl:]]'
)
),
CONSTRAINT organizations_sphere_format CHECK (
sphere IS NULL OR (
char_length(sphere) BETWEEN 1 AND 100
AND sphere !~ '^\s|\s$'
AND sphere !~ '[[:cntrl:]]'
)
),
CONSTRAINT organizations_contact_website_format CHECK (
contact_website IS NULL OR (
char_length(contact_website) BETWEEN 9 AND 300
AND contact_website ~ '^https://[^\s/?#@]+([/?#]\S*)?$'
)
),
CONSTRAINT organizations_contact_email_format CHECK (
contact_email IS NULL OR (
char_length(contact_email) BETWEEN 3 AND 254
AND contact_email ~ '^[^@\s]+@[^@\s]+$'
)
),
CONSTRAINT organizations_contact_phone_format CHECK (
contact_phone IS NULL OR contact_phone ~ '^\+[1-9][0-9]{6,14}$'
),
CONSTRAINT organizations_contact_telegram_format CHECK (
contact_telegram IS NULL OR contact_telegram ~ '^@[A-Za-z0-9_]{5,32}$'
),
-- Each level has its own bases (PRD FR07), so a level never carries the
-- ground of another one.
CONSTRAINT organizations_verification_known CHECK (
(verification_level = 'e0' AND verification_basis = 'confirmed_email')
OR (
verification_level = 'e1'
AND verification_basis = 'corporate_domain'
)
OR (
verification_level = 'e2'
AND verification_basis = 'requisites_and_authority'
)
OR (
verification_level = 'e3'
AND verification_basis IN ('manual_review', 'partner_status')
)
),
CONSTRAINT organizations_version_positive CHECK (version > 0),
CONSTRAINT organizations_timestamps_after_creation CHECK (
updated_at >= created_at
AND verification_changed_at >= created_at
)
);
-- The representatives that the owner presents on the card. They are
-- presentation only: no account link, no right. The list is replaced as a
-- whole with the organization update, in the order of ordinal.
CREATE TABLE organization_representatives (
organization_id uuid NOT NULL,
-- Position in the list, from 0; at most ten representatives.
ordinal smallint NOT NULL,
name text NOT NULL,
job_title text NOT NULL,
CONSTRAINT organization_representatives_pkey PRIMARY KEY (
organization_id, ordinal
),
-- The list is part of the organization row and goes with it.
CONSTRAINT organization_representatives_organization_id_fkey FOREIGN KEY (
organization_id
) REFERENCES organizations (id) ON DELETE CASCADE,
CONSTRAINT organization_representatives_ordinal_range CHECK (
ordinal BETWEEN 0 AND 9
),
CONSTRAINT organization_representatives_name_format CHECK (
char_length(name) BETWEEN 1 AND 100
AND name !~ '^\s|\s$'
AND name !~ '[[:cntrl:]]'
),
CONSTRAINT organization_representatives_job_title_format CHECK (
char_length(job_title) BETWEEN 1 AND 100
AND job_title !~ '^\s|\s$'
AND job_title !~ '[[:cntrl:]]'
)
);
-- One row per account and organization, whatever its role and state: a
-- former member who returns gets the same row back in the active state, and
-- the history of the pair belongs to the audit events. The role lives only
-- here, never on the organization. Only an active membership gives access;
-- the full role matrix (PRD FR07) is applied by the application, and a row
-- grants nothing by itself.
CREATE TABLE memberships (
-- UUIDv7 generated in Go; the planned assignments of needs refer to it.
id uuid NOT NULL,
organization_id uuid NOT NULL,
user_id uuid NOT NULL,
-- owner, recruiter, hiring_manager, or technical_expert.
role text NOT NULL,
-- active, suspended, removed (by the owner or the platform), or left (by
-- the member).
state text NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT memberships_pkey PRIMARY KEY (id),
-- A repeated membership of the same pair fails here. The leading
-- user_id also serves the list of an account's organizations.
CONSTRAINT memberships_user_id_organization_id_key UNIQUE (
user_id, organization_id
),
-- Target of the composite foreign keys that later tables use to bind a
-- membership to its organization, such as the assignments of needs.
CONSTRAINT memberships_organization_id_id_key UNIQUE (
organization_id, id
),
-- Both references restrict: an organization with members and an account
-- with memberships cannot be deleted until an explicit procedure ends
-- the memberships first. The application never deletes an organization.
CONSTRAINT memberships_organization_id_fkey FOREIGN KEY (
organization_id
) REFERENCES organizations (id) ON DELETE RESTRICT,
CONSTRAINT memberships_user_id_fkey FOREIGN KEY (
user_id
) REFERENCES users (id) ON DELETE RESTRICT,
CONSTRAINT memberships_role_known CHECK (
role IN ('owner', 'recruiter', 'hiring_manager', 'technical_expert')
),
CONSTRAINT memberships_state_known CHECK (
state IN ('active', 'suspended', 'removed', 'left')
),
CONSTRAINT memberships_updated_after_creation CHECK (
updated_at >= created_at
)
);
-- Serves the members of an organization and the foreign key.
CREATE INDEX memberships_organization_id_idx
ON memberships (organization_id);
-- Refuses an organization that has no active owner when the transaction that
-- inserted it commits (SQLSTATE 23514, constraint
-- organizations_owner_required). The check is deferred, so the organization
-- and its owner membership are inserted in either order inside one
-- transaction, and a transaction that fails between the two statements
-- leaves neither. Removing or demoting the last owner later is a rule of
-- the member management, not of this constraint.
-- +goose StatementBegin
CREATE FUNCTION organizations_require_owner() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM memberships
WHERE
memberships.organization_id = NEW.id
AND memberships.role = 'owner'
AND memberships.state = 'active'
) THEN
RAISE EXCEPTION USING
ERRCODE = 'check_violation',
CONSTRAINT = 'organizations_owner_required',
TABLE = 'organizations',
MESSAGE = 'an organization needs an active owner';
END IF;
RETURN NULL;
END;
$$;
-- +goose StatementEnd
CREATE CONSTRAINT TRIGGER organizations_owner_required
AFTER INSERT ON organizations
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION organizations_require_owner();
-- +goose Down
DROP TABLE memberships;
DROP TABLE organization_representatives;
DROP TABLE organizations;
DROP FUNCTION organizations_require_owner();
+224
View File
@@ -0,0 +1,224 @@
-- Stores a new organization with the verification level that the domain
-- gave it. The deferred constraint organizations_owner_required fails the
-- transaction at commit unless an active owner membership was inserted in
-- it too.
-- name: InsertOrganization :exec
INSERT INTO organizations (
id,
name,
description,
sphere,
contact_website,
contact_email,
contact_phone,
contact_telegram,
verification_level,
verification_basis,
verification_changed_at,
version,
created_at,
updated_at
) VALUES (
sqlc.arg(id),
sqlc.arg(name),
sqlc.narg(description),
sqlc.narg(sphere),
sqlc.narg(contact_website),
sqlc.narg(contact_email),
sqlc.narg(contact_phone),
sqlc.narg(contact_telegram),
sqlc.arg(verification_level),
sqlc.arg(verification_basis),
sqlc.arg(verification_changed_at),
sqlc.arg(version),
sqlc.arg(created_at),
sqlc.arg(updated_at)
);
-- Stores one representative at its position in the list. The adapter calls it
-- once per representative after it deleted the previous list, in the same
-- transaction.
-- name: InsertOrganizationRepresentative :exec
INSERT INTO organization_representatives (
organization_id,
ordinal,
name,
job_title
) VALUES (
sqlc.arg(organization_id),
sqlc.arg(ordinal),
sqlc.arg(name),
sqlc.arg(job_title)
);
-- name: DeleteOrganizationRepresentatives :exec
DELETE FROM organization_representatives
WHERE organization_id = sqlc.arg(organization_id);
-- Reads an organization together with the membership of one account in it
-- and its representatives in list order, as one statement, so the profile and
-- the list come from one snapshot. Only an active membership matches, so an
-- unknown organization, an account that is no member, and a suspended,
-- removed, or left member all return no row and cannot be told apart.
-- name: GetOrganizationForMember :one
SELECT
organization.id,
organization.name,
organization.description,
organization.sphere,
organization.contact_website,
organization.contact_email,
organization.contact_phone,
organization.contact_telegram,
organization.verification_level,
organization.verification_basis,
organization.verification_changed_at,
organization.version,
organization.created_at,
organization.updated_at,
coalesce((
SELECT
jsonb_agg(
jsonb_build_object('name', representative.name, 'job_title', representative.job_title)
ORDER BY representative.ordinal
)
FROM organization_representatives AS representative
WHERE representative.organization_id = organization.id
), '[]'::jsonb)::text AS representatives,
membership.id AS membership_id,
membership.role AS membership_role,
membership.state AS membership_state,
membership.created_at AS membership_created_at,
membership.updated_at AS membership_updated_at
FROM organizations AS organization
INNER JOIN memberships AS membership ON organization.id = membership.organization_id
WHERE
organization.id = sqlc.arg(organization_id)
AND membership.user_id = sqlc.arg(user_id)
AND membership.state = 'active';
-- Changes the profile of an organization over the version the caller read
-- and advances the version in the same statement. It names no verification
-- column, so a profile update cannot move the trust level. The change
-- applies only for an account whose active membership has one of the
-- manager roles, checked in the statement itself so that a membership that
-- ended after the caller's read still stops the write. The statement locks
-- the organization row first and then the actor's membership row FOR SHARE,
-- so a revocation that commits while the statement waits is seen again
-- (EvalPlanQual) and stops the write; the order organizations, then
-- memberships, is the lock order of every writer (member management must
-- follow it). No row returns for a stale version, an account that is no
-- active manager, or an unknown organization; the adapter reads the
-- membership to tell them apart.
-- name: UpdateOrganizationProfile :one
WITH target AS (
SELECT id FROM organizations
WHERE
id = sqlc.arg(id)
AND version = sqlc.arg(expected_version)
FOR UPDATE
),
actor AS (
SELECT memberships.id FROM memberships
INNER JOIN target ON memberships.organization_id = target.id
WHERE
memberships.user_id = sqlc.arg(actor_id)
AND memberships.state = 'active'
AND memberships.role = any(sqlc.arg(manager_roles)::text [])
FOR SHARE OF memberships
)
UPDATE organizations
SET
name = sqlc.arg(name),
description = sqlc.narg(description),
sphere = sqlc.narg(sphere),
contact_website = sqlc.narg(contact_website),
contact_email = sqlc.narg(contact_email),
contact_phone = sqlc.narg(contact_phone),
contact_telegram = sqlc.narg(contact_telegram),
updated_at = sqlc.arg(updated_at),
version = organizations.version + 1
FROM actor
WHERE
organizations.id = sqlc.arg(id)
AND organizations.version = sqlc.arg(expected_version)
RETURNING
organizations.id,
organizations.name,
organizations.description,
organizations.sphere,
organizations.contact_website,
organizations.contact_email,
organizations.contact_phone,
organizations.contact_telegram,
organizations.verification_level,
organizations.verification_basis,
organizations.verification_changed_at,
organizations.version,
organizations.created_at,
organizations.updated_at;
-- Lists the organizations where an account has an active membership,
-- newest membership first. The page continues after the (membership
-- creation time, organization ID) position of the last item of the
-- previous page. Only the active memberships of the given account match.
-- name: ListOrganizationsForUser :many
SELECT
organization.id,
organization.name,
organization.verification_level,
membership.id AS membership_id,
membership.role AS membership_role,
membership.state AS membership_state,
membership.created_at AS membership_created_at,
membership.updated_at AS membership_updated_at
FROM memberships AS membership
INNER JOIN organizations AS organization ON membership.organization_id = organization.id
WHERE
membership.user_id = sqlc.arg(user_id)
AND membership.state = 'active'
AND (
sqlc.narg(after_joined_at)::timestamptz IS NULL
OR (membership.created_at, membership.organization_id) < (
sqlc.narg(after_joined_at)::timestamptz,
sqlc.narg(after_organization_id)::uuid
)
)
ORDER BY membership.created_at DESC, membership.organization_id DESC
LIMIT sqlc.arg(row_limit);
-- name: InsertMembership :exec
INSERT INTO memberships (
id,
organization_id,
user_id,
role,
state,
created_at,
updated_at
) VALUES (
sqlc.arg(id),
sqlc.arg(organization_id),
sqlc.arg(user_id),
sqlc.arg(role),
sqlc.arg(state),
sqlc.arg(created_at),
sqlc.arg(updated_at)
);
-- Reads the membership of one account in one organization, in any state.
-- name: GetMembership :one
SELECT
id,
organization_id,
user_id,
role,
state,
created_at,
updated_at
FROM memberships
WHERE
organization_id = sqlc.arg(organization_id)
AND user_id = sqlc.arg(user_id);
@@ -89,7 +89,7 @@ func TestConsentLedger(t *testing.T) {
reset := func(t *testing.T) {
t.Helper()
// Every table that references users must be truncated with it.
truncateTables(ctx, t, pool, slices.Concat(identityTables, deliveryTables, consentTables)...)
truncateTables(ctx, t, pool, usersDependentTables...)
}
t.Run("migration publishes one demo text per purpose bound to its hash", func(t *testing.T) {
@@ -5,7 +5,6 @@ package integration_test
import (
"context"
"errors"
"slices"
"sync/atomic"
"testing"
"time"
@@ -155,7 +154,7 @@ func TestConsentGrants(t *testing.T) {
reset := func(t *testing.T) {
t.Helper()
fixture.nowNanos.Store(start.UnixNano())
truncateTables(ctx, t, pool, slices.Concat(identityTables, deliveryTables, consentTables)...)
truncateTables(ctx, t, pool, usersDependentTables...)
}
t.Run("C1 is written in the registration transaction and the other purposes separately", func(t *testing.T) {
+2 -1
View File
@@ -10,6 +10,7 @@ import (
"log/slog"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
@@ -134,7 +135,7 @@ func TestMailDelivery(t *testing.T) {
{"consumer_processed_events"},
{"consumer_dead_letters"},
}, deliveryTables...)
truncateTables(ctx, t, pool, append(append(tables, identityTables...), consentTables...)...)
truncateTables(ctx, t, pool, slices.Concat(tables, usersDependentTables)...)
}
t.Run("one event processed twice through the consumer creates one delivery", func(t *testing.T) {
+1 -2
View File
@@ -7,7 +7,6 @@ import (
"crypto/sha256"
"errors"
"fmt"
"slices"
"strings"
"sync"
"testing"
@@ -72,7 +71,7 @@ func TestIdentityRepositories(t *testing.T) {
t.Helper()
// The deliveries and consent records reference users, so TRUNCATE
// must name them too.
truncateTables(ctx, t, pool, slices.Concat(identityTables, deliveryTables, consentTables)...)
truncateTables(ctx, t, pool, usersDependentTables...)
}
t.Run("stores an account and finds it by ID and by any case of its email", func(t *testing.T) {
+2 -1
View File
@@ -6,6 +6,7 @@ import (
"context"
"errors"
"log/slog"
"slices"
"strings"
"sync"
"testing"
@@ -62,7 +63,7 @@ func TestMailQuota(t *testing.T) {
harness.recipients = &deliveryHarness{env: env, pool: pool, identity: postgresadapter.NewIdentityStore(pool), logs: harness.logs}
reset := func(t *testing.T, now time.Time) domain.User {
t.Helper()
truncateTables(ctx, t, pool, append([]pgx.Identifier{mailQuotaUsageTable, mailQuotaReservationsTable}, append(append(deliveryTables, identityTables...), consentTables...)...)...)
truncateTables(ctx, t, pool, slices.Concat([]pgx.Identifier{mailQuotaUsageTable, mailQuotaReservationsTable}, usersDependentTables)...)
harness.now = now
harness.recipients.now = now
return harness.recipients.createRecipient(ctx, t, true)
@@ -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())
}
@@ -143,7 +143,9 @@ func (env *testEnvironment) createIsolatedDatabase(ctx context.Context, t *testi
}
// truncateTables resets shared tables between sequential subtests. Callers
// must not run subtests that use these tables in parallel.
// must not run subtests that use these tables in parallel. PostgreSQL refuses
// to truncate a table that another table references unless both are listed,
// so a test that truncates users names usersDependentTables.
func truncateTables(ctx context.Context, t *testing.T, pool *pgxpool.Pool, tables ...pgx.Identifier) {
t.Helper()
names := make([]string, 0, len(tables))
@@ -33,10 +33,14 @@ const (
mailQuotaMigrationVersion = 7
// scheduledJobMigrationVersion creates scheduledJobTableNames.
scheduledJobMigrationVersion = 8
// organizationMigrationVersion creates organizationTableNames and
// organizationFunctionNames.
organizationMigrationVersion = 10
)
var (
// Tables created by 00001, 00002, 00003, 00005, 00006, 00007, and 00008.
// Tables created by 00001, 00002, 00003, 00005, 00006, 00007, 00008, and
// 00010.
outboxTables = []string{"outbox_events"}
identityTableNames = []string{"users", "email_tokens", "sessions"}
policyTableNames = []string{"policy_versions"}
@@ -44,9 +48,12 @@ var (
deliveryTableNames = []string{"mail_requests", "deliveries", "delivery_attempts"}
mailQuotaTableNames = []string{"mail_quota_usage", "mail_quota_reservations"}
scheduledJobTableNames = []string{"scheduled_jobs"}
// Trigger functions created by 00003 and 00006.
policyFunctionNames = []string{"policy_versions_refuse_change()", "policy_versions_stamp_creation()"}
deliveryFunctionNames = []string{"deliveries_refuse_content_change()", "delivery_attempts_refuse_update()"}
// organizationTableNames lists the tables of migration 00010.
organizationTableNames = []string{"organizations", "organization_representatives", "memberships"}
// Trigger functions created by 00003, 00006, and 00010.
policyFunctionNames = []string{"policy_versions_refuse_change()", "policy_versions_stamp_creation()"}
deliveryFunctionNames = []string{"deliveries_refuse_content_change()", "delivery_attempts_refuse_update()"}
organizationFunctionNames = []string{"organizations_require_owner()"}
)
func TestPostgresMigrations(t *testing.T) {
@@ -80,9 +87,11 @@ func TestPostgresMigrations(t *testing.T) {
assertFunctionsExist(ctx, t, pool, true, deliveryFunctionNames...)
assertTablesExist(ctx, t, pool, true, mailQuotaTableNames...)
assertTablesExist(ctx, t, pool, true, scheduledJobTableNames...)
assertTablesExist(ctx, t, pool, true, organizationTableNames...)
assertFunctionsExist(ctx, t, pool, true, organizationFunctionNames...)
identityRolledBack, policyRolledBack, consumerRolledBack, deliveryRolledBack, mailQuotaRolledBack := false, false, false, false, false
scheduledJobRolledBack := false
scheduledJobRolledBack, organizationRolledBack := false, false
for rolledBack := 0; ; rolledBack++ {
result, err := migrator.DownOne(ctx)
if errors.Is(err, postgresadapter.ErrNoMigrationToRollBack) {
@@ -94,6 +103,14 @@ func TestPostgresMigrations(t *testing.T) {
if err != nil {
t.Fatalf("DownOne() after %d rollbacks error = %v", rolledBack, err)
}
if result.Version == organizationMigrationVersion {
// The organization migration removes its tables and its
// function and leaves the identity tables they reference.
assertTablesExist(ctx, t, pool, false, organizationTableNames...)
assertFunctionsExist(ctx, t, pool, false, organizationFunctionNames...)
assertTablesExist(ctx, t, pool, true, identityTableNames...)
organizationRolledBack = true
}
if result.Version == scheduledJobMigrationVersion {
// The scheduled job migration removes only its own table.
assertTablesExist(ctx, t, pool, false, scheduledJobTableNames...)
@@ -137,10 +154,11 @@ func TestPostgresMigrations(t *testing.T) {
identityRolledBack = true
}
}
if !identityRolledBack || !policyRolledBack || !consumerRolledBack || !deliveryRolledBack || !mailQuotaRolledBack || !scheduledJobRolledBack {
t.Fatalf("migrations %d, %d, %d, %d, %d, and %d were not all rolled back",
if !identityRolledBack || !policyRolledBack || !consumerRolledBack || !deliveryRolledBack || !mailQuotaRolledBack ||
!scheduledJobRolledBack || !organizationRolledBack {
t.Fatalf("migrations %d, %d, %d, %d, %d, %d, and %d were not all rolled back",
identityMigrationVersion, policyMigrationVersion, consumerMigrationVersion, deliveryMigrationVersion, mailQuotaMigrationVersion,
scheduledJobMigrationVersion)
scheduledJobMigrationVersion, organizationMigrationVersion)
}
assertTablesExist(ctx, t, pool, false, outboxTables...)
assertTablesExist(ctx, t, pool, false, identityTableNames...)
@@ -181,6 +199,8 @@ func TestPostgresMigrations(t *testing.T) {
assertFunctionsExist(ctx, t, pool, true, policyFunctionNames...)
assertTablesExist(ctx, t, pool, true, consumerTableNames...)
assertTablesExist(ctx, t, pool, true, deliveryTableNames...)
assertTablesExist(ctx, t, pool, true, organizationTableNames...)
assertFunctionsExist(ctx, t, pool, true, organizationFunctionNames...)
assertAllApplied(ctx, t, migrator, total)
})
@@ -17,20 +17,22 @@ import (
)
var regexMap = map[string]ogenregex.Regexp{
"\\S": ogenregex.MustCompile("\\S"),
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
"^[a-z0-9][a-z0-9_.+#-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_.+#-]*$"),
"^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"),
"^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
"^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"),
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
"\\S": ogenregex.MustCompile("\\S"),
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
"^[a-z0-9][a-z0-9_.+#-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_.+#-]*$"),
"^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"),
"^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
"^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"),
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
"^\\S(?:[^\\n\\r]*\\S)?$": ogenregex.MustCompile("^\\S(?:[^\\n\\r]*\\S)?$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
"^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$": ogenregex.MustCompile("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$"),
}
var (
// Allocate option closure once.
@@ -1342,6 +1342,263 @@ func (s *Server) handleCreateMySupportCaseRequest(args [0]string, argsEscaped bo
}
}
// handleCreateOrganizationRequest handles CreateOrganization operation.
//
// Requires the session cookie of an employer account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the
// session: the body has no owner, membership, role, verification, or version field, and unknown fields
// fail validation.
//
// The server creates the organization and the owner membership of the caller (role `owner`, state
// `active`) in one transaction, so an organization never exists without its owner. The organization
// starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be
// requested: the creator of a company with a corporate domain, a long description, or many
// representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of
// the server that do not exist yet. Only `name` is required; the rest of the card can be completed
// with UpdateOrganization.
//
// Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates
// nothing, so a lost response never creates a second organization. A different body with the same key
// answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again.
// Two requests with different keys are two organizations; the product may limit the number of
// organizations per account (open question), which would answer 409 `state_conflict` without a change
// of the schema.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409
// idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a
// website that is not an https URL of a host name, `/name` for a name with surrounding whitespace).
// The general rate limit can answer 429 with Retry-After before any check; 429 is never stored.
//
// POST /api/v1/organizations
func (s *Server) handleCreateOrganizationRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("CreateOrganization"),
semconv.HTTPRequestMethodKey.String("POST"),
semconv.HTTPRouteKey.String("/api/v1/organizations"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), CreateOrganizationOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: CreateOrganizationOperation,
ID: "CreateOrganization",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, CreateOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, CreateOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeCreateOrganizationParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
request, rawBody, close, err := s.decodeCreateOrganizationRequest(r)
if err != nil {
err = &ogenerrors.DecodeRequestError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeRequest", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
defer func() {
if err := close(); err != nil {
recordError("CloseRequest", err)
}
}()
var response CreateOrganizationRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: CreateOrganizationOperation,
OperationSummary: "Create an organization; the caller becomes its owner.",
OperationID: "CreateOrganization",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "Idempotency-Key",
In: "header",
}: params.IdempotencyKey,
},
Raw: r,
}
type (
Request = *OrganizationCreate
Params = CreateOrganizationParams
Response = CreateOrganizationRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackCreateOrganizationParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.CreateOrganization(ctx, request, params)
return response, err
},
)
} else {
response, err = s.h.CreateOrganization(ctx, request, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeCreateOrganizationResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleCreateOrganizationInvitationRequest handles CreateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -4390,6 +4647,224 @@ func (s *Server) handleGetMySupportCaseRequest(args [1]string, argsEscaped bool,
}
}
// handleGetOrganizationRequest handles GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
// holds: it never rises because the profile is complete, because the organization has members, or
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
//
// GET /api/v1/organizations/{org_id}
func (s *Server) handleGetOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetOrganization"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: GetOrganizationOperation,
ID: "GetOrganization",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeGetOrganizationParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response GetOrganizationRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: GetOrganizationOperation,
OperationSummary: "Read an organization of which the caller is a member.",
OperationID: "GetOrganization",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "org_id",
In: "path",
}: params.OrgID,
},
Raw: r,
}
type (
Request = struct{}
Params = GetOrganizationParams
Response = GetOrganizationRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackGetOrganizationParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.GetOrganization(ctx, params)
return response, err
},
)
} else {
response, err = s.h.GetOrganization(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeGetOrganizationResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleGetOrganizationInvitationRequest handles GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -5670,6 +6145,233 @@ func (s *Server) handleListMyInvitationsRequest(args [0]string, argsEscaped bool
}
}
// handleListMyOrganizationsRequest handles ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
// request parameter, so the response holds only the caller's own memberships and no request can name
// another account.
//
// Returns a page of the organizations in which the caller has an `active` membership, newest
// membership first with the organization identifier as the tie-breaker, with cursor pagination. Each
// item names the organization (`OrganizationSummary`) and holds the caller's role and state in it
// (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not
// list its organization, so an organization the caller cannot enter is never named, and one that the
// caller was removed from disappears from the list at once.
//
// The list is the directory of the active organization context. The context is not stored on the
// server: every organization-scoped operation names its organization in the path `org_id`, and the
// server checks that identifier against the caller's active membership on every request, so a switch
// between organizations is a different `org_id` in the client's routes and cannot outlive a revoked
// membership. A client picks the context from this list, may remember the last choice in the browser
// as a convenience, and must read the list again after any answer 404 `not_found` from an organization
// path. An account with several memberships sees all of them here and works in one at a time; the
// rights and the data of the organizations stay separate.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden. An employer account without an organization gets an empty page, which
// tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400
// validation_failed.
//
// GET /api/v1/me/organizations
func (s *Server) handleListMyOrganizationsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("ListMyOrganizations"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/me/organizations"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyOrganizationsOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: ListMyOrganizationsOperation,
ID: "ListMyOrganizations",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, ListMyOrganizationsOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeListMyOrganizationsParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response ListMyOrganizationsRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: ListMyOrganizationsOperation,
OperationSummary: "List the organizations available to the current account.",
OperationID: "ListMyOrganizations",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "limit",
In: "query",
}: params.Limit,
{
Name: "cursor",
In: "query",
}: params.Cursor,
},
Raw: r,
}
type (
Request = struct{}
Params = ListMyOrganizationsParams
Response = ListMyOrganizationsRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackListMyOrganizationsParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.ListMyOrganizations(ctx, params)
return response, err
},
)
} else {
response, err = s.h.ListMyOrganizations(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeListMyOrganizationsResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleListMySupportCasesRequest handles ListMySupportCases operation.
//
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
@@ -8162,6 +8864,269 @@ func (s *Server) handleSubmitMyAssessmentAnswerRequest(args [1]string, argsEscap
}
}
// handleUpdateOrganizationRequest handles UpdateOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
// token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the
// organization (the FR07 matrix gives this to no other role), so a member with another role answers
// 403 forbidden. The role comes from the server-side membership; the body has no organization,
// membership, role, owner, or verification field.
//
// Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch.
// Each field present replaces that field as a whole and an absent field stays unchanged; `contacts`
// and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as
// null become unset; `name`, `contacts`, and `representatives` cannot be null.
//
// The body can change the profile only. The verification level, its basis, the card, the members, and
// every role are not fields of it, and unknown fields fail validation, so the owner can neither raise
// the trust level of the organization nor the rights of anyone by editing the profile; a longer
// description, a verified-looking website, or a new representative leaves the level unchanged. The
// level and the roles change only through processes of the server.
//
// Versions: every committed change creates version `expected_version + 1` and answers 200 with the
// organization. `expected_version` is the `version` the client read; when it is not current, the
// server answers 412 version_conflict and changes nothing, and the client reads the organization again
// and reapplies its edits. The version travels in the body rather than in If-Match because the
// generated client cannot read the ETag response header yet, as for needs. A body that changes nothing
// when applied to the current profile keeps the version and answers 200 with the current organization
// even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a
// change that already succeeded is harmless.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403
// forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer
// such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can
// answer 429 with Retry-After before any check.
//
// PATCH /api/v1/organizations/{org_id}
func (s *Server) handleUpdateOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("UpdateOrganization"),
semconv.HTTPRequestMethodKey.String("PATCH"),
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), UpdateOrganizationOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: UpdateOrganizationOperation,
ID: "UpdateOrganization",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, UpdateOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, UpdateOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeUpdateOrganizationParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
request, rawBody, close, err := s.decodeUpdateOrganizationRequest(r)
if err != nil {
err = &ogenerrors.DecodeRequestError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeRequest", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
defer func() {
if err := close(); err != nil {
recordError("CloseRequest", err)
}
}()
var response UpdateOrganizationRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: UpdateOrganizationOperation,
OperationSummary: "Change the profile of an organization.",
OperationID: "UpdateOrganization",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "org_id",
In: "path",
}: params.OrgID,
},
Raw: r,
}
type (
Request = *OrganizationUpdate
Params = UpdateOrganizationParams
Response = UpdateOrganizationRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackUpdateOrganizationParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.UpdateOrganization(ctx, request, params)
return response, err
},
)
} else {
response, err = s.h.UpdateOrganization(ctx, request, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeUpdateOrganizationResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleUpdateOrganizationInvitationRequest handles UpdateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -29,6 +29,10 @@ type CreateOrganizationNeedRes interface {
createOrganizationNeedRes()
}
type CreateOrganizationRes interface {
createOrganizationRes()
}
type DeclineMyInvitationRes interface {
declineMyInvitationRes()
}
@@ -85,6 +89,10 @@ type GetOrganizationNeedRes interface {
getOrganizationNeedRes()
}
type GetOrganizationRes interface {
getOrganizationRes()
}
type ListMyConsentsRes interface {
listMyConsentsRes()
}
@@ -93,6 +101,10 @@ type ListMyInvitationsRes interface {
listMyInvitationsRes()
}
type ListMyOrganizationsRes interface {
listMyOrganizationsRes()
}
type ListMySupportCasesRes interface {
listMySupportCasesRes()
}
@@ -145,6 +157,10 @@ type UpdateOrganizationNeedRes interface {
updateOrganizationNeedRes()
}
type UpdateOrganizationRes interface {
updateOrganizationRes()
}
type ViewMyInvitationRes interface {
viewMyInvitationRes()
}
File diff suppressed because it is too large. Load diff
@@ -11,6 +11,7 @@ const (
ConfirmEmailOperation OperationName = "ConfirmEmail"
CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt"
CreateMySupportCaseOperation OperationName = "CreateMySupportCase"
CreateOrganizationOperation OperationName = "CreateOrganization"
CreateOrganizationInvitationOperation OperationName = "CreateOrganizationInvitation"
CreateOrganizationNeedOperation OperationName = "CreateOrganizationNeed"
DeclineMyInvitationOperation OperationName = "DeclineMyInvitation"
@@ -25,12 +26,14 @@ const (
GetMyInvitationOperation OperationName = "GetMyInvitation"
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
GetMySupportCaseOperation OperationName = "GetMySupportCase"
GetOrganizationOperation OperationName = "GetOrganization"
GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation"
GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts"
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
ListMyConsentsOperation OperationName = "ListMyConsents"
ListMyInvitationsOperation OperationName = "ListMyInvitations"
ListMyOrganizationsOperation OperationName = "ListMyOrganizations"
ListMySupportCasesOperation OperationName = "ListMySupportCases"
ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations"
ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds"
@@ -42,6 +45,7 @@ const (
SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire"
SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation"
SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer"
UpdateOrganizationOperation OperationName = "UpdateOrganization"
UpdateOrganizationInvitationOperation OperationName = "UpdateOrganizationInvitation"
UpdateOrganizationNeedOperation OperationName = "UpdateOrganizationNeed"
ViewMyInvitationOperation OperationName = "ViewMyInvitation"
@@ -503,6 +503,100 @@ func decodeCreateMySupportCaseParams(args [0]string, argsEscaped bool, r *http.R
return params, nil
}
// CreateOrganizationParams is parameters of CreateOrganization operation.
type CreateOrganizationParams struct {
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
// is sent without quotes. The server scopes the key by caller and operation and fingerprints the
// request by method, path, and body.
//
// Stored for 24 hours after the first request and replayed with the same status, headers, and body:
// the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404
// not_found or 409 state_conflict. A replay does not repeat the side effect.
//
// Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for
// the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428
// precondition_required (nothing changed; read the resource again and retry), 422
// idempotency_key_reused, 429, and every 5xx.
//
// Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then
// the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused
// before any other key check; a running request with the same fingerprint returns 409
// idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that
// does the server check If-Match, so a retry of a completed change replays its outcome instead of
// failing on the version it has just changed. After 24 hours the key may be accepted as new.
IdempotencyKey string
}
func unpackCreateOrganizationParams(packed middleware.Parameters) (params CreateOrganizationParams) {
{
key := middleware.ParameterKey{
Name: "Idempotency-Key",
In: "header",
}
params.IdempotencyKey = packed[key].(string)
}
return params
}
func decodeCreateOrganizationParams(args [0]string, argsEscaped bool, r *http.Request) (params CreateOrganizationParams, _ error) {
h := uri.NewHeaderDecoder(r.Header)
// Decode header: Idempotency-Key.
if err := func() error {
cfg := uri.HeaderParameterDecodingConfig{
Name: "Idempotency-Key",
Explode: false,
}
if err := h.HasParam(cfg); err == nil {
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
params.IdempotencyKey = c
return nil
}); err != nil {
return err
}
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 255,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9._:-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(params.IdempotencyKey)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
} else {
return err
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "Idempotency-Key",
In: "header",
Err: err,
}
}
return params, nil
}
// CreateOrganizationInvitationParams is parameters of CreateOrganizationInvitation operation.
type CreateOrganizationInvitationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
@@ -1447,6 +1541,75 @@ func decodeGetMySupportCaseParams(args [1]string, argsEscaped bool, r *http.Requ
return params, nil
}
// GetOrganizationParams is parameters of GetOrganization operation.
type GetOrganizationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
// this organization, checked by the server on every request; the identifier itself grants nothing. An
// organization without such a membership and an unknown identifier both answer 404 not_found, so
// organizations cannot be enumerated.
OrgID uuid.UUID
}
func unpackGetOrganizationParams(packed middleware.Parameters) (params GetOrganizationParams) {
{
key := middleware.ParameterKey{
Name: "org_id",
In: "path",
}
params.OrgID = packed[key].(uuid.UUID)
}
return params
}
func decodeGetOrganizationParams(args [1]string, argsEscaped bool, r *http.Request) (params GetOrganizationParams, _ error) {
// Decode path: org_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "org_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.OrgID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "org_id",
In: "path",
Err: err,
}
}
return params, nil
}
// GetOrganizationInvitationParams is parameters of GetOrganizationInvitation operation.
type GetOrganizationInvitationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
@@ -2238,6 +2401,182 @@ func decodeListMyInvitationsParams(args [0]string, argsEscaped bool, r *http.Req
return params, nil
}
// ListMyOrganizationsParams is parameters of ListMyOrganizations operation.
type ListMyOrganizationsParams struct {
// Maximum number of items in the page. The server may return fewer items even when more remain; use
// `page.has_more` to detect the end.
Limit OptInt32 `json:",omitempty,omitzero"`
// Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the
// first page. A malformed or foreign cursor returns 400 with code validation_failed.
Cursor OptString `json:",omitempty,omitzero"`
}
func unpackListMyOrganizationsParams(packed middleware.Parameters) (params ListMyOrganizationsParams) {
{
key := middleware.ParameterKey{
Name: "limit",
In: "query",
}
if v, ok := packed[key]; ok {
params.Limit = v.(OptInt32)
}
}
{
key := middleware.ParameterKey{
Name: "cursor",
In: "query",
}
if v, ok := packed[key]; ok {
params.Cursor = v.(OptString)
}
}
return params
}
func decodeListMyOrganizationsParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyOrganizationsParams, _ error) {
q := uri.NewQueryDecoder(r.URL.Query())
// Set default value for query: limit.
{
val := int32(20)
params.Limit.SetTo(val)
}
// Decode query: limit.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "limit",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotLimitVal int32
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToInt32(val)
if err != nil {
return err
}
paramsDotLimitVal = c
return nil
}(); err != nil {
return err
}
params.Limit.SetTo(paramsDotLimitVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.Limit.Get(); ok {
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 100,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(value)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "limit",
In: "query",
Err: err,
}
}
// Decode query: cursor.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "cursor",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotCursorVal string
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
paramsDotCursorVal = c
return nil
}(); err != nil {
return err
}
params.Cursor.SetTo(paramsDotCursorVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.Cursor.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 512,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(value)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "cursor",
In: "query",
Err: err,
}
}
return params, nil
}
// ListMySupportCasesParams is parameters of ListMySupportCases operation.
type ListMySupportCasesParams struct {
// Maximum number of items in the page. The server may return fewer items even when more remain; use
@@ -3535,6 +3874,75 @@ func decodeSubmitMyAssessmentAnswerParams(args [1]string, argsEscaped bool, r *h
return params, nil
}
// UpdateOrganizationParams is parameters of UpdateOrganization operation.
type UpdateOrganizationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
// this organization, checked by the server on every request; the identifier itself grants nothing. An
// organization without such a membership and an unknown identifier both answer 404 not_found, so
// organizations cannot be enumerated.
OrgID uuid.UUID
}
func unpackUpdateOrganizationParams(packed middleware.Parameters) (params UpdateOrganizationParams) {
{
key := middleware.ParameterKey{
Name: "org_id",
In: "path",
}
params.OrgID = packed[key].(uuid.UUID)
}
return params
}
func decodeUpdateOrganizationParams(args [1]string, argsEscaped bool, r *http.Request) (params UpdateOrganizationParams, _ error) {
// Decode path: org_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "org_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.OrgID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "org_id",
In: "path",
Err: err,
}
}
return params, nil
}
// UpdateOrganizationInvitationParams is parameters of UpdateOrganizationInvitation operation.
type UpdateOrganizationInvitationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
@@ -409,6 +409,85 @@ func (s *Server) decodeCreateMySupportCaseRequest(r *http.Request) (
}
}
func (s *Server) decodeCreateOrganizationRequest(r *http.Request) (
req *OrganizationCreate,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request OrganizationCreate
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeCreateOrganizationInvitationRequest(r *http.Request) (
req *OrganizationInvitationCreate,
rawBody []byte,
@@ -1278,6 +1357,85 @@ func (s *Server) decodeSubmitMyAssessmentAnswerRequest(r *http.Request) (
}
}
func (s *Server) decodeUpdateOrganizationRequest(r *http.Request) (
req *OrganizationUpdate,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request OrganizationUpdate
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeUpdateOrganizationInvitationRequest(r *http.Request) (
req *OrganizationInvitationUpdate,
rawBody []byte,
@@ -657,6 +657,133 @@ func encodeCreateMySupportCaseResponse(response CreateMySupportCaseRes, w http.R
}
}
func encodeCreateOrganizationResponse(response CreateOrganizationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(201)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationConflict:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(409)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationUnprocessableEntity:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(422)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeCreateOrganizationInvitationResponse(response CreateOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationInvitationHeaders:
@@ -1769,6 +1896,89 @@ func encodeGetMySupportCaseResponse(response GetMySupportCaseRes, w http.Respons
}
}
func encodeGetOrganizationResponse(response GetOrganizationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetOrganizationBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetOrganizationUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetOrganizationForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetOrganizationNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeGetOrganizationInvitationResponse(response GetOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationInvitationHeaders:
@@ -2161,6 +2371,77 @@ func encodeListMyInvitationsResponse(response ListMyInvitationsRes, w http.Respo
}
}
func encodeListMyOrganizationsResponse(response ListMyOrganizationsRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *MyOrganizationListHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyOrganizationsBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyOrganizationsUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyOrganizationsForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeListMySupportCasesResponse(response ListMySupportCasesRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *SupportCaseListHeaders:
@@ -3282,6 +3563,133 @@ func encodeSubmitMyAssessmentAnswerResponse(response SubmitMyAssessmentAnswerRes
}
}
func encodeUpdateOrganizationResponse(response UpdateOrganizationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationPreconditionFailed:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(412)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeUpdateOrganizationInvitationResponse(response UpdateOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationInvitationHeaders:
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -60,6 +60,7 @@ var operationRolesSessionCookie = map[string][]string{
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
@@ -72,11 +73,13 @@ var operationRolesSessionCookie = map[string][]string{
GetMyInvitationOperation: []string{},
GetMyQuestionnaireOperation: []string{},
GetMySupportCaseOperation: []string{},
GetOrganizationOperation: []string{},
GetOrganizationInvitationOperation: []string{},
GetOrganizationInvitationContactsOperation: []string{},
GetOrganizationNeedOperation: []string{},
ListMyConsentsOperation: []string{},
ListMyInvitationsOperation: []string{},
ListMyOrganizationsOperation: []string{},
ListMySupportCasesOperation: []string{},
ListOrganizationInvitationsOperation: []string{},
ListOrganizationNeedsOperation: []string{},
@@ -85,6 +88,7 @@ var operationRolesSessionCookie = map[string][]string{
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UpdateOrganizationOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
@@ -118,6 +122,7 @@ var operationRolesSessionCsrf = map[string][]string{
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
@@ -127,6 +132,7 @@ var operationRolesSessionCsrf = map[string][]string{
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UpdateOrganizationOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
@@ -253,6 +253,36 @@ type Handler interface {
//
// POST /api/v1/me/support-cases
CreateMySupportCase(ctx context.Context, req SupportCaseCreate, params CreateMySupportCaseParams) (CreateMySupportCaseRes, error)
// CreateOrganization implements CreateOrganization operation.
//
// Requires the session cookie of an employer account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the
// session: the body has no owner, membership, role, verification, or version field, and unknown fields
// fail validation.
//
// The server creates the organization and the owner membership of the caller (role `owner`, state
// `active`) in one transaction, so an organization never exists without its owner. The organization
// starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be
// requested: the creator of a company with a corporate domain, a long description, or many
// representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of
// the server that do not exist yet. Only `name` is required; the rest of the card can be completed
// with UpdateOrganization.
//
// Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates
// nothing, so a lost response never creates a second organization. A different body with the same key
// answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again.
// Two requests with different keys are two organizations; the product may limit the number of
// organizations per account (open question), which would answer 409 `state_conflict` without a change
// of the schema.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409
// idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a
// website that is not an https URL of a host name, `/name` for a name with surrounding whitespace).
// The general rate limit can answer 429 with Retry-After before any check; 429 is never stored.
//
// POST /api/v1/organizations
CreateOrganization(ctx context.Context, req *OrganizationCreate, params CreateOrganizationParams) (CreateOrganizationRes, error)
// CreateOrganizationInvitation implements CreateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -608,6 +638,30 @@ type Handler interface {
//
// GET /api/v1/me/support-cases/{case_id}
GetMySupportCase(ctx context.Context, params GetMySupportCaseParams) (GetMySupportCaseRes, error)
// GetOrganization implements GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
// holds: it never rises because the profile is complete, because the organization has members, or
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
//
// GET /api/v1/organizations/{org_id}
GetOrganization(ctx context.Context, params GetOrganizationParams) (GetOrganizationRes, error)
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -765,6 +819,35 @@ type Handler interface {
//
// GET /api/v1/me/invitations
ListMyInvitations(ctx context.Context, params ListMyInvitationsParams) (ListMyInvitationsRes, error)
// ListMyOrganizations implements ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
// request parameter, so the response holds only the caller's own memberships and no request can name
// another account.
//
// Returns a page of the organizations in which the caller has an `active` membership, newest
// membership first with the organization identifier as the tie-breaker, with cursor pagination. Each
// item names the organization (`OrganizationSummary`) and holds the caller's role and state in it
// (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not
// list its organization, so an organization the caller cannot enter is never named, and one that the
// caller was removed from disappears from the list at once.
//
// The list is the directory of the active organization context. The context is not stored on the
// server: every organization-scoped operation names its organization in the path `org_id`, and the
// server checks that identifier against the caller's active membership on every request, so a switch
// between organizations is a different `org_id` in the client's routes and cannot outlive a revoked
// membership. A client picks the context from this list, may remember the last choice in the browser
// as a convenience, and must read the list again after any answer 404 `not_found` from an organization
// path. An account with several memberships sees all of them here and works in one at a time; the
// rights and the data of the organizations stay separate.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden. An employer account without an organization gets an empty page, which
// tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400
// validation_failed.
//
// GET /api/v1/me/organizations
ListMyOrganizations(ctx context.Context, params ListMyOrganizationsParams) (ListMyOrganizationsRes, error)
// ListMySupportCases implements ListMySupportCases operation.
//
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
@@ -1086,6 +1169,42 @@ type Handler interface {
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/answers
SubmitMyAssessmentAnswer(ctx context.Context, req *AssessmentAnswerSubmission, params SubmitMyAssessmentAnswerParams) (SubmitMyAssessmentAnswerRes, error)
// UpdateOrganization implements UpdateOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
// token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the
// organization (the FR07 matrix gives this to no other role), so a member with another role answers
// 403 forbidden. The role comes from the server-side membership; the body has no organization,
// membership, role, owner, or verification field.
//
// Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch.
// Each field present replaces that field as a whole and an absent field stays unchanged; `contacts`
// and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as
// null become unset; `name`, `contacts`, and `representatives` cannot be null.
//
// The body can change the profile only. The verification level, its basis, the card, the members, and
// every role are not fields of it, and unknown fields fail validation, so the owner can neither raise
// the trust level of the organization nor the rights of anyone by editing the profile; a longer
// description, a verified-looking website, or a new representative leaves the level unchanged. The
// level and the roles change only through processes of the server.
//
// Versions: every committed change creates version `expected_version + 1` and answers 200 with the
// organization. `expected_version` is the `version` the client read; when it is not current, the
// server answers 412 version_conflict and changes nothing, and the client reads the organization again
// and reapplies its edits. The version travels in the body rather than in If-Match because the
// generated client cannot read the ETag response header yet, as for needs. A body that changes nothing
// when applied to the current profile keeps the version and answers 200 with the current organization
// even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a
// change that already succeeded is harmless.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403
// forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer
// such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can
// answer 429 with Retry-After before any check.
//
// PATCH /api/v1/organizations/{org_id}
UpdateOrganization(ctx context.Context, req *OrganizationUpdate, params UpdateOrganizationParams) (UpdateOrganizationRes, error)
// UpdateOrganizationInvitation implements UpdateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -273,6 +273,39 @@ func (UnimplementedHandler) CreateMySupportCase(ctx context.Context, req Support
return r, ht.ErrNotImplemented
}
// CreateOrganization implements CreateOrganization operation.
//
// Requires the session cookie of an employer account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the
// session: the body has no owner, membership, role, verification, or version field, and unknown fields
// fail validation.
//
// The server creates the organization and the owner membership of the caller (role `owner`, state
// `active`) in one transaction, so an organization never exists without its owner. The organization
// starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be
// requested: the creator of a company with a corporate domain, a long description, or many
// representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of
// the server that do not exist yet. Only `name` is required; the rest of the card can be completed
// with UpdateOrganization.
//
// Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates
// nothing, so a lost response never creates a second organization. A different body with the same key
// answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again.
// Two requests with different keys are two organizations; the product may limit the number of
// organizations per account (open question), which would answer 409 `state_conflict` without a change
// of the schema.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409
// idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a
// website that is not an https URL of a host name, `/name` for a name with surrounding whitespace).
// The general rate limit can answer 429 with Retry-After before any check; 429 is never stored.
//
// POST /api/v1/organizations
func (UnimplementedHandler) CreateOrganization(ctx context.Context, req *OrganizationCreate, params CreateOrganizationParams) (r CreateOrganizationRes, _ error) {
return r, ht.ErrNotImplemented
}
// CreateOrganizationInvitation implements CreateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -670,6 +703,33 @@ func (UnimplementedHandler) GetMySupportCase(ctx context.Context, params GetMySu
return r, ht.ErrNotImplemented
}
// GetOrganization implements GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
// holds: it never rises because the profile is complete, because the organization has members, or
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
//
// GET /api/v1/organizations/{org_id}
func (UnimplementedHandler) GetOrganization(ctx context.Context, params GetOrganizationParams) (r GetOrganizationRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -845,6 +905,38 @@ func (UnimplementedHandler) ListMyInvitations(ctx context.Context, params ListMy
return r, ht.ErrNotImplemented
}
// ListMyOrganizations implements ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
// request parameter, so the response holds only the caller's own memberships and no request can name
// another account.
//
// Returns a page of the organizations in which the caller has an `active` membership, newest
// membership first with the organization identifier as the tie-breaker, with cursor pagination. Each
// item names the organization (`OrganizationSummary`) and holds the caller's role and state in it
// (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not
// list its organization, so an organization the caller cannot enter is never named, and one that the
// caller was removed from disappears from the list at once.
//
// The list is the directory of the active organization context. The context is not stored on the
// server: every organization-scoped operation names its organization in the path `org_id`, and the
// server checks that identifier against the caller's active membership on every request, so a switch
// between organizations is a different `org_id` in the client's routes and cannot outlive a revoked
// membership. A client picks the context from this list, may remember the last choice in the browser
// as a convenience, and must read the list again after any answer 404 `not_found` from an organization
// path. An account with several memberships sees all of them here and works in one at a time; the
// rights and the data of the organizations stay separate.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden. An employer account without an organization gets an empty page, which
// tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400
// validation_failed.
//
// GET /api/v1/me/organizations
func (UnimplementedHandler) ListMyOrganizations(ctx context.Context, params ListMyOrganizationsParams) (r ListMyOrganizationsRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListMySupportCases implements ListMySupportCases operation.
//
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
@@ -1199,6 +1291,45 @@ func (UnimplementedHandler) SubmitMyAssessmentAnswer(ctx context.Context, req *A
return r, ht.ErrNotImplemented
}
// UpdateOrganization implements UpdateOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
// token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the
// organization (the FR07 matrix gives this to no other role), so a member with another role answers
// 403 forbidden. The role comes from the server-side membership; the body has no organization,
// membership, role, owner, or verification field.
//
// Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch.
// Each field present replaces that field as a whole and an absent field stays unchanged; `contacts`
// and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as
// null become unset; `name`, `contacts`, and `representatives` cannot be null.
//
// The body can change the profile only. The verification level, its basis, the card, the members, and
// every role are not fields of it, and unknown fields fail validation, so the owner can neither raise
// the trust level of the organization nor the rights of anyone by editing the profile; a longer
// description, a verified-looking website, or a new representative leaves the level unchanged. The
// level and the roles change only through processes of the server.
//
// Versions: every committed change creates version `expected_version + 1` and answers 200 with the
// organization. `expected_version` is the `version` the client read; when it is not current, the
// server answers 412 version_conflict and changes nothing, and the client reads the organization again
// and reapplies its edits. The version travels in the body rather than in If-Match because the
// generated client cannot read the ETag response header yet, as for needs. A body that changes nothing
// when applied to the current profile keeps the version and answers 200 with the current organization
// even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a
// change that already succeeded is harmless.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403
// forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer
// such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can
// answer 429 with Retry-After before any check.
//
// PATCH /api/v1/organizations/{org_id}
func (UnimplementedHandler) UpdateOrganization(ctx context.Context, req *OrganizationUpdate, params UpdateOrganizationParams) (r UpdateOrganizationRes, _ error) {
return r, ht.ErrNotImplemented
}
// UpdateOrganizationInvitation implements UpdateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,576 @@
package httpadapter
import (
"context"
"log/slog"
"net/http"
"reflect"
"slices"
"strings"
"testing"
"github.com/ogen-go/ogen"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
)
// Organization request fixtures shared by the organization tests.
const (
myOrganizationsPath = "/api/v1/me/organizations"
organizationsPath = "/api/v1/organizations"
organizationPath = organizationsPath + "/01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01"
validOrganizationContacts = `{"website":"https://payments.example.com","email":"careers@payments.example.com","phone":"+74950000000","telegram":"@payments_careers"}`
emptyOrganizationContacts = `{"website":null,"email":null,"phone":null,"telegram":null}`
)
// organizationBody builds a JSON object from the given members.
func organizationBody(members ...string) string {
return "{" + strings.Join(members, ",") + "}"
}
// The schemas alone must accept the profile a company may send and reject
// what no request may carry: a role, an owner, a verification level or its
// basis, the members, the card, a version, or an identifier. Security accepts
// the session here, so the request reaches validation; a valid request then
// answers 501 until the operations are implemented. The rules that need
// storage, such as the website host or the version, pass the schema and are
// checked by the server.
func TestOrganizationSchemaValidationPrecedesImplementation(t *testing.T) {
session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}
command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey}
create := func(body string) identityRequest {
return identityRequest{method: http.MethodPost, path: organizationsPath, body: body, headers: command}
}
update := func(members ...string) identityRequest {
return identityRequest{method: http.MethodPatch, path: organizationPath, body: organizationBody(append([]string{`"expected_version":1`}, members...)...), headers: session}
}
forbiddenFields := []string{
`"role":"owner"`,
`"owner_id":"01928f7a-0000-7000-8000-00000000c0de"`,
`"verification_level":"e1"`,
`"verification":{"level":"e2","basis":"manual_review","changed_at":"2026-10-06T09:00:00Z"}`,
`"verification_basis":"corporate_domain"`,
`"members":[{"user_id":"01928f7a-0000-7000-8000-00000000c0de","role":"owner"}]`,
`"membership":{"organization_id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01","role":"owner","state":"active","joined_at":"2026-10-06T09:00:00Z"}`,
`"candidate_card":{}`,
`"id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01"`,
`"version":3`,
`"created_at":"2026-10-06T09:00:00Z"`,
}
type expectation struct {
name string
request identityRequest
location api.ProblemFieldLocation
pointer string
code string
}
tests := make([]expectation, 0, 36+2*len(forbiddenFields))
tests = append(tests, []expectation{
{
name: "list",
request: identityRequest{method: http.MethodGet, path: myOrganizationsPath + "?limit=20", headers: session},
},
{
name: "list with a limit above the maximum",
request: identityRequest{method: http.MethodGet, path: myOrganizationsPath + "?limit=101", headers: session},
location: api.ProblemFieldLocationQuery, pointer: "/limit", code: "invalid",
},
{
name: "list with a malformed cursor",
request: identityRequest{method: http.MethodGet, path: myOrganizationsPath + "?cursor=not%20a%20cursor", headers: session},
location: api.ProblemFieldLocationQuery, pointer: "/cursor", code: "invalid",
},
{
name: "create with a name only",
request: create(organizationBody(`"name":"ООО Пример Платежи"`)),
},
{
name: "create with a complete card",
request: create(organizationBody(
`"name":"ООО Пример Платежи"`,
`"description":"Платежный сервис.\nСобственное ядро."`,
`"sphere":"Платежи и финансовые сервисы"`,
`"contacts":`+validOrganizationContacts,
`"representatives":[{"name":"Анна Тестова","job_title":"Руководитель по подбору"}]`,
)),
},
{
name: "create with an explicit null description and sphere",
request: create(organizationBody(`"name":"ООО Пример"`, `"description":null`, `"sphere":null`, `"contacts":`+emptyOrganizationContacts, `"representatives":[]`)),
},
{
// A domain rule of the server: the schema accepts any https
// string without credentials, and the host rules come after it.
name: "create with a website that has a port",
request: create(organizationBody(`"name":"ООО Пример"`, `"contacts":{"website":"https://payments.example.com:8443","email":null,"phone":null,"telegram":null}`)),
},
{
name: "create without a name",
request: create(organizationBody(`"sphere":"Платежи"`)),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "required",
},
{
name: "create without an Idempotency-Key",
request: identityRequest{method: http.MethodPost, path: organizationsPath, body: organizationBody(`"name":"ООО Пример"`), headers: session},
location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required",
},
{
name: "create with an empty name",
request: create(organizationBody(`"name":""`)),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
},
{
name: "create with a name over 200 characters",
request: create(organizationBody(`"name":"` + strings.Repeat("я", 201) + `"`)),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
},
{
name: "create with a name that has a leading space",
request: create(organizationBody(`"name":" ООО"`)),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
},
{
name: "create with a name that has a line break",
request: create(organizationBody(`"name":"ООО\nПример"`)),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
},
{
name: "create with a sphere that has a trailing space",
request: create(organizationBody(`"name":"ООО"`, `"sphere":"Платежи "`)),
location: api.ProblemFieldLocationBody, pointer: "/sphere", code: "invalid",
},
{
name: "create with an empty description",
request: create(organizationBody(`"name":"ООО"`, `"description":""`)),
location: api.ProblemFieldLocationBody, pointer: "/description", code: "invalid",
},
{
name: "create with contacts that omit a field",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":null}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/telegram", code: "required",
},
{
name: "create with a personal contact kind",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":null,"telegram":null,"home_address":"ул. Тестовая"}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts", code: "invalid",
},
{
name: "create with an http website",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":"http://payments.example.com","email":null,"phone":null,"telegram":null}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/website", code: "invalid",
},
{
name: "create with a website that has credentials",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":"https://user:secret@payments.example.com","email":null,"phone":null,"telegram":null}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/website", code: "invalid",
},
{
name: "create with a phone that is not E.164",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":"8 495 000-00-00","telegram":null}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/phone", code: "invalid",
},
{
name: "create with a Telegram username without the at sign",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":null,"telegram":"payments_careers"}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/telegram", code: "invalid",
},
{
name: "create with an email that is not an address",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":"careers","phone":null,"telegram":null}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/email", code: "invalid",
},
{
name: "create with eleven representatives",
request: create(organizationBody(`"name":"ООО"`, `"representatives":[`+
strings.TrimSuffix(strings.Repeat(`{"name":"Имя","job_title":"Должность"},`, 11), ",")+`]`)),
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
},
{
// A failure inside an array element during decoding reports the
// pointer of the array, because jx reports no element index.
name: "create with a representative that has no job title",
request: create(organizationBody(`"name":"ООО"`, `"representatives":[{"name":"Анна Тестова"}]`)),
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
},
{
name: "create with a representative contact",
request: create(organizationBody(`"name":"ООО"`, `"representatives":[{"name":"Анна Тестова","job_title":"HR","email":"anna@example.com"}]`)),
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
},
{
name: "update with the version only",
request: update(),
},
{
name: "update of the profile with explicit nulls",
request: update(`"description":null`, `"sphere":null`),
},
{
name: "update of the contacts and representatives as a whole",
request: update(`"contacts":`+emptyOrganizationContacts, `"representatives":[]`),
},
{
name: "update without expected_version",
request: identityRequest{method: http.MethodPatch, path: organizationPath, body: organizationBody(`"name":"ООО Новое"`), headers: session},
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required",
},
{
name: "update with expected_version zero",
request: identityRequest{method: http.MethodPatch, path: organizationPath, body: organizationBody(`"expected_version":0`), headers: session},
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "invalid",
},
{
name: "update with a null name",
request: update(`"name":null`),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
},
{
name: "update with null representatives",
request: update(`"representatives":null`),
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
},
{
name: "update with null contacts",
request: update(`"contacts":null`),
location: api.ProblemFieldLocationBody, pointer: "/contacts", code: "invalid",
},
{
name: "read",
request: identityRequest{method: http.MethodGet, path: organizationPath, headers: session},
},
{
name: "read an organization identifier that is not a UUID",
request: identityRequest{method: http.MethodGet, path: organizationsPath + "/acme", headers: session},
location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid",
},
{
name: "update an organization identifier that is not a UUID",
request: identityRequest{method: http.MethodPatch, path: organizationsPath + "/acme", body: organizationBody(`"expected_version":1`), headers: session},
location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid",
},
}...)
// No request of either command may carry a right or a trust level, each
// one alone, as a whole-body rejection of an unknown field.
for _, field := range forbiddenFields {
tests = append(tests,
expectation{
name: "create with the forbidden field " + strings.SplitN(field, ":", 2)[0],
request: create(organizationBody(`"name":"ООО Пример"`, field)),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
expectation{
name: "update with the forbidden field " + strings.SplitN(field, ":", 2)[0],
request: update(field),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
)
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
response := serveIdentityRequest(t, router, test.request)
switch test.code {
case "":
requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented)
default:
body := requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed)
want := api.ProblemFieldError{In: test.location, Pointer: test.pointer, Code: test.code}
for _, field := range body.Errors {
if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code {
return
}
}
t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want)
}
})
}
}
// Every organization operation requires an employer session; DenyAllSecurity
// grants none, with or without a cookie and a CSRF token, and no request can
// name another account.
func TestOrganizationAccessBeforeImplementation(t *testing.T) {
session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}
command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey}
for _, test := range []identityRequest{
{method: http.MethodGet, path: myOrganizationsPath},
{method: http.MethodGet, path: myOrganizationsPath, headers: map[string]string{"Cookie": testSessionCookie}},
{method: http.MethodGet, path: myOrganizationsPath + "?user_id=01928f7a-0000-7000-8000-00000000c0de", headers: map[string]string{"Cookie": testSessionCookie}},
{method: http.MethodPost, path: organizationsPath, body: organizationBody(`"name":"ООО Пример"`), headers: command},
{method: http.MethodGet, path: organizationPath},
{method: http.MethodGet, path: organizationPath, headers: map[string]string{"Cookie": testSessionCookie}},
{method: http.MethodPatch, path: organizationPath, body: organizationBody(`"expected_version":1`, `"name":"ООО Новое"`), headers: session},
} {
t.Run(test.method+" "+test.path, func(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return nil })
requireProblem(t, serveIdentityRequest(t, router, test), http.StatusUnauthorized, api.ProblemCodeUnauthenticated)
})
}
}
// A role and a verification level never travel in the company DTOs: not in
// the response a member reads, not in the create or the update body. The
// role lives in OrganizationMembership, which a client cannot send, and the
// level in OrganizationVerification, which only the response carries.
func TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests(t *testing.T) {
raising := []string{
"role", "roles", "verification", "verification_level", "verification_basis", "level", "basis", "trust_level",
"owner", "owner_id", "members", "membership", "user_id", "account_id", "permissions", "e0", "e1", "e2", "e3",
}
for _, dto := range []any{api.Organization{}, api.OrganizationCreate{}, api.OrganizationUpdate{}, api.CandidateOrganizationCard{}, api.OrganizationContactChannels{}, api.OrganizationRepresentative{}} {
typ := reflect.TypeOf(dto)
for i := range typ.NumField() {
name, _, _ := strings.Cut(typ.Field(i).Tag.Get("json"), ",")
isVerificationReadModel := (typ == reflect.TypeFor[api.Organization]() && name == "verification") ||
(typ == reflect.TypeFor[api.CandidateOrganizationCard]() && name == "verification_level")
for _, field := range raising {
if name == field && !isVerificationReadModel {
t.Errorf("%s exposes the field %q", typ.Name(), name)
}
}
}
}
// The two request DTOs have no verification field at all, not even the
// read-only ones of the response.
for _, dto := range []any{api.OrganizationCreate{}, api.OrganizationUpdate{}} {
assertNoJSONFields(t, dto, []string{"verification", "verification_level", "candidate_card", "id", "version", "created_at", "updated_at"})
}
// The profile fields of a request are the whole editable surface.
for _, profile := range []struct {
dto any
want []string
}{
{api.OrganizationCreate{}, []string{"name", "description", "sphere", "contacts", "representatives"}},
{api.OrganizationUpdate{}, []string{"expected_version", "name", "description", "sphere", "contacts", "representatives"}},
} {
typ, want := reflect.TypeOf(profile.dto), profile.want
got := make([]string, 0, typ.NumField())
for i := range typ.NumField() {
name, _, _ := strings.Cut(typ.Field(i).Tag.Get("json"), ",")
got = append(got, name)
}
if strings.Join(got, ",") != strings.Join(want, ",") {
t.Errorf("%s fields = %v, want exactly %v", typ.Name(), got, want)
}
}
// The candidate's card holds neither a member, a role, nor the ground
// of the verification.
assertNoJSONFields(t, api.CandidateOrganizationCard{}, []string{"role", "membership", "members", "verification", "basis", "version", "created_at", "updated_at", "user_id"})
// The caller's own membership is the only place of a role, and it names
// no account.
assertNoJSONFields(t, api.OrganizationMembership{}, []string{"user_id", "account_id", "email"})
// The list takes only the page, so no parameter names another account.
params := reflect.TypeFor[api.ListMyOrganizationsParams]()
names := make([]string, 0, params.NumField())
for i := range params.NumField() {
names = append(names, params.Field(i).Name)
}
if got := strings.Join(names, ","); got != "Limit,Cursor" {
t.Fatalf("ListMyOrganizationsParams fields = %s, want only the page", got)
}
}
// An update separates an absent list (unchanged) from an empty one (replaced
// by an empty list) by nil, and null is not a list or an object.
func TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart(t *testing.T) {
var empty api.OrganizationUpdate
if err := empty.UnmarshalJSON([]byte(`{"expected_version":1,"representatives":[]}`)); err != nil {
t.Fatalf("decode an empty list: %v", err)
}
if empty.Representatives == nil || len(empty.Representatives) != 0 {
t.Fatalf("representatives = %#v, want a non-nil empty slice", empty.Representatives)
}
var absent api.OrganizationUpdate
if err := absent.UnmarshalJSON([]byte(`{"expected_version":1}`)); err != nil {
t.Fatalf("decode an absent list: %v", err)
}
if absent.Representatives != nil || absent.Name.IsSet() || absent.Contacts.IsSet() || absent.Description.IsSet() || absent.Sphere.IsSet() {
t.Fatal("absent fields are set, want unset")
}
var cleared api.OrganizationUpdate
if err := cleared.UnmarshalJSON([]byte(`{"expected_version":1,"description":null,"sphere":"Платежи"}`)); err != nil {
t.Fatalf("decode a null description: %v", err)
}
if !cleared.Description.IsSet() || !cleared.Description.IsNull() || !cleared.Sphere.IsSet() || cleared.Sphere.IsNull() {
t.Fatal("description sent as null is not a set null, or the sphere is not a value")
}
for _, body := range []string{
`{"expected_version":1,"representatives":null}`,
`{"expected_version":1,"name":null}`,
`{"expected_version":1,"contacts":null}`,
} {
var null api.OrganizationUpdate
if err := null.UnmarshalJSON([]byte(body)); err == nil {
t.Fatalf("decode %s succeeded, want an error", body)
}
}
}
// The representatives of the candidate card are optional and nullable: absent
// or null means that they are not published.
func TestCandidateOrganizationCardRepresentativesAreOptional(t *testing.T) {
const base = `"id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01","name":"ООО Пример","description":null,"sphere":null,"contacts":` + emptyOrganizationContacts + `,"verification_level":"e0"`
for name, body := range map[string]string{
"absent": "{" + base + "}",
"null": "{" + base + `,"representatives":null}`,
"empty": "{" + base + `,"representatives":[]}`,
} {
var card api.CandidateOrganizationCard
if err := card.UnmarshalJSON([]byte(body)); err != nil {
t.Fatalf("decode a card with %s representatives: %v", name, err)
}
if err := card.Validate(); err != nil {
t.Fatalf("validate a card with %s representatives: %v", name, err)
}
}
var withoutContacts api.CandidateOrganizationCard
if err := withoutContacts.UnmarshalJSON([]byte(`{"id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01","name":"ООО","description":null,"sphere":null,"verification_level":"e0"}`)); err == nil {
t.Fatal("decode a card without contacts succeeded, want an error")
}
}
// The documented examples are valid values of the generated types, and the
// organizations they show never claim a level above e0 on their own.
func TestOrganizationExamplesAreValidResponsesAndNeverRaiseTheLevel(t *testing.T) {
for _, name := range []string{"OrganizationNameOnly", "OrganizationCompleteCard"} {
var organization api.Organization
if err := organization.UnmarshalJSON(supportCaseExample(t, name)); err != nil {
t.Fatalf("decode the %s example: %v", name, err)
}
if err := organization.Validate(); err != nil {
t.Fatalf("validate the %s example: %v", name, err)
}
if organization.Verification.Level != api.OrganizationVerificationLevelE0 || organization.Verification.Basis != api.OrganizationVerificationBasisConfirmedEmail ||
organization.CandidateCard.VerificationLevel != api.OrganizationVerificationLevelE0 {
t.Fatalf("%s example verification = %+v, want e0 on the confirmed email", name, organization.Verification)
}
if organization.CandidateCard.ID != organization.ID || organization.CandidateCard.Name != organization.Name {
t.Fatalf("%s example card does not repeat the profile", name)
}
}
var page api.MyOrganizationList
if err := page.UnmarshalJSON(supportCaseExample(t, "MyOrganizationListPage")); err != nil {
t.Fatalf("decode the MyOrganizationListPage example: %v", err)
}
if err := page.Validate(); err != nil {
t.Fatalf("validate the MyOrganizationListPage example: %v", err)
}
for _, item := range page.Items {
if item.Membership.State != api.MembershipStateActive || item.Membership.OrganizationID != item.Organization.ID {
t.Fatalf("listed item %+v, want an active membership of the listed organization", item)
}
}
for _, name := range []string{"OrganizationCreateNameOnly", "OrganizationCreateCompleteCard"} {
var create api.OrganizationCreate
if err := create.UnmarshalJSON(supportCaseExample(t, name)); err != nil {
t.Fatalf("decode the %s example: %v", name, err)
}
if err := create.Validate(); err != nil {
t.Fatalf("validate the %s example: %v", name, err)
}
}
var update api.OrganizationUpdate
if err := update.UnmarshalJSON(supportCaseExample(t, "OrganizationUpdateCompleteCard")); err != nil {
t.Fatalf("decode the OrganizationUpdateCompleteCard example: %v", err)
}
if err := update.Validate(); err != nil {
t.Fatalf("validate the OrganizationUpdateCompleteCard example: %v", err)
}
}
// The contract enums list every level, basis, role, and state of the PRD now,
// so adding one later is not a contract change. At the contract level, the
// profile bodies are closed objects without a role or a level, and no
// operation sets the verification level or a role.
func TestOrganizationContractFollowsThePRD(t *testing.T) {
spec := parsePublicContract(t)
for name, want := range map[string][]string{
"OrganizationVerificationLevel": {"e0", "e1", "e2", "e3"},
"OrganizationVerificationBasis": {"confirmed_email", "corporate_domain", "requisites_and_authority", "manual_review", "partner_status"},
"OrganizationRole": {"owner", "recruiter", "hiring_manager", "technical_expert"},
"MembershipState": {"active", "suspended", "removed", "left"},
} {
if got := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/" + name})); !slices.Equal(got, want) {
t.Errorf("%s = %v, want %v", name, got, want)
}
}
// The requests are closed objects whose properties are the profile.
for name, want := range map[string][]string{
"OrganizationCreate": {"name", "description", "sphere", "contacts", "representatives"},
"OrganizationUpdate": {"expected_version", "name", "description", "sphere", "contacts", "representatives"},
} {
schema := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/" + name})
if schema.AdditionalProperties == nil || schema.AdditionalProperties.Bool == nil || *schema.AdditionalProperties.Bool {
t.Errorf("%s accepts unknown fields", name)
}
got := make([]string, 0, len(schema.Properties))
for _, property := range schema.Properties {
got = append(got, property.Name)
}
slices.Sort(got)
sorted := slices.Clone(want)
slices.Sort(sorted)
if !slices.Equal(got, sorted) {
t.Errorf("%s properties = %v, want %v", name, got, sorted)
}
}
update := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/OrganizationUpdate"})
if !slices.Contains(update.Required, "expected_version") {
t.Error("OrganizationUpdate does not require expected_version")
}
create := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/OrganizationCreate"})
if !slices.Equal(create.Required, []string{"name"}) {
t.Errorf("OrganizationCreate required = %v, want only the name", create.Required)
}
// Writing needs the CSRF token, and creating needs an Idempotency-Key.
for _, id := range []string{"CreateOrganization", "UpdateOrganization"} {
operation := operationByID(t, spec, id)
if len(operation.Security) != 1 {
t.Fatalf("%s security = %v, want one requirement", id, operation.Security)
}
if _, ok := operation.Security[0][sessionCSRFScheme]; !ok {
t.Errorf("%s does not require the CSRF token", id)
}
}
if !slices.ContainsFunc(operationByID(t, spec, "CreateOrganization").Parameters, func(parameter *ogen.Parameter) bool {
return parameter.Ref == "#/components/parameters/IdempotencyKey"
}) {
t.Error("CreateOrganization does not require an Idempotency-Key")
}
if _, ok := operationByID(t, spec, "UpdateOrganization").Responses["412"]; !ok {
t.Error("UpdateOrganization does not declare 412")
}
// Nothing in the organization paths sets a verification level or a role.
for path, item := range spec.Paths {
if !strings.HasPrefix(path, "/api/v1/organizations") && path != myOrganizationsPath {
continue
}
for _, operation := range []*ogen.Operation{item.Get, item.Post, item.Put, item.Patch, item.Delete} {
if operation == nil {
continue
}
id := strings.ToLower(operation.OperationID)
if strings.Contains(id, "verification") || strings.Contains(id, "verify") || strings.Contains(id, "role") || strings.Contains(id, "promote") {
t.Errorf("%s %s sets a level or a role", path, operation.OperationID)
}
}
}
}
@@ -0,0 +1,430 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// organizationConstraintErrors maps the organization constraints whose
// violation is a caller-visible outcome to port sentinels by SQLSTATE and
// constraint name, never by text.
var organizationConstraintErrors = map[constraintViolation]error{
{uniqueViolationCode, "memberships_user_id_organization_id_key"}: outbound.ErrMembershipExists,
{foreignKeyViolationCode, "memberships_organization_id_fkey"}: outbound.ErrOrganizationNotFound,
{foreignKeyViolationCode, "memberships_user_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "organization_representatives_organization_id_fkey"}: outbound.ErrOrganizationNotFound,
}
// mapOrganizationError turns a known organization constraint violation into
// its port sentinel and keeps the constraint name. Any other PostgreSQL error
// is replaced by its SQLSTATE and constraint name, because its detail quotes
// the failing row, which holds names of representatives. Deadlocks and
// serialization failures also match ErrTransactionConflict. A connection
// error loses the pgx prefix that names the database user and database.
func mapOrganizationError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
if sentinel, ok := organizationConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok {
return fmt.Errorf("postgres.mapOrganizationError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
var _ outbound.OrganizationRepositories = (*UnitOfWork)(nil)
func (unit *UnitOfWork) Organizations() outbound.OrganizationRepository {
return organizationRepository{queries: unit.queries}
}
func (unit *UnitOfWork) Memberships() outbound.MembershipRepository {
return membershipRepository{queries: unit.queries}
}
type organizationRepository struct {
queries *sqlc.Queries
}
var _ outbound.OrganizationRepository = organizationRepository{}
func (repository organizationRepository) CreateWithOwner(ctx context.Context, organization domain.Organization, owner domain.Membership) error {
const location = "organizationRepository.CreateWithOwner"
switch {
case organization.IsZero():
return fmt.Errorf("%s - organization was not built by domain.NewOrganization: %w", location, domain.ErrInvalidOrganization)
case owner.IsZero():
return fmt.Errorf("%s - owner was not built by domain.NewOwnerMembership: %w", location, domain.ErrInvalidMembership)
case owner.OrganizationID() != organization.ID() || owner.Role() != domain.OrganizationRoleOwner || !owner.GrantsAccess():
return fmt.Errorf("%s - owner must be the active owner membership of the organization: %w", location, domain.ErrInvalidMembership)
}
profile := organization.Profile()
contacts := profile.Contacts()
verification := organization.Verification()
err := repository.queries.InsertOrganization(ctx, sqlc.InsertOrganizationParams{
ID: pgUUID(organization.ID()),
Name: profile.Name(),
Description: pgOptionalText(profile.Description()),
Sphere: pgOptionalText(profile.Sphere()),
ContactWebsite: pgOptionalText(contacts.Website()),
ContactEmail: pgOptionalText(contacts.Email()),
ContactPhone: pgOptionalText(contacts.Phone()),
ContactTelegram: pgOptionalText(contacts.Telegram()),
VerificationLevel: string(verification.Level()),
VerificationBasis: string(verification.Basis()),
VerificationChangedAt: pgTime(verification.ChangedAt()),
Version: organization.Version(),
CreatedAt: pgTime(organization.CreatedAt()),
UpdatedAt: pgTime(organization.UpdatedAt()),
})
if err != nil {
return fmt.Errorf("%s - insert organization: %w", location, mapOrganizationError(err))
}
if err := repository.insertRepresentatives(ctx, organization.ID(), profile.Representatives()); err != nil {
return fmt.Errorf("%s - insert representatives: %w", location, err)
}
if err := insertMembership(ctx, repository.queries, owner); err != nil {
return fmt.Errorf("%s - insert owner membership: %w", location, err)
}
return nil
}
func (repository organizationRepository) insertRepresentatives(
ctx context.Context,
organizationID uuid.UUID,
representatives []domain.OrganizationRepresentative,
) error {
for index, representative := range representatives {
err := repository.queries.InsertOrganizationRepresentative(ctx, sqlc.InsertOrganizationRepresentativeParams{
OrganizationID: pgUUID(organizationID),
Ordinal: int16(index),
Name: representative.Name(),
JobTitle: representative.JobTitle(),
})
if err != nil {
return mapOrganizationError(err)
}
}
return nil
}
func (repository organizationRepository) GetForMember(
ctx context.Context,
organizationID, userID uuid.UUID,
) (domain.Organization, domain.Membership, error) {
const location = "organizationRepository.GetForMember"
row, err := repository.queries.GetOrganizationForMember(ctx, sqlc.GetOrganizationForMemberParams{
OrganizationID: pgUUID(organizationID),
UserID: pgUUID(userID),
})
if err != nil {
return domain.Organization{}, domain.Membership{}, fmt.Errorf("%s - select organization: %w", location, mapOrganizationNoRows(err, outbound.ErrOrganizationNotFound))
}
representatives, err := decodeRepresentatives(row.Representatives)
if err != nil {
return domain.Organization{}, domain.Membership{}, fmt.Errorf("%s - decode representatives: %w", location, err)
}
organization, err := organizationFromColumns(organizationColumns{
ID: row.ID, Name: row.Name, Description: row.Description, Sphere: row.Sphere,
ContactWebsite: row.ContactWebsite, ContactEmail: row.ContactEmail,
ContactPhone: row.ContactPhone, ContactTelegram: row.ContactTelegram,
VerificationLevel: row.VerificationLevel, VerificationBasis: row.VerificationBasis,
VerificationChangedAt: row.VerificationChangedAt, Version: row.Version,
CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt,
}, representatives)
if err != nil {
return domain.Organization{}, domain.Membership{}, err
}
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: optionalUUID(row.MembershipID),
OrganizationID: organizationID,
UserID: userID,
Role: row.MembershipRole,
State: row.MembershipState,
CreatedAt: row.MembershipCreatedAt.Time,
UpdatedAt: row.MembershipUpdatedAt.Time,
})
if err != nil {
return domain.Organization{}, domain.Membership{}, fmt.Errorf("%s - restore membership: %w", location, err)
}
return organization, membership, nil
}
// representativeJSON is one element of the representatives column that
// GetOrganizationForMember aggregates in the same statement as the
// organization, so the profile and the list come from one snapshot.
type representativeJSON struct {
Name string `json:"name"`
JobTitle string `json:"job_title"`
}
func decodeRepresentatives(column string) ([]domain.StoredRepresentative, error) {
var decoded []representativeJSON
if err := json.Unmarshal([]byte(column), &decoded); err != nil {
// The error of the decoder can quote the document, which holds names.
return nil, errors.New("postgres.decodeRepresentatives - the representatives column is not a list of name and job title")
}
representatives := make([]domain.StoredRepresentative, 0, len(decoded))
for _, representative := range decoded {
representatives = append(representatives, domain.StoredRepresentative(representative))
}
return representatives, nil
}
func (repository organizationRepository) ListForUser(ctx context.Context, query outbound.OrganizationListQuery) (outbound.OrganizationPage, error) {
const location = "organizationRepository.ListForUser"
if query.UserID == uuid.Nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - user ID must not be nil: %w", location, domain.ErrInvalidMembership)
}
if query.Limit < 1 || query.Limit > outbound.MaxOrganizationPageSize {
return outbound.OrganizationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxOrganizationPageSize, domain.ErrInvalidMembership)
}
params := sqlc.ListOrganizationsForUserParams{
UserID: pgUUID(query.UserID),
// One extra row tells whether another page follows.
RowLimit: query.Limit + 1,
}
if query.After != nil {
if err := requireTime(location, query.After.JoinedAt, domain.ErrInvalidMembership); err != nil {
return outbound.OrganizationPage{}, err
}
if query.After.OrganizationID == uuid.Nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - position organization ID must not be nil: %w", location, domain.ErrInvalidMembership)
}
params.AfterJoinedAt = pgTime(query.After.JoinedAt)
params.AfterOrganizationID = pgUUID(query.After.OrganizationID)
}
rows, err := repository.queries.ListOrganizationsForUser(ctx, params)
if err != nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - select organizations: %w", location, mapOrganizationError(err))
}
page := outbound.OrganizationPage{HasMore: len(rows) > int(query.Limit)}
if page.HasMore {
rows = rows[:query.Limit]
}
page.Items = make([]outbound.MemberOrganization, 0, len(rows))
for _, row := range rows {
summary, err := domain.RestoreOrganizationSummary(optionalUUID(row.ID), row.Name, row.VerificationLevel)
if err != nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - restore organization: %w", location, err)
}
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: optionalUUID(row.MembershipID),
OrganizationID: summary.ID(),
UserID: query.UserID,
Role: row.MembershipRole,
State: row.MembershipState,
CreatedAt: row.MembershipCreatedAt.Time,
UpdatedAt: row.MembershipUpdatedAt.Time,
})
if err != nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - restore membership: %w", location, err)
}
page.Items = append(page.Items, outbound.MemberOrganization{Organization: summary, Membership: membership})
}
return page, nil
}
func (repository organizationRepository) UpdateProfile(
ctx context.Context,
actorID uuid.UUID,
organization domain.Organization,
) (domain.Organization, error) {
const location = "organizationRepository.UpdateProfile"
if organization.IsZero() || actorID == uuid.Nil {
return domain.Organization{}, fmt.Errorf("%s - organization and actor must be set: %w", location, domain.ErrInvalidOrganization)
}
// The generated parameter structs of this repository hold representative
// names and contacts: never log them.
profile := organization.Profile()
contacts := profile.Contacts()
row, err := repository.queries.UpdateOrganizationProfile(ctx, sqlc.UpdateOrganizationProfileParams{
Name: profile.Name(),
Description: pgOptionalText(profile.Description()),
Sphere: pgOptionalText(profile.Sphere()),
ContactWebsite: pgOptionalText(contacts.Website()),
ContactEmail: pgOptionalText(contacts.Email()),
ContactPhone: pgOptionalText(contacts.Phone()),
ContactTelegram: pgOptionalText(contacts.Telegram()),
UpdatedAt: pgTime(organization.UpdatedAt()),
ID: pgUUID(organization.ID()),
ExpectedVersion: organization.Version(),
ActorID: pgUUID(actorID),
ManagerRoles: managerRoleNames(),
})
if errors.Is(err, pgx.ErrNoRows) {
return domain.Organization{}, fmt.Errorf("%s - update organization: %w", location, repository.explainRejectedUpdate(ctx, actorID, organization))
}
if err != nil {
return domain.Organization{}, fmt.Errorf("%s - update organization: %w", location, mapOrganizationError(err))
}
// The row lock of the update holds until the transaction ends, so no
// other writer replaces the list between these statements.
if err := repository.queries.DeleteOrganizationRepresentatives(ctx, row.ID); err != nil {
return domain.Organization{}, fmt.Errorf("%s - delete representatives: %w", location, mapOrganizationError(err))
}
if err := repository.insertRepresentatives(ctx, organization.ID(), profile.Representatives()); err != nil {
return domain.Organization{}, fmt.Errorf("%s - insert representatives: %w", location, err)
}
stored := make([]domain.StoredRepresentative, 0, len(profile.Representatives()))
for _, representative := range profile.Representatives() {
stored = append(stored, domain.StoredRepresentative{Name: representative.Name(), JobTitle: representative.JobTitle()})
}
return organizationFromColumns(organizationColumns(row), stored)
}
// explainRejectedUpdate tells why the update matched no row: an unknown
// organization or an actor without an active membership, a membership whose
// role cannot manage, or a stale version, in that order.
func (repository organizationRepository) explainRejectedUpdate(
ctx context.Context,
actorID uuid.UUID,
organization domain.Organization,
) error {
row, err := repository.queries.GetOrganizationForMember(ctx, sqlc.GetOrganizationForMemberParams{
OrganizationID: pgUUID(organization.ID()),
UserID: pgUUID(actorID),
})
switch {
case errors.Is(err, pgx.ErrNoRows):
return outbound.ErrOrganizationNotFound
case err != nil:
return mapOrganizationError(err)
}
role, err := domain.ParseOrganizationRole(row.MembershipRole)
switch {
case err != nil:
return fmt.Errorf("postgres.explainRejectedUpdate - validate role: %w", err)
case !role.CanManageOrganization():
return outbound.ErrOrganizationManagerRequired
default:
return outbound.ErrOrganizationVersionConflict
}
}
func managerRoleNames() []string {
roles := domain.ManagerRoles()
names := make([]string, 0, len(roles))
for _, role := range roles {
names = append(names, string(role))
}
return names
}
// organizationColumns has the columns of an organization row that every
// organization query returns. The generated row of UpdateOrganizationProfile
// converts to it.
type organizationColumns struct {
ID pgtype.UUID
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
func organizationFromColumns(columns organizationColumns, representatives []domain.StoredRepresentative) (domain.Organization, error) {
organization, err := domain.RestoreOrganization(domain.StoredOrganization{
ID: optionalUUID(columns.ID),
Name: columns.Name,
Description: columns.Description.String,
Sphere: columns.Sphere.String,
Website: columns.ContactWebsite.String,
Email: columns.ContactEmail.String,
Phone: columns.ContactPhone.String,
Telegram: columns.ContactTelegram.String,
Representatives: representatives,
VerificationLevel: columns.VerificationLevel,
VerificationBasis: columns.VerificationBasis,
VerificationChangedAt: columns.VerificationChangedAt.Time,
Version: columns.Version,
CreatedAt: columns.CreatedAt.Time,
UpdatedAt: columns.UpdatedAt.Time,
})
if err != nil {
return domain.Organization{}, fmt.Errorf("postgres.organizationFromColumns - restore organization: %w", err)
}
return organization, nil
}
type membershipRepository struct {
queries *sqlc.Queries
}
var _ outbound.MembershipRepository = membershipRepository{}
func (repository membershipRepository) Insert(ctx context.Context, membership domain.Membership) error {
if membership.IsZero() {
return fmt.Errorf("membershipRepository.Insert - membership was not built by domain.NewMembership: %w", domain.ErrInvalidMembership)
}
if err := insertMembership(ctx, repository.queries, membership); err != nil {
return fmt.Errorf("membershipRepository.Insert - insert membership: %w", err)
}
return nil
}
func insertMembership(ctx context.Context, queries *sqlc.Queries, membership domain.Membership) error {
err := queries.InsertMembership(ctx, sqlc.InsertMembershipParams{
ID: pgUUID(membership.ID()),
OrganizationID: pgUUID(membership.OrganizationID()),
UserID: pgUUID(membership.UserID()),
Role: string(membership.Role()),
State: string(membership.State()),
CreatedAt: pgTime(membership.CreatedAt()),
UpdatedAt: pgTime(membership.UpdatedAt()),
})
if err != nil {
return mapOrganizationError(err)
}
return nil
}
func (repository membershipRepository) Get(ctx context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) {
const location = "membershipRepository.Get"
row, err := repository.queries.GetMembership(ctx, sqlc.GetMembershipParams{
OrganizationID: pgUUID(organizationID),
UserID: pgUUID(userID),
})
if err != nil {
return domain.Membership{}, fmt.Errorf("%s - select membership: %w", location, mapOrganizationNoRows(err, outbound.ErrMembershipNotFound))
}
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: optionalUUID(row.ID),
OrganizationID: optionalUUID(row.OrganizationID),
UserID: optionalUUID(row.UserID),
Role: row.Role,
State: row.State,
CreatedAt: row.CreatedAt.Time,
UpdatedAt: row.UpdatedAt.Time,
})
if err != nil {
return domain.Membership{}, fmt.Errorf("%s - restore membership: %w", location, err)
}
return membership, nil
}
func mapOrganizationNoRows(err, sentinel error) error {
if errors.Is(err, pgx.ErrNoRows) {
return sentinel
}
return mapOrganizationError(err)
}
@@ -0,0 +1,83 @@
package postgres
import (
"context"
"errors"
"strings"
"testing"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// organizationDetailMarker stands for a row value that a PostgreSQL detail
// can quote, such as the name of a representative.
const organizationDetailMarker = "Failing row contains (Анна Тестова, Руководитель)"
func TestMapOrganizationErrorRecognizesOrganizationConstraints(t *testing.T) {
for _, test := range []struct {
code string
constraint string
want error
}{
{code: uniqueViolationCode, constraint: "memberships_user_id_organization_id_key", want: outbound.ErrMembershipExists},
{code: foreignKeyViolationCode, constraint: "memberships_organization_id_fkey", want: outbound.ErrOrganizationNotFound},
{code: foreignKeyViolationCode, constraint: "memberships_user_id_fkey", want: outbound.ErrUserNotFound},
{code: foreignKeyViolationCode, constraint: "organization_representatives_organization_id_fkey", want: outbound.ErrOrganizationNotFound},
} {
err := mapOrganizationError(&pgconn.PgError{Code: test.code, ConstraintName: test.constraint, Detail: organizationDetailMarker})
if !errors.Is(err, test.want) {
t.Fatalf("mapOrganizationError(%s %s) = %v, want %v", test.code, test.constraint, err, test.want)
}
if !strings.Contains(err.Error(), test.constraint) || strings.Contains(err.Error(), "Failing row") {
t.Fatalf("mapOrganizationError(%s) = %v, want the constraint name and no detail", test.constraint, err)
}
}
}
func TestMapOrganizationErrorDropsDetailOfOtherErrors(t *testing.T) {
// A CHECK violation that the domain should have prevented keeps only the
// SQLSTATE and the constraint, never the failing row with its names.
err := mapOrganizationError(&pgconn.PgError{Code: checkViolationCode, ConstraintName: "organization_representatives_name_format", Detail: organizationDetailMarker})
var stateError sqlStateError
if !errors.As(err, &stateError) || stateError.SQLState() != checkViolationCode {
t.Fatalf("mapOrganizationError() = %v, want SQLSTATE %s", err, checkViolationCode)
}
if strings.Contains(err.Error(), "Анна") || strings.Contains(err.Error(), "Failing row") {
t.Fatalf("mapOrganizationError() = %v, want no row values", err)
}
if err := mapOrganizationError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(err, outbound.ErrTransactionConflict) {
t.Fatalf("mapOrganizationError(deadlock) = %v, want ErrTransactionConflict", err)
}
if err := mapOrganizationError(context.Canceled); !errors.Is(err, context.Canceled) {
t.Fatalf("mapOrganizationError(context.Canceled) = %v, want the original error", err)
}
}
func TestOrganizationRepositoriesRejectInvalidInputBeforeQuerying(t *testing.T) {
// A repository without queries proves that no statement runs.
organizations := organizationRepository{}
memberships := membershipRepository{}
ctx := t.Context()
if err := organizations.CreateWithOwner(ctx, domain.Organization{}, domain.Membership{}); !errors.Is(err, domain.ErrInvalidOrganization) {
t.Fatalf("CreateWithOwner(zero organization) error = %v, want ErrInvalidOrganization", err)
}
if err := memberships.Insert(ctx, domain.Membership{}); !errors.Is(err, domain.ErrInvalidMembership) {
t.Fatalf("Insert(zero membership) error = %v, want ErrInvalidMembership", err)
}
if _, err := organizations.UpdateProfile(ctx, uuid.New(), domain.Organization{}); !errors.Is(err, domain.ErrInvalidOrganization) {
t.Fatalf("UpdateProfile(zero organization) error = %v, want ErrInvalidOrganization", err)
}
if _, err := organizations.ListForUser(ctx, outbound.OrganizationListQuery{}); !errors.Is(err, domain.ErrInvalidMembership) {
t.Fatalf("ListForUser(zero query) error = %v, want ErrInvalidMembership", err)
}
}
func TestManagerRoleNamesFollowTheDomainRule(t *testing.T) {
if got := managerRoleNames(); len(got) != 1 || got[0] != string(domain.OrganizationRoleOwner) {
t.Fatalf("managerRoleNames() = %v, want only the owner", got)
}
}
@@ -140,6 +140,40 @@ type MailRequest struct {
CreatedAt pgtype.Timestamptz
}
type Membership struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
UserID pgtype.UUID
Role string
State string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type Organization struct {
ID pgtype.UUID
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type OrganizationRepresentative struct {
OrganizationID pgtype.UUID
Ordinal int16
Name string
JobTitle string
}
type OutboxEvent struct {
Position pgtype.Int8
EventID pgtype.UUID
@@ -0,0 +1,505 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: organizations.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const deleteOrganizationRepresentatives = `-- name: DeleteOrganizationRepresentatives :exec
DELETE FROM organization_representatives
WHERE organization_id = $1
`
func (q *Queries) DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteOrganizationRepresentatives, organizationID)
return err
}
const getMembership = `-- name: GetMembership :one
SELECT
id,
organization_id,
user_id,
role,
state,
created_at,
updated_at
FROM memberships
WHERE
organization_id = $1
AND user_id = $2
`
type GetMembershipParams struct {
OrganizationID pgtype.UUID
UserID pgtype.UUID
}
// Reads the membership of one account in one organization, in any state.
func (q *Queries) GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error) {
row := q.db.QueryRow(ctx, getMembership, arg.OrganizationID, arg.UserID)
var i Membership
err := row.Scan(
&i.ID,
&i.OrganizationID,
&i.UserID,
&i.Role,
&i.State,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getOrganizationForMember = `-- name: GetOrganizationForMember :one
SELECT
organization.id,
organization.name,
organization.description,
organization.sphere,
organization.contact_website,
organization.contact_email,
organization.contact_phone,
organization.contact_telegram,
organization.verification_level,
organization.verification_basis,
organization.verification_changed_at,
organization.version,
organization.created_at,
organization.updated_at,
coalesce((
SELECT
jsonb_agg(
jsonb_build_object('name', representative.name, 'job_title', representative.job_title)
ORDER BY representative.ordinal
)
FROM organization_representatives AS representative
WHERE representative.organization_id = organization.id
), '[]'::jsonb)::text AS representatives,
membership.id AS membership_id,
membership.role AS membership_role,
membership.state AS membership_state,
membership.created_at AS membership_created_at,
membership.updated_at AS membership_updated_at
FROM organizations AS organization
INNER JOIN memberships AS membership ON organization.id = membership.organization_id
WHERE
organization.id = $1
AND membership.user_id = $2
AND membership.state = 'active'
`
type GetOrganizationForMemberParams struct {
OrganizationID pgtype.UUID
UserID pgtype.UUID
}
type GetOrganizationForMemberRow struct {
ID pgtype.UUID
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Representatives string
MembershipID pgtype.UUID
MembershipRole string
MembershipState string
MembershipCreatedAt pgtype.Timestamptz
MembershipUpdatedAt pgtype.Timestamptz
}
// Reads an organization together with the membership of one account in it
// and its representatives in list order, as one statement, so the profile and
// the list come from one snapshot. Only an active membership matches, so an
// unknown organization, an account that is no member, and a suspended,
// removed, or left member all return no row and cannot be told apart.
func (q *Queries) GetOrganizationForMember(ctx context.Context, arg GetOrganizationForMemberParams) (GetOrganizationForMemberRow, error) {
row := q.db.QueryRow(ctx, getOrganizationForMember, arg.OrganizationID, arg.UserID)
var i GetOrganizationForMemberRow
err := row.Scan(
&i.ID,
&i.Name,
&i.Description,
&i.Sphere,
&i.ContactWebsite,
&i.ContactEmail,
&i.ContactPhone,
&i.ContactTelegram,
&i.VerificationLevel,
&i.VerificationBasis,
&i.VerificationChangedAt,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
&i.Representatives,
&i.MembershipID,
&i.MembershipRole,
&i.MembershipState,
&i.MembershipCreatedAt,
&i.MembershipUpdatedAt,
)
return i, err
}
const insertMembership = `-- name: InsertMembership :exec
INSERT INTO memberships (
id,
organization_id,
user_id,
role,
state,
created_at,
updated_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7
)
`
type InsertMembershipParams struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
UserID pgtype.UUID
Role string
State string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
func (q *Queries) InsertMembership(ctx context.Context, arg InsertMembershipParams) error {
_, err := q.db.Exec(ctx, insertMembership,
arg.ID,
arg.OrganizationID,
arg.UserID,
arg.Role,
arg.State,
arg.CreatedAt,
arg.UpdatedAt,
)
return err
}
const insertOrganization = `-- name: InsertOrganization :exec
INSERT INTO organizations (
id,
name,
description,
sphere,
contact_website,
contact_email,
contact_phone,
contact_telegram,
verification_level,
verification_basis,
verification_changed_at,
version,
created_at,
updated_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12,
$13,
$14
)
`
type InsertOrganizationParams struct {
ID pgtype.UUID
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Stores a new organization with the verification level that the domain
// gave it. The deferred constraint organizations_owner_required fails the
// transaction at commit unless an active owner membership was inserted in
// it too.
func (q *Queries) InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error {
_, err := q.db.Exec(ctx, insertOrganization,
arg.ID,
arg.Name,
arg.Description,
arg.Sphere,
arg.ContactWebsite,
arg.ContactEmail,
arg.ContactPhone,
arg.ContactTelegram,
arg.VerificationLevel,
arg.VerificationBasis,
arg.VerificationChangedAt,
arg.Version,
arg.CreatedAt,
arg.UpdatedAt,
)
return err
}
const insertOrganizationRepresentative = `-- name: InsertOrganizationRepresentative :exec
INSERT INTO organization_representatives (
organization_id,
ordinal,
name,
job_title
) VALUES (
$1,
$2,
$3,
$4
)
`
type InsertOrganizationRepresentativeParams struct {
OrganizationID pgtype.UUID
Ordinal int16
Name string
JobTitle string
}
// Stores one representative at its position in the list. The adapter calls it
// once per representative after it deleted the previous list, in the same
// transaction.
func (q *Queries) InsertOrganizationRepresentative(ctx context.Context, arg InsertOrganizationRepresentativeParams) error {
_, err := q.db.Exec(ctx, insertOrganizationRepresentative,
arg.OrganizationID,
arg.Ordinal,
arg.Name,
arg.JobTitle,
)
return err
}
const listOrganizationsForUser = `-- name: ListOrganizationsForUser :many
SELECT
organization.id,
organization.name,
organization.verification_level,
membership.id AS membership_id,
membership.role AS membership_role,
membership.state AS membership_state,
membership.created_at AS membership_created_at,
membership.updated_at AS membership_updated_at
FROM memberships AS membership
INNER JOIN organizations AS organization ON membership.organization_id = organization.id
WHERE
membership.user_id = $1
AND membership.state = 'active'
AND (
$2::timestamptz IS NULL
OR (membership.created_at, membership.organization_id) < (
$2::timestamptz,
$3::uuid
)
)
ORDER BY membership.created_at DESC, membership.organization_id DESC
LIMIT $4
`
type ListOrganizationsForUserParams struct {
UserID pgtype.UUID
AfterJoinedAt pgtype.Timestamptz
AfterOrganizationID pgtype.UUID
RowLimit int32
}
type ListOrganizationsForUserRow struct {
ID pgtype.UUID
Name string
VerificationLevel string
MembershipID pgtype.UUID
MembershipRole string
MembershipState string
MembershipCreatedAt pgtype.Timestamptz
MembershipUpdatedAt pgtype.Timestamptz
}
// Lists the organizations where an account has an active membership,
// newest membership first. The page continues after the (membership
// creation time, organization ID) position of the last item of the
// previous page. Only the active memberships of the given account match.
func (q *Queries) ListOrganizationsForUser(ctx context.Context, arg ListOrganizationsForUserParams) ([]ListOrganizationsForUserRow, error) {
rows, err := q.db.Query(ctx, listOrganizationsForUser,
arg.UserID,
arg.AfterJoinedAt,
arg.AfterOrganizationID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListOrganizationsForUserRow
for rows.Next() {
var i ListOrganizationsForUserRow
if err := rows.Scan(
&i.ID,
&i.Name,
&i.VerificationLevel,
&i.MembershipID,
&i.MembershipRole,
&i.MembershipState,
&i.MembershipCreatedAt,
&i.MembershipUpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const updateOrganizationProfile = `-- name: UpdateOrganizationProfile :one
WITH target AS (
SELECT id FROM organizations
WHERE
id = $9
AND version = $10
FOR UPDATE
),
actor AS (
SELECT memberships.id FROM memberships
INNER JOIN target ON memberships.organization_id = target.id
WHERE
memberships.user_id = $11
AND memberships.state = 'active'
AND memberships.role = any($12::text [])
FOR SHARE OF memberships
)
UPDATE organizations
SET
name = $1,
description = $2,
sphere = $3,
contact_website = $4,
contact_email = $5,
contact_phone = $6,
contact_telegram = $7,
updated_at = $8,
version = organizations.version + 1
FROM actor
WHERE
organizations.id = $9
AND organizations.version = $10
RETURNING
organizations.id,
organizations.name,
organizations.description,
organizations.sphere,
organizations.contact_website,
organizations.contact_email,
organizations.contact_phone,
organizations.contact_telegram,
organizations.verification_level,
organizations.verification_basis,
organizations.verification_changed_at,
organizations.version,
organizations.created_at,
organizations.updated_at
`
type UpdateOrganizationProfileParams struct {
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
UpdatedAt pgtype.Timestamptz
ID pgtype.UUID
ExpectedVersion int64
ActorID pgtype.UUID
ManagerRoles []string
}
// Changes the profile of an organization over the version the caller read
// and advances the version in the same statement. It names no verification
// column, so a profile update cannot move the trust level. The change
// applies only for an account whose active membership has one of the
// manager roles, checked in the statement itself so that a membership that
// ended after the caller's read still stops the write. The statement locks
// the organization row first and then the actor's membership row FOR SHARE,
// so a revocation that commits while the statement waits is seen again
// (EvalPlanQual) and stops the write; the order organizations, then
// memberships, is the lock order of every writer (member management must
// follow it). No row returns for a stale version, an account that is no
// active manager, or an unknown organization; the adapter reads the
// membership to tell them apart.
func (q *Queries) UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (Organization, error) {
row := q.db.QueryRow(ctx, updateOrganizationProfile,
arg.Name,
arg.Description,
arg.Sphere,
arg.ContactWebsite,
arg.ContactEmail,
arg.ContactPhone,
arg.ContactTelegram,
arg.UpdatedAt,
arg.ID,
arg.ExpectedVersion,
arg.ActorID,
arg.ManagerRoles,
)
var i Organization
err := row.Scan(
&i.ID,
&i.Name,
&i.Description,
&i.Sphere,
&i.ContactWebsite,
&i.ContactEmail,
&i.ContactPhone,
&i.ContactTelegram,
&i.VerificationLevel,
&i.VerificationBasis,
&i.VerificationChangedAt,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
@@ -49,6 +49,7 @@ type Querier interface {
// matches no row.
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error)
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error
// Deletes one batch of accounts that stayed unverified since before cutoff,
// oldest first, with their tokens, sessions, mail requests, mail deliveries
// (and through the deliveries their attempts), and consent records. The
@@ -112,6 +113,14 @@ type Querier interface {
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
// Reads the usage of the day and the month window without locking.
GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error)
// Reads the membership of one account in one organization, in any state.
GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error)
// Reads an organization together with the membership of one account in it
// and its representatives in list order, as one statement, so the profile and
// the list come from one snapshot. Only an active membership matches, so an
// unknown organization, an account that is no member, and a suspended,
// removed, or left member all return no row and cannot be told apart.
GetOrganizationForMember(ctx context.Context, arg GetOrganizationForMemberParams) (GetOrganizationForMemberRow, error)
// Reads the relay backlog for metrics without locking. Both subqueries use
// the partial index on unpublished positions, so the cost follows the backlog
// size, not the table size. The age comes from the database clock, the same
@@ -153,6 +162,16 @@ type Querier interface {
InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error
InsertMailQuotaReservation(ctx context.Context, arg InsertMailQuotaReservationParams) error
InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error
InsertMembership(ctx context.Context, arg InsertMembershipParams) error
// Stores a new organization with the verification level that the domain
// gave it. The deferred constraint organizations_owner_required fails the
// transaction at commit unless an active owner membership was inserted in
// it too.
InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error
// Stores one representative at its position in the list. The adapter calls it
// once per representative after it deleted the previous list, in the same
// transaction.
InsertOrganizationRepresentative(ctx context.Context, arg InsertOrganizationRepresentativeParams) error
InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error
// Stores a version and returns the stored row with the publication time and
// effective time set by the stamp trigger. A taken ID or version number
@@ -189,6 +208,11 @@ type Querier interface {
ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, error)
ListCurrentContactConsentRecords(ctx context.Context, arg ListCurrentContactConsentRecordsParams) ([]ListCurrentContactConsentRecordsRow, error)
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
// Lists the organizations where an account has an active membership,
// newest membership first. The page continues after the (membership
// creation time, organization ID) position of the last item of the
// previous page. Only the active memberships of the given account match.
ListOrganizationsForUser(ctx context.Context, arg ListOrganizationsForUserParams) ([]ListOrganizationsForUserRow, error)
// Lists the other accounts of a provider that have usage in a month, so
// startup can warn about a renamed EMAIL_ACCOUNT.
ListOtherMailQuotaAccounts(ctx context.Context, arg ListOtherMailQuotaAccountsParams) ([]string, error)
@@ -304,6 +328,20 @@ type Querier interface {
// the stored version still equals expected_version and returns 0 rows
// otherwise. The trigger refuses a provider change after an attempt.
UpdateDeliveryState(ctx context.Context, arg UpdateDeliveryStateParams) (int64, error)
// Changes the profile of an organization over the version the caller read
// and advances the version in the same statement. It names no verification
// column, so a profile update cannot move the trust level. The change
// applies only for an account whose active membership has one of the
// manager roles, checked in the statement itself so that a membership that
// ended after the caller's read still stops the write. The statement locks
// the organization row first and then the actor's membership row FOR SHARE,
// so a revocation that commits while the statement waits is seen again
// (EvalPlanQual) and stops the write; the order organizations, then
// memberships, is the lock order of every writer (member management must
// follow it). No row returns for a stale version, an account that is no
// active manager, or an unknown organization; the adapter reads the
// membership to tell them apart.
UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (Organization, error)
// Replaces the registration of an unverified account and advances the
// registration version in the same statement, so no caller can choose it.
// The version check rejects a writer that read an older row; a verified
+229
View File
@@ -0,0 +1,229 @@
package domain
import (
"errors"
"fmt"
"slices"
"time"
"github.com/google/uuid"
)
// ErrInvalidMembership reports a membership, role, or state that breaks a
// rule, including a stored membership that does not match one.
var ErrInvalidMembership = errors.New("invalid membership")
// OrganizationRole is the role of a member in one organization (PRD 2.2 and
// the FR07 matrix). The role belongs to the membership, never to the
// organization profile. Values match the OrganizationRole schema of the
// public contract.
type OrganizationRole string
const (
// OrganizationRoleOwner manages the organization and its members.
OrganizationRoleOwner OrganizationRole = "owner"
// OrganizationRoleRecruiter leads the selection of candidates.
OrganizationRoleRecruiter OrganizationRole = "recruiter"
// OrganizationRoleHiringManager acts on the assigned needs.
OrganizationRoleHiringManager OrganizationRole = "hiring_manager"
// OrganizationRoleTechnicalExpert refines the requirements of the
// assigned needs.
OrganizationRoleTechnicalExpert OrganizationRole = "technical_expert"
)
// OrganizationRoles lists every role, the owner first.
func OrganizationRoles() []OrganizationRole {
return []OrganizationRole{
OrganizationRoleOwner,
OrganizationRoleRecruiter,
OrganizationRoleHiringManager,
OrganizationRoleTechnicalExpert,
}
}
// ParseOrganizationRole accepts a value of the OrganizationRole contract
// enum.
func ParseOrganizationRole(value string) (OrganizationRole, error) {
role := OrganizationRole(value)
if !slices.Contains(OrganizationRoles(), role) {
return "", fmt.Errorf("domain.ParseOrganizationRole - unknown role: %w", ErrInvalidMembership)
}
return role, nil
}
// CanManageOrganization reports whether the role changes the organization
// profile and manages its members. The FR07 matrix gives this to the owner
// only. It is the single rule of managing; the rest of the matrix (needs,
// invitations, contacts, bids) is applied by the operations it governs, and
// no role grants anything through this method alone.
func (role OrganizationRole) CanManageOrganization() bool {
return role == OrganizationRoleOwner
}
// ManagerRoles lists the roles for which CanManageOrganization is true.
func ManagerRoles() []OrganizationRole {
managers := make([]OrganizationRole, 0, 1)
for _, role := range OrganizationRoles() {
if role.CanManageOrganization() {
managers = append(managers, role)
}
}
return managers
}
// MembershipState is the state of a membership. Only an active membership
// gives access. Values match the MembershipState schema of the public
// contract.
type MembershipState string
const (
// MembershipStateActive is a member who works in the organization.
MembershipStateActive MembershipState = "active"
// MembershipStateSuspended is a member whose access is stopped and may be
// restored.
MembershipStateSuspended MembershipState = "suspended"
// MembershipStateRemoved is a membership that the owner or the platform
// ended.
MembershipStateRemoved MembershipState = "removed"
// MembershipStateLeft is a membership that the member ended.
MembershipStateLeft MembershipState = "left"
)
// ParseMembershipState accepts a value of the MembershipState contract enum.
func ParseMembershipState(value string) (MembershipState, error) {
state := MembershipState(value)
switch state {
case MembershipStateActive, MembershipStateSuspended, MembershipStateRemoved, MembershipStateLeft:
return state, nil
default:
return "", fmt.Errorf("domain.ParseMembershipState - unknown state: %w", ErrInvalidMembership)
}
}
// GrantsAccess reports whether a membership in the state gives access to its
// organization. Every state but active answers as if the account were no
// member.
func (state MembershipState) GrantsAccess() bool { return state == MembershipStateActive }
// MembershipInput describes a new membership.
type MembershipInput struct {
OrganizationID uuid.UUID
UserID uuid.UUID
Role OrganizationRole
// At is the application clock at creation.
At time.Time
}
// Membership is the role of one account in one organization. An account has
// at most one membership per organization, so storage keeps the pair unique.
// Storage reconstructs it from trusted rows with RestoreMembership; new ones
// come from NewMembership.
type Membership struct {
id uuid.UUID
organizationID uuid.UUID
userID uuid.UUID
role OrganizationRole
state MembershipState
createdAt time.Time
updatedAt time.Time
}
// NewMembership creates an active membership with a time-ordered UUIDv7
// identifier. It checks the shape only: whether the account may hold the
// role, for example whether it is an employer account, is a rule of the
// operation that adds the member.
func NewMembership(input MembershipInput) (Membership, error) {
const location = "domain.NewMembership"
if _, err := ParseOrganizationRole(string(input.Role)); err != nil {
return Membership{}, fmt.Errorf("%s - validate role: %w", location, err)
}
switch {
case input.OrganizationID == uuid.Nil:
return Membership{}, fmt.Errorf("%s - organization ID must not be nil: %w", location, ErrInvalidMembership)
case input.UserID == uuid.Nil:
return Membership{}, fmt.Errorf("%s - user ID must not be nil: %w", location, ErrInvalidMembership)
case input.At.IsZero():
return Membership{}, fmt.Errorf("%s - creation time must be set: %w", location, ErrInvalidMembership)
}
id, err := uuid.NewV7()
if err != nil {
return Membership{}, fmt.Errorf("%s - generate membership ID: %w", location, err)
}
return Membership{
id: id,
organizationID: input.OrganizationID,
userID: input.UserID,
role: input.Role,
state: MembershipStateActive,
createdAt: input.At,
updatedAt: input.At,
}, nil
}
// NewOwnerMembership creates the active owner membership of the account that
// creates an organization.
func NewOwnerMembership(organizationID, userID uuid.UUID, at time.Time) (Membership, error) {
return NewMembership(MembershipInput{OrganizationID: organizationID, UserID: userID, Role: OrganizationRoleOwner, At: at})
}
// StoredMembership carries the columns of a stored membership.
type StoredMembership struct {
ID uuid.UUID
OrganizationID uuid.UUID
UserID uuid.UUID
Role string
State string
CreatedAt time.Time
UpdatedAt time.Time
}
// RestoreMembership validates a stored membership, so a row changed outside
// the application fails with ErrInvalidMembership.
func RestoreMembership(stored StoredMembership) (Membership, error) {
const location = "domain.RestoreMembership"
role, err := ParseOrganizationRole(stored.Role)
if err != nil {
return Membership{}, fmt.Errorf("%s - validate role: %w", location, err)
}
state, err := ParseMembershipState(stored.State)
if err != nil {
return Membership{}, fmt.Errorf("%s - validate state: %w", location, err)
}
switch {
case stored.ID == uuid.Nil || stored.OrganizationID == uuid.Nil || stored.UserID == uuid.Nil:
return Membership{}, fmt.Errorf("%s - identifiers must not be nil: %w", location, ErrInvalidMembership)
case stored.CreatedAt.IsZero() || stored.UpdatedAt.Before(stored.CreatedAt):
return Membership{}, fmt.Errorf("%s - times must be set and ordered: %w", location, ErrInvalidMembership)
}
return Membership{
id: stored.ID,
organizationID: stored.OrganizationID,
userID: stored.UserID,
role: role,
state: state,
createdAt: stored.CreatedAt,
updatedAt: stored.UpdatedAt,
}, nil
}
func (membership Membership) ID() uuid.UUID { return membership.id }
func (membership Membership) OrganizationID() uuid.UUID { return membership.organizationID }
func (membership Membership) UserID() uuid.UUID { return membership.userID }
func (membership Membership) Role() OrganizationRole { return membership.role }
func (membership Membership) State() MembershipState { return membership.state }
func (membership Membership) CreatedAt() time.Time { return membership.createdAt }
func (membership Membership) UpdatedAt() time.Time { return membership.updatedAt }
// GrantsAccess reports whether the membership gives access to its
// organization: it is active. It says nothing about what the role may do.
func (membership Membership) GrantsAccess() bool { return membership.state.GrantsAccess() }
// CanManageOrganization reports whether the membership is active and its
// role manages the organization.
func (membership Membership) CanManageOrganization() bool {
return membership.GrantsAccess() && membership.role.CanManageOrganization()
}
// IsZero reports a Membership not built by NewMembership or
// RestoreMembership.
func (membership Membership) IsZero() bool { return membership.id == uuid.Nil }
+116
View File
@@ -0,0 +1,116 @@
package domain
import (
"errors"
"testing"
"time"
"github.com/google/uuid"
)
var membershipTestTime = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
func TestParseOrganizationRoleAcceptsTheFourRolesOfTheContract(t *testing.T) {
for _, value := range []string{"owner", "recruiter", "hiring_manager", "technical_expert"} {
role, err := ParseOrganizationRole(value)
if err != nil || string(role) != value {
t.Fatalf("ParseOrganizationRole(%q) = %q, %v", value, role, err)
}
}
for _, value := range []string{"", "Owner", "admin", "manager", "tech_expert", "owner "} {
if _, err := ParseOrganizationRole(value); !errors.Is(err, ErrInvalidMembership) {
t.Fatalf("ParseOrganizationRole(%q) error = %v, want ErrInvalidMembership", value, err)
}
}
if got := len(OrganizationRoles()); got != 4 {
t.Fatalf("len(OrganizationRoles()) = %d, want 4", got)
}
}
func TestOnlyTheOwnerManagesTheOrganization(t *testing.T) {
for _, role := range OrganizationRoles() {
if got, want := role.CanManageOrganization(), role == OrganizationRoleOwner; got != want {
t.Fatalf("%s.CanManageOrganization() = %v, want %v", role, got, want)
}
}
if managers := ManagerRoles(); len(managers) != 1 || managers[0] != OrganizationRoleOwner {
t.Fatalf("ManagerRoles() = %v, want only the owner", managers)
}
}
func TestOnlyAnActiveMembershipGrantsAccess(t *testing.T) {
for _, value := range []string{"active", "suspended", "removed", "left"} {
state, err := ParseMembershipState(value)
if err != nil {
t.Fatalf("ParseMembershipState(%q) error = %v", value, err)
}
if state.GrantsAccess() != (value == "active") {
t.Fatalf("%s.GrantsAccess() = %v, want true only for active", state, state.GrantsAccess())
}
}
for _, value := range []string{"", "invited", "Active", "revoked"} {
if _, err := ParseMembershipState(value); !errors.Is(err, ErrInvalidMembership) {
t.Fatalf("ParseMembershipState(%q) error = %v, want ErrInvalidMembership", value, err)
}
}
}
func TestNewMembershipIsActiveAndNewOwnerMembershipIsTheOwner(t *testing.T) {
organizationID, userID := uuid.New(), uuid.New()
membership, err := NewMembership(MembershipInput{OrganizationID: organizationID, UserID: userID, Role: OrganizationRoleRecruiter, At: membershipTestTime})
if err != nil {
t.Fatalf("NewMembership() error = %v", err)
}
if membership.Role() != OrganizationRoleRecruiter || membership.State() != MembershipStateActive || !membership.GrantsAccess() ||
membership.OrganizationID() != organizationID || membership.UserID() != userID || membership.ID().Version() != 7 ||
membership.CanManageOrganization() {
t.Fatalf("membership = %+v, want an active recruiter that cannot manage", membership)
}
owner, err := NewOwnerMembership(organizationID, userID, membershipTestTime)
if err != nil || owner.Role() != OrganizationRoleOwner || !owner.CanManageOrganization() {
t.Fatalf("NewOwnerMembership() = %+v, %v, want an active owner that manages", owner, err)
}
}
func TestNewMembershipRejectsIncompleteInput(t *testing.T) {
valid := MembershipInput{OrganizationID: uuid.New(), UserID: uuid.New(), Role: OrganizationRoleOwner, At: membershipTestTime}
for name, change := range map[string]func(*MembershipInput){
"nil organization": func(in *MembershipInput) { in.OrganizationID = uuid.Nil },
"nil user": func(in *MembershipInput) { in.UserID = uuid.Nil },
"unknown role": func(in *MembershipInput) { in.Role = "admin" },
"empty role": func(in *MembershipInput) { in.Role = "" },
"zero time": func(in *MembershipInput) { in.At = time.Time{} },
} {
input := valid
change(&input)
if _, err := NewMembership(input); !errors.Is(err, ErrInvalidMembership) {
t.Fatalf("NewMembership(%s) error = %v, want ErrInvalidMembership", name, err)
}
}
}
func TestRestoreMembershipKeepsTheStoredStateAndRejectsInvalidRows(t *testing.T) {
stored := StoredMembership{
ID: uuid.New(), OrganizationID: uuid.New(), UserID: uuid.New(), Role: "owner", State: "removed",
CreatedAt: membershipTestTime, UpdatedAt: membershipTestTime.Add(time.Hour),
}
membership, err := RestoreMembership(stored)
if err != nil || membership.State() != MembershipStateRemoved || membership.GrantsAccess() || membership.CanManageOrganization() {
t.Fatalf("RestoreMembership() = %+v, %v, want a removed owner without access", membership, err)
}
for name, change := range map[string]func(*StoredMembership){
"unknown role": func(s *StoredMembership) { s.Role = "admin" },
"unknown state": func(s *StoredMembership) { s.State = "invited" },
"nil ID": func(s *StoredMembership) { s.ID = uuid.Nil },
"nil organization": func(s *StoredMembership) { s.OrganizationID = uuid.Nil },
"nil user": func(s *StoredMembership) { s.UserID = uuid.Nil },
"update before create": func(s *StoredMembership) { s.UpdatedAt = membershipTestTime.Add(-time.Second) },
"zero creation time": func(s *StoredMembership) { s.CreatedAt = time.Time{} },
} {
row := stored
change(&row)
if _, err := RestoreMembership(row); !errors.Is(err, ErrInvalidMembership) {
t.Fatalf("RestoreMembership(%s) error = %v, want ErrInvalidMembership", name, err)
}
}
}
+701
View File
@@ -0,0 +1,701 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"net"
"net/url"
"regexp"
"slices"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
)
// ErrInvalidOrganization reports an organization profile, verification, or
// stored organization that breaks a rule.
var ErrInvalidOrganization = errors.New("invalid organization")
// OrganizationFieldError reports the request field of an organization
// profile that broke a rule. It matches ErrInvalidOrganization with
// errors.Is, and an HTTP adapter reads Pointer with errors.As to answer 400
// with the pointer of the field. Reason is fixed text; neither field quotes
// the submitted value, which can be personal data.
type OrganizationFieldError struct {
// Pointer is the JSON Pointer of the field in the request body, such as
// "/contacts/website" or "/representatives/2/name".
Pointer string
// Reason says which rule the field broke.
Reason string
}
func (err *OrganizationFieldError) Error() string {
return "organization field " + err.Pointer + " " + err.Reason
}
func (err *OrganizationFieldError) Unwrap() error { return ErrInvalidOrganization }
func invalidOrganizationField(location, pointer, reason string) error {
return fmt.Errorf("%s - %w", location, &OrganizationFieldError{Pointer: pointer, Reason: reason})
}
const (
// The bounds match the OrganizationDescription, OrganizationSphere,
// OrganizationWebsite, and OrganizationRepresentative contract schemas
// and the CHECK constraints of the organizations tables. The name bound,
// maxOrganizationNameRunes, is shared with the consent snapshot of it.
maxOrganizationDescriptionRunes = 2000
maxOrganizationSphereRunes = 100
maxOrganizationWebsiteRunes = 300
maxOrganizationRepresentatives = 10
maxRepresentativeNameRunes = 100
maxRepresentativeJobTitleRunes = 100
// maxHostnameBytes and maxHostnameLabelBytes follow RFC 1035.
maxHostnameBytes = 253
maxHostnameLabelBytes = 63
httpsPrefix = "https://"
)
var (
// organizationPhonePattern is the E.164 format of ContactPhoneNumber.
organizationPhonePattern = regexp.MustCompile(`^\+[1-9][0-9]{6,14}$`)
// organizationTelegramPattern is the format of ContactTelegramUsername.
organizationTelegramPattern = regexp.MustCompile(`^@[A-Za-z0-9_]{5,32}$`)
)
// OrganizationVerificationLevel is the trust level of an organization (PRD
// FR07). It starts at e0 and changes only through a verification process of
// the server, never through a profile edit. Values match the
// OrganizationVerificationLevel schema of the public contract.
type OrganizationVerificationLevel string
const (
// OrganizationVerificationE0 is the confirmed email of the creating
// account; every organization starts here.
OrganizationVerificationE0 OrganizationVerificationLevel = "e0"
// OrganizationVerificationE1 is a corporate email, a verified domain, and
// a link with the organization.
OrganizationVerificationE1 OrganizationVerificationLevel = "e1"
// OrganizationVerificationE2 is a check of the requisites and the
// authority.
OrganizationVerificationE2 OrganizationVerificationLevel = "e2"
// OrganizationVerificationE3 is a manual check or a partner status.
OrganizationVerificationE3 OrganizationVerificationLevel = "e3"
)
// QuotaTier returns the quota tier of the level, and false for a level that
// has no quota policy yet. The PRD gives E3 a separate policy, so it has no
// tier.
func (level OrganizationVerificationLevel) QuotaTier() (OrganizationTier, bool) {
switch level {
case OrganizationVerificationE0:
return OrganizationTierE0, true
case OrganizationVerificationE1:
return OrganizationTierE1, true
case OrganizationVerificationE2:
return OrganizationTierE2, true
case OrganizationVerificationE3:
// The PRD gives E3 a separate policy, not a quota tier. A caller that
// reads quotas (TASK-087) must fail closed on false: grant no quota
// and refuse the action, never fall back to a lower or a default tier.
return "", false
default:
return "", false
}
}
// OrganizationVerificationBasis is the ground of a verification level. Each
// level has its own bases. Values match the OrganizationVerificationBasis
// schema of the public contract.
type OrganizationVerificationBasis string
const (
OrganizationBasisConfirmedEmail OrganizationVerificationBasis = "confirmed_email"
OrganizationBasisCorporateDomain OrganizationVerificationBasis = "corporate_domain"
OrganizationBasisRequisitesAndAuthority OrganizationVerificationBasis = "requisites_and_authority"
OrganizationBasisManualReview OrganizationVerificationBasis = "manual_review"
OrganizationBasisPartnerStatus OrganizationVerificationBasis = "partner_status"
)
// OrganizationVerification is the verification level of an organization with
// its ground and the time it was set. It has no setter and no constructor
// but the initial one: a later verification process of the server will
// construct the higher levels.
type OrganizationVerification struct {
level OrganizationVerificationLevel
basis OrganizationVerificationBasis
changedAt time.Time
}
// InitialOrganizationVerification returns e0 on the ground of the confirmed
// email, the level every new organization starts at.
func InitialOrganizationVerification(at time.Time) (OrganizationVerification, error) {
return RestoreOrganizationVerification(
string(OrganizationVerificationE0), string(OrganizationBasisConfirmedEmail), at)
}
// RestoreOrganizationVerification validates a stored level, its basis, and
// the time, and that the basis belongs to the level.
func RestoreOrganizationVerification(level, basis string, changedAt time.Time) (OrganizationVerification, error) {
const location = "domain.RestoreOrganizationVerification"
var allowed []OrganizationVerificationBasis
switch OrganizationVerificationLevel(level) {
case OrganizationVerificationE0:
allowed = []OrganizationVerificationBasis{OrganizationBasisConfirmedEmail}
case OrganizationVerificationE1:
allowed = []OrganizationVerificationBasis{OrganizationBasisCorporateDomain}
case OrganizationVerificationE2:
allowed = []OrganizationVerificationBasis{OrganizationBasisRequisitesAndAuthority}
case OrganizationVerificationE3:
allowed = []OrganizationVerificationBasis{OrganizationBasisManualReview, OrganizationBasisPartnerStatus}
default:
return OrganizationVerification{}, fmt.Errorf("%s - unknown level: %w", location, ErrInvalidOrganization)
}
if !slices.Contains(allowed, OrganizationVerificationBasis(basis)) {
return OrganizationVerification{}, fmt.Errorf("%s - the basis does not belong to the level: %w", location, ErrInvalidOrganization)
}
if changedAt.IsZero() {
return OrganizationVerification{}, fmt.Errorf("%s - time must be set: %w", location, ErrInvalidOrganization)
}
return OrganizationVerification{
level: OrganizationVerificationLevel(level),
basis: OrganizationVerificationBasis(basis),
changedAt: changedAt,
}, nil
}
func (verification OrganizationVerification) Level() OrganizationVerificationLevel {
return verification.level
}
func (verification OrganizationVerification) Basis() OrganizationVerificationBasis {
return verification.basis
}
func (verification OrganizationVerification) ChangedAt() time.Time { return verification.changedAt }
// OrganizationContactsInput holds the public contacts of an organization as
// the request gave them; an empty string is a contact that is not set.
type OrganizationContactsInput struct {
Website string
Email string
Phone string
Telegram string
}
// OrganizationContacts are the public contacts of an organization: company
// channels, never the personal contacts of an employee. The zero value has
// no contact set.
type OrganizationContacts struct {
website string
email string
phone string
telegram string
}
// Website returns the https URL of the website, or "" when it is not set.
func (contacts OrganizationContacts) Website() string { return contacts.website }
// Email returns the public mailbox, or "" when it is not set.
func (contacts OrganizationContacts) Email() string { return contacts.email }
// Phone returns the E.164 phone number, or "" when it is not set.
func (contacts OrganizationContacts) Phone() string { return contacts.phone }
// Telegram returns the Telegram username with the leading @, or "" when it
// is not set.
func (contacts OrganizationContacts) Telegram() string { return contacts.telegram }
// OrganizationRepresentativeInput is a representative as the request gave
// it. The name is personal data of an employee: never log the value, and
// never log a struct that holds it.
type OrganizationRepresentativeInput struct {
Name string
JobTitle string
}
// OrganizationRepresentative is a person that speaks for the organization to
// candidates, as the owner presents them. It is presentation only: no
// account link and no right. The name is personal data of an employee, so
// String, GoString, Format, and LogValue redact the value; the fields sit
// behind a pointer so that printing an enclosing struct shows only an
// address.
type OrganizationRepresentative struct {
value *representativeValue
}
type representativeValue struct {
name string
jobTitle string
}
const redactedRepresentative = "[redacted representative]"
// Name returns the name as the card shows it.
func (representative OrganizationRepresentative) Name() string {
if representative.value == nil {
return ""
}
return representative.value.name
}
// JobTitle returns the position as the card shows it.
func (representative OrganizationRepresentative) JobTitle() string {
if representative.value == nil {
return ""
}
return representative.value.jobTitle
}
func (representative OrganizationRepresentative) String() string { return redactedRepresentative }
func (representative OrganizationRepresentative) GoString() string { return redactedRepresentative }
func (representative OrganizationRepresentative) LogValue() slog.Value {
return slog.StringValue(redactedRepresentative)
}
func (representative OrganizationRepresentative) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedRepresentative)
}
// OrganizationProfileInput is the editable profile of an organization as a
// request gave it. An empty Description or Sphere is a field that is not
// set. It holds the names of representatives, which are personal data of
// employees: never log it.
type OrganizationProfileInput struct {
Name string
Description string
Sphere string
Contacts OrganizationContactsInput
Representatives []OrganizationRepresentativeInput
}
// OrganizationProfile is the validated profile that the owner edits: the
// name, the description, the field of business, the public contacts, and the
// representatives. It holds no verification level, no role, and no member,
// so changing it can neither raise a right nor raise the trust level.
type OrganizationProfile struct {
name string
description string
sphere string
contacts OrganizationContacts
representatives []OrganizationRepresentative
}
// NewOrganizationProfile validates input and normalizes CRLF line breaks in
// the description to LF. The first rule that fails returns an error
// matching ErrInvalidOrganization with an *OrganizationFieldError that names
// the field.
func NewOrganizationProfile(input OrganizationProfileInput) (OrganizationProfile, error) {
const location = "domain.NewOrganizationProfile"
if reason := singleLineTextProblem(input.Name, maxOrganizationNameRunes); reason != "" {
return OrganizationProfile{}, invalidOrganizationField(location, "/name", reason)
}
description := strings.ReplaceAll(input.Description, "\r\n", "\n")
if description != "" {
if reason := multiLineTextProblem(description, maxOrganizationDescriptionRunes); reason != "" {
return OrganizationProfile{}, invalidOrganizationField(location, "/description", reason)
}
}
if input.Sphere != "" {
if reason := singleLineTextProblem(input.Sphere, maxOrganizationSphereRunes); reason != "" {
return OrganizationProfile{}, invalidOrganizationField(location, "/sphere", reason)
}
}
contacts, err := newOrganizationContacts(location, input.Contacts)
if err != nil {
return OrganizationProfile{}, err
}
if len(input.Representatives) > maxOrganizationRepresentatives {
return OrganizationProfile{}, invalidOrganizationField(location, "/representatives",
fmt.Sprintf("must have at most %d items", maxOrganizationRepresentatives))
}
representatives := make([]OrganizationRepresentative, 0, len(input.Representatives))
for index, representative := range input.Representatives {
pointer := fmt.Sprintf("/representatives/%d", index)
if reason := singleLineTextProblem(representative.Name, maxRepresentativeNameRunes); reason != "" {
return OrganizationProfile{}, invalidOrganizationField(location, pointer+"/name", reason)
}
if reason := singleLineTextProblem(representative.JobTitle, maxRepresentativeJobTitleRunes); reason != "" {
return OrganizationProfile{}, invalidOrganizationField(location, pointer+"/job_title", reason)
}
representatives = append(representatives, OrganizationRepresentative{
value: &representativeValue{name: representative.Name, jobTitle: representative.JobTitle},
})
}
return OrganizationProfile{
name: input.Name,
description: description,
sphere: input.Sphere,
contacts: contacts,
representatives: representatives,
}, nil
}
func newOrganizationContacts(location string, input OrganizationContactsInput) (OrganizationContacts, error) {
var contacts OrganizationContacts
if input.Website != "" {
if reason := websiteProblem(input.Website); reason != "" {
return OrganizationContacts{}, invalidOrganizationField(location, "/contacts/website", reason)
}
contacts.website = input.Website
}
if input.Email != "" {
email, err := NewEmailAddress(input.Email)
if err != nil {
return OrganizationContacts{}, invalidOrganizationField(location, "/contacts/email", "must be an email address")
}
contacts.email = email.Address()
}
if input.Phone != "" {
if !organizationPhonePattern.MatchString(input.Phone) {
return OrganizationContacts{}, invalidOrganizationField(location, "/contacts/phone", "must be an E.164 phone number")
}
contacts.phone = input.Phone
}
if input.Telegram != "" {
if !organizationTelegramPattern.MatchString(input.Telegram) {
return OrganizationContacts{}, invalidOrganizationField(location, "/contacts/telegram", "must be a Telegram username with the leading @")
}
contacts.telegram = input.Telegram
}
return contacts, nil
}
func (profile OrganizationProfile) Name() string { return profile.name }
// Description returns the description, or "" when it is not set.
func (profile OrganizationProfile) Description() string { return profile.description }
// Sphere returns the field of business, or "" when it is not set.
func (profile OrganizationProfile) Sphere() string { return profile.sphere }
func (profile OrganizationProfile) Contacts() OrganizationContacts { return profile.contacts }
// Representatives returns a copy of the list in the order the owner gave it.
func (profile OrganizationProfile) Representatives() []OrganizationRepresentative {
return slices.Clone(profile.representatives)
}
// Equal reports whether both profiles hold the same values, which tells a
// change from a body that changes nothing.
func (profile OrganizationProfile) Equal(other OrganizationProfile) bool {
return profile.name == other.name &&
profile.description == other.description &&
profile.sphere == other.sphere &&
profile.contacts == other.contacts &&
slices.EqualFunc(profile.representatives, other.representatives, func(left, right OrganizationRepresentative) bool {
return left.Name() == right.Name() && left.JobTitle() == right.JobTitle()
})
}
// singleLineTextProblem returns the rule that value breaks, or "" when it is
// a valid single-line text: not empty, valid UTF-8, within maxRunes, without
// surrounding whitespace, and without control characters.
func singleLineTextProblem(value string, maxRunes int) string {
switch {
case value == "":
return "must not be empty"
case !utf8.ValidString(value):
return "must be valid UTF-8"
case utf8.RuneCountInString(value) > maxRunes:
return fmt.Sprintf("must have at most %d characters", maxRunes)
case strings.TrimSpace(value) != value:
return "must not have leading or trailing whitespace"
case strings.ContainsFunc(value, isForbiddenTextRune):
return "must not contain control characters"
default:
return ""
}
}
// multiLineTextProblem is singleLineTextProblem for a text that may contain
// LF line breaks.
func multiLineTextProblem(value string, maxRunes int) string {
switch {
case !utf8.ValidString(value):
return "must be valid UTF-8"
case utf8.RuneCountInString(value) > maxRunes:
return fmt.Sprintf("must have at most %d characters", maxRunes)
case strings.TrimSpace(value) != value:
return "must not have leading or trailing whitespace"
case strings.ContainsFunc(value, func(character rune) bool { return character != '\n' && isForbiddenTextRune(character) }):
return "must not contain control characters"
default:
return ""
}
}
// isForbiddenTextRune reports a control character or a Unicode line or
// paragraph separator, which break one-line text and which the database
// refuses in its control character class.
func isForbiddenTextRune(character rune) bool {
return unicode.IsControl(character) || character == '\u2028' || character == '\u2029'
}
// websiteProblem returns the rule that value breaks, or "" when it is an
// https URL of a host name: no credentials, no port, no IP address, and a
// host with at least two labels whose last one starts with a letter. The
// server never fetches the address; a later feature that does must resolve
// it and refuse private ranges on its own.
func websiteProblem(value string) string {
switch {
case utf8.RuneCountInString(value) > maxOrganizationWebsiteRunes:
return fmt.Sprintf("must have at most %d characters", maxOrganizationWebsiteRunes)
case !strings.HasPrefix(value, httpsPrefix):
return "must be an https URL"
case strings.ContainsFunc(value, func(character rune) bool { return unicode.IsSpace(character) || isForbiddenTextRune(character) }):
return "must not contain whitespace or control characters"
}
parsed, err := url.Parse(value)
switch {
case err != nil || parsed.Opaque != "":
return "must be an https URL"
case parsed.User != nil:
return "must not contain credentials"
case parsed.Port() != "":
return "must not contain a port"
}
return hostnameProblem(parsed.Hostname())
}
func hostnameProblem(host string) string {
const notHostName = "must have a host name"
if host == "" || len(host) > maxHostnameBytes || net.ParseIP(host) != nil {
return notHostName
}
labels := strings.Split(host, ".")
if len(labels) < 2 {
return notHostName
}
for _, label := range labels {
if label == "" || len(label) > maxHostnameLabelBytes ||
strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") {
return notHostName
}
for _, character := range label {
if character != '-' && !unicode.IsLetter(character) && !unicode.IsDigit(character) {
return notHostName
}
}
}
// A top-level domain starts with a letter, which also refuses numeric
// spellings of an IP address such as 127.1 or 0x7f.1.
if first, _ := utf8.DecodeRuneInString(labels[len(labels)-1]); !unicode.IsLetter(first) {
return notHostName
}
return ""
}
// OrganizationCandidateCard is the card of an organization as a candidate sees
// it. It carries the profile and the verification level only: no version, no
// time, no ground of the verification, no member, no role, and no account.
type OrganizationCandidateCard struct {
id uuid.UUID
profile OrganizationProfile
level OrganizationVerificationLevel
}
func (card OrganizationCandidateCard) ID() uuid.UUID { return card.id }
func (card OrganizationCandidateCard) Profile() OrganizationProfile { return card.profile }
func (card OrganizationCandidateCard) VerificationLevel() OrganizationVerificationLevel {
return card.level
}
// Organization is a company that employer accounts work in: the profile its
// owner edits and the verification level that only the server sets. It holds
// no membership and no role; those belong to Membership. Storage
// reconstructs it from trusted rows with RestoreOrganization; new ones come
// from NewOrganization.
type Organization struct {
id uuid.UUID
profile OrganizationProfile
verification OrganizationVerification
// version is the optimistic concurrency version of the profile. Storage
// checks it as the expected version and advances it in the same
// statement, so a domain method never changes it.
version int64
createdAt time.Time
updatedAt time.Time
}
// NewOrganization creates an organization at version 1 with a time-ordered
// UUIDv7 identifier and the initial verification level e0. No input chooses
// the level: a company that looks verified still starts at e0.
func NewOrganization(profile OrganizationProfile, createdAt time.Time) (Organization, error) {
const location = "domain.NewOrganization"
if profile.name == "" {
return Organization{}, fmt.Errorf("%s - profile must be built by NewOrganizationProfile: %w", location, ErrInvalidOrganization)
}
verification, err := InitialOrganizationVerification(createdAt)
if err != nil {
return Organization{}, fmt.Errorf("%s - set the initial verification: %w", location, err)
}
id, err := uuid.NewV7()
if err != nil {
return Organization{}, fmt.Errorf("%s - generate organization ID: %w", location, err)
}
return Organization{
id: id,
profile: profile,
verification: verification,
version: 1,
createdAt: createdAt,
updatedAt: createdAt,
}, nil
}
// StoredRepresentative carries the columns of a stored representative. The
// name is personal data of an employee: never log the value, and never log a
// struct that holds it.
type StoredRepresentative struct {
Name string
JobTitle string
}
// StoredOrganization carries the columns of a stored organization with its
// representatives in list order. An empty Description, Sphere, or contact is
// a column that is NULL.
type StoredOrganization struct {
ID uuid.UUID
Name string
Description string
Sphere string
Website string
Email string
Phone string
Telegram string
Representatives []StoredRepresentative
VerificationLevel string
VerificationBasis string
VerificationChangedAt time.Time
Version int64
CreatedAt time.Time
UpdatedAt time.Time
}
// RestoreOrganization validates a stored organization with the rules of
// NewOrganizationProfile and the verification rules, so a row changed
// outside the application fails with ErrInvalidOrganization.
func RestoreOrganization(stored StoredOrganization) (Organization, error) {
const location = "domain.RestoreOrganization"
representatives := make([]OrganizationRepresentativeInput, 0, len(stored.Representatives))
for _, representative := range stored.Representatives {
representatives = append(representatives, OrganizationRepresentativeInput(representative))
}
profile, err := NewOrganizationProfile(OrganizationProfileInput{
Name: stored.Name,
Description: stored.Description,
Sphere: stored.Sphere,
Contacts: OrganizationContactsInput{
Website: stored.Website, Email: stored.Email, Phone: stored.Phone, Telegram: stored.Telegram,
},
Representatives: representatives,
})
if err != nil {
return Organization{}, fmt.Errorf("%s - validate profile: %w", location, err)
}
verification, err := RestoreOrganizationVerification(stored.VerificationLevel, stored.VerificationBasis, stored.VerificationChangedAt)
if err != nil {
return Organization{}, fmt.Errorf("%s - validate verification: %w", location, err)
}
switch {
case stored.ID == uuid.Nil:
return Organization{}, fmt.Errorf("%s - ID must not be nil: %w", location, ErrInvalidOrganization)
case stored.Version < 1:
return Organization{}, fmt.Errorf("%s - version must be positive: %w", location, ErrInvalidOrganization)
case stored.CreatedAt.IsZero() || stored.UpdatedAt.Before(stored.CreatedAt):
return Organization{}, fmt.Errorf("%s - times must be set and ordered: %w", location, ErrInvalidOrganization)
}
return Organization{
id: stored.ID,
profile: profile,
verification: verification,
version: stored.Version,
createdAt: stored.CreatedAt,
updatedAt: stored.UpdatedAt,
}, nil
}
func (organization Organization) ID() uuid.UUID { return organization.id }
func (organization Organization) Profile() OrganizationProfile { return organization.profile }
func (organization Organization) Verification() OrganizationVerification {
return organization.verification
}
func (organization Organization) Version() int64 { return organization.version }
func (organization Organization) CreatedAt() time.Time { return organization.createdAt }
func (organization Organization) UpdatedAt() time.Time { return organization.updatedAt }
// ApplyProfile returns the organization with profile as its profile. The
// identifier, the version, and the verification stay as they are: storage
// checks Version as the expected version and advances it, and only a
// verification process changes the level. A time before the last update,
// from clock skew between instances, is stored as the last update.
func (organization Organization) ApplyProfile(profile OrganizationProfile, at time.Time) (Organization, error) {
const location = "Organization.ApplyProfile"
switch {
case organization.id == uuid.Nil:
return Organization{}, fmt.Errorf("%s - organization must be built by NewOrganization: %w", location, ErrInvalidOrganization)
case profile.name == "":
return Organization{}, fmt.Errorf("%s - profile must be built by NewOrganizationProfile: %w", location, ErrInvalidOrganization)
case at.IsZero():
return Organization{}, fmt.Errorf("%s - time must be set: %w", location, ErrInvalidOrganization)
}
updated := organization
updated.profile = profile
updated.updatedAt = at
if at.Before(organization.updatedAt) {
updated.updatedAt = organization.updatedAt
}
return updated, nil
}
// CandidateCard returns the card of the organization as a candidate sees it.
func (organization Organization) CandidateCard() OrganizationCandidateCard {
return OrganizationCandidateCard{id: organization.id, profile: organization.profile, level: organization.verification.level}
}
// IsZero reports an Organization not built by NewOrganization or
// RestoreOrganization.
func (organization Organization) IsZero() bool { return organization.id == uuid.Nil }
// LogValue logs the identifier, the version, and the level only: the
// profile holds representatives' names, which are personal data.
func (organization Organization) LogValue() slog.Value {
return slog.GroupValue(
slog.String("id", organization.id.String()),
slog.Int64("version", organization.version),
slog.String("verification_level", string(organization.verification.level)),
)
}
// OrganizationSummary is an organization as the list of an account's
// organizations names it.
type OrganizationSummary struct {
id uuid.UUID
name string
level OrganizationVerificationLevel
}
// RestoreOrganizationSummary validates a stored name and level.
func RestoreOrganizationSummary(id uuid.UUID, name, level string) (OrganizationSummary, error) {
const location = "domain.RestoreOrganizationSummary"
if singleLineTextProblem(name, maxOrganizationNameRunes) != "" || id == uuid.Nil {
return OrganizationSummary{}, fmt.Errorf("%s - ID and name must be valid: %w", location, ErrInvalidOrganization)
}
switch OrganizationVerificationLevel(level) {
case OrganizationVerificationE0, OrganizationVerificationE1, OrganizationVerificationE2, OrganizationVerificationE3:
return OrganizationSummary{id: id, name: name, level: OrganizationVerificationLevel(level)}, nil
default:
return OrganizationSummary{}, fmt.Errorf("%s - unknown level: %w", location, ErrInvalidOrganization)
}
}
func (summary OrganizationSummary) ID() uuid.UUID { return summary.id }
func (summary OrganizationSummary) Name() string { return summary.name }
func (summary OrganizationSummary) VerificationLevel() OrganizationVerificationLevel {
return summary.level
}
@@ -0,0 +1,389 @@
package domain
import (
"bytes"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
var organizationTestTime = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
func completeOrganizationProfileInput() OrganizationProfileInput {
return OrganizationProfileInput{
Name: "ООО Пример Платежи",
Description: "Платежный сервис для малого бизнеса.\nСобственное ядро платежей.",
Sphere: "Платежи и финансовые сервисы",
Contacts: OrganizationContactsInput{
Website: "https://payments.example.com/careers?team=core",
Email: "careers@payments.example.com",
Phone: "+74950000000",
Telegram: "@payments_careers",
},
Representatives: []OrganizationRepresentativeInput{{Name: "Анна Тестова", JobTitle: "Руководитель по подбору"}},
}
}
func mustOrganizationProfile(t *testing.T, input OrganizationProfileInput) OrganizationProfile {
t.Helper()
profile, err := NewOrganizationProfile(input)
if err != nil {
t.Fatalf("NewOrganizationProfile() error = %v", err)
}
return profile
}
func TestNewOrganizationProfileAcceptsACompleteAndAMinimalProfile(t *testing.T) {
profile := mustOrganizationProfile(t, completeOrganizationProfileInput())
if profile.Name() != "ООО Пример Платежи" || profile.Sphere() != "Платежи и финансовые сервисы" ||
profile.Contacts().Website() != "https://payments.example.com/careers?team=core" ||
profile.Contacts().Phone() != "+74950000000" || profile.Contacts().Telegram() != "@payments_careers" ||
profile.Contacts().Email() != "careers@payments.example.com" {
t.Fatalf("profile = %+v, want the given values", profile)
}
if representatives := profile.Representatives(); len(representatives) != 1 || representatives[0].Name() != "Анна Тестова" ||
representatives[0].JobTitle() != "Руководитель по подбору" {
t.Fatalf("representatives = %v, want the given one", representatives)
}
minimal := mustOrganizationProfile(t, OrganizationProfileInput{Name: "A"})
if minimal.Description() != "" || minimal.Sphere() != "" || minimal.Contacts() != (OrganizationContacts{}) || len(minimal.Representatives()) != 0 {
t.Fatalf("minimal profile = %+v, want every optional field unset", minimal)
}
}
func TestNewOrganizationProfileNormalizesDescriptionLineBreaks(t *testing.T) {
input := completeOrganizationProfileInput()
input.Description = "first\r\nsecond"
if got := mustOrganizationProfile(t, input).Description(); got != "first\nsecond" {
t.Fatalf("Description() = %q, want CRLF stored as LF", got)
}
input.Description = "first\rsecond"
if _, err := NewOrganizationProfile(input); !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("NewOrganizationProfile(lone CR) error = %v, want ErrInvalidOrganization", err)
}
}
func TestNewOrganizationProfileNamesTheFieldThatBreaksARule(t *testing.T) {
longName := strings.Repeat("я", maxOrganizationNameRunes+1)
for _, test := range []struct {
name string
change func(*OrganizationProfileInput)
pointer string
}{
{"empty name", func(in *OrganizationProfileInput) { in.Name = "" }, "/name"},
{"name with a leading space", func(in *OrganizationProfileInput) { in.Name = " ООО" }, "/name"},
{"name with a trailing tab", func(in *OrganizationProfileInput) { in.Name = "ООО\t" }, "/name"},
{"name with a line break", func(in *OrganizationProfileInput) { in.Name = "ООО\nПример" }, "/name"},
{"name with a line separator", func(in *OrganizationProfileInput) { in.Name = "ООО\u2028Пример" }, "/name"},
{"name over 200 characters", func(in *OrganizationProfileInput) { in.Name = longName }, "/name"},
{"name that is not UTF-8", func(in *OrganizationProfileInput) { in.Name = "ООО\xff" }, "/name"},
{"description with a leading line break", func(in *OrganizationProfileInput) { in.Description = "\nтекст" }, "/description"},
{"description with a control character", func(in *OrganizationProfileInput) { in.Description = "текст\x07" }, "/description"},
{"description over 2000 characters", func(in *OrganizationProfileInput) {
in.Description = strings.Repeat("я", maxOrganizationDescriptionRunes+1)
}, "/description"},
{"sphere with a line break", func(in *OrganizationProfileInput) { in.Sphere = "Платежи\nи сервисы" }, "/sphere"},
{"website over http", func(in *OrganizationProfileInput) { in.Contacts.Website = "http://payments.example.com" }, "/contacts/website"},
{"website in capitals scheme", func(in *OrganizationProfileInput) { in.Contacts.Website = "HTTPS://payments.example.com" }, "/contacts/website"},
{"website with credentials", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://user:secret@payments.example.com" }, "/contacts/website"},
{"website with a port", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://payments.example.com:8443" }, "/contacts/website"},
{"website with an IPv4 address", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://10.0.0.5/admin" }, "/contacts/website"},
{"website with an IPv6 address", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://[::1]/" }, "/contacts/website"},
{"website with a short numeric host", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://127.1" }, "/contacts/website"},
{"website with a hexadecimal host", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://0x7f.0x1" }, "/contacts/website"},
{"website without a dot", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://localhost/" }, "/contacts/website"},
{"website with a space", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://payments.example.com/a b" }, "/contacts/website"},
{"website with an empty label", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://payments..example.com" }, "/contacts/website"},
{"website with a hyphen-led label", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://-payments.example.com" }, "/contacts/website"},
{"website with an underscore", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://pay_ments.example.com" }, "/contacts/website"},
{"website over 300 characters", func(in *OrganizationProfileInput) {
in.Contacts.Website = "https://payments.example.com/" + strings.Repeat("a", 300)
}, "/contacts/website"},
{"email without a domain dot", func(in *OrganizationProfileInput) { in.Contacts.Email = "careers@payments" }, "/contacts/email"},
{"email with a display name", func(in *OrganizationProfileInput) { in.Contacts.Email = "HR <careers@payments.example.com>" }, "/contacts/email"},
{"phone without a plus", func(in *OrganizationProfileInput) { in.Contacts.Phone = "74950000000" }, "/contacts/phone"},
{"phone with spaces", func(in *OrganizationProfileInput) { in.Contacts.Phone = "+7 495 000 00 00" }, "/contacts/phone"},
{"phone with a leading zero country code", func(in *OrganizationProfileInput) { in.Contacts.Phone = "+04950000000" }, "/contacts/phone"},
{"telegram without an at sign", func(in *OrganizationProfileInput) { in.Contacts.Telegram = "payments_careers" }, "/contacts/telegram"},
{"telegram that is too short", func(in *OrganizationProfileInput) { in.Contacts.Telegram = "@abc" }, "/contacts/telegram"},
{"eleven representatives", func(in *OrganizationProfileInput) {
in.Representatives = make([]OrganizationRepresentativeInput, maxOrganizationRepresentatives+1)
for index := range in.Representatives {
in.Representatives[index] = OrganizationRepresentativeInput{Name: "Имя", JobTitle: "Должность"}
}
}, "/representatives"},
{"representative with an empty name", func(in *OrganizationProfileInput) {
in.Representatives = []OrganizationRepresentativeInput{{Name: "Анна", JobTitle: "HR"}, {Name: "", JobTitle: "HR"}}
}, "/representatives/1/name"},
{"representative with a padded job title", func(in *OrganizationProfileInput) {
in.Representatives = []OrganizationRepresentativeInput{{Name: "Анна", JobTitle: " HR"}}
}, "/representatives/0/job_title"},
} {
t.Run(test.name, func(t *testing.T) {
input := completeOrganizationProfileInput()
test.change(&input)
_, err := NewOrganizationProfile(input)
if !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("NewOrganizationProfile() error = %v, want ErrInvalidOrganization", err)
}
var fieldError *OrganizationFieldError
if !errors.As(err, &fieldError) || fieldError.Pointer != test.pointer {
t.Fatalf("NewOrganizationProfile() error = %v, want the pointer %s", err, test.pointer)
}
})
}
}
func TestOrganizationFieldErrorDoesNotQuoteTheSubmittedValue(t *testing.T) {
const secret = "Конфиденциальная Фамилия"
input := completeOrganizationProfileInput()
input.Representatives = []OrganizationRepresentativeInput{{Name: secret, JobTitle: " " + secret}}
_, err := NewOrganizationProfile(input)
if err == nil || strings.Contains(err.Error(), secret) {
t.Fatalf("NewOrganizationProfile() error = %v, want an error without the submitted value", err)
}
}
func TestNewOrganizationProfileAcceptsInternationalizedAndPathWebsites(t *testing.T) {
for _, website := range []string{
"https://example.com",
"https://пример.рф/vacancies",
"https://xn--e1afmkfd.xn--p1ai",
"https://careers.example.co.uk/a/b?c=d#e",
} {
input := OrganizationProfileInput{Name: "A", Contacts: OrganizationContactsInput{Website: website}}
if _, err := NewOrganizationProfile(input); err != nil {
t.Fatalf("NewOrganizationProfile(%q) error = %v, want it accepted", website, err)
}
}
}
func TestOrganizationProfileCopiesItsRepresentatives(t *testing.T) {
profile := mustOrganizationProfile(t, completeOrganizationProfileInput())
representatives := profile.Representatives()
representatives[0] = OrganizationRepresentative{}
if profile.Representatives()[0].Name() != "Анна Тестова" {
t.Fatal("changing the returned slice changed the profile")
}
}
func TestOrganizationProfileEqualTellsAChangeFromNoChange(t *testing.T) {
base := completeOrganizationProfileInput()
profile := mustOrganizationProfile(t, base)
if !profile.Equal(mustOrganizationProfile(t, base)) {
t.Fatal("equal inputs give unequal profiles")
}
for name, change := range map[string]func(*OrganizationProfileInput){
"name": func(in *OrganizationProfileInput) { in.Name = "Другое имя" },
"description": func(in *OrganizationProfileInput) { in.Description = "" },
"contact": func(in *OrganizationProfileInput) { in.Contacts.Phone = "" },
"representative": func(in *OrganizationProfileInput) { in.Representatives[0].JobTitle = "Директор" },
"list length": func(in *OrganizationProfileInput) { in.Representatives = nil },
} {
input := base
input.Representatives = append([]OrganizationRepresentativeInput(nil), base.Representatives...)
change(&input)
if profile.Equal(mustOrganizationProfile(t, input)) {
t.Fatalf("a changed %s still compares equal", name)
}
}
}
func TestNewOrganizationStartsAtE0WhateverTheProfileLooksLike(t *testing.T) {
profile := mustOrganizationProfile(t, completeOrganizationProfileInput())
organization, err := NewOrganization(profile, organizationTestTime)
if err != nil {
t.Fatalf("NewOrganization() error = %v", err)
}
verification := organization.Verification()
if verification.Level() != OrganizationVerificationE0 || verification.Basis() != OrganizationBasisConfirmedEmail ||
!verification.ChangedAt().Equal(organizationTestTime) {
t.Fatalf("verification = %s %s %s, want e0 on the confirmed email at the creation time",
verification.Level(), verification.Basis(), verification.ChangedAt())
}
if organization.Version() != 1 || organization.ID().Version() != 7 || !organization.CreatedAt().Equal(organizationTestTime) ||
!organization.UpdatedAt().Equal(organizationTestTime) {
t.Fatalf("organization = %v, want version 1, a UUIDv7, and the creation time", organization)
}
if _, err := NewOrganization(OrganizationProfile{}, organizationTestTime); !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("NewOrganization(zero profile) error = %v, want ErrInvalidOrganization", err)
}
if _, err := NewOrganization(profile, time.Time{}); !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("NewOrganization(zero time) error = %v, want ErrInvalidOrganization", err)
}
}
func TestApplyProfileKeepsTheVerificationVersionAndIdentity(t *testing.T) {
organization, err := NewOrganization(mustOrganizationProfile(t, OrganizationProfileInput{Name: "Старое имя"}), organizationTestTime)
if err != nil {
t.Fatalf("NewOrganization() error = %v", err)
}
later := organizationTestTime.Add(time.Hour)
updated, err := organization.ApplyProfile(mustOrganizationProfile(t, completeOrganizationProfileInput()), later)
if err != nil {
t.Fatalf("ApplyProfile() error = %v", err)
}
if updated.ID() != organization.ID() || updated.Version() != organization.Version() || updated.Verification() != organization.Verification() ||
!updated.CreatedAt().Equal(organizationTestTime) || !updated.UpdatedAt().Equal(later) {
t.Fatalf("updated = %v, want the same identity, version, and verification and the new update time", updated)
}
if updated.Profile().Name() != "ООО Пример Платежи" || organization.Profile().Name() != "Старое имя" {
t.Fatal("ApplyProfile changed the receiver or did not apply the profile")
}
// Clock skew between instances never moves the update time backwards.
skewed, err := updated.ApplyProfile(updated.Profile(), organizationTestTime)
if err != nil || !skewed.UpdatedAt().Equal(later) {
t.Fatalf("ApplyProfile(earlier time) = %v, %v, want the last update time kept", skewed.UpdatedAt(), err)
}
if _, err := organization.ApplyProfile(OrganizationProfile{}, later); !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("ApplyProfile(zero profile) error = %v, want ErrInvalidOrganization", err)
}
if _, err := (Organization{}).ApplyProfile(updated.Profile(), later); !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("ApplyProfile on a zero organization error = %v, want ErrInvalidOrganization", err)
}
}
func TestRestoreOrganizationVerificationAllowsOnlyTheBasesOfALevel(t *testing.T) {
for _, test := range []struct {
level, basis string
ok bool
}{
{"e0", "confirmed_email", true},
{"e1", "corporate_domain", true},
{"e2", "requisites_and_authority", true},
{"e3", "manual_review", true},
{"e3", "partner_status", true},
{"e0", "corporate_domain", false},
{"e1", "confirmed_email", false},
{"e2", "manual_review", false},
{"e4", "manual_review", false},
{"", "", false},
} {
_, err := RestoreOrganizationVerification(test.level, test.basis, organizationTestTime)
if (err == nil) != test.ok || (err != nil && !errors.Is(err, ErrInvalidOrganization)) {
t.Fatalf("RestoreOrganizationVerification(%q, %q) error = %v, want ok = %v", test.level, test.basis, err, test.ok)
}
}
if _, err := RestoreOrganizationVerification("e0", "confirmed_email", time.Time{}); !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("RestoreOrganizationVerification(zero time) error = %v, want ErrInvalidOrganization", err)
}
}
func TestVerificationLevelMapsToTheQuotaTiersOfThePolicy(t *testing.T) {
for level, want := range map[OrganizationVerificationLevel]OrganizationTier{
OrganizationVerificationE0: OrganizationTierE0,
OrganizationVerificationE1: OrganizationTierE1,
OrganizationVerificationE2: OrganizationTierE2,
} {
if tier, ok := level.QuotaTier(); !ok || tier != want {
t.Fatalf("%s.QuotaTier() = %q, %v, want %q", level, tier, ok, want)
}
}
if _, ok := OrganizationVerificationE3.QuotaTier(); ok {
t.Fatal("e3 has a quota tier, but the PRD gives it a separate policy")
}
}
func TestRestoreOrganizationRejectsARowChangedOutsideTheApplication(t *testing.T) {
valid := func() StoredOrganization {
return StoredOrganization{
ID: uuid.New(), Name: "ООО Пример", Version: 1,
VerificationLevel: "e0", VerificationBasis: "confirmed_email", VerificationChangedAt: organizationTestTime,
CreatedAt: organizationTestTime, UpdatedAt: organizationTestTime,
}
}
if _, err := RestoreOrganization(valid()); err != nil {
t.Fatalf("RestoreOrganization(valid) error = %v", err)
}
for name, change := range map[string]func(*StoredOrganization){
"nil ID": func(s *StoredOrganization) { s.ID = uuid.Nil },
"empty name": func(s *StoredOrganization) { s.Name = "" },
"version zero": func(s *StoredOrganization) { s.Version = 0 },
"unknown level": func(s *StoredOrganization) { s.VerificationLevel = "e9" },
"basis of another level": func(s *StoredOrganization) { s.VerificationBasis = "manual_review" },
"update before creation": func(s *StoredOrganization) { s.UpdatedAt = organizationTestTime.Add(-time.Second) },
"invalid website": func(s *StoredOrganization) { s.Website = "http://example.com" },
"too many representative": func(s *StoredOrganization) { s.Representatives = make([]StoredRepresentative, 11) },
} {
stored := valid()
change(&stored)
if _, err := RestoreOrganization(stored); !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("RestoreOrganization(%s) error = %v, want ErrInvalidOrganization", name, err)
}
}
}
func TestCandidateCardHoldsTheProfileAndTheLevelOnly(t *testing.T) {
organization, err := NewOrganization(mustOrganizationProfile(t, completeOrganizationProfileInput()), organizationTestTime)
if err != nil {
t.Fatalf("NewOrganization() error = %v", err)
}
card := organization.CandidateCard()
if card.ID() != organization.ID() || !card.Profile().Equal(organization.Profile()) || card.VerificationLevel() != OrganizationVerificationE0 {
t.Fatalf("card = %+v, want the id, the profile, and the level of the organization", card)
}
}
func TestRepresentativesAndOrganizationsAreRedactedInLogsAndFormatting(t *testing.T) {
const name = "Конфиденциальная Фамилия"
profile := mustOrganizationProfile(t, OrganizationProfileInput{
Name: "ООО Пример",
Representatives: []OrganizationRepresentativeInput{{Name: name, JobTitle: "Руководитель"}},
})
organization, err := NewOrganization(profile, organizationTestTime)
if err != nil {
t.Fatalf("NewOrganization() error = %v", err)
}
representative := profile.Representatives()[0]
type enclosing struct {
Representative OrganizationRepresentative
Hidden []OrganizationRepresentative
}
wrapped := enclosing{Representative: representative, Hidden: profile.Representatives()}
var logs bytes.Buffer
for _, logger := range []*slog.Logger{slog.New(slog.NewTextHandler(&logs, nil)), slog.New(slog.NewJSONHandler(&logs, nil))} {
logger.Info("organization", "representative", representative, "organization", organization)
}
output := fmt.Sprintf("%v %+v %#v %s %v %+v", representative, representative, representative, representative, wrapped, wrapped) + logs.String()
for _, secret := range []string{name, "Руководитель"} {
if strings.Contains(output, secret) {
t.Fatalf("printing a representative exposes %q: %s", secret, output)
}
}
if !strings.Contains(logs.String(), `"verification_level":"e0"`) {
t.Fatalf("logs = %s, want the organization logged by id, version, and level", logs.String())
}
}
func TestRestoreOrganizationSummaryValidatesTheNameAndTheLevel(t *testing.T) {
id := uuid.New()
if summary, err := RestoreOrganizationSummary(id, "ООО Пример", "e1"); err != nil || summary.ID() != id ||
summary.Name() != "ООО Пример" || summary.VerificationLevel() != OrganizationVerificationE1 {
t.Fatalf("RestoreOrganizationSummary() = %+v, %v, want the stored values", summary, err)
}
for _, test := range []struct {
id uuid.UUID
name, level string
}{
{uuid.Nil, "ООО", "e0"},
{id, "", "e0"},
{id, " ООО", "e0"},
{id, "ООО", "e5"},
} {
if _, err := RestoreOrganizationSummary(test.id, test.name, test.level); !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("RestoreOrganizationSummary(%v, %q, %q) error = %v, want ErrInvalidOrganization", test.id, test.name, test.level, err)
}
}
}
@@ -0,0 +1,153 @@
package outbound
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
// ErrOrganizationNotFound reports that the organization does not exist or
// that the account has no active membership in it. The two cases are the
// same on purpose, so a caller cannot tell an organization that exists
// from one that it may not enter.
ErrOrganizationNotFound = errors.New("organization not found")
// ErrOrganizationManagerRequired reports an account whose active
// membership does not have a role that manages the organization.
ErrOrganizationManagerRequired = errors.New("membership role cannot manage the organization")
// ErrOrganizationVersionConflict reports that the expected version of an
// organization is stale: another change advanced it. Nothing was changed;
// read the organization again.
ErrOrganizationVersionConflict = errors.New("organization changed concurrently")
// ErrMembershipExists reports a second membership for an account and
// organization that already have one, in any state.
ErrMembershipExists = errors.New("membership already exists")
// ErrMembershipNotFound reports that the account has no membership in the
// organization, in any state.
ErrMembershipNotFound = errors.New("membership not found")
)
// MaxOrganizationPageSize matches the largest page of the contract.
const MaxOrganizationPageSize = 100
// OrganizationRepositories exposes the organization and membership
// repositories. UnitOfWork binds them to one transaction, which a write
// needs: an organization and its owner membership commit together.
//
// Tenant data of other aggregates, such as needs and invitations, refers to
// organizations(id) with a restricting foreign key and always filters by the
// organization taken from a membership, never from a body.
type OrganizationRepositories interface {
Organizations() OrganizationRepository
Memberships() MembershipRepository
}
// OrganizationRepository stores organizations. Every read and write names an
// account, and only an active membership gives access, so a caller cannot
// reach an organization through it without the membership that the
// operations of the contract require.
type OrganizationRepository interface {
// CreateWithOwner stores a new organization and the active owner
// membership of its creator. The two inserts run in the surrounding
// transaction, so a failure between them leaves neither. The database also
// refuses to commit an organization that has no active owner (constraint
// organizations_owner_required, SQLSTATE 23514, raised by the commit of
// the transaction), whatever code inserted it. owner must be an active
// owner membership of organization; an unknown account fails with
// ErrUserNotFound, and the caller's transaction is aborted.
CreateWithOwner(ctx context.Context, organization domain.Organization, owner domain.Membership) error
// GetForMember returns the organization with its representatives and the
// active membership of the account in it, read from one snapshot in one
// statement, so the profile and the list never come from two states. It
// returns ErrOrganizationNotFound when the organization does not exist,
// when the account has no membership in it, and when the membership is
// suspended, removed, or left.
GetForMember(ctx context.Context, organizationID, userID uuid.UUID) (domain.Organization, domain.Membership, error)
// ListForUser returns one page of the organizations where the account has
// an active membership, newest membership first.
ListForUser(ctx context.Context, query OrganizationListQuery) (OrganizationPage, error)
// UpdateProfile stores the profile of organization as returned by
// domain.Organization.ApplyProfile on behalf of the account actorID. It
// applies only when the stored version still equals organization.Version()
// and the actor has an active membership with a role that manages the
// organization. The same statement advances the version by one, and the
// representative list is replaced in the same transaction, so the returned
// organization carries the new version. It never changes the verification
// level.
//
// Lock order: the statement locks the organization row, then the actor's
// membership row FOR SHARE, so a revocation committed while it waits stops
// the write. Every writer of both tables, such as the member management,
// must lock organizations first and memberships second, or two
// transactions can deadlock.
//
// It returns ErrOrganizationNotFound for an unknown organization or an
// actor without an active membership, ErrOrganizationManagerRequired for
// an active member whose role cannot manage, and
// ErrOrganizationVersionConflict for a stale version, checked in that
// order. A failure leaves the organization unchanged.
UpdateProfile(ctx context.Context, actorID uuid.UUID, organization domain.Organization) (domain.Organization, error)
}
// MembershipRepository stores memberships. A membership is unique per account
// and organization.
type MembershipRepository interface {
// Insert stores a membership. A second membership of the same account in
// the same organization, in any state, returns an error wrapping
// ErrMembershipExists; an unknown organization returns
// ErrOrganizationNotFound and an unknown account ErrUserNotFound. The
// database error aborts the surrounding transaction.
Insert(ctx context.Context, membership domain.Membership) error
// Get returns the membership of the account in the organization in any
// state, or ErrMembershipNotFound. The caller checks GrantsAccess before
// it trusts the membership.
Get(ctx context.Context, organizationID, userID uuid.UUID) (domain.Membership, error)
}
// OrganizationListQuery selects one page of an account's organizations.
type OrganizationListQuery struct {
UserID uuid.UUID
// After continues after the position of the last item of the previous
// page; nil reads the first page.
After *OrganizationListPosition
// Limit is the page size, from 1 to MaxOrganizationPageSize.
Limit int32
}
// OrganizationListPosition is the ordering key of an item in ListForUser.
type OrganizationListPosition struct {
JoinedAt time.Time
OrganizationID uuid.UUID
}
// MemberOrganization is an organization with the membership of the account
// that listed it.
type MemberOrganization struct {
Organization domain.OrganizationSummary
Membership domain.Membership
}
// OrganizationPositionOf returns the ordering key of item for the next page.
func OrganizationPositionOf(item MemberOrganization) OrganizationListPosition {
return OrganizationListPosition{JoinedAt: item.Membership.CreatedAt(), OrganizationID: item.Organization.ID()}
}
// OrganizationPage is one page of ListForUser.
type OrganizationPage struct {
Items []MemberOrganization
// HasMore reports that another page follows; read it with After set to
// the position of the last item.
HasMore bool
}
@@ -50,6 +50,7 @@ type Transactor interface {
type UnitOfWork interface {
IdentityRepositories
ConsentRepositories
OrganizationRepositories
Policies() PolicyRepository
Deliveries() DeliveryRepository
MailRequests() MailRequestRepository