feat(invitations): add organization invitation drafts with salary range rules

This commit is contained in:
shira committed 2026-10-09 14:28:36 +03:00
1 parent 28337d84cb
commit bd23c839fd
36 files changed
+7018 -83

No files matched your search

+521
View File
@@ -0,0 +1,521 @@
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)
}
+418
View File
@@ -0,0 +1,418 @@
package domain
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"slices"
"strconv"
"strings"
"unicode"
"unicode/utf8"
)
// ErrInvalidInvitation reports an invitation value that breaks the public
// contract or cannot be restored from storage.
var ErrInvalidInvitation = errors.New("invalid invitation")
// InvitationFieldError names the field of an invitation request that failed.
// Pointer is a JSON Pointer into the request body, such as
// /terms/salary/salary_to. The error carries the reason only, never a value:
// terms are employer text, and a rejected value is not echoed.
type InvitationFieldError struct {
Pointer string
Reason string
}
func (err *InvitationFieldError) Error() string {
return fmt.Sprintf("invitation field %s: %s", err.Pointer, err.Reason)
}
func (err *InvitationFieldError) Unwrap() error { return ErrInvalidInvitation }
func invalidInvitationField(pointer, reason string) error {
return &InvitationFieldError{Pointer: pointer, Reason: reason}
}
const (
maxInvitationRoleTitleRunes = 200
maxInvitationTaskRunes = 300
maxInvitationTeamRunes = 1000
maxInvitationTechnologyRunes = 100
maxInvitationLocationRunes = 100
maxInvitationNoteRunes = 300
maxInvitationPackageTextRunes = 300
maxInvitationTasks = 20
maxInvitationTechnologies = 30
maxInvitationWorkFormats = 3
// MaxInvitationTermsBytes bounds the encoded terms of one version. The
// longest text fields fit with room even when every character takes four
// bytes; the database repeats the bound with a margin for jsonb spacing.
MaxInvitationTermsBytes = 98304
)
// InvitationOfferType is the type of the offer.
type InvitationOfferType string
const (
InvitationOfferFullTime InvitationOfferType = "full_time"
InvitationOfferPartTime InvitationOfferType = "part_time"
InvitationOfferContract InvitationOfferType = "contract"
InvitationOfferInternship InvitationOfferType = "internship"
)
func (offer InvitationOfferType) IsKnown() bool {
switch offer {
case InvitationOfferFullTime, InvitationOfferPartTime, InvitationOfferContract, InvitationOfferInternship:
return true
default:
return false
}
}
// InvitationCommunicationChannel is how the organization plans to reach the
// candidate after an acceptance. It never selects a contact field.
type InvitationCommunicationChannel string
const (
InvitationChannelEmail InvitationCommunicationChannel = "email"
InvitationChannelPhone InvitationCommunicationChannel = "phone"
InvitationChannelTelegram InvitationCommunicationChannel = "telegram"
InvitationChannelVideoCall InvitationCommunicationChannel = "video_call"
)
func (channel InvitationCommunicationChannel) IsKnown() bool {
switch channel {
case InvitationChannelEmail, InvitationChannelPhone, InvitationChannelTelegram, InvitationChannelVideoCall:
return true
default:
return false
}
}
// InvitationCommunicationMethod is part of the terms: a draft without it
// cannot exist.
type InvitationCommunicationMethod struct {
Channel InvitationCommunicationChannel `json:"channel"`
Details *string `json:"details"`
}
// InvitationPackageStatus says whether a package condition is offered.
type InvitationPackageStatus string
const (
InvitationPackageProvided InvitationPackageStatus = "provided"
InvitationPackageNotProvided InvitationPackageStatus = "not_provided"
)
// InvitationPackageItem is one required package condition. "Not provided" is
// an explicit choice with no description; a missing condition is not the same
// thing and fails validation.
type InvitationPackageItem struct {
Status InvitationPackageStatus `json:"status"`
Description *string `json:"description,omitempty"`
}
// InvitationPackage is the required section of the package (PRD FR12). The
// work format is the separate required term WorkFormats.
type InvitationPackage struct {
Bonus InvitationPackageItem `json:"bonus"`
Equipment InvitationPackageItem `json:"equipment"`
Training InvitationPackageItem `json:"training"`
HealthInsurance InvitationPackageItem `json:"health_insurance"`
}
// InvitationTerms is everything a candidate sees before deciding. The same
// value is the request field of a draft and the stored snapshot of a terms
// version. It holds no data of the candidate.
type InvitationTerms struct {
RoleTitle string `json:"role_title"`
Specialization SpecializationCode `json:"specialization"`
Grade GradeCode `json:"grade"`
OfferType InvitationOfferType `json:"offer_type"`
Tasks []string `json:"tasks"`
Team string `json:"team"`
TechStack []string `json:"tech_stack"`
WorkFormats []NeedWorkFormat `json:"work_formats"`
Location *string `json:"location"`
CommunicationMethod InvitationCommunicationMethod `json:"communication_method"`
Salary SalaryRange `json:"salary"`
Package InvitationPackage `json:"package"`
}
// Validate applies the rules the schema cannot express and repeats the
// schema rules a stored value must also satisfy. The error is an
// *InvitationFieldError with the pointer of the first failing field.
func (terms InvitationTerms) Validate() error {
checks := []func() error{
func() error {
if !validInvitationLine(terms.RoleTitle, maxInvitationRoleTitleRunes) {
return invalidInvitationField("/terms/role_title", "must be one line of 1 to 200 characters")
}
return nil
},
func() error {
if !terms.Specialization.IsKnown() {
return invalidInvitationField("/terms/specialization", "must be a known specialization")
}
return nil
},
func() error {
if !terms.Grade.IsKnown() {
return invalidInvitationField("/terms/grade", "must be a known grade")
}
return nil
},
func() error {
if !terms.OfferType.IsKnown() {
return invalidInvitationField("/terms/offer_type", "must be a known offer type")
}
return nil
},
terms.validateTasks,
func() error {
if !validInvitationText(terms.Team, maxInvitationTeamRunes) {
return invalidInvitationField("/terms/team", "must be text of 1 to 1000 characters")
}
return nil
},
terms.validateTechStack,
terms.validateWorkFormats,
terms.validateLocation,
terms.validateCommunicationMethod,
terms.validateSalary,
terms.Package.validate,
}
for _, check := range checks {
if err := check(); err != nil {
return err
}
}
return nil
}
func (terms InvitationTerms) validateTasks() error {
if len(terms.Tasks) < 1 || len(terms.Tasks) > maxInvitationTasks {
return invalidInvitationField("/terms/tasks", "must have 1 to 20 tasks")
}
for index, task := range terms.Tasks {
if !validInvitationLine(task, maxInvitationTaskRunes) {
return invalidInvitationField("/terms/tasks/"+strconv.Itoa(index), "must be one line of 1 to 300 characters")
}
}
return nil
}
// validateTechStack compares names without regard to letter case, so Go and
// GO are one technology. The pointer names the later of two equal items.
func (terms InvitationTerms) validateTechStack() error {
if len(terms.TechStack) < 1 || len(terms.TechStack) > maxInvitationTechnologies {
return invalidInvitationField("/terms/tech_stack", "must have 1 to 30 technologies")
}
seen := make(map[string]struct{}, len(terms.TechStack))
for index, name := range terms.TechStack {
pointer := "/terms/tech_stack/" + strconv.Itoa(index)
if !validInvitationLine(name, maxInvitationTechnologyRunes) {
return invalidInvitationField(pointer, "must be one line of 1 to 100 characters")
}
folded := strings.ToLower(name)
if _, duplicate := seen[folded]; duplicate {
return invalidInvitationField(pointer, "must not repeat a technology")
}
seen[folded] = struct{}{}
}
return nil
}
func (terms InvitationTerms) validateWorkFormats() error {
if len(terms.WorkFormats) < 1 || len(terms.WorkFormats) > maxInvitationWorkFormats {
return invalidInvitationField("/terms/work_formats", "must have 1 to 3 work formats")
}
for index, format := range terms.WorkFormats {
pointer := "/terms/work_formats/" + strconv.Itoa(index)
if !format.IsKnown() {
return invalidInvitationField(pointer, "must be a known work format")
}
if slices.Contains(terms.WorkFormats[:index], format) {
return invalidInvitationField(pointer, "must not repeat a work format")
}
}
return nil
}
// validateLocation requires a place of work whenever the role has an office:
// only a fully remote role may leave it null.
func (terms InvitationTerms) validateLocation() error {
officeFormat := slices.Contains(terms.WorkFormats, NeedWorkFormatOffice) || slices.Contains(terms.WorkFormats, NeedWorkFormatHybrid)
if terms.Location == nil {
if officeFormat {
return invalidInvitationField("/terms/location", "is required for the office or hybrid format")
}
return nil
}
if !validInvitationLine(*terms.Location, maxInvitationLocationRunes) {
return invalidInvitationField("/terms/location", "must be one line of 1 to 100 characters")
}
return nil
}
func (terms InvitationTerms) validateCommunicationMethod() error {
method := terms.CommunicationMethod
if !method.Channel.IsKnown() {
return invalidInvitationField("/terms/communication_method/channel", "must be a known channel")
}
if method.Details != nil && !validInvitationLine(*method.Details, maxInvitationNoteRunes) {
return invalidInvitationField("/terms/communication_method/details", "must be one line of 1 to 300 characters")
}
return nil
}
func (terms InvitationTerms) validateSalary() error {
err := terms.Salary.Validate()
if err == nil {
return nil
}
if rangeError, ok := errors.AsType[*SalaryRangeError](err); ok {
return invalidInvitationField("/terms/salary/"+rangeError.Field, rangeError.Reason)
}
return invalidInvitationField("/terms/salary", "must be a valid monthly RUB range")
}
func (pack InvitationPackage) validate() error {
items := []struct {
name string
item InvitationPackageItem
}{
{"bonus", pack.Bonus}, {"equipment", pack.Equipment},
{"training", pack.Training}, {"health_insurance", pack.HealthInsurance},
}
for _, entry := range items {
if err := entry.item.validate("/terms/package/" + entry.name); err != nil {
return err
}
}
return nil
}
func (item InvitationPackageItem) validate(pointer string) error {
switch item.Status {
case InvitationPackageProvided:
if item.Description == nil {
return invalidInvitationField(pointer+"/description", "is required for a provided condition")
}
if !validInvitationLine(*item.Description, maxInvitationPackageTextRunes) {
return invalidInvitationField(pointer+"/description", "must be one line of 1 to 300 characters")
}
case InvitationPackageNotProvided:
if item.Description != nil {
return invalidInvitationField(pointer, "a condition that is not provided has no description")
}
default:
return invalidInvitationField(pointer+"/status", "must be provided or not_provided")
}
return nil
}
// Clone returns a deep copy, so a caller cannot change a stored value.
func (terms InvitationTerms) Clone() InvitationTerms {
cloned := terms
cloned.Tasks = slices.Clone(terms.Tasks)
cloned.TechStack = slices.Clone(terms.TechStack)
cloned.WorkFormats = slices.Clone(terms.WorkFormats)
cloned.Location = cloneString(terms.Location)
cloned.CommunicationMethod.Details = cloneString(terms.CommunicationMethod.Details)
cloned.Package = InvitationPackage{
Bonus: terms.Package.Bonus.clone(), Equipment: terms.Package.Equipment.clone(),
Training: terms.Package.Training.clone(), HealthInsurance: terms.Package.HealthInsurance.clone(),
}
return cloned
}
func (item InvitationPackageItem) clone() InvitationPackageItem {
item.Description = cloneString(item.Description)
return item
}
func cloneString(value *string) *string {
if value == nil {
return nil
}
copied := *value
return &copied
}
// Equal reports whether two terms hold the same content. A reordered list is
// a different content, because the order of tasks and technologies is shown.
func (terms InvitationTerms) Equal(other InvitationTerms) bool {
return reflect.DeepEqual(terms, other)
}
// EncodeInvitationTerms returns the canonical JSON of a validated snapshot.
func EncodeInvitationTerms(terms InvitationTerms) ([]byte, error) {
if err := terms.Validate(); err != nil {
return nil, fmt.Errorf("domain.EncodeInvitationTerms - validate terms: %w", err)
}
encoded, err := json.Marshal(terms)
if err != nil {
return nil, fmt.Errorf("domain.EncodeInvitationTerms - encode terms: %w", err)
}
if len(encoded) > MaxInvitationTermsBytes {
return nil, fmt.Errorf("domain.EncodeInvitationTerms - terms exceed %d bytes: %w", MaxInvitationTermsBytes, ErrInvalidInvitation)
}
return encoded, nil
}
// DecodeInvitationTerms restores a stored snapshot. Unknown fields, trailing
// data, and rule violations fail, so a row changed outside the application is
// not served.
func DecodeInvitationTerms(encoded []byte) (InvitationTerms, error) {
const location = "domain.DecodeInvitationTerms"
if len(encoded) == 0 || len(encoded) > MaxInvitationTermsBytes {
return InvitationTerms{}, fmt.Errorf("%s - stored terms are outside their size bound: %w", location, ErrInvalidInvitation)
}
var terms InvitationTerms
if err := decodeStrictJSON(encoded, &terms); err != nil {
return InvitationTerms{}, fmt.Errorf("%s - decode terms: %w: %w", location, ErrInvalidInvitation, err)
}
if err := terms.Validate(); err != nil {
return InvitationTerms{}, fmt.Errorf("%s - validate terms: %w", location, err)
}
return terms, nil
}
// validInvitationLine accepts one line of plain text: 1 to maxRunes
// characters, no control character, and no ASCII whitespace at either end.
func validInvitationLine(value string, maxRunes int) bool {
if !validInvitationText(value, maxRunes) {
return false
}
return !strings.ContainsAny(value, "\r\n\t")
}
// validInvitationText accepts plain text of 1 to maxRunes characters that may
// contain line breaks and tabs but no other control character, and does not
// start or end with ASCII whitespace.
func validInvitationText(value string, maxRunes int) bool {
if value == "" || !utf8.ValidString(value) || utf8.RuneCountInString(value) > maxRunes {
return false
}
if strings.TrimFunc(value, isASCIISpace) != value {
return false
}
for _, character := range value {
if unicode.IsControl(character) && character != '\n' && character != '\r' && character != '\t' {
return false
}
}
return true
}
func isASCIISpace(character rune) bool {
switch character {
case ' ', '\t', '\n', '\v', '\f', '\r':
return true
default:
return false
}
}
+296
View File
@@ -0,0 +1,296 @@
package domain
import (
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
func invitationTestString(value string) *string { return &value }
func validInvitationTerms() InvitationTerms {
provided := func(text string) InvitationPackageItem {
return InvitationPackageItem{Status: InvitationPackageProvided, Description: invitationTestString(text)}
}
return InvitationTerms{
RoleTitle: "Middle Go developer",
Specialization: SpecializationBackend,
Grade: GradeMiddle,
OfferType: InvitationOfferFullTime,
Tasks: []string{"Move the payout service to an event model"},
Team: "Six engineers\nworking in two-week iterations",
TechStack: []string{"Go", "PostgreSQL"},
WorkFormats: []NeedWorkFormat{NeedWorkFormatRemote},
CommunicationMethod: InvitationCommunicationMethod{
Channel: InvitationChannelEmail,
},
Salary: SalaryRange{SalaryFrom: 100_000, SalaryTo: 140_000, Currency: SalaryCurrencyRUB, Period: SalaryPeriodMonth, TaxBasis: SalaryTaxNet},
Package: InvitationPackage{
Bonus: provided("Quarterly bonus"),
Equipment: provided("Laptop"),
Training: InvitationPackageItem{Status: InvitationPackageNotProvided},
HealthInsurance: InvitationPackageItem{Status: InvitationPackageNotProvided},
},
}
}
func validInvitationDraftInput() NewInvitationDraftInput {
policyID, _ := NewPolicyVersionID()
return NewInvitationDraftInput{
ID: uuid.New(), OrganizationID: uuid.New(), CandidateID: uuid.New(), ActorID: uuid.New(),
PolicyVersionID: policyID,
Content: InvitationDraftContent{ResponsePeriod: 7, Terms: validInvitationTerms()},
At: time.Date(2026, 10, 9, 12, 0, 0, 123456789, time.UTC),
}
}
func TestNewInvitationDraftStartsAtVersionOne(t *testing.T) {
input := validInvitationDraftInput()
draft, err := NewInvitationDraft(input)
if err != nil {
t.Fatalf("NewInvitationDraft() error = %v", err)
}
snapshot := draft.Snapshot()
if snapshot.State != InvitationDraft || snapshot.Version != 1 || snapshot.TermsVersion != 1 ||
snapshot.ResponseDeadlineAt != nil || snapshot.DeliveredAt != nil || snapshot.SalaryRaiseUsed || snapshot.ExpiryReason != nil {
t.Fatalf("draft snapshot = %+v, want an unsent version 1", snapshot)
}
event, err := draft.DraftEvent(input.ActorID, []InvitationChangedField{InvitationChangedTerms})
if err != nil {
t.Fatalf("DraftEvent() error = %v", err)
}
if event.Kind != InvitationEventDraftCreated || event.Version != 1 || len(event.ChangedFields) != 0 {
t.Fatalf("creation event = %+v, want draft_created at version 1 with no changed fields", event)
}
}
func TestInvitationTermsValidationPointsAtTheFailingField(t *testing.T) {
tests := []struct {
name string
change func(*InvitationTerms)
wantPointer string
}{
{"role title with a line break", func(t *InvitationTerms) { t.RoleTitle = "Go\ndeveloper" }, "/terms/role_title"},
{"role title with a NUL", func(t *InvitationTerms) { t.RoleTitle = "Go\x00developer" }, "/terms/role_title"},
{"role title with edge whitespace", func(t *InvitationTerms) { t.RoleTitle = " Go developer" }, "/terms/role_title"},
{"unknown specialization", func(t *InvitationTerms) { t.Specialization = "wizard" }, "/terms/specialization"},
{"unknown grade", func(t *InvitationTerms) { t.Grade = "guru" }, "/terms/grade"},
{"unknown offer type", func(t *InvitationTerms) { t.OfferType = "volunteer" }, "/terms/offer_type"},
{"no tasks", func(t *InvitationTerms) { t.Tasks = nil }, "/terms/tasks"},
{"empty second task", func(t *InvitationTerms) { t.Tasks = []string{"First", ""} }, "/terms/tasks/1"},
{"empty team", func(t *InvitationTerms) { t.Team = "" }, "/terms/team"},
{"repeated technology ignoring case", func(t *InvitationTerms) { t.TechStack = []string{"Go", "PostgreSQL", "GO"} }, "/terms/tech_stack/2"},
{"repeated work format", func(t *InvitationTerms) {
t.WorkFormats = []NeedWorkFormat{NeedWorkFormatRemote, NeedWorkFormatRemote}
t.Location = invitationTestString("Moscow")
}, "/terms/work_formats/1"},
{"office without a place", func(t *InvitationTerms) { t.WorkFormats = []NeedWorkFormat{NeedWorkFormatOffice} }, "/terms/location"},
{"hybrid among remote without a place", func(t *InvitationTerms) {
t.WorkFormats = []NeedWorkFormat{NeedWorkFormatRemote, NeedWorkFormatHybrid}
}, "/terms/location"},
{"unknown channel", func(t *InvitationTerms) { t.CommunicationMethod.Channel = "pigeon" }, "/terms/communication_method/channel"},
{"empty communication note", func(t *InvitationTerms) { t.CommunicationMethod.Details = invitationTestString("") }, "/terms/communication_method/details"},
{"reversed salary", func(t *InvitationTerms) { t.Salary.SalaryFrom, t.Salary.SalaryTo = 140_000, 100_000 }, "/terms/salary/salary_to"},
{"salary without a basis", func(t *InvitationTerms) { t.Salary.TaxBasis = "" }, "/terms/salary/tax_basis"},
{"zero lower bound", func(t *InvitationTerms) { t.Salary.SalaryFrom = 0 }, "/terms/salary/salary_from"},
{"lower bound off the step", func(t *InvitationTerms) { t.Salary.SalaryFrom = 100_500 }, "/terms/salary/salary_from"},
{"bonus left without a status", func(t *InvitationTerms) { t.Package.Bonus = InvitationPackageItem{} }, "/terms/package/bonus/status"},
{"provided without a description", func(t *InvitationTerms) {
t.Package.Training = InvitationPackageItem{Status: InvitationPackageProvided}
}, "/terms/package/training/description"},
{"not provided with a description", func(t *InvitationTerms) {
t.Package.HealthInsurance = InvitationPackageItem{Status: InvitationPackageNotProvided, Description: invitationTestString("Premium plan")}
}, "/terms/package/health_insurance"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
terms := validInvitationTerms()
test.change(&terms)
var field *InvitationFieldError
err := terms.Validate()
if !errors.As(err, &field) || field.Pointer != test.wantPointer || !errors.Is(err, ErrInvalidInvitation) {
t.Fatalf("Validate() error = %v, want a field error at %s", err, test.wantPointer)
}
})
}
}
// Every package condition may explicitly be "not provided"; the explicit
// choice is a complete package.
func TestInvitationPackageMayDeclareEveryConditionNotProvided(t *testing.T) {
terms := validInvitationTerms()
none := InvitationPackageItem{Status: InvitationPackageNotProvided}
terms.Package = InvitationPackage{Bonus: none, Equipment: none, Training: none, HealthInsurance: none}
if err := terms.Validate(); err != nil {
t.Fatalf("Validate() error = %v, want an explicit empty package to be valid", err)
}
}
func TestInvitationTermsRoundTripThroughTheStoredSnapshot(t *testing.T) {
terms := validInvitationTerms()
terms.Location = invitationTestString("Kazan")
encoded, err := EncodeInvitationTerms(terms)
if err != nil {
t.Fatalf("EncodeInvitationTerms() error = %v", err)
}
decoded, err := DecodeInvitationTerms(encoded)
if err != nil || !decoded.Equal(terms) {
t.Fatalf("DecodeInvitationTerms() = %+v, %v; want the same terms", decoded, err)
}
var generic map[string]any
if err := json.Unmarshal(encoded, &generic); err != nil {
t.Fatalf("decode snapshot: %v", err)
}
salary, _ := generic["salary"].(map[string]any)
if salary["salary_from"] != float64(100000) || salary["currency"] != "RUB" || salary["tax_basis"] != "net" {
t.Fatalf("snapshot salary = %v, want whole rubles with their basis", salary)
}
if _, present := generic["candidate_email"]; present {
t.Fatal("snapshot carries a candidate field")
}
for name, mutate := range map[string]func(string) string{
"unknown field": func(s string) string { return strings.Replace(s, `"team"`, `"salary_minimum":1,"team"`, 1) },
"trailing data": func(s string) string { return s + " {}" },
"salary string": func(s string) string { return strings.Replace(s, `"salary_from":100000`, `"salary_from":"100000"`, 1) },
} {
if _, err := DecodeInvitationTerms([]byte(mutate(string(encoded)))); err == nil {
t.Errorf("DecodeInvitationTerms(%s) accepted a changed snapshot", name)
}
}
}
func TestReviseDraftCreatesNextVersionsOnlyWhenContentChanges(t *testing.T) {
input := validInvitationDraftInput()
draft, err := NewInvitationDraft(input)
if err != nil {
t.Fatalf("NewInvitationDraft() error = %v", err)
}
later := input.At.Add(time.Minute)
policyID, _ := NewPolicyVersionID()
same, changed, err := draft.ReviseDraft(draft.DraftContent(), policyID, later)
if err != nil || len(changed) != 0 || same.Version() != 1 || !same.UpdatedAt().Equal(draft.UpdatedAt()) {
t.Fatalf("no-op revision = version %d changed %v err %v, want the draft untouched", same.Version(), changed, err)
}
content := draft.DraftContent()
content.ResponsePeriod = 14
revised, changed, err := draft.ReviseDraft(content, policyID, later)
if err != nil {
t.Fatalf("ReviseDraft(period) error = %v", err)
}
if revised.Version() != 2 || revised.TermsVersion() != 1 || len(changed) != 1 || changed[0] != InvitationChangedResponsePeriod ||
revised.PolicyVersionID() != policyID {
t.Fatalf("period revision = version %d/%d changed %v, want version 2 with terms version 1", revised.Version(), revised.TermsVersion(), changed)
}
content = revised.DraftContent()
content.Terms.Salary.SalaryTo = 150_000
content.Need = &InvitationNeedRef{NeedID: uuid.New(), RequirementsVersion: 2}
third, changed, err := revised.ReviseDraft(content, policyID, later.Add(time.Minute))
if err != nil {
t.Fatalf("ReviseDraft(terms and need) error = %v", err)
}
if third.Version() != 3 || third.TermsVersion() != 2 || fmt.Sprint(changed) != "[terms need]" {
t.Fatalf("terms revision = version %d/%d changed %v, want 3/2 with terms and need", third.Version(), third.TermsVersion(), changed)
}
event, err := third.DraftEvent(input.ActorID, changed)
if err != nil || event.Kind != InvitationEventDraftUpdated || event.Version != 3 || event.TermsVersion != 2 {
t.Fatalf("update event = %+v, %v; want draft_updated at 3/2", event, err)
}
// The earlier values were not changed in place.
if draft.Snapshot().Terms.Salary.SalaryTo != 140_000 || revised.Snapshot().Terms.Salary.SalaryTo != 140_000 {
t.Fatal("a revision changed an earlier invitation value")
}
}
func TestReviseDraftRefusesAnInvitationThatIsNotADraft(t *testing.T) {
input := validInvitationDraftInput()
draft, err := NewInvitationDraft(input)
if err != nil {
t.Fatalf("NewInvitationDraft() error = %v", err)
}
stored := draft.Stored()
stored.State = string(InvitationWithdrawn)
withdrawn, err := RestoreInvitation(stored)
if err != nil {
t.Fatalf("RestoreInvitation(withdrawn) error = %v", err)
}
content := withdrawn.DraftContent()
content.ResponsePeriod = 14
if _, _, err := withdrawn.ReviseDraft(content, input.PolicyVersionID, input.At.Add(time.Minute)); !errors.Is(err, ErrInvitationNotDraft) {
t.Fatalf("ReviseDraft(withdrawn) error = %v, want ErrInvitationNotDraft", err)
}
}
func TestRestoreInvitationRejectsInconsistentRows(t *testing.T) {
input := validInvitationDraftInput()
draft, err := NewInvitationDraft(input)
if err != nil {
t.Fatalf("NewInvitationDraft() error = %v", err)
}
now := input.At.Add(time.Hour)
tests := map[string]func(*StoredInvitation){
"unknown state": func(s *StoredInvitation) { s.State = "sent" },
"expiry reason without expiry": func(s *StoredInvitation) { s.ExpiryReason = invitationTestString("invitation_timeout") },
"terms version ahead": func(s *StoredInvitation) { s.TermsVersion = 2 },
"draft with a delivery": func(s *StoredInvitation) {
s.DeliveredAt, s.ResponseDeadlineAt = &now, &now
},
"salary range that is too wide": func(s *StoredInvitation) { s.Terms.Salary.SalaryTo = 500_000 },
"updated before created": func(s *StoredInvitation) { s.UpdatedAt = s.CreatedAt.Add(-time.Second) },
"no policy version": func(s *StoredInvitation) { s.PolicyVersionID = PolicyVersionID{} },
}
for name, mutate := range tests {
t.Run(name, func(t *testing.T) {
stored := draft.Stored()
mutate(&stored)
if _, err := RestoreInvitation(stored); !errors.Is(err, ErrInvalidInvitation) {
t.Fatalf("RestoreInvitation() error = %v, want ErrInvalidInvitation", err)
}
})
}
}
func TestInvitationHidesTheCandidateAndTheTermsWhenPrinted(t *testing.T) {
input := validInvitationDraftInput()
draft, err := NewInvitationDraft(input)
if err != nil {
t.Fatalf("NewInvitationDraft() error = %v", err)
}
view := OrganizationInvitationView{InvitationSnapshot: draft.Snapshot(), CandidateHandle: "cv1_" + strings.Repeat("A", 43)}
for _, printed := range []string{
fmt.Sprintf("%v %+v %#v %s", draft, draft, draft, draft),
fmt.Sprintf("%v %+v %#v", view, view, view),
fmt.Sprintf("%v", draft.Snapshot()),
} {
if strings.Contains(printed, input.CandidateID.String()) || strings.Contains(printed, "Middle Go developer") {
t.Fatalf("printed invitation leaks a candidate or term: %s", printed)
}
}
encoded, err := json.Marshal(view)
if err != nil || strings.Contains(string(encoded), input.CandidateID.String()) {
t.Fatalf("serialized view = %s, %v; want no candidate identifier", encoded, err)
}
}
func TestInvitationPolicyResolvesTheResponsePeriod(t *testing.T) {
policy := InvitationPolicy{ResponseDeadlineOptions: []CalendarDays{3, 7, 14}, DefaultResponseDeadline: 7}
if period, err := policy.ResolveResponsePeriod(nil); err != nil || period != 7 {
t.Fatalf("ResolveResponsePeriod(nil) = %d, %v; want the default 7", period, err)
}
three := CalendarDays(3)
if period, err := policy.ResolveResponsePeriod(&three); err != nil || period != 3 {
t.Fatalf("ResolveResponsePeriod(3) = %d, %v; want 3", period, err)
}
five := CalendarDays(5)
var field *InvitationFieldError
if _, err := policy.ResolveResponsePeriod(&five); !errors.As(err, &field) || field.Pointer != "/response_period_days" {
t.Fatalf("ResolveResponsePeriod(5) error = %v, want a field error", err)
}
}
+4 -17
View File
@@ -102,14 +102,9 @@ func (format NeedWorkFormat) IsKnown() bool {
}
}
// NeedSalaryRange is a monthly RUB range with an explicit tax basis.
type NeedSalaryRange struct {
SalaryFrom int64 `json:"salary_from"`
SalaryTo int64 `json:"salary_to"`
Currency string `json:"currency"`
Period string `json:"period"`
TaxBasis string `json:"tax_basis"`
}
// NeedSalaryRange is a monthly RUB range with an explicit tax basis. A need
// and an invitation share the money rules of SalaryRange.
type NeedSalaryRange = SalaryRange
// NeedSkill is one ordered required or desired skill. TaxonomyCode is nil
// when the platform has no reviewed mapping for the supplied name.
@@ -749,15 +744,7 @@ func validNeedWorkFormats(formats []NeedWorkFormat) bool {
}
func validNeedSalaryRange(value NeedSalaryRange) bool {
if value.SalaryFrom < 1000 || value.SalaryFrom > 100000000 || value.SalaryFrom%1000 != 0 ||
value.SalaryTo < 1000 || value.SalaryTo > 100000000 || value.SalaryTo%1000 != 0 ||
value.Currency != "RUB" || value.Period != "month" || (value.TaxBasis != "net" && value.TaxBasis != "gross") ||
value.SalaryFrom >= value.SalaryTo {
return false
}
width := value.SalaryTo - value.SalaryFrom
sum := value.SalaryTo + value.SalaryFrom
return 20*width >= sum && 5*width <= sum
return value.Validate() == nil
}
func validNeedTaxonomyCode(value string) bool {
+100
View File
@@ -0,0 +1,100 @@
package domain
import (
"errors"
"fmt"
)
// ErrInvalidSalaryRange reports a salary range that breaks the money rules.
var ErrInvalidSalaryRange = errors.New("invalid salary range")
const (
// SalaryCurrencyRUB is the only currency of the MVP.
SalaryCurrencyRUB = "RUB"
// SalaryPeriodMonth is the only pay period of the MVP.
SalaryPeriodMonth = "month"
// SalaryTaxNet is a net ("after personal income tax") amount.
SalaryTaxNet = "net"
// SalaryTaxGross is a gross ("before personal income tax") amount.
SalaryTaxGross = "gross"
// SalaryStepRubles is the step of every salary bound (PRD FR13).
SalaryStepRubles int64 = 1000
// MaxSalaryRubles caps a bound, so the integer width test below cannot
// overflow: the largest product is 20 * MaxSalaryRubles.
MaxSalaryRubles int64 = 100_000_000
)
// SalaryRange is a monthly range [From; To] in whole rubles with its tax
// basis. Amounts are exact integers; no float takes part in any comparison.
type SalaryRange struct {
SalaryFrom int64 `json:"salary_from"`
SalaryTo int64 `json:"salary_to"`
Currency string `json:"currency"`
Period string `json:"period"`
TaxBasis string `json:"tax_basis"`
}
// SalaryRangeError names the field of the range that failed. The field is the
// JSON name inside the range, so a caller can build the pointer of its own
// request from it. The error never carries an amount.
type SalaryRangeError struct {
Field string
Reason string
}
func (err *SalaryRangeError) Error() string {
return fmt.Sprintf("salary range field %s: %s", err.Field, err.Reason)
}
func (err *SalaryRangeError) Unwrap() error { return ErrInvalidSalaryRange }
// Validate applies the rules of PRD FR13:
//
// - the currency is RUB, the period is a month, and the base is net or gross;
// - A and B are positive multiples of 1000 (and at most MaxSalaryRubles);
// - A < B;
// - the width 2 * (B - A) / (A + B), the range relative to its midpoint, is
// from 10% to 40% inclusive.
//
// The width test is the integer pair 20 * (B - A) >= A + B and
// 5 * (B - A) <= A + B, which holds exactly at 10% and 40% without a rounding
// error. The first failing field is reported; a reversed or too narrow or wide
// range is attributed to salary_to.
func (salary SalaryRange) Validate() error {
if err := validSalaryBound("salary_from", salary.SalaryFrom); err != nil {
return err
}
if err := validSalaryBound("salary_to", salary.SalaryTo); err != nil {
return err
}
switch {
case salary.Currency != SalaryCurrencyRUB:
return &SalaryRangeError{Field: "currency", Reason: "must be RUB"}
case salary.Period != SalaryPeriodMonth:
return &SalaryRangeError{Field: "period", Reason: "must be month"}
case salary.TaxBasis != SalaryTaxNet && salary.TaxBasis != SalaryTaxGross:
return &SalaryRangeError{Field: "tax_basis", Reason: "must be net or gross"}
case salary.SalaryFrom >= salary.SalaryTo:
return &SalaryRangeError{Field: "salary_to", Reason: "must be above salary_from"}
}
width := salary.SalaryTo - salary.SalaryFrom
sum := salary.SalaryTo + salary.SalaryFrom
if 20*width < sum {
return &SalaryRangeError{Field: "salary_to", Reason: "the range is narrower than 10% of its midpoint"}
}
if 5*width > sum {
return &SalaryRangeError{Field: "salary_to", Reason: "the range is wider than 40% of its midpoint"}
}
return nil
}
func validSalaryBound(field string, amount int64) error {
if amount < SalaryStepRubles || amount > MaxSalaryRubles {
return &SalaryRangeError{Field: field, Reason: "must be from 1000 to 100000000 rubles"}
}
if amount%SalaryStepRubles != 0 {
return &SalaryRangeError{Field: field, Reason: "must be a multiple of 1000"}
}
return nil
}
@@ -0,0 +1,82 @@
package domain
import (
"errors"
"testing"
)
func rubRange(from, to int64, basis string) SalaryRange {
return SalaryRange{SalaryFrom: from, SalaryTo: to, Currency: SalaryCurrencyRUB, Period: SalaryPeriodMonth, TaxBasis: basis}
}
// The width is checked in integers: the exact 10% and 40% ranges pass, and a
// step of 1000 beyond either bound fails.
func TestSalaryRangeWidthIsExactAtTheBoundaries(t *testing.T) {
tests := []struct {
name string
from, to int64
wantField string
}{
{name: "exactly 10 percent", from: 95_000, to: 105_000},
{name: "exactly 40 percent", from: 80_000, to: 120_000},
{name: "typical range", from: 100_000, to: 140_000},
{name: "exactly 10 percent at a large scale", from: 76_000_000, to: 84_000_000},
{name: "just below 10 percent", from: 95_000, to: 104_000, wantField: "salary_to"},
{name: "just above 40 percent", from: 80_000, to: 121_000, wantField: "salary_to"},
{name: "narrowest lower neighbour", from: 96_000, to: 105_000, wantField: "salary_to"},
{name: "equal bounds", from: 100_000, to: 100_000, wantField: "salary_to"},
{name: "reversed bounds", from: 140_000, to: 100_000, wantField: "salary_to"},
{name: "far too wide", from: 1_000, to: 100_000_000, wantField: "salary_to"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := rubRange(test.from, test.to, SalaryTaxNet).Validate()
if test.wantField == "" {
if err != nil {
t.Fatalf("Validate() error = %v, want nil", err)
}
return
}
var rangeError *SalaryRangeError
if !errors.As(err, &rangeError) || rangeError.Field != test.wantField || !errors.Is(err, ErrInvalidSalaryRange) {
t.Fatalf("Validate() error = %v, want a range error on %s", err, test.wantField)
}
})
}
}
func TestSalaryRangeRejectsBoundsOutsideTheStep(t *testing.T) {
tests := []struct {
name string
salary SalaryRange
wantField string
}{
{name: "zero lower bound", salary: rubRange(0, 100_000, SalaryTaxNet), wantField: "salary_from"},
{name: "negative lower bound", salary: rubRange(-100_000, 100_000, SalaryTaxNet), wantField: "salary_from"},
{name: "lower bound off the step", salary: rubRange(100_500, 140_000, SalaryTaxNet), wantField: "salary_from"},
{name: "upper bound off the step", salary: rubRange(100_000, 140_500, SalaryTaxNet), wantField: "salary_to"},
{name: "upper bound over the cap", salary: rubRange(80_000_000, 120_000_000, SalaryTaxNet), wantField: "salary_to"},
{name: "overflowing bound", salary: rubRange(100_000, 9_223_372_036_854_775_000, SalaryTaxNet), wantField: "salary_to"},
{name: "no tax basis", salary: rubRange(100_000, 140_000, ""), wantField: "tax_basis"},
{name: "unknown tax basis", salary: rubRange(100_000, 140_000, "pre-tax"), wantField: "tax_basis"},
{name: "foreign currency", salary: SalaryRange{SalaryFrom: 100_000, SalaryTo: 140_000, Currency: "USD", Period: SalaryPeriodMonth, TaxBasis: SalaryTaxNet}, wantField: "currency"},
{name: "yearly period", salary: SalaryRange{SalaryFrom: 100_000, SalaryTo: 140_000, Currency: SalaryCurrencyRUB, Period: "year", TaxBasis: SalaryTaxNet}, wantField: "period"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var rangeError *SalaryRangeError
if err := test.salary.Validate(); !errors.As(err, &rangeError) || rangeError.Field != test.wantField {
t.Fatalf("Validate() error = %v, want a range error on %s", err, test.wantField)
}
})
}
}
// Both bases are valid; the base is never inferred or converted.
func TestSalaryRangeAcceptsBothTaxBases(t *testing.T) {
for _, basis := range []string{SalaryTaxNet, SalaryTaxGross} {
if err := rubRange(100_000, 140_000, basis).Validate(); err != nil {
t.Errorf("Validate(%s) error = %v", basis, err)
}
}
}