feat: persist candidate questionnaires and enforce company quotas
This commit is contained in:
1 parent
73c7caa225
commit
3a61a8e8bb
51 files changed
+6280
-38
No files matched your search
@@ -333,6 +333,10 @@ type OpenCategoryInput struct {
|
||||
// is not the one in force are refused.
|
||||
GradingPolicyID domain.PolicyVersionID
|
||||
OpenedBy domain.AssessmentOperator
|
||||
// CatalogMetadata is the explicit public mapping reviewed for this exact
|
||||
// published bank opening. An opening without it is not exposed in the
|
||||
// public specialization catalog.
|
||||
CatalogMetadata *domain.AssessmentCategoryCatalogMetadata
|
||||
}
|
||||
|
||||
// OpenCategory makes a category available. It reads the referenced policy
|
||||
@@ -370,6 +374,14 @@ func (bank *Bank) OpenCategory(ctx context.Context, input OpenCategoryInput) (do
|
||||
if err != nil {
|
||||
return storageRefusal(fmt.Errorf("store opening: %w", err), domain.RefusalNotDraft)
|
||||
}
|
||||
if input.CatalogMetadata != nil {
|
||||
if input.CatalogMetadata.IsZero() {
|
||||
return fmt.Errorf("bind public catalog metadata: %w", domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
if err := repository.BindCategoryCatalog(ctx, opening, *input.CatalogMetadata); err != nil {
|
||||
return fmt.Errorf("bind public catalog metadata: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
@@ -378,6 +390,24 @@ func (bank *Bank) OpenCategory(ctx context.Context, input OpenCategoryInput) (do
|
||||
return opening, nil
|
||||
}
|
||||
|
||||
// SpecializationAvailability returns only catalog mappings whose opening,
|
||||
// current policy, live coverage, and published-family manifest still match.
|
||||
func (bank *Bank) SpecializationAvailability(ctx context.Context) ([]domain.SpecializationAvailability, error) {
|
||||
var availability []domain.SpecializationAvailability
|
||||
err := bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
availability, err = unit.AssessmentBank().ListCurrentSpecializationAvailability(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read current bank availability: %w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Bank.SpecializationAvailability - read catalog: %w", err)
|
||||
}
|
||||
return availability, nil
|
||||
}
|
||||
|
||||
// readGradingPolicy reads the referenced policy version and requires it to
|
||||
// be the version of the product policy in force now.
|
||||
func readGradingPolicy(ctx context.Context, unit outbound.UnitOfWork, id domain.PolicyVersionID) (domain.PolicyVersion, error) {
|
||||
|
||||
@@ -104,6 +104,16 @@ func (bank *fakeBank) CreateCategoryOpening(context.Context, domain.AssessmentCa
|
||||
return domain.AssessmentCategoryOpening{}, bank.openErr
|
||||
}
|
||||
|
||||
func (bank *fakeBank) BindCategoryCatalog(context.Context, domain.AssessmentCategoryOpening, domain.AssessmentCategoryCatalogMetadata) error {
|
||||
bank.calls = append(bank.calls, "bind_catalog")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (bank *fakeBank) ListCurrentSpecializationAvailability(context.Context) ([]domain.SpecializationAvailability, error) {
|
||||
bank.calls = append(bank.calls, "availability")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (bank *fakeBank) GetCurrentCategoryOpening(context.Context, domain.AssessmentCategory) (domain.AssessmentCategoryOpening, error) {
|
||||
if bank.opening == nil {
|
||||
return domain.AssessmentCategoryOpening{}, outbound.ErrAssessmentCategoryNotOpen
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
// Package companyquota resolves current organization limits and reserves
|
||||
// invitation or candidate-card usage in the caller's transaction.
|
||||
package companyquota
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrQuotaRepositoriesMissing = errors.New("company quota repositories are missing")
|
||||
ErrQuotaServiceUnavailable = errors.New("company quota service is unavailable")
|
||||
)
|
||||
|
||||
// Repositories is the transaction-scoped surface needed for one quota
|
||||
// operation. The service does not retain it, because the repositories are
|
||||
// bound to the caller's transaction.
|
||||
type Repositories interface {
|
||||
Policies() outbound.PolicyRepository
|
||||
CompanyQuotas() outbound.CompanyQuotaRepository
|
||||
}
|
||||
|
||||
// Service reads the current policy and delegates the atomic reservation. It
|
||||
// stores only the application clock and is safe to reuse between calls.
|
||||
type Service struct {
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
// NewService takes the application clock used once per operation. A nil
|
||||
// clock is a wiring error and panics at construction.
|
||||
func NewService(clock func() time.Time) *Service {
|
||||
if clock == nil {
|
||||
panic("companyquota.NewService - clock must not be nil")
|
||||
}
|
||||
return &Service{clock: clock}
|
||||
}
|
||||
|
||||
// ReserveInvitation atomically records a new invitation against the policy
|
||||
// effective at the operation's clock snapshot. Repeating invitationID is
|
||||
// idempotent even when the caller uses a different request key.
|
||||
func (service *Service) ReserveInvitation(
|
||||
ctx context.Context,
|
||||
repositories Repositories,
|
||||
organization domain.Organization,
|
||||
invitationID uuid.UUID,
|
||||
) (outbound.CompanyQuotaDecision, error) {
|
||||
const location = "Service.ReserveInvitation"
|
||||
if invitationID == uuid.Nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation ID must be set: %w", location, domain.ErrInvalidCompanyQuota)
|
||||
}
|
||||
quota, repository, err := service.resolve(ctx, repositories, organization, location)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
decision, err := repository.ReserveInvitation(ctx, quota, invitationID)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - reserve invitation usage: %w", location, err)
|
||||
}
|
||||
if !decision.RetryAt.IsZero() {
|
||||
decision.RetryAt = decision.RetryAt.UTC()
|
||||
}
|
||||
if err := validateDecision(quota, decision); err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - validate reservation result: %w", location, err)
|
||||
}
|
||||
return decision, nil
|
||||
}
|
||||
|
||||
// ReserveCardView atomically counts a distinct candidate in the organization's
|
||||
// rolling view window. A repeat within the window refreshes the stored time
|
||||
// without charging another distinct view.
|
||||
func (service *Service) ReserveCardView(
|
||||
ctx context.Context,
|
||||
repositories Repositories,
|
||||
organization domain.Organization,
|
||||
candidateID uuid.UUID,
|
||||
) (outbound.CompanyQuotaDecision, error) {
|
||||
const location = "Service.ReserveCardView"
|
||||
if candidateID == uuid.Nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCompanyQuota)
|
||||
}
|
||||
quota, repository, err := service.resolve(ctx, repositories, organization, location)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, err
|
||||
}
|
||||
decision, err := repository.ReserveCardView(ctx, quota, candidateID)
|
||||
if err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - reserve card-view usage: %w", location, err)
|
||||
}
|
||||
if !decision.RetryAt.IsZero() {
|
||||
decision.RetryAt = decision.RetryAt.UTC()
|
||||
}
|
||||
if err := validateDecision(quota, decision); err != nil {
|
||||
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - validate reservation result: %w", location, err)
|
||||
}
|
||||
return decision, nil
|
||||
}
|
||||
|
||||
func (service *Service) resolve(
|
||||
ctx context.Context,
|
||||
repositories Repositories,
|
||||
organization domain.Organization,
|
||||
location string,
|
||||
) (domain.CompanyQuota, outbound.CompanyQuotaRepository, error) {
|
||||
if service == nil || service.clock == nil {
|
||||
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - service clock is missing: %w", location, ErrQuotaServiceUnavailable)
|
||||
}
|
||||
if repositories == nil {
|
||||
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - transaction repositories are missing: %w", location, ErrQuotaRepositoriesMissing)
|
||||
}
|
||||
policies := repositories.Policies()
|
||||
quotaRepository := repositories.CompanyQuotas()
|
||||
if policies == nil || quotaRepository == nil {
|
||||
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - transaction repository is missing: %w", location, ErrQuotaRepositoriesMissing)
|
||||
}
|
||||
now := service.clock().UTC()
|
||||
if now.IsZero() || now.Unix() < 0 {
|
||||
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - application clock must be set and non-negative: %w", location, domain.ErrInvalidCompanyQuota)
|
||||
}
|
||||
version, err := policies.GetEffective(ctx, domain.ProductPolicyKey, now)
|
||||
if err != nil {
|
||||
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - read effective product policy: %w", location, err)
|
||||
}
|
||||
quota, err := domain.NewCompanyQuota(organization, version, now)
|
||||
if err != nil {
|
||||
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - resolve organization quota: %w", location, err)
|
||||
}
|
||||
return quota, quotaRepository, nil
|
||||
}
|
||||
|
||||
func validateDecision(quota domain.CompanyQuota, decision outbound.CompanyQuotaDecision) error {
|
||||
switch {
|
||||
case decision.Allowed && !decision.RetryAt.IsZero():
|
||||
return errors.New("an allowed reservation cannot have a retry time")
|
||||
case decision.Reused && !decision.Allowed:
|
||||
return errors.New("a reused reservation must be allowed")
|
||||
case !decision.Allowed && (decision.Reused || decision.RetryAt.IsZero() || !decision.RetryAt.After(quota.At())):
|
||||
return errors.New("a denied reservation must be new and have a future retry time")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package companyquota
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type quotaTestPolicies struct {
|
||||
outbound.PolicyRepository
|
||||
|
||||
version domain.PolicyVersion
|
||||
err error
|
||||
calls int
|
||||
key domain.PolicyKey
|
||||
at time.Time
|
||||
}
|
||||
|
||||
func (policies *quotaTestPolicies) GetEffective(_ context.Context, key domain.PolicyKey, at time.Time) (domain.PolicyVersion, error) {
|
||||
policies.calls++
|
||||
policies.key = key
|
||||
policies.at = at
|
||||
return policies.version, policies.err
|
||||
}
|
||||
|
||||
type quotaTestRepository struct {
|
||||
decision outbound.CompanyQuotaDecision
|
||||
err error
|
||||
invitationCalls int
|
||||
cardViewCalls int
|
||||
invitationID uuid.UUID
|
||||
candidateID uuid.UUID
|
||||
invitationQuota domain.CompanyQuota
|
||||
cardViewQuota domain.CompanyQuota
|
||||
}
|
||||
|
||||
func (repository *quotaTestRepository) ReserveInvitation(_ context.Context, quota domain.CompanyQuota, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
repository.invitationCalls++
|
||||
repository.invitationQuota = quota
|
||||
repository.invitationID = invitationID
|
||||
return repository.decision, repository.err
|
||||
}
|
||||
|
||||
func (repository *quotaTestRepository) ReserveCardView(_ context.Context, quota domain.CompanyQuota, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
repository.cardViewCalls++
|
||||
repository.cardViewQuota = quota
|
||||
repository.candidateID = candidateID
|
||||
return repository.decision, repository.err
|
||||
}
|
||||
|
||||
type quotaTestRepositories struct {
|
||||
policies *quotaTestPolicies
|
||||
quotas *quotaTestRepository
|
||||
}
|
||||
|
||||
func (repositories *quotaTestRepositories) Policies() outbound.PolicyRepository {
|
||||
return repositories.policies
|
||||
}
|
||||
|
||||
func (repositories *quotaTestRepositories) CompanyQuotas() outbound.CompanyQuotaRepository {
|
||||
return repositories.quotas
|
||||
}
|
||||
|
||||
func TestReserveInvitationReadsOneEffectivePolicySnapshotAndDelegates(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.FixedZone("owner", 3*60*60))
|
||||
policy := quotaTestPolicyVersion(t, at.UTC().Add(-time.Hour))
|
||||
organization := quotaTestOrganization(t, domain.OrganizationVerificationE0, domain.OrganizationBasisConfirmedEmail, at.Add(-24*time.Hour), at.Add(-24*time.Hour))
|
||||
decision := outbound.CompanyQuotaDecision{Allowed: true}
|
||||
repositories := "aTestRepositories{
|
||||
policies: "aTestPolicies{version: policy},
|
||||
quotas: "aTestRepository{decision: decision},
|
||||
}
|
||||
clockCalls := 0
|
||||
service := NewService(func() time.Time {
|
||||
clockCalls++
|
||||
return at
|
||||
})
|
||||
invitationID := uuid.New()
|
||||
|
||||
got, err := service.ReserveInvitation(context.Background(), repositories, organization, invitationID)
|
||||
if err != nil {
|
||||
t.Fatalf("ReserveInvitation() error = %v", err)
|
||||
}
|
||||
if got != decision || clockCalls != 1 || repositories.policies.calls != 1 ||
|
||||
repositories.policies.key != domain.ProductPolicyKey || !repositories.policies.at.Equal(at.UTC()) ||
|
||||
repositories.policies.at.Location() != time.UTC {
|
||||
t.Fatalf("decision=%+v clockCalls=%d policyReads=%d key=%s at=%s", got, clockCalls, repositories.policies.calls, repositories.policies.key, repositories.policies.at)
|
||||
}
|
||||
if repositories.quotas.invitationCalls != 1 || repositories.quotas.cardViewCalls != 0 || repositories.quotas.invitationID != invitationID {
|
||||
t.Fatalf("quota calls: invitations=%d views=%d invitationID=%s", repositories.quotas.invitationCalls, repositories.quotas.cardViewCalls, repositories.quotas.invitationID)
|
||||
}
|
||||
quota := repositories.quotas.invitationQuota
|
||||
if quota.OrganizationID() != organization.ID() || quota.PolicyVersionID() != policy.ID() || quota.Tier() != domain.OrganizationTierE0 ||
|
||||
quota.InvitationLimit() != 10 || quota.CardViewLimit() != 50 || !quota.At().Equal(at.UTC()) {
|
||||
t.Fatalf("reservation snapshot = org %s policy %s tier %s limits %d/%d at %s", quota.OrganizationID(), quota.PolicyVersionID(), quota.Tier(), quota.InvitationLimit(), quota.CardViewLimit(), quota.At())
|
||||
}
|
||||
}
|
||||
|
||||
func TestReserveCardViewReturnsAtomicReuseOrDenialDecision(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
|
||||
policy := quotaTestPolicyVersion(t, at.Add(-time.Hour))
|
||||
organization := quotaTestOrganization(t, domain.OrganizationVerificationE1, domain.OrganizationBasisCorporateDomain, at.Add(-24*time.Hour), at.Add(-time.Hour))
|
||||
candidateID := uuid.New()
|
||||
ownerZone := time.FixedZone("owner", 3*60*60)
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
decision outbound.CompanyQuotaDecision
|
||||
}{
|
||||
{name: "repeat is allowed without another charge", decision: outbound.CompanyQuotaDecision{Allowed: true, Reused: true}},
|
||||
{name: "denied includes the earliest expiry", decision: outbound.CompanyQuotaDecision{RetryAt: at.Add(time.Hour).In(ownerZone)}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
repositories := "aTestRepositories{
|
||||
policies: "aTestPolicies{version: policy},
|
||||
quotas: "aTestRepository{decision: test.decision},
|
||||
}
|
||||
service := NewService(func() time.Time { return at })
|
||||
got, err := service.ReserveCardView(context.Background(), repositories, organization, candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ReserveCardView() error = %v", err)
|
||||
}
|
||||
if got.Allowed != test.decision.Allowed || got.Reused != test.decision.Reused ||
|
||||
!got.RetryAt.Equal(test.decision.RetryAt) || repositories.quotas.cardViewCalls != 1 || repositories.quotas.invitationCalls != 0 ||
|
||||
repositories.quotas.candidateID != candidateID {
|
||||
t.Fatalf("decision=%+v calls=%d/%d candidateID=%s", got, repositories.quotas.cardViewCalls, repositories.quotas.invitationCalls, repositories.quotas.candidateID)
|
||||
}
|
||||
if !got.RetryAt.IsZero() && got.RetryAt.Location() != time.UTC {
|
||||
t.Fatalf("RetryAt() location = %s, want UTC", got.RetryAt.Location())
|
||||
}
|
||||
quota := repositories.quotas.cardViewQuota
|
||||
if quota.Tier() != domain.OrganizationTierE1 || quota.CardViewLimit() != 150 || quota.InvitationLimit() != 40 {
|
||||
t.Fatalf("E1 quota = tier %s limits %d/%d", quota.Tier(), quota.InvitationLimit(), quota.CardViewLimit())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaServiceFailsClosedBeforeReservation(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
|
||||
policy := quotaTestPolicyVersion(t, at.Add(-time.Hour))
|
||||
organization := quotaTestOrganization(t, domain.OrganizationVerificationE0, domain.OrganizationBasisConfirmedEmail, at.Add(-24*time.Hour), at.Add(-24*time.Hour))
|
||||
policyFailure := errors.New("policy store unavailable")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
organization domain.Organization
|
||||
policyError error
|
||||
clock time.Time
|
||||
want error
|
||||
}{
|
||||
{name: "policy unavailable", organization: organization, policyError: policyFailure, clock: at, want: policyFailure},
|
||||
{name: "clock is zero", organization: organization, clock: time.Time{}, want: domain.ErrInvalidCompanyQuota},
|
||||
{name: "clock predates organization trust", organization: organization, clock: at.Add(-48 * time.Hour), want: domain.ErrInvalidCompanyQuota},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
repositories := "aTestRepositories{
|
||||
policies: "aTestPolicies{version: policy, err: test.policyError},
|
||||
quotas: "aTestRepository{decision: outbound.CompanyQuotaDecision{Allowed: true}},
|
||||
}
|
||||
service := NewService(func() time.Time { return test.clock })
|
||||
_, err := service.ReserveInvitation(context.Background(), repositories, test.organization, uuid.New())
|
||||
if !errors.Is(err, test.want) {
|
||||
t.Fatalf("ReserveInvitation() error = %v, want %v", err, test.want)
|
||||
}
|
||||
if repositories.quotas.invitationCalls != 0 || repositories.quotas.cardViewCalls != 0 {
|
||||
t.Fatalf("quota repository was called: invitation=%d view=%d", repositories.quotas.invitationCalls, repositories.quotas.cardViewCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaServiceDeniesE3AndInactiveE2WithoutFallback(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
|
||||
policy := quotaTestPolicyVersion(t, at.Add(-time.Hour))
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
level domain.OrganizationVerificationLevel
|
||||
basis domain.OrganizationVerificationBasis
|
||||
}{
|
||||
{name: "E3", level: domain.OrganizationVerificationE3, basis: domain.OrganizationBasisManualReview},
|
||||
{name: "E2 inactive in policy", level: domain.OrganizationVerificationE2, basis: domain.OrganizationBasisRequisitesAndAuthority},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
organization := quotaTestOrganization(t, test.level, test.basis, at.Add(-24*time.Hour), at.Add(-time.Hour))
|
||||
repositories := "aTestRepositories{
|
||||
policies: "aTestPolicies{version: policy},
|
||||
quotas: "aTestRepository{decision: outbound.CompanyQuotaDecision{Allowed: true}},
|
||||
}
|
||||
service := NewService(func() time.Time { return at })
|
||||
_, err := service.ReserveCardView(context.Background(), repositories, organization, uuid.New())
|
||||
if !errors.Is(err, domain.ErrCompanyQuotaDenied) {
|
||||
t.Fatalf("ReserveCardView() error = %v, want ErrCompanyQuotaDenied", err)
|
||||
}
|
||||
if repositories.quotas.cardViewCalls != 0 {
|
||||
t.Fatalf("quota repository calls = %d, want 0", repositories.quotas.cardViewCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaServiceRejectsInconsistentRepositoryDecisions(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
|
||||
policy := quotaTestPolicyVersion(t, at.Add(-time.Hour))
|
||||
organization := quotaTestOrganization(t, domain.OrganizationVerificationE0, domain.OrganizationBasisConfirmedEmail, at.Add(-24*time.Hour), at.Add(-24*time.Hour))
|
||||
|
||||
for _, decision := range []outbound.CompanyQuotaDecision{
|
||||
{Allowed: true, RetryAt: at.Add(time.Hour)},
|
||||
{Reused: true},
|
||||
{RetryAt: at},
|
||||
} {
|
||||
repositories := "aTestRepositories{
|
||||
policies: "aTestPolicies{version: policy},
|
||||
quotas: "aTestRepository{decision: decision},
|
||||
}
|
||||
service := NewService(func() time.Time { return at })
|
||||
if _, err := service.ReserveInvitation(context.Background(), repositories, organization, uuid.New()); err == nil {
|
||||
t.Fatalf("ReserveInvitation(decision=%+v) succeeded, want invalid result", decision)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaServiceRejectsMissingIDsBeforeReadingPolicy(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
|
||||
policy := quotaTestPolicyVersion(t, at.Add(-time.Hour))
|
||||
organization := quotaTestOrganization(t, domain.OrganizationVerificationE0, domain.OrganizationBasisConfirmedEmail, at.Add(-24*time.Hour), at.Add(-24*time.Hour))
|
||||
repositories := "aTestRepositories{policies: "aTestPolicies{version: policy}, quotas: "aTestRepository{}}
|
||||
service := NewService(func() time.Time { return at })
|
||||
|
||||
if _, err := service.ReserveInvitation(context.Background(), repositories, organization, uuid.Nil); !errors.Is(err, domain.ErrInvalidCompanyQuota) {
|
||||
t.Fatalf("ReserveInvitation(zero ID) error = %v, want ErrInvalidCompanyQuota", err)
|
||||
}
|
||||
if _, err := service.ReserveCardView(context.Background(), repositories, organization, uuid.Nil); !errors.Is(err, domain.ErrInvalidCompanyQuota) {
|
||||
t.Fatalf("ReserveCardView(zero ID) error = %v, want ErrInvalidCompanyQuota", err)
|
||||
}
|
||||
if repositories.policies.calls != 0 || repositories.quotas.invitationCalls != 0 || repositories.quotas.cardViewCalls != 0 {
|
||||
t.Fatalf("repositories called for invalid IDs: policies=%d invitation=%d view=%d", repositories.policies.calls, repositories.quotas.invitationCalls, repositories.quotas.cardViewCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func quotaTestOrganization(
|
||||
t *testing.T,
|
||||
level domain.OrganizationVerificationLevel,
|
||||
basis domain.OrganizationVerificationBasis,
|
||||
createdAt, changedAt time.Time,
|
||||
) domain.Organization {
|
||||
t.Helper()
|
||||
updatedAt := createdAt
|
||||
if changedAt.After(updatedAt) {
|
||||
updatedAt = changedAt
|
||||
}
|
||||
organization, err := domain.RestoreOrganization(domain.StoredOrganization{
|
||||
ID: uuid.New(), Name: "Example Company", VerificationLevel: string(level), VerificationBasis: string(basis),
|
||||
VerificationChangedAt: changedAt, Version: 1, CreatedAt: createdAt, UpdatedAt: updatedAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreOrganization() error = %v", err)
|
||||
}
|
||||
return organization
|
||||
}
|
||||
|
||||
func quotaTestPolicyVersion(t *testing.T, effectiveAt time.Time) domain.PolicyVersion {
|
||||
t.Helper()
|
||||
policy := domain.DemoProductPolicyV1()
|
||||
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: policy,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
|
||||
}
|
||||
numbered, err := draft.WithVersion(1)
|
||||
if err != nil {
|
||||
t.Fatalf("WithVersion() error = %v", err)
|
||||
}
|
||||
hash := numbered.DocumentHash()
|
||||
version, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{
|
||||
ID: numbered.ID(), Key: string(numbered.Key()), Version: numbered.Version(), Kind: string(numbered.Kind()),
|
||||
Author: string(numbered.Author()), EffectiveAt: effectiveAt, CreatedAt: effectiveAt,
|
||||
Document: numbered.Document(), DocumentHash: hash[:],
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestorePolicyVersion() error = %v", err)
|
||||
}
|
||||
return version
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// Package questionnaire reads and version-saves a candidate's private questionnaire.
|
||||
package questionnaire
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrForbidden = errors.New("candidate questionnaire operation forbidden")
|
||||
ErrEmailNotVerified = errors.New("candidate questionnaire requires a confirmed email")
|
||||
)
|
||||
|
||||
// Service keeps questionnaire answers and onboarding movement in one
|
||||
// transaction.
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
func NewService(transactor outbound.Transactor, clock func() time.Time) *Service {
|
||||
if transactor == nil {
|
||||
panic("questionnaire.NewService - transactor must not be nil")
|
||||
}
|
||||
if clock == nil {
|
||||
panic("questionnaire.NewService - clock must not be nil")
|
||||
}
|
||||
return &Service{transactor: transactor, clock: clock}
|
||||
}
|
||||
|
||||
// GetMyQuestionnaire reads only the questionnaire owned by the verified
|
||||
// candidate userID. Version zero means no questionnaire has been saved.
|
||||
func (service *Service) GetMyQuestionnaire(ctx context.Context, userID uuid.UUID) (domain.CandidateQuestionnaire, error) {
|
||||
const location = "Service.GetMyQuestionnaire"
|
||||
if userID == uuid.Nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
var result domain.CandidateQuestionnaire
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireCandidate(ctx, unit, userID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
result, err = unit.CandidateQuestionnaires().Get(ctx, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read questionnaire: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// SaveMyQuestionnaire replaces the complete questionnaire at expectedVersion.
|
||||
// A changed stale save fails; an identical retry is a no-op. The first valid
|
||||
// save advances onboarding only from candidate_questionnaire.
|
||||
func (service *Service) SaveMyQuestionnaire(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
expectedVersion int64,
|
||||
input domain.CandidateQuestionnaireInput,
|
||||
) (domain.CandidateQuestionnaire, error) {
|
||||
const location = "Service.SaveMyQuestionnaire"
|
||||
if userID == uuid.Nil {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
at := service.clock().UTC()
|
||||
if at.IsZero() {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - application clock returned zero: %w", location, domain.ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
var result domain.CandidateQuestionnaire
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireCandidate(ctx, unit, userID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
repository := unit.CandidateQuestionnaires()
|
||||
current, err := repository.Get(ctx, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read questionnaire: %w", location, err)
|
||||
}
|
||||
availability, err := unit.AssessmentBank().ListCurrentSpecializationAvailability(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read current task language availability: %w", location, err)
|
||||
}
|
||||
updated, changed, err := current.Replace(input, expectedVersion, at, availability)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - apply replacement: %w", location, err)
|
||||
}
|
||||
if changed {
|
||||
updated, err = repository.Save(ctx, expectedVersion, updated)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - save replacement: %w", location, err)
|
||||
}
|
||||
}
|
||||
if err := repository.AdvanceOnboarding(ctx, userID, at); err != nil {
|
||||
return fmt.Errorf("%s - advance onboarding: %w", location, err)
|
||||
}
|
||||
result = updated
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrCandidateQuestionnaireVersionConflict) || errors.Is(err, domain.ErrCandidateQuestionnaireVersionConflict) {
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - transaction: %w", location, domain.ErrCandidateQuestionnaireVersionConflict)
|
||||
}
|
||||
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func requireCandidate(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, location string) error {
|
||||
user, err := unit.Users().GetByID(ctx, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return ErrForbidden
|
||||
}
|
||||
return fmt.Errorf("%s - read account: %w", location, err)
|
||||
}
|
||||
if !user.EmailVerified() {
|
||||
return ErrEmailNotVerified
|
||||
}
|
||||
if user.Scenario != domain.ScenarioCandidate {
|
||||
return ErrForbidden
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package questionnaire
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type questionnaireTestTransactor struct{ unit outbound.UnitOfWork }
|
||||
|
||||
func (transactor questionnaireTestTransactor) WithinTransaction(
|
||||
ctx context.Context,
|
||||
fn func(context.Context, outbound.UnitOfWork) error,
|
||||
) error {
|
||||
return fn(ctx, transactor.unit)
|
||||
}
|
||||
|
||||
type questionnaireTestUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
users outbound.UserRepository
|
||||
questionnaire outbound.CandidateQuestionnaireRepository
|
||||
bank outbound.AssessmentBankRepository
|
||||
}
|
||||
|
||||
func (unit questionnaireTestUnit) Users() outbound.UserRepository { return unit.users }
|
||||
|
||||
func (unit questionnaireTestUnit) CandidateQuestionnaires() outbound.CandidateQuestionnaireRepository {
|
||||
return unit.questionnaire
|
||||
}
|
||||
|
||||
func (unit questionnaireTestUnit) AssessmentBank() outbound.AssessmentBankRepository {
|
||||
return unit.bank
|
||||
}
|
||||
|
||||
type questionnaireTestUsers struct {
|
||||
outbound.UserRepository
|
||||
|
||||
user domain.User
|
||||
err error
|
||||
getCalls int
|
||||
}
|
||||
|
||||
func (users *questionnaireTestUsers) GetByID(_ context.Context, userID uuid.UUID) (domain.User, error) {
|
||||
users.getCalls++
|
||||
if users.err != nil {
|
||||
return domain.User{}, users.err
|
||||
}
|
||||
if users.user.ID != userID {
|
||||
return domain.User{}, outbound.ErrUserNotFound
|
||||
}
|
||||
return users.user, nil
|
||||
}
|
||||
|
||||
type questionnaireTestRepository struct {
|
||||
questionnaire domain.CandidateQuestionnaire
|
||||
getCalls int
|
||||
saveCalls int
|
||||
advanceCalls int
|
||||
saveErr error
|
||||
advanceErr error
|
||||
}
|
||||
|
||||
func (repository *questionnaireTestRepository) Get(_ context.Context, userID uuid.UUID) (domain.CandidateQuestionnaire, error) {
|
||||
repository.getCalls++
|
||||
if repository.questionnaire.IsZero() {
|
||||
return domain.EmptyCandidateQuestionnaire(userID)
|
||||
}
|
||||
return repository.questionnaire, nil
|
||||
}
|
||||
|
||||
func (repository *questionnaireTestRepository) Save(
|
||||
_ context.Context,
|
||||
expectedVersion int64,
|
||||
questionnaire domain.CandidateQuestionnaire,
|
||||
) (domain.CandidateQuestionnaire, error) {
|
||||
repository.saveCalls++
|
||||
if repository.saveErr != nil {
|
||||
return domain.CandidateQuestionnaire{}, repository.saveErr
|
||||
}
|
||||
repository.questionnaire, _ = domain.RestoreCandidateQuestionnaire(domain.StoredCandidateQuestionnaire{
|
||||
UserID: questionnaire.UserID(), Version: expectedVersion + 1,
|
||||
Specializations: questionnaire.Specializations(), WorkFormats: questionnaire.WorkFormats(),
|
||||
CreatedAt: questionnaire.CreatedAt(), UpdatedAt: questionnaire.UpdatedAt(),
|
||||
})
|
||||
return repository.questionnaire, nil
|
||||
}
|
||||
|
||||
func (repository *questionnaireTestRepository) AdvanceOnboarding(context.Context, uuid.UUID, time.Time) error {
|
||||
repository.advanceCalls++
|
||||
return repository.advanceErr
|
||||
}
|
||||
|
||||
type questionnaireTestBank struct {
|
||||
outbound.AssessmentBankRepository
|
||||
|
||||
availability []domain.SpecializationAvailability
|
||||
err error
|
||||
}
|
||||
|
||||
func (bank questionnaireTestBank) ListCurrentSpecializationAvailability(context.Context) ([]domain.SpecializationAvailability, error) {
|
||||
return bank.availability, bank.err
|
||||
}
|
||||
|
||||
func TestServiceRequiresVerifiedCandidateBeforeQuestionnaireAccess(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
tests := []struct {
|
||||
name string
|
||||
scenario domain.Scenario
|
||||
verified bool
|
||||
wantErr error
|
||||
}{
|
||||
{name: "verified candidate", scenario: domain.ScenarioCandidate, verified: true},
|
||||
{name: "unverified candidate", scenario: domain.ScenarioCandidate, wantErr: ErrEmailNotVerified},
|
||||
{name: "verified employer", scenario: domain.ScenarioEmployer, verified: true, wantErr: ErrForbidden},
|
||||
{name: "unverified employer", scenario: domain.ScenarioEmployer, wantErr: ErrEmailNotVerified},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
id := uuid.Must(uuid.NewV7())
|
||||
user := domain.User{ID: id, Scenario: test.scenario}
|
||||
if test.verified {
|
||||
user.EmailVerifiedAt = &now
|
||||
}
|
||||
users := &questionnaireTestUsers{user: user}
|
||||
questionnaires := &questionnaireTestRepository{}
|
||||
bank := questionnaireTestBank{availability: []domain.SpecializationAvailability{{
|
||||
Specialization: domain.SpecializationBackend,
|
||||
TaskLanguages: []domain.TaskLanguageCode{domain.TaskLanguageGo},
|
||||
}}}
|
||||
service := NewService(questionnaireTestTransactor{unit: questionnaireTestUnit{
|
||||
users: users, questionnaire: questionnaires, bank: bank,
|
||||
}}, func() time.Time { return now })
|
||||
|
||||
_, readErr := service.GetMyQuestionnaire(context.Background(), id)
|
||||
if !errors.Is(readErr, test.wantErr) {
|
||||
t.Fatalf("GetMyQuestionnaire() error = %v, want %v", readErr, test.wantErr)
|
||||
}
|
||||
_, saveErr := service.SaveMyQuestionnaire(context.Background(), id, 0, validQuestionnaireInput())
|
||||
if !errors.Is(saveErr, test.wantErr) {
|
||||
t.Fatalf("SaveMyQuestionnaire() error = %v, want %v", saveErr, test.wantErr)
|
||||
}
|
||||
wantReads, wantSaves, wantAdvances := 0, 0, 0
|
||||
if test.wantErr == nil {
|
||||
wantReads, wantSaves, wantAdvances = 2, 1, 1
|
||||
}
|
||||
if questionnaires.getCalls != wantReads || questionnaires.saveCalls != wantSaves || questionnaires.advanceCalls != wantAdvances {
|
||||
t.Fatalf("questionnaire calls = get %d, save %d, advance %d; want %d, %d, %d", questionnaires.getCalls, questionnaires.saveCalls, questionnaires.advanceCalls, wantReads, wantSaves, wantAdvances)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveMyQuestionnairePersistsChangesAndAdvancesAfterNoOp(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
id := uuid.Must(uuid.NewV7())
|
||||
user := domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
|
||||
users := &questionnaireTestUsers{user: user}
|
||||
questionnaires := &questionnaireTestRepository{}
|
||||
bank := questionnaireTestBank{availability: []domain.SpecializationAvailability{{
|
||||
Specialization: domain.SpecializationBackend,
|
||||
Grades: []domain.GradeCode{domain.GradeJunior},
|
||||
TaskLanguages: []domain.TaskLanguageCode{domain.TaskLanguageGo},
|
||||
}}}
|
||||
service := NewService(questionnaireTestTransactor{unit: questionnaireTestUnit{
|
||||
users: users, questionnaire: questionnaires, bank: bank,
|
||||
}}, func() time.Time { return now })
|
||||
input := validQuestionnaireInput()
|
||||
|
||||
first, err := service.SaveMyQuestionnaire(context.Background(), id, 0, input)
|
||||
if err != nil {
|
||||
t.Fatalf("SaveMyQuestionnaire(first) error = %v", err)
|
||||
}
|
||||
if first.Version() != 1 || questionnaires.saveCalls != 1 || questionnaires.advanceCalls != 1 {
|
||||
t.Fatalf("first save version/calls = %d/%d/%d; want 1/1/1", first.Version(), questionnaires.saveCalls, questionnaires.advanceCalls)
|
||||
}
|
||||
input.Specializations[0].SelfAssessedGrade = domain.GradeSenior
|
||||
second, err := service.SaveMyQuestionnaire(context.Background(), id, 1, input)
|
||||
if err != nil {
|
||||
t.Fatalf("SaveMyQuestionnaire(self-assessed senior) error = %v", err)
|
||||
}
|
||||
if second.Version() != 2 || second.Specializations()[0].SelfAssessedGrade != domain.GradeSenior {
|
||||
t.Fatalf("saved self-assessment = version %d grade %q; want version 2 senior", second.Version(), second.Specializations()[0].SelfAssessedGrade)
|
||||
}
|
||||
if _, err := service.SaveMyQuestionnaire(context.Background(), id, 1, input); err != nil {
|
||||
t.Fatalf("SaveMyQuestionnaire(stale identical retry) error = %v", err)
|
||||
}
|
||||
if questionnaires.saveCalls != 2 || questionnaires.advanceCalls != 3 {
|
||||
t.Fatalf("save/onboarding calls = %d/%d; want 2/3", questionnaires.saveCalls, questionnaires.advanceCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveMyQuestionnaireRejectsUnavailableLanguageBeforeMutation(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
id := uuid.Must(uuid.NewV7())
|
||||
user := domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
|
||||
users := &questionnaireTestUsers{user: user}
|
||||
questionnaires := &questionnaireTestRepository{}
|
||||
bank := questionnaireTestBank{availability: []domain.SpecializationAvailability{{
|
||||
Specialization: domain.SpecializationBackend,
|
||||
TaskLanguages: []domain.TaskLanguageCode{domain.TaskLanguagePython},
|
||||
}}}
|
||||
service := NewService(questionnaireTestTransactor{unit: questionnaireTestUnit{
|
||||
users: users, questionnaire: questionnaires, bank: bank,
|
||||
}}, func() time.Time { return now })
|
||||
|
||||
_, err := service.SaveMyQuestionnaire(context.Background(), id, 0, validQuestionnaireInput())
|
||||
fieldError, ok := errors.AsType[*domain.CandidateQuestionnaireFieldError](err)
|
||||
if !ok || fieldError.Pointer != "/specializations/0/task_languages/0" {
|
||||
t.Fatalf("SaveMyQuestionnaire(unavailable language) error = %v; want task-language field error", err)
|
||||
}
|
||||
if questionnaires.saveCalls != 0 || questionnaires.advanceCalls != 0 {
|
||||
t.Fatalf("mutation calls after invalid language = save %d advance %d; want 0/0", questionnaires.saveCalls, questionnaires.advanceCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func validQuestionnaireInput() domain.CandidateQuestionnaireInput {
|
||||
return domain.CandidateQuestionnaireInput{
|
||||
Specializations: []domain.QuestionnaireSpecialization{{
|
||||
Specialization: domain.SpecializationBackend,
|
||||
SelfAssessedGrade: domain.GradeJunior,
|
||||
TaskLanguages: []domain.TaskLanguageCode{domain.TaskLanguageGo},
|
||||
}},
|
||||
WorkFormats: []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatRemote},
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user