feat: add assessment, privacy and support flows
This commit is contained in:
1 parent
ee3738ee73
commit
e4f24fa202
339 files changed
+56454
-1126
No files matched your search
@@ -0,0 +1,11 @@
|
||||
package need
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrForbidden = errors.New("organization need operation forbidden")
|
||||
ErrEmailNotVerified = errors.New("organization need requires a confirmed email")
|
||||
ErrIdempotencyKeyReused = errors.New("idempotency key reused with a different request")
|
||||
ErrInvalidIdempotencyKey = errors.New("invalid idempotency key")
|
||||
ErrInvalidCreateRequest = errors.New("invalid organization need create request")
|
||||
)
|
||||
@@ -0,0 +1,841 @@
|
||||
package need
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
var ErrInvalidRequest = errors.New("invalid organization need request")
|
||||
|
||||
// ValidationError identifies the contract field that rejected a need request.
|
||||
type ValidationError struct {
|
||||
Pointer string
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (validation *ValidationError) Error() string {
|
||||
return fmt.Sprintf("need request field %s: %s", validation.Pointer, validation.Reason)
|
||||
}
|
||||
|
||||
func (validation *ValidationError) Unwrap() error { return ErrInvalidRequest }
|
||||
|
||||
// Field distinguishes a missing property from a property explicitly set to null.
|
||||
type Field[T any] struct {
|
||||
Set bool
|
||||
Null bool
|
||||
Value T
|
||||
}
|
||||
|
||||
// Decision is an explicit value and confirmation state sent by an owner.
|
||||
type Decision[T any] struct {
|
||||
Value T
|
||||
Status domain.NeedValueStatus
|
||||
}
|
||||
|
||||
type SkillInput struct {
|
||||
Name string
|
||||
Status domain.NeedItemStatus
|
||||
}
|
||||
|
||||
type TaskInput struct {
|
||||
Text string
|
||||
Status domain.NeedItemStatus
|
||||
}
|
||||
|
||||
// CreateInput preserves request presence so absent fields may use source text
|
||||
// while explicit nulls and empty lists suppress extraction for that field.
|
||||
type CreateInput struct {
|
||||
Title string
|
||||
VacancyID Field[uuid.UUID]
|
||||
SourceText Field[string]
|
||||
Specialization Field[Decision[domain.SpecializationCode]]
|
||||
Grade Field[Decision[domain.GradeCode]]
|
||||
RequiredSkills []SkillInput
|
||||
DesiredSkills []SkillInput
|
||||
Tasks []TaskInput
|
||||
Domain Field[Decision[string]]
|
||||
WorkFormats Field[Decision[[]domain.NeedWorkFormat]]
|
||||
Location Field[Decision[string]]
|
||||
Salary Field[Decision[domain.NeedSalaryRange]]
|
||||
}
|
||||
|
||||
// UpdateInput is a full replacement for every field it sets. Nil lists mean
|
||||
// absent; non-nil empty lists explicitly delete all items in that list.
|
||||
type UpdateInput struct {
|
||||
ExpectedVersion int64
|
||||
Title Field[string]
|
||||
VacancyID Field[uuid.UUID]
|
||||
SourceText Field[string]
|
||||
Specialization Field[Decision[domain.SpecializationCode]]
|
||||
Grade Field[Decision[domain.GradeCode]]
|
||||
RequiredSkills []SkillInput
|
||||
DesiredSkills []SkillInput
|
||||
Tasks []TaskInput
|
||||
Domain Field[Decision[string]]
|
||||
WorkFormats Field[Decision[[]domain.NeedWorkFormat]]
|
||||
Location Field[Decision[string]]
|
||||
Salary Field[Decision[domain.NeedSalaryRange]]
|
||||
}
|
||||
|
||||
func createNeed(input CreateInput, organizationID, needID uuid.UUID, now time.Time) (domain.Need, error) {
|
||||
const location = "need.createNeed"
|
||||
if organizationID == uuid.Nil || needID == uuid.Nil || now.IsZero() {
|
||||
return domain.Need{}, fmt.Errorf("%s - organization, need, and application time must be set: %w", location, ErrInvalidRequest)
|
||||
}
|
||||
if input.VacancyID.Set && !input.VacancyID.Null {
|
||||
return domain.Need{}, invalidRequest("/vacancy_id", "vacancies are not available")
|
||||
}
|
||||
sourceText, sourceProvided, err := createSourceText(input.SourceText)
|
||||
if err != nil {
|
||||
return domain.Need{}, err
|
||||
}
|
||||
requirements, err := createNeedRequirements(input, sourceText, sourceProvided)
|
||||
if err != nil {
|
||||
return domain.Need{}, err
|
||||
}
|
||||
snapshot := domain.NeedSnapshot{
|
||||
ID: needID, OrganizationID: organizationID, Title: input.Title,
|
||||
SourceText: sourceText, Version: 1, RequirementsVersion: 1,
|
||||
Requirements: requirements, RejectedSuggestions: []domain.NeedRejectedSuggestion{},
|
||||
CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
created, err := domain.NewNeed(snapshot)
|
||||
if err != nil {
|
||||
return domain.Need{}, mapDomainValidation(err)
|
||||
}
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func createNeedRequirements(input CreateInput, sourceText *string, sourceProvided bool) (domain.NeedRequirements, error) {
|
||||
requirements := domain.EmptyNeedRequirements()
|
||||
if sourceProvided {
|
||||
requirements = parseSourceText(*sourceText, 1)
|
||||
}
|
||||
if err := applyCreateScalars(&requirements, input); err != nil {
|
||||
return domain.NeedRequirements{}, err
|
||||
}
|
||||
if input.RequiredSkills != nil {
|
||||
created, err := createSkills(input.RequiredSkills, "/required_skills")
|
||||
if err != nil {
|
||||
return domain.NeedRequirements{}, err
|
||||
}
|
||||
requirements.RequiredSkills = created
|
||||
}
|
||||
if input.DesiredSkills != nil {
|
||||
created, err := createSkills(input.DesiredSkills, "/desired_skills")
|
||||
if err != nil {
|
||||
return domain.NeedRequirements{}, err
|
||||
}
|
||||
requirements.DesiredSkills = created
|
||||
}
|
||||
if input.Tasks != nil {
|
||||
created, err := createTasks(input.Tasks, "/tasks")
|
||||
if err != nil {
|
||||
return domain.NeedRequirements{}, err
|
||||
}
|
||||
requirements.Tasks = created
|
||||
}
|
||||
removeExtractedSkillsShadowedByConfirmed(&requirements)
|
||||
if err := validateSkillUniqueness(requirements); err != nil {
|
||||
return domain.NeedRequirements{}, err
|
||||
}
|
||||
return requirements, nil
|
||||
}
|
||||
|
||||
func createSourceText(field Field[string]) (*string, bool, error) {
|
||||
if !field.Set || field.Null {
|
||||
return nil, false, nil
|
||||
}
|
||||
if field.Value == "" {
|
||||
return nil, false, invalidRequest("/source_text", "must contain text or be null")
|
||||
}
|
||||
value := field.Value
|
||||
return &value, true, nil
|
||||
}
|
||||
|
||||
func applyCreateScalars(requirements *domain.NeedRequirements, input CreateInput) error {
|
||||
var err error
|
||||
if requirements.Specialization, err = createScalar(input.Specialization, requirements.Specialization, "/specialization"); err != nil {
|
||||
return err
|
||||
}
|
||||
if requirements.Grade, err = createScalar(input.Grade, requirements.Grade, "/grade"); err != nil {
|
||||
return err
|
||||
}
|
||||
if requirements.Domain, err = createScalar(input.Domain, requirements.Domain, "/domain"); err != nil {
|
||||
return err
|
||||
}
|
||||
if requirements.WorkFormats, err = createScalar(input.WorkFormats, requirements.WorkFormats, "/work_formats"); err != nil {
|
||||
return err
|
||||
}
|
||||
if requirements.Location, err = createScalar(input.Location, requirements.Location, "/location"); err != nil {
|
||||
return err
|
||||
}
|
||||
if requirements.Salary, err = createScalar(input.Salary, requirements.Salary, "/salary"); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func createScalar[T any](field Field[Decision[T]], parsed domain.NeedValue[T], pointer string) (domain.NeedValue[T], error) {
|
||||
if !field.Set {
|
||||
return parsed, nil
|
||||
}
|
||||
if field.Null {
|
||||
return unknownNeedValue[T](), nil
|
||||
}
|
||||
if field.Value.Status != domain.NeedValueConfirmed {
|
||||
return domain.NeedValue[T]{}, invalidRequest(pointer+"/status", "a new need requires confirmed values")
|
||||
}
|
||||
return confirmedNeedValue(field.Value.Value, manualNeedSource()), nil
|
||||
}
|
||||
|
||||
func createSkills(inputs []SkillInput, pointer string) ([]domain.NeedSkill, error) {
|
||||
result := make([]domain.NeedSkill, 0, len(inputs))
|
||||
for index, input := range inputs {
|
||||
itemPointer := fmt.Sprintf("%s/%d", pointer, index)
|
||||
if input.Status != domain.NeedItemConfirmed {
|
||||
return nil, invalidRequest(itemPointer+"/status", "a new need requires confirmed items")
|
||||
}
|
||||
result = append(result, domain.NeedSkill{
|
||||
Name: input.Name, TaxonomyCode: taxonomyForSkillName(input.Name), Status: domain.NeedItemConfirmed,
|
||||
Source: *manualNeedSource(),
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func createTasks(inputs []TaskInput, pointer string) ([]domain.NeedTask, error) {
|
||||
result := make([]domain.NeedTask, 0, len(inputs))
|
||||
for index, input := range inputs {
|
||||
if input.Status != domain.NeedItemConfirmed {
|
||||
return nil, invalidRequest(fmt.Sprintf("%s/%d/status", pointer, index), "a new need requires confirmed items")
|
||||
}
|
||||
result = append(result, domain.NeedTask{Text: input.Text, Status: domain.NeedItemConfirmed, Source: *manualNeedSource()})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func reviseNeed(current domain.Need, input UpdateInput, now time.Time) (domain.Need, bool, error) {
|
||||
const location = "need.reviseNeed"
|
||||
if current.IsZero() || now.IsZero() {
|
||||
return domain.Need{}, false, fmt.Errorf("%s - current need and application time must be set: %w", location, ErrInvalidRequest)
|
||||
}
|
||||
if input.ExpectedVersion < 1 {
|
||||
return domain.Need{}, false, invalidRequest("/expected_version", "must be positive")
|
||||
}
|
||||
snapshot := current.Snapshot()
|
||||
if err := applyNeedUpdate(current, &snapshot, input); err != nil {
|
||||
return domain.Need{}, false, err
|
||||
}
|
||||
snapshot.UpdatedAt = now
|
||||
return current.Revise(input.ExpectedVersion, snapshot)
|
||||
}
|
||||
|
||||
func applyNeedUpdate(current domain.Need, snapshot *domain.NeedSnapshot, input UpdateInput) error {
|
||||
if input.Title.Set {
|
||||
if input.Title.Null {
|
||||
return stalePatchError(current, input.ExpectedVersion, invalidRequest("/title", "cannot be null"))
|
||||
}
|
||||
snapshot.Title = input.Title.Value
|
||||
}
|
||||
if input.VacancyID.Set {
|
||||
if !input.VacancyID.Null {
|
||||
return stalePatchError(current, input.ExpectedVersion, invalidRequest("/vacancy_id", "vacancies are not available"))
|
||||
}
|
||||
snapshot.VacancyID = nil
|
||||
}
|
||||
newSourceText, sourceChanged, sourceErr := updateSourceText(input.SourceText, snapshot.SourceText)
|
||||
if sourceErr != nil {
|
||||
return stalePatchError(current, input.ExpectedVersion, sourceErr)
|
||||
}
|
||||
snapshot.SourceText = newSourceText
|
||||
requirements := snapshot.Requirements
|
||||
if err := applyExplicitScalars(snapshot, &requirements, input); err != nil {
|
||||
return stalePatchError(current, input.ExpectedVersion, err)
|
||||
}
|
||||
if err := applyExplicitLists(snapshot, &requirements, input); err != nil {
|
||||
return stalePatchError(current, input.ExpectedVersion, err)
|
||||
}
|
||||
if sourceChanged {
|
||||
parsed := parseSourceText(*snapshot.SourceText, current.Version()+1)
|
||||
reparseScalars(snapshot, &requirements, parsed, input)
|
||||
reparseLists(snapshot, &requirements, parsed, current.Snapshot().Requirements, input)
|
||||
}
|
||||
if err := validateSkillUniqueness(requirements); err != nil {
|
||||
return stalePatchError(current, input.ExpectedVersion, err)
|
||||
}
|
||||
snapshot.Requirements = requirements
|
||||
return nil
|
||||
}
|
||||
|
||||
func stalePatchError(current domain.Need, expectedVersion int64, err error) error {
|
||||
if expectedVersion != current.Version() {
|
||||
return domain.ErrNeedVersionConflict
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func updateSourceText(field Field[string], current *string) (*string, bool, error) {
|
||||
if !field.Set {
|
||||
return cloneString(current), false, nil
|
||||
}
|
||||
if field.Null {
|
||||
return nil, false, nil
|
||||
}
|
||||
if field.Value == "" {
|
||||
return nil, false, invalidRequest("/source_text", "must contain text or be null")
|
||||
}
|
||||
value := field.Value
|
||||
changed := current == nil || *current != value
|
||||
return &value, changed, nil
|
||||
}
|
||||
|
||||
func applyExplicitScalars(snapshot *domain.NeedSnapshot, requirements *domain.NeedRequirements, input UpdateInput) error {
|
||||
if err := applyScalarPatch(snapshot, &requirements.Specialization, input.Specialization, domain.NeedRejectedSpecialization, "/specialization", scalarString[domain.SpecializationCode]); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := applyScalarPatch(snapshot, &requirements.Grade, input.Grade, domain.NeedRejectedGrade, "/grade", scalarString[domain.GradeCode]); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := applyScalarPatch(snapshot, &requirements.Domain, input.Domain, domain.NeedRejectedDomain, "/domain", scalarString[string]); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := applyScalarPatch(snapshot, &requirements.WorkFormats, input.WorkFormats, domain.NeedRejectedWorkFormats, "/work_formats", scalarWorkFormats); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := applyScalarPatch(snapshot, &requirements.Location, input.Location, domain.NeedRejectedLocation, "/location", scalarString[string]); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := applyScalarPatch(snapshot, &requirements.Salary, input.Salary, domain.NeedRejectedSalary, "/salary", scalarSalary); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyScalarPatch[T any](
|
||||
snapshot *domain.NeedSnapshot,
|
||||
current *domain.NeedValue[T],
|
||||
field Field[Decision[T]],
|
||||
rejectedField domain.NeedRejectedSuggestionField,
|
||||
pointer string,
|
||||
canonical func(T) []string,
|
||||
) error {
|
||||
if !field.Set {
|
||||
return nil
|
||||
}
|
||||
if field.Null {
|
||||
if err := rejectExtractedScalar(snapshot, rejectedField, *current, canonical, pointer); err != nil {
|
||||
return err
|
||||
}
|
||||
*current = unknownNeedValue[T]()
|
||||
return nil
|
||||
}
|
||||
decision := field.Value
|
||||
switch decision.Status {
|
||||
case domain.NeedValueUnknown:
|
||||
return invalidRequest(pointer+"/status", "must be confirmed or extracted")
|
||||
case domain.NeedValueExtracted:
|
||||
if current.Status != domain.NeedValueExtracted || current.Value == nil || !reflect.DeepEqual(*current.Value, decision.Value) {
|
||||
return invalidRequest(pointer+"/status", "extracted is allowed only for the stored suggestion")
|
||||
}
|
||||
return nil
|
||||
case domain.NeedValueConfirmed:
|
||||
if current.Value != nil && reflect.DeepEqual(*current.Value, decision.Value) {
|
||||
current.Status = domain.NeedValueConfirmed
|
||||
return nil
|
||||
}
|
||||
if err := rejectExtractedScalar(snapshot, rejectedField, *current, canonical, pointer); err != nil {
|
||||
return err
|
||||
}
|
||||
*current = confirmedNeedValue(decision.Value, manualNeedSource())
|
||||
return nil
|
||||
default:
|
||||
return invalidRequest(pointer+"/status", "must be confirmed or extracted")
|
||||
}
|
||||
}
|
||||
|
||||
func rejectExtractedScalar[T any](
|
||||
snapshot *domain.NeedSnapshot,
|
||||
field domain.NeedRejectedSuggestionField,
|
||||
value domain.NeedValue[T],
|
||||
canonical func(T) []string,
|
||||
pointer string,
|
||||
) error {
|
||||
if value.Status != domain.NeedValueExtracted || value.Value == nil {
|
||||
return nil
|
||||
}
|
||||
for _, candidate := range canonical(*value.Value) {
|
||||
if err := addRejectedSuggestion(snapshot, field, candidate, pointer); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func reparseScalars(snapshot *domain.NeedSnapshot, requirements *domain.NeedRequirements, parsed domain.NeedRequirements, input UpdateInput) {
|
||||
if !input.Specialization.Set && requirements.Specialization.Status != domain.NeedValueConfirmed {
|
||||
requirements.Specialization = filterRejectedScalar(snapshot, domain.NeedRejectedSpecialization, parsed.Specialization, scalarString[domain.SpecializationCode])
|
||||
}
|
||||
if !input.Grade.Set && requirements.Grade.Status != domain.NeedValueConfirmed {
|
||||
requirements.Grade = filterRejectedScalar(snapshot, domain.NeedRejectedGrade, parsed.Grade, scalarString[domain.GradeCode])
|
||||
}
|
||||
if !input.Domain.Set && requirements.Domain.Status != domain.NeedValueConfirmed {
|
||||
requirements.Domain = filterRejectedScalar(snapshot, domain.NeedRejectedDomain, parsed.Domain, scalarString[string])
|
||||
}
|
||||
if !input.WorkFormats.Set && requirements.WorkFormats.Status != domain.NeedValueConfirmed {
|
||||
requirements.WorkFormats = filterRejectedWorkFormats(snapshot, parsed.WorkFormats)
|
||||
}
|
||||
if !input.Location.Set && requirements.Location.Status != domain.NeedValueConfirmed {
|
||||
requirements.Location = filterRejectedScalar(snapshot, domain.NeedRejectedLocation, parsed.Location, scalarString[string])
|
||||
}
|
||||
if !input.Salary.Set && requirements.Salary.Status != domain.NeedValueConfirmed {
|
||||
requirements.Salary = filterRejectedScalar(snapshot, domain.NeedRejectedSalary, parsed.Salary, scalarSalary)
|
||||
}
|
||||
}
|
||||
|
||||
func filterRejectedWorkFormats(snapshot *domain.NeedSnapshot, value domain.NeedValue[[]domain.NeedWorkFormat]) domain.NeedValue[[]domain.NeedWorkFormat] {
|
||||
if value.Status != domain.NeedValueExtracted || value.Value == nil {
|
||||
return value
|
||||
}
|
||||
filtered := make([]domain.NeedWorkFormat, 0, len(*value.Value))
|
||||
for _, format := range *value.Value {
|
||||
if !isRejected(snapshot.RejectedSuggestions, domain.NeedRejectedWorkFormats, string(format)) {
|
||||
filtered = append(filtered, format)
|
||||
}
|
||||
}
|
||||
if len(filtered) == 0 {
|
||||
return unknownNeedValue[[]domain.NeedWorkFormat]()
|
||||
}
|
||||
value.Value = &filtered
|
||||
return value
|
||||
}
|
||||
|
||||
func filterRejectedScalar[T any](
|
||||
snapshot *domain.NeedSnapshot,
|
||||
field domain.NeedRejectedSuggestionField,
|
||||
value domain.NeedValue[T],
|
||||
canonical func(T) []string,
|
||||
) domain.NeedValue[T] {
|
||||
if value.Status != domain.NeedValueExtracted || value.Value == nil {
|
||||
return value
|
||||
}
|
||||
for _, candidate := range canonical(*value.Value) {
|
||||
if isRejected(snapshot.RejectedSuggestions, field, candidate) {
|
||||
return unknownNeedValue[T]()
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func applyExplicitLists(snapshot *domain.NeedSnapshot, requirements *domain.NeedRequirements, input UpdateInput) error {
|
||||
if err := rejectRemovedSkillSuggestions(snapshot, *requirements, input); err != nil {
|
||||
return err
|
||||
}
|
||||
oldSkills := append(append([]domain.NeedSkill(nil), requirements.RequiredSkills...), requirements.DesiredSkills...)
|
||||
if err := replaceExplicitSkillList(&requirements.RequiredSkills, input.RequiredSkills, oldSkills, "/required_skills"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := replaceExplicitSkillList(&requirements.DesiredSkills, input.DesiredSkills, oldSkills, "/desired_skills"); err != nil {
|
||||
return err
|
||||
}
|
||||
return replaceExplicitTaskList(snapshot, requirements, input.Tasks)
|
||||
}
|
||||
|
||||
func rejectRemovedSkillSuggestions(snapshot *domain.NeedSnapshot, requirements domain.NeedRequirements, input UpdateInput) error {
|
||||
if input.RequiredSkills == nil && input.DesiredSkills == nil {
|
||||
return nil
|
||||
}
|
||||
requested := append(append([]SkillInput(nil), input.RequiredSkills...), input.DesiredSkills...)
|
||||
groups := []struct {
|
||||
items []domain.NeedSkill
|
||||
present bool
|
||||
pointer string
|
||||
}{
|
||||
{items: requirements.RequiredSkills, present: input.RequiredSkills != nil, pointer: "/required_skills"},
|
||||
{items: requirements.DesiredSkills, present: input.DesiredSkills != nil, pointer: "/desired_skills"},
|
||||
}
|
||||
for _, group := range groups {
|
||||
for _, old := range group.items {
|
||||
if !group.present || old.Status != domain.NeedItemExtracted || skillInputIndex(requested, old.Name) >= 0 {
|
||||
continue
|
||||
}
|
||||
if err := addRejectedSuggestion(snapshot, domain.NeedRejectedSkills, old.Name, group.pointer); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func replaceExplicitSkillList(target *[]domain.NeedSkill, inputs []SkillInput, old []domain.NeedSkill, pointer string) error {
|
||||
if inputs == nil {
|
||||
return nil
|
||||
}
|
||||
updated, err := replaceSkills(inputs, old, pointer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*target = updated
|
||||
return nil
|
||||
}
|
||||
|
||||
func replaceExplicitTaskList(snapshot *domain.NeedSnapshot, requirements *domain.NeedRequirements, inputs []TaskInput) error {
|
||||
if inputs == nil {
|
||||
return nil
|
||||
}
|
||||
for _, old := range requirements.Tasks {
|
||||
if old.Status != domain.NeedItemExtracted || taskInputIndex(inputs, old.Text) >= 0 {
|
||||
continue
|
||||
}
|
||||
if err := addRejectedSuggestion(snapshot, domain.NeedRejectedTasks, old.Text, "/tasks"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
updated, err := replaceTasks(inputs, requirements.Tasks)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
requirements.Tasks = updated
|
||||
return nil
|
||||
}
|
||||
|
||||
func removeExtractedSkillsShadowedByConfirmed(requirements *domain.NeedRequirements) {
|
||||
confirmed := confirmedSkillNames(requirements.RequiredSkills, requirements.DesiredSkills)
|
||||
filter := func(skills []domain.NeedSkill) []domain.NeedSkill {
|
||||
result := make([]domain.NeedSkill, 0, len(skills))
|
||||
for _, skill := range skills {
|
||||
if skill.Status == domain.NeedItemExtracted {
|
||||
if _, exists := confirmed[canonicalNeedKey(skill.Name)]; exists {
|
||||
continue
|
||||
}
|
||||
}
|
||||
result = append(result, skill)
|
||||
}
|
||||
return result
|
||||
}
|
||||
requirements.RequiredSkills = filter(requirements.RequiredSkills)
|
||||
requirements.DesiredSkills = filter(requirements.DesiredSkills)
|
||||
}
|
||||
|
||||
func replaceSkills(inputs []SkillInput, old []domain.NeedSkill, pointer string) ([]domain.NeedSkill, error) {
|
||||
updated := make([]domain.NeedSkill, 0, len(inputs))
|
||||
seen := make(map[string]struct{}, len(inputs))
|
||||
for index, input := range inputs {
|
||||
itemPointer := fmt.Sprintf("%s/%d", pointer, index)
|
||||
key := canonicalNeedKey(input.Name)
|
||||
if _, exists := seen[key]; exists {
|
||||
return nil, invalidRequest(itemPointer+"/name", "duplicates a skill in this request")
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
previous, exists := findSkill(old, key)
|
||||
switch input.Status {
|
||||
case domain.NeedItemExtracted:
|
||||
if !exists || previous.Status != domain.NeedItemExtracted {
|
||||
return nil, invalidRequest(itemPointer+"/status", "extracted is allowed only for a stored suggestion")
|
||||
}
|
||||
updated = append(updated, previous)
|
||||
case domain.NeedItemConfirmed:
|
||||
if exists {
|
||||
previous.Status = domain.NeedItemConfirmed
|
||||
updated = append(updated, previous)
|
||||
continue
|
||||
}
|
||||
updated = append(updated, domain.NeedSkill{
|
||||
Name: input.Name, TaxonomyCode: taxonomyForSkillName(input.Name), Status: domain.NeedItemConfirmed,
|
||||
Source: *manualNeedSource(),
|
||||
})
|
||||
default:
|
||||
return nil, invalidRequest(itemPointer+"/status", "must be confirmed or extracted")
|
||||
}
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func replaceTasks(inputs []TaskInput, old []domain.NeedTask) ([]domain.NeedTask, error) {
|
||||
updated := make([]domain.NeedTask, 0, len(inputs))
|
||||
seen := make(map[string]struct{}, len(inputs))
|
||||
for index, input := range inputs {
|
||||
pointer := fmt.Sprintf("/tasks/%d", index)
|
||||
key := canonicalNeedKey(input.Text)
|
||||
if _, exists := seen[key]; exists {
|
||||
return nil, invalidRequest(pointer+"/text", "duplicates a task in this request")
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
previous, exists := findTask(old, input.Text)
|
||||
switch input.Status {
|
||||
case domain.NeedItemExtracted:
|
||||
if !exists || previous.Status != domain.NeedItemExtracted {
|
||||
return nil, invalidRequest(pointer+"/status", "extracted is allowed only for a stored suggestion")
|
||||
}
|
||||
updated = append(updated, previous)
|
||||
case domain.NeedItemConfirmed:
|
||||
if exists {
|
||||
previous.Status = domain.NeedItemConfirmed
|
||||
updated = append(updated, previous)
|
||||
continue
|
||||
}
|
||||
updated = append(updated, domain.NeedTask{Text: input.Text, Status: domain.NeedItemConfirmed, Source: *manualNeedSource()})
|
||||
default:
|
||||
return nil, invalidRequest(pointer+"/status", "must be confirmed or extracted")
|
||||
}
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func reparseLists(
|
||||
snapshot *domain.NeedSnapshot,
|
||||
requirements *domain.NeedRequirements,
|
||||
parsed domain.NeedRequirements,
|
||||
previous domain.NeedRequirements,
|
||||
input UpdateInput,
|
||||
) {
|
||||
if input.RequiredSkills != nil || input.DesiredSkills != nil {
|
||||
blocked := confirmedSkillNames(requirements.RequiredSkills, requirements.DesiredSkills)
|
||||
if input.RequiredSkills != nil {
|
||||
addSkillNames(blocked, requirements.RequiredSkills)
|
||||
}
|
||||
if input.DesiredSkills != nil {
|
||||
addSkillNames(blocked, requirements.DesiredSkills)
|
||||
}
|
||||
if input.RequiredSkills == nil {
|
||||
requirements.RequiredSkills = reparseSkills(snapshot, previous.RequiredSkills, parsed.RequiredSkills, blocked)
|
||||
addSkillNames(blocked, requirements.RequiredSkills)
|
||||
}
|
||||
if input.DesiredSkills == nil {
|
||||
requirements.DesiredSkills = reparseSkills(snapshot, previous.DesiredSkills, parsed.DesiredSkills, blocked)
|
||||
}
|
||||
} else {
|
||||
blocked := confirmedSkillNames(previous.RequiredSkills, previous.DesiredSkills)
|
||||
requirements.RequiredSkills = reparseSkills(snapshot, previous.RequiredSkills, parsed.RequiredSkills, blocked)
|
||||
addSkillNames(blocked, requirements.RequiredSkills)
|
||||
requirements.DesiredSkills = reparseSkills(snapshot, previous.DesiredSkills, parsed.DesiredSkills, blocked)
|
||||
}
|
||||
if input.Tasks == nil {
|
||||
requirements.Tasks = reparseTasks(snapshot, previous.Tasks, parsed.Tasks)
|
||||
}
|
||||
}
|
||||
|
||||
func reparseSkills(
|
||||
snapshot *domain.NeedSnapshot,
|
||||
previous, parsed []domain.NeedSkill,
|
||||
blocked map[string]struct{},
|
||||
) []domain.NeedSkill {
|
||||
result := make([]domain.NeedSkill, 0, len(previous)+len(parsed))
|
||||
seen := make(map[string]struct{}, len(previous)+len(parsed))
|
||||
for _, skill := range previous {
|
||||
if skill.Status != domain.NeedItemConfirmed {
|
||||
continue
|
||||
}
|
||||
key := canonicalNeedKey(skill.Name)
|
||||
result = append(result, skill)
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
for _, skill := range parsed {
|
||||
key := canonicalNeedKey(skill.Name)
|
||||
if _, exists := seen[key]; exists {
|
||||
continue
|
||||
}
|
||||
if _, exists := blocked[key]; exists || isRejected(snapshot.RejectedSuggestions, domain.NeedRejectedSkills, skill.Name) {
|
||||
continue
|
||||
}
|
||||
result = append(result, skill)
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func reparseTasks(snapshot *domain.NeedSnapshot, previous, parsed []domain.NeedTask) []domain.NeedTask {
|
||||
result := make([]domain.NeedTask, 0, len(previous)+len(parsed))
|
||||
seen := make(map[string]struct{}, len(previous)+len(parsed))
|
||||
for _, task := range previous {
|
||||
if task.Status != domain.NeedItemConfirmed {
|
||||
continue
|
||||
}
|
||||
key := canonicalNeedKey(task.Text)
|
||||
result = append(result, task)
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
for _, task := range parsed {
|
||||
key := canonicalNeedKey(task.Text)
|
||||
if _, exists := seen[key]; exists || isRejected(snapshot.RejectedSuggestions, domain.NeedRejectedTasks, task.Text) {
|
||||
continue
|
||||
}
|
||||
result = append(result, task)
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func skillInputIndex(inputs []SkillInput, name string) int {
|
||||
key := canonicalNeedKey(name)
|
||||
for index, input := range inputs {
|
||||
if canonicalNeedKey(input.Name) == key {
|
||||
return index
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func taskInputIndex(inputs []TaskInput, text string) int {
|
||||
key := canonicalNeedKey(text)
|
||||
for index, input := range inputs {
|
||||
if canonicalNeedKey(input.Text) == key {
|
||||
return index
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func findSkill(skills []domain.NeedSkill, key string) (domain.NeedSkill, bool) {
|
||||
for _, skill := range skills {
|
||||
if canonicalNeedKey(skill.Name) == key {
|
||||
return skill, true
|
||||
}
|
||||
}
|
||||
return domain.NeedSkill{}, false
|
||||
}
|
||||
|
||||
func findTask(tasks []domain.NeedTask, text string) (domain.NeedTask, bool) {
|
||||
for _, task := range tasks {
|
||||
if task.Text == text {
|
||||
return task, true
|
||||
}
|
||||
}
|
||||
return domain.NeedTask{}, false
|
||||
}
|
||||
|
||||
func confirmedSkillNames(groups ...[]domain.NeedSkill) map[string]struct{} {
|
||||
result := make(map[string]struct{})
|
||||
for _, group := range groups {
|
||||
for _, skill := range group {
|
||||
if skill.Status == domain.NeedItemConfirmed {
|
||||
result[canonicalNeedKey(skill.Name)] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func addSkillNames(names map[string]struct{}, skills []domain.NeedSkill) {
|
||||
for _, skill := range skills {
|
||||
names[canonicalNeedKey(skill.Name)] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func validateSkillUniqueness(requirements domain.NeedRequirements) error {
|
||||
seen := make(map[string]struct{}, len(requirements.RequiredSkills)+len(requirements.DesiredSkills))
|
||||
for _, skill := range requirements.RequiredSkills {
|
||||
seen[canonicalNeedKey(skill.Name)] = struct{}{}
|
||||
}
|
||||
for index, skill := range requirements.DesiredSkills {
|
||||
key := canonicalNeedKey(skill.Name)
|
||||
if _, exists := seen[key]; exists {
|
||||
return invalidRequest(fmt.Sprintf("/desired_skills/%d/name", index), "duplicates a skill in required_skills")
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func addRejectedSuggestion(snapshot *domain.NeedSnapshot, field domain.NeedRejectedSuggestionField, value, pointer string) error {
|
||||
canonical := canonicalRejectedValue(field, value)
|
||||
if canonical == "" || isRejected(snapshot.RejectedSuggestions, field, canonical) {
|
||||
return nil
|
||||
}
|
||||
if len(snapshot.RejectedSuggestions) >= domain.MaxNeedRejectedSuggestions {
|
||||
return invalidRequest(pointer, "too many rejected suggestions")
|
||||
}
|
||||
snapshot.RejectedSuggestions = append(snapshot.RejectedSuggestions, domain.NeedRejectedSuggestion{Field: field, Value: canonical})
|
||||
return nil
|
||||
}
|
||||
|
||||
func isRejected(suggestions []domain.NeedRejectedSuggestion, field domain.NeedRejectedSuggestionField, value string) bool {
|
||||
canonical := canonicalRejectedValue(field, value)
|
||||
for _, suggestion := range suggestions {
|
||||
if suggestion.Field == field && suggestion.Value == canonical {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func canonicalRejectedValue(_ domain.NeedRejectedSuggestionField, value string) string {
|
||||
return canonicalNeedKey(value)
|
||||
}
|
||||
|
||||
func canonicalNeedKey(value string) string {
|
||||
return strings.ToLower(strings.Join(strings.Fields(value), " "))
|
||||
}
|
||||
|
||||
func scalarString[T ~string](value T) []string { return []string{string(value)} }
|
||||
|
||||
func scalarWorkFormats(value []domain.NeedWorkFormat) []string {
|
||||
result := make([]string, 0, len(value))
|
||||
for _, format := range value {
|
||||
result = append(result, string(format))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func scalarSalary(value domain.NeedSalaryRange) []string {
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return []string{string(encoded)}
|
||||
}
|
||||
|
||||
func taxonomyForSkillName(name string) *string {
|
||||
key := canonicalNeedKey(name)
|
||||
for _, rule := range needSkillRules {
|
||||
if strings.EqualFold(rule.name, key) && rule.taxonomy != "" {
|
||||
value := rule.taxonomy
|
||||
return &value
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func unknownNeedValue[T any]() domain.NeedValue[T] {
|
||||
return domain.NeedValue[T]{Status: domain.NeedValueUnknown}
|
||||
}
|
||||
|
||||
func confirmedNeedValue[T any](value T, source *domain.NeedValueSource) domain.NeedValue[T] {
|
||||
return domain.NeedValue[T]{Status: domain.NeedValueConfirmed, Value: &value, Source: source}
|
||||
}
|
||||
|
||||
func manualNeedSource() *domain.NeedValueSource {
|
||||
return &domain.NeedValueSource{Origin: domain.NeedValueManual}
|
||||
}
|
||||
|
||||
func cloneString(value *string) *string {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
cloned := *value
|
||||
return &cloned
|
||||
}
|
||||
|
||||
func invalidRequest(pointer, reason string) error {
|
||||
return &ValidationError{Pointer: pointer, Reason: reason}
|
||||
}
|
||||
|
||||
func mapDomainValidation(err error) error {
|
||||
if errors.Is(err, domain.ErrInvalidNeed) {
|
||||
pointer := ""
|
||||
if message := err.Error(); strings.Contains(message, "invalid need field ") {
|
||||
field := strings.SplitN(strings.SplitN(message, "invalid need field ", 2)[1], " ", 2)[0]
|
||||
pointer = field
|
||||
}
|
||||
return &ValidationError{Pointer: pointer, Reason: "value does not satisfy the need contract"}
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
package need
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
func TestCreateNeedUsesOnlyExplicitValuesAndSourceSuggestions(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
created := mustCreateNeed(t, CreateInput{
|
||||
Title: "Backend engineer",
|
||||
SourceText: Field[string]{Set: true, Value: "Ищем backend developer. Обязательно: Go, PostgreSQL. Желательно: Kafka."},
|
||||
Grade: Field[Decision[domain.GradeCode]]{Set: true, Null: true},
|
||||
DesiredSkills: []SkillInput{},
|
||||
}, now)
|
||||
requirements := created.Snapshot().Requirements
|
||||
if requirements.Specialization.Status != domain.NeedValueExtracted || requirements.Specialization.Value == nil || *requirements.Specialization.Value != domain.SpecializationBackend {
|
||||
t.Fatalf("specialization = %+v, want extracted backend", requirements.Specialization)
|
||||
}
|
||||
if requirements.Grade.Status != domain.NeedValueUnknown {
|
||||
t.Fatalf("grade = %+v, want explicitly unknown", requirements.Grade)
|
||||
}
|
||||
if len(requirements.RequiredSkills) != 2 || requirements.RequiredSkills[0].Name != "Go" || requirements.RequiredSkills[1].Name != "PostgreSQL" {
|
||||
t.Fatalf("required skills = %+v, want Go and PostgreSQL suggestions", requirements.RequiredSkills)
|
||||
}
|
||||
if requirements.DesiredSkills == nil || len(requirements.DesiredSkills) != 0 {
|
||||
t.Fatalf("desired skills = %#v, want explicitly empty", requirements.DesiredSkills)
|
||||
}
|
||||
if created.Version() != 1 || created.RequirementsVersion() != 1 || !created.CreatedAt().Equal(now) {
|
||||
t.Fatalf("created version/timestamp = %d/%d/%s", created.Version(), created.RequirementsVersion(), created.CreatedAt())
|
||||
}
|
||||
|
||||
manual := mustCreateNeed(t, CreateInput{
|
||||
Title: "Go engineer",
|
||||
Specialization: Field[Decision[domain.SpecializationCode]]{
|
||||
Set: true, Value: Decision[domain.SpecializationCode]{Value: domain.SpecializationBackend, Status: domain.NeedValueConfirmed},
|
||||
},
|
||||
RequiredSkills: []SkillInput{{Name: "Go", Status: domain.NeedItemConfirmed}},
|
||||
}, now)
|
||||
manualRequirements := manual.Snapshot().Requirements
|
||||
if manualRequirements.Specialization.Status != domain.NeedValueConfirmed || manualRequirements.Grade.Status != domain.NeedValueUnknown ||
|
||||
len(manualRequirements.RequiredSkills) != 1 || manualRequirements.RequiredSkills[0].Source.Origin != domain.NeedValueManual {
|
||||
t.Fatalf("manual requirements = %+v, want only supplied confirmed values", manualRequirements)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateConfirmsAndMovesStoredSuggestionWithoutLosingProvenance(t *testing.T) {
|
||||
current := mustCreateNeed(t, CreateInput{
|
||||
Title: "Backend engineer",
|
||||
SourceText: Field[string]{Set: true, Value: "Ищем backend developer. Обязательно: Go, PostgreSQL. Желательно: Kafka."},
|
||||
}, testNeedTime())
|
||||
before := current.Snapshot().Requirements
|
||||
if len(before.RequiredSkills) != 2 || len(before.DesiredSkills) != 1 {
|
||||
t.Fatalf("parsed lists = %v / %v", before.RequiredSkills, before.DesiredSkills)
|
||||
}
|
||||
goSource := before.RequiredSkills[0].Source
|
||||
updated, changed, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1,
|
||||
RequiredSkills: []SkillInput{{Name: "PostgreSQL", Status: domain.NeedItemExtracted}},
|
||||
DesiredSkills: []SkillInput{{Name: "Go", Status: domain.NeedItemConfirmed}, {Name: "Kafka", Status: domain.NeedItemExtracted}},
|
||||
}, testNeedTime().Add(time.Second))
|
||||
if err != nil {
|
||||
t.Fatalf("reviseNeed() error = %v", err)
|
||||
}
|
||||
if !changed || updated.Version() != 2 || updated.RequirementsVersion() != 2 {
|
||||
t.Fatalf("updated version/change = %d/%d/%v, want 2/2/true", updated.Version(), updated.RequirementsVersion(), changed)
|
||||
}
|
||||
got := updated.Snapshot().Requirements
|
||||
if len(got.RequiredSkills) != 1 || got.RequiredSkills[0].Name != "PostgreSQL" || len(got.DesiredSkills) != 2 {
|
||||
t.Fatalf("updated skill lists = %v / %v", got.RequiredSkills, got.DesiredSkills)
|
||||
}
|
||||
confirmedGo := got.DesiredSkills[0]
|
||||
if confirmedGo.Name != "Go" || confirmedGo.Status != domain.NeedItemConfirmed || confirmedGo.Source.Origin != domain.NeedValueExtractedFromText || !reflect.DeepEqual(confirmedGo.Source, goSource) {
|
||||
t.Fatalf("confirmed Go = %+v, want original extracted provenance", confirmedGo)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceEditReextractsSuggestionsButKeepsConfirmedValues(t *testing.T) {
|
||||
current := mustCreateNeed(t, CreateInput{
|
||||
Title: "Backend engineer",
|
||||
SourceText: Field[string]{Set: true, Value: "Ищем backend developer. Обязательно: Go, PostgreSQL."},
|
||||
}, testNeedTime())
|
||||
current, changed, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1,
|
||||
RequiredSkills: []SkillInput{{Name: "Go", Status: domain.NeedItemConfirmed}, {Name: "PostgreSQL", Status: domain.NeedItemExtracted}},
|
||||
}, testNeedTime().Add(time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("confirm first skill: changed=%v error=%v", changed, err)
|
||||
}
|
||||
confirmed := current.Snapshot().Requirements.RequiredSkills[0]
|
||||
updated, changed, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 2,
|
||||
SourceText: Field[string]{Set: true, Value: "Ищем backend developer. Обязательно: Go, Kafka."},
|
||||
}, testNeedTime().Add(2*time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("change source: changed=%v error=%v", changed, err)
|
||||
}
|
||||
requirements := updated.Snapshot().Requirements
|
||||
if updated.RequirementsVersion() != current.RequirementsVersion() {
|
||||
t.Fatalf("requirements_version = %d, want unchanged %d", updated.RequirementsVersion(), current.RequirementsVersion())
|
||||
}
|
||||
if len(requirements.RequiredSkills) != 2 || requirements.RequiredSkills[0].Name != confirmed.Name || requirements.RequiredSkills[0].Status != domain.NeedItemConfirmed || !reflect.DeepEqual(requirements.RequiredSkills[0].Source, confirmed.Source) {
|
||||
t.Fatalf("confirmed skill after source edit = %+v", requirements.RequiredSkills)
|
||||
}
|
||||
if requirements.RequiredSkills[1].Name != "Kafka" || requirements.RequiredSkills[1].Status != domain.NeedItemExtracted {
|
||||
t.Fatalf("reparsed suggestions = %+v, want Kafka only after confirmed Go", requirements.RequiredSkills)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeletedSkillSuggestionStaysSuppressedAcrossListsAndManualReadd(t *testing.T) {
|
||||
current := mustCreateNeed(t, CreateInput{
|
||||
Title: "Backend engineer",
|
||||
SourceText: Field[string]{Set: true, Value: "Желательно: PostgreSQL."},
|
||||
}, testNeedTime())
|
||||
deleted, changed, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1,
|
||||
DesiredSkills: []SkillInput{},
|
||||
}, testNeedTime().Add(time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("delete extracted skill: changed=%v error=%v", changed, err)
|
||||
}
|
||||
if !hasRejected(deleted.Snapshot().RejectedSuggestions, domain.NeedRejectedSkills, "POSTGRESQL") {
|
||||
t.Fatalf("deleted skill suppression = %+v, want case-insensitive common skill key", deleted.Snapshot().RejectedSuggestions)
|
||||
}
|
||||
|
||||
manual, changed, err := reviseNeed(deleted, UpdateInput{
|
||||
ExpectedVersion: 2,
|
||||
DesiredSkills: []SkillInput{{Name: "PostgreSQL", Status: domain.NeedItemConfirmed}},
|
||||
}, testNeedTime().Add(2*time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("manual readd: changed=%v error=%v", changed, err)
|
||||
}
|
||||
if len(manual.Snapshot().Requirements.DesiredSkills) != 1 || manual.Snapshot().Requirements.DesiredSkills[0].Source.Origin != domain.NeedValueManual {
|
||||
t.Fatalf("manual readd = %+v, want confirmed manual skill", manual.Snapshot().Requirements.DesiredSkills)
|
||||
}
|
||||
if !hasRejected(manual.Snapshot().RejectedSuggestions, domain.NeedRejectedSkills, "postgresql") {
|
||||
t.Fatalf("manual readd cleared old rejection: %+v", manual.Snapshot().RejectedSuggestions)
|
||||
}
|
||||
|
||||
deletedAgain, changed, err := reviseNeed(manual, UpdateInput{
|
||||
ExpectedVersion: 3,
|
||||
DesiredSkills: []SkillInput{},
|
||||
}, testNeedTime().Add(3*time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("delete manual readd: changed=%v error=%v", changed, err)
|
||||
}
|
||||
updated, changed, err := reviseNeed(deletedAgain, UpdateInput{
|
||||
ExpectedVersion: 4,
|
||||
SourceText: Field[string]{Set: true, Value: "Обязательно: PostgreSQL."},
|
||||
}, testNeedTime().Add(4*time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("change source after readd removal: changed=%v error=%v", changed, err)
|
||||
}
|
||||
final := updated.Snapshot()
|
||||
if len(final.Requirements.RequiredSkills) != 0 || len(final.Requirements.DesiredSkills) != 0 || !hasRejected(final.RejectedSuggestions, domain.NeedRejectedSkills, "postgresql") {
|
||||
t.Fatalf("suppressed skill returned after source edit: %+v", final.Requirements)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeletedScalarSuggestionStaysSuppressedAfterSourceEdit(t *testing.T) {
|
||||
current := mustCreateNeed(t, CreateInput{
|
||||
Title: "Backend engineer",
|
||||
SourceText: Field[string]{Set: true, Value: "Ищем backend developer."},
|
||||
}, testNeedTime())
|
||||
deleted, changed, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1,
|
||||
Specialization: Field[Decision[domain.SpecializationCode]]{Set: true, Null: true},
|
||||
}, testNeedTime().Add(time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("delete specialization: changed=%v error=%v", changed, err)
|
||||
}
|
||||
updated, changed, err := reviseNeed(deleted, UpdateInput{
|
||||
ExpectedVersion: 2,
|
||||
SourceText: Field[string]{Set: true, Value: "Ищем backend developer снова."},
|
||||
}, testNeedTime().Add(2*time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("change source: changed=%v error=%v", changed, err)
|
||||
}
|
||||
if got := updated.Snapshot(); got.Requirements.Specialization.Status != domain.NeedValueUnknown || !hasRejected(got.RejectedSuggestions, domain.NeedRejectedSpecialization, "BACKEND") {
|
||||
t.Fatalf("specialization was proposed again: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceNullKeepsEveryRequirementAndSourceOnlyEditKeepsRequirementsVersion(t *testing.T) {
|
||||
current := mustCreateNeed(t, CreateInput{
|
||||
Title: "Backend engineer",
|
||||
SourceText: Field[string]{Set: true, Value: "Ищем backend developer. Обязательно: Go."},
|
||||
}, testNeedTime())
|
||||
cleared, changed, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1,
|
||||
SourceText: Field[string]{Set: true, Null: true},
|
||||
}, testNeedTime().Add(time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("clear source text: changed=%v error=%v", changed, err)
|
||||
}
|
||||
if cleared.Snapshot().SourceText != nil || !reflect.DeepEqual(cleared.Snapshot().Requirements, current.Snapshot().Requirements) || cleared.RequirementsVersion() != current.RequirementsVersion() {
|
||||
t.Fatalf("cleared source changed requirements: %+v", cleared.Snapshot())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStalePatchReturnsNoopBeforeConflictAndConflictBeforeDomainError(t *testing.T) {
|
||||
current := mustCreateNeed(t, CreateInput{Title: "Backend engineer"}, testNeedTime())
|
||||
current, changed, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1, Title: Field[string]{Set: true, Value: "Updated title"},
|
||||
}, testNeedTime().Add(time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("initial title edit: changed=%v error=%v", changed, err)
|
||||
}
|
||||
noOp, changed, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1, Title: Field[string]{Set: true, Value: "Updated title"},
|
||||
}, testNeedTime().Add(2*time.Second))
|
||||
if err != nil || changed || noOp.Version() != current.Version() {
|
||||
t.Fatalf("stale no-op: version=%d changed=%v error=%v", noOp.Version(), changed, err)
|
||||
}
|
||||
_, _, err = reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1,
|
||||
Grade: Field[Decision[domain.GradeCode]]{Set: true, Value: Decision[domain.GradeCode]{Value: domain.GradeSenior, Status: domain.NeedValueExtracted}},
|
||||
}, testNeedTime().Add(2*time.Second))
|
||||
if !errors.Is(err, domain.ErrNeedVersionConflict) {
|
||||
t.Fatalf("stale invalid patch error = %v, want version conflict", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchRejectsExtractedValueNotStoredAsSuggestion(t *testing.T) {
|
||||
current := mustCreateNeed(t, CreateInput{Title: "Backend engineer"}, testNeedTime())
|
||||
_, _, err := reviseNeed(current, UpdateInput{
|
||||
ExpectedVersion: 1,
|
||||
Grade: Field[Decision[domain.GradeCode]]{Set: true, Value: Decision[domain.GradeCode]{Value: domain.GradeSenior, Status: domain.NeedValueExtracted}},
|
||||
}, testNeedTime().Add(time.Second))
|
||||
var validation *ValidationError
|
||||
if !errors.As(err, &validation) || validation.Pointer != "/grade/status" {
|
||||
t.Fatalf("invalid extracted grade error = %v, want /grade/status validation", err)
|
||||
}
|
||||
}
|
||||
|
||||
func mustCreateNeed(t *testing.T, input CreateInput, now time.Time) domain.Need {
|
||||
t.Helper()
|
||||
needID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
t.Fatalf("generate need ID: %v", err)
|
||||
}
|
||||
organizationID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
t.Fatalf("generate organization ID: %v", err)
|
||||
}
|
||||
created, err := createNeed(input, organizationID, needID, now)
|
||||
if err != nil {
|
||||
t.Fatalf("createNeed() error = %v", err)
|
||||
}
|
||||
return created
|
||||
}
|
||||
|
||||
func testNeedTime() time.Time {
|
||||
return time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func hasRejected(suggestions []domain.NeedRejectedSuggestion, field domain.NeedRejectedSuggestionField, value string) bool {
|
||||
canonical := canonicalNeedKey(value)
|
||||
for _, suggestion := range suggestions {
|
||||
if suggestion.Field == field && suggestion.Value == canonical {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
package need
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
const needRulesVersion = "need-rules.2026-10.1"
|
||||
|
||||
var (
|
||||
needSectionPattern = regexp.MustCompile(`(?i)(обязательно|обязательные навыки|требуемые навыки|требования|желательно|желательные навыки|предпочтительно|технологии|стек|required skills|requirements|preferred skills|technology stack)\s*:?\s*`)
|
||||
needTaskPattern = regexp.MustCompile(`(?i)(задачи|обязанности|tasks|responsibilities)\s*:`)
|
||||
needNegationPattern = regexp.MustCompile(`(?i)(?:без|without|no|not(?:\s+required)?|не(?:\s+(?:требуется|нужен|нужна|нужно|обязательно|обязателен|обязательна|обязательны|требуемый|требуемая))?)\s*[:,\-]?\s*$`)
|
||||
needDomainPatterns = []domainRule{
|
||||
{pattern: regexp.MustCompile(`(?i)(в команду платежей)`), value: "платежи"},
|
||||
{pattern: regexp.MustCompile(`(?i)(в команду выплат)`), value: "выплаты"},
|
||||
{pattern: regexp.MustCompile(`(?i)(payments team)`), value: "payments"},
|
||||
{pattern: regexp.MustCompile(`(?i)(logistics team)`), value: "logistics"},
|
||||
}
|
||||
needSpecializationPatterns = []domainRule{
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])((?:ищем\s+)?(?:backend[ -](?:developer|engineer)|back-end[ -](?:developer|engineer)|бэкенд[- ]разработчик\p{L}*|бэкэнд[- ]разработчик\p{L}*|серверн\p{L}*\s+разработчик\p{L}*))(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationBackend)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])((?:ищем\s+)?(?:frontend[ -](?:developer|engineer)|front-end[ -](?:developer|engineer)|фронтенд[- ]разработчик\p{L}*|фронтэнд[- ]разработчик\p{L}*))(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationFrontend)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])((?:ищем\s+)?(?:mobile[ -](?:developer|engineer)|мобильн\p{L}*\s+разработчик\p{L}*))(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationMobile)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(network engineer|сетев\p{L}* инженер\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationNetworkEngineer)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(devops|sre)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationDevopsSRE)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(data analyst|аналитик данных)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationDataAnalyst)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(data scientist|machine learning|ml engineer|специалист\p{L}* машинн\p{L}* обучен\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationDSML)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(information security|информационн\p{L}* безопасност\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationInformationSecurity)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(qa engineer|тестировщик\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.SpecializationQA)},
|
||||
}
|
||||
needGradePatterns = []domainRule{
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(intern|internship|стаж[её]р\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.GradeIntern)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(junior|jun|джуниор\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.GradeJunior)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(middle|mid|мидл\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.GradeMiddle)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(senior|sen|сеньор\p{L}*)(?:$|[^\p{L}\p{N}_])`), value: string(domain.GradeSenior)},
|
||||
{pattern: regexp.MustCompile(`(?i)(младш(?:ий|его|ему))\s+(?:backend|back-end|frontend|front-end|разработчик|инженер)`), value: string(domain.GradeJunior)},
|
||||
{pattern: regexp.MustCompile(`(?i)(средн(?:ий|его|ему))\s+(?:backend|back-end|frontend|front-end|разработчик|инженер)`), value: string(domain.GradeMiddle)},
|
||||
{pattern: regexp.MustCompile(`(?i)(старш(?:ий|его|ему))\s+(?:backend|back-end|frontend|front-end|разработчик|инженер)`), value: string(domain.GradeSenior)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:уров(?:ень|ня|не)|грейд(?:а|е)?|позици(?:я|и))\s+(младш(?:ий|его|ему))`), value: string(domain.GradeJunior)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:уров(?:ень|ня|не)|грейд(?:а|е)?|позици(?:я|и))\s+(средн(?:ий|его|ему))`), value: string(domain.GradeMiddle)},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:уров(?:ень|ня|не)|грейд(?:а|е)?|позици(?:я|и))\s+(старш(?:ий|его|ему))`), value: string(domain.GradeSenior)},
|
||||
}
|
||||
needWorkFormatRules = []formatRule{
|
||||
{pattern: regexp.MustCompile(`(?i)(удал[её]нн\p{L}*|дистанционн\p{L}*|remote)`), value: domain.NeedWorkFormatRemote},
|
||||
{pattern: regexp.MustCompile(`(?i)(офис\p{L}*|office)`), value: domain.NeedWorkFormatOffice},
|
||||
{pattern: regexp.MustCompile(`(?i)(гибрид\p{L}*|hybrid)`), value: domain.NeedWorkFormatHybrid},
|
||||
}
|
||||
needSkillRules = []skillRule{
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(postgresql)(?:$|[^\p{L}\p{N}_])`), name: "PostgreSQL", taxonomy: "postgresql"},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(kafka)(?:$|[^\p{L}\p{N}_])`), name: "Kafka", taxonomy: "kafka"},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(temporal)(?:$|[^\p{L}\p{N}_])`), name: "Temporal"},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(docker)(?:$|[^\p{L}\p{N}_])`), name: "Docker", taxonomy: "docker"},
|
||||
{pattern: regexp.MustCompile(`(?i)(?:^|[^\p{L}\p{N}_])(go)(?:$|[^\p{L}\p{N}_])`), name: "Go", taxonomy: "go"},
|
||||
}
|
||||
)
|
||||
|
||||
type domainRule struct {
|
||||
pattern *regexp.Regexp
|
||||
value string
|
||||
}
|
||||
|
||||
type formatRule struct {
|
||||
pattern *regexp.Regexp
|
||||
value domain.NeedWorkFormat
|
||||
}
|
||||
|
||||
type skillRule struct {
|
||||
pattern *regexp.Regexp
|
||||
name string
|
||||
taxonomy string
|
||||
}
|
||||
|
||||
type needTextSection struct {
|
||||
start int
|
||||
end int
|
||||
quote string
|
||||
want bool
|
||||
}
|
||||
|
||||
type skillOccurrence struct {
|
||||
start int
|
||||
name string
|
||||
taxonomy string
|
||||
quote string
|
||||
section needTextSection
|
||||
}
|
||||
|
||||
const maxParsedEvidenceRunes = 300
|
||||
|
||||
func parseSourceText(source string, version int64) domain.NeedRequirements {
|
||||
requirements := domain.EmptyNeedRequirements()
|
||||
requirements.Specialization = parseNeedScalar(source, version, needSpecializationPatterns, func(value string) domain.SpecializationCode {
|
||||
return domain.SpecializationCode(value)
|
||||
})
|
||||
requirements.Grade = parseNeedScalar(source, version, needGradePatterns, func(value string) domain.GradeCode {
|
||||
return domain.GradeCode(value)
|
||||
})
|
||||
requirements.Domain = parseNeedScalar(source, version, needDomainPatterns, func(value string) string {
|
||||
return value
|
||||
})
|
||||
requirements.WorkFormats = parseWorkFormats(source, version)
|
||||
requirements.RequiredSkills, requirements.DesiredSkills = parseSkills(source, version)
|
||||
requirements.Tasks = parseTasks(source, version)
|
||||
return requirements
|
||||
}
|
||||
|
||||
func parseNeedScalar[T any](source string, version int64, rules []domainRule, convert func(string) T) domain.NeedValue[T] {
|
||||
type candidate struct {
|
||||
start int
|
||||
value T
|
||||
quote string
|
||||
}
|
||||
found := make([]candidate, 0, len(rules))
|
||||
values := make(map[string]struct{}, len(rules))
|
||||
for _, rule := range rules {
|
||||
for _, indices := range rule.pattern.FindAllStringSubmatchIndex(source, -1) {
|
||||
if len(indices) < 4 || hasNeedNegation(source, indices[2]) {
|
||||
continue
|
||||
}
|
||||
value := convert(rule.value)
|
||||
key := fmt.Sprint(value)
|
||||
values[key] = struct{}{}
|
||||
found = append(found, candidate{
|
||||
start: indices[2], value: value,
|
||||
quote: strings.TrimSpace(source[indices[2]:indices[3]]),
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(values) != 1 || len(found) == 0 {
|
||||
return unknownNeedValue[T]()
|
||||
}
|
||||
sort.Slice(found, func(i, j int) bool { return found[i].start < found[j].start })
|
||||
value := found[0].value
|
||||
return domain.NeedValue[T]{Status: domain.NeedValueExtracted, Value: &value, Source: extractedNeedSource(found[0].quote, version)}
|
||||
}
|
||||
|
||||
func parseWorkFormats(source string, version int64) domain.NeedValue[[]domain.NeedWorkFormat] {
|
||||
type foundFormat struct {
|
||||
start int
|
||||
end int
|
||||
format domain.NeedWorkFormat
|
||||
}
|
||||
found := make([]foundFormat, 0, len(needWorkFormatRules))
|
||||
seen := make(map[domain.NeedWorkFormat]struct{}, len(needWorkFormatRules))
|
||||
for _, rule := range needWorkFormatRules {
|
||||
for _, indices := range rule.pattern.FindAllStringSubmatchIndex(source, -1) {
|
||||
if len(indices) < 4 || hasNeedNegation(source, indices[2]) {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[rule.value]; ok {
|
||||
continue
|
||||
}
|
||||
seen[rule.value] = struct{}{}
|
||||
found = append(found, foundFormat{start: indices[2], end: indices[3], format: rule.value})
|
||||
}
|
||||
}
|
||||
if len(found) == 0 {
|
||||
return domain.NeedValue[[]domain.NeedWorkFormat]{Status: domain.NeedValueUnknown}
|
||||
}
|
||||
sort.Slice(found, func(i, j int) bool { return found[i].start < found[j].start })
|
||||
formats := make([]domain.NeedWorkFormat, 0, len(found))
|
||||
for _, item := range found {
|
||||
formats = append(formats, item.format)
|
||||
}
|
||||
quote := strings.TrimSpace(source[found[0].start:found[len(found)-1].end])
|
||||
if utf8.RuneCountInString(quote) > maxParsedEvidenceRunes {
|
||||
return domain.NeedValue[[]domain.NeedWorkFormat]{Status: domain.NeedValueUnknown}
|
||||
}
|
||||
value := formats
|
||||
return domain.NeedValue[[]domain.NeedWorkFormat]{
|
||||
Status: domain.NeedValueExtracted,
|
||||
Value: &value,
|
||||
Source: extractedNeedSource(quote, version),
|
||||
}
|
||||
}
|
||||
|
||||
func parseSkills(source string, version int64) ([]domain.NeedSkill, []domain.NeedSkill) {
|
||||
sections := skillSections(source)
|
||||
occurrences := make([]skillOccurrence, 0, len(needSkillRules))
|
||||
for _, section := range sections {
|
||||
segment := source[section.start:section.end]
|
||||
for _, rule := range needSkillRules {
|
||||
for _, indices := range rule.pattern.FindAllStringSubmatchIndex(segment, -1) {
|
||||
if len(indices) < 4 || hasNeedNegation(source, section.start+indices[2]) {
|
||||
continue
|
||||
}
|
||||
start := section.start + indices[2]
|
||||
occurrences = append(occurrences, skillOccurrence{
|
||||
start: start, name: rule.name, taxonomy: rule.taxonomy,
|
||||
quote: source[section.start+indices[2] : section.start+indices[3]], section: section,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(occurrences, func(i, j int) bool { return occurrences[i].start < occurrences[j].start })
|
||||
seen := make(map[string]struct{}, len(occurrences))
|
||||
required := make([]domain.NeedSkill, 0, len(occurrences))
|
||||
desired := make([]domain.NeedSkill, 0, len(occurrences))
|
||||
for _, occurrence := range occurrences {
|
||||
key := strings.ToLower(occurrence.name)
|
||||
if _, ok := seen[key]; ok {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
var taxonomy *string
|
||||
if occurrence.taxonomy != "" {
|
||||
value := occurrence.taxonomy
|
||||
taxonomy = &value
|
||||
}
|
||||
item := domain.NeedSkill{
|
||||
Name: occurrence.name, TaxonomyCode: taxonomy, Status: domain.NeedItemExtracted,
|
||||
Source: *extractedNeedSource(skillQuote(occurrence), version),
|
||||
}
|
||||
if occurrence.section.want {
|
||||
desired = append(desired, item)
|
||||
} else {
|
||||
required = append(required, item)
|
||||
}
|
||||
}
|
||||
return required, desired
|
||||
}
|
||||
|
||||
func skillQuote(occurrence skillOccurrence) string {
|
||||
if occurrence.section.quote != "" && utf8.RuneCountInString(occurrence.section.quote) <= maxParsedEvidenceRunes {
|
||||
return occurrence.section.quote
|
||||
}
|
||||
return occurrence.quote
|
||||
}
|
||||
|
||||
func skillSections(source string) []needTextSection {
|
||||
matches := needSectionPattern.FindAllStringSubmatchIndex(source, -1)
|
||||
if len(matches) == 0 {
|
||||
return []needTextSection{{start: 0, end: len(source), quote: ""}}
|
||||
}
|
||||
sections := make([]needTextSection, 0, len(matches))
|
||||
for index, match := range matches {
|
||||
end := len(source)
|
||||
if index+1 < len(matches) {
|
||||
end = matches[index+1][0]
|
||||
}
|
||||
if sentenceEnd := strings.IndexAny(source[match[1]:end], ".!?\n"); sentenceEnd >= 0 {
|
||||
end = match[1] + sentenceEnd
|
||||
}
|
||||
segment := strings.TrimSpace(source[match[0]:end])
|
||||
if segment == "" {
|
||||
continue
|
||||
}
|
||||
want := isDesiredSection(source[match[2]:match[3]])
|
||||
sections = append(sections, needTextSection{start: match[0], end: end, quote: segment, want: want})
|
||||
}
|
||||
if len(sections) == 0 {
|
||||
return []needTextSection{{start: 0, end: len(source), quote: ""}}
|
||||
}
|
||||
return sections
|
||||
}
|
||||
|
||||
func isDesiredSection(label string) bool {
|
||||
label = strings.ToLower(label)
|
||||
return strings.Contains(label, "желат") || strings.Contains(label, "предпочт") || strings.Contains(label, "preferred")
|
||||
}
|
||||
|
||||
func hasNeedNegation(source string, start int) bool {
|
||||
if start < 0 || start > len(source) {
|
||||
return false
|
||||
}
|
||||
prefix := source[:start]
|
||||
if boundary := strings.LastIndexAny(prefix, ".!?;,\n"); boundary >= 0 {
|
||||
prefix = prefix[boundary+1:]
|
||||
}
|
||||
return needNegationPattern.MatchString(prefix)
|
||||
}
|
||||
|
||||
func parseTasks(source string, version int64) []domain.NeedTask {
|
||||
indices := needTaskPattern.FindStringSubmatchIndex(source)
|
||||
if len(indices) < 4 {
|
||||
return []domain.NeedTask{}
|
||||
}
|
||||
start := indices[1]
|
||||
end := len(source)
|
||||
if sentenceEnd := strings.IndexAny(source[start:], ".!?\n"); sentenceEnd >= 0 {
|
||||
end = start + sentenceEnd
|
||||
}
|
||||
text := strings.TrimSpace(source[start:end])
|
||||
text = strings.Trim(text, " :;,-\t\r")
|
||||
quote := strings.TrimSpace(source[indices[0]:end])
|
||||
if text == "" || utf8.RuneCountInString(text) > maxParsedEvidenceRunes || utf8.RuneCountInString(quote) > maxParsedEvidenceRunes {
|
||||
return []domain.NeedTask{}
|
||||
}
|
||||
value := []rune(text)
|
||||
value[0] = unicode.ToUpper(value[0])
|
||||
text = string(value)
|
||||
return []domain.NeedTask{{
|
||||
Text: text, Status: domain.NeedItemExtracted,
|
||||
Source: *extractedNeedSource(quote, version),
|
||||
}}
|
||||
}
|
||||
|
||||
func extractedNeedSource(quote string, version int64) *domain.NeedValueSource {
|
||||
versionLabel := needRulesVersion
|
||||
var quoteValue *string
|
||||
if quote != "" {
|
||||
quoteValue = "e
|
||||
}
|
||||
extractedVersion := version
|
||||
return &domain.NeedValueSource{
|
||||
Origin: domain.NeedValueExtractedFromText,
|
||||
Quote: quoteValue,
|
||||
ExtractedInVersion: &extractedVersion,
|
||||
ExtractionVersion: &versionLabel,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package need
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
func TestParseSourceTextUsesDeterministicSuggestions(t *testing.T) {
|
||||
const source = "Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно."
|
||||
requirements := parseSourceText(source, 1)
|
||||
|
||||
if got := requirements.Specialization; got.Status != domain.NeedValueExtracted || got.Value == nil || *got.Value != domain.SpecializationBackend {
|
||||
t.Fatalf("specialization = %+v, want an extracted backend suggestion", got)
|
||||
}
|
||||
if got := requirements.Specialization.Source; got == nil || got.Quote == nil || *got.Quote != "Ищем бэкенд-разработчика" || *got.ExtractedInVersion != 1 || *got.ExtractionVersion != needRulesVersion {
|
||||
t.Fatalf("specialization provenance = %+v, want exact source and rules version", got)
|
||||
}
|
||||
if got := requirements.Grade; got.Status != domain.NeedValueUnknown || got.Value != nil || got.Source != nil {
|
||||
t.Fatalf("grade = %+v, want unknown", got)
|
||||
}
|
||||
if got := requirements.Domain; got.Status != domain.NeedValueExtracted || got.Value == nil || *got.Value != "платежи" || got.Source == nil || got.Source.Quote == nil || *got.Source.Quote != "в команду платежей" {
|
||||
t.Fatalf("domain = %+v, want a quoted suggestion", got)
|
||||
}
|
||||
if got := requirements.WorkFormats; got.Status != domain.NeedValueExtracted || got.Value == nil || len(*got.Value) != 1 || (*got.Value)[0] != domain.NeedWorkFormatRemote || got.Source == nil || got.Source.Quote == nil || *got.Source.Quote != "удаленно" {
|
||||
t.Fatalf("work formats = %+v, want a quoted remote suggestion", got)
|
||||
}
|
||||
if len(requirements.RequiredSkills) != 3 || len(requirements.DesiredSkills) != 1 {
|
||||
t.Fatalf("skill counts = %d required, %d desired, want 3 and 1", len(requirements.RequiredSkills), len(requirements.DesiredSkills))
|
||||
}
|
||||
wantRequired := []struct {
|
||||
name string
|
||||
taxonomy *string
|
||||
}{
|
||||
{name: "Go", taxonomy: needStringPointer("go")},
|
||||
{name: "PostgreSQL", taxonomy: needStringPointer("postgresql")},
|
||||
{name: "Temporal"},
|
||||
}
|
||||
for index, want := range wantRequired {
|
||||
got := requirements.RequiredSkills[index]
|
||||
if got.Name != want.name || got.Status != domain.NeedItemExtracted || !equalNeedStringPointer(got.TaxonomyCode, want.taxonomy) {
|
||||
t.Errorf("required_skills[%d] = %+v, want name %q, extracted, taxonomy %v", index, got, want.name, want.taxonomy)
|
||||
}
|
||||
if got.Source.Origin != domain.NeedValueExtractedFromText || got.Source.Quote == nil || *got.Source.Quote != "Обязательно: Go, PostgreSQL и Temporal" || got.Source.ExtractedInVersion == nil || *got.Source.ExtractedInVersion != 1 {
|
||||
t.Errorf("required_skills[%d] provenance = %+v, want the exact required section", index, got.Source)
|
||||
}
|
||||
}
|
||||
desired := requirements.DesiredSkills[0]
|
||||
if desired.Name != "Kafka" || desired.Status != domain.NeedItemExtracted || desired.Source.Quote == nil || *desired.Source.Quote != "Желательно опыт с Kafka" {
|
||||
t.Fatalf("desired skill = %+v, want a quoted extracted Kafka suggestion", desired)
|
||||
}
|
||||
if len(requirements.Tasks) != 1 || requirements.Tasks[0].Text != "Развивать сервис выплат и переводить его на событийную модель" || requirements.Tasks[0].Status != domain.NeedItemExtracted {
|
||||
t.Fatalf("tasks = %+v, want one extracted task", requirements.Tasks)
|
||||
}
|
||||
if got := requirements.Tasks[0].Source.Quote; got == nil || *got != "Задачи: развивать сервис выплат и переводить его на событийную модель" {
|
||||
t.Fatalf("task quote = %v, want exact source excerpt", got)
|
||||
}
|
||||
if requirements.Location.Status != domain.NeedValueUnknown || requirements.Salary.Status != domain.NeedValueUnknown {
|
||||
t.Fatalf("location or salary was inferred: location=%+v salary=%+v", requirements.Location, requirements.Salary)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSourceTextDoesNotSupplyDefaultsOrDuplicateSkills(t *testing.T) {
|
||||
requirements := parseSourceText("Разработчик использует GO и go, зарплата обсуждается позже.", 2)
|
||||
if requirements.Grade.Status != domain.NeedValueUnknown || requirements.WorkFormats.Status != domain.NeedValueUnknown || requirements.Salary.Status != domain.NeedValueUnknown {
|
||||
t.Fatalf("parser supplied an absent value: grade=%+v formats=%+v salary=%+v", requirements.Grade, requirements.WorkFormats, requirements.Salary)
|
||||
}
|
||||
if len(requirements.RequiredSkills) != 1 || requirements.RequiredSkills[0].Name != "Go" {
|
||||
t.Fatalf("required skills = %+v, want one case-insensitive suggestion", requirements.RequiredSkills)
|
||||
}
|
||||
if got := requirements.RequiredSkills[0].Source; got.ExtractedInVersion == nil || *got.ExtractedInVersion != 2 {
|
||||
t.Fatalf("source version = %+v, want version 2", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSourceTextCanSuggestExplicitGrade(t *testing.T) {
|
||||
requirements := parseSourceText("Нужен backend developer уровня Junior. Обязательно: Go.", 1)
|
||||
if requirements.Grade.Status != domain.NeedValueExtracted || requirements.Grade.Value == nil || *requirements.Grade.Value != domain.GradeJunior {
|
||||
t.Fatalf("grade = %+v, want extracted junior suggestion", requirements.Grade)
|
||||
}
|
||||
if requirements.Grade.Source == nil || requirements.Grade.Source.Quote == nil || *requirements.Grade.Source.Quote != "Junior" {
|
||||
t.Fatalf("grade provenance = %+v, want exact source term", requirements.Grade.Source)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSourceTextLeavesAmbiguousOrIncidentalGradesUnknown(t *testing.T) {
|
||||
for _, source := range []string{
|
||||
"Нужен backend developer уровня Junior или Senior.",
|
||||
"Возраст: старше 35 лет, младше 30 лет, среднее образование.",
|
||||
} {
|
||||
requirements := parseSourceText(source, 1)
|
||||
if requirements.Grade.Status != domain.NeedValueUnknown {
|
||||
t.Errorf("grade for %q = %+v, want unknown", source, requirements.Grade)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSourceTextLeavesAmbiguousSpecializationUnknown(t *testing.T) {
|
||||
requirements := parseSourceText("Нужен backend developer и frontend engineer.", 1)
|
||||
if requirements.Specialization.Status != domain.NeedValueUnknown {
|
||||
t.Fatalf("specialization = %+v, want unknown for conflicting roles", requirements.Specialization)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSourceTextSkipsNegatedRequirements(t *testing.T) {
|
||||
requirements := parseSourceText("Не Senior и не требуется PostgreSQL; без Go.", 1)
|
||||
if requirements.Grade.Status != domain.NeedValueUnknown {
|
||||
t.Fatalf("grade = %+v, want unknown for a negated value", requirements.Grade)
|
||||
}
|
||||
if len(requirements.RequiredSkills) != 0 || len(requirements.DesiredSkills) != 0 {
|
||||
t.Fatalf("skills = required %v, desired %v; want no negated suggestions", requirements.RequiredSkills, requirements.DesiredSkills)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSourceTextUsesUnicodeAwareEnglishBoundaries(t *testing.T) {
|
||||
requirements := parseSourceText("ищем xjunior разработчика, разрабатываем goплатформу", 1)
|
||||
if requirements.Grade.Status != domain.NeedValueUnknown || len(requirements.RequiredSkills) != 0 {
|
||||
t.Fatalf("grade=%+v skills=%v; want no substring matches", requirements.Grade, requirements.RequiredSkills)
|
||||
}
|
||||
}
|
||||
|
||||
func needStringPointer(value string) *string { return &value }
|
||||
|
||||
func equalNeedStringPointer(left, right *string) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == right
|
||||
}
|
||||
return *left == *right
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
package need
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
createOperation = "organization_need.create"
|
||||
createLocation = "need.Service.Create"
|
||||
maxIdempotencyKeySize = 255
|
||||
maxCanonicalBodySize = 1 << 20
|
||||
purgeExpiredBatch = 100
|
||||
)
|
||||
|
||||
// Keyring computes scoped idempotency digests. identity.Keyring implements
|
||||
// this interface so need commands use the existing server secret and store.
|
||||
type Keyring interface {
|
||||
IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte
|
||||
Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte
|
||||
}
|
||||
|
||||
// Dependencies configure one stateless need service.
|
||||
type Dependencies struct {
|
||||
Transactor outbound.Transactor
|
||||
Keyring Keyring
|
||||
Clock func() time.Time
|
||||
}
|
||||
|
||||
// Service applies organization-scoped need commands and reads.
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
keyring Keyring
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
// NewService fails at startup when a required dependency is missing.
|
||||
func NewService(deps Dependencies) (*Service, error) {
|
||||
if deps.Transactor == nil || deps.Keyring == nil || deps.Clock == nil {
|
||||
return nil, errors.New("need.NewService - every dependency must be set")
|
||||
}
|
||||
return &Service{transactor: deps.Transactor, keyring: deps.Keyring, clock: deps.Clock}, nil
|
||||
}
|
||||
|
||||
// CreateCommand binds the authenticated actor and path organization to one
|
||||
// validated create request.
|
||||
type CreateCommand struct {
|
||||
ActorID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
IdempotencyKey string
|
||||
CanonicalBody []byte
|
||||
Input CreateInput
|
||||
}
|
||||
|
||||
// Create returns the original immutable response snapshot, including on an
|
||||
// identical retry after the live need has changed.
|
||||
func (service *Service) Create(ctx context.Context, command CreateCommand) (domain.NeedResponseSnapshot, error) {
|
||||
request, err := service.prepareCreate(command)
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, err
|
||||
}
|
||||
var result domain.NeedResponseSnapshot
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
result, err = service.createInTransaction(ctx, unit, command, request)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - run transaction: %w", createLocation, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (service *Service) createInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command CreateCommand,
|
||||
request createRequest,
|
||||
) (domain.NeedResponseSnapshot, error) {
|
||||
if err := authorizeNeedOwner(ctx, unit, command.ActorID, command.OrganizationID, createLocation); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, err
|
||||
}
|
||||
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - reserve idempotency record: %w", createLocation, err)
|
||||
}
|
||||
if !created {
|
||||
return replayNeedCreation(ctx, unit.NeedCreationResults(), request, command.OrganizationID, stored)
|
||||
}
|
||||
needID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - generate need ID: %w", createLocation, err)
|
||||
}
|
||||
createdNeed, err := createNeed(command.Input, command.OrganizationID, needID, request.now)
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - validate need: %w", createLocation, err)
|
||||
}
|
||||
snapshot := createdNeed.ResponseSnapshot()
|
||||
if err := validateCreationResultSize(snapshot); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - validate immutable creation response: %w", createLocation, err)
|
||||
}
|
||||
if err := unit.Needs().Create(ctx, createdNeed); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - store need: %w", createLocation, err)
|
||||
}
|
||||
if err := unit.NeedCreationResults().SaveCreationResult(ctx, request.scope, snapshot); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - store immutable creation response: %w", createLocation, err)
|
||||
}
|
||||
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err)
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
func replayNeedCreation(
|
||||
ctx context.Context,
|
||||
results outbound.NeedCreationResultRepository,
|
||||
request createRequest,
|
||||
organizationID uuid.UUID,
|
||||
stored outbound.IdempotencyRecord,
|
||||
) (domain.NeedResponseSnapshot, error) {
|
||||
if stored.Fingerprint != request.fingerprint {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - compare request fingerprint: %w", createLocation, ErrIdempotencyKeyReused)
|
||||
}
|
||||
snapshot, err := results.GetCreationResult(ctx, request.scope)
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - read immutable creation response: %w", createLocation, err)
|
||||
}
|
||||
result, err := domain.RestoreNeedResponseSnapshot(snapshot)
|
||||
if err != nil || result.Need.OrganizationID != organizationID {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - validate immutable creation response: %w", createLocation, domain.ErrInvalidNeed)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func validateCreationResultSize(snapshot domain.NeedResponseSnapshot) error {
|
||||
encoded, err := json.Marshal(snapshot)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - encode immutable creation response: %w", createLocation, err)
|
||||
}
|
||||
if len(encoded) > domain.MaxNeedCreationResultBytes {
|
||||
return invalidRequest("", "combined need response exceeds its storage bound")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type createRequest struct {
|
||||
fingerprint [outbound.IdempotencyDigestSize]byte
|
||||
scope [outbound.IdempotencyDigestSize]byte
|
||||
record outbound.IdempotencyRecord
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func (service *Service) prepareCreate(command CreateCommand) (createRequest, error) {
|
||||
const location = "need.Service.prepareCreate"
|
||||
switch {
|
||||
case command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil:
|
||||
return createRequest{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
|
||||
case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize:
|
||||
return createRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey)
|
||||
case len(command.CanonicalBody) == 0 || len(command.CanonicalBody) > maxCanonicalBodySize:
|
||||
return createRequest{}, fmt.Errorf("%s - canonical request body is outside its bound: %w", location, ErrInvalidCreateRequest)
|
||||
}
|
||||
fingerprint := service.keyring.Fingerprint(command.CanonicalBody)
|
||||
principal := command.ActorID.String() + ":" + command.OrganizationID.String()
|
||||
scope := service.keyring.IdempotencyScope(createOperation, command.IdempotencyKey, principal)
|
||||
now := service.clock().UTC().Truncate(time.Microsecond)
|
||||
if !validNeedApplicationTime(now) {
|
||||
return createRequest{}, invalidRequest("", "application time must be representable by the need contract")
|
||||
}
|
||||
expiresAt := now.Add(outbound.IdempotencyRetention)
|
||||
if !validNeedApplicationTime(expiresAt) {
|
||||
return createRequest{}, invalidRequest("", "idempotency expiry exceeds the need contract date range")
|
||||
}
|
||||
record := outbound.IdempotencyRecord{
|
||||
Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: expiresAt,
|
||||
}
|
||||
return createRequest{fingerprint: fingerprint, scope: scope, record: record, now: now}, nil
|
||||
}
|
||||
|
||||
// ListCommand selects an owner-scoped page of needs.
|
||||
type ListCommand struct {
|
||||
ActorID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
After *outbound.NeedListPosition
|
||||
Limit int32
|
||||
}
|
||||
|
||||
// List reads one page after checking the current account and owner membership
|
||||
// in the same transaction.
|
||||
func (service *Service) List(ctx context.Context, command ListCommand) (outbound.NeedPage, error) {
|
||||
const location = "need.Service.List"
|
||||
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil {
|
||||
return outbound.NeedPage{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
|
||||
}
|
||||
if command.Limit < 1 || command.Limit > outbound.MaxNeedPageSize {
|
||||
return outbound.NeedPage{}, fmt.Errorf("%s - page limit must be 1 to %d: %w", location, outbound.MaxNeedPageSize, domain.ErrInvalidNeed)
|
||||
}
|
||||
var result outbound.NeedPage
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeNeedOwner(ctx, unit, command.ActorID, command.OrganizationID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
page, err := unit.NeedLists().List(ctx, outbound.NeedListQuery{
|
||||
OrganizationID: command.OrganizationID, After: command.After, Limit: command.Limit,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - list organization needs: %w", location, err)
|
||||
}
|
||||
result = page
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.NeedPage{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Get reads the current need version for an active owner.
|
||||
func (service *Service) Get(ctx context.Context, actorID, organizationID, needID uuid.UUID) (domain.Need, error) {
|
||||
const location = "need.Service.Get"
|
||||
if actorID == uuid.Nil || organizationID == uuid.Nil || needID == uuid.Nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - actor, organization, and need IDs must be set: %w", location, ErrForbidden)
|
||||
}
|
||||
var result domain.Need
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeNeedOwner(ctx, unit, actorID, organizationID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
need, err := unit.Needs().Get(ctx, organizationID, needID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read organization need: %w", location, err)
|
||||
}
|
||||
result = need
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Update replaces the fields explicitly supplied by an active owner and
|
||||
// commits one immutable version when the merged request changes content.
|
||||
func (service *Service) Update(ctx context.Context, command UpdateCommand) (domain.Need, error) {
|
||||
const location = "need.Service.Update"
|
||||
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil || command.NeedID == uuid.Nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - actor, organization, and need IDs must be set: %w", location, ErrForbidden)
|
||||
}
|
||||
if command.Input.ExpectedVersion < 1 {
|
||||
return domain.Need{}, invalidRequest("/expected_version", "must be positive")
|
||||
}
|
||||
now := service.clock().UTC().Truncate(time.Microsecond)
|
||||
if !validNeedApplicationTime(now) {
|
||||
return domain.Need{}, invalidRequest("", "application time must be representable by the need contract")
|
||||
}
|
||||
var result domain.Need
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
result, err = service.updateInTransaction(ctx, unit, command, now)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func validNeedApplicationTime(value time.Time) bool {
|
||||
return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999
|
||||
}
|
||||
|
||||
func (service *Service) updateInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
command UpdateCommand,
|
||||
now time.Time,
|
||||
) (domain.Need, error) {
|
||||
const location = "need.Service.Update"
|
||||
if err := authorizeNeedOwner(ctx, unit, command.ActorID, command.OrganizationID, location); err != nil {
|
||||
return domain.Need{}, err
|
||||
}
|
||||
store := unit.Needs()
|
||||
current, err := store.Get(ctx, command.OrganizationID, command.NeedID)
|
||||
if err != nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - read organization need: %w", location, err)
|
||||
}
|
||||
updated, changed, err := reviseNeed(current, command.Input, now)
|
||||
if err != nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - merge need update: %w", location, err)
|
||||
}
|
||||
if !changed {
|
||||
return updated, nil
|
||||
}
|
||||
if err := store.Save(ctx, command.OrganizationID, command.NeedID, current.Version(), updated); err != nil {
|
||||
if !errors.Is(err, outbound.ErrNeedVersionConflict) {
|
||||
return domain.Need{}, fmt.Errorf("%s - append need version: %w", location, err)
|
||||
}
|
||||
return service.recoverConcurrentUpdate(ctx, store, command, now)
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func (service *Service) recoverConcurrentUpdate(
|
||||
ctx context.Context,
|
||||
store outbound.NeedRepository,
|
||||
command UpdateCommand,
|
||||
now time.Time,
|
||||
) (domain.Need, error) {
|
||||
const location = "need.Service.Update"
|
||||
latest, err := store.Get(ctx, command.OrganizationID, command.NeedID)
|
||||
if err != nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - read winning need version: %w", location, err)
|
||||
}
|
||||
latest, changed, err := reviseNeed(latest, command.Input, now)
|
||||
if err != nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - compare concurrent need update: %w", location, err)
|
||||
}
|
||||
if changed {
|
||||
return domain.Need{}, fmt.Errorf("%s - append need version: %w", location, outbound.ErrNeedVersionConflict)
|
||||
}
|
||||
return latest, nil
|
||||
}
|
||||
|
||||
// UpdateCommand binds one versioned replacement to a trusted actor and path.
|
||||
type UpdateCommand struct {
|
||||
ActorID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
NeedID uuid.UUID
|
||||
Input UpdateInput
|
||||
}
|
||||
|
||||
func authorizeNeedOwner(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
actorID, organizationID uuid.UUID,
|
||||
location string,
|
||||
) error {
|
||||
user, err := unit.Users().GetByID(ctx, actorID)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return fmt.Errorf("%s - require existing employer account: %w", location, ErrForbidden)
|
||||
}
|
||||
return fmt.Errorf("%s - read account: %w", location, err)
|
||||
}
|
||||
if user.Scenario != domain.ScenarioEmployer {
|
||||
return fmt.Errorf("%s - require employer account: %w", location, ErrForbidden)
|
||||
}
|
||||
if !user.EmailVerified() {
|
||||
return fmt.Errorf("%s - require verified email: %w", location, ErrEmailNotVerified)
|
||||
}
|
||||
membership, err := unit.Organizations().LockActiveMembership(ctx, organizationID, actorID)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrOrganizationNotFound) {
|
||||
return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound)
|
||||
}
|
||||
return fmt.Errorf("%s - lock active membership: %w", location, err)
|
||||
}
|
||||
if membership.Role() != domain.OrganizationRoleOwner {
|
||||
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
package need
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type serviceTestKeyring struct{}
|
||||
|
||||
func (serviceTestKeyring) IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte {
|
||||
return sha256.Sum256([]byte(operation + "\x00" + key + "\x00" + principal))
|
||||
}
|
||||
|
||||
func (serviceTestKeyring) Fingerprint(body []byte) [outbound.IdempotencyDigestSize]byte {
|
||||
return sha256.Sum256(body)
|
||||
}
|
||||
|
||||
type serviceTestState struct {
|
||||
users map[uuid.UUID]domain.User
|
||||
memberships map[serviceTestMembershipKey]domain.Membership
|
||||
needs map[serviceTestNeedKey]domain.Need
|
||||
versions map[serviceTestVersionKey]domain.Need
|
||||
idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord
|
||||
results map[[outbound.IdempotencyDigestSize]byte]domain.NeedResponseSnapshot
|
||||
createCount int
|
||||
updateCount int
|
||||
}
|
||||
|
||||
type serviceTestMembershipKey struct {
|
||||
organizationID uuid.UUID
|
||||
userID uuid.UUID
|
||||
}
|
||||
|
||||
type serviceTestNeedKey struct {
|
||||
organizationID uuid.UUID
|
||||
needID uuid.UUID
|
||||
}
|
||||
|
||||
type serviceTestVersionKey struct {
|
||||
serviceTestNeedKey
|
||||
|
||||
version int64
|
||||
}
|
||||
|
||||
func newServiceTestState() serviceTestState {
|
||||
return serviceTestState{
|
||||
users: map[uuid.UUID]domain.User{}, memberships: map[serviceTestMembershipKey]domain.Membership{},
|
||||
needs: map[serviceTestNeedKey]domain.Need{}, versions: map[serviceTestVersionKey]domain.Need{},
|
||||
idempotency: map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord{},
|
||||
results: map[[outbound.IdempotencyDigestSize]byte]domain.NeedResponseSnapshot{},
|
||||
}
|
||||
}
|
||||
|
||||
func (state serviceTestState) clone() serviceTestState {
|
||||
cloned := newServiceTestState()
|
||||
for id, user := range state.users {
|
||||
cloned.users[id] = user
|
||||
}
|
||||
for key, membership := range state.memberships {
|
||||
cloned.memberships[key] = membership
|
||||
}
|
||||
for key, need := range state.needs {
|
||||
copyNeed, err := domain.RestoreNeed(need.Snapshot())
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
cloned.needs[key] = copyNeed
|
||||
}
|
||||
for key, need := range state.versions {
|
||||
copyNeed, err := domain.RestoreNeed(need.Snapshot())
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
cloned.versions[key] = copyNeed
|
||||
}
|
||||
for scope, record := range state.idempotency {
|
||||
cloned.idempotency[scope] = record
|
||||
}
|
||||
for scope, result := range state.results {
|
||||
copyResult, err := domain.RestoreNeedResponseSnapshot(result)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
cloned.results[scope] = copyResult
|
||||
}
|
||||
cloned.createCount = state.createCount
|
||||
cloned.updateCount = state.updateCount
|
||||
return cloned
|
||||
}
|
||||
|
||||
type serviceTestTransactor struct {
|
||||
mu sync.Mutex
|
||||
|
||||
state serviceTestState
|
||||
failResultSave bool
|
||||
}
|
||||
|
||||
func newServiceTestTransactor(state serviceTestState) *serviceTestTransactor {
|
||||
return &serviceTestTransactor{state: state}
|
||||
}
|
||||
|
||||
func (transactor *serviceTestTransactor) WithinTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error {
|
||||
transactor.mu.Lock()
|
||||
defer transactor.mu.Unlock()
|
||||
working := transactor.state.clone()
|
||||
unit := &serviceTestUnit{state: &working, failResultSave: transactor.failResultSave}
|
||||
if err := work(ctx, unit); err != nil {
|
||||
return err
|
||||
}
|
||||
transactor.state = working
|
||||
return nil
|
||||
}
|
||||
|
||||
func (transactor *serviceTestTransactor) snapshot() serviceTestState {
|
||||
transactor.mu.Lock()
|
||||
defer transactor.mu.Unlock()
|
||||
return transactor.state.clone()
|
||||
}
|
||||
|
||||
type serviceTestUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
state *serviceTestState
|
||||
failResultSave bool
|
||||
}
|
||||
|
||||
func (unit *serviceTestUnit) Users() outbound.UserRepository {
|
||||
return serviceTestUsers{state: unit.state}
|
||||
}
|
||||
|
||||
func (unit *serviceTestUnit) Organizations() outbound.OrganizationRepository {
|
||||
return serviceTestOrganizations{state: unit.state}
|
||||
}
|
||||
|
||||
func (unit *serviceTestUnit) IdempotencyRecords() outbound.IdempotencyRepository {
|
||||
return serviceTestIdempotency{state: unit.state}
|
||||
}
|
||||
|
||||
func (unit *serviceTestUnit) Needs() outbound.NeedRepository {
|
||||
return serviceTestNeeds{state: unit.state, failResultSave: unit.failResultSave}
|
||||
}
|
||||
|
||||
func (unit *serviceTestUnit) NeedLists() outbound.NeedListRepository {
|
||||
return serviceTestNeeds{state: unit.state, failResultSave: unit.failResultSave}
|
||||
}
|
||||
|
||||
func (unit *serviceTestUnit) NeedCreationResults() outbound.NeedCreationResultRepository {
|
||||
return serviceTestNeeds{state: unit.state, failResultSave: unit.failResultSave}
|
||||
}
|
||||
|
||||
type serviceTestUsers struct {
|
||||
outbound.UserRepository
|
||||
|
||||
state *serviceTestState
|
||||
}
|
||||
|
||||
func (repository serviceTestUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
|
||||
user, ok := repository.state.users[id]
|
||||
if !ok {
|
||||
return domain.User{}, outbound.ErrUserNotFound
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
type serviceTestOrganizations struct {
|
||||
outbound.OrganizationRepository
|
||||
|
||||
state *serviceTestState
|
||||
}
|
||||
|
||||
func (repository serviceTestOrganizations) LockActiveMembership(_ context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) {
|
||||
membership, ok := repository.state.memberships[serviceTestMembershipKey{organizationID: organizationID, userID: userID}]
|
||||
if !ok || !membership.GrantsAccess() {
|
||||
return domain.Membership{}, outbound.ErrOrganizationNotFound
|
||||
}
|
||||
return membership, nil
|
||||
}
|
||||
|
||||
type serviceTestIdempotency struct {
|
||||
outbound.IdempotencyRepository
|
||||
|
||||
state *serviceTestState
|
||||
}
|
||||
|
||||
func (repository serviceTestIdempotency) Reserve(_ context.Context, record outbound.IdempotencyRecord) (outbound.IdempotencyRecord, bool, error) {
|
||||
if existing, ok := repository.state.idempotency[record.Scope]; ok && existing.ExpiresAt.After(record.CreatedAt) {
|
||||
return existing, false, nil
|
||||
}
|
||||
repository.state.idempotency[record.Scope] = record
|
||||
return record, true, nil
|
||||
}
|
||||
|
||||
func (repository serviceTestIdempotency) Find(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, at time.Time) (outbound.IdempotencyRecord, error) {
|
||||
record, ok := repository.state.idempotency[scope]
|
||||
if !ok || !record.ExpiresAt.After(at) {
|
||||
return outbound.IdempotencyRecord{}, outbound.ErrIdempotencyRecordNotFound
|
||||
}
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func (repository serviceTestIdempotency) PurgeExpired(_ context.Context, at time.Time, limit int32) (int64, error) {
|
||||
var deleted int64
|
||||
for scope, record := range repository.state.idempotency {
|
||||
if deleted >= int64(limit) {
|
||||
break
|
||||
}
|
||||
if !record.ExpiresAt.After(at) {
|
||||
delete(repository.state.idempotency, scope)
|
||||
delete(repository.state.results, scope)
|
||||
deleted++
|
||||
}
|
||||
}
|
||||
return deleted, nil
|
||||
}
|
||||
|
||||
type serviceTestNeeds struct {
|
||||
outbound.NeedRepository
|
||||
|
||||
state *serviceTestState
|
||||
failResultSave bool
|
||||
}
|
||||
|
||||
func (repository serviceTestNeeds) Create(_ context.Context, need domain.Need) error {
|
||||
key := serviceTestNeedKey{organizationID: need.OrganizationID(), needID: need.ID()}
|
||||
if _, exists := repository.state.needs[key]; exists {
|
||||
return outbound.ErrNeedAlreadyExists
|
||||
}
|
||||
repository.state.needs[key] = need
|
||||
repository.state.versions[serviceTestVersionKey{serviceTestNeedKey: key, version: need.Version()}] = need
|
||||
repository.state.createCount++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository serviceTestNeeds) Get(_ context.Context, organizationID, needID uuid.UUID) (domain.Need, error) {
|
||||
need, ok := repository.state.needs[serviceTestNeedKey{organizationID: organizationID, needID: needID}]
|
||||
if !ok {
|
||||
return domain.Need{}, outbound.ErrNeedNotFound
|
||||
}
|
||||
return need, nil
|
||||
}
|
||||
|
||||
func (repository serviceTestNeeds) GetVersion(_ context.Context, organizationID, needID uuid.UUID, version int64) (domain.Need, error) {
|
||||
need, ok := repository.state.versions[serviceTestVersionKey{serviceTestNeedKey: serviceTestNeedKey{organizationID: organizationID, needID: needID}, version: version}]
|
||||
if !ok {
|
||||
return domain.Need{}, outbound.ErrNeedNotFound
|
||||
}
|
||||
return need, nil
|
||||
}
|
||||
|
||||
func (repository serviceTestNeeds) Save(_ context.Context, organizationID, needID uuid.UUID, expectedVersion int64, next domain.Need) error {
|
||||
key := serviceTestNeedKey{organizationID: organizationID, needID: needID}
|
||||
current, ok := repository.state.needs[key]
|
||||
if !ok {
|
||||
return outbound.ErrNeedNotFound
|
||||
}
|
||||
if !current.IsNextVersionOf(next, expectedVersion) {
|
||||
return outbound.ErrNeedVersionConflict
|
||||
}
|
||||
repository.state.needs[key] = next
|
||||
repository.state.versions[serviceTestVersionKey{serviceTestNeedKey: key, version: next.Version()}] = next
|
||||
repository.state.updateCount++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository serviceTestNeeds) List(_ context.Context, query outbound.NeedListQuery) (outbound.NeedPage, error) {
|
||||
items := make([]domain.Need, 0)
|
||||
for key, need := range repository.state.needs {
|
||||
if key.organizationID != query.OrganizationID {
|
||||
continue
|
||||
}
|
||||
position := outbound.NeedCreationPosition(need)
|
||||
if query.After != nil && needPositionIsNotBefore(position, *query.After) {
|
||||
continue
|
||||
}
|
||||
items = append(items, need)
|
||||
}
|
||||
for left := 0; left < len(items); left++ {
|
||||
for right := left + 1; right < len(items); right++ {
|
||||
leftPosition, rightPosition := outbound.NeedCreationPosition(items[left]), outbound.NeedCreationPosition(items[right])
|
||||
if rightPosition.CreatedAt.After(leftPosition.CreatedAt) || rightPosition.CreatedAt.Equal(leftPosition.CreatedAt) && rightPosition.NeedID.String() > leftPosition.NeedID.String() {
|
||||
items[left], items[right] = items[right], items[left]
|
||||
}
|
||||
}
|
||||
}
|
||||
page := outbound.NeedPage{Items: make([]domain.Need, 0, min(int(query.Limit), len(items)))}
|
||||
if len(items) > int(query.Limit) {
|
||||
page.HasMore = true
|
||||
items = items[:query.Limit]
|
||||
}
|
||||
page.Items = append(page.Items, items...)
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func needPositionIsNotBefore(position, after outbound.NeedListPosition) bool {
|
||||
if position.CreatedAt.After(after.CreatedAt) {
|
||||
return true
|
||||
}
|
||||
if position.CreatedAt.Before(after.CreatedAt) {
|
||||
return false
|
||||
}
|
||||
return position.NeedID.String() >= after.NeedID.String()
|
||||
}
|
||||
|
||||
func (repository serviceTestNeeds) SaveCreationResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, snapshot domain.NeedResponseSnapshot) error {
|
||||
if repository.failResultSave {
|
||||
return errors.New("simulated response snapshot failure")
|
||||
}
|
||||
if _, ok := repository.state.idempotency[scope]; !ok {
|
||||
return outbound.ErrIdempotencyRecordNotFound
|
||||
}
|
||||
repository.state.results[scope] = snapshot
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository serviceTestNeeds) GetCreationResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (domain.NeedResponseSnapshot, error) {
|
||||
snapshot, ok := repository.state.results[scope]
|
||||
if !ok {
|
||||
return domain.NeedResponseSnapshot{}, outbound.ErrNeedCreationResultNotFound
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
func newNeedServiceHarness(t *testing.T) (*Service, *serviceTestTransactor, uuid.UUID, uuid.UUID, func(time.Time)) {
|
||||
t.Helper()
|
||||
now := time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC)
|
||||
current := now
|
||||
userID, organizationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7())
|
||||
verifiedAt := now.Add(-time.Hour)
|
||||
state := newServiceTestState()
|
||||
state.users[userID] = domain.User{ID: userID, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verifiedAt}
|
||||
membership, err := domain.NewOwnerMembership(organizationID, userID, now)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOwnerMembership() error = %v", err)
|
||||
}
|
||||
state.memberships[serviceTestMembershipKey{organizationID: organizationID, userID: userID}] = membership
|
||||
transactor := newServiceTestTransactor(state)
|
||||
service, err := NewService(Dependencies{Transactor: transactor, Keyring: serviceTestKeyring{}, Clock: func() time.Time { return current }})
|
||||
if err != nil {
|
||||
t.Fatalf("NewService() error = %v", err)
|
||||
}
|
||||
setTime := func(value time.Time) { current = value }
|
||||
return service, transactor, userID, organizationID, setTime
|
||||
}
|
||||
|
||||
func testNeedCreateCommand(actorID, organizationID uuid.UUID, key, title string) CreateCommand {
|
||||
return CreateCommand{
|
||||
ActorID: actorID, OrganizationID: organizationID, IdempotencyKey: key,
|
||||
CanonicalBody: []byte(fmt.Sprintf(`{"title":%q}`, title)),
|
||||
Input: CreateInput{Title: title},
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateReplaysOriginalNeedAfterUpdate(t *testing.T) {
|
||||
service, transactor, actorID, organizationID, _ := newNeedServiceHarness(t)
|
||||
command := testNeedCreateCommand(actorID, organizationID, "request-1", "Initial need")
|
||||
created, err := service.Create(t.Context(), command)
|
||||
if err != nil {
|
||||
t.Fatalf("Create() error = %v", err)
|
||||
}
|
||||
updated, err := service.Update(t.Context(), UpdateCommand{
|
||||
ActorID: actorID, OrganizationID: organizationID, NeedID: created.Need.ID,
|
||||
Input: UpdateInput{ExpectedVersion: 1, Title: Field[string]{Set: true, Value: "Updated need"}},
|
||||
})
|
||||
if err != nil || updated.Version() != 2 {
|
||||
t.Fatalf("Update() version = %d, error = %v", updated.Version(), err)
|
||||
}
|
||||
replayed, err := service.Create(t.Context(), command)
|
||||
if err != nil || replayed.Need.ID != created.Need.ID || replayed.Need.Version != 1 || replayed.Need.Title != "Initial need" {
|
||||
t.Fatalf("Create(retry) = id %s version %d title %q error %v, want the original response", replayed.Need.ID, replayed.Need.Version, replayed.Need.Title, err)
|
||||
}
|
||||
current, err := service.Get(t.Context(), actorID, organizationID, created.Need.ID)
|
||||
if err != nil || current.Version() != 2 || current.Snapshot().Title != "Updated need" {
|
||||
t.Fatalf("Get after replay = version %d title %q error %v", current.Version(), current.Snapshot().Title, err)
|
||||
}
|
||||
state := transactor.snapshot()
|
||||
if state.createCount != 1 || state.updateCount != 1 {
|
||||
t.Fatalf("stored creates = %d updates = %d, want 1 create and 1 update", state.createCount, state.updateCount)
|
||||
}
|
||||
command.CanonicalBody = []byte(`{"title":"Different body"}`)
|
||||
command.Input.Title = "Different body"
|
||||
if _, err := service.Create(t.Context(), command); !errors.Is(err, ErrIdempotencyKeyReused) {
|
||||
t.Fatalf("Create(same key, changed body) error = %v, want ErrIdempotencyKeyReused", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateReusesExpiredIdempotencyScopeAtExactDeadline(t *testing.T) {
|
||||
service, transactor, actorID, organizationID, setTime := newNeedServiceHarness(t)
|
||||
firstCommand := testNeedCreateCommand(actorID, organizationID, "request-2", "Before expiry")
|
||||
first, err := service.Create(t.Context(), firstCommand)
|
||||
if err != nil {
|
||||
t.Fatalf("Create(first) error = %v", err)
|
||||
}
|
||||
setTime(first.Need.CreatedAt.Add(outbound.IdempotencyRetention))
|
||||
secondCommand := testNeedCreateCommand(actorID, organizationID, "request-2", "After expiry")
|
||||
second, err := service.Create(t.Context(), secondCommand)
|
||||
if err != nil || second.Need.ID == first.Need.ID || second.Need.Title != "After expiry" {
|
||||
t.Fatalf("Create(expired key) = id %s title %q error %v", second.Need.ID, second.Need.Title, err)
|
||||
}
|
||||
state := transactor.snapshot()
|
||||
if state.createCount != 2 || len(state.results) != 1 {
|
||||
t.Fatalf("stored creates = %d results = %d, want two creates and one replaced snapshot", state.createCount, len(state.results))
|
||||
}
|
||||
replayed, err := service.Create(t.Context(), secondCommand)
|
||||
if err != nil || replayed.Need.ID != second.Need.ID || replayed.Need.Title != "After expiry" {
|
||||
t.Fatalf("Create(replay after reuse) = id %s title %q error %v", replayed.Need.ID, replayed.Need.Title, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRejectsIdempotencyExpiryOutsideNeedDateRange(t *testing.T) {
|
||||
service, transactor, actorID, organizationID, setTime := newNeedServiceHarness(t)
|
||||
setTime(time.Date(9999, time.December, 31, 23, 59, 59, 0, time.UTC))
|
||||
if _, err := service.Create(t.Context(), testNeedCreateCommand(actorID, organizationID, "request-edge", "Edge need")); !errors.Is(err, ErrInvalidRequest) {
|
||||
t.Fatalf("Create() at the final contract date error = %v, want ErrInvalidRequest for 24-hour expiry", err)
|
||||
}
|
||||
state := transactor.snapshot()
|
||||
if state.createCount != 0 || len(state.idempotency) != 0 || len(state.results) != 0 {
|
||||
t.Fatalf("out-of-range expiry wrote state: creates=%d keys=%d results=%d", state.createCount, len(state.idempotency), len(state.results))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRollbackLeavesNoNeedOrReplayResult(t *testing.T) {
|
||||
service, transactor, actorID, organizationID, _ := newNeedServiceHarness(t)
|
||||
transactor.failResultSave = true
|
||||
command := testNeedCreateCommand(actorID, organizationID, "request-3", "Rollback need")
|
||||
if _, err := service.Create(t.Context(), command); err == nil {
|
||||
t.Fatal("Create() succeeded despite result snapshot failure")
|
||||
}
|
||||
state := transactor.snapshot()
|
||||
if state.createCount != 0 || len(state.needs) != 0 || len(state.idempotency) != 0 || len(state.results) != 0 {
|
||||
t.Fatalf("failed create left state: creates %d needs %d keys %d results %d", state.createCount, len(state.needs), len(state.idempotency), len(state.results))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentCreateWithSameKeyCreatesOneNeed(t *testing.T) {
|
||||
service, transactor, actorID, organizationID, _ := newNeedServiceHarness(t)
|
||||
command := testNeedCreateCommand(actorID, organizationID, "request-4", "One need")
|
||||
var group sync.WaitGroup
|
||||
errorsFound := make(chan error, 2)
|
||||
ids := make(chan uuid.UUID, 2)
|
||||
for range 2 {
|
||||
group.Go(func() {
|
||||
result, err := service.Create(t.Context(), command)
|
||||
if err != nil {
|
||||
errorsFound <- err
|
||||
return
|
||||
}
|
||||
ids <- result.Need.ID
|
||||
})
|
||||
}
|
||||
group.Wait()
|
||||
close(errorsFound)
|
||||
for err := range errorsFound {
|
||||
t.Fatalf("concurrent Create() error = %v", err)
|
||||
}
|
||||
close(ids)
|
||||
var first uuid.UUID
|
||||
for id := range ids {
|
||||
if first != uuid.Nil && first != id {
|
||||
t.Fatalf("concurrent calls returned different need IDs: %s and %s", first, id)
|
||||
}
|
||||
first = id
|
||||
}
|
||||
state := transactor.snapshot()
|
||||
if first == uuid.Nil || state.createCount != 1 || len(state.needs) != 1 {
|
||||
t.Fatalf("concurrent calls left ID %s, creates %d, needs %d", first, state.createCount, len(state.needs))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user