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)