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,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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user