feat(invitations): add organization invitation drafts with salary range rules
This commit is contained in:
1 parent
28337d84cb
commit
bd23c839fd
36 files changed
+7018
-83
No files matched your search
@@ -314,6 +314,54 @@ func (service *Service) AuthorizeCategoriesSection(
|
||||
return candidateID, slices.Clone(view.Categories), nil
|
||||
}
|
||||
|
||||
// ResolveCandidateHandle turns the handle of a card of this organization into
|
||||
// the candidate it stands for, inside the caller's transaction. It applies the
|
||||
// checks of a card read under the same locks: the active membership of the
|
||||
// actor, the effective C2 publication, the hiding of this organization, and
|
||||
// the minimum cohort, so a handle of another organization, an unknown handle,
|
||||
// a candidate who revoked the publication or hid the profile from the
|
||||
// organization, and a card that the cohort rules suppress all answer
|
||||
// ErrCandidateCardNotFound. The caller cannot tell the cases apart.
|
||||
//
|
||||
// It consumes no card-view quota and writes no access history: it returns an
|
||||
// identifier for the server's own use and shows no card content, and the
|
||||
// search or the card read that produced the handle was charged when it
|
||||
// revealed the candidate. The identifier must never leave the server.
|
||||
//
|
||||
// The caller's transaction must not hold a share lock of the organization yet,
|
||||
// so that the exclusive organization lock of the quota writers is taken first.
|
||||
func (service *Service) ResolveCandidateHandle(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
actorID, organizationID uuid.UUID,
|
||||
handle string,
|
||||
) (uuid.UUID, error) {
|
||||
const location = "candidateview.Service.ResolveCandidateHandle"
|
||||
if actorID == uuid.Nil || organizationID == uuid.Nil {
|
||||
return uuid.Nil, ErrForbidden
|
||||
}
|
||||
if !domain.IsCandidateViewPseudonym(handle) {
|
||||
return uuid.Nil, ErrInvalidCandidateHandle
|
||||
}
|
||||
if err := lockOrganizationFirst(ctx, unit, organizationID); err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
_, _, sources, err := loadCurrentVisibleCohort(ctx, unit, actorID, organizationID, location)
|
||||
if err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
candidateID, err := candidateIDForHandle(service, organizationID, sources, handle, location)
|
||||
if err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
// A card that the cohort rules suppress is not offered by a search, so its
|
||||
// handle is not accepted either.
|
||||
if _, err := projectedViewForHandle(service, organizationID, sources, handle, location); err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return candidateID, nil
|
||||
}
|
||||
|
||||
func (service *Service) currentOrganizationCard(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
package invitation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/candidateview"
|
||||
)
|
||||
|
||||
const (
|
||||
createLocation = "invitation.Service.Create"
|
||||
updateLocation = "invitation.Service.Update"
|
||||
getLocation = "invitation.Service.Get"
|
||||
listLocation = "invitation.Service.List"
|
||||
)
|
||||
|
||||
// CreateCommand binds the authenticated actor and the path organization to
|
||||
// one validated create request. The candidate is named only by the handle.
|
||||
type CreateCommand struct {
|
||||
ActorID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
IdempotencyKey string
|
||||
CanonicalBody []byte
|
||||
CandidateHandle string
|
||||
Need *domain.InvitationNeedRef
|
||||
ResponsePeriodDays *int32
|
||||
Terms domain.InvitationTerms
|
||||
}
|
||||
|
||||
type createRequest struct {
|
||||
fingerprint [outbound.IdempotencyDigestSize]byte
|
||||
scope [outbound.IdempotencyDigestSize]byte
|
||||
record outbound.IdempotencyRecord
|
||||
now time.Time
|
||||
}
|
||||
|
||||
// Create stores a new draft addressed to one candidate of the organization's
|
||||
// visible cards, or replays the original response of the same request within
|
||||
// the idempotency window. Nothing is stored when any rule fails.
|
||||
func (service *Service) Create(ctx context.Context, command CreateCommand) (domain.OrganizationInvitationView, error) {
|
||||
request, err := service.prepareCreate(command)
|
||||
if err != nil {
|
||||
return domain.OrganizationInvitationView{}, err
|
||||
}
|
||||
var result domain.OrganizationInvitationView
|
||||
// The visible cohort can change while it is locked. The whole command is
|
||||
// then repeated, a bounded number of times, and the writes of a failed
|
||||
// attempt roll back with it.
|
||||
for range maxCreateAttempts {
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
result, err = service.createInTransaction(ctx, unit, command, request)
|
||||
return err
|
||||
})
|
||||
if !errors.Is(err, candidateview.ErrConcurrentVisibilityChange) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - run transaction: %w", createLocation, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (service *Service) prepareCreate(command CreateCommand) (createRequest, error) {
|
||||
const location = "invitation.Service.prepareCreate"
|
||||
switch {
|
||||
case command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil:
|
||||
return createRequest{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
|
||||
case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize:
|
||||
return createRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey)
|
||||
case len(command.CanonicalBody) == 0 || len(command.CanonicalBody) > maxCanonicalBodySize:
|
||||
return createRequest{}, fmt.Errorf("%s - canonical request body is outside its bound: %w", location, ErrInvalidRequest)
|
||||
}
|
||||
now, err := service.now(location)
|
||||
if err != nil {
|
||||
return createRequest{}, err
|
||||
}
|
||||
expiresAt := now.Add(outbound.IdempotencyRetention)
|
||||
principal := command.ActorID.String() + ":" + command.OrganizationID.String()
|
||||
fingerprint := service.keyring.Fingerprint(command.CanonicalBody)
|
||||
scope := service.keyring.IdempotencyScope(createOperation, command.IdempotencyKey, principal)
|
||||
return createRequest{
|
||||
fingerprint: fingerprint, scope: scope, now: now,
|
||||
record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: expiresAt},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (service *Service) createInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command CreateCommand,
|
||||
request createRequest,
|
||||
) (domain.OrganizationInvitationView, error) {
|
||||
if err := lockOrganizationFirst(ctx, unit, command.OrganizationID, createLocation); err != nil {
|
||||
return domain.OrganizationInvitationView{}, err
|
||||
}
|
||||
if err := authorizeOwner(ctx, unit, command.ActorID, command.OrganizationID, createLocation); err != nil {
|
||||
return domain.OrganizationInvitationView{}, err
|
||||
}
|
||||
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
|
||||
if err != nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - reserve idempotency record: %w", createLocation, err)
|
||||
}
|
||||
if !created {
|
||||
return replayCreation(ctx, unit, request, command.OrganizationID, stored)
|
||||
}
|
||||
invitation, err := service.buildDraft(ctx, unit, command, request.now)
|
||||
if err != nil {
|
||||
return domain.OrganizationInvitationView{}, err
|
||||
}
|
||||
event, err := invitation.DraftEvent(command.ActorID, nil)
|
||||
if err != nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - build audit event: %w", createLocation, err)
|
||||
}
|
||||
if err := unit.Invitations().Create(ctx, invitation, event); err != nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - store draft: %w", createLocation, err)
|
||||
}
|
||||
view, err := service.view(invitation)
|
||||
if err != nil {
|
||||
return domain.OrganizationInvitationView{}, err
|
||||
}
|
||||
if err := unit.InvitationCreationResults().SaveCreationResult(ctx, request.scope, view); err != nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - store original response: %w", createLocation, err)
|
||||
}
|
||||
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err)
|
||||
}
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// buildDraft applies the domain rules in the order of the contract: the
|
||||
// candidate handle, the need link, then the terms. The handle is resolved
|
||||
// through the same visibility barrier as a card read, so a draft cannot be
|
||||
// addressed to a candidate that the organization may not see.
|
||||
func (service *Service) buildDraft(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command CreateCommand,
|
||||
now time.Time,
|
||||
) (domain.Invitation, error) {
|
||||
policy, policyVersionID, err := effectiveInvitationPolicy(ctx, unit, now, createLocation)
|
||||
if err != nil {
|
||||
return domain.Invitation{}, err
|
||||
}
|
||||
var requested *domain.CalendarDays
|
||||
if command.ResponsePeriodDays != nil {
|
||||
period := domain.CalendarDays(*command.ResponsePeriodDays)
|
||||
requested = &period
|
||||
}
|
||||
period, err := policy.ResolveResponsePeriod(requested)
|
||||
if err != nil {
|
||||
return domain.Invitation{}, fmt.Errorf("%s - resolve response period: %w", createLocation, err)
|
||||
}
|
||||
candidateID, err := service.candidates(ctx, unit, command.ActorID, command.OrganizationID, command.CandidateHandle)
|
||||
if err != nil {
|
||||
if errors.Is(err, candidateview.ErrCandidateCardNotFound) || errors.Is(err, candidateview.ErrInvalidCandidateHandle) {
|
||||
return domain.Invitation{}, fmt.Errorf("%s - resolve candidate handle: %w", createLocation,
|
||||
&domain.InvitationFieldError{Pointer: "/candidate_handle", Reason: "must be a handle of a candidate this organization can see"})
|
||||
}
|
||||
return domain.Invitation{}, fmt.Errorf("%s - resolve candidate handle: %w", createLocation, err)
|
||||
}
|
||||
if err := checkNeedLink(ctx, unit, command.OrganizationID, command.Need); err != nil {
|
||||
return domain.Invitation{}, fmt.Errorf("%s - %w", createLocation, err)
|
||||
}
|
||||
draftID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return domain.Invitation{}, fmt.Errorf("%s - generate invitation ID: %w", createLocation, err)
|
||||
}
|
||||
invitation, err := domain.NewInvitationDraft(domain.NewInvitationDraftInput{
|
||||
ID: draftID, OrganizationID: command.OrganizationID, CandidateID: candidateID, ActorID: command.ActorID,
|
||||
PolicyVersionID: policyVersionID, At: now,
|
||||
Content: domain.InvitationDraftContent{Need: command.Need, ResponsePeriod: period, Terms: command.Terms},
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Invitation{}, fmt.Errorf("%s - build draft: %w", createLocation, err)
|
||||
}
|
||||
return invitation, nil
|
||||
}
|
||||
|
||||
// checkNeedLink requires that a linked need belongs to the organization and
|
||||
// has had the stated requirements version. Both cases give one pointer, so the
|
||||
// answer does not tell whether the need exists in another organization.
|
||||
func checkNeedLink(ctx context.Context, unit outbound.UnitOfWork, organizationID uuid.UUID, need *domain.InvitationNeedRef) error {
|
||||
if need == nil {
|
||||
return nil
|
||||
}
|
||||
exists, err := unit.Invitations().NeedVersionExists(ctx, organizationID, need.NeedID, need.RequirementsVersion)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check need link: %w", err)
|
||||
}
|
||||
if !exists {
|
||||
return &domain.InvitationFieldError{Pointer: "/need", Reason: "must be a need of this organization with a requirements version it has had"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func replayCreation(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
request createRequest,
|
||||
organizationID uuid.UUID,
|
||||
stored outbound.IdempotencyRecord,
|
||||
) (domain.OrganizationInvitationView, error) {
|
||||
if stored.Fingerprint != request.fingerprint {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - compare request fingerprint: %w", createLocation, ErrIdempotencyKeyReused)
|
||||
}
|
||||
original, err := unit.InvitationCreationResults().GetCreationResult(ctx, request.scope)
|
||||
if err != nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - read original response: %w", createLocation, err)
|
||||
}
|
||||
if original.OrganizationID != organizationID {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - validate original response: %w", createLocation, domain.ErrInvalidInvitation)
|
||||
}
|
||||
return original, nil
|
||||
}
|
||||
|
||||
// Field distinguishes a property that the request left out from one it set,
|
||||
// and from one it set to null.
|
||||
type Field[T any] struct {
|
||||
Set bool
|
||||
Null bool
|
||||
Value T
|
||||
}
|
||||
|
||||
// UpdateCommand binds one versioned replacement to a trusted actor and path.
|
||||
// A field that is not set stays unchanged; terms are replaced as a whole.
|
||||
type UpdateCommand struct {
|
||||
ActorID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
InvitationID uuid.UUID
|
||||
ExpectedVersion int64
|
||||
Need Field[domain.InvitationNeedRef]
|
||||
ResponsePeriodDays *int32
|
||||
Terms *domain.InvitationTerms
|
||||
}
|
||||
|
||||
// Update replaces the fields the request sets, in the order of the contract:
|
||||
// a request that changes nothing returns the current invitation, then the
|
||||
// version is compared, then the state, then the domain rules. Only a draft
|
||||
// changes. A change appends the next invitation version, and a change of the
|
||||
// terms appends the next immutable terms version.
|
||||
func (service *Service) Update(ctx context.Context, command UpdateCommand) (domain.OrganizationInvitationView, error) {
|
||||
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", updateLocation, ErrForbidden)
|
||||
}
|
||||
if command.ExpectedVersion < 1 {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - %w", updateLocation,
|
||||
&domain.InvitationFieldError{Pointer: "/expected_version", Reason: "must be positive"})
|
||||
}
|
||||
now, err := service.now(updateLocation)
|
||||
if err != nil {
|
||||
return domain.OrganizationInvitationView{}, err
|
||||
}
|
||||
var result domain.OrganizationInvitationView
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
result, err = service.updateInTransaction(ctx, unit, command, now)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - run transaction: %w", updateLocation, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (service *Service) updateInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command UpdateCommand,
|
||||
now time.Time,
|
||||
) (domain.OrganizationInvitationView, error) {
|
||||
// Every invitation command takes the organization lock before the
|
||||
// membership share lock and the invitation row lock, in the order of the
|
||||
// create, the card read, and the search, so a later command that also
|
||||
// charges the organization (sending, the salary limit) cannot deadlock
|
||||
// against an update.
|
||||
if err := lockOrganizationFirst(ctx, unit, command.OrganizationID, updateLocation); err != nil {
|
||||
return domain.OrganizationInvitationView{}, err
|
||||
}
|
||||
if err := authorizeOwner(ctx, unit, command.ActorID, command.OrganizationID, updateLocation); err != nil {
|
||||
return domain.OrganizationInvitationView{}, err
|
||||
}
|
||||
// The nil identifier cannot name an invitation. It answers like any
|
||||
// unknown identifier, after the authorization above.
|
||||
if command.InvitationID == uuid.Nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - nil invitation: %w", updateLocation, outbound.ErrInvitationNotFound)
|
||||
}
|
||||
current, err := unit.Invitations().GetForUpdate(ctx, command.OrganizationID, command.InvitationID)
|
||||
if err != nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - lock invitation: %w", updateLocation, err)
|
||||
}
|
||||
before := current.DraftContent()
|
||||
merged := mergeDraft(before, command)
|
||||
changed := before.ChangedFields(merged)
|
||||
if len(changed) == 0 {
|
||||
return service.view(current)
|
||||
}
|
||||
if command.ExpectedVersion != current.Version() {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - compare expected version: %w", updateLocation, domain.ErrInvitationVersionConflict)
|
||||
}
|
||||
if current.State() != domain.InvitationDraft {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - require a draft: %w", updateLocation, domain.ErrInvitationNotDraft)
|
||||
}
|
||||
policyVersionID, err := service.checkRevision(ctx, unit, current, merged, changed, now)
|
||||
if err != nil {
|
||||
return domain.OrganizationInvitationView{}, err
|
||||
}
|
||||
// A clock that stepped back must not make the revision older than the
|
||||
// draft it revises.
|
||||
at := now
|
||||
if at.Before(current.UpdatedAt()) {
|
||||
at = current.UpdatedAt()
|
||||
}
|
||||
next, appliedFields, err := current.ReviseDraft(merged, policyVersionID, at)
|
||||
if err != nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - revise draft: %w", updateLocation, err)
|
||||
}
|
||||
event, err := next.DraftEvent(command.ActorID, appliedFields)
|
||||
if err != nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - build audit event: %w", updateLocation, err)
|
||||
}
|
||||
termsChanged := next.TermsVersion() != current.TermsVersion()
|
||||
if err := unit.Invitations().SaveDraft(ctx, current.Version(), next, termsChanged, event); err != nil {
|
||||
if errors.Is(err, outbound.ErrInvitationVersionConflict) {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - save draft: %w", updateLocation, domain.ErrInvitationVersionConflict)
|
||||
}
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - save draft: %w", updateLocation, err)
|
||||
}
|
||||
return service.view(next)
|
||||
}
|
||||
|
||||
// mergeDraft applies the fields the command sets over the current content.
|
||||
func mergeDraft(current domain.InvitationDraftContent, command UpdateCommand) domain.InvitationDraftContent {
|
||||
merged := current
|
||||
if command.Need.Set {
|
||||
merged.Need = nil
|
||||
if !command.Need.Null {
|
||||
need := command.Need.Value
|
||||
merged.Need = &need
|
||||
}
|
||||
}
|
||||
if command.ResponsePeriodDays != nil {
|
||||
merged.ResponsePeriod = domain.CalendarDays(*command.ResponsePeriodDays)
|
||||
}
|
||||
if command.Terms != nil {
|
||||
merged.Terms = *command.Terms
|
||||
}
|
||||
return merged
|
||||
}
|
||||
|
||||
// checkRevision runs the rules that need storage or the policy and returns the
|
||||
// policy version that governs the stored response period. The period is
|
||||
// checked against the policy in force only when the request changes it.
|
||||
func (service *Service) checkRevision(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
current domain.Invitation,
|
||||
merged domain.InvitationDraftContent,
|
||||
changed []domain.InvitationChangedField,
|
||||
now time.Time,
|
||||
) (domain.PolicyVersionID, error) {
|
||||
policyVersionID := current.PolicyVersionID()
|
||||
for _, field := range changed {
|
||||
switch field {
|
||||
case domain.InvitationChangedResponsePeriod:
|
||||
policy, versionID, err := effectiveInvitationPolicy(ctx, unit, now, updateLocation)
|
||||
if err != nil {
|
||||
return domain.PolicyVersionID{}, err
|
||||
}
|
||||
if _, err := policy.ResolveResponsePeriod(&merged.ResponsePeriod); err != nil {
|
||||
return domain.PolicyVersionID{}, fmt.Errorf("%s - resolve response period: %w", updateLocation, err)
|
||||
}
|
||||
policyVersionID = versionID
|
||||
case domain.InvitationChangedNeed:
|
||||
if err := checkNeedLink(ctx, unit, current.OrganizationID(), merged.Need); err != nil {
|
||||
return domain.PolicyVersionID{}, fmt.Errorf("%s - %w", updateLocation, err)
|
||||
}
|
||||
case domain.InvitationChangedTerms:
|
||||
// The terms need no storage: the domain validates them when the
|
||||
// draft is revised, after the need link, as on creation.
|
||||
}
|
||||
}
|
||||
return policyVersionID, nil
|
||||
}
|
||||
|
||||
// Get reads the current invitation for an active owner.
|
||||
func (service *Service) Get(ctx context.Context, actorID, organizationID, invitationID uuid.UUID) (domain.OrganizationInvitationView, error) {
|
||||
if actorID == uuid.Nil || organizationID == uuid.Nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", getLocation, ErrForbidden)
|
||||
}
|
||||
var result domain.OrganizationInvitationView
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeOwner(ctx, unit, actorID, organizationID, getLocation); err != nil {
|
||||
return err
|
||||
}
|
||||
if invitationID == uuid.Nil {
|
||||
return fmt.Errorf("%s - nil invitation: %w", getLocation, outbound.ErrInvitationNotFound)
|
||||
}
|
||||
current, err := unit.Invitations().Get(ctx, organizationID, invitationID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read invitation: %w", getLocation, err)
|
||||
}
|
||||
result, err = service.view(current)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - run transaction: %w", getLocation, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ListCommand selects an owner-scoped page of invitations.
|
||||
type ListCommand struct {
|
||||
ActorID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
After *outbound.InvitationListPosition
|
||||
Limit int32
|
||||
}
|
||||
|
||||
// Page is one page of invitations, newest first.
|
||||
type Page struct {
|
||||
Items []domain.OrganizationInvitationView
|
||||
HasMore bool
|
||||
}
|
||||
|
||||
// List reads one page of the organization's invitations of every state after
|
||||
// checking the current account and owner membership in the same transaction.
|
||||
func (service *Service) List(ctx context.Context, command ListCommand) (Page, error) {
|
||||
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil {
|
||||
return Page{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", listLocation, ErrForbidden)
|
||||
}
|
||||
if command.Limit < 1 || command.Limit > outbound.MaxInvitationPageSize {
|
||||
return Page{}, fmt.Errorf("%s - page limit must be 1 to %d: %w", listLocation, outbound.MaxInvitationPageSize, ErrInvalidRequest)
|
||||
}
|
||||
var result Page
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeOwner(ctx, unit, command.ActorID, command.OrganizationID, listLocation); err != nil {
|
||||
return err
|
||||
}
|
||||
page, err := unit.Invitations().List(ctx, outbound.InvitationListQuery{
|
||||
OrganizationID: command.OrganizationID, After: command.After, Limit: command.Limit,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - list invitations: %w", listLocation, err)
|
||||
}
|
||||
result = Page{Items: make([]domain.OrganizationInvitationView, 0, len(page.Items)), HasMore: page.HasMore}
|
||||
for _, invitation := range page.Items {
|
||||
item, err := service.view(invitation)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result.Items = append(result.Items, item)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return Page{}, fmt.Errorf("%s - run transaction: %w", listLocation, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,699 @@
|
||||
package invitation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/candidateview"
|
||||
)
|
||||
|
||||
type testKeyring struct{}
|
||||
|
||||
func (testKeyring) IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte {
|
||||
return sha256.Sum256([]byte(operation + "\x00" + key + "\x00" + principal))
|
||||
}
|
||||
|
||||
func (testKeyring) Fingerprint(body []byte) [outbound.IdempotencyDigestSize]byte {
|
||||
return sha256.Sum256(body)
|
||||
}
|
||||
|
||||
type termsKey struct {
|
||||
invitationID uuid.UUID
|
||||
version int64
|
||||
}
|
||||
|
||||
type testState struct {
|
||||
users map[uuid.UUID]domain.User
|
||||
memberships map[[2]uuid.UUID]domain.Membership
|
||||
invitations map[uuid.UUID]domain.Invitation
|
||||
terms map[termsKey]domain.InvitationTerms
|
||||
events []domain.InvitationEvent
|
||||
idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord
|
||||
results map[[outbound.IdempotencyDigestSize]byte]domain.OrganizationInvitationView
|
||||
needVersions map[[3]string]bool
|
||||
}
|
||||
|
||||
func newTestState() testState {
|
||||
return testState{
|
||||
users: map[uuid.UUID]domain.User{}, memberships: map[[2]uuid.UUID]domain.Membership{},
|
||||
invitations: map[uuid.UUID]domain.Invitation{}, terms: map[termsKey]domain.InvitationTerms{},
|
||||
idempotency: map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord{},
|
||||
results: map[[outbound.IdempotencyDigestSize]byte]domain.OrganizationInvitationView{},
|
||||
needVersions: map[[3]string]bool{},
|
||||
}
|
||||
}
|
||||
|
||||
func (state testState) clone() testState {
|
||||
cloned := newTestState()
|
||||
for id, user := range state.users {
|
||||
cloned.users[id] = user
|
||||
}
|
||||
for key, membership := range state.memberships {
|
||||
cloned.memberships[key] = membership
|
||||
}
|
||||
for id, invitation := range state.invitations {
|
||||
cloned.invitations[id] = invitation
|
||||
}
|
||||
for key, terms := range state.terms {
|
||||
cloned.terms[key] = terms.Clone()
|
||||
}
|
||||
cloned.events = slices.Clone(state.events)
|
||||
for scope, record := range state.idempotency {
|
||||
cloned.idempotency[scope] = record
|
||||
}
|
||||
for scope, result := range state.results {
|
||||
cloned.results[scope] = result
|
||||
}
|
||||
for key, found := range state.needVersions {
|
||||
cloned.needVersions[key] = found
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
|
||||
type testTransactor struct {
|
||||
mu sync.Mutex
|
||||
state testState
|
||||
policy domain.PolicyVersion
|
||||
failResultSave bool
|
||||
}
|
||||
|
||||
func (transactor *testTransactor) WithinTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error {
|
||||
transactor.mu.Lock()
|
||||
defer transactor.mu.Unlock()
|
||||
working := transactor.state.clone()
|
||||
unit := &testUnit{state: &working, policy: transactor.policy, failResultSave: transactor.failResultSave}
|
||||
if err := work(ctx, unit); err != nil {
|
||||
return err
|
||||
}
|
||||
transactor.state = working
|
||||
return nil
|
||||
}
|
||||
|
||||
func (transactor *testTransactor) snapshot() testState {
|
||||
transactor.mu.Lock()
|
||||
defer transactor.mu.Unlock()
|
||||
return transactor.state.clone()
|
||||
}
|
||||
|
||||
type testUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
state *testState
|
||||
policy domain.PolicyVersion
|
||||
failResultSave bool
|
||||
}
|
||||
|
||||
func (unit *testUnit) Users() outbound.UserRepository { return testUsers{state: unit.state} }
|
||||
func (unit *testUnit) Organizations() outbound.OrganizationRepository {
|
||||
return testOrganizations{state: unit.state}
|
||||
}
|
||||
func (unit *testUnit) IdempotencyRecords() outbound.IdempotencyRepository {
|
||||
return testIdempotency{state: unit.state}
|
||||
}
|
||||
func (unit *testUnit) CompanyQuotas() outbound.CompanyQuotaRepository { return testQuotas{} }
|
||||
func (unit *testUnit) Policies() outbound.PolicyRepository { return testPolicies{version: unit.policy} }
|
||||
func (unit *testUnit) Invitations() outbound.InvitationRepository {
|
||||
return testInvitations{state: unit.state}
|
||||
}
|
||||
func (unit *testUnit) InvitationCreationResults() outbound.InvitationCreationResultRepository {
|
||||
return testInvitations{state: unit.state, failResultSave: unit.failResultSave}
|
||||
}
|
||||
|
||||
type testUsers struct {
|
||||
outbound.UserRepository
|
||||
|
||||
state *testState
|
||||
}
|
||||
|
||||
func (repository testUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
|
||||
user, ok := repository.state.users[id]
|
||||
if !ok {
|
||||
return domain.User{}, outbound.ErrUserNotFound
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
type testOrganizations struct {
|
||||
outbound.OrganizationRepository
|
||||
|
||||
state *testState
|
||||
}
|
||||
|
||||
func (repository testOrganizations) LockActiveMembership(_ context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) {
|
||||
membership, ok := repository.state.memberships[[2]uuid.UUID{organizationID, userID}]
|
||||
if !ok || !membership.GrantsAccess() {
|
||||
return domain.Membership{}, outbound.ErrOrganizationNotFound
|
||||
}
|
||||
return membership, nil
|
||||
}
|
||||
|
||||
type testQuotas struct {
|
||||
outbound.CompanyQuotaRepository
|
||||
}
|
||||
|
||||
func (testQuotas) LockOrganization(context.Context, uuid.UUID) error { return nil }
|
||||
|
||||
type testPolicies struct {
|
||||
outbound.PolicyRepository
|
||||
|
||||
version domain.PolicyVersion
|
||||
}
|
||||
|
||||
func (policies testPolicies) GetEffective(context.Context, domain.PolicyKey, time.Time) (domain.PolicyVersion, error) {
|
||||
return policies.version, nil
|
||||
}
|
||||
|
||||
type testIdempotency struct {
|
||||
outbound.IdempotencyRepository
|
||||
|
||||
state *testState
|
||||
}
|
||||
|
||||
func (repository testIdempotency) Reserve(_ context.Context, record outbound.IdempotencyRecord) (outbound.IdempotencyRecord, bool, error) {
|
||||
if existing, ok := repository.state.idempotency[record.Scope]; ok && existing.ExpiresAt.After(record.CreatedAt) {
|
||||
return existing, false, nil
|
||||
}
|
||||
repository.state.idempotency[record.Scope] = record
|
||||
return record, true, nil
|
||||
}
|
||||
|
||||
func (repository testIdempotency) PurgeExpired(_ context.Context, at time.Time, _ int32) (int64, error) {
|
||||
var deleted int64
|
||||
for scope, record := range repository.state.idempotency {
|
||||
if !record.ExpiresAt.After(at) {
|
||||
delete(repository.state.idempotency, scope)
|
||||
delete(repository.state.results, scope)
|
||||
deleted++
|
||||
}
|
||||
}
|
||||
return deleted, nil
|
||||
}
|
||||
|
||||
type testInvitations struct {
|
||||
state *testState
|
||||
failResultSave bool
|
||||
}
|
||||
|
||||
func (repository testInvitations) Create(_ context.Context, invitation domain.Invitation, event domain.InvitationEvent) error {
|
||||
repository.state.invitations[invitation.ID()] = invitation
|
||||
repository.state.terms[termsKey{invitation.ID(), 1}] = invitation.Snapshot().Terms
|
||||
repository.state.events = append(repository.state.events, event)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository testInvitations) Get(_ context.Context, organizationID, invitationID uuid.UUID) (domain.Invitation, error) {
|
||||
invitation, ok := repository.state.invitations[invitationID]
|
||||
if !ok || invitation.OrganizationID() != organizationID {
|
||||
return domain.Invitation{}, outbound.ErrInvitationNotFound
|
||||
}
|
||||
return invitation, nil
|
||||
}
|
||||
|
||||
func (repository testInvitations) GetForUpdate(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.Invitation, error) {
|
||||
return repository.Get(ctx, organizationID, invitationID)
|
||||
}
|
||||
|
||||
func (repository testInvitations) List(_ context.Context, query outbound.InvitationListQuery) (outbound.InvitationPage, error) {
|
||||
var items []domain.Invitation
|
||||
for _, invitation := range repository.state.invitations {
|
||||
if invitation.OrganizationID() == query.OrganizationID {
|
||||
items = append(items, invitation)
|
||||
}
|
||||
}
|
||||
slices.SortFunc(items, func(left, right domain.Invitation) int {
|
||||
return strings.Compare(right.ID().String(), left.ID().String())
|
||||
})
|
||||
page := outbound.InvitationPage{HasMore: len(items) > int(query.Limit)}
|
||||
if page.HasMore {
|
||||
items = items[:query.Limit]
|
||||
}
|
||||
page.Items = items
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (repository testInvitations) SaveDraft(_ context.Context, expectedVersion int64, next domain.Invitation, termsChanged bool, event domain.InvitationEvent) error {
|
||||
current, ok := repository.state.invitations[next.ID()]
|
||||
if !ok || current.Version() != expectedVersion || current.State() != domain.InvitationDraft {
|
||||
return outbound.ErrInvitationVersionConflict
|
||||
}
|
||||
repository.state.invitations[next.ID()] = next
|
||||
if termsChanged {
|
||||
repository.state.terms[termsKey{next.ID(), next.TermsVersion()}] = next.Snapshot().Terms
|
||||
}
|
||||
repository.state.events = append(repository.state.events, event)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository testInvitations) NeedVersionExists(_ context.Context, organizationID, needID uuid.UUID, version int64) (bool, error) {
|
||||
return repository.state.needVersions[[3]string{organizationID.String(), needID.String(), fmt.Sprint(version)}], nil
|
||||
}
|
||||
|
||||
func (repository testInvitations) SaveCreationResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, result domain.OrganizationInvitationView) error {
|
||||
if repository.failResultSave {
|
||||
return errors.New("result store failed")
|
||||
}
|
||||
repository.state.results[scope] = result
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository testInvitations) GetCreationResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (domain.OrganizationInvitationView, error) {
|
||||
result, ok := repository.state.results[scope]
|
||||
if !ok {
|
||||
return domain.OrganizationInvitationView{}, outbound.ErrInvitationCreationResultNotFound
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type harness struct {
|
||||
service *Service
|
||||
transactor *testTransactor
|
||||
key domain.CandidateViewPseudonymKey
|
||||
actorID uuid.UUID
|
||||
organizationID uuid.UUID
|
||||
// visible maps a handle of the organization to its candidate.
|
||||
visible map[string]uuid.UUID
|
||||
setTime func(time.Time)
|
||||
}
|
||||
|
||||
func newHarness(t *testing.T) *harness {
|
||||
t.Helper()
|
||||
now := time.Date(2026, time.October, 9, 10, 0, 0, 0, time.UTC)
|
||||
current := now
|
||||
actorID, organizationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7())
|
||||
verifiedAt := now.Add(-time.Hour)
|
||||
state := newTestState()
|
||||
state.users[actorID] = domain.User{ID: actorID, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verifiedAt}
|
||||
owner, err := domain.NewOwnerMembership(organizationID, actorID, now)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOwnerMembership() error = %v", err)
|
||||
}
|
||||
state.memberships[[2]uuid.UUID{organizationID, actorID}] = owner
|
||||
key, err := domain.NewCandidateViewPseudonymKey([]byte(strings.Repeat("invitation-test-key-", 3)))
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
test := &harness{
|
||||
transactor: &testTransactor{state: state, policy: testPolicyVersion(t, now)},
|
||||
key: key, actorID: actorID, organizationID: organizationID, visible: map[string]uuid.UUID{},
|
||||
setTime: func(value time.Time) { current = value },
|
||||
}
|
||||
test.service, err = NewService(Dependencies{
|
||||
Transactor: test.transactor, Keyring: testKeyring{}, PseudonymKey: key, Clock: func() time.Time { return current },
|
||||
Candidates: func(_ context.Context, _ outbound.UnitOfWork, _, organizationID uuid.UUID, handle string) (uuid.UUID, error) {
|
||||
candidateID, ok := test.visible[handle]
|
||||
if !ok || organizationID != test.organizationID {
|
||||
return uuid.Nil, candidateview.ErrCandidateCardNotFound
|
||||
}
|
||||
return candidateID, nil
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewService() error = %v", err)
|
||||
}
|
||||
return test
|
||||
}
|
||||
|
||||
// showCandidate makes a new candidate visible to the organization and returns
|
||||
// the handle of the card.
|
||||
func (test *harness) showCandidate(t *testing.T) (string, uuid.UUID) {
|
||||
t.Helper()
|
||||
candidateID := uuid.Must(uuid.NewV7())
|
||||
handle, err := test.key.ForOrganization(test.organizationID, candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() error = %v", err)
|
||||
}
|
||||
test.visible[handle] = candidateID
|
||||
return handle, candidateID
|
||||
}
|
||||
|
||||
func testPolicyVersion(t *testing.T, at time.Time) domain.PolicyVersion {
|
||||
t.Helper()
|
||||
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV1(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
|
||||
}
|
||||
numbered, err := draft.WithVersion(1)
|
||||
if err != nil {
|
||||
t.Fatalf("WithVersion() error = %v", err)
|
||||
}
|
||||
hash := numbered.DocumentHash()
|
||||
version, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{
|
||||
ID: numbered.ID(), Key: string(numbered.Key()), Version: numbered.Version(), Kind: string(numbered.Kind()),
|
||||
Author: string(numbered.Author()), EffectiveAt: at, CreatedAt: at, Document: numbered.Document(), DocumentHash: hash[:],
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestorePolicyVersion() error = %v", err)
|
||||
}
|
||||
return version
|
||||
}
|
||||
|
||||
func testTerms() domain.InvitationTerms {
|
||||
none := domain.InvitationPackageItem{Status: domain.InvitationPackageNotProvided}
|
||||
return domain.InvitationTerms{
|
||||
RoleTitle: "Middle Go developer", Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle,
|
||||
OfferType: domain.InvitationOfferFullTime, Tasks: []string{"Build the payout service"}, Team: "Six engineers",
|
||||
TechStack: []string{"Go"}, WorkFormats: []domain.NeedWorkFormat{domain.NeedWorkFormatRemote},
|
||||
CommunicationMethod: domain.InvitationCommunicationMethod{Channel: domain.InvitationChannelEmail},
|
||||
Salary: domain.SalaryRange{SalaryFrom: 100_000, SalaryTo: 140_000, Currency: "RUB", Period: "month", TaxBasis: "net"},
|
||||
Package: domain.InvitationPackage{Bonus: none, Equipment: none, Training: none, HealthInsurance: none},
|
||||
}
|
||||
}
|
||||
|
||||
func (test *harness) createCommand(handle, key string) CreateCommand {
|
||||
return CreateCommand{
|
||||
ActorID: test.actorID, OrganizationID: test.organizationID, IdempotencyKey: key,
|
||||
CanonicalBody: []byte(fmt.Sprintf(`{"candidate_handle":%q,"key":%q}`, handle, key)),
|
||||
CandidateHandle: handle, Terms: testTerms(),
|
||||
}
|
||||
}
|
||||
|
||||
func fieldPointer(t *testing.T, err error) string {
|
||||
t.Helper()
|
||||
field, ok := errors.AsType[*domain.InvitationFieldError](err)
|
||||
if !ok {
|
||||
t.Fatalf("error = %v, want a field error", err)
|
||||
}
|
||||
return field.Pointer
|
||||
}
|
||||
|
||||
func TestCreateStoresADraftForAVisibleCandidateWithTheDefaultPeriod(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
handle, candidateID := test.showCandidate(t)
|
||||
view, err := test.service.Create(t.Context(), test.createCommand(handle, "key-1"))
|
||||
if err != nil {
|
||||
t.Fatalf("Create() error = %v", err)
|
||||
}
|
||||
if view.State != domain.InvitationDraft || view.Version != 1 || view.TermsVersion != 1 || view.ResponsePeriodDays != 7 ||
|
||||
view.CandidateHandle != handle || view.SalaryFit != domain.InvitationSalaryNotAvailable ||
|
||||
view.ContactAccess != domain.InvitationContactAccessNone || view.ResponseDeadlineAt != nil {
|
||||
t.Fatalf("created view = %+v, want an unsent version 1 with the default period for the card handle", view.InvitationSnapshot)
|
||||
}
|
||||
state := test.transactor.snapshot()
|
||||
stored := state.invitations[view.ID]
|
||||
if stored.CandidateID() != candidateID || len(state.events) != 1 || state.events[0].Kind != domain.InvitationEventDraftCreated ||
|
||||
state.events[0].ActorID != test.actorID {
|
||||
t.Fatalf("stored candidate/events = %v/%+v, want the resolved candidate and one creation event", stored.CandidateID() == candidateID, state.events)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRefusesEveryCandidateTheOrganizationCannotUseWithTheSamePointer(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
otherOrganization := uuid.Must(uuid.NewV7())
|
||||
foreign, err := test.key.ForOrganization(otherOrganization, uuid.Must(uuid.NewV7()))
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() error = %v", err)
|
||||
}
|
||||
unknown := "cv1_" + strings.Repeat("Z", 43)
|
||||
for name, handle := range map[string]string{"another organization": foreign, "unknown": unknown, "malformed": "not-a-handle"} {
|
||||
command := test.createCommand(handle, "key-"+name)
|
||||
_, err := test.service.Create(t.Context(), command)
|
||||
if pointer := fieldPointer(t, err); pointer != "/candidate_handle" {
|
||||
t.Errorf("%s: pointer = %s, want /candidate_handle", name, pointer)
|
||||
}
|
||||
}
|
||||
state := test.transactor.snapshot()
|
||||
if len(state.invitations) != 0 || len(state.events) != 0 || len(state.idempotency) != 0 || len(state.results) != 0 {
|
||||
t.Fatalf("refused creates left state: %d invitations, %d events, %d keys, %d results", len(state.invitations), len(state.events), len(state.idempotency), len(state.results))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAppliesTheDomainRulesInTheContractOrderAndStoresNothingOnFailure(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
handle, _ := test.showCandidate(t)
|
||||
needID := uuid.Must(uuid.NewV7())
|
||||
|
||||
command := test.createCommand(handle, "key-need")
|
||||
command.Need = &domain.InvitationNeedRef{NeedID: needID, RequirementsVersion: 1}
|
||||
command.Terms.Salary.SalaryTo = 500_000
|
||||
_, err := test.service.Create(t.Context(), command)
|
||||
if pointer := fieldPointer(t, err); pointer != "/need" {
|
||||
t.Fatalf("pointer = %s, want /need before the terms", pointer)
|
||||
}
|
||||
|
||||
test.transactor.state.needVersions[[3]string{test.organizationID.String(), needID.String(), "1"}] = true
|
||||
_, err = test.service.Create(t.Context(), command)
|
||||
if pointer := fieldPointer(t, err); pointer != "/terms/salary/salary_to" {
|
||||
t.Fatalf("pointer = %s, want the salary range", pointer)
|
||||
}
|
||||
|
||||
command = test.createCommand(handle, "key-period")
|
||||
period := int32(5)
|
||||
command.ResponsePeriodDays = &period
|
||||
_, err = test.service.Create(t.Context(), command)
|
||||
if pointer := fieldPointer(t, err); pointer != "/response_period_days" {
|
||||
t.Fatalf("pointer = %s, want /response_period_days", pointer)
|
||||
}
|
||||
if state := test.transactor.snapshot(); len(state.invitations) != 0 || len(state.idempotency) != 0 {
|
||||
t.Fatalf("failed creates stored %d invitations and %d keys", len(state.invitations), len(state.idempotency))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateReplaysTheOriginalResponseAndRejectsAChangedRequest(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
handle, _ := test.showCandidate(t)
|
||||
command := test.createCommand(handle, "key-replay")
|
||||
first, err := test.service.Create(t.Context(), command)
|
||||
if err != nil {
|
||||
t.Fatalf("Create() error = %v", err)
|
||||
}
|
||||
// The candidate stops being visible; the replay still returns the stored
|
||||
// response and creates nothing.
|
||||
delete(test.visible, handle)
|
||||
replay, err := test.service.Create(t.Context(), command)
|
||||
if err != nil || replay.ID != first.ID || replay.Version != 1 {
|
||||
t.Fatalf("replay = %v, %v; want the original draft", replay.ID, err)
|
||||
}
|
||||
changed := command
|
||||
changed.CanonicalBody = []byte(`{"different":true}`)
|
||||
if _, err := test.service.Create(t.Context(), changed); !errors.Is(err, ErrIdempotencyKeyReused) {
|
||||
t.Fatalf("Create(changed body) error = %v, want ErrIdempotencyKeyReused", err)
|
||||
}
|
||||
if state := test.transactor.snapshot(); len(state.invitations) != 1 || len(state.events) != 1 {
|
||||
t.Fatalf("replay stored %d invitations and %d events, want one each", len(state.invitations), len(state.events))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRollbackLeavesNoDraftWhenTheResponseCannotBeStored(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
handle, _ := test.showCandidate(t)
|
||||
test.transactor.failResultSave = true
|
||||
if _, err := test.service.Create(t.Context(), test.createCommand(handle, "key-fail")); err == nil {
|
||||
t.Fatal("Create() succeeded although the response could not be stored")
|
||||
}
|
||||
if state := test.transactor.snapshot(); len(state.invitations) != 0 || len(state.events) != 0 || len(state.idempotency) != 0 {
|
||||
t.Fatalf("failed create left %d invitations, %d events, %d keys", len(state.invitations), len(state.events), len(state.idempotency))
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyTheActiveOwnerOfAnEmployerAccountMayWorkWithInvitations(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
handle, _ := test.showCandidate(t)
|
||||
verified := time.Date(2026, time.October, 9, 9, 0, 0, 0, time.UTC)
|
||||
addAccount := func(scenario domain.Scenario) uuid.UUID {
|
||||
id := uuid.Must(uuid.NewV7())
|
||||
test.transactor.state.users[id] = domain.User{ID: id, Scenario: scenario, EmailVerifiedAt: &verified}
|
||||
return id
|
||||
}
|
||||
recruiter := addAccount(domain.ScenarioEmployer)
|
||||
membership, err := domain.NewMembership(domain.MembershipInput{
|
||||
OrganizationID: test.organizationID, UserID: recruiter, Role: domain.OrganizationRoleRecruiter, At: verified,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewMembership() error = %v", err)
|
||||
}
|
||||
test.transactor.state.memberships[[2]uuid.UUID{test.organizationID, recruiter}] = membership
|
||||
unverified := uuid.Must(uuid.NewV7())
|
||||
test.transactor.state.users[unverified] = domain.User{ID: unverified, Scenario: domain.ScenarioEmployer}
|
||||
ownerMembership, _ := domain.NewOwnerMembership(test.organizationID, unverified, verified)
|
||||
test.transactor.state.memberships[[2]uuid.UUID{test.organizationID, unverified}] = ownerMembership
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
actor uuid.UUID
|
||||
want error
|
||||
}{
|
||||
{"recruiter", recruiter, outbound.ErrOrganizationManagerRequired},
|
||||
{"candidate account", addAccount(domain.ScenarioCandidate), ErrForbidden},
|
||||
{"employer outside the organization", addAccount(domain.ScenarioEmployer), outbound.ErrOrganizationNotFound},
|
||||
{"owner without a confirmed email", unverified, ErrEmailNotVerified},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
command := test.createCommand(handle, "key-"+tt.name)
|
||||
command.ActorID = tt.actor
|
||||
if _, err := test.service.Create(t.Context(), command); !errors.Is(err, tt.want) {
|
||||
t.Errorf("Create() error = %v, want %v", err, tt.want)
|
||||
}
|
||||
if _, err := test.service.List(t.Context(), ListCommand{ActorID: tt.actor, OrganizationID: test.organizationID, Limit: 10}); !errors.Is(err, tt.want) {
|
||||
t.Errorf("List() error = %v, want %v", err, tt.want)
|
||||
}
|
||||
if _, err := test.service.Get(t.Context(), tt.actor, test.organizationID, uuid.New()); !errors.Is(err, tt.want) {
|
||||
t.Errorf("Get() error = %v, want %v", err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
if state := test.transactor.snapshot(); len(state.invitations) != 0 {
|
||||
t.Fatalf("a refused actor created %d invitations", len(state.invitations))
|
||||
}
|
||||
}
|
||||
|
||||
func (test *harness) createDraft(t *testing.T, key string) domain.OrganizationInvitationView {
|
||||
t.Helper()
|
||||
handle, _ := test.showCandidate(t)
|
||||
view, err := test.service.Create(t.Context(), test.createCommand(handle, key))
|
||||
if err != nil {
|
||||
t.Fatalf("Create() error = %v", err)
|
||||
}
|
||||
return view
|
||||
}
|
||||
|
||||
func (test *harness) update(command UpdateCommand) (domain.OrganizationInvitationView, error) {
|
||||
command.ActorID, command.OrganizationID = test.actorID, test.organizationID
|
||||
return test.service.Update(context.Background(), command)
|
||||
}
|
||||
|
||||
func TestUpdateFollowsTheDocumentedOrderOfChecks(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
draft := test.createDraft(t, "key-order")
|
||||
test.setTime(time.Date(2026, time.October, 9, 10, 5, 0, 0, time.UTC))
|
||||
|
||||
changedTerms := testTerms()
|
||||
changedTerms.Salary.SalaryTo = 150_000
|
||||
updated, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 1, Terms: &changedTerms})
|
||||
if err != nil || updated.Version != 2 || updated.TermsVersion != 2 || updated.Terms.Salary.SalaryTo != 150_000 {
|
||||
t.Fatalf("Update(terms) = version %d/%d, %v; want 2/2", updated.Version, updated.TermsVersion, err)
|
||||
}
|
||||
state := test.transactor.snapshot()
|
||||
if first := state.terms[termsKey{draft.ID, 1}]; first.Salary.SalaryTo != 140_000 {
|
||||
t.Fatalf("terms version 1 changed to %d", first.Salary.SalaryTo)
|
||||
}
|
||||
if len(state.events) != 2 || state.events[1].Kind != domain.InvitationEventDraftUpdated ||
|
||||
fmt.Sprint(state.events[1].ChangedFields) != "[terms]" {
|
||||
t.Fatalf("events = %+v, want a draft_updated event for the terms", state.events)
|
||||
}
|
||||
|
||||
// 1. A body that changes nothing answers with the current invitation even
|
||||
// when the version it names is stale.
|
||||
repeated, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 1, Terms: &changedTerms})
|
||||
if err != nil || repeated.Version != 2 {
|
||||
t.Fatalf("Update(retry) = version %d, %v; want the current version 2", repeated.Version, err)
|
||||
}
|
||||
// 2. A stale version beats the domain rules.
|
||||
invalid := testTerms()
|
||||
invalid.Salary.SalaryTo = 500_000
|
||||
if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 1, Terms: &invalid}); !errors.Is(err, domain.ErrInvitationVersionConflict) {
|
||||
t.Fatalf("Update(stale, invalid) error = %v, want a version conflict", err)
|
||||
}
|
||||
// 3. A rule violation of a current version is a field error and changes nothing.
|
||||
_, err = test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 2, Terms: &invalid})
|
||||
if pointer := fieldPointer(t, err); pointer != "/terms/salary/salary_to" {
|
||||
t.Fatalf("pointer = %s, want the salary range", pointer)
|
||||
}
|
||||
// 4. A period outside the policy and an unknown need are field errors.
|
||||
period := int32(5)
|
||||
if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 2, ResponsePeriodDays: &period}); fieldPointer(t, err) != "/response_period_days" {
|
||||
t.Fatalf("Update(period 5) error = %v", err)
|
||||
}
|
||||
need := Field[domain.InvitationNeedRef]{Set: true, Value: domain.InvitationNeedRef{NeedID: uuid.New(), RequirementsVersion: 1}}
|
||||
if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 2, Need: need}); fieldPointer(t, err) != "/need" {
|
||||
t.Fatalf("Update(unknown need) error = %v", err)
|
||||
}
|
||||
if after := test.transactor.snapshot(); after.invitations[draft.ID].Version() != 2 || len(after.events) != 2 {
|
||||
t.Fatalf("rejected updates changed the draft: version %d, %d events", after.invitations[draft.ID].Version(), len(after.events))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateKeepsTheTermsVersionWhenOnlyThePeriodOrTheNeedChanges(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
draft := test.createDraft(t, "key-parts")
|
||||
needID := uuid.Must(uuid.NewV7())
|
||||
test.transactor.state.needVersions[[3]string{test.organizationID.String(), needID.String(), "2"}] = true
|
||||
period := int32(14)
|
||||
linked, err := test.update(UpdateCommand{
|
||||
InvitationID: draft.ID, ExpectedVersion: 1, ResponsePeriodDays: &period,
|
||||
Need: Field[domain.InvitationNeedRef]{Set: true, Value: domain.InvitationNeedRef{NeedID: needID, RequirementsVersion: 2}},
|
||||
})
|
||||
if err != nil || linked.Version != 2 || linked.TermsVersion != 1 || linked.ResponsePeriodDays != 14 ||
|
||||
linked.Need == nil || linked.Need.NeedID != needID {
|
||||
t.Fatalf("Update(period, need) = version %d/%d period %d, %v; want 2/1 with the link", linked.Version, linked.TermsVersion, linked.ResponsePeriodDays, err)
|
||||
}
|
||||
unlinked, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 2, Need: Field[domain.InvitationNeedRef]{Set: true, Null: true}})
|
||||
if err != nil || unlinked.Version != 3 || unlinked.Need != nil || unlinked.TermsVersion != 1 {
|
||||
t.Fatalf("Update(unlink) = version %d need %v, %v; want version 3 without a need", unlinked.Version, unlinked.Need, err)
|
||||
}
|
||||
if state := test.transactor.snapshot(); len(state.terms) != 1 {
|
||||
t.Fatalf("stored %d terms versions, want only the first", len(state.terms))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateRefusesAnInvitationThatLeftTheDraftState(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
draft := test.createDraft(t, "key-state")
|
||||
stored := test.transactor.state.invitations[draft.ID].Stored()
|
||||
stored.State = string(domain.InvitationWithdrawn)
|
||||
withdrawn, err := domain.RestoreInvitation(stored)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreInvitation() error = %v", err)
|
||||
}
|
||||
test.transactor.state.invitations[draft.ID] = withdrawn
|
||||
changed := testTerms()
|
||||
changed.RoleTitle = "Senior Go developer"
|
||||
if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 1, Terms: &changed}); !errors.Is(err, domain.ErrInvitationNotDraft) {
|
||||
t.Fatalf("Update(withdrawn) error = %v, want ErrInvitationNotDraft", err)
|
||||
}
|
||||
// A stale version of a withdrawn invitation is still reported as the state.
|
||||
if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 7, Terms: &changed}); !errors.Is(err, domain.ErrInvitationVersionConflict) {
|
||||
t.Fatalf("Update(stale, withdrawn) error = %v, want the version comparison first", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadsAreScopedToTheOrganizationAndPaged(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
first := test.createDraft(t, "key-1")
|
||||
second := test.createDraft(t, "key-2")
|
||||
third := test.createDraft(t, "key-3")
|
||||
|
||||
if got, err := test.service.Get(t.Context(), test.actorID, test.organizationID, second.ID); err != nil || got.ID != second.ID {
|
||||
t.Fatalf("Get() = %v, %v; want the draft", got.ID, err)
|
||||
}
|
||||
if _, err := test.service.Get(t.Context(), test.actorID, uuid.Must(uuid.NewV7()), second.ID); !errors.Is(err, outbound.ErrOrganizationNotFound) {
|
||||
t.Fatalf("Get(other organization) error = %v, want not found", err)
|
||||
}
|
||||
if _, err := test.service.Get(t.Context(), test.actorID, test.organizationID, uuid.New()); !errors.Is(err, outbound.ErrInvitationNotFound) {
|
||||
t.Fatalf("Get(unknown) error = %v, want not found", err)
|
||||
}
|
||||
page, err := test.service.List(t.Context(), ListCommand{ActorID: test.actorID, OrganizationID: test.organizationID, Limit: 2})
|
||||
if err != nil || len(page.Items) != 2 || !page.HasMore {
|
||||
t.Fatalf("List(2) = %d items more=%t, %v; want a first page of two", len(page.Items), page.HasMore, err)
|
||||
}
|
||||
ids := map[uuid.UUID]bool{first.ID: true, second.ID: true, third.ID: true}
|
||||
for _, item := range page.Items {
|
||||
if !ids[item.ID] || item.CandidateHandle == "" {
|
||||
t.Fatalf("listed item %v is unknown or has no alias", item.ID)
|
||||
}
|
||||
}
|
||||
if _, err := test.service.List(t.Context(), ListCommand{ActorID: test.actorID, OrganizationID: test.organizationID, Limit: 0}); !errors.Is(err, ErrInvalidRequest) {
|
||||
t.Fatalf("List(0) error = %v, want ErrInvalidRequest", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (repository testInvitations) GetTermsVersion(_ context.Context, _, invitationID uuid.UUID, version int64) (domain.InvitationTerms, error) {
|
||||
terms, ok := repository.state.terms[termsKey{invitationID, version}]
|
||||
if !ok {
|
||||
return domain.InvitationTerms{}, outbound.ErrInvitationNotFound
|
||||
}
|
||||
return terms, nil
|
||||
}
|
||||
Reference in new issue
Block a user