package domain import ( "errors" "fmt" "log/slog" "slices" "strings" "time" "unicode" "unicode/utf8" "github.com/google/uuid" ) // ErrInvitationNotAnswerable reports a candidate command that the state or // the deadline of the invitation does not allow, such as a decline of a // withdrawn invitation or one received at the deadline or later. The API // answers 409 state_conflict. var ErrInvitationNotAnswerable = errors.New("invitation state does not allow the answer") const ( // InvitationEventViewed is the audit event of the first view of the // terms: the invitation moved from delivered to viewed. InvitationEventViewed InvitationEventKind = "viewed" // InvitationEventDeclined is the audit event of a decline. It is the // 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" ) const ( // maxInvitationDeclineCommentRunes matches InvitationDeclineComment. maxInvitationDeclineCommentRunes = 500 redactedInvitationDecline = "[redacted invitation decline]" ) var ( // terminalInvitationStates are the final states that no command leaves. terminalInvitationStates = []InvitationState{ InvitationDeclined, InvitationExpired, InvitationWithdrawn, InvitationCancelledByCandidate, } // answerableInvitationStates allow the candidate's answer: the delivered // and viewed invitation and the planned counter offer. answerableInvitationStates = []InvitationState{InvitationDelivered, InvitationViewed, InvitationCounter} // answerEventKinds name the audit event of each answer state. answerEventKinds = map[InvitationState]InvitationEventKind{ InvitationViewed: InvitationEventViewed, InvitationDeclined: InvitationEventDeclined, } ) // InvitationDeclineReason is the structured reason of a decline. Every reason // is neutral, and none requires a comment. type InvitationDeclineReason string const ( InvitationDeclineSalary InvitationDeclineReason = "salary" InvitationDeclineTasks InvitationDeclineReason = "tasks" InvitationDeclineStack InvitationDeclineReason = "stack" InvitationDeclineWorkFormat InvitationDeclineReason = "work_format" InvitationDeclinePackage InvitationDeclineReason = "package" InvitationDeclineCompany InvitationDeclineReason = "company" InvitationDeclineNotLooking InvitationDeclineReason = "not_looking" InvitationDeclineOtherOffer InvitationDeclineReason = "other_offer" InvitationDeclineOther InvitationDeclineReason = "other" ) func (reason InvitationDeclineReason) IsKnown() bool { switch reason { case InvitationDeclineSalary, InvitationDeclineTasks, InvitationDeclineStack, InvitationDeclineWorkFormat, InvitationDeclinePackage, InvitationDeclineCompany, InvitationDeclineNotLooking, InvitationDeclineOtherOffer, InvitationDeclineOther: return true default: return false } } // InvitationDeclineChoice is what the candidate sends with a decline: the // reason and an optional comment. The comment is private to the candidate: // the organization never reads it, and it is never logged or notified. type InvitationDeclineChoice struct { Reason InvitationDeclineReason Comment *string } // Validate repeats the schema rules that a stored choice must satisfy and // refuses what PostgreSQL text cannot hold. A comment has 1 to 500 // characters, at least one that is not white space in the Unicode sense, and // no control character other than a line break or a tab. func (choice InvitationDeclineChoice) Validate() error { if !choice.Reason.IsKnown() { return invalidInvitationField("/reason", "must be a known decline reason") } if choice.Comment == nil { return nil } comment := *choice.Comment if comment == "" || !utf8.ValidString(comment) || utf8.RuneCountInString(comment) > maxInvitationDeclineCommentRunes { return invalidInvitationField("/comment", "must have 1 to 500 characters") } if strings.TrimFunc(comment, unicode.IsSpace) == "" { return invalidInvitationField("/comment", "must contain a character that is not white space") } for _, character := range comment { if unicode.IsControl(character) && character != '\n' && character != '\r' && character != '\t' { return invalidInvitationField("/comment", "must not contain control characters") } } return nil } // Equal reports whether both choices have the same reason and comment. An // absent comment equals another absent comment only. func (choice InvitationDeclineChoice) Equal(other InvitationDeclineChoice) bool { if choice.Reason != other.Reason || (choice.Comment == nil) != (other.Comment == nil) { return false } return choice.Comment == nil || *choice.Comment == *other.Comment } func (choice InvitationDeclineChoice) String() string { return redactedInvitationDecline } func (choice InvitationDeclineChoice) GoString() string { return redactedInvitationDecline } func (choice InvitationDeclineChoice) Format(state fmt.State, _ rune) { writeRedacted(state, redactedInvitationDecline) } func (choice InvitationDeclineChoice) LogValue() slog.Value { return slog.StringValue(redactedInvitationDecline) } // InvitationDecline is the stored decline of one invitation. Only the // candidate reads it back; the organization sees the state and the time of // the answer only, because a reason such as salary would tell it that the // hidden minimum is above the range. type InvitationDecline struct { InvitationID uuid.UUID OrganizationID uuid.UUID Choice InvitationDeclineChoice DeclinedAt time.Time } // Validate checks a decline before it is stored or after it is read. func (decline InvitationDecline) Validate() error { if decline.InvitationID == uuid.Nil || decline.OrganizationID == uuid.Nil || !validInvitationTime(decline.DeclinedAt) { return fmt.Errorf("InvitationDecline.Validate - identifiers and time must be set: %w", ErrInvalidInvitation) } return decline.Choice.Validate() } func (decline InvitationDecline) String() string { return redactedInvitationDecline } func (decline InvitationDecline) GoString() string { return redactedInvitationDecline } func (decline InvitationDecline) Format(state fmt.State, _ rune) { writeRedacted(state, redactedInvitationDecline) } func (decline InvitationDecline) LogValue() slog.Value { return slog.StringValue(redactedInvitationDecline) } // IsTerminal reports a final state that no candidate or organization command // leaves: declined, expired, withdrawn, or cancelled by the candidate. func (invitation Invitation) IsTerminal() bool { return slices.Contains(terminalInvitationStates, invitation.State()) } // ResponseDeadlinePassed reports whether a command received at the time is // late: at the deadline or later. An undelivered draft has no deadline. func (invitation Invitation) ResponseDeadlinePassed(at time.Time) bool { deadline := invitation.record.ResponseDeadlineAt return deadline != nil && !at.Before(*deadline) } // answerable reports the states from which the candidate may still answer: // the delivered and viewed invitation and the planned counter offer. func (invitation Invitation) answerable() bool { return slices.Contains(answerableInvitationStates, invitation.State()) } // RecordView returns the next version in the state viewed when the candidate // opens the terms of a delivered invitation before its deadline. In every // other state, and at the deadline or later, the view changes nothing and // RecordView returns the invitation as it is with changed false. The view // never moves the deadline. func (invitation Invitation) RecordView(at time.Time) (Invitation, bool, error) { const location = "Invitation.RecordView" if !validInvitationTime(at) || at.Before(invitation.record.UpdatedAt) { return Invitation{}, false, fmt.Errorf("%s - view time must be set and not before the last change: %w", location, ErrInvalidInvitation) } if invitation.State() != InvitationDelivered || !invitation.IsDelivered() || invitation.ResponseDeadlinePassed(at) { return invitation, false, nil } at = at.UTC() next := invitation.Stored() next.State = string(InvitationViewed) next.Version++ next.UpdatedAt = at next.ViewedAt = &at viewed, err := RestoreInvitation(next) if err != nil { return Invitation{}, false, fmt.Errorf("%s - restore viewed invitation: %w", location, err) } return viewed, true, nil } // Decline returns the next version in the terminal state declined with the // stored decline. It is allowed from delivered, viewed, and the planned // counter offer before the deadline; any other state or a late command // returns ErrInvitationNotAnswerable. A decline creates no consent and no // contact grant. func (invitation Invitation) Decline(choice InvitationDeclineChoice, at time.Time) (Invitation, InvitationDecline, error) { const location = "Invitation.Decline" if err := choice.Validate(); err != nil { return Invitation{}, InvitationDecline{}, fmt.Errorf("%s - validate choice: %w", location, err) } if !validInvitationTime(at) || at.Before(invitation.record.UpdatedAt) { return Invitation{}, InvitationDecline{}, fmt.Errorf("%s - decline time must be set and not before the last change: %w", location, ErrInvalidInvitation) } if !invitation.answerable() || !invitation.IsDelivered() || invitation.ResponseDeadlinePassed(at) { return Invitation{}, InvitationDecline{}, fmt.Errorf("%s - %w", location, ErrInvitationNotAnswerable) } at = at.UTC() next := invitation.Stored() next.State = string(InvitationDeclined) next.Version++ next.UpdatedAt = at next.RespondedAt = &at declined, err := RestoreInvitation(next) if err != nil { return Invitation{}, InvitationDecline{}, fmt.Errorf("%s - restore declined invitation: %w", location, err) } decline := InvitationDecline{ InvitationID: next.ID, OrganizationID: next.OrganizationID, DeclinedAt: at, Choice: InvitationDeclineChoice{Reason: choice.Reason, Comment: cloneString(choice.Comment)}, } 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 // the reason nor the comment of a decline. func (invitation Invitation) AnswerEvent(actorID uuid.UUID) (InvitationEvent, error) { const location = "Invitation.AnswerEvent" if actorID == uuid.Nil { return InvitationEvent{}, fmt.Errorf("%s - actor must be set: %w", location, ErrInvalidInvitation) } kind, ok := answerEventKinds[invitation.State()] if !ok { return InvitationEvent{}, fmt.Errorf("%s - the invitation must be viewed or declined: %w", location, ErrInvalidInvitation) } id, err := uuid.NewV7() if err != nil { return InvitationEvent{}, fmt.Errorf("%s - generate event ID: %w", location, err) } 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: []InvitationChangedField{}, OccurredAt: invitation.record.UpdatedAt, }, nil } // 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. func storedInvitationAnswerDefect(stored StoredInvitation) string { state := InvitationState(stored.State) switch { case state == InvitationDelivered && (stored.ViewedAt != nil || stored.RespondedAt != nil): 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 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)): return "an answer follows the delivery" } return "" } // InvitationDeclineView is the candidate's own decline as the candidate // reads it back. type InvitationDeclineView struct { Reason InvitationDeclineReason Comment *string DeclinedAt time.Time } // CandidateInvitationView is a delivered invitation as the addressed // candidate reads it: the organization, the current terms with their // version, the state, the deadline, and the candidate's own decline. It has // no candidate identifier, handle, need, salary indicator, or contact value. // The consent offer and the contact grant belong to the acceptance and are // absent until it exists. type CandidateInvitationView struct { ID uuid.UUID Organization InvitationOrganizationRef State InvitationState ExpiryReason *InvitationExpiryReason Version int64 TermsVersion int64 Terms InvitationTerms ResponseDeadlineAt time.Time DeliveredAt time.Time ViewedAt *time.Time RespondedAt *time.Time UpdatedAt time.Time Decline *InvitationDeclineView } // CandidateView returns the invitation for the candidate it is addressed to. // The decline must be given exactly when the invitation is declined, and it // must belong to this invitation. func (invitation Invitation) CandidateView(organization InvitationOrganizationRef, decline *InvitationDecline) (CandidateInvitationView, error) { const location = "Invitation.CandidateView" stored := invitation.Stored() if stored.DeliveredAt == nil || stored.ResponseDeadlineAt == nil { return CandidateInvitationView{}, fmt.Errorf("%s - only a delivered invitation is shown to the candidate: %w", location, ErrInvalidInvitation) } if organization.ID != stored.OrganizationID || organization.Name == "" { return CandidateInvitationView{}, fmt.Errorf("%s - the organization must be the sender: %w", location, ErrInvalidInvitation) } if (invitation.State() == InvitationDeclined) != (decline != nil) || (decline != nil && (decline.InvitationID != stored.ID || decline.OrganizationID != stored.OrganizationID)) { return CandidateInvitationView{}, fmt.Errorf("%s - the decline must belong to a declined invitation: %w", location, ErrInvalidInvitation) } snapshot := invitation.Snapshot() view := CandidateInvitationView{ ID: stored.ID, Organization: organization, State: snapshot.State, ExpiryReason: snapshot.ExpiryReason, Version: stored.Version, TermsVersion: stored.TermsVersion, Terms: stored.Terms, ResponseDeadlineAt: *stored.ResponseDeadlineAt, DeliveredAt: *stored.DeliveredAt, ViewedAt: stored.ViewedAt, RespondedAt: stored.RespondedAt, UpdatedAt: stored.UpdatedAt, } if decline != nil { view.Decline = &InvitationDeclineView{ Reason: decline.Choice.Reason, Comment: cloneString(decline.Choice.Comment), DeclinedAt: decline.DeclinedAt.UTC(), } } return view, nil } func (view CandidateInvitationView) String() string { return redactedInvitation } func (view CandidateInvitationView) GoString() string { return redactedInvitation } func (view CandidateInvitationView) Format(state fmt.State, _ rune) { writeRedacted(state, redactedInvitation) } func (view CandidateInvitationView) LogValue() slog.Value { return slog.StringValue(redactedInvitation) }