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

+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)
}
}
}