feat(invitations): send invitations into the candidate inbox atomically
This commit is contained in:
1 parent
fc35e27af5
commit
1a067221f7
46 files changed
+3276
-113
No files matched your search
@@ -14035,7 +14035,8 @@ func (s *Server) handleSearchOrganizationMatchesRequest(args [1]string, argsEsca
|
||||
// answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the
|
||||
// organization and the candidate after a decline or a no deal, regardless of the member or the need,
|
||||
// both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and
|
||||
// Retry-After. Enforcement of the pending limit and the organization quota is planned.
|
||||
// Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are
|
||||
// not checked yet.
|
||||
//
|
||||
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
|
||||
// and a send of an invitation that was already sent answers 200 with the invitation in its current
|
||||
|
||||
@@ -20754,10 +20754,10 @@ func (s *NotificationContent) SetLinkPath(val NilString) {
|
||||
// Which event put the notification into the inbox. The inbox stores a reference to the event, never
|
||||
// its text.
|
||||
//
|
||||
// - invitation_delivered: an invitation reached the candidate's inbox. This is the in-platform
|
||||
// delivery state of the invitation: it does not depend on any email, and a failed or missing email
|
||||
// never blocks it. The invitation operations are planned; no invitation produces a notification
|
||||
// yet.
|
||||
// - invitation_delivered: an invitation reached the candidate's inbox. It does not depend on any
|
||||
// email, and a failed or missing email never blocks it. The send of an invitation produces it
|
||||
// through the outbox, so the notice appears shortly after the commit of the send, while the
|
||||
// invitation itself is in ListMyInvitations from that commit.
|
||||
// - synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility
|
||||
// check, the list, and the read state). It has no product meaning, needs no action, and is never
|
||||
// produced by a user action.
|
||||
|
||||
@@ -1725,7 +1725,8 @@ type Handler interface {
|
||||
// answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the
|
||||
// organization and the candidate after a decline or a no deal, regardless of the member or the need,
|
||||
// both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and
|
||||
// Retry-After. Enforcement of the pending limit and the organization quota is planned.
|
||||
// Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are
|
||||
// not checked yet.
|
||||
//
|
||||
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
|
||||
// and a send of an invitation that was already sent answers 200 with the invitation in its current
|
||||
|
||||
@@ -1916,7 +1916,8 @@ func (UnimplementedHandler) SearchOrganizationMatches(ctx context.Context, req M
|
||||
// answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the
|
||||
// organization and the candidate after a decline or a no deal, regardless of the member or the need,
|
||||
// both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and
|
||||
// Retry-After. Enforcement of the pending limit and the organization quota is planned.
|
||||
// Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are
|
||||
// not checked yet.
|
||||
//
|
||||
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
|
||||
// and a send of an invitation that was already sent answers 200 with the invitation in its current
|
||||
|
||||
@@ -18,18 +18,22 @@ import (
|
||||
|
||||
const defaultInvitationLimit = 20
|
||||
|
||||
// InvitationOperations are the owner-scoped invitation draft reads and
|
||||
// commands served by HTTP.
|
||||
// InvitationOperations are the owner-scoped invitation reads and commands and
|
||||
// the candidate's read of the own inbox 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)
|
||||
Send(ctx context.Context, command invitationusecase.SendCommand) (domain.OrganizationInvitationView, error)
|
||||
ListMine(ctx context.Context, command invitationusecase.CandidateListCommand) (invitationusecase.CandidatePage, 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.
|
||||
// InvitationHandler serves the organization side of invitation drafts and
|
||||
// their sending, and the candidate's inbox. The organization comes from the
|
||||
// path and the server-side membership, never from a body, the candidate is
|
||||
// only ever named by the opaque card handle, and the candidate's inbox is
|
||||
// bound to the session.
|
||||
type InvitationHandler struct {
|
||||
operations InvitationOperations
|
||||
}
|
||||
@@ -69,6 +73,20 @@ func (handler *Handler) UpdateOrganizationInvitation(ctx context.Context, reques
|
||||
return handler.invitation.UpdateOrganizationInvitation(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) SendOrganizationInvitation(ctx context.Context, request *api.InvitationCommand, params api.SendOrganizationInvitationParams) (api.SendOrganizationInvitationRes, error) {
|
||||
if handler.invitation == nil {
|
||||
return handler.UnimplementedHandler.SendOrganizationInvitation(ctx, request, params)
|
||||
}
|
||||
return handler.invitation.SendOrganizationInvitation(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) ListMyInvitations(ctx context.Context, params api.ListMyInvitationsParams) (api.ListMyInvitationsRes, error) {
|
||||
if handler.invitation == nil {
|
||||
return handler.UnimplementedHandler.ListMyInvitations(ctx, params)
|
||||
}
|
||||
return handler.invitation.ListMyInvitations(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *InvitationHandler) CreateOrganizationInvitation(
|
||||
ctx context.Context,
|
||||
request *api.OrganizationInvitationCreate,
|
||||
@@ -203,6 +221,66 @@ func (handler *InvitationHandler) UpdateOrganizationInvitation(
|
||||
return &api.OrganizationInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: organizationInvitationResponse(view)}, nil
|
||||
}
|
||||
|
||||
func (handler *InvitationHandler) SendOrganizationInvitation(
|
||||
ctx context.Context,
|
||||
request *api.InvitationCommand,
|
||||
params api.SendOrganizationInvitationParams,
|
||||
) (api.SendOrganizationInvitationRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.SendOrganizationInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.SendOrganizationInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
view, err := handler.operations.Send(ctx, invitationusecase.SendCommand{
|
||||
ActorID: principal.UserID, OrganizationID: params.OrgID, InvitationID: params.InvitationID,
|
||||
IdempotencyKey: params.IdempotencyKey, ExpectedVersion: int64(request.ExpectedVersion),
|
||||
})
|
||||
if err != nil {
|
||||
return invitationSendFailure(ctx, err)
|
||||
}
|
||||
return &api.OrganizationInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: organizationInvitationResponse(view)}, nil
|
||||
}
|
||||
|
||||
func (handler *InvitationHandler) ListMyInvitations(ctx context.Context, params api.ListMyInvitationsParams) (api.ListMyInvitationsRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListMyInvitationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
command, pointer := candidateInvitationListCommand(principal.UserID, params)
|
||||
if pointer != "" {
|
||||
return (*api.ListMyInvitationsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
|
||||
}
|
||||
page, err := handler.operations.ListMine(ctx, command)
|
||||
if err != nil {
|
||||
if errors.Is(err, invitationusecase.ErrForbidden) {
|
||||
return (*api.ListMyInvitationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
items := make([]api.CandidateInvitationSummary, 0, len(page.Items))
|
||||
for _, item := range page.Items {
|
||||
items = append(items, candidateInvitationSummary(item))
|
||||
}
|
||||
next := api.NilString{}
|
||||
next.SetToNull()
|
||||
if page.HasMore && len(page.Items) > 0 {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
cursor, err := encodeCandidateInvitationCursor(principal.UserID, outbound.CandidateInvitationPosition{
|
||||
DeliveredAt: last.DeliveredAt, InvitationID: last.ID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("InvitationHandler.ListMyInvitations - encode cursor: %w", err)
|
||||
}
|
||||
next.SetTo(cursor)
|
||||
}
|
||||
return &api.CandidateInvitationListHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.CandidateInvitationList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
|
||||
}, 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.
|
||||
@@ -232,7 +310,7 @@ func classifyInvitationError(err error) invitationFailure {
|
||||
return invitationFailureBadKey
|
||||
case errors.Is(err, domain.ErrInvitationVersionConflict), errors.Is(err, outbound.ErrInvitationVersionConflict):
|
||||
return invitationFailureVersionConflict
|
||||
case errors.Is(err, domain.ErrInvitationNotDraft):
|
||||
case errors.Is(err, domain.ErrInvitationNotDraft), errors.Is(err, invitationusecase.ErrSendBlocked):
|
||||
return invitationFailureStateConflict
|
||||
case errors.Is(err, domain.ErrInvalidInvitation), errors.Is(err, domain.ErrInvalidSalaryRange):
|
||||
if _, ok := errors.AsType[*domain.InvitationFieldError](err); ok {
|
||||
@@ -301,6 +379,52 @@ func invitationUpdateFailure(ctx context.Context, err error) (api.UpdateOrganiza
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func invitationSendFailure(ctx context.Context, err error) (api.SendOrganizationInvitationRes, error) {
|
||||
// The organization quota is a 429 with the time when it frees room; it is
|
||||
// not stored under the key, so a later retry can succeed.
|
||||
if limited, ok := errors.AsType[*invitationusecase.QuotaExceededError](err); ok {
|
||||
return problem.RateLimited(ctx, wholeSeconds(time.Until(limited.RetryAt))), nil
|
||||
}
|
||||
switch classifyInvitationError(err) {
|
||||
case invitationFailureForbidden:
|
||||
return (*api.SendOrganizationInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case invitationFailureNotFound:
|
||||
return (*api.SendOrganizationInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case invitationFailureKeyReused:
|
||||
return (*api.SendOrganizationInvitationUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
|
||||
case invitationFailureBadKey:
|
||||
return (*api.SendOrganizationInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
|
||||
case invitationFailureInvalid:
|
||||
return (*api.SendOrganizationInvitationBadRequest)(invitationValidationProblem(ctx, err)), nil
|
||||
case invitationFailureVersionConflict:
|
||||
return (*api.SendOrganizationInvitationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
|
||||
case invitationFailureStateConflict:
|
||||
return (*api.SendOrganizationInvitationConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
|
||||
case invitationFailureOther:
|
||||
return nil, err
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func candidateInvitationListCommand(actorID uuid.UUID, params api.ListMyInvitationsParams) (invitationusecase.CandidateListCommand, string) {
|
||||
limit, ok := params.Limit.Get()
|
||||
if !ok {
|
||||
limit = defaultInvitationLimit
|
||||
}
|
||||
if limit < 1 || limit > outbound.MaxInvitationPageSize {
|
||||
return invitationusecase.CandidateListCommand{}, "limit"
|
||||
}
|
||||
command := invitationusecase.CandidateListCommand{ActorID: actorID, Limit: limit}
|
||||
if cursor, ok := params.Cursor.Get(); ok {
|
||||
position, err := decodeCandidateInvitationCursor(cursor, actorID)
|
||||
if err != nil {
|
||||
return invitationusecase.CandidateListCommand{}, "cursor"
|
||||
}
|
||||
command.After = &position
|
||||
}
|
||||
return command, ""
|
||||
}
|
||||
|
||||
func invitationListCommand(actorID uuid.UUID, params api.ListOrganizationInvitationsParams) (invitationusecase.ListCommand, string) {
|
||||
limit, ok := params.Limit.Get()
|
||||
if !ok {
|
||||
@@ -493,3 +617,19 @@ func organizationInvitationSummary(view domain.OrganizationInvitationView) api.O
|
||||
CreatedAt: api.Timestamp(view.CreatedAt), UpdatedAt: api.Timestamp(view.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func candidateInvitationSummary(summary domain.CandidateInvitationSummary) api.CandidateInvitationSummary {
|
||||
formats := make([]api.WorkFormat, 0, len(summary.WorkFormats))
|
||||
for _, format := range summary.WorkFormats {
|
||||
formats = append(formats, api.WorkFormat(format))
|
||||
}
|
||||
return api.CandidateInvitationSummary{
|
||||
ID: summary.ID,
|
||||
Organization: api.InvitationOrganization{ID: summary.Organization.ID, Name: summary.Organization.Name},
|
||||
State: api.InvitationState(summary.State), ExpiryReason: invitationExpiryResponse(summary.ExpiryReason),
|
||||
Version: api.InvitationVersion(summary.Version), TermsVersion: api.InvitationTermsVersion(summary.TermsVersion),
|
||||
RoleTitle: api.InvitationRoleTitle(summary.RoleTitle), Salary: salaryRangeResponse(summary.Salary), WorkFormats: formats,
|
||||
ResponseDeadlineAt: api.Timestamp(summary.ResponseDeadlineAt), DeliveredAt: api.Timestamp(summary.DeliveredAt),
|
||||
ViewedAt: nullableTimestamp(summary.ViewedAt), UpdatedAt: api.Timestamp(summary.UpdatedAt),
|
||||
}
|
||||
}
|
||||
@@ -13,43 +13,79 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
invitationCursorVersion = 1
|
||||
invitationCursorBytes = 61
|
||||
maxInvitationCursorTime = uint64(253402300799)
|
||||
// invitationCursorVersion marks a page of one organization's invitations;
|
||||
// candidateInvitationCursorVersion marks a page of one candidate's inbox.
|
||||
// A cursor of one listing is refused by the other.
|
||||
invitationCursorVersion = 1
|
||||
candidateInvitationCursorVersion = 2
|
||||
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")
|
||||
if organizationID == uuid.Nil {
|
||||
return "", errors.New("invitation cursor requires an organization")
|
||||
}
|
||||
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
|
||||
return encodeInvitationPosition(invitationCursorVersion, actorID, organizationID, position.CreatedAt, position.InvitationID)
|
||||
}
|
||||
|
||||
func decodeInvitationCursor(cursor string, actorID, organizationID uuid.UUID) (outbound.InvitationListPosition, error) {
|
||||
if organizationID == uuid.Nil {
|
||||
return outbound.InvitationListPosition{}, errors.New("invitation cursor requires an organization")
|
||||
}
|
||||
at, invitationID, err := decodeInvitationPosition(cursor, invitationCursorVersion, actorID, organizationID)
|
||||
if err != nil {
|
||||
return outbound.InvitationListPosition{}, err
|
||||
}
|
||||
return outbound.InvitationListPosition{CreatedAt: at, InvitationID: invitationID}, nil
|
||||
}
|
||||
|
||||
// encodeCandidateInvitationCursor binds the position of the candidate's inbox
|
||||
// to the candidate who read the page.
|
||||
func encodeCandidateInvitationCursor(actorID uuid.UUID, position outbound.CandidateInvitationPosition) (string, error) {
|
||||
return encodeInvitationPosition(candidateInvitationCursorVersion, actorID, actorID, position.DeliveredAt, position.InvitationID)
|
||||
}
|
||||
|
||||
func decodeCandidateInvitationCursor(cursor string, actorID uuid.UUID) (outbound.CandidateInvitationPosition, error) {
|
||||
at, invitationID, err := decodeInvitationPosition(cursor, candidateInvitationCursorVersion, actorID, actorID)
|
||||
if err != nil {
|
||||
return outbound.CandidateInvitationPosition{}, err
|
||||
}
|
||||
return outbound.CandidateInvitationPosition{DeliveredAt: at, InvitationID: invitationID}, nil
|
||||
}
|
||||
|
||||
func encodeInvitationPosition(version byte, actorID, scopeID uuid.UUID, at time.Time, invitationID uuid.UUID) (string, error) {
|
||||
seconds, nanos := at.Unix(), at.Nanosecond()
|
||||
if actorID == uuid.Nil || scopeID == uuid.Nil || invitationID == uuid.Nil || at.IsZero() ||
|
||||
at.Year() < 1 || at.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, a scope, and a valid page position")
|
||||
}
|
||||
var value [invitationCursorBytes]byte
|
||||
value[0] = version
|
||||
copy(value[1:17], actorID[:])
|
||||
copy(value[17:33], scopeID[:])
|
||||
binary.BigEndian.PutUint64(value[33:41], uint64(seconds))
|
||||
binary.BigEndian.PutUint32(value[41:45], uint32(nanos))
|
||||
copy(value[45:61], invitationID[:])
|
||||
return base64.RawURLEncoding.EncodeToString(value[:]), nil
|
||||
}
|
||||
|
||||
func decodeInvitationPosition(cursor string, version byte, actorID, scopeID uuid.UUID) (time.Time, uuid.UUID, 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")
|
||||
if err != nil || len(value) != invitationCursorBytes || actorID == uuid.Nil || scopeID == uuid.Nil ||
|
||||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != version ||
|
||||
uuid.UUID(value[1:17]) != actorID || uuid.UUID(value[17:33]) != scopeID {
|
||||
return time.Time{}, uuid.Nil, 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 time.Time{}, uuid.Nil, errors.New("invitation cursor position is invalid")
|
||||
}
|
||||
return outbound.InvitationListPosition{CreatedAt: time.Unix(int64(seconds), int64(nanos)).UTC(), InvitationID: invitationID}, nil
|
||||
return time.Unix(int64(seconds), int64(nanos)).UTC(), invitationID, nil
|
||||
}
|
||||
@@ -191,3 +191,73 @@ func TestInvitationCursorIsBoundToActorAndOrganization(t *testing.T) {
|
||||
t.Error("a cursor with trailing data was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationSendFailuresMapToTheContractStatuses(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
send := func(err error) any {
|
||||
response, unexpected := invitationSendFailure(ctx, err)
|
||||
if unexpected != nil {
|
||||
return unexpected
|
||||
}
|
||||
return fmt.Sprintf("%T", response)
|
||||
}
|
||||
for name, test := range map[string]struct {
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
"forbidden": {fmt.Errorf("wrapped: %w", outbound.ErrOrganizationManagerRequired), "*api.SendOrganizationInvitationForbidden"},
|
||||
"unknown invitation": {fmt.Errorf("wrapped: %w", outbound.ErrInvitationNotFound), "*api.SendOrganizationInvitationNotFound"},
|
||||
"reused key": {invitationusecase.ErrIdempotencyKeyReused, "*api.SendOrganizationInvitationUnprocessableEntity"},
|
||||
"bad key": {invitationusecase.ErrInvalidIdempotencyKey, "*api.SendOrganizationInvitationBadRequest"},
|
||||
"stale version": {fmt.Errorf("wrapped: %w", domain.ErrInvitationVersionConflict), "*api.SendOrganizationInvitationPreconditionFailed"},
|
||||
"blocked send": {fmt.Errorf("wrapped: %w", invitationusecase.ErrSendBlocked), "*api.SendOrganizationInvitationConflict"},
|
||||
"quota": {&invitationusecase.QuotaExceededError{RetryAt: time.Now().Add(90 * time.Second)}, "*api.TooManyRequestsHeaders"},
|
||||
} {
|
||||
if got := send(test.err); got != test.want {
|
||||
t.Errorf("%s: send failure = %v, want %s", name, got, test.want)
|
||||
}
|
||||
}
|
||||
response, err := invitationSendFailure(ctx, fmt.Errorf("wrapped: %w", &invitationusecase.QuotaExceededError{RetryAt: time.Now().Add(90 * time.Second)}))
|
||||
limited, ok := response.(*api.TooManyRequestsHeaders)
|
||||
if err != nil || !ok || limited.Response.Code != api.ProblemCodeRateLimited {
|
||||
t.Fatalf("quota failure = %T, %v; want 429 rate_limited", response, err)
|
||||
}
|
||||
if wait, set := limited.RetryAfter.Get(); !set || wait < 89 || wait > 90 {
|
||||
t.Fatalf("Retry-After = %d, %v; want the seconds until the quota frees room", wait, set)
|
||||
}
|
||||
if _, passedOn := send(errors.New("storage failed")).(error); !passedOn {
|
||||
t.Error("an unknown failure produced a public response instead of reaching the responder")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateInvitationCursorIsBoundToTheCandidateAndItsListing(t *testing.T) {
|
||||
actorID := uuid.Must(uuid.NewV7())
|
||||
position := outbound.CandidateInvitationPosition{
|
||||
DeliveredAt: time.Date(2026, time.October, 9, 10, 0, 0, 123456000, time.UTC), InvitationID: uuid.Must(uuid.NewV7()),
|
||||
}
|
||||
cursor, err := encodeCandidateInvitationCursor(actorID, position)
|
||||
if err != nil {
|
||||
t.Fatalf("encodeCandidateInvitationCursor() error = %v", err)
|
||||
}
|
||||
decoded, err := decodeCandidateInvitationCursor(cursor, actorID)
|
||||
if err != nil || !decoded.DeliveredAt.Equal(position.DeliveredAt) || decoded.InvitationID != position.InvitationID {
|
||||
t.Fatalf("decodeCandidateInvitationCursor() = %+v, %v; want the same position", decoded, err)
|
||||
}
|
||||
if _, err := decodeCandidateInvitationCursor(cursor, uuid.Must(uuid.NewV7())); err == nil {
|
||||
t.Error("a cursor of another candidate was accepted")
|
||||
}
|
||||
// An organization cursor of the same account does not continue the
|
||||
// candidate's inbox, and the other way round.
|
||||
organizationCursor, err := encodeInvitationCursor(actorID, actorID, outbound.InvitationListPosition{
|
||||
CreatedAt: position.DeliveredAt, InvitationID: position.InvitationID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("encodeInvitationCursor() error = %v", err)
|
||||
}
|
||||
if _, err := decodeCandidateInvitationCursor(organizationCursor, actorID); err == nil {
|
||||
t.Error("an organization cursor continued the candidate's inbox")
|
||||
}
|
||||
if _, err := decodeInvitationCursor(cursor, actorID, actorID); err == nil {
|
||||
t.Error("a candidate cursor continued an organization listing")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var _ outbound.InvitationSendResultRepository = invitationRepository{}
|
||||
|
||||
// maxInvitationOrganizationNameRunes is the bound of the organization name
|
||||
// that the candidate's inbox shows, as in the public contract.
|
||||
const maxInvitationOrganizationNameRunes = 200
|
||||
|
||||
func (unit *UnitOfWork) InvitationSendResults() outbound.InvitationSendResultRepository {
|
||||
return invitationRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
func (repository invitationRepository) Deliver(
|
||||
ctx context.Context,
|
||||
expectedVersion int64,
|
||||
next domain.Invitation,
|
||||
event domain.InvitationEvent,
|
||||
) error {
|
||||
const location = "invitationRepository.Deliver"
|
||||
stored := next.Stored()
|
||||
if expectedVersion < 1 || stored.Version != expectedVersion+1 || stored.State != string(domain.InvitationDelivered) ||
|
||||
stored.DeliveredAt == nil || stored.ResponseDeadlineAt == nil || event.Kind != domain.InvitationEventDelivered {
|
||||
return fmt.Errorf("%s - the next version must be the delivery that follows the expected one: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
if err := repository.insertEventPrerequisites(location, next, event, stored.Version); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := repository.queries.DeliverInvitation(ctx, sqlc.DeliverInvitationParams{
|
||||
NextVersion: stored.Version, DeliveredAt: pgTime(*stored.DeliveredAt), ResponseDeadlineAt: pgTime(*stored.ResponseDeadlineAt),
|
||||
OrganizationID: pgUUID(stored.OrganizationID), InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion,
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return fmt.Errorf("%s - deliver draft: %w", location, outbound.ErrInvitationVersionConflict)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - deliver draft: %w", location, mapInvitationError(err))
|
||||
}
|
||||
return repository.insertEvent(ctx, location, event)
|
||||
}
|
||||
|
||||
func (repository invitationRepository) ListForCandidate(
|
||||
ctx context.Context,
|
||||
query outbound.CandidateInvitationListQuery,
|
||||
) (outbound.CandidateInvitationPage, error) {
|
||||
const location = "invitationRepository.ListForCandidate"
|
||||
if query.CandidateID == uuid.Nil {
|
||||
return outbound.CandidateInvitationPage{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
if query.Limit < 1 || query.Limit > outbound.MaxInvitationPageSize {
|
||||
return outbound.CandidateInvitationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxInvitationPageSize, domain.ErrInvalidInvitation)
|
||||
}
|
||||
params := sqlc.ListCandidateInvitationsParams{CandidateID: pgUUID(query.CandidateID), RowLimit: query.Limit + 1}
|
||||
if query.After != nil {
|
||||
after := *query.After
|
||||
if after.InvitationID == uuid.Nil || !validStoredInvitationTime(after.DeliveredAt) {
|
||||
return outbound.CandidateInvitationPage{}, fmt.Errorf("%s - pagination position is invalid: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
params.AfterDeliveredAt = pgTime(after.DeliveredAt)
|
||||
params.AfterInvitationID = pgUUID(after.InvitationID)
|
||||
}
|
||||
rows, err := repository.queries.ListCandidateInvitations(ctx, params)
|
||||
if err != nil {
|
||||
return outbound.CandidateInvitationPage{}, fmt.Errorf("%s - select invitations: %w", location, mapInvitationError(err))
|
||||
}
|
||||
page := outbound.CandidateInvitationPage{HasMore: len(rows) > int(query.Limit)}
|
||||
if page.HasMore {
|
||||
rows = rows[:query.Limit]
|
||||
}
|
||||
page.Items = make([]outbound.CandidateInvitationEntry, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
entry, err := restoreCandidateInvitationRow(location, row, query.CandidateID)
|
||||
if err != nil {
|
||||
return outbound.CandidateInvitationPage{}, err
|
||||
}
|
||||
page.Items = append(page.Items, entry)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (repository invitationRepository) GetForCandidate(
|
||||
ctx context.Context,
|
||||
candidateID, invitationID uuid.UUID,
|
||||
) (domain.Invitation, error) {
|
||||
const location = "invitationRepository.GetForCandidate"
|
||||
if candidateID == uuid.Nil || invitationID == uuid.Nil {
|
||||
return domain.Invitation{}, fmt.Errorf("%s - candidate and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
row, err := repository.queries.ReadCandidateInvitation(ctx, sqlc.ReadCandidateInvitationParams{
|
||||
CandidateID: pgUUID(candidateID), InvitationID: pgUUID(invitationID),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Invitation{}, fmt.Errorf("%s - read invitation: %w", location, mapInvitationNoRows(err))
|
||||
}
|
||||
if !row.OrganizationID.Valid || !row.CandidateID.Valid || uuid.UUID(row.CandidateID.Bytes) != candidateID {
|
||||
return domain.Invitation{}, fmt.Errorf("%s - invitation row has an invalid scope: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
return restoreInvitationRow(location, sqlc.ListInvitationsRow(row), uuid.UUID(row.OrganizationID.Bytes))
|
||||
}
|
||||
|
||||
func (repository invitationRepository) SaveSendResult(
|
||||
ctx context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
result outbound.InvitationSendResult,
|
||||
) error {
|
||||
const location = "invitationRepository.SaveSendResult"
|
||||
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
||||
return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
if err := validateInvitationSendResult(result); err != nil {
|
||||
return fmt.Errorf("%s - validate outcome: %w", location, err)
|
||||
}
|
||||
var snapshot []byte
|
||||
if result.View != nil {
|
||||
encoded, err := encodeInvitationCreationResult(*result.View)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - encode response: %w", location, err)
|
||||
}
|
||||
snapshot = encoded
|
||||
}
|
||||
if err := repository.queries.InsertInvitationSendResult(ctx, sqlc.InsertInvitationSendResultParams{
|
||||
ScopeHash: scope[:], OrganizationID: pgUUID(result.OrganizationID), InvitationID: pgUUID(result.InvitationID),
|
||||
Outcome: string(result.Outcome), Snapshot: snapshot,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - store outcome: %w", location, mapInvitationSendResultError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository invitationRepository) GetSendResult(
|
||||
ctx context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
) (outbound.InvitationSendResult, error) {
|
||||
const location = "invitationRepository.GetSendResult"
|
||||
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
||||
return outbound.InvitationSendResult{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
row, err := repository.queries.GetInvitationSendResult(ctx, scope[:])
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return outbound.InvitationSendResult{}, outbound.ErrInvitationSendResultNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return outbound.InvitationSendResult{}, fmt.Errorf("%s - read outcome: %w", location, mapInvitationError(err))
|
||||
}
|
||||
if !row.OrganizationID.Valid || !row.InvitationID.Valid {
|
||||
return outbound.InvitationSendResult{}, fmt.Errorf("%s - stored outcome has no scope: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
result := outbound.InvitationSendResult{
|
||||
OrganizationID: uuid.UUID(row.OrganizationID.Bytes), InvitationID: uuid.UUID(row.InvitationID.Bytes),
|
||||
Outcome: outbound.InvitationSendOutcome(row.Outcome),
|
||||
}
|
||||
if row.Snapshot != "" {
|
||||
view, err := decodeInvitationSendView(location, []byte(row.Snapshot))
|
||||
if err != nil {
|
||||
return outbound.InvitationSendResult{}, err
|
||||
}
|
||||
result.View = &view
|
||||
}
|
||||
if err := validateInvitationSendResult(result); err != nil {
|
||||
return outbound.InvitationSendResult{}, fmt.Errorf("%s - validate stored outcome: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// decodeInvitationSendView restores the original response of a send. It
|
||||
// shares the shape and the checks of a stored creation response.
|
||||
func decodeInvitationSendView(location string, encoded []byte) (domain.OrganizationInvitationView, error) {
|
||||
var view domain.OrganizationInvitationView
|
||||
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&view); err != nil || decoder.More() {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - stored response has an unexpected shape: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
if err := validateInvitationCreationResult(view); err != nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - validate stored response: %w", location, err)
|
||||
}
|
||||
return view, nil
|
||||
}
|
||||
|
||||
func validateInvitationSendResult(result outbound.InvitationSendResult) error {
|
||||
const location = "postgres.validateInvitationSendResult"
|
||||
// The invitation of a refusal is the identifier of the path, which may
|
||||
// name nothing, even the nil identifier; only a sent outcome names a real
|
||||
// invitation.
|
||||
if result.OrganizationID == uuid.Nil {
|
||||
return fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
switch result.Outcome {
|
||||
case outbound.InvitationSendSent:
|
||||
if result.View == nil || result.View.ID != result.InvitationID || result.View.OrganizationID != result.OrganizationID ||
|
||||
!result.View.State.IsKnown() || result.View.DeliveredAt == nil {
|
||||
return fmt.Errorf("%s - a sent outcome must hold the delivered invitation: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
case outbound.InvitationSendNotFound, outbound.InvitationSendStateConflict:
|
||||
if result.View != nil {
|
||||
return fmt.Errorf("%s - a refused outcome holds no response: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("%s - outcome is unknown: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func restoreCandidateInvitationRow(
|
||||
location string,
|
||||
row sqlc.ListCandidateInvitationsRow,
|
||||
candidateID uuid.UUID,
|
||||
) (outbound.CandidateInvitationEntry, error) {
|
||||
if !row.OrganizationID.Valid || !row.CandidateID.Valid || uuid.UUID(row.CandidateID.Bytes) != candidateID ||
|
||||
!utf8.ValidString(row.OrganizationName) || row.OrganizationName == "" ||
|
||||
utf8.RuneCountInString(row.OrganizationName) > maxInvitationOrganizationNameRunes {
|
||||
return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - invitation row has an invalid scope or sender: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
invitation, err := restoreInvitationRow(location, sqlc.ListInvitationsRow{
|
||||
ID: row.ID, OrganizationID: row.OrganizationID, CandidateID: row.CandidateID, NeedID: row.NeedID,
|
||||
NeedRequirementsVersion: row.NeedRequirementsVersion, State: row.State, ExpiryReason: row.ExpiryReason,
|
||||
Version: row.Version, TermsVersion: row.TermsVersion, ResponsePeriodDays: row.ResponsePeriodDays,
|
||||
PolicyVersionID: row.PolicyVersionID, ResponseDeadlineAt: row.ResponseDeadlineAt, SalaryRaiseUsed: row.SalaryRaiseUsed,
|
||||
CreatedBy: row.CreatedBy, CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt, DeliveredAt: row.DeliveredAt,
|
||||
ViewedAt: row.ViewedAt, RespondedAt: row.RespondedAt, Terms: row.Terms,
|
||||
}, uuid.UUID(row.OrganizationID.Bytes))
|
||||
if err != nil {
|
||||
return outbound.CandidateInvitationEntry{}, err
|
||||
}
|
||||
if !invitation.IsDelivered() {
|
||||
return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - an undelivered invitation is not in the inbox: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
return outbound.CandidateInvitationEntry{Invitation: invitation, OrganizationName: row.OrganizationName}, nil
|
||||
}
|
||||
|
||||
func mapInvitationSendResultError(err error) error {
|
||||
var pgError *pgconn.PgError
|
||||
if errors.As(err, &pgError) && pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitation_send_results_idempotency_fkey" {
|
||||
return fmt.Errorf("postgres.mapInvitationSendResultError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound)
|
||||
}
|
||||
return mapInvitationError(err)
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: invitation_delivery.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const deliverInvitation = `-- name: DeliverInvitation :one
|
||||
UPDATE invitations
|
||||
SET
|
||||
state = 'delivered',
|
||||
version = $1,
|
||||
delivered_at = $2,
|
||||
response_deadline_at = $3,
|
||||
updated_at = $2
|
||||
WHERE
|
||||
organization_id = $4
|
||||
AND id = $5
|
||||
AND state = 'draft'
|
||||
AND version = $6
|
||||
AND $1::bigint = $6::bigint + 1
|
||||
RETURNING id
|
||||
`
|
||||
|
||||
type DeliverInvitationParams struct {
|
||||
NextVersion int64
|
||||
DeliveredAt pgtype.Timestamptz
|
||||
ResponseDeadlineAt pgtype.Timestamptz
|
||||
OrganizationID pgtype.UUID
|
||||
InvitationID pgtype.UUID
|
||||
ExpectedVersion int64
|
||||
}
|
||||
|
||||
// The conditional update is the compare-and-swap of a send: it applies only to
|
||||
// a draft whose version is still the one the caller read, records the first
|
||||
// delivery with its deadline, and advances the version by one. No row is
|
||||
// returned when it lost a race or the invitation is no longer a draft.
|
||||
func (q *Queries) DeliverInvitation(ctx context.Context, arg DeliverInvitationParams) (pgtype.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, deliverInvitation,
|
||||
arg.NextVersion,
|
||||
arg.DeliveredAt,
|
||||
arg.ResponseDeadlineAt,
|
||||
arg.OrganizationID,
|
||||
arg.InvitationID,
|
||||
arg.ExpectedVersion,
|
||||
)
|
||||
var id pgtype.UUID
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
const getInvitationSendResult = `-- name: GetInvitationSendResult :one
|
||||
SELECT
|
||||
organization_id,
|
||||
invitation_id,
|
||||
outcome,
|
||||
-- A refusal has no snapshot; the empty text stands for it.
|
||||
coalesce(snapshot::text, '')::text AS snapshot
|
||||
FROM invitation_send_results
|
||||
WHERE scope_hash = $1
|
||||
`
|
||||
|
||||
type GetInvitationSendResultRow struct {
|
||||
OrganizationID pgtype.UUID
|
||||
InvitationID pgtype.UUID
|
||||
Outcome string
|
||||
Snapshot string
|
||||
}
|
||||
|
||||
func (q *Queries) GetInvitationSendResult(ctx context.Context, scopeHash []byte) (GetInvitationSendResultRow, error) {
|
||||
row := q.db.QueryRow(ctx, getInvitationSendResult, scopeHash)
|
||||
var i GetInvitationSendResultRow
|
||||
err := row.Scan(
|
||||
&i.OrganizationID,
|
||||
&i.InvitationID,
|
||||
&i.Outcome,
|
||||
&i.Snapshot,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertInvitationSendResult = `-- name: InsertInvitationSendResult :exec
|
||||
INSERT INTO invitation_send_results (
|
||||
scope_hash,
|
||||
organization_id,
|
||||
invitation_id,
|
||||
outcome,
|
||||
snapshot
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5::jsonb
|
||||
)
|
||||
`
|
||||
|
||||
type InsertInvitationSendResultParams struct {
|
||||
ScopeHash []byte
|
||||
OrganizationID pgtype.UUID
|
||||
InvitationID pgtype.UUID
|
||||
Outcome string
|
||||
Snapshot []byte
|
||||
}
|
||||
|
||||
func (q *Queries) InsertInvitationSendResult(ctx context.Context, arg InsertInvitationSendResultParams) error {
|
||||
_, err := q.db.Exec(ctx, insertInvitationSendResult,
|
||||
arg.ScopeHash,
|
||||
arg.OrganizationID,
|
||||
arg.InvitationID,
|
||||
arg.Outcome,
|
||||
arg.Snapshot,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const listCandidateInvitations = `-- name: ListCandidateInvitations :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,
|
||||
organization.name AS organization_name
|
||||
FROM invitations AS invitation
|
||||
INNER JOIN invitation_terms_versions AS terms
|
||||
ON terms.invitation_id = invitation.id
|
||||
AND terms.version = invitation.terms_version
|
||||
INNER JOIN organizations AS organization
|
||||
ON organization.id = invitation.organization_id
|
||||
WHERE
|
||||
invitation.candidate_id = $1
|
||||
AND invitation.delivered_at IS NOT NULL
|
||||
AND (
|
||||
$2::timestamptz IS NULL
|
||||
OR (invitation.delivered_at, invitation.id) < (
|
||||
$2::timestamptz,
|
||||
$3::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY invitation.delivered_at DESC, invitation.id DESC
|
||||
LIMIT $4
|
||||
`
|
||||
|
||||
type ListCandidateInvitationsParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
AfterDeliveredAt pgtype.Timestamptz
|
||||
AfterInvitationID pgtype.UUID
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
type ListCandidateInvitationsRow 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
|
||||
OrganizationName string
|
||||
}
|
||||
|
||||
// One bounded page of the candidate's inbox: every invitation delivered to
|
||||
// the candidate, in any later state, newest first by delivery time. Drafts
|
||||
// have no delivery and are never listed. The candidate scopes the rows, so
|
||||
// no identifier of another candidate can appear.
|
||||
func (q *Queries) ListCandidateInvitations(ctx context.Context, arg ListCandidateInvitationsParams) ([]ListCandidateInvitationsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listCandidateInvitations,
|
||||
arg.CandidateID,
|
||||
arg.AfterDeliveredAt,
|
||||
arg.AfterInvitationID,
|
||||
arg.RowLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListCandidateInvitationsRow
|
||||
for rows.Next() {
|
||||
var i ListCandidateInvitationsRow
|
||||
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,
|
||||
&i.OrganizationName,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const readCandidateInvitation = `-- name: ReadCandidateInvitation :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.candidate_id = $1
|
||||
AND invitation.id = $2
|
||||
AND invitation.delivered_at IS NOT NULL
|
||||
`
|
||||
|
||||
type ReadCandidateInvitationParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
InvitationID pgtype.UUID
|
||||
}
|
||||
|
||||
type ReadCandidateInvitationRow 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 delivered invitation addressed to the candidate. A draft and an
|
||||
// invitation of another candidate find nothing.
|
||||
func (q *Queries) ReadCandidateInvitation(ctx context.Context, arg ReadCandidateInvitationParams) (ReadCandidateInvitationRow, error) {
|
||||
row := q.db.QueryRow(ctx, readCandidateInvitation, arg.CandidateID, arg.InvitationID)
|
||||
var i ReadCandidateInvitationRow
|
||||
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
|
||||
}
|
||||
@@ -609,6 +609,14 @@ type InvitationEvent struct {
|
||||
OccurredAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type InvitationSendResult struct {
|
||||
ScopeHash []byte
|
||||
OrganizationID pgtype.UUID
|
||||
InvitationID pgtype.UUID
|
||||
Outcome string
|
||||
Snapshot []byte
|
||||
}
|
||||
|
||||
type InvitationTermsVersion struct {
|
||||
InvitationID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
|
||||
@@ -201,6 +201,11 @@ type Querier interface {
|
||||
// The restricting foreign key is checked at the end of the statement, after
|
||||
// these rows are gone.
|
||||
DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error)
|
||||
// The conditional update is the compare-and-swap of a send: it applies only to
|
||||
// a draft whose version is still the one the caller read, records the first
|
||||
// delivery with its deadline, and advances the version by one. No row is
|
||||
// returned when it lost a race or the invitation is no longer a draft.
|
||||
DeliverInvitation(ctx context.Context, arg DeliverInvitationParams) (pgtype.UUID, error)
|
||||
// Lock order. Every transaction that writes mail_quota_usage first creates
|
||||
// and locks all the usage rows it will touch with EnsureMailQuotaRows and
|
||||
// LockMailQuotaRows, which both work in (period_kind, period_start) order,
|
||||
@@ -297,6 +302,7 @@ type Querier interface {
|
||||
// Explains why ConsumeEmailToken matched no row.
|
||||
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
|
||||
GetInvitationCreationResult(ctx context.Context, scopeHash []byte) (string, error)
|
||||
GetInvitationSendResult(ctx context.Context, scopeHash []byte) (GetInvitationSendResultRow, 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)
|
||||
@@ -472,6 +478,7 @@ type Querier interface {
|
||||
// current terms version is checked when the transaction commits.
|
||||
InsertInvitation(ctx context.Context, arg InsertInvitationParams) error
|
||||
InsertInvitationEvent(ctx context.Context, arg InsertInvitationEventParams) error
|
||||
InsertInvitationSendResult(ctx context.Context, arg InsertInvitationSendResultParams) error
|
||||
InsertInvitationTermsVersion(ctx context.Context, arg InsertInvitationTermsVersionParams) error
|
||||
InsertMailQuotaReservation(ctx context.Context, arg InsertMailQuotaReservationParams) error
|
||||
InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error
|
||||
@@ -592,6 +599,11 @@ type Querier interface {
|
||||
// (hidden_at, organization_id) position of the last record of the previous
|
||||
// page.
|
||||
ListCandidateHiddenOrganizations(ctx context.Context, arg ListCandidateHiddenOrganizationsParams) ([]ListCandidateHiddenOrganizationsRow, error)
|
||||
// One bounded page of the candidate's inbox: every invitation delivered to
|
||||
// the candidate, in any later state, newest first by delivery time. Drafts
|
||||
// have no delivery and are never listed. The candidate scopes the rows, so
|
||||
// no identifier of another candidate can appear.
|
||||
ListCandidateInvitations(ctx context.Context, arg ListCandidateInvitationsParams) ([]ListCandidateInvitationsRow, error)
|
||||
// The same selection for the candidate's own card preview, so the candidate
|
||||
// sees what an organization would read. It is scoped by the owner and runs
|
||||
// after the caller locked the effective C2 and publication; it does not apply
|
||||
@@ -831,6 +843,9 @@ type Querier interface {
|
||||
// Deletes at most batch_limit expired records. Locked rows are skipped, so
|
||||
// the statement never waits for a concurrent reservation.
|
||||
PurgeExpiredIdempotencyRecords(ctx context.Context, arg PurgeExpiredIdempotencyRecordsParams) (int64, error)
|
||||
// Read one delivered invitation addressed to the candidate. A draft and an
|
||||
// invitation of another candidate find nothing.
|
||||
ReadCandidateInvitation(ctx context.Context, arg ReadCandidateInvitationParams) (ReadCandidateInvitationRow, error)
|
||||
// Queries of the candidate visibility settings: the publication of
|
||||
// the card, the search status, the hidden organizations, and the history of
|
||||
// these settings. Every statement is scoped by the candidate's user_id, and
|
||||
|
||||
@@ -6,18 +6,27 @@ import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/config"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/companyquota"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
"lincodex/backend/internal/usecase/invitation"
|
||||
"lincodex/backend/internal/usecase/notification"
|
||||
"lincodex/backend/internal/usecase/notification/mailtemplate"
|
||||
)
|
||||
|
||||
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.
|
||||
// newInvitationHandler builds the invitation 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. A send
|
||||
// charges the shared company quota and records its notification and email
|
||||
// through the outbox of the same transaction.
|
||||
func newInvitationHandler(
|
||||
ctx context.Context,
|
||||
settings config.Config,
|
||||
@@ -45,8 +54,23 @@ func newInvitationHandler(
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newInvitationHandler - create view service: %w", err)
|
||||
}
|
||||
renderer, err := mailtemplate.NewRenderer(settings.AppPublicURL)
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newInvitationHandler - create mail renderer: %w", err)
|
||||
}
|
||||
notifier, err := notification.NewInvitationNotifier(notification.NewMailRequester(notification.NewTemplateRenderer(renderer), time.Now))
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newInvitationHandler - create notifier: %w", err)
|
||||
}
|
||||
quota := companyquota.NewService(time.Now)
|
||||
service, err := invitation.NewService(invitation.Dependencies{
|
||||
Transactor: transactor, Keyring: keyring, PseudonymKey: key, Candidates: views.ResolveCandidateHandle, Clock: time.Now,
|
||||
Transactor: transactor, Keyring: keyring, PseudonymKey: key, Candidates: views.ResolveCandidateHandle,
|
||||
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
return quota.ReserveInvitation(ctx, unit, organization, invitationID)
|
||||
},
|
||||
Notifier: notifier, Clock: time.Now,
|
||||
})
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
|
||||
@@ -232,7 +232,11 @@ func RestoreInvitation(stored StoredInvitation) (Invitation, error) {
|
||||
return Invitation{}, fmt.Errorf("%s - validate terms: %w", location, err)
|
||||
}
|
||||
stored.Terms = stored.Terms.Clone()
|
||||
// Every time of an invitation is kept in UTC, whatever the time zone of
|
||||
// the storage session, so a response is the same after a read.
|
||||
stored.CreatedAt, stored.UpdatedAt = stored.CreatedAt.UTC(), stored.UpdatedAt.UTC()
|
||||
stored.ResponseDeadlineAt, stored.DeliveredAt = utcInvitationTime(stored.ResponseDeadlineAt), utcInvitationTime(stored.DeliveredAt)
|
||||
stored.ViewedAt, stored.RespondedAt = utcInvitationTime(stored.ViewedAt), utcInvitationTime(stored.RespondedAt)
|
||||
if stored.Need != nil {
|
||||
need := *stored.Need
|
||||
stored.Need = &need
|
||||
@@ -286,6 +290,14 @@ func storedInvitationLifecycleDefect(stored StoredInvitation) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func utcInvitationTime(value *time.Time) *time.Time {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
converted := value.UTC()
|
||||
return &converted
|
||||
}
|
||||
|
||||
func validInvitationTime(value time.Time) bool {
|
||||
return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// InvitationEventDelivered is the audit event of a send. Sending itself is an
|
||||
// internal step and never a state: the event records the version at which
|
||||
// the draft became a delivered invitation.
|
||||
const InvitationEventDelivered InvitationEventKind = "delivered"
|
||||
|
||||
// IsDelivered reports whether the invitation has reached the candidate's
|
||||
// inbox. A delivery is never undone, so every later state keeps it.
|
||||
func (invitation Invitation) IsDelivered() bool { return invitation.record.DeliveredAt != nil }
|
||||
|
||||
// Deliver returns the draft as the next version in the state delivered. The
|
||||
// response deadline starts at the delivery: deliveredAt plus the response
|
||||
// period of the draft, in whole calendar days. The deadline is fixed here and
|
||||
// nothing else moves it, so a notification or its retries cannot change it.
|
||||
func (invitation Invitation) Deliver(deliveredAt time.Time) (Invitation, error) {
|
||||
const location = "Invitation.Deliver"
|
||||
if invitation.State() != InvitationDraft || invitation.IsDelivered() {
|
||||
return Invitation{}, fmt.Errorf("%s - only an unsent draft can be delivered: %w", location, ErrInvitationNotDraft)
|
||||
}
|
||||
if !validInvitationTime(deliveredAt) || deliveredAt.Before(invitation.record.UpdatedAt) {
|
||||
return Invitation{}, fmt.Errorf("%s - delivery time must be set and not before the last change: %w", location, ErrInvalidInvitation)
|
||||
}
|
||||
deliveredAt = deliveredAt.UTC()
|
||||
deadline := deliveredAt.Add(CalendarDays(invitation.record.ResponsePeriodDays).Duration())
|
||||
next := invitation.Stored()
|
||||
next.State = string(InvitationDelivered)
|
||||
next.Version++
|
||||
next.UpdatedAt = deliveredAt
|
||||
next.DeliveredAt = &deliveredAt
|
||||
next.ResponseDeadlineAt = &deadline
|
||||
delivered, err := RestoreInvitation(next)
|
||||
if err != nil {
|
||||
return Invitation{}, fmt.Errorf("%s - restore delivered invitation: %w", location, err)
|
||||
}
|
||||
return delivered, nil
|
||||
}
|
||||
|
||||
// DeliveryEvent builds the audit event of the delivered version this
|
||||
// invitation has just reached. It names the actor who sent it and no field.
|
||||
func (invitation Invitation) DeliveryEvent(actorID uuid.UUID) (InvitationEvent, error) {
|
||||
const location = "Invitation.DeliveryEvent"
|
||||
if actorID == uuid.Nil {
|
||||
return InvitationEvent{}, fmt.Errorf("%s - actor must be set: %w", location, ErrInvalidInvitation)
|
||||
}
|
||||
if invitation.State() != InvitationDelivered || !invitation.IsDelivered() {
|
||||
return InvitationEvent{}, fmt.Errorf("%s - the invitation must be delivered: %w", location, ErrInvalidInvitation)
|
||||
}
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return InvitationEvent{}, fmt.Errorf("%s - generate event ID: %w", location, err)
|
||||
}
|
||||
return InvitationEvent{
|
||||
ID: id, InvitationID: invitation.record.ID, OrganizationID: invitation.record.OrganizationID,
|
||||
Version: invitation.record.Version, TermsVersion: invitation.record.TermsVersion, Kind: InvitationEventDelivered,
|
||||
ActorID: actorID, ChangedFields: []InvitationChangedField{}, OccurredAt: *invitation.record.DeliveredAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// InvitationOrganizationRef names the organization that sent an invitation,
|
||||
// as the candidate sees it.
|
||||
type InvitationOrganizationRef struct {
|
||||
ID uuid.UUID
|
||||
Name string
|
||||
}
|
||||
|
||||
// CandidateInvitationSummary is an invitation in the inbox of the candidate it
|
||||
// is addressed to: the organization, the state, the versions, the role, the
|
||||
// salary range, the work formats, and the deadline. It has no candidate
|
||||
// identifier, handle, need, or salary indicator.
|
||||
type CandidateInvitationSummary struct {
|
||||
ID uuid.UUID
|
||||
Organization InvitationOrganizationRef
|
||||
State InvitationState
|
||||
ExpiryReason *InvitationExpiryReason
|
||||
Version int64
|
||||
TermsVersion int64
|
||||
RoleTitle string
|
||||
Salary SalaryRange
|
||||
WorkFormats []NeedWorkFormat
|
||||
ResponseDeadlineAt time.Time
|
||||
DeliveredAt time.Time
|
||||
ViewedAt *time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// CandidateSummary returns the inbox entry of a delivered invitation for the
|
||||
// organization that sent it.
|
||||
func (invitation Invitation) CandidateSummary(organization InvitationOrganizationRef) (CandidateInvitationSummary, error) {
|
||||
const location = "Invitation.CandidateSummary"
|
||||
stored := invitation.Stored()
|
||||
if stored.DeliveredAt == nil || stored.ResponseDeadlineAt == nil {
|
||||
return CandidateInvitationSummary{}, fmt.Errorf("%s - only a delivered invitation is in the inbox: %w", location, ErrInvalidInvitation)
|
||||
}
|
||||
if organization.ID != stored.OrganizationID || organization.Name == "" {
|
||||
return CandidateInvitationSummary{}, fmt.Errorf("%s - the organization must be the sender: %w", location, ErrInvalidInvitation)
|
||||
}
|
||||
snapshot := invitation.Snapshot()
|
||||
return CandidateInvitationSummary{
|
||||
ID: stored.ID, Organization: organization, State: snapshot.State, ExpiryReason: snapshot.ExpiryReason,
|
||||
Version: stored.Version, TermsVersion: stored.TermsVersion, RoleTitle: stored.Terms.RoleTitle,
|
||||
Salary: stored.Terms.Salary, WorkFormats: stored.Terms.WorkFormats,
|
||||
ResponseDeadlineAt: stored.ResponseDeadlineAt.UTC(), DeliveredAt: stored.DeliveredAt.UTC(),
|
||||
ViewedAt: stored.ViewedAt, UpdatedAt: stored.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (summary CandidateInvitationSummary) String() string { return redactedInvitation }
|
||||
func (summary CandidateInvitationSummary) GoString() string { return redactedInvitation }
|
||||
func (summary CandidateInvitationSummary) Format(state fmt.State, _ rune) {
|
||||
writeRedacted(state, redactedInvitation)
|
||||
}
|
||||
func (summary CandidateInvitationSummary) LogValue() slog.Value {
|
||||
return slog.StringValue(redactedInvitation)
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestDeliverStartsTheDeadlineAtTheDeliveryForEveryPeriod(t *testing.T) {
|
||||
for _, period := range []CalendarDays{3, 7, 14} {
|
||||
input := validInvitationDraftInput()
|
||||
input.Content.ResponsePeriod = period
|
||||
draft, err := NewInvitationDraft(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewInvitationDraft() error = %v", err)
|
||||
}
|
||||
deliveredAt := input.At.Add(time.Hour)
|
||||
delivered, err := draft.Deliver(deliveredAt)
|
||||
if err != nil {
|
||||
t.Fatalf("Deliver(%d days) error = %v", period, err)
|
||||
}
|
||||
snapshot := delivered.Snapshot()
|
||||
if snapshot.State != InvitationDelivered || snapshot.Version != draft.Version()+1 || snapshot.TermsVersion != draft.TermsVersion() ||
|
||||
!snapshot.DeliveredAt.Equal(deliveredAt) || !snapshot.ResponseDeadlineAt.Equal(deliveredAt.Add(time.Duration(period)*24*time.Hour)) ||
|
||||
!snapshot.UpdatedAt.Equal(deliveredAt) || !delivered.IsDelivered() || draft.IsDelivered() {
|
||||
t.Fatalf("delivered %d-day invitation = %+v", period, snapshot)
|
||||
}
|
||||
event, err := delivered.DeliveryEvent(input.ActorID)
|
||||
if err != nil {
|
||||
t.Fatalf("DeliveryEvent() error = %v", err)
|
||||
}
|
||||
if event.Kind != InvitationEventDelivered || event.Version != snapshot.Version || len(event.ChangedFields) != 0 ||
|
||||
!event.OccurredAt.Equal(deliveredAt) {
|
||||
t.Fatalf("delivery event = %+v", event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliverRefusesAnythingButAnUnsentDraft(t *testing.T) {
|
||||
input := validInvitationDraftInput()
|
||||
draft, err := NewInvitationDraft(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewInvitationDraft() error = %v", err)
|
||||
}
|
||||
if _, err := draft.Deliver(input.At.Add(-time.Second)); !errors.Is(err, ErrInvalidInvitation) {
|
||||
t.Fatalf("Deliver(before the last change) error = %v, want ErrInvalidInvitation", err)
|
||||
}
|
||||
delivered, err := draft.Deliver(input.At)
|
||||
if err != nil {
|
||||
t.Fatalf("Deliver() error = %v", err)
|
||||
}
|
||||
if _, err := delivered.Deliver(input.At.Add(time.Hour)); !errors.Is(err, ErrInvitationNotDraft) {
|
||||
t.Fatalf("Deliver(delivered) error = %v, want ErrInvitationNotDraft", err)
|
||||
}
|
||||
if _, err := draft.DeliveryEvent(input.ActorID); !errors.Is(err, ErrInvalidInvitation) {
|
||||
t.Fatalf("DeliveryEvent(draft) error = %v, want ErrInvalidInvitation", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateSummaryCarriesNoCandidateIdentifier(t *testing.T) {
|
||||
input := validInvitationDraftInput()
|
||||
draft, err := NewInvitationDraft(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewInvitationDraft() error = %v", err)
|
||||
}
|
||||
if _, err := draft.CandidateSummary(InvitationOrganizationRef{ID: input.OrganizationID, Name: "Sender"}); !errors.Is(err, ErrInvalidInvitation) {
|
||||
t.Fatalf("CandidateSummary(draft) error = %v, want ErrInvalidInvitation", err)
|
||||
}
|
||||
delivered, err := draft.Deliver(input.At)
|
||||
if err != nil {
|
||||
t.Fatalf("Deliver() error = %v", err)
|
||||
}
|
||||
if _, err := delivered.CandidateSummary(InvitationOrganizationRef{ID: uuid.New(), Name: "Other"}); !errors.Is(err, ErrInvalidInvitation) {
|
||||
t.Fatalf("CandidateSummary(other organization) error = %v, want ErrInvalidInvitation", err)
|
||||
}
|
||||
summary, err := delivered.CandidateSummary(InvitationOrganizationRef{ID: input.OrganizationID, Name: "Sender"})
|
||||
if err != nil {
|
||||
t.Fatalf("CandidateSummary() error = %v", err)
|
||||
}
|
||||
if summary.State != InvitationDelivered || summary.RoleTitle != input.Content.Terms.RoleTitle || !summary.DeliveredAt.Equal(input.At) {
|
||||
t.Fatalf("summary = %+v", summary)
|
||||
}
|
||||
for _, text := range []string{fmt.Sprint(summary), fmt.Sprintf("%+v", summary), fmt.Sprintf("%#v", summary)} {
|
||||
if strings.Contains(text, input.CandidateID.String()) || strings.Contains(text, summary.RoleTitle) {
|
||||
t.Fatalf("formatted summary leaks its content: %s", text)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,10 +24,14 @@ var (
|
||||
// ErrInvitationCreationResultNotFound reports a missing original response
|
||||
// for a live idempotency record.
|
||||
ErrInvitationCreationResultNotFound = errors.New("organization invitation creation result not found")
|
||||
|
||||
// ErrInvitationSendResultNotFound reports a missing outcome of a send for
|
||||
// a live idempotency record.
|
||||
ErrInvitationSendResultNotFound = errors.New("organization invitation send result not found")
|
||||
)
|
||||
|
||||
// MaxInvitationPageSize is the largest organization-scoped page in the
|
||||
// contract.
|
||||
// MaxInvitationPageSize is the largest organization-scoped or candidate page
|
||||
// in the contract.
|
||||
const MaxInvitationPageSize = 100
|
||||
|
||||
// InvitationRepositories exposes the invitation storage bound to one
|
||||
@@ -35,6 +39,7 @@ const MaxInvitationPageSize = 100
|
||||
type InvitationRepositories interface {
|
||||
Invitations() InvitationRepository
|
||||
InvitationCreationResults() InvitationCreationResultRepository
|
||||
InvitationSendResults() InvitationSendResultRepository
|
||||
}
|
||||
|
||||
// InvitationRepository stores invitations, their immutable terms versions, and
|
||||
@@ -69,6 +74,24 @@ type InvitationRepository interface {
|
||||
// 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)
|
||||
|
||||
// Deliver moves a draft to its delivered version in the surrounding
|
||||
// transaction: the invitation row moves from expectedVersion to the
|
||||
// version of next with the delivery time and the deadline of next, and
|
||||
// the audit event is recorded. The terms are not touched. It returns
|
||||
// ErrInvitationVersionConflict when the stored row is not a draft at
|
||||
// expectedVersion.
|
||||
Deliver(ctx context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error
|
||||
|
||||
// ListForCandidate returns one newest-first page of the invitations
|
||||
// delivered to the candidate, in any later state, with the name of the
|
||||
// organization that sent each of them. Drafts are never listed.
|
||||
ListForCandidate(ctx context.Context, query CandidateInvitationListQuery) (CandidateInvitationPage, error)
|
||||
|
||||
// GetForCandidate returns a delivered invitation addressed to the
|
||||
// candidate. A draft, an invitation of another candidate, and an unknown
|
||||
// identifier return ErrInvitationNotFound alike.
|
||||
GetForCandidate(ctx context.Context, candidateID, invitationID uuid.UUID) (domain.Invitation, error)
|
||||
}
|
||||
|
||||
// InvitationCreationResultRepository stores the original response of a
|
||||
@@ -79,6 +102,61 @@ type InvitationCreationResultRepository interface {
|
||||
GetCreationResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (domain.OrganizationInvitationView, error)
|
||||
}
|
||||
|
||||
// InvitationSendOutcome is the stored result of a send under an
|
||||
// Idempotency-Key. The contract stores a success, a missing invitation, and a
|
||||
// state conflict; other failures are not stored.
|
||||
type InvitationSendOutcome string
|
||||
|
||||
const (
|
||||
InvitationSendSent InvitationSendOutcome = "sent"
|
||||
InvitationSendNotFound InvitationSendOutcome = "not_found"
|
||||
InvitationSendStateConflict InvitationSendOutcome = "state_conflict"
|
||||
)
|
||||
|
||||
// InvitationSendResult is the outcome of one send. View is set only for
|
||||
// InvitationSendSent and is the original response.
|
||||
type InvitationSendResult struct {
|
||||
OrganizationID uuid.UUID
|
||||
InvitationID uuid.UUID
|
||||
Outcome InvitationSendOutcome
|
||||
View *domain.OrganizationInvitationView
|
||||
}
|
||||
|
||||
// InvitationSendResultRepository stores the outcome of an idempotent send.
|
||||
// The scope references the generic idempotency record, so the outcome is
|
||||
// removed when that record is purged.
|
||||
type InvitationSendResultRepository interface {
|
||||
SaveSendResult(ctx context.Context, scope [IdempotencyDigestSize]byte, result InvitationSendResult) error
|
||||
GetSendResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (InvitationSendResult, error)
|
||||
}
|
||||
|
||||
// CandidateInvitationListQuery selects one page of one candidate's inbox.
|
||||
type CandidateInvitationListQuery struct {
|
||||
CandidateID uuid.UUID
|
||||
After *CandidateInvitationPosition
|
||||
Limit int32
|
||||
}
|
||||
|
||||
// CandidateInvitationPosition is the stable newest-first ordering key of the
|
||||
// candidate's inbox.
|
||||
type CandidateInvitationPosition struct {
|
||||
DeliveredAt time.Time
|
||||
InvitationID uuid.UUID
|
||||
}
|
||||
|
||||
// CandidateInvitationEntry is one invitation of the candidate's inbox with
|
||||
// the current name of the organization that sent it.
|
||||
type CandidateInvitationEntry struct {
|
||||
Invitation domain.Invitation
|
||||
OrganizationName string
|
||||
}
|
||||
|
||||
// CandidateInvitationPage contains one page of the candidate's inbox.
|
||||
type CandidateInvitationPage struct {
|
||||
Items []CandidateInvitationEntry
|
||||
HasMore bool
|
||||
}
|
||||
|
||||
// InvitationListQuery selects one page within a single organization.
|
||||
type InvitationListQuery struct {
|
||||
OrganizationID uuid.UUID
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package invitation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const listMineLocation = "invitation.Service.ListMine"
|
||||
|
||||
// CandidateListCommand selects one page of the inbox of the session candidate.
|
||||
// The candidate comes only from the session.
|
||||
type CandidateListCommand struct {
|
||||
ActorID uuid.UUID
|
||||
After *outbound.CandidateInvitationPosition
|
||||
Limit int32
|
||||
}
|
||||
|
||||
// CandidatePage is one page of the candidate's inbox, newest first by
|
||||
// delivery time.
|
||||
type CandidatePage struct {
|
||||
Items []domain.CandidateInvitationSummary
|
||||
HasMore bool
|
||||
}
|
||||
|
||||
// ListMine reads one page of the invitations delivered to the session
|
||||
// candidate, in any later state. Listing has no side effect: it records no
|
||||
// view. Drafts and invitations of other candidates are never listed.
|
||||
func (service *Service) ListMine(ctx context.Context, command CandidateListCommand) (CandidatePage, error) {
|
||||
if command.ActorID == uuid.Nil {
|
||||
return CandidatePage{}, fmt.Errorf("%s - actor ID must be set: %w", listMineLocation, ErrForbidden)
|
||||
}
|
||||
if command.Limit < 1 || command.Limit > outbound.MaxInvitationPageSize {
|
||||
return CandidatePage{}, fmt.Errorf("%s - page limit must be 1 to %d: %w", listMineLocation, outbound.MaxInvitationPageSize, ErrInvalidRequest)
|
||||
}
|
||||
var result CandidatePage
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeCandidate(ctx, unit, command.ActorID); err != nil {
|
||||
return err
|
||||
}
|
||||
page, err := unit.Invitations().ListForCandidate(ctx, outbound.CandidateInvitationListQuery{
|
||||
CandidateID: command.ActorID, After: command.After, Limit: command.Limit,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - list invitations: %w", listMineLocation, err)
|
||||
}
|
||||
result = CandidatePage{Items: make([]domain.CandidateInvitationSummary, 0, len(page.Items)), HasMore: page.HasMore}
|
||||
for _, entry := range page.Items {
|
||||
summary, err := entry.Invitation.CandidateSummary(domain.InvitationOrganizationRef{
|
||||
ID: entry.Invitation.OrganizationID(), Name: entry.OrganizationName,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build inbox entry: %w", listMineLocation, err)
|
||||
}
|
||||
result.Items = append(result.Items, summary)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return CandidatePage{}, fmt.Errorf("%s - run transaction: %w", listMineLocation, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// authorizeCandidate requires an existing candidate account with a confirmed
|
||||
// email. An employer account, which has no inbox of invitations, is refused.
|
||||
func authorizeCandidate(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID) error {
|
||||
const location = "invitation.authorizeCandidate"
|
||||
user, err := unit.Users().GetByID(ctx, actorID)
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return fmt.Errorf("%s - require existing candidate account: %w", location, ErrForbidden)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read account: %w", location, err)
|
||||
}
|
||||
if user.Scenario != domain.ScenarioCandidate || !user.EmailVerified() {
|
||||
return fmt.Errorf("%s - require verified candidate account: %w", location, ErrForbidden)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
package invitation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/candidateview"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrSendBlocked reports a send that the state of the invitation or the
|
||||
// current visibility of its candidate does not allow. The API answers 409
|
||||
// state_conflict without telling which rule applied.
|
||||
ErrSendBlocked = errors.New("organization invitation cannot be sent")
|
||||
// ErrInvitationQuotaExceeded reports that the rolling invitation quota of
|
||||
// the organization is spent. QuotaExceededError carries the retry time.
|
||||
ErrInvitationQuotaExceeded = errors.New("organization invitation quota is exhausted")
|
||||
)
|
||||
|
||||
// QuotaExceededError carries only the time when the organization quota frees
|
||||
// room again; it holds no candidate or invitation value.
|
||||
type QuotaExceededError struct{ RetryAt time.Time }
|
||||
|
||||
func (err *QuotaExceededError) Error() string { return ErrInvitationQuotaExceeded.Error() }
|
||||
func (err *QuotaExceededError) Unwrap() error { return ErrInvitationQuotaExceeded }
|
||||
|
||||
const (
|
||||
sendOperation = "organization_invitation.send"
|
||||
sendLocation = "invitation.Service.Send"
|
||||
// maxSendAttempts bounds the repeats of a send after the visible cohort
|
||||
// changed while it was locked, as for a create.
|
||||
maxSendAttempts = 3
|
||||
)
|
||||
|
||||
// SendCommand binds the authenticated actor and the path to one send of the
|
||||
// current terms version of a draft.
|
||||
type SendCommand struct {
|
||||
ActorID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
InvitationID uuid.UUID
|
||||
IdempotencyKey string
|
||||
ExpectedVersion int64
|
||||
}
|
||||
|
||||
type sendRequest struct {
|
||||
fingerprint [outbound.IdempotencyDigestSize]byte
|
||||
scope [outbound.IdempotencyDigestSize]byte
|
||||
record outbound.IdempotencyRecord
|
||||
now time.Time
|
||||
}
|
||||
|
||||
// sendOutcome is what a committed send transaction decided: the invitation,
|
||||
// or a refusal that the contract stores under the key and that the caller
|
||||
// returns after the commit.
|
||||
type sendOutcome struct {
|
||||
view domain.OrganizationInvitationView
|
||||
refusal error
|
||||
}
|
||||
|
||||
// Send delivers the current terms version of a draft to the candidate's
|
||||
// inbox. In one transaction it checks the owner, the key, the invitation, its
|
||||
// version and state, and the current visibility of the candidate, spends one
|
||||
// invitation of the organization quota, records the delivery with its
|
||||
// deadline and the audit event, and writes the outbox events of the
|
||||
// notification. The internal sending step is never visible: a success means
|
||||
// the invitation is already delivered. A send of an invitation that was
|
||||
// already delivered answers with its current state and charges nothing.
|
||||
func (service *Service) Send(ctx context.Context, command SendCommand) (domain.OrganizationInvitationView, error) {
|
||||
request, err := service.prepareSend(command)
|
||||
if err != nil {
|
||||
return domain.OrganizationInvitationView{}, err
|
||||
}
|
||||
var outcome sendOutcome
|
||||
for range maxSendAttempts {
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
outcome, err = service.sendInTransaction(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", sendLocation, err)
|
||||
}
|
||||
if outcome.refusal != nil {
|
||||
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - %w", sendLocation, outcome.refusal)
|
||||
}
|
||||
return outcome.view, nil
|
||||
}
|
||||
|
||||
func (service *Service) prepareSend(command SendCommand) (sendRequest, error) {
|
||||
const location = "invitation.Service.prepareSend"
|
||||
switch {
|
||||
case command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil:
|
||||
return sendRequest{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
|
||||
case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize:
|
||||
return sendRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey)
|
||||
case command.ExpectedVersion < 1:
|
||||
return sendRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: "/expected_version", Reason: "must be positive"})
|
||||
}
|
||||
now, err := service.now(location)
|
||||
if err != nil {
|
||||
return sendRequest{}, err
|
||||
}
|
||||
// The fingerprint covers the path and the body, so one key used for
|
||||
// another invitation or another version is a reused key.
|
||||
canonical := []byte(`{"invitation_id":"` + command.InvitationID.String() + `","expected_version":` +
|
||||
strconv.FormatInt(command.ExpectedVersion, 10) + `}`)
|
||||
principal := command.ActorID.String() + ":" + command.OrganizationID.String()
|
||||
fingerprint := service.keyring.Fingerprint(canonical)
|
||||
scope := service.keyring.IdempotencyScope(sendOperation, command.IdempotencyKey, principal)
|
||||
return sendRequest{
|
||||
fingerprint: fingerprint, scope: scope, now: now,
|
||||
record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention)},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// sendInTransaction follows the order of checks of the contract after the
|
||||
// HTTP boundary: the owner, the key, the invitation (404, stored), the repeat
|
||||
// of a completed send (200), the version (412, not stored), the state and the
|
||||
// visibility of the candidate (409, stored), and the quota (429, not stored).
|
||||
// The locks follow the order of every invitation command: the organization,
|
||||
// the membership, the invitation row, and then the cohort of the cards.
|
||||
func (service *Service) sendInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command SendCommand,
|
||||
request sendRequest,
|
||||
) (sendOutcome, error) {
|
||||
if err := lockOrganizationFirst(ctx, unit, command.OrganizationID, sendLocation); err != nil {
|
||||
return sendOutcome{}, err
|
||||
}
|
||||
if err := authorizeOwner(ctx, unit, command.ActorID, command.OrganizationID, sendLocation); err != nil {
|
||||
return sendOutcome{}, err
|
||||
}
|
||||
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
|
||||
if err != nil {
|
||||
return sendOutcome{}, fmt.Errorf("%s - reserve idempotency record: %w", sendLocation, err)
|
||||
}
|
||||
if !created {
|
||||
return replaySend(ctx, unit, request, command, stored)
|
||||
}
|
||||
if command.InvitationID == uuid.Nil {
|
||||
return service.refuseSend(ctx, unit, command, request, outbound.InvitationSendNotFound)
|
||||
}
|
||||
current, err := unit.Invitations().GetForUpdate(ctx, command.OrganizationID, command.InvitationID)
|
||||
if errors.Is(err, outbound.ErrInvitationNotFound) {
|
||||
return service.refuseSend(ctx, unit, command, request, outbound.InvitationSendNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return sendOutcome{}, fmt.Errorf("%s - lock invitation: %w", sendLocation, err)
|
||||
}
|
||||
if current.IsDelivered() {
|
||||
// A completed send answers with the current invitation, whatever the
|
||||
// key or the version, and charges nothing again.
|
||||
return service.completeSend(ctx, unit, request, current)
|
||||
}
|
||||
if command.ExpectedVersion != current.Version() {
|
||||
return sendOutcome{}, fmt.Errorf("%s - compare expected version: %w", sendLocation, domain.ErrInvitationVersionConflict)
|
||||
}
|
||||
if current.State() != domain.InvitationDraft {
|
||||
return service.refuseSend(ctx, unit, command, request, outbound.InvitationSendStateConflict)
|
||||
}
|
||||
visible, err := service.candidateStillVisible(ctx, unit, command, current)
|
||||
if err != nil {
|
||||
return sendOutcome{}, err
|
||||
}
|
||||
if !visible {
|
||||
return service.refuseSend(ctx, unit, command, request, outbound.InvitationSendStateConflict)
|
||||
}
|
||||
if err := service.chargeQuota(ctx, unit, command, current); err != nil {
|
||||
return sendOutcome{}, err
|
||||
}
|
||||
delivered, err := service.deliver(ctx, unit, command, current, request.now)
|
||||
if err != nil {
|
||||
return sendOutcome{}, err
|
||||
}
|
||||
return service.completeSend(ctx, unit, request, delivered)
|
||||
}
|
||||
|
||||
// candidateStillVisible runs the visibility barrier of the card read again:
|
||||
// a draft keeps its candidate after a revoked publication C2, a hiding of the
|
||||
// organization, or a cohort that fell below its minimum, and none of them may
|
||||
// be bypassed by sending an older draft. The answer does not say which rule
|
||||
// applied.
|
||||
func (service *Service) candidateStillVisible(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command SendCommand,
|
||||
current domain.Invitation,
|
||||
) (bool, error) {
|
||||
handle, err := service.pseudonymKey.ForOrganization(current.OrganizationID(), current.CandidateID())
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s - derive candidate alias: %w", sendLocation, err)
|
||||
}
|
||||
candidateID, err := service.candidates(ctx, unit, command.ActorID, command.OrganizationID, handle)
|
||||
switch {
|
||||
case errors.Is(err, candidateview.ErrCandidateCardNotFound), errors.Is(err, candidateview.ErrInvalidCandidateHandle):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("%s - check candidate visibility: %w", sendLocation, err)
|
||||
}
|
||||
return candidateID == current.CandidateID(), nil
|
||||
}
|
||||
|
||||
// chargeQuota spends one invitation of the organization quota. The charge is
|
||||
// keyed by the invitation, so it is written once; a denial writes nothing and
|
||||
// the whole send rolls back.
|
||||
func (service *Service) chargeQuota(ctx context.Context, unit outbound.UnitOfWork, command SendCommand, current domain.Invitation) error {
|
||||
organization, _, err := unit.Organizations().GetForMember(ctx, command.OrganizationID, command.ActorID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read organization: %w", sendLocation, err)
|
||||
}
|
||||
decision, err := service.quota(ctx, unit, organization, current.ID())
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - reserve invitation quota: %w", sendLocation, err)
|
||||
}
|
||||
if !decision.Allowed {
|
||||
return &QuotaExceededError{RetryAt: decision.RetryAt.UTC()}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// deliver stores the delivered version with its deadline and audit event and
|
||||
// writes the notification events in the same transaction.
|
||||
func (service *Service) deliver(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command SendCommand,
|
||||
current domain.Invitation,
|
||||
now time.Time,
|
||||
) (domain.Invitation, error) {
|
||||
// A clock that stepped back must not deliver before the last change.
|
||||
at := now
|
||||
if at.Before(current.UpdatedAt()) {
|
||||
at = current.UpdatedAt()
|
||||
}
|
||||
delivered, err := current.Deliver(at)
|
||||
if err != nil {
|
||||
return domain.Invitation{}, fmt.Errorf("%s - deliver draft: %w", sendLocation, err)
|
||||
}
|
||||
event, err := delivered.DeliveryEvent(command.ActorID)
|
||||
if err != nil {
|
||||
return domain.Invitation{}, fmt.Errorf("%s - build audit event: %w", sendLocation, err)
|
||||
}
|
||||
if err := unit.Invitations().Deliver(ctx, current.Version(), delivered, event); err != nil {
|
||||
if errors.Is(err, outbound.ErrInvitationVersionConflict) {
|
||||
return domain.Invitation{}, fmt.Errorf("%s - store delivery: %w", sendLocation, domain.ErrInvitationVersionConflict)
|
||||
}
|
||||
return domain.Invitation{}, fmt.Errorf("%s - store delivery: %w", sendLocation, err)
|
||||
}
|
||||
if err := service.notifier.InvitationDelivered(ctx, unit, delivered); err != nil {
|
||||
return domain.Invitation{}, fmt.Errorf("%s - record notification: %w", sendLocation, err)
|
||||
}
|
||||
return delivered, nil
|
||||
}
|
||||
|
||||
// completeSend stores the successful response under the key.
|
||||
func (service *Service) completeSend(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
request sendRequest,
|
||||
invitation domain.Invitation,
|
||||
) (sendOutcome, error) {
|
||||
view, err := service.view(invitation)
|
||||
if err != nil {
|
||||
return sendOutcome{}, err
|
||||
}
|
||||
result := outbound.InvitationSendResult{
|
||||
OrganizationID: invitation.OrganizationID(), InvitationID: invitation.ID(), Outcome: outbound.InvitationSendSent, View: &view,
|
||||
}
|
||||
if err := finishSend(ctx, unit, request, result); err != nil {
|
||||
return sendOutcome{}, err
|
||||
}
|
||||
return sendOutcome{view: view}, nil
|
||||
}
|
||||
|
||||
// refuseSend stores a refusal that the contract keeps under the key and lets
|
||||
// the transaction commit, since nothing else was written.
|
||||
func (service *Service) refuseSend(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command SendCommand,
|
||||
request sendRequest,
|
||||
outcome outbound.InvitationSendOutcome,
|
||||
) (sendOutcome, error) {
|
||||
result := outbound.InvitationSendResult{OrganizationID: command.OrganizationID, InvitationID: command.InvitationID, Outcome: outcome}
|
||||
if err := finishSend(ctx, unit, request, result); err != nil {
|
||||
return sendOutcome{}, err
|
||||
}
|
||||
return sendOutcome{refusal: sendRefusal(outcome)}, nil
|
||||
}
|
||||
|
||||
func finishSend(ctx context.Context, unit outbound.UnitOfWork, request sendRequest, result outbound.InvitationSendResult) error {
|
||||
if err := unit.InvitationSendResults().SaveSendResult(ctx, request.scope, result); err != nil {
|
||||
return fmt.Errorf("%s - store outcome: %w", sendLocation, err)
|
||||
}
|
||||
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
|
||||
return fmt.Errorf("%s - purge expired idempotency records: %w", sendLocation, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sendRefusal(outcome outbound.InvitationSendOutcome) error {
|
||||
if outcome == outbound.InvitationSendNotFound {
|
||||
return outbound.ErrInvitationNotFound
|
||||
}
|
||||
return ErrSendBlocked
|
||||
}
|
||||
|
||||
// replaySend returns the stored outcome of the same request, or refuses a key
|
||||
// used with another request.
|
||||
func replaySend(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
request sendRequest,
|
||||
command SendCommand,
|
||||
stored outbound.IdempotencyRecord,
|
||||
) (sendOutcome, error) {
|
||||
if stored.Fingerprint != request.fingerprint {
|
||||
return sendOutcome{}, fmt.Errorf("%s - compare request fingerprint: %w", sendLocation, ErrIdempotencyKeyReused)
|
||||
}
|
||||
original, err := unit.InvitationSendResults().GetSendResult(ctx, request.scope)
|
||||
if err != nil {
|
||||
return sendOutcome{}, fmt.Errorf("%s - read original outcome: %w", sendLocation, err)
|
||||
}
|
||||
if original.OrganizationID != command.OrganizationID {
|
||||
return sendOutcome{}, fmt.Errorf("%s - validate original outcome: %w", sendLocation, domain.ErrInvalidInvitation)
|
||||
}
|
||||
if original.Outcome != outbound.InvitationSendSent {
|
||||
return sendOutcome{refusal: sendRefusal(original.Outcome)}, nil
|
||||
}
|
||||
if original.View == nil || original.InvitationID != command.InvitationID {
|
||||
return sendOutcome{}, fmt.Errorf("%s - validate original response: %w", sendLocation, domain.ErrInvalidInvitation)
|
||||
}
|
||||
return sendOutcome{view: *original.View}, nil
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package invitation
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// draftFor creates a draft for a new visible candidate and returns it with
|
||||
// the candidate's handle and identifier.
|
||||
func (test *harness) draftFor(t *testing.T, period *int32) (domain.OrganizationInvitationView, string, uuid.UUID) {
|
||||
t.Helper()
|
||||
handle, candidateID := test.showCandidate(t)
|
||||
command := test.createCommand(handle, "create-"+handle)
|
||||
command.ResponsePeriodDays = period
|
||||
view, err := test.service.Create(t.Context(), command)
|
||||
if err != nil {
|
||||
t.Fatalf("Create() error = %v", err)
|
||||
}
|
||||
return view, handle, candidateID
|
||||
}
|
||||
|
||||
func (test *harness) sendCommand(invitationID uuid.UUID, version int64, key string) SendCommand {
|
||||
return SendCommand{
|
||||
ActorID: test.actorID, OrganizationID: test.organizationID, InvitationID: invitationID,
|
||||
IdempotencyKey: key, ExpectedVersion: version,
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendDeliversTheDraftWithTheDeadlineChargeAndNotificationAtOnce(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
threeDays := int32(3)
|
||||
draft, _, _ := test.draftFor(t, &threeDays)
|
||||
sentAt := time.Date(2026, time.October, 9, 11, 0, 0, 0, time.UTC)
|
||||
test.setTime(sentAt)
|
||||
|
||||
view, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-1"))
|
||||
if err != nil {
|
||||
t.Fatalf("Send() error = %v", err)
|
||||
}
|
||||
if view.State != domain.InvitationDelivered || view.Version != draft.Version+1 || view.TermsVersion != draft.TermsVersion ||
|
||||
view.DeliveredAt == nil || !view.DeliveredAt.Equal(sentAt) ||
|
||||
view.ResponseDeadlineAt == nil || !view.ResponseDeadlineAt.Equal(sentAt.Add(3*24*time.Hour)) {
|
||||
t.Fatalf("sent view = %+v, want delivered now with a deadline three days later", view.InvitationSnapshot)
|
||||
}
|
||||
state := test.transactor.snapshot()
|
||||
last := state.events[len(state.events)-1]
|
||||
if last.Kind != domain.InvitationEventDelivered || last.Version != view.Version || last.ActorID != test.actorID || len(last.ChangedFields) != 0 {
|
||||
t.Fatalf("audit event = %+v, want one delivery event of the sent version", last)
|
||||
}
|
||||
if len(state.charged) != 1 || state.charged[0] != draft.ID || len(state.notified) != 1 || state.notified[0] != draft.ID {
|
||||
t.Fatalf("charged %v and notified %v, want the invitation once each", state.charged, state.notified)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendRepeatsReturnTheSameInvitationWithoutASecondChargeOrEvent(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
draft, _, _ := test.draftFor(t, nil)
|
||||
first, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-repeat"))
|
||||
if err != nil {
|
||||
t.Fatalf("Send() error = %v", err)
|
||||
}
|
||||
events := len(test.transactor.snapshot().events)
|
||||
test.setTime(time.Date(2026, time.October, 10, 10, 0, 0, 0, time.UTC))
|
||||
|
||||
replay, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-repeat"))
|
||||
if err != nil || replay.Version != first.Version || !replay.ResponseDeadlineAt.Equal(*first.ResponseDeadlineAt) {
|
||||
t.Fatalf("replay = %+v, %v; want the original response", replay.InvitationSnapshot, err)
|
||||
}
|
||||
// A new key and the older draft version still answer with the current
|
||||
// invitation instead of a version conflict.
|
||||
again, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-repeat-new-key"))
|
||||
if err != nil || again.State != domain.InvitationDelivered || !again.DeliveredAt.Equal(*first.DeliveredAt) {
|
||||
t.Fatalf("repeat with a new key = %+v, %v; want the delivered invitation", again.InvitationSnapshot, err)
|
||||
}
|
||||
state := test.transactor.snapshot()
|
||||
if len(state.charged) != 1 || len(state.notified) != 1 || len(state.events) != events {
|
||||
t.Fatalf("repeats charged %d, notified %d, events %d -> %d; want nothing new", len(state.charged), len(state.notified), events, len(state.events))
|
||||
}
|
||||
other, _, _ := test.draftFor(t, nil)
|
||||
if _, err := test.service.Send(t.Context(), test.sendCommand(other.ID, other.Version, "send-repeat")); !errors.Is(err, ErrIdempotencyKeyReused) {
|
||||
t.Fatalf("Send(same key, other invitation) error = %v, want ErrIdempotencyKeyReused", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendRefusesAStaleVersionWithoutStoringTheOutcome(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
draft, _, _ := test.draftFor(t, nil)
|
||||
if _, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version+1, "send-stale")); !errors.Is(err, domain.ErrInvitationVersionConflict) {
|
||||
t.Fatalf("Send(stale) error = %v, want ErrInvitationVersionConflict", err)
|
||||
}
|
||||
state := test.transactor.snapshot()
|
||||
if len(state.sendResults) != 0 || len(state.charged) != 0 || state.invitations[draft.ID].State() != domain.InvitationDraft {
|
||||
t.Fatalf("a stale send stored %d outcomes and %d charges", len(state.sendResults), len(state.charged))
|
||||
}
|
||||
// Nothing was kept under the key, so the corrected request with the
|
||||
// same key sends the draft.
|
||||
if view, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-stale")); err != nil || view.State != domain.InvitationDelivered {
|
||||
t.Fatalf("Send(after stale) = %v, %v; want delivered", view.State, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendRefusesACandidateWhoIsNoLongerVisibleAndStoresTheRefusal(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
draft, handle, candidateID := test.draftFor(t, nil)
|
||||
delete(test.visible, handle)
|
||||
if _, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-hidden")); !errors.Is(err, ErrSendBlocked) {
|
||||
t.Fatalf("Send(hidden candidate) error = %v, want ErrSendBlocked", err)
|
||||
}
|
||||
state := test.transactor.snapshot()
|
||||
if state.invitations[draft.ID].State() != domain.InvitationDraft || len(state.charged) != 0 || len(state.notified) != 0 {
|
||||
t.Fatal("a refused send changed the draft, charged the quota, or notified")
|
||||
}
|
||||
// The refusal is stored under the key and replayed.
|
||||
test.visible[handle] = candidateID
|
||||
if _, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-hidden")); !errors.Is(err, ErrSendBlocked) {
|
||||
t.Fatalf("Send(replay) error = %v, want the stored ErrSendBlocked", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendAnswersAnUnknownInvitationAsNotFoundAndStoresIt(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
command := test.sendCommand(uuid.New(), 1, "send-unknown")
|
||||
for range 2 {
|
||||
if _, err := test.service.Send(t.Context(), command); !errors.Is(err, outbound.ErrInvitationNotFound) {
|
||||
t.Fatalf("Send(unknown) error = %v, want ErrInvitationNotFound", err)
|
||||
}
|
||||
}
|
||||
if state := test.transactor.snapshot(); len(state.sendResults) != 1 {
|
||||
t.Fatalf("stored %d outcomes, want the one refusal", len(state.sendResults))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendRefusesAnExhaustedQuotaAndKeepsTheDraft(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
test.quotaLeft = 0
|
||||
draft, _, _ := test.draftFor(t, nil)
|
||||
_, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-quota"))
|
||||
limited, ok := errors.AsType[*QuotaExceededError](err)
|
||||
if !ok || !errors.Is(err, ErrInvitationQuotaExceeded) || limited.RetryAt.IsZero() {
|
||||
t.Fatalf("Send(no quota) error = %v, want QuotaExceededError with a retry time", err)
|
||||
}
|
||||
state := test.transactor.snapshot()
|
||||
if state.invitations[draft.ID].State() != domain.InvitationDraft || len(state.sendResults) != 0 || len(state.notified) != 0 {
|
||||
t.Fatal("a refused quota changed the draft or stored the outcome")
|
||||
}
|
||||
// Room in the quota lets the same key send the draft.
|
||||
test.quotaLeft = 1
|
||||
if view, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-quota")); err != nil || view.State != domain.InvitationDelivered {
|
||||
t.Fatalf("Send(after quota) = %v, %v; want delivered", view.State, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListMineShowsOnlyTheDeliveredInvitationsOfTheCandidate(t *testing.T) {
|
||||
test := newHarness(t)
|
||||
sent, _, candidateID := test.draftFor(t, nil)
|
||||
if _, err := test.service.Send(t.Context(), test.sendCommand(sent.ID, sent.Version, "send-list")); err != nil {
|
||||
t.Fatalf("Send() error = %v", err)
|
||||
}
|
||||
verified := time.Date(2026, time.October, 9, 9, 0, 0, 0, time.UTC)
|
||||
test.transactor.state.users[candidateID] = domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &verified}
|
||||
test.draftFor(t, nil)
|
||||
|
||||
page, err := test.service.ListMine(t.Context(), CandidateListCommand{ActorID: candidateID, Limit: 10})
|
||||
if err != nil {
|
||||
t.Fatalf("ListMine() error = %v", err)
|
||||
}
|
||||
if len(page.Items) != 1 || page.Items[0].ID != sent.ID || page.Items[0].State != domain.InvitationDelivered ||
|
||||
page.Items[0].Organization.ID != test.organizationID || page.Items[0].RoleTitle == "" {
|
||||
t.Fatalf("inbox = %+v, want the one delivered invitation", page.Items)
|
||||
}
|
||||
if _, err := test.service.ListMine(t.Context(), CandidateListCommand{ActorID: test.actorID, Limit: 10}); !errors.Is(err, ErrForbidden) {
|
||||
t.Fatalf("ListMine(employer) error = %v, want ErrForbidden", err)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
// 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 applies the owner-only rules of invitation drafts and of
|
||||
// their sending: the terms and their immutable versions, the link to a
|
||||
// candidate card of the organization, the idempotent creation, and the
|
||||
// idempotent send that delivers a draft to the candidate's inbox. It also
|
||||
// lists that inbox for the candidate. The candidate's answers and the contact
|
||||
// grant belong to later operations that build on the same records.
|
||||
package invitation
|
||||
|
||||
import (
|
||||
@@ -60,6 +62,21 @@ type Keyring interface {
|
||||
// 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)
|
||||
|
||||
// InvitationQuota reserves one invitation of the organization quota inside
|
||||
// the caller's transaction. Bootstrap adapts the shared company-quota usecase,
|
||||
// so the verification tiers and their limits stay in one place. Repeating an
|
||||
// invitation that is already charged is allowed without a second charge.
|
||||
type InvitationQuota func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error)
|
||||
|
||||
// DeliveryNotifier records, inside the caller's transaction, the outbox
|
||||
// events that tell the candidate about a delivered invitation: the in-platform
|
||||
// notification and the email. Neither blocks the delivery: the invitation is
|
||||
// in the candidate's inbox when the transaction commits, and an email that
|
||||
// fails or is retried later never changes it.
|
||||
type DeliveryNotifier interface {
|
||||
InvitationDelivered(ctx context.Context, unit outbound.UnitOfWork, invitation domain.Invitation) error
|
||||
}
|
||||
|
||||
// Dependencies configure one stateless invitation service.
|
||||
type Dependencies struct {
|
||||
Transactor outbound.Transactor
|
||||
@@ -69,21 +86,27 @@ type Dependencies struct {
|
||||
// a handle in an invitation is the handle of the card.
|
||||
PseudonymKey domain.CandidateViewPseudonymKey
|
||||
Candidates CandidateResolver
|
||||
Quota InvitationQuota
|
||||
Notifier DeliveryNotifier
|
||||
Clock func() time.Time
|
||||
}
|
||||
|
||||
// Service applies organization-scoped invitation draft commands and reads.
|
||||
// Service applies organization-scoped invitation commands and reads, and the
|
||||
// candidate's read of the own inbox.
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
keyring Keyring
|
||||
pseudonymKey domain.CandidateViewPseudonymKey
|
||||
candidates CandidateResolver
|
||||
quota InvitationQuota
|
||||
notifier DeliveryNotifier
|
||||
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 {
|
||||
if deps.Transactor == nil || deps.Keyring == nil || deps.Candidates == nil || deps.Quota == nil ||
|
||||
deps.Notifier == 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 {
|
||||
@@ -91,7 +114,7 @@ func NewService(deps Dependencies) (*Service, error) {
|
||||
}
|
||||
return &Service{
|
||||
transactor: deps.Transactor, keyring: deps.Keyring, pseudonymKey: deps.PseudonymKey,
|
||||
candidates: deps.Candidates, clock: deps.Clock,
|
||||
candidates: deps.Candidates, quota: deps.Quota, notifier: deps.Notifier, clock: deps.Clock,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -41,7 +41,12 @@ type testState struct {
|
||||
events []domain.InvitationEvent
|
||||
idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord
|
||||
results map[[outbound.IdempotencyDigestSize]byte]domain.OrganizationInvitationView
|
||||
sendResults map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationSendResult
|
||||
needVersions map[[3]string]bool
|
||||
// charged lists the invitations charged against the organization quota,
|
||||
// and notified the delivered invitations that were notified.
|
||||
charged []uuid.UUID
|
||||
notified []uuid.UUID
|
||||
}
|
||||
|
||||
func newTestState() testState {
|
||||
@@ -50,6 +55,7 @@ func newTestState() testState {
|
||||
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{},
|
||||
sendResults: map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationSendResult{},
|
||||
needVersions: map[[3]string]bool{},
|
||||
}
|
||||
}
|
||||
@@ -75,9 +81,14 @@ func (state testState) clone() testState {
|
||||
for scope, result := range state.results {
|
||||
cloned.results[scope] = result
|
||||
}
|
||||
for scope, result := range state.sendResults {
|
||||
cloned.sendResults[scope] = result
|
||||
}
|
||||
for key, found := range state.needVersions {
|
||||
cloned.needVersions[key] = found
|
||||
}
|
||||
cloned.charged = slices.Clone(state.charged)
|
||||
cloned.notified = slices.Clone(state.notified)
|
||||
return cloned
|
||||
}
|
||||
|
||||
@@ -129,6 +140,9 @@ func (unit *testUnit) Invitations() outbound.InvitationRepository {
|
||||
func (unit *testUnit) InvitationCreationResults() outbound.InvitationCreationResultRepository {
|
||||
return testInvitations{state: unit.state, failResultSave: unit.failResultSave}
|
||||
}
|
||||
func (unit *testUnit) InvitationSendResults() outbound.InvitationSendResultRepository {
|
||||
return testInvitations{state: unit.state}
|
||||
}
|
||||
|
||||
type testUsers struct {
|
||||
outbound.UserRepository
|
||||
@@ -158,6 +172,14 @@ func (repository testOrganizations) LockActiveMembership(_ context.Context, orga
|
||||
return membership, nil
|
||||
}
|
||||
|
||||
func (repository testOrganizations) GetForMember(_ context.Context, organizationID, userID uuid.UUID) (domain.Organization, domain.Membership, error) {
|
||||
membership, ok := repository.state.memberships[[2]uuid.UUID{organizationID, userID}]
|
||||
if !ok || !membership.GrantsAccess() {
|
||||
return domain.Organization{}, domain.Membership{}, outbound.ErrOrganizationNotFound
|
||||
}
|
||||
return domain.Organization{}, membership, nil
|
||||
}
|
||||
|
||||
type testQuotas struct {
|
||||
outbound.CompanyQuotaRepository
|
||||
}
|
||||
@@ -194,6 +216,7 @@ func (repository testIdempotency) PurgeExpired(_ context.Context, at time.Time,
|
||||
if !record.ExpiresAt.After(at) {
|
||||
delete(repository.state.idempotency, scope)
|
||||
delete(repository.state.results, scope)
|
||||
delete(repository.state.sendResults, scope)
|
||||
deleted++
|
||||
}
|
||||
}
|
||||
@@ -255,6 +278,52 @@ func (repository testInvitations) SaveDraft(_ context.Context, expectedVersion i
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository testInvitations) Deliver(_ context.Context, expectedVersion int64, next domain.Invitation, 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
|
||||
repository.state.events = append(repository.state.events, event)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository testInvitations) ListForCandidate(_ context.Context, query outbound.CandidateInvitationListQuery) (outbound.CandidateInvitationPage, error) {
|
||||
var items []outbound.CandidateInvitationEntry
|
||||
for _, invitation := range repository.state.invitations {
|
||||
if invitation.CandidateID() == query.CandidateID && invitation.IsDelivered() {
|
||||
items = append(items, outbound.CandidateInvitationEntry{Invitation: invitation, OrganizationName: "Test organization"})
|
||||
}
|
||||
}
|
||||
page := outbound.CandidateInvitationPage{HasMore: len(items) > int(query.Limit)}
|
||||
if page.HasMore {
|
||||
items = items[:query.Limit]
|
||||
}
|
||||
page.Items = items
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (repository testInvitations) GetForCandidate(_ context.Context, candidateID, invitationID uuid.UUID) (domain.Invitation, error) {
|
||||
invitation, ok := repository.state.invitations[invitationID]
|
||||
if !ok || invitation.CandidateID() != candidateID || !invitation.IsDelivered() {
|
||||
return domain.Invitation{}, outbound.ErrInvitationNotFound
|
||||
}
|
||||
return invitation, nil
|
||||
}
|
||||
|
||||
func (repository testInvitations) SaveSendResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, result outbound.InvitationSendResult) error {
|
||||
repository.state.sendResults[scope] = result
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository testInvitations) GetSendResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (outbound.InvitationSendResult, error) {
|
||||
result, ok := repository.state.sendResults[scope]
|
||||
if !ok {
|
||||
return outbound.InvitationSendResult{}, outbound.ErrInvitationSendResultNotFound
|
||||
}
|
||||
return result, 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
|
||||
}
|
||||
@@ -276,8 +345,11 @@ func (repository testInvitations) GetCreationResult(_ context.Context, scope [ou
|
||||
}
|
||||
|
||||
type harness struct {
|
||||
service *Service
|
||||
transactor *testTransactor
|
||||
service *Service
|
||||
transactor *testTransactor
|
||||
// quotaLeft is the number of new invitations the organization quota
|
||||
// still allows.
|
||||
quotaLeft int
|
||||
key domain.CandidateViewPseudonymKey
|
||||
actorID uuid.UUID
|
||||
organizationID uuid.UUID
|
||||
@@ -305,7 +377,7 @@ func newHarness(t *testing.T) *harness {
|
||||
}
|
||||
test := &harness{
|
||||
transactor: &testTransactor{state: state, policy: testPolicyVersion(t, now)},
|
||||
key: key, actorID: actorID, organizationID: organizationID, visible: map[string]uuid.UUID{},
|
||||
key: key, actorID: actorID, organizationID: organizationID, visible: map[string]uuid.UUID{}, quotaLeft: 10,
|
||||
setTime: func(value time.Time) { current = value },
|
||||
}
|
||||
test.service, err = NewService(Dependencies{
|
||||
@@ -317,6 +389,18 @@ func newHarness(t *testing.T) *harness {
|
||||
}
|
||||
return candidateID, nil
|
||||
},
|
||||
Quota: func(_ context.Context, unit outbound.UnitOfWork, _ domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
state := unit.(*testUnit).state
|
||||
if slices.Contains(state.charged, invitationID) {
|
||||
return outbound.CompanyQuotaDecision{Allowed: true, Reused: true}, nil
|
||||
}
|
||||
if len(state.charged) >= test.quotaLeft {
|
||||
return outbound.CompanyQuotaDecision{RetryAt: current.Add(time.Hour)}, nil
|
||||
}
|
||||
state.charged = append(state.charged, invitationID)
|
||||
return outbound.CompanyQuotaDecision{Allowed: true}, nil
|
||||
},
|
||||
Notifier: testNotifier{},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewService() error = %v", err)
|
||||
@@ -337,6 +421,14 @@ func (test *harness) showCandidate(t *testing.T) (string, uuid.UUID) {
|
||||
return handle, candidateID
|
||||
}
|
||||
|
||||
type testNotifier struct{}
|
||||
|
||||
func (testNotifier) InvitationDelivered(_ context.Context, unit outbound.UnitOfWork, invitation domain.Invitation) error {
|
||||
state := unit.(*testUnit).state
|
||||
state.notified = append(state.notified, invitation.ID())
|
||||
return nil
|
||||
}
|
||||
|
||||
func testPolicyVersion(t *testing.T, at time.Time) domain.PolicyVersion {
|
||||
t.Helper()
|
||||
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
|
||||
@@ -543,6 +635,10 @@ func TestOnlyTheActiveOwnerOfAnEmployerAccountMayWorkWithInvitations(t *testing.
|
||||
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)
|
||||
}
|
||||
send := SendCommand{ActorID: tt.actor, OrganizationID: test.organizationID, InvitationID: uuid.New(), IdempotencyKey: "send-" + tt.name, ExpectedVersion: 1}
|
||||
if _, err := test.service.Send(t.Context(), send); !errors.Is(err, tt.want) {
|
||||
t.Errorf("Send() error = %v, want %v", err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
if state := test.transactor.snapshot(); len(state.invitations) != 0 {
|
||||
|
||||
@@ -28,13 +28,14 @@ func NewInboxContentResolver(resolvers map[domain.NotificationInboxSourceType]In
|
||||
}
|
||||
|
||||
// DefaultInboxSourceResolvers lists the source types that have a resolver
|
||||
// today. The synthetic notice resolver is registered only when
|
||||
// syntheticEnabled is true (development and browser-test stands); a stored
|
||||
// synthetic row is then listed without content. The invitation module adds
|
||||
// domain.NotificationInboxSourceInvitation with its own resolver; the
|
||||
// handler, the table, and the API need no change.
|
||||
// today: the delivered invitation, and the synthetic notice. The synthetic
|
||||
// notice resolver is registered only when syntheticEnabled is true
|
||||
// (development and browser-test stands); otherwise a stored synthetic row is
|
||||
// listed without content.
|
||||
func DefaultInboxSourceResolvers(syntheticEnabled bool) map[domain.NotificationInboxSourceType]InboxSourceResolver {
|
||||
resolvers := map[domain.NotificationInboxSourceType]InboxSourceResolver{}
|
||||
resolvers := map[domain.NotificationInboxSourceType]InboxSourceResolver{
|
||||
domain.NotificationInboxSourceInvitation: ResolveInvitationNotice,
|
||||
}
|
||||
if syntheticEnabled {
|
||||
resolvers[domain.NotificationInboxSourceOrganization] = ResolveSyntheticNotice
|
||||
}
|
||||
|
||||
@@ -274,12 +274,63 @@ func TestSyntheticNoticeResolverFollowsTheRecipientStanding(t *testing.T) {
|
||||
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC),
|
||||
})
|
||||
if _, err := resolvers.Resolve(context.Background(), unit, invitation); !errors.Is(err, ErrInboxContentUnavailable) {
|
||||
t.Fatalf("Resolve(source without a resolver) error = %v, want ErrInboxContentUnavailable", err)
|
||||
t.Fatalf("Resolve(invitation the recipient cannot read) error = %v, want ErrInboxContentUnavailable", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveInvitationNoticeNamesTheSenderOnlyWhileVisible(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fixture := newInboxFixture(t, domain.ScenarioCandidate)
|
||||
delivered := fixture.deliveredInvitation(t)
|
||||
entry := fixtureEntry(t, domain.NotificationInboxEntryInput{
|
||||
EventID: uuid.New(), RecipientUserID: fixture.user.ID, OrganizationID: fixture.organizationID,
|
||||
EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1,
|
||||
SourceType: domain.NotificationInboxSourceInvitation, SourceID: delivered.ID(),
|
||||
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC),
|
||||
})
|
||||
resolvers := NewInboxContentResolver(DefaultInboxSourceResolvers(false))
|
||||
content, err := resolvers.Resolve(context.Background(), fixture.unit(), entry)
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve(delivered invitation) error = %v", err)
|
||||
}
|
||||
if content.Title() != invitationNoticeTitle || content.LinkPath() != candidateInvitationsPath ||
|
||||
!strings.Contains(content.Summary(), "«Север»") || !strings.Contains(content.Summary(), "«Inbox role»") {
|
||||
t.Fatalf("invitation content = %q / %q / %q", content.Title(), content.Summary(), content.LinkPath())
|
||||
}
|
||||
if strings.Contains(content.Summary(), fixture.user.ID.String()) {
|
||||
t.Fatal("invitation content names the candidate")
|
||||
}
|
||||
|
||||
// Another recipient and another organization context find nothing.
|
||||
foreign := fixtureEntry(t, domain.NotificationInboxEntryInput{
|
||||
EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: fixture.organizationID,
|
||||
EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1,
|
||||
SourceType: domain.NotificationInboxSourceInvitation, SourceID: delivered.ID(),
|
||||
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC),
|
||||
})
|
||||
if _, err := ResolveInvitationNotice(context.Background(), fixture.unit(), foreign); !errors.Is(err, ErrInboxContentUnavailable) {
|
||||
t.Fatalf("ResolveInvitationNotice(other recipient) error = %v, want ErrInboxContentUnavailable", err)
|
||||
}
|
||||
otherContext := fixtureEntry(t, domain.NotificationInboxEntryInput{
|
||||
EventID: uuid.New(), RecipientUserID: fixture.user.ID, OrganizationID: uuid.New(),
|
||||
EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1,
|
||||
SourceType: domain.NotificationInboxSourceInvitation, SourceID: delivered.ID(),
|
||||
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC),
|
||||
})
|
||||
if _, err := ResolveInvitationNotice(context.Background(), fixture.unit(), otherContext); !errors.Is(err, ErrInboxContentUnavailable) {
|
||||
t.Fatalf("ResolveInvitationNotice(other organization) error = %v, want ErrInboxContentUnavailable", err)
|
||||
}
|
||||
// A hidden organization is no longer named.
|
||||
fixture.repository.organizationName = ""
|
||||
if _, err := ResolveInvitationNotice(context.Background(), fixture.unit(), entry); !errors.Is(err, ErrInboxContentUnavailable) {
|
||||
t.Fatalf("ResolveInvitationNotice(hidden sender) error = %v, want ErrInboxContentUnavailable", err)
|
||||
}
|
||||
}
|
||||
|
||||
type inboxFixture struct {
|
||||
service *InboxService
|
||||
invitations map[uuid.UUID]domain.Invitation
|
||||
repository *memoryInboxRepository
|
||||
resolver *memoryInboxResolver
|
||||
users map[uuid.UUID]domain.User
|
||||
@@ -298,6 +349,7 @@ func newInboxFixtureWithClock(t *testing.T, scenario domain.Scenario, clock func
|
||||
t.Helper()
|
||||
verifiedAt := time.Date(2026, time.October, 1, 10, 0, 0, 0, time.UTC)
|
||||
fixture := &inboxFixture{
|
||||
invitations: map[uuid.UUID]domain.Invitation{},
|
||||
repository: &memoryInboxRepository{organizationName: "Север"},
|
||||
resolver: &memoryInboxResolver{unavailable: map[uuid.UUID]bool{}},
|
||||
users: map[uuid.UUID]domain.User{},
|
||||
@@ -316,6 +368,39 @@ func newInboxFixtureWithClock(t *testing.T, scenario domain.Scenario, clock func
|
||||
|
||||
func (fixture *inboxFixture) unit() outbound.UnitOfWork { return inboxTestUnit{fixture: fixture} }
|
||||
|
||||
// deliveredInvitation stores a delivered invitation of the fixture
|
||||
// organization addressed to the fixture user.
|
||||
func (fixture *inboxFixture) deliveredInvitation(t *testing.T) domain.Invitation {
|
||||
t.Helper()
|
||||
policyID, err := domain.NewPolicyVersionID()
|
||||
if err != nil {
|
||||
t.Fatalf("NewPolicyVersionID() error = %v", err)
|
||||
}
|
||||
none := domain.InvitationPackageItem{Status: domain.InvitationPackageNotProvided}
|
||||
at := time.Date(2026, time.October, 8, 11, 0, 0, 0, time.UTC)
|
||||
draft, err := domain.NewInvitationDraft(domain.NewInvitationDraftInput{
|
||||
ID: uuid.New(), OrganizationID: fixture.organizationID, CandidateID: fixture.user.ID, ActorID: uuid.New(),
|
||||
PolicyVersionID: policyID, At: at,
|
||||
Content: domain.InvitationDraftContent{ResponsePeriod: 7, Terms: domain.InvitationTerms{
|
||||
RoleTitle: "Inbox role", Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle,
|
||||
OfferType: domain.InvitationOfferFullTime, Tasks: []string{"Read the inbox"}, Team: "Inbox team",
|
||||
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},
|
||||
}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewInvitationDraft() error = %v", err)
|
||||
}
|
||||
delivered, err := draft.Deliver(at.Add(time.Minute))
|
||||
if err != nil {
|
||||
t.Fatalf("Deliver() error = %v", err)
|
||||
}
|
||||
fixture.invitations[delivered.ID()] = delivered
|
||||
return delivered
|
||||
}
|
||||
|
||||
func (fixture *inboxFixture) entryInput() domain.NotificationInboxEntryInput {
|
||||
return fixtureEntryInput(fixture.user.ID, fixture.organizationID)
|
||||
}
|
||||
@@ -379,6 +464,25 @@ func (unit inboxTestUnit) Organizations() outbound.OrganizationRepository {
|
||||
func (unit inboxTestUnit) NotificationInbox() outbound.NotificationInboxRepository {
|
||||
return unit.fixture.repository
|
||||
}
|
||||
func (unit inboxTestUnit) Invitations() outbound.InvitationRepository {
|
||||
return inboxTestInvitations{fixture: unit.fixture}
|
||||
}
|
||||
|
||||
type inboxTestInvitations struct {
|
||||
outbound.InvitationRepository
|
||||
|
||||
fixture *inboxFixture
|
||||
}
|
||||
|
||||
// GetForCandidate answers like the real repository: only a delivered
|
||||
// invitation addressed to the candidate is found.
|
||||
func (repository inboxTestInvitations) GetForCandidate(_ context.Context, candidateID, invitationID uuid.UUID) (domain.Invitation, error) {
|
||||
invitation, ok := repository.fixture.invitations[invitationID]
|
||||
if !ok || invitation.CandidateID() != candidateID || !invitation.IsDelivered() {
|
||||
return domain.Invitation{}, outbound.ErrInvitationNotFound
|
||||
}
|
||||
return invitation, nil
|
||||
}
|
||||
|
||||
type inboxTestUsers struct {
|
||||
outbound.UserRepository
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package notification
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/notification/mailtemplate"
|
||||
)
|
||||
|
||||
const (
|
||||
// invitationAggregateType is the aggregate of invitation.delivered, which
|
||||
// is also the source of the inbox content.
|
||||
invitationAggregateType = "invitation"
|
||||
// candidateInvitationsPath is the inbox of invitations in the candidate
|
||||
// cabinet. Both the notification and the email link to it.
|
||||
candidateInvitationsPath = "/candidate/invitations"
|
||||
|
||||
invitationNoticeTitle = "Новое приглашение"
|
||||
// invitationNoticeSummary has one slot for the organization name and one
|
||||
// for the role.
|
||||
invitationNoticeSummary = "Организация «%s» отправила вам приглашение на роль «%s». Условия и срок ответа указаны в разделе «Приглашения»."
|
||||
|
||||
// The email names neither the organization nor the terms: the candidate
|
||||
// reads them in the cabinet, where a hiding or a later change applies.
|
||||
// It never holds a contact or an identifier of the candidate.
|
||||
invitationMailSubject = "Новое приглашение от работодателя"
|
||||
invitationMailBody = "Работодатель отправил вам приглашение на платформе Lincodex. Условия, организация и срок ответа указаны в разделе «Приглашения» личного кабинета кандидата."
|
||||
)
|
||||
|
||||
// InvitationNotifier records the notifications of a delivered invitation in
|
||||
// the transaction of the send: the invitation.delivered event that the inbox
|
||||
// consumer turns into the candidate's notification, and a mail request. The
|
||||
// invitation is delivered when that transaction commits; neither the
|
||||
// notification nor the email, nor any retry of them, changes its state or
|
||||
// deadline.
|
||||
type InvitationNotifier struct {
|
||||
mail *MailRequester
|
||||
}
|
||||
|
||||
// NewInvitationNotifier fails at startup without a mail requester.
|
||||
func NewInvitationNotifier(mail *MailRequester) (*InvitationNotifier, error) {
|
||||
if mail == nil {
|
||||
return nil, errors.New("notification.NewInvitationNotifier - mail requester must be set")
|
||||
}
|
||||
return &InvitationNotifier{mail: mail}, nil
|
||||
}
|
||||
|
||||
// InvitationDelivered appends the inbox event and requests the email through
|
||||
// unit, which must be the transaction that delivered the invitation. The
|
||||
// event payload names the recipient and the organization only, as the inbox
|
||||
// contract requires; it never leaves the internal event bus.
|
||||
func (notifier *InvitationNotifier) InvitationDelivered(ctx context.Context, unit outbound.UnitOfWork, invitation domain.Invitation) error {
|
||||
const location = "InvitationNotifier.InvitationDelivered"
|
||||
if invitation.State() != domain.InvitationDelivered || !invitation.IsDelivered() {
|
||||
return fmt.Errorf("%s - the invitation must be delivered: %w", location, domain.ErrInvalidInvitation)
|
||||
}
|
||||
payload, err := json.Marshal(inboxEventPayload{RecipientUserID: invitation.CandidateID(), OrganizationID: invitation.OrganizationID()})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - encode payload: %w", location, err)
|
||||
}
|
||||
event, err := domain.NewDomainEvent(domain.DomainEventInput{
|
||||
EventType: string(domain.NotificationInboxInvitationDelivered),
|
||||
SchemaVersion: inboxPayloadSchemaVersion,
|
||||
AggregateType: invitationAggregateType,
|
||||
AggregateID: invitation.ID(),
|
||||
AggregateVersion: invitation.Version(),
|
||||
Payload: payload,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build event: %w", location, err)
|
||||
}
|
||||
if err := unit.Outbox().Append(ctx, event); err != nil {
|
||||
return fmt.Errorf("%s - append event: %w", location, err)
|
||||
}
|
||||
if _, err := notifier.mail.RequestNotification(ctx, unit, NotificationRequest{
|
||||
RecipientUserID: invitation.CandidateID(),
|
||||
Notification: mailtemplate.NotificationData{
|
||||
Subject: invitationMailSubject, Body: invitationMailBody, LinkPath: candidateInvitationsPath,
|
||||
},
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - request email: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResolveInvitationNotice resolves the notification of a delivered
|
||||
// invitation from the current invitation and the recipient's current
|
||||
// standing. The recipient must be the candidate it was delivered to, and the
|
||||
// organization is named only while the candidate has not hidden it;
|
||||
// otherwise the entry stays in the list without content.
|
||||
func ResolveInvitationNotice(ctx context.Context, unit outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error) {
|
||||
const location = "notification.ResolveInvitationNotice"
|
||||
invitation, err := unit.Invitations().GetForCandidate(ctx, entry.RecipientUserID(), entry.SourceID())
|
||||
if errors.Is(err, outbound.ErrInvitationNotFound) {
|
||||
return InboxContent{}, ErrInboxContentUnavailable
|
||||
}
|
||||
if err != nil {
|
||||
return InboxContent{}, fmt.Errorf("%s - read invitation: %w", location, err)
|
||||
}
|
||||
if invitation.OrganizationID() != entry.OrganizationID() {
|
||||
return InboxContent{}, ErrInboxContentUnavailable
|
||||
}
|
||||
name, err := unit.NotificationInbox().OrganizationNameForRecipient(ctx, entry.RecipientUserID(), entry.OrganizationID())
|
||||
if errors.Is(err, outbound.ErrNotificationInboxSourceNotVisible) {
|
||||
return InboxContent{}, ErrInboxContentUnavailable
|
||||
}
|
||||
if err != nil {
|
||||
return InboxContent{}, fmt.Errorf("%s - read sender organization: %w", location, err)
|
||||
}
|
||||
content, err := NewInboxContent(invitationNoticeTitle,
|
||||
fmt.Sprintf(invitationNoticeSummary, name, invitation.Snapshot().Terms.RoleTitle), candidateInvitationsPath)
|
||||
if err != nil {
|
||||
// A stored name or role that does not fit the presentation is not
|
||||
// shown.
|
||||
return InboxContent{}, ErrInboxContentUnavailable
|
||||
}
|
||||
return content, nil
|
||||
}
|
||||
Reference in new issue
Block a user