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

@@ -25,6 +25,7 @@ type Handler struct {
catalog *CatalogHandler
organization *OrganizationHandler
need *NeedHandler
invitation *InvitationHandler
support *SupportHandler
assessment *AssessmentHandler
assessmentSignals *AssessmentSignalHandler
@@ -75,6 +76,11 @@ func WithNeed(need *NeedHandler) HandlerOption {
return func(handler *Handler) { handler.need = need }
}
// WithInvitation serves the organization side of invitation drafts.
func WithInvitation(invitation *InvitationHandler) HandlerOption {
return func(handler *Handler) { handler.invitation = invitation }
}
// WithSupport serves account-owned support cases.
func WithSupport(support *SupportHandler) HandlerOption {
return func(handler *Handler) { handler.support = support }
@@ -0,0 +1,495 @@
package v1
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
invitationusecase "lincodex/backend/internal/usecase/invitation"
)
const defaultInvitationLimit = 20
// InvitationOperations are the owner-scoped invitation draft reads and
// commands served by HTTP.
type InvitationOperations interface {
Create(ctx context.Context, command invitationusecase.CreateCommand) (domain.OrganizationInvitationView, error)
Get(ctx context.Context, actorID, organizationID, invitationID uuid.UUID) (domain.OrganizationInvitationView, error)
List(ctx context.Context, command invitationusecase.ListCommand) (invitationusecase.Page, error)
Update(ctx context.Context, command invitationusecase.UpdateCommand) (domain.OrganizationInvitationView, error)
}
// InvitationHandler serves the organization side of invitation drafts. The
// organization comes from the path and the server-side membership, never from
// a body, and the candidate is only ever named by the opaque card handle.
type InvitationHandler struct {
operations InvitationOperations
}
func NewInvitationHandler(operations InvitationOperations) *InvitationHandler {
if operations == nil {
panic("v1.NewInvitationHandler - invitation operations must not be nil")
}
return &InvitationHandler{operations: operations}
}
func (handler *Handler) ListOrganizationInvitations(ctx context.Context, params api.ListOrganizationInvitationsParams) (api.ListOrganizationInvitationsRes, error) {
if handler.invitation == nil {
return handler.UnimplementedHandler.ListOrganizationInvitations(ctx, params)
}
return handler.invitation.ListOrganizationInvitations(ctx, params)
}
func (handler *Handler) CreateOrganizationInvitation(ctx context.Context, request *api.OrganizationInvitationCreate, params api.CreateOrganizationInvitationParams) (api.CreateOrganizationInvitationRes, error) {
if handler.invitation == nil {
return handler.UnimplementedHandler.CreateOrganizationInvitation(ctx, request, params)
}
return handler.invitation.CreateOrganizationInvitation(ctx, request, params)
}
func (handler *Handler) GetOrganizationInvitation(ctx context.Context, params api.GetOrganizationInvitationParams) (api.GetOrganizationInvitationRes, error) {
if handler.invitation == nil {
return handler.UnimplementedHandler.GetOrganizationInvitation(ctx, params)
}
return handler.invitation.GetOrganizationInvitation(ctx, params)
}
func (handler *Handler) UpdateOrganizationInvitation(ctx context.Context, request *api.OrganizationInvitationUpdate, params api.UpdateOrganizationInvitationParams) (api.UpdateOrganizationInvitationRes, error) {
if handler.invitation == nil {
return handler.UnimplementedHandler.UpdateOrganizationInvitation(ctx, request, params)
}
return handler.invitation.UpdateOrganizationInvitation(ctx, request, params)
}
func (handler *InvitationHandler) CreateOrganizationInvitation(
ctx context.Context,
request *api.OrganizationInvitationCreate,
params api.CreateOrganizationInvitationParams,
) (api.CreateOrganizationInvitationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.CreateOrganizationInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return (*api.CreateOrganizationInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
canonical, err := json.Marshal(request)
if err != nil {
return nil, errors.New("InvitationHandler.CreateOrganizationInvitation - encode canonical request")
}
command := invitationusecase.CreateCommand{
ActorID: principal.UserID, OrganizationID: params.OrgID, IdempotencyKey: params.IdempotencyKey,
CanonicalBody: canonical, CandidateHandle: string(request.CandidateHandle),
Terms: invitationTermsFromRequest(request.Terms),
}
if need, set := request.Need.Get(); set {
command.Need = &domain.InvitationNeedRef{NeedID: need.NeedID, RequirementsVersion: int64(need.RequirementsVersion)}
}
if period, set := request.ResponsePeriodDays.Get(); set {
days := int32(period)
command.ResponsePeriodDays = &days
}
view, err := handler.operations.Create(ctx, command)
if err != nil {
return invitationCreateFailure(ctx, err)
}
return &api.OrganizationInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: organizationInvitationResponse(view)}, nil
}
func (handler *InvitationHandler) GetOrganizationInvitation(
ctx context.Context,
params api.GetOrganizationInvitationParams,
) (api.GetOrganizationInvitationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetOrganizationInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
view, err := handler.operations.Get(ctx, principal.UserID, params.OrgID, params.InvitationID)
if err != nil {
return invitationReadFailure(ctx, err)
}
return &api.OrganizationInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: organizationInvitationResponse(view)}, nil
}
func (handler *InvitationHandler) ListOrganizationInvitations(
ctx context.Context,
params api.ListOrganizationInvitationsParams,
) (api.ListOrganizationInvitationsRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListOrganizationInvitationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
command, pointer := invitationListCommand(principal.UserID, params)
if pointer != "" {
return (*api.ListOrganizationInvitationsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
}
page, err := handler.operations.List(ctx, command)
if err != nil {
switch {
case errors.Is(err, invitationusecase.ErrForbidden), errors.Is(err, invitationusecase.ErrEmailNotVerified), errors.Is(err, outbound.ErrOrganizationManagerRequired):
return (*api.ListOrganizationInvitationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrOrganizationNotFound):
return (*api.ListOrganizationInvitationsNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
default:
return nil, err
}
}
items := make([]api.OrganizationInvitationSummary, 0, len(page.Items))
for _, item := range page.Items {
items = append(items, organizationInvitationSummary(item))
}
next := api.NilString{}
next.SetToNull()
if page.HasMore && len(page.Items) > 0 {
last := page.Items[len(page.Items)-1]
cursor, err := encodeInvitationCursor(principal.UserID, params.OrgID, outbound.InvitationListPosition{
CreatedAt: last.CreatedAt, InvitationID: last.ID,
})
if err != nil {
return nil, fmt.Errorf("InvitationHandler.ListOrganizationInvitations - encode cursor: %w", err)
}
next.SetTo(cursor)
}
return &api.OrganizationInvitationListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.OrganizationInvitationList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
}, nil
}
func (handler *InvitationHandler) UpdateOrganizationInvitation(
ctx context.Context,
request *api.OrganizationInvitationUpdate,
params api.UpdateOrganizationInvitationParams,
) (api.UpdateOrganizationInvitationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.UpdateOrganizationInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return (*api.UpdateOrganizationInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
command := invitationusecase.UpdateCommand{
ActorID: principal.UserID, OrganizationID: params.OrgID, InvitationID: params.InvitationID,
ExpectedVersion: int64(request.ExpectedVersion),
}
if request.Need.Set {
command.Need = invitationusecase.Field[domain.InvitationNeedRef]{Set: true, Null: request.Need.Null}
if !request.Need.Null {
command.Need.Value = domain.InvitationNeedRef{
NeedID: request.Need.Value.NeedID, RequirementsVersion: int64(request.Need.Value.RequirementsVersion),
}
}
}
if period, set := request.ResponsePeriodDays.Get(); set {
days := int32(period)
command.ResponsePeriodDays = &days
}
if terms, set := request.Terms.Get(); set {
converted := invitationTermsFromRequest(terms)
command.Terms = &converted
}
view, err := handler.operations.Update(ctx, command)
if err != nil {
return invitationUpdateFailure(ctx, err)
}
return &api.OrganizationInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: organizationInvitationResponse(view)}, nil
}
// invitationFailure is the public classification of a usecase error. Every
// kind has one fixed problem, so a response never depends on which of two
// indistinguishable causes happened.
type invitationFailure int
const (
invitationFailureOther invitationFailure = iota
invitationFailureForbidden
invitationFailureNotFound
invitationFailureKeyReused
invitationFailureBadKey
invitationFailureInvalid
invitationFailureVersionConflict
invitationFailureStateConflict
)
func classifyInvitationError(err error) invitationFailure {
switch {
case errors.Is(err, invitationusecase.ErrForbidden), errors.Is(err, invitationusecase.ErrEmailNotVerified),
errors.Is(err, outbound.ErrOrganizationManagerRequired):
return invitationFailureForbidden
case errors.Is(err, outbound.ErrOrganizationNotFound), errors.Is(err, outbound.ErrInvitationNotFound):
return invitationFailureNotFound
case errors.Is(err, invitationusecase.ErrIdempotencyKeyReused):
return invitationFailureKeyReused
case errors.Is(err, invitationusecase.ErrInvalidIdempotencyKey):
return invitationFailureBadKey
case errors.Is(err, domain.ErrInvitationVersionConflict), errors.Is(err, outbound.ErrInvitationVersionConflict):
return invitationFailureVersionConflict
case errors.Is(err, domain.ErrInvitationNotDraft):
return invitationFailureStateConflict
case errors.Is(err, domain.ErrInvalidInvitation), errors.Is(err, domain.ErrInvalidSalaryRange):
if _, ok := errors.AsType[*domain.InvitationFieldError](err); ok {
return invitationFailureInvalid
}
return invitationFailureOther
default:
return invitationFailureOther
}
}
func invitationValidationProblem(ctx context.Context, err error) *api.Problem {
field, ok := errors.AsType[*domain.InvitationFieldError](err)
if !ok {
return &problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response
}
return &problem.InvalidField(ctx, api.ProblemFieldLocationBody, field.Pointer).Response
}
func invitationCreateFailure(ctx context.Context, err error) (api.CreateOrganizationInvitationRes, error) {
switch classifyInvitationError(err) {
case invitationFailureForbidden:
return (*api.CreateOrganizationInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case invitationFailureNotFound:
return (*api.CreateOrganizationInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case invitationFailureKeyReused:
return (*api.CreateOrganizationInvitationUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
case invitationFailureBadKey:
return (*api.CreateOrganizationInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
case invitationFailureInvalid:
return (*api.CreateOrganizationInvitationBadRequest)(invitationValidationProblem(ctx, err)), nil
case invitationFailureVersionConflict, invitationFailureStateConflict, invitationFailureOther:
return nil, err
}
return nil, err
}
func invitationReadFailure(ctx context.Context, err error) (api.GetOrganizationInvitationRes, error) {
switch classifyInvitationError(err) {
case invitationFailureForbidden:
return (*api.GetOrganizationInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case invitationFailureNotFound:
return (*api.GetOrganizationInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case invitationFailureKeyReused, invitationFailureBadKey, invitationFailureInvalid,
invitationFailureVersionConflict, invitationFailureStateConflict, invitationFailureOther:
return nil, err
}
return nil, err
}
func invitationUpdateFailure(ctx context.Context, err error) (api.UpdateOrganizationInvitationRes, error) {
switch classifyInvitationError(err) {
case invitationFailureForbidden:
return (*api.UpdateOrganizationInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case invitationFailureNotFound:
return (*api.UpdateOrganizationInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case invitationFailureVersionConflict:
return (*api.UpdateOrganizationInvitationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case invitationFailureStateConflict:
return (*api.UpdateOrganizationInvitationConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
case invitationFailureInvalid:
return (*api.UpdateOrganizationInvitationBadRequest)(invitationValidationProblem(ctx, err)), nil
case invitationFailureKeyReused, invitationFailureBadKey, invitationFailureOther:
return nil, err
}
return nil, err
}
func invitationListCommand(actorID uuid.UUID, params api.ListOrganizationInvitationsParams) (invitationusecase.ListCommand, string) {
limit, ok := params.Limit.Get()
if !ok {
limit = defaultInvitationLimit
}
if limit < 1 || limit > outbound.MaxInvitationPageSize {
return invitationusecase.ListCommand{}, "limit"
}
command := invitationusecase.ListCommand{ActorID: actorID, OrganizationID: params.OrgID, Limit: limit}
if cursor, ok := params.Cursor.Get(); ok {
position, err := decodeInvitationCursor(cursor, actorID, params.OrgID)
if err != nil {
return invitationusecase.ListCommand{}, "cursor"
}
command.After = &position
}
return command, ""
}
// invitationTermsFromRequest copies the request terms into the domain value.
// It validates nothing: the schema has already run, and the domain rules run
// in the usecase in the order of the contract.
func invitationTermsFromRequest(terms api.InvitationTerms) domain.InvitationTerms {
converted := domain.InvitationTerms{
RoleTitle: string(terms.RoleTitle), Specialization: domain.SpecializationCode(terms.Specialization),
Grade: domain.GradeCode(terms.Grade), OfferType: domain.InvitationOfferType(terms.OfferType),
Team: string(terms.Team),
CommunicationMethod: domain.InvitationCommunicationMethod{
Channel: domain.InvitationCommunicationChannel(terms.CommunicationMethod.Channel),
},
Salary: domain.SalaryRange{
SalaryFrom: int64(terms.Salary.SalaryFrom), SalaryTo: int64(terms.Salary.SalaryTo),
Currency: string(terms.Salary.Currency), Period: string(terms.Salary.Period), TaxBasis: string(terms.Salary.TaxBasis),
},
Package: domain.InvitationPackage{
Bonus: packageItemFromRequest(terms.Package.Bonus), Equipment: packageItemFromRequest(terms.Package.Equipment),
Training: packageItemFromRequest(terms.Package.Training), HealthInsurance: packageItemFromRequest(terms.Package.HealthInsurance),
},
}
converted.Tasks = make([]string, 0, len(terms.Tasks))
for _, task := range terms.Tasks {
converted.Tasks = append(converted.Tasks, string(task))
}
converted.TechStack = make([]string, 0, len(terms.TechStack))
for _, name := range terms.TechStack {
converted.TechStack = append(converted.TechStack, string(name))
}
converted.WorkFormats = make([]domain.NeedWorkFormat, 0, len(terms.WorkFormats))
for _, format := range terms.WorkFormats {
converted.WorkFormats = append(converted.WorkFormats, domain.NeedWorkFormat(format))
}
if !terms.Location.Null {
location := string(terms.Location.Value)
converted.Location = &location
}
if !terms.CommunicationMethod.Details.Null {
details := string(terms.CommunicationMethod.Details.Value)
converted.CommunicationMethod.Details = &details
}
return converted
}
func packageItemFromRequest(item api.InvitationPackageItem) domain.InvitationPackageItem {
switch item.Type {
case api.InvitationPackageItemProvidedInvitationPackageItem:
description := string(item.InvitationPackageItemProvided.Description)
return domain.InvitationPackageItem{Status: domain.InvitationPackageProvided, Description: &description}
case api.InvitationPackageItemNotProvidedInvitationPackageItem:
return domain.InvitationPackageItem{Status: domain.InvitationPackageNotProvided}
}
// The schema admits only the two variants; anything else is left without a
// status, which the domain validation refuses with the pointer of the item.
return domain.InvitationPackageItem{}
}
func packageItemResponse(item domain.InvitationPackageItem) api.InvitationPackageItem {
if item.Status == domain.InvitationPackageProvided && item.Description != nil {
return api.NewInvitationPackageItemProvidedInvitationPackageItem(api.InvitationPackageItemProvided{
Status: api.InvitationPackageItemProvidedStatusProvided,
Description: api.InvitationPackageItemText(*item.Description),
})
}
return api.NewInvitationPackageItemNotProvidedInvitationPackageItem(api.InvitationPackageItemNotProvided{
Status: api.InvitationPackageItemNotProvidedStatusNotProvided,
})
}
func invitationTermsResponse(terms domain.InvitationTerms) api.InvitationTerms {
response := api.InvitationTerms{
RoleTitle: api.InvitationRoleTitle(terms.RoleTitle), Specialization: api.SpecializationCode(terms.Specialization),
Grade: api.GradeCode(terms.Grade), OfferType: api.InvitationOfferType(terms.OfferType),
Team: api.InvitationTeamDescription(terms.Team),
CommunicationMethod: api.InvitationCommunicationMethod{Channel: api.InvitationCommunicationChannel(terms.CommunicationMethod.Channel)},
Salary: salaryRangeResponse(terms.Salary),
Package: api.InvitationPackage{
Bonus: packageItemResponse(terms.Package.Bonus), Equipment: packageItemResponse(terms.Package.Equipment),
Training: packageItemResponse(terms.Package.Training), HealthInsurance: packageItemResponse(terms.Package.HealthInsurance),
},
}
response.Tasks = make([]api.NeedTaskText, 0, len(terms.Tasks))
for _, task := range terms.Tasks {
response.Tasks = append(response.Tasks, api.NeedTaskText(task))
}
response.TechStack = make([]api.SkillName, 0, len(terms.TechStack))
for _, name := range terms.TechStack {
response.TechStack = append(response.TechStack, api.SkillName(name))
}
response.WorkFormats = make([]api.WorkFormat, 0, len(terms.WorkFormats))
for _, format := range terms.WorkFormats {
response.WorkFormats = append(response.WorkFormats, api.WorkFormat(format))
}
if terms.Location == nil {
response.Location.SetToNull()
} else {
response.Location.SetTo(api.NeedLocationName(*terms.Location))
}
if terms.CommunicationMethod.Details == nil {
response.CommunicationMethod.Details.SetToNull()
} else {
response.CommunicationMethod.Details.SetTo(api.InvitationCommunicationNote(*terms.CommunicationMethod.Details))
}
return response
}
func salaryRangeResponse(salary domain.SalaryRange) api.SalaryRange {
return api.SalaryRange{
SalaryFrom: api.RubAmount(salary.SalaryFrom), SalaryTo: api.RubAmount(salary.SalaryTo),
Currency: api.CurrencyCode(salary.Currency), Period: api.SalaryPeriod(salary.Period), TaxBasis: api.SalaryTaxBasis(salary.TaxBasis),
}
}
func invitationNeedResponse(need *domain.InvitationNeedRef) api.NilInvitationNeedReference {
var response api.NilInvitationNeedReference
if need == nil {
response.SetToNull()
return response
}
response.SetTo(api.InvitationNeedReference{NeedID: need.NeedID, RequirementsVersion: api.NeedVersion(need.RequirementsVersion)})
return response
}
func invitationExpiryResponse(reason *domain.InvitationExpiryReason) api.NilInvitationExpiryReason {
var response api.NilInvitationExpiryReason
if reason == nil {
response.SetToNull()
return response
}
response.SetTo(api.InvitationExpiryReason(*reason))
return response
}
func nullableTimestamp(value *time.Time) api.NilTimestamp {
var response api.NilTimestamp
if value == nil {
response.SetToNull()
return response
}
response.SetTo(api.Timestamp(*value))
return response
}
func invitationContactAccessResponse(access domain.InvitationContactAccess) api.InvitationContactAccess {
// No contact grant exists before an acceptance, so no kind of contact is
// listed and no contact value is ever part of this response.
return api.InvitationContactAccess{Status: api.InvitationContactAccessState(access), Fields: []api.ContactFieldKind{}}
}
func organizationInvitationResponse(view domain.OrganizationInvitationView) api.OrganizationInvitation {
return api.OrganizationInvitation{
ID: view.ID, OrganizationID: view.OrganizationID, CandidateHandle: api.CandidateHandle(view.CandidateHandle),
Need: invitationNeedResponse(view.Need), State: api.InvitationState(view.State),
ExpiryReason: invitationExpiryResponse(view.ExpiryReason), Version: api.InvitationVersion(view.Version),
TermsVersion: api.InvitationTermsVersion(view.TermsVersion), Terms: invitationTermsResponse(view.Terms),
ResponsePeriodDays: api.InvitationResponsePeriod(view.ResponsePeriodDays),
ResponseDeadlineAt: nullableTimestamp(view.ResponseDeadlineAt), SalaryRaiseUsed: view.SalaryRaiseUsed,
SalaryFit: api.InvitationSalaryFit(view.SalaryFit), ContactAccess: invitationContactAccessResponse(view.ContactAccess),
CreatedAt: api.Timestamp(view.CreatedAt), UpdatedAt: api.Timestamp(view.UpdatedAt),
DeliveredAt: nullableTimestamp(view.DeliveredAt), ViewedAt: nullableTimestamp(view.ViewedAt),
RespondedAt: nullableTimestamp(view.RespondedAt),
}
}
func organizationInvitationSummary(view domain.OrganizationInvitationView) api.OrganizationInvitationSummary {
return api.OrganizationInvitationSummary{
ID: view.ID, CandidateHandle: api.CandidateHandle(view.CandidateHandle), Need: invitationNeedResponse(view.Need),
State: api.InvitationState(view.State), ExpiryReason: invitationExpiryResponse(view.ExpiryReason),
Version: api.InvitationVersion(view.Version), TermsVersion: api.InvitationTermsVersion(view.TermsVersion),
RoleTitle: api.InvitationRoleTitle(view.Terms.RoleTitle), Salary: salaryRangeResponse(view.Terms.Salary),
ResponseDeadlineAt: nullableTimestamp(view.ResponseDeadlineAt), ContactAccess: invitationContactAccessResponse(view.ContactAccess),
CreatedAt: api.Timestamp(view.CreatedAt), UpdatedAt: api.Timestamp(view.UpdatedAt),
}
}
@@ -0,0 +1,55 @@
package v1
import (
"encoding/base64"
"encoding/binary"
"errors"
"math"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/port/outbound"
)
const (
invitationCursorVersion = 1
invitationCursorBytes = 61
maxInvitationCursorTime = uint64(253402300799)
)
// encodeInvitationCursor binds the position to the account and the
// organization that read the page, so a cursor of another reader or tenant is
// refused instead of continuing a foreign listing.
func encodeInvitationCursor(actorID, organizationID uuid.UUID, position outbound.InvitationListPosition) (string, error) {
seconds, nanos := position.CreatedAt.Unix(), position.CreatedAt.Nanosecond()
if actorID == uuid.Nil || organizationID == uuid.Nil || position.InvitationID == uuid.Nil || position.CreatedAt.IsZero() ||
position.CreatedAt.Year() < 1 || position.CreatedAt.Year() > 9999 || seconds < 0 || uint64(seconds) > maxInvitationCursorTime ||
nanos < 0 || nanos >= 1_000_000_000 || nanos%int(time.Microsecond) != 0 {
return "", errors.New("invitation cursor requires an actor, organization, and valid page position")
}
var value [invitationCursorBytes]byte
value[0] = invitationCursorVersion
copy(value[1:17], actorID[:])
copy(value[17:33], organizationID[:])
binary.BigEndian.PutUint64(value[33:41], uint64(seconds))
binary.BigEndian.PutUint32(value[41:45], uint32(nanos))
copy(value[45:61], position.InvitationID[:])
return base64.RawURLEncoding.EncodeToString(value[:]), nil
}
func decodeInvitationCursor(cursor string, actorID, organizationID uuid.UUID) (outbound.InvitationListPosition, error) {
value, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil || len(value) != invitationCursorBytes || actorID == uuid.Nil || organizationID == uuid.Nil ||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != invitationCursorVersion ||
uuid.UUID(value[1:17]) != actorID || uuid.UUID(value[17:33]) != organizationID {
return outbound.InvitationListPosition{}, errors.New("invitation cursor is invalid")
}
seconds := binary.BigEndian.Uint64(value[33:41])
nanos := binary.BigEndian.Uint32(value[41:45])
invitationID := uuid.UUID(value[45:61])
if seconds > uint64(math.MaxInt64) || seconds > maxInvitationCursorTime || nanos >= 1_000_000_000 || nanos%1_000 != 0 || invitationID == uuid.Nil {
return outbound.InvitationListPosition{}, errors.New("invitation cursor position is invalid")
}
return outbound.InvitationListPosition{CreatedAt: time.Unix(int64(seconds), int64(nanos)).UTC(), InvitationID: invitationID}, nil
}
@@ -0,0 +1,193 @@
package v1
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
invitationusecase "lincodex/backend/internal/usecase/invitation"
)
func invitationTestTerms() api.InvitationTerms {
provided := api.NewInvitationPackageItemProvidedInvitationPackageItem(api.InvitationPackageItemProvided{
Status: api.InvitationPackageItemProvidedStatusProvided, Description: "Quarterly bonus",
})
notProvided := api.NewInvitationPackageItemNotProvidedInvitationPackageItem(api.InvitationPackageItemNotProvided{
Status: api.InvitationPackageItemNotProvidedStatusNotProvided,
})
terms := api.InvitationTerms{
RoleTitle: "Middle Go developer", Specialization: "backend", Grade: "middle", OfferType: api.InvitationOfferTypeFullTime,
Tasks: []api.NeedTaskText{"Build the payout service"}, Team: "Six engineers", TechStack: []api.SkillName{"Go"},
WorkFormats: []api.WorkFormat{api.WorkFormatRemote},
CommunicationMethod: api.InvitationCommunicationMethod{Channel: api.InvitationCommunicationChannelEmail},
Salary: api.SalaryRange{SalaryFrom: 100000, SalaryTo: 140000, Currency: api.CurrencyCodeRUB, Period: api.SalaryPeriodMonth, TaxBasis: api.SalaryTaxBasisNet},
Package: api.InvitationPackage{Bonus: provided, Equipment: notProvided, Training: notProvided, HealthInsurance: notProvided},
}
terms.Location.SetToNull()
terms.CommunicationMethod.Details.SetToNull()
return terms
}
// The request terms and the response terms are the same value: a response can
// be sent back unchanged, and a nullable term keeps its meaning both ways.
func TestInvitationTermsSurviveTheRequestResponseRoundTrip(t *testing.T) {
request := invitationTestTerms()
converted := invitationTermsFromRequest(request)
if err := converted.Validate(); err != nil {
t.Fatalf("converted terms are invalid: %v", err)
}
if converted.Location != nil || converted.CommunicationMethod.Details != nil {
t.Fatalf("null terms were mapped to values: %+v", converted)
}
if converted.Package.Bonus.Status != domain.InvitationPackageProvided || converted.Package.Bonus.Description == nil ||
converted.Package.Equipment.Status != domain.InvitationPackageNotProvided || converted.Package.Equipment.Description != nil {
t.Fatalf("package mapped wrongly: %+v", converted.Package)
}
encodedRequest, err := json.Marshal(request)
if err != nil {
t.Fatalf("marshal request terms: %v", err)
}
encodedResponse, err := json.Marshal(invitationTermsResponse(converted))
if err != nil {
t.Fatalf("marshal response terms: %v", err)
}
if string(encodedRequest) != string(encodedResponse) {
t.Fatalf("response terms differ from the request terms:\n%s\n%s", encodedRequest, encodedResponse)
}
}
func TestInvitationResponseNeverCarriesACandidateIdentifierOrAContact(t *testing.T) {
candidateID := uuid.Must(uuid.NewV7())
organizationID := uuid.Must(uuid.NewV7())
policyID, err := domain.NewPolicyVersionID()
if err != nil {
t.Fatalf("NewPolicyVersionID() error = %v", err)
}
now := time.Date(2026, time.October, 9, 10, 0, 0, 0, time.UTC)
draft, err := domain.NewInvitationDraft(domain.NewInvitationDraftInput{
ID: uuid.Must(uuid.NewV7()), OrganizationID: organizationID, CandidateID: candidateID, ActorID: uuid.Must(uuid.NewV7()),
PolicyVersionID: policyID, At: now,
Content: domain.InvitationDraftContent{ResponsePeriod: 7, Terms: invitationTermsFromRequest(invitationTestTerms())},
})
if err != nil {
t.Fatalf("NewInvitationDraft() error = %v", err)
}
view := domain.OrganizationInvitationView{
InvitationSnapshot: draft.Snapshot(), CandidateHandle: "cv1_" + strings.Repeat("A", 43),
SalaryFit: domain.InvitationSalaryNotAvailable, ContactAccess: domain.InvitationContactAccessNone,
}
for name, response := range map[string]any{
"invitation": organizationInvitationResponse(view),
"summary": organizationInvitationSummary(view),
} {
encoded, err := json.Marshal(response)
if err != nil {
t.Fatalf("marshal %s: %v", name, err)
}
text := string(encoded)
if strings.Contains(text, candidateID.String()) {
t.Errorf("%s carries the candidate identifier: %s", name, text)
}
for _, field := range []string{"email", "phone", "telegram", "full_name", "salary_minimum", "candidate_id"} {
if strings.Contains(text, `"`+field+`":`) {
t.Errorf("%s carries the field %s: %s", name, field, text)
}
}
if !strings.Contains(text, `"candidate_handle":"cv1_`) {
t.Errorf("%s does not name the candidate by the card handle: %s", name, text)
}
}
encoded, _ := json.Marshal(organizationInvitationResponse(view))
for _, want := range []string{`"state":"draft"`, `"version":1`, `"terms_version":1`, `"response_deadline_at":null`, `"salary_fit":"not_available"`, `"contact_access":{"status":"not_granted","fields":[]}`, `"need":null`} {
if !strings.Contains(string(encoded), want) {
t.Errorf("draft response lacks %s: %s", want, encoded)
}
}
}
func TestInvitationFailuresMapToTheContractStatuses(t *testing.T) {
ctx := context.Background()
field := &domain.InvitationFieldError{Pointer: "/terms/salary/salary_to", Reason: "x"}
create := func(err error) any {
response, unexpected := invitationCreateFailure(ctx, err)
if unexpected != nil {
return unexpected
}
return fmt.Sprintf("%T", response)
}
update := func(err error) any {
response, unexpected := invitationUpdateFailure(ctx, err)
if unexpected != nil {
return unexpected
}
return fmt.Sprintf("%T", response)
}
tests := []struct {
name string
err error
wantCreate string
wantUpdate string
}{
{"forbidden", invitationusecase.ErrForbidden, "*api.CreateOrganizationInvitationForbidden", "*api.UpdateOrganizationInvitationForbidden"},
{"not an owner", fmt.Errorf("wrapped: %w", outbound.ErrOrganizationManagerRequired), "*api.CreateOrganizationInvitationForbidden", "*api.UpdateOrganizationInvitationForbidden"},
{"unknown organization", outbound.ErrOrganizationNotFound, "*api.CreateOrganizationInvitationNotFound", "*api.UpdateOrganizationInvitationNotFound"},
{"unknown invitation", outbound.ErrInvitationNotFound, "*api.CreateOrganizationInvitationNotFound", "*api.UpdateOrganizationInvitationNotFound"},
{"field error", fmt.Errorf("wrapped: %w", field), "*api.CreateOrganizationInvitationBadRequest", "*api.UpdateOrganizationInvitationBadRequest"},
{"stale version", domain.ErrInvitationVersionConflict, "", "*api.UpdateOrganizationInvitationPreconditionFailed"},
{"not a draft", domain.ErrInvitationNotDraft, "", "*api.UpdateOrganizationInvitationConflict"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if test.wantCreate != "" {
if got := create(test.err); got != test.wantCreate {
t.Errorf("create failure = %v, want %s", got, test.wantCreate)
}
}
if got := update(test.err); got != test.wantUpdate {
t.Errorf("update failure = %v, want %s", got, test.wantUpdate)
}
})
}
if got := create(invitationusecase.ErrIdempotencyKeyReused); got != "*api.CreateOrganizationInvitationUnprocessableEntity" {
t.Errorf("reused key = %v, want 422", got)
}
// An error without a public meaning is left to the responder, which logs
// it and answers with a fixed 500.
if _, passedOn := create(errors.New("storage failed")).(error); !passedOn {
t.Error("an unknown failure produced a public response instead of reaching the responder")
}
}
func TestInvitationCursorIsBoundToActorAndOrganization(t *testing.T) {
actorID, organizationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7())
position := outbound.InvitationListPosition{
CreatedAt: time.Date(2026, time.October, 9, 10, 0, 0, 123456000, time.UTC), InvitationID: uuid.Must(uuid.NewV7()),
}
cursor, err := encodeInvitationCursor(actorID, organizationID, position)
if err != nil {
t.Fatalf("encodeInvitationCursor() error = %v", err)
}
decoded, err := decodeInvitationCursor(cursor, actorID, organizationID)
if err != nil || !decoded.CreatedAt.Equal(position.CreatedAt) || decoded.InvitationID != position.InvitationID {
t.Fatalf("decodeInvitationCursor() = %+v, %v; want the same position", decoded, err)
}
for name, test := range map[string]struct{ actor, organization uuid.UUID }{
"another actor": {uuid.Must(uuid.NewV7()), organizationID}, "another organization": {actorID, uuid.Must(uuid.NewV7())},
} {
if _, err := decodeInvitationCursor(cursor, test.actor, test.organization); err == nil {
t.Errorf("a cursor of %s was accepted", name)
}
}
if _, err := decodeInvitationCursor(cursor+"A", actorID, organizationID); err == nil {
t.Error("a cursor with trailing data was accepted")
}
}
@@ -0,0 +1,443 @@
package postgres
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"math"
"slices"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var (
_ outbound.InvitationRepository = invitationRepository{}
_ outbound.InvitationCreationResultRepository = invitationRepository{}
)
// maxInvitationCreationResultBytes bounds the stored original response of a
// create: the terms plus the alias and the fixed fields.
const maxInvitationCreationResultBytes = 163840
func (unit *UnitOfWork) Invitations() outbound.InvitationRepository {
return invitationRepository{queries: unit.queries}
}
func (unit *UnitOfWork) InvitationCreationResults() outbound.InvitationCreationResultRepository {
return invitationRepository{queries: unit.queries}
}
type invitationRepository struct {
queries *sqlc.Queries
}
func (repository invitationRepository) Create(
ctx context.Context,
invitation domain.Invitation,
event domain.InvitationEvent,
) error {
const location = "invitationRepository.Create"
stored := invitation.Stored()
if stored.State != string(domain.InvitationDraft) || stored.Version != 1 || stored.TermsVersion != 1 {
return fmt.Errorf("%s - creation must store a draft at version 1: %w", location, domain.ErrInvalidInvitation)
}
if err := repository.insertEventPrerequisites(location, invitation, event, 1); err != nil {
return err
}
period, err := invitationResponsePeriodParam(location, stored.ResponsePeriodDays)
if err != nil {
return err
}
if err := repository.queries.InsertInvitation(ctx, sqlc.InsertInvitationParams{
ID: pgUUID(stored.ID), OrganizationID: pgUUID(stored.OrganizationID), CandidateID: pgUUID(stored.CandidateID),
NeedID: invitationNeedID(stored.Need), NeedRequirementsVersion: invitationNeedVersion(stored.Need),
State: stored.State, Version: stored.Version, TermsVersion: stored.TermsVersion,
ResponsePeriodDays: period, PolicyVersionID: pgUUID(stored.PolicyVersionID.UUID()),
CreatedBy: pgUUID(stored.CreatedBy), CreatedAt: pgTime(stored.CreatedAt), UpdatedAt: pgTime(stored.UpdatedAt),
}); err != nil {
return fmt.Errorf("%s - insert invitation: %w", location, mapInvitationError(err))
}
if err := repository.insertTermsVersion(ctx, location, stored, stored.TermsVersion, stored.UpdatedAt); err != nil {
return err
}
return repository.insertEvent(ctx, location, event)
}
func (repository invitationRepository) Get(
ctx context.Context,
organizationID, invitationID uuid.UUID,
) (domain.Invitation, error) {
const location = "invitationRepository.Get"
if organizationID == uuid.Nil || invitationID == uuid.Nil {
return domain.Invitation{}, fmt.Errorf("%s - organization and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation)
}
row, err := repository.queries.ReadInvitation(ctx, sqlc.ReadInvitationParams{
OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID),
})
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - read invitation: %w", location, mapInvitationNoRows(err))
}
return restoreInvitationRow(location, sqlc.ListInvitationsRow(row), organizationID)
}
func (repository invitationRepository) GetForUpdate(
ctx context.Context,
organizationID, invitationID uuid.UUID,
) (domain.Invitation, error) {
const location = "invitationRepository.GetForUpdate"
if organizationID == uuid.Nil || invitationID == uuid.Nil {
return domain.Invitation{}, fmt.Errorf("%s - organization and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation)
}
if _, err := repository.queries.LockInvitation(ctx, sqlc.LockInvitationParams{
OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID),
}); err != nil {
return domain.Invitation{}, fmt.Errorf("%s - lock invitation: %w", location, mapInvitationNoRows(err))
}
invitation, err := repository.Get(ctx, organizationID, invitationID)
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - read locked invitation: %w", location, err)
}
return invitation, nil
}
func (repository invitationRepository) GetTermsVersion(
ctx context.Context,
organizationID, invitationID uuid.UUID,
version int64,
) (domain.InvitationTerms, error) {
const location = "invitationRepository.GetTermsVersion"
if organizationID == uuid.Nil || invitationID == uuid.Nil || version < 1 {
return domain.InvitationTerms{}, fmt.Errorf("%s - scope and version must be set: %w", location, domain.ErrInvalidInvitation)
}
encoded, err := repository.queries.ReadInvitationTermsVersion(ctx, sqlc.ReadInvitationTermsVersionParams{
OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID), Version: version,
})
if err != nil {
return domain.InvitationTerms{}, fmt.Errorf("%s - read terms version: %w", location, mapInvitationNoRows(err))
}
terms, err := domain.DecodeInvitationTerms([]byte(encoded))
if err != nil {
return domain.InvitationTerms{}, fmt.Errorf("%s - restore terms: %w", location, err)
}
return terms, nil
}
func (repository invitationRepository) List(
ctx context.Context,
query outbound.InvitationListQuery,
) (outbound.InvitationPage, error) {
const location = "invitationRepository.List"
if query.OrganizationID == uuid.Nil {
return outbound.InvitationPage{}, fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidInvitation)
}
if query.Limit < 1 || query.Limit > outbound.MaxInvitationPageSize {
return outbound.InvitationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxInvitationPageSize, domain.ErrInvalidInvitation)
}
params := sqlc.ListInvitationsParams{OrganizationID: pgUUID(query.OrganizationID), RowLimit: query.Limit + 1}
if query.After != nil {
after := *query.After
if after.InvitationID == uuid.Nil || !validStoredInvitationTime(after.CreatedAt) {
return outbound.InvitationPage{}, fmt.Errorf("%s - pagination position is invalid: %w", location, domain.ErrInvalidInvitation)
}
params.AfterCreatedAt = pgTime(after.CreatedAt)
params.AfterInvitationID = pgUUID(after.InvitationID)
}
rows, err := repository.queries.ListInvitations(ctx, params)
if err != nil {
return outbound.InvitationPage{}, fmt.Errorf("%s - select invitations: %w", location, mapInvitationError(err))
}
page := outbound.InvitationPage{HasMore: len(rows) > int(query.Limit)}
if page.HasMore {
rows = rows[:query.Limit]
}
page.Items = make([]domain.Invitation, 0, len(rows))
for _, row := range rows {
invitation, err := restoreInvitationRow(location, row, query.OrganizationID)
if err != nil {
return outbound.InvitationPage{}, err
}
page.Items = append(page.Items, invitation)
}
return page, nil
}
func (repository invitationRepository) SaveDraft(
ctx context.Context,
expectedVersion int64,
next domain.Invitation,
termsChanged bool,
event domain.InvitationEvent,
) error {
const location = "invitationRepository.SaveDraft"
stored := next.Stored()
if expectedVersion < 1 || stored.Version != expectedVersion+1 {
return fmt.Errorf("%s - the next version must follow the expected one: %w", location, domain.ErrInvalidInvitation)
}
if err := repository.insertEventPrerequisites(location, next, event, stored.Version); err != nil {
return err
}
period, err := invitationResponsePeriodParam(location, stored.ResponsePeriodDays)
if err != nil {
return err
}
_, err = repository.queries.AdvanceInvitationDraft(ctx, sqlc.AdvanceInvitationDraftParams{
NeedID: invitationNeedID(stored.Need), NeedRequirementsVersion: invitationNeedVersion(stored.Need),
ResponsePeriodDays: period, PolicyVersionID: pgUUID(stored.PolicyVersionID.UUID()),
TermsVersion: stored.TermsVersion, NextVersion: stored.Version, UpdatedAt: pgTime(stored.UpdatedAt),
OrganizationID: pgUUID(stored.OrganizationID), InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion,
})
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%s - advance draft: %w", location, outbound.ErrInvitationVersionConflict)
}
if err != nil {
return fmt.Errorf("%s - advance draft: %w", location, mapInvitationError(err))
}
if termsChanged {
if err := repository.insertTermsVersion(ctx, location, stored, stored.TermsVersion, stored.UpdatedAt); err != nil {
return err
}
}
return repository.insertEvent(ctx, location, event)
}
func (repository invitationRepository) NeedVersionExists(
ctx context.Context,
organizationID, needID uuid.UUID,
requirementsVersion int64,
) (bool, error) {
const location = "invitationRepository.NeedVersionExists"
if organizationID == uuid.Nil || needID == uuid.Nil || requirementsVersion < 1 {
return false, fmt.Errorf("%s - scope and version must be set: %w", location, domain.ErrInvalidInvitation)
}
found, err := repository.queries.InvitationNeedVersionExists(ctx, sqlc.InvitationNeedVersionExistsParams{
OrganizationID: pgUUID(organizationID), NeedID: pgUUID(needID), RequirementsVersion: requirementsVersion,
})
if err != nil {
return false, fmt.Errorf("%s - look up need version: %w", location, mapInvitationError(err))
}
return found, nil
}
func (repository invitationRepository) SaveCreationResult(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
result domain.OrganizationInvitationView,
) error {
const location = "invitationRepository.SaveCreationResult"
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
}
encoded, err := encodeInvitationCreationResult(result)
if err != nil {
return fmt.Errorf("%s - encode response: %w", location, err)
}
if err := repository.queries.SaveInvitationCreationResult(ctx, sqlc.SaveInvitationCreationResultParams{
ScopeHash: scope[:], Snapshot: encoded,
}); err != nil {
return fmt.Errorf("%s - store response: %w", location, mapInvitationError(err))
}
return nil
}
func (repository invitationRepository) GetCreationResult(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
) (domain.OrganizationInvitationView, error) {
const location = "invitationRepository.GetCreationResult"
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
}
encoded, err := repository.queries.GetInvitationCreationResult(ctx, scope[:])
if errors.Is(err, pgx.ErrNoRows) {
return domain.OrganizationInvitationView{}, outbound.ErrInvitationCreationResultNotFound
}
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - read response: %w", location, mapInvitationError(err))
}
return decodeInvitationCreationResult(location, []byte(encoded))
}
// insertEventPrerequisites checks that the audit event describes the version
// that the caller is about to store.
func (repository invitationRepository) insertEventPrerequisites(
location string,
invitation domain.Invitation,
event domain.InvitationEvent,
version int64,
) error {
if event.ID == uuid.Nil || event.InvitationID != invitation.ID() || event.OrganizationID != invitation.OrganizationID() ||
event.Version != version || event.TermsVersion != invitation.TermsVersion() || event.ActorID == uuid.Nil ||
!validStoredInvitationTime(event.OccurredAt) {
return fmt.Errorf("%s - the audit event does not describe the stored version: %w", location, domain.ErrInvalidInvitation)
}
return nil
}
func (repository invitationRepository) insertTermsVersion(
ctx context.Context,
location string,
stored domain.StoredInvitation,
version int64,
at time.Time,
) error {
encoded, err := domain.EncodeInvitationTerms(stored.Terms)
if err != nil {
return fmt.Errorf("%s - encode terms: %w", location, err)
}
if err := repository.queries.InsertInvitationTermsVersion(ctx, sqlc.InsertInvitationTermsVersionParams{
InvitationID: pgUUID(stored.ID), OrganizationID: pgUUID(stored.OrganizationID), Version: version,
Terms: encoded, SalaryFrom: stored.Terms.Salary.SalaryFrom, SalaryTo: stored.Terms.Salary.SalaryTo,
SalaryCurrency: stored.Terms.Salary.Currency, SalaryPeriod: stored.Terms.Salary.Period,
SalaryTaxBasis: stored.Terms.Salary.TaxBasis, CreatedAt: pgTime(at),
}); err != nil {
return fmt.Errorf("%s - append terms version: %w", location, mapInvitationError(err))
}
return nil
}
func (repository invitationRepository) insertEvent(ctx context.Context, location string, event domain.InvitationEvent) error {
fields := make([]string, 0, len(event.ChangedFields))
for _, field := range event.ChangedFields {
fields = append(fields, string(field))
}
slices.Sort(fields)
if err := repository.queries.InsertInvitationEvent(ctx, sqlc.InsertInvitationEventParams{
ID: pgUUID(event.ID), InvitationID: pgUUID(event.InvitationID), OrganizationID: pgUUID(event.OrganizationID),
Version: event.Version, TermsVersion: event.TermsVersion, Kind: string(event.Kind), ActorID: pgUUID(event.ActorID),
ChangedFields: fields, OccurredAt: pgTime(event.OccurredAt),
}); err != nil {
return fmt.Errorf("%s - record audit event: %w", location, mapInvitationError(err))
}
return nil
}
func restoreInvitationRow(location string, row sqlc.ListInvitationsRow, organizationID uuid.UUID) (domain.Invitation, error) {
if !row.ID.Valid || !row.OrganizationID.Valid || !row.CandidateID.Valid || !row.CreatedBy.Valid || !row.PolicyVersionID.Valid ||
!row.CreatedAt.Valid || !row.UpdatedAt.Valid || uuid.UUID(row.OrganizationID.Bytes) != organizationID {
return domain.Invitation{}, fmt.Errorf("%s - invitation row has invalid scope or metadata: %w", location, domain.ErrInvalidInvitation)
}
terms, err := domain.DecodeInvitationTerms([]byte(row.Terms))
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - restore terms: %w", location, err)
}
stored := domain.StoredInvitation{
ID: uuid.UUID(row.ID.Bytes), OrganizationID: uuid.UUID(row.OrganizationID.Bytes),
CandidateID: uuid.UUID(row.CandidateID.Bytes), State: row.State, Version: row.Version,
TermsVersion: row.TermsVersion, Terms: terms, ResponsePeriodDays: int32(row.ResponsePeriodDays),
PolicyVersionID: domain.PolicyVersionID(row.PolicyVersionID.Bytes), SalaryRaiseUsed: row.SalaryRaiseUsed,
CreatedBy: uuid.UUID(row.CreatedBy.Bytes), CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time,
ResponseDeadlineAt: optionalTime(row.ResponseDeadlineAt), DeliveredAt: optionalTime(row.DeliveredAt),
ViewedAt: optionalTime(row.ViewedAt), RespondedAt: optionalTime(row.RespondedAt),
}
if row.ExpiryReason.Valid {
reason := row.ExpiryReason.String
stored.ExpiryReason = &reason
}
if row.NeedID.Valid != row.NeedRequirementsVersion.Valid {
return domain.Invitation{}, fmt.Errorf("%s - need link is incomplete: %w", location, domain.ErrInvalidInvitation)
}
if row.NeedID.Valid {
stored.Need = &domain.InvitationNeedRef{NeedID: uuid.UUID(row.NeedID.Bytes), RequirementsVersion: row.NeedRequirementsVersion.Int64}
}
invitation, err := domain.RestoreInvitation(stored)
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - restore invitation: %w", location, err)
}
return invitation, nil
}
func encodeInvitationCreationResult(result domain.OrganizationInvitationView) ([]byte, error) {
if err := validateInvitationCreationResult(result); err != nil {
return nil, err
}
encoded, err := json.Marshal(result)
if err != nil {
return nil, fmt.Errorf("postgres.encodeInvitationCreationResult - marshal: %w", err)
}
if len(encoded) > maxInvitationCreationResultBytes {
return nil, fmt.Errorf("postgres.encodeInvitationCreationResult - response exceeds %d bytes: %w", maxInvitationCreationResultBytes, domain.ErrInvalidInvitation)
}
return encoded, nil
}
func decodeInvitationCreationResult(location string, encoded []byte) (domain.OrganizationInvitationView, error) {
var result domain.OrganizationInvitationView
decoder := json.NewDecoder(bytes.NewReader(encoded))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&result); err != nil || decoder.More() {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - stored response has an unexpected shape: %w", location, domain.ErrInvalidInvitation)
}
if err := validateInvitationCreationResult(result); err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - validate stored response: %w", location, err)
}
return result, nil
}
func validateInvitationCreationResult(result domain.OrganizationInvitationView) error {
if result.ID == uuid.Nil || result.OrganizationID == uuid.Nil || !domain.IsCandidateViewPseudonym(result.CandidateHandle) {
return fmt.Errorf("postgres.validateInvitationCreationResult - identity is incomplete: %w", domain.ErrInvalidInvitation)
}
if err := result.Terms.Validate(); err != nil {
return fmt.Errorf("postgres.validateInvitationCreationResult - validate terms: %w", err)
}
return nil
}
func invitationNeedID(need *domain.InvitationNeedRef) pgtype.UUID {
if need == nil {
return pgtype.UUID{}
}
return pgUUID(need.NeedID)
}
func invitationNeedVersion(need *domain.InvitationNeedRef) pgtype.Int8 {
if need == nil {
return pgtype.Int8{}
}
return pgtype.Int8{Int64: need.RequirementsVersion, Valid: true}
}
func validStoredInvitationTime(value time.Time) bool {
return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999 && value.Unix() >= 0
}
func mapInvitationNoRows(err error) error {
if errors.Is(err, pgx.ErrNoRows) {
return outbound.ErrInvitationNotFound
}
return mapInvitationError(err)
}
func mapInvitationError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
if pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitations_organization_fkey" {
return fmt.Errorf("postgres.mapInvitationError - organization no longer exists: %w", outbound.ErrOrganizationNotFound)
}
if pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitation_creation_results_idempotency_fkey" {
return fmt.Errorf("postgres.mapInvitationError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
// invitationResponsePeriodParam converts the period to its smallint column.
// The domain allows only the periods of the product policy, so a value out of
// range is an invalid invitation, never a silently truncated one.
func invitationResponsePeriodParam(location string, days int32) (int16, error) {
if days < 1 || days > math.MaxInt16 {
return 0, fmt.Errorf("%s - response period is out of range: %w", location, domain.ErrInvalidInvitation)
}
return int16(days), nil
}
@@ -0,0 +1,557 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: invitations.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const advanceInvitationDraft = `-- name: AdvanceInvitationDraft :one
UPDATE invitations
SET
need_id = $1,
need_requirements_version = $2,
response_period_days = $3,
policy_version_id = $4,
terms_version = $5,
version = $6,
updated_at = $7
WHERE
organization_id = $8
AND id = $9
AND state = 'draft'
AND version = $10
AND $6::bigint = $10::bigint + 1
RETURNING id
`
type AdvanceInvitationDraftParams struct {
NeedID pgtype.UUID
NeedRequirementsVersion pgtype.Int8
ResponsePeriodDays int16
PolicyVersionID pgtype.UUID
TermsVersion int64
NextVersion int64
UpdatedAt pgtype.Timestamptz
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
ExpectedVersion int64
}
// The conditional update is the compare-and-swap of a draft: it applies only
// to a draft whose version is still the one the caller read, and advances the
// version by one. No row is returned when it lost a race or the invitation
// left the draft state.
func (q *Queries) AdvanceInvitationDraft(ctx context.Context, arg AdvanceInvitationDraftParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, advanceInvitationDraft,
arg.NeedID,
arg.NeedRequirementsVersion,
arg.ResponsePeriodDays,
arg.PolicyVersionID,
arg.TermsVersion,
arg.NextVersion,
arg.UpdatedAt,
arg.OrganizationID,
arg.InvitationID,
arg.ExpectedVersion,
)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const getInvitationCreationResult = `-- name: GetInvitationCreationResult :one
SELECT snapshot::text AS snapshot
FROM invitation_creation_results
WHERE scope_hash = $1
`
func (q *Queries) GetInvitationCreationResult(ctx context.Context, scopeHash []byte) (string, error) {
row := q.db.QueryRow(ctx, getInvitationCreationResult, scopeHash)
var snapshot string
err := row.Scan(&snapshot)
return snapshot, err
}
const insertInvitation = `-- name: InsertInvitation :exec
INSERT INTO invitations (
id,
organization_id,
candidate_id,
need_id,
need_requirements_version,
state,
version,
terms_version,
response_period_days,
policy_version_id,
created_by,
created_at,
updated_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12,
$13
)
`
type InsertInvitationParams struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
NeedID pgtype.UUID
NeedRequirementsVersion pgtype.Int8
State string
Version int64
TermsVersion int64
ResponsePeriodDays int16
PolicyVersionID pgtype.UUID
CreatedBy pgtype.UUID
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// The invitation row, its first terms version, and its first audit event are
// inserted in one caller-owned transaction. The deferred reference to the
// current terms version is checked when the transaction commits.
func (q *Queries) InsertInvitation(ctx context.Context, arg InsertInvitationParams) error {
_, err := q.db.Exec(ctx, insertInvitation,
arg.ID,
arg.OrganizationID,
arg.CandidateID,
arg.NeedID,
arg.NeedRequirementsVersion,
arg.State,
arg.Version,
arg.TermsVersion,
arg.ResponsePeriodDays,
arg.PolicyVersionID,
arg.CreatedBy,
arg.CreatedAt,
arg.UpdatedAt,
)
return err
}
const insertInvitationEvent = `-- name: InsertInvitationEvent :exec
INSERT INTO invitation_events (
id,
invitation_id,
organization_id,
version,
terms_version,
kind,
actor_id,
changed_fields,
occurred_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8::text [],
$9
)
`
type InsertInvitationEventParams struct {
ID pgtype.UUID
InvitationID pgtype.UUID
OrganizationID pgtype.UUID
Version int64
TermsVersion int64
Kind string
ActorID pgtype.UUID
ChangedFields []string
OccurredAt pgtype.Timestamptz
}
func (q *Queries) InsertInvitationEvent(ctx context.Context, arg InsertInvitationEventParams) error {
_, err := q.db.Exec(ctx, insertInvitationEvent,
arg.ID,
arg.InvitationID,
arg.OrganizationID,
arg.Version,
arg.TermsVersion,
arg.Kind,
arg.ActorID,
arg.ChangedFields,
arg.OccurredAt,
)
return err
}
const insertInvitationTermsVersion = `-- name: InsertInvitationTermsVersion :exec
INSERT INTO invitation_terms_versions (
invitation_id,
organization_id,
version,
terms,
salary_from,
salary_to,
salary_currency,
salary_period,
salary_tax_basis,
created_at
) VALUES (
$1,
$2,
$3,
$4::jsonb,
$5,
$6,
$7,
$8,
$9,
$10
)
`
type InsertInvitationTermsVersionParams struct {
InvitationID pgtype.UUID
OrganizationID pgtype.UUID
Version int64
Terms []byte
SalaryFrom int64
SalaryTo int64
SalaryCurrency string
SalaryPeriod string
SalaryTaxBasis string
CreatedAt pgtype.Timestamptz
}
func (q *Queries) InsertInvitationTermsVersion(ctx context.Context, arg InsertInvitationTermsVersionParams) error {
_, err := q.db.Exec(ctx, insertInvitationTermsVersion,
arg.InvitationID,
arg.OrganizationID,
arg.Version,
arg.Terms,
arg.SalaryFrom,
arg.SalaryTo,
arg.SalaryCurrency,
arg.SalaryPeriod,
arg.SalaryTaxBasis,
arg.CreatedAt,
)
return err
}
const invitationNeedVersionExists = `-- name: InvitationNeedVersionExists :one
SELECT EXISTS (
SELECT 1
FROM organization_need_versions
WHERE
organization_id = $1
AND need_id = $2
AND version = $3::bigint
AND snapshot ->> 'requirements_version' = $3::bigint::text
) AS found
`
type InvitationNeedVersionExistsParams struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
RequirementsVersion int64
}
// A requirements version that a need of the organization has had is the
// version number of a stored snapshot whose own requirements version is that
// number, so a later edit that only renamed the need is not accepted.
func (q *Queries) InvitationNeedVersionExists(ctx context.Context, arg InvitationNeedVersionExistsParams) (bool, error) {
row := q.db.QueryRow(ctx, invitationNeedVersionExists, arg.OrganizationID, arg.NeedID, arg.RequirementsVersion)
var found bool
err := row.Scan(&found)
return found, err
}
const listInvitations = `-- name: ListInvitations :many
SELECT
invitation.id,
invitation.organization_id,
invitation.candidate_id,
invitation.need_id,
invitation.need_requirements_version,
invitation.state,
invitation.expiry_reason,
invitation.version,
invitation.terms_version,
invitation.response_period_days,
invitation.policy_version_id,
invitation.response_deadline_at,
invitation.salary_raise_used,
invitation.created_by,
invitation.created_at,
invitation.updated_at,
invitation.delivered_at,
invitation.viewed_at,
invitation.responded_at,
terms.terms::text AS terms
FROM invitations AS invitation
INNER JOIN invitation_terms_versions AS terms
ON terms.invitation_id = invitation.id
AND terms.version = invitation.terms_version
WHERE
invitation.organization_id = $1
AND (
$2::timestamptz IS NULL
OR (invitation.created_at, invitation.id) < (
$2::timestamptz,
$3::uuid
)
)
ORDER BY invitation.created_at DESC, invitation.id DESC
LIMIT $4
`
type ListInvitationsParams struct {
OrganizationID pgtype.UUID
AfterCreatedAt pgtype.Timestamptz
AfterInvitationID pgtype.UUID
RowLimit int32
}
type ListInvitationsRow struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
NeedID pgtype.UUID
NeedRequirementsVersion pgtype.Int8
State string
ExpiryReason pgtype.Text
Version int64
TermsVersion int64
ResponsePeriodDays int16
PolicyVersionID pgtype.UUID
ResponseDeadlineAt pgtype.Timestamptz
SalaryRaiseUsed bool
CreatedBy pgtype.UUID
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
DeliveredAt pgtype.Timestamptz
ViewedAt pgtype.Timestamptz
RespondedAt pgtype.Timestamptz
Terms string
}
// One bounded newest-first page. Both the organization scope and the tuple
// cursor are applied before the limit.
func (q *Queries) ListInvitations(ctx context.Context, arg ListInvitationsParams) ([]ListInvitationsRow, error) {
rows, err := q.db.Query(ctx, listInvitations,
arg.OrganizationID,
arg.AfterCreatedAt,
arg.AfterInvitationID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListInvitationsRow
for rows.Next() {
var i ListInvitationsRow
if err := rows.Scan(
&i.ID,
&i.OrganizationID,
&i.CandidateID,
&i.NeedID,
&i.NeedRequirementsVersion,
&i.State,
&i.ExpiryReason,
&i.Version,
&i.TermsVersion,
&i.ResponsePeriodDays,
&i.PolicyVersionID,
&i.ResponseDeadlineAt,
&i.SalaryRaiseUsed,
&i.CreatedBy,
&i.CreatedAt,
&i.UpdatedAt,
&i.DeliveredAt,
&i.ViewedAt,
&i.RespondedAt,
&i.Terms,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockInvitation = `-- name: LockInvitation :one
SELECT id
FROM invitations
WHERE
organization_id = $1
AND id = $2
FOR UPDATE
`
type LockInvitationParams struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
}
// Takes the row lock of one invitation. It is a statement of its own, ahead of
// ReadInvitation, because a locking read that joins the terms table is
// re-checked against the new row version after a wait and then pairs the
// updated terms_version with the terms row it fetched before the wait, which
// finds nothing. Once the lock is held, the following read sees the committed
// state and no writer can change it.
func (q *Queries) LockInvitation(ctx context.Context, arg LockInvitationParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockInvitation, arg.OrganizationID, arg.InvitationID)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const readInvitation = `-- name: ReadInvitation :one
SELECT
invitation.id,
invitation.organization_id,
invitation.candidate_id,
invitation.need_id,
invitation.need_requirements_version,
invitation.state,
invitation.expiry_reason,
invitation.version,
invitation.terms_version,
invitation.response_period_days,
invitation.policy_version_id,
invitation.response_deadline_at,
invitation.salary_raise_used,
invitation.created_by,
invitation.created_at,
invitation.updated_at,
invitation.delivered_at,
invitation.viewed_at,
invitation.responded_at,
terms.terms::text AS terms
FROM invitations AS invitation
INNER JOIN invitation_terms_versions AS terms
ON terms.invitation_id = invitation.id
AND terms.version = invitation.terms_version
WHERE
invitation.organization_id = $1
AND invitation.id = $2
`
type ReadInvitationParams struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
}
type ReadInvitationRow struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
NeedID pgtype.UUID
NeedRequirementsVersion pgtype.Int8
State string
ExpiryReason pgtype.Text
Version int64
TermsVersion int64
ResponsePeriodDays int16
PolicyVersionID pgtype.UUID
ResponseDeadlineAt pgtype.Timestamptz
SalaryRaiseUsed bool
CreatedBy pgtype.UUID
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
DeliveredAt pgtype.Timestamptz
ViewedAt pgtype.Timestamptz
RespondedAt pgtype.Timestamptz
Terms string
}
// Read one current invitation with its terms snapshot. Both the organization
// and the invitation scope the row, so another organization's identifier
// finds nothing.
func (q *Queries) ReadInvitation(ctx context.Context, arg ReadInvitationParams) (ReadInvitationRow, error) {
row := q.db.QueryRow(ctx, readInvitation, arg.OrganizationID, arg.InvitationID)
var i ReadInvitationRow
err := row.Scan(
&i.ID,
&i.OrganizationID,
&i.CandidateID,
&i.NeedID,
&i.NeedRequirementsVersion,
&i.State,
&i.ExpiryReason,
&i.Version,
&i.TermsVersion,
&i.ResponsePeriodDays,
&i.PolicyVersionID,
&i.ResponseDeadlineAt,
&i.SalaryRaiseUsed,
&i.CreatedBy,
&i.CreatedAt,
&i.UpdatedAt,
&i.DeliveredAt,
&i.ViewedAt,
&i.RespondedAt,
&i.Terms,
)
return i, err
}
const readInvitationTermsVersion = `-- name: ReadInvitationTermsVersion :one
SELECT terms::text AS terms
FROM invitation_terms_versions
WHERE
organization_id = $1
AND invitation_id = $2
AND version = $3
`
type ReadInvitationTermsVersionParams struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
Version int64
}
// Read one historical terms version of one invitation of one organization.
func (q *Queries) ReadInvitationTermsVersion(ctx context.Context, arg ReadInvitationTermsVersionParams) (string, error) {
row := q.db.QueryRow(ctx, readInvitationTermsVersion, arg.OrganizationID, arg.InvitationID, arg.Version)
var terms string
err := row.Scan(&terms)
return terms, err
}
const saveInvitationCreationResult = `-- name: SaveInvitationCreationResult :exec
INSERT INTO invitation_creation_results (scope_hash, snapshot)
VALUES ($1, $2::jsonb)
ON CONFLICT (scope_hash) DO UPDATE
SET snapshot = excluded.snapshot
`
type SaveInvitationCreationResultParams struct {
ScopeHash []byte
Snapshot []byte
}
func (q *Queries) SaveInvitationCreationResult(ctx context.Context, arg SaveInvitationCreationResultParams) error {
_, err := q.db.Exec(ctx, saveInvitationCreationResult, arg.ScopeHash, arg.Snapshot)
return err
}
@@ -570,6 +570,58 @@ type IdempotencyRecord struct {
ExpiresAt pgtype.Timestamptz
}
type Invitation struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
NeedID pgtype.UUID
NeedRequirementsVersion pgtype.Int8
State string
ExpiryReason pgtype.Text
Version int64
TermsVersion int64
ResponsePeriodDays int16
PolicyVersionID pgtype.UUID
ResponseDeadlineAt pgtype.Timestamptz
SalaryRaiseUsed bool
CreatedBy pgtype.UUID
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
DeliveredAt pgtype.Timestamptz
ViewedAt pgtype.Timestamptz
RespondedAt pgtype.Timestamptz
}
type InvitationCreationResult struct {
ScopeHash []byte
Snapshot []byte
}
type InvitationEvent struct {
ID pgtype.UUID
InvitationID pgtype.UUID
OrganizationID pgtype.UUID
Version int64
TermsVersion int64
Kind string
ActorID pgtype.UUID
ChangedFields []string
OccurredAt pgtype.Timestamptz
}
type InvitationTermsVersion struct {
InvitationID pgtype.UUID
OrganizationID pgtype.UUID
Version int64
Terms []byte
SalaryFrom int64
SalaryTo int64
SalaryCurrency string
SalaryPeriod string
SalaryTaxBasis string
CreatedAt pgtype.Timestamptz
}
type MailQuotaReservation struct {
ID pgtype.UUID
DeliveryID pgtype.UUID
@@ -30,6 +30,11 @@ type Querier interface {
// Advances an existing questionnaire only at the version read by the caller.
// The row lock serializes saves for one user; a stale writer returns no row.
AdvanceCandidateQuestionnaireVersion(ctx context.Context, arg AdvanceCandidateQuestionnaireVersionParams) (CandidateQuestionnaire, error)
// The conditional update is the compare-and-swap of a draft: it applies only
// to a draft whose version is still the one the caller read, and advances the
// version by one. No row is returned when it lost a race or the invitation
// left the draft state.
AdvanceInvitationDraft(ctx context.Context, arg AdvanceInvitationDraftParams) (pgtype.UUID, error)
// The conditional parent update is the compare-and-swap. Appending the
// snapshot is part of the same SQL statement, so a failed insert leaves the
// parent pointer unchanged even before the surrounding transaction rolls
@@ -291,6 +296,7 @@ type Querier interface {
GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error)
// Explains why ConsumeEmailToken matched no row.
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
GetInvitationCreationResult(ctx context.Context, scopeHash []byte) (string, error)
// The caller holds the attempt row lock, so the last mark is stable.
GetLastAssessmentOriginMark(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptOriginMark, error)
GetLatestAssessmentFamily(ctx context.Context, familyKey string) (AssessmentFamily, error)
@@ -461,6 +467,12 @@ type Querier interface {
// for it.
InsertDelivery(ctx context.Context, arg InsertDeliveryParams) (int64, error)
InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error
// The invitation row, its first terms version, and its first audit event are
// inserted in one caller-owned transaction. The deferred reference to the
// current terms version is checked when the transaction commits.
InsertInvitation(ctx context.Context, arg InsertInvitationParams) error
InsertInvitationEvent(ctx context.Context, arg InsertInvitationEventParams) error
InsertInvitationTermsVersion(ctx context.Context, arg InsertInvitationTermsVersionParams) error
InsertMailQuotaReservation(ctx context.Context, arg InsertMailQuotaReservationParams) error
InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error
InsertMembership(ctx context.Context, arg InsertMembershipParams) error
@@ -518,6 +530,10 @@ type Querier interface {
InsertSyntheticCategoryReview(ctx context.Context, arg InsertSyntheticCategoryReviewParams) (int64, error)
InsertUser(ctx context.Context, arg InsertUserParams) error
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
// A requirements version that a need of the organization has had is the
// version number of a stored snapshot whose own requirements version is that
// number, so a later edit that only renamed the need is not accepted.
InvitationNeedVersionExists(ctx context.Context, arg InvitationNeedVersionExistsParams) (bool, error)
// Read the latest serialized event so a temporarily regressing application
// clock cannot make the next request fall before an event already counted.
LatestSupportCaseRequestEvent(ctx context.Context, ownerID pgtype.UUID) (pgtype.Timestamptz, error)
@@ -607,6 +623,9 @@ type Querier interface {
// fingerprint; stale bindings are omitted fail-closed.
ListCurrentSpecializationAvailability(ctx context.Context) ([]ListCurrentSpecializationAvailabilityRow, error)
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
// One bounded newest-first page. Both the organization scope and the tuple
// cursor are applied before the limit.
ListInvitations(ctx context.Context, arg ListInvitationsParams) ([]ListInvitationsRow, error)
// List only the authenticated recipient's rows, optionally narrowed to one
// organization context. The caller resolves current source visibility before
// returning content.
@@ -730,6 +749,13 @@ type Querier interface {
// Keeps the current C3 grant stable through a real assessment transaction.
// Revocation updates this row and therefore waits until the caller commits.
LockCurrentConsentForUse(ctx context.Context, subjectID pgtype.UUID) (LockCurrentConsentForUseRow, error)
// Takes the row lock of one invitation. It is a statement of its own, ahead of
// ReadInvitation, because a locking read that joins the terms table is
// re-checked against the new row version after a wait and then pairs the
// updated terms_version with the terms row it fetched before the wait, which
// finds nothing. Once the lock is held, the following read sees the committed
// state and no writer can change it.
LockInvitation(ctx context.Context, arg LockInvitationParams) (pgtype.UUID, error)
// Locks the listed window rows until the transaction ends, in
// (period_kind, period_start) order, the same order for every caller, and
// returns their usage. Under READ COMMITTED a waiting caller reads the usage
@@ -843,6 +869,12 @@ type Querier interface {
ReadCandidateViewSourceForPreview(ctx context.Context, candidateID pgtype.UUID) ([]ReadCandidateViewSourceForPreviewRow, error)
// Read one current version with its organization-scoped parent metadata.
ReadCurrentOrganizationNeed(ctx context.Context, arg ReadCurrentOrganizationNeedParams) (ReadCurrentOrganizationNeedRow, error)
// Read one current invitation with its terms snapshot. Both the organization
// and the invitation scope the row, so another organization's identifier
// finds nothing.
ReadInvitation(ctx context.Context, arg ReadInvitationParams) (ReadInvitationRow, error)
// Read one historical terms version of one invitation of one organization.
ReadInvitationTermsVersion(ctx context.Context, arg ReadInvitationTermsVersionParams) (string, error)
// Read one historical version without exposing another organization's record.
ReadOrganizationNeedVersion(ctx context.Context, arg ReadOrganizationNeedVersionParams) (string, error)
// Reads a full owner-scoped record. Object values are identifiers only.
@@ -937,6 +969,7 @@ type Querier interface {
// compares it with the policy captured in the assigned result.
SaveCandidateAssessmentCategory(ctx context.Context, arg SaveCandidateAssessmentCategoryParams) (int64, error)
SaveCompanyCardViewQuotaUsage(ctx context.Context, arg SaveCompanyCardViewQuotaUsageParams) error
SaveInvitationCreationResult(ctx context.Context, arg SaveInvitationCreationResultParams) error
// Stores the immutable domain snapshot of a successful create command. The
// generic idempotency row and this result are committed with the organization
// and owner membership. A reused expired scope replaces the snapshot in the
+2
View File
@@ -41,6 +41,7 @@ func newAPIHandler(
catalogHandler *v1.CatalogHandler,
organizationHandler *v1.OrganizationHandler,
needHandler *v1.NeedHandler,
invitationHandler *v1.InvitationHandler,
supportHandler *v1.SupportHandler,
assessmentHandler *v1.AssessmentHandler,
assessmentSignalHandler *v1.AssessmentSignalHandler,
@@ -57,6 +58,7 @@ func newAPIHandler(
v1.WithCatalog(catalogHandler),
v1.WithOrganization(organizationHandler),
v1.WithNeed(needHandler),
v1.WithInvitation(invitationHandler),
v1.WithSupport(supportHandler),
v1.WithAssessment(assessmentHandler),
v1.WithAssessmentSignals(assessmentSignalHandler),
+56
View File
@@ -0,0 +1,56 @@
package bootstrap
import (
"context"
"fmt"
"log/slog"
"time"
"lincodex/backend/config"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/invitation"
)
const invitationPoolMaxConns = 4
// newInvitationHandler builds the invitation draft operations. They resolve a
// card handle through the same visibility service as the card read and the
// search, so the pseudonym key and the cohort rules are the ones of the cards.
func newInvitationHandler(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
keyring *identity.Keyring,
) (*v1.InvitationHandler, func(), error) {
if settings.DatabaseURL == "" {
logger.Warn("invitation operations are not served because DATABASE_URL is not set")
return nil, func() {}, nil
}
if keyring == nil {
return nil, nil, fmt.Errorf("bootstrap.newInvitationHandler - identity keyring must be set")
}
key, err := keyring.CandidateViewPseudonymKey()
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newInvitationHandler - derive projection key: %w", err)
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, invitationPoolMaxConns)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newInvitationHandler - create pool: %w", err)
}
transactor := postgres.NewTransactor(pool)
views, err := newCandidateViewService(pool, transactor, key)
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newInvitationHandler - create view service: %w", err)
}
service, err := invitation.NewService(invitation.Dependencies{
Transactor: transactor, Keyring: keyring, PseudonymKey: key, Candidates: views.ResolveCandidateHandle, Clock: time.Now,
})
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newInvitationHandler - create service: %w", err)
}
return v1.NewInvitationHandler(service), pool.Close, nil
}
+1
View File
@@ -53,6 +53,7 @@ func initialize(
newCatalogHandler,
newOrganizationHandler,
newNeedHandler,
newInvitationHandler,
newSupportHandler,
newAssessmentHandler,
newAssessmentSignalHandler,
+81 -53
View File
@@ -122,7 +122,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
supportHandler, cleanup11, err := newSupportHandler(ctx, config2, logger, keyring)
invitationHandler, cleanup11, err := newInvitationHandler(ctx, config2, logger, keyring)
if err != nil {
cleanup10()
cleanup9()
@@ -136,7 +136,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
assessmentHandler, cleanup12, err := newAssessmentHandler(ctx, config2, logger, keyring)
supportHandler, cleanup12, err := newSupportHandler(ctx, config2, logger, keyring)
if err != nil {
cleanup11()
cleanup10()
@@ -151,7 +151,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
assessmentSignalHandler, cleanup13, err := newAssessmentSignalHandler(ctx, config2, logger, keyring)
assessmentHandler, cleanup13, err := newAssessmentHandler(ctx, config2, logger, keyring)
if err != nil {
cleanup12()
cleanup11()
@@ -167,7 +167,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
privacyHandler, cleanup14, err := newPrivacyHandler(ctx, config2, logger, keyring)
assessmentSignalHandler, cleanup14, err := newAssessmentSignalHandler(ctx, config2, logger, keyring)
if err != nil {
cleanup13()
cleanup12()
@@ -184,7 +184,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
evidenceHandler, cleanup15, err := newEvidenceHandler(ctx, config2, logger, keyring)
privacyHandler, cleanup15, err := newPrivacyHandler(ctx, config2, logger, keyring)
if err != nil {
cleanup14()
cleanup13()
@@ -202,7 +202,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
notificationHandler, cleanup16, err := newNotificationHandler(ctx, config2, logger)
evidenceHandler, cleanup16, err := newEvidenceHandler(ctx, config2, logger, keyring)
if err != nil {
cleanup15()
cleanup14()
@@ -221,7 +221,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
matchHandler, cleanup17, err := newMatchHandler(ctx, config2, logger, keyring)
notificationHandler, cleanup17, err := newNotificationHandler(ctx, config2, logger)
if err != nil {
cleanup16()
cleanup15()
@@ -241,52 +241,31 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, supportHandler, assessmentHandler, assessmentSignalHandler, privacyHandler, evidenceHandler, notificationHandler, matchHandler)
matchHandler, cleanup18, err := newMatchHandler(ctx, config2, logger, keyring)
if err != nil {
cleanup17()
cleanup16()
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, invitationHandler, supportHandler, assessmentHandler, assessmentSignalHandler, privacyHandler, evidenceHandler, notificationHandler, matchHandler)
sessionSecurity := newSessionSecurity(identityHandler)
v := newTrustedProxies(config2)
httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler)
if err != nil {
cleanup17()
cleanup16()
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
relay, cleanup18, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup17()
cleanup16()
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup19, err := newEventConsumers(ctx, config2, logger, metrics)
if err != nil {
cleanup18()
cleanup17()
@@ -308,7 +287,29 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
worker, cleanup20, err := newJobWorker(ctx, config2, logger, metrics)
relay, cleanup19, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup18()
cleanup17()
cleanup16()
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup20, err := newEventConsumers(ctx, config2, logger, metrics)
if err != nil {
cleanup19()
cleanup18()
@@ -331,7 +332,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
mailsenderWorker, cleanup21, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
worker, cleanup21, err := newJobWorker(ctx, config2, logger, metrics)
if err != nil {
cleanup20()
cleanup19()
@@ -355,7 +356,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup22, err := newDeliveryMetrics(ctx, config2, logger, metrics)
mailsenderWorker, cleanup22, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
if err != nil {
cleanup21()
cleanup20()
@@ -380,8 +381,35 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup23, err := newDeliveryMetrics(ctx, config2, logger, metrics)
if err != nil {
cleanup22()
cleanup21()
cleanup20()
cleanup19()
cleanup18()
cleanup17()
cleanup16()
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler)
return application, func() {
cleanup23()
cleanup22()
cleanup21()
cleanup20()
+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)
}
}
}
@@ -0,0 +1,104 @@
package outbound
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
// ErrInvitationNotFound reports that the invitation does not exist in the
// organization. An invitation of another organization is reported the same
// way, so an identifier reveals nothing.
ErrInvitationNotFound = errors.New("organization invitation not found")
// ErrInvitationVersionConflict reports that the draft is no longer at the
// version the caller read, or is no longer a draft. The surrounding
// transaction stays usable and the caller decides which conflict applies.
ErrInvitationVersionConflict = errors.New("organization invitation changed concurrently")
// ErrInvitationCreationResultNotFound reports a missing original response
// for a live idempotency record.
ErrInvitationCreationResultNotFound = errors.New("organization invitation creation result not found")
)
// MaxInvitationPageSize is the largest organization-scoped page in the
// contract.
const MaxInvitationPageSize = 100
// InvitationRepositories exposes the invitation storage bound to one
// UnitOfWork transaction.
type InvitationRepositories interface {
Invitations() InvitationRepository
InvitationCreationResults() InvitationCreationResultRepository
}
// InvitationRepository stores invitations, their immutable terms versions, and
// their audit events. Every read scopes by the organization and the
// invitation, so a foreign identifier finds nothing.
type InvitationRepository interface {
// Create inserts version 1 of a draft, its first terms version, and its
// first audit event in the surrounding transaction.
Create(ctx context.Context, invitation domain.Invitation, event domain.InvitationEvent) error
// Get returns the current invitation or ErrInvitationNotFound.
Get(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.Invitation, error)
// GetForUpdate returns the current invitation and holds its row lock until
// the surrounding transaction ends.
GetForUpdate(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.Invitation, error)
// GetTermsVersion returns one immutable historical terms version or
// ErrInvitationNotFound.
GetTermsVersion(ctx context.Context, organizationID, invitationID uuid.UUID, version int64) (domain.InvitationTerms, error)
// List returns one newest-first page of the organization's invitations.
List(ctx context.Context, query InvitationListQuery) (InvitationPage, error)
// SaveDraft appends the next version of a draft in the surrounding
// transaction: the invitation row moves from expectedVersion to the version
// of next, a changed terms version is appended as a new immutable snapshot,
// and the audit event is recorded. It returns ErrInvitationVersionConflict
// when the stored row is not a draft at expectedVersion.
SaveDraft(ctx context.Context, expectedVersion int64, next domain.Invitation, termsChanged bool, event domain.InvitationEvent) error
// NeedVersionExists reports whether the need of the organization has had
// the requirements version.
NeedVersionExists(ctx context.Context, organizationID, needID uuid.UUID, requirementsVersion int64) (bool, error)
}
// InvitationCreationResultRepository stores the original response of a
// successful idempotent create. The scope references the generic idempotency
// record, so the response is removed when that record is purged.
type InvitationCreationResultRepository interface {
SaveCreationResult(ctx context.Context, scope [IdempotencyDigestSize]byte, result domain.OrganizationInvitationView) error
GetCreationResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (domain.OrganizationInvitationView, error)
}
// InvitationListQuery selects one page within a single organization.
type InvitationListQuery struct {
OrganizationID uuid.UUID
After *InvitationListPosition
Limit int32
}
// InvitationListPosition is the stable newest-first ordering key.
type InvitationListPosition struct {
CreatedAt time.Time
InvitationID uuid.UUID
}
// InvitationPage contains one organization-scoped page of invitations.
type InvitationPage struct {
Items []domain.Invitation
HasMore bool
}
// InvitationCreationPosition returns the pagination key of one invitation.
func InvitationCreationPosition(invitation domain.Invitation) InvitationListPosition {
return InvitationListPosition{CreatedAt: invitation.CreatedAt(), InvitationID: invitation.ID()}
}
@@ -68,6 +68,7 @@ type UnitOfWork interface {
ConsentRevocationEffects() ConsentRevocationEffects
OrganizationRepositories
NeedRepositories
InvitationRepositories
CompanyQuotas() CompanyQuotaRepository
AssessmentBankRepositories
AssessmentAttemptRepositories
@@ -314,6 +314,54 @@ func (service *Service) AuthorizeCategoriesSection(
return candidateID, slices.Clone(view.Categories), nil
}
// ResolveCandidateHandle turns the handle of a card of this organization into
// the candidate it stands for, inside the caller's transaction. It applies the
// checks of a card read under the same locks: the active membership of the
// actor, the effective C2 publication, the hiding of this organization, and
// the minimum cohort, so a handle of another organization, an unknown handle,
// a candidate who revoked the publication or hid the profile from the
// organization, and a card that the cohort rules suppress all answer
// ErrCandidateCardNotFound. The caller cannot tell the cases apart.
//
// It consumes no card-view quota and writes no access history: it returns an
// identifier for the server's own use and shows no card content, and the
// search or the card read that produced the handle was charged when it
// revealed the candidate. The identifier must never leave the server.
//
// The caller's transaction must not hold a share lock of the organization yet,
// so that the exclusive organization lock of the quota writers is taken first.
func (service *Service) ResolveCandidateHandle(
ctx context.Context,
unit outbound.UnitOfWork,
actorID, organizationID uuid.UUID,
handle string,
) (uuid.UUID, error) {
const location = "candidateview.Service.ResolveCandidateHandle"
if actorID == uuid.Nil || organizationID == uuid.Nil {
return uuid.Nil, ErrForbidden
}
if !domain.IsCandidateViewPseudonym(handle) {
return uuid.Nil, ErrInvalidCandidateHandle
}
if err := lockOrganizationFirst(ctx, unit, organizationID); err != nil {
return uuid.Nil, err
}
_, _, sources, err := loadCurrentVisibleCohort(ctx, unit, actorID, organizationID, location)
if err != nil {
return uuid.Nil, err
}
candidateID, err := candidateIDForHandle(service, organizationID, sources, handle, location)
if err != nil {
return uuid.Nil, err
}
// A card that the cohort rules suppress is not offered by a search, so its
// handle is not accepted either.
if _, err := projectedViewForHandle(service, organizationID, sources, handle, location); err != nil {
return uuid.Nil, err
}
return candidateID, nil
}
func (service *Service) currentOrganizationCard(
ctx context.Context,
unit outbound.UnitOfWork,
@@ -0,0 +1,467 @@
package invitation
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateview"
)
const (
createLocation = "invitation.Service.Create"
updateLocation = "invitation.Service.Update"
getLocation = "invitation.Service.Get"
listLocation = "invitation.Service.List"
)
// CreateCommand binds the authenticated actor and the path organization to
// one validated create request. The candidate is named only by the handle.
type CreateCommand struct {
ActorID uuid.UUID
OrganizationID uuid.UUID
IdempotencyKey string
CanonicalBody []byte
CandidateHandle string
Need *domain.InvitationNeedRef
ResponsePeriodDays *int32
Terms domain.InvitationTerms
}
type createRequest struct {
fingerprint [outbound.IdempotencyDigestSize]byte
scope [outbound.IdempotencyDigestSize]byte
record outbound.IdempotencyRecord
now time.Time
}
// Create stores a new draft addressed to one candidate of the organization's
// visible cards, or replays the original response of the same request within
// the idempotency window. Nothing is stored when any rule fails.
func (service *Service) Create(ctx context.Context, command CreateCommand) (domain.OrganizationInvitationView, error) {
request, err := service.prepareCreate(command)
if err != nil {
return domain.OrganizationInvitationView{}, err
}
var result domain.OrganizationInvitationView
// The visible cohort can change while it is locked. The whole command is
// then repeated, a bounded number of times, and the writes of a failed
// attempt roll back with it.
for range maxCreateAttempts {
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
result, err = service.createInTransaction(ctx, unit, command, request)
return err
})
if !errors.Is(err, candidateview.ErrConcurrentVisibilityChange) {
break
}
}
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - run transaction: %w", createLocation, err)
}
return result, nil
}
func (service *Service) prepareCreate(command CreateCommand) (createRequest, error) {
const location = "invitation.Service.prepareCreate"
switch {
case command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil:
return createRequest{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize:
return createRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey)
case len(command.CanonicalBody) == 0 || len(command.CanonicalBody) > maxCanonicalBodySize:
return createRequest{}, fmt.Errorf("%s - canonical request body is outside its bound: %w", location, ErrInvalidRequest)
}
now, err := service.now(location)
if err != nil {
return createRequest{}, err
}
expiresAt := now.Add(outbound.IdempotencyRetention)
principal := command.ActorID.String() + ":" + command.OrganizationID.String()
fingerprint := service.keyring.Fingerprint(command.CanonicalBody)
scope := service.keyring.IdempotencyScope(createOperation, command.IdempotencyKey, principal)
return createRequest{
fingerprint: fingerprint, scope: scope, now: now,
record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: expiresAt},
}, nil
}
func (service *Service) createInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
command CreateCommand,
request createRequest,
) (domain.OrganizationInvitationView, error) {
if err := lockOrganizationFirst(ctx, unit, command.OrganizationID, createLocation); err != nil {
return domain.OrganizationInvitationView{}, err
}
if err := authorizeOwner(ctx, unit, command.ActorID, command.OrganizationID, createLocation); err != nil {
return domain.OrganizationInvitationView{}, err
}
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - reserve idempotency record: %w", createLocation, err)
}
if !created {
return replayCreation(ctx, unit, request, command.OrganizationID, stored)
}
invitation, err := service.buildDraft(ctx, unit, command, request.now)
if err != nil {
return domain.OrganizationInvitationView{}, err
}
event, err := invitation.DraftEvent(command.ActorID, nil)
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - build audit event: %w", createLocation, err)
}
if err := unit.Invitations().Create(ctx, invitation, event); err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - store draft: %w", createLocation, err)
}
view, err := service.view(invitation)
if err != nil {
return domain.OrganizationInvitationView{}, err
}
if err := unit.InvitationCreationResults().SaveCreationResult(ctx, request.scope, view); err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - store original response: %w", createLocation, err)
}
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err)
}
return view, nil
}
// buildDraft applies the domain rules in the order of the contract: the
// candidate handle, the need link, then the terms. The handle is resolved
// through the same visibility barrier as a card read, so a draft cannot be
// addressed to a candidate that the organization may not see.
func (service *Service) buildDraft(
ctx context.Context,
unit outbound.UnitOfWork,
command CreateCommand,
now time.Time,
) (domain.Invitation, error) {
policy, policyVersionID, err := effectiveInvitationPolicy(ctx, unit, now, createLocation)
if err != nil {
return domain.Invitation{}, err
}
var requested *domain.CalendarDays
if command.ResponsePeriodDays != nil {
period := domain.CalendarDays(*command.ResponsePeriodDays)
requested = &period
}
period, err := policy.ResolveResponsePeriod(requested)
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - resolve response period: %w", createLocation, err)
}
candidateID, err := service.candidates(ctx, unit, command.ActorID, command.OrganizationID, command.CandidateHandle)
if err != nil {
if errors.Is(err, candidateview.ErrCandidateCardNotFound) || errors.Is(err, candidateview.ErrInvalidCandidateHandle) {
return domain.Invitation{}, fmt.Errorf("%s - resolve candidate handle: %w", createLocation,
&domain.InvitationFieldError{Pointer: "/candidate_handle", Reason: "must be a handle of a candidate this organization can see"})
}
return domain.Invitation{}, fmt.Errorf("%s - resolve candidate handle: %w", createLocation, err)
}
if err := checkNeedLink(ctx, unit, command.OrganizationID, command.Need); err != nil {
return domain.Invitation{}, fmt.Errorf("%s - %w", createLocation, err)
}
draftID, err := uuid.NewV7()
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - generate invitation ID: %w", createLocation, err)
}
invitation, err := domain.NewInvitationDraft(domain.NewInvitationDraftInput{
ID: draftID, OrganizationID: command.OrganizationID, CandidateID: candidateID, ActorID: command.ActorID,
PolicyVersionID: policyVersionID, At: now,
Content: domain.InvitationDraftContent{Need: command.Need, ResponsePeriod: period, Terms: command.Terms},
})
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - build draft: %w", createLocation, err)
}
return invitation, nil
}
// checkNeedLink requires that a linked need belongs to the organization and
// has had the stated requirements version. Both cases give one pointer, so the
// answer does not tell whether the need exists in another organization.
func checkNeedLink(ctx context.Context, unit outbound.UnitOfWork, organizationID uuid.UUID, need *domain.InvitationNeedRef) error {
if need == nil {
return nil
}
exists, err := unit.Invitations().NeedVersionExists(ctx, organizationID, need.NeedID, need.RequirementsVersion)
if err != nil {
return fmt.Errorf("check need link: %w", err)
}
if !exists {
return &domain.InvitationFieldError{Pointer: "/need", Reason: "must be a need of this organization with a requirements version it has had"}
}
return nil
}
func replayCreation(
ctx context.Context,
unit outbound.UnitOfWork,
request createRequest,
organizationID uuid.UUID,
stored outbound.IdempotencyRecord,
) (domain.OrganizationInvitationView, error) {
if stored.Fingerprint != request.fingerprint {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - compare request fingerprint: %w", createLocation, ErrIdempotencyKeyReused)
}
original, err := unit.InvitationCreationResults().GetCreationResult(ctx, request.scope)
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - read original response: %w", createLocation, err)
}
if original.OrganizationID != organizationID {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - validate original response: %w", createLocation, domain.ErrInvalidInvitation)
}
return original, nil
}
// Field distinguishes a property that the request left out from one it set,
// and from one it set to null.
type Field[T any] struct {
Set bool
Null bool
Value T
}
// UpdateCommand binds one versioned replacement to a trusted actor and path.
// A field that is not set stays unchanged; terms are replaced as a whole.
type UpdateCommand struct {
ActorID uuid.UUID
OrganizationID uuid.UUID
InvitationID uuid.UUID
ExpectedVersion int64
Need Field[domain.InvitationNeedRef]
ResponsePeriodDays *int32
Terms *domain.InvitationTerms
}
// Update replaces the fields the request sets, in the order of the contract:
// a request that changes nothing returns the current invitation, then the
// version is compared, then the state, then the domain rules. Only a draft
// changes. A change appends the next invitation version, and a change of the
// terms appends the next immutable terms version.
func (service *Service) Update(ctx context.Context, command UpdateCommand) (domain.OrganizationInvitationView, error) {
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", updateLocation, ErrForbidden)
}
if command.ExpectedVersion < 1 {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - %w", updateLocation,
&domain.InvitationFieldError{Pointer: "/expected_version", Reason: "must be positive"})
}
now, err := service.now(updateLocation)
if err != nil {
return domain.OrganizationInvitationView{}, err
}
var result domain.OrganizationInvitationView
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
result, err = service.updateInTransaction(ctx, unit, command, now)
return err
})
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - run transaction: %w", updateLocation, err)
}
return result, nil
}
func (service *Service) updateInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
command UpdateCommand,
now time.Time,
) (domain.OrganizationInvitationView, error) {
// Every invitation command takes the organization lock before the
// membership share lock and the invitation row lock, in the order of the
// create, the card read, and the search, so a later command that also
// charges the organization (sending, the salary limit) cannot deadlock
// against an update.
if err := lockOrganizationFirst(ctx, unit, command.OrganizationID, updateLocation); err != nil {
return domain.OrganizationInvitationView{}, err
}
if err := authorizeOwner(ctx, unit, command.ActorID, command.OrganizationID, updateLocation); err != nil {
return domain.OrganizationInvitationView{}, err
}
// The nil identifier cannot name an invitation. It answers like any
// unknown identifier, after the authorization above.
if command.InvitationID == uuid.Nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - nil invitation: %w", updateLocation, outbound.ErrInvitationNotFound)
}
current, err := unit.Invitations().GetForUpdate(ctx, command.OrganizationID, command.InvitationID)
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - lock invitation: %w", updateLocation, err)
}
before := current.DraftContent()
merged := mergeDraft(before, command)
changed := before.ChangedFields(merged)
if len(changed) == 0 {
return service.view(current)
}
if command.ExpectedVersion != current.Version() {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - compare expected version: %w", updateLocation, domain.ErrInvitationVersionConflict)
}
if current.State() != domain.InvitationDraft {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - require a draft: %w", updateLocation, domain.ErrInvitationNotDraft)
}
policyVersionID, err := service.checkRevision(ctx, unit, current, merged, changed, now)
if err != nil {
return domain.OrganizationInvitationView{}, err
}
// A clock that stepped back must not make the revision older than the
// draft it revises.
at := now
if at.Before(current.UpdatedAt()) {
at = current.UpdatedAt()
}
next, appliedFields, err := current.ReviseDraft(merged, policyVersionID, at)
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - revise draft: %w", updateLocation, err)
}
event, err := next.DraftEvent(command.ActorID, appliedFields)
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - build audit event: %w", updateLocation, err)
}
termsChanged := next.TermsVersion() != current.TermsVersion()
if err := unit.Invitations().SaveDraft(ctx, current.Version(), next, termsChanged, event); err != nil {
if errors.Is(err, outbound.ErrInvitationVersionConflict) {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - save draft: %w", updateLocation, domain.ErrInvitationVersionConflict)
}
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - save draft: %w", updateLocation, err)
}
return service.view(next)
}
// mergeDraft applies the fields the command sets over the current content.
func mergeDraft(current domain.InvitationDraftContent, command UpdateCommand) domain.InvitationDraftContent {
merged := current
if command.Need.Set {
merged.Need = nil
if !command.Need.Null {
need := command.Need.Value
merged.Need = &need
}
}
if command.ResponsePeriodDays != nil {
merged.ResponsePeriod = domain.CalendarDays(*command.ResponsePeriodDays)
}
if command.Terms != nil {
merged.Terms = *command.Terms
}
return merged
}
// checkRevision runs the rules that need storage or the policy and returns the
// policy version that governs the stored response period. The period is
// checked against the policy in force only when the request changes it.
func (service *Service) checkRevision(
ctx context.Context,
unit outbound.UnitOfWork,
current domain.Invitation,
merged domain.InvitationDraftContent,
changed []domain.InvitationChangedField,
now time.Time,
) (domain.PolicyVersionID, error) {
policyVersionID := current.PolicyVersionID()
for _, field := range changed {
switch field {
case domain.InvitationChangedResponsePeriod:
policy, versionID, err := effectiveInvitationPolicy(ctx, unit, now, updateLocation)
if err != nil {
return domain.PolicyVersionID{}, err
}
if _, err := policy.ResolveResponsePeriod(&merged.ResponsePeriod); err != nil {
return domain.PolicyVersionID{}, fmt.Errorf("%s - resolve response period: %w", updateLocation, err)
}
policyVersionID = versionID
case domain.InvitationChangedNeed:
if err := checkNeedLink(ctx, unit, current.OrganizationID(), merged.Need); err != nil {
return domain.PolicyVersionID{}, fmt.Errorf("%s - %w", updateLocation, err)
}
case domain.InvitationChangedTerms:
// The terms need no storage: the domain validates them when the
// draft is revised, after the need link, as on creation.
}
}
return policyVersionID, nil
}
// Get reads the current invitation for an active owner.
func (service *Service) Get(ctx context.Context, actorID, organizationID, invitationID uuid.UUID) (domain.OrganizationInvitationView, error) {
if actorID == uuid.Nil || organizationID == uuid.Nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", getLocation, ErrForbidden)
}
var result domain.OrganizationInvitationView
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := authorizeOwner(ctx, unit, actorID, organizationID, getLocation); err != nil {
return err
}
if invitationID == uuid.Nil {
return fmt.Errorf("%s - nil invitation: %w", getLocation, outbound.ErrInvitationNotFound)
}
current, err := unit.Invitations().Get(ctx, organizationID, invitationID)
if err != nil {
return fmt.Errorf("%s - read invitation: %w", getLocation, err)
}
result, err = service.view(current)
return err
})
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - run transaction: %w", getLocation, err)
}
return result, nil
}
// ListCommand selects an owner-scoped page of invitations.
type ListCommand struct {
ActorID uuid.UUID
OrganizationID uuid.UUID
After *outbound.InvitationListPosition
Limit int32
}
// Page is one page of invitations, newest first.
type Page struct {
Items []domain.OrganizationInvitationView
HasMore bool
}
// List reads one page of the organization's invitations of every state after
// checking the current account and owner membership in the same transaction.
func (service *Service) List(ctx context.Context, command ListCommand) (Page, error) {
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil {
return Page{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", listLocation, ErrForbidden)
}
if command.Limit < 1 || command.Limit > outbound.MaxInvitationPageSize {
return Page{}, fmt.Errorf("%s - page limit must be 1 to %d: %w", listLocation, outbound.MaxInvitationPageSize, ErrInvalidRequest)
}
var result Page
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := authorizeOwner(ctx, unit, command.ActorID, command.OrganizationID, listLocation); err != nil {
return err
}
page, err := unit.Invitations().List(ctx, outbound.InvitationListQuery{
OrganizationID: command.OrganizationID, After: command.After, Limit: command.Limit,
})
if err != nil {
return fmt.Errorf("%s - list invitations: %w", listLocation, err)
}
result = Page{Items: make([]domain.OrganizationInvitationView, 0, len(page.Items)), HasMore: page.HasMore}
for _, invitation := range page.Items {
item, err := service.view(invitation)
if err != nil {
return err
}
result.Items = append(result.Items, item)
}
return nil
})
if err != nil {
return Page{}, fmt.Errorf("%s - run transaction: %w", listLocation, err)
}
return result, nil
}
@@ -0,0 +1,191 @@
// Package invitation applies the owner-only rules of invitation drafts: the
// terms and their immutable versions, the link to a candidate card of the
// organization, and the idempotent creation. Sending, the candidate's side, and
// the contact grant belong to later operations that build on the same records.
package invitation
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var (
// ErrForbidden reports an account that may not work with the invitations
// of the organization: not an employer, or not its owner in the MVP.
ErrForbidden = errors.New("organization invitation operation forbidden")
// ErrEmailNotVerified reports an employer without a confirmed email.
ErrEmailNotVerified = errors.New("organization invitation requires a confirmed email")
// ErrIdempotencyKeyReused reports a key that was used with another request.
ErrIdempotencyKeyReused = errors.New("idempotency key reused with a different request")
// ErrInvalidIdempotencyKey reports a key outside 1 to 255 bytes.
ErrInvalidIdempotencyKey = errors.New("invalid idempotency key")
// ErrInvalidRequest reports a command that is incomplete before storage is
// read, such as a missing identifier or canonical body.
ErrInvalidRequest = errors.New("invalid organization invitation request")
// ErrPolicyUnavailable reports an effective product policy that cannot
// answer the invitation rules. It is a configuration error.
ErrPolicyUnavailable = errors.New("invitation policy is unavailable")
)
const (
createOperation = "organization_invitation.create"
maxIdempotencyKeySize = 255
maxCanonicalBodySize = 1 << 20
purgeExpiredBatch = 100
// maxCreateAttempts bounds the repeats of a create after the visible
// cohort changed while it was locked.
maxCreateAttempts = 3
)
// Keyring computes scoped idempotency digests. identity.Keyring implements
// this interface, so invitation commands use the existing server secret and
// store.
type Keyring interface {
IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte
Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte
}
// CandidateResolver turns a card handle of the organization into the candidate
// it stands for, inside the caller's transaction. It applies the same
// visibility barrier as the card read: the effective publication, the hiding
// of the organization, and the cohort rules. It answers
// candidateview.ErrCandidateCardNotFound for every handle the organization may
// not use. The identifier it returns never leaves the server.
type CandidateResolver func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID, handle string) (uuid.UUID, error)
// Dependencies configure one stateless invitation service.
type Dependencies struct {
Transactor outbound.Transactor
Keyring Keyring
// PseudonymKey derives the organization-scoped alias that responses show
// instead of the candidate. It is the key of the cards and the search, so
// a handle in an invitation is the handle of the card.
PseudonymKey domain.CandidateViewPseudonymKey
Candidates CandidateResolver
Clock func() time.Time
}
// Service applies organization-scoped invitation draft commands and reads.
type Service struct {
transactor outbound.Transactor
keyring Keyring
pseudonymKey domain.CandidateViewPseudonymKey
candidates CandidateResolver
clock func() time.Time
}
// NewService fails at startup when a required dependency is missing.
func NewService(deps Dependencies) (*Service, error) {
if deps.Transactor == nil || deps.Keyring == nil || deps.Candidates == nil || deps.Clock == nil {
return nil, errors.New("invitation.NewService - every dependency must be set")
}
if _, err := deps.PseudonymKey.ForOrganization(uuid.New(), uuid.New()); err != nil {
return nil, errors.New("invitation.NewService - the pseudonym key must be usable")
}
return &Service{
transactor: deps.Transactor, keyring: deps.Keyring, pseudonymKey: deps.PseudonymKey,
candidates: deps.Candidates, clock: deps.Clock,
}, nil
}
// now returns the application time at the precision the database stores.
func (service *Service) now(location string) (time.Time, error) {
now := service.clock().UTC().Truncate(time.Microsecond)
if now.IsZero() || now.Year() < 1 || now.Year() > 9999 {
return time.Time{}, fmt.Errorf("%s - application time must be representable: %w", location, ErrInvalidRequest)
}
return now, nil
}
// view is the invitation as its organization reads it. The salary indicator
// and the contact access are not derived from the candidate's minimum or from
// a grant yet: the indicator is not_available, the least revealing value, and
// no grant exists before an acceptance.
func (service *Service) view(invitation domain.Invitation) (domain.OrganizationInvitationView, error) {
handle, err := service.pseudonymKey.ForOrganization(invitation.OrganizationID(), invitation.CandidateID())
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("invitation.Service.view - derive candidate alias: %w", err)
}
return domain.OrganizationInvitationView{
InvitationSnapshot: invitation.Snapshot(),
CandidateHandle: handle,
SalaryFit: domain.InvitationSalaryNotAvailable,
ContactAccess: domain.InvitationContactAccessNone,
}, nil
}
// lockOrganizationFirst takes the exclusive organization lock of the company
// quota port, ahead of the share lock of the membership check and of the
// cohort locks, so two commands of one organization queue instead of
// deadlocking on a lock upgrade. An organization that does not exist answers
// like a missing membership.
func lockOrganizationFirst(ctx context.Context, unit outbound.UnitOfWork, organizationID uuid.UUID, location string) error {
if err := unit.CompanyQuotas().LockOrganization(ctx, organizationID); err != nil {
if errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) {
return fmt.Errorf("%s - lock organization: %w", location, outbound.ErrOrganizationNotFound)
}
return fmt.Errorf("%s - lock organization: %w", location, err)
}
return nil
}
// authorizeOwner repeats, inside the transaction, the checks of the HTTP
// boundary: an existing employer with a confirmed email whose membership in
// the organization is active and owner. The MVP milestone grants a membership
// by itself no right over invitations.
func authorizeOwner(
ctx context.Context,
unit outbound.UnitOfWork,
actorID, organizationID uuid.UUID,
location string,
) error {
if actorID == uuid.Nil || organizationID == uuid.Nil {
return fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
}
user, err := unit.Users().GetByID(ctx, actorID)
if err != nil {
if errors.Is(err, outbound.ErrUserNotFound) {
return fmt.Errorf("%s - require existing employer account: %w", location, ErrForbidden)
}
return fmt.Errorf("%s - read account: %w", location, err)
}
if user.Scenario != domain.ScenarioEmployer {
return fmt.Errorf("%s - require employer account: %w", location, ErrForbidden)
}
if !user.EmailVerified() {
return fmt.Errorf("%s - require verified email: %w", location, ErrEmailNotVerified)
}
membership, err := unit.Organizations().LockActiveMembership(ctx, organizationID, actorID)
if err != nil {
if errors.Is(err, outbound.ErrOrganizationNotFound) {
return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound)
}
return fmt.Errorf("%s - lock active membership: %w", location, err)
}
if membership.Role() != domain.OrganizationRoleOwner {
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
}
return nil
}
// effectiveInvitationPolicy reads the invitation section of the product
// policy in force at the time, with the version that governed the decision.
func effectiveInvitationPolicy(
ctx context.Context,
unit outbound.UnitOfWork,
at time.Time,
location string,
) (domain.InvitationPolicy, domain.PolicyVersionID, error) {
version, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, at)
if err != nil {
return domain.InvitationPolicy{}, domain.PolicyVersionID{}, fmt.Errorf("%s - read effective product policy: %w: %w", location, ErrPolicyUnavailable, err)
}
return version.Policy().Invitations, version.ID(), nil
}
@@ -0,0 +1,699 @@
package invitation
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateview"
)
type testKeyring struct{}
func (testKeyring) IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte {
return sha256.Sum256([]byte(operation + "\x00" + key + "\x00" + principal))
}
func (testKeyring) Fingerprint(body []byte) [outbound.IdempotencyDigestSize]byte {
return sha256.Sum256(body)
}
type termsKey struct {
invitationID uuid.UUID
version int64
}
type testState struct {
users map[uuid.UUID]domain.User
memberships map[[2]uuid.UUID]domain.Membership
invitations map[uuid.UUID]domain.Invitation
terms map[termsKey]domain.InvitationTerms
events []domain.InvitationEvent
idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord
results map[[outbound.IdempotencyDigestSize]byte]domain.OrganizationInvitationView
needVersions map[[3]string]bool
}
func newTestState() testState {
return testState{
users: map[uuid.UUID]domain.User{}, memberships: map[[2]uuid.UUID]domain.Membership{},
invitations: map[uuid.UUID]domain.Invitation{}, terms: map[termsKey]domain.InvitationTerms{},
idempotency: map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord{},
results: map[[outbound.IdempotencyDigestSize]byte]domain.OrganizationInvitationView{},
needVersions: map[[3]string]bool{},
}
}
func (state testState) clone() testState {
cloned := newTestState()
for id, user := range state.users {
cloned.users[id] = user
}
for key, membership := range state.memberships {
cloned.memberships[key] = membership
}
for id, invitation := range state.invitations {
cloned.invitations[id] = invitation
}
for key, terms := range state.terms {
cloned.terms[key] = terms.Clone()
}
cloned.events = slices.Clone(state.events)
for scope, record := range state.idempotency {
cloned.idempotency[scope] = record
}
for scope, result := range state.results {
cloned.results[scope] = result
}
for key, found := range state.needVersions {
cloned.needVersions[key] = found
}
return cloned
}
type testTransactor struct {
mu sync.Mutex
state testState
policy domain.PolicyVersion
failResultSave bool
}
func (transactor *testTransactor) WithinTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error {
transactor.mu.Lock()
defer transactor.mu.Unlock()
working := transactor.state.clone()
unit := &testUnit{state: &working, policy: transactor.policy, failResultSave: transactor.failResultSave}
if err := work(ctx, unit); err != nil {
return err
}
transactor.state = working
return nil
}
func (transactor *testTransactor) snapshot() testState {
transactor.mu.Lock()
defer transactor.mu.Unlock()
return transactor.state.clone()
}
type testUnit struct {
outbound.UnitOfWork
state *testState
policy domain.PolicyVersion
failResultSave bool
}
func (unit *testUnit) Users() outbound.UserRepository { return testUsers{state: unit.state} }
func (unit *testUnit) Organizations() outbound.OrganizationRepository {
return testOrganizations{state: unit.state}
}
func (unit *testUnit) IdempotencyRecords() outbound.IdempotencyRepository {
return testIdempotency{state: unit.state}
}
func (unit *testUnit) CompanyQuotas() outbound.CompanyQuotaRepository { return testQuotas{} }
func (unit *testUnit) Policies() outbound.PolicyRepository { return testPolicies{version: unit.policy} }
func (unit *testUnit) Invitations() outbound.InvitationRepository {
return testInvitations{state: unit.state}
}
func (unit *testUnit) InvitationCreationResults() outbound.InvitationCreationResultRepository {
return testInvitations{state: unit.state, failResultSave: unit.failResultSave}
}
type testUsers struct {
outbound.UserRepository
state *testState
}
func (repository testUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
user, ok := repository.state.users[id]
if !ok {
return domain.User{}, outbound.ErrUserNotFound
}
return user, nil
}
type testOrganizations struct {
outbound.OrganizationRepository
state *testState
}
func (repository testOrganizations) LockActiveMembership(_ context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) {
membership, ok := repository.state.memberships[[2]uuid.UUID{organizationID, userID}]
if !ok || !membership.GrantsAccess() {
return domain.Membership{}, outbound.ErrOrganizationNotFound
}
return membership, nil
}
type testQuotas struct {
outbound.CompanyQuotaRepository
}
func (testQuotas) LockOrganization(context.Context, uuid.UUID) error { return nil }
type testPolicies struct {
outbound.PolicyRepository
version domain.PolicyVersion
}
func (policies testPolicies) GetEffective(context.Context, domain.PolicyKey, time.Time) (domain.PolicyVersion, error) {
return policies.version, nil
}
type testIdempotency struct {
outbound.IdempotencyRepository
state *testState
}
func (repository testIdempotency) Reserve(_ context.Context, record outbound.IdempotencyRecord) (outbound.IdempotencyRecord, bool, error) {
if existing, ok := repository.state.idempotency[record.Scope]; ok && existing.ExpiresAt.After(record.CreatedAt) {
return existing, false, nil
}
repository.state.idempotency[record.Scope] = record
return record, true, nil
}
func (repository testIdempotency) PurgeExpired(_ context.Context, at time.Time, _ int32) (int64, error) {
var deleted int64
for scope, record := range repository.state.idempotency {
if !record.ExpiresAt.After(at) {
delete(repository.state.idempotency, scope)
delete(repository.state.results, scope)
deleted++
}
}
return deleted, nil
}
type testInvitations struct {
state *testState
failResultSave bool
}
func (repository testInvitations) Create(_ context.Context, invitation domain.Invitation, event domain.InvitationEvent) error {
repository.state.invitations[invitation.ID()] = invitation
repository.state.terms[termsKey{invitation.ID(), 1}] = invitation.Snapshot().Terms
repository.state.events = append(repository.state.events, event)
return nil
}
func (repository testInvitations) Get(_ context.Context, organizationID, invitationID uuid.UUID) (domain.Invitation, error) {
invitation, ok := repository.state.invitations[invitationID]
if !ok || invitation.OrganizationID() != organizationID {
return domain.Invitation{}, outbound.ErrInvitationNotFound
}
return invitation, nil
}
func (repository testInvitations) GetForUpdate(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.Invitation, error) {
return repository.Get(ctx, organizationID, invitationID)
}
func (repository testInvitations) List(_ context.Context, query outbound.InvitationListQuery) (outbound.InvitationPage, error) {
var items []domain.Invitation
for _, invitation := range repository.state.invitations {
if invitation.OrganizationID() == query.OrganizationID {
items = append(items, invitation)
}
}
slices.SortFunc(items, func(left, right domain.Invitation) int {
return strings.Compare(right.ID().String(), left.ID().String())
})
page := outbound.InvitationPage{HasMore: len(items) > int(query.Limit)}
if page.HasMore {
items = items[:query.Limit]
}
page.Items = items
return page, nil
}
func (repository testInvitations) SaveDraft(_ context.Context, expectedVersion int64, next domain.Invitation, termsChanged bool, event domain.InvitationEvent) error {
current, ok := repository.state.invitations[next.ID()]
if !ok || current.Version() != expectedVersion || current.State() != domain.InvitationDraft {
return outbound.ErrInvitationVersionConflict
}
repository.state.invitations[next.ID()] = next
if termsChanged {
repository.state.terms[termsKey{next.ID(), next.TermsVersion()}] = next.Snapshot().Terms
}
repository.state.events = append(repository.state.events, event)
return nil
}
func (repository testInvitations) NeedVersionExists(_ context.Context, organizationID, needID uuid.UUID, version int64) (bool, error) {
return repository.state.needVersions[[3]string{organizationID.String(), needID.String(), fmt.Sprint(version)}], nil
}
func (repository testInvitations) SaveCreationResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, result domain.OrganizationInvitationView) error {
if repository.failResultSave {
return errors.New("result store failed")
}
repository.state.results[scope] = result
return nil
}
func (repository testInvitations) GetCreationResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (domain.OrganizationInvitationView, error) {
result, ok := repository.state.results[scope]
if !ok {
return domain.OrganizationInvitationView{}, outbound.ErrInvitationCreationResultNotFound
}
return result, nil
}
type harness struct {
service *Service
transactor *testTransactor
key domain.CandidateViewPseudonymKey
actorID uuid.UUID
organizationID uuid.UUID
// visible maps a handle of the organization to its candidate.
visible map[string]uuid.UUID
setTime func(time.Time)
}
func newHarness(t *testing.T) *harness {
t.Helper()
now := time.Date(2026, time.October, 9, 10, 0, 0, 0, time.UTC)
current := now
actorID, organizationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7())
verifiedAt := now.Add(-time.Hour)
state := newTestState()
state.users[actorID] = domain.User{ID: actorID, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verifiedAt}
owner, err := domain.NewOwnerMembership(organizationID, actorID, now)
if err != nil {
t.Fatalf("NewOwnerMembership() error = %v", err)
}
state.memberships[[2]uuid.UUID{organizationID, actorID}] = owner
key, err := domain.NewCandidateViewPseudonymKey([]byte(strings.Repeat("invitation-test-key-", 3)))
if err != nil {
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
}
test := &harness{
transactor: &testTransactor{state: state, policy: testPolicyVersion(t, now)},
key: key, actorID: actorID, organizationID: organizationID, visible: map[string]uuid.UUID{},
setTime: func(value time.Time) { current = value },
}
test.service, err = NewService(Dependencies{
Transactor: test.transactor, Keyring: testKeyring{}, PseudonymKey: key, Clock: func() time.Time { return current },
Candidates: func(_ context.Context, _ outbound.UnitOfWork, _, organizationID uuid.UUID, handle string) (uuid.UUID, error) {
candidateID, ok := test.visible[handle]
if !ok || organizationID != test.organizationID {
return uuid.Nil, candidateview.ErrCandidateCardNotFound
}
return candidateID, nil
},
})
if err != nil {
t.Fatalf("NewService() error = %v", err)
}
return test
}
// showCandidate makes a new candidate visible to the organization and returns
// the handle of the card.
func (test *harness) showCandidate(t *testing.T) (string, uuid.UUID) {
t.Helper()
candidateID := uuid.Must(uuid.NewV7())
handle, err := test.key.ForOrganization(test.organizationID, candidateID)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
test.visible[handle] = candidateID
return handle, candidateID
}
func testPolicyVersion(t *testing.T, at time.Time) domain.PolicyVersion {
t.Helper()
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV1(),
})
if err != nil {
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
}
numbered, err := draft.WithVersion(1)
if err != nil {
t.Fatalf("WithVersion() error = %v", err)
}
hash := numbered.DocumentHash()
version, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{
ID: numbered.ID(), Key: string(numbered.Key()), Version: numbered.Version(), Kind: string(numbered.Kind()),
Author: string(numbered.Author()), EffectiveAt: at, CreatedAt: at, Document: numbered.Document(), DocumentHash: hash[:],
})
if err != nil {
t.Fatalf("RestorePolicyVersion() error = %v", err)
}
return version
}
func testTerms() domain.InvitationTerms {
none := domain.InvitationPackageItem{Status: domain.InvitationPackageNotProvided}
return domain.InvitationTerms{
RoleTitle: "Middle Go developer", Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle,
OfferType: domain.InvitationOfferFullTime, Tasks: []string{"Build the payout service"}, Team: "Six engineers",
TechStack: []string{"Go"}, WorkFormats: []domain.NeedWorkFormat{domain.NeedWorkFormatRemote},
CommunicationMethod: domain.InvitationCommunicationMethod{Channel: domain.InvitationChannelEmail},
Salary: domain.SalaryRange{SalaryFrom: 100_000, SalaryTo: 140_000, Currency: "RUB", Period: "month", TaxBasis: "net"},
Package: domain.InvitationPackage{Bonus: none, Equipment: none, Training: none, HealthInsurance: none},
}
}
func (test *harness) createCommand(handle, key string) CreateCommand {
return CreateCommand{
ActorID: test.actorID, OrganizationID: test.organizationID, IdempotencyKey: key,
CanonicalBody: []byte(fmt.Sprintf(`{"candidate_handle":%q,"key":%q}`, handle, key)),
CandidateHandle: handle, Terms: testTerms(),
}
}
func fieldPointer(t *testing.T, err error) string {
t.Helper()
field, ok := errors.AsType[*domain.InvitationFieldError](err)
if !ok {
t.Fatalf("error = %v, want a field error", err)
}
return field.Pointer
}
func TestCreateStoresADraftForAVisibleCandidateWithTheDefaultPeriod(t *testing.T) {
test := newHarness(t)
handle, candidateID := test.showCandidate(t)
view, err := test.service.Create(t.Context(), test.createCommand(handle, "key-1"))
if err != nil {
t.Fatalf("Create() error = %v", err)
}
if view.State != domain.InvitationDraft || view.Version != 1 || view.TermsVersion != 1 || view.ResponsePeriodDays != 7 ||
view.CandidateHandle != handle || view.SalaryFit != domain.InvitationSalaryNotAvailable ||
view.ContactAccess != domain.InvitationContactAccessNone || view.ResponseDeadlineAt != nil {
t.Fatalf("created view = %+v, want an unsent version 1 with the default period for the card handle", view.InvitationSnapshot)
}
state := test.transactor.snapshot()
stored := state.invitations[view.ID]
if stored.CandidateID() != candidateID || len(state.events) != 1 || state.events[0].Kind != domain.InvitationEventDraftCreated ||
state.events[0].ActorID != test.actorID {
t.Fatalf("stored candidate/events = %v/%+v, want the resolved candidate and one creation event", stored.CandidateID() == candidateID, state.events)
}
}
func TestCreateRefusesEveryCandidateTheOrganizationCannotUseWithTheSamePointer(t *testing.T) {
test := newHarness(t)
otherOrganization := uuid.Must(uuid.NewV7())
foreign, err := test.key.ForOrganization(otherOrganization, uuid.Must(uuid.NewV7()))
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
unknown := "cv1_" + strings.Repeat("Z", 43)
for name, handle := range map[string]string{"another organization": foreign, "unknown": unknown, "malformed": "not-a-handle"} {
command := test.createCommand(handle, "key-"+name)
_, err := test.service.Create(t.Context(), command)
if pointer := fieldPointer(t, err); pointer != "/candidate_handle" {
t.Errorf("%s: pointer = %s, want /candidate_handle", name, pointer)
}
}
state := test.transactor.snapshot()
if len(state.invitations) != 0 || len(state.events) != 0 || len(state.idempotency) != 0 || len(state.results) != 0 {
t.Fatalf("refused creates left state: %d invitations, %d events, %d keys, %d results", len(state.invitations), len(state.events), len(state.idempotency), len(state.results))
}
}
func TestCreateAppliesTheDomainRulesInTheContractOrderAndStoresNothingOnFailure(t *testing.T) {
test := newHarness(t)
handle, _ := test.showCandidate(t)
needID := uuid.Must(uuid.NewV7())
command := test.createCommand(handle, "key-need")
command.Need = &domain.InvitationNeedRef{NeedID: needID, RequirementsVersion: 1}
command.Terms.Salary.SalaryTo = 500_000
_, err := test.service.Create(t.Context(), command)
if pointer := fieldPointer(t, err); pointer != "/need" {
t.Fatalf("pointer = %s, want /need before the terms", pointer)
}
test.transactor.state.needVersions[[3]string{test.organizationID.String(), needID.String(), "1"}] = true
_, err = test.service.Create(t.Context(), command)
if pointer := fieldPointer(t, err); pointer != "/terms/salary/salary_to" {
t.Fatalf("pointer = %s, want the salary range", pointer)
}
command = test.createCommand(handle, "key-period")
period := int32(5)
command.ResponsePeriodDays = &period
_, err = test.service.Create(t.Context(), command)
if pointer := fieldPointer(t, err); pointer != "/response_period_days" {
t.Fatalf("pointer = %s, want /response_period_days", pointer)
}
if state := test.transactor.snapshot(); len(state.invitations) != 0 || len(state.idempotency) != 0 {
t.Fatalf("failed creates stored %d invitations and %d keys", len(state.invitations), len(state.idempotency))
}
}
func TestCreateReplaysTheOriginalResponseAndRejectsAChangedRequest(t *testing.T) {
test := newHarness(t)
handle, _ := test.showCandidate(t)
command := test.createCommand(handle, "key-replay")
first, err := test.service.Create(t.Context(), command)
if err != nil {
t.Fatalf("Create() error = %v", err)
}
// The candidate stops being visible; the replay still returns the stored
// response and creates nothing.
delete(test.visible, handle)
replay, err := test.service.Create(t.Context(), command)
if err != nil || replay.ID != first.ID || replay.Version != 1 {
t.Fatalf("replay = %v, %v; want the original draft", replay.ID, err)
}
changed := command
changed.CanonicalBody = []byte(`{"different":true}`)
if _, err := test.service.Create(t.Context(), changed); !errors.Is(err, ErrIdempotencyKeyReused) {
t.Fatalf("Create(changed body) error = %v, want ErrIdempotencyKeyReused", err)
}
if state := test.transactor.snapshot(); len(state.invitations) != 1 || len(state.events) != 1 {
t.Fatalf("replay stored %d invitations and %d events, want one each", len(state.invitations), len(state.events))
}
}
func TestCreateRollbackLeavesNoDraftWhenTheResponseCannotBeStored(t *testing.T) {
test := newHarness(t)
handle, _ := test.showCandidate(t)
test.transactor.failResultSave = true
if _, err := test.service.Create(t.Context(), test.createCommand(handle, "key-fail")); err == nil {
t.Fatal("Create() succeeded although the response could not be stored")
}
if state := test.transactor.snapshot(); len(state.invitations) != 0 || len(state.events) != 0 || len(state.idempotency) != 0 {
t.Fatalf("failed create left %d invitations, %d events, %d keys", len(state.invitations), len(state.events), len(state.idempotency))
}
}
func TestOnlyTheActiveOwnerOfAnEmployerAccountMayWorkWithInvitations(t *testing.T) {
test := newHarness(t)
handle, _ := test.showCandidate(t)
verified := time.Date(2026, time.October, 9, 9, 0, 0, 0, time.UTC)
addAccount := func(scenario domain.Scenario) uuid.UUID {
id := uuid.Must(uuid.NewV7())
test.transactor.state.users[id] = domain.User{ID: id, Scenario: scenario, EmailVerifiedAt: &verified}
return id
}
recruiter := addAccount(domain.ScenarioEmployer)
membership, err := domain.NewMembership(domain.MembershipInput{
OrganizationID: test.organizationID, UserID: recruiter, Role: domain.OrganizationRoleRecruiter, At: verified,
})
if err != nil {
t.Fatalf("NewMembership() error = %v", err)
}
test.transactor.state.memberships[[2]uuid.UUID{test.organizationID, recruiter}] = membership
unverified := uuid.Must(uuid.NewV7())
test.transactor.state.users[unverified] = domain.User{ID: unverified, Scenario: domain.ScenarioEmployer}
ownerMembership, _ := domain.NewOwnerMembership(test.organizationID, unverified, verified)
test.transactor.state.memberships[[2]uuid.UUID{test.organizationID, unverified}] = ownerMembership
tests := []struct {
name string
actor uuid.UUID
want error
}{
{"recruiter", recruiter, outbound.ErrOrganizationManagerRequired},
{"candidate account", addAccount(domain.ScenarioCandidate), ErrForbidden},
{"employer outside the organization", addAccount(domain.ScenarioEmployer), outbound.ErrOrganizationNotFound},
{"owner without a confirmed email", unverified, ErrEmailNotVerified},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
command := test.createCommand(handle, "key-"+tt.name)
command.ActorID = tt.actor
if _, err := test.service.Create(t.Context(), command); !errors.Is(err, tt.want) {
t.Errorf("Create() error = %v, want %v", err, tt.want)
}
if _, err := test.service.List(t.Context(), ListCommand{ActorID: tt.actor, OrganizationID: test.organizationID, Limit: 10}); !errors.Is(err, tt.want) {
t.Errorf("List() error = %v, want %v", err, tt.want)
}
if _, err := test.service.Get(t.Context(), tt.actor, test.organizationID, uuid.New()); !errors.Is(err, tt.want) {
t.Errorf("Get() error = %v, want %v", err, tt.want)
}
})
}
if state := test.transactor.snapshot(); len(state.invitations) != 0 {
t.Fatalf("a refused actor created %d invitations", len(state.invitations))
}
}
func (test *harness) createDraft(t *testing.T, key string) domain.OrganizationInvitationView {
t.Helper()
handle, _ := test.showCandidate(t)
view, err := test.service.Create(t.Context(), test.createCommand(handle, key))
if err != nil {
t.Fatalf("Create() error = %v", err)
}
return view
}
func (test *harness) update(command UpdateCommand) (domain.OrganizationInvitationView, error) {
command.ActorID, command.OrganizationID = test.actorID, test.organizationID
return test.service.Update(context.Background(), command)
}
func TestUpdateFollowsTheDocumentedOrderOfChecks(t *testing.T) {
test := newHarness(t)
draft := test.createDraft(t, "key-order")
test.setTime(time.Date(2026, time.October, 9, 10, 5, 0, 0, time.UTC))
changedTerms := testTerms()
changedTerms.Salary.SalaryTo = 150_000
updated, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 1, Terms: &changedTerms})
if err != nil || updated.Version != 2 || updated.TermsVersion != 2 || updated.Terms.Salary.SalaryTo != 150_000 {
t.Fatalf("Update(terms) = version %d/%d, %v; want 2/2", updated.Version, updated.TermsVersion, err)
}
state := test.transactor.snapshot()
if first := state.terms[termsKey{draft.ID, 1}]; first.Salary.SalaryTo != 140_000 {
t.Fatalf("terms version 1 changed to %d", first.Salary.SalaryTo)
}
if len(state.events) != 2 || state.events[1].Kind != domain.InvitationEventDraftUpdated ||
fmt.Sprint(state.events[1].ChangedFields) != "[terms]" {
t.Fatalf("events = %+v, want a draft_updated event for the terms", state.events)
}
// 1. A body that changes nothing answers with the current invitation even
// when the version it names is stale.
repeated, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 1, Terms: &changedTerms})
if err != nil || repeated.Version != 2 {
t.Fatalf("Update(retry) = version %d, %v; want the current version 2", repeated.Version, err)
}
// 2. A stale version beats the domain rules.
invalid := testTerms()
invalid.Salary.SalaryTo = 500_000
if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 1, Terms: &invalid}); !errors.Is(err, domain.ErrInvitationVersionConflict) {
t.Fatalf("Update(stale, invalid) error = %v, want a version conflict", err)
}
// 3. A rule violation of a current version is a field error and changes nothing.
_, err = test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 2, Terms: &invalid})
if pointer := fieldPointer(t, err); pointer != "/terms/salary/salary_to" {
t.Fatalf("pointer = %s, want the salary range", pointer)
}
// 4. A period outside the policy and an unknown need are field errors.
period := int32(5)
if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 2, ResponsePeriodDays: &period}); fieldPointer(t, err) != "/response_period_days" {
t.Fatalf("Update(period 5) error = %v", err)
}
need := Field[domain.InvitationNeedRef]{Set: true, Value: domain.InvitationNeedRef{NeedID: uuid.New(), RequirementsVersion: 1}}
if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 2, Need: need}); fieldPointer(t, err) != "/need" {
t.Fatalf("Update(unknown need) error = %v", err)
}
if after := test.transactor.snapshot(); after.invitations[draft.ID].Version() != 2 || len(after.events) != 2 {
t.Fatalf("rejected updates changed the draft: version %d, %d events", after.invitations[draft.ID].Version(), len(after.events))
}
}
func TestUpdateKeepsTheTermsVersionWhenOnlyThePeriodOrTheNeedChanges(t *testing.T) {
test := newHarness(t)
draft := test.createDraft(t, "key-parts")
needID := uuid.Must(uuid.NewV7())
test.transactor.state.needVersions[[3]string{test.organizationID.String(), needID.String(), "2"}] = true
period := int32(14)
linked, err := test.update(UpdateCommand{
InvitationID: draft.ID, ExpectedVersion: 1, ResponsePeriodDays: &period,
Need: Field[domain.InvitationNeedRef]{Set: true, Value: domain.InvitationNeedRef{NeedID: needID, RequirementsVersion: 2}},
})
if err != nil || linked.Version != 2 || linked.TermsVersion != 1 || linked.ResponsePeriodDays != 14 ||
linked.Need == nil || linked.Need.NeedID != needID {
t.Fatalf("Update(period, need) = version %d/%d period %d, %v; want 2/1 with the link", linked.Version, linked.TermsVersion, linked.ResponsePeriodDays, err)
}
unlinked, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 2, Need: Field[domain.InvitationNeedRef]{Set: true, Null: true}})
if err != nil || unlinked.Version != 3 || unlinked.Need != nil || unlinked.TermsVersion != 1 {
t.Fatalf("Update(unlink) = version %d need %v, %v; want version 3 without a need", unlinked.Version, unlinked.Need, err)
}
if state := test.transactor.snapshot(); len(state.terms) != 1 {
t.Fatalf("stored %d terms versions, want only the first", len(state.terms))
}
}
func TestUpdateRefusesAnInvitationThatLeftTheDraftState(t *testing.T) {
test := newHarness(t)
draft := test.createDraft(t, "key-state")
stored := test.transactor.state.invitations[draft.ID].Stored()
stored.State = string(domain.InvitationWithdrawn)
withdrawn, err := domain.RestoreInvitation(stored)
if err != nil {
t.Fatalf("RestoreInvitation() error = %v", err)
}
test.transactor.state.invitations[draft.ID] = withdrawn
changed := testTerms()
changed.RoleTitle = "Senior Go developer"
if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 1, Terms: &changed}); !errors.Is(err, domain.ErrInvitationNotDraft) {
t.Fatalf("Update(withdrawn) error = %v, want ErrInvitationNotDraft", err)
}
// A stale version of a withdrawn invitation is still reported as the state.
if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 7, Terms: &changed}); !errors.Is(err, domain.ErrInvitationVersionConflict) {
t.Fatalf("Update(stale, withdrawn) error = %v, want the version comparison first", err)
}
}
func TestReadsAreScopedToTheOrganizationAndPaged(t *testing.T) {
test := newHarness(t)
first := test.createDraft(t, "key-1")
second := test.createDraft(t, "key-2")
third := test.createDraft(t, "key-3")
if got, err := test.service.Get(t.Context(), test.actorID, test.organizationID, second.ID); err != nil || got.ID != second.ID {
t.Fatalf("Get() = %v, %v; want the draft", got.ID, err)
}
if _, err := test.service.Get(t.Context(), test.actorID, uuid.Must(uuid.NewV7()), second.ID); !errors.Is(err, outbound.ErrOrganizationNotFound) {
t.Fatalf("Get(other organization) error = %v, want not found", err)
}
if _, err := test.service.Get(t.Context(), test.actorID, test.organizationID, uuid.New()); !errors.Is(err, outbound.ErrInvitationNotFound) {
t.Fatalf("Get(unknown) error = %v, want not found", err)
}
page, err := test.service.List(t.Context(), ListCommand{ActorID: test.actorID, OrganizationID: test.organizationID, Limit: 2})
if err != nil || len(page.Items) != 2 || !page.HasMore {
t.Fatalf("List(2) = %d items more=%t, %v; want a first page of two", len(page.Items), page.HasMore, err)
}
ids := map[uuid.UUID]bool{first.ID: true, second.ID: true, third.ID: true}
for _, item := range page.Items {
if !ids[item.ID] || item.CandidateHandle == "" {
t.Fatalf("listed item %v is unknown or has no alias", item.ID)
}
}
if _, err := test.service.List(t.Context(), ListCommand{ActorID: test.actorID, OrganizationID: test.organizationID, Limit: 0}); !errors.Is(err, ErrInvalidRequest) {
t.Fatalf("List(0) error = %v, want ErrInvalidRequest", err)
}
}
func (repository testInvitations) GetTermsVersion(_ context.Context, _, invitationID uuid.UUID, version int64) (domain.InvitationTerms, error) {
terms, ok := repository.state.terms[termsKey{invitationID, version}]
if !ok {
return domain.InvitationTerms{}, outbound.ErrInvitationNotFound
}
return terms, nil
}