package domain import ( "encoding/json" "errors" "fmt" "reflect" "strings" "testing" "time" "github.com/google/uuid" ) func TestNewNeedStartsIncompleteAtVersionOne(t *testing.T) { snapshot := validNeedSnapshot() need, err := NewNeed(snapshot) if err != nil { t.Fatalf("NewNeed() error = %v", err) } if need.Version() != 1 || need.RequirementsVersion() != 1 { t.Fatalf("version pair = %d/%d, want 1/1", need.Version(), need.RequirementsVersion()) } readiness := need.Readiness() wantFields := []NeedMissingFieldName{ NeedMissingSpecialization, NeedMissingGrade, NeedMissingRequiredSkills, NeedMissingWorkFormats, NeedMissingSalary, } gotFields := make([]NeedMissingFieldName, 0, len(readiness.MissingFields)) for _, field := range readiness.MissingFields { gotFields = append(gotFields, field.Field) } if readiness.Status != NeedReadinessIncomplete || !reflect.DeepEqual(gotFields, wantFields) { t.Fatalf("readiness = %+v, want incomplete fields %v", readiness, wantFields) } } func TestNewNeedCanonicalizesTimestampsToStoragePrecision(t *testing.T) { snapshot := validNeedSnapshot() zone := time.FixedZone("test", 3*60*60) snapshot.CreatedAt = time.Date(2026, 10, 7, 15, 0, 0, 123456789, zone) snapshot.UpdatedAt = snapshot.CreatedAt.Add(time.Nanosecond) need, err := NewNeed(snapshot) if err != nil { t.Fatalf("NewNeed() error = %v", err) } want := snapshot.CreatedAt.UTC().Truncate(time.Microsecond) if !need.CreatedAt().Equal(want) || !need.UpdatedAt().Equal(want) || need.CreatedAt().Location() != time.UTC { t.Fatalf("canonical timestamps = %s / %s, want UTC %s", need.CreatedAt(), need.UpdatedAt(), want) } } func TestNeedRejectsTimestampsOutsideContractDateTimeRange(t *testing.T) { snapshot := validNeedSnapshot() snapshot.CreatedAt = time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC) snapshot.UpdatedAt = snapshot.CreatedAt if _, err := NewNeed(snapshot); !errors.Is(err, ErrInvalidNeed) { t.Fatalf("NewNeed(year 10000) error = %v, want ErrInvalidNeed", err) } } func TestNeedReadinessRequiresLocationOnlyForConfirmedOfficeOrHybrid(t *testing.T) { snapshot := validNeedSnapshot() formats := []NeedWorkFormat{NeedWorkFormatRemote} snapshot.Requirements.WorkFormats = confirmedNeedValue(formats, manualNeedSource()) need, err := NewNeed(snapshot) if err != nil { t.Fatalf("NewNeed(remote) error = %v", err) } if containsNeedField(need.Readiness().MissingFields, NeedMissingLocation) { t.Fatal("remote-only need requires a location") } snapshot.Requirements.WorkFormats = confirmedNeedValue([]NeedWorkFormat{NeedWorkFormatOffice}, manualNeedSource()) need, err = NewNeed(snapshot) if err != nil { t.Fatalf("NewNeed(office) error = %v", err) } if !containsNeedField(need.Readiness().MissingFields, NeedMissingLocation) { t.Fatal("confirmed office need is missing its location question") } snapshot.Requirements.WorkFormats = NeedValue[[]NeedWorkFormat]{Status: NeedValueExtracted, Value: needPointer([]NeedWorkFormat{NeedWorkFormatOffice}), Source: textNeedSource(1)} need, err = NewNeed(snapshot) if err != nil { t.Fatalf("NewNeed(extracted office) error = %v", err) } if containsNeedField(need.Readiness().MissingFields, NeedMissingLocation) { t.Fatal("unconfirmed office suggestion cannot make location critical") } } func TestNeedRevisePreservesVersionSemanticsAndNoOpOrder(t *testing.T) { snapshot := validNeedSnapshot() snapshot.Requirements.Specialization = NeedValue[SpecializationCode]{ Status: NeedValueExtracted, Value: needPointer(SpecializationBackend), Source: textNeedSource(1), } current, err := NewNeed(snapshot) if err != nil { t.Fatalf("NewNeed() error = %v", err) } proposal := current.Snapshot() unchanged, changed, err := current.Revise(0, proposal) if err != nil || changed || unchanged.Version() != 1 { t.Fatalf("Revise(stale no-op) = version %d changed %v error %v, want unchanged version 1", unchanged.Version(), changed, err) } proposal.Title = "Payments team" proposal.UpdatedAt = proposal.UpdatedAt.Add(time.Hour) if _, _, err := current.Revise(0, proposal); !errors.Is(err, ErrNeedVersionConflict) { t.Fatalf("Revise(stale edit) error = %v, want version conflict", err) } proposal = current.Snapshot() proposal.Title = "Payments team" proposal.UpdatedAt = proposal.UpdatedAt.Add(time.Hour) titleOnly, changed, err := current.Revise(1, proposal) if err != nil || !changed || titleOnly.Version() != 2 || titleOnly.RequirementsVersion() != 1 { t.Fatalf("Revise(title) = version %d requirements %d changed %v error %v", titleOnly.Version(), titleOnly.RequirementsVersion(), changed, err) } proposal = titleOnly.Snapshot() proposal.UpdatedAt = proposal.UpdatedAt.Add(time.Hour) proposal.Requirements.Specialization.Value = needPointer(SpecializationFrontend) suggestionOnly, changed, err := titleOnly.Revise(2, proposal) if err != nil || !changed || suggestionOnly.Version() != 3 || suggestionOnly.RequirementsVersion() != 1 { t.Fatalf("Revise(suggestion) = version %d requirements %d changed %v error %v", suggestionOnly.Version(), suggestionOnly.RequirementsVersion(), changed, err) } proposal = suggestionOnly.Snapshot() proposal.UpdatedAt = proposal.UpdatedAt.Add(time.Hour) proposal.Requirements.Specialization.Status = NeedValueConfirmed confirmed, changed, err := suggestionOnly.Revise(3, proposal) if err != nil || !changed || confirmed.Version() != 4 || confirmed.RequirementsVersion() != 4 { t.Fatalf("Revise(confirm) = version %d requirements %d changed %v error %v", confirmed.Version(), confirmed.RequirementsVersion(), changed, err) } proposal = confirmed.Snapshot() proposal.UpdatedAt = proposal.UpdatedAt.Add(time.Hour) proposal.Requirements.Specialization = NeedValue[SpecializationCode]{Status: NeedValueUnknown} removed, changed, err := confirmed.Revise(4, proposal) if err != nil || !changed || removed.Version() != 5 || removed.RequirementsVersion() != 5 { t.Fatalf("Revise(remove confirmed) = version %d requirements %d changed %v error %v", removed.Version(), removed.RequirementsVersion(), changed, err) } } func TestNeedIsNextVersionOfRejectsVersionOverflow(t *testing.T) { maximum := int64(^uint64(0) >> 1) snapshot := validNeedSnapshot() snapshot.Version = maximum snapshot.RequirementsVersion = maximum current, err := RestoreNeed(snapshot) if err != nil { t.Fatalf("RestoreNeed(maximum version) error = %v", err) } candidateSnapshot := snapshot candidateSnapshot.Version = 1 candidateSnapshot.RequirementsVersion = 1 candidate, err := RestoreNeed(candidateSnapshot) if err != nil { t.Fatalf("RestoreNeed(candidate) error = %v", err) } if current.IsNextVersionOf(candidate, maximum) { t.Fatal("IsNextVersionOf() accepted an overflowed next version") } } func TestNeedSnapshotIsDefensiveAndRedacted(t *testing.T) { snapshot := validNeedSnapshot() formats := []NeedWorkFormat{NeedWorkFormatRemote} snapshot.Requirements.WorkFormats = NeedValue[[]NeedWorkFormat]{ Status: NeedValueExtracted, Value: &formats, Source: textNeedSource(1), } snapshot.Requirements.RequiredSkills = []NeedSkill{{ Name: "Go", Status: NeedItemExtracted, Source: *textNeedSource(1), }} need, err := NewNeed(snapshot) if err != nil { t.Fatalf("NewNeed() error = %v", err) } copiedSnapshot := need.Snapshot() *copiedSnapshot.SourceText = "changed private text" (*copiedSnapshot.Requirements.WorkFormats.Value)[0] = NeedWorkFormatOffice *copiedSnapshot.Requirements.RequiredSkills[0].Source.Quote = "changed quote" if got := *need.Snapshot().SourceText; got != "internal payments platform" { t.Fatalf("source text changed through snapshot copy: %q", got) } if got := (*need.Snapshot().Requirements.WorkFormats.Value)[0]; got != NeedWorkFormatRemote { t.Fatalf("work format changed through snapshot copy: %q", got) } if got := *need.Snapshot().Requirements.RequiredSkills[0].Source.Quote; got != "Go" { t.Fatalf("quote changed through snapshot copy: %q", got) } for _, printed := range []string{fmt.Sprint(need), fmt.Sprintf("%+v", need), fmt.Sprintf("%#v", snapshot)} { if strings.Contains(printed, "internal payments platform") || strings.Contains(printed, "changed private text") { t.Fatalf("need formatting exposed private text: %q", printed) } } } func TestNeedRejectedSuggestionsArePrivateDefensiveAndBounded(t *testing.T) { snapshot := validNeedSnapshot() snapshot.RejectedSuggestions = []NeedRejectedSuggestion{{Field: NeedRejectedSkills, Value: "postgresql"}} need, err := NewNeed(snapshot) if err != nil { t.Fatalf("NewNeed() error = %v", err) } copied := need.Snapshot() copied.RejectedSuggestions[0].Value = "changed" if got := need.Snapshot().RejectedSuggestions[0].Value; got != "postgresql" { t.Fatalf("suppressed value changed through snapshot copy: %q", got) } if printed := fmt.Sprintf("%+v", need); strings.Contains(printed, "postgresql") { t.Fatalf("need formatting exposed a suppressed suggestion: %q", printed) } tests := []struct { name string suggestions []NeedRejectedSuggestion }{ {name: "unknown field", suggestions: []NeedRejectedSuggestion{{Field: "role", Value: "owner"}}}, {name: "empty value", suggestions: []NeedRejectedSuggestion{{Field: NeedRejectedSkills}}}, {name: "not normalized", suggestions: []NeedRejectedSuggestion{{Field: NeedRejectedSkills, Value: "PostgreSQL"}}}, {name: "duplicate", suggestions: []NeedRejectedSuggestion{ {Field: NeedRejectedSkills, Value: "postgresql"}, {Field: NeedRejectedSkills, Value: "postgresql"}, }}, {name: "too many", suggestions: tooManyNeedRejectedSuggestions()}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { invalid := validNeedSnapshot() invalid.RejectedSuggestions = test.suggestions if _, err := NewNeed(invalid); !errors.Is(err, ErrInvalidNeed) { t.Fatalf("NewNeed() error = %v, want ErrInvalidNeed", err) } }) } } func TestNeedRejectsSnapshotThatExceedsSerializedStorageBound(t *testing.T) { snapshot := validNeedSnapshot() controlText := strings.Repeat("\x01", maxNeedSourceTextRunes) snapshot.SourceText = &controlText snapshot.RejectedSuggestions = make([]NeedRejectedSuggestion, MaxNeedRejectedSuggestions) for index := range snapshot.RejectedSuggestions { value := strings.Repeat("\x01", maxNeedTaskRunes-3) + fmt.Sprintf("%03d", index) snapshot.RejectedSuggestions[index] = NeedRejectedSuggestion{Field: NeedRejectedTasks, Value: value} } for index := 0; index < maxNeedSkillItems; index++ { quote := strings.Repeat("\x01", maxNeedQuoteRunes) snapshot.Requirements.RequiredSkills = append(snapshot.Requirements.RequiredSkills, NeedSkill{ Name: fmt.Sprintf("skill-%02d", index), Status: NeedItemExtracted, Source: NeedValueSource{Origin: NeedValueExtractedFromText, Quote: "e, ExtractedInVersion: needPointer(int64(1)), ExtractionVersion: needPointer("rules.1")}, }) } for index := 0; index < maxNeedSkillItems; index++ { quote := strings.Repeat("\x01", maxNeedQuoteRunes) snapshot.Requirements.DesiredSkills = append(snapshot.Requirements.DesiredSkills, NeedSkill{ Name: fmt.Sprintf("other-%02d", index), Status: NeedItemExtracted, Source: NeedValueSource{Origin: NeedValueExtractedFromText, Quote: "e, ExtractedInVersion: needPointer(int64(1)), ExtractionVersion: needPointer("rules.1")}, }) } _, err := NewNeed(snapshot) if !errors.Is(err, ErrInvalidNeed) || !strings.Contains(fmt.Sprint(err), "/rejected_suggestions") { t.Fatalf("NewNeed(oversized snapshot) error = %v, want bounded snapshot validation error", err) } } func TestRestoreNeedAcceptsLegacySnapshotWithoutRejectedSuggestions(t *testing.T) { encoded, err := json.Marshal(validNeedSnapshot()) if err != nil { t.Fatalf("marshal snapshot: %v", err) } var fields map[string]json.RawMessage if err := json.Unmarshal(encoded, &fields); err != nil { t.Fatalf("decode snapshot fields: %v", err) } delete(fields, "rejected_suggestions") legacy, err := json.Marshal(fields) if err != nil { t.Fatalf("marshal legacy snapshot: %v", err) } var snapshot NeedSnapshot if err := json.Unmarshal(legacy, &snapshot); err != nil { t.Fatalf("decode legacy snapshot: %v", err) } need, err := RestoreNeed(snapshot) if err != nil { t.Fatalf("RestoreNeed(legacy) error = %v", err) } if got := need.Snapshot().RejectedSuggestions; got == nil || len(got) != 0 { t.Fatalf("legacy rejected suggestions = %#v, want an empty list", got) } } func TestNeedRestoresContractProvenanceAndRejectsInvalidValues(t *testing.T) { tests := []struct { name string change func(*NeedSnapshot) }{ {name: "unknown has a value", change: func(snapshot *NeedSnapshot) { snapshot.Requirements.Specialization.Value = needPointer(SpecializationBackend) }}, {name: "manual suggestion", change: func(snapshot *NeedSnapshot) { snapshot.Requirements.Grade = NeedValue[GradeCode]{Status: NeedValueExtracted, Value: needPointer(GradeJunior), Source: manualNeedSource()} }}, {name: "future quote version", change: func(snapshot *NeedSnapshot) { snapshot.Requirements.Domain = NeedValue[string]{Status: NeedValueExtracted, Value: needPointer("payments"), Source: textNeedSource(2)} }}, {name: "duplicate skills across lists", change: func(snapshot *NeedSnapshot) { source := manualNeedSource() snapshot.Requirements.RequiredSkills = []NeedSkill{{Name: "Go", Status: NeedItemConfirmed, Source: *source}} snapshot.Requirements.DesiredSkills = []NeedSkill{{Name: "go", Status: NeedItemConfirmed, Source: *source}} }}, {name: "invalid salary width", change: func(snapshot *NeedSnapshot) { snapshot.Requirements.Salary = confirmedNeedValue(NeedSalaryRange{SalaryFrom: 100000, SalaryTo: 109000, Currency: "RUB", Period: "month", TaxBasis: "gross"}, manualNeedSource()) }}, {name: "work formats not unique", change: func(snapshot *NeedSnapshot) { snapshot.Requirements.WorkFormats = confirmedNeedValue([]NeedWorkFormat{NeedWorkFormatRemote, NeedWorkFormatRemote}, manualNeedSource()) }}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { snapshot := validNeedSnapshot() test.change(&snapshot) if _, err := NewNeed(snapshot); !errors.Is(err, ErrInvalidNeed) { t.Fatalf("NewNeed(invalid) error = %v, want invalid need", err) } }) } } func TestNeedRejectsInvalidUTF8InContractText(t *testing.T) { invalid := string([]byte{0xff}) nul := "role\x00name" tests := []struct { name string change func(*NeedSnapshot) }{ {name: "title", change: func(snapshot *NeedSnapshot) { snapshot.Title = invalid }}, {name: "source text", change: func(snapshot *NeedSnapshot) { snapshot.SourceText = &invalid }}, {name: "title with NUL", change: func(snapshot *NeedSnapshot) { snapshot.Title = nul }}, {name: "source text with NUL", change: func(snapshot *NeedSnapshot) { snapshot.SourceText = &nul }}, {name: "provenance quote", change: func(snapshot *NeedSnapshot) { snapshot.Requirements.Specialization = NeedValue[SpecializationCode]{ Status: NeedValueExtracted, Value: needPointer(SpecializationBackend), Source: textNeedSource(1), } snapshot.Requirements.Specialization.Source.Quote = &invalid }}, {name: "skill name with NUL", change: func(snapshot *NeedSnapshot) { snapshot.Requirements.RequiredSkills = []NeedSkill{{Name: nul, Status: NeedItemConfirmed, Source: *manualNeedSource()}} }}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { snapshot := validNeedSnapshot() test.change(&snapshot) if _, err := NewNeed(snapshot); !errors.Is(err, ErrInvalidNeed) { t.Fatalf("NewNeed() error = %v, want ErrInvalidNeed", err) } }) } } func TestNeedSalaryAcceptsContractBoundaries(t *testing.T) { for _, test := range []struct { from int64 to int64 }{ {from: 95000, to: 105000}, {from: 80000, to: 120000}, } { snapshot := validNeedSnapshot() snapshot.Requirements.Salary = confirmedNeedValue(NeedSalaryRange{ SalaryFrom: test.from, SalaryTo: test.to, Currency: "RUB", Period: "month", TaxBasis: "net", }, manualNeedSource()) if _, err := NewNeed(snapshot); err != nil { t.Fatalf("NewNeed(salary %d-%d) error = %v", test.from, test.to, err) } } } func TestNeedValueSourceManualAndTextRules(t *testing.T) { manual := manualNeedSource() if err := validateNeedValueSource("test", 1, "/source", NeedValueConfirmed, *manual); err != nil { t.Fatalf("validate manual source error = %v", err) } text := textNeedSource(1) if err := validateNeedValueSource("test", 1, "/source", NeedValueExtracted, *text); err != nil { t.Fatalf("validate text suggestion source error = %v", err) } } func TestNeedReadinessOnlyCountsConfirmedRequirements(t *testing.T) { snapshot := validNeedSnapshot() snapshot.Requirements.Specialization = NeedValue[SpecializationCode]{ Status: NeedValueExtracted, Value: needPointer(SpecializationBackend), Source: textNeedSource(1), } need, err := NewNeed(snapshot) if err != nil { t.Fatalf("NewNeed() error = %v", err) } readiness := need.Readiness() if readiness.MissingFields[0].Field != NeedMissingSpecialization || readiness.MissingFields[0].Reason != NeedMissingUnconfirmed || readiness.MissingFields[0].Question != "Подтвердите специализацию, найденную в описании." { t.Fatalf("specialization readiness = %+v", readiness.MissingFields[0]) } snapshot = validNeedSnapshot() snapshot.Requirements.Specialization = NeedValue[SpecializationCode]{ Status: NeedValueExtracted, Value: needPointer(SpecializationBackend), Source: textNeedSource(1), } snapshot.Requirements.RequiredSkills = []NeedSkill{{Name: "Go", Status: NeedItemExtracted, Source: *textNeedSource(1)}} snapshot.Requirements.WorkFormats = NeedValue[[]NeedWorkFormat]{ Status: NeedValueExtracted, Value: needPointer([]NeedWorkFormat{NeedWorkFormatRemote}), Source: textNeedSource(1), } snapshot.Requirements.Salary = NeedValue[NeedSalaryRange]{ Status: NeedValueExtracted, Value: needPointer(NeedSalaryRange{SalaryFrom: 80000, SalaryTo: 120000, Currency: "RUB", Period: "month", TaxBasis: "gross"}), Source: textNeedSource(1), } need, err = NewNeed(snapshot) if err != nil { t.Fatalf("NewNeed(extracted criticals) error = %v", err) } readiness = need.Readiness() for _, field := range readiness.MissingFields { if field.Field == NeedMissingSpecialization || field.Field == NeedMissingRequiredSkills || field.Field == NeedMissingWorkFormats || field.Field == NeedMissingSalary { if field.Reason != NeedMissingUnconfirmed { t.Errorf("field %s reason = %s, want unconfirmed", field.Field, field.Reason) } } } } func validNeedSnapshot() NeedSnapshot { now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) sourceText := "internal payments platform" return NeedSnapshot{ ID: uuid.Must(uuid.NewV7()), OrganizationID: uuid.Must(uuid.NewV7()), Title: "Backend payments", SourceText: &sourceText, Version: 1, RequirementsVersion: 1, Requirements: EmptyNeedRequirements(), CreatedAt: now, UpdatedAt: now, } } func manualNeedSource() *NeedValueSource { return &NeedValueSource{Origin: NeedValueManual} } func textNeedSource(version int64) *NeedValueSource { quote := "Go" extractor := "need-rules.2026-10.1" return &NeedValueSource{ Origin: NeedValueExtractedFromText, Quote: "e, ExtractedInVersion: &version, ExtractionVersion: &extractor, } } func confirmedNeedValue[T any](value T, source *NeedValueSource) NeedValue[T] { return NeedValue[T]{Status: NeedValueConfirmed, Value: &value, Source: source} } func needPointer[T any](value T) *T { return &value } func tooManyNeedRejectedSuggestions() []NeedRejectedSuggestion { suggestions := make([]NeedRejectedSuggestion, MaxNeedRejectedSuggestions+1) for index := range suggestions { suggestions[index] = NeedRejectedSuggestion{Field: NeedRejectedTasks, Value: fmt.Sprintf("task-%d", index)} } return suggestions } func containsNeedField(fields []NeedMissingField, field NeedMissingFieldName) bool { for _, candidate := range fields { if candidate.Field == field { return true } } return false }