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
@@ -0,0 +1,71 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// AssessmentCategoryCatalogMetadata is the explicit public-catalog mapping
|
||||
// reviewed for a published bank category before it is opened. It does not
|
||||
// derive public specialization from an assessment family's internal topic.
|
||||
type AssessmentCategoryCatalogMetadata struct {
|
||||
specialization SpecializationCode
|
||||
grade GradeCode
|
||||
taskLanguages []TaskLanguageCode
|
||||
}
|
||||
|
||||
// NewAssessmentCategoryCatalogMetadata validates the mapping attached to a
|
||||
// reviewed category opening.
|
||||
func NewAssessmentCategoryCatalogMetadata(
|
||||
specialization SpecializationCode,
|
||||
grade GradeCode,
|
||||
taskLanguages []TaskLanguageCode,
|
||||
) (AssessmentCategoryCatalogMetadata, error) {
|
||||
const location = "domain.NewAssessmentCategoryCatalogMetadata"
|
||||
if !specialization.IsKnown() {
|
||||
return AssessmentCategoryCatalogMetadata{}, fmt.Errorf("%s - specialization is not in the public catalog: %w", location, ErrInvalidAssessmentFamily)
|
||||
}
|
||||
if !grade.IsKnown() {
|
||||
return AssessmentCategoryCatalogMetadata{}, fmt.Errorf("%s - grade is not in the public catalog: %w", location, ErrInvalidAssessmentFamily)
|
||||
}
|
||||
if len(taskLanguages) > maxQuestionnaireTaskLanguages {
|
||||
return AssessmentCategoryCatalogMetadata{}, fmt.Errorf("%s - at most two task languages are allowed: %w", location, ErrInvalidAssessmentFamily)
|
||||
}
|
||||
seen := make(map[TaskLanguageCode]struct{}, len(taskLanguages))
|
||||
for _, language := range taskLanguages {
|
||||
if !language.IsKnown() {
|
||||
return AssessmentCategoryCatalogMetadata{}, fmt.Errorf("%s - task language is not in the public catalog: %w", location, ErrInvalidAssessmentFamily)
|
||||
}
|
||||
if _, exists := seen[language]; exists {
|
||||
return AssessmentCategoryCatalogMetadata{}, fmt.Errorf("%s - task languages must be unique: %w", location, ErrInvalidAssessmentFamily)
|
||||
}
|
||||
seen[language] = struct{}{}
|
||||
}
|
||||
return AssessmentCategoryCatalogMetadata{
|
||||
specialization: specialization,
|
||||
grade: grade,
|
||||
taskLanguages: slices.Clone(taskLanguages),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (metadata AssessmentCategoryCatalogMetadata) Specialization() SpecializationCode {
|
||||
return metadata.specialization
|
||||
}
|
||||
|
||||
func (metadata AssessmentCategoryCatalogMetadata) Grade() GradeCode { return metadata.grade }
|
||||
|
||||
func (metadata AssessmentCategoryCatalogMetadata) TaskLanguages() []TaskLanguageCode {
|
||||
return slices.Clone(metadata.taskLanguages)
|
||||
}
|
||||
|
||||
func (metadata AssessmentCategoryCatalogMetadata) IsZero() bool {
|
||||
return metadata.specialization == "" || metadata.grade == ""
|
||||
}
|
||||
|
||||
// AssessmentCategoryManifestEntry is an immutable published family identity
|
||||
// used to pin public catalog metadata to one reviewed bank composition.
|
||||
type AssessmentCategoryManifestEntry struct {
|
||||
FamilyKey AssessmentFamilyKey
|
||||
Version int32
|
||||
ContentSHA256 []byte
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidCompanyQuota reports a quota request that has incomplete or
|
||||
// inconsistent trusted inputs.
|
||||
ErrInvalidCompanyQuota = errors.New("invalid company quota")
|
||||
|
||||
// ErrCompanyQuotaDenied reports an organization level that has no active
|
||||
// quota tier. Callers must refuse the action instead of falling back.
|
||||
ErrCompanyQuotaDenied = errors.New("company quota denied")
|
||||
)
|
||||
|
||||
// CompanyQuota is an immutable snapshot of the limits that apply to one
|
||||
// organization at one instant. It carries the stored verification and
|
||||
// effective policy identities so the transactional repository can verify
|
||||
// that neither changed before it reserves usage.
|
||||
type CompanyQuota struct {
|
||||
organizationID uuid.UUID
|
||||
policyVersionID PolicyVersionID
|
||||
verificationLevel OrganizationVerificationLevel
|
||||
verificationBasis OrganizationVerificationBasis
|
||||
verificationChanged time.Time
|
||||
tier OrganizationTier
|
||||
at time.Time
|
||||
invitationWindow time.Duration
|
||||
invitationLimit int64
|
||||
cardViewWindow time.Duration
|
||||
cardViewLimit int64
|
||||
}
|
||||
|
||||
// NewCompanyQuota resolves the organization's trusted verification against
|
||||
// an effective product policy. at is the application clock snapshot for the
|
||||
// whole operation; a request from before the organization or its current
|
||||
// verification record is rejected so a stale timestamp cannot use older
|
||||
// trust.
|
||||
func NewCompanyQuota(organization Organization, version PolicyVersion, at time.Time) (CompanyQuota, error) {
|
||||
const location = "domain.NewCompanyQuota"
|
||||
if organization.IsZero() {
|
||||
return CompanyQuota{}, fmt.Errorf("%s - organization must be restored from trusted storage: %w", location, ErrInvalidCompanyQuota)
|
||||
}
|
||||
if version.IsZero() || version.Key() != ProductPolicyKey {
|
||||
return CompanyQuota{}, fmt.Errorf("%s - an effective product policy is required: %w", location, ErrInvalidCompanyQuota)
|
||||
}
|
||||
if at.IsZero() || at.Unix() < 0 {
|
||||
return CompanyQuota{}, fmt.Errorf("%s - application time must be set and non-negative: %w", location, ErrInvalidCompanyQuota)
|
||||
}
|
||||
at = at.UTC()
|
||||
verification := organization.Verification()
|
||||
if at.Before(organization.CreatedAt()) || at.Before(verification.ChangedAt()) {
|
||||
return CompanyQuota{}, fmt.Errorf("%s - application time predates organization trust: %w", location, ErrInvalidCompanyQuota)
|
||||
}
|
||||
if version.EffectiveAt().After(at) {
|
||||
return CompanyQuota{}, fmt.Errorf("%s - policy is not effective at application time: %w", location, ErrInvalidCompanyQuota)
|
||||
}
|
||||
|
||||
tier, ok := verification.Level().QuotaTier()
|
||||
if !ok {
|
||||
return CompanyQuota{}, fmt.Errorf("%s - verification level has no quota tier: %w", location, ErrCompanyQuotaDenied)
|
||||
}
|
||||
policy := version.Policy().OrganizationQuotas
|
||||
tierPolicy, err := policy.Tier(tier)
|
||||
if err != nil {
|
||||
return CompanyQuota{}, fmt.Errorf("%s - read the organization tier: %w", location, err)
|
||||
}
|
||||
if !tierPolicy.Active {
|
||||
return CompanyQuota{}, fmt.Errorf("%s - organization tier is not active: %w", location, ErrCompanyQuotaDenied)
|
||||
}
|
||||
|
||||
return CompanyQuota{
|
||||
organizationID: organization.ID(),
|
||||
policyVersionID: version.ID(),
|
||||
verificationLevel: verification.Level(),
|
||||
verificationBasis: verification.Basis(),
|
||||
verificationChanged: verification.ChangedAt().UTC(),
|
||||
tier: tier,
|
||||
at: at,
|
||||
invitationWindow: policy.InvitationWindow.Duration(),
|
||||
invitationLimit: int64(tierPolicy.InvitationsPerWindow),
|
||||
cardViewWindow: policy.CardViewWindow.Duration(),
|
||||
cardViewLimit: int64(tierPolicy.DistinctCardViewsPerWindow),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (quota CompanyQuota) OrganizationID() uuid.UUID { return quota.organizationID }
|
||||
|
||||
func (quota CompanyQuota) PolicyVersionID() PolicyVersionID { return quota.policyVersionID }
|
||||
|
||||
func (quota CompanyQuota) VerificationLevel() OrganizationVerificationLevel {
|
||||
return quota.verificationLevel
|
||||
}
|
||||
|
||||
func (quota CompanyQuota) VerificationBasis() OrganizationVerificationBasis {
|
||||
return quota.verificationBasis
|
||||
}
|
||||
|
||||
func (quota CompanyQuota) VerificationChangedAt() time.Time { return quota.verificationChanged }
|
||||
|
||||
func (quota CompanyQuota) Tier() OrganizationTier { return quota.tier }
|
||||
|
||||
func (quota CompanyQuota) At() time.Time { return quota.at }
|
||||
|
||||
func (quota CompanyQuota) InvitationWindow() time.Duration { return quota.invitationWindow }
|
||||
|
||||
func (quota CompanyQuota) InvitationWindowStart() time.Time {
|
||||
if quota.invitationWindow <= 0 {
|
||||
return time.Time{}
|
||||
}
|
||||
return quota.at.Add(-quota.invitationWindow)
|
||||
}
|
||||
|
||||
func (quota CompanyQuota) InvitationLimit() int64 { return quota.invitationLimit }
|
||||
|
||||
func (quota CompanyQuota) CardViewWindow() time.Duration { return quota.cardViewWindow }
|
||||
|
||||
func (quota CompanyQuota) CardViewWindowStart() time.Time {
|
||||
if quota.cardViewWindow <= 0 {
|
||||
return time.Time{}
|
||||
}
|
||||
return quota.at.Add(-quota.cardViewWindow)
|
||||
}
|
||||
|
||||
func (quota CompanyQuota) CardViewLimit() int64 { return quota.cardViewLimit }
|
||||
|
||||
// IsZero reports a snapshot that was not built by NewCompanyQuota.
|
||||
func (quota CompanyQuota) IsZero() bool { return quota.organizationID == uuid.Nil }
|
||||
@@ -0,0 +1,146 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestNewCompanyQuotaUsesStoredVerificationAndEffectivePolicy(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.FixedZone("owner", 3*60*60))
|
||||
createdAt := at.Add(-30 * 24 * time.Hour).UTC()
|
||||
organization := companyQuotaTestOrganization(t, string(OrganizationVerificationE0), string(OrganizationBasisConfirmedEmail), createdAt, createdAt)
|
||||
policy := companyQuotaTestPolicy(t, at.UTC().Add(-time.Hour), false)
|
||||
|
||||
quota, err := NewCompanyQuota(organization, policy, at)
|
||||
if err != nil {
|
||||
t.Fatalf("NewCompanyQuota() error = %v", err)
|
||||
}
|
||||
if quota.OrganizationID() != organization.ID() || quota.PolicyVersionID() != policy.ID() ||
|
||||
quota.Tier() != OrganizationTierE0 || quota.VerificationLevel() != OrganizationVerificationE0 ||
|
||||
quota.VerificationBasis() != OrganizationBasisConfirmedEmail || !quota.VerificationChangedAt().Equal(createdAt) {
|
||||
t.Fatalf("quota identity = org %s, policy %s, tier %s, verification %s/%s at %s", quota.OrganizationID(), quota.PolicyVersionID(), quota.Tier(), quota.VerificationLevel(), quota.VerificationBasis(), quota.VerificationChangedAt())
|
||||
}
|
||||
if !quota.At().Equal(at.UTC()) || quota.At().Location() != time.UTC {
|
||||
t.Fatalf("At() = %s, want %s in UTC", quota.At(), at.UTC())
|
||||
}
|
||||
if quota.InvitationLimit() != 10 || quota.CardViewLimit() != 50 ||
|
||||
quota.InvitationWindow() != 7*24*time.Hour || quota.CardViewWindow() != 24*time.Hour {
|
||||
t.Fatalf("quota limits/windows = %d/%s and %d/%s", quota.InvitationLimit(), quota.InvitationWindow(), quota.CardViewLimit(), quota.CardViewWindow())
|
||||
}
|
||||
if want := at.UTC().Add(-7 * 24 * time.Hour); !quota.InvitationWindowStart().Equal(want) {
|
||||
t.Fatalf("InvitationWindowStart() = %s, want %s", quota.InvitationWindowStart(), want)
|
||||
}
|
||||
if want := at.UTC().Add(-24 * time.Hour); !quota.CardViewWindowStart().Equal(want) {
|
||||
t.Fatalf("CardViewWindowStart() = %s, want %s", quota.CardViewWindowStart(), want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewCompanyQuotaRequiresBothStoredE2VerificationAndActivePolicyTier(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
|
||||
organization := companyQuotaTestOrganization(t, string(OrganizationVerificationE2), string(OrganizationBasisRequisitesAndAuthority), at.Add(-time.Hour), at.Add(-time.Hour))
|
||||
|
||||
if _, err := NewCompanyQuota(organization, companyQuotaTestPolicy(t, at.Add(-time.Hour), false), at); !errors.Is(err, ErrCompanyQuotaDenied) {
|
||||
t.Fatalf("NewCompanyQuota(E2, inactive policy tier) error = %v, want ErrCompanyQuotaDenied", err)
|
||||
}
|
||||
|
||||
quota, err := NewCompanyQuota(organization, companyQuotaTestPolicy(t, at.Add(-time.Hour), true), at)
|
||||
if err != nil {
|
||||
t.Fatalf("NewCompanyQuota(E2, active policy tier) error = %v", err)
|
||||
}
|
||||
if quota.Tier() != OrganizationTierE2 || quota.InvitationLimit() != 100 || quota.CardViewLimit() != 400 {
|
||||
t.Fatalf("E2 quota = tier %s, limits %d/%d", quota.Tier(), quota.InvitationLimit(), quota.CardViewLimit())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewCompanyQuotaDeniesE3WithoutFallingBackToE0(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
|
||||
organization := companyQuotaTestOrganization(t, string(OrganizationVerificationE3), string(OrganizationBasisManualReview), at.Add(-time.Hour), at.Add(-time.Hour))
|
||||
|
||||
if _, err := NewCompanyQuota(organization, companyQuotaTestPolicy(t, at.Add(-time.Hour), true), at); !errors.Is(err, ErrCompanyQuotaDenied) {
|
||||
t.Fatalf("NewCompanyQuota(E3) error = %v, want ErrCompanyQuotaDenied", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewCompanyQuotaRejectsUntrustedOrBackdatedInputs(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
|
||||
organization := companyQuotaTestOrganization(t, string(OrganizationVerificationE0), string(OrganizationBasisConfirmedEmail), at.Add(-time.Hour), at.Add(-time.Hour))
|
||||
policy := companyQuotaTestPolicy(t, at.Add(-time.Hour), false)
|
||||
futurePolicy := companyQuotaTestPolicy(t, at.Add(time.Hour), false)
|
||||
beforeEpoch := time.Date(1969, 12, 31, 23, 59, 59, 0, time.UTC)
|
||||
createdInFuture := companyQuotaTestOrganization(t, string(OrganizationVerificationE0), string(OrganizationBasisConfirmedEmail), at.Add(time.Hour), at.Add(time.Hour))
|
||||
verifiedInFuture := companyQuotaTestOrganization(t, string(OrganizationVerificationE1), string(OrganizationBasisCorporateDomain), at.Add(-time.Hour), at.Add(time.Hour))
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
organization Organization
|
||||
policy PolicyVersion
|
||||
at time.Time
|
||||
want error
|
||||
}{
|
||||
{name: "zero organization", organization: Organization{}, policy: policy, at: at, want: ErrInvalidCompanyQuota},
|
||||
{name: "zero policy", organization: organization, policy: PolicyVersion{}, at: at, want: ErrInvalidCompanyQuota},
|
||||
{name: "zero application time", organization: organization, policy: policy, want: ErrInvalidCompanyQuota},
|
||||
{name: "negative application time", organization: organization, policy: policy, at: beforeEpoch, want: ErrInvalidCompanyQuota},
|
||||
{name: "organization created after request time", organization: createdInFuture, policy: policy, at: at, want: ErrInvalidCompanyQuota},
|
||||
{name: "verification changed after request time", organization: verifiedInFuture, policy: policy, at: at, want: ErrInvalidCompanyQuota},
|
||||
{name: "policy effective after request time", organization: organization, policy: futurePolicy, at: at, want: ErrInvalidCompanyQuota},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if _, err := NewCompanyQuota(test.organization, test.policy, test.at); !errors.Is(err, test.want) {
|
||||
t.Fatalf("NewCompanyQuota() error = %v, want %v", err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func companyQuotaTestOrganization(t *testing.T, level, basis string, createdAt, changedAt time.Time) Organization {
|
||||
t.Helper()
|
||||
updatedAt := createdAt
|
||||
if changedAt.After(updatedAt) {
|
||||
updatedAt = changedAt
|
||||
}
|
||||
organization, err := RestoreOrganization(StoredOrganization{
|
||||
ID: uuid.New(),
|
||||
Name: "Example Company",
|
||||
VerificationLevel: level,
|
||||
VerificationBasis: basis,
|
||||
VerificationChangedAt: changedAt,
|
||||
Version: 1,
|
||||
CreatedAt: createdAt,
|
||||
UpdatedAt: updatedAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreOrganization() error = %v", err)
|
||||
}
|
||||
return organization
|
||||
}
|
||||
|
||||
func companyQuotaTestPolicy(t *testing.T, effectiveAt time.Time, activateE2 bool) PolicyVersion {
|
||||
t.Helper()
|
||||
policy := DemoProductPolicyV1()
|
||||
policy.OrganizationQuotas.TierE2.Active = activateE2
|
||||
draft, err := NewPolicyVersionDraft(NewPolicyVersionDraftInput{
|
||||
Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: 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 := RestorePolicyVersion(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,486 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidCandidateQuestionnaire reports a questionnaire value that
|
||||
// breaks its contract or cannot be restored from storage.
|
||||
ErrInvalidCandidateQuestionnaire = errors.New("invalid candidate questionnaire")
|
||||
|
||||
// ErrCandidateQuestionnaireVersionConflict reports that the saved
|
||||
// questionnaire changed after the caller read it.
|
||||
ErrCandidateQuestionnaireVersionConflict = errors.New("candidate questionnaire changed concurrently")
|
||||
)
|
||||
|
||||
const (
|
||||
maxQuestionnaireSpecializations = 2
|
||||
maxQuestionnaireTaskLanguages = 2
|
||||
maxQuestionnaireStackItems = 20
|
||||
maxQuestionnaireStackTagRunes = 50
|
||||
maxQuestionnaireExperienceMonth = 600
|
||||
)
|
||||
|
||||
const redactedQuestionnaire = "[redacted candidate questionnaire]"
|
||||
|
||||
// CandidateQuestionnaireFieldError describes one invalid request field. The
|
||||
// reason is fixed text and never includes the submitted value.
|
||||
type CandidateQuestionnaireFieldError struct {
|
||||
Pointer string
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (fieldError *CandidateQuestionnaireFieldError) Error() string {
|
||||
return "candidate questionnaire field " + fieldError.Pointer + " " + fieldError.Reason
|
||||
}
|
||||
|
||||
func (fieldError *CandidateQuestionnaireFieldError) Unwrap() error {
|
||||
return ErrInvalidCandidateQuestionnaire
|
||||
}
|
||||
|
||||
func invalidQuestionnaireField(location, pointer, reason string) error {
|
||||
return fmt.Errorf("%s - %w", location, &CandidateQuestionnaireFieldError{Pointer: pointer, Reason: reason})
|
||||
}
|
||||
|
||||
// TaskLanguageCode identifies a language actually offered by a published
|
||||
// assessment bank. The catalog projection, not this enum, decides which one
|
||||
// is currently valid for a specialization.
|
||||
type TaskLanguageCode string
|
||||
|
||||
const (
|
||||
TaskLanguagePython TaskLanguageCode = "python"
|
||||
TaskLanguageGo TaskLanguageCode = "go"
|
||||
)
|
||||
|
||||
func (language TaskLanguageCode) IsKnown() bool {
|
||||
return language == TaskLanguagePython || language == TaskLanguageGo
|
||||
}
|
||||
|
||||
// QuestionnaireWorkFormat is an acceptable work format.
|
||||
type QuestionnaireWorkFormat string
|
||||
|
||||
const (
|
||||
QuestionnaireWorkFormatRemote QuestionnaireWorkFormat = "remote"
|
||||
QuestionnaireWorkFormatOffice QuestionnaireWorkFormat = "office"
|
||||
QuestionnaireWorkFormatHybrid QuestionnaireWorkFormat = "hybrid"
|
||||
)
|
||||
|
||||
func (format QuestionnaireWorkFormat) IsKnown() bool {
|
||||
switch format {
|
||||
case QuestionnaireWorkFormatRemote, QuestionnaireWorkFormatOffice, QuestionnaireWorkFormatHybrid:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// QuestionnaireExperience contains self-reported month totals. It does not
|
||||
// contribute assessment points and has no field for a confirmed grade.
|
||||
type QuestionnaireExperience struct {
|
||||
CommercialMonths int32
|
||||
AcademicMonths int32
|
||||
}
|
||||
|
||||
func (QuestionnaireExperience) String() string { return redactedQuestionnaire }
|
||||
func (QuestionnaireExperience) GoString() string { return redactedQuestionnaire }
|
||||
func (QuestionnaireExperience) Format(state fmt.State, _ rune) {
|
||||
writeRedacted(state, redactedQuestionnaire)
|
||||
}
|
||||
func (QuestionnaireExperience) LogValue() slog.Value {
|
||||
return slog.StringValue(redactedQuestionnaire)
|
||||
}
|
||||
|
||||
// QuestionnaireSpecialization is one self-assessed specialization. Its grade
|
||||
// is a candidate claim, never a confirmed grade or category.
|
||||
type QuestionnaireSpecialization struct {
|
||||
Specialization SpecializationCode
|
||||
SelfAssessedGrade GradeCode
|
||||
TaskLanguages []TaskLanguageCode
|
||||
Stack []string
|
||||
Experience *QuestionnaireExperience
|
||||
}
|
||||
|
||||
func (QuestionnaireSpecialization) String() string { return redactedQuestionnaire }
|
||||
func (QuestionnaireSpecialization) GoString() string { return redactedQuestionnaire }
|
||||
func (QuestionnaireSpecialization) Format(state fmt.State, _ rune) {
|
||||
writeRedacted(state, redactedQuestionnaire)
|
||||
}
|
||||
func (QuestionnaireSpecialization) LogValue() slog.Value {
|
||||
return slog.StringValue(redactedQuestionnaire)
|
||||
}
|
||||
|
||||
// CandidateQuestionnaireInput is the complete replacement sent by a
|
||||
// candidate. It contains personal data and must not be logged.
|
||||
type CandidateQuestionnaireInput struct {
|
||||
Specializations []QuestionnaireSpecialization
|
||||
WorkFormats []QuestionnaireWorkFormat
|
||||
}
|
||||
|
||||
func (CandidateQuestionnaireInput) String() string { return redactedQuestionnaire }
|
||||
func (CandidateQuestionnaireInput) GoString() string { return redactedQuestionnaire }
|
||||
func (CandidateQuestionnaireInput) Format(state fmt.State, _ rune) {
|
||||
writeRedacted(state, redactedQuestionnaire)
|
||||
}
|
||||
func (CandidateQuestionnaireInput) LogValue() slog.Value {
|
||||
return slog.StringValue(redactedQuestionnaire)
|
||||
}
|
||||
|
||||
// SpecializationAvailability is the current published-bank projection shared
|
||||
// by the public catalog and questionnaire validation. Empty grades and
|
||||
// languages mean that the specialization is not currently available.
|
||||
type SpecializationAvailability struct {
|
||||
Specialization SpecializationCode
|
||||
Grades []GradeCode
|
||||
TaskLanguages []TaskLanguageCode
|
||||
}
|
||||
|
||||
// CandidateQuestionnaire is the private questionnaire of one candidate.
|
||||
// Version zero means no questionnaire has been saved yet.
|
||||
type CandidateQuestionnaire struct {
|
||||
userID uuid.UUID
|
||||
version int64
|
||||
specializations []QuestionnaireSpecialization
|
||||
workFormats []QuestionnaireWorkFormat
|
||||
createdAt time.Time
|
||||
updatedAt time.Time
|
||||
}
|
||||
|
||||
// EmptyCandidateQuestionnaire returns the unsaved questionnaire of userID.
|
||||
func EmptyCandidateQuestionnaire(userID uuid.UUID) (CandidateQuestionnaire, error) {
|
||||
if userID == uuid.Nil {
|
||||
return CandidateQuestionnaire{}, fmt.Errorf("domain.EmptyCandidateQuestionnaire - user ID must not be nil: %w", ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
return CandidateQuestionnaire{userID: userID}, nil
|
||||
}
|
||||
|
||||
func (questionnaire CandidateQuestionnaire) UserID() uuid.UUID { return questionnaire.userID }
|
||||
func (questionnaire CandidateQuestionnaire) Version() int64 { return questionnaire.version }
|
||||
func (questionnaire CandidateQuestionnaire) CreatedAt() time.Time {
|
||||
return questionnaire.createdAt
|
||||
}
|
||||
func (questionnaire CandidateQuestionnaire) UpdatedAt() time.Time {
|
||||
return questionnaire.updatedAt
|
||||
}
|
||||
|
||||
func (questionnaire CandidateQuestionnaire) Specializations() []QuestionnaireSpecialization {
|
||||
return cloneQuestionnaireSpecializations(questionnaire.specializations)
|
||||
}
|
||||
|
||||
func (questionnaire CandidateQuestionnaire) WorkFormats() []QuestionnaireWorkFormat {
|
||||
return slices.Clone(questionnaire.workFormats)
|
||||
}
|
||||
|
||||
func (questionnaire CandidateQuestionnaire) IsZero() bool { return questionnaire.userID == uuid.Nil }
|
||||
|
||||
// SameContent reports whether two questionnaires for the same candidate have
|
||||
// identical validated answers, without comparing versions or timestamps.
|
||||
func (questionnaire CandidateQuestionnaire) SameContent(other CandidateQuestionnaire) bool {
|
||||
return !questionnaire.IsZero() && questionnaire.userID == other.userID &&
|
||||
equalQuestionnaireContent(questionnaire.specializations, questionnaire.workFormats, questionnaireContent{
|
||||
specializations: other.specializations,
|
||||
workFormats: other.workFormats,
|
||||
})
|
||||
}
|
||||
|
||||
func (questionnaire CandidateQuestionnaire) String() string { return redactedQuestionnaire }
|
||||
func (questionnaire CandidateQuestionnaire) GoString() string { return redactedQuestionnaire }
|
||||
func (questionnaire CandidateQuestionnaire) Format(state fmt.State, _ rune) {
|
||||
writeRedacted(state, redactedQuestionnaire)
|
||||
}
|
||||
func (questionnaire CandidateQuestionnaire) LogValue() slog.Value {
|
||||
return slog.GroupValue(
|
||||
slog.String("user_id", questionnaire.userID.String()),
|
||||
slog.Int64("version", questionnaire.version),
|
||||
)
|
||||
}
|
||||
|
||||
// StoredCandidateQuestionnaire is the database projection used to restore a
|
||||
// saved questionnaire. A missing row is represented by EmptyCandidateQuestionnaire.
|
||||
type StoredCandidateQuestionnaire struct {
|
||||
UserID uuid.UUID
|
||||
Version int64
|
||||
Specializations []QuestionnaireSpecialization
|
||||
WorkFormats []QuestionnaireWorkFormat
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// RestoreCandidateQuestionnaire validates a saved questionnaire before it is
|
||||
// exposed to a usecase. Current bank availability is intentionally not part
|
||||
// of restoration; a later bank change must not make saved answers unreadable.
|
||||
func RestoreCandidateQuestionnaire(stored StoredCandidateQuestionnaire) (CandidateQuestionnaire, error) {
|
||||
const location = "domain.RestoreCandidateQuestionnaire"
|
||||
if stored.UserID == uuid.Nil || stored.Version < 1 || stored.CreatedAt.IsZero() || stored.UpdatedAt.Before(stored.CreatedAt) {
|
||||
return CandidateQuestionnaire{}, fmt.Errorf("%s - stored identity, version, or time is invalid: %w", location, ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
content, err := validateQuestionnaireInput(CandidateQuestionnaireInput{
|
||||
Specializations: stored.Specializations,
|
||||
WorkFormats: stored.WorkFormats,
|
||||
}, location)
|
||||
if err != nil {
|
||||
return CandidateQuestionnaire{}, fmt.Errorf("%s - validate stored content: %w", location, err)
|
||||
}
|
||||
return CandidateQuestionnaire{
|
||||
userID: stored.UserID, version: stored.Version,
|
||||
specializations: content.specializations, workFormats: content.workFormats,
|
||||
createdAt: stored.CreatedAt, updatedAt: stored.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Replace validates a complete replacement and reports whether it changes
|
||||
// the current questionnaire. Identical retries are no-ops even with an older
|
||||
// expected version; a changed stale request conflicts.
|
||||
func (questionnaire CandidateQuestionnaire) Replace(
|
||||
input CandidateQuestionnaireInput,
|
||||
expectedVersion int64,
|
||||
at time.Time,
|
||||
availability []SpecializationAvailability,
|
||||
) (CandidateQuestionnaire, bool, error) {
|
||||
const location = "CandidateQuestionnaire.Replace"
|
||||
if questionnaire.IsZero() {
|
||||
return CandidateQuestionnaire{}, false, fmt.Errorf("%s - questionnaire was not built by EmptyCandidateQuestionnaire or RestoreCandidateQuestionnaire: %w", location, ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
conflict := fmt.Errorf("%s - expected version is not current: %w", location, ErrCandidateQuestionnaireVersionConflict)
|
||||
if expectedVersion < 0 || expectedVersion > questionnaire.version {
|
||||
return CandidateQuestionnaire{}, false, conflict
|
||||
}
|
||||
if at.IsZero() {
|
||||
return CandidateQuestionnaire{}, false, fmt.Errorf("%s - time must be set: %w", location, ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
content, err := validateQuestionnaireInput(input, location)
|
||||
if err != nil {
|
||||
return CandidateQuestionnaire{}, false, fmt.Errorf("%s - validate content: %w", location, err)
|
||||
}
|
||||
if equalQuestionnaireContent(questionnaire.specializations, questionnaire.workFormats, content) {
|
||||
return questionnaire, false, nil
|
||||
}
|
||||
if expectedVersion != questionnaire.version {
|
||||
return CandidateQuestionnaire{}, false, conflict
|
||||
}
|
||||
if err := validateQuestionnaireTaskLanguages(content.specializations, availability, location); err != nil {
|
||||
return CandidateQuestionnaire{}, false, err
|
||||
}
|
||||
updated := questionnaire
|
||||
updated.specializations = content.specializations
|
||||
updated.workFormats = content.workFormats
|
||||
updated.updatedAt = at
|
||||
if at.Before(questionnaire.updatedAt) {
|
||||
updated.updatedAt = questionnaire.updatedAt
|
||||
}
|
||||
if updated.createdAt.IsZero() {
|
||||
updated.createdAt = updated.updatedAt
|
||||
}
|
||||
return updated, true, nil
|
||||
}
|
||||
|
||||
type questionnaireContent struct {
|
||||
specializations []QuestionnaireSpecialization
|
||||
workFormats []QuestionnaireWorkFormat
|
||||
}
|
||||
|
||||
func validateQuestionnaireInput(input CandidateQuestionnaireInput, location string) (questionnaireContent, error) {
|
||||
if len(input.Specializations) < 1 || len(input.Specializations) > maxQuestionnaireSpecializations {
|
||||
return questionnaireContent{}, invalidQuestionnaireField(location, "/specializations", "must contain one or two items")
|
||||
}
|
||||
if len(input.WorkFormats) < 1 || len(input.WorkFormats) > 3 {
|
||||
return questionnaireContent{}, invalidQuestionnaireField(location, "/work_context/work_formats", "must contain one to three items")
|
||||
}
|
||||
content := questionnaireContent{
|
||||
specializations: make([]QuestionnaireSpecialization, 0, len(input.Specializations)),
|
||||
workFormats: slices.Clone(input.WorkFormats),
|
||||
}
|
||||
var err error
|
||||
content.specializations, err = validateQuestionnaireSpecializations(input.Specializations, location)
|
||||
if err != nil {
|
||||
return questionnaireContent{}, err
|
||||
}
|
||||
if err := validateQuestionnaireWorkFormats(content.workFormats, location); err != nil {
|
||||
return questionnaireContent{}, err
|
||||
}
|
||||
return content, nil
|
||||
}
|
||||
|
||||
func validateQuestionnaireSpecializations(
|
||||
answers []QuestionnaireSpecialization,
|
||||
location string,
|
||||
) ([]QuestionnaireSpecialization, error) {
|
||||
validated := make([]QuestionnaireSpecialization, 0, len(answers))
|
||||
seenSpecializations := make(map[SpecializationCode]struct{}, len(answers))
|
||||
for index, answer := range answers {
|
||||
pointer := fmt.Sprintf("/specializations/%d", index)
|
||||
if !answer.Specialization.IsKnown() {
|
||||
return nil, invalidQuestionnaireField(location, pointer+"/specialization", "must be a specialization of the catalog")
|
||||
}
|
||||
if _, exists := seenSpecializations[answer.Specialization]; exists {
|
||||
return nil, invalidQuestionnaireField(location, pointer+"/specialization", "must not repeat an earlier item")
|
||||
}
|
||||
seenSpecializations[answer.Specialization] = struct{}{}
|
||||
validatedAnswer, err := validateQuestionnaireSpecialization(answer, pointer, location)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
validated = append(validated, validatedAnswer)
|
||||
}
|
||||
return validated, nil
|
||||
}
|
||||
|
||||
func validateQuestionnaireSpecialization(
|
||||
answer QuestionnaireSpecialization,
|
||||
pointer, location string,
|
||||
) (QuestionnaireSpecialization, error) {
|
||||
if !answer.SelfAssessedGrade.IsKnown() {
|
||||
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/self_assessed_grade", "must be a grade of the catalog")
|
||||
}
|
||||
if len(answer.TaskLanguages) > maxQuestionnaireTaskLanguages {
|
||||
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/task_languages", "must have at most two items")
|
||||
}
|
||||
if len(answer.Stack) > maxQuestionnaireStackItems {
|
||||
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/stack", "must have at most twenty items")
|
||||
}
|
||||
answer.TaskLanguages = slices.Clone(answer.TaskLanguages)
|
||||
if err := validateQuestionnaireTaskLanguageInputs(answer.TaskLanguages, pointer, location); err != nil {
|
||||
return QuestionnaireSpecialization{}, err
|
||||
}
|
||||
answer.Stack = slices.Clone(answer.Stack)
|
||||
if err := validateQuestionnaireStack(answer.Stack, pointer, location); err != nil {
|
||||
return QuestionnaireSpecialization{}, err
|
||||
}
|
||||
if answer.Experience != nil {
|
||||
experience := *answer.Experience
|
||||
if experience.CommercialMonths < 0 || experience.CommercialMonths > maxQuestionnaireExperienceMonth {
|
||||
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/experience/commercial_months", "must be between zero and 600")
|
||||
}
|
||||
if experience.AcademicMonths < 0 || experience.AcademicMonths > maxQuestionnaireExperienceMonth {
|
||||
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/experience/academic_months", "must be between zero and 600")
|
||||
}
|
||||
answer.Experience = &experience
|
||||
}
|
||||
return answer, nil
|
||||
}
|
||||
|
||||
func validateQuestionnaireTaskLanguageInputs(languages []TaskLanguageCode, pointer, location string) error {
|
||||
seen := make(map[TaskLanguageCode]struct{}, len(languages))
|
||||
for index, language := range languages {
|
||||
languagePointer := fmt.Sprintf("%s/task_languages/%d", pointer, index)
|
||||
if !language.IsKnown() {
|
||||
return invalidQuestionnaireField(location, languagePointer, "must be a task language of the catalog")
|
||||
}
|
||||
if _, exists := seen[language]; exists {
|
||||
return invalidQuestionnaireField(location, languagePointer, "must not repeat an earlier item")
|
||||
}
|
||||
seen[language] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateQuestionnaireStack(tags []string, pointer, location string) error {
|
||||
seen := make(map[string]struct{}, len(tags))
|
||||
for index, tag := range tags {
|
||||
tagPointer := fmt.Sprintf("%s/stack/%d", pointer, index)
|
||||
if reason := singleLineTextProblem(tag, maxQuestionnaireStackTagRunes); reason != "" {
|
||||
return invalidQuestionnaireField(location, tagPointer, reason)
|
||||
}
|
||||
key := strings.ToLower(tag)
|
||||
if _, exists := seen[key]; exists {
|
||||
return invalidQuestionnaireField(location, tagPointer, "must not repeat an earlier item")
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateQuestionnaireWorkFormats(formats []QuestionnaireWorkFormat, location string) error {
|
||||
seen := make(map[QuestionnaireWorkFormat]struct{}, len(formats))
|
||||
for index, format := range formats {
|
||||
pointer := fmt.Sprintf("/work_context/work_formats/%d", index)
|
||||
if !format.IsKnown() {
|
||||
return invalidQuestionnaireField(location, pointer, "must be remote, office, or hybrid")
|
||||
}
|
||||
if _, exists := seen[format]; exists {
|
||||
return invalidQuestionnaireField(location, pointer, "must not repeat an earlier item")
|
||||
}
|
||||
seen[format] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateQuestionnaireTaskLanguages(
|
||||
answers []QuestionnaireSpecialization,
|
||||
availability []SpecializationAvailability,
|
||||
location string,
|
||||
) error {
|
||||
allowed := make(map[SpecializationCode]map[TaskLanguageCode]struct{}, len(availability))
|
||||
for _, item := range availability {
|
||||
if !item.Specialization.IsKnown() {
|
||||
return fmt.Errorf("%s - availability contains an unknown specialization: %w", location, ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
languages := make(map[TaskLanguageCode]struct{}, len(item.TaskLanguages))
|
||||
for _, language := range item.TaskLanguages {
|
||||
if !language.IsKnown() {
|
||||
return fmt.Errorf("%s - availability contains an unknown task language: %w", location, ErrInvalidCandidateQuestionnaire)
|
||||
}
|
||||
languages[language] = struct{}{}
|
||||
}
|
||||
allowed[item.Specialization] = languages
|
||||
}
|
||||
for specializationIndex, answer := range answers {
|
||||
for languageIndex, language := range answer.TaskLanguages {
|
||||
if _, exists := allowed[answer.Specialization][language]; !exists {
|
||||
pointer := fmt.Sprintf("/specializations/%d/task_languages/%d", specializationIndex, languageIndex)
|
||||
return invalidQuestionnaireField(location, pointer, "must be offered by the current published bank for this specialization")
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func equalQuestionnaireContent(
|
||||
leftSpecializations []QuestionnaireSpecialization,
|
||||
leftFormats []QuestionnaireWorkFormat,
|
||||
right questionnaireContent,
|
||||
) bool {
|
||||
if !slices.Equal(leftFormats, right.workFormats) || len(leftSpecializations) != len(right.specializations) {
|
||||
return false
|
||||
}
|
||||
for index, left := range leftSpecializations {
|
||||
right := right.specializations[index]
|
||||
if left.Specialization != right.Specialization || left.SelfAssessedGrade != right.SelfAssessedGrade ||
|
||||
!slices.Equal(left.TaskLanguages, right.TaskLanguages) || !slices.Equal(left.Stack, right.Stack) ||
|
||||
!equalQuestionnaireExperience(left.Experience, right.Experience) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func equalQuestionnaireExperience(left, right *QuestionnaireExperience) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == right
|
||||
}
|
||||
return *left == *right
|
||||
}
|
||||
|
||||
func cloneQuestionnaireSpecializations(items []QuestionnaireSpecialization) []QuestionnaireSpecialization {
|
||||
if items == nil {
|
||||
return nil
|
||||
}
|
||||
cloned := make([]QuestionnaireSpecialization, len(items))
|
||||
for index, item := range items {
|
||||
cloned[index] = item
|
||||
cloned[index].TaskLanguages = slices.Clone(item.TaskLanguages)
|
||||
cloned[index].Stack = slices.Clone(item.Stack)
|
||||
if item.Experience != nil {
|
||||
experience := *item.Experience
|
||||
cloned[index].Experience = &experience
|
||||
}
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestCandidateQuestionnaireReplaceValidatesCurrentTaskLanguages(t *testing.T) {
|
||||
id := uuid.Must(uuid.NewV7())
|
||||
questionnaire, err := EmptyCandidateQuestionnaire(id)
|
||||
if err != nil {
|
||||
t.Fatalf("EmptyCandidateQuestionnaire() error = %v", err)
|
||||
}
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
input := validQuestionnaireInput()
|
||||
availability := []SpecializationAvailability{{
|
||||
Specialization: SpecializationBackend,
|
||||
Grades: []GradeCode{GradeJunior},
|
||||
TaskLanguages: []TaskLanguageCode{TaskLanguageGo},
|
||||
}}
|
||||
updated, changed, err := questionnaire.Replace(input, 0, now, availability)
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("Replace(valid) = changed %v, error %v; want changed", changed, err)
|
||||
}
|
||||
if updated.Version() != 0 || !updated.CreatedAt().Equal(now) || !updated.UpdatedAt().Equal(now) {
|
||||
t.Fatalf("updated version/times = %d %s %s, want version 0 and application time", updated.Version(), updated.CreatedAt(), updated.UpdatedAt())
|
||||
}
|
||||
if got := updated.Specializations()[0].SelfAssessedGrade; got != GradeJunior {
|
||||
t.Fatalf("self-assessed grade = %q, want junior", got)
|
||||
}
|
||||
|
||||
badInput := validQuestionnaireInput()
|
||||
badInput.Specializations[0].TaskLanguages = []TaskLanguageCode{TaskLanguagePython}
|
||||
_, _, err = questionnaire.Replace(badInput, 0, now, availability)
|
||||
if !errors.Is(err, ErrInvalidCandidateQuestionnaire) {
|
||||
t.Fatalf("Replace(unoffered language) error = %v, want invalid questionnaire", err)
|
||||
}
|
||||
fieldError, ok := errors.AsType[*CandidateQuestionnaireFieldError](err)
|
||||
if !ok || fieldError.Pointer != "/specializations/0/task_languages/0" || strings.Contains(err.Error(), "python") {
|
||||
t.Fatalf("unoffered language error = %v, want fixed field error without submitted value", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateQuestionnaireAllowsInDevelopmentSpecializationWithoutLanguages(t *testing.T) {
|
||||
questionnaire, err := EmptyCandidateQuestionnaire(uuid.Must(uuid.NewV7()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input := validQuestionnaireInput()
|
||||
input.Specializations[0].Specialization = SpecializationDSML
|
||||
input.Specializations[0].TaskLanguages = nil
|
||||
_, changed, err := questionnaire.Replace(input, 0, time.Now().UTC(), nil)
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("Replace(in-development specialization) = changed %v, error %v; want success with empty languages", changed, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateQuestionnaireNoOpAndVersionConflict(t *testing.T) {
|
||||
id := uuid.Must(uuid.NewV7())
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
stored, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
|
||||
UserID: id, Version: 2, Specializations: validQuestionnaireInput().Specializations,
|
||||
WorkFormats: validQuestionnaireInput().WorkFormats, CreatedAt: now, UpdatedAt: now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreCandidateQuestionnaire() error = %v", err)
|
||||
}
|
||||
input := validQuestionnaireInput()
|
||||
noOp, changed, err := stored.Replace(input, 1, now.Add(time.Hour), nil)
|
||||
if err != nil || changed || noOp.Version() != 2 || !noOp.UpdatedAt().Equal(now) {
|
||||
t.Fatalf("Replace(stale no-op) = changed %v, version %d, time %s, error %v; want unchanged version 2", changed, noOp.Version(), noOp.UpdatedAt(), err)
|
||||
}
|
||||
input.WorkFormats = []QuestionnaireWorkFormat{QuestionnaireWorkFormatOffice}
|
||||
_, _, err = stored.Replace(input, 1, now.Add(time.Hour), nil)
|
||||
if !errors.Is(err, ErrCandidateQuestionnaireVersionConflict) {
|
||||
t.Fatalf("Replace(stale changed) error = %v, want version conflict", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateQuestionnaireSameContentIgnoresVersionAndTimes(t *testing.T) {
|
||||
id := uuid.Must(uuid.NewV7())
|
||||
input := validQuestionnaireInput()
|
||||
firstAt := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
first, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
|
||||
UserID: id, Version: 2, Specializations: input.Specializations,
|
||||
WorkFormats: input.WorkFormats, CreatedAt: firstAt, UpdatedAt: firstAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreCandidateQuestionnaire(first) error = %v", err)
|
||||
}
|
||||
secondAt := firstAt.Add(time.Hour)
|
||||
second, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
|
||||
UserID: id, Version: 3, Specializations: input.Specializations,
|
||||
WorkFormats: input.WorkFormats, CreatedAt: firstAt, UpdatedAt: secondAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreCandidateQuestionnaire(second) error = %v", err)
|
||||
}
|
||||
if !first.SameContent(second) || !second.SameContent(first) {
|
||||
t.Fatal("SameContent() must ignore version and timestamps but require the same user")
|
||||
}
|
||||
|
||||
otherUser, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
|
||||
UserID: uuid.Must(uuid.NewV7()), Version: 3, Specializations: input.Specializations,
|
||||
WorkFormats: input.WorkFormats, CreatedAt: firstAt, UpdatedAt: secondAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreCandidateQuestionnaire(other user) error = %v", err)
|
||||
}
|
||||
if first.SameContent(otherUser) {
|
||||
t.Fatal("SameContent() treated another user's questionnaire as identical")
|
||||
}
|
||||
|
||||
changedInput := input
|
||||
changedInput.Specializations = slices.Clone(input.Specializations)
|
||||
changedInput.Specializations[0].Stack = []string{"gRPC"}
|
||||
changed, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
|
||||
UserID: id, Version: 3, Specializations: changedInput.Specializations,
|
||||
WorkFormats: input.WorkFormats, CreatedAt: firstAt, UpdatedAt: secondAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreCandidateQuestionnaire(changed) error = %v", err)
|
||||
}
|
||||
if first.SameContent(changed) {
|
||||
t.Fatal("SameContent() ignored a changed answer")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateQuestionnaireRejectsDuplicateAndMalformedValues(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*CandidateQuestionnaireInput)
|
||||
pointer string
|
||||
}{
|
||||
{
|
||||
name: "repeated specialization",
|
||||
mutate: func(input *CandidateQuestionnaireInput) {
|
||||
input.Specializations = append(input.Specializations, input.Specializations[0])
|
||||
},
|
||||
pointer: "/specializations/1/specialization",
|
||||
},
|
||||
{
|
||||
name: "case insensitive stack duplicate",
|
||||
mutate: func(input *CandidateQuestionnaireInput) {
|
||||
input.Specializations[0].Stack = []string{"PostgreSQL", "postgresql"}
|
||||
},
|
||||
pointer: "/specializations/0/stack/1",
|
||||
},
|
||||
{
|
||||
name: "experience above bound",
|
||||
mutate: func(input *CandidateQuestionnaireInput) {
|
||||
input.Specializations[0].Experience = &QuestionnaireExperience{CommercialMonths: 601}
|
||||
},
|
||||
pointer: "/specializations/0/experience/commercial_months",
|
||||
},
|
||||
{
|
||||
name: "duplicate work format",
|
||||
mutate: func(input *CandidateQuestionnaireInput) {
|
||||
input.WorkFormats = []QuestionnaireWorkFormat{QuestionnaireWorkFormatRemote, QuestionnaireWorkFormatRemote}
|
||||
},
|
||||
pointer: "/work_context/work_formats/1",
|
||||
},
|
||||
}
|
||||
questionnaire, err := EmptyCandidateQuestionnaire(uuid.Must(uuid.NewV7()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
input := validQuestionnaireInput()
|
||||
test.mutate(&input)
|
||||
_, _, err := questionnaire.Replace(input, 0, time.Now().UTC(), []SpecializationAvailability{{
|
||||
Specialization: SpecializationBackend, TaskLanguages: []TaskLanguageCode{TaskLanguageGo},
|
||||
}})
|
||||
fieldError, ok := errors.AsType[*CandidateQuestionnaireFieldError](err)
|
||||
if !ok || fieldError.Pointer != test.pointer {
|
||||
t.Fatalf("Replace() error = %v, want field pointer %s", err, test.pointer)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateQuestionnaireCopiesSensitiveCollectionsAndRedacts(t *testing.T) {
|
||||
input := validQuestionnaireInput()
|
||||
questionnaire, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
|
||||
UserID: uuid.Must(uuid.NewV7()), Version: 1, Specializations: input.Specializations,
|
||||
WorkFormats: input.WorkFormats, CreatedAt: time.Now().UTC(), UpdatedAt: time.Now().UTC(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreCandidateQuestionnaire() error = %v", err)
|
||||
}
|
||||
items := questionnaire.Specializations()
|
||||
items[0].Stack[0] = "changed"
|
||||
items[0].Experience.CommercialMonths = 0
|
||||
if questionnaire.Specializations()[0].Stack[0] != "PostgreSQL" || questionnaire.Specializations()[0].Experience.CommercialMonths != 12 {
|
||||
t.Fatal("Specializations() exposed mutable internal data")
|
||||
}
|
||||
for _, formatted := range []string{fmt.Sprint(questionnaire), fmt.Sprintf("%+v", input.Specializations[0]), fmt.Sprint(input)} {
|
||||
if strings.Contains(formatted, "PostgreSQL") || strings.Contains(formatted, "12") {
|
||||
t.Fatalf("formatted questionnaire data leaked personal values: %s", formatted)
|
||||
}
|
||||
}
|
||||
for _, typ := range []reflect.Type{
|
||||
reflect.TypeFor[CandidateQuestionnaire](),
|
||||
reflect.TypeFor[QuestionnaireSpecialization](),
|
||||
} {
|
||||
for index := range typ.NumField() {
|
||||
name := strings.ToLower(typ.Field(index).Name)
|
||||
if strings.Contains(name, "confirmed") || name == "category" {
|
||||
t.Errorf("%s has forbidden field %q", typ.Name(), typ.Field(index).Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func validQuestionnaireInput() CandidateQuestionnaireInput {
|
||||
return CandidateQuestionnaireInput{
|
||||
Specializations: []QuestionnaireSpecialization{{
|
||||
Specialization: SpecializationBackend, SelfAssessedGrade: GradeJunior,
|
||||
TaskLanguages: []TaskLanguageCode{TaskLanguageGo}, Stack: []string{"PostgreSQL"},
|
||||
Experience: &QuestionnaireExperience{CommercialMonths: 12, AcademicMonths: 4},
|
||||
}},
|
||||
WorkFormats: []QuestionnaireWorkFormat{QuestionnaireWorkFormatRemote},
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user