package domain import ( "errors" "fmt" "log/slog" "slices" "time" "github.com/google/uuid" ) var ( // ErrInvitationNotDraft reports a change of the terms, the need link, or // the response period of an invitation that is no longer a draft. ErrInvitationNotDraft = errors.New("invitation is not a draft") // ErrInvitationVersionConflict reports that an invitation changed after the // caller read it. The API maps it to 412. ErrInvitationVersionConflict = errors.New("invitation changed concurrently") ) const redactedInvitation = "[redacted invitation]" // InvitationState is the lifecycle state of an invitation (PRD FR12). The // internal sending step is never a stored or visible state. type InvitationState string const ( InvitationDraft InvitationState = "draft" InvitationDelivered InvitationState = "delivered" InvitationViewed InvitationState = "viewed" InvitationCounter InvitationState = "counter" InvitationAccepted InvitationState = "accepted" InvitationInterviewScheduled InvitationState = "interview_scheduled" InvitationInterviewed InvitationState = "interviewed" InvitationNegotiation InvitationState = "negotiation" InvitationTermsAgreed InvitationState = "terms_agreed" InvitationNoDeal InvitationState = "no_deal" InvitationDeclined InvitationState = "declined" InvitationExpired InvitationState = "expired" InvitationWithdrawn InvitationState = "withdrawn" InvitationCancelledByCandidate InvitationState = "cancelled_by_candidate" ) // invitationFirstVersion is the version of a new draft and of its terms. const invitationFirstVersion = int64(1) func (state InvitationState) IsKnown() bool { switch state { case InvitationDraft, InvitationDelivered, InvitationViewed, InvitationCounter, InvitationAccepted, InvitationInterviewScheduled, InvitationInterviewed, InvitationNegotiation, InvitationTermsAgreed, InvitationNoDeal, InvitationDeclined, InvitationExpired, InvitationWithdrawn, InvitationCancelledByCandidate: return true default: return false } } // InvitationExpiryReason says why an invitation expired. type InvitationExpiryReason string const ( InvitationExpiryTimeout InvitationExpiryReason = "invitation_timeout" InvitationExpiryNegotiationTimeout InvitationExpiryReason = "negotiation_timeout" ) func (reason InvitationExpiryReason) IsKnown() bool { return reason == InvitationExpiryTimeout || reason == InvitationExpiryNegotiationTimeout } // InvitationNeedRef links an invitation to the need it was built from. The // link is informational: the invitation keeps its own terms. type InvitationNeedRef struct { NeedID uuid.UUID `json:"need_id"` RequirementsVersion int64 `json:"requirements_version"` } func (ref InvitationNeedRef) valid() bool { return ref.NeedID != uuid.Nil && ref.RequirementsVersion >= 1 } // ResolveResponsePeriod returns the period the draft stores. An absent // request takes the default of the policy, and a requested period must be one // of its options. func (policy InvitationPolicy) ResolveResponsePeriod(requested *CalendarDays) (CalendarDays, error) { if requested == nil { return policy.DefaultResponseDeadline, nil } if !slices.Contains(policy.ResponseDeadlineOptions, *requested) { return 0, invalidInvitationField("/response_period_days", "must be one of the response periods of the product policy") } return *requested, nil } // InvitationDraftContent is what the organization edits in a draft: the terms, // the optional link to a need, and the response period. The candidate is not // part of it, because a draft for another candidate is a new draft. type InvitationDraftContent struct { Need *InvitationNeedRef ResponsePeriod CalendarDays Terms InvitationTerms } // InvitationChangedField names a part of a draft that a change touched. type InvitationChangedField string const ( InvitationChangedTerms InvitationChangedField = "terms" InvitationChangedNeed InvitationChangedField = "need" InvitationChangedResponsePeriod InvitationChangedField = "response_period_days" ) // ChangedFields lists, in a fixed order, the parts of other that differ from // content. The terms are compared as stored, without validation. func (content InvitationDraftContent) ChangedFields(other InvitationDraftContent) []InvitationChangedField { changed := make([]InvitationChangedField, 0, 3) if !content.Terms.Equal(other.Terms) { changed = append(changed, InvitationChangedTerms) } if !equalNeedRef(content.Need, other.Need) { changed = append(changed, InvitationChangedNeed) } if content.ResponsePeriod != other.ResponsePeriod { changed = append(changed, InvitationChangedResponsePeriod) } return changed } func equalNeedRef(left, right *InvitationNeedRef) bool { if left == nil || right == nil { return left == right } return *left == *right } // Validate applies the rules of a draft that need no storage: the terms and // the shape of the need link. Whether the need exists is checked by the // usecase against storage. func (content InvitationDraftContent) Validate() error { if content.Need != nil && !content.Need.valid() { return invalidInvitationField("/need", "must name a need and a requirements version") } if content.ResponsePeriod < 1 { return invalidInvitationField("/response_period_days", "must be positive") } return content.Terms.Validate() } // StoredInvitation is the persisted form of an invitation. Only // RestoreInvitation turns it into an Invitation. type StoredInvitation struct { ID uuid.UUID OrganizationID uuid.UUID CandidateID uuid.UUID Need *InvitationNeedRef State string ExpiryReason *string Version int64 TermsVersion int64 Terms InvitationTerms ResponsePeriodDays int32 PolicyVersionID PolicyVersionID ResponseDeadlineAt *time.Time SalaryRaiseUsed bool CreatedBy uuid.UUID CreatedAt time.Time UpdatedAt time.Time DeliveredAt *time.Time ViewedAt *time.Time RespondedAt *time.Time } // Invitation is an offer of one organization to one candidate. The candidate // identifier is internal: it is never serialized, logged, or printed. type Invitation struct { record StoredInvitation } // NewInvitationDraftInput describes a draft that the organization creates. type NewInvitationDraftInput struct { ID uuid.UUID OrganizationID uuid.UUID CandidateID uuid.UUID ActorID uuid.UUID PolicyVersionID PolicyVersionID Content InvitationDraftContent At time.Time } // NewInvitationDraft builds version 1 of a draft with terms version 1. The // candidate does not see a draft. func NewInvitationDraft(input NewInvitationDraftInput) (Invitation, error) { const location = "domain.NewInvitationDraft" if input.ID == uuid.Nil || input.OrganizationID == uuid.Nil || input.CandidateID == uuid.Nil || input.ActorID == uuid.Nil || input.PolicyVersionID.IsZero() || !validInvitationTime(input.At) { return Invitation{}, fmt.Errorf("%s - identifiers and time must be set: %w", location, ErrInvalidInvitation) } if err := input.Content.Validate(); err != nil { return Invitation{}, fmt.Errorf("%s - validate draft: %w", location, err) } content := cloneDraftContent(input.Content) return RestoreInvitation(StoredInvitation{ ID: input.ID, OrganizationID: input.OrganizationID, CandidateID: input.CandidateID, Need: content.Need, State: string(InvitationDraft), Version: invitationFirstVersion, TermsVersion: invitationFirstVersion, Terms: content.Terms, ResponsePeriodDays: int32(content.ResponsePeriod), PolicyVersionID: input.PolicyVersionID, CreatedBy: input.ActorID, CreatedAt: input.At.UTC(), UpdatedAt: input.At.UTC(), }) } func cloneDraftContent(content InvitationDraftContent) InvitationDraftContent { content.Terms = content.Terms.Clone() if content.Need != nil { need := *content.Need content.Need = &need } return content } // RestoreInvitation validates a stored invitation, so a row changed outside // the application is not served. func RestoreInvitation(stored StoredInvitation) (Invitation, error) { const location = "domain.RestoreInvitation" for _, defect := range []func(StoredInvitation) string{ storedInvitationIdentityDefect, storedInvitationVersionDefect, storedInvitationLifecycleDefect, } { if reason := defect(stored); reason != "" { return Invitation{}, fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidInvitation) } } if err := stored.Terms.Validate(); err != nil { return Invitation{}, fmt.Errorf("%s - validate terms: %w", location, err) } stored.Terms = stored.Terms.Clone() stored.CreatedAt, stored.UpdatedAt = stored.CreatedAt.UTC(), stored.UpdatedAt.UTC() if stored.Need != nil { need := *stored.Need stored.Need = &need } return Invitation{record: stored}, nil } // storedInvitationIdentityDefect checks the identifiers, the state, and the // expiry reason. It returns the reason of the first defect or "". func storedInvitationIdentityDefect(stored StoredInvitation) string { state := InvitationState(stored.State) switch { case stored.ID == uuid.Nil || stored.OrganizationID == uuid.Nil || stored.CandidateID == uuid.Nil || stored.CreatedBy == uuid.Nil || stored.PolicyVersionID.IsZero(): return "identifiers must be set" case !state.IsKnown(): return "state is unknown" case (state == InvitationExpired) != (stored.ExpiryReason != nil) || (stored.ExpiryReason != nil && !InvitationExpiryReason(*stored.ExpiryReason).IsKnown()): return "expiry reason does not match the state" } return "" } // storedInvitationVersionDefect checks the versions, the need link, the // timestamps, and the response period. func storedInvitationVersionDefect(stored StoredInvitation) string { switch { case stored.Version < invitationFirstVersion || stored.TermsVersion < invitationFirstVersion || stored.TermsVersion > stored.Version: return "versions are out of range" case stored.Need != nil && !stored.Need.valid(): return "need link is invalid" case !validInvitationTime(stored.CreatedAt) || !validInvitationTime(stored.UpdatedAt) || stored.UpdatedAt.Before(stored.CreatedAt): return "timestamps are invalid" case stored.ResponsePeriodDays < 1: return "response period must be positive" } return "" } // storedInvitationLifecycleDefect checks that a draft is unsent and that the // deadline is set together with the delivery. func storedInvitationLifecycleDefect(stored StoredInvitation) string { switch { case InvitationState(stored.State) == InvitationDraft && (stored.DeliveredAt != nil || stored.ViewedAt != nil || stored.RespondedAt != nil || stored.ResponseDeadlineAt != nil || stored.SalaryRaiseUsed): return "a draft has no delivery, view, answer, or raise" case (stored.ResponseDeadlineAt == nil) != (stored.DeliveredAt == nil): return "deadline and delivery are set together" } return "" } func validInvitationTime(value time.Time) bool { return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999 } func (invitation Invitation) ID() uuid.UUID { return invitation.record.ID } func (invitation Invitation) OrganizationID() uuid.UUID { return invitation.record.OrganizationID } // CandidateID is internal: only the server resolves it, and no response, // log, or error shows it. func (invitation Invitation) CandidateID() uuid.UUID { return invitation.record.CandidateID } func (invitation Invitation) State() InvitationState { return InvitationState(invitation.record.State) } func (invitation Invitation) Version() int64 { return invitation.record.Version } func (invitation Invitation) TermsVersion() int64 { return invitation.record.TermsVersion } func (invitation Invitation) PolicyVersionID() PolicyVersionID { return invitation.record.PolicyVersionID } func (invitation Invitation) CreatedAt() time.Time { return invitation.record.CreatedAt } func (invitation Invitation) UpdatedAt() time.Time { return invitation.record.UpdatedAt } // Stored returns a deep copy of the persisted form. func (invitation Invitation) Stored() StoredInvitation { stored := invitation.record stored.Terms = stored.Terms.Clone() if stored.Need != nil { need := *stored.Need stored.Need = &need } stored.ExpiryReason = cloneString(stored.ExpiryReason) stored.ResponseDeadlineAt = cloneTime(stored.ResponseDeadlineAt) stored.DeliveredAt = cloneTime(stored.DeliveredAt) stored.ViewedAt = cloneTime(stored.ViewedAt) stored.RespondedAt = cloneTime(stored.RespondedAt) return stored } func cloneTime(value *time.Time) *time.Time { if value == nil { return nil } copied := *value return &copied } // DraftContent returns the editable part of the invitation. func (invitation Invitation) DraftContent() InvitationDraftContent { stored := invitation.Stored() return InvitationDraftContent{ Need: stored.Need, ResponsePeriod: CalendarDays(stored.ResponsePeriodDays), Terms: stored.Terms, } } // ReviseDraft returns the draft with the new content as the next version. A // change of the terms also creates the next terms version, an immutable // snapshot; a change of anything else keeps the terms version. Content that // changes nothing returns the invitation as it is and no changed fields. Only // a draft can change. func (invitation Invitation) ReviseDraft( content InvitationDraftContent, policyVersionID PolicyVersionID, at time.Time, ) (Invitation, []InvitationChangedField, error) { const location = "Invitation.ReviseDraft" if invitation.State() != InvitationDraft { return Invitation{}, nil, fmt.Errorf("%s - only a draft can change: %w", location, ErrInvitationNotDraft) } if policyVersionID.IsZero() || !validInvitationTime(at) || at.Before(invitation.record.UpdatedAt) { return Invitation{}, nil, fmt.Errorf("%s - policy version and a non-decreasing time must be set: %w", location, ErrInvalidInvitation) } if err := content.Validate(); err != nil { return Invitation{}, nil, fmt.Errorf("%s - validate draft: %w", location, err) } changed := invitation.DraftContent().ChangedFields(content) if len(changed) == 0 { return invitation, nil, nil } next := invitation.Stored() content = cloneDraftContent(content) next.Need, next.Terms, next.ResponsePeriodDays = content.Need, content.Terms, int32(content.ResponsePeriod) if slices.Contains(changed, InvitationChangedResponsePeriod) { next.PolicyVersionID = policyVersionID } if slices.Contains(changed, InvitationChangedTerms) { next.TermsVersion++ } next.Version++ next.UpdatedAt = at.UTC() revised, err := RestoreInvitation(next) if err != nil { return Invitation{}, nil, fmt.Errorf("%s - restore revised draft: %w", location, err) } return revised, changed, nil } // InvitationEventKind is the kind of an audit event. type InvitationEventKind string const ( InvitationEventDraftCreated InvitationEventKind = "draft_created" InvitationEventDraftUpdated InvitationEventKind = "draft_updated" ) // InvitationEvent is the audit record of one committed invitation version. It // names the actor and the parts that changed and holds no content. type InvitationEvent struct { ID uuid.UUID InvitationID uuid.UUID OrganizationID uuid.UUID Version int64 TermsVersion int64 Kind InvitationEventKind ActorID uuid.UUID ChangedFields []InvitationChangedField OccurredAt time.Time } // DraftEvent builds the audit event of the version this invitation has just // reached through a draft change by actor. A creation event has version 1. func (invitation Invitation) DraftEvent(actorID uuid.UUID, changed []InvitationChangedField) (InvitationEvent, error) { const location = "Invitation.DraftEvent" id, err := uuid.NewV7() if err != nil { return InvitationEvent{}, fmt.Errorf("%s - generate event ID: %w", location, err) } if actorID == uuid.Nil { return InvitationEvent{}, fmt.Errorf("%s - actor must be set: %w", location, ErrInvalidInvitation) } kind := InvitationEventDraftUpdated if invitation.record.Version == invitationFirstVersion { kind = InvitationEventDraftCreated changed = []InvitationChangedField{} } return InvitationEvent{ ID: id, InvitationID: invitation.record.ID, OrganizationID: invitation.record.OrganizationID, Version: invitation.record.Version, TermsVersion: invitation.record.TermsVersion, Kind: kind, ActorID: actorID, ChangedFields: slices.Clone(changed), OccurredAt: invitation.record.UpdatedAt, }, nil } // InvitationSalaryFit is the coarse indicator of the salary range against the // candidate's hidden minimum (PRD FR13). type InvitationSalaryFit string const ( InvitationSalaryWithinRange InvitationSalaryFit = "within_range" InvitationSalaryUpToTenPercent InvitationSalaryFit = "up_to_10_percent_above" InvitationSalaryAbove InvitationSalaryFit = "above" InvitationSalaryWithheld InvitationSalaryFit = "withheld" InvitationSalaryNotAvailable InvitationSalaryFit = "not_available" ) // InvitationContactAccess says whether the organization may read contacts // through the invitation now. type InvitationContactAccess string const ( InvitationContactAccessNone InvitationContactAccess = "not_granted" InvitationContactAccessAvailable InvitationContactAccess = "available" InvitationContactAccessClosed InvitationContactAccess = "closed" ) // InvitationSnapshot is the serializable part of an invitation that an // organization may read. It has no candidate identifier, so it cannot reveal // who the invitation is for. type InvitationSnapshot struct { ID uuid.UUID `json:"id"` OrganizationID uuid.UUID `json:"organization_id"` Need *InvitationNeedRef `json:"need"` State InvitationState `json:"state"` ExpiryReason *InvitationExpiryReason `json:"expiry_reason"` Version int64 `json:"version"` TermsVersion int64 `json:"terms_version"` Terms InvitationTerms `json:"terms"` ResponsePeriodDays int32 `json:"response_period_days"` ResponseDeadlineAt *time.Time `json:"response_deadline_at"` SalaryRaiseUsed bool `json:"salary_raise_used"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` DeliveredAt *time.Time `json:"delivered_at"` ViewedAt *time.Time `json:"viewed_at"` RespondedAt *time.Time `json:"responded_at"` } // Snapshot returns the organization-facing part of the invitation. func (invitation Invitation) Snapshot() InvitationSnapshot { stored := invitation.Stored() var reason *InvitationExpiryReason if stored.ExpiryReason != nil { value := InvitationExpiryReason(*stored.ExpiryReason) reason = &value } return InvitationSnapshot{ ID: stored.ID, OrganizationID: stored.OrganizationID, Need: stored.Need, State: InvitationState(stored.State), ExpiryReason: reason, Version: stored.Version, TermsVersion: stored.TermsVersion, Terms: stored.Terms, ResponsePeriodDays: stored.ResponsePeriodDays, ResponseDeadlineAt: stored.ResponseDeadlineAt, SalaryRaiseUsed: stored.SalaryRaiseUsed, CreatedAt: stored.CreatedAt, UpdatedAt: stored.UpdatedAt, DeliveredAt: stored.DeliveredAt, ViewedAt: stored.ViewedAt, RespondedAt: stored.RespondedAt, } } // OrganizationInvitationView is an invitation as its organization reads it: // the snapshot, the organization-scoped alias of the candidate, the coarse // salary indicator, and the state of the contact access without any contact // value. It also serves as the stored original response of an idempotent // create. type OrganizationInvitationView struct { InvitationSnapshot CandidateHandle string `json:"candidate_handle"` SalaryFit InvitationSalaryFit `json:"salary_fit"` ContactAccess InvitationContactAccess `json:"contact_access"` } func (invitation Invitation) String() string { return redactedInvitation } func (invitation Invitation) GoString() string { return redactedInvitation } func (invitation Invitation) Format(state fmt.State, _ rune) { writeRedacted(state, redactedInvitation) } func (invitation Invitation) LogValue() slog.Value { return slog.StringValue(redactedInvitation) } func (view OrganizationInvitationView) String() string { return redactedInvitation } func (view OrganizationInvitationView) GoString() string { return redactedInvitation } func (view OrganizationInvitationView) Format(state fmt.State, _ rune) { writeRedacted(state, redactedInvitation) } func (view OrganizationInvitationView) LogValue() slog.Value { return slog.StringValue(redactedInvitation) } func (snapshot InvitationSnapshot) String() string { return redactedInvitation } func (snapshot InvitationSnapshot) GoString() string { return redactedInvitation } func (snapshot InvitationSnapshot) Format(state fmt.State, _ rune) { writeRedacted(state, redactedInvitation) }