feat(invitations): add organization invitation drafts with salary range rules
This commit is contained in:
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
|
||||
|
||||
Reference in new issue
Block a user