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
@@ -30,6 +30,7 @@ type InvitationOperations interface {
|
||||
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)
|
||||
AcceptMine(ctx context.Context, command invitationusecase.AcceptCommand) (domain.CandidateInvitationView, error)
|
||||
}
|
||||
|
||||
// InvitationHandler serves the organization side of invitation drafts and
|
||||
|
||||
@@ -31,6 +31,66 @@ func (handler *Handler) DeclineMyInvitation(ctx context.Context, request *api.In
|
||||
return handler.invitation.DeclineMyInvitation(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) AcceptMyInvitation(ctx context.Context, request *api.InvitationAcceptance, params api.AcceptMyInvitationParams) (api.AcceptMyInvitationRes, error) {
|
||||
if handler.invitation == nil {
|
||||
return handler.UnimplementedHandler.AcceptMyInvitation(ctx, request, params)
|
||||
}
|
||||
return handler.invitation.AcceptMyInvitation(ctx, request, params)
|
||||
}
|
||||
|
||||
// AcceptMyInvitation accepts the current terms of an invitation with the consent
|
||||
// C4. The fields come from the body as kinds only; the server takes the values
|
||||
// from the profile, and the request never carries them.
|
||||
func (handler *InvitationHandler) AcceptMyInvitation(
|
||||
ctx context.Context,
|
||||
request *api.InvitationAcceptance,
|
||||
params api.AcceptMyInvitationParams,
|
||||
) (api.AcceptMyInvitationRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.AcceptMyInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.AcceptMyInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
fields := make([]domain.ContactField, 0, len(request.ConsentC4.Fields))
|
||||
for _, field := range request.ConsentC4.Fields {
|
||||
fields = append(fields, domain.ContactField(field))
|
||||
}
|
||||
view, err := handler.operations.AcceptMine(ctx, invitationusecase.AcceptCommand{
|
||||
ActorID: principal.UserID, InvitationID: params.InvitationID, IdempotencyKey: params.IdempotencyKey,
|
||||
ExpectedVersion: int64(request.ExpectedVersion), TermsVersion: int64(request.TermsVersion),
|
||||
TextVersion: string(request.ConsentC4.TextVersion), Fields: fields,
|
||||
})
|
||||
if err != nil {
|
||||
return invitationAcceptFailure(ctx, err)
|
||||
}
|
||||
return &api.CandidateInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: candidateInvitationResponse(view)}, nil
|
||||
}
|
||||
|
||||
func invitationAcceptFailure(ctx context.Context, err error) (api.AcceptMyInvitationRes, error) {
|
||||
if errors.Is(err, invitationusecase.ErrAnswerBlocked) {
|
||||
return (*api.AcceptMyInvitationConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
|
||||
}
|
||||
switch classifyInvitationError(err) {
|
||||
case invitationFailureForbidden:
|
||||
return (*api.AcceptMyInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case invitationFailureNotFound:
|
||||
return (*api.AcceptMyInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case invitationFailureKeyReused:
|
||||
return (*api.AcceptMyInvitationUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
|
||||
case invitationFailureBadKey:
|
||||
return (*api.AcceptMyInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
|
||||
case invitationFailureInvalid:
|
||||
return (*api.AcceptMyInvitationBadRequest)(invitationValidationProblem(ctx, err)), nil
|
||||
case invitationFailureVersionConflict:
|
||||
return (*api.AcceptMyInvitationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
|
||||
case invitationFailureStateConflict, invitationFailureOther:
|
||||
return nil, err
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (handler *InvitationHandler) GetMyInvitation(ctx context.Context, params api.GetMyInvitationParams) (api.GetMyInvitationRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
@@ -123,10 +183,9 @@ func invitationDeclineFailure(ctx context.Context, err error) (api.DeclineMyInvi
|
||||
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.
|
||||
// candidateInvitationResponse maps the candidate's view. The consent offer is
|
||||
// set only while an acceptance is possible, and the contact grant only after
|
||||
// the acceptance; otherwise both are null, as the contract requires.
|
||||
func candidateInvitationResponse(view domain.CandidateInvitationView) api.CandidateInvitation {
|
||||
response := api.CandidateInvitation{
|
||||
ID: view.ID,
|
||||
@@ -138,7 +197,13 @@ func candidateInvitationResponse(view domain.CandidateInvitationView) api.Candid
|
||||
RespondedAt: nullableTimestamp(view.RespondedAt), UpdatedAt: api.Timestamp(view.UpdatedAt),
|
||||
}
|
||||
response.ContactConsent.SetToNull()
|
||||
if view.ContactConsent != nil {
|
||||
response.ContactConsent.SetTo(contactConsentOfferResponse(*view.ContactConsent))
|
||||
}
|
||||
response.ContactGrant.SetToNull()
|
||||
if view.ContactGrant != nil {
|
||||
response.ContactGrant.SetTo(contactGrantResponse(*view.ContactGrant))
|
||||
}
|
||||
if view.Decline == nil {
|
||||
response.Decline.SetToNull()
|
||||
return response
|
||||
@@ -154,3 +219,43 @@ func candidateInvitationResponse(view domain.CandidateInvitationView) api.Candid
|
||||
response.Decline.SetTo(record)
|
||||
return response
|
||||
}
|
||||
|
||||
func contactConsentOfferResponse(offer domain.ContactConsentOffer) api.ContactConsentOffer {
|
||||
fields := make([]api.ContactFieldKind, 0, len(offer.AvailableFields))
|
||||
for _, field := range offer.AvailableFields {
|
||||
fields = append(fields, api.ContactFieldKind(field))
|
||||
}
|
||||
return api.ContactConsentOffer{
|
||||
Text: api.ContactConsentText{
|
||||
TextVersion: api.ConsentTextVersion(offer.Text.TextVersion), Text: offer.Text.Text,
|
||||
},
|
||||
AvailableFields: fields,
|
||||
}
|
||||
}
|
||||
|
||||
// contactGrantResponse maps the grant as the candidate reads it: the kinds, the
|
||||
// status, and whether the organization can read them now, never a value.
|
||||
func contactGrantResponse(view domain.ContactGrantView) api.ContactGrant {
|
||||
fields := make([]api.ContactFieldKind, 0, len(view.Fields))
|
||||
for _, field := range view.Fields {
|
||||
fields = append(fields, api.ContactFieldKind(field))
|
||||
}
|
||||
response := api.ContactGrant{
|
||||
ID: view.ID, Fields: fields, Status: api.ContactGrantState(view.Status), Readable: view.Readable,
|
||||
TermsVersion: api.InvitationTermsVersion(view.TermsVersion),
|
||||
ConsentTextVersion: api.ConsentTextVersion(view.ConsentTextVersion),
|
||||
GrantedAt: api.Timestamp(view.GrantedAt),
|
||||
}
|
||||
if view.BlockedBy == nil {
|
||||
response.BlockedBy.SetToNull()
|
||||
} else {
|
||||
response.BlockedBy.SetTo(api.ContactAccessBlock(*view.BlockedBy))
|
||||
}
|
||||
response.RevokedAt = nullableTimestamp(view.RevokedAt)
|
||||
if view.RevocationReason == nil {
|
||||
response.RevocationReason.SetToNull()
|
||||
} else {
|
||||
response.RevocationReason.SetTo(api.ContactRevocationReason(*view.RevocationReason))
|
||||
}
|
||||
return response
|
||||
}
|
||||
@@ -94,3 +94,28 @@ func TestCandidateInvitationResponseCarriesTheDeclineAndNoCandidateData(t *testi
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationAcceptFailuresMapToTheContractStatuses(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
text := &domain.InvitationFieldError{Pointer: "/consent_c4/text_version", Reason: "x"}
|
||||
for name, test := range map[string]struct {
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
"employer": {invitationusecase.ErrForbidden, "*api.AcceptMyInvitationForbidden"},
|
||||
"unknown": {fmt.Errorf("wrapped: %w", outbound.ErrInvitationNotFound), "*api.AcceptMyInvitationNotFound"},
|
||||
"reused key": {invitationusecase.ErrIdempotencyKeyReused, "*api.AcceptMyInvitationUnprocessableEntity"},
|
||||
"bad key": {invitationusecase.ErrInvalidIdempotencyKey, "*api.AcceptMyInvitationBadRequest"},
|
||||
"consent text": {fmt.Errorf("wrapped: %w", text), "*api.AcceptMyInvitationBadRequest"},
|
||||
"stale version": {fmt.Errorf("wrapped: %w", domain.ErrInvitationVersionConflict), "*api.AcceptMyInvitationPreconditionFailed"},
|
||||
"terminal or late": {fmt.Errorf("wrapped: %w", invitationusecase.ErrAnswerBlocked), "*api.AcceptMyInvitationConflict"},
|
||||
} {
|
||||
response, unexpected := invitationAcceptFailure(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 := invitationAcceptFailure(ctx, errors.New("storage failed")); unexpected == nil {
|
||||
t.Error("an unknown failure produced a public response instead of reaching the responder")
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
@@ -26,6 +27,20 @@ type companyQuotaRepository struct {
|
||||
|
||||
var _ outbound.CompanyQuotaRepository = companyQuotaRepository{}
|
||||
|
||||
// quotaScope names the usage rows that one reservation counts. An organization
|
||||
// at a tier that shares its holding pool counts the usage of every E0
|
||||
// organization of the holding; any other tier counts its own usage only.
|
||||
type quotaScope struct {
|
||||
organizationID uuid.UUID
|
||||
// holdingID is the holding of the shared pool, and uuid.Nil when the
|
||||
// organization keeps its own pool.
|
||||
holdingID uuid.UUID
|
||||
}
|
||||
|
||||
func (scope quotaScope) sharesHoldingPool() bool {
|
||||
return scope.holdingID != uuid.Nil
|
||||
}
|
||||
|
||||
func (repository companyQuotaRepository) ReserveInvitation(
|
||||
ctx context.Context,
|
||||
quota domain.CompanyQuota,
|
||||
@@ -38,7 +53,8 @@ func (repository companyQuotaRepository) ReserveInvitation(
|
||||
if invitationID == uuid.Nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation ID must be set: %w", location, domain.ErrInvalidCompanyQuota)
|
||||
}
|
||||
if err := repository.lockAndCheckSnapshot(ctx, location, quota); err != nil {
|
||||
scope, err := repository.lockAndCheckSnapshot(ctx, location, quota)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
|
||||
@@ -57,18 +73,15 @@ func (repository companyQuotaRepository) ReserveInvitation(
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read invitation usage: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
|
||||
usage, err := repository.queries.CountCompanyInvitationQuotaWindow(ctx, sqlc.CountCompanyInvitationQuotaWindowParams{
|
||||
OrganizationID: organizationID,
|
||||
WindowStart: pgTime(quota.InvitationWindowStart()),
|
||||
})
|
||||
count, earliestAt, err := repository.countInvitationUsage(ctx, location, scope, quota.InvitationWindowStart())
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - count invitation usage: %w", location, mapOrganizationError(err))
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
if usage.UsageCount < 0 {
|
||||
if count < 0 {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation usage count is negative", location)
|
||||
}
|
||||
if usage.UsageCount >= quota.InvitationLimit() {
|
||||
earliest, err := quotaWindowEarliest(usage.EarliestAt)
|
||||
if count >= quota.InvitationLimit() {
|
||||
earliest, err := quotaWindowEarliest(earliestAt)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read earliest invitation expiry: %w", location, err)
|
||||
}
|
||||
@@ -92,7 +105,8 @@ func (repository companyQuotaRepository) ReserveCardView(
|
||||
if candidateID == uuid.Nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCompanyQuota)
|
||||
}
|
||||
if err := repository.lockAndCheckSnapshot(ctx, location, quota); err != nil {
|
||||
scope, err := repository.lockAndCheckSnapshot(ctx, location, quota)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
|
||||
@@ -101,7 +115,7 @@ func (repository companyQuotaRepository) ReserveCardView(
|
||||
if err != nil || handled {
|
||||
return decision, err
|
||||
}
|
||||
return repository.reserveNewCardView(ctx, location, quota, candidateID, organizationID)
|
||||
return repository.reserveNewCardView(ctx, location, quota, candidateID, scope)
|
||||
}
|
||||
|
||||
func (repository companyQuotaRepository) reserveExistingCardView(
|
||||
@@ -166,20 +180,17 @@ func (repository companyQuotaRepository) reserveNewCardView(
|
||||
location string,
|
||||
quota domain.CompanyQuota,
|
||||
candidateID uuid.UUID,
|
||||
organizationID uuid.UUID,
|
||||
scope quotaScope,
|
||||
) (outbound.CompanyQuotaDecision, error) {
|
||||
usage, err := repository.queries.CountCompanyCardViewQuotaWindow(ctx, sqlc.CountCompanyCardViewQuotaWindowParams{
|
||||
OrganizationID: pgUUID(organizationID),
|
||||
WindowStart: pgTime(quota.CardViewWindowStart()),
|
||||
})
|
||||
count, earliestAt, err := repository.countCardViewUsage(ctx, location, scope, quota.CardViewWindowStart())
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - count card-view usage: %w", location, mapOrganizationError(err))
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
if usage.UsageCount < 0 {
|
||||
if count < 0 {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - card-view usage count is negative", location)
|
||||
}
|
||||
if usage.UsageCount >= quota.CardViewLimit() {
|
||||
earliest, err := quotaWindowEarliest(usage.EarliestAt)
|
||||
if count >= quota.CardViewLimit() {
|
||||
earliest, err := quotaWindowEarliest(earliestAt)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read earliest card-view expiry: %w", location, err)
|
||||
}
|
||||
@@ -194,30 +205,119 @@ func (repository companyQuotaRepository) reserveNewCardView(
|
||||
return outbound.CompanyQuotaDecision{Allowed: true}, nil
|
||||
}
|
||||
|
||||
// countInvitationUsage returns the invitation usage in the window of scope and
|
||||
// the earliest counted reservation, which sets the retry time of a denial.
|
||||
func (repository companyQuotaRepository) countInvitationUsage(
|
||||
ctx context.Context,
|
||||
location string,
|
||||
scope quotaScope,
|
||||
windowStart time.Time,
|
||||
) (int64, any, error) {
|
||||
if scope.sharesHoldingPool() {
|
||||
usage, err := repository.queries.CountCompanyInvitationQuotaHoldingWindow(ctx, sqlc.CountCompanyInvitationQuotaHoldingWindowParams{
|
||||
HoldingID: pgUUID(scope.holdingID),
|
||||
WindowStart: pgTime(windowStart),
|
||||
})
|
||||
if err != nil {
|
||||
return 0, nil, fmt.Errorf("%s - count invitation usage of the holding pool: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
return usage.UsageCount, usage.EarliestAt, nil
|
||||
}
|
||||
usage, err := repository.queries.CountCompanyInvitationQuotaWindow(ctx, sqlc.CountCompanyInvitationQuotaWindowParams{
|
||||
OrganizationID: pgUUID(scope.organizationID),
|
||||
WindowStart: pgTime(windowStart),
|
||||
})
|
||||
if err != nil {
|
||||
return 0, nil, fmt.Errorf("%s - count invitation usage: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
return usage.UsageCount, usage.EarliestAt, nil
|
||||
}
|
||||
|
||||
// countCardViewUsage is countInvitationUsage for distinct card views.
|
||||
func (repository companyQuotaRepository) countCardViewUsage(
|
||||
ctx context.Context,
|
||||
location string,
|
||||
scope quotaScope,
|
||||
windowStart time.Time,
|
||||
) (int64, any, error) {
|
||||
if scope.sharesHoldingPool() {
|
||||
usage, err := repository.queries.CountCompanyCardViewQuotaHoldingWindow(ctx, sqlc.CountCompanyCardViewQuotaHoldingWindowParams{
|
||||
HoldingID: pgUUID(scope.holdingID),
|
||||
WindowStart: pgTime(windowStart),
|
||||
})
|
||||
if err != nil {
|
||||
return 0, nil, fmt.Errorf("%s - count card-view usage of the holding pool: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
return usage.UsageCount, usage.EarliestAt, nil
|
||||
}
|
||||
usage, err := repository.queries.CountCompanyCardViewQuotaWindow(ctx, sqlc.CountCompanyCardViewQuotaWindowParams{
|
||||
OrganizationID: pgUUID(scope.organizationID),
|
||||
WindowStart: pgTime(windowStart),
|
||||
})
|
||||
if err != nil {
|
||||
return 0, nil, fmt.Errorf("%s - count card-view usage: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
return usage.UsageCount, usage.EarliestAt, nil
|
||||
}
|
||||
|
||||
// LockOrganization takes the organization lock and, for an E0 organization,
|
||||
// the lock of its holding, in that order. Every caller that reserves usage
|
||||
// later takes it first, so the pool is serialized before any other lock.
|
||||
func (repository companyQuotaRepository) LockOrganization(ctx context.Context, organizationID uuid.UUID) error {
|
||||
const location = "companyQuotaRepository.LockOrganization"
|
||||
if _, err := repository.queries.LockCompanyQuotaOrganizationFirst(ctx, pgUUID(organizationID)); err != nil {
|
||||
organization, err := repository.queries.LockCompanyQuotaOrganizationFirst(ctx, pgUUID(organizationID))
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return fmt.Errorf("%s - organization was removed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
|
||||
}
|
||||
return fmt.Errorf("%s - lock organization: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
// The level is read under the organization lock, which a trust change
|
||||
// must also take, so the tier cannot change before the holding is locked.
|
||||
if tier, ok := domain.OrganizationVerificationLevel(organization.VerificationLevel).QuotaTier(); ok && tier.SharesHoldingPool() {
|
||||
if _, err := lockQuotaHolding(ctx, repository.queries, location, organization.HoldingID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// lockAndCheckSnapshot takes the organization lock for the reservation, checks
|
||||
// the stored trust and effective policy against the snapshot, and returns the
|
||||
// usage scope. The holding of an E0 organization is locked after the
|
||||
// organization and before the usage is counted.
|
||||
func (repository companyQuotaRepository) lockAndCheckSnapshot(
|
||||
ctx context.Context,
|
||||
location string,
|
||||
quota domain.CompanyQuota,
|
||||
) error {
|
||||
organizationID := pgUUID(quota.OrganizationID())
|
||||
organization, err := repository.queries.LockCompanyQuotaOrganization(ctx, organizationID)
|
||||
) (quotaScope, error) {
|
||||
organization, err := repository.queries.LockCompanyQuotaOrganization(ctx, pgUUID(quota.OrganizationID()))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return fmt.Errorf("%s - organization was removed after quota resolution: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
|
||||
return quotaScope{}, fmt.Errorf("%s - organization was removed after quota resolution: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - lock organization: %w", location, mapOrganizationError(err))
|
||||
return quotaScope{}, fmt.Errorf("%s - lock organization: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
if err := checkStoredTrust(location, quota, organization); err != nil {
|
||||
return quotaScope{}, err
|
||||
}
|
||||
|
||||
scope := quotaScope{organizationID: quota.OrganizationID()}
|
||||
if quota.Tier().SharesHoldingPool() {
|
||||
scope.holdingID, err = lockQuotaHolding(ctx, repository.queries, location, organization.HoldingID)
|
||||
if err != nil {
|
||||
return quotaScope{}, err
|
||||
}
|
||||
}
|
||||
if err := repository.checkEffectivePolicy(ctx, location, quota); err != nil {
|
||||
return quotaScope{}, err
|
||||
}
|
||||
return scope, nil
|
||||
}
|
||||
|
||||
// checkStoredTrust refuses a reservation whose snapshot no longer matches the
|
||||
// verification of the locked organization.
|
||||
func checkStoredTrust(location string, quota domain.CompanyQuota, organization sqlc.LockCompanyQuotaOrganizationRow) error {
|
||||
if !organization.ID.Valid || organization.ID.Bytes != quota.OrganizationID() ||
|
||||
!organization.VerificationChangedAt.Valid ||
|
||||
organization.VerificationLevel != string(quota.VerificationLevel()) ||
|
||||
@@ -225,7 +325,12 @@ func (repository companyQuotaRepository) lockAndCheckSnapshot(
|
||||
!organization.VerificationChangedAt.Time.Equal(quota.VerificationChangedAt()) {
|
||||
return fmt.Errorf("%s - stored organization trust changed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkEffectivePolicy refuses a reservation whose policy version is no longer
|
||||
// the effective product policy at the application clock snapshot.
|
||||
func (repository companyQuotaRepository) checkEffectivePolicy(ctx context.Context, location string, quota domain.CompanyQuota) error {
|
||||
policy, err := repository.queries.GetEffectivePolicyVersion(ctx, sqlc.GetEffectivePolicyVersionParams{
|
||||
PolicyKey: string(domain.ProductPolicyKey),
|
||||
At: pgTime(quota.At()),
|
||||
@@ -242,6 +347,30 @@ func (repository companyQuotaRepository) lockAndCheckSnapshot(
|
||||
return nil
|
||||
}
|
||||
|
||||
// lockQuotaHolding takes the pool lock of an E0 holding. The caller must hold
|
||||
// the lock of the organization that names the holding.
|
||||
func lockQuotaHolding(
|
||||
ctx context.Context,
|
||||
queries *sqlc.Queries,
|
||||
location string,
|
||||
holdingID pgtype.UUID,
|
||||
) (uuid.UUID, error) {
|
||||
if !holdingID.Valid {
|
||||
return uuid.Nil, fmt.Errorf("%s - organization has no holding", location)
|
||||
}
|
||||
locked, err := queries.LockCompanyQuotaHolding(ctx, holdingID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return uuid.Nil, fmt.Errorf("%s - holding was removed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - lock holding: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
if !locked.Valid {
|
||||
return uuid.Nil, fmt.Errorf("%s - locked holding has no identifier", location)
|
||||
}
|
||||
return uuid.UUID(locked.Bytes), nil
|
||||
}
|
||||
|
||||
func (repository companyQuotaRepository) cleanupExpiredCardViews(
|
||||
ctx context.Context,
|
||||
location string,
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var (
|
||||
_ outbound.InvitationAcceptResultRepository = invitationRepository{}
|
||||
_ outbound.ContactGrantRepository = contactGrantRepository{}
|
||||
)
|
||||
|
||||
func (unit *UnitOfWork) InvitationAcceptResults() outbound.InvitationAcceptResultRepository {
|
||||
return invitationRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
func (unit *UnitOfWork) ContactGrants() outbound.ContactGrantRepository {
|
||||
return contactGrantRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
type contactGrantRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
// Accept stores the acceptance of an invitation. The compare-and-swap applies
|
||||
// only to a delivered or viewed invitation at the expected version and terms
|
||||
// version, before its deadline, so a stale writer loses without changing it.
|
||||
func (repository invitationRepository) Accept(
|
||||
ctx context.Context,
|
||||
expectedVersion int64,
|
||||
next domain.Invitation,
|
||||
event domain.InvitationEvent,
|
||||
) error {
|
||||
const location = "invitationRepository.Accept"
|
||||
stored := next.Stored()
|
||||
if expectedVersion < 1 || stored.Version != expectedVersion+1 || stored.State != string(domain.InvitationAccepted) ||
|
||||
stored.RespondedAt == nil || event.Kind != domain.InvitationEventAccepted {
|
||||
return fmt.Errorf("%s - the next version must be the acceptance 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.AcceptInvitation(ctx, sqlc.AcceptInvitationParams{
|
||||
NextVersion: stored.Version, AcceptedAt: pgTime(*stored.RespondedAt), OrganizationID: pgUUID(stored.OrganizationID),
|
||||
InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion, TermsVersion: stored.TermsVersion,
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return fmt.Errorf("%s - accept invitation: %w", location, outbound.ErrInvitationVersionConflict)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - accept invitation: %w", location, mapInvitationError(err))
|
||||
}
|
||||
return repository.insertEvent(ctx, location, event)
|
||||
}
|
||||
|
||||
func (repository invitationRepository) SaveAcceptResult(
|
||||
ctx context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
result outbound.InvitationAcceptResult,
|
||||
) error {
|
||||
const location = "invitationRepository.SaveAcceptResult"
|
||||
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
||||
return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
if err := validateInvitationAcceptResult(result); err != nil {
|
||||
return fmt.Errorf("%s - validate outcome: %w", location, err)
|
||||
}
|
||||
if err := repository.queries.InsertInvitationAcceptResult(ctx, sqlc.InsertInvitationAcceptResultParams{
|
||||
ScopeHash: scope[:], InvitationID: pgUUID(result.InvitationID), Outcome: string(result.Outcome),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - store outcome: %w", location, mapInvitationAcceptResultError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository invitationRepository) GetAcceptResult(
|
||||
ctx context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
) (outbound.InvitationAcceptResult, error) {
|
||||
const location = "invitationRepository.GetAcceptResult"
|
||||
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
||||
return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
row, err := repository.queries.GetInvitationAcceptResult(ctx, scope[:])
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return outbound.InvitationAcceptResult{}, outbound.ErrInvitationAcceptResultNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - read outcome: %w", location, mapInvitationError(err))
|
||||
}
|
||||
if !row.InvitationID.Valid {
|
||||
return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - stored outcome has no invitation: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
result := outbound.InvitationAcceptResult{
|
||||
InvitationID: uuid.UUID(row.InvitationID.Bytes), Outcome: outbound.InvitationAcceptOutcome(row.Outcome),
|
||||
}
|
||||
if err := validateInvitationAcceptResult(result); err != nil {
|
||||
return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - validate stored outcome: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func validateInvitationAcceptResult(result outbound.InvitationAcceptResult) error {
|
||||
const location = "postgres.validateInvitationAcceptResult"
|
||||
switch result.Outcome {
|
||||
case outbound.InvitationAcceptAccepted:
|
||||
if result.InvitationID == uuid.Nil {
|
||||
return fmt.Errorf("%s - an accepted outcome names the invitation: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
case outbound.InvitationAcceptNotFound, outbound.InvitationAcceptStateConflict:
|
||||
// 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 mapInvitationAcceptResultError(err error) error {
|
||||
var pgError *pgconn.PgError
|
||||
if errors.As(err, &pgError) && pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitation_accept_results_idempotency_fkey" {
|
||||
return fmt.Errorf("postgres.mapInvitationAcceptResultError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound)
|
||||
}
|
||||
return mapInvitationError(err)
|
||||
}
|
||||
|
||||
// Create stores a grant of an accepted invitation. The row can only be created
|
||||
// active: a revoked grant is never stored by a new acceptance.
|
||||
func (repository contactGrantRepository) Create(ctx context.Context, grant domain.ContactGrant) error {
|
||||
const location = "contactGrantRepository.Create"
|
||||
if grant.IsZero() || grant.Status() != domain.ContactGrantActive {
|
||||
return fmt.Errorf("%s - the grant must be built by the domain and active: %w", location, domain.ErrInvalidContactGrant)
|
||||
}
|
||||
stored := grant.Stored()
|
||||
if err := repository.queries.InsertContactGrant(ctx, sqlc.InsertContactGrantParams{
|
||||
ID: pgUUID(stored.ID), OrganizationID: pgUUID(stored.OrganizationID), CandidateID: pgUUID(stored.CandidateID),
|
||||
SourceInvitationID: pgUUID(stored.InvitationID), ConsentRecordID: pgUUID(stored.ConsentRecordID),
|
||||
TermsVersion: stored.TermsVersion, Fields: stored.Fields, ConsentTextVersion: stored.ConsentTextVersion,
|
||||
GrantedAt: pgTime(stored.GrantedAt),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert contact grant: %w", location, mapInvitationError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByInvitation reads the grant of one invitation of one organization. The
|
||||
// read rebuilds the grant through the domain, so a stored row that breaks a
|
||||
// rule fails instead of being served.
|
||||
func (repository contactGrantRepository) GetByInvitation(
|
||||
ctx context.Context,
|
||||
organizationID, invitationID uuid.UUID,
|
||||
) (domain.ContactGrant, error) {
|
||||
const location = "contactGrantRepository.GetByInvitation"
|
||||
if organizationID == uuid.Nil || invitationID == uuid.Nil {
|
||||
return domain.ContactGrant{}, fmt.Errorf("%s - organization and invitation IDs must be set: %w", location, domain.ErrInvalidContactGrant)
|
||||
}
|
||||
row, err := repository.queries.GetContactGrantByInvitation(ctx, sqlc.GetContactGrantByInvitationParams{
|
||||
OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.ContactGrant{}, fmt.Errorf("%s - select contact grant: %w", location, outbound.ErrContactGrantNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.ContactGrant{}, fmt.Errorf("%s - select contact grant: %w", location, mapInvitationError(err))
|
||||
}
|
||||
stored, err := storedContactGrantRow(row)
|
||||
if err != nil {
|
||||
return domain.ContactGrant{}, fmt.Errorf("%s - read stored grant: %w", location, err)
|
||||
}
|
||||
grant, err := domain.RestoreContactGrant(stored)
|
||||
if err != nil {
|
||||
return domain.ContactGrant{}, fmt.Errorf("%s - restore contact grant: %w", location, err)
|
||||
}
|
||||
if stored.OrganizationID != organizationID || stored.InvitationID != invitationID {
|
||||
return domain.ContactGrant{}, fmt.Errorf("%s - stored grant has another scope: %w", location, domain.ErrInvalidContactGrant)
|
||||
}
|
||||
return grant, nil
|
||||
}
|
||||
|
||||
// storedContactGrantRow maps a grant row to its stored form. A row without an
|
||||
// identifier or a time is refused before the domain rebuilds the grant.
|
||||
func storedContactGrantRow(row sqlc.ContactGrant) (domain.StoredContactGrant, error) {
|
||||
if !row.ID.Valid || !row.OrganizationID.Valid || !row.CandidateID.Valid || !row.SourceInvitationID.Valid ||
|
||||
!row.ConsentRecordID.Valid || !row.GrantedAt.Valid {
|
||||
return domain.StoredContactGrant{}, fmt.Errorf("stored grant has missing identifiers: %w", domain.ErrInvalidContactGrant)
|
||||
}
|
||||
stored := domain.StoredContactGrant{
|
||||
ID: uuid.UUID(row.ID.Bytes), OrganizationID: uuid.UUID(row.OrganizationID.Bytes),
|
||||
CandidateID: uuid.UUID(row.CandidateID.Bytes), InvitationID: uuid.UUID(row.SourceInvitationID.Bytes),
|
||||
ConsentRecordID: uuid.UUID(row.ConsentRecordID.Bytes), TermsVersion: row.TermsVersion, Fields: row.Fields,
|
||||
ConsentTextVersion: row.ConsentTextVersion, GrantedAt: row.GrantedAt.Time.UTC(),
|
||||
}
|
||||
if row.RevokedAt.Valid {
|
||||
revokedAt := row.RevokedAt.Time.UTC()
|
||||
stored.RevokedAt = &revokedAt
|
||||
}
|
||||
if row.RevocationReason.Valid {
|
||||
stored.RevocationReason = row.RevocationReason.String
|
||||
}
|
||||
return stored, nil
|
||||
}
|
||||
@@ -24,6 +24,7 @@ var organizationConstraintErrors = map[constraintViolation]error{
|
||||
{uniqueViolationCode, "memberships_user_id_organization_id_key"}: outbound.ErrMembershipExists,
|
||||
{foreignKeyViolationCode, "memberships_organization_id_fkey"}: outbound.ErrOrganizationNotFound,
|
||||
{foreignKeyViolationCode, "memberships_user_id_fkey"}: outbound.ErrUserNotFound,
|
||||
{foreignKeyViolationCode, "holdings_founder_account_id_fkey"}: outbound.ErrUserNotFound,
|
||||
{foreignKeyViolationCode, "organization_representatives_organization_id_fkey"}: outbound.ErrOrganizationNotFound,
|
||||
}
|
||||
|
||||
@@ -72,10 +73,14 @@ func (repository organizationRepository) CreateWithOwner(ctx context.Context, or
|
||||
case owner.OrganizationID() != organization.ID() || owner.Role() != domain.OrganizationRoleOwner || !owner.GrantsAccess():
|
||||
return fmt.Errorf("%s - owner must be the active owner membership of the organization: %w", location, domain.ErrInvalidMembership)
|
||||
}
|
||||
holdingID, err := repository.ensureFounderHolding(ctx, owner.UserID(), organization.CreatedAt())
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - join founder holding: %w", location, err)
|
||||
}
|
||||
profile := organization.Profile()
|
||||
contacts := profile.Contacts()
|
||||
verification := organization.Verification()
|
||||
err := repository.queries.InsertOrganization(ctx, sqlc.InsertOrganizationParams{
|
||||
err = repository.queries.InsertOrganization(ctx, sqlc.InsertOrganizationParams{
|
||||
ID: pgUUID(organization.ID()),
|
||||
Name: profile.Name(),
|
||||
Description: pgOptionalText(profile.Description()),
|
||||
@@ -90,6 +95,7 @@ func (repository organizationRepository) CreateWithOwner(ctx context.Context, or
|
||||
Version: organization.Version(),
|
||||
CreatedAt: pgTime(organization.CreatedAt()),
|
||||
UpdatedAt: pgTime(organization.UpdatedAt()),
|
||||
HoldingID: pgUUID(holdingID),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - insert organization: %w", location, mapOrganizationError(err))
|
||||
@@ -103,6 +109,37 @@ func (repository organizationRepository) CreateWithOwner(ctx context.Context, or
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureFounderHolding returns the holding of the founder account and creates
|
||||
// it in the caller's transaction when the account has none. The insert ignores
|
||||
// an existing holding, so a concurrent creation of the same account waits for
|
||||
// the other transaction and then reads the holding that was stored.
|
||||
func (repository organizationRepository) ensureFounderHolding(
|
||||
ctx context.Context,
|
||||
founderID uuid.UUID,
|
||||
createdAt time.Time,
|
||||
) (uuid.UUID, error) {
|
||||
const location = "organizationRepository.ensureFounderHolding"
|
||||
holding, err := domain.NewHolding(founderID, createdAt)
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - build holding: %w", location, err)
|
||||
}
|
||||
if err := repository.queries.InsertHoldingIfAbsent(ctx, sqlc.InsertHoldingIfAbsentParams{
|
||||
ID: pgUUID(holding.ID()),
|
||||
FounderAccountID: pgUUID(holding.FounderAccountID()),
|
||||
CreatedAt: pgTime(holding.CreatedAt()),
|
||||
}); err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - insert holding: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
stored, err := repository.queries.GetHoldingIDByFounder(ctx, pgUUID(founderID))
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - read stored holding: %w", location, mapOrganizationError(err))
|
||||
}
|
||||
if !stored.Valid {
|
||||
return uuid.Nil, fmt.Errorf("%s - stored holding has no identifier", location)
|
||||
}
|
||||
return uuid.UUID(stored.Bytes), nil
|
||||
}
|
||||
|
||||
func (repository organizationRepository) SaveCreationResult(
|
||||
ctx context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
|
||||
@@ -11,6 +11,39 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const countCompanyCardViewQuotaHoldingWindow = `-- name: CountCompanyCardViewQuotaHoldingWindow :one
|
||||
SELECT
|
||||
count(*)::bigint AS usage_count,
|
||||
min(usage.last_seen_at) AS earliest_at
|
||||
FROM company_card_view_quota_usage AS usage
|
||||
INNER JOIN organizations AS organization ON organization.id = usage.organization_id
|
||||
WHERE
|
||||
organization.holding_id = $1
|
||||
AND organization.verification_level = 'e0'
|
||||
AND usage.last_seen_at > $2
|
||||
`
|
||||
|
||||
type CountCompanyCardViewQuotaHoldingWindowParams struct {
|
||||
HoldingID pgtype.UUID
|
||||
WindowStart pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type CountCompanyCardViewQuotaHoldingWindowRow struct {
|
||||
UsageCount int64
|
||||
EarliestAt interface{}
|
||||
}
|
||||
|
||||
// Counts the distinct-card usage of the E0 pool of a holding, with the same
|
||||
// rule as CountCompanyInvitationQuotaHoldingWindow. A view is still counted
|
||||
// per organization: the same candidate seen by two organizations of one
|
||||
// holding is two charges.
|
||||
func (q *Queries) CountCompanyCardViewQuotaHoldingWindow(ctx context.Context, arg CountCompanyCardViewQuotaHoldingWindowParams) (CountCompanyCardViewQuotaHoldingWindowRow, error) {
|
||||
row := q.db.QueryRow(ctx, countCompanyCardViewQuotaHoldingWindow, arg.HoldingID, arg.WindowStart)
|
||||
var i CountCompanyCardViewQuotaHoldingWindowRow
|
||||
err := row.Scan(&i.UsageCount, &i.EarliestAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const countCompanyCardViewQuotaWindow = `-- name: CountCompanyCardViewQuotaWindow :one
|
||||
SELECT
|
||||
count(*)::bigint AS usage_count,
|
||||
@@ -38,6 +71,38 @@ func (q *Queries) CountCompanyCardViewQuotaWindow(ctx context.Context, arg Count
|
||||
return i, err
|
||||
}
|
||||
|
||||
const countCompanyInvitationQuotaHoldingWindow = `-- name: CountCompanyInvitationQuotaHoldingWindow :one
|
||||
SELECT
|
||||
count(*)::bigint AS usage_count,
|
||||
min(usage.reserved_at) AS earliest_at
|
||||
FROM company_invitation_quota_usage AS usage
|
||||
INNER JOIN organizations AS organization ON organization.id = usage.organization_id
|
||||
WHERE
|
||||
organization.holding_id = $1
|
||||
AND organization.verification_level = 'e0'
|
||||
AND usage.reserved_at > $2
|
||||
`
|
||||
|
||||
type CountCompanyInvitationQuotaHoldingWindowParams struct {
|
||||
HoldingID pgtype.UUID
|
||||
WindowStart pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type CountCompanyInvitationQuotaHoldingWindowRow struct {
|
||||
UsageCount int64
|
||||
EarliestAt interface{}
|
||||
}
|
||||
|
||||
// Counts the invitation usage of the E0 pool of a holding: the usage of every
|
||||
// organization of the holding whose trust level is E0 when the count runs. Each
|
||||
// row stays attributed to the organization that consumed it.
|
||||
func (q *Queries) CountCompanyInvitationQuotaHoldingWindow(ctx context.Context, arg CountCompanyInvitationQuotaHoldingWindowParams) (CountCompanyInvitationQuotaHoldingWindowRow, error) {
|
||||
row := q.db.QueryRow(ctx, countCompanyInvitationQuotaHoldingWindow, arg.HoldingID, arg.WindowStart)
|
||||
var i CountCompanyInvitationQuotaHoldingWindowRow
|
||||
err := row.Scan(&i.UsageCount, &i.EarliestAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const countCompanyInvitationQuotaWindow = `-- name: CountCompanyInvitationQuotaWindow :one
|
||||
SELECT
|
||||
count(*)::bigint AS usage_count,
|
||||
@@ -185,12 +250,33 @@ func (q *Queries) InsertCompanyInvitationQuotaUsage(ctx context.Context, arg Ins
|
||||
return err
|
||||
}
|
||||
|
||||
const lockCompanyQuotaHolding = `-- name: LockCompanyQuotaHolding :one
|
||||
SELECT id
|
||||
FROM holdings
|
||||
WHERE id = $1
|
||||
FOR NO KEY UPDATE
|
||||
`
|
||||
|
||||
// Takes the pool lock of an E0 holding. It follows the organization lock, so
|
||||
// every writer locks an organization first and its holding second. Two
|
||||
// reservations of one holding queue here, and the second one counts the
|
||||
// usage that the first one committed. The lock does not conflict with the
|
||||
// FOR KEY SHARE that organizations.holding_id takes when an organization joins
|
||||
// the holding.
|
||||
func (q *Queries) LockCompanyQuotaHolding(ctx context.Context, holdingID pgtype.UUID) (pgtype.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, lockCompanyQuotaHolding, holdingID)
|
||||
var id pgtype.UUID
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
const lockCompanyQuotaOrganization = `-- name: LockCompanyQuotaOrganization :one
|
||||
SELECT
|
||||
id,
|
||||
verification_level,
|
||||
verification_basis,
|
||||
verification_changed_at
|
||||
verification_changed_at,
|
||||
holding_id
|
||||
FROM organizations
|
||||
WHERE id = $1
|
||||
FOR UPDATE
|
||||
@@ -201,6 +287,7 @@ type LockCompanyQuotaOrganizationRow struct {
|
||||
VerificationLevel string
|
||||
VerificationBasis string
|
||||
VerificationChangedAt pgtype.Timestamptz
|
||||
HoldingID pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error) {
|
||||
@@ -211,21 +298,33 @@ func (q *Queries) LockCompanyQuotaOrganization(ctx context.Context, organization
|
||||
&i.VerificationLevel,
|
||||
&i.VerificationBasis,
|
||||
&i.VerificationChangedAt,
|
||||
&i.HoldingID,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const lockCompanyQuotaOrganizationFirst = `-- name: LockCompanyQuotaOrganizationFirst :one
|
||||
|
||||
SELECT id
|
||||
SELECT
|
||||
id,
|
||||
verification_level,
|
||||
holding_id
|
||||
FROM organizations
|
||||
WHERE id = $1
|
||||
FOR NO KEY UPDATE
|
||||
`
|
||||
|
||||
// Writers lock the organization first, then invitation/card-view state, and
|
||||
// finally usage rows. The organization lock serializes quota decisions for
|
||||
// the tenant and makes the subsequent count and insert atomic.
|
||||
type LockCompanyQuotaOrganizationFirstRow struct {
|
||||
ID pgtype.UUID
|
||||
VerificationLevel string
|
||||
HoldingID pgtype.UUID
|
||||
}
|
||||
|
||||
// Writers lock the organization first, then, for an E0 organization, the holding
|
||||
// whose pool it shares, then invitation/card-view state, and finally usage rows.
|
||||
// The organization lock serializes quota decisions for the tenant, the holding
|
||||
// lock serializes the E0 pool across the organizations of one holding, and
|
||||
// together they make the subsequent count and insert atomic.
|
||||
// Takes the organization lock ahead of every share lock of a reader that will
|
||||
// reserve usage later. FOR NO KEY UPDATE conflicts with itself and with FOR
|
||||
// SHARE, so readers of one organization queue up instead of deadlocking on a
|
||||
@@ -233,12 +332,13 @@ FOR NO KEY UPDATE
|
||||
// FOR KEY SHARE that a foreign key takes, such as the hidden-organization
|
||||
// insert of a candidate, which holds the candidate's row and then needs this
|
||||
// one. The reservation itself still takes FOR UPDATE inside the same
|
||||
// transaction.
|
||||
func (q *Queries) LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (pgtype.UUID, error) {
|
||||
// transaction. The result carries the holding, whose pool an E0 organization
|
||||
// shares; the caller locks that holding right after this lock.
|
||||
func (q *Queries) LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationFirstRow, error) {
|
||||
row := q.db.QueryRow(ctx, lockCompanyQuotaOrganizationFirst, organizationID)
|
||||
var id pgtype.UUID
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
var i LockCompanyQuotaOrganizationFirstRow
|
||||
err := row.Scan(&i.ID, &i.VerificationLevel, &i.HoldingID)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const refreshCompanyCardViewQuotaUsage = `-- name: RefreshCompanyCardViewQuotaUsage :execrows
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: contact_grants.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const getContactGrantByInvitation = `-- name: GetContactGrantByInvitation :one
|
||||
SELECT
|
||||
id,
|
||||
organization_id,
|
||||
candidate_id,
|
||||
source_invitation_id,
|
||||
consent_record_id,
|
||||
terms_version,
|
||||
fields,
|
||||
consent_text_version,
|
||||
granted_at,
|
||||
revoked_at,
|
||||
revocation_reason
|
||||
FROM contact_grants
|
||||
WHERE
|
||||
organization_id = $1
|
||||
AND source_invitation_id = $2
|
||||
`
|
||||
|
||||
type GetContactGrantByInvitationParams struct {
|
||||
OrganizationID pgtype.UUID
|
||||
InvitationID pgtype.UUID
|
||||
}
|
||||
|
||||
// Read the grant of one invitation of one organization. An invitation of
|
||||
// another organization finds nothing.
|
||||
func (q *Queries) GetContactGrantByInvitation(ctx context.Context, arg GetContactGrantByInvitationParams) (ContactGrant, error) {
|
||||
row := q.db.QueryRow(ctx, getContactGrantByInvitation, arg.OrganizationID, arg.InvitationID)
|
||||
var i ContactGrant
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrganizationID,
|
||||
&i.CandidateID,
|
||||
&i.SourceInvitationID,
|
||||
&i.ConsentRecordID,
|
||||
&i.TermsVersion,
|
||||
&i.Fields,
|
||||
&i.ConsentTextVersion,
|
||||
&i.GrantedAt,
|
||||
&i.RevokedAt,
|
||||
&i.RevocationReason,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertContactGrant = `-- name: InsertContactGrant :exec
|
||||
INSERT INTO contact_grants (
|
||||
id,
|
||||
organization_id,
|
||||
candidate_id,
|
||||
source_invitation_id,
|
||||
consent_record_id,
|
||||
terms_version,
|
||||
fields,
|
||||
consent_text_version,
|
||||
granted_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7::text [],
|
||||
$8,
|
||||
$9
|
||||
)
|
||||
`
|
||||
|
||||
type InsertContactGrantParams struct {
|
||||
ID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
SourceInvitationID pgtype.UUID
|
||||
ConsentRecordID pgtype.UUID
|
||||
TermsVersion int64
|
||||
Fields []string
|
||||
ConsentTextVersion string
|
||||
GrantedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Store the contact grant of an acceptance. The row is inserted in the same
|
||||
// transaction as its C4 consent record and the accepted state; the database
|
||||
// checks that the record, the invitation, and the candidate agree.
|
||||
func (q *Queries) InsertContactGrant(ctx context.Context, arg InsertContactGrantParams) error {
|
||||
_, err := q.db.Exec(ctx, insertContactGrant,
|
||||
arg.ID,
|
||||
arg.OrganizationID,
|
||||
arg.CandidateID,
|
||||
arg.SourceInvitationID,
|
||||
arg.ConsentRecordID,
|
||||
arg.TermsVersion,
|
||||
arg.Fields,
|
||||
arg.ConsentTextVersion,
|
||||
arg.GrantedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: holdings.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const getHoldingIDByFounder = `-- name: GetHoldingIDByFounder :one
|
||||
SELECT id
|
||||
FROM holdings
|
||||
WHERE founder_account_id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetHoldingIDByFounder(ctx context.Context, founderAccountID pgtype.UUID) (pgtype.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, getHoldingIDByFounder, founderAccountID)
|
||||
var id pgtype.UUID
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
const insertHoldingIfAbsent = `-- name: InsertHoldingIfAbsent :exec
|
||||
INSERT INTO holdings (
|
||||
id,
|
||||
founder_account_id,
|
||||
created_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3
|
||||
)
|
||||
ON CONFLICT (founder_account_id) DO NOTHING
|
||||
`
|
||||
|
||||
type InsertHoldingIfAbsentParams struct {
|
||||
ID pgtype.UUID
|
||||
FounderAccountID pgtype.UUID
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Stores the holding of a founder account unless the account already has one.
|
||||
// A concurrent creation of the same account waits on the founder key until the
|
||||
// other transaction ends; then this insert does nothing, and the caller reads
|
||||
// the stored holding with GetHoldingIDByFounder.
|
||||
func (q *Queries) InsertHoldingIfAbsent(ctx context.Context, arg InsertHoldingIfAbsentParams) error {
|
||||
_, err := q.db.Exec(ctx, insertHoldingIfAbsent, arg.ID, arg.FounderAccountID, arg.CreatedAt)
|
||||
return err
|
||||
}
|
||||
@@ -11,6 +11,51 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const acceptInvitation = `-- name: AcceptInvitation :one
|
||||
UPDATE invitations
|
||||
SET
|
||||
state = 'accepted',
|
||||
version = $1,
|
||||
responded_at = $2,
|
||||
updated_at = $2
|
||||
WHERE
|
||||
organization_id = $3
|
||||
AND id = $4
|
||||
AND state IN ('delivered', 'viewed')
|
||||
AND version = $5
|
||||
AND terms_version = $6
|
||||
AND response_deadline_at > $2
|
||||
AND $1::bigint = $5::bigint + 1
|
||||
RETURNING id
|
||||
`
|
||||
|
||||
type AcceptInvitationParams struct {
|
||||
NextVersion int64
|
||||
AcceptedAt pgtype.Timestamptz
|
||||
OrganizationID pgtype.UUID
|
||||
InvitationID pgtype.UUID
|
||||
ExpectedVersion int64
|
||||
TermsVersion int64
|
||||
}
|
||||
|
||||
// The compare-and-swap of an acceptance: it applies only to a delivered or
|
||||
// viewed invitation at the version and the terms version that the candidate
|
||||
// read, and before its deadline. The answer is the acceptance time, and the
|
||||
// deadline is kept.
|
||||
func (q *Queries) AcceptInvitation(ctx context.Context, arg AcceptInvitationParams) (pgtype.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, acceptInvitation,
|
||||
arg.NextVersion,
|
||||
arg.AcceptedAt,
|
||||
arg.OrganizationID,
|
||||
arg.InvitationID,
|
||||
arg.ExpectedVersion,
|
||||
arg.TermsVersion,
|
||||
)
|
||||
var id pgtype.UUID
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
const declineInvitation = `-- name: DeclineInvitation :one
|
||||
UPDATE invitations
|
||||
SET
|
||||
@@ -51,6 +96,26 @@ func (q *Queries) DeclineInvitation(ctx context.Context, arg DeclineInvitationPa
|
||||
return id, err
|
||||
}
|
||||
|
||||
const getInvitationAcceptResult = `-- name: GetInvitationAcceptResult :one
|
||||
SELECT
|
||||
invitation_id,
|
||||
outcome
|
||||
FROM invitation_accept_results
|
||||
WHERE scope_hash = $1
|
||||
`
|
||||
|
||||
type GetInvitationAcceptResultRow struct {
|
||||
InvitationID pgtype.UUID
|
||||
Outcome string
|
||||
}
|
||||
|
||||
func (q *Queries) GetInvitationAcceptResult(ctx context.Context, scopeHash []byte) (GetInvitationAcceptResultRow, error) {
|
||||
row := q.db.QueryRow(ctx, getInvitationAcceptResult, scopeHash)
|
||||
var i GetInvitationAcceptResultRow
|
||||
err := row.Scan(&i.InvitationID, &i.Outcome)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getInvitationDeclineResult = `-- name: GetInvitationDeclineResult :one
|
||||
SELECT
|
||||
invitation_id,
|
||||
@@ -71,6 +136,29 @@ func (q *Queries) GetInvitationDeclineResult(ctx context.Context, scopeHash []by
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertInvitationAcceptResult = `-- name: InsertInvitationAcceptResult :exec
|
||||
INSERT INTO invitation_accept_results (
|
||||
scope_hash,
|
||||
invitation_id,
|
||||
outcome
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3
|
||||
)
|
||||
`
|
||||
|
||||
type InsertInvitationAcceptResultParams struct {
|
||||
ScopeHash []byte
|
||||
InvitationID pgtype.UUID
|
||||
Outcome string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertInvitationAcceptResult(ctx context.Context, arg InsertInvitationAcceptResultParams) error {
|
||||
_, err := q.db.Exec(ctx, insertInvitationAcceptResult, arg.ScopeHash, arg.InvitationID, arg.Outcome)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertInvitationDecline = `-- name: InsertInvitationDecline :exec
|
||||
INSERT INTO invitation_declines (
|
||||
invitation_id,
|
||||
|
||||
@@ -476,6 +476,20 @@ type ConsumerProcessedEvent struct {
|
||||
ProcessedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type ContactGrant struct {
|
||||
ID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
SourceInvitationID pgtype.UUID
|
||||
ConsentRecordID pgtype.UUID
|
||||
TermsVersion int64
|
||||
Fields []string
|
||||
ConsentTextVersion string
|
||||
GrantedAt pgtype.Timestamptz
|
||||
RevokedAt pgtype.Timestamptz
|
||||
RevocationReason pgtype.Text
|
||||
}
|
||||
|
||||
type Delivery struct {
|
||||
ID pgtype.UUID
|
||||
SourceEventID pgtype.UUID
|
||||
@@ -563,6 +577,12 @@ type EmailToken struct {
|
||||
PendingOnboardingStep pgtype.Text
|
||||
}
|
||||
|
||||
type Holding struct {
|
||||
ID pgtype.UUID
|
||||
FounderAccountID pgtype.UUID
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type IdempotencyRecord struct {
|
||||
ScopeHash []byte
|
||||
Fingerprint []byte
|
||||
@@ -592,6 +612,12 @@ type Invitation struct {
|
||||
RespondedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type InvitationAcceptResult struct {
|
||||
ScopeHash []byte
|
||||
InvitationID pgtype.UUID
|
||||
Outcome string
|
||||
}
|
||||
|
||||
type InvitationCreationResult struct {
|
||||
ScopeHash []byte
|
||||
Snapshot []byte
|
||||
@@ -715,6 +741,7 @@ type Organization struct {
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
HoldingID pgtype.UUID
|
||||
}
|
||||
|
||||
type OrganizationCreationResult struct {
|
||||
|
||||
@@ -229,7 +229,8 @@ INSERT INTO organizations (
|
||||
verification_changed_at,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
updated_at,
|
||||
holding_id
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
@@ -244,7 +245,8 @@ INSERT INTO organizations (
|
||||
$11,
|
||||
$12,
|
||||
$13,
|
||||
$14
|
||||
$14,
|
||||
$15
|
||||
)
|
||||
`
|
||||
|
||||
@@ -263,12 +265,13 @@ type InsertOrganizationParams struct {
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
HoldingID pgtype.UUID
|
||||
}
|
||||
|
||||
// Stores a new organization with the verification level that the domain
|
||||
// gave it. The deferred constraint organizations_owner_required fails the
|
||||
// transaction at commit unless an active owner membership was inserted in
|
||||
// it too.
|
||||
// gave it and the holding of its creator. The deferred constraint
|
||||
// organizations_owner_required fails the transaction at commit unless an
|
||||
// active owner membership was inserted in it too.
|
||||
func (q *Queries) InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error {
|
||||
_, err := q.db.Exec(ctx, insertOrganization,
|
||||
arg.ID,
|
||||
@@ -285,6 +288,7 @@ func (q *Queries) InsertOrganization(ctx context.Context, arg InsertOrganization
|
||||
arg.Version,
|
||||
arg.CreatedAt,
|
||||
arg.UpdatedAt,
|
||||
arg.HoldingID,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -549,6 +553,23 @@ type UpdateOrganizationProfileParams struct {
|
||||
ManagerRoles []string
|
||||
}
|
||||
|
||||
type UpdateOrganizationProfileRow struct {
|
||||
ID pgtype.UUID
|
||||
Name string
|
||||
Description pgtype.Text
|
||||
Sphere pgtype.Text
|
||||
ContactWebsite pgtype.Text
|
||||
ContactEmail pgtype.Text
|
||||
ContactPhone pgtype.Text
|
||||
ContactTelegram pgtype.Text
|
||||
VerificationLevel string
|
||||
VerificationBasis string
|
||||
VerificationChangedAt pgtype.Timestamptz
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Changes the profile of an organization over the version the caller read
|
||||
// and advances the version in the same statement. It names no verification
|
||||
// column, so a profile update cannot move the trust level. The change
|
||||
@@ -562,7 +583,7 @@ type UpdateOrganizationProfileParams struct {
|
||||
// follow it). No row returns for a stale version, an account that is no
|
||||
// active manager, or an unknown organization; the adapter reads the
|
||||
// membership to tell them apart.
|
||||
func (q *Queries) UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (Organization, error) {
|
||||
func (q *Queries) UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (UpdateOrganizationProfileRow, error) {
|
||||
row := q.db.QueryRow(ctx, updateOrganizationProfile,
|
||||
arg.Name,
|
||||
arg.Description,
|
||||
@@ -577,7 +598,7 @@ func (q *Queries) UpdateOrganizationProfile(ctx context.Context, arg UpdateOrgan
|
||||
arg.ActorID,
|
||||
arg.ManagerRoles,
|
||||
)
|
||||
var i Organization
|
||||
var i UpdateOrganizationProfileRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Name,
|
||||
|
||||
@@ -11,6 +11,11 @@ import (
|
||||
)
|
||||
|
||||
type Querier interface {
|
||||
// The compare-and-swap of an acceptance: it applies only to a delivered or
|
||||
// viewed invitation at the version and the terms version that the candidate
|
||||
// read, and before its deadline. The answer is the acceptance time, and the
|
||||
// deadline is kept.
|
||||
AcceptInvitation(ctx context.Context, arg AcceptInvitationParams) (pgtype.UUID, error)
|
||||
// Adds recipients to the day and the month row. The caller holds their
|
||||
// locks from LockMailQuotaRows and has checked both limits.
|
||||
AddMailQuotaUsage(ctx context.Context, arg AddMailQuotaUsageParams) (int64, error)
|
||||
@@ -131,7 +136,16 @@ type Querier interface {
|
||||
CountAssessmentSignalEvents(ctx context.Context, attemptID pgtype.UUID) (int64, error)
|
||||
// Counts the hiding records of one candidate for the settings read.
|
||||
CountCandidateHiddenOrganizations(ctx context.Context, userID pgtype.UUID) (int64, error)
|
||||
// Counts the distinct-card usage of the E0 pool of a holding, with the same
|
||||
// rule as CountCompanyInvitationQuotaHoldingWindow. A view is still counted
|
||||
// per organization: the same candidate seen by two organizations of one
|
||||
// holding is two charges.
|
||||
CountCompanyCardViewQuotaHoldingWindow(ctx context.Context, arg CountCompanyCardViewQuotaHoldingWindowParams) (CountCompanyCardViewQuotaHoldingWindowRow, error)
|
||||
CountCompanyCardViewQuotaWindow(ctx context.Context, arg CountCompanyCardViewQuotaWindowParams) (CountCompanyCardViewQuotaWindowRow, error)
|
||||
// Counts the invitation usage of the E0 pool of a holding: the usage of every
|
||||
// organization of the holding whose trust level is E0 when the count runs. Each
|
||||
// row stays attributed to the organization that consumed it.
|
||||
CountCompanyInvitationQuotaHoldingWindow(ctx context.Context, arg CountCompanyInvitationQuotaHoldingWindowParams) (CountCompanyInvitationQuotaHoldingWindowRow, error)
|
||||
CountCompanyInvitationQuotaWindow(ctx context.Context, arg CountCompanyInvitationQuotaWindowParams) (CountCompanyInvitationQuotaWindowRow, error)
|
||||
// Counts the families of a category that have at least one published
|
||||
// version, however many versions each has.
|
||||
@@ -275,6 +289,9 @@ type Querier interface {
|
||||
GetCandidateHiddenOrganization(ctx context.Context, arg GetCandidateHiddenOrganizationParams) (GetCandidateHiddenOrganizationRow, error)
|
||||
GetConsentText(ctx context.Context, arg GetConsentTextParams) (ConsentText, error)
|
||||
GetContactConsentRecordByInvitation(ctx context.Context, arg GetContactConsentRecordByInvitationParams) (GetContactConsentRecordByInvitationRow, error)
|
||||
// Read the grant of one invitation of one organization. An invitation of
|
||||
// another organization finds nothing.
|
||||
GetContactGrantByInvitation(ctx context.Context, arg GetContactGrantByInvitationParams) (ContactGrant, error)
|
||||
GetCurrentAssessmentCategoryOpening(ctx context.Context, category string) (AssessmentCategoryOpening, error)
|
||||
// The newest unrevoked record of a purpose other than C4.
|
||||
GetCurrentConsentRecord(ctx context.Context, arg GetCurrentConsentRecordParams) (GetCurrentConsentRecordRow, error)
|
||||
@@ -304,6 +321,8 @@ type Querier interface {
|
||||
GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error)
|
||||
// Explains why ConsumeEmailToken matched no row.
|
||||
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
|
||||
GetHoldingIDByFounder(ctx context.Context, founderAccountID pgtype.UUID) (pgtype.UUID, error)
|
||||
GetInvitationAcceptResult(ctx context.Context, scopeHash []byte) (GetInvitationAcceptResultRow, 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)
|
||||
@@ -470,6 +489,10 @@ type Querier interface {
|
||||
// when no row returns; the insert then changes nothing and does not abort
|
||||
// the transaction.
|
||||
InsertContactConsentRecord(ctx context.Context, arg InsertContactConsentRecordParams) (InsertContactConsentRecordRow, error)
|
||||
// Store the contact grant of an acceptance. The row is inserted in the same
|
||||
// transaction as its C4 consent record and the accepted state; the database
|
||||
// checks that the record, the invitation, and the candidate agree.
|
||||
InsertContactGrant(ctx context.Context, arg InsertContactGrantParams) error
|
||||
// Stores a new delivery. A delivery with the same ID already exists when the
|
||||
// same request is handled again; the statement then inserts nothing and
|
||||
// returns 0 rows, and the stored content stays as it was. While another
|
||||
@@ -477,10 +500,16 @@ type Querier interface {
|
||||
// for it.
|
||||
InsertDelivery(ctx context.Context, arg InsertDeliveryParams) (int64, error)
|
||||
InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error
|
||||
// Stores the holding of a founder account unless the account already has one.
|
||||
// A concurrent creation of the same account waits on the founder key until the
|
||||
// other transaction ends; then this insert does nothing, and the caller reads
|
||||
// the stored holding with GetHoldingIDByFounder.
|
||||
InsertHoldingIfAbsent(ctx context.Context, arg InsertHoldingIfAbsentParams) error
|
||||
// The invitation row, its first terms version, and its first audit event are
|
||||
// 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
|
||||
InsertInvitationAcceptResult(ctx context.Context, arg InsertInvitationAcceptResultParams) error
|
||||
InsertInvitationDecline(ctx context.Context, arg InsertInvitationDeclineParams) error
|
||||
InsertInvitationDeclineResult(ctx context.Context, arg InsertInvitationDeclineResultParams) error
|
||||
InsertInvitationEvent(ctx context.Context, arg InsertInvitationEventParams) error
|
||||
@@ -493,9 +522,9 @@ type Querier interface {
|
||||
// unique key absorbs at-least-once redelivery without copying event content.
|
||||
InsertNotificationInboxEvent(ctx context.Context, arg InsertNotificationInboxEventParams) (int64, error)
|
||||
// Stores a new organization with the verification level that the domain
|
||||
// gave it. The deferred constraint organizations_owner_required fails the
|
||||
// transaction at commit unless an active owner membership was inserted in
|
||||
// it too.
|
||||
// gave it and the holding of its creator. The deferred constraint
|
||||
// organizations_owner_required fails the transaction at commit unless an
|
||||
// active owner membership was inserted in it too.
|
||||
InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error
|
||||
// The parent and first immutable snapshot are inserted in one caller-owned
|
||||
// transaction. Deferred version references are checked when it commits.
|
||||
@@ -741,10 +770,19 @@ type Querier interface {
|
||||
// canceled, or reclaimed after the lease expired. While the lock is held,
|
||||
// other workers skip the row, so the handler never runs twice at once.
|
||||
LockClaimedScheduledJob(ctx context.Context, arg LockClaimedScheduledJobParams) (int64, error)
|
||||
// Takes the pool lock of an E0 holding. It follows the organization lock, so
|
||||
// every writer locks an organization first and its holding second. Two
|
||||
// reservations of one holding queue here, and the second one counts the
|
||||
// usage that the first one committed. The lock does not conflict with the
|
||||
// FOR KEY SHARE that organizations.holding_id takes when an organization joins
|
||||
// the holding.
|
||||
LockCompanyQuotaHolding(ctx context.Context, holdingID pgtype.UUID) (pgtype.UUID, error)
|
||||
LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error)
|
||||
// Writers lock the organization first, then invitation/card-view state, and
|
||||
// finally usage rows. The organization lock serializes quota decisions for
|
||||
// the tenant and makes the subsequent count and insert atomic.
|
||||
// Writers lock the organization first, then, for an E0 organization, the holding
|
||||
// whose pool it shares, then invitation/card-view state, and finally usage rows.
|
||||
// The organization lock serializes quota decisions for the tenant, the holding
|
||||
// lock serializes the E0 pool across the organizations of one holding, and
|
||||
// together they make the subsequent count and insert atomic.
|
||||
// Takes the organization lock ahead of every share lock of a reader that will
|
||||
// reserve usage later. FOR NO KEY UPDATE conflicts with itself and with FOR
|
||||
// SHARE, so readers of one organization queue up instead of deadlocking on a
|
||||
@@ -752,8 +790,9 @@ type Querier interface {
|
||||
// FOR KEY SHARE that a foreign key takes, such as the hidden-organization
|
||||
// insert of a candidate, which holds the candidate's row and then needs this
|
||||
// one. The reservation itself still takes FOR UPDATE inside the same
|
||||
// transaction.
|
||||
LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (pgtype.UUID, error)
|
||||
// transaction. The result carries the holding, whose pool an E0 organization
|
||||
// shares; the caller locks that holding right after this lock.
|
||||
LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationFirstRow, error)
|
||||
// Lock the current C2 before locking the publication. C2 revocation updates
|
||||
// this row before it locks the publication, so preserving this order avoids
|
||||
// a lock inversion and makes the current consent stable through the read.
|
||||
@@ -1086,7 +1125,7 @@ type Querier interface {
|
||||
// follow it). No row returns for a stale version, an account that is no
|
||||
// active manager, or an unknown organization; the adapter reads the
|
||||
// membership to tell them apart.
|
||||
UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (Organization, error)
|
||||
UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (UpdateOrganizationProfileRow, error)
|
||||
// Replaces the registration of an unverified account and advances the
|
||||
// registration version in the same statement, so no caller can choose it.
|
||||
// The version check rejects a writer that read an older row; a verified
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/companyquota"
|
||||
"lincodex/backend/internal/usecase/consent"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
"lincodex/backend/internal/usecase/invitation"
|
||||
"lincodex/backend/internal/usecase/notification"
|
||||
@@ -70,7 +71,7 @@ func newInvitationHandler(
|
||||
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
return quota.ReserveInvitation(ctx, unit, organization, invitationID)
|
||||
},
|
||||
Notifier: notifier, Clock: time.Now,
|
||||
Notifier: notifier, Consents: consent.NewService(transactor, time.Now), Clock: time.Now,
|
||||
})
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
|
||||
@@ -18,10 +18,21 @@ var (
|
||||
ErrCompanyQuotaDenied = errors.New("company quota denied")
|
||||
)
|
||||
|
||||
// SharesHoldingPool reports whether the usage of an organization at this tier
|
||||
// is counted in the pool of its holding instead of its own. Only the
|
||||
// unverified tier E0 shares a pool: the organizations of one holding at E0
|
||||
// draw on one allowance, so creating more of them does not multiply it. A
|
||||
// verified tier keeps its own pool, and usage of any organization that is no
|
||||
// longer E0 leaves the shared pool.
|
||||
func (tier OrganizationTier) SharesHoldingPool() bool {
|
||||
return tier == OrganizationTierE0
|
||||
}
|
||||
|
||||
// CompanyQuota is an immutable snapshot of the limits that apply to one
|
||||
// organization at one instant. It carries the stored verification and
|
||||
// effective policy identities so the transactional repository can verify
|
||||
// that neither changed before it reserves usage.
|
||||
// that neither changed before it reserves usage. Its usage scope is the
|
||||
// organization, or the holding pool for a tier that SharesHoldingPool.
|
||||
type CompanyQuota struct {
|
||||
organizationID uuid.UUID
|
||||
policyVersionID PolicyVersionID
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidContactGrant reports a grant that breaks a rule of the contact
|
||||
// grant or does not agree with the accepted invitation and its C4 record.
|
||||
ErrInvalidContactGrant = errors.New("invalid contact grant")
|
||||
)
|
||||
|
||||
// ContactRevocationReason says why a contact grant was revoked. It is shown
|
||||
// only to the candidate. The revocation itself belongs to a later operation.
|
||||
type ContactRevocationReason string
|
||||
|
||||
const (
|
||||
// ContactRevocationConsentRevoked closes every grant under a revoked C4.
|
||||
ContactRevocationConsentRevoked ContactRevocationReason = "consent_revoked"
|
||||
// ContactRevocationParticipationCancelled closes the grant of one
|
||||
// invitation that the candidate cancelled.
|
||||
ContactRevocationParticipationCancelled ContactRevocationReason = "participation_cancelled"
|
||||
// ContactRevocationVisibilityClosed closes a grant after the publication
|
||||
// was closed or the organization was hidden.
|
||||
ContactRevocationVisibilityClosed ContactRevocationReason = "visibility_closed"
|
||||
)
|
||||
|
||||
func (reason ContactRevocationReason) known() bool {
|
||||
switch reason {
|
||||
case ContactRevocationConsentRevoked, ContactRevocationParticipationCancelled, ContactRevocationVisibilityClosed:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// ContactAccessBlock says why an active grant does not allow a read now.
|
||||
type ContactAccessBlock string
|
||||
|
||||
// ContactAccessBlockVisibility means the profile is not published (C2) or is
|
||||
// hidden from the organization. The acceptance never publishes the profile or
|
||||
// lifts the hiding, so the grant becomes readable only when the candidate does.
|
||||
const ContactAccessBlockVisibility ContactAccessBlock = "visibility"
|
||||
|
||||
// ContactGrantStatus is the state of a contact grant.
|
||||
type ContactGrantStatus string
|
||||
|
||||
const (
|
||||
ContactGrantActive ContactGrantStatus = "active"
|
||||
ContactGrantRevoked ContactGrantStatus = "revoked"
|
||||
)
|
||||
|
||||
const redactedContactGrant = "[redacted contact grant]"
|
||||
|
||||
// ContactGrant is the permission of one organization to read the selected
|
||||
// contact kinds of one candidate, created by the acceptance of one invitation.
|
||||
// It names the C4 consent record that gave it, so the grant and its consent
|
||||
// always agree. The candidate identifier is internal and never logged.
|
||||
type ContactGrant struct {
|
||||
id uuid.UUID
|
||||
organizationID uuid.UUID
|
||||
candidateID uuid.UUID
|
||||
invitationID uuid.UUID
|
||||
consentRecordID uuid.UUID
|
||||
fields ContactFieldSet
|
||||
termsVersion int64
|
||||
consentTextVersion ConsentTextVersion
|
||||
grantedAt time.Time
|
||||
revokedAt time.Time
|
||||
revocationReason ContactRevocationReason
|
||||
}
|
||||
|
||||
// StoredContactGrant carries the columns of a stored grant. A nil RevokedAt
|
||||
// marks an active grant, and an empty RevocationReason goes with it.
|
||||
type StoredContactGrant struct {
|
||||
ID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
CandidateID uuid.UUID
|
||||
InvitationID uuid.UUID
|
||||
ConsentRecordID uuid.UUID
|
||||
TermsVersion int64
|
||||
Fields []string
|
||||
ConsentTextVersion string
|
||||
GrantedAt time.Time
|
||||
RevokedAt *time.Time
|
||||
RevocationReason string
|
||||
}
|
||||
|
||||
// NewContactGrant builds the grant of an accepted invitation from its C4
|
||||
// consent record. The record and the invitation must name the same subject,
|
||||
// organization, invitation, and terms version, and the invitation must be
|
||||
// accepted. The grant takes the fields, the text version, and the grant time
|
||||
// of the record, so it covers exactly what the candidate consented to.
|
||||
func NewContactGrant(record ConsentRecord, invitation Invitation) (ContactGrant, error) {
|
||||
const location = "domain.NewContactGrant"
|
||||
if record.Purpose() != ConsentPurposeContactDisclosure || record.Source() != ConsentSourceInvitationAcceptance {
|
||||
return ContactGrant{}, fmt.Errorf("%s - the grant needs the C4 record of an acceptance: %w", location, ErrInvalidContactGrant)
|
||||
}
|
||||
if _, revoked := record.RevokedAt(); revoked {
|
||||
return ContactGrant{}, fmt.Errorf("%s - a revoked C4 record gives no grant: %w", location, ErrInvalidContactGrant)
|
||||
}
|
||||
if invitation.State() != InvitationAccepted {
|
||||
return ContactGrant{}, fmt.Errorf("%s - only an accepted invitation has a grant: %w", location, ErrInvalidContactGrant)
|
||||
}
|
||||
switch {
|
||||
case record.OrganizationID() != invitation.OrganizationID(),
|
||||
record.InvitationID() != invitation.ID(),
|
||||
record.SubjectID() != invitation.CandidateID(),
|
||||
record.InvitationTermsVersion() != invitation.TermsVersion():
|
||||
return ContactGrant{}, fmt.Errorf("%s - the C4 record must name the accepted invitation: %w", location, ErrInvalidContactGrant)
|
||||
case record.Fields().IsZero():
|
||||
return ContactGrant{}, fmt.Errorf("%s - the C4 record must name its fields: %w", location, ErrInvalidContactGrant)
|
||||
}
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return ContactGrant{}, fmt.Errorf("%s - generate grant ID: %w", location, err)
|
||||
}
|
||||
return ContactGrant{
|
||||
id: id,
|
||||
organizationID: invitation.OrganizationID(),
|
||||
candidateID: invitation.CandidateID(),
|
||||
invitationID: invitation.ID(),
|
||||
consentRecordID: record.ID(),
|
||||
fields: record.Fields(),
|
||||
termsVersion: invitation.TermsVersion(),
|
||||
consentTextVersion: record.TextVersion(),
|
||||
grantedAt: record.GrantedAt(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RestoreContactGrant validates a stored grant, so a row changed outside the
|
||||
// application is not served.
|
||||
func RestoreContactGrant(stored StoredContactGrant) (ContactGrant, error) {
|
||||
const location = "domain.RestoreContactGrant"
|
||||
switch {
|
||||
case stored.ID == uuid.Nil, stored.OrganizationID == uuid.Nil, stored.CandidateID == uuid.Nil,
|
||||
stored.InvitationID == uuid.Nil, stored.ConsentRecordID == uuid.Nil:
|
||||
return ContactGrant{}, fmt.Errorf("%s - identifiers must be set: %w", location, ErrInvalidContactGrant)
|
||||
case stored.TermsVersion < 1, stored.GrantedAt.IsZero():
|
||||
return ContactGrant{}, fmt.Errorf("%s - terms version and grant time must be set: %w", location, ErrInvalidContactGrant)
|
||||
}
|
||||
fields, err := restoreGrantFields(stored.Fields)
|
||||
if err != nil {
|
||||
return ContactGrant{}, fmt.Errorf("%s - validate fields: %w", location, err)
|
||||
}
|
||||
version, err := ParseConsentTextVersion(stored.ConsentTextVersion)
|
||||
if err != nil {
|
||||
return ContactGrant{}, fmt.Errorf("%s - validate consent text version: %w", location, err)
|
||||
}
|
||||
grant := ContactGrant{
|
||||
id: stored.ID, organizationID: stored.OrganizationID, candidateID: stored.CandidateID,
|
||||
invitationID: stored.InvitationID, consentRecordID: stored.ConsentRecordID, fields: fields,
|
||||
termsVersion: stored.TermsVersion, consentTextVersion: version, grantedAt: stored.GrantedAt,
|
||||
}
|
||||
switch {
|
||||
case stored.RevokedAt == nil && stored.RevocationReason == "":
|
||||
case stored.RevokedAt != nil && ContactRevocationReason(stored.RevocationReason).known() &&
|
||||
!stored.RevokedAt.Before(stored.GrantedAt):
|
||||
grant.revokedAt = *stored.RevokedAt
|
||||
grant.revocationReason = ContactRevocationReason(stored.RevocationReason)
|
||||
default:
|
||||
return ContactGrant{}, fmt.Errorf("%s - the revocation stamp is inconsistent: %w", location, ErrInvalidContactGrant)
|
||||
}
|
||||
return grant, nil
|
||||
}
|
||||
|
||||
// restoreGrantFields accepts the stored kinds only in the canonical form the
|
||||
// database stores: distinct, known, and ascending.
|
||||
func restoreGrantFields(stored []string) (ContactFieldSet, error) {
|
||||
fields := make([]ContactField, 0, len(stored))
|
||||
for _, value := range stored {
|
||||
field, err := ParseContactField(value)
|
||||
if err != nil {
|
||||
return ContactFieldSet{}, err
|
||||
}
|
||||
fields = append(fields, field)
|
||||
}
|
||||
set, err := NewContactFieldSet(fields...)
|
||||
if err != nil {
|
||||
return ContactFieldSet{}, err
|
||||
}
|
||||
if !slices.Equal(contactFieldCodes(set), stored) {
|
||||
return ContactFieldSet{}, fmt.Errorf("stored fields are not in canonical order: %w", ErrInvalidContactGrant)
|
||||
}
|
||||
return set, nil
|
||||
}
|
||||
|
||||
func (grant ContactGrant) ID() uuid.UUID { return grant.id }
|
||||
func (grant ContactGrant) OrganizationID() uuid.UUID { return grant.organizationID }
|
||||
func (grant ContactGrant) CandidateID() uuid.UUID { return grant.candidateID }
|
||||
func (grant ContactGrant) InvitationID() uuid.UUID { return grant.invitationID }
|
||||
func (grant ContactGrant) ConsentRecordID() uuid.UUID { return grant.consentRecordID }
|
||||
func (grant ContactGrant) Fields() ContactFieldSet { return grant.fields }
|
||||
func (grant ContactGrant) TermsVersion() int64 { return grant.termsVersion }
|
||||
func (grant ContactGrant) ConsentTextVersion() ConsentTextVersion { return grant.consentTextVersion }
|
||||
func (grant ContactGrant) GrantedAt() time.Time { return grant.grantedAt }
|
||||
|
||||
// RevokedAt returns the revocation time, and false while the grant is active.
|
||||
func (grant ContactGrant) RevokedAt() (time.Time, bool) {
|
||||
return grant.revokedAt, !grant.revokedAt.IsZero()
|
||||
}
|
||||
|
||||
// RevocationReason is empty while the grant is active.
|
||||
func (grant ContactGrant) RevocationReason() ContactRevocationReason { return grant.revocationReason }
|
||||
|
||||
// Status is revoked once a revocation stamp is set; a grant never becomes
|
||||
// active again.
|
||||
func (grant ContactGrant) Status() ContactGrantStatus {
|
||||
if grant.revokedAt.IsZero() {
|
||||
return ContactGrantActive
|
||||
}
|
||||
return ContactGrantRevoked
|
||||
}
|
||||
|
||||
// IsZero reports a grant not built by NewContactGrant or RestoreContactGrant.
|
||||
func (grant ContactGrant) IsZero() bool { return grant.id == uuid.Nil }
|
||||
|
||||
// Stored returns the persisted form of the grant.
|
||||
func (grant ContactGrant) Stored() StoredContactGrant {
|
||||
stored := StoredContactGrant{
|
||||
ID: grant.id, OrganizationID: grant.organizationID, CandidateID: grant.candidateID,
|
||||
InvitationID: grant.invitationID, ConsentRecordID: grant.consentRecordID,
|
||||
TermsVersion: grant.termsVersion, Fields: contactFieldCodes(grant.fields),
|
||||
ConsentTextVersion: string(grant.consentTextVersion), GrantedAt: grant.grantedAt,
|
||||
RevocationReason: string(grant.revocationReason),
|
||||
}
|
||||
if !grant.revokedAt.IsZero() {
|
||||
revokedAt := grant.revokedAt
|
||||
stored.RevokedAt = &revokedAt
|
||||
}
|
||||
return stored
|
||||
}
|
||||
|
||||
// ContactGrantView is the grant as the candidate reads it. It holds kinds
|
||||
// only, never contact values, and it names no organization identifier. The
|
||||
// organization reads it through its own view.
|
||||
type ContactGrantView struct {
|
||||
ID uuid.UUID
|
||||
Fields []ContactField
|
||||
Status ContactGrantStatus
|
||||
Readable bool
|
||||
BlockedBy *ContactAccessBlock
|
||||
TermsVersion int64
|
||||
ConsentTextVersion ConsentTextVersion
|
||||
GrantedAt time.Time
|
||||
RevokedAt *time.Time
|
||||
RevocationReason *ContactRevocationReason
|
||||
}
|
||||
|
||||
// CandidateView returns the grant for the candidate. visible reports whether
|
||||
// the organization may read the profile now, which is the publication and the
|
||||
// hiding of the organization. An active grant is readable only when it is
|
||||
// visible; a revoked grant is never readable and shows its reason instead.
|
||||
func (grant ContactGrant) CandidateView(visible bool) ContactGrantView {
|
||||
view := ContactGrantView{
|
||||
ID: grant.id, Fields: grant.fields.Fields(), Status: grant.Status(),
|
||||
TermsVersion: grant.termsVersion, ConsentTextVersion: grant.consentTextVersion, GrantedAt: grant.grantedAt,
|
||||
}
|
||||
if view.Status == ContactGrantRevoked {
|
||||
revokedAt, reason := grant.revokedAt, grant.revocationReason
|
||||
view.RevokedAt, view.RevocationReason = &revokedAt, &reason
|
||||
return view
|
||||
}
|
||||
if visible {
|
||||
view.Readable = true
|
||||
return view
|
||||
}
|
||||
block := ContactAccessBlockVisibility
|
||||
view.BlockedBy = &block
|
||||
return view
|
||||
}
|
||||
|
||||
func (grant ContactGrant) String() string { return redactedContactGrant }
|
||||
func (grant ContactGrant) GoString() string { return redactedContactGrant }
|
||||
func (grant ContactGrant) Format(state fmt.State, _ rune) {
|
||||
writeRedacted(state, redactedContactGrant)
|
||||
}
|
||||
|
||||
// LogValue carries the grant identifier and its status only.
|
||||
func (grant ContactGrant) LogValue() slog.Value {
|
||||
return slog.GroupValue(slog.String("grant_id", grant.id.String()), slog.String("status", string(grant.Status())))
|
||||
}
|
||||
|
||||
// ContactConsentText is the published C4 text that the candidate sees, with
|
||||
// the organization name in it.
|
||||
type ContactConsentText struct {
|
||||
TextVersion ConsentTextVersion
|
||||
Text string
|
||||
}
|
||||
|
||||
// ContactConsentOffer is what the candidate can consent to while an
|
||||
// acceptance is possible: the rendered text and the kinds the profile holds.
|
||||
// Nothing is preselected, and no contact value is part of it.
|
||||
type ContactConsentOffer struct {
|
||||
Text ContactConsentText
|
||||
AvailableFields []ContactField
|
||||
}
|
||||
|
||||
// NewContactConsentOffer renders the C4 text for the organization name and
|
||||
// lists the kinds that the profile holds, in the order given. It needs at least
|
||||
// one kind, because a grant covers at least one field.
|
||||
func NewContactConsentOffer(text ConsentText, organizationName string, available []ContactField) (ContactConsentOffer, error) {
|
||||
const location = "domain.NewContactConsentOffer"
|
||||
if len(available) == 0 || len(available) > maxContactFields {
|
||||
return ContactConsentOffer{}, fmt.Errorf("%s - the offer needs 1 to %d kinds: %w", location, maxContactFields, ErrInvalidContactGrant)
|
||||
}
|
||||
for index, field := range available {
|
||||
if _, err := ParseContactField(string(field)); err != nil {
|
||||
return ContactConsentOffer{}, fmt.Errorf("%s - validate kind: %w", location, err)
|
||||
}
|
||||
if slices.Contains(available[:index], field) {
|
||||
return ContactConsentOffer{}, fmt.Errorf("%s - kinds must be distinct: %w", location, ErrInvalidContactGrant)
|
||||
}
|
||||
}
|
||||
rendered, err := text.RenderForOrganization(organizationName)
|
||||
if err != nil {
|
||||
return ContactConsentOffer{}, fmt.Errorf("%s - render consent text: %w", location, err)
|
||||
}
|
||||
return ContactConsentOffer{
|
||||
Text: ContactConsentText{TextVersion: text.Version(), Text: rendered},
|
||||
AvailableFields: slices.Clone(available),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// contactFieldCodes returns the kinds of a set as the stored strings, in the
|
||||
// set's canonical order.
|
||||
func contactFieldCodes(set ContactFieldSet) []string {
|
||||
codes := make([]string, 0, len(set.Fields()))
|
||||
for _, field := range set.Fields() {
|
||||
codes = append(codes, string(field))
|
||||
}
|
||||
return codes
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const testContactTextBody = "I consent to the transfer of the contact data I select to {organization} for this invitation."
|
||||
|
||||
// testContactText is the published C4 text of the domain tests.
|
||||
func testContactText(t *testing.T) ConsentText {
|
||||
t.Helper()
|
||||
hash := HashConsentText(testContactTextBody)
|
||||
text, err := RestoreConsentText(StoredConsentText{
|
||||
Purpose: string(ConsentPurposeContactDisclosure), Version: "c4-2026-10-01", Body: testContactTextBody,
|
||||
Hash: hash[:], Kind: string(ConsentTextKindDemo), PublishedAt: time.Date(2026, time.October, 1, 0, 0, 0, 0, time.UTC),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreConsentText() error = %v", err)
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// acceptedTestInvitation accepts the delivered test invitation an hour after
|
||||
// its delivery, from its delivered state and at its current terms version.
|
||||
func acceptedTestInvitation(t *testing.T) (Invitation, time.Time) {
|
||||
t.Helper()
|
||||
delivered, _ := deliveredTestInvitation(t)
|
||||
at := delivered.UpdatedAt().Add(time.Hour)
|
||||
accepted, err := delivered.Accept(delivered.TermsVersion(), at)
|
||||
if err != nil {
|
||||
t.Fatalf("Accept() error = %v", err)
|
||||
}
|
||||
return accepted, at
|
||||
}
|
||||
|
||||
// testConsentRecordFor stores the C4 record of an acceptance the way the ledger
|
||||
// does: the hash of the text with the organization name filled in.
|
||||
func testStoredConsentRecord(t *testing.T, invitation Invitation, granted time.Time, fields ...string) StoredConsentRecord {
|
||||
t.Helper()
|
||||
shown, err := testContactText(t).RenderForOrganization("Acme")
|
||||
if err != nil {
|
||||
t.Fatalf("RenderForOrganization() error = %v", err)
|
||||
}
|
||||
hash := HashConsentText(shown)
|
||||
return StoredConsentRecord{
|
||||
ID: uuid.Must(uuid.NewV7()), SubjectID: invitation.CandidateID(), Purpose: string(ConsentPurposeContactDisclosure),
|
||||
TextVersion: "c4-2026-10-01", TextHash: hash[:], Source: string(ConsentSourceInvitationAcceptance),
|
||||
State: string(ConsentStateActive), GrantedAt: granted, OrganizationID: invitation.OrganizationID(),
|
||||
OrganizationName: "Acme", FieldSet: fields, InvitationID: invitation.ID(), InvitationTermsVersion: invitation.TermsVersion(),
|
||||
}
|
||||
}
|
||||
|
||||
// testConsentRecordFor restores the stored C4 record of an acceptance.
|
||||
func testConsentRecordFor(t *testing.T, invitation Invitation, granted time.Time, fields ...string) ConsentRecord {
|
||||
t.Helper()
|
||||
record, err := RestoreConsentRecord(testStoredConsentRecord(t, invitation, granted, fields...))
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreConsentRecord() error = %v", err)
|
||||
}
|
||||
return record
|
||||
}
|
||||
|
||||
func TestNewContactGrantCoversExactlyTheRecordedFields(t *testing.T) {
|
||||
accepted, at := acceptedTestInvitation(t)
|
||||
record := testConsentRecordFor(t, accepted, at, "email")
|
||||
grant, err := NewContactGrant(record, accepted)
|
||||
if err != nil {
|
||||
t.Fatalf("NewContactGrant() error = %v", err)
|
||||
}
|
||||
if grant.OrganizationID() != accepted.OrganizationID() || grant.InvitationID() != accepted.ID() ||
|
||||
grant.CandidateID() != accepted.CandidateID() || grant.ConsentRecordID() != record.ID() ||
|
||||
grant.TermsVersion() != accepted.TermsVersion() || grant.ConsentTextVersion() != "c4-2026-10-01" ||
|
||||
!grant.GrantedAt().Equal(at) || grant.Status() != ContactGrantActive {
|
||||
t.Fatalf("grant = %+v, want the scope of the accepted invitation and its record", grant.Stored())
|
||||
}
|
||||
if fields := grant.Fields().Fields(); len(fields) != 1 || fields[0] != ContactFieldEmail {
|
||||
t.Fatalf("fields = %v, want the email only", fields)
|
||||
}
|
||||
if _, revoked := grant.RevokedAt(); revoked {
|
||||
t.Fatal("a new grant is revoked")
|
||||
}
|
||||
restored, err := RestoreContactGrant(grant.Stored())
|
||||
if err != nil || restored.ID() != grant.ID() || !restored.Fields().Equal(grant.Fields()) {
|
||||
t.Fatalf("RestoreContactGrant(stored) = %+v, %v; want the same grant", restored.Stored(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewContactGrantNeedsAnAcceptedInvitationAndItsOwnRecord(t *testing.T) {
|
||||
accepted, at := acceptedTestInvitation(t)
|
||||
delivered, _ := deliveredTestInvitation(t)
|
||||
|
||||
if _, err := NewContactGrant(testConsentRecordFor(t, delivered, at, "email"), delivered); !errors.Is(err, ErrInvalidContactGrant) {
|
||||
t.Fatalf("grant of a delivered invitation error = %v, want ErrInvalidContactGrant", err)
|
||||
}
|
||||
otherInvitation := testConsentRecordFor(t, delivered, at, "email")
|
||||
if _, err := NewContactGrant(otherInvitation, accepted); !errors.Is(err, ErrInvalidContactGrant) {
|
||||
t.Fatalf("grant with another invitation's record error = %v, want ErrInvalidContactGrant", err)
|
||||
}
|
||||
stored := testStoredConsentRecord(t, accepted, at, "email")
|
||||
stored.RevokedAt = &at
|
||||
stored.RevocationSource = string(ConsentRevocationSourceConsentSettings)
|
||||
stored.State = string(ConsentStateRevoked)
|
||||
revoked, err := RestoreConsentRecord(stored)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreConsentRecord(revoked) error = %v", err)
|
||||
}
|
||||
if _, err := NewContactGrant(revoked, accepted); !errors.Is(err, ErrInvalidContactGrant) {
|
||||
t.Fatalf("grant of a revoked record error = %v, want ErrInvalidContactGrant", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestContactGrantShowsWhetherTheOrganizationCanReadItNow(t *testing.T) {
|
||||
accepted, at := acceptedTestInvitation(t)
|
||||
grant, err := NewContactGrant(testConsentRecordFor(t, accepted, at, "email"), accepted)
|
||||
if err != nil {
|
||||
t.Fatalf("NewContactGrant() error = %v", err)
|
||||
}
|
||||
if view := grant.CandidateView(true); !view.Readable || view.BlockedBy != nil || view.Status != ContactGrantActive {
|
||||
t.Fatalf("visible view = %+v, want readable and not blocked", view)
|
||||
}
|
||||
view := grant.CandidateView(false)
|
||||
if view.Readable || view.BlockedBy == nil || *view.BlockedBy != ContactAccessBlockVisibility {
|
||||
t.Fatalf("hidden view = %+v, want blocked by visibility", view)
|
||||
}
|
||||
|
||||
revokedAt := at.Add(time.Hour)
|
||||
revoked, err := RestoreContactGrant(StoredContactGrant{
|
||||
ID: grant.ID(), OrganizationID: grant.OrganizationID(), CandidateID: grant.CandidateID(), InvitationID: grant.InvitationID(),
|
||||
ConsentRecordID: grant.ConsentRecordID(), TermsVersion: grant.TermsVersion(), Fields: []string{"email"},
|
||||
ConsentTextVersion: "c4-2026-10-01", GrantedAt: at, RevokedAt: &revokedAt, RevocationReason: string(ContactRevocationConsentRevoked),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreContactGrant(revoked) error = %v", err)
|
||||
}
|
||||
closed := revoked.CandidateView(true)
|
||||
if closed.Readable || closed.BlockedBy != nil || closed.Status != ContactGrantRevoked || closed.RevokedAt == nil ||
|
||||
!closed.RevokedAt.Equal(revokedAt) || closed.RevocationReason == nil || *closed.RevocationReason != ContactRevocationConsentRevoked {
|
||||
t.Fatalf("revoked view = %+v, want closed with its reason and no read", closed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreContactGrantRefusesNonCanonicalFieldsAndBrokenRevocation(t *testing.T) {
|
||||
accepted, at := acceptedTestInvitation(t)
|
||||
valid := StoredContactGrant{
|
||||
ID: uuid.Must(uuid.NewV7()), OrganizationID: accepted.OrganizationID(), CandidateID: accepted.CandidateID(),
|
||||
InvitationID: accepted.ID(), ConsentRecordID: uuid.Must(uuid.NewV7()), TermsVersion: accepted.TermsVersion(),
|
||||
Fields: []string{"email", "phone"}, ConsentTextVersion: "c4-2026-10-01", GrantedAt: at,
|
||||
}
|
||||
if _, err := RestoreContactGrant(valid); err != nil {
|
||||
t.Fatalf("RestoreContactGrant(valid) error = %v", err)
|
||||
}
|
||||
reversed := valid
|
||||
reversed.Fields = []string{"phone", "email"}
|
||||
beforeGrant := valid
|
||||
beforeGrant.RevokedAt = ptrTime(at.Add(-time.Minute))
|
||||
beforeGrant.RevocationReason = string(ContactRevocationVisibilityClosed)
|
||||
noReason := valid
|
||||
noReason.RevokedAt = ptrTime(at.Add(time.Minute))
|
||||
unknownKind := valid
|
||||
unknownKind.Fields = []string{"address"}
|
||||
for name, stored := range map[string]StoredContactGrant{
|
||||
"reversed fields": reversed,
|
||||
"unknown kind": unknownKind,
|
||||
"revocation before grant": beforeGrant,
|
||||
"revocation without a reason": noReason,
|
||||
} {
|
||||
if _, err := RestoreContactGrant(stored); !errors.Is(err, ErrInvalidContactGrant) && !errors.Is(err, ErrInvalidConsent) {
|
||||
t.Errorf("%s: RestoreContactGrant() error = %v, want a refusal", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ptrTime(value time.Time) *time.Time { return &value }
|
||||
|
||||
func TestInvitationAcceptsOnlyTheCurrentTermsFromAnAnswerableState(t *testing.T) {
|
||||
delivered, _ := deliveredTestInvitation(t)
|
||||
at := delivered.UpdatedAt().Add(time.Hour)
|
||||
if _, err := delivered.Accept(delivered.TermsVersion()+1, at); !errors.Is(err, ErrInvitationVersionConflict) {
|
||||
t.Fatalf("stale terms error = %v, want ErrInvitationVersionConflict", err)
|
||||
}
|
||||
counter := withState(t, delivered, InvitationCounter, nil)
|
||||
if _, err := counter.Accept(counter.TermsVersion(), at); !errors.Is(err, ErrInvitationNotAnswerable) {
|
||||
t.Fatalf("counter error = %v, want ErrInvitationNotAnswerable", err)
|
||||
}
|
||||
if _, err := delivered.Accept(delivered.TermsVersion(), *delivered.Snapshot().ResponseDeadlineAt); !errors.Is(err, ErrInvitationNotAnswerable) {
|
||||
t.Fatalf("accept at the deadline error = %v, want ErrInvitationNotAnswerable", err)
|
||||
}
|
||||
viewed, _, err := delivered.RecordView(at)
|
||||
if err != nil {
|
||||
t.Fatalf("RecordView() error = %v", err)
|
||||
}
|
||||
accepted, err := viewed.Accept(viewed.TermsVersion(), at.Add(time.Minute))
|
||||
if err != nil {
|
||||
t.Fatalf("Accept(viewed) error = %v", err)
|
||||
}
|
||||
snapshot := accepted.Snapshot()
|
||||
if snapshot.State != InvitationAccepted || snapshot.Version != viewed.Version()+1 || snapshot.RespondedAt == nil ||
|
||||
!snapshot.ResponseDeadlineAt.Equal(*delivered.Snapshot().ResponseDeadlineAt) {
|
||||
t.Fatalf("accepted = %+v, want the next version accepted with the deadline kept", snapshot)
|
||||
}
|
||||
event, err := accepted.AnswerEvent(delivered.CandidateID())
|
||||
if err != nil || event.Kind != InvitationEventAccepted || len(event.ChangedFields) != 0 {
|
||||
t.Fatalf("AnswerEvent() = %+v, %v; want an accepted event naming no field", event, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewContactConsentOfferRendersTheTextAndListsTheHeldKinds(t *testing.T) {
|
||||
offer, err := NewContactConsentOffer(testContactText(t), "Acme", []ContactField{ContactFieldFullName, ContactFieldEmail})
|
||||
if err != nil {
|
||||
t.Fatalf("NewContactConsentOffer() error = %v", err)
|
||||
}
|
||||
if !strings.Contains(offer.Text.Text, "Acme") || strings.Contains(offer.Text.Text, ConsentTextOrganizationPlaceholder) ||
|
||||
offer.Text.TextVersion != "c4-2026-10-01" || !slices.Equal(offer.AvailableFields, []ContactField{ContactFieldFullName, ContactFieldEmail}) {
|
||||
t.Fatalf("offer = %+v, want the rendered text and the kinds in the given order", offer)
|
||||
}
|
||||
if _, err := NewContactConsentOffer(testContactText(t), "Acme", nil); !errors.Is(err, ErrInvalidContactGrant) {
|
||||
t.Fatalf("empty offer error = %v, want ErrInvalidContactGrant", err)
|
||||
}
|
||||
if _, err := NewContactConsentOffer(testContactText(t), "Acme", []ContactField{ContactFieldEmail, ContactFieldEmail}); !errors.Is(err, ErrInvalidContactGrant) {
|
||||
t.Fatalf("repeated kind error = %v, want ErrInvalidContactGrant", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestContactGrantValuesAreRedacted(t *testing.T) {
|
||||
accepted, at := acceptedTestInvitation(t)
|
||||
grant, err := NewContactGrant(testConsentRecordFor(t, accepted, at, "email"), accepted)
|
||||
if err != nil {
|
||||
t.Fatalf("NewContactGrant() error = %v", err)
|
||||
}
|
||||
for _, rendered := range []string{fmt.Sprint(grant), fmt.Sprintf("%+v", grant), fmt.Sprintf("%#v", grant)} {
|
||||
if strings.Contains(rendered, accepted.CandidateID().String()) || strings.Contains(rendered, "email") {
|
||||
t.Fatalf("rendered grant = %q, want the identifier and the kinds hidden", rendered)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ErrInvalidHolding reports a holding that was not built with a founder
|
||||
// account and a creation time.
|
||||
var ErrInvalidHolding = errors.New("invalid holding")
|
||||
|
||||
// Holding groups the organizations that one founder account created, as the
|
||||
// divisions of one company belong to one parent. It carries no profile and no
|
||||
// right: its only effect is the E0 quota pool that its organizations share.
|
||||
// Organizations of one account are grouped; cross-owner merges are not
|
||||
// modelled.
|
||||
type Holding struct {
|
||||
id uuid.UUID
|
||||
founderAccountID uuid.UUID
|
||||
createdAt time.Time
|
||||
}
|
||||
|
||||
// NewHolding creates the holding of a founder account with a time-ordered
|
||||
// UUIDv7 identifier. The storage keeps one holding per founder and returns the
|
||||
// stored one when the account already has it, so the identifier of this value
|
||||
// is only used when the holding is new.
|
||||
func NewHolding(founderAccountID uuid.UUID, createdAt time.Time) (Holding, error) {
|
||||
const location = "domain.NewHolding"
|
||||
if founderAccountID == uuid.Nil {
|
||||
return Holding{}, fmt.Errorf("%s - founder account must be set: %w", location, ErrInvalidHolding)
|
||||
}
|
||||
if createdAt.IsZero() {
|
||||
return Holding{}, fmt.Errorf("%s - creation time must be set: %w", location, ErrInvalidHolding)
|
||||
}
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return Holding{}, fmt.Errorf("%s - generate holding ID: %w", location, err)
|
||||
}
|
||||
return Holding{id: id, founderAccountID: founderAccountID, createdAt: createdAt.UTC()}, nil
|
||||
}
|
||||
|
||||
func (holding Holding) ID() uuid.UUID { return holding.id }
|
||||
|
||||
func (holding Holding) FounderAccountID() uuid.UUID { return holding.founderAccountID }
|
||||
|
||||
func (holding Holding) CreatedAt() time.Time { return holding.createdAt }
|
||||
@@ -27,6 +27,9 @@ const (
|
||||
// candidate's answer for the responsiveness metrics, never a consent or
|
||||
// a hire, and it holds neither the reason nor the comment.
|
||||
InvitationEventDeclined InvitationEventKind = "declined"
|
||||
// InvitationEventAccepted is the audit event of an acceptance. It names no
|
||||
// field: the consent C4 and the grant are stored in their own records.
|
||||
InvitationEventAccepted InvitationEventKind = "accepted"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -46,6 +49,7 @@ var (
|
||||
// answerEventKinds name the audit event of each answer state.
|
||||
answerEventKinds = map[InvitationState]InvitationEventKind{
|
||||
InvitationViewed: InvitationEventViewed, InvitationDeclined: InvitationEventDeclined,
|
||||
InvitationAccepted: InvitationEventAccepted,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -234,8 +238,44 @@ func (invitation Invitation) Decline(choice InvitationDeclineChoice, at time.Tim
|
||||
return declined, decline, nil
|
||||
}
|
||||
|
||||
// AnswerEvent builds the audit event of the version that a view or a
|
||||
// decline by actor has just produced. It names no field and holds neither
|
||||
// Accept returns the next version in the state accepted. The candidate may
|
||||
// accept a delivered or viewed invitation before its deadline and only at the
|
||||
// terms version that the candidate read; any other state, a late command, and
|
||||
// a stale terms version are refused. The deadline and the terms are kept. The
|
||||
// consent C4, the contact grant, and the audit event belong to the same
|
||||
// transaction and are built by the caller.
|
||||
func (invitation Invitation) Accept(termsVersion int64, at time.Time) (Invitation, error) {
|
||||
const location = "Invitation.Accept"
|
||||
if !validInvitationTime(at) || at.Before(invitation.record.UpdatedAt) {
|
||||
return Invitation{}, fmt.Errorf("%s - accept time must be set and not before the last change: %w", location, ErrInvalidInvitation)
|
||||
}
|
||||
if !invitation.acceptable() || !invitation.IsDelivered() || invitation.ResponseDeadlinePassed(at) {
|
||||
return Invitation{}, fmt.Errorf("%s - %w", location, ErrInvitationNotAnswerable)
|
||||
}
|
||||
if termsVersion != invitation.record.TermsVersion {
|
||||
return Invitation{}, fmt.Errorf("%s - the candidate read another terms version: %w", location, ErrInvitationVersionConflict)
|
||||
}
|
||||
at = at.UTC()
|
||||
next := invitation.Stored()
|
||||
next.State = string(InvitationAccepted)
|
||||
next.Version++
|
||||
next.UpdatedAt = at
|
||||
next.RespondedAt = &at
|
||||
accepted, err := RestoreInvitation(next)
|
||||
if err != nil {
|
||||
return Invitation{}, fmt.Errorf("%s - restore accepted invitation: %w", location, err)
|
||||
}
|
||||
return accepted, nil
|
||||
}
|
||||
|
||||
// acceptable reports the states from which the candidate may accept: the
|
||||
// delivered and viewed invitation. The planned counter offer is not one.
|
||||
func (invitation Invitation) acceptable() bool {
|
||||
return invitation.State() == InvitationDelivered || invitation.State() == InvitationViewed
|
||||
}
|
||||
|
||||
// AnswerEvent builds the audit event of the version that a view, a decline,
|
||||
// or an acceptance by actor has just produced. It names no field and holds neither
|
||||
// the reason nor the comment of a decline.
|
||||
func (invitation Invitation) AnswerEvent(actorID uuid.UUID) (InvitationEvent, error) {
|
||||
const location = "Invitation.AnswerEvent"
|
||||
@@ -257,6 +297,12 @@ func (invitation Invitation) AnswerEvent(actorID uuid.UUID) (InvitationEvent, er
|
||||
}, nil
|
||||
}
|
||||
|
||||
// answeredInvitationState reports the states that record the candidate's answer:
|
||||
// a declined or an accepted invitation has its answer time.
|
||||
func answeredInvitationState(state InvitationState) bool {
|
||||
return state == InvitationDeclined || state == InvitationAccepted
|
||||
}
|
||||
|
||||
// storedInvitationAnswerDefect checks the view and the answer against the
|
||||
// state: a delivered invitation has neither, a viewed one has its view, a
|
||||
// declined one has its answer, and neither precedes the delivery.
|
||||
@@ -267,8 +313,8 @@ func storedInvitationAnswerDefect(stored StoredInvitation) string {
|
||||
return "a delivered invitation has no view or answer"
|
||||
case state == InvitationViewed && (stored.ViewedAt == nil || stored.RespondedAt != nil):
|
||||
return "a viewed invitation has a view and no answer"
|
||||
case state == InvitationDeclined && stored.RespondedAt == nil:
|
||||
return "a declined invitation has an answer"
|
||||
case answeredInvitationState(state) && stored.RespondedAt == nil:
|
||||
return "a declined or accepted invitation has an answer"
|
||||
case stored.ViewedAt != nil && (stored.DeliveredAt == nil || stored.ViewedAt.Before(*stored.DeliveredAt)):
|
||||
return "a view follows the delivery"
|
||||
case stored.RespondedAt != nil && (stored.DeliveredAt == nil || stored.RespondedAt.Before(*stored.DeliveredAt)):
|
||||
@@ -305,6 +351,11 @@ type CandidateInvitationView struct {
|
||||
RespondedAt *time.Time
|
||||
UpdatedAt time.Time
|
||||
Decline *InvitationDeclineView
|
||||
// ContactConsent is set while an acceptance is possible, and ContactGrant
|
||||
// once the invitation was accepted. The usecase fills both: they need the
|
||||
// profile, the consent texts, and the visibility, which the view does not.
|
||||
ContactConsent *ContactConsentOffer
|
||||
ContactGrant *ContactGrantView
|
||||
}
|
||||
|
||||
// CandidateView returns the invitation for the candidate it is addressed to.
|
||||
|
||||
@@ -28,12 +28,18 @@ type CompanyQuotaDecision struct {
|
||||
// creates the invitation or applies the visibility change in the same
|
||||
// transaction, so a failed business operation cannot leave quota charged.
|
||||
//
|
||||
// Writers lock rows in this order: organization, active membership,
|
||||
// invitation or visibility record, then quota usage. A repository may take an
|
||||
// organization lock again inside the same transaction, but must not invert
|
||||
// this order. Each method rechecks the organization's stored verification
|
||||
// level, basis, and changed_at against the snapshot in CompanyQuota before it
|
||||
// writes; a caller cannot grant itself a tier by supplying a different level.
|
||||
// Writers lock rows in this order: organization, then for an E0 organization
|
||||
// its holding, then active membership, invitation or visibility record, and
|
||||
// last quota usage. A repository may take an organization lock again inside
|
||||
// the same transaction, but must not invert this order. Each method rechecks
|
||||
// the organization's stored verification level, basis, and changed_at against
|
||||
// the snapshot in CompanyQuota before it writes; a caller cannot grant itself
|
||||
// a tier by supplying a different level.
|
||||
//
|
||||
// The E0 limits are pooled per holding: the usage of every E0 organization of
|
||||
// one holding counts toward the same window. Usage rows stay attributed to the
|
||||
// organization that consumed them, and idempotency stays per organization.
|
||||
// Organizations at E1 and above count only their own usage.
|
||||
//
|
||||
// Invitation usage is keyed by organization and invitation ID and remains
|
||||
// until the organization is deleted. The unique key makes retries idempotent
|
||||
@@ -49,24 +55,28 @@ type CompanyQuotaRepository interface {
|
||||
// LockOrganization takes the organization lock that serializes the
|
||||
// reservations of one organization (FOR NO KEY UPDATE, which does not block
|
||||
// the foreign-key lock of a candidate's own hide), ahead of the share locks
|
||||
// of a membership check. A
|
||||
// caller that checks the membership first and reserves later would hold a
|
||||
// share lock and then ask for the exclusive one, and two such callers of one
|
||||
// organization deadlock. A caller that reserves after a share lock takes
|
||||
// this lock first, in the documented order. It returns
|
||||
// of a membership check. A caller that checks the membership first and
|
||||
// reserves later would hold a share lock and then ask for the exclusive
|
||||
// one, and two such callers of one organization deadlock. A caller that
|
||||
// reserves after a share lock takes this lock first, in the documented
|
||||
// order. For an E0 organization it also takes the lock of its holding,
|
||||
// which serializes the shared E0 pool; the holding is locked right after
|
||||
// the organization, before any other lock of the caller, so the callers of
|
||||
// one holding cannot deadlock on it. It returns
|
||||
// ErrCompanyQuotaSnapshotChanged for a removed organization.
|
||||
LockOrganization(ctx context.Context, organizationID uuid.UUID) error
|
||||
|
||||
// ReserveInvitation counts a new invitation against the current policy
|
||||
// limit. An existing invitation ID is returned as allowed and reused
|
||||
// without a second charge, regardless of its age or the request key. A
|
||||
// denied new invitation writes no usage and reports RetryAt after the
|
||||
// earliest currently counted invitation expires.
|
||||
// limit of the organization's usage scope. An existing invitation ID is
|
||||
// returned as allowed and reused without a second charge, regardless of
|
||||
// its age or the request key. A denied new invitation writes no usage and
|
||||
// reports RetryAt after the earliest currently counted invitation expires.
|
||||
ReserveInvitation(ctx context.Context, quota domain.CompanyQuota, invitationID uuid.UUID) (CompanyQuotaDecision, error)
|
||||
|
||||
// ReserveCardView counts a distinct candidate within the rolling card-view
|
||||
// window. A repeat while the prior view is active is allowed and reused,
|
||||
// and refreshes last_seen with a monotonic update. A denied new view writes
|
||||
// no usage and reports RetryAt after the earliest active view expires.
|
||||
// window of the organization's usage scope. A repeat while the prior view
|
||||
// of the same organization is active is allowed and reused, and refreshes
|
||||
// last_seen with a monotonic update. A denied new view writes no usage and
|
||||
// reports RetryAt after the earliest active view expires.
|
||||
ReserveCardView(ctx context.Context, quota domain.CompanyQuota, candidateID uuid.UUID) (CompanyQuotaDecision, error)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
// ErrContactGrantNotFound reports that the invitation has no contact grant of
|
||||
// the organization. An accepted invitation always has one, so a missing grant
|
||||
// of an accepted invitation is a storage defect.
|
||||
var ErrContactGrantNotFound = errors.New("contact grant not found")
|
||||
|
||||
// ContactGrantRepository stores the contact grants of accepted invitations. A
|
||||
// grant is created in the acceptance transaction next to its consent C4
|
||||
// record; it is never updated here, and a read is always scoped by the
|
||||
// organization.
|
||||
type ContactGrantRepository interface {
|
||||
// Create inserts the grant in the surrounding transaction. The database
|
||||
// checks that the grant agrees with its consent record and invitation.
|
||||
Create(ctx context.Context, grant domain.ContactGrant) error
|
||||
|
||||
// GetByInvitation returns the grant of one invitation of one organization,
|
||||
// or ErrContactGrantNotFound.
|
||||
GetByInvitation(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.ContactGrant, error)
|
||||
}
|
||||
@@ -36,6 +36,10 @@ var (
|
||||
// ErrInvitationDeclineResultNotFound reports a missing outcome of a
|
||||
// decline for a live idempotency record.
|
||||
ErrInvitationDeclineResultNotFound = errors.New("invitation decline result not found")
|
||||
|
||||
// ErrInvitationAcceptResultNotFound reports a missing outcome of an
|
||||
// acceptance for a live idempotency record.
|
||||
ErrInvitationAcceptResultNotFound = errors.New("invitation accept result not found")
|
||||
)
|
||||
|
||||
// MaxInvitationPageSize is the largest organization-scoped or candidate page
|
||||
@@ -49,6 +53,8 @@ type InvitationRepositories interface {
|
||||
InvitationCreationResults() InvitationCreationResultRepository
|
||||
InvitationSendResults() InvitationSendResultRepository
|
||||
InvitationDeclineResults() InvitationDeclineResultRepository
|
||||
InvitationAcceptResults() InvitationAcceptResultRepository
|
||||
ContactGrants() ContactGrantRepository
|
||||
}
|
||||
|
||||
// InvitationRepository stores invitations, their immutable terms versions, and
|
||||
@@ -130,6 +136,14 @@ type InvitationRepository interface {
|
||||
// GetDecline returns the stored decline of the invitation or
|
||||
// ErrInvitationDeclineNotFound.
|
||||
GetDecline(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.InvitationDecline, error)
|
||||
|
||||
// Accept moves a delivered or viewed invitation from expectedVersion to the
|
||||
// accepted version of next before its deadline, keeps the deadline and the
|
||||
// terms, and records the audit event. It returns
|
||||
// ErrInvitationVersionConflict when the stored row is not answerable at
|
||||
// expectedVersion, at its terms version, or before its deadline. The consent
|
||||
// C4 and the contact grant are stored by the caller in the same transaction.
|
||||
Accept(ctx context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error
|
||||
}
|
||||
|
||||
// InvitationCreationResultRepository stores the original response of a
|
||||
@@ -246,3 +260,30 @@ type InvitationDeclineResultRepository interface {
|
||||
SaveDeclineResult(ctx context.Context, scope [IdempotencyDigestSize]byte, result InvitationDeclineResult) error
|
||||
GetDeclineResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (InvitationDeclineResult, error)
|
||||
}
|
||||
|
||||
// InvitationAcceptOutcome is the stored result of an acceptance under an
|
||||
// Idempotency-Key. The contract stores a success, a missing invitation, and a
|
||||
// state conflict; a stale version and a consent refusal are not stored.
|
||||
type InvitationAcceptOutcome string
|
||||
|
||||
const (
|
||||
InvitationAcceptAccepted InvitationAcceptOutcome = "accepted"
|
||||
InvitationAcceptNotFound InvitationAcceptOutcome = "not_found"
|
||||
InvitationAcceptStateConflict InvitationAcceptOutcome = "state_conflict"
|
||||
)
|
||||
|
||||
// InvitationAcceptResult is the outcome of one acceptance. It keeps no copy of
|
||||
// the response: an accepted invitation keeps its answer and its grant, so a
|
||||
// replay rebuilds the response from them.
|
||||
type InvitationAcceptResult struct {
|
||||
InvitationID uuid.UUID
|
||||
Outcome InvitationAcceptOutcome
|
||||
}
|
||||
|
||||
// InvitationAcceptResultRepository stores the outcome of an idempotent
|
||||
// acceptance. The scope references the generic idempotency record, so the
|
||||
// outcome is removed when that record is purged.
|
||||
type InvitationAcceptResultRepository interface {
|
||||
SaveAcceptResult(ctx context.Context, scope [IdempotencyDigestSize]byte, result InvitationAcceptResult) error
|
||||
GetAcceptResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (InvitationAcceptResult, error)
|
||||
}
|
||||
@@ -61,11 +61,14 @@ type OrganizationRepositories interface {
|
||||
type OrganizationRepository interface {
|
||||
// CreateWithOwner stores a new organization and the active owner
|
||||
// membership of its creator. The two inserts run in the surrounding
|
||||
// transaction, so a failure between them leaves neither. The database also
|
||||
// refuses to commit an organization that has no active owner (constraint
|
||||
// organizations_owner_required, SQLSTATE 23514, raised by the commit of
|
||||
// the transaction), whatever code inserted it. owner must be an active
|
||||
// owner membership of organization; an unknown account fails with
|
||||
// transaction, so a failure between them leaves neither. The organization
|
||||
// joins the holding of the owner account: the holding is created in the
|
||||
// same transaction when that account has none, and an existing one is
|
||||
// reused, so concurrent creations of one account end in one holding. The
|
||||
// database also refuses to commit an organization that has no active owner
|
||||
// (constraint organizations_owner_required, SQLSTATE 23514, raised by the
|
||||
// commit of the transaction), whatever code inserted it. owner must be an
|
||||
// active owner membership of organization; an unknown account fails with
|
||||
// ErrUserNotFound, and the caller's transaction is aborted.
|
||||
CreateWithOwner(ctx context.Context, organization domain.Organization, owner domain.Membership) error
|
||||
|
||||
|
||||
@@ -43,8 +43,9 @@ func NewService(clock func() time.Time) *Service {
|
||||
}
|
||||
|
||||
// ReserveInvitation atomically records a new invitation against the policy
|
||||
// effective at the operation's clock snapshot. Repeating invitationID is
|
||||
// idempotent even when the caller uses a different request key.
|
||||
// effective at the operation's clock snapshot. The limit applies to the usage
|
||||
// scope of the organization: its own usage, or the holding pool at E0. Repeating
|
||||
// invitationID is idempotent even when the caller uses a different request key.
|
||||
func (service *Service) ReserveInvitation(
|
||||
ctx context.Context,
|
||||
repositories Repositories,
|
||||
@@ -72,9 +73,10 @@ func (service *Service) ReserveInvitation(
|
||||
return decision, nil
|
||||
}
|
||||
|
||||
// ReserveCardView atomically counts a distinct candidate in the organization's
|
||||
// rolling view window. A repeat within the window refreshes the stored time
|
||||
// without charging another distinct view.
|
||||
// ReserveCardView atomically counts a distinct candidate in the rolling view
|
||||
// window of the organization's usage scope. A repeat within the window by the
|
||||
// same organization refreshes the stored time without charging another distinct
|
||||
// view.
|
||||
func (service *Service) ReserveCardView(
|
||||
ctx context.Context,
|
||||
repositories Repositories,
|
||||
|
||||
@@ -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