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

@@ -19,7 +19,7 @@ import (
const defaultInvitationLimit = 20
// InvitationOperations are the owner-scoped invitation reads and commands and
// the candidate's read of the own inbox served by HTTP.
// the candidate's inbox, read, view, and decline served by HTTP.
type InvitationOperations interface {
Create(ctx context.Context, command invitationusecase.CreateCommand) (domain.OrganizationInvitationView, error)
Get(ctx context.Context, actorID, organizationID, invitationID uuid.UUID) (domain.OrganizationInvitationView, error)
@@ -27,6 +27,9 @@ type InvitationOperations interface {
Update(ctx context.Context, command invitationusecase.UpdateCommand) (domain.OrganizationInvitationView, error)
Send(ctx context.Context, command invitationusecase.SendCommand) (domain.OrganizationInvitationView, error)
ListMine(ctx context.Context, command invitationusecase.CandidateListCommand) (invitationusecase.CandidatePage, error)
GetMine(ctx context.Context, actorID, invitationID uuid.UUID) (domain.CandidateInvitationView, error)
ViewMine(ctx context.Context, actorID, invitationID uuid.UUID) (domain.CandidateInvitationView, error)
DeclineMine(ctx context.Context, command invitationusecase.DeclineCommand) (domain.CandidateInvitationView, error)
}
// InvitationHandler serves the organization side of invitation drafts and
@@ -0,0 +1,156 @@
package v1
import (
"context"
"errors"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
invitationusecase "lincodex/backend/internal/usecase/invitation"
)
func (handler *Handler) GetMyInvitation(ctx context.Context, params api.GetMyInvitationParams) (api.GetMyInvitationRes, error) {
if handler.invitation == nil {
return handler.UnimplementedHandler.GetMyInvitation(ctx, params)
}
return handler.invitation.GetMyInvitation(ctx, params)
}
func (handler *Handler) ViewMyInvitation(ctx context.Context, params api.ViewMyInvitationParams) (api.ViewMyInvitationRes, error) {
if handler.invitation == nil {
return handler.UnimplementedHandler.ViewMyInvitation(ctx, params)
}
return handler.invitation.ViewMyInvitation(ctx, params)
}
func (handler *Handler) DeclineMyInvitation(ctx context.Context, request *api.InvitationDeclineRequest, params api.DeclineMyInvitationParams) (api.DeclineMyInvitationRes, error) {
if handler.invitation == nil {
return handler.UnimplementedHandler.DeclineMyInvitation(ctx, request, params)
}
return handler.invitation.DeclineMyInvitation(ctx, request, params)
}
func (handler *InvitationHandler) GetMyInvitation(ctx context.Context, params api.GetMyInvitationParams) (api.GetMyInvitationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetMyInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
view, err := handler.operations.GetMine(ctx, principal.UserID, params.InvitationID)
if err != nil {
switch classifyInvitationError(err) {
case invitationFailureForbidden:
return (*api.GetMyInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case invitationFailureNotFound:
return (*api.GetMyInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case invitationFailureKeyReused, invitationFailureBadKey, invitationFailureInvalid,
invitationFailureVersionConflict, invitationFailureStateConflict, invitationFailureOther:
return nil, err
}
return nil, err
}
return &api.CandidateInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: candidateInvitationResponse(view)}, nil
}
func (handler *InvitationHandler) ViewMyInvitation(ctx context.Context, params api.ViewMyInvitationParams) (api.ViewMyInvitationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ViewMyInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
view, err := handler.operations.ViewMine(ctx, principal.UserID, params.InvitationID)
if err != nil {
switch classifyInvitationError(err) {
case invitationFailureForbidden:
return (*api.ViewMyInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case invitationFailureNotFound:
return (*api.ViewMyInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case invitationFailureKeyReused, invitationFailureBadKey, invitationFailureInvalid,
invitationFailureVersionConflict, invitationFailureStateConflict, invitationFailureOther:
return nil, err
}
return nil, err
}
return &api.CandidateInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: candidateInvitationResponse(view)}, nil
}
func (handler *InvitationHandler) DeclineMyInvitation(
ctx context.Context,
request *api.InvitationDeclineRequest,
params api.DeclineMyInvitationParams,
) (api.DeclineMyInvitationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.DeclineMyInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return (*api.DeclineMyInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
choice := domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineReason(request.Reason)}
if comment, set := request.Comment.Get(); set {
text := string(comment)
choice.Comment = &text
}
view, err := handler.operations.DeclineMine(ctx, invitationusecase.DeclineCommand{
ActorID: principal.UserID, InvitationID: params.InvitationID, IdempotencyKey: params.IdempotencyKey,
ExpectedVersion: int64(request.ExpectedVersion), Choice: choice,
})
if err != nil {
return invitationDeclineFailure(ctx, err)
}
return &api.CandidateInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: candidateInvitationResponse(view)}, nil
}
func invitationDeclineFailure(ctx context.Context, err error) (api.DeclineMyInvitationRes, error) {
if errors.Is(err, invitationusecase.ErrAnswerBlocked) {
return (*api.DeclineMyInvitationConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
}
switch classifyInvitationError(err) {
case invitationFailureForbidden:
return (*api.DeclineMyInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case invitationFailureNotFound:
return (*api.DeclineMyInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case invitationFailureKeyReused:
return (*api.DeclineMyInvitationUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
case invitationFailureBadKey:
return (*api.DeclineMyInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
case invitationFailureInvalid:
return (*api.DeclineMyInvitationBadRequest)(invitationValidationProblem(ctx, err)), nil
case invitationFailureVersionConflict:
return (*api.DeclineMyInvitationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case invitationFailureStateConflict, invitationFailureOther:
return nil, err
}
return nil, err
}
// candidateInvitationResponse maps the candidate's view. The consent offer
// and the contact grant belong to the acceptance, which is not served yet,
// so an acceptance is impossible now and both are null, as the contract
// requires when no acceptance can be made.
func candidateInvitationResponse(view domain.CandidateInvitationView) api.CandidateInvitation {
response := api.CandidateInvitation{
ID: view.ID,
Organization: api.InvitationOrganization{ID: view.Organization.ID, Name: view.Organization.Name},
State: api.InvitationState(view.State), ExpiryReason: invitationExpiryResponse(view.ExpiryReason),
Version: api.InvitationVersion(view.Version), TermsVersion: api.InvitationTermsVersion(view.TermsVersion),
Terms: invitationTermsResponse(view.Terms), ResponseDeadlineAt: api.Timestamp(view.ResponseDeadlineAt),
DeliveredAt: api.Timestamp(view.DeliveredAt), ViewedAt: nullableTimestamp(view.ViewedAt),
RespondedAt: nullableTimestamp(view.RespondedAt), UpdatedAt: api.Timestamp(view.UpdatedAt),
}
response.ContactConsent.SetToNull()
response.ContactGrant.SetToNull()
if view.Decline == nil {
response.Decline.SetToNull()
return response
}
record := api.InvitationDeclineRecord{
Reason: api.InvitationDeclineReason(view.Decline.Reason), DeclinedAt: api.Timestamp(view.Decline.DeclinedAt),
}
if view.Decline.Comment == nil {
record.Comment.SetToNull()
} else {
record.Comment.SetTo(api.InvitationDeclineComment(*view.Decline.Comment))
}
response.Decline.SetTo(record)
return response
}
@@ -0,0 +1,96 @@
package v1
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
invitationusecase "lincodex/backend/internal/usecase/invitation"
)
func TestInvitationDeclineFailuresMapToTheContractStatuses(t *testing.T) {
ctx := context.Background()
field := &domain.InvitationFieldError{Pointer: "/comment", Reason: "x"}
for name, test := range map[string]struct {
err error
want string
}{
"employer": {invitationusecase.ErrForbidden, "*api.DeclineMyInvitationForbidden"},
"unknown": {fmt.Errorf("wrapped: %w", outbound.ErrInvitationNotFound), "*api.DeclineMyInvitationNotFound"},
"reused key": {invitationusecase.ErrIdempotencyKeyReused, "*api.DeclineMyInvitationUnprocessableEntity"},
"bad key": {invitationusecase.ErrInvalidIdempotencyKey, "*api.DeclineMyInvitationBadRequest"},
"comment": {fmt.Errorf("wrapped: %w", field), "*api.DeclineMyInvitationBadRequest"},
"stale version": {domain.ErrInvitationVersionConflict, "*api.DeclineMyInvitationPreconditionFailed"},
"terminal or late": {fmt.Errorf("wrapped: %w", invitationusecase.ErrAnswerBlocked), "*api.DeclineMyInvitationConflict"},
} {
response, unexpected := invitationDeclineFailure(ctx, test.err)
if unexpected != nil || fmt.Sprintf("%T", response) != test.want {
t.Errorf("%s: failure = %T, %v; want %s", name, response, unexpected, test.want)
}
}
if _, unexpected := invitationDeclineFailure(ctx, errors.New("storage failed")); unexpected == nil {
t.Error("an unknown failure produced a public response instead of reaching the responder")
}
}
// The candidate's response carries the own decline and nothing of the
// candidate: no identifier, handle, salary indicator, need, or contact. The
// consent offer and the grant are null until an acceptance exists.
func TestCandidateInvitationResponseCarriesTheDeclineAndNoCandidateData(t *testing.T) {
candidateID, organizationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7())
policyID, err := domain.NewPolicyVersionID()
if err != nil {
t.Fatalf("NewPolicyVersionID() error = %v", err)
}
now := time.Date(2026, time.October, 9, 10, 0, 0, 0, time.UTC)
draft, err := domain.NewInvitationDraft(domain.NewInvitationDraftInput{
ID: uuid.Must(uuid.NewV7()), OrganizationID: organizationID, CandidateID: candidateID, ActorID: uuid.Must(uuid.NewV7()),
PolicyVersionID: policyID, At: now,
Content: domain.InvitationDraftContent{ResponsePeriod: 7, Terms: invitationTermsFromRequest(invitationTestTerms())},
})
if err != nil {
t.Fatalf("NewInvitationDraft() error = %v", err)
}
delivered, err := draft.Deliver(now)
if err != nil {
t.Fatalf("Deliver() error = %v", err)
}
declined, decline, err := delivered.Decline(domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther}, now.Add(time.Hour))
if err != nil {
t.Fatalf("Decline() error = %v", err)
}
view, err := declined.CandidateView(domain.InvitationOrganizationRef{ID: organizationID, Name: "Acme"}, &decline)
if err != nil {
t.Fatalf("CandidateView() error = %v", err)
}
encoded, err := json.Marshal(candidateInvitationResponse(view))
if err != nil {
t.Fatalf("marshal response: %v", err)
}
text := string(encoded)
if strings.Contains(text, candidateID.String()) {
t.Errorf("response carries the candidate identifier: %s", text)
}
for _, key := range []string{"candidate_handle", "candidate_id", "salary_fit", "need", "email", "phone", "telegram", "full_name"} {
if strings.Contains(text, `"`+key+`":`) {
t.Errorf("response carries %s: %s", key, text)
}
}
for _, want := range []string{
`"state":"declined"`, `"decline":{"reason":"other","comment":null,"declined_at":"2026-10-09T11:00:00Z"}`,
`"contact_consent":null`, `"contact_grant":null`, `"organization":{"id":"` + organizationID.String() + `","name":"Acme"}`,
`"response_deadline_at":"2026-10-16T10:00:00Z"`,
} {
if !strings.Contains(text, want) {
t.Errorf("response lacks %s: %s", want, text)
}
}
}
@@ -0,0 +1,244 @@
package postgres
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var _ outbound.InvitationDeclineResultRepository = invitationRepository{}
func (unit *UnitOfWork) InvitationDeclineResults() outbound.InvitationDeclineResultRepository {
return invitationRepository{queries: unit.queries}
}
func (repository invitationRepository) GetCandidateEntry(
ctx context.Context,
candidateID, invitationID uuid.UUID,
) (outbound.CandidateInvitationEntry, error) {
const location = "invitationRepository.GetCandidateEntry"
if candidateID == uuid.Nil || invitationID == uuid.Nil {
return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - candidate and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation)
}
row, err := repository.queries.ReadCandidateInvitationEntry(ctx, sqlc.ReadCandidateInvitationEntryParams{
CandidateID: pgUUID(candidateID), InvitationID: pgUUID(invitationID),
})
if err != nil {
return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - read invitation: %w", location, mapInvitationNoRows(err))
}
return restoreCandidateInvitationRow(location, sqlc.ListCandidateInvitationsRow(row), candidateID)
}
func (repository invitationRepository) GetCandidateEntryForUpdate(
ctx context.Context,
candidateID, invitationID uuid.UUID,
) (outbound.CandidateInvitationEntry, error) {
const location = "invitationRepository.GetCandidateEntryForUpdate"
if candidateID == uuid.Nil || invitationID == uuid.Nil {
return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - candidate and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation)
}
// The row is locked by a statement of its own and read afterwards, as
// for the organization side: a locking read joined to the terms would,
// after waiting for a concurrent commit, pair the new terms version with
// the terms row it fetched before the wait.
if _, err := repository.queries.LockCandidateInvitation(ctx, sqlc.LockCandidateInvitationParams{
CandidateID: pgUUID(candidateID), InvitationID: pgUUID(invitationID),
}); err != nil {
return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - lock invitation: %w", location, mapInvitationNoRows(err))
}
entry, err := repository.GetCandidateEntry(ctx, candidateID, invitationID)
if err != nil {
return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - read locked invitation: %w", location, err)
}
return entry, nil
}
func (repository invitationRepository) RecordView(
ctx context.Context,
expectedVersion int64,
next domain.Invitation,
event domain.InvitationEvent,
) error {
const location = "invitationRepository.RecordView"
stored := next.Stored()
if expectedVersion < 1 || stored.Version != expectedVersion+1 || stored.State != string(domain.InvitationViewed) ||
stored.ViewedAt == nil || event.Kind != domain.InvitationEventViewed {
return fmt.Errorf("%s - the next version must be the view that follows the expected one: %w", location, domain.ErrInvalidInvitation)
}
if err := repository.insertEventPrerequisites(location, next, event, stored.Version); err != nil {
return err
}
_, err := repository.queries.RecordInvitationView(ctx, sqlc.RecordInvitationViewParams{
NextVersion: stored.Version, ViewedAt: pgTime(*stored.ViewedAt), OrganizationID: pgUUID(stored.OrganizationID),
InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion,
})
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%s - record view: %w", location, outbound.ErrInvitationVersionConflict)
}
if err != nil {
return fmt.Errorf("%s - record view: %w", location, mapInvitationError(err))
}
return repository.insertEvent(ctx, location, event)
}
func (repository invitationRepository) Decline(
ctx context.Context,
expectedVersion int64,
next domain.Invitation,
decline domain.InvitationDecline,
event domain.InvitationEvent,
) error {
const location = "invitationRepository.Decline"
stored := next.Stored()
if expectedVersion < 1 || stored.Version != expectedVersion+1 || stored.State != string(domain.InvitationDeclined) ||
stored.RespondedAt == nil || event.Kind != domain.InvitationEventDeclined {
return fmt.Errorf("%s - the next version must be the decline that follows the expected one: %w", location, domain.ErrInvalidInvitation)
}
if err := decline.Validate(); err != nil {
return fmt.Errorf("%s - validate decline: %w", location, err)
}
if decline.InvitationID != stored.ID || decline.OrganizationID != stored.OrganizationID || !decline.DeclinedAt.Equal(*stored.RespondedAt) {
return fmt.Errorf("%s - the decline must describe the declined version: %w", location, domain.ErrInvalidInvitation)
}
if err := repository.insertEventPrerequisites(location, next, event, stored.Version); err != nil {
return err
}
_, err := repository.queries.DeclineInvitation(ctx, sqlc.DeclineInvitationParams{
NextVersion: stored.Version, DeclinedAt: pgTime(*stored.RespondedAt), OrganizationID: pgUUID(stored.OrganizationID),
InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion,
})
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%s - decline invitation: %w", location, outbound.ErrInvitationVersionConflict)
}
if err != nil {
return fmt.Errorf("%s - decline invitation: %w", location, mapInvitationError(err))
}
comment := pgtype.Text{}
if decline.Choice.Comment != nil {
comment = pgtype.Text{String: *decline.Choice.Comment, Valid: true}
}
if err := repository.queries.InsertInvitationDecline(ctx, sqlc.InsertInvitationDeclineParams{
InvitationID: pgUUID(decline.InvitationID), OrganizationID: pgUUID(decline.OrganizationID),
Reason: string(decline.Choice.Reason), Comment: comment, DeclinedAt: pgTime(decline.DeclinedAt),
}); err != nil {
return fmt.Errorf("%s - store decline: %w", location, mapInvitationError(err))
}
return repository.insertEvent(ctx, location, event)
}
func (repository invitationRepository) GetDecline(
ctx context.Context,
organizationID, invitationID uuid.UUID,
) (domain.InvitationDecline, error) {
const location = "invitationRepository.GetDecline"
if organizationID == uuid.Nil || invitationID == uuid.Nil {
return domain.InvitationDecline{}, fmt.Errorf("%s - organization and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation)
}
row, err := repository.queries.ReadInvitationDecline(ctx, sqlc.ReadInvitationDeclineParams{
OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID),
})
if errors.Is(err, pgx.ErrNoRows) {
return domain.InvitationDecline{}, fmt.Errorf("%s - read decline: %w", location, outbound.ErrInvitationDeclineNotFound)
}
if err != nil {
return domain.InvitationDecline{}, fmt.Errorf("%s - read decline: %w", location, mapInvitationError(err))
}
if !row.InvitationID.Valid || !row.OrganizationID.Valid || !row.DeclinedAt.Valid {
return domain.InvitationDecline{}, fmt.Errorf("%s - stored decline has no scope: %w", location, domain.ErrInvalidInvitation)
}
decline := domain.InvitationDecline{
InvitationID: uuid.UUID(row.InvitationID.Bytes), OrganizationID: uuid.UUID(row.OrganizationID.Bytes),
Choice: domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineReason(row.Reason)},
DeclinedAt: row.DeclinedAt.Time.UTC(),
}
if row.Comment.Valid {
comment := row.Comment.String
decline.Choice.Comment = &comment
}
if decline.InvitationID != invitationID || decline.OrganizationID != organizationID {
return domain.InvitationDecline{}, fmt.Errorf("%s - stored decline has another scope: %w", location, domain.ErrInvalidInvitation)
}
if err := decline.Validate(); err != nil {
return domain.InvitationDecline{}, fmt.Errorf("%s - validate stored decline: %w", location, err)
}
return decline, nil
}
func (repository invitationRepository) SaveDeclineResult(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
result outbound.InvitationDeclineResult,
) error {
const location = "invitationRepository.SaveDeclineResult"
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
}
if err := validateInvitationDeclineResult(result); err != nil {
return fmt.Errorf("%s - validate outcome: %w", location, err)
}
if err := repository.queries.InsertInvitationDeclineResult(ctx, sqlc.InsertInvitationDeclineResultParams{
ScopeHash: scope[:], InvitationID: pgUUID(result.InvitationID), Outcome: string(result.Outcome),
}); err != nil {
return fmt.Errorf("%s - store outcome: %w", location, mapInvitationDeclineResultError(err))
}
return nil
}
func (repository invitationRepository) GetDeclineResult(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
) (outbound.InvitationDeclineResult, error) {
const location = "invitationRepository.GetDeclineResult"
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
return outbound.InvitationDeclineResult{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
}
row, err := repository.queries.GetInvitationDeclineResult(ctx, scope[:])
if errors.Is(err, pgx.ErrNoRows) {
return outbound.InvitationDeclineResult{}, outbound.ErrInvitationDeclineResultNotFound
}
if err != nil {
return outbound.InvitationDeclineResult{}, fmt.Errorf("%s - read outcome: %w", location, mapInvitationError(err))
}
if !row.InvitationID.Valid {
return outbound.InvitationDeclineResult{}, fmt.Errorf("%s - stored outcome has no invitation: %w", location, domain.ErrInvalidInvitation)
}
result := outbound.InvitationDeclineResult{
InvitationID: uuid.UUID(row.InvitationID.Bytes), Outcome: outbound.InvitationDeclineOutcome(row.Outcome),
}
if err := validateInvitationDeclineResult(result); err != nil {
return outbound.InvitationDeclineResult{}, fmt.Errorf("%s - validate stored outcome: %w", location, err)
}
return result, nil
}
func validateInvitationDeclineResult(result outbound.InvitationDeclineResult) error {
const location = "postgres.validateInvitationDeclineResult"
switch result.Outcome {
case outbound.InvitationDeclineDeclined:
if result.InvitationID == uuid.Nil {
return fmt.Errorf("%s - a declined outcome names the invitation: %w", location, domain.ErrInvalidInvitation)
}
case outbound.InvitationDeclineNotFound, outbound.InvitationDeclineStateConflict:
// A refusal names the identifier of the path, which may name nothing.
default:
return fmt.Errorf("%s - outcome is unknown: %w", location, domain.ErrInvalidInvitation)
}
return nil
}
func mapInvitationDeclineResultError(err error) error {
var pgError *pgconn.PgError
if errors.As(err, &pgError) && pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitation_decline_results_idempotency_fkey" {
return fmt.Errorf("postgres.mapInvitationDeclineResultError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound)
}
return mapInvitationError(err)
}
@@ -0,0 +1,322 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: invitation_answers.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const declineInvitation = `-- name: DeclineInvitation :one
UPDATE invitations
SET
state = 'declined',
version = $1,
responded_at = $2,
updated_at = $2
WHERE
organization_id = $3
AND id = $4
AND state IN ('delivered', 'viewed', 'counter')
AND version = $5
AND response_deadline_at > $2
AND $1::bigint = $5::bigint + 1
RETURNING id
`
type DeclineInvitationParams struct {
NextVersion int64
DeclinedAt pgtype.Timestamptz
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
ExpectedVersion int64
}
// The compare-and-swap of a decline: it applies only to an answerable
// invitation at the version the caller read and before its deadline.
func (q *Queries) DeclineInvitation(ctx context.Context, arg DeclineInvitationParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, declineInvitation,
arg.NextVersion,
arg.DeclinedAt,
arg.OrganizationID,
arg.InvitationID,
arg.ExpectedVersion,
)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const getInvitationDeclineResult = `-- name: GetInvitationDeclineResult :one
SELECT
invitation_id,
outcome
FROM invitation_decline_results
WHERE scope_hash = $1
`
type GetInvitationDeclineResultRow struct {
InvitationID pgtype.UUID
Outcome string
}
func (q *Queries) GetInvitationDeclineResult(ctx context.Context, scopeHash []byte) (GetInvitationDeclineResultRow, error) {
row := q.db.QueryRow(ctx, getInvitationDeclineResult, scopeHash)
var i GetInvitationDeclineResultRow
err := row.Scan(&i.InvitationID, &i.Outcome)
return i, err
}
const insertInvitationDecline = `-- name: InsertInvitationDecline :exec
INSERT INTO invitation_declines (
invitation_id,
organization_id,
reason,
comment,
declined_at
) VALUES (
$1,
$2,
$3,
$4,
$5
)
`
type InsertInvitationDeclineParams struct {
InvitationID pgtype.UUID
OrganizationID pgtype.UUID
Reason string
Comment pgtype.Text
DeclinedAt pgtype.Timestamptz
}
func (q *Queries) InsertInvitationDecline(ctx context.Context, arg InsertInvitationDeclineParams) error {
_, err := q.db.Exec(ctx, insertInvitationDecline,
arg.InvitationID,
arg.OrganizationID,
arg.Reason,
arg.Comment,
arg.DeclinedAt,
)
return err
}
const insertInvitationDeclineResult = `-- name: InsertInvitationDeclineResult :exec
INSERT INTO invitation_decline_results (
scope_hash,
invitation_id,
outcome
) VALUES (
$1,
$2,
$3
)
`
type InsertInvitationDeclineResultParams struct {
ScopeHash []byte
InvitationID pgtype.UUID
Outcome string
}
func (q *Queries) InsertInvitationDeclineResult(ctx context.Context, arg InsertInvitationDeclineResultParams) error {
_, err := q.db.Exec(ctx, insertInvitationDeclineResult, arg.ScopeHash, arg.InvitationID, arg.Outcome)
return err
}
const lockCandidateInvitation = `-- name: LockCandidateInvitation :one
SELECT id
FROM invitations
WHERE
candidate_id = $1
AND id = $2
AND delivered_at IS NOT NULL
FOR UPDATE
`
type LockCandidateInvitationParams struct {
CandidateID pgtype.UUID
InvitationID pgtype.UUID
}
// Lock one delivered invitation addressed to the candidate. Only the
// invitation row is locked, never the organization.
func (q *Queries) LockCandidateInvitation(ctx context.Context, arg LockCandidateInvitationParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockCandidateInvitation, arg.CandidateID, arg.InvitationID)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const readCandidateInvitationEntry = `-- name: ReadCandidateInvitationEntry :one
SELECT
invitation.id,
invitation.organization_id,
invitation.candidate_id,
invitation.need_id,
invitation.need_requirements_version,
invitation.state,
invitation.expiry_reason,
invitation.version,
invitation.terms_version,
invitation.response_period_days,
invitation.policy_version_id,
invitation.response_deadline_at,
invitation.salary_raise_used,
invitation.created_by,
invitation.created_at,
invitation.updated_at,
invitation.delivered_at,
invitation.viewed_at,
invitation.responded_at,
terms.terms::text AS terms,
organization.name AS organization_name
FROM invitations AS invitation
INNER JOIN invitation_terms_versions AS terms
ON terms.invitation_id = invitation.id
AND terms.version = invitation.terms_version
INNER JOIN organizations AS organization
ON organization.id = invitation.organization_id
WHERE
invitation.candidate_id = $1
AND invitation.id = $2
AND invitation.delivered_at IS NOT NULL
`
type ReadCandidateInvitationEntryParams struct {
CandidateID pgtype.UUID
InvitationID pgtype.UUID
}
type ReadCandidateInvitationEntryRow struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
NeedID pgtype.UUID
NeedRequirementsVersion pgtype.Int8
State string
ExpiryReason pgtype.Text
Version int64
TermsVersion int64
ResponsePeriodDays int16
PolicyVersionID pgtype.UUID
ResponseDeadlineAt pgtype.Timestamptz
SalaryRaiseUsed bool
CreatedBy pgtype.UUID
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
DeliveredAt pgtype.Timestamptz
ViewedAt pgtype.Timestamptz
RespondedAt pgtype.Timestamptz
Terms string
OrganizationName string
}
// Read one delivered invitation addressed to the candidate with the current
// name of the organization that sent it. A draft and an invitation of
// another candidate find nothing.
func (q *Queries) ReadCandidateInvitationEntry(ctx context.Context, arg ReadCandidateInvitationEntryParams) (ReadCandidateInvitationEntryRow, error) {
row := q.db.QueryRow(ctx, readCandidateInvitationEntry, arg.CandidateID, arg.InvitationID)
var i ReadCandidateInvitationEntryRow
err := row.Scan(
&i.ID,
&i.OrganizationID,
&i.CandidateID,
&i.NeedID,
&i.NeedRequirementsVersion,
&i.State,
&i.ExpiryReason,
&i.Version,
&i.TermsVersion,
&i.ResponsePeriodDays,
&i.PolicyVersionID,
&i.ResponseDeadlineAt,
&i.SalaryRaiseUsed,
&i.CreatedBy,
&i.CreatedAt,
&i.UpdatedAt,
&i.DeliveredAt,
&i.ViewedAt,
&i.RespondedAt,
&i.Terms,
&i.OrganizationName,
)
return i, err
}
const readInvitationDecline = `-- name: ReadInvitationDecline :one
SELECT
invitation_id,
organization_id,
reason,
comment,
declined_at
FROM invitation_declines
WHERE
organization_id = $1
AND invitation_id = $2
`
type ReadInvitationDeclineParams struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
}
func (q *Queries) ReadInvitationDecline(ctx context.Context, arg ReadInvitationDeclineParams) (InvitationDecline, error) {
row := q.db.QueryRow(ctx, readInvitationDecline, arg.OrganizationID, arg.InvitationID)
var i InvitationDecline
err := row.Scan(
&i.InvitationID,
&i.OrganizationID,
&i.Reason,
&i.Comment,
&i.DeclinedAt,
)
return i, err
}
const recordInvitationView = `-- name: RecordInvitationView :one
UPDATE invitations
SET
state = 'viewed',
version = $1,
viewed_at = $2,
updated_at = $2
WHERE
organization_id = $3
AND id = $4
AND state = 'delivered'
AND version = $5
AND response_deadline_at > $2
AND $1::bigint = $5::bigint + 1
RETURNING id
`
type RecordInvitationViewParams struct {
NextVersion int64
ViewedAt pgtype.Timestamptz
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
ExpectedVersion int64
}
// The compare-and-swap of the first view: it applies only to a delivered
// invitation at the version the caller read and before its deadline, and it
// keeps the deadline.
func (q *Queries) RecordInvitationView(ctx context.Context, arg RecordInvitationViewParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, recordInvitationView,
arg.NextVersion,
arg.ViewedAt,
arg.OrganizationID,
arg.InvitationID,
arg.ExpectedVersion,
)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
@@ -597,6 +597,20 @@ type InvitationCreationResult struct {
Snapshot []byte
}
type InvitationDecline struct {
InvitationID pgtype.UUID
OrganizationID pgtype.UUID
Reason string
Comment pgtype.Text
DeclinedAt pgtype.Timestamptz
}
type InvitationDeclineResult struct {
ScopeHash []byte
InvitationID pgtype.UUID
Outcome string
}
type InvitationEvent struct {
ID pgtype.UUID
InvitationID pgtype.UUID
@@ -157,6 +157,9 @@ type Querier interface {
// The caller appends the matching outbox intent in the same transaction only
// when this insert returns a row.
CreateAccountDeletionRequest(ctx context.Context, arg CreateAccountDeletionRequestParams) (CreateAccountDeletionRequestRow, error)
// The compare-and-swap of a decline: it applies only to an answerable
// invitation at the version the caller read and before its deadline.
DeclineInvitation(ctx context.Context, arg DeclineInvitationParams) (pgtype.UUID, error)
// A newly reserved generic idempotency window can replace an expired typed
// outcome before the new immutable response is inserted.
DeleteAssessmentAttemptIdempotencyOutcome(ctx context.Context, scopeHash []byte) error
@@ -302,6 +305,7 @@ type Querier interface {
// Explains why ConsumeEmailToken matched no row.
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
GetInvitationCreationResult(ctx context.Context, scopeHash []byte) (string, error)
GetInvitationDeclineResult(ctx context.Context, scopeHash []byte) (GetInvitationDeclineResultRow, error)
GetInvitationSendResult(ctx context.Context, scopeHash []byte) (GetInvitationSendResultRow, error)
// The caller holds the attempt row lock, so the last mark is stable.
GetLastAssessmentOriginMark(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptOriginMark, error)
@@ -477,6 +481,8 @@ type Querier interface {
// inserted in one caller-owned transaction. The deferred reference to the
// current terms version is checked when the transaction commits.
InsertInvitation(ctx context.Context, arg InsertInvitationParams) error
InsertInvitationDecline(ctx context.Context, arg InsertInvitationDeclineParams) error
InsertInvitationDeclineResult(ctx context.Context, arg InsertInvitationDeclineResultParams) error
InsertInvitationEvent(ctx context.Context, arg InsertInvitationEventParams) error
InsertInvitationSendResult(ctx context.Context, arg InsertInvitationSendResultParams) error
InsertInvitationTermsVersion(ctx context.Context, arg InsertInvitationTermsVersionParams) error
@@ -716,6 +722,9 @@ type Querier interface {
// Acquired after C3, candidate/specialization scope, and attempt row locks.
// This independent lock serializes current category upgrades for one scope.
LockCandidateAssessmentCategory(ctx context.Context, arg LockCandidateAssessmentCategoryParams) error
// Lock one delivered invitation addressed to the candidate. Only the
// invitation row is locked, never the organization.
LockCandidateInvitation(ctx context.Context, arg LockCandidateInvitationParams) (pgtype.UUID, error)
// Locks the candidate's published row only when it refers to a C2 record
// revoked by this transaction. The setting remains linked to that immutable
// record; ReadCandidatePublication computes the effective closed state and
@@ -846,6 +855,10 @@ type Querier interface {
// Read one delivered invitation addressed to the candidate. A draft and an
// invitation of another candidate find nothing.
ReadCandidateInvitation(ctx context.Context, arg ReadCandidateInvitationParams) (ReadCandidateInvitationRow, error)
// Read one delivered invitation addressed to the candidate with the current
// name of the organization that sent it. A draft and an invitation of
// another candidate find nothing.
ReadCandidateInvitationEntry(ctx context.Context, arg ReadCandidateInvitationEntryParams) (ReadCandidateInvitationEntryRow, error)
// Queries of the candidate visibility settings: the publication of
// the card, the search status, the hidden organizations, and the history of
// these settings. Every statement is scoped by the candidate's user_id, and
@@ -888,6 +901,7 @@ type Querier interface {
// and the invitation scope the row, so another organization's identifier
// finds nothing.
ReadInvitation(ctx context.Context, arg ReadInvitationParams) (ReadInvitationRow, error)
ReadInvitationDecline(ctx context.Context, arg ReadInvitationDeclineParams) (InvitationDecline, error)
// Read one historical terms version of one invitation of one organization.
ReadInvitationTermsVersion(ctx context.Context, arg ReadInvitationTermsVersionParams) (string, error)
// Read one historical version without exposing another organization's record.
@@ -933,6 +947,10 @@ type Querier interface {
// the delivery is no longer pending or waiting, or another worker holds it.
// now is the application clock.
RecordDeliveryFailure(ctx context.Context, arg RecordDeliveryFailureParams) (string, error)
// The compare-and-swap of the first view: it applies only to a delivered
// invitation at the version the caller read and before its deadline, and it
// keeps the deadline.
RecordInvitationView(ctx context.Context, arg RecordInvitationViewParams) (pgtype.UUID, error)
// Records the latest settled outcome of a send under the reservation.
RecordMailQuotaOutcome(ctx context.Context, arg RecordMailQuotaOutcomeParams) (int64, error)
RefreshCompanyCardViewQuotaUsage(ctx context.Context, arg RefreshCompanyCardViewQuotaUsageParams) (int64, error)
+1
View File
@@ -223,6 +223,7 @@ func RestoreInvitation(stored StoredInvitation) (Invitation, error) {
const location = "domain.RestoreInvitation"
for _, defect := range []func(StoredInvitation) string{
storedInvitationIdentityDefect, storedInvitationVersionDefect, storedInvitationLifecycleDefect,
storedInvitationAnswerDefect,
} {
if reason := defect(stored); reason != "" {
return Invitation{}, fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidInvitation)
@@ -0,0 +1,348 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"slices"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
)
// ErrInvitationNotAnswerable reports a candidate command that the state or
// the deadline of the invitation does not allow, such as a decline of a
// withdrawn invitation or one received at the deadline or later. The API
// answers 409 state_conflict.
var ErrInvitationNotAnswerable = errors.New("invitation state does not allow the answer")
const (
// InvitationEventViewed is the audit event of the first view of the
// terms: the invitation moved from delivered to viewed.
InvitationEventViewed InvitationEventKind = "viewed"
// InvitationEventDeclined is the audit event of a decline. It is the
// candidate's answer for the responsiveness metrics, never a consent or
// a hire, and it holds neither the reason nor the comment.
InvitationEventDeclined InvitationEventKind = "declined"
)
const (
// maxInvitationDeclineCommentRunes matches InvitationDeclineComment.
maxInvitationDeclineCommentRunes = 500
redactedInvitationDecline = "[redacted invitation decline]"
)
var (
// terminalInvitationStates are the final states that no command leaves.
terminalInvitationStates = []InvitationState{
InvitationDeclined, InvitationExpired, InvitationWithdrawn, InvitationCancelledByCandidate,
}
// answerableInvitationStates allow the candidate's answer: the delivered
// and viewed invitation and the planned counter offer.
answerableInvitationStates = []InvitationState{InvitationDelivered, InvitationViewed, InvitationCounter}
// answerEventKinds name the audit event of each answer state.
answerEventKinds = map[InvitationState]InvitationEventKind{
InvitationViewed: InvitationEventViewed, InvitationDeclined: InvitationEventDeclined,
}
)
// InvitationDeclineReason is the structured reason of a decline. Every reason
// is neutral, and none requires a comment.
type InvitationDeclineReason string
const (
InvitationDeclineSalary InvitationDeclineReason = "salary"
InvitationDeclineTasks InvitationDeclineReason = "tasks"
InvitationDeclineStack InvitationDeclineReason = "stack"
InvitationDeclineWorkFormat InvitationDeclineReason = "work_format"
InvitationDeclinePackage InvitationDeclineReason = "package"
InvitationDeclineCompany InvitationDeclineReason = "company"
InvitationDeclineNotLooking InvitationDeclineReason = "not_looking"
InvitationDeclineOtherOffer InvitationDeclineReason = "other_offer"
InvitationDeclineOther InvitationDeclineReason = "other"
)
func (reason InvitationDeclineReason) IsKnown() bool {
switch reason {
case InvitationDeclineSalary, InvitationDeclineTasks, InvitationDeclineStack, InvitationDeclineWorkFormat,
InvitationDeclinePackage, InvitationDeclineCompany, InvitationDeclineNotLooking, InvitationDeclineOtherOffer,
InvitationDeclineOther:
return true
default:
return false
}
}
// InvitationDeclineChoice is what the candidate sends with a decline: the
// reason and an optional comment. The comment is private to the candidate:
// the organization never reads it, and it is never logged or notified.
type InvitationDeclineChoice struct {
Reason InvitationDeclineReason
Comment *string
}
// Validate repeats the schema rules that a stored choice must satisfy and
// refuses what PostgreSQL text cannot hold. A comment has 1 to 500
// characters, at least one that is not white space in the Unicode sense, and
// no control character other than a line break or a tab.
func (choice InvitationDeclineChoice) Validate() error {
if !choice.Reason.IsKnown() {
return invalidInvitationField("/reason", "must be a known decline reason")
}
if choice.Comment == nil {
return nil
}
comment := *choice.Comment
if comment == "" || !utf8.ValidString(comment) || utf8.RuneCountInString(comment) > maxInvitationDeclineCommentRunes {
return invalidInvitationField("/comment", "must have 1 to 500 characters")
}
if strings.TrimFunc(comment, unicode.IsSpace) == "" {
return invalidInvitationField("/comment", "must contain a character that is not white space")
}
for _, character := range comment {
if unicode.IsControl(character) && character != '\n' && character != '\r' && character != '\t' {
return invalidInvitationField("/comment", "must not contain control characters")
}
}
return nil
}
// Equal reports whether both choices have the same reason and comment. An
// absent comment equals another absent comment only.
func (choice InvitationDeclineChoice) Equal(other InvitationDeclineChoice) bool {
if choice.Reason != other.Reason || (choice.Comment == nil) != (other.Comment == nil) {
return false
}
return choice.Comment == nil || *choice.Comment == *other.Comment
}
func (choice InvitationDeclineChoice) String() string { return redactedInvitationDecline }
func (choice InvitationDeclineChoice) GoString() string { return redactedInvitationDecline }
func (choice InvitationDeclineChoice) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedInvitationDecline)
}
func (choice InvitationDeclineChoice) LogValue() slog.Value {
return slog.StringValue(redactedInvitationDecline)
}
// InvitationDecline is the stored decline of one invitation. Only the
// candidate reads it back; the organization sees the state and the time of
// the answer only, because a reason such as salary would tell it that the
// hidden minimum is above the range.
type InvitationDecline struct {
InvitationID uuid.UUID
OrganizationID uuid.UUID
Choice InvitationDeclineChoice
DeclinedAt time.Time
}
// Validate checks a decline before it is stored or after it is read.
func (decline InvitationDecline) Validate() error {
if decline.InvitationID == uuid.Nil || decline.OrganizationID == uuid.Nil || !validInvitationTime(decline.DeclinedAt) {
return fmt.Errorf("InvitationDecline.Validate - identifiers and time must be set: %w", ErrInvalidInvitation)
}
return decline.Choice.Validate()
}
func (decline InvitationDecline) String() string { return redactedInvitationDecline }
func (decline InvitationDecline) GoString() string { return redactedInvitationDecline }
func (decline InvitationDecline) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedInvitationDecline)
}
func (decline InvitationDecline) LogValue() slog.Value {
return slog.StringValue(redactedInvitationDecline)
}
// IsTerminal reports a final state that no candidate or organization command
// leaves: declined, expired, withdrawn, or cancelled by the candidate.
func (invitation Invitation) IsTerminal() bool {
return slices.Contains(terminalInvitationStates, invitation.State())
}
// ResponseDeadlinePassed reports whether a command received at the time is
// late: at the deadline or later. An undelivered draft has no deadline.
func (invitation Invitation) ResponseDeadlinePassed(at time.Time) bool {
deadline := invitation.record.ResponseDeadlineAt
return deadline != nil && !at.Before(*deadline)
}
// answerable reports the states from which the candidate may still answer:
// the delivered and viewed invitation and the planned counter offer.
func (invitation Invitation) answerable() bool {
return slices.Contains(answerableInvitationStates, invitation.State())
}
// RecordView returns the next version in the state viewed when the candidate
// opens the terms of a delivered invitation before its deadline. In every
// other state, and at the deadline or later, the view changes nothing and
// RecordView returns the invitation as it is with changed false. The view
// never moves the deadline.
func (invitation Invitation) RecordView(at time.Time) (Invitation, bool, error) {
const location = "Invitation.RecordView"
if !validInvitationTime(at) || at.Before(invitation.record.UpdatedAt) {
return Invitation{}, false, fmt.Errorf("%s - view time must be set and not before the last change: %w", location, ErrInvalidInvitation)
}
if invitation.State() != InvitationDelivered || !invitation.IsDelivered() || invitation.ResponseDeadlinePassed(at) {
return invitation, false, nil
}
at = at.UTC()
next := invitation.Stored()
next.State = string(InvitationViewed)
next.Version++
next.UpdatedAt = at
next.ViewedAt = &at
viewed, err := RestoreInvitation(next)
if err != nil {
return Invitation{}, false, fmt.Errorf("%s - restore viewed invitation: %w", location, err)
}
return viewed, true, nil
}
// Decline returns the next version in the terminal state declined with the
// stored decline. It is allowed from delivered, viewed, and the planned
// counter offer before the deadline; any other state or a late command
// returns ErrInvitationNotAnswerable. A decline creates no consent and no
// contact grant.
func (invitation Invitation) Decline(choice InvitationDeclineChoice, at time.Time) (Invitation, InvitationDecline, error) {
const location = "Invitation.Decline"
if err := choice.Validate(); err != nil {
return Invitation{}, InvitationDecline{}, fmt.Errorf("%s - validate choice: %w", location, err)
}
if !validInvitationTime(at) || at.Before(invitation.record.UpdatedAt) {
return Invitation{}, InvitationDecline{}, fmt.Errorf("%s - decline time must be set and not before the last change: %w", location, ErrInvalidInvitation)
}
if !invitation.answerable() || !invitation.IsDelivered() || invitation.ResponseDeadlinePassed(at) {
return Invitation{}, InvitationDecline{}, fmt.Errorf("%s - %w", location, ErrInvitationNotAnswerable)
}
at = at.UTC()
next := invitation.Stored()
next.State = string(InvitationDeclined)
next.Version++
next.UpdatedAt = at
next.RespondedAt = &at
declined, err := RestoreInvitation(next)
if err != nil {
return Invitation{}, InvitationDecline{}, fmt.Errorf("%s - restore declined invitation: %w", location, err)
}
decline := InvitationDecline{
InvitationID: next.ID, OrganizationID: next.OrganizationID, DeclinedAt: at,
Choice: InvitationDeclineChoice{Reason: choice.Reason, Comment: cloneString(choice.Comment)},
}
return declined, decline, nil
}
// AnswerEvent builds the audit event of the version that a view or a
// decline by actor has just produced. It names no field and holds neither
// the reason nor the comment of a decline.
func (invitation Invitation) AnswerEvent(actorID uuid.UUID) (InvitationEvent, error) {
const location = "Invitation.AnswerEvent"
if actorID == uuid.Nil {
return InvitationEvent{}, fmt.Errorf("%s - actor must be set: %w", location, ErrInvalidInvitation)
}
kind, ok := answerEventKinds[invitation.State()]
if !ok {
return InvitationEvent{}, fmt.Errorf("%s - the invitation must be viewed or declined: %w", location, ErrInvalidInvitation)
}
id, err := uuid.NewV7()
if err != nil {
return InvitationEvent{}, fmt.Errorf("%s - generate event ID: %w", location, err)
}
return InvitationEvent{
ID: id, InvitationID: invitation.record.ID, OrganizationID: invitation.record.OrganizationID,
Version: invitation.record.Version, TermsVersion: invitation.record.TermsVersion, Kind: kind,
ActorID: actorID, ChangedFields: []InvitationChangedField{}, OccurredAt: invitation.record.UpdatedAt,
}, nil
}
// storedInvitationAnswerDefect checks the view and the answer against the
// state: a delivered invitation has neither, a viewed one has its view, a
// declined one has its answer, and neither precedes the delivery.
func storedInvitationAnswerDefect(stored StoredInvitation) string {
state := InvitationState(stored.State)
switch {
case state == InvitationDelivered && (stored.ViewedAt != nil || stored.RespondedAt != nil):
return "a delivered invitation has no view or answer"
case state == InvitationViewed && (stored.ViewedAt == nil || stored.RespondedAt != nil):
return "a viewed invitation has a view and no answer"
case state == InvitationDeclined && stored.RespondedAt == nil:
return "a declined invitation has an answer"
case stored.ViewedAt != nil && (stored.DeliveredAt == nil || stored.ViewedAt.Before(*stored.DeliveredAt)):
return "a view follows the delivery"
case stored.RespondedAt != nil && (stored.DeliveredAt == nil || stored.RespondedAt.Before(*stored.DeliveredAt)):
return "an answer follows the delivery"
}
return ""
}
// InvitationDeclineView is the candidate's own decline as the candidate
// reads it back.
type InvitationDeclineView struct {
Reason InvitationDeclineReason
Comment *string
DeclinedAt time.Time
}
// CandidateInvitationView is a delivered invitation as the addressed
// candidate reads it: the organization, the current terms with their
// version, the state, the deadline, and the candidate's own decline. It has
// no candidate identifier, handle, need, salary indicator, or contact value.
// The consent offer and the contact grant belong to the acceptance and are
// absent until it exists.
type CandidateInvitationView struct {
ID uuid.UUID
Organization InvitationOrganizationRef
State InvitationState
ExpiryReason *InvitationExpiryReason
Version int64
TermsVersion int64
Terms InvitationTerms
ResponseDeadlineAt time.Time
DeliveredAt time.Time
ViewedAt *time.Time
RespondedAt *time.Time
UpdatedAt time.Time
Decline *InvitationDeclineView
}
// CandidateView returns the invitation for the candidate it is addressed to.
// The decline must be given exactly when the invitation is declined, and it
// must belong to this invitation.
func (invitation Invitation) CandidateView(organization InvitationOrganizationRef, decline *InvitationDecline) (CandidateInvitationView, error) {
const location = "Invitation.CandidateView"
stored := invitation.Stored()
if stored.DeliveredAt == nil || stored.ResponseDeadlineAt == nil {
return CandidateInvitationView{}, fmt.Errorf("%s - only a delivered invitation is shown to the candidate: %w", location, ErrInvalidInvitation)
}
if organization.ID != stored.OrganizationID || organization.Name == "" {
return CandidateInvitationView{}, fmt.Errorf("%s - the organization must be the sender: %w", location, ErrInvalidInvitation)
}
if (invitation.State() == InvitationDeclined) != (decline != nil) ||
(decline != nil && (decline.InvitationID != stored.ID || decline.OrganizationID != stored.OrganizationID)) {
return CandidateInvitationView{}, fmt.Errorf("%s - the decline must belong to a declined invitation: %w", location, ErrInvalidInvitation)
}
snapshot := invitation.Snapshot()
view := CandidateInvitationView{
ID: stored.ID, Organization: organization, State: snapshot.State, ExpiryReason: snapshot.ExpiryReason,
Version: stored.Version, TermsVersion: stored.TermsVersion, Terms: stored.Terms,
ResponseDeadlineAt: *stored.ResponseDeadlineAt, DeliveredAt: *stored.DeliveredAt,
ViewedAt: stored.ViewedAt, RespondedAt: stored.RespondedAt, UpdatedAt: stored.UpdatedAt,
}
if decline != nil {
view.Decline = &InvitationDeclineView{
Reason: decline.Choice.Reason, Comment: cloneString(decline.Choice.Comment), DeclinedAt: decline.DeclinedAt.UTC(),
}
}
return view, nil
}
func (view CandidateInvitationView) String() string { return redactedInvitation }
func (view CandidateInvitationView) GoString() string { return redactedInvitation }
func (view CandidateInvitationView) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedInvitation)
}
func (view CandidateInvitationView) LogValue() slog.Value {
return slog.StringValue(redactedInvitation)
}
@@ -0,0 +1,225 @@
package domain
import (
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
// deliveredTestInvitation returns a draft delivered an hour after it was
// created, with the default seven-day deadline.
func deliveredTestInvitation(t *testing.T) (Invitation, NewInvitationDraftInput) {
t.Helper()
input := validInvitationDraftInput()
draft, err := NewInvitationDraft(input)
if err != nil {
t.Fatalf("NewInvitationDraft() error = %v", err)
}
delivered, err := draft.Deliver(input.At.Add(time.Hour))
if err != nil {
t.Fatalf("Deliver() error = %v", err)
}
return delivered, input
}
// withState restores the invitation in another state, as a later operation
// would store it.
func withState(t *testing.T, invitation Invitation, state InvitationState, change func(*StoredInvitation)) Invitation {
t.Helper()
stored := invitation.Stored()
stored.State = string(state)
stored.Version++
if change != nil {
change(&stored)
}
restored, err := RestoreInvitation(stored)
if err != nil {
t.Fatalf("RestoreInvitation(%s) error = %v", state, err)
}
return restored
}
func TestRecordViewMovesOnlyADeliveredInvitationBeforeItsDeadline(t *testing.T) {
delivered, input := deliveredTestInvitation(t)
deadline := *delivered.Snapshot().ResponseDeadlineAt
viewedAt := deadline.Add(-time.Microsecond)
viewed, changed, err := delivered.RecordView(viewedAt)
if err != nil || !changed {
t.Fatalf("RecordView() = %v, %v; want a change", changed, err)
}
snapshot := viewed.Snapshot()
if snapshot.State != InvitationViewed || snapshot.Version != delivered.Version()+1 || snapshot.TermsVersion != delivered.TermsVersion() ||
!snapshot.ViewedAt.Equal(viewedAt) || !snapshot.ResponseDeadlineAt.Equal(deadline) || !snapshot.UpdatedAt.Equal(viewedAt) {
t.Fatalf("viewed = %+v, want the next version viewed with the same deadline", snapshot)
}
event, err := viewed.AnswerEvent(input.ActorID)
if err != nil || event.Kind != InvitationEventViewed || event.Version != snapshot.Version || len(event.ChangedFields) != 0 || !event.OccurredAt.Equal(viewedAt) {
t.Fatalf("AnswerEvent() = %+v, %v", event, err)
}
// A repeat, a late view, and a view of another state change nothing.
for name, test := range map[string]struct {
invitation Invitation
at time.Time
}{
"viewed": {viewed, viewedAt},
"at the deadline": {delivered, deadline},
"after it": {delivered, deadline.Add(time.Hour)},
"declined": {withState(t, delivered, InvitationDeclined, func(s *StoredInvitation) { s.RespondedAt = &viewedAt }), deadline.Add(-time.Second)},
"withdrawn": {withState(t, delivered, InvitationWithdrawn, nil), viewedAt},
"planned counter": {withState(t, viewed, InvitationCounter, nil), viewedAt},
"expired by timing": {withState(t, delivered, InvitationExpired, func(s *StoredInvitation) { reason := string(InvitationExpiryTimeout); s.ExpiryReason = &reason }), viewedAt},
} {
same, changed, err := test.invitation.RecordView(test.at)
if err != nil || changed || same.Version() != test.invitation.Version() || same.State() != test.invitation.State() {
t.Errorf("RecordView(%s) = %s v%d, %v, %v; want no change", name, same.State(), same.Version(), changed, err)
}
}
if _, _, err := delivered.RecordView(delivered.UpdatedAt().Add(-time.Second)); !errors.Is(err, ErrInvalidInvitation) {
t.Fatalf("RecordView(before the last change) error = %v, want ErrInvalidInvitation", err)
}
if _, err := delivered.AnswerEvent(input.ActorID); !errors.Is(err, ErrInvalidInvitation) {
t.Fatalf("AnswerEvent(delivered) error = %v, want ErrInvalidInvitation", err)
}
}
func TestDeclineIsAllowedFromDeliveredViewedAndCounterBeforeTheDeadline(t *testing.T) {
delivered, input := deliveredTestInvitation(t)
deadline := *delivered.Snapshot().ResponseDeadlineAt
viewed, _, err := delivered.RecordView(delivered.UpdatedAt().Add(time.Minute))
if err != nil {
t.Fatalf("RecordView() error = %v", err)
}
counter := withState(t, viewed, InvitationCounter, nil)
choice := InvitationDeclineChoice{Reason: InvitationDeclineOther}
for name, invitation := range map[string]Invitation{"delivered": delivered, "viewed": viewed, "counter": counter} {
at := deadline.Add(-time.Microsecond)
declined, decline, err := invitation.Decline(choice, at)
if err != nil {
t.Fatalf("Decline(%s) error = %v", name, err)
}
snapshot := declined.Snapshot()
if snapshot.State != InvitationDeclined || snapshot.Version != invitation.Version()+1 || !snapshot.RespondedAt.Equal(at) ||
!snapshot.ResponseDeadlineAt.Equal(deadline) || !declined.IsTerminal() {
t.Fatalf("declined %s = %+v", name, snapshot)
}
if decline.InvitationID != invitation.ID() || decline.OrganizationID != invitation.OrganizationID() ||
decline.Choice.Reason != InvitationDeclineOther || decline.Choice.Comment != nil || !decline.DeclinedAt.Equal(at) {
t.Fatalf("decline of %s = %+v", name, decline)
}
event, err := declined.AnswerEvent(input.CandidateID)
if err != nil || event.Kind != InvitationEventDeclined || event.ActorID != input.CandidateID || len(event.ChangedFields) != 0 {
t.Fatalf("AnswerEvent(%s) = %+v, %v", name, event, err)
}
view, err := declined.CandidateView(InvitationOrganizationRef{ID: input.OrganizationID, Name: "Org"}, &decline)
if err != nil || view.Decline == nil || view.Decline.Reason != InvitationDeclineOther || view.Decline.Comment != nil {
t.Fatalf("CandidateView(%s) = %+v, %v", name, view, err)
}
}
}
func TestDeclineRefusesTerminalAndLateInvitations(t *testing.T) {
delivered, _ := deliveredTestInvitation(t)
deadline := *delivered.Snapshot().ResponseDeadlineAt
responded := delivered.UpdatedAt().Add(time.Minute)
choice := InvitationDeclineChoice{Reason: InvitationDeclineSalary}
draft, err := NewInvitationDraft(validInvitationDraftInput())
if err != nil {
t.Fatalf("NewInvitationDraft() error = %v", err)
}
for name, test := range map[string]struct {
invitation Invitation
at time.Time
}{
"at the deadline": {delivered, deadline},
"draft": {draft, draft.UpdatedAt()},
"declined": {withState(t, delivered, InvitationDeclined, func(s *StoredInvitation) { s.RespondedAt = &responded }), responded},
"accepted": {withState(t, delivered, InvitationAccepted, func(s *StoredInvitation) { s.RespondedAt = &responded }), responded},
"withdrawn": {withState(t, delivered, InvitationWithdrawn, nil), responded},
"cancelled": {withState(t, delivered, InvitationCancelledByCandidate, nil), responded},
} {
if _, _, err := test.invitation.Decline(choice, test.at); !errors.Is(err, ErrInvitationNotAnswerable) {
t.Errorf("Decline(%s) error = %v, want ErrInvitationNotAnswerable", name, err)
}
}
}
func TestDeclineChoiceValidatesTheReasonAndTheComment(t *testing.T) {
text := func(value string) *string { return &value }
for name, comment := range map[string]*string{
"absent": nil, "line breaks": text("Не подходит\nстек"), "500 characters": text(strings.Repeat("я", 500)),
"leading space": text(" ok"),
} {
if err := (InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: comment}).Validate(); err != nil {
t.Errorf("Validate(%s) error = %v", name, err)
}
}
for name, test := range map[string]struct {
choice InvitationDeclineChoice
pointer string
}{
"unknown reason": {InvitationDeclineChoice{Reason: "rude"}, "/reason"},
"empty": {InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: text("")}, "/comment"},
"white space": {InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: text(" \n  ")}, "/comment"},
"501 characters": {InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: text(strings.Repeat("я", 501))}, "/comment"},
"NUL": {InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: text("a\x00b")}, "/comment"},
"invalid UTF-8": {InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: text("a\xffb")}, "/comment"},
"escape characters": {InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: text("a\x1bb")}, "/comment"},
} {
err := test.choice.Validate()
field, ok := errors.AsType[*InvitationFieldError](err)
if !ok || field.Pointer != test.pointer {
t.Errorf("Validate(%s) error = %v, want a field error at %s", name, err, test.pointer)
}
}
same := InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: text("x")}
if !same.Equal(InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: text("x")}) ||
same.Equal(InvitationDeclineChoice{Reason: InvitationDeclineOther}) ||
same.Equal(InvitationDeclineChoice{Reason: InvitationDeclineStack, Comment: text("x")}) {
t.Fatal("Equal does not compare the reason and the comment")
}
}
func TestStoredAnswersMustMatchTheState(t *testing.T) {
delivered, _ := deliveredTestInvitation(t)
before := delivered.Snapshot().DeliveredAt.Add(-time.Second)
after := delivered.Snapshot().DeliveredAt.Add(time.Second)
for name, change := range map[string]func(*StoredInvitation){
"delivered with a view": func(s *StoredInvitation) { s.ViewedAt = &after },
"viewed without a view": func(s *StoredInvitation) { s.State = string(InvitationViewed) },
"declined without time": func(s *StoredInvitation) { s.State = string(InvitationDeclined) },
"view before delivery": func(s *StoredInvitation) { s.State = string(InvitationViewed); s.ViewedAt = &before },
"answer before delivery": func(s *StoredInvitation) { s.State = string(InvitationDeclined); s.RespondedAt = &before },
} {
stored := delivered.Stored()
change(&stored)
if _, err := RestoreInvitation(stored); !errors.Is(err, ErrInvalidInvitation) {
t.Errorf("RestoreInvitation(%s) error = %v, want ErrInvalidInvitation", name, err)
}
}
}
func TestDeclineValuesAreRedacted(t *testing.T) {
comment := "private-decline-comment"
decline := InvitationDecline{
InvitationID: uuid.New(), OrganizationID: uuid.New(), DeclinedAt: time.Now(),
Choice: InvitationDeclineChoice{Reason: InvitationDeclineSalary, Comment: &comment},
}
delivered, input := deliveredTestInvitation(t)
view, err := delivered.CandidateView(InvitationOrganizationRef{ID: input.OrganizationID, Name: "Org"}, nil)
if err != nil {
t.Fatalf("CandidateView() error = %v", err)
}
for _, value := range []any{decline, decline.Choice, view} {
for _, format := range []string{"%v", "%+v", "%#v", "%s"} {
if output := fmt.Sprintf(format, value); strings.Contains(output, comment) || strings.Contains(output, string(InvitationDeclineSalary)) ||
strings.Contains(output, input.CandidateID.String()) {
t.Errorf("%s of %T discloses a private value: %s", format, value, output)
}
}
}
}
@@ -28,6 +28,14 @@ var (
// ErrInvitationSendResultNotFound reports a missing outcome of a send for
// a live idempotency record.
ErrInvitationSendResultNotFound = errors.New("organization invitation send result not found")
// ErrInvitationDeclineNotFound reports a declined invitation without its
// stored decline.
ErrInvitationDeclineNotFound = errors.New("invitation decline not found")
// ErrInvitationDeclineResultNotFound reports a missing outcome of a
// decline for a live idempotency record.
ErrInvitationDeclineResultNotFound = errors.New("invitation decline result not found")
)
// MaxInvitationPageSize is the largest organization-scoped or candidate page
@@ -40,6 +48,7 @@ type InvitationRepositories interface {
Invitations() InvitationRepository
InvitationCreationResults() InvitationCreationResultRepository
InvitationSendResults() InvitationSendResultRepository
InvitationDeclineResults() InvitationDeclineResultRepository
}
// InvitationRepository stores invitations, their immutable terms versions, and
@@ -92,6 +101,35 @@ type InvitationRepository interface {
// candidate. A draft, an invitation of another candidate, and an unknown
// identifier return ErrInvitationNotFound alike.
GetForCandidate(ctx context.Context, candidateID, invitationID uuid.UUID) (domain.Invitation, error)
// GetCandidateEntry returns a delivered invitation addressed to the
// candidate with the current name of the organization that sent it. A
// draft, an invitation of another candidate, and an unknown identifier
// return ErrInvitationNotFound alike.
GetCandidateEntry(ctx context.Context, candidateID, invitationID uuid.UUID) (CandidateInvitationEntry, error)
// GetCandidateEntryForUpdate is GetCandidateEntry that also holds the
// row lock of the invitation until the surrounding transaction ends. It
// locks nothing else, so a candidate command never waits for an
// organization lock while it holds the invitation row.
GetCandidateEntryForUpdate(ctx context.Context, candidateID, invitationID uuid.UUID) (CandidateInvitationEntry, error)
// RecordView moves a delivered invitation from expectedVersion to the
// viewed version of next before its deadline and records the audit
// event. It returns ErrInvitationVersionConflict when the stored row is
// not delivered at expectedVersion or its deadline has passed.
RecordView(ctx context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error
// Decline moves an answerable invitation from expectedVersion to the
// declined version of next before its deadline, stores the decline, and
// records the audit event. It returns ErrInvitationVersionConflict when
// the stored row is not answerable at expectedVersion or its deadline has
// passed.
Decline(ctx context.Context, expectedVersion int64, next domain.Invitation, decline domain.InvitationDecline, event domain.InvitationEvent) error
// GetDecline returns the stored decline of the invitation or
// ErrInvitationDeclineNotFound.
GetDecline(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.InvitationDecline, error)
}
// InvitationCreationResultRepository stores the original response of a
@@ -180,3 +218,31 @@ type InvitationPage struct {
func InvitationCreationPosition(invitation domain.Invitation) InvitationListPosition {
return InvitationListPosition{CreatedAt: invitation.CreatedAt(), InvitationID: invitation.ID()}
}
// InvitationDeclineOutcome is the stored result of a decline under an
// Idempotency-Key. The contract stores a success, a missing invitation, and a
// state conflict; other failures are not stored.
type InvitationDeclineOutcome string
const (
InvitationDeclineDeclined InvitationDeclineOutcome = "declined"
InvitationDeclineNotFound InvitationDeclineOutcome = "not_found"
InvitationDeclineStateConflict InvitationDeclineOutcome = "state_conflict"
)
// InvitationDeclineResult is the outcome of one decline. It keeps no copy of
// the response: a declined invitation is terminal and its decline is
// immutable, so a replay rebuilds the same response from them, and the
// comment is stored once.
type InvitationDeclineResult struct {
InvitationID uuid.UUID
Outcome InvitationDeclineOutcome
}
// InvitationDeclineResultRepository stores the outcome of an idempotent
// decline. The scope references the generic idempotency record, so the
// outcome is removed when that record is purged.
type InvitationDeclineResultRepository interface {
SaveDeclineResult(ctx context.Context, scope [IdempotencyDigestSize]byte, result InvitationDeclineResult) error
GetDeclineResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (InvitationDeclineResult, error)
}
@@ -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
}