feat(invitations): add organization invitation drafts with salary range rules

This commit is contained in:
shira committed 2026-10-09 14:28:36 +03:00
1 parent 28337d84cb
commit bd23c839fd
36 files changed
+7018 -83

No files matched your search

@@ -0,0 +1,191 @@
// Package invitation applies the owner-only rules of invitation drafts: the
// terms and their immutable versions, the link to a candidate card of the
// organization, and the idempotent creation. Sending, the candidate's side, and
// the contact grant belong to later operations that build on the same records.
package invitation
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var (
// ErrForbidden reports an account that may not work with the invitations
// of the organization: not an employer, or not its owner in the MVP.
ErrForbidden = errors.New("organization invitation operation forbidden")
// ErrEmailNotVerified reports an employer without a confirmed email.
ErrEmailNotVerified = errors.New("organization invitation requires a confirmed email")
// ErrIdempotencyKeyReused reports a key that was used with another request.
ErrIdempotencyKeyReused = errors.New("idempotency key reused with a different request")
// ErrInvalidIdempotencyKey reports a key outside 1 to 255 bytes.
ErrInvalidIdempotencyKey = errors.New("invalid idempotency key")
// ErrInvalidRequest reports a command that is incomplete before storage is
// read, such as a missing identifier or canonical body.
ErrInvalidRequest = errors.New("invalid organization invitation request")
// ErrPolicyUnavailable reports an effective product policy that cannot
// answer the invitation rules. It is a configuration error.
ErrPolicyUnavailable = errors.New("invitation policy is unavailable")
)
const (
createOperation = "organization_invitation.create"
maxIdempotencyKeySize = 255
maxCanonicalBodySize = 1 << 20
purgeExpiredBatch = 100
// maxCreateAttempts bounds the repeats of a create after the visible
// cohort changed while it was locked.
maxCreateAttempts = 3
)
// Keyring computes scoped idempotency digests. identity.Keyring implements
// this interface, so invitation commands use the existing server secret and
// store.
type Keyring interface {
IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte
Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte
}
// CandidateResolver turns a card handle of the organization into the candidate
// it stands for, inside the caller's transaction. It applies the same
// visibility barrier as the card read: the effective publication, the hiding
// of the organization, and the cohort rules. It answers
// candidateview.ErrCandidateCardNotFound for every handle the organization may
// not use. The identifier it returns never leaves the server.
type CandidateResolver func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID, handle string) (uuid.UUID, error)
// Dependencies configure one stateless invitation service.
type Dependencies struct {
Transactor outbound.Transactor
Keyring Keyring
// PseudonymKey derives the organization-scoped alias that responses show
// instead of the candidate. It is the key of the cards and the search, so
// a handle in an invitation is the handle of the card.
PseudonymKey domain.CandidateViewPseudonymKey
Candidates CandidateResolver
Clock func() time.Time
}
// Service applies organization-scoped invitation draft commands and reads.
type Service struct {
transactor outbound.Transactor
keyring Keyring
pseudonymKey domain.CandidateViewPseudonymKey
candidates CandidateResolver
clock func() time.Time
}
// NewService fails at startup when a required dependency is missing.
func NewService(deps Dependencies) (*Service, error) {
if deps.Transactor == nil || deps.Keyring == nil || deps.Candidates == nil || deps.Clock == nil {
return nil, errors.New("invitation.NewService - every dependency must be set")
}
if _, err := deps.PseudonymKey.ForOrganization(uuid.New(), uuid.New()); err != nil {
return nil, errors.New("invitation.NewService - the pseudonym key must be usable")
}
return &Service{
transactor: deps.Transactor, keyring: deps.Keyring, pseudonymKey: deps.PseudonymKey,
candidates: deps.Candidates, clock: deps.Clock,
}, nil
}
// now returns the application time at the precision the database stores.
func (service *Service) now(location string) (time.Time, error) {
now := service.clock().UTC().Truncate(time.Microsecond)
if now.IsZero() || now.Year() < 1 || now.Year() > 9999 {
return time.Time{}, fmt.Errorf("%s - application time must be representable: %w", location, ErrInvalidRequest)
}
return now, nil
}
// view is the invitation as its organization reads it. The salary indicator
// and the contact access are not derived from the candidate's minimum or from
// a grant yet: the indicator is not_available, the least revealing value, and
// no grant exists before an acceptance.
func (service *Service) view(invitation domain.Invitation) (domain.OrganizationInvitationView, error) {
handle, err := service.pseudonymKey.ForOrganization(invitation.OrganizationID(), invitation.CandidateID())
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("invitation.Service.view - derive candidate alias: %w", err)
}
return domain.OrganizationInvitationView{
InvitationSnapshot: invitation.Snapshot(),
CandidateHandle: handle,
SalaryFit: domain.InvitationSalaryNotAvailable,
ContactAccess: domain.InvitationContactAccessNone,
}, nil
}
// lockOrganizationFirst takes the exclusive organization lock of the company
// quota port, ahead of the share lock of the membership check and of the
// cohort locks, so two commands of one organization queue instead of
// deadlocking on a lock upgrade. An organization that does not exist answers
// like a missing membership.
func lockOrganizationFirst(ctx context.Context, unit outbound.UnitOfWork, organizationID uuid.UUID, location string) error {
if err := unit.CompanyQuotas().LockOrganization(ctx, organizationID); err != nil {
if errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) {
return fmt.Errorf("%s - lock organization: %w", location, outbound.ErrOrganizationNotFound)
}
return fmt.Errorf("%s - lock organization: %w", location, err)
}
return nil
}
// authorizeOwner repeats, inside the transaction, the checks of the HTTP
// boundary: an existing employer with a confirmed email whose membership in
// the organization is active and owner. The MVP milestone grants a membership
// by itself no right over invitations.
func authorizeOwner(
ctx context.Context,
unit outbound.UnitOfWork,
actorID, organizationID uuid.UUID,
location string,
) error {
if actorID == uuid.Nil || organizationID == uuid.Nil {
return fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
}
user, err := unit.Users().GetByID(ctx, actorID)
if err != nil {
if errors.Is(err, outbound.ErrUserNotFound) {
return fmt.Errorf("%s - require existing employer account: %w", location, ErrForbidden)
}
return fmt.Errorf("%s - read account: %w", location, err)
}
if user.Scenario != domain.ScenarioEmployer {
return fmt.Errorf("%s - require employer account: %w", location, ErrForbidden)
}
if !user.EmailVerified() {
return fmt.Errorf("%s - require verified email: %w", location, ErrEmailNotVerified)
}
membership, err := unit.Organizations().LockActiveMembership(ctx, organizationID, actorID)
if err != nil {
if errors.Is(err, outbound.ErrOrganizationNotFound) {
return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound)
}
return fmt.Errorf("%s - lock active membership: %w", location, err)
}
if membership.Role() != domain.OrganizationRoleOwner {
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
}
return nil
}
// effectiveInvitationPolicy reads the invitation section of the product
// policy in force at the time, with the version that governed the decision.
func effectiveInvitationPolicy(
ctx context.Context,
unit outbound.UnitOfWork,
at time.Time,
location string,
) (domain.InvitationPolicy, domain.PolicyVersionID, error) {
version, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, at)
if err != nil {
return domain.InvitationPolicy{}, domain.PolicyVersionID{}, fmt.Errorf("%s - read effective product policy: %w: %w", location, ErrPolicyUnavailable, err)
}
return version.Policy().Invitations, version.ID(), nil
}