feat(invitations): accept invitations with C4 consent and contact grants; share the E0 quota across holdings

This commit is contained in:
shira committed 2026-10-09 18:03:35 +03:00
1 parent a5990d3fc6
commit 676b3c6e24
59 files changed
+4926 -194

No files matched your search

+12 -1
View File
@@ -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
+339
View File
@@ -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)
}
}
}
+49
View File
@@ -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 }
+55 -4
View File
@@ -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.