feat: add assessment, privacy and support flows
This commit is contained in:
1 parent
ee3738ee73
commit
e4f24fa202
339 files changed
+56454
-1126
No files matched your search
@@ -0,0 +1,121 @@
|
||||
// Package anonymousprofile builds organization-scoped, privacy-preserving
|
||||
// projections from the candidates that the storage adapter has already
|
||||
// filtered by effective publication and hidden-organization state.
|
||||
package anonymousprofile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var ErrInvalidOrganization = errors.New("anonymous profile organization is invalid")
|
||||
|
||||
type Service struct {
|
||||
reader outbound.PrivacyCohortRepository
|
||||
key domain.CandidateViewPseudonymKey
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
func NewService(reader outbound.PrivacyCohortRepository, key domain.CandidateViewPseudonymKey, clock func() time.Time) *Service {
|
||||
if reader == nil {
|
||||
panic("anonymousprofile.NewService - reader must not be nil")
|
||||
}
|
||||
if clock == nil {
|
||||
panic("anonymousprofile.NewService - clock must not be nil")
|
||||
}
|
||||
return &Service{reader: reader, key: key, clock: clock}
|
||||
}
|
||||
|
||||
// ListVisible returns only candidates whose complete generalized visible
|
||||
// cohort has at least five members. Active organization membership is checked
|
||||
// by the caller; the repository independently enforces publication and
|
||||
// organization hiding in one read statement.
|
||||
func (service *Service) ListVisible(ctx context.Context, organizationID uuid.UUID) ([]domain.AnonymousCandidateViewDTO, error) {
|
||||
const location = "anonymousprofile.Service.ListVisible"
|
||||
if organizationID == uuid.Nil {
|
||||
return nil, fmt.Errorf("%s - organization ID must be set: %w", location, ErrInvalidOrganization)
|
||||
}
|
||||
sources, err := service.reader.ListVisibleCandidateViewSources(ctx, organizationID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - read visible candidate sources: %w", location, err)
|
||||
}
|
||||
return service.ProjectSources(organizationID, sources)
|
||||
}
|
||||
|
||||
// ProjectSources builds a generalized view from a caller-provided current
|
||||
// source snapshot. A transactional reader can lock the source rows first and
|
||||
// reuse that exact snapshot without issuing a second, potentially newer query.
|
||||
func (service *Service) ProjectSources(
|
||||
organizationID uuid.UUID,
|
||||
sources []domain.CandidateViewSource,
|
||||
) ([]domain.AnonymousCandidateViewDTO, error) {
|
||||
const location = "anonymousprofile.Service.ProjectSources"
|
||||
if organizationID == uuid.Nil {
|
||||
return nil, fmt.Errorf("%s - organization ID must be set: %w", location, ErrInvalidOrganization)
|
||||
}
|
||||
asOf := service.clock().UTC()
|
||||
if asOf.IsZero() {
|
||||
return nil, fmt.Errorf("%s - clock returned zero: %w", location, domain.ErrInvalidAnonymousCandidateView)
|
||||
}
|
||||
views := make([]domain.AnonymousCandidateView, 0, len(sources))
|
||||
seenCandidates := make(map[uuid.UUID]struct{}, len(sources))
|
||||
for _, source := range sources {
|
||||
if err := domain.ValidateCandidateViewSource(source); err != nil {
|
||||
return nil, fmt.Errorf("%s - source is invalid: %w", location, domain.ErrInvalidAnonymousCandidateView)
|
||||
}
|
||||
candidateID := source.CandidateID()
|
||||
if _, duplicate := seenCandidates[candidateID]; duplicate {
|
||||
return nil, fmt.Errorf("%s - source list contains a duplicate candidate: %w", location, domain.ErrInvalidAnonymousCandidateView)
|
||||
}
|
||||
seenCandidates[candidateID] = struct{}{}
|
||||
pseudonym, err := service.key.ForOrganization(organizationID, candidateID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - derive candidate alias: %w", location, domain.ErrInvalidAnonymousCandidateView)
|
||||
}
|
||||
view, err := domain.NewAnonymousCandidateView(source.Input(pseudonym, asOf))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - build candidate projection: %w", location, domain.ErrInvalidAnonymousCandidateView)
|
||||
}
|
||||
views = append(views, view)
|
||||
}
|
||||
var err error
|
||||
views, err = domain.GeneralizeAnonymousCandidateCohort(views)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - generalize visible cohort: %w", location, domain.ErrInvalidAnonymousCandidateView)
|
||||
}
|
||||
result := make([]domain.AnonymousCandidateViewDTO, 0, len(views))
|
||||
for _, view := range views {
|
||||
result = append(result, view.DTO())
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// PreviewSource builds the candidate's private card preview with a purpose-
|
||||
// separated alias. It does not apply an organization cohort because no
|
||||
// organization context exists for this read.
|
||||
func (service *Service) PreviewSource(source domain.CandidateViewSource) (domain.AnonymousCandidateViewDTO, error) {
|
||||
const location = "anonymousprofile.Service.PreviewSource"
|
||||
if err := domain.ValidateCandidateViewSource(source); err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - source is invalid: %w", location, domain.ErrInvalidAnonymousCandidateView)
|
||||
}
|
||||
asOf := service.clock().UTC()
|
||||
if asOf.IsZero() {
|
||||
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - clock returned zero: %w", location, domain.ErrInvalidAnonymousCandidateView)
|
||||
}
|
||||
pseudonym, err := service.key.ForCandidatePreview(source.CandidateID())
|
||||
if err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - derive preview alias: %w", location, domain.ErrInvalidAnonymousCandidateView)
|
||||
}
|
||||
view, err := domain.NewAnonymousCandidateView(source.Input(pseudonym, asOf))
|
||||
if err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - build candidate preview: %w", location, err)
|
||||
}
|
||||
return view.DTO(), nil
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package anonymousprofile
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
type privacyCohortReaderFunc func(context.Context, uuid.UUID) ([]domain.CandidateViewSource, error)
|
||||
|
||||
func (reader privacyCohortReaderFunc) ListVisibleCandidateViewSources(ctx context.Context, organizationID uuid.UUID) ([]domain.CandidateViewSource, error) {
|
||||
return reader(ctx, organizationID)
|
||||
}
|
||||
|
||||
func TestListVisibleReturnsOrganizationScopedAliasesAndSuppressesSmallCohort(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
organizationID := uuid.New()
|
||||
candidateIDs := make([]uuid.UUID, 5)
|
||||
sources := make([]domain.CandidateViewSource, 0, len(candidateIDs))
|
||||
fields, err := domain.NewCardFieldSet([]domain.CardField{domain.CardFieldStack})
|
||||
if err != nil {
|
||||
t.Fatalf("NewCardFieldSet() error = %v", err)
|
||||
}
|
||||
for index := range candidateIDs {
|
||||
candidateIDs[index] = uuid.New()
|
||||
profile, err := domain.EmptyCandidateProfile(candidateIDs[index])
|
||||
if err != nil {
|
||||
t.Fatalf("EmptyCandidateProfile() error = %v", err)
|
||||
}
|
||||
source, err := domain.NewCandidateViewSource(
|
||||
candidateIDs[index], fields, domain.CandidateViewProfileFromContent(profile.Content()), nil, nil, nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewSource() error = %v", err)
|
||||
}
|
||||
sources = append(sources, source)
|
||||
}
|
||||
key, err := domain.NewCandidateViewPseudonymKey(bytes.Repeat([]byte("purpose-specific-key"), 2))
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
service := NewService(privacyCohortReaderFunc(func(_ context.Context, got uuid.UUID) ([]domain.CandidateViewSource, error) {
|
||||
if got != organizationID {
|
||||
t.Fatalf("reader organization = %s, want %s", got, organizationID)
|
||||
}
|
||||
return sources, nil
|
||||
}), key, func() time.Time { return time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) })
|
||||
|
||||
views, err := service.ListVisible(context.Background(), organizationID)
|
||||
if err != nil {
|
||||
t.Fatalf("ListVisible() error = %v", err)
|
||||
}
|
||||
if len(views) != 5 {
|
||||
t.Fatalf("ListVisible() returned %d views, want five", len(views))
|
||||
}
|
||||
aliases := make([]string, 0, len(views))
|
||||
for _, view := range views {
|
||||
aliases = append(aliases, view.Pseudonym)
|
||||
}
|
||||
seenAliases := make(map[string]struct{}, len(aliases))
|
||||
for _, alias := range aliases {
|
||||
if _, duplicate := seenAliases[alias]; duplicate {
|
||||
t.Fatalf("pseudonyms are not unique within the organization: %v", aliases)
|
||||
}
|
||||
seenAliases[alias] = struct{}{}
|
||||
}
|
||||
encoded, err := json.Marshal(views)
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal() error = %v", err)
|
||||
}
|
||||
for _, candidateID := range candidateIDs {
|
||||
if bytes.Contains(encoded, []byte(candidateID.String())) {
|
||||
t.Fatalf("organization-facing projection contains source ID %s", candidateID)
|
||||
}
|
||||
}
|
||||
|
||||
otherOrganization := uuid.New()
|
||||
otherService := NewService(privacyCohortReaderFunc(func(context.Context, uuid.UUID) ([]domain.CandidateViewSource, error) {
|
||||
return sources, nil
|
||||
}), key, func() time.Time { return time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) })
|
||||
otherViews, err := otherService.ListVisible(context.Background(), otherOrganization)
|
||||
if err != nil {
|
||||
t.Fatalf("ListVisible(other organization) error = %v", err)
|
||||
}
|
||||
if otherViews[0].Pseudonym == views[0].Pseudonym {
|
||||
t.Fatal("candidate pseudonym was reused across organizations")
|
||||
}
|
||||
|
||||
smallService := NewService(privacyCohortReaderFunc(func(context.Context, uuid.UUID) ([]domain.CandidateViewSource, error) {
|
||||
return sources[:4], nil
|
||||
}), key, time.Now)
|
||||
small, err := smallService.ListVisible(context.Background(), organizationID)
|
||||
if err != nil {
|
||||
t.Fatalf("ListVisible(small cohort) error = %v", err)
|
||||
}
|
||||
if len(small) != 0 {
|
||||
t.Fatalf("small cohort returned %d views, want suppression", len(small))
|
||||
}
|
||||
}
|
||||
|
||||
func TestListVisibleRejectsInvalidScopeAndSourceFailures(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
key, err := domain.NewCandidateViewPseudonymKey(bytes.Repeat([]byte("purpose-specific-key"), 2))
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
service := NewService(privacyCohortReaderFunc(func(context.Context, uuid.UUID) ([]domain.CandidateViewSource, error) {
|
||||
return nil, errors.New("storage unavailable")
|
||||
}), key, time.Now)
|
||||
if _, err := service.ListVisible(context.Background(), uuid.Nil); !errors.Is(err, ErrInvalidOrganization) {
|
||||
t.Fatalf("ListVisible(empty organization) error = %v, want ErrInvalidOrganization", err)
|
||||
}
|
||||
if _, err := service.ListVisible(context.Background(), uuid.New()); err == nil || !strings.Contains(err.Error(), "read visible candidate sources") {
|
||||
t.Fatalf("ListVisible(storage error) = %v, want wrapped read error", err)
|
||||
}
|
||||
|
||||
invalidSourceService := NewService(privacyCohortReaderFunc(func(context.Context, uuid.UUID) ([]domain.CandidateViewSource, error) {
|
||||
return []domain.CandidateViewSource{{}}, nil
|
||||
}), key, time.Now)
|
||||
if _, err := invalidSourceService.ListVisible(context.Background(), uuid.New()); !errors.Is(err, domain.ErrInvalidAnonymousCandidateView) {
|
||||
t.Fatalf("ListVisible(invalid source) error = %v, want invalid projection", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const submitAnswerOperation = "assessment_attempt.answer"
|
||||
|
||||
// SubmitAttemptAnswerCommand is one candidate answer to the current frozen
|
||||
// item. The answer is private and must not be logged.
|
||||
type SubmitAttemptAnswerCommand struct {
|
||||
ActorID uuid.UUID
|
||||
AttemptID domain.AssessmentAttemptID
|
||||
ItemID uuid.UUID
|
||||
ExpectedVersion int64
|
||||
IdempotencyKey string
|
||||
Answer json.RawMessage
|
||||
}
|
||||
|
||||
type canonicalAttemptAnswerBody struct {
|
||||
AttemptID string `json:"attempt_id"`
|
||||
ItemID string `json:"item_id"`
|
||||
ExpectedVersion int64 `json:"expected_version"`
|
||||
Answer json.RawMessage `json:"answer"`
|
||||
}
|
||||
|
||||
// SubmitAnswer persists the current answer and an immutable public response in
|
||||
// one transaction. Raw answer data never enters the idempotency table.
|
||||
func (service *AttemptService) SubmitAnswer(
|
||||
ctx context.Context,
|
||||
command SubmitAttemptAnswerCommand,
|
||||
) (outbound.AssessmentAttemptCommandResult, error) {
|
||||
const location = "AttemptService.SubmitAnswer"
|
||||
if command.ActorID == uuid.Nil {
|
||||
return outbound.AssessmentAttemptCommandResult{}, ErrAttemptForbidden
|
||||
}
|
||||
if command.AttemptID.IsZero() || command.ItemID == uuid.Nil || command.ExpectedVersion < 1 {
|
||||
return outbound.AssessmentAttemptCommandResult{}, attemptFieldError("/expected_version", "must be a positive version and identify one item")
|
||||
}
|
||||
canonicalAnswer, err := domain.CanonicalAssessmentAnswer(command.Answer)
|
||||
if err != nil {
|
||||
return outbound.AssessmentAttemptCommandResult{}, attemptFieldError("/answer", "must match a supported answer format")
|
||||
}
|
||||
body, err := json.Marshal(canonicalAttemptAnswerBody{
|
||||
AttemptID: command.AttemptID.String(), ItemID: command.ItemID.String(), ExpectedVersion: command.ExpectedVersion,
|
||||
Answer: canonicalAnswer,
|
||||
})
|
||||
if err != nil || len(body) > maxAttemptCanonicalBodyBytes {
|
||||
return outbound.AssessmentAttemptCommandResult{}, ErrInvalidAttemptRequest
|
||||
}
|
||||
keyTime, err := assessmentIdempotencyTime(service.clock())
|
||||
if err != nil {
|
||||
return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - validate application time: %w", location, err)
|
||||
}
|
||||
request, err := service.prepareAttemptIdempotency(submitAnswerOperation, command.IdempotencyKey, command.ActorID, body, keyTime)
|
||||
if err != nil {
|
||||
return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - prepare idempotency: %w", location, err)
|
||||
}
|
||||
var result outbound.AssessmentAttemptCommandResult
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - reserve idempotency: %w", location, err)
|
||||
}
|
||||
repository := unit.AssessmentAttempts()
|
||||
if !created {
|
||||
return replayAttemptAnswer(ctx, repository, request, stored, &result)
|
||||
}
|
||||
if err := repository.DeleteExpiredOutcome(ctx, request.scope); err != nil {
|
||||
return fmt.Errorf("%s - remove expired answer response: %w", location, err)
|
||||
}
|
||||
return service.submitNewAnswer(ctx, unit, repository, request.scope, command, &result)
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func replayAttemptAnswer(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentAttemptRepository,
|
||||
request attemptIdempotencyRequest,
|
||||
stored outbound.IdempotencyRecord,
|
||||
result *outbound.AssessmentAttemptCommandResult,
|
||||
) error {
|
||||
const location = "assessment.replayAttemptAnswer"
|
||||
if stored.Fingerprint != request.record.Fingerprint {
|
||||
return fmt.Errorf("%s - compare request fingerprint: %w", location, ErrAttemptKeyReused)
|
||||
}
|
||||
outcome, err := repository.GetAnswerOutcome(ctx, request.scope)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read immutable answer response: %w", location, err)
|
||||
}
|
||||
*result = outbound.AssessmentAttemptCommandResult{Outcome: outcome, Replayed: true}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service *AttemptService) submitNewAnswer(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repository outbound.AssessmentAttemptRepository,
|
||||
scope outbound.AssessmentAttemptIdempotencyScope,
|
||||
command SubmitAttemptAnswerCommand,
|
||||
result *outbound.AssessmentAttemptCommandResult,
|
||||
) error {
|
||||
const location = "AttemptService.submitNewAnswer"
|
||||
current, err := lockAttemptForAnswer(ctx, unit, repository, command.ActorID, command.AttemptID)
|
||||
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
||||
return storeAttemptCommandProblem(ctx, repository, scope, "answer", 404, result)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
|
||||
}
|
||||
if !attemptHasItem(current, command.ItemID) {
|
||||
return attemptFieldError("/item_id", "does not identify an item in this attempt")
|
||||
}
|
||||
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read database time after consent and attempt locks: %w", location, err)
|
||||
}
|
||||
databaseTime = databaseTime.UTC().Truncate(time.Microsecond)
|
||||
return service.persistSubmittedAnswer(ctx, repository, scope, command, current, databaseTime, result)
|
||||
}
|
||||
|
||||
func lockAttemptForAnswer(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repository outbound.AssessmentAttemptRepository,
|
||||
actorID uuid.UUID,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
) (domain.AssessmentAttempt, error) {
|
||||
const location = "AttemptService.lockAttemptForAnswer"
|
||||
kind, err := repository.GetKindForCandidate(ctx, actorID, attemptID)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
||||
return domain.AssessmentAttempt{}, outbound.ErrAssessmentAttemptNotFound
|
||||
}
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err)
|
||||
}
|
||||
if err := lockSessionConsent(ctx, unit, actorID, kind); err != nil {
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - authorize answer: %w", location, err)
|
||||
}
|
||||
current, err := repository.GetForCandidateForUpdate(ctx, actorID, attemptID)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
||||
return domain.AssessmentAttempt{}, outbound.ErrAssessmentAttemptNotFound
|
||||
}
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
|
||||
}
|
||||
if current.Kind() != kind {
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt kind changed: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func (service *AttemptService) persistSubmittedAnswer(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentAttemptRepository,
|
||||
scope outbound.AssessmentAttemptIdempotencyScope,
|
||||
command SubmitAttemptAnswerCommand,
|
||||
current domain.AssessmentAttempt,
|
||||
databaseTime time.Time,
|
||||
result *outbound.AssessmentAttemptCommandResult,
|
||||
) error {
|
||||
const location = "AttemptService.persistSubmittedAnswer"
|
||||
updated, changed, submitErr := current.SubmitAnswer(command.ExpectedVersion, command.ItemID, command.Answer, databaseTime)
|
||||
if submitErr != nil && errors.Is(submitErr, domain.ErrAssessmentAttemptNotActive) && command.ExpectedVersion == current.Version() {
|
||||
expired, expiredChanged, expireErr := current.ExpireIfDue(databaseTime)
|
||||
if expireErr != nil {
|
||||
return fmt.Errorf("%s - apply due deadline transition: %w", location, expireErr)
|
||||
}
|
||||
if expiredChanged {
|
||||
if err := repository.SaveTransition(ctx, current, expired); err != nil {
|
||||
return fmt.Errorf("%s - persist due deadline transition: %w", location, err)
|
||||
}
|
||||
return storeAttemptCommandProblem(ctx, repository, scope, "answer", 409, result)
|
||||
}
|
||||
}
|
||||
if submitErr != nil {
|
||||
if errors.Is(submitErr, domain.ErrAssessmentAttemptNotActive) {
|
||||
return storeAttemptCommandProblem(ctx, repository, scope, "answer", 409, result)
|
||||
}
|
||||
return mapAttemptAnswerError(submitErr)
|
||||
}
|
||||
if changed {
|
||||
if err := repository.SaveAnswer(ctx, current, updated, command.ItemID); err != nil {
|
||||
return fmt.Errorf("%s - persist answer and attempt transition: %w", location, err)
|
||||
}
|
||||
}
|
||||
outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: updated.PublicSnapshot()}
|
||||
if err := repository.SaveAnswerOutcome(ctx, scope, outcome); err != nil {
|
||||
return fmt.Errorf("%s - store immutable answer response: %w", location, err)
|
||||
}
|
||||
*result = outbound.AssessmentAttemptCommandResult{Outcome: outcome}
|
||||
return nil
|
||||
}
|
||||
|
||||
func attemptHasItem(attempt domain.AssessmentAttempt, itemID uuid.UUID) bool {
|
||||
for _, item := range attempt.Snapshot().Items {
|
||||
if item.ID == itemID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func mapAttemptAnswerError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrAssessmentAttemptVersionConflict), errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict):
|
||||
return fmt.Errorf("AttemptService.SubmitAnswer - check expected version: %w", ErrAttemptVersionConflict)
|
||||
case errors.Is(err, domain.ErrAssessmentAttemptNotActive):
|
||||
return fmt.Errorf("AttemptService.SubmitAnswer - check answer state: %w", ErrAttemptStateConflict)
|
||||
case errors.Is(err, domain.ErrInvalidAssessmentAttempt):
|
||||
return attemptFieldError("/answer", "does not match the current item")
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,517 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var ErrAssessmentAvailabilityNotImplemented = errors.New("assessment availability is not implemented for the effective policy")
|
||||
|
||||
type AvailabilityStatus string
|
||||
|
||||
const (
|
||||
AvailabilityStatusAvailable AvailabilityStatus = "available"
|
||||
AvailabilityStatusActiveAttempt AvailabilityStatus = "active_attempt"
|
||||
AvailabilityStatusCooldown AvailabilityStatus = "cooldown"
|
||||
AvailabilityStatusInsufficientBank AvailabilityStatus = "insufficient_bank"
|
||||
)
|
||||
|
||||
type AssessmentAvailability struct {
|
||||
Specializations []SpecializationAvailability
|
||||
}
|
||||
|
||||
type SpecializationAvailability struct {
|
||||
Specialization domain.SpecializationCode
|
||||
ConfirmedGrade *domain.GradeCode
|
||||
ActiveAttemptID *domain.AssessmentAttemptID
|
||||
Grades []GradeAvailability
|
||||
}
|
||||
|
||||
type GradeAvailability struct {
|
||||
Grade domain.GradeCode
|
||||
Status AvailabilityStatus
|
||||
Mode *domain.AssessmentRealMode
|
||||
AvailableAt *time.Time
|
||||
TimeLimitSeconds *int32
|
||||
MaxSessions *int32
|
||||
MaxItems *int32
|
||||
PracticeRequired *bool
|
||||
}
|
||||
|
||||
// GetMyAssessmentAvailability is a read-only candidate preflight. All
|
||||
// repositories run under one repeatable-read snapshot so policy, bank,
|
||||
// questionnaire, attempts, and disclosed families agree on one database view.
|
||||
func (service *AttemptService) GetMyAssessmentAvailability(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
) (AssessmentAvailability, error) {
|
||||
const location = "AttemptService.GetMyAssessmentAvailability"
|
||||
var availability AssessmentAvailability
|
||||
err := service.snapshotExecutor.WithinReadOnlySnapshot(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireAttemptCandidate(ctx, unit, userID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
now, err := unit.AssessmentBank().DatabaseTime(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read snapshot database time: %w", location, err)
|
||||
}
|
||||
now = now.UTC().Truncate(time.Microsecond)
|
||||
assessmentPolicy, err := readAvailabilityPolicy(ctx, unit, now)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read effective assessment policy: %w", location, err)
|
||||
}
|
||||
questionnaire, err := unit.CandidateQuestionnaires().Get(ctx, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read candidate questionnaire: %w", location, err)
|
||||
}
|
||||
availability, err = buildAssessmentAvailability(ctx, unit, userID, now, assessmentPolicy, questionnaire)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build assessment availability: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return AssessmentAvailability{}, fmt.Errorf("%s - read snapshot: %w", location, err)
|
||||
}
|
||||
return availability, nil
|
||||
}
|
||||
|
||||
func readAvailabilityPolicy(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
now time.Time,
|
||||
) (domain.AssessmentPolicy, error) {
|
||||
const location = "assessment.readAvailabilityPolicy"
|
||||
version, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, now)
|
||||
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
|
||||
return domain.AssessmentPolicy{}, fmt.Errorf("%s - no effective assessment policy: %w", location, ErrAssessmentAvailabilityNotImplemented)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentPolicy{}, err
|
||||
}
|
||||
policy := version.Policy().Assessment
|
||||
if policy.Attempt == nil || policy.Attempt.RealMode != domain.AssessmentRealModeDemoBasic {
|
||||
return domain.AssessmentPolicy{}, fmt.Errorf("%s - effective real assessment mode is not implemented: %w", location, ErrAssessmentAvailabilityNotImplemented)
|
||||
}
|
||||
return policy, nil
|
||||
}
|
||||
|
||||
type assessmentAvailabilityReads struct {
|
||||
selections []outbound.AssessmentAvailabilitySelection
|
||||
active map[domain.SpecializationCode]outbound.AssessmentActiveAttemptSummary
|
||||
rootHistory map[domain.SpecializationCode][]outbound.AssessmentRootAvailabilitySummary
|
||||
quota outbound.AssessmentRootQuotaSnapshot
|
||||
seen map[domain.AssessmentFamilyKey]struct{}
|
||||
}
|
||||
|
||||
func buildAssessmentAvailability(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
userID uuid.UUID,
|
||||
now time.Time,
|
||||
policy domain.AssessmentPolicy,
|
||||
questionnaire domain.CandidateQuestionnaire,
|
||||
) (AssessmentAvailability, error) {
|
||||
reads, err := readAssessmentAvailability(ctx, unit, userID, now, policy, questionnaire)
|
||||
if err != nil {
|
||||
return AssessmentAvailability{}, err
|
||||
}
|
||||
seconds, err := assessmentLimitSeconds(policy.Attempt.Lifetime.Duration())
|
||||
if err != nil {
|
||||
return AssessmentAvailability{}, err
|
||||
}
|
||||
itemCount := policy.StopRule.MaxScoredItems + policy.StopRule.SeedItems
|
||||
result := AssessmentAvailability{Specializations: make([]SpecializationAvailability, 0, len(questionnaire.Specializations()))}
|
||||
for _, answer := range questionnaire.Specializations() {
|
||||
result.Specializations = append(result.Specializations, buildSpecializationAvailability(
|
||||
answer, reads, policy, now, seconds, itemCount,
|
||||
))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func assessmentLimitSeconds(duration time.Duration) (int32, error) {
|
||||
seconds := duration / time.Second
|
||||
if seconds <= 0 || seconds > time.Duration(1<<31-1) {
|
||||
return 0, fmt.Errorf("assessment availability limit exceeds supported seconds: %w", domain.ErrInvalidPolicy)
|
||||
}
|
||||
return int32(seconds), nil
|
||||
}
|
||||
|
||||
func readAssessmentAvailability(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
userID uuid.UUID,
|
||||
now time.Time,
|
||||
policy domain.AssessmentPolicy,
|
||||
questionnaire domain.CandidateQuestionnaire,
|
||||
) (assessmentAvailabilityReads, error) {
|
||||
const location = "assessment.readAssessmentAvailability"
|
||||
selections, err := unit.AssessmentBank().ListCurrentAssessmentAvailabilitySelections(ctx, now)
|
||||
if err != nil {
|
||||
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read bank: %w", location, err)
|
||||
}
|
||||
reads := assessmentAvailabilityReads{selections: selections}
|
||||
reads.active, err = readActiveAvailabilityAttempts(ctx, unit, userID, now, questionnaire)
|
||||
if err != nil {
|
||||
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read active attempts: %w", location, err)
|
||||
}
|
||||
window := policy.AttemptWindow.Duration()
|
||||
reads.quota, err = unit.AssessmentAttempts().GetRootQuotaSnapshot(
|
||||
ctx, userID, now.Add(-window), now, window, policy.MaxAttemptsPerWindow,
|
||||
)
|
||||
if err != nil {
|
||||
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read root quota: %w", location, err)
|
||||
}
|
||||
reads.rootHistory, err = readAvailabilityRootHistory(ctx, unit, userID, now, policy, questionnaire)
|
||||
if err != nil {
|
||||
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read root retry history: %w", location, err)
|
||||
}
|
||||
keys, err := unit.AssessmentAttempts().ListDisclosedFamilyKeys(ctx, userID, now.Add(-365*24*time.Hour))
|
||||
if err != nil {
|
||||
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read disclosed families: %w", location, err)
|
||||
}
|
||||
reads.seen = make(map[domain.AssessmentFamilyKey]struct{}, len(keys))
|
||||
for _, key := range keys {
|
||||
reads.seen[key] = struct{}{}
|
||||
}
|
||||
return reads, nil
|
||||
}
|
||||
|
||||
func readActiveAvailabilityAttempts(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
userID uuid.UUID,
|
||||
now time.Time,
|
||||
questionnaire domain.CandidateQuestionnaire,
|
||||
) (map[domain.SpecializationCode]outbound.AssessmentActiveAttemptSummary, error) {
|
||||
activeBySpecialization := make(map[domain.SpecializationCode]outbound.AssessmentActiveAttemptSummary)
|
||||
for _, answer := range questionnaire.Specializations() {
|
||||
active, found, err := unit.AssessmentAttempts().GetAvailabilityActiveAttempt(ctx, userID, answer.Specialization)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if found && active.ExpiresAt.After(now) {
|
||||
activeBySpecialization[answer.Specialization] = active
|
||||
}
|
||||
}
|
||||
return activeBySpecialization, nil
|
||||
}
|
||||
|
||||
func readAvailabilityRootHistory(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
userID uuid.UUID,
|
||||
now time.Time,
|
||||
policy domain.AssessmentPolicy,
|
||||
questionnaire domain.CandidateQuestionnaire,
|
||||
) (map[domain.SpecializationCode][]outbound.AssessmentRootAvailabilitySummary, error) {
|
||||
horizon := max(policy.AttemptWindow.Duration(), policy.SameGradeRetryAfter.Duration(),
|
||||
policy.PromotionMinInterval.Duration()) + policy.Attempt.ChainDeadline.Duration()
|
||||
history := make(map[domain.SpecializationCode][]outbound.AssessmentRootAvailabilitySummary)
|
||||
for _, answer := range questionnaire.Specializations() {
|
||||
rows, err := unit.AssessmentAttempts().ListAvailabilityRootSummaries(
|
||||
ctx, userID, answer.Specialization, now.Add(-horizon),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
history[answer.Specialization] = rows
|
||||
}
|
||||
return history, nil
|
||||
}
|
||||
|
||||
func buildSpecializationAvailability(
|
||||
answer domain.QuestionnaireSpecialization,
|
||||
reads assessmentAvailabilityReads,
|
||||
policy domain.AssessmentPolicy,
|
||||
now time.Time,
|
||||
seconds, itemCount int32,
|
||||
) SpecializationAvailability {
|
||||
active, hasActive := reads.active[answer.Specialization]
|
||||
result := SpecializationAvailability{
|
||||
Specialization: answer.Specialization,
|
||||
Grades: make([]GradeAvailability, 0, len(availabilityGrades)),
|
||||
}
|
||||
if hasActive {
|
||||
id := active.ID
|
||||
result.ActiveAttemptID = &id
|
||||
}
|
||||
for _, grade := range availabilityGrades {
|
||||
result.Grades = append(result.Grades, buildGradeAvailability(
|
||||
answer, grade, reads, policy, now, seconds, itemCount, hasActive,
|
||||
))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func buildGradeAvailability(
|
||||
answer domain.QuestionnaireSpecialization,
|
||||
grade domain.GradeCode,
|
||||
reads assessmentAvailabilityReads,
|
||||
policy domain.AssessmentPolicy,
|
||||
now time.Time,
|
||||
seconds, itemCount int32,
|
||||
hasActive bool,
|
||||
) GradeAvailability {
|
||||
result := GradeAvailability{Grade: grade}
|
||||
if hasActive {
|
||||
result.Status = AvailabilityStatusActiveAttempt
|
||||
} else if !hasSufficientUnseenBank(answer, grade, reads.selections, reads.seen, itemCount) {
|
||||
result.Status = AvailabilityStatusInsufficientBank
|
||||
return result
|
||||
} else if availableAt := rootCooldownUntil(reads.rootHistory[answer.Specialization], grade, policy, reads.quota, now); availableAt != nil {
|
||||
result.Status = AvailabilityStatusCooldown
|
||||
result.AvailableAt = availableAt
|
||||
} else {
|
||||
result.Status = AvailabilityStatusAvailable
|
||||
}
|
||||
mode := policy.Attempt.RealMode
|
||||
result.setLimits(mode, seconds, policy.Attempt.MaxSessions, itemCount, false)
|
||||
return result
|
||||
}
|
||||
|
||||
var availabilityGrades = [...]domain.GradeCode{
|
||||
domain.GradeIntern, domain.GradeJunior, domain.GradeMiddle, domain.GradeSenior,
|
||||
}
|
||||
|
||||
func (grade *GradeAvailability) setLimits(
|
||||
mode domain.AssessmentRealMode,
|
||||
seconds, maxSessions, maxItems int32,
|
||||
practiceRequired bool,
|
||||
) {
|
||||
grade.Mode = &mode
|
||||
grade.TimeLimitSeconds = &seconds
|
||||
grade.MaxSessions = &maxSessions
|
||||
grade.MaxItems = &maxItems
|
||||
grade.PracticeRequired = &practiceRequired
|
||||
}
|
||||
|
||||
func hasSufficientUnseenBank(
|
||||
answer domain.QuestionnaireSpecialization,
|
||||
grade domain.GradeCode,
|
||||
selections []outbound.AssessmentAvailabilitySelection,
|
||||
seen map[domain.AssessmentFamilyKey]struct{},
|
||||
minimum int32,
|
||||
) bool {
|
||||
catalogLanguages := availabilityLanguages(answer.Specialization, selections)
|
||||
if len(catalogLanguages) > 0 && len(answer.TaskLanguages) == 0 {
|
||||
return false
|
||||
}
|
||||
languages := answer.TaskLanguages
|
||||
if len(catalogLanguages) == 0 {
|
||||
if len(languages) > 0 {
|
||||
return false
|
||||
}
|
||||
languages = []domain.TaskLanguageCode{""}
|
||||
}
|
||||
for _, language := range languages {
|
||||
if len(catalogLanguages) > 0 && !slices.Contains(catalogLanguages, language) {
|
||||
continue
|
||||
}
|
||||
selection, found := uniqueAvailabilitySelection(selections, answer.Specialization, grade, language)
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
unseen := int32(0)
|
||||
for _, key := range selection.FamilyKeys {
|
||||
if _, exists := seen[key]; !exists {
|
||||
unseen++
|
||||
}
|
||||
}
|
||||
if unseen >= minimum {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func availabilityLanguages(
|
||||
specialization domain.SpecializationCode,
|
||||
selections []outbound.AssessmentAvailabilitySelection,
|
||||
) []domain.TaskLanguageCode {
|
||||
var languages []domain.TaskLanguageCode
|
||||
for _, selection := range selections {
|
||||
if selection.Specialization != specialization {
|
||||
continue
|
||||
}
|
||||
for _, language := range selection.TaskLanguages {
|
||||
if !slices.Contains(languages, language) {
|
||||
languages = append(languages, language)
|
||||
}
|
||||
}
|
||||
}
|
||||
return languages
|
||||
}
|
||||
|
||||
func uniqueAvailabilitySelection(
|
||||
selections []outbound.AssessmentAvailabilitySelection,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
language domain.TaskLanguageCode,
|
||||
) (outbound.AssessmentAvailabilitySelection, bool) {
|
||||
var match outbound.AssessmentAvailabilitySelection
|
||||
count := 0
|
||||
for _, selection := range selections {
|
||||
if selection.Specialization != specialization || selection.Grade != grade {
|
||||
continue
|
||||
}
|
||||
if language == "" && len(selection.TaskLanguages) == 0 || slices.Contains(selection.TaskLanguages, language) {
|
||||
match = selection
|
||||
count++
|
||||
}
|
||||
}
|
||||
return match, count == 1
|
||||
}
|
||||
|
||||
func rootCooldownUntil(
|
||||
roots []outbound.AssessmentRootAvailabilitySummary,
|
||||
target domain.GradeCode,
|
||||
policy domain.AssessmentPolicy,
|
||||
quota outbound.AssessmentRootQuotaSnapshot,
|
||||
now time.Time,
|
||||
) *time.Time {
|
||||
latest, latestSameGrade := latestAvailabilityRoots(roots, target)
|
||||
var blockedUntil time.Time
|
||||
blockedUntil = sameGradeAvailabilityCooldown(blockedUntil, latestSameGrade, policy, now)
|
||||
blockedUntil = latestRootAvailabilityCooldown(blockedUntil, latest, target, policy, now)
|
||||
if quota.Count >= policy.MaxAttemptsPerWindow && quota.AvailableAt != nil {
|
||||
blockedUntil = laterAvailability(blockedUntil, *quota.AvailableAt, now)
|
||||
}
|
||||
if blockedUntil.IsZero() {
|
||||
return nil
|
||||
}
|
||||
availableAt := blockedUntil.UTC().Truncate(time.Microsecond)
|
||||
return &availableAt
|
||||
}
|
||||
|
||||
func latestAvailabilityRoots(
|
||||
roots []outbound.AssessmentRootAvailabilitySummary,
|
||||
target domain.GradeCode,
|
||||
) (*outbound.AssessmentRootAvailabilitySummary, *outbound.AssessmentRootAvailabilitySummary) {
|
||||
var latest *outbound.AssessmentRootAvailabilitySummary
|
||||
var latestSameGrade *outbound.AssessmentRootAvailabilitySummary
|
||||
for index := range roots {
|
||||
root := &roots[index]
|
||||
if latest == nil || root.RootCreatedAt.After(latest.RootCreatedAt) {
|
||||
latest = root
|
||||
}
|
||||
if root.RootTargetGrade == target &&
|
||||
(latestSameGrade == nil || root.RootCreatedAt.After(latestSameGrade.RootCreatedAt)) {
|
||||
latestSameGrade = root
|
||||
}
|
||||
}
|
||||
return latest, latestSameGrade
|
||||
}
|
||||
|
||||
func sameGradeAvailabilityCooldown(
|
||||
blockedUntil time.Time,
|
||||
latestSameGrade *outbound.AssessmentRootAvailabilitySummary,
|
||||
policy domain.AssessmentPolicy,
|
||||
now time.Time,
|
||||
) time.Time {
|
||||
if latestSameGrade != nil {
|
||||
updatedAt := effectiveAvailabilityUpdatedAt(latestSameGrade.RootState, latestSameGrade.RootUpdatedAt, latestSameGrade.RootExpiresAt, now)
|
||||
blockedUntil = laterAvailability(blockedUntil, updatedAt.Add(policy.SameGradeRetryAfter.Duration()), now)
|
||||
}
|
||||
return blockedUntil
|
||||
}
|
||||
|
||||
func latestRootAvailabilityCooldown(
|
||||
blockedUntil time.Time,
|
||||
latest *outbound.AssessmentRootAvailabilitySummary,
|
||||
target domain.GradeCode,
|
||||
policy domain.AssessmentPolicy,
|
||||
now time.Time,
|
||||
) time.Time {
|
||||
if latest != nil {
|
||||
lastUpdatedAt := effectiveAvailabilityUpdatedAt(latest.LatestState, latest.LatestUpdatedAt, latest.LatestExpiresAt, now)
|
||||
platformFailure := latest.LatestState == domain.AssessmentAttemptStateInsufficientBank ||
|
||||
isPlatformAttemptFailure(latest.LatestPlatformError)
|
||||
if !platformFailure &&
|
||||
availabilityCorrectionWindowOpen(latest, now) {
|
||||
blockedUntil = laterAvailability(blockedUntil, latest.LatestChainDeadline, now)
|
||||
}
|
||||
if !platformFailure && gradeRank(target) > gradeRank(latest.LatestTargetGrade) {
|
||||
blockedUntil = laterAvailability(blockedUntil, lastUpdatedAt.Add(policy.PromotionMinInterval.Duration()), now)
|
||||
}
|
||||
}
|
||||
return blockedUntil
|
||||
}
|
||||
|
||||
func effectiveAvailabilityUpdatedAt(
|
||||
state domain.AssessmentAttemptState,
|
||||
updatedAt, expiresAt, now time.Time,
|
||||
) time.Time {
|
||||
if isAssessmentAttemptActiveState(state) && !expiresAt.After(now) {
|
||||
// A read-only preflight may notice expiry after the deadline. Use the
|
||||
// attempt's fixed deadline as the transition time so polling cannot
|
||||
// extend the retry interval.
|
||||
return expiresAt
|
||||
}
|
||||
return updatedAt
|
||||
}
|
||||
|
||||
func availabilityCorrectionWindowOpen(root *outbound.AssessmentRootAvailabilitySummary, now time.Time) bool {
|
||||
if !root.LatestChainDeadline.After(root.RootCreatedAt) || !now.Before(root.LatestChainDeadline) {
|
||||
return false
|
||||
}
|
||||
if root.LatestState == domain.AssessmentAttemptStateInsufficientBank ||
|
||||
isPlatformAttemptFailure(root.LatestPlatformError) {
|
||||
return false
|
||||
}
|
||||
switch root.LatestState {
|
||||
case domain.AssessmentAttemptStateInProgress,
|
||||
domain.AssessmentAttemptStatePracticePending,
|
||||
domain.AssessmentAttemptStateAdditionalPracticePending,
|
||||
domain.AssessmentAttemptStateReadyToFinalize:
|
||||
// The GET does not write the expiry transition. An expired active
|
||||
// attempt still holds its correction chain until the immutable chain
|
||||
// deadline, matching the POST path that records expiry at expires_at.
|
||||
return !root.LatestExpiresAt.After(now) && root.LatestOutcome == ""
|
||||
case domain.AssessmentAttemptStateInsufficientBank:
|
||||
return false
|
||||
case domain.AssessmentAttemptStateExpired:
|
||||
return root.LatestOutcome == ""
|
||||
case domain.AssessmentAttemptStateCompleted:
|
||||
return root.LatestOutcome == domain.AssessmentAttemptOutcomeNotConfirmed ||
|
||||
root.LatestOutcome == domain.AssessmentAttemptOutcomeNotDetermined
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func isAssessmentAttemptActiveState(state domain.AssessmentAttemptState) bool {
|
||||
switch state {
|
||||
case domain.AssessmentAttemptStateInProgress, domain.AssessmentAttemptStatePracticePending,
|
||||
domain.AssessmentAttemptStateAdditionalPracticePending, domain.AssessmentAttemptStateReadyToFinalize:
|
||||
return true
|
||||
case domain.AssessmentAttemptStateCompleted, domain.AssessmentAttemptStateExpired,
|
||||
domain.AssessmentAttemptStateInsufficientBank:
|
||||
return false
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func isPlatformAttemptFailure(reason string) bool {
|
||||
return reason == "insufficient_bank" || reason == "sandbox_unavailable"
|
||||
}
|
||||
|
||||
func laterAvailability(current, candidate, now time.Time) time.Time {
|
||||
if !candidate.After(now) {
|
||||
return current
|
||||
}
|
||||
if current.IsZero() || candidate.After(current) {
|
||||
return candidate
|
||||
}
|
||||
return current
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestExpiredActiveAttemptCooldownDoesNotMoveWithAvailabilityReads(t *testing.T) {
|
||||
createdAt := time.Date(2026, time.January, 1, 12, 0, 0, 0, time.UTC)
|
||||
expiresAt := createdAt.Add(24 * time.Hour)
|
||||
chainDeadline := createdAt.Add(72 * time.Hour)
|
||||
root := outbound.AssessmentRootAvailabilitySummary{
|
||||
RootTargetGrade: domain.GradeJunior,
|
||||
RootCreatedAt: createdAt,
|
||||
RootUpdatedAt: createdAt.Add(12 * time.Hour),
|
||||
RootExpiresAt: expiresAt,
|
||||
RootState: domain.AssessmentAttemptStateInProgress,
|
||||
RootChainDeadline: chainDeadline,
|
||||
LatestTargetGrade: domain.GradeJunior,
|
||||
LatestUpdatedAt: createdAt.Add(12 * time.Hour),
|
||||
LatestExpiresAt: expiresAt,
|
||||
LatestState: domain.AssessmentAttemptStateInProgress,
|
||||
LatestChainDeadline: chainDeadline,
|
||||
}
|
||||
policy := domain.AssessmentPolicy{SameGradeRetryAfter: 7}
|
||||
firstReadAt := expiresAt.Add(time.Hour)
|
||||
secondReadAt := firstReadAt.Add(6 * time.Hour)
|
||||
want := expiresAt.Add(7 * 24 * time.Hour)
|
||||
|
||||
for _, now := range []time.Time{firstReadAt, secondReadAt} {
|
||||
got := rootCooldownUntil([]outbound.AssessmentRootAvailabilitySummary{root}, domain.GradeJunior, policy,
|
||||
outbound.AssessmentRootQuotaSnapshot{}, now)
|
||||
if got == nil || !got.Equal(want) {
|
||||
t.Fatalf("rootCooldownUntil(%s) = %v, want fixed expiry-based deadline %s", now, got, want)
|
||||
}
|
||||
}
|
||||
if got := rootCooldownUntil([]outbound.AssessmentRootAvailabilitySummary{root}, domain.GradeJunior, policy,
|
||||
outbound.AssessmentRootQuotaSnapshot{}, want); got != nil {
|
||||
t.Fatalf("rootCooldownUntil(after deadline) = %s, want no cooldown", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpiredActiveAttemptUsesNaturalExpiryForRetryTimestamp(t *testing.T) {
|
||||
updatedAt := time.Date(2026, time.January, 2, 10, 0, 0, 0, time.UTC)
|
||||
expiresAt := updatedAt.Add(-time.Hour)
|
||||
now := updatedAt.Add(30 * time.Minute)
|
||||
if got := effectiveAvailabilityUpdatedAt(domain.AssessmentAttemptStateInProgress, updatedAt, expiresAt, now); !got.Equal(expiresAt) {
|
||||
t.Fatalf("effectiveAvailabilityUpdatedAt() = %s, want original expiry %s", got, expiresAt)
|
||||
}
|
||||
root := &outbound.AssessmentRootAvailabilitySummary{
|
||||
RootCreatedAt: expiresAt.Add(-24 * time.Hour),
|
||||
LatestState: domain.AssessmentAttemptStateInProgress,
|
||||
LatestOutcome: "",
|
||||
LatestExpiresAt: expiresAt,
|
||||
LatestChainDeadline: expiresAt.Add(48 * time.Hour),
|
||||
}
|
||||
if !availabilityCorrectionWindowOpen(root, now) {
|
||||
t.Fatal("expired active attempt should hold the correction chain until its fixed deadline")
|
||||
}
|
||||
if availabilityCorrectionWindowOpen(root, root.LatestChainDeadline) {
|
||||
t.Fatal("correction chain should close at its fixed deadline")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlatformFailureDoesNotAddPromotionCooldown(t *testing.T) {
|
||||
now := time.Date(2026, time.January, 4, 12, 0, 0, 0, time.UTC)
|
||||
updatedAt := now.Add(-time.Hour)
|
||||
policy := domain.AssessmentPolicy{PromotionMinInterval: 90}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
state domain.AssessmentAttemptState
|
||||
reason string
|
||||
}{
|
||||
{name: "sandbox failure result", state: domain.AssessmentAttemptStateCompleted, reason: "sandbox_unavailable"},
|
||||
{name: "insufficient bank state", state: domain.AssessmentAttemptStateInsufficientBank},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
root := outbound.AssessmentRootAvailabilitySummary{
|
||||
RootTargetGrade: domain.GradeJunior,
|
||||
RootCreatedAt: now.Add(-48 * time.Hour),
|
||||
RootUpdatedAt: now.Add(-48 * time.Hour),
|
||||
RootState: domain.AssessmentAttemptStateCompleted,
|
||||
LatestTargetGrade: domain.GradeMiddle,
|
||||
LatestUpdatedAt: updatedAt,
|
||||
LatestExpiresAt: updatedAt.Add(-time.Hour),
|
||||
LatestState: test.state,
|
||||
LatestPlatformError: test.reason,
|
||||
}
|
||||
if got := rootCooldownUntil([]outbound.AssessmentRootAvailabilitySummary{root}, domain.GradeSenior,
|
||||
policy, outbound.AssessmentRootQuotaSnapshot{}, now); got != nil {
|
||||
t.Fatalf("rootCooldownUntil() = %s, want no platform-failure cooldown", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const finalizeAttemptOperation = "assessment_attempt.finalize"
|
||||
|
||||
type FinalizeAssessmentAttemptCommand struct {
|
||||
ActorID uuid.UUID
|
||||
AttemptID domain.AssessmentAttemptID
|
||||
ExpectedVersion int64
|
||||
IdempotencyKey string
|
||||
}
|
||||
|
||||
type canonicalAttemptFinalizeBody struct {
|
||||
AttemptID string `json:"attempt_id"`
|
||||
ExpectedVersion int64 `json:"expected_version"`
|
||||
}
|
||||
|
||||
// AssessmentAttemptResult contains only the candidate-visible result data.
|
||||
type AssessmentAttemptResult struct {
|
||||
Attempt domain.AssessmentAttemptPublicSnapshot
|
||||
Outcome domain.AssessmentAttemptOutcome
|
||||
NotDeterminedReason string
|
||||
BasicScore *domain.AssessmentBasicScore
|
||||
Limitations []string
|
||||
Summary string
|
||||
DecidedAt time.Time
|
||||
}
|
||||
|
||||
// FinalizeAttempt stores a pinned-policy decision and its idempotent response
|
||||
// in the same transaction as the attempt transition.
|
||||
func (service *AttemptService) FinalizeAttempt(
|
||||
ctx context.Context,
|
||||
command FinalizeAssessmentAttemptCommand,
|
||||
) (outbound.AssessmentAttemptCommandResult, error) {
|
||||
const location = "AttemptService.FinalizeAttempt"
|
||||
if command.ActorID == uuid.Nil || command.AttemptID.IsZero() || command.ExpectedVersion < 1 {
|
||||
return outbound.AssessmentAttemptCommandResult{}, ErrInvalidAttemptRequest
|
||||
}
|
||||
body, err := json.Marshal(canonicalAttemptFinalizeBody{
|
||||
AttemptID: command.AttemptID.String(), ExpectedVersion: command.ExpectedVersion,
|
||||
})
|
||||
if err != nil || len(body) > maxAttemptCanonicalBodyBytes {
|
||||
return outbound.AssessmentAttemptCommandResult{}, ErrInvalidAttemptRequest
|
||||
}
|
||||
keyTime, err := assessmentIdempotencyTime(service.clock())
|
||||
if err != nil {
|
||||
return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - validate application time: %w", location, err)
|
||||
}
|
||||
request, err := service.prepareAttemptIdempotency(finalizeAttemptOperation, command.IdempotencyKey, command.ActorID, body, keyTime)
|
||||
if err != nil {
|
||||
return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - prepare idempotency: %w", location, err)
|
||||
}
|
||||
var result outbound.AssessmentAttemptCommandResult
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - reserve idempotency: %w", location, err)
|
||||
}
|
||||
repository := unit.AssessmentAttempts()
|
||||
if !created {
|
||||
return replayAttemptFinalize(ctx, repository, request, stored, &result)
|
||||
}
|
||||
if err := repository.DeleteExpiredOutcome(ctx, request.scope); err != nil {
|
||||
return fmt.Errorf("%s - remove expired finalize response: %w", location, err)
|
||||
}
|
||||
return service.finalizeNewAttempt(ctx, unit, repository, request.scope, command, &result)
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.AssessmentAttemptCommandResult{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func replayAttemptFinalize(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentAttemptRepository,
|
||||
request attemptIdempotencyRequest,
|
||||
stored outbound.IdempotencyRecord,
|
||||
result *outbound.AssessmentAttemptCommandResult,
|
||||
) error {
|
||||
const location = "assessment.replayAttemptFinalize"
|
||||
if stored.Fingerprint != request.record.Fingerprint {
|
||||
return fmt.Errorf("%s - compare request fingerprint: %w", location, ErrAttemptKeyReused)
|
||||
}
|
||||
outcome, err := repository.GetFinalizeOutcome(ctx, request.scope)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read immutable finalize response: %w", location, err)
|
||||
}
|
||||
*result = outbound.AssessmentAttemptCommandResult{Outcome: outcome, Replayed: true}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service *AttemptService) finalizeNewAttempt(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repository outbound.AssessmentAttemptRepository,
|
||||
scope outbound.AssessmentAttemptIdempotencyScope,
|
||||
command FinalizeAssessmentAttemptCommand,
|
||||
result *outbound.AssessmentAttemptCommandResult,
|
||||
) error {
|
||||
const location = "AttemptService.finalizeNewAttempt"
|
||||
current, err := lockAttemptForFinalize(ctx, unit, repository, command)
|
||||
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
||||
return storeAttemptCommandProblem(ctx, repository, scope, "finalize", 404, result)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
|
||||
}
|
||||
if current.State() != domain.AssessmentAttemptStateCompleted && command.ExpectedVersion != current.Version() {
|
||||
return fmt.Errorf("%s - check expected version: %w", location, ErrAttemptVersionConflict)
|
||||
}
|
||||
if current.State() == domain.AssessmentAttemptStateCompleted {
|
||||
return storeCompletedFinalize(ctx, repository, scope, command, current, result)
|
||||
}
|
||||
return service.finalizeActiveAttempt(ctx, unit, repository, scope, command, current, result)
|
||||
}
|
||||
|
||||
func lockAttemptForFinalize(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repository outbound.AssessmentAttemptRepository,
|
||||
command FinalizeAssessmentAttemptCommand,
|
||||
) (domain.AssessmentAttempt, error) {
|
||||
const location = "AttemptService.lockAttemptForFinalize"
|
||||
kind, err := repository.GetKindForCandidate(ctx, command.ActorID, command.AttemptID)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
||||
return domain.AssessmentAttempt{}, outbound.ErrAssessmentAttemptNotFound
|
||||
}
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err)
|
||||
}
|
||||
if err := lockSessionConsent(ctx, unit, command.ActorID, kind); err != nil {
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - authorize finalization: %w", location, err)
|
||||
}
|
||||
current, err := repository.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
||||
return domain.AssessmentAttempt{}, outbound.ErrAssessmentAttemptNotFound
|
||||
}
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
|
||||
}
|
||||
if current.Kind() != kind {
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt kind changed: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func storeCompletedFinalize(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentAttemptRepository,
|
||||
scope outbound.AssessmentAttemptIdempotencyScope,
|
||||
command FinalizeAssessmentAttemptCommand,
|
||||
current domain.AssessmentAttempt,
|
||||
result *outbound.AssessmentAttemptCommandResult,
|
||||
) error {
|
||||
const location = "AttemptService.storeCompletedFinalize"
|
||||
if _, err := repository.GetResult(ctx, command.ActorID, command.AttemptID); err != nil {
|
||||
return fmt.Errorf("%s - completed attempt has no immutable result: %w", location, err)
|
||||
}
|
||||
outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: current.PublicSnapshot()}
|
||||
if err := repository.SaveFinalizeOutcome(ctx, scope, outcome); err != nil {
|
||||
return fmt.Errorf("%s - store completed finalize response: %w", location, err)
|
||||
}
|
||||
*result = outbound.AssessmentAttemptCommandResult{Outcome: outcome}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service *AttemptService) finalizeActiveAttempt(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repository outbound.AssessmentAttemptRepository,
|
||||
scope outbound.AssessmentAttemptIdempotencyScope,
|
||||
command FinalizeAssessmentAttemptCommand,
|
||||
current domain.AssessmentAttempt,
|
||||
result *outbound.AssessmentAttemptCommandResult,
|
||||
) error {
|
||||
const location = "AttemptService.finalizeActiveAttempt"
|
||||
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read database time after consent and attempt locks: %w", location, err)
|
||||
}
|
||||
databaseTime = databaseTime.UTC().Truncate(time.Microsecond)
|
||||
policyID := current.Snapshot().Versions.ProductPolicyVersionID
|
||||
policy, err := unit.Policies().GetByID(ctx, policyID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read pinned product policy: %w", location, err)
|
||||
}
|
||||
if current.State() == domain.AssessmentAttemptStateInProgress {
|
||||
expired, changed, expireErr := current.ExpireIfDue(databaseTime)
|
||||
if expireErr != nil {
|
||||
return fmt.Errorf("%s - apply due attempt deadline: %w", location, expireErr)
|
||||
}
|
||||
if changed {
|
||||
if err := repository.SaveTransition(ctx, current, expired); err != nil {
|
||||
return fmt.Errorf("%s - persist due attempt deadline: %w", location, err)
|
||||
}
|
||||
return storeAttemptCommandProblem(ctx, repository, scope, "finalize", 409, result)
|
||||
}
|
||||
}
|
||||
if pendingItemIDs := current.PendingItemIDs(); len(pendingItemIDs) > 0 {
|
||||
return storeFinalizePendingItems(ctx, repository, scope, pendingItemIDs, result)
|
||||
}
|
||||
updated, changed, decision, finalizeErr := current.FinalizeDemo(
|
||||
command.ExpectedVersion, policy.Policy().Assessment, databaseTime,
|
||||
)
|
||||
if finalizeErr != nil {
|
||||
if errors.Is(finalizeErr, domain.ErrAssessmentAttemptVersionConflict) {
|
||||
return fmt.Errorf("%s - check expected version: %w", location, ErrAttemptVersionConflict)
|
||||
}
|
||||
if errors.Is(finalizeErr, domain.ErrAssessmentAttemptNotActive) {
|
||||
return storeAttemptCommandProblem(ctx, repository, scope, "finalize", 409, result)
|
||||
}
|
||||
return fmt.Errorf("%s - calculate pinned decision: %w", location, finalizeErr)
|
||||
}
|
||||
return persistFinalizedAttempt(ctx, repository, scope, command, current, updated, changed, decision, result)
|
||||
}
|
||||
|
||||
func persistFinalizedAttempt(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentAttemptRepository,
|
||||
scope outbound.AssessmentAttemptIdempotencyScope,
|
||||
command FinalizeAssessmentAttemptCommand,
|
||||
current, updated domain.AssessmentAttempt,
|
||||
changed bool,
|
||||
decision domain.AssessmentAttemptDecision,
|
||||
result *outbound.AssessmentAttemptCommandResult,
|
||||
) error {
|
||||
const location = "AttemptService.persistFinalizedAttempt"
|
||||
if changed {
|
||||
if err := repository.SaveTransition(ctx, current, updated); err != nil {
|
||||
return fmt.Errorf("%s - persist final decision: %w", location, err)
|
||||
}
|
||||
summary, limitations := assessmentFinalizedResultPresentation(updated.Kind())
|
||||
storedResult, err := domain.NewAssessmentAttemptResultSnapshot(updated, decision, summary, limitations)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build immutable result snapshot: %w", location, err)
|
||||
}
|
||||
if err := repository.SaveResult(ctx, command.ActorID, storedResult); err != nil {
|
||||
return fmt.Errorf("%s - persist immutable result snapshot: %w", location, err)
|
||||
}
|
||||
}
|
||||
outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: updated.PublicSnapshot()}
|
||||
if err := repository.SaveFinalizeOutcome(ctx, scope, outcome); err != nil {
|
||||
return fmt.Errorf("%s - store immutable finalize response: %w", location, err)
|
||||
}
|
||||
*result = outbound.AssessmentAttemptCommandResult{Outcome: outcome}
|
||||
return nil
|
||||
}
|
||||
|
||||
func assessmentFinalizedResultPresentation(kind domain.AssessmentAttemptKind) (string, []string) {
|
||||
if kind == domain.AssessmentAttemptKindDemoExpress {
|
||||
return "This training run is educational only. It does not assess or confirm a grade.", []string{"demonstration_only"}
|
||||
}
|
||||
return "", []string{"uncalibrated_thresholds", "demo_bank", "practice_not_included", "unproctored"}
|
||||
}
|
||||
|
||||
// GetMyResult returns an immutable completed result or a terminal no-result projection.
|
||||
func (service *AttemptService) GetMyResult(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
) (AssessmentAttemptResult, error) {
|
||||
const location = "AttemptService.GetMyResult"
|
||||
if userID == uuid.Nil || attemptID.IsZero() {
|
||||
return AssessmentAttemptResult{}, fmt.Errorf("%s - candidate and attempt IDs are required: %w", location, ErrAttemptForbidden)
|
||||
}
|
||||
var result AssessmentAttemptResult
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireAttemptCandidate(ctx, unit, userID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
var readErr error
|
||||
result, readErr = service.readAttemptResult(ctx, unit, userID, attemptID)
|
||||
return readErr
|
||||
})
|
||||
if err != nil {
|
||||
return AssessmentAttemptResult{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (service *AttemptService) readAttemptResult(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
userID uuid.UUID,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
) (AssessmentAttemptResult, error) {
|
||||
const location = "AttemptService.readAttemptResult"
|
||||
attempt, err := unit.AssessmentAttempts().GetForCandidate(ctx, userID, attemptID)
|
||||
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
||||
return AssessmentAttemptResult{}, fmt.Errorf("%s - read owner-scoped attempt: %w", location, ErrAttemptNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return AssessmentAttemptResult{}, fmt.Errorf("%s - read owner-scoped attempt: %w", location, err)
|
||||
}
|
||||
snapshot := attempt.Snapshot()
|
||||
if err := validateAttemptResultState(snapshot); err != nil {
|
||||
return AssessmentAttemptResult{}, fmt.Errorf("%s - validate terminal attempt: %w", location, err)
|
||||
}
|
||||
if snapshot.State == domain.AssessmentAttemptStateCompleted {
|
||||
return readCompletedAttemptResult(ctx, unit, userID, attemptID, attempt)
|
||||
}
|
||||
return terminalAttemptResult(attempt)
|
||||
}
|
||||
|
||||
func validateAttemptResultState(snapshot domain.AssessmentAttemptSnapshot) error {
|
||||
switch snapshot.State {
|
||||
case domain.AssessmentAttemptStateCompleted, domain.AssessmentAttemptStateExpired,
|
||||
domain.AssessmentAttemptStateInsufficientBank:
|
||||
if snapshot.EndedAt.IsZero() {
|
||||
return domain.ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return nil
|
||||
case domain.AssessmentAttemptStateInProgress, domain.AssessmentAttemptStatePracticePending,
|
||||
domain.AssessmentAttemptStateAdditionalPracticePending, domain.AssessmentAttemptStateReadyToFinalize:
|
||||
return ErrAttemptStateConflict
|
||||
default:
|
||||
return domain.ErrInvalidAssessmentAttempt
|
||||
}
|
||||
}
|
||||
|
||||
func readCompletedAttemptResult(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
userID uuid.UUID,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
attempt domain.AssessmentAttempt,
|
||||
) (AssessmentAttemptResult, error) {
|
||||
const location = "AttemptService.readCompletedAttemptResult"
|
||||
stored, err := unit.AssessmentAttempts().GetResult(ctx, userID, attemptID)
|
||||
if err != nil {
|
||||
return AssessmentAttemptResult{}, fmt.Errorf("%s - read immutable result: %w", location, err)
|
||||
}
|
||||
if !assessmentResultMatchesAttempt(stored, attempt) {
|
||||
return AssessmentAttemptResult{}, fmt.Errorf("%s - immutable result does not match its attempt: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
return assessmentAttemptResultFromSnapshot(stored), nil
|
||||
}
|
||||
|
||||
func terminalAttemptResult(attempt domain.AssessmentAttempt) (AssessmentAttemptResult, error) {
|
||||
snapshot := attempt.Snapshot()
|
||||
result := AssessmentAttemptResult{Attempt: attempt.PublicSnapshot(), DecidedAt: snapshot.EndedAt}
|
||||
switch snapshot.Kind {
|
||||
case domain.AssessmentAttemptKindDemoExpress:
|
||||
result.Outcome = domain.AssessmentAttemptOutcomeDemonstration
|
||||
result.Summary = "This training run ended before completion. It does not assess or confirm a grade."
|
||||
case domain.AssessmentAttemptKindRoot, domain.AssessmentAttemptKindCorrective:
|
||||
result.Limitations = []string{"uncalibrated_thresholds", "demo_bank", "practice_not_included", "unproctored"}
|
||||
result.Outcome = domain.AssessmentAttemptOutcomeNotDetermined
|
||||
if snapshot.State == domain.AssessmentAttemptStateExpired {
|
||||
result.NotDeterminedReason = "expired"
|
||||
} else {
|
||||
result.NotDeterminedReason = "insufficient_bank"
|
||||
}
|
||||
default:
|
||||
return AssessmentAttemptResult{}, fmt.Errorf("AttemptService.terminalAttemptResult - attempt kind is unsupported: %w", domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func assessmentResultMatchesAttempt(
|
||||
result domain.AssessmentAttemptResultSnapshot,
|
||||
attempt domain.AssessmentAttempt,
|
||||
) bool {
|
||||
snapshot := attempt.Snapshot()
|
||||
pins := result.Pins
|
||||
public := attempt.PublicSnapshot()
|
||||
return reflect.DeepEqual(result.Attempt, public) && result.Outcome == snapshot.Outcome &&
|
||||
result.Attempt.FinishedAt != nil && snapshot.EndedAt.Equal(*result.Attempt.FinishedAt) &&
|
||||
pins.ProductPolicyVersionID == snapshot.Versions.ProductPolicyVersionID &&
|
||||
pins.ProductPolicyVersion == snapshot.Versions.ProductPolicyVersion &&
|
||||
pins.GradingPolicyVersionID == snapshot.Versions.GradingPolicyVersionID &&
|
||||
pins.OpeningID == snapshot.Versions.OpeningID && pins.OpeningManifestHash == snapshot.Versions.OpeningManifestHash &&
|
||||
pins.TrainingBindingID == snapshot.Versions.TrainingBindingID &&
|
||||
pins.TrainingManifestHash == snapshot.Versions.TrainingManifestHash &&
|
||||
pins.BankVersion == snapshot.Versions.BankVersion && pins.AlgorithmVersion == snapshot.Versions.AlgorithmVersion
|
||||
}
|
||||
|
||||
func assessmentAttemptResultFromSnapshot(
|
||||
snapshot domain.AssessmentAttemptResultSnapshot,
|
||||
) AssessmentAttemptResult {
|
||||
return AssessmentAttemptResult{
|
||||
Attempt: snapshot.Attempt, Outcome: snapshot.Outcome,
|
||||
NotDeterminedReason: snapshot.NotDeterminedReason,
|
||||
BasicScore: snapshot.BasicScore, Limitations: append([]string{}, snapshot.Limitations...),
|
||||
Summary: snapshot.Summary, DecidedAt: snapshot.DecidedAt,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
assessmentSignalOperation = "assessment_attempt.signals"
|
||||
assessmentSignalRateWindow = time.Minute
|
||||
assessmentSignalMaxReceipts = int64(30)
|
||||
assessmentSignalMaxEvents = int64(10000)
|
||||
assessmentSignalTimestampSkew = 5 * time.Minute
|
||||
assessmentSignalMaximumBodySize = 32 << 10
|
||||
assessmentSignalMaximumEvents = 50
|
||||
)
|
||||
|
||||
var (
|
||||
ErrAttemptSignalForbidden = errors.New("assessment signals are forbidden")
|
||||
ErrAttemptSignalConsentRequired = errors.New("assessment signals require current C3 consent")
|
||||
ErrAttemptSignalStateConflict = errors.New("assessment attempt cannot accept signals")
|
||||
ErrAttemptSignalRateLimited = errors.New("assessment signal receipt rate limit exceeded")
|
||||
ErrInvalidAttemptSignalRequest = errors.New("invalid assessment signal request")
|
||||
)
|
||||
|
||||
// SignalRateLimitError carries the first time a new receipt can be retried.
|
||||
// Its message contains no candidate, attempt, or event data.
|
||||
type SignalRateLimitError struct {
|
||||
RetryAt time.Time
|
||||
}
|
||||
|
||||
func (limitError *SignalRateLimitError) Error() string {
|
||||
return ErrAttemptSignalRateLimited.Error()
|
||||
}
|
||||
|
||||
func (limitError *SignalRateLimitError) Unwrap() error {
|
||||
return ErrAttemptSignalRateLimited
|
||||
}
|
||||
|
||||
// SignalService stores bounded client-reported event metadata for real
|
||||
// assessment attempts. The signals do not participate in grading.
|
||||
type SignalService struct {
|
||||
transactor outbound.Transactor
|
||||
keyring Keyring
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
func NewSignalService(transactor outbound.Transactor, keyring Keyring, clock func() time.Time) (*SignalService, error) {
|
||||
if transactor == nil || keyring == nil || clock == nil {
|
||||
return nil, errors.New("assessment.NewSignalService - every dependency must be set")
|
||||
}
|
||||
return &SignalService{transactor: transactor, keyring: keyring, clock: clock}, nil
|
||||
}
|
||||
|
||||
type RecordSignalsCommand struct {
|
||||
ActorID uuid.UUID
|
||||
AttemptID domain.AssessmentAttemptID
|
||||
IdempotencyKey string
|
||||
Events []domain.AssessmentSignalEvent
|
||||
}
|
||||
|
||||
type canonicalSignalRequest struct {
|
||||
AttemptID string `json:"attempt_id"`
|
||||
Events []canonicalSignalEvent `json:"events"`
|
||||
}
|
||||
|
||||
type canonicalSignalEvent struct {
|
||||
Kind domain.AssessmentSignalKind `json:"kind"`
|
||||
ItemInstanceID uuid.UUID `json:"item_instance_id"`
|
||||
OccurredAt time.Time `json:"occurred_at"`
|
||||
DurationMS *int32 `json:"duration_ms,omitempty"`
|
||||
SizeBytes *int32 `json:"size_bytes,omitempty"`
|
||||
}
|
||||
|
||||
type signalIdempotencyRequest struct {
|
||||
scope outbound.AssessmentAttemptIdempotencyScope
|
||||
record outbound.IdempotencyRecord
|
||||
}
|
||||
|
||||
// RecordSignals stores all events in a batch or stores none. A replay returns
|
||||
// the original receipt without rechecking or repeating storage effects.
|
||||
func (service *SignalService) RecordSignals(
|
||||
ctx context.Context,
|
||||
command RecordSignalsCommand,
|
||||
) (domain.AssessmentSignalReceipt, error) {
|
||||
const location = "SignalService.RecordSignals"
|
||||
canonicalEvents, body, err := canonicalSignalBody(command)
|
||||
if err != nil {
|
||||
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - validate request: %w", location, err)
|
||||
}
|
||||
now, err := assessmentIdempotencyTime(service.clock())
|
||||
if err != nil {
|
||||
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - validate application time: %w", location, err)
|
||||
}
|
||||
request, err := service.prepareSignalIdempotency(command, body, now)
|
||||
if err != nil {
|
||||
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - prepare idempotency: %w", location, err)
|
||||
}
|
||||
|
||||
var receipt domain.AssessmentSignalReceipt
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - reserve idempotency: %w", location, err)
|
||||
}
|
||||
repository := unit.AssessmentSignals()
|
||||
if !created {
|
||||
if stored.Fingerprint != request.record.Fingerprint {
|
||||
return fmt.Errorf("%s - compare request fingerprint: %w", location, ErrAttemptKeyReused)
|
||||
}
|
||||
if err := requireReplayableSignalAttempt(ctx, unit, command); err != nil {
|
||||
return fmt.Errorf("%s - verify owner-scoped attempt before replay: %w", location, err)
|
||||
}
|
||||
receipt, err = repository.GetOutcome(ctx, request.scope)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrAssessmentSignalOutcomeNotFound) {
|
||||
if attemptErr := requireReplayableSignalAttempt(ctx, unit, command); attemptErr != nil {
|
||||
return fmt.Errorf("%s - verify attempt after missing receipt: %w", location, attemptErr)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("%s - read immutable receipt: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := repository.DeleteExpiredOutcome(ctx, request.scope); err != nil {
|
||||
return fmt.Errorf("%s - remove expired receipt: %w", location, err)
|
||||
}
|
||||
return service.recordNewSignals(ctx, unit, repository, command, canonicalEvents, request.scope, &receipt)
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return receipt, nil
|
||||
}
|
||||
|
||||
func requireReplayableSignalAttempt(ctx context.Context, unit outbound.UnitOfWork, command RecordSignalsCommand) error {
|
||||
const location = "SignalService.requireReplayableSignalAttempt"
|
||||
kind, err := unit.AssessmentAttempts().GetKindForCandidate(ctx, command.ActorID, command.AttemptID)
|
||||
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
||||
return fmt.Errorf("%s - owner-scoped attempt is missing: %w", location, ErrAttemptNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err)
|
||||
}
|
||||
if kind != domain.AssessmentAttemptKindRoot && kind != domain.AssessmentAttemptKindCorrective {
|
||||
return fmt.Errorf("%s - training attempts do not have signal receipts: %w", location, ErrAttemptSignalStateConflict)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service *SignalService) recordNewSignals(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repository outbound.AssessmentSignalRepository,
|
||||
command RecordSignalsCommand,
|
||||
events []domain.AssessmentSignalEvent,
|
||||
scope outbound.AssessmentAttemptIdempotencyScope,
|
||||
receipt *domain.AssessmentSignalReceipt,
|
||||
) error {
|
||||
const location = "SignalService.recordNewSignals"
|
||||
attempt, err := lockAttemptForSignals(ctx, unit, command)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - lock attempt and C3 consent: %w", location, err)
|
||||
}
|
||||
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read database time after consent and attempt locks: %w", location, err)
|
||||
}
|
||||
databaseTime = databaseTime.UTC().Truncate(time.Microsecond)
|
||||
if !attempt.IsActive() || !databaseTime.Before(attempt.ExpiresAt()) {
|
||||
return fmt.Errorf("%s - attempt is terminal or expired: %w", location, ErrAttemptSignalStateConflict)
|
||||
}
|
||||
if err := validateSignalItemsAndTimes(attempt, events, databaseTime); err != nil {
|
||||
return fmt.Errorf("%s - validate item binding and timestamp: %w", location, err)
|
||||
}
|
||||
if err := checkSignalReceiptRate(ctx, repository, attempt.ID(), databaseTime); err != nil {
|
||||
return fmt.Errorf("%s - check receipt rate: %w", location, err)
|
||||
}
|
||||
status, acceptedCount, err := service.persistSignalBatch(ctx, repository, attempt.ID(), events, databaseTime)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - persist bounded event batch: %w", location, err)
|
||||
}
|
||||
newReceipt, err := domain.NewAssessmentSignalReceipt(status, acceptedCount, databaseTime)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build receipt: %w", location, err)
|
||||
}
|
||||
if err := repository.SaveOutcome(ctx, scope, attempt.ID(), newReceipt); err != nil {
|
||||
return fmt.Errorf("%s - store immutable receipt: %w", location, err)
|
||||
}
|
||||
*receipt = newReceipt
|
||||
return nil
|
||||
}
|
||||
|
||||
func lockAttemptForSignals(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command RecordSignalsCommand,
|
||||
) (domain.AssessmentAttempt, error) {
|
||||
const location = "SignalService.lockAttemptForSignals"
|
||||
attempts := unit.AssessmentAttempts()
|
||||
kind, err := attempts.GetKindForCandidate(ctx, command.ActorID, command.AttemptID)
|
||||
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, ErrAttemptNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err)
|
||||
}
|
||||
if kind != domain.AssessmentAttemptKindRoot && kind != domain.AssessmentAttemptKindCorrective {
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - training attempts do not accept signals: %w", location, ErrAttemptSignalStateConflict)
|
||||
}
|
||||
if _, err := unit.ConsentLedger().LockCurrentForUse(ctx, command.ActorID, domain.ConsentPurposeAutoCategorization); err != nil {
|
||||
if errors.Is(err, outbound.ErrConsentNotFound) {
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - require current C3 consent: %w", location, ErrAttemptSignalConsentRequired)
|
||||
}
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock current C3 consent: %w", location, err)
|
||||
}
|
||||
attempt, err := attempts.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID)
|
||||
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, ErrAttemptNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
|
||||
}
|
||||
if attempt.Kind() != kind {
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt kind changed: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
return attempt, nil
|
||||
}
|
||||
|
||||
func checkSignalReceiptRate(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentSignalRepository,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
databaseTime time.Time,
|
||||
) error {
|
||||
const location = "SignalService.checkSignalReceiptRate"
|
||||
count, oldest, err := repository.CountRecentOutcomes(ctx, attemptID, databaseTime.Add(-assessmentSignalRateWindow))
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - count recent receipts: %w", location, err)
|
||||
}
|
||||
if count < assessmentSignalMaxReceipts {
|
||||
return nil
|
||||
}
|
||||
retryAt := oldest.Add(assessmentSignalRateWindow).UTC().Truncate(time.Microsecond)
|
||||
if !retryAt.After(databaseTime) {
|
||||
retryAt = databaseTime.Add(time.Second).Truncate(time.Second)
|
||||
}
|
||||
return fmt.Errorf("%s - wait for the next receipt window: %w", location, &SignalRateLimitError{RetryAt: retryAt})
|
||||
}
|
||||
|
||||
func (service *SignalService) persistSignalBatch(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentSignalRepository,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
events []domain.AssessmentSignalEvent,
|
||||
databaseTime time.Time,
|
||||
) (domain.AssessmentSignalReceiptStatus, int32, error) {
|
||||
const location = "SignalService.persistSignalBatch"
|
||||
acceptedCount, err := assessmentSignalEventCount(len(events))
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("%s - event count is invalid: %w", location, err)
|
||||
}
|
||||
storedCount, err := repository.CountAttemptEvents(ctx, attemptID)
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("%s - count stored events: %w", location, err)
|
||||
}
|
||||
if storedCount+int64(len(events)) > assessmentSignalMaxEvents {
|
||||
return domain.AssessmentSignalReceiptSaturated, 0, nil
|
||||
}
|
||||
batchID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("%s - generate batch ID: %w", location, err)
|
||||
}
|
||||
batch, err := domain.NewAssessmentSignalBatch(batchID, attemptID, databaseTime, events)
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("%s - build event batch: %w", location, err)
|
||||
}
|
||||
if err := repository.SaveBatch(ctx, batch); err != nil {
|
||||
return "", 0, fmt.Errorf("%s - store event batch: %w", location, err)
|
||||
}
|
||||
return domain.AssessmentSignalReceiptAccepted, acceptedCount, nil
|
||||
}
|
||||
|
||||
func assessmentSignalEventCount(count int) (int32, error) {
|
||||
if count < 1 || count > assessmentSignalMaximumEvents {
|
||||
return 0, ErrInvalidAttemptSignalRequest
|
||||
}
|
||||
return int32(count), nil
|
||||
}
|
||||
|
||||
func (service *SignalService) prepareSignalIdempotency(
|
||||
command RecordSignalsCommand,
|
||||
body []byte,
|
||||
now time.Time,
|
||||
) (signalIdempotencyRequest, error) {
|
||||
if !validAttemptIdempotencyKey(command.IdempotencyKey) {
|
||||
return signalIdempotencyRequest{}, ErrInvalidAttemptKey
|
||||
}
|
||||
expiresAt := now.Add(outbound.IdempotencyRetention)
|
||||
if !expiresAt.After(now) || expiresAt.Year() > 9999 {
|
||||
return signalIdempotencyRequest{}, ErrInvalidAttemptSignalRequest
|
||||
}
|
||||
scopeBytes := service.keyring.IdempotencyScope(assessmentSignalOperation, command.IdempotencyKey, command.ActorID.String())
|
||||
return signalIdempotencyRequest{
|
||||
scope: outbound.AssessmentAttemptIdempotencyScope(scopeBytes),
|
||||
record: outbound.IdempotencyRecord{
|
||||
Scope: scopeBytes, Fingerprint: service.keyring.Fingerprint(body), CreatedAt: now, ExpiresAt: expiresAt,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func canonicalSignalBody(command RecordSignalsCommand) ([]domain.AssessmentSignalEvent, []byte, error) {
|
||||
if command.ActorID == uuid.Nil || command.AttemptID.IsZero() || len(command.Events) == 0 || len(command.Events) > assessmentSignalMaximumEvents {
|
||||
return nil, nil, ErrInvalidAttemptSignalRequest
|
||||
}
|
||||
canonical := canonicalSignalRequest{AttemptID: command.AttemptID.String(), Events: make([]canonicalSignalEvent, 0, len(command.Events))}
|
||||
validated := make([]domain.AssessmentSignalEvent, 0, len(command.Events))
|
||||
for _, event := range command.Events {
|
||||
duration, hasDuration := event.DurationMS()
|
||||
size, hasSize := event.SizeBytes()
|
||||
input := domain.AssessmentSignalEventInput{
|
||||
Kind: event.Kind(), ItemInstanceID: event.ItemInstanceID(), OccurredAt: event.OccurredAt(),
|
||||
}
|
||||
encodedEvent := canonicalSignalEvent{Kind: event.Kind(), ItemInstanceID: event.ItemInstanceID(), OccurredAt: event.OccurredAt()}
|
||||
if hasDuration {
|
||||
input.DurationMS = &duration
|
||||
encodedEvent.DurationMS = &duration
|
||||
}
|
||||
if hasSize {
|
||||
input.SizeBytes = &size
|
||||
encodedEvent.SizeBytes = &size
|
||||
}
|
||||
checked, err := domain.NewAssessmentSignalEvent(input)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("%w", ErrInvalidAttemptSignalRequest)
|
||||
}
|
||||
validated = append(validated, checked)
|
||||
canonical.Events = append(canonical.Events, encodedEvent)
|
||||
}
|
||||
body, err := json.Marshal(canonical)
|
||||
if err != nil || len(body) == 0 || len(body) > assessmentSignalMaximumBodySize {
|
||||
return nil, nil, ErrInvalidAttemptSignalRequest
|
||||
}
|
||||
return validated, body, nil
|
||||
}
|
||||
|
||||
func validateSignalItemsAndTimes(
|
||||
attempt domain.AssessmentAttempt,
|
||||
events []domain.AssessmentSignalEvent,
|
||||
databaseTime time.Time,
|
||||
) error {
|
||||
snapshot := attempt.Snapshot()
|
||||
itemIDs := make(map[uuid.UUID]struct{}, len(snapshot.Items))
|
||||
for _, item := range snapshot.Items {
|
||||
itemIDs[item.ID] = struct{}{}
|
||||
}
|
||||
earliest := snapshot.CreatedAt.UTC().Add(-assessmentSignalTimestampSkew)
|
||||
latest := databaseTime.Add(assessmentSignalTimestampSkew)
|
||||
for _, event := range events {
|
||||
if _, exists := itemIDs[event.ItemInstanceID()]; !exists {
|
||||
return ErrInvalidAttemptSignalRequest
|
||||
}
|
||||
occurredAt := event.OccurredAt()
|
||||
if occurredAt.Before(earliest) || occurredAt.After(latest) {
|
||||
return ErrInvalidAttemptSignalRequest
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
type signalKeyring struct{}
|
||||
|
||||
func (signalKeyring) IdempotencyScope(operation, key, principal string) [32]byte {
|
||||
return sha256.Sum256([]byte(operation + ":" + key + ":" + principal))
|
||||
}
|
||||
|
||||
func (signalKeyring) Fingerprint(body []byte) [32]byte {
|
||||
return sha256.Sum256(body)
|
||||
}
|
||||
|
||||
func TestCanonicalSignalBodyContainsOnlyBoundedAllowlistedFields(t *testing.T) {
|
||||
attemptID, itemID := domain.AssessmentAttemptID(uuid.New()), uuid.New()
|
||||
at := time.Date(2026, time.October, 7, 12, 0, 0, 987654321, time.FixedZone("offset", 3*60*60))
|
||||
size := int32(128)
|
||||
event, err := domain.NewAssessmentSignalEvent(domain.AssessmentSignalEventInput{
|
||||
Kind: domain.AssessmentSignalPaste, ItemInstanceID: itemID, OccurredAt: at, SizeBytes: &size,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentSignalEvent() error = %v", err)
|
||||
}
|
||||
validated, encoded, err := canonicalSignalBody(RecordSignalsCommand{
|
||||
ActorID: uuid.New(), AttemptID: attemptID, Events: []domain.AssessmentSignalEvent{event},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("canonicalSignalBody() error = %v", err)
|
||||
}
|
||||
if len(validated) != 1 || int64(len(encoded)) > assessmentSignalMaximumBodySize {
|
||||
t.Fatalf("canonical body has %d events and %d bytes", len(validated), len(encoded))
|
||||
}
|
||||
var document map[string]any
|
||||
if err := json.Unmarshal(encoded, &document); err != nil {
|
||||
t.Fatalf("json.Unmarshal() error = %v", err)
|
||||
}
|
||||
if document["attempt_id"] != attemptID.String() || len(document) != 2 {
|
||||
t.Fatalf("canonical request keys/value = %+v", document)
|
||||
}
|
||||
events, ok := document["events"].([]any)
|
||||
if !ok || len(events) != 1 {
|
||||
t.Fatalf("canonical events = %#v", document["events"])
|
||||
}
|
||||
fields, ok := events[0].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("canonical event = %#v", events[0])
|
||||
}
|
||||
if fields["kind"] != "paste" || fields["item_instance_id"] != itemID.String() || fields["size_bytes"] != float64(size) {
|
||||
t.Fatalf("canonical event fields = %+v", fields)
|
||||
}
|
||||
if _, ok := fields["occurred_at"].(string); !ok || len(fields) != 4 {
|
||||
t.Fatalf("canonical event includes unexpected fields: %+v", fields)
|
||||
}
|
||||
for _, forbidden := range []string{"answer", "answer_text", "clipboard", "content", "organization_id", "score"} {
|
||||
if strings.Contains(string(encoded), forbidden) {
|
||||
t.Errorf("canonical request contains forbidden term %q", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignalIdempotencyFingerprintBindsAttemptAndRejectsInvalidKeys(t *testing.T) {
|
||||
actorID, itemID := uuid.New(), uuid.New()
|
||||
at := time.Now().UTC().Truncate(time.Microsecond)
|
||||
event, err := domain.NewAssessmentSignalEvent(domain.AssessmentSignalEventInput{
|
||||
Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: itemID, OccurredAt: at,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentSignalEvent() error = %v", err)
|
||||
}
|
||||
service := &SignalService{keyring: signalKeyring{}}
|
||||
command := RecordSignalsCommand{ActorID: actorID, AttemptID: domain.AssessmentAttemptID(uuid.New()), IdempotencyKey: "same-key", Events: []domain.AssessmentSignalEvent{event}}
|
||||
_, firstBody, err := canonicalSignalBody(command)
|
||||
if err != nil {
|
||||
t.Fatalf("canonicalSignalBody(first) error = %v", err)
|
||||
}
|
||||
first, err := service.prepareSignalIdempotency(command, firstBody, at)
|
||||
if err != nil {
|
||||
t.Fatalf("prepareSignalIdempotency(first) error = %v", err)
|
||||
}
|
||||
command.AttemptID = domain.AssessmentAttemptID(uuid.New())
|
||||
_, secondBody, err := canonicalSignalBody(command)
|
||||
if err != nil {
|
||||
t.Fatalf("canonicalSignalBody(second) error = %v", err)
|
||||
}
|
||||
second, err := service.prepareSignalIdempotency(command, secondBody, at)
|
||||
if err != nil {
|
||||
t.Fatalf("prepareSignalIdempotency(second) error = %v", err)
|
||||
}
|
||||
if first.scope != second.scope || first.record.Fingerprint == second.record.Fingerprint {
|
||||
t.Fatal("same actor key should share its scope and reject a different attempt body")
|
||||
}
|
||||
for _, invalidKey := range []string{"", strings.Repeat("a", maxAttemptIdempotencyKeyBytes+1), "key with spaces"} {
|
||||
command.IdempotencyKey = invalidKey
|
||||
if _, err := service.prepareSignalIdempotency(command, secondBody, at); !errors.Is(err, ErrInvalidAttemptKey) {
|
||||
t.Errorf("prepareSignalIdempotency(%q) error = %v, want ErrInvalidAttemptKey", invalidKey, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanonicalSignalBodyRejectsUnbuiltEvents(t *testing.T) {
|
||||
_, _, err := canonicalSignalBody(RecordSignalsCommand{
|
||||
ActorID: uuid.New(), AttemptID: domain.AssessmentAttemptID(uuid.New()),
|
||||
Events: []domain.AssessmentSignalEvent{{}},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("canonicalSignalBody() accepted a zero event")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,565 @@
|
||||
// Package candidateprivacy implements candidate-owned publication and privacy
|
||||
// settings. Every command is scoped to the authenticated candidate.
|
||||
package candidateprivacy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrForbidden = errors.New("candidate privacy operation is forbidden")
|
||||
ErrEmailNotVerified = errors.New("candidate email is not verified")
|
||||
ErrPrivacyServiceUnavailable = errors.New("candidate privacy service is unavailable")
|
||||
ErrHiddenOrganizationNotFound = errors.New("hidden organization not found")
|
||||
)
|
||||
|
||||
// Dependencies configure the candidate privacy settings service.
|
||||
type Dependencies struct {
|
||||
Transactor outbound.Transactor
|
||||
Clock func() time.Time
|
||||
}
|
||||
|
||||
// Service applies candidate-owned privacy settings in one transaction.
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
func NewService(deps Dependencies) (*Service, error) {
|
||||
if deps.Transactor == nil || deps.Clock == nil {
|
||||
return nil, fmt.Errorf("candidateprivacy.NewService - dependencies are missing: %w", ErrPrivacyServiceUnavailable)
|
||||
}
|
||||
return &Service{transactor: deps.Transactor, clock: deps.Clock}, nil
|
||||
}
|
||||
|
||||
func (service *Service) GetMyPrivacySettings(ctx context.Context, userID uuid.UUID) (outbound.CandidatePrivacySettings, error) {
|
||||
const location = "candidateprivacy.Service.GetMyPrivacySettings"
|
||||
var result outbound.CandidatePrivacySettings
|
||||
at, err := service.now()
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeCandidate(ctx, unit, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
repository, err := settingsRepository(unit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err = repository.ReadSettings(ctx, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read candidate settings: %w", location, err)
|
||||
}
|
||||
result.AsOf = at
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (service *Service) SetMyPublication(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
expectedVersion int64,
|
||||
state domain.PublicationState,
|
||||
fields []domain.CardField,
|
||||
) (domain.Publication, error) {
|
||||
const location = "candidateprivacy.Service.SetMyPublication"
|
||||
request, err := domain.NewPublicationRequest(state, fields)
|
||||
if err != nil {
|
||||
return domain.Publication{}, err
|
||||
}
|
||||
at, err := service.now()
|
||||
if err != nil {
|
||||
return domain.Publication{}, err
|
||||
}
|
||||
var result domain.Publication
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeCandidate(ctx, unit, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
repository, err := settingsRepository(unit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
activeC2, err := currentC2ForPublication(ctx, repository, userID, location)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
settings, err := repository.ReadSettings(ctx, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read current publication: %w", location, err)
|
||||
}
|
||||
change, err := settings.Publication.Apply(request, expectedVersion, activeC2, at)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result = change.Publication
|
||||
if !change.Changed {
|
||||
return nil
|
||||
}
|
||||
return persistPublicationChange(ctx, unit, repository, userID, expectedVersion, change, at, location)
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Publication{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func currentC2ForPublication(
|
||||
ctx context.Context,
|
||||
repository outbound.PrivacySettingsRepository,
|
||||
userID uuid.UUID,
|
||||
location string,
|
||||
) (uuid.UUID, error) {
|
||||
activeC2, err := repository.LockCurrentC2ForPublication(ctx, userID)
|
||||
if errors.Is(err, outbound.ErrConsentNotFound) {
|
||||
return uuid.Nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - lock current C2: %w", location, err)
|
||||
}
|
||||
return activeC2, nil
|
||||
}
|
||||
|
||||
func persistPublicationChange(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repository outbound.PrivacySettingsRepository,
|
||||
userID uuid.UUID,
|
||||
expectedVersion int64,
|
||||
change domain.PublicationChange,
|
||||
at time.Time,
|
||||
location string,
|
||||
) error {
|
||||
if err := repository.SavePublication(ctx, change.Publication, expectedVersion); err != nil {
|
||||
return fmt.Errorf("%s - save publication: %w", location, err)
|
||||
}
|
||||
if change.Event == domain.PrivacyEventPublicationClosed {
|
||||
if err := closeContactGrants(ctx, unit.PrivacyView(), userID, uuid.Nil, at, location, "publication close"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
event, err := domain.NewPublicationEvent(change, at)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build publication history: %w", location, err)
|
||||
}
|
||||
if err := repository.RecordPrivacyEvent(ctx, event); err != nil {
|
||||
return fmt.Errorf("%s - record publication history: %w", location, err)
|
||||
}
|
||||
if change.Event != domain.PrivacyEventPublicationClosed {
|
||||
return nil
|
||||
}
|
||||
if err := appendVisibilityClosed(ctx, unit, userID, uuid.Nil, "publication_closed", at, event.ID()); err != nil {
|
||||
return fmt.Errorf("%s - append visibility closure intent: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func closeContactGrants(
|
||||
ctx context.Context,
|
||||
repository outbound.ContactAccessRepository,
|
||||
candidateID, organizationID uuid.UUID,
|
||||
at time.Time,
|
||||
location, reason string,
|
||||
) error {
|
||||
if repository == nil {
|
||||
return ErrPrivacyServiceUnavailable
|
||||
}
|
||||
if err := repository.CloseForVisibility(ctx, candidateID, organizationID, at); err != nil {
|
||||
return fmt.Errorf("%s - close contact grants after %s: %w", location, reason, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service *Service) SetMySearchStatus(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
expectedVersion int64,
|
||||
value domain.SearchStatusValue,
|
||||
) (domain.SearchStatus, time.Time, error) {
|
||||
const location = "candidateprivacy.Service.SetMySearchStatus"
|
||||
at, err := service.now()
|
||||
if err != nil {
|
||||
return domain.SearchStatus{}, time.Time{}, err
|
||||
}
|
||||
var result domain.SearchStatus
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeCandidate(ctx, unit, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
repository, err := settingsRepository(unit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
settings, err := repository.ReadSettings(ctx, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read current search status: %w", location, err)
|
||||
}
|
||||
var confirmation domain.SearchStatusConfirmation
|
||||
if value == domain.SearchStatusLooking && expectedVersion == settings.SearchStatus.Version() {
|
||||
policyVersion, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, at)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read effective product policy: %w", location, err)
|
||||
}
|
||||
confirmation, err = domain.NewSearchStatusConfirmation(policyVersion.ID(), policyVersion.Policy().SearchStatus)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build search status confirmation: %w", location, err)
|
||||
}
|
||||
}
|
||||
change, err := settings.SearchStatus.Apply(value, expectedVersion, confirmation, at)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result = change.Status
|
||||
if !change.Changed {
|
||||
return nil
|
||||
}
|
||||
if err := repository.SaveSearchStatus(ctx, change.Status, expectedVersion, at); err != nil {
|
||||
return fmt.Errorf("%s - save search status: %w", location, err)
|
||||
}
|
||||
event, err := domain.NewSearchStatusEvent(change, at)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build search status history: %w", location, err)
|
||||
}
|
||||
if err := repository.RecordPrivacyEvent(ctx, event); err != nil {
|
||||
return fmt.Errorf("%s - record search status history: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.SearchStatus{}, time.Time{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, at, nil
|
||||
}
|
||||
|
||||
func (service *Service) ListMyPrivacyHistory(
|
||||
ctx context.Context,
|
||||
query outbound.CandidatePrivacyEventListQuery,
|
||||
) (outbound.CandidatePrivacyEventPage, error) {
|
||||
const location = "candidateprivacy.Service.ListMyPrivacyHistory"
|
||||
if err := validatePage(query.UserID, query.Limit, query.After); err != nil {
|
||||
return outbound.CandidatePrivacyEventPage{}, err
|
||||
}
|
||||
var result outbound.CandidatePrivacyEventPage
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeCandidate(ctx, unit, query.UserID); err != nil {
|
||||
return err
|
||||
}
|
||||
repository, err := settingsRepository(unit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err = repository.ListPrivacyEvents(ctx, query)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - list privacy history: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.CandidatePrivacyEventPage{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (service *Service) ListMyHiddenOrganizations(
|
||||
ctx context.Context,
|
||||
query outbound.HiddenOrganizationListQuery,
|
||||
) (outbound.HiddenOrganizationPage, error) {
|
||||
const location = "candidateprivacy.Service.ListMyHiddenOrganizations"
|
||||
if err := validatePage(query.UserID, query.Limit, query.After); err != nil {
|
||||
return outbound.HiddenOrganizationPage{}, err
|
||||
}
|
||||
var result outbound.HiddenOrganizationPage
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeCandidate(ctx, unit, query.UserID); err != nil {
|
||||
return err
|
||||
}
|
||||
repository, err := settingsRepository(unit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err = repository.ListHiddenOrganizations(ctx, query)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - list hidden organizations: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.HiddenOrganizationPage{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (service *Service) HideOrganization(
|
||||
ctx context.Context,
|
||||
userID, organizationID uuid.UUID,
|
||||
) (outbound.HiddenOrganizationRecord, error) {
|
||||
const location = "candidateprivacy.Service.HideOrganization"
|
||||
at, err := service.now()
|
||||
if err != nil {
|
||||
return outbound.HiddenOrganizationRecord{}, err
|
||||
}
|
||||
var result outbound.HiddenOrganizationRecord
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeCandidate(ctx, unit, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
repository, err := settingsRepository(unit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err = service.hideOrganizationInTransaction(ctx, unit, repository, userID, organizationID, at, location)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.HiddenOrganizationRecord{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (service *Service) hideOrganizationInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repository outbound.PrivacySettingsRepository,
|
||||
userID, organizationID uuid.UUID,
|
||||
at time.Time,
|
||||
location string,
|
||||
) (outbound.HiddenOrganizationRecord, error) {
|
||||
visible, err := repository.CandidateCanSeeOrganization(ctx, userID, organizationID)
|
||||
if err != nil {
|
||||
return outbound.HiddenOrganizationRecord{}, fmt.Errorf("%s - verify organization visibility: %w", location, err)
|
||||
}
|
||||
result := outbound.HiddenOrganizationRecord{OrganizationID: visible.ID, OrganizationName: visible.Name}
|
||||
current, err := repository.GetHiddenOrganization(ctx, userID, organizationID)
|
||||
if err == nil {
|
||||
result.HiddenAt = current.HiddenAt
|
||||
return result, closeContactGrants(ctx, unit.PrivacyView(), userID, organizationID, at, location, "organization hiding")
|
||||
}
|
||||
if !errors.Is(err, outbound.ErrCandidatePrivacySettingsNotFound) {
|
||||
return outbound.HiddenOrganizationRecord{}, fmt.Errorf("%s - read existing hiding: %w", location, err)
|
||||
}
|
||||
hiddenAt, created, err := createOrganizationHiding(ctx, repository, userID, organizationID, at, location)
|
||||
if err != nil {
|
||||
return outbound.HiddenOrganizationRecord{}, err
|
||||
}
|
||||
result.HiddenAt = hiddenAt
|
||||
if !created {
|
||||
return result, nil
|
||||
}
|
||||
if err := persistOrganizationHiding(ctx, unit, repository, userID, organizationID, at, location); err != nil {
|
||||
return outbound.HiddenOrganizationRecord{}, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func createOrganizationHiding(
|
||||
ctx context.Context,
|
||||
repository outbound.PrivacySettingsRepository,
|
||||
userID, organizationID uuid.UUID,
|
||||
at time.Time,
|
||||
location string,
|
||||
) (time.Time, bool, error) {
|
||||
count, err := repository.CountHiddenOrganizations(ctx, userID)
|
||||
if err != nil {
|
||||
return time.Time{}, false, fmt.Errorf("%s - count hidden organizations: %w", location, err)
|
||||
}
|
||||
if count >= domain.MaxHiddenOrganizations {
|
||||
return time.Time{}, false, outbound.ErrCandidateHiddenOrganizationLimit
|
||||
}
|
||||
hidden, err := domain.NewHiddenOrganization(userID, organizationID, at)
|
||||
if err != nil {
|
||||
return time.Time{}, false, err
|
||||
}
|
||||
created, err := repository.HideOrganization(ctx, hidden)
|
||||
if err != nil {
|
||||
return time.Time{}, false, fmt.Errorf("%s - store hiding: %w", location, err)
|
||||
}
|
||||
if created {
|
||||
return at, true, nil
|
||||
}
|
||||
current, err := repository.GetHiddenOrganization(ctx, userID, organizationID)
|
||||
if err != nil {
|
||||
return time.Time{}, false, fmt.Errorf("%s - read concurrent hiding: %w", location, err)
|
||||
}
|
||||
return current.HiddenAt, false, nil
|
||||
}
|
||||
|
||||
func persistOrganizationHiding(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repository outbound.PrivacySettingsRepository,
|
||||
userID, organizationID uuid.UUID,
|
||||
at time.Time,
|
||||
location string,
|
||||
) error {
|
||||
if err := closeContactGrants(ctx, unit.PrivacyView(), userID, organizationID, at, location, "organization hiding"); err != nil {
|
||||
return err
|
||||
}
|
||||
event, err := domain.NewOrganizationEvent(domain.PrivacyEventOrganizationHidden, userID, organizationID, at)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build hiding history: %w", location, err)
|
||||
}
|
||||
if err := repository.RecordPrivacyEvent(ctx, event); err != nil {
|
||||
return fmt.Errorf("%s - record hiding history: %w", location, err)
|
||||
}
|
||||
if err := appendVisibilityClosed(ctx, unit, userID, organizationID, "organization_hidden", at, event.ID()); err != nil {
|
||||
return fmt.Errorf("%s - append visibility closure intent: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service *Service) UnhideOrganization(ctx context.Context, userID, organizationID uuid.UUID) error {
|
||||
const location = "candidateprivacy.Service.UnhideOrganization"
|
||||
at, err := service.now()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeCandidate(ctx, unit, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
repository, err := settingsRepository(unit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
deleted, err := repository.UnhideOrganization(ctx, userID, organizationID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - delete hiding: %w", location, err)
|
||||
}
|
||||
if !deleted {
|
||||
return nil
|
||||
}
|
||||
event, err := domain.NewOrganizationEvent(domain.PrivacyEventOrganizationUnhidden, userID, organizationID, at)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build unhiding history: %w", location, err)
|
||||
}
|
||||
if err := repository.RecordPrivacyEvent(ctx, event); err != nil {
|
||||
return fmt.Errorf("%s - record unhiding history: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service *Service) now() (time.Time, error) {
|
||||
at := service.clock().UTC().Truncate(time.Microsecond)
|
||||
if at.IsZero() {
|
||||
return time.Time{}, fmt.Errorf("candidateprivacy.Service - clock returned zero: %w", ErrPrivacyServiceUnavailable)
|
||||
}
|
||||
return at, nil
|
||||
}
|
||||
|
||||
func validatePage(userID uuid.UUID, limit int32, after any) error {
|
||||
if userID == uuid.Nil || limit < 1 || limit > outbound.MaxPrivacyPageSize {
|
||||
return domain.ErrInvalidVisibility
|
||||
}
|
||||
switch position := after.(type) {
|
||||
case nil:
|
||||
case *outbound.CandidatePrivacyEventPosition:
|
||||
if position != nil && (position.ID == uuid.Nil || position.OccurredAt.IsZero()) {
|
||||
return domain.ErrInvalidVisibility
|
||||
}
|
||||
case *outbound.HiddenOrganizationPosition:
|
||||
if position != nil && (position.OrganizationID == uuid.Nil || position.HiddenAt.IsZero()) {
|
||||
return domain.ErrInvalidVisibility
|
||||
}
|
||||
default:
|
||||
return domain.ErrInvalidVisibility
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func authorizeCandidate(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID) error {
|
||||
if userID == uuid.Nil {
|
||||
return ErrForbidden
|
||||
}
|
||||
user, err := unit.Users().GetByID(ctx, userID)
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return ErrForbidden
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("candidateprivacy.authorizeCandidate - read account: %w", err)
|
||||
}
|
||||
if user.Scenario != domain.ScenarioCandidate {
|
||||
return ErrForbidden
|
||||
}
|
||||
if !user.EmailVerified() {
|
||||
return ErrEmailNotVerified
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func settingsRepository(unit outbound.UnitOfWork) (outbound.PrivacySettingsRepository, error) {
|
||||
repository := unit.PrivacySettings()
|
||||
if repository == nil {
|
||||
return nil, ErrPrivacyServiceUnavailable
|
||||
}
|
||||
return repository, nil
|
||||
}
|
||||
|
||||
type visibilityClosedPayload struct {
|
||||
CandidateID uuid.UUID `json:"candidate_id"`
|
||||
OrganizationID *uuid.UUID `json:"organization_id"`
|
||||
Reason string `json:"reason"`
|
||||
OccurredAt time.Time `json:"occurred_at"`
|
||||
PrivacyEventID uuid.UUID `json:"privacy_event_id"`
|
||||
}
|
||||
|
||||
func appendVisibilityClosed(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
candidateID, organizationID uuid.UUID,
|
||||
reason string,
|
||||
at time.Time,
|
||||
privacyEventID uuid.UUID,
|
||||
) error {
|
||||
const location = "candidateprivacy.appendVisibilityClosed"
|
||||
if candidateID == uuid.Nil || privacyEventID == uuid.Nil || at.IsZero() ||
|
||||
(reason != "publication_closed" && reason != "organization_hidden") ||
|
||||
(reason == "organization_hidden" && organizationID == uuid.Nil) ||
|
||||
(reason == "publication_closed" && organizationID != uuid.Nil) {
|
||||
return fmt.Errorf("%s - closure facts are invalid: %w", location, domain.ErrInvalidDomainEvent)
|
||||
}
|
||||
var organization *uuid.UUID
|
||||
if organizationID != uuid.Nil {
|
||||
organization = &organizationID
|
||||
}
|
||||
payload, err := json.Marshal(visibilityClosedPayload{
|
||||
CandidateID: candidateID, OrganizationID: organization, Reason: reason,
|
||||
OccurredAt: at.UTC().Truncate(time.Microsecond), PrivacyEventID: privacyEventID,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - encode payload", location)
|
||||
}
|
||||
event, err := domain.NewDomainEvent(domain.DomainEventInput{
|
||||
EventType: "privacy.visibility_closed", SchemaVersion: 1,
|
||||
AggregateType: "privacy_event", AggregateID: privacyEventID, AggregateVersion: 1, Payload: payload,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build event: %w", location, err)
|
||||
}
|
||||
writer := unit.Outbox()
|
||||
if writer == nil {
|
||||
return fmt.Errorf("%s - transactional outbox is unavailable: %w", location, ErrPrivacyServiceUnavailable)
|
||||
}
|
||||
if err := writer.Append(ctx, event); err != nil {
|
||||
return fmt.Errorf("%s - append event: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package candidateprivacy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestPublicationCloseWritesHistoryAndTransactionalClosureIntentOnce(t *testing.T) {
|
||||
const now = "2026-10-07T12:00:00.123456Z"
|
||||
at := mustTime(t, now)
|
||||
candidateID, consentID := uuid.New(), uuid.New()
|
||||
initial := mustPublished(t, candidateID, consentID, at.Add(-time.Hour))
|
||||
transactor := &privacyTestTransactor{
|
||||
user: domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: timePointer(at)},
|
||||
publication: initial,
|
||||
}
|
||||
service := mustPrivacyService(t, transactor, at)
|
||||
|
||||
closed, err := service.SetMyPublication(context.Background(), candidateID, initial.Version(), domain.PublicationClosed, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("SetMyPublication(close) error = %v", err)
|
||||
}
|
||||
if closed.StoredState() != domain.PublicationClosed || closed.Version() != initial.Version()+1 {
|
||||
t.Fatalf("close result = %s v%d, want closed v%d", closed.StoredState(), closed.Version(), initial.Version()+1)
|
||||
}
|
||||
if len(transactor.history) != 1 || len(transactor.outboxEvents) != 1 || len(transactor.closureCalls) != 1 {
|
||||
t.Fatalf("committed close effects = history %d, outbox %d, grants %d; want one each", len(transactor.history), len(transactor.outboxEvents), len(transactor.closureCalls))
|
||||
}
|
||||
if got := transactor.sequence; fmt.Sprint(got) != "[close history outbox]" {
|
||||
t.Fatalf("closure order = %v, want close -> history -> outbox", got)
|
||||
}
|
||||
assertVisibilityClosedEvent(t, transactor.outboxEvents[0], candidateID, uuid.Nil, transactor.history[0].ID(), at)
|
||||
|
||||
_, err = service.SetMyPublication(context.Background(), candidateID, closed.Version(), domain.PublicationClosed, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("repeated SetMyPublication(close) error = %v", err)
|
||||
}
|
||||
if len(transactor.history) != 1 || len(transactor.outboxEvents) != 1 || len(transactor.closureCalls) != 1 {
|
||||
t.Fatalf("repeated close effects = history %d, outbox %d, grants %d; want no duplicate intent", len(transactor.history), len(transactor.outboxEvents), len(transactor.closureCalls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatePageAcceptsTypedNilInitialCursors(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var privacyCursor *outbound.CandidatePrivacyEventPosition
|
||||
var hiddenCursor *outbound.HiddenOrganizationPosition
|
||||
userID := uuid.New()
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
after any
|
||||
}{
|
||||
{name: "privacy history", after: privacyCursor},
|
||||
{name: "hidden organizations", after: hiddenCursor},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
if err := validatePage(userID, 20, test.after); err != nil {
|
||||
t.Fatalf("validatePage(initial cursor) error = %v, want nil", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicationCloseRollsBackWhenClosureIntentCannotBeStored(t *testing.T) {
|
||||
at := mustTime(t, "2026-10-07T12:00:00.123456Z")
|
||||
candidateID, consentID := uuid.New(), uuid.New()
|
||||
initial := mustPublished(t, candidateID, consentID, at.Add(-time.Hour))
|
||||
transactor := &privacyTestTransactor{
|
||||
user: domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: timePointer(at)},
|
||||
publication: initial, outboxError: errors.New("outbox unavailable"),
|
||||
}
|
||||
service := mustPrivacyService(t, transactor, at)
|
||||
|
||||
if _, err := service.SetMyPublication(context.Background(), candidateID, initial.Version(), domain.PublicationClosed, nil); err == nil {
|
||||
t.Fatal("SetMyPublication(close) error = nil, want closure intent failure")
|
||||
}
|
||||
if transactor.publication.Version() != initial.Version() || transactor.publication.StoredState() != domain.PublicationPublished {
|
||||
t.Fatalf("publication after failed transaction = %s v%d, want unchanged published v%d", transactor.publication.StoredState(), transactor.publication.Version(), initial.Version())
|
||||
}
|
||||
if len(transactor.history) != 0 || len(transactor.outboxEvents) != 0 || len(transactor.closureCalls) != 0 {
|
||||
t.Fatalf("effects after failed transaction = history %d, outbox %d, grants %d; want rollback", len(transactor.history), len(transactor.outboxEvents), len(transactor.closureCalls))
|
||||
}
|
||||
}
|
||||
|
||||
func mustPrivacyService(t *testing.T, transactor outbound.Transactor, at time.Time) *Service {
|
||||
t.Helper()
|
||||
service, err := NewService(Dependencies{Transactor: transactor, Clock: func() time.Time { return at }})
|
||||
if err != nil {
|
||||
t.Fatalf("NewService() error = %v", err)
|
||||
}
|
||||
return service
|
||||
}
|
||||
|
||||
func mustPublished(t *testing.T, candidateID, consentID uuid.UUID, at time.Time) domain.Publication {
|
||||
t.Helper()
|
||||
publication, err := domain.NewPublication(candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("NewPublication() error = %v", err)
|
||||
}
|
||||
request, err := domain.NewPublicationRequest(domain.PublicationPublished, []domain.CardField{domain.CardFieldStack})
|
||||
if err != nil {
|
||||
t.Fatalf("NewPublicationRequest() error = %v", err)
|
||||
}
|
||||
change, err := publication.Apply(request, 0, consentID, at)
|
||||
if err != nil || !change.Changed {
|
||||
t.Fatalf("Apply(publish) = %+v, %v, want change", change, err)
|
||||
}
|
||||
return change.Publication
|
||||
}
|
||||
|
||||
func assertVisibilityClosedEvent(t *testing.T, event domain.DomainEvent, candidateID, organizationID, privacyEventID uuid.UUID, at time.Time) {
|
||||
t.Helper()
|
||||
if event.EventType() != "privacy.visibility_closed" || event.SchemaVersion() != 1 ||
|
||||
event.AggregateType() != "privacy_event" || event.AggregateID() != privacyEventID || event.AggregateVersion() != 1 {
|
||||
t.Fatalf("closure event identity = %s v%d %s/%s v%d", event.EventType(), event.SchemaVersion(), event.AggregateType(), event.AggregateID(), event.AggregateVersion())
|
||||
}
|
||||
var payload struct {
|
||||
CandidateID uuid.UUID `json:"candidate_id"`
|
||||
OrganizationID *uuid.UUID `json:"organization_id"`
|
||||
Reason string `json:"reason"`
|
||||
OccurredAt time.Time `json:"occurred_at"`
|
||||
PrivacyEventID uuid.UUID `json:"privacy_event_id"`
|
||||
}
|
||||
if err := json.Unmarshal(event.Payload(), &payload); err != nil {
|
||||
t.Fatalf("decode closure payload: %v", err)
|
||||
}
|
||||
if payload.CandidateID != candidateID || payload.Reason != "publication_closed" ||
|
||||
payload.PrivacyEventID != privacyEventID || !payload.OccurredAt.Equal(at) || payload.OrganizationID != nil || organizationID != uuid.Nil {
|
||||
t.Fatalf("closure payload = %+v", payload)
|
||||
}
|
||||
}
|
||||
|
||||
func mustTime(t *testing.T, value string) time.Time {
|
||||
t.Helper()
|
||||
at, err := time.Parse(time.RFC3339Nano, value)
|
||||
if err != nil {
|
||||
t.Fatalf("parse test time: %v", err)
|
||||
}
|
||||
return at
|
||||
}
|
||||
|
||||
func timePointer(value time.Time) *time.Time { return &value }
|
||||
|
||||
type privacyTestTransactor struct {
|
||||
user domain.User
|
||||
publication domain.Publication
|
||||
history []domain.PrivacyEvent
|
||||
outboxEvents []domain.DomainEvent
|
||||
closureCalls []privacyClosureCall
|
||||
sequence []string
|
||||
outboxError error
|
||||
}
|
||||
|
||||
type privacyClosureCall struct {
|
||||
candidateID uuid.UUID
|
||||
organizationID uuid.UUID
|
||||
at time.Time
|
||||
}
|
||||
|
||||
func (transactor *privacyTestTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error {
|
||||
draft := &privacyTestTransactor{
|
||||
user: transactor.user, publication: transactor.publication,
|
||||
history: append([]domain.PrivacyEvent(nil), transactor.history...),
|
||||
outboxEvents: append([]domain.DomainEvent(nil), transactor.outboxEvents...),
|
||||
closureCalls: append([]privacyClosureCall(nil), transactor.closureCalls...),
|
||||
sequence: append([]string(nil), transactor.sequence...), outboxError: transactor.outboxError,
|
||||
}
|
||||
unit := privacyTestUnit{
|
||||
users: privacyTestUsers{user: draft.user},
|
||||
settings: privacyTestSettings{transactor: draft},
|
||||
view: privacyTestView{transactor: draft},
|
||||
outbox: privacyTestOutbox{transactor: draft},
|
||||
}
|
||||
if err := fn(ctx, unit); err != nil {
|
||||
return err
|
||||
}
|
||||
transactor.publication = draft.publication
|
||||
transactor.history = draft.history
|
||||
transactor.outboxEvents = draft.outboxEvents
|
||||
transactor.closureCalls = draft.closureCalls
|
||||
transactor.sequence = draft.sequence
|
||||
return nil
|
||||
}
|
||||
|
||||
type privacyTestUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
users outbound.UserRepository
|
||||
settings outbound.PrivacySettingsRepository
|
||||
view outbound.PrivacyViewRepository
|
||||
outbox outbound.OutboxWriter
|
||||
}
|
||||
|
||||
func (unit privacyTestUnit) Users() outbound.UserRepository { return unit.users }
|
||||
func (unit privacyTestUnit) PrivacySettings() outbound.PrivacySettingsRepository {
|
||||
return unit.settings
|
||||
}
|
||||
func (unit privacyTestUnit) PrivacyView() outbound.PrivacyViewRepository { return unit.view }
|
||||
func (unit privacyTestUnit) Outbox() outbound.OutboxWriter { return unit.outbox }
|
||||
|
||||
type privacyTestUsers struct {
|
||||
outbound.UserRepository
|
||||
|
||||
user domain.User
|
||||
}
|
||||
|
||||
func (users privacyTestUsers) GetByID(context.Context, uuid.UUID) (domain.User, error) {
|
||||
return users.user, nil
|
||||
}
|
||||
|
||||
type privacyTestSettings struct {
|
||||
outbound.PrivacySettingsRepository
|
||||
|
||||
transactor *privacyTestTransactor
|
||||
}
|
||||
|
||||
func (settings privacyTestSettings) ReadSettings(context.Context, uuid.UUID) (outbound.CandidatePrivacySettings, error) {
|
||||
return outbound.CandidatePrivacySettings{Publication: settings.transactor.publication}, nil
|
||||
}
|
||||
|
||||
func (settings privacyTestSettings) LockCurrentC2ForPublication(context.Context, uuid.UUID) (uuid.UUID, error) {
|
||||
return settings.transactor.publication.ConsentRecordID(), nil
|
||||
}
|
||||
|
||||
func (settings privacyTestSettings) SavePublication(_ context.Context, publication domain.Publication, _ int64) error {
|
||||
settings.transactor.publication = publication
|
||||
return nil
|
||||
}
|
||||
|
||||
func (settings privacyTestSettings) RecordPrivacyEvent(_ context.Context, event domain.PrivacyEvent) error {
|
||||
settings.transactor.history = append(settings.transactor.history, event)
|
||||
settings.transactor.sequence = append(settings.transactor.sequence, "history")
|
||||
return nil
|
||||
}
|
||||
|
||||
type privacyTestView struct {
|
||||
outbound.PrivacyViewRepository
|
||||
|
||||
transactor *privacyTestTransactor
|
||||
}
|
||||
|
||||
func (view privacyTestView) CloseForVisibility(_ context.Context, candidateID, organizationID uuid.UUID, at time.Time) error {
|
||||
view.transactor.closureCalls = append(view.transactor.closureCalls, privacyClosureCall{
|
||||
candidateID: candidateID, organizationID: organizationID, at: at,
|
||||
})
|
||||
view.transactor.sequence = append(view.transactor.sequence, "close")
|
||||
return nil
|
||||
}
|
||||
|
||||
type privacyTestOutbox struct {
|
||||
outbound.OutboxWriter
|
||||
|
||||
transactor *privacyTestTransactor
|
||||
}
|
||||
|
||||
func (outbox privacyTestOutbox) Append(_ context.Context, events ...domain.DomainEvent) error {
|
||||
if outbox.transactor.outboxError != nil {
|
||||
return outbox.transactor.outboxError
|
||||
}
|
||||
outbox.transactor.outboxEvents = append(outbox.transactor.outboxEvents, events...)
|
||||
outbox.transactor.sequence = append(outbox.transactor.sequence, "outbox")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
package candidateview
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type contactAccessFixture struct {
|
||||
fields domain.ContactFieldSet
|
||||
grantActive bool
|
||||
workflowAccept bool
|
||||
audits []domain.CandidateCardAccess
|
||||
}
|
||||
|
||||
func TestCurrentContactFieldsUsesOnlyCurrentGrantFields(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
selected, err := domain.NewContactFieldSet(domain.ContactFieldPhone, domain.ContactFieldEmail)
|
||||
if err != nil {
|
||||
t.Fatalf("NewContactFieldSet() error = %v", err)
|
||||
}
|
||||
full, err := domain.NewContactFieldSet(
|
||||
domain.ContactFieldEmail, domain.ContactFieldFullName,
|
||||
domain.ContactFieldPhone, domain.ContactFieldTelegram,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("NewContactFieldSet(full) error = %v", err)
|
||||
}
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
grantFields domain.ContactFieldSet
|
||||
grantActive bool
|
||||
workflowAccept bool
|
||||
wantFields []domain.ContactField
|
||||
wantError error
|
||||
}{
|
||||
{
|
||||
name: "active invitation C4 returns only selected fields",
|
||||
grantFields: selected, grantActive: true, workflowAccept: true,
|
||||
wantFields: []domain.ContactField{domain.ContactFieldEmail, domain.ContactFieldPhone},
|
||||
},
|
||||
{
|
||||
name: "accepted workflow without a C4 grant remains closed",
|
||||
grantFields: full, workflowAccept: true, wantError: outbound.ErrContactAccessClosed,
|
||||
},
|
||||
{
|
||||
name: "revoked C4 remains closed after workflow acceptance",
|
||||
grantFields: selected, workflowAccept: true, wantError: outbound.ErrContactAccessClosed,
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
service, fixture, actorID, organizationID, handle := newContactAccessService(t, test.grantFields, test.grantActive, test.workflowAccept)
|
||||
|
||||
got, err := service.CurrentContactFields(context.Background(), actorID, organizationID, handle)
|
||||
if test.wantError != nil {
|
||||
if !errors.Is(err, test.wantError) {
|
||||
t.Fatalf("CurrentContactFields() error = %v, want %v", err, test.wantError)
|
||||
}
|
||||
if len(fixture.audits) != 0 {
|
||||
t.Fatalf("closed contact read recorded audits: %v", fixture.audits)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("CurrentContactFields() error = %v", err)
|
||||
}
|
||||
if gotFields := got.Fields(); !slices.Equal(gotFields, test.wantFields) {
|
||||
t.Fatalf("CurrentContactFields() fields = %v, want %v", gotFields, test.wantFields)
|
||||
}
|
||||
if len(fixture.audits) != 1 || fixture.audits[0].Kind() != domain.CandidateCardAccessContactRead ||
|
||||
!slices.Equal(fixture.audits[0].FieldCodes(), []string{"email", "phone"}) {
|
||||
t.Fatalf("contact read audit = %v, want only selected email and phone codes", fixture.audits)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func newContactAccessService(
|
||||
t *testing.T,
|
||||
fields domain.ContactFieldSet,
|
||||
grantActive, workflowAccepted bool,
|
||||
) (*Service, *contactAccessFixture, uuid.UUID, uuid.UUID, string) {
|
||||
t.Helper()
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
actorID, candidateID := uuid.New(), uuid.New()
|
||||
organization, membership := newContactAccessOrganization(t, actorID, now)
|
||||
organizationID := organization.ID()
|
||||
actor := domain.User{ID: actorID, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &now}
|
||||
candidate := domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
|
||||
users := contactAccessUsers{users: map[uuid.UUID]domain.User{actorID: actor, candidateID: candidate}}
|
||||
organizations := contactAccessOrganizations{organization: organization, membership: membership}
|
||||
publication, err := domain.NewCardFieldSet([]domain.CardField{domain.CardFieldStack})
|
||||
if err != nil {
|
||||
t.Fatalf("NewCardFieldSet() error = %v", err)
|
||||
}
|
||||
source, err := domain.NewCandidateViewSource(candidateID, publication, domain.CandidateViewProfile{}, nil, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewSource() error = %v", err)
|
||||
}
|
||||
key, err := domain.NewCandidateViewPseudonymKey(bytes.Repeat([]byte("contact-view-key"), 2))
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
handle, err := key.ForOrganization(organizationID, candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() error = %v", err)
|
||||
}
|
||||
fixture := &contactAccessFixture{
|
||||
fields: fields, grantActive: grantActive, workflowAccept: workflowAccepted,
|
||||
}
|
||||
viewRepository := contactAccessViewRepository{fixture: fixture, source: source}
|
||||
unit := contactAccessUnit{users: users, organizations: organizations, view: viewRepository}
|
||||
service, err := NewService(Dependencies{
|
||||
Transactor: contactAccessTransactor{unit: unit},
|
||||
Projector: contactAccessProjector{key: key, source: source},
|
||||
PseudonymKey: key, Quota: func(context.Context, outbound.UnitOfWork, domain.Organization, uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
return outbound.CompanyQuotaDecision{Allowed: true}, nil
|
||||
}, Clock: func() time.Time { return now },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewService() error = %v", err)
|
||||
}
|
||||
return service, fixture, actorID, organizationID, handle
|
||||
}
|
||||
|
||||
func newContactAccessOrganization(t *testing.T, actorID uuid.UUID, at time.Time) (domain.Organization, domain.Membership) {
|
||||
t.Helper()
|
||||
profile, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{
|
||||
Name: "Example Company", Description: "A sample company", Sphere: "Technology",
|
||||
Contacts: domain.OrganizationContactsInput{Website: "https://example.com", Email: "jobs@example.com", Phone: "+12025550101", Telegram: "@examplejobs"},
|
||||
Representatives: []domain.OrganizationRepresentativeInput{{Name: "Example Person", JobTitle: "Recruiter"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewOrganizationProfile() error = %v", err)
|
||||
}
|
||||
organization, err := domain.NewOrganization(profile, at)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOrganization() error = %v", err)
|
||||
}
|
||||
membership, err := domain.NewOwnerMembership(organization.ID(), actorID, at)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOwnerMembership() error = %v", err)
|
||||
}
|
||||
return organization, membership
|
||||
}
|
||||
|
||||
type contactAccessTransactor struct{ unit outbound.UnitOfWork }
|
||||
|
||||
func (transactor contactAccessTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error {
|
||||
return fn(ctx, transactor.unit)
|
||||
}
|
||||
|
||||
type contactAccessUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
users outbound.UserRepository
|
||||
organizations outbound.OrganizationRepository
|
||||
view outbound.PrivacyViewRepository
|
||||
}
|
||||
|
||||
func (unit contactAccessUnit) Users() outbound.UserRepository { return unit.users }
|
||||
func (unit contactAccessUnit) Organizations() outbound.OrganizationRepository {
|
||||
return unit.organizations
|
||||
}
|
||||
func (unit contactAccessUnit) PrivacyView() outbound.PrivacyViewRepository { return unit.view }
|
||||
|
||||
type contactAccessUsers struct {
|
||||
outbound.UserRepository
|
||||
|
||||
users map[uuid.UUID]domain.User
|
||||
}
|
||||
|
||||
func (repository contactAccessUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
|
||||
user, ok := repository.users[id]
|
||||
if !ok {
|
||||
return domain.User{}, outbound.ErrUserNotFound
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
type contactAccessOrganizations struct {
|
||||
outbound.OrganizationRepository
|
||||
|
||||
organization domain.Organization
|
||||
membership domain.Membership
|
||||
}
|
||||
|
||||
func (repository contactAccessOrganizations) LockActiveMembership(context.Context, uuid.UUID, uuid.UUID) (domain.Membership, error) {
|
||||
return repository.membership, nil
|
||||
}
|
||||
func (repository contactAccessOrganizations) GetForMember(context.Context, uuid.UUID, uuid.UUID) (domain.Organization, domain.Membership, error) {
|
||||
return repository.organization, repository.membership, nil
|
||||
}
|
||||
|
||||
type contactAccessViewRepository struct {
|
||||
outbound.PrivacyViewRepository
|
||||
|
||||
fixture *contactAccessFixture
|
||||
source domain.CandidateViewSource
|
||||
}
|
||||
|
||||
func (repository contactAccessViewRepository) ListVisibleCandidateViewSources(context.Context, uuid.UUID) ([]domain.CandidateViewSource, error) {
|
||||
return []domain.CandidateViewSource{repository.source}, nil
|
||||
}
|
||||
func (contactAccessViewRepository) LockCandidateAccountForView(context.Context, uuid.UUID) error {
|
||||
return nil
|
||||
}
|
||||
func (contactAccessViewRepository) LockCurrentC2ForView(context.Context, uuid.UUID) (uuid.UUID, error) {
|
||||
return uuid.New(), nil
|
||||
}
|
||||
func (contactAccessViewRepository) LockVisiblePublicationForView(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
func (repository contactAccessViewRepository) CurrentFields(context.Context, uuid.UUID, uuid.UUID) (domain.ContactFieldSet, error) {
|
||||
if !repository.fixture.grantActive {
|
||||
return domain.ContactFieldSet{}, outbound.ErrContactAccessClosed
|
||||
}
|
||||
return repository.fixture.fields, nil
|
||||
}
|
||||
func (repository contactAccessViewRepository) RecordCandidateCardAccess(_ context.Context, access domain.CandidateCardAccess) error {
|
||||
repository.fixture.audits = append(repository.fixture.audits, access)
|
||||
return nil
|
||||
}
|
||||
|
||||
type contactAccessProjector struct {
|
||||
key domain.CandidateViewPseudonymKey
|
||||
source domain.CandidateViewSource
|
||||
}
|
||||
|
||||
func (projector contactAccessProjector) ProjectSources(organizationID uuid.UUID, sources []domain.CandidateViewSource) ([]domain.AnonymousCandidateViewDTO, error) {
|
||||
if len(sources) != 1 || sources[0].CandidateID() != projector.source.CandidateID() {
|
||||
return nil, errors.New("contact access test projector received an unexpected source")
|
||||
}
|
||||
pseudonym, err := projector.key.ForOrganization(organizationID, projector.source.CandidateID())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []domain.AnonymousCandidateViewDTO{{Pseudonym: pseudonym}}, nil
|
||||
}
|
||||
|
||||
func (projector contactAccessProjector) PreviewSource(domain.CandidateViewSource) (domain.AnonymousCandidateViewDTO, error) {
|
||||
return domain.AnonymousCandidateViewDTO{}, errors.New("preview is not part of the contact access test")
|
||||
}
|
||||
@@ -0,0 +1,515 @@
|
||||
// Package candidateview applies current publication, membership, hidden-
|
||||
// organization, cohort, and quota rules to anonymous candidate reads.
|
||||
package candidateview
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrForbidden = errors.New("candidate view is forbidden")
|
||||
ErrCandidateCardNotFound = errors.New("candidate card not found")
|
||||
ErrInvalidCandidateHandle = errors.New("candidate handle is invalid")
|
||||
ErrConcurrentVisibilityChange = errors.New("candidate visibility changed during read")
|
||||
ErrCandidateViewServiceMissing = errors.New("candidate view service is unavailable")
|
||||
ErrCandidateViewQuotaExceeded = errors.New("candidate view quota is exhausted")
|
||||
)
|
||||
|
||||
const maxCohortStabilizationPasses = 8
|
||||
|
||||
// Projector builds the shared, strict anonymous-card projection.
|
||||
type Projector interface {
|
||||
ProjectSources(organizationID uuid.UUID, sources []domain.CandidateViewSource) ([]domain.AnonymousCandidateViewDTO, error)
|
||||
PreviewSource(source domain.CandidateViewSource) (domain.AnonymousCandidateViewDTO, error)
|
||||
}
|
||||
|
||||
// CardViewQuota reserves the current policy's distinct card-view allowance.
|
||||
// Bootstrap adapts the shared company-quota usecase without making this
|
||||
// read-policy package depend on another usecase package.
|
||||
type CardViewQuota func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error)
|
||||
|
||||
// Dependencies configure the stateless candidate-view policy service.
|
||||
type Dependencies struct {
|
||||
Transactor outbound.Transactor
|
||||
Projector Projector
|
||||
PseudonymKey domain.CandidateViewPseudonymKey
|
||||
Quota CardViewQuota
|
||||
Clock func() time.Time
|
||||
}
|
||||
|
||||
// Service rechecks private visibility state in a transaction for each read.
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
projector Projector
|
||||
pseudonymKey domain.CandidateViewPseudonymKey
|
||||
quota CardViewQuota
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
func NewService(deps Dependencies) (*Service, error) {
|
||||
if deps.Transactor == nil || deps.Projector == nil || deps.Quota == nil || deps.Clock == nil {
|
||||
return nil, fmt.Errorf("candidateview.NewService - dependencies are missing: %w", ErrCandidateViewServiceMissing)
|
||||
}
|
||||
if _, err := deps.PseudonymKey.ForOrganization(uuid.New(), uuid.New()); err != nil {
|
||||
return nil, fmt.Errorf("candidateview.NewService - pseudonym key is invalid: %w", ErrCandidateViewServiceMissing)
|
||||
}
|
||||
return &Service{
|
||||
transactor: deps.Transactor, projector: deps.Projector, pseudonymKey: deps.PseudonymKey, quota: deps.Quota,
|
||||
clock: deps.Clock,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RateLimitedError carries only the retry time derived from the current
|
||||
// organization quota; it does not include candidate or organization values.
|
||||
type RateLimitedError struct{ RetryAt time.Time }
|
||||
|
||||
func (err *RateLimitedError) Error() string { return ErrCandidateViewQuotaExceeded.Error() }
|
||||
func (err *RateLimitedError) Unwrap() error { return ErrCandidateViewQuotaExceeded }
|
||||
|
||||
// GetOrganizationCard reads a handle only from the current, locked,
|
||||
// organization-visible cohort. Quota and the field-code audit commit with the
|
||||
// visibility checks, so failed reads leave neither behind.
|
||||
func (service *Service) GetOrganizationCard(
|
||||
ctx context.Context,
|
||||
actorID, organizationID uuid.UUID,
|
||||
handle string,
|
||||
) (domain.AnonymousCandidateViewDTO, error) {
|
||||
const location = "candidateview.Service.GetOrganizationCard"
|
||||
if actorID == uuid.Nil || organizationID == uuid.Nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, ErrForbidden
|
||||
}
|
||||
if !domain.IsCandidateViewPseudonym(handle) {
|
||||
return domain.AnonymousCandidateViewDTO{}, ErrInvalidCandidateHandle
|
||||
}
|
||||
var result domain.AnonymousCandidateViewDTO
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
view, err := service.getOrganizationCardInTransaction(ctx, unit, actorID, organizationID, handle, location)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result = view
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (service *Service) getOrganizationCardInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
actorID, organizationID uuid.UUID,
|
||||
handle, location string,
|
||||
) (domain.AnonymousCandidateViewDTO, error) {
|
||||
organization, repository, candidateID, view, err := service.currentOrganizationCard(ctx, unit, actorID, organizationID, handle, location)
|
||||
if err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, err
|
||||
}
|
||||
decision, err := service.quota(ctx, unit, organization, candidateID)
|
||||
if err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - reserve card view: %w", location, err)
|
||||
}
|
||||
if !decision.Allowed {
|
||||
return domain.AnonymousCandidateViewDTO{}, &RateLimitedError{RetryAt: decision.RetryAt.UTC()}
|
||||
}
|
||||
event, err := cardViewAccessEvent(candidateID, organizationID, actorID, view, service.clock())
|
||||
if err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - build access audit: %w", location, err)
|
||||
}
|
||||
if err := repository.RecordCandidateCardAccess(ctx, event); err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - record access audit: %w", location, err)
|
||||
}
|
||||
return view, nil
|
||||
}
|
||||
|
||||
func (service *Service) currentOrganizationCard(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
actorID, organizationID uuid.UUID,
|
||||
handle, location string,
|
||||
) (domain.Organization, outbound.PrivacyViewRepository, uuid.UUID, domain.AnonymousCandidateViewDTO, error) {
|
||||
organization, repository, sources, err := loadCurrentVisibleCohort(ctx, unit, actorID, organizationID, location)
|
||||
if err != nil {
|
||||
return domain.Organization{}, nil, uuid.Nil, domain.AnonymousCandidateViewDTO{}, err
|
||||
}
|
||||
candidateID, err := candidateIDForHandle(service, organizationID, sources, handle, location)
|
||||
if err != nil {
|
||||
return domain.Organization{}, nil, uuid.Nil, domain.AnonymousCandidateViewDTO{}, err
|
||||
}
|
||||
view, err := projectedViewForHandle(service, organizationID, sources, handle, location)
|
||||
if err != nil {
|
||||
return domain.Organization{}, nil, uuid.Nil, domain.AnonymousCandidateViewDTO{}, err
|
||||
}
|
||||
return organization, repository, candidateID, view, nil
|
||||
}
|
||||
|
||||
func loadCurrentVisibleCohort(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
actorID, organizationID uuid.UUID,
|
||||
location string,
|
||||
) (domain.Organization, outbound.PrivacyViewRepository, []domain.CandidateViewSource, error) {
|
||||
organization, err := authorizeEmployer(ctx, unit, actorID, organizationID)
|
||||
if err != nil {
|
||||
return domain.Organization{}, nil, nil, err
|
||||
}
|
||||
repository, err := privacyViewRepository(unit)
|
||||
if err != nil {
|
||||
return domain.Organization{}, nil, nil, err
|
||||
}
|
||||
sources, err := repository.ListVisibleCandidateViewSources(ctx, organizationID)
|
||||
if err != nil {
|
||||
return domain.Organization{}, nil, nil, fmt.Errorf("%s - read candidate cohort: %w", location, err)
|
||||
}
|
||||
sources, err = lockCurrentVisibleCohort(ctx, unit, repository, organizationID, sources)
|
||||
if err != nil {
|
||||
return domain.Organization{}, nil, nil, err
|
||||
}
|
||||
return organization, repository, sources, nil
|
||||
}
|
||||
|
||||
func candidateIDForHandle(
|
||||
service *Service,
|
||||
organizationID uuid.UUID,
|
||||
sources []domain.CandidateViewSource,
|
||||
handle, location string,
|
||||
) (uuid.UUID, error) {
|
||||
for _, source := range sources {
|
||||
alias, err := service.sourceAlias(organizationID, source)
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - derive current alias: %w", location, err)
|
||||
}
|
||||
if alias == handle {
|
||||
return source.CandidateID(), nil
|
||||
}
|
||||
}
|
||||
return uuid.Nil, ErrCandidateCardNotFound
|
||||
}
|
||||
|
||||
func projectedViewForHandle(
|
||||
service *Service,
|
||||
organizationID uuid.UUID,
|
||||
sources []domain.CandidateViewSource,
|
||||
handle, location string,
|
||||
) (domain.AnonymousCandidateViewDTO, error) {
|
||||
views, err := service.projector.ProjectSources(organizationID, sources)
|
||||
if err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - build current candidate view: %w", location, err)
|
||||
}
|
||||
for _, view := range views {
|
||||
if view.Pseudonym == handle {
|
||||
return view, nil
|
||||
}
|
||||
}
|
||||
return domain.AnonymousCandidateViewDTO{}, ErrCandidateCardNotFound
|
||||
}
|
||||
|
||||
// PreviewResult contains only the candidate's own current publication state
|
||||
// and the strict anonymous-card projection.
|
||||
type PreviewResult struct {
|
||||
Published bool
|
||||
Fields domain.CardFieldSet
|
||||
Card *domain.AnonymousCandidateViewDTO
|
||||
GeneratedAt time.Time
|
||||
}
|
||||
|
||||
// GetMyCardPreview computes a private preview without organization cohort
|
||||
// context, employer quota, or access history.
|
||||
func (service *Service) GetMyCardPreview(ctx context.Context, actorID uuid.UUID) (PreviewResult, error) {
|
||||
const location = "candidateview.Service.GetMyCardPreview"
|
||||
if actorID == uuid.Nil {
|
||||
return PreviewResult{}, ErrForbidden
|
||||
}
|
||||
var result PreviewResult
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeCandidate(ctx, unit, actorID); err != nil {
|
||||
return err
|
||||
}
|
||||
repository, err := privacyViewRepository(unit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
generatedAt := service.clock().UTC().Truncate(time.Microsecond)
|
||||
if generatedAt.IsZero() {
|
||||
return fmt.Errorf("%s - clock returned zero: %w", location, ErrCandidateViewServiceMissing)
|
||||
}
|
||||
_, consentErr := repository.LockCurrentC2ForView(ctx, actorID)
|
||||
if errors.Is(consentErr, outbound.ErrCandidateC2Unavailable) {
|
||||
result = PreviewResult{GeneratedAt: generatedAt}
|
||||
return nil
|
||||
}
|
||||
if consentErr != nil {
|
||||
return fmt.Errorf("%s - lock current C2: %w", location, consentErr)
|
||||
}
|
||||
published, err := repository.LockPublicationForPreview(ctx, actorID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - lock publication: %w", location, err)
|
||||
}
|
||||
if !published {
|
||||
result = PreviewResult{GeneratedAt: generatedAt}
|
||||
return nil
|
||||
}
|
||||
source, err := repository.ReadCandidateViewSourceForPreview(ctx, actorID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read private preview source: %w", location, err)
|
||||
}
|
||||
card, err := service.projector.PreviewSource(source)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build private preview: %w", location, err)
|
||||
}
|
||||
result = PreviewResult{Published: true, Fields: source.PublishedFields(), Card: &card, GeneratedAt: generatedAt}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return PreviewResult{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ListMyCardAccessHistory returns one owner-scoped history page.
|
||||
func (service *Service) ListMyCardAccessHistory(
|
||||
ctx context.Context,
|
||||
command outbound.CandidateCardAccessListQuery,
|
||||
) (outbound.CandidateCardAccessListPage, error) {
|
||||
const location = "candidateview.Service.ListMyCardAccessHistory"
|
||||
if command.CandidateID == uuid.Nil || command.Limit < 1 || command.Limit > outbound.MaxCandidateCardAccessPageSize {
|
||||
return outbound.CandidateCardAccessListPage{}, domain.ErrInvalidCandidateCardAccess
|
||||
}
|
||||
var result outbound.CandidateCardAccessListPage
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeCandidate(ctx, unit, command.CandidateID); err != nil {
|
||||
return err
|
||||
}
|
||||
repository, err := privacyViewRepository(unit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err = repository.ListCandidateCardAccess(ctx, command)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read owner access history: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.CandidateCardAccessListPage{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// CurrentContactFields returns only the current allowlisted grant fields.
|
||||
// The production repository is closed until invitation grants are persisted.
|
||||
// No workflow state or C4 ledger entry alone can open this read.
|
||||
func (service *Service) CurrentContactFields(
|
||||
ctx context.Context,
|
||||
actorID, organizationID uuid.UUID,
|
||||
handle string,
|
||||
) (domain.ContactFieldSet, error) {
|
||||
const location = "candidateview.Service.CurrentContactFields"
|
||||
if actorID == uuid.Nil || organizationID == uuid.Nil {
|
||||
return domain.ContactFieldSet{}, ErrForbidden
|
||||
}
|
||||
if !domain.IsCandidateViewPseudonym(handle) {
|
||||
return domain.ContactFieldSet{}, ErrInvalidCandidateHandle
|
||||
}
|
||||
var fields domain.ContactFieldSet
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
_, repository, candidateID, _, err := service.currentOrganizationCard(ctx, unit, actorID, organizationID, handle, location)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fields, err = repository.CurrentFields(ctx, organizationID, candidateID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read current contact grant: %w", location, err)
|
||||
}
|
||||
if fields.IsZero() {
|
||||
return outbound.ErrContactAccessClosed
|
||||
}
|
||||
event, err := domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{
|
||||
CandidateID: candidateID, OrganizationID: organizationID, ActorID: actorID,
|
||||
Kind: domain.CandidateCardAccessContactRead, ContactFields: fields.Fields(), OccurredAt: service.clock(),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build contact access audit: %w", location, err)
|
||||
}
|
||||
if err := repository.RecordCandidateCardAccess(ctx, event); err != nil {
|
||||
return fmt.Errorf("%s - record contact access audit: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.ContactFieldSet{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
func authorizeEmployer(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (domain.Organization, error) {
|
||||
user, err := unit.Users().GetByID(ctx, actorID)
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return domain.Organization{}, ErrForbidden
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Organization{}, fmt.Errorf("candidateview.authorizeEmployer - read actor account: %w", err)
|
||||
}
|
||||
if !user.EmailVerified() || user.Scenario != domain.ScenarioEmployer {
|
||||
return domain.Organization{}, ErrForbidden
|
||||
}
|
||||
if _, err := unit.Organizations().LockActiveMembership(ctx, organizationID, actorID); err != nil {
|
||||
if errors.Is(err, outbound.ErrOrganizationNotFound) {
|
||||
return domain.Organization{}, outbound.ErrOrganizationNotFound
|
||||
}
|
||||
return domain.Organization{}, fmt.Errorf("candidateview.authorizeEmployer - lock membership: %w", err)
|
||||
}
|
||||
organization, _, err := unit.Organizations().GetForMember(ctx, organizationID, actorID)
|
||||
if err != nil {
|
||||
return domain.Organization{}, fmt.Errorf("candidateview.authorizeEmployer - read organization: %w", err)
|
||||
}
|
||||
return organization, nil
|
||||
}
|
||||
|
||||
func authorizeCandidate(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID) error {
|
||||
user, err := unit.Users().GetByID(ctx, actorID)
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return ErrForbidden
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("candidateview.authorizeCandidate - read actor account: %w", err)
|
||||
}
|
||||
if !user.EmailVerified() || user.Scenario != domain.ScenarioCandidate {
|
||||
return ErrForbidden
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func privacyViewRepository(unit outbound.UnitOfWork) (outbound.PrivacyViewRepository, error) {
|
||||
repository := unit.PrivacyView()
|
||||
if repository == nil {
|
||||
return nil, ErrCandidateViewServiceMissing
|
||||
}
|
||||
return repository, nil
|
||||
}
|
||||
|
||||
func lockCurrentVisibleCohort(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repository outbound.PrivacyViewRepository,
|
||||
organizationID uuid.UUID,
|
||||
sources []domain.CandidateViewSource,
|
||||
) ([]domain.CandidateViewSource, error) {
|
||||
checked := make(map[uuid.UUID]bool)
|
||||
current := sources
|
||||
for range maxCohortStabilizationPasses {
|
||||
for _, source := range current {
|
||||
candidateID := source.CandidateID()
|
||||
if _, exists := checked[candidateID]; exists {
|
||||
continue
|
||||
}
|
||||
visible, err := lockCandidateVisibility(ctx, unit, repository, organizationID, candidateID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
checked[candidateID] = visible
|
||||
}
|
||||
refreshed, err := repository.ListVisibleCandidateViewSources(ctx, organizationID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("candidateview.lockCurrentVisibleCohort - re-read cohort: %w", err)
|
||||
}
|
||||
allLocked := true
|
||||
for _, source := range refreshed {
|
||||
eligible, exists := checked[source.CandidateID()]
|
||||
if !exists {
|
||||
allLocked = false
|
||||
break
|
||||
}
|
||||
if !eligible {
|
||||
return nil, ErrConcurrentVisibilityChange
|
||||
}
|
||||
}
|
||||
if allLocked {
|
||||
return refreshed, nil
|
||||
}
|
||||
current = refreshed
|
||||
}
|
||||
return nil, ErrConcurrentVisibilityChange
|
||||
}
|
||||
|
||||
func lockCandidateVisibility(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repository outbound.PrivacyViewRepository,
|
||||
organizationID, candidateID uuid.UUID,
|
||||
) (bool, error) {
|
||||
if err := repository.LockCandidateAccountForView(ctx, candidateID); err != nil {
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
candidate, err := unit.Users().GetByID(ctx, candidateID)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf("candidateview.lockCandidateVisibility - read candidate account: %w", err)
|
||||
}
|
||||
if !candidate.EmailVerified() || candidate.Scenario != domain.ScenarioCandidate {
|
||||
return false, nil
|
||||
}
|
||||
consentID, err := repository.LockCurrentC2ForView(ctx, candidateID)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrCandidateC2Unavailable) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
return repository.LockVisiblePublicationForView(ctx, organizationID, candidateID, consentID)
|
||||
}
|
||||
|
||||
func (service *Service) sourceAlias(organizationID uuid.UUID, source domain.CandidateViewSource) (string, error) {
|
||||
alias, err := service.pseudonymKey.ForOrganization(organizationID, source.CandidateID())
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("candidateview.Service.sourceAlias - derive candidate alias: %w", domain.ErrInvalidAnonymousCandidateView)
|
||||
}
|
||||
return alias, nil
|
||||
}
|
||||
|
||||
func cardViewAccessEvent(
|
||||
candidateID, organizationID, actorID uuid.UUID,
|
||||
view domain.AnonymousCandidateViewDTO,
|
||||
at time.Time,
|
||||
) (domain.CandidateCardAccess, error) {
|
||||
var fields []domain.CardField
|
||||
if len(view.Categories) > 0 {
|
||||
fields = append(fields, domain.CardFieldCategories)
|
||||
}
|
||||
if len(view.Skills) > 0 {
|
||||
fields = append(fields, domain.CardFieldStack)
|
||||
}
|
||||
if view.ExperienceBand != nil {
|
||||
fields = append(fields, domain.CardFieldExperience)
|
||||
}
|
||||
if len(view.SelfAssessment) > 0 {
|
||||
fields = append(fields, domain.CardFieldSelfAssessment)
|
||||
}
|
||||
if len(view.WorkFormats) > 0 {
|
||||
fields = append(fields, domain.CardFieldWorkFormats)
|
||||
}
|
||||
if view.SalaryCompatibility != nil {
|
||||
fields = append(fields, domain.CardFieldSalaryCompatibility)
|
||||
}
|
||||
if !domain.IsCandidateViewPseudonym(view.Pseudonym) {
|
||||
return domain.CandidateCardAccess{}, ErrInvalidCandidateHandle
|
||||
}
|
||||
return domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{
|
||||
CandidateID: candidateID, OrganizationID: organizationID, ActorID: actorID,
|
||||
Kind: domain.CandidateCardAccessCardViewed, ProjectionFields: fields, OccurredAt: at,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package candidateview
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
func TestCardViewAccessEventRecordsOnlyFieldsReturnedInTheProjection(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
key, err := domain.NewCandidateViewPseudonymKey(bytes.Repeat([]byte("candidate-view-key"), 2))
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
candidateID, organizationID, actorID := uuid.New(), uuid.New(), uuid.New()
|
||||
pseudonym, err := key.ForOrganization(organizationID, candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() error = %v", err)
|
||||
}
|
||||
|
||||
view := domain.AnonymousCandidateViewDTO{Pseudonym: pseudonym}
|
||||
event, err := cardViewAccessEvent(candidateID, organizationID, actorID, view, time.Now())
|
||||
if err != nil {
|
||||
t.Fatalf("cardViewAccessEvent(pseudonym only) error = %v", err)
|
||||
}
|
||||
if got := event.FieldCodes(); len(got) != 0 {
|
||||
t.Fatalf("pseudonym-only field codes = %v, want empty", got)
|
||||
}
|
||||
|
||||
band := domain.CandidateExperienceBandOneToThree
|
||||
compatibility := domain.CandidateViewSalaryCompatible
|
||||
view.Categories = []domain.CandidateViewCategory{{Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior, Strength: domain.CandidateViewStrengthStandard}}
|
||||
view.Skills = []domain.CandidateViewSkillCode{domain.CandidateViewSkillGo}
|
||||
view.ExperienceBand = &band
|
||||
view.WorkFormats = []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatRemote}
|
||||
view.SalaryCompatibility = &compatibility
|
||||
event, err = cardViewAccessEvent(candidateID, organizationID, actorID, view, time.Now())
|
||||
if err != nil {
|
||||
t.Fatalf("cardViewAccessEvent(projected fields) error = %v", err)
|
||||
}
|
||||
want := []string{"categories", "experience", "salary_compatibility", "stack", "work_formats"}
|
||||
if got := event.FieldCodes(); !slices.Equal(got, want) {
|
||||
t.Fatalf("projected field codes = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCardViewAccessEventRejectsAHandleThatIsNotAnOpaqueAlias(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := cardViewAccessEvent(uuid.New(), uuid.New(), uuid.New(), domain.AnonymousCandidateViewDTO{Pseudonym: "candidate-id"}, time.Now())
|
||||
if !errors.Is(err, ErrInvalidCandidateHandle) {
|
||||
t.Fatalf("cardViewAccessEvent(invalid alias) error = %v, want ErrInvalidCandidateHandle", err)
|
||||
}
|
||||
}
|
||||
@@ -676,6 +676,17 @@ func (ledger *fakeLedger) Current(_ context.Context, subjectID uuid.UUID, purpos
|
||||
return domain.ConsentRecord{}, outbound.ErrConsentNotFound
|
||||
}
|
||||
|
||||
func (ledger *fakeLedger) LockCurrentForUse(
|
||||
ctx context.Context,
|
||||
subjectID uuid.UUID,
|
||||
purpose domain.ConsentPurpose,
|
||||
) (domain.ConsentRecord, error) {
|
||||
if purpose != domain.ConsentPurposeAutoCategorization {
|
||||
return domain.ConsentRecord{}, domain.ErrInvalidConsent
|
||||
}
|
||||
return ledger.Current(ctx, subjectID, purpose)
|
||||
}
|
||||
|
||||
func (ledger *fakeLedger) LockRegistration(_ context.Context, subjectID uuid.UUID, registrationVersion int64) (domain.ConsentRecord, error) {
|
||||
for index := len(ledger.records) - 1; index >= 0; index-- {
|
||||
if record := ledger.records[index]; record.SubjectID() == subjectID &&
|
||||
|
||||
@@ -23,6 +23,7 @@ const (
|
||||
labelClientBucket = "lincodex/identity/client-bucket/v1"
|
||||
labelTokenBucket = "lincodex/identity/verification-token-bucket/v1"
|
||||
labelSessionCSRF = "lincodex/identity/session-csrf/v1"
|
||||
labelCandidateView = "lincodex/identity/candidate-view/v1"
|
||||
)
|
||||
|
||||
// Keyring computes the keyed digests of the anonymous identity operations:
|
||||
@@ -31,12 +32,13 @@ const (
|
||||
// stores hold can neither confirm that an address is registered nor serve as
|
||||
// an offline check of a password without the server secret.
|
||||
type Keyring struct {
|
||||
scopeKey []byte
|
||||
fingerprintKey []byte
|
||||
bucketKey []byte
|
||||
clientKey []byte
|
||||
tokenKey []byte
|
||||
sessionCSRFKey []byte
|
||||
scopeKey []byte
|
||||
fingerprintKey []byte
|
||||
bucketKey []byte
|
||||
clientKey []byte
|
||||
tokenKey []byte
|
||||
sessionCSRFKey []byte
|
||||
candidateViewKey []byte
|
||||
}
|
||||
|
||||
// NewKeyring derives the purpose keys from secret.
|
||||
@@ -45,15 +47,29 @@ func NewKeyring(secret []byte) (*Keyring, error) {
|
||||
return nil, fmt.Errorf("identity.NewKeyring - secret must have at least %d bytes", MinKeySecretBytes)
|
||||
}
|
||||
return &Keyring{
|
||||
scopeKey: derive(secret, labelIdempotencyScope),
|
||||
fingerprintKey: derive(secret, labelFingerprint),
|
||||
bucketKey: derive(secret, labelEmailBucket),
|
||||
clientKey: derive(secret, labelClientBucket),
|
||||
tokenKey: derive(secret, labelTokenBucket),
|
||||
sessionCSRFKey: derive(secret, labelSessionCSRF),
|
||||
scopeKey: derive(secret, labelIdempotencyScope),
|
||||
fingerprintKey: derive(secret, labelFingerprint),
|
||||
bucketKey: derive(secret, labelEmailBucket),
|
||||
clientKey: derive(secret, labelClientBucket),
|
||||
tokenKey: derive(secret, labelTokenBucket),
|
||||
sessionCSRFKey: derive(secret, labelSessionCSRF),
|
||||
candidateViewKey: derive(secret, labelCandidateView),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CandidateViewPseudonymKey returns a purpose-specific key for anonymous
|
||||
// candidate view aliases without exposing the root identity secret.
|
||||
func (keyring *Keyring) CandidateViewPseudonymKey() (domain.CandidateViewPseudonymKey, error) {
|
||||
if keyring == nil {
|
||||
return domain.CandidateViewPseudonymKey{}, fmt.Errorf("identity.Keyring.CandidateViewPseudonymKey - keyring is nil")
|
||||
}
|
||||
key, err := domain.NewCandidateViewPseudonymKey(keyring.candidateViewKey)
|
||||
if err != nil {
|
||||
return domain.CandidateViewPseudonymKey{}, fmt.Errorf("identity.Keyring.CandidateViewPseudonymKey - derive typed key: %w", err)
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
func derive(secret []byte, label string) []byte {
|
||||
mac := hmac.New(sha256.New, secret)
|
||||
mac.Write([]byte(label))
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package identity
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestCandidateViewPseudonymKeyIsPurposeDerived(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
secret := bytes.Repeat([]byte("k"), MinKeySecretBytes)
|
||||
keyring, err := NewKeyring(secret)
|
||||
if err != nil {
|
||||
t.Fatalf("NewKeyring() error = %v", err)
|
||||
}
|
||||
key, err := keyring.CandidateViewPseudonymKey()
|
||||
if err != nil {
|
||||
t.Fatalf("CandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
|
||||
candidateID := uuid.New()
|
||||
organizationID := uuid.New()
|
||||
first, err := key.ForOrganization(organizationID, candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() error = %v", err)
|
||||
}
|
||||
preview, err := key.ForCandidatePreview(candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForCandidatePreview() error = %v", err)
|
||||
}
|
||||
repeated, err := keyring.CandidateViewPseudonymKey()
|
||||
if err != nil {
|
||||
t.Fatalf("CandidateViewPseudonymKey() repeat error = %v", err)
|
||||
}
|
||||
previewAgain, err := repeated.ForCandidatePreview(candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForCandidatePreview() repeat error = %v", err)
|
||||
}
|
||||
|
||||
if preview == first || previewAgain != preview {
|
||||
t.Fatal("preview pseudonym must be stable and separate from organization pseudonyms")
|
||||
}
|
||||
if bytes.Contains([]byte(preview), secret) {
|
||||
t.Fatal("preview pseudonym exposed the root secret")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateViewPseudonymKeyRequiresValidKeyring(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if _, err := (*Keyring)(nil).CandidateViewPseudonymKey(); err == nil {
|
||||
t.Fatal("CandidateViewPseudonymKey() accepted a nil keyring")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package need
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrForbidden = errors.New("organization need operation forbidden")
|
||||
ErrEmailNotVerified = errors.New("organization need requires a confirmed email")
|
||||
ErrIdempotencyKeyReused = errors.New("idempotency key reused with a different request")
|
||||
ErrInvalidIdempotencyKey = errors.New("invalid idempotency key")
|
||||
ErrInvalidCreateRequest = errors.New("invalid organization need create request")
|
||||
)
|
||||
@@ -0,0 +1,841 @@
|
||||
package need
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
var ErrInvalidRequest = errors.New("invalid organization need request")
|
||||
|
||||
// ValidationError identifies the contract field that rejected a need request.
|
||||
type ValidationError struct {
|
||||
Pointer string
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (validation *ValidationError) Error() string {
|
||||
return fmt.Sprintf("need request field %s: %s", validation.Pointer, validation.Reason)
|
||||
}
|
||||
|
||||
func (validation *ValidationError) Unwrap() error { return ErrInvalidRequest }
|
||||
|
||||
// Field distinguishes a missing property from a property explicitly set to null.
|
||||
type Field[T any] struct {
|
||||
Set bool
|
||||
Null bool
|
||||
Value T
|
||||
}
|
||||
|
||||
// Decision is an explicit value and confirmation state sent by an owner.
|
||||
type Decision[T any] struct {
|
||||
Value T
|
||||
Status domain.NeedValueStatus
|
||||
}
|
||||
|
||||
type SkillInput struct {
|
||||
Name string
|
||||
Status domain.NeedItemStatus
|
||||
}
|
||||
|
||||
type TaskInput struct {
|
||||
Text string
|
||||
Status domain.NeedItemStatus
|
||||
}
|
||||
|
||||
// CreateInput preserves request presence so absent fields may use source text
|
||||
// while explicit nulls and empty lists suppress extraction for that field.
|
||||
type CreateInput struct {
|
||||
Title string
|
||||
VacancyID Field[uuid.UUID]
|
||||
SourceText Field[string]
|
||||
Specialization Field[Decision[domain.SpecializationCode]]
|
||||
Grade Field[Decision[domain.GradeCode]]
|
||||
RequiredSkills []SkillInput
|
||||
DesiredSkills []SkillInput
|
||||
Tasks []TaskInput
|
||||
Domain Field[Decision[string]]
|
||||
WorkFormats Field[Decision[[]domain.NeedWorkFormat]]
|
||||
Location Field[Decision[string]]
|
||||
Salary Field[Decision[domain.NeedSalaryRange]]
|
||||
}
|
||||
|
||||
// UpdateInput is a full replacement for every field it sets. Nil lists mean
|
||||
// absent; non-nil empty lists explicitly delete all items in that list.
|
||||
type UpdateInput struct {
|
||||
ExpectedVersion int64
|
||||
Title Field[string]
|
||||
VacancyID Field[uuid.UUID]
|
||||
SourceText Field[string]
|
||||
Specialization Field[Decision[domain.SpecializationCode]]
|
||||
Grade Field[Decision[domain.GradeCode]]
|
||||
RequiredSkills []SkillInput
|
||||
DesiredSkills []SkillInput
|
||||
Tasks []TaskInput
|
||||
Domain Field[Decision[string]]
|
||||
WorkFormats Field[Decision[[]domain.NeedWorkFormat]]
|
||||
Location Field[Decision[string]]
|
||||
Salary Field[Decision[domain.NeedSalaryRange]]
|
||||
}
|
||||
|
||||
func createNeed(input CreateInput, organizationID, needID uuid.UUID, now time.Time) (domain.Need, error) {
|
||||
const location = "need.createNeed"
|
||||
if organizationID == uuid.Nil || needID == uuid.Nil || now.IsZero() {
|
||||
return domain.Need{}, fmt.Errorf("%s - organization, need, and application time must be set: %w", location, ErrInvalidRequest)
|
||||
}
|
||||
if input.VacancyID.Set && !input.VacancyID.Null {
|
||||
return domain.Need{}, invalidRequest("/vacancy_id", "vacancies are not available")
|
||||
}
|
||||
sourceText, sourceProvided, err := createSourceText(input.SourceText)
|
||||
if err != nil {
|
||||
return domain.Need{}, err
|
||||
}
|
||||
requirements, err := createNeedRequirements(input, sourceText, sourceProvided)
|
||||
if err != nil {
|
||||
return domain.Need{}, err
|
||||
}
|
||||
snapshot := domain.NeedSnapshot{
|
||||
ID: needID, OrganizationID: organizationID, Title: input.Title,
|
||||
SourceText: sourceText, Version: 1, RequirementsVersion: 1,
|
||||
Requirements: requirements, RejectedSuggestions: []domain.NeedRejectedSuggestion{},
|
||||
CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
created, err := domain.NewNeed(snapshot)
|
||||
if err != nil {
|
||||
return domain.Need{}, mapDomainValidation(err)
|
||||
}
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func createNeedRequirements(input CreateInput, sourceText *string, sourceProvided bool) (domain.NeedRequirements, error) {
|
||||
requirements := domain.EmptyNeedRequirements()
|
||||
if sourceProvided {
|
||||
requirements = parseSourceText(*sourceText, 1)
|
||||
}
|
||||
if err := applyCreateScalars(&requirements, input); err != nil {
|
||||
return domain.NeedRequirements{}, err
|
||||
}
|
||||
if input.RequiredSkills != nil {
|
||||
created, err := createSkills(input.RequiredSkills, "/required_skills")
|
||||
if err != nil {
|
||||
return domain.NeedRequirements{}, err
|
||||
}
|
||||
requirements.RequiredSkills = created
|
||||
}
|
||||
if input.DesiredSkills != nil {
|
||||
created, err := createSkills(input.DesiredSkills, "/desired_skills")
|
||||
if err != nil {
|
||||
return domain.NeedRequirements{}, err
|
||||
}
|
||||
requirements.DesiredSkills = created
|
||||
}
|
||||
if input.Tasks != nil {
|
||||
created, err := createTasks(input.Tasks, "/tasks")
|
||||
if err != nil {
|
||||
return domain.NeedRequirements{}, err
|
||||
}
|
||||
requirements.Tasks = created
|
||||
}
|
||||
removeExtractedSkillsShadowedByConfirmed(&requirements)
|
||||
if err := validateSkillUniqueness(requirements); err != nil {
|
||||
return domain.NeedRequirements{}, err
|
||||
}
|
||||
return requirements, nil
|
||||
}
|
||||
|
||||
func createSourceText(field Field[string]) (*string, bool, error) {
|
||||
if !field.Set || field.Null {
|
||||
return nil, false, nil
|
||||
}
|
||||
if field.Value == "" {
|
||||
return nil, false, invalidRequest("/source_text", "must contain text or be null")
|
||||
}
|
||||
value := field.Value
|
||||
return &value, true, nil
|
||||
}
|
||||
|
||||
func applyCreateScalars(requirements *domain.NeedRequirements, input CreateInput) error {
|
||||
var err error
|
||||
if requirements.Specialization, err = createScalar(input.Specialization, requirements.Specialization, "/specialization"); err != nil {
|
||||
return err
|
||||
}
|
||||
if requirements.Grade, err = createScalar(input.Grade, requirements.Grade, "/grade"); err != nil {
|
||||
return err
|
||||
}
|
||||
if requirements.Domain, err = createScalar(input.Domain, requirements.Domain, "/domain"); err != nil {
|
||||
return err
|
||||
}
|
||||
if requirements.WorkFormats, err = createScalar(input.WorkFormats, requirements.WorkFormats, "/work_formats"); err != nil {
|
||||
return err
|
||||
}
|
||||
if requirements.Location, err = createScalar(input.Location, requirements.Location, "/location"); err != nil {
|
||||
return err
|
||||
}
|
||||
if requirements.Salary, err = createScalar(input.Salary, requirements.Salary, "/salary"); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func createScalar[T any](field Field[Decision[T]], parsed domain.NeedValue[T], pointer string) (domain.NeedValue[T], error) {
|
||||
if !field.Set {
|
||||
return parsed, nil
|
||||
}
|
||||
if field.Null {
|
||||
return unknownNeedValue[T](), nil
|
||||
}
|
||||
if field.Value.Status != domain.NeedValueConfirmed {
|
||||
return domain.NeedValue[T]{}, invalidRequest(pointer+"/status", "a new need requires confirmed values")
|
||||
}
|
||||
return confirmedNeedValue(field.Value.Value, manualNeedSource()), nil
|
||||
}
|
||||
|
||||
func createSkills(inputs []SkillInput, pointer string) ([]domain.NeedSkill, error) {
|
||||
result := make([]domain.NeedSkill, 0, len(inputs))
|
||||
for index, input := range inputs {
|
||||
itemPointer := fmt.Sprintf("%s/%d", pointer, index)
|
||||
if input.Status != domain.NeedItemConfirmed {
|
||||
return nil, invalidRequest(itemPointer+"/status", "a new need requires confirmed items")
|
||||
}
|
||||
result = append(result, domain.NeedSkill{
|
||||
Name: input.Name, TaxonomyCode: taxonomyForSkillName(input.Name), Status: domain.NeedItemConfirmed,
|
||||
Source: *manualNeedSource(),
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func createTasks(inputs []TaskInput, pointer string) ([]domain.NeedTask, error) {
|
||||
result := make([]domain.NeedTask, 0, len(inputs))
|
||||
for index, input := range inputs {
|
||||
if input.Status != domain.NeedItemConfirmed {
|
||||
return nil, invalidRequest(fmt.Sprintf("%s/%d/status", pointer, index), "a new need requires confirmed items")
|
||||
}
|
||||
result = append(result, domain.NeedTask{Text: input.Text, Status: domain.NeedItemConfirmed, Source: *manualNeedSource()})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func reviseNeed(current domain.Need, input UpdateInput, now time.Time) (domain.Need, bool, error) {
|
||||
const location = "need.reviseNeed"
|
||||
if current.IsZero() || now.IsZero() {
|
||||
return domain.Need{}, false, fmt.Errorf("%s - current need and application time must be set: %w", location, ErrInvalidRequest)
|
||||
}
|
||||
if input.ExpectedVersion < 1 {
|
||||
return domain.Need{}, false, invalidRequest("/expected_version", "must be positive")
|
||||
}
|
||||
snapshot := current.Snapshot()
|
||||
if err := applyNeedUpdate(current, &snapshot, input); err != nil {
|
||||
return domain.Need{}, false, err
|
||||
}
|
||||
snapshot.UpdatedAt = now
|
||||
return current.Revise(input.ExpectedVersion, snapshot)
|
||||
}
|
||||
|
||||
func applyNeedUpdate(current domain.Need, snapshot *domain.NeedSnapshot, input UpdateInput) error {
|
||||
if input.Title.Set {
|
||||
if input.Title.Null {
|
||||
return stalePatchError(current, input.ExpectedVersion, invalidRequest("/title", "cannot be null"))
|
||||
}
|
||||
snapshot.Title = input.Title.Value
|
||||
}
|
||||
if input.VacancyID.Set {
|
||||
if !input.VacancyID.Null {
|
||||
return stalePatchError(current, input.ExpectedVersion, invalidRequest("/vacancy_id", "vacancies are not available"))
|
||||
}
|
||||
snapshot.VacancyID = nil
|
||||
}
|
||||
newSourceText, sourceChanged, sourceErr := updateSourceText(input.SourceText, snapshot.SourceText)
|
||||
if sourceErr != nil {
|
||||
return stalePatchError(current, input.ExpectedVersion, sourceErr)
|
||||
}
|
||||
snapshot.SourceText = newSourceText
|
||||
requirements := snapshot.Requirements
|
||||
if err := applyExplicitScalars(snapshot, &requirements, input); err != nil {
|
||||
return stalePatchError(current, input.ExpectedVersion, err)
|
||||
}
|
||||
if err := applyExplicitLists(snapshot, &requirements, input); err != nil {
|
||||
return stalePatchError(current, input.ExpectedVersion, err)
|
||||
}
|
||||
if sourceChanged {
|
||||
parsed := parseSourceText(*snapshot.SourceText, current.Version()+1)
|
||||
reparseScalars(snapshot, &requirements, parsed, input)
|
||||
reparseLists(snapshot, &requirements, parsed, current.Snapshot().Requirements, input)
|
||||
}
|
||||
if err := validateSkillUniqueness(requirements); err != nil {
|
||||
return stalePatchError(current, input.ExpectedVersion, err)
|
||||
}
|
||||
snapshot.Requirements = requirements
|
||||
return nil
|
||||
}
|
||||
|
||||
func stalePatchError(current domain.Need, expectedVersion int64, err error) error {
|
||||
if expectedVersion != current.Version() {
|
||||
return domain.ErrNeedVersionConflict
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func updateSourceText(field Field[string], current *string) (*string, bool, error) {
|
||||
if !field.Set {
|
||||
return cloneString(current), false, nil
|
||||
}
|
||||
if field.Null {
|
||||
return nil, false, nil
|
||||
}
|
||||
if field.Value == "" {
|
||||
return nil, false, invalidRequest("/source_text", "must contain text or be null")
|
||||
}
|
||||
value := field.Value
|
||||
changed := current == nil || *current != value
|
||||
return &value, changed, nil
|
||||
}
|
||||
|
||||
func applyExplicitScalars(snapshot *domain.NeedSnapshot, requirements *domain.NeedRequirements, input UpdateInput) error {
|
||||
if err := applyScalarPatch(snapshot, &requirements.Specialization, input.Specialization, domain.NeedRejectedSpecialization, "/specialization", scalarString[domain.SpecializationCode]); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := applyScalarPatch(snapshot, &requirements.Grade, input.Grade, domain.NeedRejectedGrade, "/grade", scalarString[domain.GradeCode]); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := applyScalarPatch(snapshot, &requirements.Domain, input.Domain, domain.NeedRejectedDomain, "/domain", scalarString[string]); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := applyScalarPatch(snapshot, &requirements.WorkFormats, input.WorkFormats, domain.NeedRejectedWorkFormats, "/work_formats", scalarWorkFormats); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := applyScalarPatch(snapshot, &requirements.Location, input.Location, domain.NeedRejectedLocation, "/location", scalarString[string]); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := applyScalarPatch(snapshot, &requirements.Salary, input.Salary, domain.NeedRejectedSalary, "/salary", scalarSalary); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyScalarPatch[T any](
|
||||
snapshot *domain.NeedSnapshot,
|
||||
current *domain.NeedValue[T],
|
||||
field Field[Decision[T]],
|
||||
rejectedField domain.NeedRejectedSuggestionField,
|
||||
pointer string,
|
||||
canonical func(T) []string,
|
||||
) error {
|
||||
if !field.Set {
|
||||
return nil
|
||||
}
|
||||
if field.Null {
|
||||
if err := rejectExtractedScalar(snapshot, rejectedField, *current, canonical, pointer); err != nil {
|
||||
return err
|
||||
}
|
||||
*current = unknownNeedValue[T]()
|
||||
return nil
|
||||
}
|
||||
decision := field.Value
|
||||
switch decision.Status {
|
||||
case domain.NeedValueUnknown:
|
||||
return invalidRequest(pointer+"/status", "must be confirmed or extracted")
|
||||
case domain.NeedValueExtracted:
|
||||
if current.Status != domain.NeedValueExtracted || current.Value == nil || !reflect.DeepEqual(*current.Value, decision.Value) {
|
||||
return invalidRequest(pointer+"/status", "extracted is allowed only for the stored suggestion")
|
||||
}
|
||||
return nil
|
||||
case domain.NeedValueConfirmed:
|
||||
if current.Value != nil && reflect.DeepEqual(*current.Value, decision.Value) {
|
||||
current.Status = domain.NeedValueConfirmed
|
||||
return nil
|
||||
}
|
||||
if err := rejectExtractedScalar(snapshot, rejectedField, *current, canonical, pointer); err != nil {
|
||||
return err
|
||||
}
|
||||
*current = confirmedNeedValue(decision.Value, manualNeedSource())
|
||||
return nil
|
||||
default:
|
||||
return invalidRequest(pointer+"/status", "must be confirmed or extracted")
|
||||
}
|
||||
}
|
||||
|
||||
func rejectExtractedScalar[T any](
|
||||
snapshot *domain.NeedSnapshot,
|
||||
field domain.NeedRejectedSuggestionField,
|
||||
value domain.NeedValue[T],
|
||||
canonical func(T) []string,
|
||||
pointer string,
|
||||
) error {
|
||||
if value.Status != domain.NeedValueExtracted || value.Value == nil {
|
||||
return nil
|
||||
}
|
||||
for _, candidate := range canonical(*value.Value) {
|
||||
if err := addRejectedSuggestion(snapshot, field, candidate, pointer); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func reparseScalars(snapshot *domain.NeedSnapshot, requirements *domain.NeedRequirements, parsed domain.NeedRequirements, input UpdateInput) {
|
||||
if !input.Specialization.Set && requirements.Specialization.Status != domain.NeedValueConfirmed {
|
||||
requirements.Specialization = filterRejectedScalar(snapshot, domain.NeedRejectedSpecialization, parsed.Specialization, scalarString[domain.SpecializationCode])
|
||||
}
|
||||
if !input.Grade.Set && requirements.Grade.Status != domain.NeedValueConfirmed {
|
||||
requirements.Grade = filterRejectedScalar(snapshot, domain.NeedRejectedGrade, parsed.Grade, scalarString[domain.GradeCode])
|
||||
}
|
||||
if !input.Domain.Set && requirements.Domain.Status != domain.NeedValueConfirmed {
|
||||
requirements.Domain = filterRejectedScalar(snapshot, domain.NeedRejectedDomain, parsed.Domain, scalarString[string])
|
||||
}
|
||||
if !input.WorkFormats.Set && requirements.WorkFormats.Status != domain.NeedValueConfirmed {
|
||||
requirements.WorkFormats = filterRejectedWorkFormats(snapshot, parsed.WorkFormats)
|
||||
}
|
||||
if !input.Location.Set && requirements.Location.Status != domain.NeedValueConfirmed {
|
||||
requirements.Location = filterRejectedScalar(snapshot, domain.NeedRejectedLocation, parsed.Location, scalarString[string])
|
||||
}
|
||||
if !input.Salary.Set && requirements.Salary.Status != domain.NeedValueConfirmed {
|
||||
requirements.Salary = filterRejectedScalar(snapshot, domain.NeedRejectedSalary, parsed.Salary, scalarSalary)
|
||||
}
|
||||
}
|
||||
|
||||
func filterRejectedWorkFormats(snapshot *domain.NeedSnapshot, value domain.NeedValue[[]domain.NeedWorkFormat]) domain.NeedValue[[]domain.NeedWorkFormat] {
|
||||
if value.Status != domain.NeedValueExtracted || value.Value == nil {
|
||||
return value
|
||||
}
|
||||
filtered := make([]domain.NeedWorkFormat, 0, len(*value.Value))
|
||||
for _, format := range *value.Value {
|
||||
if !isRejected(snapshot.RejectedSuggestions, domain.NeedRejectedWorkFormats, string(format)) {
|
||||
filtered = append(filtered, format)
|
||||
}
|
||||
}
|
||||
if len(filtered) == 0 {
|
||||
return unknownNeedValue[[]domain.NeedWorkFormat]()
|
||||
}
|
||||
value.Value = &filtered
|
||||
return value
|
||||
}
|
||||
|
||||
func filterRejectedScalar[T any](
|
||||
snapshot *domain.NeedSnapshot,
|
||||
field domain.NeedRejectedSuggestionField,
|
||||
value domain.NeedValue[T],
|
||||
canonical func(T) []string,
|
||||
) domain.NeedValue[T] {
|
||||
if value.Status != domain.NeedValueExtracted || value.Value == nil {
|
||||
return value
|
||||
}
|
||||
for _, candidate := range canonical(*value.Value) {
|
||||
if isRejected(snapshot.RejectedSuggestions, field, candidate) {
|
||||
return unknownNeedValue[T]()
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func applyExplicitLists(snapshot *domain.NeedSnapshot, requirements *domain.NeedRequirements, input UpdateInput) error {
|
||||
if err := rejectRemovedSkillSuggestions(snapshot, *requirements, input); err != nil {
|
||||
return err
|
||||
}
|
||||
oldSkills := append(append([]domain.NeedSkill(nil), requirements.RequiredSkills...), requirements.DesiredSkills...)
|
||||
if err := replaceExplicitSkillList(&requirements.RequiredSkills, input.RequiredSkills, oldSkills, "/required_skills"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := replaceExplicitSkillList(&requirements.DesiredSkills, input.DesiredSkills, oldSkills, "/desired_skills"); err != nil {
|
||||
return err
|
||||
}
|
||||
return replaceExplicitTaskList(snapshot, requirements, input.Tasks)
|
||||
}
|
||||
|
||||
func rejectRemovedSkillSuggestions(snapshot *domain.NeedSnapshot, requirements domain.NeedRequirements, input UpdateInput) error {
|
||||
if input.RequiredSkills == nil && input.DesiredSkills == nil {
|
||||
return nil
|
||||
}
|
||||
requested := append(append([]SkillInput(nil), input.RequiredSkills...), input.DesiredSkills...)
|
||||
groups := []struct {
|
||||
items []domain.NeedSkill
|
||||
present bool
|
||||
pointer string
|
||||
}{
|
||||
{items: requirements.RequiredSkills, present: input.RequiredSkills != nil, pointer: "/required_skills"},
|
||||
{items: requirements.DesiredSkills, present: input.DesiredSkills != nil, pointer: "/desired_skills"},
|
||||
}
|
||||
for _, group := range groups {
|
||||
for _, old := range group.items {
|
||||
if !group.present || old.Status != domain.NeedItemExtracted || skillInputIndex(requested, old.Name) >= 0 {
|
||||
continue
|
||||
}
|
||||
if err := addRejectedSuggestion(snapshot, domain.NeedRejectedSkills, old.Name, group.pointer); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func replaceExplicitSkillList(target *[]domain.NeedSkill, inputs []SkillInput, old []domain.NeedSkill, pointer string) error {
|
||||
if inputs == nil {
|
||||
return nil
|
||||
}
|
||||
updated, err := replaceSkills(inputs, old, pointer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*target = updated
|
||||
return nil
|
||||
}
|
||||
|
||||
func replaceExplicitTaskList(snapshot *domain.NeedSnapshot, requirements *domain.NeedRequirements, inputs []TaskInput) error {
|
||||
if inputs == nil {
|
||||
return nil
|
||||
}
|
||||
for _, old := range requirements.Tasks {
|
||||
if old.Status != domain.NeedItemExtracted || taskInputIndex(inputs, old.Text) >= 0 {
|
||||
continue
|
||||
}
|
||||
if err := addRejectedSuggestion(snapshot, domain.NeedRejectedTasks, old.Text, "/tasks"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
updated, err := replaceTasks(inputs, requirements.Tasks)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
requirements.Tasks = updated
|
||||
return nil
|
||||
}
|
||||
|
||||
func removeExtractedSkillsShadowedByConfirmed(requirements *domain.NeedRequirements) {
|
||||
confirmed := confirmedSkillNames(requirements.RequiredSkills, requirements.DesiredSkills)
|
||||
filter := func(skills []domain.NeedSkill) []domain.NeedSkill {
|
||||
result := make([]domain.NeedSkill, 0, len(skills))
|
||||
for _, skill := range skills {
|
||||
if skill.Status == domain.NeedItemExtracted {
|
||||
if _, exists := confirmed[canonicalNeedKey(skill.Name)]; exists {
|
||||
continue
|
||||
}
|
||||
}
|
||||
result = append(result, skill)
|
||||
}
|
||||
return result
|
||||
}
|
||||
requirements.RequiredSkills = filter(requirements.RequiredSkills)
|
||||
requirements.DesiredSkills = filter(requirements.DesiredSkills)
|
||||
}
|
||||
|
||||
func replaceSkills(inputs []SkillInput, old []domain.NeedSkill, pointer string) ([]domain.NeedSkill, error) {
|
||||
updated := make([]domain.NeedSkill, 0, len(inputs))
|
||||
seen := make(map[string]struct{}, len(inputs))
|
||||
for index, input := range inputs {
|
||||
itemPointer := fmt.Sprintf("%s/%d", pointer, index)
|
||||
key := canonicalNeedKey(input.Name)
|
||||
if _, exists := seen[key]; exists {
|
||||
return nil, invalidRequest(itemPointer+"/name", "duplicates a skill in this request")
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
previous, exists := findSkill(old, key)
|
||||
switch input.Status {
|
||||
case domain.NeedItemExtracted:
|
||||
if !exists || previous.Status != domain.NeedItemExtracted {
|
||||
return nil, invalidRequest(itemPointer+"/status", "extracted is allowed only for a stored suggestion")
|
||||
}
|
||||
updated = append(updated, previous)
|
||||
case domain.NeedItemConfirmed:
|
||||
if exists {
|
||||
previous.Status = domain.NeedItemConfirmed
|
||||
updated = append(updated, previous)
|
||||
continue
|
||||
}
|
||||
updated = append(updated, domain.NeedSkill{
|
||||
Name: input.Name, TaxonomyCode: taxonomyForSkillName(input.Name), Status: domain.NeedItemConfirmed,
|
||||
Source: *manualNeedSource(),
|
||||
})
|
||||
default:
|
||||
return nil, invalidRequest(itemPointer+"/status", "must be confirmed or extracted")
|
||||
}
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func replaceTasks(inputs []TaskInput, old []domain.NeedTask) ([]domain.NeedTask, error) {
|
||||
updated := make([]domain.NeedTask, 0, len(inputs))
|
||||
seen := make(map[string]struct{}, len(inputs))
|
||||
for index, input := range inputs {
|
||||
pointer := fmt.Sprintf("/tasks/%d", index)
|
||||
key := canonicalNeedKey(input.Text)
|
||||
if _, exists := seen[key]; exists {
|
||||
return nil, invalidRequest(pointer+"/text", "duplicates a task in this request")
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
previous, exists := findTask(old, input.Text)
|
||||
switch input.Status {
|
||||
case domain.NeedItemExtracted:
|
||||
if !exists || previous.Status != domain.NeedItemExtracted {
|
||||
return nil, invalidRequest(pointer+"/status", "extracted is allowed only for a stored suggestion")
|
||||
}
|
||||
updated = append(updated, previous)
|
||||
case domain.NeedItemConfirmed:
|
||||
if exists {
|
||||
previous.Status = domain.NeedItemConfirmed
|
||||
updated = append(updated, previous)
|
||||
continue
|
||||
}
|
||||
updated = append(updated, domain.NeedTask{Text: input.Text, Status: domain.NeedItemConfirmed, Source: *manualNeedSource()})
|
||||
default:
|
||||
return nil, invalidRequest(pointer+"/status", "must be confirmed or extracted")
|
||||
}
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func reparseLists(
|
||||
snapshot *domain.NeedSnapshot,
|
||||
requirements *domain.NeedRequirements,
|
||||
parsed domain.NeedRequirements,
|
||||
previous domain.NeedRequirements,
|
||||
input UpdateInput,
|
||||
) {
|
||||
if input.RequiredSkills != nil || input.DesiredSkills != nil {
|
||||
blocked := confirmedSkillNames(requirements.RequiredSkills, requirements.DesiredSkills)
|
||||
if input.RequiredSkills != nil {
|
||||
addSkillNames(blocked, requirements.RequiredSkills)
|
||||
}
|
||||
if input.DesiredSkills != nil {
|
||||
addSkillNames(blocked, requirements.DesiredSkills)
|
||||
}
|
||||
if input.RequiredSkills == nil {
|
||||
requirements.RequiredSkills = reparseSkills(snapshot, previous.RequiredSkills, parsed.RequiredSkills, blocked)
|
||||
addSkillNames(blocked, requirements.RequiredSkills)
|
||||
}
|
||||
if input.DesiredSkills == nil {
|
||||
requirements.DesiredSkills = reparseSkills(snapshot, previous.DesiredSkills, parsed.DesiredSkills, blocked)
|
||||
}
|
||||
} else {
|
||||
blocked := confirmedSkillNames(previous.RequiredSkills, previous.DesiredSkills)
|
||||
requirements.RequiredSkills = reparseSkills(snapshot, previous.RequiredSkills, parsed.RequiredSkills, blocked)
|
||||
addSkillNames(blocked, requirements.RequiredSkills)
|
||||
requirements.DesiredSkills = reparseSkills(snapshot, previous.DesiredSkills, parsed.DesiredSkills, blocked)
|
||||
}
|
||||
if input.Tasks == nil {
|
||||
requirements.Tasks = reparseTasks(snapshot, previous.Tasks, parsed.Tasks)
|
||||
}
|
||||
}
|
||||
|
||||
func reparseSkills(
|
||||
snapshot *domain.NeedSnapshot,
|
||||
previous, parsed []domain.NeedSkill,
|
||||
blocked map[string]struct{},
|
||||
) []domain.NeedSkill {
|
||||
result := make([]domain.NeedSkill, 0, len(previous)+len(parsed))
|
||||
seen := make(map[string]struct{}, len(previous)+len(parsed))
|
||||
for _, skill := range previous {
|
||||
if skill.Status != domain.NeedItemConfirmed {
|
||||
continue
|
||||
}
|
||||
key := canonicalNeedKey(skill.Name)
|
||||
result = append(result, skill)
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
for _, skill := range parsed {
|
||||
key := canonicalNeedKey(skill.Name)
|
||||
if _, exists := seen[key]; exists {
|
||||
continue
|
||||
}
|
||||
if _, exists := blocked[key]; exists || isRejected(snapshot.RejectedSuggestions, domain.NeedRejectedSkills, skill.Name) {
|
||||
continue
|
||||
}
|
||||
result = append(result, skill)
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func reparseTasks(snapshot *domain.NeedSnapshot, previous, parsed []domain.NeedTask) []domain.NeedTask {
|
||||
result := make([]domain.NeedTask, 0, len(previous)+len(parsed))
|
||||
seen := make(map[string]struct{}, len(previous)+len(parsed))
|
||||
for _, task := range previous {
|
||||
if task.Status != domain.NeedItemConfirmed {
|
||||
continue
|
||||
}
|
||||
key := canonicalNeedKey(task.Text)
|
||||
result = append(result, task)
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
for _, task := range parsed {
|
||||
key := canonicalNeedKey(task.Text)
|
||||
if _, exists := seen[key]; exists || isRejected(snapshot.RejectedSuggestions, domain.NeedRejectedTasks, task.Text) {
|
||||
continue
|
||||
}
|
||||
result = append(result, task)
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func skillInputIndex(inputs []SkillInput, name string) int {
|
||||
key := canonicalNeedKey(name)
|
||||
for index, input := range inputs {
|
||||
if canonicalNeedKey(input.Name) == key {
|
||||
return index
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func taskInputIndex(inputs []TaskInput, text string) int {
|
||||
key := canonicalNeedKey(text)
|
||||
for index, input := range inputs {
|
||||
if canonicalNeedKey(input.Text) == key {
|
||||
return index
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func findSkill(skills []domain.NeedSkill, key string) (domain.NeedSkill, bool) {
|
||||
for _, skill := range skills {
|
||||
if canonicalNeedKey(skill.Name) == key {
|
||||
return skill, true
|
||||
}
|
||||
}
|
||||
return domain.NeedSkill{}, false
|
||||
}
|
||||
|
||||
func findTask(tasks []domain.NeedTask, text string) (domain.NeedTask, bool) {
|
||||
for _, task := range tasks {
|
||||
if task.Text == text {
|
||||
return task, true
|
||||
}
|
||||
}
|
||||
return domain.NeedTask{}, false
|
||||
}
|
||||
|
||||
func confirmedSkillNames(groups ...[]domain.NeedSkill) map[string]struct{} {
|
||||
result := make(map[string]struct{})
|
||||
for _, group := range groups {
|
||||
for _, skill := range group {
|
||||
if skill.Status == domain.NeedItemConfirmed {
|
||||
result[canonicalNeedKey(skill.Name)] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func addSkillNames(names map[string]struct{}, skills []domain.NeedSkill) {
|
||||
for _, skill := range skills {
|
||||
names[canonicalNeedKey(skill.Name)] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func validateSkillUniqueness(requirements domain.NeedRequirements) error {
|
||||
seen := make(map[string]struct{}, len(requirements.RequiredSkills)+len(requirements.DesiredSkills))
|
||||
for _, skill := range requirements.RequiredSkills {
|
||||
seen[canonicalNeedKey(skill.Name)] = struct{}{}
|
||||
}
|
||||
for index, skill := range requirements.DesiredSkills {
|
||||
key := canonicalNeedKey(skill.Name)
|
||||
if _, exists := seen[key]; exists {
|
||||
return invalidRequest(fmt.Sprintf("/desired_skills/%d/name", index), "duplicates a skill in required_skills")
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func addRejectedSuggestion(snapshot *domain.NeedSnapshot, field domain.NeedRejectedSuggestionField, value, pointer string) error {
|
||||
canonical := canonicalRejectedValue(field, value)
|
||||
if canonical == "" || isRejected(snapshot.RejectedSuggestions, field, canonical) {
|
||||
return nil
|
||||
}
|
||||
if len(snapshot.RejectedSuggestions) >= domain.MaxNeedRejectedSuggestions {
|
||||
return invalidRequest(pointer, "too many rejected suggestions")
|
||||
}
|
||||
snapshot.RejectedSuggestions = append(snapshot.RejectedSuggestions, domain.NeedRejectedSuggestion{Field: field, Value: canonical})
|
||||
return nil
|
||||
}
|
||||
|
||||
func isRejected(suggestions []domain.NeedRejectedSuggestion, field domain.NeedRejectedSuggestionField, value string) bool {
|
||||
canonical := canonicalRejectedValue(field, value)
|
||||
for _, suggestion := range suggestions {
|
||||
if suggestion.Field == field && suggestion.Value == canonical {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func canonicalRejectedValue(_ domain.NeedRejectedSuggestionField, value string) string {
|
||||
return canonicalNeedKey(value)
|
||||
}
|
||||
|
||||
func canonicalNeedKey(value string) string {
|
||||
return strings.ToLower(strings.Join(strings.Fields(value), " "))
|
||||
}
|
||||
|
||||
func scalarString[T ~string](value T) []string { return []string{string(value)} }
|
||||
|
||||
func scalarWorkFormats(value []domain.NeedWorkFormat) []string {
|
||||
result := make([]string, 0, len(value))
|
||||
for _, format := range value {
|
||||
result = append(result, string(format))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func scalarSalary(value domain.NeedSalaryRange) []string {
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return []string{string(encoded)}
|
||||
}
|
||||
|
||||
func taxonomyForSkillName(name string) *string {
|
||||
key := canonicalNeedKey(name)
|
||||
for _, rule := range needSkillRules {
|
||||
if strings.EqualFold(rule.name, key) && rule.taxonomy != "" {
|
||||
value := rule.taxonomy
|
||||
return &value
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func unknownNeedValue[T any]() domain.NeedValue[T] {
|
||||
return domain.NeedValue[T]{Status: domain.NeedValueUnknown}
|
||||
}
|
||||
|
||||
func confirmedNeedValue[T any](value T, source *domain.NeedValueSource) domain.NeedValue[T] {
|
||||
return domain.NeedValue[T]{Status: domain.NeedValueConfirmed, Value: &value, Source: source}
|
||||
}
|
||||
|
||||
func manualNeedSource() *domain.NeedValueSource {
|
||||
return &domain.NeedValueSource{Origin: domain.NeedValueManual}
|
||||
}
|
||||
|
||||
func cloneString(value *string) *string {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
cloned := *value
|
||||
return &cloned
|
||||
}
|
||||
|
||||
func invalidRequest(pointer, reason string) error {
|
||||
return &ValidationError{Pointer: pointer, Reason: reason}
|
||||
}
|
||||
|
||||
func mapDomainValidation(err error) error {
|
||||
if errors.Is(err, domain.ErrInvalidNeed) {
|
||||
pointer := ""
|
||||
if message := err.Error(); strings.Contains(message, "invalid need field ") {
|
||||
field := strings.SplitN(strings.SplitN(message, "invalid need field ", 2)[1], " ", 2)[0]
|
||||
pointer = field
|
||||
}
|
||||
return &ValidationError{Pointer: pointer, Reason: "value does not satisfy the need contract"}
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
package need
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
func TestCreateNeedUsesOnlyExplicitValuesAndSourceSuggestions(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
created := mustCreateNeed(t, CreateInput{
|
||||
Title: "Backend engineer",
|
||||
SourceText: Field[string]{Set: true, Value: "Ищем backend developer. Обязательно: Go, PostgreSQL. Желательно: Kafka."},
|
||||
Grade: Field[Decision[domain.GradeCode]]{Set: true, Null: true},
|
||||
DesiredSkills: []SkillInput{},
|
||||
}, now)
|
||||
requirements := created.Snapshot().Requirements
|
||||
if requirements.Specialization.Status != domain.NeedValueExtracted || requirements.Specialization.Value == nil || *requirements.Specialization.Value != domain.SpecializationBackend {
|
||||
t.Fatalf("specialization = %+v, want extracted backend", requirements.Specialization)
|
||||
}
|
||||
if requirements.Grade.Status != domain.NeedValueUnknown {
|
||||
t.Fatalf("grade = %+v, want explicitly unknown", requirements.Grade)
|
||||
}
|
||||
if len(requirements.RequiredSkills) != 2 || requirements.RequiredSkills[0].Name != "Go" || requirements.RequiredSkills[1].Name != "PostgreSQL" {
|
||||
t.Fatalf("required skills = %+v, want Go and PostgreSQL suggestions", requirements.RequiredSkills)
|
||||
}
|
||||
if requirements.DesiredSkills == nil || len(requirements.DesiredSkills) != 0 {
|
||||
t.Fatalf("desired skills = %#v, want explicitly empty", requirements.DesiredSkills)
|
||||
}
|
||||
if created.Version() != 1 || created.RequirementsVersion() != 1 || !created.CreatedAt().Equal(now) {
|
||||
t.Fatalf("created version/timestamp = %d/%d/%s", created.Version(), created.RequirementsVersion(), created.CreatedAt())
|
||||
}
|
||||
|
||||
manual := mustCreateNeed(t, CreateInput{
|
||||
Title: "Go engineer",
|
||||
Specialization: Field[Decision[domain.SpecializationCode]]{
|
||||
Set: true, Value: Decision[domain.SpecializationCode]{Value: domain.SpecializationBackend, Status: domain.NeedValueConfirmed},
|
||||
},
|
||||
RequiredSkills: []SkillInput{{Name: "Go", Status: domain.NeedItemConfirmed}},
|
||||
}, now)
|
||||
manualRequirements := manual.Snapshot().Requirements
|
||||
if manualRequirements.Specialization.Status != domain.NeedValueConfirmed || manualRequirements.Grade.Status != domain.NeedValueUnknown ||
|
||||
len(manualRequirements.RequiredSkills) != 1 || manualRequirements.RequiredSkills[0].Source.Origin != domain.NeedValueManual {
|
||||
t.Fatalf("manual requirements = %+v, want only supplied confirmed values", manualRequirements)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateConfirmsAndMovesStoredSuggestionWithoutLosingProvenance(t *testing.T) {
|
||||
current := mustCreateNeed(t, CreateInput{
|
||||
Title: "Backend engineer",
|
||||
SourceText: Field[string]{Set: true, Value: "Ищем backend developer. Обязательно: Go, PostgreSQL. Желательно: Kafka."},
|
||||
}, testNeedTime())
|
||||
before := current.Snapshot().Requirements
|
||||
if len(before.RequiredSkills) != 2 || len(before.DesiredSkills) != 1 {
|
||||
t.Fatalf("parsed lists = %v / %v", before.RequiredSkills, before.DesiredSkills)
|
||||
}
|
||||
goSource := before.RequiredSkills[0].Source
|
||||
updated, changed, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1,
|
||||
RequiredSkills: []SkillInput{{Name: "PostgreSQL", Status: domain.NeedItemExtracted}},
|
||||
DesiredSkills: []SkillInput{{Name: "Go", Status: domain.NeedItemConfirmed}, {Name: "Kafka", Status: domain.NeedItemExtracted}},
|
||||
}, testNeedTime().Add(time.Second))
|
||||
if err != nil {
|
||||
t.Fatalf("reviseNeed() error = %v", err)
|
||||
}
|
||||
if !changed || updated.Version() != 2 || updated.RequirementsVersion() != 2 {
|
||||
t.Fatalf("updated version/change = %d/%d/%v, want 2/2/true", updated.Version(), updated.RequirementsVersion(), changed)
|
||||
}
|
||||
got := updated.Snapshot().Requirements
|
||||
if len(got.RequiredSkills) != 1 || got.RequiredSkills[0].Name != "PostgreSQL" || len(got.DesiredSkills) != 2 {
|
||||
t.Fatalf("updated skill lists = %v / %v", got.RequiredSkills, got.DesiredSkills)
|
||||
}
|
||||
confirmedGo := got.DesiredSkills[0]
|
||||
if confirmedGo.Name != "Go" || confirmedGo.Status != domain.NeedItemConfirmed || confirmedGo.Source.Origin != domain.NeedValueExtractedFromText || !reflect.DeepEqual(confirmedGo.Source, goSource) {
|
||||
t.Fatalf("confirmed Go = %+v, want original extracted provenance", confirmedGo)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceEditReextractsSuggestionsButKeepsConfirmedValues(t *testing.T) {
|
||||
current := mustCreateNeed(t, CreateInput{
|
||||
Title: "Backend engineer",
|
||||
SourceText: Field[string]{Set: true, Value: "Ищем backend developer. Обязательно: Go, PostgreSQL."},
|
||||
}, testNeedTime())
|
||||
current, changed, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1,
|
||||
RequiredSkills: []SkillInput{{Name: "Go", Status: domain.NeedItemConfirmed}, {Name: "PostgreSQL", Status: domain.NeedItemExtracted}},
|
||||
}, testNeedTime().Add(time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("confirm first skill: changed=%v error=%v", changed, err)
|
||||
}
|
||||
confirmed := current.Snapshot().Requirements.RequiredSkills[0]
|
||||
updated, changed, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 2,
|
||||
SourceText: Field[string]{Set: true, Value: "Ищем backend developer. Обязательно: Go, Kafka."},
|
||||
}, testNeedTime().Add(2*time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("change source: changed=%v error=%v", changed, err)
|
||||
}
|
||||
requirements := updated.Snapshot().Requirements
|
||||
if updated.RequirementsVersion() != current.RequirementsVersion() {
|
||||
t.Fatalf("requirements_version = %d, want unchanged %d", updated.RequirementsVersion(), current.RequirementsVersion())
|
||||
}
|
||||
if len(requirements.RequiredSkills) != 2 || requirements.RequiredSkills[0].Name != confirmed.Name || requirements.RequiredSkills[0].Status != domain.NeedItemConfirmed || !reflect.DeepEqual(requirements.RequiredSkills[0].Source, confirmed.Source) {
|
||||
t.Fatalf("confirmed skill after source edit = %+v", requirements.RequiredSkills)
|
||||
}
|
||||
if requirements.RequiredSkills[1].Name != "Kafka" || requirements.RequiredSkills[1].Status != domain.NeedItemExtracted {
|
||||
t.Fatalf("reparsed suggestions = %+v, want Kafka only after confirmed Go", requirements.RequiredSkills)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeletedSkillSuggestionStaysSuppressedAcrossListsAndManualReadd(t *testing.T) {
|
||||
current := mustCreateNeed(t, CreateInput{
|
||||
Title: "Backend engineer",
|
||||
SourceText: Field[string]{Set: true, Value: "Желательно: PostgreSQL."},
|
||||
}, testNeedTime())
|
||||
deleted, changed, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1,
|
||||
DesiredSkills: []SkillInput{},
|
||||
}, testNeedTime().Add(time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("delete extracted skill: changed=%v error=%v", changed, err)
|
||||
}
|
||||
if !hasRejected(deleted.Snapshot().RejectedSuggestions, domain.NeedRejectedSkills, "POSTGRESQL") {
|
||||
t.Fatalf("deleted skill suppression = %+v, want case-insensitive common skill key", deleted.Snapshot().RejectedSuggestions)
|
||||
}
|
||||
|
||||
manual, changed, err := reviseNeed(deleted, UpdateInput{
|
||||
ExpectedVersion: 2,
|
||||
DesiredSkills: []SkillInput{{Name: "PostgreSQL", Status: domain.NeedItemConfirmed}},
|
||||
}, testNeedTime().Add(2*time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("manual readd: changed=%v error=%v", changed, err)
|
||||
}
|
||||
if len(manual.Snapshot().Requirements.DesiredSkills) != 1 || manual.Snapshot().Requirements.DesiredSkills[0].Source.Origin != domain.NeedValueManual {
|
||||
t.Fatalf("manual readd = %+v, want confirmed manual skill", manual.Snapshot().Requirements.DesiredSkills)
|
||||
}
|
||||
if !hasRejected(manual.Snapshot().RejectedSuggestions, domain.NeedRejectedSkills, "postgresql") {
|
||||
t.Fatalf("manual readd cleared old rejection: %+v", manual.Snapshot().RejectedSuggestions)
|
||||
}
|
||||
|
||||
deletedAgain, changed, err := reviseNeed(manual, UpdateInput{
|
||||
ExpectedVersion: 3,
|
||||
DesiredSkills: []SkillInput{},
|
||||
}, testNeedTime().Add(3*time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("delete manual readd: changed=%v error=%v", changed, err)
|
||||
}
|
||||
updated, changed, err := reviseNeed(deletedAgain, UpdateInput{
|
||||
ExpectedVersion: 4,
|
||||
SourceText: Field[string]{Set: true, Value: "Обязательно: PostgreSQL."},
|
||||
}, testNeedTime().Add(4*time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("change source after readd removal: changed=%v error=%v", changed, err)
|
||||
}
|
||||
final := updated.Snapshot()
|
||||
if len(final.Requirements.RequiredSkills) != 0 || len(final.Requirements.DesiredSkills) != 0 || !hasRejected(final.RejectedSuggestions, domain.NeedRejectedSkills, "postgresql") {
|
||||
t.Fatalf("suppressed skill returned after source edit: %+v", final.Requirements)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeletedScalarSuggestionStaysSuppressedAfterSourceEdit(t *testing.T) {
|
||||
current := mustCreateNeed(t, CreateInput{
|
||||
Title: "Backend engineer",
|
||||
SourceText: Field[string]{Set: true, Value: "Ищем backend developer."},
|
||||
}, testNeedTime())
|
||||
deleted, changed, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1,
|
||||
Specialization: Field[Decision[domain.SpecializationCode]]{Set: true, Null: true},
|
||||
}, testNeedTime().Add(time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("delete specialization: changed=%v error=%v", changed, err)
|
||||
}
|
||||
updated, changed, err := reviseNeed(deleted, UpdateInput{
|
||||
ExpectedVersion: 2,
|
||||
SourceText: Field[string]{Set: true, Value: "Ищем backend developer снова."},
|
||||
}, testNeedTime().Add(2*time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("change source: changed=%v error=%v", changed, err)
|
||||
}
|
||||
if got := updated.Snapshot(); got.Requirements.Specialization.Status != domain.NeedValueUnknown || !hasRejected(got.RejectedSuggestions, domain.NeedRejectedSpecialization, "BACKEND") {
|
||||
t.Fatalf("specialization was proposed again: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceNullKeepsEveryRequirementAndSourceOnlyEditKeepsRequirementsVersion(t *testing.T) {
|
||||
current := mustCreateNeed(t, CreateInput{
|
||||
Title: "Backend engineer",
|
||||
SourceText: Field[string]{Set: true, Value: "Ищем backend developer. Обязательно: Go."},
|
||||
}, testNeedTime())
|
||||
cleared, changed, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1,
|
||||
SourceText: Field[string]{Set: true, Null: true},
|
||||
}, testNeedTime().Add(time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("clear source text: changed=%v error=%v", changed, err)
|
||||
}
|
||||
if cleared.Snapshot().SourceText != nil || !reflect.DeepEqual(cleared.Snapshot().Requirements, current.Snapshot().Requirements) || cleared.RequirementsVersion() != current.RequirementsVersion() {
|
||||
t.Fatalf("cleared source changed requirements: %+v", cleared.Snapshot())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStalePatchReturnsNoopBeforeConflictAndConflictBeforeDomainError(t *testing.T) {
|
||||
current := mustCreateNeed(t, CreateInput{Title: "Backend engineer"}, testNeedTime())
|
||||
current, changed, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1, Title: Field[string]{Set: true, Value: "Updated title"},
|
||||
}, testNeedTime().Add(time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("initial title edit: changed=%v error=%v", changed, err)
|
||||
}
|
||||
noOp, changed, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1, Title: Field[string]{Set: true, Value: "Updated title"},
|
||||
}, testNeedTime().Add(2*time.Second))
|
||||
if err != nil || changed || noOp.Version() != current.Version() {
|
||||
t.Fatalf("stale no-op: version=%d changed=%v error=%v", noOp.Version(), changed, err)
|
||||
}
|
||||
_, _, err = reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1,
|
||||
Grade: Field[Decision[domain.GradeCode]]{Set: true, Value: Decision[domain.GradeCode]{Value: domain.GradeSenior, Status: domain.NeedValueExtracted}},
|
||||
}, testNeedTime().Add(2*time.Second))
|
||||
if !errors.Is(err, domain.ErrNeedVersionConflict) {
|
||||
t.Fatalf("stale invalid patch error = %v, want version conflict", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchRejectsExtractedValueNotStoredAsSuggestion(t *testing.T) {
|
||||
current := mustCreateNeed(t, CreateInput{Title: "Backend engineer"}, testNeedTime())
|
||||
_, _, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1,
|
||||
Grade: Field[Decision[domain.GradeCode]]{Set: true, Value: Decision[domain.GradeCode]{Value: domain.GradeSenior, Status: domain.NeedValueExtracted}},
|
||||
}, testNeedTime().Add(time.Second))
|
||||
var validation *ValidationError
|
||||
if !errors.As(err, &validation) || validation.Pointer != "/grade/status" {
|
||||
t.Fatalf("invalid extracted grade error = %v, want /grade/status validation", err)
|
||||
}
|
||||
}
|
||||
|
||||
func mustCreateNeed(t *testing.T, input CreateInput, now time.Time) domain.Need {
|
||||
t.Helper()
|
||||
needID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
t.Fatalf("generate need ID: %v", err)
|
||||
}
|
||||
organizationID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
t.Fatalf("generate organization ID: %v", err)
|
||||
}
|
||||
created, err := createNeed(input, organizationID, needID, now)
|
||||
if err != nil {
|
||||
t.Fatalf("createNeed() error = %v", err)
|
||||
}
|
||||
return created
|
||||
}
|
||||
|
||||
func testNeedTime() time.Time {
|
||||
return time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func hasRejected(suggestions []domain.NeedRejectedSuggestion, field domain.NeedRejectedSuggestionField, value string) bool {
|
||||
canonical := canonicalNeedKey(value)
|
||||
for _, suggestion := range suggestions {
|
||||
if suggestion.Field == field && suggestion.Value == canonical {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
package need
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
const needRulesVersion = "need-rules.2026-10.1"
|
||||
|
||||
var (
|
||||
needSectionPattern = regexp.MustCompile(`(?i)(обязательно|обязательные навыки|требуемые навыки|требования|желательно|желательные навыки|предпочтительно|технологии|стек|required skills|requirements|preferred skills|technology stack)\s*:?\s*`)
|
||||
needTaskPattern = regexp.MustCompile(`(?i)(задачи|обязанности|tasks|responsibilities)\s*:`)
|
||||
needNegationPattern = regexp.MustCompile(`(?i)(?:без|without|no|not(?:\s+required)?|не(?:\s+(?:требуется|нужен|нужна|нужно|обязательно|обязателен|обязательна|обязательны|требуемый|требуемая))?)\s*[:,\-]?\s*$`)
|
||||
needDomainPatterns = []domainRule{
|
||||
{pattern: regexp.MustCompile(`(?i)(в команду платежей)`), value: "платежи"},
|
||||
{pattern: regexp.MustCompile(`(?i)(в команду выплат)`), value: "выплаты"},
|
||||
{pattern: regexp.MustCompile(`(?i)(payments team)`), value: "payments"},
|
||||
{pattern: regexp.MustCompile(`(?i)(logistics team)`), value: "logistics"},
|
||||
}
|
||||
needSpecializationPatterns = []domainRule{
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])((?:ищем\s+)?(?:backend[ -](?:developer|engineer)|back-end[ -](?:developer|engineer)|бэкенд[- ]разработчик\p{L}*|бэкэнд[- ]разработчик\p{L}*|серверн\p{L}*\s+разработчик\p{L}*))(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationBackend)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])((?:ищем\s+)?(?:frontend[ -](?:developer|engineer)|front-end[ -](?:developer|engineer)|фронтенд[- ]разработчик\p{L}*|фронтэнд[- ]разработчик\p{L}*))(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationFrontend)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])((?:ищем\s+)?(?:mobile[ -](?:developer|engineer)|мобильн\p{L}*\s+разработчик\p{L}*))(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationMobile)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(network engineer|сетев\p{L}* инженер\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationNetworkEngineer)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(devops|sre)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationDevopsSRE)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(data analyst|аналитик данных)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationDataAnalyst)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(data scientist|machine learning|ml engineer|специалист\p{L}* машинн\p{L}* обучен\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationDSML)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(information security|информационн\p{L}* безопасност\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationInformationSecurity)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(qa engineer|тестировщик\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationQA)},
|
||||
}
|
||||
needGradePatterns = []domainRule{
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(intern|internship|стаж[её]р\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.GradeIntern)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(junior|jun|джуниор\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.GradeJunior)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(middle|mid|мидл\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.GradeMiddle)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(senior|sen|сеньор\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.GradeSenior)},
|
||||
{pattern: regexp.MustCompile(`(?i)(младш(?:ий|его|ему))\s+(?:backend|back-end|frontend|front-end|разработчик|инженер)`), value: string(domain.GradeJunior)},
|
||||
{pattern: regexp.MustCompile(`(?i)(средн(?:ий|его|ему))\s+(?:backend|back-end|frontend|front-end|разработчик|инженер)`), value: string(domain.GradeMiddle)},
|
||||
{pattern: regexp.MustCompile(`(?i)(старш(?:ий|его|ему))\s+(?:backend|back-end|frontend|front-end|разработчик|инженер)`), value: string(domain.GradeSenior)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:уров(?:ень|ня|не)|грейд(?:а|е)?|позици(?:я|и))\s+(младш(?:ий|его|ему))`), value: string(domain.GradeJunior)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:уров(?:ень|ня|не)|грейд(?:а|е)?|позици(?:я|и))\s+(средн(?:ий|его|ему))`), value: string(domain.GradeMiddle)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:уров(?:ень|ня|не)|грейд(?:а|е)?|позици(?:я|и))\s+(старш(?:ий|его|ему))`), value: string(domain.GradeSenior)},
|
||||
}
|
||||
needWorkFormatRules = []formatRule{
|
||||
{pattern: regexp.MustCompile(`(?i)(удал[её]нн\p{L}*|дистанционн\p{L}*|remote)`), value: domain.NeedWorkFormatRemote},
|
||||
{pattern: regexp.MustCompile(`(?i)(офис\p{L}*|office)`), value: domain.NeedWorkFormatOffice},
|
||||
{pattern: regexp.MustCompile(`(?i)(гибрид\p{L}*|hybrid)`), value: domain.NeedWorkFormatHybrid},
|
||||
}
|
||||
needSkillRules = []skillRule{
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(postgresql)(?:$|[^\p{L}\p{N}_])`), name: "PostgreSQL", taxonomy: "postgresql"},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(kafka)(?:$|[^\p{L}\p{N}_])`), name: "Kafka", taxonomy: "kafka"},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(temporal)(?:$|[^\p{L}\p{N}_])`), name: "Temporal"},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(docker)(?:$|[^\p{L}\p{N}_])`), name: "Docker", taxonomy: "docker"},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(go)(?:$|[^\p{L}\p{N}_])`), name: "Go", taxonomy: "go"},
|
||||
}
|
||||
)
|
||||
|
||||
type domainRule struct {
|
||||
pattern *regexp.Regexp
|
||||
value string
|
||||
}
|
||||
|
||||
type formatRule struct {
|
||||
pattern *regexp.Regexp
|
||||
value domain.NeedWorkFormat
|
||||
}
|
||||
|
||||
type skillRule struct {
|
||||
pattern *regexp.Regexp
|
||||
name string
|
||||
taxonomy string
|
||||
}
|
||||
|
||||
type needTextSection struct {
|
||||
start int
|
||||
end int
|
||||
quote string
|
||||
want bool
|
||||
}
|
||||
|
||||
type skillOccurrence struct {
|
||||
start int
|
||||
name string
|
||||
taxonomy string
|
||||
quote string
|
||||
section needTextSection
|
||||
}
|
||||
|
||||
const maxParsedEvidenceRunes = 300
|
||||
|
||||
func parseSourceText(source string, version int64) domain.NeedRequirements {
|
||||
requirements := domain.EmptyNeedRequirements()
|
||||
requirements.Specialization = parseNeedScalar(source, version, needSpecializationPatterns, func(value string) domain.SpecializationCode {
|
||||
return domain.SpecializationCode(value)
|
||||
})
|
||||
requirements.Grade = parseNeedScalar(source, version, needGradePatterns, func(value string) domain.GradeCode {
|
||||
return domain.GradeCode(value)
|
||||
})
|
||||
requirements.Domain = parseNeedScalar(source, version, needDomainPatterns, func(value string) string {
|
||||
return value
|
||||
})
|
||||
requirements.WorkFormats = parseWorkFormats(source, version)
|
||||
requirements.RequiredSkills, requirements.DesiredSkills = parseSkills(source, version)
|
||||
requirements.Tasks = parseTasks(source, version)
|
||||
return requirements
|
||||
}
|
||||
|
||||
func parseNeedScalar[T any](source string, version int64, rules []domainRule, convert func(string) T) domain.NeedValue[T] {
|
||||
type candidate struct {
|
||||
start int
|
||||
value T
|
||||
quote string
|
||||
}
|
||||
found := make([]candidate, 0, len(rules))
|
||||
values := make(map[string]struct{}, len(rules))
|
||||
for _, rule := range rules {
|
||||
for _, indices := range rule.pattern.FindAllStringSubmatchIndex(source, -1) {
|
||||
if len(indices) < 4 || hasNeedNegation(source, indices[2]) {
|
||||
continue
|
||||
}
|
||||
value := convert(rule.value)
|
||||
key := fmt.Sprint(value)
|
||||
values[key] = struct{}{}
|
||||
found = append(found, candidate{
|
||||
start: indices[2], value: value,
|
||||
quote: strings.TrimSpace(source[indices[2]:indices[3]]),
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(values) != 1 || len(found) == 0 {
|
||||
return unknownNeedValue[T]()
|
||||
}
|
||||
sort.Slice(found, func(i, j int) bool { return found[i].start < found[j].start })
|
||||
value := found[0].value
|
||||
return domain.NeedValue[T]{Status: domain.NeedValueExtracted, Value: &value, Source: extractedNeedSource(found[0].quote, version)}
|
||||
}
|
||||
|
||||
func parseWorkFormats(source string, version int64) domain.NeedValue[[]domain.NeedWorkFormat] {
|
||||
type foundFormat struct {
|
||||
start int
|
||||
end int
|
||||
format domain.NeedWorkFormat
|
||||
}
|
||||
found := make([]foundFormat, 0, len(needWorkFormatRules))
|
||||
seen := make(map[domain.NeedWorkFormat]struct{}, len(needWorkFormatRules))
|
||||
for _, rule := range needWorkFormatRules {
|
||||
for _, indices := range rule.pattern.FindAllStringSubmatchIndex(source, -1) {
|
||||
if len(indices) < 4 || hasNeedNegation(source, indices[2]) {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[rule.value]; ok {
|
||||
continue
|
||||
}
|
||||
seen[rule.value] = struct{}{}
|
||||
found = append(found, foundFormat{start: indices[2], end: indices[3], format: rule.value})
|
||||
}
|
||||
}
|
||||
if len(found) == 0 {
|
||||
return domain.NeedValue[[]domain.NeedWorkFormat]{Status: domain.NeedValueUnknown}
|
||||
}
|
||||
sort.Slice(found, func(i, j int) bool { return found[i].start < found[j].start })
|
||||
formats := make([]domain.NeedWorkFormat, 0, len(found))
|
||||
for _, item := range found {
|
||||
formats = append(formats, item.format)
|
||||
}
|
||||
quote := strings.TrimSpace(source[found[0].start:found[len(found)-1].end])
|
||||
if utf8.RuneCountInString(quote) > maxParsedEvidenceRunes {
|
||||
return domain.NeedValue[[]domain.NeedWorkFormat]{Status: domain.NeedValueUnknown}
|
||||
}
|
||||
value := formats
|
||||
return domain.NeedValue[[]domain.NeedWorkFormat]{
|
||||
Status: domain.NeedValueExtracted,
|
||||
Value: &value,
|
||||
Source: extractedNeedSource(quote, version),
|
||||
}
|
||||
}
|
||||
|
||||
func parseSkills(source string, version int64) ([]domain.NeedSkill, []domain.NeedSkill) {
|
||||
sections := skillSections(source)
|
||||
occurrences := make([]skillOccurrence, 0, len(needSkillRules))
|
||||
for _, section := range sections {
|
||||
segment := source[section.start:section.end]
|
||||
for _, rule := range needSkillRules {
|
||||
for _, indices := range rule.pattern.FindAllStringSubmatchIndex(segment, -1) {
|
||||
if len(indices) < 4 || hasNeedNegation(source, section.start+indices[2]) {
|
||||
continue
|
||||
}
|
||||
start := section.start + indices[2]
|
||||
occurrences = append(occurrences, skillOccurrence{
|
||||
start: start, name: rule.name, taxonomy: rule.taxonomy,
|
||||
quote: source[section.start+indices[2] : section.start+indices[3]], section: section,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(occurrences, func(i, j int) bool { return occurrences[i].start < occurrences[j].start })
|
||||
seen := make(map[string]struct{}, len(occurrences))
|
||||
required := make([]domain.NeedSkill, 0, len(occurrences))
|
||||
desired := make([]domain.NeedSkill, 0, len(occurrences))
|
||||
for _, occurrence := range occurrences {
|
||||
key := strings.ToLower(occurrence.name)
|
||||
if _, ok := seen[key]; ok {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
var taxonomy *string
|
||||
if occurrence.taxonomy != "" {
|
||||
value := occurrence.taxonomy
|
||||
taxonomy = &value
|
||||
}
|
||||
item := domain.NeedSkill{
|
||||
Name: occurrence.name, TaxonomyCode: taxonomy, Status: domain.NeedItemExtracted,
|
||||
Source: *extractedNeedSource(skillQuote(occurrence), version),
|
||||
}
|
||||
if occurrence.section.want {
|
||||
desired = append(desired, item)
|
||||
} else {
|
||||
required = append(required, item)
|
||||
}
|
||||
}
|
||||
return required, desired
|
||||
}
|
||||
|
||||
func skillQuote(occurrence skillOccurrence) string {
|
||||
if occurrence.section.quote != "" && utf8.RuneCountInString(occurrence.section.quote) <= maxParsedEvidenceRunes {
|
||||
return occurrence.section.quote
|
||||
}
|
||||
return occurrence.quote
|
||||
}
|
||||
|
||||
func skillSections(source string) []needTextSection {
|
||||
matches := needSectionPattern.FindAllStringSubmatchIndex(source, -1)
|
||||
if len(matches) == 0 {
|
||||
return []needTextSection{{start: 0, end: len(source), quote: ""}}
|
||||
}
|
||||
sections := make([]needTextSection, 0, len(matches))
|
||||
for index, match := range matches {
|
||||
end := len(source)
|
||||
if index+1 < len(matches) {
|
||||
end = matches[index+1][0]
|
||||
}
|
||||
if sentenceEnd := strings.IndexAny(source[match[1]:end], ".!?\n"); sentenceEnd >= 0 {
|
||||
end = match[1] + sentenceEnd
|
||||
}
|
||||
segment := strings.TrimSpace(source[match[0]:end])
|
||||
if segment == "" {
|
||||
continue
|
||||
}
|
||||
want := isDesiredSection(source[match[2]:match[3]])
|
||||
sections = append(sections, needTextSection{start: match[0], end: end, quote: segment, want: want})
|
||||
}
|
||||
if len(sections) == 0 {
|
||||
return []needTextSection{{start: 0, end: len(source), quote: ""}}
|
||||
}
|
||||
return sections
|
||||
}
|
||||
|
||||
func isDesiredSection(label string) bool {
|
||||
label = strings.ToLower(label)
|
||||
return strings.Contains(label, "желат") || strings.Contains(label, "предпочт") || strings.Contains(label, "preferred")
|
||||
}
|
||||
|
||||
func hasNeedNegation(source string, start int) bool {
|
||||
if start < 0 || start > len(source) {
|
||||
return false
|
||||
}
|
||||
prefix := source[:start]
|
||||
if boundary := strings.LastIndexAny(prefix, ".!?;,\n"); boundary >= 0 {
|
||||
prefix = prefix[boundary+1:]
|
||||
}
|
||||
return needNegationPattern.MatchString(prefix)
|
||||
}
|
||||
|
||||
func parseTasks(source string, version int64) []domain.NeedTask {
|
||||
indices := needTaskPattern.FindStringSubmatchIndex(source)
|
||||
if len(indices) < 4 {
|
||||
return []domain.NeedTask{}
|
||||
}
|
||||
start := indices[1]
|
||||
end := len(source)
|
||||
if sentenceEnd := strings.IndexAny(source[start:], ".!?\n"); sentenceEnd >= 0 {
|
||||
end = start + sentenceEnd
|
||||
}
|
||||
text := strings.TrimSpace(source[start:end])
|
||||
text = strings.Trim(text, " :;,-\t\r")
|
||||
quote := strings.TrimSpace(source[indices[0]:end])
|
||||
if text == "" || utf8.RuneCountInString(text) > maxParsedEvidenceRunes || utf8.RuneCountInString(quote) > maxParsedEvidenceRunes {
|
||||
return []domain.NeedTask{}
|
||||
}
|
||||
value := []rune(text)
|
||||
value[0] = unicode.ToUpper(value[0])
|
||||
text = string(value)
|
||||
return []domain.NeedTask{{
|
||||
Text: text, Status: domain.NeedItemExtracted,
|
||||
Source: *extractedNeedSource(quote, version),
|
||||
}}
|
||||
}
|
||||
|
||||
func extractedNeedSource(quote string, version int64) *domain.NeedValueSource {
|
||||
versionLabel := needRulesVersion
|
||||
var quoteValue *string
|
||||
if quote != "" {
|
||||
quoteValue = "e
|
||||
}
|
||||
extractedVersion := version
|
||||
return &domain.NeedValueSource{
|
||||
Origin: domain.NeedValueExtractedFromText,
|
||||
Quote: quoteValue,
|
||||
ExtractedInVersion: &extractedVersion,
|
||||
ExtractionVersion: &versionLabel,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package need
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
func TestParseSourceTextUsesDeterministicSuggestions(t *testing.T) {
|
||||
const source = "Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно."
|
||||
requirements := parseSourceText(source, 1)
|
||||
|
||||
if got := requirements.Specialization; got.Status != domain.NeedValueExtracted || got.Value == nil || *got.Value != domain.SpecializationBackend {
|
||||
t.Fatalf("specialization = %+v, want an extracted backend suggestion", got)
|
||||
}
|
||||
if got := requirements.Specialization.Source; got == nil || got.Quote == nil || *got.Quote != "Ищем бэкенд-разработчика" || *got.ExtractedInVersion != 1 || *got.ExtractionVersion != needRulesVersion {
|
||||
t.Fatalf("specialization provenance = %+v, want exact source and rules version", got)
|
||||
}
|
||||
if got := requirements.Grade; got.Status != domain.NeedValueUnknown || got.Value != nil || got.Source != nil {
|
||||
t.Fatalf("grade = %+v, want unknown", got)
|
||||
}
|
||||
if got := requirements.Domain; got.Status != domain.NeedValueExtracted || got.Value == nil || *got.Value != "платежи" || got.Source == nil || got.Source.Quote == nil || *got.Source.Quote != "в команду платежей" {
|
||||
t.Fatalf("domain = %+v, want a quoted suggestion", got)
|
||||
}
|
||||
if got := requirements.WorkFormats; got.Status != domain.NeedValueExtracted || got.Value == nil || len(*got.Value) != 1 || (*got.Value)[0] != domain.NeedWorkFormatRemote || got.Source == nil || got.Source.Quote == nil || *got.Source.Quote != "удаленно" {
|
||||
t.Fatalf("work formats = %+v, want a quoted remote suggestion", got)
|
||||
}
|
||||
if len(requirements.RequiredSkills) != 3 || len(requirements.DesiredSkills) != 1 {
|
||||
t.Fatalf("skill counts = %d required, %d desired, want 3 and 1", len(requirements.RequiredSkills), len(requirements.DesiredSkills))
|
||||
}
|
||||
wantRequired := []struct {
|
||||
name string
|
||||
taxonomy *string
|
||||
}{
|
||||
{name: "Go", taxonomy: needStringPointer("go")},
|
||||
{name: "PostgreSQL", taxonomy: needStringPointer("postgresql")},
|
||||
{name: "Temporal"},
|
||||
}
|
||||
for index, want := range wantRequired {
|
||||
got := requirements.RequiredSkills[index]
|
||||
if got.Name != want.name || got.Status != domain.NeedItemExtracted || !equalNeedStringPointer(got.TaxonomyCode, want.taxonomy) {
|
||||
t.Errorf("required_skills[%d] = %+v, want name %q, extracted, taxonomy %v", index, got, want.name, want.taxonomy)
|
||||
}
|
||||
if got.Source.Origin != domain.NeedValueExtractedFromText || got.Source.Quote == nil || *got.Source.Quote != "Обязательно: Go, PostgreSQL и Temporal" || got.Source.ExtractedInVersion == nil || *got.Source.ExtractedInVersion != 1 {
|
||||
t.Errorf("required_skills[%d] provenance = %+v, want the exact required section", index, got.Source)
|
||||
}
|
||||
}
|
||||
desired := requirements.DesiredSkills[0]
|
||||
if desired.Name != "Kafka" || desired.Status != domain.NeedItemExtracted || desired.Source.Quote == nil || *desired.Source.Quote != "Желательно опыт с Kafka" {
|
||||
t.Fatalf("desired skill = %+v, want a quoted extracted Kafka suggestion", desired)
|
||||
}
|
||||
if len(requirements.Tasks) != 1 || requirements.Tasks[0].Text != "Развивать сервис выплат и переводить его на событийную модель" || requirements.Tasks[0].Status != domain.NeedItemExtracted {
|
||||
t.Fatalf("tasks = %+v, want one extracted task", requirements.Tasks)
|
||||
}
|
||||
if got := requirements.Tasks[0].Source.Quote; got == nil || *got != "Задачи: развивать сервис выплат и переводить его на событийную модель" {
|
||||
t.Fatalf("task quote = %v, want exact source excerpt", got)
|
||||
}
|
||||
if requirements.Location.Status != domain.NeedValueUnknown || requirements.Salary.Status != domain.NeedValueUnknown {
|
||||
t.Fatalf("location or salary was inferred: location=%+v salary=%+v", requirements.Location, requirements.Salary)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSourceTextDoesNotSupplyDefaultsOrDuplicateSkills(t *testing.T) {
|
||||
requirements := parseSourceText("Разработчик использует GO и go, зарплата обсуждается позже.", 2)
|
||||
if requirements.Grade.Status != domain.NeedValueUnknown || requirements.WorkFormats.Status != domain.NeedValueUnknown || requirements.Salary.Status != domain.NeedValueUnknown {
|
||||
t.Fatalf("parser supplied an absent value: grade=%+v formats=%+v salary=%+v", requirements.Grade, requirements.WorkFormats, requirements.Salary)
|
||||
}
|
||||
if len(requirements.RequiredSkills) != 1 || requirements.RequiredSkills[0].Name != "Go" {
|
||||
t.Fatalf("required skills = %+v, want one case-insensitive suggestion", requirements.RequiredSkills)
|
||||
}
|
||||
if got := requirements.RequiredSkills[0].Source; got.ExtractedInVersion == nil || *got.ExtractedInVersion != 2 {
|
||||
t.Fatalf("source version = %+v, want version 2", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSourceTextCanSuggestExplicitGrade(t *testing.T) {
|
||||
requirements := parseSourceText("Нужен backend developer уровня Junior. Обязательно: Go.", 1)
|
||||
if requirements.Grade.Status != domain.NeedValueExtracted || requirements.Grade.Value == nil || *requirements.Grade.Value != domain.GradeJunior {
|
||||
t.Fatalf("grade = %+v, want extracted junior suggestion", requirements.Grade)
|
||||
}
|
||||
if requirements.Grade.Source == nil || requirements.Grade.Source.Quote == nil || *requirements.Grade.Source.Quote != "Junior" {
|
||||
t.Fatalf("grade provenance = %+v, want exact source term", requirements.Grade.Source)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSourceTextLeavesAmbiguousOrIncidentalGradesUnknown(t *testing.T) {
|
||||
for _, source := range []string{
|
||||
"Нужен backend developer уровня Junior или Senior.",
|
||||
"Возраст: старше 35 лет, младше 30 лет, среднее образование.",
|
||||
} {
|
||||
requirements := parseSourceText(source, 1)
|
||||
if requirements.Grade.Status != domain.NeedValueUnknown {
|
||||
t.Errorf("grade for %q = %+v, want unknown", source, requirements.Grade)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSourceTextLeavesAmbiguousSpecializationUnknown(t *testing.T) {
|
||||
requirements := parseSourceText("Нужен backend developer и frontend engineer.", 1)
|
||||
if requirements.Specialization.Status != domain.NeedValueUnknown {
|
||||
t.Fatalf("specialization = %+v, want unknown for conflicting roles", requirements.Specialization)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSourceTextSkipsNegatedRequirements(t *testing.T) {
|
||||
requirements := parseSourceText("Не Senior и не требуется PostgreSQL; без Go.", 1)
|
||||
if requirements.Grade.Status != domain.NeedValueUnknown {
|
||||
t.Fatalf("grade = %+v, want unknown for a negated value", requirements.Grade)
|
||||
}
|
||||
if len(requirements.RequiredSkills) != 0 || len(requirements.DesiredSkills) != 0 {
|
||||
t.Fatalf("skills = required %v, desired %v; want no negated suggestions", requirements.RequiredSkills, requirements.DesiredSkills)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSourceTextUsesUnicodeAwareEnglishBoundaries(t *testing.T) {
|
||||
requirements := parseSourceText("ищем xjunior разработчика, разрабатываем goплатформу", 1)
|
||||
if requirements.Grade.Status != domain.NeedValueUnknown || len(requirements.RequiredSkills) != 0 {
|
||||
t.Fatalf("grade=%+v skills=%v; want no substring matches", requirements.Grade, requirements.RequiredSkills)
|
||||
}
|
||||
}
|
||||
|
||||
func needStringPointer(value string) *string { return &value }
|
||||
|
||||
func equalNeedStringPointer(left, right *string) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == right
|
||||
}
|
||||
return *left == *right
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
package need
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
createOperation = "organization_need.create"
|
||||
createLocation = "need.Service.Create"
|
||||
maxIdempotencyKeySize = 255
|
||||
maxCanonicalBodySize = 1 << 20
|
||||
purgeExpiredBatch = 100
|
||||
)
|
||||
|
||||
// Keyring computes scoped idempotency digests. identity.Keyring implements
|
||||
// this interface so need commands use the existing server secret and store.
|
||||
type Keyring interface {
|
||||
IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte
|
||||
Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte
|
||||
}
|
||||
|
||||
// Dependencies configure one stateless need service.
|
||||
type Dependencies struct {
|
||||
Transactor outbound.Transactor
|
||||
Keyring Keyring
|
||||
Clock func() time.Time
|
||||
}
|
||||
|
||||
// Service applies organization-scoped need commands and reads.
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
keyring Keyring
|
||||
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.Clock == nil {
|
||||
return nil, errors.New("need.NewService - every dependency must be set")
|
||||
}
|
||||
return &Service{transactor: deps.Transactor, keyring: deps.Keyring, clock: deps.Clock}, nil
|
||||
}
|
||||
|
||||
// CreateCommand binds the authenticated actor and path organization to one
|
||||
// validated create request.
|
||||
type CreateCommand struct {
|
||||
ActorID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
IdempotencyKey string
|
||||
CanonicalBody []byte
|
||||
Input CreateInput
|
||||
}
|
||||
|
||||
// Create returns the original immutable response snapshot, including on an
|
||||
// identical retry after the live need has changed.
|
||||
func (service *Service) Create(ctx context.Context, command CreateCommand) (domain.NeedResponseSnapshot, error) {
|
||||
request, err := service.prepareCreate(command)
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, err
|
||||
}
|
||||
var result domain.NeedResponseSnapshot
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
result, err = service.createInTransaction(ctx, unit, command, request)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - run transaction: %w", createLocation, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (service *Service) createInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command CreateCommand,
|
||||
request createRequest,
|
||||
) (domain.NeedResponseSnapshot, error) {
|
||||
if err := authorizeNeedOwner(ctx, unit, command.ActorID, command.OrganizationID, createLocation); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, err
|
||||
}
|
||||
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - reserve idempotency record: %w", createLocation, err)
|
||||
}
|
||||
if !created {
|
||||
return replayNeedCreation(ctx, unit.NeedCreationResults(), request, command.OrganizationID, stored)
|
||||
}
|
||||
needID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - generate need ID: %w", createLocation, err)
|
||||
}
|
||||
createdNeed, err := createNeed(command.Input, command.OrganizationID, needID, request.now)
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - validate need: %w", createLocation, err)
|
||||
}
|
||||
snapshot := createdNeed.ResponseSnapshot()
|
||||
if err := validateCreationResultSize(snapshot); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - validate immutable creation response: %w", createLocation, err)
|
||||
}
|
||||
if err := unit.Needs().Create(ctx, createdNeed); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - store need: %w", createLocation, err)
|
||||
}
|
||||
if err := unit.NeedCreationResults().SaveCreationResult(ctx, request.scope, snapshot); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - store immutable creation response: %w", createLocation, err)
|
||||
}
|
||||
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err)
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
func replayNeedCreation(
|
||||
ctx context.Context,
|
||||
results outbound.NeedCreationResultRepository,
|
||||
request createRequest,
|
||||
organizationID uuid.UUID,
|
||||
stored outbound.IdempotencyRecord,
|
||||
) (domain.NeedResponseSnapshot, error) {
|
||||
if stored.Fingerprint != request.fingerprint {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - compare request fingerprint: %w", createLocation, ErrIdempotencyKeyReused)
|
||||
}
|
||||
snapshot, err := results.GetCreationResult(ctx, request.scope)
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - read immutable creation response: %w", createLocation, err)
|
||||
}
|
||||
result, err := domain.RestoreNeedResponseSnapshot(snapshot)
|
||||
if err != nil || result.Need.OrganizationID != organizationID {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - validate immutable creation response: %w", createLocation, domain.ErrInvalidNeed)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func validateCreationResultSize(snapshot domain.NeedResponseSnapshot) error {
|
||||
encoded, err := json.Marshal(snapshot)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - encode immutable creation response: %w", createLocation, err)
|
||||
}
|
||||
if len(encoded) > domain.MaxNeedCreationResultBytes {
|
||||
return invalidRequest("", "combined need response exceeds its storage bound")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type createRequest struct {
|
||||
fingerprint [outbound.IdempotencyDigestSize]byte
|
||||
scope [outbound.IdempotencyDigestSize]byte
|
||||
record outbound.IdempotencyRecord
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func (service *Service) prepareCreate(command CreateCommand) (createRequest, error) {
|
||||
const location = "need.Service.prepareCreate"
|
||||
switch {
|
||||
case command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil:
|
||||
return createRequest{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
|
||||
case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize:
|
||||
return createRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey)
|
||||
case len(command.CanonicalBody) == 0 || len(command.CanonicalBody) > maxCanonicalBodySize:
|
||||
return createRequest{}, fmt.Errorf("%s - canonical request body is outside its bound: %w", location, ErrInvalidCreateRequest)
|
||||
}
|
||||
fingerprint := service.keyring.Fingerprint(command.CanonicalBody)
|
||||
principal := command.ActorID.String() + ":" + command.OrganizationID.String()
|
||||
scope := service.keyring.IdempotencyScope(createOperation, command.IdempotencyKey, principal)
|
||||
now := service.clock().UTC().Truncate(time.Microsecond)
|
||||
if !validNeedApplicationTime(now) {
|
||||
return createRequest{}, invalidRequest("", "application time must be representable by the need contract")
|
||||
}
|
||||
expiresAt := now.Add(outbound.IdempotencyRetention)
|
||||
if !validNeedApplicationTime(expiresAt) {
|
||||
return createRequest{}, invalidRequest("", "idempotency expiry exceeds the need contract date range")
|
||||
}
|
||||
record := outbound.IdempotencyRecord{
|
||||
Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: expiresAt,
|
||||
}
|
||||
return createRequest{fingerprint: fingerprint, scope: scope, record: record, now: now}, nil
|
||||
}
|
||||
|
||||
// ListCommand selects an owner-scoped page of needs.
|
||||
type ListCommand struct {
|
||||
ActorID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
After *outbound.NeedListPosition
|
||||
Limit int32
|
||||
}
|
||||
|
||||
// List reads one page after checking the current account and owner membership
|
||||
// in the same transaction.
|
||||
func (service *Service) List(ctx context.Context, command ListCommand) (outbound.NeedPage, error) {
|
||||
const location = "need.Service.List"
|
||||
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil {
|
||||
return outbound.NeedPage{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
|
||||
}
|
||||
if command.Limit < 1 || command.Limit > outbound.MaxNeedPageSize {
|
||||
return outbound.NeedPage{}, fmt.Errorf("%s - page limit must be 1 to %d: %w", location, outbound.MaxNeedPageSize, domain.ErrInvalidNeed)
|
||||
}
|
||||
var result outbound.NeedPage
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeNeedOwner(ctx, unit, command.ActorID, command.OrganizationID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
page, err := unit.NeedLists().List(ctx, outbound.NeedListQuery{
|
||||
OrganizationID: command.OrganizationID, After: command.After, Limit: command.Limit,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - list organization needs: %w", location, err)
|
||||
}
|
||||
result = page
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.NeedPage{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Get reads the current need version for an active owner.
|
||||
func (service *Service) Get(ctx context.Context, actorID, organizationID, needID uuid.UUID) (domain.Need, error) {
|
||||
const location = "need.Service.Get"
|
||||
if actorID == uuid.Nil || organizationID == uuid.Nil || needID == uuid.Nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - actor, organization, and need IDs must be set: %w", location, ErrForbidden)
|
||||
}
|
||||
var result domain.Need
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeNeedOwner(ctx, unit, actorID, organizationID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
need, err := unit.Needs().Get(ctx, organizationID, needID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read organization need: %w", location, err)
|
||||
}
|
||||
result = need
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Update replaces the fields explicitly supplied by an active owner and
|
||||
// commits one immutable version when the merged request changes content.
|
||||
func (service *Service) Update(ctx context.Context, command UpdateCommand) (domain.Need, error) {
|
||||
const location = "need.Service.Update"
|
||||
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil || command.NeedID == uuid.Nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - actor, organization, and need IDs must be set: %w", location, ErrForbidden)
|
||||
}
|
||||
if command.Input.ExpectedVersion < 1 {
|
||||
return domain.Need{}, invalidRequest("/expected_version", "must be positive")
|
||||
}
|
||||
now := service.clock().UTC().Truncate(time.Microsecond)
|
||||
if !validNeedApplicationTime(now) {
|
||||
return domain.Need{}, invalidRequest("", "application time must be representable by the need contract")
|
||||
}
|
||||
var result domain.Need
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
result, err = service.updateInTransaction(ctx, unit, command, now)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func validNeedApplicationTime(value time.Time) bool {
|
||||
return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999
|
||||
}
|
||||
|
||||
func (service *Service) updateInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command UpdateCommand,
|
||||
now time.Time,
|
||||
) (domain.Need, error) {
|
||||
const location = "need.Service.Update"
|
||||
if err := authorizeNeedOwner(ctx, unit, command.ActorID, command.OrganizationID, location); err != nil {
|
||||
return domain.Need{}, err
|
||||
}
|
||||
store := unit.Needs()
|
||||
current, err := store.Get(ctx, command.OrganizationID, command.NeedID)
|
||||
if err != nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - read organization need: %w", location, err)
|
||||
}
|
||||
updated, changed, err := reviseNeed(current, command.Input, now)
|
||||
if err != nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - merge need update: %w", location, err)
|
||||
}
|
||||
if !changed {
|
||||
return updated, nil
|
||||
}
|
||||
if err := store.Save(ctx, command.OrganizationID, command.NeedID, current.Version(), updated); err != nil {
|
||||
if !errors.Is(err, outbound.ErrNeedVersionConflict) {
|
||||
return domain.Need{}, fmt.Errorf("%s - append need version: %w", location, err)
|
||||
}
|
||||
return service.recoverConcurrentUpdate(ctx, store, command, now)
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func (service *Service) recoverConcurrentUpdate(
|
||||
ctx context.Context,
|
||||
store outbound.NeedRepository,
|
||||
command UpdateCommand,
|
||||
now time.Time,
|
||||
) (domain.Need, error) {
|
||||
const location = "need.Service.Update"
|
||||
latest, err := store.Get(ctx, command.OrganizationID, command.NeedID)
|
||||
if err != nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - read winning need version: %w", location, err)
|
||||
}
|
||||
latest, changed, err := reviseNeed(latest, command.Input, now)
|
||||
if err != nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - compare concurrent need update: %w", location, err)
|
||||
}
|
||||
if changed {
|
||||
return domain.Need{}, fmt.Errorf("%s - append need version: %w", location, outbound.ErrNeedVersionConflict)
|
||||
}
|
||||
return latest, nil
|
||||
}
|
||||
|
||||
// UpdateCommand binds one versioned replacement to a trusted actor and path.
|
||||
type UpdateCommand struct {
|
||||
ActorID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
NeedID uuid.UUID
|
||||
Input UpdateInput
|
||||
}
|
||||
|
||||
func authorizeNeedOwner(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
actorID, organizationID uuid.UUID,
|
||||
location string,
|
||||
) error {
|
||||
user, err := unit.Users().GetByID(ctx, actorID)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return fmt.Errorf("%s - require existing employer account: %w", location, ErrForbidden)
|
||||
}
|
||||
return fmt.Errorf("%s - read account: %w", location, err)
|
||||
}
|
||||
if user.Scenario != domain.ScenarioEmployer {
|
||||
return fmt.Errorf("%s - require employer account: %w", location, ErrForbidden)
|
||||
}
|
||||
if !user.EmailVerified() {
|
||||
return fmt.Errorf("%s - require verified email: %w", location, ErrEmailNotVerified)
|
||||
}
|
||||
membership, err := unit.Organizations().LockActiveMembership(ctx, organizationID, actorID)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrOrganizationNotFound) {
|
||||
return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound)
|
||||
}
|
||||
return fmt.Errorf("%s - lock active membership: %w", location, err)
|
||||
}
|
||||
if membership.Role() != domain.OrganizationRoleOwner {
|
||||
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
package need
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type serviceTestKeyring struct{}
|
||||
|
||||
func (serviceTestKeyring) IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte {
|
||||
return sha256.Sum256([]byte(operation + "\x00" + key + "\x00" + principal))
|
||||
}
|
||||
|
||||
func (serviceTestKeyring) Fingerprint(body []byte) [outbound.IdempotencyDigestSize]byte {
|
||||
return sha256.Sum256(body)
|
||||
}
|
||||
|
||||
type serviceTestState struct {
|
||||
users map[uuid.UUID]domain.User
|
||||
memberships map[serviceTestMembershipKey]domain.Membership
|
||||
needs map[serviceTestNeedKey]domain.Need
|
||||
versions map[serviceTestVersionKey]domain.Need
|
||||
idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord
|
||||
results map[[outbound.IdempotencyDigestSize]byte]domain.NeedResponseSnapshot
|
||||
createCount int
|
||||
updateCount int
|
||||
}
|
||||
|
||||
type serviceTestMembershipKey struct {
|
||||
organizationID uuid.UUID
|
||||
userID uuid.UUID
|
||||
}
|
||||
|
||||
type serviceTestNeedKey struct {
|
||||
organizationID uuid.UUID
|
||||
needID uuid.UUID
|
||||
}
|
||||
|
||||
type serviceTestVersionKey struct {
|
||||
serviceTestNeedKey
|
||||
|
||||
version int64
|
||||
}
|
||||
|
||||
func newServiceTestState() serviceTestState {
|
||||
return serviceTestState{
|
||||
users: map[uuid.UUID]domain.User{}, memberships: map[serviceTestMembershipKey]domain.Membership{},
|
||||
needs: map[serviceTestNeedKey]domain.Need{}, versions: map[serviceTestVersionKey]domain.Need{},
|
||||
idempotency: map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord{},
|
||||
results: map[[outbound.IdempotencyDigestSize]byte]domain.NeedResponseSnapshot{},
|
||||
}
|
||||
}
|
||||
|
||||
func (state serviceTestState) clone() serviceTestState {
|
||||
cloned := newServiceTestState()
|
||||
for id, user := range state.users {
|
||||
cloned.users[id] = user
|
||||
}
|
||||
for key, membership := range state.memberships {
|
||||
cloned.memberships[key] = membership
|
||||
}
|
||||
for key, need := range state.needs {
|
||||
copyNeed, err := domain.RestoreNeed(need.Snapshot())
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
cloned.needs[key] = copyNeed
|
||||
}
|
||||
for key, need := range state.versions {
|
||||
copyNeed, err := domain.RestoreNeed(need.Snapshot())
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
cloned.versions[key] = copyNeed
|
||||
}
|
||||
for scope, record := range state.idempotency {
|
||||
cloned.idempotency[scope] = record
|
||||
}
|
||||
for scope, result := range state.results {
|
||||
copyResult, err := domain.RestoreNeedResponseSnapshot(result)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
cloned.results[scope] = copyResult
|
||||
}
|
||||
cloned.createCount = state.createCount
|
||||
cloned.updateCount = state.updateCount
|
||||
return cloned
|
||||
}
|
||||
|
||||
type serviceTestTransactor struct {
|
||||
mu sync.Mutex
|
||||
|
||||
state serviceTestState
|
||||
failResultSave bool
|
||||
}
|
||||
|
||||
func newServiceTestTransactor(state serviceTestState) *serviceTestTransactor {
|
||||
return &serviceTestTransactor{state: state}
|
||||
}
|
||||
|
||||
func (transactor *serviceTestTransactor) WithinTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error {
|
||||
transactor.mu.Lock()
|
||||
defer transactor.mu.Unlock()
|
||||
working := transactor.state.clone()
|
||||
unit := &serviceTestUnit{state: &working, failResultSave: transactor.failResultSave}
|
||||
if err := work(ctx, unit); err != nil {
|
||||
return err
|
||||
}
|
||||
transactor.state = working
|
||||
return nil
|
||||
}
|
||||
|
||||
func (transactor *serviceTestTransactor) snapshot() serviceTestState {
|
||||
transactor.mu.Lock()
|
||||
defer transactor.mu.Unlock()
|
||||
return transactor.state.clone()
|
||||
}
|
||||
|
||||
type serviceTestUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
state *serviceTestState
|
||||
failResultSave bool
|
||||
}
|
||||
|
||||
func (unit *serviceTestUnit) Users() outbound.UserRepository {
|
||||
return serviceTestUsers{state: unit.state}
|
||||
}
|
||||
|
||||
func (unit *serviceTestUnit) Organizations() outbound.OrganizationRepository {
|
||||
return serviceTestOrganizations{state: unit.state}
|
||||
}
|
||||
|
||||
func (unit *serviceTestUnit) IdempotencyRecords() outbound.IdempotencyRepository {
|
||||
return serviceTestIdempotency{state: unit.state}
|
||||
}
|
||||
|
||||
func (unit *serviceTestUnit) Needs() outbound.NeedRepository {
|
||||
return serviceTestNeeds{state: unit.state, failResultSave: unit.failResultSave}
|
||||
}
|
||||
|
||||
func (unit *serviceTestUnit) NeedLists() outbound.NeedListRepository {
|
||||
return serviceTestNeeds{state: unit.state, failResultSave: unit.failResultSave}
|
||||
}
|
||||
|
||||
func (unit *serviceTestUnit) NeedCreationResults() outbound.NeedCreationResultRepository {
|
||||
return serviceTestNeeds{state: unit.state, failResultSave: unit.failResultSave}
|
||||
}
|
||||
|
||||
type serviceTestUsers struct {
|
||||
outbound.UserRepository
|
||||
|
||||
state *serviceTestState
|
||||
}
|
||||
|
||||
func (repository serviceTestUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
|
||||
user, ok := repository.state.users[id]
|
||||
if !ok {
|
||||
return domain.User{}, outbound.ErrUserNotFound
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
type serviceTestOrganizations struct {
|
||||
outbound.OrganizationRepository
|
||||
|
||||
state *serviceTestState
|
||||
}
|
||||
|
||||
func (repository serviceTestOrganizations) LockActiveMembership(_ context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) {
|
||||
membership, ok := repository.state.memberships[serviceTestMembershipKey{organizationID: organizationID, userID: userID}]
|
||||
if !ok || !membership.GrantsAccess() {
|
||||
return domain.Membership{}, outbound.ErrOrganizationNotFound
|
||||
}
|
||||
return membership, nil
|
||||
}
|
||||
|
||||
type serviceTestIdempotency struct {
|
||||
outbound.IdempotencyRepository
|
||||
|
||||
state *serviceTestState
|
||||
}
|
||||
|
||||
func (repository serviceTestIdempotency) Reserve(_ context.Context, record outbound.IdempotencyRecord) (outbound.IdempotencyRecord, bool, error) {
|
||||
if existing, ok := repository.state.idempotency[record.Scope]; ok && existing.ExpiresAt.After(record.CreatedAt) {
|
||||
return existing, false, nil
|
||||
}
|
||||
repository.state.idempotency[record.Scope] = record
|
||||
return record, true, nil
|
||||
}
|
||||
|
||||
func (repository serviceTestIdempotency) Find(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, at time.Time) (outbound.IdempotencyRecord, error) {
|
||||
record, ok := repository.state.idempotency[scope]
|
||||
if !ok || !record.ExpiresAt.After(at) {
|
||||
return outbound.IdempotencyRecord{}, outbound.ErrIdempotencyRecordNotFound
|
||||
}
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func (repository serviceTestIdempotency) PurgeExpired(_ context.Context, at time.Time, limit int32) (int64, error) {
|
||||
var deleted int64
|
||||
for scope, record := range repository.state.idempotency {
|
||||
if deleted >= int64(limit) {
|
||||
break
|
||||
}
|
||||
if !record.ExpiresAt.After(at) {
|
||||
delete(repository.state.idempotency, scope)
|
||||
delete(repository.state.results, scope)
|
||||
deleted++
|
||||
}
|
||||
}
|
||||
return deleted, nil
|
||||
}
|
||||
|
||||
type serviceTestNeeds struct {
|
||||
outbound.NeedRepository
|
||||
|
||||
state *serviceTestState
|
||||
failResultSave bool
|
||||
}
|
||||
|
||||
func (repository serviceTestNeeds) Create(_ context.Context, need domain.Need) error {
|
||||
key := serviceTestNeedKey{organizationID: need.OrganizationID(), needID: need.ID()}
|
||||
if _, exists := repository.state.needs[key]; exists {
|
||||
return outbound.ErrNeedAlreadyExists
|
||||
}
|
||||
repository.state.needs[key] = need
|
||||
repository.state.versions[serviceTestVersionKey{serviceTestNeedKey: key, version: need.Version()}] = need
|
||||
repository.state.createCount++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository serviceTestNeeds) Get(_ context.Context, organizationID, needID uuid.UUID) (domain.Need, error) {
|
||||
need, ok := repository.state.needs[serviceTestNeedKey{organizationID: organizationID, needID: needID}]
|
||||
if !ok {
|
||||
return domain.Need{}, outbound.ErrNeedNotFound
|
||||
}
|
||||
return need, nil
|
||||
}
|
||||
|
||||
func (repository serviceTestNeeds) GetVersion(_ context.Context, organizationID, needID uuid.UUID, version int64) (domain.Need, error) {
|
||||
need, ok := repository.state.versions[serviceTestVersionKey{serviceTestNeedKey: serviceTestNeedKey{organizationID: organizationID, needID: needID}, version: version}]
|
||||
if !ok {
|
||||
return domain.Need{}, outbound.ErrNeedNotFound
|
||||
}
|
||||
return need, nil
|
||||
}
|
||||
|
||||
func (repository serviceTestNeeds) Save(_ context.Context, organizationID, needID uuid.UUID, expectedVersion int64, next domain.Need) error {
|
||||
key := serviceTestNeedKey{organizationID: organizationID, needID: needID}
|
||||
current, ok := repository.state.needs[key]
|
||||
if !ok {
|
||||
return outbound.ErrNeedNotFound
|
||||
}
|
||||
if !current.IsNextVersionOf(next, expectedVersion) {
|
||||
return outbound.ErrNeedVersionConflict
|
||||
}
|
||||
repository.state.needs[key] = next
|
||||
repository.state.versions[serviceTestVersionKey{serviceTestNeedKey: key, version: next.Version()}] = next
|
||||
repository.state.updateCount++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository serviceTestNeeds) List(_ context.Context, query outbound.NeedListQuery) (outbound.NeedPage, error) {
|
||||
items := make([]domain.Need, 0)
|
||||
for key, need := range repository.state.needs {
|
||||
if key.organizationID != query.OrganizationID {
|
||||
continue
|
||||
}
|
||||
position := outbound.NeedCreationPosition(need)
|
||||
if query.After != nil && needPositionIsNotBefore(position, *query.After) {
|
||||
continue
|
||||
}
|
||||
items = append(items, need)
|
||||
}
|
||||
for left := 0; left < len(items); left++ {
|
||||
for right := left + 1; right < len(items); right++ {
|
||||
leftPosition, rightPosition := outbound.NeedCreationPosition(items[left]), outbound.NeedCreationPosition(items[right])
|
||||
if rightPosition.CreatedAt.After(leftPosition.CreatedAt) || rightPosition.CreatedAt.Equal(leftPosition.CreatedAt) && rightPosition.NeedID.String() > leftPosition.NeedID.String() {
|
||||
items[left], items[right] = items[right], items[left]
|
||||
}
|
||||
}
|
||||
}
|
||||
page := outbound.NeedPage{Items: make([]domain.Need, 0, min(int(query.Limit), len(items)))}
|
||||
if len(items) > int(query.Limit) {
|
||||
page.HasMore = true
|
||||
items = items[:query.Limit]
|
||||
}
|
||||
page.Items = append(page.Items, items...)
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func needPositionIsNotBefore(position, after outbound.NeedListPosition) bool {
|
||||
if position.CreatedAt.After(after.CreatedAt) {
|
||||
return true
|
||||
}
|
||||
if position.CreatedAt.Before(after.CreatedAt) {
|
||||
return false
|
||||
}
|
||||
return position.NeedID.String() >= after.NeedID.String()
|
||||
}
|
||||
|
||||
func (repository serviceTestNeeds) SaveCreationResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, snapshot domain.NeedResponseSnapshot) error {
|
||||
if repository.failResultSave {
|
||||
return errors.New("simulated response snapshot failure")
|
||||
}
|
||||
if _, ok := repository.state.idempotency[scope]; !ok {
|
||||
return outbound.ErrIdempotencyRecordNotFound
|
||||
}
|
||||
repository.state.results[scope] = snapshot
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository serviceTestNeeds) GetCreationResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (domain.NeedResponseSnapshot, error) {
|
||||
snapshot, ok := repository.state.results[scope]
|
||||
if !ok {
|
||||
return domain.NeedResponseSnapshot{}, outbound.ErrNeedCreationResultNotFound
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
func newNeedServiceHarness(t *testing.T) (*Service, *serviceTestTransactor, uuid.UUID, uuid.UUID, func(time.Time)) {
|
||||
t.Helper()
|
||||
now := time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC)
|
||||
current := now
|
||||
userID, organizationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7())
|
||||
verifiedAt := now.Add(-time.Hour)
|
||||
state := newServiceTestState()
|
||||
state.users[userID] = domain.User{ID: userID, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verifiedAt}
|
||||
membership, err := domain.NewOwnerMembership(organizationID, userID, now)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOwnerMembership() error = %v", err)
|
||||
}
|
||||
state.memberships[serviceTestMembershipKey{organizationID: organizationID, userID: userID}] = membership
|
||||
transactor := newServiceTestTransactor(state)
|
||||
service, err := NewService(Dependencies{Transactor: transactor, Keyring: serviceTestKeyring{}, Clock: func() time.Time { return current }})
|
||||
if err != nil {
|
||||
t.Fatalf("NewService() error = %v", err)
|
||||
}
|
||||
setTime := func(value time.Time) { current = value }
|
||||
return service, transactor, userID, organizationID, setTime
|
||||
}
|
||||
|
||||
func testNeedCreateCommand(actorID, organizationID uuid.UUID, key, title string) CreateCommand {
|
||||
return CreateCommand{
|
||||
ActorID: actorID, OrganizationID: organizationID, IdempotencyKey: key,
|
||||
CanonicalBody: []byte(fmt.Sprintf(`{"title":%q}`, title)),
|
||||
Input: CreateInput{Title: title},
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateReplaysOriginalNeedAfterUpdate(t *testing.T) {
|
||||
service, transactor, actorID, organizationID, _ := newNeedServiceHarness(t)
|
||||
command := testNeedCreateCommand(actorID, organizationID, "request-1", "Initial need")
|
||||
created, err := service.Create(t.Context(), command)
|
||||
if err != nil {
|
||||
t.Fatalf("Create() error = %v", err)
|
||||
}
|
||||
updated, err := service.Update(t.Context(), UpdateCommand{
|
||||
ActorID: actorID, OrganizationID: organizationID, NeedID: created.Need.ID,
|
||||
Input: UpdateInput{ExpectedVersion: 1, Title: Field[string]{Set: true, Value: "Updated need"}},
|
||||
})
|
||||
if err != nil || updated.Version() != 2 {
|
||||
t.Fatalf("Update() version = %d, error = %v", updated.Version(), err)
|
||||
}
|
||||
replayed, err := service.Create(t.Context(), command)
|
||||
if err != nil || replayed.Need.ID != created.Need.ID || replayed.Need.Version != 1 || replayed.Need.Title != "Initial need" {
|
||||
t.Fatalf("Create(retry) = id %s version %d title %q error %v, want the original response", replayed.Need.ID, replayed.Need.Version, replayed.Need.Title, err)
|
||||
}
|
||||
current, err := service.Get(t.Context(), actorID, organizationID, created.Need.ID)
|
||||
if err != nil || current.Version() != 2 || current.Snapshot().Title != "Updated need" {
|
||||
t.Fatalf("Get after replay = version %d title %q error %v", current.Version(), current.Snapshot().Title, err)
|
||||
}
|
||||
state := transactor.snapshot()
|
||||
if state.createCount != 1 || state.updateCount != 1 {
|
||||
t.Fatalf("stored creates = %d updates = %d, want 1 create and 1 update", state.createCount, state.updateCount)
|
||||
}
|
||||
command.CanonicalBody = []byte(`{"title":"Different body"}`)
|
||||
command.Input.Title = "Different body"
|
||||
if _, err := service.Create(t.Context(), command); !errors.Is(err, ErrIdempotencyKeyReused) {
|
||||
t.Fatalf("Create(same key, changed body) error = %v, want ErrIdempotencyKeyReused", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateReusesExpiredIdempotencyScopeAtExactDeadline(t *testing.T) {
|
||||
service, transactor, actorID, organizationID, setTime := newNeedServiceHarness(t)
|
||||
firstCommand := testNeedCreateCommand(actorID, organizationID, "request-2", "Before expiry")
|
||||
first, err := service.Create(t.Context(), firstCommand)
|
||||
if err != nil {
|
||||
t.Fatalf("Create(first) error = %v", err)
|
||||
}
|
||||
setTime(first.Need.CreatedAt.Add(outbound.IdempotencyRetention))
|
||||
secondCommand := testNeedCreateCommand(actorID, organizationID, "request-2", "After expiry")
|
||||
second, err := service.Create(t.Context(), secondCommand)
|
||||
if err != nil || second.Need.ID == first.Need.ID || second.Need.Title != "After expiry" {
|
||||
t.Fatalf("Create(expired key) = id %s title %q error %v", second.Need.ID, second.Need.Title, err)
|
||||
}
|
||||
state := transactor.snapshot()
|
||||
if state.createCount != 2 || len(state.results) != 1 {
|
||||
t.Fatalf("stored creates = %d results = %d, want two creates and one replaced snapshot", state.createCount, len(state.results))
|
||||
}
|
||||
replayed, err := service.Create(t.Context(), secondCommand)
|
||||
if err != nil || replayed.Need.ID != second.Need.ID || replayed.Need.Title != "After expiry" {
|
||||
t.Fatalf("Create(replay after reuse) = id %s title %q error %v", replayed.Need.ID, replayed.Need.Title, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRejectsIdempotencyExpiryOutsideNeedDateRange(t *testing.T) {
|
||||
service, transactor, actorID, organizationID, setTime := newNeedServiceHarness(t)
|
||||
setTime(time.Date(9999, time.December, 31, 23, 59, 59, 0, time.UTC))
|
||||
if _, err := service.Create(t.Context(), testNeedCreateCommand(actorID, organizationID, "request-edge", "Edge need")); !errors.Is(err, ErrInvalidRequest) {
|
||||
t.Fatalf("Create() at the final contract date error = %v, want ErrInvalidRequest for 24-hour expiry", err)
|
||||
}
|
||||
state := transactor.snapshot()
|
||||
if state.createCount != 0 || len(state.idempotency) != 0 || len(state.results) != 0 {
|
||||
t.Fatalf("out-of-range expiry wrote state: creates=%d keys=%d results=%d", state.createCount, len(state.idempotency), len(state.results))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRollbackLeavesNoNeedOrReplayResult(t *testing.T) {
|
||||
service, transactor, actorID, organizationID, _ := newNeedServiceHarness(t)
|
||||
transactor.failResultSave = true
|
||||
command := testNeedCreateCommand(actorID, organizationID, "request-3", "Rollback need")
|
||||
if _, err := service.Create(t.Context(), command); err == nil {
|
||||
t.Fatal("Create() succeeded despite result snapshot failure")
|
||||
}
|
||||
state := transactor.snapshot()
|
||||
if state.createCount != 0 || len(state.needs) != 0 || len(state.idempotency) != 0 || len(state.results) != 0 {
|
||||
t.Fatalf("failed create left state: creates %d needs %d keys %d results %d", state.createCount, len(state.needs), len(state.idempotency), len(state.results))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentCreateWithSameKeyCreatesOneNeed(t *testing.T) {
|
||||
service, transactor, actorID, organizationID, _ := newNeedServiceHarness(t)
|
||||
command := testNeedCreateCommand(actorID, organizationID, "request-4", "One need")
|
||||
var group sync.WaitGroup
|
||||
errorsFound := make(chan error, 2)
|
||||
ids := make(chan uuid.UUID, 2)
|
||||
for range 2 {
|
||||
group.Go(func() {
|
||||
result, err := service.Create(t.Context(), command)
|
||||
if err != nil {
|
||||
errorsFound <- err
|
||||
return
|
||||
}
|
||||
ids <- result.Need.ID
|
||||
})
|
||||
}
|
||||
group.Wait()
|
||||
close(errorsFound)
|
||||
for err := range errorsFound {
|
||||
t.Fatalf("concurrent Create() error = %v", err)
|
||||
}
|
||||
close(ids)
|
||||
var first uuid.UUID
|
||||
for id := range ids {
|
||||
if first != uuid.Nil && first != id {
|
||||
t.Fatalf("concurrent calls returned different need IDs: %s and %s", first, id)
|
||||
}
|
||||
first = id
|
||||
}
|
||||
state := transactor.snapshot()
|
||||
if first == uuid.Nil || state.createCount != 1 || len(state.needs) != 1 {
|
||||
t.Fatalf("concurrent calls left ID %s, creates %d, needs %d", first, state.createCount, len(state.needs))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,658 @@
|
||||
// Package supportcase creates and reads account-owned support cases.
|
||||
package supportcase
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrForbidden = errors.New("support case operation forbidden")
|
||||
ErrEmailNotVerified = errors.New("support case operation requires a confirmed email")
|
||||
ErrIdempotencyKeyReused = errors.New("support case idempotency key was reused")
|
||||
ErrInvalidIdempotencyKey = errors.New("invalid support case idempotency key")
|
||||
ErrInvalidCreateRequest = errors.New("invalid support case create request")
|
||||
ErrStateConflict = errors.New("support case conflicts with current state")
|
||||
ErrPolicyUnavailable = errors.New("support case policy is unavailable")
|
||||
ErrRateLimited = errors.New("support case request limit reached")
|
||||
)
|
||||
|
||||
const (
|
||||
createOperation = "support.case.create"
|
||||
createLocation = "supportcase.Service.Create"
|
||||
maxIdempotencyKeySize = 255
|
||||
maxCanonicalBodySize = 1 << 20
|
||||
purgeExpiredBatch = 100
|
||||
)
|
||||
|
||||
// Keyring computes scoped idempotency digests. identity.Keyring implements
|
||||
// this interface so support cases use the existing server secret and storage.
|
||||
type Keyring interface {
|
||||
IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte
|
||||
Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte
|
||||
}
|
||||
|
||||
// Dependencies are the collaborators of Service.
|
||||
type Dependencies struct {
|
||||
Transactor outbound.Transactor
|
||||
Keyring Keyring
|
||||
Clock func() time.Time
|
||||
}
|
||||
|
||||
// Service applies support-case commands and reads.
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
keyring Keyring
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
func NewService(dependencies Dependencies) (*Service, error) {
|
||||
if dependencies.Transactor == nil || dependencies.Keyring == nil || dependencies.Clock == nil {
|
||||
return nil, errors.New("supportcase.NewService - every dependency must be set")
|
||||
}
|
||||
return &Service{
|
||||
transactor: dependencies.Transactor,
|
||||
keyring: dependencies.Keyring,
|
||||
clock: dependencies.Clock,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CreateCommand contains only user-stated fields and the authenticated actor.
|
||||
// Object data, policy decisions, status, response target, rubric, and staff
|
||||
// identities are resolved by the service.
|
||||
type CreateCommand struct {
|
||||
ActorID uuid.UUID
|
||||
IdempotencyKey string
|
||||
CanonicalBody []byte
|
||||
Type domain.SupportCaseType
|
||||
Description string
|
||||
Object *domain.SupportCaseReference
|
||||
AssessmentTarget *domain.SupportCaseAssessmentTarget
|
||||
ComplaintReason *domain.SupportCaseComplaintReason
|
||||
}
|
||||
|
||||
func (CreateCommand) String() string { return "[support case create command]" }
|
||||
func (CreateCommand) GoString() string { return "[support case create command]" }
|
||||
func (CreateCommand) LogValue() slog.Value {
|
||||
return slog.StringValue("[support case create command]")
|
||||
}
|
||||
|
||||
// CreateResult is the immutable response snapshot for a successful create.
|
||||
type CreateResult struct {
|
||||
Case domain.SupportCase
|
||||
Replayed bool
|
||||
TargetLate bool
|
||||
}
|
||||
|
||||
type createRequest struct {
|
||||
command CreateCommand
|
||||
scope [outbound.IdempotencyDigestSize]byte
|
||||
fingerprint [outbound.IdempotencyDigestSize]byte
|
||||
record outbound.IdempotencyRecord
|
||||
now time.Time
|
||||
}
|
||||
|
||||
type createAttempt struct {
|
||||
result CreateResult
|
||||
err error
|
||||
}
|
||||
|
||||
// Create opens a support case and stores its stable result with the generic
|
||||
// idempotency record in one transaction. Domain rejections after the request
|
||||
// budget is consumed are returned only after the transaction commits.
|
||||
func (service *Service) Create(ctx context.Context, command CreateCommand) (CreateResult, error) {
|
||||
request, err := service.prepareCreateRequest(command)
|
||||
if err != nil {
|
||||
return CreateResult{}, err
|
||||
}
|
||||
var attempt createAttempt
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
attempt, err = service.createInTransaction(ctx, unit, request)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return CreateResult{}, fmt.Errorf("%s - run transaction: %w", createLocation, err)
|
||||
}
|
||||
return attempt.result, attempt.err
|
||||
}
|
||||
|
||||
func (service *Service) prepareCreateRequest(command CreateCommand) (createRequest, error) {
|
||||
const location = "supportcase.Service.prepareCreateRequest"
|
||||
if command.ActorID == uuid.Nil {
|
||||
return createRequest{}, fmt.Errorf("%s - actor ID must be set: %w", location, ErrForbidden)
|
||||
}
|
||||
if !validIdempotencyKey(command.IdempotencyKey) {
|
||||
return createRequest{}, fmt.Errorf("%s - key must have 1 to 255 allowed bytes: %w", location, ErrInvalidIdempotencyKey)
|
||||
}
|
||||
canonicalBody := command.CanonicalBody
|
||||
if len(canonicalBody) == 0 {
|
||||
var err error
|
||||
canonicalBody, err = canonicalCreateBody(command)
|
||||
if err != nil {
|
||||
return createRequest{}, fmt.Errorf("%s - encode canonical request: %w", location, ErrInvalidCreateRequest)
|
||||
}
|
||||
}
|
||||
if len(canonicalBody) > maxCanonicalBodySize {
|
||||
return createRequest{}, fmt.Errorf("%s - request body exceeds its bound: %w", location, ErrInvalidCreateRequest)
|
||||
}
|
||||
fingerprint := service.keyring.Fingerprint(canonicalBody)
|
||||
scope := service.keyring.IdempotencyScope(createOperation, command.IdempotencyKey, command.ActorID.String())
|
||||
return createRequest{
|
||||
command: command, scope: scope, fingerprint: fingerprint,
|
||||
record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (service *Service) createInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
request createRequest,
|
||||
) (createAttempt, error) {
|
||||
user, err := requireAccount(ctx, unit, request.command.ActorID, createLocation)
|
||||
if err != nil {
|
||||
return createAttempt{}, err
|
||||
}
|
||||
if user.Scenario == domain.ScenarioEmployer && request.command.Type != domain.SupportCaseTypeSupport {
|
||||
return createAttempt{}, ErrForbidden
|
||||
}
|
||||
repositories, attempts, err := supportCaseRepositories(unit)
|
||||
if err != nil {
|
||||
return createAttempt{}, err
|
||||
}
|
||||
latestRequestAt, err := repositories.SupportCaseRequestLimits().LockOwner(ctx, request.command.ActorID)
|
||||
if err != nil {
|
||||
return createAttempt{}, fmt.Errorf("%s - lock account request budget: %w", createLocation, err)
|
||||
}
|
||||
now := service.clock().UTC().Truncate(time.Microsecond)
|
||||
if now.IsZero() {
|
||||
return createAttempt{}, fmt.Errorf("%s - application time must be set", createLocation)
|
||||
}
|
||||
if latestRequestAt.After(now) {
|
||||
now = latestRequestAt.UTC().Truncate(time.Microsecond)
|
||||
}
|
||||
request.now = now
|
||||
request.record = outbound.IdempotencyRecord{
|
||||
Scope: request.scope, Fingerprint: request.fingerprint,
|
||||
CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention),
|
||||
}
|
||||
version, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, request.now)
|
||||
if err != nil {
|
||||
return createAttempt{}, fmt.Errorf("%s - read effective product policy: %w", createLocation, err)
|
||||
}
|
||||
policy := version.Policy().Support
|
||||
if policy == nil {
|
||||
return createAttempt{}, fmt.Errorf("%s - current policy has no support section: %w", createLocation, ErrPolicyUnavailable)
|
||||
}
|
||||
limit, err := repositories.SupportCaseRequestLimits().Consume(
|
||||
ctx, request.command.ActorID, request.now, policy.MaxRequestsPerWindow(), policy.RequestWindow(),
|
||||
)
|
||||
if err != nil {
|
||||
return createAttempt{}, fmt.Errorf("%s - consume request budget: %w", createLocation, err)
|
||||
}
|
||||
if !limit.Allowed {
|
||||
return createAttempt{err: &RateLimitedError{RetryAfter: limit.RetryAfter}}, nil
|
||||
}
|
||||
prepared, attempt, finished, err := prepareCreateInTransaction(ctx, unit, repositories, policy, version.Version(), user, request)
|
||||
if err != nil || finished {
|
||||
return attempt, err
|
||||
}
|
||||
return createSupportCaseInTransaction(ctx, unit, repositories, attempts, user, prepared)
|
||||
}
|
||||
|
||||
type preparedSupportCase struct {
|
||||
request createRequest
|
||||
fields domain.NewSupportCaseInput
|
||||
}
|
||||
|
||||
func prepareCreateInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repositories outbound.SupportCaseRepositories,
|
||||
policy *domain.SupportPolicy,
|
||||
policyVersion int32,
|
||||
user domain.User,
|
||||
request createRequest,
|
||||
) (preparedSupportCase, createAttempt, bool, error) {
|
||||
stored, err := unit.IdempotencyRecords().Find(ctx, request.scope, request.now)
|
||||
if err == nil {
|
||||
attempt, replayErr := replayCreateOutcome(ctx, repositories, request, stored)
|
||||
return preparedSupportCase{}, attempt, true, replayErr
|
||||
}
|
||||
if !errors.Is(err, outbound.ErrIdempotencyRecordNotFound) {
|
||||
return preparedSupportCase{}, createAttempt{}, false, fmt.Errorf("%s - read idempotency record: %w", createLocation, err)
|
||||
}
|
||||
|
||||
fields := newCaseInput(request.command, user.ID, domain.SupportResponseTarget{}, request.now)
|
||||
if validationErr := domain.ValidateSupportCaseRequest(fields); validationErr != nil {
|
||||
return rejectedCreateRequest(validationErr)
|
||||
}
|
||||
responseTarget, err := policy.ResponseTarget(request.command.Type, policyVersion, request.now)
|
||||
if err != nil {
|
||||
return preparedSupportCase{}, createAttempt{}, false, fmt.Errorf("%s - fix response target: %w", createLocation, err)
|
||||
}
|
||||
fields.ResponseTarget = responseTarget
|
||||
|
||||
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
|
||||
if err != nil {
|
||||
return preparedSupportCase{}, createAttempt{}, false, fmt.Errorf("%s - reserve idempotency record: %w", createLocation, err)
|
||||
}
|
||||
if !created {
|
||||
attempt, replayErr := replayCreateOutcome(ctx, repositories, request, stored)
|
||||
return preparedSupportCase{}, attempt, true, replayErr
|
||||
}
|
||||
if err := repositories.SupportCaseCreateOutcomes().DeleteCreateOutcome(ctx, request.scope); err != nil {
|
||||
return preparedSupportCase{}, createAttempt{}, false, fmt.Errorf("%s - remove expired create outcome: %w", createLocation, err)
|
||||
}
|
||||
return preparedSupportCase{request: request, fields: fields}, createAttempt{}, false, nil
|
||||
}
|
||||
|
||||
func rejectedCreateRequest(validationErr error) (preparedSupportCase, createAttempt, bool, error) {
|
||||
return preparedSupportCase{}, createAttempt{err: validationErr}, true, nil
|
||||
}
|
||||
|
||||
func createSupportCaseInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repositories outbound.SupportCaseRepositories,
|
||||
attempts outbound.AssessmentAttemptRepository,
|
||||
user domain.User,
|
||||
prepared preparedSupportCase,
|
||||
) (createAttempt, error) {
|
||||
request, fields := prepared.request, prepared.fields
|
||||
if err := resolveReferences(ctx, unit, repositories.SupportCases(), attempts, user, fields); err != nil {
|
||||
return storeReferenceFailure(ctx, unit, repositories, request, err)
|
||||
}
|
||||
if err := resolveManualAssessmentRubric(ctx, repositories, &fields); err != nil {
|
||||
return createAttempt{}, err
|
||||
}
|
||||
|
||||
number, err := repositories.SupportCases().NextNumber(ctx, request.now)
|
||||
if err != nil {
|
||||
return createAttempt{}, fmt.Errorf("%s - allocate case number: %w", createLocation, err)
|
||||
}
|
||||
fields.Number = number
|
||||
supportCase, err := domain.NewSupportCase(fields)
|
||||
if err != nil {
|
||||
return createAttempt{}, fmt.Errorf("%s - build validated case: %w", createLocation, err)
|
||||
}
|
||||
if err := repositories.SupportCases().Create(ctx, supportCase); err != nil {
|
||||
if errors.Is(err, outbound.ErrSupportCaseConflict) {
|
||||
return storeCreateFailure(ctx, unit, repositories, request, domain.NewSupportCaseStateConflictOutcome(), ErrStateConflict)
|
||||
}
|
||||
return createAttempt{}, fmt.Errorf("%s - store case: %w", createLocation, err)
|
||||
}
|
||||
return storeCreatedCase(ctx, unit, repositories, request, supportCase)
|
||||
}
|
||||
|
||||
func resolveManualAssessmentRubric(
|
||||
ctx context.Context,
|
||||
repositories outbound.SupportCaseRepositories,
|
||||
fields *domain.NewSupportCaseInput,
|
||||
) error {
|
||||
if fields.Type != domain.SupportCaseTypeManualAssessment || fields.AssessmentTarget == nil {
|
||||
return nil
|
||||
}
|
||||
rubric, err := repositories.SupportCaseRubrics().ResolveCurrent(
|
||||
ctx, fields.AssessmentTarget.Specialization, fields.AssessmentTarget.Grade,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - resolve current manual assessment rubric: %w", createLocation, err)
|
||||
}
|
||||
if rubric == nil {
|
||||
return nil
|
||||
}
|
||||
if rubric.Version < 1 || rubric.OpeningID == uuid.Nil || rubric.PolicyVersionID.IsZero() {
|
||||
return fmt.Errorf("%s - rubric resolver returned an incomplete pin: %w", createLocation, domain.ErrInvalidSupportCase)
|
||||
}
|
||||
fields.RubricVersion = &rubric.Version
|
||||
fields.RubricOpeningID = &rubric.OpeningID
|
||||
fields.RubricPolicyID = &rubric.PolicyVersionID
|
||||
return nil
|
||||
}
|
||||
|
||||
func storeReferenceFailure(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repositories outbound.SupportCaseRepositories,
|
||||
request createRequest,
|
||||
resolveErr error,
|
||||
) (createAttempt, error) {
|
||||
switch {
|
||||
case errors.Is(resolveErr, ErrStateConflict):
|
||||
return storeCreateFailure(ctx, unit, repositories, request, domain.NewSupportCaseStateConflictOutcome(), ErrStateConflict)
|
||||
case errors.Is(resolveErr, outbound.ErrSupportCaseNotFound):
|
||||
return storeCreateFailure(ctx, unit, repositories, request, domain.NewSupportCaseNotFoundOutcome(), outbound.ErrSupportCaseNotFound)
|
||||
default:
|
||||
return createAttempt{}, resolveErr
|
||||
}
|
||||
}
|
||||
|
||||
func storeCreatedCase(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repositories outbound.SupportCaseRepositories,
|
||||
request createRequest,
|
||||
supportCase domain.SupportCase,
|
||||
) (createAttempt, error) {
|
||||
outcome, err := domain.NewSupportCaseCreatedOutcome(supportCase)
|
||||
if err != nil {
|
||||
return createAttempt{}, fmt.Errorf("%s - build create outcome: %w", createLocation, err)
|
||||
}
|
||||
if err := repositories.SupportCaseCreateOutcomes().SaveCreateOutcome(ctx, request.scope, outcome, request.now); err != nil {
|
||||
return createAttempt{}, fmt.Errorf("%s - store create outcome: %w", createLocation, err)
|
||||
}
|
||||
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
|
||||
return createAttempt{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err)
|
||||
}
|
||||
result := CreateResult{Case: supportCase, TargetLate: supportCase.ResponseTarget().IsLate(request.now)}
|
||||
return createAttempt{result: result}, nil
|
||||
}
|
||||
|
||||
func storeCreateFailure(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repositories outbound.SupportCaseRepositories,
|
||||
request createRequest,
|
||||
outcome domain.SupportCaseCreateOutcome,
|
||||
responseErr error,
|
||||
) (createAttempt, error) {
|
||||
if err := repositories.SupportCaseCreateOutcomes().SaveCreateOutcome(ctx, request.scope, outcome, request.now); err != nil {
|
||||
return createAttempt{}, fmt.Errorf("%s - store failure outcome: %w", createLocation, err)
|
||||
}
|
||||
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
|
||||
return createAttempt{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err)
|
||||
}
|
||||
return createAttempt{err: responseErr}, nil
|
||||
}
|
||||
|
||||
func replayCreateOutcome(
|
||||
ctx context.Context,
|
||||
repositories outbound.SupportCaseRepositories,
|
||||
request createRequest,
|
||||
stored outbound.IdempotencyRecord,
|
||||
) (createAttempt, error) {
|
||||
if stored.Fingerprint != request.fingerprint {
|
||||
return createAttempt{err: ErrIdempotencyKeyReused}, nil
|
||||
}
|
||||
outcome, err := repositories.SupportCaseCreateOutcomes().GetCreateOutcome(ctx, request.scope)
|
||||
if err != nil {
|
||||
return createAttempt{}, fmt.Errorf("%s - read immutable create outcome: %w", createLocation, err)
|
||||
}
|
||||
switch outcome.Kind() {
|
||||
case domain.SupportCaseCreateOutcomeCreated:
|
||||
supportCase, ok := outcome.Case()
|
||||
if !ok {
|
||||
return createAttempt{}, fmt.Errorf("%s - restore immutable create outcome: %w", createLocation, domain.ErrInvalidSupportCase)
|
||||
}
|
||||
late, ok := outcome.CreationTargetWasLate()
|
||||
if !ok {
|
||||
return createAttempt{}, fmt.Errorf("%s - read original response target state: %w", createLocation, domain.ErrInvalidSupportCase)
|
||||
}
|
||||
return createAttempt{result: CreateResult{Case: supportCase, Replayed: true, TargetLate: late}}, nil
|
||||
case domain.SupportCaseCreateOutcomeNotFound:
|
||||
return createAttempt{err: outbound.ErrSupportCaseNotFound}, nil
|
||||
case domain.SupportCaseCreateOutcomeStateConflict:
|
||||
return createAttempt{err: ErrStateConflict}, nil
|
||||
default:
|
||||
return createAttempt{}, fmt.Errorf("%s - stored outcome kind is invalid: %w", createLocation, domain.ErrInvalidSupportCase)
|
||||
}
|
||||
}
|
||||
|
||||
func newCaseInput(
|
||||
command CreateCommand,
|
||||
ownerID uuid.UUID,
|
||||
responseTarget domain.SupportResponseTarget,
|
||||
createdAt time.Time,
|
||||
) domain.NewSupportCaseInput {
|
||||
return domain.NewSupportCaseInput{
|
||||
OwnerID: ownerID, Type: command.Type, Description: command.Description,
|
||||
Object: command.Object, AssessmentTarget: command.AssessmentTarget,
|
||||
ComplaintReason: command.ComplaintReason, ResponseTarget: responseTarget,
|
||||
CreatedAt: createdAt,
|
||||
}
|
||||
}
|
||||
|
||||
func resolveReferences(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
cases outbound.SupportCaseRepository,
|
||||
attempts outbound.AssessmentAttemptRepository,
|
||||
user domain.User,
|
||||
input domain.NewSupportCaseInput,
|
||||
) error {
|
||||
object := input.Object
|
||||
if object == nil {
|
||||
return nil
|
||||
}
|
||||
switch object.Type {
|
||||
case domain.SupportCaseObjectInvitation:
|
||||
return outbound.ErrSupportCaseNotFound
|
||||
case domain.SupportCaseObjectOrganization:
|
||||
return resolveOrganizationReference(ctx, unit, user, object.ID)
|
||||
case domain.SupportCaseObjectAssessmentAttempt:
|
||||
return resolveAttemptReference(ctx, attempts, user, object.ID, input)
|
||||
case domain.SupportCaseObjectSupportCase:
|
||||
return resolveSupportCaseReference(ctx, cases, user, object.ID, input.Type)
|
||||
default:
|
||||
return outbound.ErrSupportCaseNotFound
|
||||
}
|
||||
}
|
||||
|
||||
func resolveOrganizationReference(ctx context.Context, unit outbound.UnitOfWork, user domain.User, id uuid.UUID) error {
|
||||
if user.Scenario != domain.ScenarioEmployer {
|
||||
return outbound.ErrSupportCaseNotFound
|
||||
}
|
||||
if _, _, err := unit.Organizations().GetForMember(ctx, id, user.ID); err != nil {
|
||||
if errors.Is(err, outbound.ErrOrganizationNotFound) {
|
||||
return outbound.ErrSupportCaseNotFound
|
||||
}
|
||||
return fmt.Errorf("%s - resolve organization reference: %w", createLocation, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func resolveAttemptReference(
|
||||
ctx context.Context,
|
||||
attempts outbound.AssessmentAttemptRepository,
|
||||
user domain.User,
|
||||
id uuid.UUID,
|
||||
input domain.NewSupportCaseInput,
|
||||
) error {
|
||||
attempt, err := attempts.GetForCandidate(ctx, user.ID, domain.AssessmentAttemptID(id))
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
||||
return outbound.ErrSupportCaseNotFound
|
||||
}
|
||||
return fmt.Errorf("%s - resolve assessment attempt reference: %w", createLocation, err)
|
||||
}
|
||||
return validateAttemptReference(input, attempt)
|
||||
}
|
||||
|
||||
func resolveSupportCaseReference(
|
||||
ctx context.Context,
|
||||
cases outbound.SupportCaseRepository,
|
||||
user domain.User,
|
||||
id uuid.UUID,
|
||||
caseType domain.SupportCaseType,
|
||||
) error {
|
||||
referenced, err := cases.GetOwned(ctx, user.ID, domain.SupportCaseID(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if caseType != domain.SupportCaseTypeGradeAppeal {
|
||||
return nil
|
||||
}
|
||||
decision := referenced.Decision()
|
||||
if referenced.Type() != domain.SupportCaseTypeManualAssessment ||
|
||||
referenced.Status() != domain.SupportCaseStatusResolved || decision == nil || decision.Outcome() != domain.SupportCaseDecisionAssessed {
|
||||
return ErrStateConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAttemptReference(input domain.NewSupportCaseInput, attempt domain.AssessmentAttempt) error {
|
||||
switch input.Type {
|
||||
case domain.SupportCaseTypeSupport, domain.SupportCaseTypeComplaint:
|
||||
return nil
|
||||
case domain.SupportCaseTypeManualAssessment:
|
||||
target := input.AssessmentTarget
|
||||
attemptSnapshot := attempt.Snapshot()
|
||||
if target == nil || attemptSnapshot.Specialization == nil || *attemptSnapshot.Specialization != target.Specialization {
|
||||
return ErrStateConflict
|
||||
}
|
||||
case domain.SupportCaseTypeGradeAppeal:
|
||||
if attempt.State() != domain.AssessmentAttemptStateCompleted {
|
||||
return ErrStateConflict
|
||||
}
|
||||
case domain.SupportCaseTypeAnticheatAppeal:
|
||||
// Anti-cheat review decisions are not implemented. An owned attempt
|
||||
// therefore has no appealable decision yet.
|
||||
return ErrStateConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func supportCaseRepositories(
|
||||
unit outbound.UnitOfWork,
|
||||
) (outbound.SupportCaseRepositories, outbound.AssessmentAttemptRepository, error) {
|
||||
repositories, ok := unit.(outbound.SupportCaseRepositories)
|
||||
if !ok {
|
||||
return nil, nil, errors.New("supportcase.Service - unit of work does not expose support case repositories")
|
||||
}
|
||||
attempts, ok := unit.(outbound.AssessmentAttemptRepositories)
|
||||
if !ok {
|
||||
return nil, nil, errors.New("supportcase.Service - unit of work does not expose assessment attempts")
|
||||
}
|
||||
return repositories, attempts.AssessmentAttempts(), nil
|
||||
}
|
||||
|
||||
func requireAccount(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID, location string) (domain.User, error) {
|
||||
user, err := unit.Users().GetByID(ctx, actorID)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return domain.User{}, ErrForbidden
|
||||
}
|
||||
return domain.User{}, fmt.Errorf("%s - read account: %w", location, err)
|
||||
}
|
||||
if !user.EmailVerified() {
|
||||
return domain.User{}, ErrEmailNotVerified
|
||||
}
|
||||
if user.Scenario != domain.ScenarioCandidate && user.Scenario != domain.ScenarioEmployer {
|
||||
return domain.User{}, ErrForbidden
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func validIdempotencyKey(value string) bool {
|
||||
if len(value) == 0 || len(value) > maxIdempotencyKeySize {
|
||||
return false
|
||||
}
|
||||
for index := range len(value) {
|
||||
character := value[index]
|
||||
if character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' ||
|
||||
character >= '0' && character <= '9' || character == '.' || character == '_' ||
|
||||
character == ':' || character == '-' {
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func canonicalCreateBody(command CreateCommand) ([]byte, error) {
|
||||
var object any
|
||||
if command.Object != nil {
|
||||
object = []any{string(command.Object.Type), command.Object.ID.String()}
|
||||
}
|
||||
var target any
|
||||
if command.AssessmentTarget != nil {
|
||||
target = []any{string(command.AssessmentTarget.Specialization), string(command.AssessmentTarget.Grade)}
|
||||
}
|
||||
var reason any
|
||||
if command.ComplaintReason != nil {
|
||||
reason = string(*command.ComplaintReason)
|
||||
}
|
||||
return json.Marshal([]any{string(command.Type), command.Description, object, target, reason})
|
||||
}
|
||||
|
||||
// RateLimitedError carries the server-computed Retry-After interval.
|
||||
type RateLimitedError struct {
|
||||
RetryAfter time.Duration
|
||||
}
|
||||
|
||||
func (RateLimitedError) Error() string { return ErrRateLimited.Error() }
|
||||
func (RateLimitedError) Unwrap() error { return ErrRateLimited }
|
||||
|
||||
// GetMyCase returns one full case only to its account owner.
|
||||
func (service *Service) GetMyCase(ctx context.Context, actorID uuid.UUID, caseID domain.SupportCaseID) (domain.SupportCase, error) {
|
||||
const location = "supportcase.Service.GetMyCase"
|
||||
if actorID == uuid.Nil || caseID.IsZero() {
|
||||
return domain.SupportCase{}, fmt.Errorf("%s - identifiers must be set: %w", location, ErrForbidden)
|
||||
}
|
||||
var result domain.SupportCase
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if _, err := requireAccount(ctx, unit, actorID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
repositories, _, err := supportCaseRepositories(unit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err = repositories.SupportCases().GetOwned(ctx, actorID, caseID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read owned case: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.SupportCase{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ListCommand selects one owner-scoped page.
|
||||
type ListCommand struct {
|
||||
ActorID uuid.UUID
|
||||
After *outbound.SupportCaseListPosition
|
||||
Limit int32
|
||||
}
|
||||
|
||||
// ListMyCases returns summaries and never loads descriptions or history.
|
||||
func (service *Service) ListMyCases(ctx context.Context, command ListCommand) (outbound.SupportCaseListPage, error) {
|
||||
const location = "supportcase.Service.ListMyCases"
|
||||
if command.ActorID == uuid.Nil || command.Limit < 1 || command.Limit > outbound.MaxSupportCasePageSize ||
|
||||
command.After != nil && (command.After.ID.IsZero() || command.After.CreatedAt.IsZero()) {
|
||||
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - query is invalid: %w", location, domain.ErrInvalidSupportCase)
|
||||
}
|
||||
var result outbound.SupportCaseListPage
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if _, err := requireAccount(ctx, unit, command.ActorID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
repositories, _, err := supportCaseRepositories(unit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err = repositories.SupportCases().ListOwned(ctx, outbound.SupportCaseListQuery{
|
||||
OwnerID: command.ActorID, After: command.After, Limit: command.Limit,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - list owned cases: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
Reference in new issue
Block a user