feat(invitations): let candidates read, view and decline their invitations

This commit is contained in:
shira committed 2026-10-09 17:25:12 +03:00
1 parent c410636b7f
commit ac57c05aca
27 files changed
+3285 -21

No files matched your search

@@ -0,0 +1,267 @@
package invitation
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func (repository testInvitations) GetCandidateEntry(ctx context.Context, candidateID, invitationID uuid.UUID) (outbound.CandidateInvitationEntry, error) {
invitation, err := repository.GetForCandidate(ctx, candidateID, invitationID)
if err != nil {
return outbound.CandidateInvitationEntry{}, err
}
return outbound.CandidateInvitationEntry{Invitation: invitation, OrganizationName: "Test organization"}, nil
}
func (repository testInvitations) GetCandidateEntryForUpdate(ctx context.Context, candidateID, invitationID uuid.UUID) (outbound.CandidateInvitationEntry, error) {
return repository.GetCandidateEntry(ctx, candidateID, invitationID)
}
func (repository testInvitations) RecordView(_ context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error {
current, ok := repository.state.invitations[next.ID()]
if !ok || current.Version() != expectedVersion || current.State() != domain.InvitationDelivered {
return outbound.ErrInvitationVersionConflict
}
repository.state.invitations[next.ID()] = next
repository.state.events = append(repository.state.events, event)
return nil
}
func (repository testInvitations) Decline(_ context.Context, expectedVersion int64, next domain.Invitation, decline domain.InvitationDecline, event domain.InvitationEvent) error {
current, ok := repository.state.invitations[next.ID()]
if !ok || current.Version() != expectedVersion {
return outbound.ErrInvitationVersionConflict
}
repository.state.invitations[next.ID()] = next
repository.state.declines[next.ID()] = decline
repository.state.events = append(repository.state.events, event)
return nil
}
func (repository testInvitations) GetDecline(_ context.Context, organizationID, invitationID uuid.UUID) (domain.InvitationDecline, error) {
decline, ok := repository.state.declines[invitationID]
if !ok || decline.OrganizationID != organizationID {
return domain.InvitationDecline{}, outbound.ErrInvitationDeclineNotFound
}
return decline, nil
}
func (repository testInvitations) SaveDeclineResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, result outbound.InvitationDeclineResult) error {
repository.state.declineResults[scope] = result
return nil
}
func (repository testInvitations) GetDeclineResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (outbound.InvitationDeclineResult, error) {
result, ok := repository.state.declineResults[scope]
if !ok {
return outbound.InvitationDeclineResult{}, outbound.ErrInvitationDeclineResultNotFound
}
return result, nil
}
// deliveredTo sends a new draft to a new candidate who can sign in and
// returns the delivered invitation with the candidate.
func (test *harness) deliveredTo(t *testing.T) (domain.OrganizationInvitationView, uuid.UUID) {
t.Helper()
draft, _, candidateID := test.draftFor(t, nil)
sent, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-"+draft.ID.String()))
if err != nil {
t.Fatalf("Send() error = %v", err)
}
verified := time.Date(2026, time.October, 9, 9, 0, 0, 0, time.UTC)
test.transactor.mu.Lock()
test.transactor.state.users[candidateID] = domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &verified}
test.transactor.mu.Unlock()
return sent, candidateID
}
func declineCommand(actorID, invitationID uuid.UUID, version int64, key string, reason domain.InvitationDeclineReason, comment *string) DeclineCommand {
return DeclineCommand{
ActorID: actorID, InvitationID: invitationID, IdempotencyKey: key, ExpectedVersion: version,
Choice: domain.InvitationDeclineChoice{Reason: reason, Comment: comment},
}
}
func TestGetMineHasNoSideEffectAndViewMineKeepsTheDeadline(t *testing.T) {
test := newHarness(t)
sent, candidateID := test.deliveredTo(t)
events := len(test.transactor.snapshot().events)
read, err := test.service.GetMine(t.Context(), candidateID, sent.ID)
if err != nil {
t.Fatalf("GetMine() error = %v", err)
}
if read.State != domain.InvitationDelivered || read.Version != sent.Version || read.ViewedAt != nil || read.Decline != nil ||
read.Organization.ID != test.organizationID || read.Organization.Name == "" || read.Terms.RoleTitle == "" {
t.Fatalf("read = %+v, want the delivered invitation unchanged", read)
}
if len(test.transactor.snapshot().events) != events {
t.Fatal("a read recorded an event")
}
viewedAt := sent.DeliveredAt.Add(time.Hour)
test.setTime(viewedAt)
viewed, err := test.service.ViewMine(t.Context(), candidateID, sent.ID)
if err != nil {
t.Fatalf("ViewMine() error = %v", err)
}
if viewed.State != domain.InvitationViewed || viewed.Version != sent.Version+1 || viewed.TermsVersion != sent.TermsVersion ||
viewed.ViewedAt == nil || !viewed.ViewedAt.Equal(viewedAt) || !viewed.ResponseDeadlineAt.Equal(*sent.ResponseDeadlineAt) {
t.Fatalf("viewed = %+v, want viewed now with the deadline of the delivery", viewed)
}
state := test.transactor.snapshot()
last := state.events[len(state.events)-1]
if len(state.events) != events+1 || last.Kind != domain.InvitationEventViewed || last.ActorID != candidateID || last.Version != viewed.Version {
t.Fatalf("events = %+v, want one view event by the candidate", state.events[events:])
}
// A repeat changes nothing and records nothing.
test.setTime(viewedAt.Add(time.Hour))
again, err := test.service.ViewMine(t.Context(), candidateID, sent.ID)
if err != nil || again.Version != viewed.Version || !again.ViewedAt.Equal(viewedAt) {
t.Fatalf("repeated view = %+v, %v; want the first view", again, err)
}
if len(test.transactor.snapshot().events) != events+1 {
t.Fatal("a repeated view recorded an event")
}
}
func TestViewMineAtTheDeadlineChangesNothing(t *testing.T) {
test := newHarness(t)
sent, candidateID := test.deliveredTo(t)
test.setTime(*sent.ResponseDeadlineAt)
view, err := test.service.ViewMine(t.Context(), candidateID, sent.ID)
if err != nil || view.State != domain.InvitationDelivered || view.Version != sent.Version || view.ViewedAt != nil {
t.Fatalf("late view = %+v, %v; want the delivered invitation unchanged", view, err)
}
}
func TestDeclineMineWithOtherAndNoCommentIsAStoredAnswer(t *testing.T) {
test := newHarness(t)
sent, candidateID := test.deliveredTo(t)
notified := len(test.transactor.snapshot().notified)
declinedAt := sent.DeliveredAt.Add(2 * time.Hour)
test.setTime(declinedAt)
command := declineCommand(candidateID, sent.ID, sent.Version, "decline-1", domain.InvitationDeclineOther, nil)
declined, err := test.service.DeclineMine(t.Context(), command)
if err != nil {
t.Fatalf("DeclineMine() error = %v", err)
}
if declined.State != domain.InvitationDeclined || declined.Version != sent.Version+1 || declined.RespondedAt == nil ||
!declined.RespondedAt.Equal(declinedAt) || declined.Decline == nil || declined.Decline.Reason != domain.InvitationDeclineOther ||
declined.Decline.Comment != nil || !declined.Decline.DeclinedAt.Equal(declinedAt) ||
!declined.ResponseDeadlineAt.Equal(*sent.ResponseDeadlineAt) {
t.Fatalf("declined = %+v, want declined now with the reason other and no comment", declined)
}
state := test.transactor.snapshot()
last := state.events[len(state.events)-1]
if last.Kind != domain.InvitationEventDeclined || last.ActorID != candidateID || last.Version != declined.Version ||
len(last.ChangedFields) != 0 || len(state.notified) != notified {
t.Fatalf("event %+v and %d notifications, want one decline event and no notification", last, len(state.notified)-notified)
}
// The same key replays, and the same decline under a new key with the
// older version answers with the declined invitation.
test.setTime(declinedAt.Add(time.Hour))
for _, repeat := range []DeclineCommand{command, declineCommand(candidateID, sent.ID, sent.Version, "decline-2", domain.InvitationDeclineOther, nil)} {
again, err := test.service.DeclineMine(t.Context(), repeat)
if err != nil || again.Version != declined.Version || !again.Decline.DeclinedAt.Equal(declinedAt) {
t.Fatalf("repeat %s = %+v, %v; want the original decline", repeat.IdempotencyKey, again, err)
}
}
if events := len(test.transactor.snapshot().events); events != len(state.events) {
t.Fatalf("repeats recorded %d events", events-len(state.events))
}
comment := "Не подходит стек"
if _, err := test.service.DeclineMine(t.Context(), declineCommand(candidateID, sent.ID, declined.Version, "decline-3", domain.InvitationDeclineOther, &comment)); !errors.Is(err, ErrAnswerBlocked) {
t.Fatalf("another comment on a declined invitation error = %v, want ErrAnswerBlocked", err)
}
if _, err := test.service.DeclineMine(t.Context(), declineCommand(candidateID, sent.ID, sent.Version, "decline-1", domain.InvitationDeclineSalary, nil)); !errors.Is(err, ErrIdempotencyKeyReused) {
t.Fatalf("the same key with another reason error = %v, want ErrIdempotencyKeyReused", err)
}
}
func TestDeclineMineFollowsTheOrderOfChecks(t *testing.T) {
test := newHarness(t)
sent, candidateID := test.deliveredTo(t)
// A stale version answers 412 and is not stored under the key.
if _, err := test.service.DeclineMine(t.Context(), declineCommand(candidateID, sent.ID, sent.Version+1, "stale", domain.InvitationDeclineStack, nil)); !errors.Is(err, domain.ErrInvitationVersionConflict) {
t.Fatalf("stale decline error = %v, want ErrInvitationVersionConflict", err)
}
if state := test.transactor.snapshot(); len(state.declineResults) != 0 || state.invitations[sent.ID].State() != domain.InvitationDelivered {
t.Fatal("a stale decline stored an outcome or changed the invitation")
}
// At the deadline a decline is late whatever the version, and the
// refusal is stored.
test.setTime(*sent.ResponseDeadlineAt)
late := declineCommand(candidateID, sent.ID, sent.Version+5, "late", domain.InvitationDeclineStack, nil)
for range 2 {
if _, err := test.service.DeclineMine(t.Context(), late); !errors.Is(err, ErrAnswerBlocked) {
t.Fatalf("late decline error = %v, want ErrAnswerBlocked", err)
}
}
if state := test.transactor.snapshot(); len(state.declineResults) != 1 || state.invitations[sent.ID].State() != domain.InvitationDelivered {
t.Fatal("a late decline was not stored once or changed the invitation")
}
// An unknown identifier is not found and stored as well.
unknown := declineCommand(candidateID, uuid.New(), 1, "unknown", domain.InvitationDeclineOther, nil)
for range 2 {
if _, err := test.service.DeclineMine(t.Context(), unknown); !errors.Is(err, outbound.ErrInvitationNotFound) {
t.Fatalf("unknown decline error = %v, want ErrInvitationNotFound", err)
}
}
}
func TestCandidateCommandsShowNothingOfAnotherCandidatesInvitation(t *testing.T) {
test := newHarness(t)
sent, _ := test.deliveredTo(t)
_, stranger := test.deliveredTo(t)
draft, _, _ := test.draftFor(t, nil)
for name, invitationID := range map[string]uuid.UUID{"of another candidate": sent.ID, "draft": draft.ID, "unknown": uuid.New()} {
if _, err := test.service.GetMine(t.Context(), stranger, invitationID); !errors.Is(err, outbound.ErrInvitationNotFound) {
t.Errorf("GetMine(%s) error = %v, want ErrInvitationNotFound", name, err)
}
if _, err := test.service.ViewMine(t.Context(), stranger, invitationID); !errors.Is(err, outbound.ErrInvitationNotFound) {
t.Errorf("ViewMine(%s) error = %v, want ErrInvitationNotFound", name, err)
}
if _, err := test.service.DeclineMine(t.Context(), declineCommand(stranger, invitationID, 2, "foreign-"+name, domain.InvitationDeclineOther, nil)); !errors.Is(err, outbound.ErrInvitationNotFound) {
t.Errorf("DeclineMine(%s) error = %v, want ErrInvitationNotFound", name, err)
}
}
// The employer that sent it has no candidate inbox.
if _, err := test.service.GetMine(t.Context(), test.actorID, sent.ID); !errors.Is(err, ErrForbidden) {
t.Fatalf("GetMine(employer) error = %v, want ErrForbidden", err)
}
if _, err := test.service.DeclineMine(t.Context(), declineCommand(test.actorID, sent.ID, sent.Version, "employer", domain.InvitationDeclineOther, nil)); !errors.Is(err, ErrForbidden) {
t.Fatalf("DeclineMine(employer) error = %v, want ErrForbidden", err)
}
if state := test.transactor.snapshot(); state.invitations[sent.ID].State() != domain.InvitationDelivered {
t.Fatal("a foreign caller changed the invitation")
}
}
func TestDeclineMineRefusesAnUnstorableCommentBeforeAnyRead(t *testing.T) {
test := newHarness(t)
sent, candidateID := test.deliveredTo(t)
for name, comment := range map[string]string{"only non-breaking spaces": "  ", "NUL": "ok\x00", "too long": strings.Repeat("я", 501)} {
_, err := test.service.DeclineMine(t.Context(), declineCommand(candidateID, sent.ID, sent.Version, "bad-"+name, domain.InvitationDeclineOther, &comment))
if pointer := fieldPointer(t, err); pointer != "/comment" {
t.Errorf("%s: pointer = %s, want /comment", name, pointer)
}
}
if state := test.transactor.snapshot(); len(state.declineResults) != 0 || len(state.declines) != 0 {
t.Fatal("an invalid comment stored an outcome or a decline")
}
}
@@ -0,0 +1,298 @@
package invitation
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// ErrAnswerBlocked reports a candidate answer that the state of the invitation
// or its deadline does not allow: a terminal state, another reason or comment
// on a declined invitation, a state without an open answer, or a command at
// the deadline or later. The API answers 409 state_conflict.
var ErrAnswerBlocked = errors.New("candidate invitation answer is not allowed")
const (
declineOperation = "candidate_invitation.decline"
declineLocation = "invitation.Service.DeclineMine"
)
// DeclineCommand binds the session candidate and the path to one structured
// decline over the invitation version the client read.
type DeclineCommand struct {
ActorID uuid.UUID
InvitationID uuid.UUID
IdempotencyKey string
ExpectedVersion int64
Choice domain.InvitationDeclineChoice
}
type declineRequest struct {
fingerprint [outbound.IdempotencyDigestSize]byte
scope [outbound.IdempotencyDigestSize]byte
record outbound.IdempotencyRecord
now time.Time
}
// declineOutcome is what a committed decline transaction decided: the
// invitation, or a refusal that the contract stores under the key and that
// the caller returns after the commit.
type declineOutcome struct {
view domain.CandidateInvitationView
refusal error
}
// declineFingerprint is the canonical request of a decline. An absent comment
// and null are the same request.
type declineFingerprint struct {
InvitationID uuid.UUID `json:"invitation_id"`
ExpectedVersion int64 `json:"expected_version"`
Reason domain.InvitationDeclineReason `json:"reason"`
Comment *string `json:"comment"`
}
// DeclineMine declines an invitation of the session candidate with a
// structured reason. In one transaction it checks the candidate, the key,
// the invitation, the repeat of the same decline, a terminal state or a
// passed deadline, the version, and the state, then moves the invitation to
// declined, stores the decline, and appends the audit event. The decline is
// the candidate's answer for the responsiveness metrics; it creates no
// consent and no contact grant, and the organization sees only the state and
// the time of the answer.
//
// Locks: the idempotency record of the candidate's own key and then only the
// invitation row, never the organization, as for the view.
func (service *Service) DeclineMine(ctx context.Context, command DeclineCommand) (domain.CandidateInvitationView, error) {
request, err := service.prepareDecline(command)
if err != nil {
return domain.CandidateInvitationView{}, err
}
var outcome declineOutcome
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
outcome, err = service.declineInTransaction(ctx, unit, command, request)
return err
})
if err != nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - run transaction: %w", declineLocation, err)
}
if outcome.refusal != nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - %w", declineLocation, outcome.refusal)
}
return outcome.view, nil
}
// prepareDecline validates the request before any storage is read, in the
// order of the contract: the request is validated before the account.
func (service *Service) prepareDecline(command DeclineCommand) (declineRequest, error) {
const location = "invitation.Service.prepareDecline"
switch {
case command.ActorID == uuid.Nil:
return declineRequest{}, fmt.Errorf("%s - actor ID must be set: %w", location, ErrForbidden)
case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize:
return declineRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey)
case command.ExpectedVersion < 1:
return declineRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: "/expected_version", Reason: "must be positive"})
}
if err := command.Choice.Validate(); err != nil {
return declineRequest{}, fmt.Errorf("%s - validate choice: %w", location, err)
}
now, err := service.now(location)
if err != nil {
return declineRequest{}, err
}
// The fingerprint covers the path and the body, so one key used for
// another invitation, version, reason, or comment is a reused key.
canonical, err := json.Marshal(declineFingerprint{
InvitationID: command.InvitationID, ExpectedVersion: command.ExpectedVersion,
Reason: command.Choice.Reason, Comment: command.Choice.Comment,
})
if err != nil {
return declineRequest{}, fmt.Errorf("%s - encode canonical request: %w", location, err)
}
fingerprint := service.keyring.Fingerprint(canonical)
scope := service.keyring.IdempotencyScope(declineOperation, command.IdempotencyKey, command.ActorID.String())
return declineRequest{
fingerprint: fingerprint, scope: scope, now: now,
record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention)},
}, nil
}
// declineInTransaction follows the order of checks of the contract after the
// HTTP boundary: the account (403), the key (422 or a replay), the invitation
// (404, stored), the repeat of the same decline (200), a terminal state or a
// passed deadline (409 whatever the version, stored), the version (412, not
// stored), and any other state without an open answer (409, stored).
func (service *Service) declineInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
command DeclineCommand,
request declineRequest,
) (declineOutcome, error) {
if err := authorizeCandidate(ctx, unit, command.ActorID); err != nil {
return declineOutcome{}, err
}
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
if err != nil {
return declineOutcome{}, fmt.Errorf("%s - reserve idempotency record: %w", declineLocation, err)
}
if !created {
return replayDecline(ctx, unit, request, command, stored)
}
entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, true)
if errors.Is(err, outbound.ErrInvitationNotFound) {
return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineNotFound)
}
if err != nil {
return declineOutcome{}, err
}
return service.declineFound(ctx, unit, command, request, entry)
}
// declineFound applies the checks that follow a found invitation: the repeat
// of the same decline, a terminal state or a passed deadline, the version,
// and the state, and then stores the decline.
func (service *Service) declineFound(
ctx context.Context,
unit outbound.UnitOfWork,
command DeclineCommand,
request declineRequest,
entry outbound.CandidateInvitationEntry,
) (declineOutcome, error) {
current := entry.Invitation
at := notBefore(request.now, current.UpdatedAt())
if current.State() == domain.InvitationDeclined {
previous, err := unit.Invitations().GetDecline(ctx, current.OrganizationID(), current.ID())
if err != nil {
return declineOutcome{}, fmt.Errorf("%s - read decline: %w", declineLocation, err)
}
if previous.Choice.Equal(command.Choice) {
// The same decline answers with the invitation as it is, whatever
// the key or the version, and records nothing again.
return completeDecline(ctx, unit, request, entry)
}
return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineStateConflict)
}
if current.IsTerminal() || current.ResponseDeadlinePassed(at) {
return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineStateConflict)
}
if command.ExpectedVersion != current.Version() {
return declineOutcome{}, fmt.Errorf("%s - compare expected version: %w", declineLocation, domain.ErrInvitationVersionConflict)
}
declined, decline, err := current.Decline(command.Choice, at)
if errors.Is(err, domain.ErrInvitationNotAnswerable) {
return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineStateConflict)
}
if err != nil {
return declineOutcome{}, fmt.Errorf("%s - decline invitation: %w", declineLocation, err)
}
event, err := declined.AnswerEvent(command.ActorID)
if err != nil {
return declineOutcome{}, fmt.Errorf("%s - build audit event: %w", declineLocation, err)
}
if err := unit.Invitations().Decline(ctx, current.Version(), declined, decline, event); err != nil {
if errors.Is(err, outbound.ErrInvitationVersionConflict) {
return declineOutcome{}, fmt.Errorf("%s - store decline: %w", declineLocation, domain.ErrInvitationVersionConflict)
}
return declineOutcome{}, fmt.Errorf("%s - store decline: %w", declineLocation, err)
}
entry.Invitation = declined
return completeDecline(ctx, unit, request, entry)
}
// completeDecline stores the successful outcome under the key and builds the
// response with the stored decline.
func completeDecline(
ctx context.Context,
unit outbound.UnitOfWork,
request declineRequest,
entry outbound.CandidateInvitationEntry,
) (declineOutcome, error) {
view, err := candidateView(ctx, unit, entry)
if err != nil {
return declineOutcome{}, err
}
result := outbound.InvitationDeclineResult{InvitationID: entry.Invitation.ID(), Outcome: outbound.InvitationDeclineDeclined}
if err := finishDecline(ctx, unit, request, result); err != nil {
return declineOutcome{}, err
}
return declineOutcome{view: view}, nil
}
// refuseDecline stores a refusal that the contract keeps under the key and
// lets the transaction commit, since nothing else was written.
func refuseDecline(
ctx context.Context,
unit outbound.UnitOfWork,
command DeclineCommand,
request declineRequest,
outcome outbound.InvitationDeclineOutcome,
) (declineOutcome, error) {
result := outbound.InvitationDeclineResult{InvitationID: command.InvitationID, Outcome: outcome}
if err := finishDecline(ctx, unit, request, result); err != nil {
return declineOutcome{}, err
}
return declineOutcome{refusal: declineRefusal(outcome)}, nil
}
func finishDecline(ctx context.Context, unit outbound.UnitOfWork, request declineRequest, result outbound.InvitationDeclineResult) error {
if err := unit.InvitationDeclineResults().SaveDeclineResult(ctx, request.scope, result); err != nil {
return fmt.Errorf("%s - store outcome: %w", declineLocation, err)
}
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
return fmt.Errorf("%s - purge expired idempotency records: %w", declineLocation, err)
}
return nil
}
func declineRefusal(outcome outbound.InvitationDeclineOutcome) error {
if outcome == outbound.InvitationDeclineNotFound {
return outbound.ErrInvitationNotFound
}
return ErrAnswerBlocked
}
// replayDecline returns the stored outcome of the same request, or refuses a
// key used with another request. A stored success is rebuilt from the
// declined invitation and its decline: both are final, so the replay shows
// the same answer without a second copy of the comment.
func replayDecline(
ctx context.Context,
unit outbound.UnitOfWork,
request declineRequest,
command DeclineCommand,
stored outbound.IdempotencyRecord,
) (declineOutcome, error) {
if stored.Fingerprint != request.fingerprint {
return declineOutcome{}, fmt.Errorf("%s - compare request fingerprint: %w", declineLocation, ErrIdempotencyKeyReused)
}
original, err := unit.InvitationDeclineResults().GetDeclineResult(ctx, request.scope)
if err != nil {
return declineOutcome{}, fmt.Errorf("%s - read original outcome: %w", declineLocation, err)
}
if original.InvitationID != command.InvitationID {
return declineOutcome{}, fmt.Errorf("%s - validate original outcome: %w", declineLocation, domain.ErrInvalidInvitation)
}
if original.Outcome != outbound.InvitationDeclineDeclined {
return declineOutcome{refusal: declineRefusal(original.Outcome)}, nil
}
entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, false)
if err != nil {
return declineOutcome{}, err
}
if entry.Invitation.State() != domain.InvitationDeclined {
return declineOutcome{}, fmt.Errorf("%s - validate original response: %w", declineLocation, domain.ErrInvalidInvitation)
}
view, err := candidateView(ctx, unit, entry)
if err != nil {
return declineOutcome{}, err
}
return declineOutcome{view: view}, nil
}
@@ -1,9 +1,11 @@
// Package invitation applies the owner-only rules of invitation drafts and of
// their sending: the terms and their immutable versions, the link to a
// candidate card of the organization, the idempotent creation, and the
// idempotent send that delivers a draft to the candidate's inbox. It also
// lists that inbox for the candidate. The candidate's answers and the contact
// grant belong to later operations that build on the same records.
// idempotent send that delivers a draft to the candidate's inbox. On the
// candidate's side it lists that inbox, reads one invitation, records the
// view, and records a structured decline. The acceptance, the cancellation,
// and the contact grant belong to later operations that build on the same
// records.
package invitation
import (
@@ -92,7 +94,7 @@ type Dependencies struct {
}
// Service applies organization-scoped invitation commands and reads, and the
// candidate's read of the own inbox.
// candidate's reads, view, and decline of the own invitations.
type Service struct {
transactor outbound.Transactor
keyring Keyring
@@ -43,6 +43,10 @@ type testState struct {
results map[[outbound.IdempotencyDigestSize]byte]domain.OrganizationInvitationView
sendResults map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationSendResult
needVersions map[[3]string]bool
// declines holds the stored declines by invitation, and declineResults
// the decline outcomes kept under a key.
declines map[uuid.UUID]domain.InvitationDecline
declineResults map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationDeclineResult
// charged lists the invitations charged against the organization quota,
// and notified the delivered invitations that were notified.
charged []uuid.UUID
@@ -53,10 +57,12 @@ 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{},
sendResults: map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationSendResult{},
needVersions: map[[3]string]bool{},
idempotency: map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord{},
results: map[[outbound.IdempotencyDigestSize]byte]domain.OrganizationInvitationView{},
sendResults: map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationSendResult{},
needVersions: map[[3]string]bool{},
declines: map[uuid.UUID]domain.InvitationDecline{},
declineResults: map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationDeclineResult{},
}
}
@@ -87,6 +93,12 @@ func (state testState) clone() testState {
for key, found := range state.needVersions {
cloned.needVersions[key] = found
}
for id, decline := range state.declines {
cloned.declines[id] = decline
}
for scope, result := range state.declineResults {
cloned.declineResults[scope] = result
}
cloned.charged = slices.Clone(state.charged)
cloned.notified = slices.Clone(state.notified)
return cloned
@@ -143,6 +155,9 @@ func (unit *testUnit) InvitationCreationResults() outbound.InvitationCreationRes
func (unit *testUnit) InvitationSendResults() outbound.InvitationSendResultRepository {
return testInvitations{state: unit.state}
}
func (unit *testUnit) InvitationDeclineResults() outbound.InvitationDeclineResultRepository {
return testInvitations{state: unit.state}
}
type testUsers struct {
outbound.UserRepository
@@ -217,6 +232,7 @@ func (repository testIdempotency) PurgeExpired(_ context.Context, at time.Time,
delete(repository.state.idempotency, scope)
delete(repository.state.results, scope)
delete(repository.state.sendResults, scope)
delete(repository.state.declineResults, scope)
deleted++
}
}
+152
View File
@@ -0,0 +1,152 @@
package invitation
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const (
getMineLocation = "invitation.Service.GetMine"
viewMineLocation = "invitation.Service.ViewMine"
)
// GetMine reads one invitation delivered to the session candidate with the
// current terms. Reading has no side effect: it never records a view, so a
// prefetch or a cache refresh never changes what the organization sees. A
// draft, an invitation of another candidate, and an unknown identifier are
// not found alike.
func (service *Service) GetMine(ctx context.Context, actorID, invitationID uuid.UUID) (domain.CandidateInvitationView, error) {
if actorID == uuid.Nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - actor ID must be set: %w", getMineLocation, ErrForbidden)
}
var view domain.CandidateInvitationView
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := authorizeCandidate(ctx, unit, actorID); err != nil {
return err
}
entry, err := readCandidateEntry(ctx, unit, actorID, invitationID, false)
if err != nil {
return err
}
view, err = candidateView(ctx, unit, entry)
return err
})
if err != nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - run transaction: %w", getMineLocation, err)
}
return view, nil
}
// ViewMine records that the session candidate opened the terms. A delivered
// invitation moves to viewed with the next version and keeps its deadline;
// every other state, and a view at the deadline or later, changes nothing and
// returns the invitation as it is. The command is idempotent by its effect,
// so it takes neither a key nor an expected version.
//
// Locks: only the invitation row, never the organization. A candidate
// command therefore never holds the row while it waits for an organization
// lock, and an organization command that holds the organization lock and
// waits for the row cannot deadlock with it.
func (service *Service) ViewMine(ctx context.Context, actorID, invitationID uuid.UUID) (domain.CandidateInvitationView, error) {
if actorID == uuid.Nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - actor ID must be set: %w", viewMineLocation, ErrForbidden)
}
now, err := service.now(viewMineLocation)
if err != nil {
return domain.CandidateInvitationView{}, err
}
var view domain.CandidateInvitationView
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := authorizeCandidate(ctx, unit, actorID); err != nil {
return err
}
entry, err := readCandidateEntry(ctx, unit, actorID, invitationID, true)
if err != nil {
return err
}
current := entry.Invitation
viewed, changed, err := current.RecordView(notBefore(now, current.UpdatedAt()))
if err != nil {
return fmt.Errorf("%s - record view: %w", viewMineLocation, err)
}
if changed {
event, err := viewed.AnswerEvent(actorID)
if err != nil {
return fmt.Errorf("%s - build audit event: %w", viewMineLocation, err)
}
if err := unit.Invitations().RecordView(ctx, current.Version(), viewed, event); err != nil {
return fmt.Errorf("%s - store view: %w", viewMineLocation, err)
}
entry.Invitation = viewed
}
view, err = candidateView(ctx, unit, entry)
return err
})
if err != nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - run transaction: %w", viewMineLocation, err)
}
return view, nil
}
// readCandidateEntry reads, and with forUpdate locks, a delivered invitation
// addressed to the candidate. The nil identifier finds nothing.
func readCandidateEntry(
ctx context.Context,
unit outbound.UnitOfWork,
actorID, invitationID uuid.UUID,
forUpdate bool,
) (outbound.CandidateInvitationEntry, error) {
const location = "invitation.readCandidateEntry"
if invitationID == uuid.Nil {
return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - the nil identifier names no invitation: %w", location, outbound.ErrInvitationNotFound)
}
read := unit.Invitations().GetCandidateEntry
if forUpdate {
read = unit.Invitations().GetCandidateEntryForUpdate
}
entry, err := read(ctx, actorID, invitationID)
if err != nil {
return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - read invitation: %w", location, err)
}
return entry, nil
}
// candidateView builds the candidate's response with the own decline of a
// declined invitation. The organization is shown by its current name even
// when the candidate has hidden the profile from it: the hiding stops the
// organization from seeing the candidate, while the candidate needs to know
// who sent the offer to answer it. Pushed content, such as the inbox
// notification, follows the hiding instead.
func candidateView(ctx context.Context, unit outbound.UnitOfWork, entry outbound.CandidateInvitationEntry) (domain.CandidateInvitationView, error) {
const location = "invitation.candidateView"
var decline *domain.InvitationDecline
if entry.Invitation.State() == domain.InvitationDeclined {
stored, err := unit.Invitations().GetDecline(ctx, entry.Invitation.OrganizationID(), entry.Invitation.ID())
if err != nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - read decline: %w", location, err)
}
decline = &stored
}
view, err := entry.Invitation.CandidateView(domain.InvitationOrganizationRef{
ID: entry.Invitation.OrganizationID(), Name: entry.OrganizationName,
}, decline)
if err != nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - build view: %w", location, err)
}
return view, nil
}
// notBefore keeps a clock that stepped back from recording a change before
// the last one.
func notBefore(now, last time.Time) time.Time {
if now.Before(last) {
return last
}
return now
}