feat(invitations): accept invitations with C4 consent and contact grants; share the E0 quota across holdings
This commit is contained in:
1 parent
a5990d3fc6
commit
676b3c6e24
59 files changed
+4926
-194
No files matched your search
@@ -0,0 +1,413 @@
|
||||
package invitation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/consent"
|
||||
)
|
||||
|
||||
const (
|
||||
acceptOperation = "candidate_invitation.accept"
|
||||
acceptLocation = "invitation.Service.AcceptMine"
|
||||
// consentTextPointer and consentFieldsPointer name the consent rules of
|
||||
// the body in the problem response.
|
||||
consentTextPointer = "/consent_c4/text_version"
|
||||
consentFieldsPointer = "/consent_c4/fields"
|
||||
)
|
||||
|
||||
// AcceptCommand binds the session candidate and the path to one acceptance:
|
||||
// the invitation version and the terms version that the candidate read, the
|
||||
// consent text version that the candidate saw, and the contact kinds that the
|
||||
// candidate selected, in the order sent.
|
||||
type AcceptCommand struct {
|
||||
ActorID uuid.UUID
|
||||
InvitationID uuid.UUID
|
||||
IdempotencyKey string
|
||||
ExpectedVersion int64
|
||||
TermsVersion int64
|
||||
TextVersion string
|
||||
Fields []domain.ContactField
|
||||
}
|
||||
|
||||
type acceptRequest struct {
|
||||
fingerprint [outbound.IdempotencyDigestSize]byte
|
||||
scope [outbound.IdempotencyDigestSize]byte
|
||||
record outbound.IdempotencyRecord
|
||||
now time.Time
|
||||
textVersion domain.ConsentTextVersion
|
||||
fields domain.ContactFieldSet
|
||||
}
|
||||
|
||||
// acceptFingerprint is the canonical request of an acceptance. The fields keep
|
||||
// their order, so a reordered choice is a different request under one key.
|
||||
type acceptFingerprint struct {
|
||||
InvitationID uuid.UUID `json:"invitation_id"`
|
||||
ExpectedVersion int64 `json:"expected_version"`
|
||||
TermsVersion int64 `json:"terms_version"`
|
||||
TextVersion string `json:"text_version"`
|
||||
Fields []domain.ContactField `json:"fields"`
|
||||
}
|
||||
|
||||
// acceptOutcome is what a committed acceptance transaction decided: the
|
||||
// invitation, or a refusal that the contract stores under the key and that the
|
||||
// caller returns after the commit.
|
||||
type acceptOutcome struct {
|
||||
view domain.CandidateInvitationView
|
||||
refusal error
|
||||
}
|
||||
|
||||
// AcceptMine accepts the current terms of an invitation of the session
|
||||
// candidate with the consent C4. In one transaction it checks the candidate,
|
||||
// the key, the invitation, a repeat of the acceptance, a terminal state or a
|
||||
// passed deadline, the versions, the state, and the consent rules; then it
|
||||
// moves the invitation to accepted, records the consent C4 in the consent
|
||||
// ledger, stores the contact grant of exactly the selected fields, and appends
|
||||
// the audit event. The acceptance never publishes the profile and never lifts
|
||||
// a hiding: the grant is readable only while the organization may read the
|
||||
// profile.
|
||||
//
|
||||
// Locks: the idempotency record of the candidate's own key and then only the
|
||||
// invitation row, never the organization, as for the other candidate commands.
|
||||
func (service *Service) AcceptMine(ctx context.Context, command AcceptCommand) (domain.CandidateInvitationView, error) {
|
||||
request, err := service.prepareAccept(command)
|
||||
if err != nil {
|
||||
return domain.CandidateInvitationView{}, err
|
||||
}
|
||||
var outcome acceptOutcome
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
outcome, err = service.acceptInTransaction(ctx, unit, command, request)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.CandidateInvitationView{}, fmt.Errorf("%s - run transaction: %w", acceptLocation, err)
|
||||
}
|
||||
if outcome.refusal != nil {
|
||||
return domain.CandidateInvitationView{}, fmt.Errorf("%s - %w", acceptLocation, outcome.refusal)
|
||||
}
|
||||
return outcome.view, nil
|
||||
}
|
||||
|
||||
// prepareAccept validates the request before any storage is read, in the order
|
||||
// of the contract: the request is validated before the account.
|
||||
func (service *Service) prepareAccept(command AcceptCommand) (acceptRequest, error) {
|
||||
const location = "invitation.Service.prepareAccept"
|
||||
switch {
|
||||
case command.ActorID == uuid.Nil:
|
||||
return acceptRequest{}, fmt.Errorf("%s - actor ID must be set: %w", location, ErrForbidden)
|
||||
case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize:
|
||||
return acceptRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey)
|
||||
case command.ExpectedVersion < 1:
|
||||
return acceptRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: "/expected_version", Reason: "must be positive"})
|
||||
case command.TermsVersion < 1:
|
||||
return acceptRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: "/terms_version", Reason: "must be positive"})
|
||||
}
|
||||
textVersion, err := domain.ParseConsentTextVersion(command.TextVersion)
|
||||
if err != nil {
|
||||
return acceptRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: consentTextPointer, Reason: "must be a consent text version"})
|
||||
}
|
||||
fields, err := domain.NewContactFieldSet(command.Fields...)
|
||||
if err != nil {
|
||||
return acceptRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: consentFieldsPointer, Reason: "must name one to four distinct kinds"})
|
||||
}
|
||||
now, err := service.now(location)
|
||||
if err != nil {
|
||||
return acceptRequest{}, err
|
||||
}
|
||||
canonical, err := json.Marshal(acceptFingerprint{
|
||||
InvitationID: command.InvitationID, ExpectedVersion: command.ExpectedVersion, TermsVersion: command.TermsVersion,
|
||||
TextVersion: command.TextVersion, Fields: command.Fields,
|
||||
})
|
||||
if err != nil {
|
||||
return acceptRequest{}, fmt.Errorf("%s - encode canonical request: %w", location, err)
|
||||
}
|
||||
fingerprint := service.keyring.Fingerprint(canonical)
|
||||
scope := service.keyring.IdempotencyScope(acceptOperation, command.IdempotencyKey, command.ActorID.String())
|
||||
return acceptRequest{
|
||||
fingerprint: fingerprint, scope: scope, now: now, textVersion: textVersion, fields: fields,
|
||||
record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention)},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// acceptInTransaction 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 an accepted invitation (200), a terminal state
|
||||
// or a passed deadline (409, stored), the versions (412, not stored), any other
|
||||
// state that does not allow an acceptance (409, stored), and the consent rules
|
||||
// (400, not stored).
|
||||
func (service *Service) acceptInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command AcceptCommand,
|
||||
request acceptRequest,
|
||||
) (acceptOutcome, error) {
|
||||
if err := authorizeCandidate(ctx, unit, command.ActorID); err != nil {
|
||||
return acceptOutcome{}, err
|
||||
}
|
||||
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
|
||||
if err != nil {
|
||||
return acceptOutcome{}, fmt.Errorf("%s - reserve idempotency record: %w", acceptLocation, err)
|
||||
}
|
||||
if !created {
|
||||
return service.replayAccept(ctx, unit, request, command, stored)
|
||||
}
|
||||
entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, true)
|
||||
if errors.Is(err, outbound.ErrInvitationNotFound) {
|
||||
return service.refuseAccept(ctx, unit, command, request, outbound.InvitationAcceptNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return acceptOutcome{}, err
|
||||
}
|
||||
return service.acceptFound(ctx, unit, command, request, entry)
|
||||
}
|
||||
|
||||
// acceptFound applies the checks that follow a found invitation and, when they
|
||||
// pass, stores the acceptance with its consent and grant.
|
||||
func (service *Service) acceptFound(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command AcceptCommand,
|
||||
request acceptRequest,
|
||||
entry outbound.CandidateInvitationEntry,
|
||||
) (acceptOutcome, error) {
|
||||
current := entry.Invitation
|
||||
at := notBefore(request.now, current.UpdatedAt())
|
||||
switch {
|
||||
case current.State() == domain.InvitationAccepted:
|
||||
return service.repeatAccept(ctx, unit, command, request, entry)
|
||||
case current.IsTerminal() || current.ResponseDeadlinePassed(at):
|
||||
return service.refuseAccept(ctx, unit, command, request, outbound.InvitationAcceptStateConflict)
|
||||
}
|
||||
if command.ExpectedVersion != current.Version() || command.TermsVersion != current.TermsVersion() {
|
||||
return acceptOutcome{}, fmt.Errorf("%s - compare versions: %w", acceptLocation, domain.ErrInvitationVersionConflict)
|
||||
}
|
||||
accepted, err := current.Accept(command.TermsVersion, at)
|
||||
if errors.Is(err, domain.ErrInvitationNotAnswerable) {
|
||||
return service.refuseAccept(ctx, unit, command, request, outbound.InvitationAcceptStateConflict)
|
||||
}
|
||||
if err != nil {
|
||||
return acceptOutcome{}, fmt.Errorf("%s - accept invitation: %w", acceptLocation, err)
|
||||
}
|
||||
if err := service.checkAcceptConsent(ctx, unit, command, request); err != nil {
|
||||
return acceptOutcome{}, err
|
||||
}
|
||||
if err := service.storeAcceptance(ctx, unit, command, request, entry, accepted); err != nil {
|
||||
return acceptOutcome{}, err
|
||||
}
|
||||
entry.Invitation = accepted
|
||||
return service.completeAccept(ctx, unit, request, entry)
|
||||
}
|
||||
|
||||
// checkAcceptConsent refuses a consent text that is not the published one and a
|
||||
// kind that the profile does not hold. It stores nothing: the caller returns the
|
||||
// error, and the transaction rolls back.
|
||||
func (service *Service) checkAcceptConsent(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command AcceptCommand,
|
||||
request acceptRequest,
|
||||
) error {
|
||||
if _, err := service.consents.CheckTextVersion(ctx, unit, domain.ConsentPurposeContactDisclosure, request.textVersion); err != nil {
|
||||
if errors.Is(err, consent.ErrStaleConsentText) {
|
||||
return fmt.Errorf("%s - %w", acceptLocation, &domain.InvitationFieldError{Pointer: consentTextPointer, Reason: "must be the published consent text"})
|
||||
}
|
||||
return fmt.Errorf("%s - check consent text: %w", acceptLocation, err)
|
||||
}
|
||||
profile, err := unit.CandidateProfiles().Get(ctx, command.ActorID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read candidate profile: %w", acceptLocation, err)
|
||||
}
|
||||
held := heldContactFields(profile)
|
||||
for index, field := range command.Fields {
|
||||
if !slices.Contains(held, field) {
|
||||
return fmt.Errorf("%s - %w", acceptLocation, &domain.InvitationFieldError{
|
||||
Pointer: fmt.Sprintf("%s/%d", consentFieldsPointer, index), Reason: "the profile holds no such contact",
|
||||
})
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// storeAcceptance writes the acceptance in the transaction: the invitation moves
|
||||
// to accepted with its audit event, the consent C4 is recorded in the ledger, and
|
||||
// the grant of the selected fields is stored next to them.
|
||||
func (service *Service) storeAcceptance(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command AcceptCommand,
|
||||
request acceptRequest,
|
||||
entry outbound.CandidateInvitationEntry,
|
||||
accepted domain.Invitation,
|
||||
) error {
|
||||
current := entry.Invitation
|
||||
event, err := accepted.AnswerEvent(command.ActorID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build audit event: %w", acceptLocation, err)
|
||||
}
|
||||
if err := unit.Invitations().Accept(ctx, current.Version(), accepted, event); err != nil {
|
||||
if errors.Is(err, outbound.ErrInvitationVersionConflict) {
|
||||
return fmt.Errorf("%s - store acceptance: %w", acceptLocation, domain.ErrInvitationVersionConflict)
|
||||
}
|
||||
return fmt.Errorf("%s - store acceptance: %w", acceptLocation, err)
|
||||
}
|
||||
granted, err := service.consents.GrantContact(ctx, unit, consent.ContactGrantInput{
|
||||
SubjectID: command.ActorID, OrganizationID: current.OrganizationID(), OrganizationName: entry.OrganizationName,
|
||||
Fields: request.fields, InvitationID: current.ID(), InvitationTermsVersion: command.TermsVersion,
|
||||
TextVersion: request.textVersion,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - grant consent C4: %w", acceptLocation, err)
|
||||
}
|
||||
if !granted.Created {
|
||||
return fmt.Errorf("%s - the invitation already has a consent C4 record: %w", acceptLocation, domain.ErrInvalidContactGrant)
|
||||
}
|
||||
grant, err := domain.NewContactGrant(granted.Record, accepted)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build contact grant: %w", acceptLocation, err)
|
||||
}
|
||||
if err := unit.ContactGrants().Create(ctx, grant); err != nil {
|
||||
return fmt.Errorf("%s - store contact grant: %w", acceptLocation, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// repeatAccept answers an acceptance of an invitation that is already accepted.
|
||||
// The same terms version and the same fields answer 200 with the invitation,
|
||||
// even under a new key or an older expected version, and record nothing. Any
|
||||
// other terms version or field set is a conflict with the accepted answer.
|
||||
func (service *Service) repeatAccept(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command AcceptCommand,
|
||||
request acceptRequest,
|
||||
entry outbound.CandidateInvitationEntry,
|
||||
) (acceptOutcome, error) {
|
||||
grant, err := unit.ContactGrants().GetByInvitation(ctx, entry.Invitation.OrganizationID(), entry.Invitation.ID())
|
||||
if err != nil {
|
||||
return acceptOutcome{}, fmt.Errorf("%s - read contact grant: %w", acceptLocation, err)
|
||||
}
|
||||
if grant.TermsVersion() == command.TermsVersion && grant.Fields().Equal(request.fields) {
|
||||
return service.completeAccept(ctx, unit, request, entry)
|
||||
}
|
||||
return service.refuseAccept(ctx, unit, command, request, outbound.InvitationAcceptStateConflict)
|
||||
}
|
||||
|
||||
// completeAccept stores the successful outcome under the key and builds the
|
||||
// response with the contact grant.
|
||||
func (service *Service) completeAccept(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
request acceptRequest,
|
||||
entry outbound.CandidateInvitationEntry,
|
||||
) (acceptOutcome, error) {
|
||||
view, err := service.candidateView(ctx, unit, entry, request.now)
|
||||
if err != nil {
|
||||
return acceptOutcome{}, err
|
||||
}
|
||||
result := outbound.InvitationAcceptResult{InvitationID: entry.Invitation.ID(), Outcome: outbound.InvitationAcceptAccepted}
|
||||
if err := finishAccept(ctx, unit, request, result); err != nil {
|
||||
return acceptOutcome{}, err
|
||||
}
|
||||
return acceptOutcome{view: view}, nil
|
||||
}
|
||||
|
||||
// refuseAccept stores a refusal that the contract keeps under the key and lets
|
||||
// the transaction commit, since nothing else was written.
|
||||
func (service *Service) refuseAccept(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command AcceptCommand,
|
||||
request acceptRequest,
|
||||
outcome outbound.InvitationAcceptOutcome,
|
||||
) (acceptOutcome, error) {
|
||||
result := outbound.InvitationAcceptResult{InvitationID: command.InvitationID, Outcome: outcome}
|
||||
if err := finishAccept(ctx, unit, request, result); err != nil {
|
||||
return acceptOutcome{}, err
|
||||
}
|
||||
return acceptOutcome{refusal: acceptRefusal(outcome)}, nil
|
||||
}
|
||||
|
||||
func finishAccept(ctx context.Context, unit outbound.UnitOfWork, request acceptRequest, result outbound.InvitationAcceptResult) error {
|
||||
if err := unit.InvitationAcceptResults().SaveAcceptResult(ctx, request.scope, result); err != nil {
|
||||
return fmt.Errorf("%s - store outcome: %w", acceptLocation, err)
|
||||
}
|
||||
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
|
||||
return fmt.Errorf("%s - purge expired idempotency records: %w", acceptLocation, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func acceptRefusal(outcome outbound.InvitationAcceptOutcome) error {
|
||||
if outcome == outbound.InvitationAcceptNotFound {
|
||||
return outbound.ErrInvitationNotFound
|
||||
}
|
||||
return ErrAnswerBlocked
|
||||
}
|
||||
|
||||
// replayAccept returns the stored outcome of the same request, or refuses a key
|
||||
// used with another request. A stored acceptance is rebuilt from the invitation
|
||||
// and its grant, which the acceptance keeps.
|
||||
func (service *Service) replayAccept(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
request acceptRequest,
|
||||
command AcceptCommand,
|
||||
stored outbound.IdempotencyRecord,
|
||||
) (acceptOutcome, error) {
|
||||
if stored.Fingerprint != request.fingerprint {
|
||||
return acceptOutcome{}, fmt.Errorf("%s - compare request fingerprint: %w", acceptLocation, ErrIdempotencyKeyReused)
|
||||
}
|
||||
original, err := unit.InvitationAcceptResults().GetAcceptResult(ctx, request.scope)
|
||||
if err != nil {
|
||||
return acceptOutcome{}, fmt.Errorf("%s - read original outcome: %w", acceptLocation, err)
|
||||
}
|
||||
if original.InvitationID != command.InvitationID {
|
||||
return acceptOutcome{}, fmt.Errorf("%s - validate original outcome: %w", acceptLocation, domain.ErrInvalidInvitation)
|
||||
}
|
||||
if original.Outcome != outbound.InvitationAcceptAccepted {
|
||||
return acceptOutcome{refusal: acceptRefusal(original.Outcome)}, nil
|
||||
}
|
||||
entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, false)
|
||||
if err != nil {
|
||||
return acceptOutcome{}, err
|
||||
}
|
||||
view, err := service.candidateView(ctx, unit, entry, request.now)
|
||||
if err != nil {
|
||||
return acceptOutcome{}, err
|
||||
}
|
||||
return acceptOutcome{view: view}, nil
|
||||
}
|
||||
|
||||
// heldContactFields lists the kinds that the profile holds as confirmed claims,
|
||||
// in the order of ContactFieldKind. A suggestion that nobody confirmed is not
|
||||
// held, so it can never be disclosed.
|
||||
func heldContactFields(profile domain.CandidateProfile) []domain.ContactField {
|
||||
content := profile.Content()
|
||||
held := make([]domain.ContactField, 0, 4)
|
||||
if claim, ok := content.FullName(); confirmedClaim(claim.Status(), ok) {
|
||||
held = append(held, domain.ContactFieldFullName)
|
||||
}
|
||||
if claim, ok := content.Email(); confirmedClaim(claim.Status(), ok) {
|
||||
held = append(held, domain.ContactFieldEmail)
|
||||
}
|
||||
if claim, ok := content.Phone(); confirmedClaim(claim.Status(), ok) {
|
||||
held = append(held, domain.ContactFieldPhone)
|
||||
}
|
||||
if claim, ok := content.Telegram(); confirmedClaim(claim.Status(), ok) {
|
||||
held = append(held, domain.ContactFieldTelegram)
|
||||
}
|
||||
return held
|
||||
}
|
||||
|
||||
func confirmedClaim(status domain.ProfileClaimStatus, present bool) bool {
|
||||
return present && status == domain.ProfileClaimConfirmed
|
||||
}
|
||||
@@ -0,0 +1,467 @@
|
||||
package invitation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// testC4Version is the published C4 text of the fakes.
|
||||
const testC4Version = domain.ConsentTextVersion("c4-2026-10-01")
|
||||
|
||||
func (unit *testUnit) ContactGrants() outbound.ContactGrantRepository {
|
||||
return testContactGrants{state: unit.state}
|
||||
}
|
||||
|
||||
func (unit *testUnit) InvitationAcceptResults() outbound.InvitationAcceptResultRepository {
|
||||
return testInvitations{state: unit.state}
|
||||
}
|
||||
|
||||
func (unit *testUnit) CandidateProfiles() outbound.CandidateProfileRepository {
|
||||
return testProfiles{state: unit.state}
|
||||
}
|
||||
|
||||
func (unit *testUnit) ConsentTexts() outbound.ConsentTextRepository {
|
||||
return testConsentTexts{}
|
||||
}
|
||||
|
||||
func (unit *testUnit) ConsentLedger() outbound.ConsentLedger {
|
||||
return testConsentLedger{state: unit.state}
|
||||
}
|
||||
|
||||
func (unit *testUnit) PrivacySettings() outbound.PrivacySettingsRepository {
|
||||
return testPrivacySettings{state: unit.state}
|
||||
}
|
||||
|
||||
// Accept applies the compare-and-swap of the acceptance like the database does:
|
||||
// the stored invitation must be answerable at the expected version.
|
||||
func (repository testInvitations) Accept(_ context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error {
|
||||
current, ok := repository.state.invitations[next.ID()]
|
||||
answerable := current.State() == domain.InvitationDelivered || current.State() == domain.InvitationViewed
|
||||
if !ok || current.Version() != expectedVersion || !answerable {
|
||||
return outbound.ErrInvitationVersionConflict
|
||||
}
|
||||
repository.state.invitations[next.ID()] = next
|
||||
repository.state.events = append(repository.state.events, event)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository testInvitations) SaveAcceptResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, result outbound.InvitationAcceptResult) error {
|
||||
repository.state.acceptResults[scope] = result
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository testInvitations) GetAcceptResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (outbound.InvitationAcceptResult, error) {
|
||||
result, ok := repository.state.acceptResults[scope]
|
||||
if !ok {
|
||||
return outbound.InvitationAcceptResult{}, outbound.ErrInvitationAcceptResultNotFound
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type testContactGrants struct {
|
||||
state *testState
|
||||
}
|
||||
|
||||
func (repository testContactGrants) Create(_ context.Context, grant domain.ContactGrant) error {
|
||||
if _, exists := repository.state.grants[grant.InvitationID()]; exists {
|
||||
return errors.New("contact grant already exists")
|
||||
}
|
||||
repository.state.grants[grant.InvitationID()] = grant
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository testContactGrants) GetByInvitation(_ context.Context, organizationID, invitationID uuid.UUID) (domain.ContactGrant, error) {
|
||||
grant, ok := repository.state.grants[invitationID]
|
||||
if !ok || grant.OrganizationID() != organizationID {
|
||||
return domain.ContactGrant{}, outbound.ErrContactGrantNotFound
|
||||
}
|
||||
return grant, nil
|
||||
}
|
||||
|
||||
type testProfiles struct {
|
||||
outbound.CandidateProfileRepository
|
||||
|
||||
state *testState
|
||||
}
|
||||
|
||||
func (repository testProfiles) Get(_ context.Context, userID uuid.UUID) (domain.CandidateProfile, error) {
|
||||
if profile, ok := repository.state.profiles[userID]; ok {
|
||||
return profile, nil
|
||||
}
|
||||
return domain.EmptyCandidateProfile(userID)
|
||||
}
|
||||
|
||||
// testConsentTexts publishes one C4 text that names the organization.
|
||||
type testConsentTexts struct {
|
||||
outbound.ConsentTextRepository
|
||||
}
|
||||
|
||||
func (testConsentTexts) Current(_ context.Context, purpose domain.ConsentPurpose, _ time.Time) (domain.ConsentText, error) {
|
||||
if purpose != domain.ConsentPurposeContactDisclosure {
|
||||
return domain.ConsentText{}, outbound.ErrConsentTextNotFound
|
||||
}
|
||||
body := "I consent to the transfer of the contact data I select to {organization} for this invitation."
|
||||
hash := domain.HashConsentText(body)
|
||||
text, err := domain.RestoreConsentText(domain.StoredConsentText{
|
||||
Purpose: string(purpose), Version: string(testC4Version), Body: body, Hash: hash[:], Kind: string(domain.ConsentTextKindDemo),
|
||||
PublishedAt: time.Date(2026, time.October, 1, 0, 0, 0, 0, time.UTC),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.ConsentText{}, err
|
||||
}
|
||||
return text, nil
|
||||
}
|
||||
|
||||
// testConsentLedger stores the C4 record of an acceptance once per invitation,
|
||||
// as the ledger does.
|
||||
type testConsentLedger struct {
|
||||
outbound.ConsentLedger
|
||||
|
||||
state *testState
|
||||
}
|
||||
|
||||
func (ledger testConsentLedger) GrantContact(_ context.Context, grant domain.ContactConsentGrant) (domain.ConsentRecord, bool, error) {
|
||||
if existing, ok := ledger.state.consentRecords[grant.InvitationID()]; ok {
|
||||
return existing, false, nil
|
||||
}
|
||||
hash := grant.TextHash()
|
||||
fields := make([]string, 0, 4)
|
||||
for _, field := range grant.Fields().Fields() {
|
||||
fields = append(fields, string(field))
|
||||
}
|
||||
record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{
|
||||
ID: grant.ID(), SubjectID: grant.SubjectID(), Purpose: string(domain.ConsentPurposeContactDisclosure),
|
||||
TextVersion: string(grant.TextVersion()), TextHash: hash[:], Source: string(domain.ConsentSourceInvitationAcceptance),
|
||||
State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(), OrganizationID: grant.OrganizationID(),
|
||||
OrganizationName: grant.OrganizationName(), FieldSet: fields, InvitationID: grant.InvitationID(),
|
||||
InvitationTermsVersion: grant.InvitationTermsVersion(),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.ConsentRecord{}, false, err
|
||||
}
|
||||
ledger.state.consentRecords[grant.InvitationID()] = record
|
||||
return record, true, nil
|
||||
}
|
||||
|
||||
// testPrivacySettings reads the publication and the hidings of the fakes. A
|
||||
// candidate who never published has the closed publication.
|
||||
type testPrivacySettings struct {
|
||||
outbound.PrivacySettingsRepository
|
||||
|
||||
state *testState
|
||||
}
|
||||
|
||||
func (repository testPrivacySettings) ReadSettings(_ context.Context, userID uuid.UUID) (outbound.CandidatePrivacySettings, error) {
|
||||
publication, ok := repository.state.publications[userID]
|
||||
if !ok {
|
||||
closed, err := domain.NewPublication(userID)
|
||||
if err != nil {
|
||||
return outbound.CandidatePrivacySettings{}, err
|
||||
}
|
||||
publication = closed
|
||||
}
|
||||
return outbound.CandidatePrivacySettings{Publication: publication}, nil
|
||||
}
|
||||
|
||||
func (repository testPrivacySettings) GetHiddenOrganization(_ context.Context, userID, organizationID uuid.UUID) (outbound.HiddenOrganizationRecord, error) {
|
||||
if !repository.state.hidden[[2]uuid.UUID{userID, organizationID}] {
|
||||
return outbound.HiddenOrganizationRecord{}, outbound.ErrCandidatePrivacySettingsNotFound
|
||||
}
|
||||
return outbound.HiddenOrganizationRecord{OrganizationID: organizationID, OrganizationName: "Test organization"}, nil
|
||||
}
|
||||
|
||||
// testProfile builds a candidate profile whose confirmed claims are the held
|
||||
// kinds, the way the profile service stores them.
|
||||
func testProfile(t *testing.T, candidateID uuid.UUID, held ...domain.ContactField) domain.CandidateProfile {
|
||||
t.Helper()
|
||||
confirmed := func(value string) *domain.ProfileClaimInput[string] {
|
||||
return &domain.ProfileClaimInput[string]{Value: value, Status: domain.ProfileClaimConfirmed}
|
||||
}
|
||||
var input domain.CandidateProfileInput
|
||||
for _, field := range held {
|
||||
switch field {
|
||||
case domain.ContactFieldFullName:
|
||||
input.FullName = confirmed("Test Candidate")
|
||||
case domain.ContactFieldEmail:
|
||||
input.Email = confirmed("candidate@example.test")
|
||||
case domain.ContactFieldPhone:
|
||||
input.Phone = confirmed("+70000000000")
|
||||
case domain.ContactFieldTelegram:
|
||||
input.Telegram = confirmed("@candidate_test")
|
||||
}
|
||||
}
|
||||
empty, err := domain.EmptyCandidateProfile(candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("EmptyCandidateProfile() error = %v", err)
|
||||
}
|
||||
profile, _, err := empty.Replace(input, 0, time.Date(2026, time.October, 9, 9, 0, 0, 0, time.UTC))
|
||||
if err != nil {
|
||||
t.Fatalf("Replace() error = %v", err)
|
||||
}
|
||||
return profile
|
||||
}
|
||||
|
||||
// setState changes the committed state of the fakes between commands.
|
||||
func (test *harness) setState(change func(state *testState)) {
|
||||
test.transactor.mu.Lock()
|
||||
defer test.transactor.mu.Unlock()
|
||||
change(&test.transactor.state)
|
||||
}
|
||||
|
||||
func (test *harness) setProfile(t *testing.T, candidateID uuid.UUID, held ...domain.ContactField) {
|
||||
t.Helper()
|
||||
profile := testProfile(t, candidateID, held...)
|
||||
test.setState(func(state *testState) { state.profiles[candidateID] = profile })
|
||||
}
|
||||
|
||||
func (test *harness) publish(candidateID uuid.UUID, at time.Time) {
|
||||
publication, err := domain.RestorePublication(domain.StoredPublication{
|
||||
UserID: candidateID, State: string(domain.PublicationPublished), Fields: []string{string(domain.CardFieldCategories)},
|
||||
ConsentRecordID: uuid.Must(uuid.NewV7()), PublishedAt: at, Version: 1,
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
test.setState(func(state *testState) { state.publications[candidateID] = publication })
|
||||
}
|
||||
|
||||
func acceptCommand(actorID, invitationID uuid.UUID, version, terms int64, key string, fields ...domain.ContactField) AcceptCommand {
|
||||
return AcceptCommand{
|
||||
ActorID: actorID, InvitationID: invitationID, IdempotencyKey: key, ExpectedVersion: version,
|
||||
TermsVersion: terms, TextVersion: string(testC4Version), Fields: fields,
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcceptMineStoresTheAcceptanceAndTheGrantOfTheSelectedFieldsOnly(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
sent, candidateID := test.deliveredTo(t)
|
||||
test.setProfile(t, candidateID, domain.ContactFieldEmail)
|
||||
test.setTime(sent.DeliveredAt.Add(time.Hour))
|
||||
|
||||
// The profile holds only the email, so a phone request is refused by its
|
||||
// pointer, and nothing is stored.
|
||||
_, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-phone",
|
||||
domain.ContactFieldPhone))
|
||||
if got := fieldPointer(t, err); got != "/consent_c4/fields/0" {
|
||||
t.Fatalf("pointer = %s, want /consent_c4/fields/0", got)
|
||||
}
|
||||
if state := test.transactor.snapshot(); len(state.grants) != 0 || len(state.consentRecords) != 0 || len(state.acceptResults) != 0 {
|
||||
t.Fatalf("a refused acceptance stored grants %d, consents %d, outcomes %d", len(state.grants), len(state.consentRecords), len(state.acceptResults))
|
||||
}
|
||||
|
||||
view, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-email",
|
||||
domain.ContactFieldEmail))
|
||||
if err != nil {
|
||||
t.Fatalf("AcceptMine() error = %v", err)
|
||||
}
|
||||
if view.State != domain.InvitationAccepted || view.Version != sent.Version+1 || view.TermsVersion != sent.TermsVersion ||
|
||||
view.RespondedAt == nil || view.ContactConsent != nil || view.ContactGrant == nil {
|
||||
t.Fatalf("accepted = %+v, want the accepted invitation with its grant and no offer", view)
|
||||
}
|
||||
grant := view.ContactGrant
|
||||
if len(grant.Fields) != 1 || grant.Fields[0] != domain.ContactFieldEmail || grant.Status != domain.ContactGrantActive ||
|
||||
grant.Readable || grant.BlockedBy == nil || *grant.BlockedBy != domain.ContactAccessBlockVisibility ||
|
||||
grant.TermsVersion != sent.TermsVersion || grant.ConsentTextVersion != testC4Version {
|
||||
t.Fatalf("grant = %+v, want the email only, active, blocked by visibility while the profile is not published", grant)
|
||||
}
|
||||
state := test.transactor.snapshot()
|
||||
invitation := state.invitations[sent.ID]
|
||||
last := state.events[len(state.events)-1]
|
||||
if invitation.State() != domain.InvitationAccepted || len(state.grants) != 1 || len(state.consentRecords) != 1 ||
|
||||
last.Kind != domain.InvitationEventAccepted || last.ActorID != candidateID || len(last.ChangedFields) != 0 {
|
||||
t.Fatalf("stored state = %s grants %d consents %d last event %s, want one acceptance, grant, and consent",
|
||||
invitation.State(), len(state.grants), len(state.consentRecords), last.Kind)
|
||||
}
|
||||
record := state.consentRecords[sent.ID]
|
||||
if record.InvitationTermsVersion() != sent.TermsVersion || record.OrganizationName() != "Test organization" ||
|
||||
len(record.Fields().Fields()) != 1 || record.Fields().Fields()[0] != domain.ContactFieldEmail {
|
||||
t.Fatalf("C4 record = %s, want the organization, the terms version, and the email only", record)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcceptMineRepeatsWithoutRecordingAgainAndRefusesAnotherChoice(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
sent, candidateID := test.deliveredTo(t)
|
||||
test.setProfile(t, candidateID, domain.ContactFieldEmail, domain.ContactFieldPhone)
|
||||
test.setTime(sent.DeliveredAt.Add(time.Hour))
|
||||
first, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-first",
|
||||
domain.ContactFieldEmail))
|
||||
if err != nil {
|
||||
t.Fatalf("AcceptMine() error = %v", err)
|
||||
}
|
||||
before := test.transactor.snapshot()
|
||||
|
||||
test.setTime(sent.DeliveredAt.Add(2 * time.Hour))
|
||||
// A new key with the older expected version and the same terms and fields
|
||||
// answers the accepted invitation without a second grant or event.
|
||||
again, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-again",
|
||||
domain.ContactFieldEmail))
|
||||
if err != nil || again.Version != first.Version || again.ContactGrant == nil || again.ContactGrant.ID != first.ContactGrant.ID {
|
||||
t.Fatalf("repeat = %+v, %v; want the first acceptance", again, err)
|
||||
}
|
||||
replay, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-first",
|
||||
domain.ContactFieldEmail))
|
||||
if err != nil || replay.ContactGrant == nil || replay.ContactGrant.ID != first.ContactGrant.ID {
|
||||
t.Fatalf("replay = %+v, %v; want the stored response", replay, err)
|
||||
}
|
||||
after := test.transactor.snapshot()
|
||||
if len(after.events) != len(before.events) || len(after.grants) != 1 || len(after.consentRecords) != 1 {
|
||||
t.Fatalf("repeats stored events %d to %d, grants %d, consents %d", len(before.events), len(after.events), len(after.grants), len(after.consentRecords))
|
||||
}
|
||||
|
||||
// Another field set or a reused key with another body is refused, and the
|
||||
// refusal is stored under its key.
|
||||
if _, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-more",
|
||||
domain.ContactFieldEmail, domain.ContactFieldPhone)); !errors.Is(err, ErrAnswerBlocked) {
|
||||
t.Fatalf("another field set error = %v, want ErrAnswerBlocked", err)
|
||||
}
|
||||
if _, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-first",
|
||||
domain.ContactFieldPhone)); !errors.Is(err, ErrIdempotencyKeyReused) {
|
||||
t.Fatalf("reused key error = %v, want ErrIdempotencyKeyReused", err)
|
||||
}
|
||||
if got := test.transactor.snapshot().acceptResults; len(got) != 3 {
|
||||
t.Fatalf("stored outcomes = %d, want accepted, accepted again, and the refused field set", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcceptMineRefusesAStaleTermsVersionWithoutStoringAnything(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
sent, candidateID := test.deliveredTo(t)
|
||||
test.setProfile(t, candidateID, domain.ContactFieldEmail)
|
||||
before := test.transactor.snapshot()
|
||||
|
||||
// The terms the candidate read are not the current ones: 412, nothing
|
||||
// recorded, and no outcome under the key.
|
||||
for name, command := range map[string]AcceptCommand{
|
||||
"stale terms": acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion+1, "stale-terms", domain.ContactFieldEmail),
|
||||
"stale version": acceptCommand(candidateID, sent.ID, sent.Version+1, sent.TermsVersion, "stale-version", domain.ContactFieldEmail),
|
||||
} {
|
||||
if _, err := test.service.AcceptMine(t.Context(), command); !errors.Is(err, domain.ErrInvitationVersionConflict) {
|
||||
t.Fatalf("%s error = %v, want ErrInvitationVersionConflict", name, err)
|
||||
}
|
||||
}
|
||||
after := test.transactor.snapshot()
|
||||
if len(after.grants) != 0 || len(after.consentRecords) != 0 || len(after.acceptResults) != 0 || len(after.events) != len(before.events) {
|
||||
t.Fatalf("a stale acceptance stored grants %d, consents %d, outcomes %d", len(after.grants), len(after.consentRecords), len(after.acceptResults))
|
||||
}
|
||||
if after.invitations[sent.ID].State() != domain.InvitationDelivered {
|
||||
t.Fatalf("state = %s, want delivered", after.invitations[sent.ID].State())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcceptMineAtTheDeadlineStoresTheConflictAndGrantsNothing(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
sent, candidateID := test.deliveredTo(t)
|
||||
test.setProfile(t, candidateID, domain.ContactFieldEmail)
|
||||
test.setTime(*sent.ResponseDeadlineAt)
|
||||
|
||||
_, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version+5, sent.TermsVersion, "late",
|
||||
domain.ContactFieldEmail))
|
||||
if !errors.Is(err, ErrAnswerBlocked) {
|
||||
t.Fatalf("late acceptance error = %v, want ErrAnswerBlocked whatever the version", err)
|
||||
}
|
||||
state := test.transactor.snapshot()
|
||||
if result := state.acceptResults[testKeyring{}.IdempotencyScope(acceptOperation, "late", candidateID.String())]; result.Outcome != outbound.InvitationAcceptStateConflict {
|
||||
t.Fatalf("stored outcome = %+v, want state_conflict under the key", result)
|
||||
}
|
||||
if len(state.grants) != 0 || len(state.consentRecords) != 0 || state.invitations[sent.ID].State() != domain.InvitationDelivered {
|
||||
t.Fatalf("a late acceptance changed the invitation: grants %d, consents %d", len(state.grants), len(state.consentRecords))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcceptMineChecksTheConsentTextAndTheHeldKinds(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
sent, candidateID := test.deliveredTo(t)
|
||||
test.setProfile(t, candidateID, domain.ContactFieldFullName)
|
||||
test.setTime(sent.DeliveredAt.Add(time.Hour))
|
||||
|
||||
outdated := acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "outdated", domain.ContactFieldFullName)
|
||||
outdated.TextVersion = "c4-2025-01-01"
|
||||
if got := fieldPointer(t, mustFail(t, test, outdated)); got != "/consent_c4/text_version" {
|
||||
t.Fatalf("outdated text pointer = %s, want /consent_c4/text_version", got)
|
||||
}
|
||||
if got := fieldPointer(t, mustFail(t, test, acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "email",
|
||||
domain.ContactFieldFullName, domain.ContactFieldEmail))); got != "/consent_c4/fields/1" {
|
||||
t.Fatalf("unheld kind pointer = %s, want /consent_c4/fields/1", got)
|
||||
}
|
||||
if state := test.transactor.snapshot(); len(state.grants) != 0 || len(state.consentRecords) != 0 || len(state.acceptResults) != 0 {
|
||||
t.Fatalf("refused consent stored grants %d, consents %d, outcomes %d", len(state.grants), len(state.consentRecords), len(state.acceptResults))
|
||||
}
|
||||
|
||||
// The offer lists the held kinds in the order of the contract and shows the
|
||||
// text with the organization name. A profile without a kind has no offer.
|
||||
offered := decodeOffer(t, test, candidateID, sent.ID)
|
||||
if offered.Text.TextVersion != testC4Version || !strings.Contains(offered.Text.Text, "Test organization") ||
|
||||
strings.Contains(offered.Text.Text, "{organization}") || len(offered.AvailableFields) != 1 || offered.AvailableFields[0] != domain.ContactFieldFullName {
|
||||
t.Fatalf("offer = %+v, want the rendered text and the held kind", offered)
|
||||
}
|
||||
test.setProfile(t, candidateID)
|
||||
read, err := test.service.GetMine(t.Context(), candidateID, sent.ID)
|
||||
if err != nil || read.ContactConsent != nil {
|
||||
t.Fatalf("GetMine without a held kind = %+v, %v; want no offer", read.ContactConsent, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcceptedInvitationReadsTheGrantAndKeepsThePublicationAndTheHiding(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
sent, candidateID := test.deliveredTo(t)
|
||||
test.setProfile(t, candidateID, domain.ContactFieldEmail)
|
||||
test.setTime(sent.DeliveredAt.Add(time.Hour))
|
||||
test.publish(candidateID, *sent.DeliveredAt)
|
||||
test.setState(func(state *testState) { state.hidden[[2]uuid.UUID{candidateID, test.organizationID}] = true })
|
||||
publications := test.transactor.snapshot().publications
|
||||
|
||||
accepted, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "hidden",
|
||||
domain.ContactFieldEmail))
|
||||
if err != nil {
|
||||
t.Fatalf("AcceptMine() while hidden error = %v", err)
|
||||
}
|
||||
if accepted.ContactGrant == nil || accepted.ContactGrant.Readable || accepted.ContactGrant.BlockedBy == nil {
|
||||
t.Fatalf("grant while hidden = %+v, want stored and blocked by visibility", accepted.ContactGrant)
|
||||
}
|
||||
state := test.transactor.snapshot()
|
||||
if len(state.publications) != len(publications) || state.publications[candidateID].State() != domain.PublicationPublished ||
|
||||
!state.hidden[[2]uuid.UUID{candidateID, test.organizationID}] {
|
||||
t.Fatal("the acceptance changed the publication or lifted the hiding")
|
||||
}
|
||||
|
||||
// Unhiding the organization makes the same grant readable; the grant
|
||||
// itself never changes.
|
||||
test.setState(func(state *testState) { delete(state.hidden, [2]uuid.UUID{candidateID, test.organizationID}) })
|
||||
read, err := test.service.GetMine(t.Context(), candidateID, sent.ID)
|
||||
if err != nil || read.ContactGrant == nil || !read.ContactGrant.Readable || read.ContactGrant.BlockedBy != nil ||
|
||||
read.ContactGrant.ID != accepted.ContactGrant.ID {
|
||||
t.Fatalf("read after unhiding = %+v, %v; want the same grant readable", read.ContactGrant, err)
|
||||
}
|
||||
}
|
||||
|
||||
// decodeOffer reads the invitation of the candidate and returns its consent offer.
|
||||
func decodeOffer(t *testing.T, test *harness, candidateID, invitationID uuid.UUID) domain.ContactConsentOffer {
|
||||
t.Helper()
|
||||
read, err := test.service.GetMine(t.Context(), candidateID, invitationID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetMine() error = %v", err)
|
||||
}
|
||||
if read.ContactConsent == nil {
|
||||
t.Fatal("GetMine() = no contact consent offer, want one")
|
||||
}
|
||||
return *read.ContactConsent
|
||||
}
|
||||
|
||||
// mustFail returns the error of an acceptance that must be refused.
|
||||
func mustFail(t *testing.T, test *harness, command AcceptCommand) error {
|
||||
t.Helper()
|
||||
_, err := test.service.AcceptMine(t.Context(), command)
|
||||
if err == nil {
|
||||
t.Fatalf("AcceptMine(%s) succeeded, want a refusal", command.IdempotencyKey)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -144,7 +144,7 @@ func (service *Service) declineInTransaction(
|
||||
return declineOutcome{}, fmt.Errorf("%s - reserve idempotency record: %w", declineLocation, err)
|
||||
}
|
||||
if !created {
|
||||
return replayDecline(ctx, unit, request, command, stored)
|
||||
return service.replayDecline(ctx, unit, request, command, stored)
|
||||
}
|
||||
entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, true)
|
||||
if errors.Is(err, outbound.ErrInvitationNotFound) {
|
||||
@@ -176,7 +176,7 @@ func (service *Service) declineFound(
|
||||
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 service.completeDecline(ctx, unit, request, entry)
|
||||
}
|
||||
return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineStateConflict)
|
||||
}
|
||||
@@ -204,18 +204,18 @@ func (service *Service) declineFound(
|
||||
return declineOutcome{}, fmt.Errorf("%s - store decline: %w", declineLocation, err)
|
||||
}
|
||||
entry.Invitation = declined
|
||||
return completeDecline(ctx, unit, request, entry)
|
||||
return service.completeDecline(ctx, unit, request, entry)
|
||||
}
|
||||
|
||||
// completeDecline stores the successful outcome under the key and builds the
|
||||
// response with the stored decline.
|
||||
func completeDecline(
|
||||
func (service *Service) completeDecline(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
request declineRequest,
|
||||
entry outbound.CandidateInvitationEntry,
|
||||
) (declineOutcome, error) {
|
||||
view, err := candidateView(ctx, unit, entry)
|
||||
view, err := service.candidateView(ctx, unit, entry, request.now)
|
||||
if err != nil {
|
||||
return declineOutcome{}, err
|
||||
}
|
||||
@@ -263,7 +263,7 @@ func declineRefusal(outcome outbound.InvitationDeclineOutcome) error {
|
||||
// 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(
|
||||
func (service *Service) replayDecline(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
request declineRequest,
|
||||
@@ -290,7 +290,7 @@ func replayDecline(
|
||||
if entry.Invitation.State() != domain.InvitationDeclined {
|
||||
return declineOutcome{}, fmt.Errorf("%s - validate original response: %w", declineLocation, domain.ErrInvalidInvitation)
|
||||
}
|
||||
view, err := candidateView(ctx, unit, entry)
|
||||
view, err := service.candidateView(ctx, unit, entry, request.now)
|
||||
if err != nil {
|
||||
return declineOutcome{}, err
|
||||
}
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
// candidate card of the organization, the idempotent creation, and the
|
||||
// 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.
|
||||
// view, records a structured decline, and accepts the current terms with the
|
||||
// consent C4 and its contact grant in one transaction. The cancellation and
|
||||
// the revocation of a grant belong to later operations.
|
||||
package invitation
|
||||
|
||||
import (
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/consent"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -70,6 +71,14 @@ type CandidateResolver func(ctx context.Context, unit outbound.UnitOfWork, actor
|
||||
// invitation that is already charged is allowed without a second charge.
|
||||
type InvitationQuota func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error)
|
||||
|
||||
// ContactConsents is the consent ledger of the acceptance. It reads the
|
||||
// published C4 text, checks the version that the candidate saw, and records
|
||||
// the C4 grant inside the caller's transaction. consent.Service implements it.
|
||||
type ContactConsents interface {
|
||||
CheckTextVersion(ctx context.Context, repositories outbound.ConsentRepositories, purpose domain.ConsentPurpose, version domain.ConsentTextVersion) (domain.ConsentText, error)
|
||||
GrantContact(ctx context.Context, repositories outbound.ConsentRepositories, input consent.ContactGrantInput) (consent.GrantResult, error)
|
||||
}
|
||||
|
||||
// DeliveryNotifier records, inside the caller's transaction, the outbox
|
||||
// events that tell the candidate about a delivered invitation: the in-platform
|
||||
// notification and the email. Neither blocks the delivery: the invitation is
|
||||
@@ -90,11 +99,13 @@ type Dependencies struct {
|
||||
Candidates CandidateResolver
|
||||
Quota InvitationQuota
|
||||
Notifier DeliveryNotifier
|
||||
Clock func() time.Time
|
||||
// Consents records the consent C4 of an acceptance in its transaction.
|
||||
Consents ContactConsents
|
||||
Clock func() time.Time
|
||||
}
|
||||
|
||||
// Service applies organization-scoped invitation commands and reads, and the
|
||||
// candidate's reads, view, and decline of the own invitations.
|
||||
// candidate's reads, view, decline, and acceptance of the own invitations.
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
keyring Keyring
|
||||
@@ -102,13 +113,14 @@ type Service struct {
|
||||
candidates CandidateResolver
|
||||
quota InvitationQuota
|
||||
notifier DeliveryNotifier
|
||||
consents ContactConsents
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
// NewService fails at startup when a required dependency is missing.
|
||||
func NewService(deps Dependencies) (*Service, error) {
|
||||
if deps.Transactor == nil || deps.Keyring == nil || deps.Candidates == nil || deps.Quota == nil ||
|
||||
deps.Notifier == nil || deps.Clock == nil {
|
||||
deps.Notifier == nil || deps.Consents == nil || deps.Clock == nil {
|
||||
return nil, errors.New("invitation.NewService - every dependency must be set")
|
||||
}
|
||||
if _, err := deps.PseudonymKey.ForOrganization(uuid.New(), uuid.New()); err != nil {
|
||||
@@ -116,7 +128,8 @@ func NewService(deps Dependencies) (*Service, error) {
|
||||
}
|
||||
return &Service{
|
||||
transactor: deps.Transactor, keyring: deps.Keyring, pseudonymKey: deps.PseudonymKey,
|
||||
candidates: deps.Candidates, quota: deps.Quota, notifier: deps.Notifier, clock: deps.Clock,
|
||||
candidates: deps.Candidates, quota: deps.Quota, notifier: deps.Notifier, consents: deps.Consents,
|
||||
clock: deps.Clock,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/candidateview"
|
||||
"lincodex/backend/internal/usecase/consent"
|
||||
)
|
||||
|
||||
type testKeyring struct{}
|
||||
@@ -47,6 +48,16 @@ type testState struct {
|
||||
// the decline outcomes kept under a key.
|
||||
declines map[uuid.UUID]domain.InvitationDecline
|
||||
declineResults map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationDeclineResult
|
||||
// grants holds the contact grants by invitation, acceptResults the
|
||||
// acceptance outcomes by key, and consentRecords the C4 records by
|
||||
// invitation. profiles and publications are the candidates' profiles and
|
||||
// publication settings, and hidden the hidden organizations by candidate.
|
||||
grants map[uuid.UUID]domain.ContactGrant
|
||||
acceptResults map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationAcceptResult
|
||||
consentRecords map[uuid.UUID]domain.ConsentRecord
|
||||
profiles map[uuid.UUID]domain.CandidateProfile
|
||||
publications map[uuid.UUID]domain.Publication
|
||||
hidden map[[2]uuid.UUID]bool
|
||||
// charged lists the invitations charged against the organization quota,
|
||||
// and notified the delivered invitations that were notified.
|
||||
charged []uuid.UUID
|
||||
@@ -63,6 +74,12 @@ func newTestState() testState {
|
||||
needVersions: map[[3]string]bool{},
|
||||
declines: map[uuid.UUID]domain.InvitationDecline{},
|
||||
declineResults: map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationDeclineResult{},
|
||||
grants: map[uuid.UUID]domain.ContactGrant{},
|
||||
acceptResults: map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationAcceptResult{},
|
||||
consentRecords: map[uuid.UUID]domain.ConsentRecord{},
|
||||
profiles: map[uuid.UUID]domain.CandidateProfile{},
|
||||
publications: map[uuid.UUID]domain.Publication{},
|
||||
hidden: map[[2]uuid.UUID]bool{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,6 +116,24 @@ func (state testState) clone() testState {
|
||||
for scope, result := range state.declineResults {
|
||||
cloned.declineResults[scope] = result
|
||||
}
|
||||
for id, grant := range state.grants {
|
||||
cloned.grants[id] = grant
|
||||
}
|
||||
for scope, result := range state.acceptResults {
|
||||
cloned.acceptResults[scope] = result
|
||||
}
|
||||
for id, record := range state.consentRecords {
|
||||
cloned.consentRecords[id] = record
|
||||
}
|
||||
for id, profile := range state.profiles {
|
||||
cloned.profiles[id] = profile
|
||||
}
|
||||
for id, publication := range state.publications {
|
||||
cloned.publications[id] = publication
|
||||
}
|
||||
for key, hidden := range state.hidden {
|
||||
cloned.hidden[key] = hidden
|
||||
}
|
||||
cloned.charged = slices.Clone(state.charged)
|
||||
cloned.notified = slices.Clone(state.notified)
|
||||
return cloned
|
||||
@@ -417,6 +452,7 @@ func newHarness(t *testing.T) *harness {
|
||||
return outbound.CompanyQuotaDecision{Allowed: true}, nil
|
||||
},
|
||||
Notifier: testNotifier{},
|
||||
Consents: consent.NewService(test.transactor, func() time.Time { return current }),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewService() error = %v", err)
|
||||
|
||||
@@ -2,6 +2,7 @@ package invitation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
@@ -25,8 +26,12 @@ func (service *Service) GetMine(ctx context.Context, actorID, invitationID uuid.
|
||||
if actorID == uuid.Nil {
|
||||
return domain.CandidateInvitationView{}, fmt.Errorf("%s - actor ID must be set: %w", getMineLocation, ErrForbidden)
|
||||
}
|
||||
now, err := service.now(getMineLocation)
|
||||
if err != nil {
|
||||
return domain.CandidateInvitationView{}, err
|
||||
}
|
||||
var view domain.CandidateInvitationView
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeCandidate(ctx, unit, actorID); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -34,7 +39,7 @@ func (service *Service) GetMine(ctx context.Context, actorID, invitationID uuid.
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
view, err = candidateView(ctx, unit, entry)
|
||||
view, err = service.candidateView(ctx, unit, entry, now)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
@@ -85,7 +90,7 @@ func (service *Service) ViewMine(ctx context.Context, actorID, invitationID uuid
|
||||
}
|
||||
entry.Invitation = viewed
|
||||
}
|
||||
view, err = candidateView(ctx, unit, entry)
|
||||
view, err = service.candidateView(ctx, unit, entry, now)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
@@ -123,25 +128,118 @@ func readCandidateEntry(
|
||||
// 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"
|
||||
//
|
||||
// The consent offer is set while an acceptance is possible, and the contact
|
||||
// grant once the invitation is accepted. The grant is readable only while the
|
||||
// organization may read the profile, so a hidden profile shows the grant as
|
||||
// blocked by visibility. at is the time of the command that builds the view.
|
||||
func (service *Service) candidateView(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
entry outbound.CandidateInvitationEntry,
|
||||
at time.Time,
|
||||
) (domain.CandidateInvitationView, error) {
|
||||
const location = "invitation.Service.candidateView"
|
||||
current := entry.Invitation
|
||||
var decline *domain.InvitationDecline
|
||||
if entry.Invitation.State() == domain.InvitationDeclined {
|
||||
stored, err := unit.Invitations().GetDecline(ctx, entry.Invitation.OrganizationID(), entry.Invitation.ID())
|
||||
if current.State() == domain.InvitationDeclined {
|
||||
stored, err := unit.Invitations().GetDecline(ctx, current.OrganizationID(), current.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,
|
||||
view, err := current.CandidateView(domain.InvitationOrganizationRef{
|
||||
ID: current.OrganizationID(), Name: entry.OrganizationName,
|
||||
}, decline)
|
||||
if err != nil {
|
||||
return domain.CandidateInvitationView{}, fmt.Errorf("%s - build view: %w", location, err)
|
||||
}
|
||||
switch {
|
||||
case current.State() == domain.InvitationAccepted:
|
||||
grant, err := unit.ContactGrants().GetByInvitation(ctx, current.OrganizationID(), current.ID())
|
||||
if err != nil {
|
||||
return domain.CandidateInvitationView{}, fmt.Errorf("%s - read contact grant: %w", location, err)
|
||||
}
|
||||
visible, err := candidateVisibleTo(ctx, unit, current.CandidateID(), current.OrganizationID())
|
||||
if err != nil {
|
||||
return domain.CandidateInvitationView{}, fmt.Errorf("%s - read visibility: %w", location, err)
|
||||
}
|
||||
grantView := grant.CandidateView(visible)
|
||||
view.ContactGrant = &grantView
|
||||
case acceptancePossible(current, at):
|
||||
offer, offered, err := contactConsentOffer(ctx, unit, current, entry.OrganizationName, at)
|
||||
if err != nil {
|
||||
return domain.CandidateInvitationView{}, fmt.Errorf("%s - build consent offer: %w", location, err)
|
||||
}
|
||||
if offered {
|
||||
view.ContactConsent = &offer
|
||||
}
|
||||
}
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// acceptancePossible reports the states and the time in which the candidate
|
||||
// may accept: a delivered or viewed invitation before its deadline.
|
||||
func acceptancePossible(invitation domain.Invitation, at time.Time) bool {
|
||||
state := invitation.State()
|
||||
return (state == domain.InvitationDelivered || state == domain.InvitationViewed) &&
|
||||
invitation.IsDelivered() && !invitation.ResponseDeadlinePassed(at)
|
||||
}
|
||||
|
||||
// candidateVisibleTo reports whether the organization may read the profile of
|
||||
// the candidate now: the publication is effective, and the candidate has not
|
||||
// hidden the organization. The read model of the profile applies C2 and the
|
||||
// revocation of C2; the hiding is a record of its own.
|
||||
func candidateVisibleTo(ctx context.Context, unit outbound.UnitOfWork, candidateID, organizationID uuid.UUID) (bool, error) {
|
||||
const location = "invitation.candidateVisibleTo"
|
||||
settings, err := unit.PrivacySettings().ReadSettings(ctx, candidateID)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s - read privacy settings: %w", location, err)
|
||||
}
|
||||
if settings.Publication.State() != domain.PublicationPublished {
|
||||
return false, nil
|
||||
}
|
||||
_, err = unit.PrivacySettings().GetHiddenOrganization(ctx, candidateID, organizationID)
|
||||
switch {
|
||||
case err == nil:
|
||||
return false, nil
|
||||
case errors.Is(err, outbound.ErrCandidatePrivacySettingsNotFound):
|
||||
return true, nil
|
||||
default:
|
||||
return false, fmt.Errorf("%s - read hidden organization: %w", location, err)
|
||||
}
|
||||
}
|
||||
|
||||
// contactConsentOffer builds the consent offer of an invitation: the rendered
|
||||
// C4 text and the kinds that the profile holds. It reports false when the
|
||||
// profile holds no kind, because a grant must cover at least one field.
|
||||
func contactConsentOffer(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
invitation domain.Invitation,
|
||||
organizationName string,
|
||||
at time.Time,
|
||||
) (domain.ContactConsentOffer, bool, error) {
|
||||
profile, err := unit.CandidateProfiles().Get(ctx, invitation.CandidateID())
|
||||
if err != nil {
|
||||
return domain.ContactConsentOffer{}, false, fmt.Errorf("read candidate profile: %w", err)
|
||||
}
|
||||
held := heldContactFields(profile)
|
||||
if len(held) == 0 {
|
||||
return domain.ContactConsentOffer{}, false, nil
|
||||
}
|
||||
text, err := unit.ConsentTexts().Current(ctx, domain.ConsentPurposeContactDisclosure, at)
|
||||
if err != nil {
|
||||
return domain.ContactConsentOffer{}, false, fmt.Errorf("read consent C4 text: %w", err)
|
||||
}
|
||||
offer, err := domain.NewContactConsentOffer(text, organizationName, held)
|
||||
if err != nil {
|
||||
return domain.ContactConsentOffer{}, false, fmt.Errorf("build offer: %w", err)
|
||||
}
|
||||
return offer, true, nil
|
||||
}
|
||||
|
||||
// notBefore keeps a clock that stepped back from recording a change before
|
||||
// the last one.
|
||||
func notBefore(now, last time.Time) time.Time {
|
||||
|
||||
Reference in new issue
Block a user