1593 lines
66 KiB
Go
1593 lines
66 KiB
Go
package domain
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"regexp"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
// ErrCandidateProfileVersionConflict reports that the expected version of a
|
|
// profile is not the current one: another save advanced it, or the client
|
|
// named a version that does not exist. Nothing was changed; the client reads
|
|
// the profile again.
|
|
var ErrCandidateProfileVersionConflict = errors.New("candidate profile changed concurrently")
|
|
|
|
// ErrInvalidCandidateProfile reports a candidate profile value, decision, or
|
|
// stored profile that breaks a rule.
|
|
var ErrInvalidCandidateProfile = errors.New("invalid candidate profile")
|
|
|
|
// CandidateProfileFieldError reports the request field of a candidate profile
|
|
// that broke a rule. It matches ErrInvalidCandidateProfile with errors.Is, and
|
|
// an HTTP adapter reads Pointer with errors.As to answer 400 with the pointer
|
|
// of the field. Reason is fixed text; neither field quotes the submitted
|
|
// value, which is personal data.
|
|
type CandidateProfileFieldError struct {
|
|
// Pointer is the JSON Pointer of the field in the request body, such as
|
|
// "/contacts/phone/value" or "/roles/1/specialization".
|
|
Pointer string
|
|
// Reason says which rule the field broke.
|
|
Reason string
|
|
// stateDependent marks a rule that is judged against the stored claims,
|
|
// such as a decision extracted: against a stale version the verdict is
|
|
// meaningless, so Replace answers a version conflict instead.
|
|
stateDependent bool
|
|
}
|
|
|
|
func (err *CandidateProfileFieldError) Error() string {
|
|
return "candidate profile field " + err.Pointer + " " + err.Reason
|
|
}
|
|
|
|
func (err *CandidateProfileFieldError) Unwrap() error { return ErrInvalidCandidateProfile }
|
|
|
|
func invalidStateDependentProfileField(location, pointer, reason string) error {
|
|
return fmt.Errorf("%s - %w", location, &CandidateProfileFieldError{Pointer: pointer, Reason: reason, stateDependent: true})
|
|
}
|
|
|
|
func invalidProfileField(location, pointer, reason string) error {
|
|
return fmt.Errorf("%s - %w", location, &CandidateProfileFieldError{Pointer: pointer, Reason: reason})
|
|
}
|
|
|
|
const (
|
|
// The bounds match the schemas of the public contract and the CHECK
|
|
// constraints of candidate_profile_claims. The full name bound is the one
|
|
// of ContactFullName, so a contact disclosure never has to cut it.
|
|
maxProfileFullNameRunes = 200
|
|
maxProfileLocationRunes = 100
|
|
maxProfileTagRunes = 50
|
|
maxProfileEmployerRunes = 200
|
|
maxProfileSummaryRunes = 1000
|
|
maxProfileQuoteRunes = 300
|
|
maxProfileStackItems = 30
|
|
maxProfileExperienceItems = 20
|
|
maxProfileSoftSkills = 10
|
|
// minProfileSalaryAmount is also the step of an amount: PRD FR13 sets 1000
|
|
// roubles for the bounds of a salary.
|
|
minProfileSalaryAmount = 1000
|
|
maxProfileSalaryAmount = 100_000_000
|
|
// profileCurrency and profilePeriod are the only values of the MVP.
|
|
profileCurrency = "RUB"
|
|
profilePeriod = "month"
|
|
|
|
// ProfileClaimTrustLevel is the trust level of every profile claim.
|
|
// Whatever its origin, a claim is an unverified statement; a candidate
|
|
// confirming a suggestion changes its status, never its level. Higher
|
|
// levels belong to evidence, such as an assessment result, which is
|
|
// stored elsewhere and never written into a claim.
|
|
ProfileClaimTrustLevel = 0
|
|
)
|
|
|
|
var (
|
|
// profileMonthPattern is the YYYY-MM format of ProfileYearMonth.
|
|
profileMonthPattern = regexp.MustCompile(`^[0-9]{4}-(0[1-9]|1[0-2])$`)
|
|
// profileExtractionLabelPattern is the format of an extractor version.
|
|
profileExtractionLabelPattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`)
|
|
)
|
|
|
|
// SpecializationCode is the stable code of a catalog specialization. A
|
|
// category is a specialization together with a confirmed grade; the code
|
|
// values match the SpecializationCode schema of the public contract.
|
|
type SpecializationCode string
|
|
|
|
const (
|
|
SpecializationBackend SpecializationCode = "backend"
|
|
SpecializationFrontend SpecializationCode = "frontend"
|
|
SpecializationMobile SpecializationCode = "mobile"
|
|
SpecializationNetworkEngineer SpecializationCode = "network_engineer"
|
|
SpecializationDevopsSRE SpecializationCode = "devops_sre"
|
|
SpecializationDataAnalyst SpecializationCode = "data_analyst"
|
|
SpecializationDSML SpecializationCode = "ds_ml"
|
|
SpecializationInformationSecurity SpecializationCode = "information_security"
|
|
SpecializationQA SpecializationCode = "qa"
|
|
)
|
|
|
|
// specializationCodes lists the catalog in catalog order.
|
|
var specializationCodes = []SpecializationCode{
|
|
SpecializationBackend, SpecializationFrontend, SpecializationMobile, SpecializationNetworkEngineer,
|
|
SpecializationDevopsSRE, SpecializationDataAnalyst, SpecializationDSML, SpecializationInformationSecurity,
|
|
SpecializationQA,
|
|
}
|
|
|
|
// IsKnown reports whether code is a specialization of the catalog.
|
|
func (code SpecializationCode) IsKnown() bool { return slices.Contains(specializationCodes, code) }
|
|
|
|
// SpecializationCatalog returns the specializations in catalog order. The
|
|
// result is a copy that the caller may change.
|
|
func SpecializationCatalog() []SpecializationCode { return slices.Clone(specializationCodes) }
|
|
|
|
// GradeCode is a grade of the MVP scale. The same codes describe a
|
|
// self-assessed grade, which the candidate states, and a confirmed grade,
|
|
// which only an assessment result establishes; a profile stores only the
|
|
// first. The values match the GradeCode schema of the public contract.
|
|
type GradeCode string
|
|
|
|
const (
|
|
GradeIntern GradeCode = "intern"
|
|
GradeJunior GradeCode = "junior"
|
|
GradeMiddle GradeCode = "middle"
|
|
GradeSenior GradeCode = "senior"
|
|
)
|
|
|
|
// IsKnown reports whether code is a grade of the scale.
|
|
func (code GradeCode) IsKnown() bool {
|
|
switch code {
|
|
case GradeIntern, GradeJunior, GradeMiddle, GradeSenior:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
// ProfileClaimStatus is the confirmation state of a stored profile value. A
|
|
// value that does not exist has no claim at all, which is the contract's
|
|
// `unknown` state. Values match the ProfileItemStatus schema.
|
|
type ProfileClaimStatus string
|
|
|
|
const (
|
|
// ProfileClaimConfirmed means the candidate typed the value or confirmed
|
|
// a suggestion.
|
|
ProfileClaimConfirmed ProfileClaimStatus = "confirmed"
|
|
// ProfileClaimExtracted means the value is a suggestion from an imported
|
|
// document or source that nobody has confirmed yet.
|
|
ProfileClaimExtracted ProfileClaimStatus = "extracted"
|
|
)
|
|
|
|
// ProfileClaimOrigin says where a claim came from. Values match the
|
|
// ProfileClaimOrigin schema. Only manual claims exist before an import is
|
|
// built; the import origins are planned.
|
|
type ProfileClaimOrigin string
|
|
|
|
const (
|
|
ProfileOriginManual ProfileClaimOrigin = "manual"
|
|
ProfileOriginExtractedFromResume ProfileClaimOrigin = "extracted_from_resume"
|
|
ProfileOriginImported ProfileClaimOrigin = "imported"
|
|
)
|
|
|
|
// ProfileClaimSource is the provenance of one claim: its origin, the excerpt
|
|
// and extractor version of an import, and the time the candidate confirmed
|
|
// it. It holds no reference to a file, the ML service, or an FSP account: a
|
|
// profile never requires one. The quote can hold personal data, so String,
|
|
// GoString, Format, and LogValue redact the source.
|
|
type ProfileClaimSource struct {
|
|
origin ProfileClaimOrigin
|
|
quote string
|
|
extractionVersion string
|
|
confirmedAt time.Time
|
|
}
|
|
|
|
const redactedProfile = "[redacted candidate profile]"
|
|
|
|
// NewManualProfileClaimSource returns the source of a value that the
|
|
// candidate typed at the given time.
|
|
func NewManualProfileClaimSource(confirmedAt time.Time) (ProfileClaimSource, error) {
|
|
const location = "domain.NewManualProfileClaimSource"
|
|
if confirmedAt.IsZero() {
|
|
return ProfileClaimSource{}, fmt.Errorf("%s - time must be set: %w", location, ErrInvalidCandidateProfile)
|
|
}
|
|
return ProfileClaimSource{origin: ProfileOriginManual, confirmedAt: confirmedAt}, nil
|
|
}
|
|
|
|
// RestoreProfileClaimSource validates the provenance columns of a stored
|
|
// claim. confirmedAt is the zero time for an unconfirmed suggestion. A row
|
|
// that breaks the provenance rules fails with ErrInvalidCandidateProfile.
|
|
func RestoreProfileClaimSource(
|
|
origin ProfileClaimOrigin, trustLevel int, quote, extractionVersion string, confirmedAt time.Time,
|
|
) (ProfileClaimSource, error) {
|
|
const location = "domain.RestoreProfileClaimSource"
|
|
fail := func(reason string) (ProfileClaimSource, error) {
|
|
return ProfileClaimSource{}, fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidCandidateProfile)
|
|
}
|
|
if trustLevel != ProfileClaimTrustLevel {
|
|
return fail("every claim has trust level 0")
|
|
}
|
|
switch origin {
|
|
case ProfileOriginManual:
|
|
if quote != "" || extractionVersion != "" || confirmedAt.IsZero() {
|
|
return fail("a manual claim is confirmed and has no import data")
|
|
}
|
|
case ProfileOriginExtractedFromResume, ProfileOriginImported:
|
|
if !profileExtractionLabelPattern.MatchString(extractionVersion) {
|
|
return fail("an imported claim must name its extractor version")
|
|
}
|
|
if quote != "" && !validProfileQuote(quote) {
|
|
return fail("quote must be 1 to 300 characters without control characters")
|
|
}
|
|
default:
|
|
return fail("origin is unknown")
|
|
}
|
|
return ProfileClaimSource{origin: origin, quote: quote, extractionVersion: extractionVersion, confirmedAt: confirmedAt}, nil
|
|
}
|
|
|
|
func validProfileQuote(quote string) bool {
|
|
return utf8.ValidString(quote) && utf8.RuneCountInString(quote) <= maxProfileQuoteRunes &&
|
|
!strings.ContainsFunc(quote, func(character rune) bool { return character != '\n' && isForbiddenTextRune(character) })
|
|
}
|
|
|
|
func (source ProfileClaimSource) Origin() ProfileClaimOrigin { return source.origin }
|
|
|
|
// TrustLevel returns the trust level of the claim, always
|
|
// ProfileClaimTrustLevel.
|
|
func (source ProfileClaimSource) TrustLevel() int { return ProfileClaimTrustLevel }
|
|
|
|
// Quote returns the excerpt of the imported document, or "" for a manual
|
|
// value or an import without an excerpt.
|
|
func (source ProfileClaimSource) Quote() string { return source.quote }
|
|
|
|
// ExtractionVersion returns the extractor version of an imported claim, or ""
|
|
// for a manual one.
|
|
func (source ProfileClaimSource) ExtractionVersion() string { return source.extractionVersion }
|
|
|
|
// ConfirmedAt returns the time the candidate typed or confirmed the value, or
|
|
// the zero time while it is an unconfirmed suggestion.
|
|
func (source ProfileClaimSource) ConfirmedAt() time.Time { return source.confirmedAt }
|
|
|
|
func (source ProfileClaimSource) confirm(at time.Time) ProfileClaimSource {
|
|
source.confirmedAt = at
|
|
return source
|
|
}
|
|
|
|
func (source ProfileClaimSource) String() string { return redactedProfile }
|
|
func (source ProfileClaimSource) GoString() string { return redactedProfile }
|
|
func (source ProfileClaimSource) LogValue() slog.Value {
|
|
return slog.StringValue(redactedProfile)
|
|
}
|
|
func (source ProfileClaimSource) Format(state fmt.State, _ rune) {
|
|
writeRedacted(state, redactedProfile)
|
|
}
|
|
|
|
// ProfileClaim is one stored profile value with its status and provenance.
|
|
// The value is personal data of the candidate, so String, GoString, Format,
|
|
// and LogValue redact the claim.
|
|
type ProfileClaim[V comparable] struct {
|
|
value V
|
|
status ProfileClaimStatus
|
|
source ProfileClaimSource
|
|
}
|
|
|
|
// RestoreProfileClaim returns a claim from a stored value. The status must
|
|
// agree with the source: a confirmed claim has a confirmation time and an
|
|
// unconfirmed suggestion has none and is an import.
|
|
func RestoreProfileClaim[V comparable](value V, status ProfileClaimStatus, source ProfileClaimSource) (ProfileClaim[V], error) {
|
|
const location = "domain.RestoreProfileClaim"
|
|
switch {
|
|
case source.origin == "":
|
|
return ProfileClaim[V]{}, fmt.Errorf("%s - source must be built by a source constructor: %w", location, ErrInvalidCandidateProfile)
|
|
case status == ProfileClaimConfirmed && source.confirmedAt.IsZero():
|
|
return ProfileClaim[V]{}, fmt.Errorf("%s - a confirmed claim needs its confirmation time: %w", location, ErrInvalidCandidateProfile)
|
|
case status == ProfileClaimExtracted && (!source.confirmedAt.IsZero() || source.origin == ProfileOriginManual):
|
|
return ProfileClaim[V]{}, fmt.Errorf("%s - a suggestion is an unconfirmed import: %w", location, ErrInvalidCandidateProfile)
|
|
case status != ProfileClaimConfirmed && status != ProfileClaimExtracted:
|
|
return ProfileClaim[V]{}, fmt.Errorf("%s - status is unknown: %w", location, ErrInvalidCandidateProfile)
|
|
}
|
|
return ProfileClaim[V]{value: value, status: status, source: source}, nil
|
|
}
|
|
|
|
func (claim ProfileClaim[V]) Value() V { return claim.value }
|
|
func (claim ProfileClaim[V]) Status() ProfileClaimStatus { return claim.status }
|
|
func (claim ProfileClaim[V]) Source() ProfileClaimSource { return claim.source }
|
|
|
|
func (claim ProfileClaim[V]) String() string { return redactedProfile }
|
|
func (claim ProfileClaim[V]) GoString() string { return redactedProfile }
|
|
func (claim ProfileClaim[V]) LogValue() slog.Value {
|
|
return slog.StringValue(redactedProfile)
|
|
}
|
|
func (claim ProfileClaim[V]) Format(state fmt.State, _ rune) {
|
|
writeRedacted(state, redactedProfile)
|
|
}
|
|
|
|
func claimsEqual[V comparable](left, right ProfileClaim[V]) bool {
|
|
return left.value == right.value && left.status == right.status &&
|
|
left.source.origin == right.source.origin && left.source.quote == right.source.quote &&
|
|
left.source.extractionVersion == right.source.extractionVersion &&
|
|
left.source.confirmedAt.Equal(right.source.confirmedAt)
|
|
}
|
|
|
|
func optionalClaimsEqual[V comparable](left, right *ProfileClaim[V]) bool {
|
|
if left == nil || right == nil {
|
|
return left == right
|
|
}
|
|
return claimsEqual(*left, *right)
|
|
}
|
|
|
|
// ProfileRole is a role of the candidate: a specialization with the grade the
|
|
// candidate claims for it. SelfAssessedGrade is "" when the candidate names
|
|
// none. It is a claim, the same one that the questionnaire calls the
|
|
// self-assessed grade: it never becomes a confirmed grade or a category. The
|
|
// type has no field for a confirmed grade on purpose.
|
|
type ProfileRole struct {
|
|
Specialization SpecializationCode
|
|
SelfAssessedGrade GradeCode
|
|
}
|
|
|
|
// ProfileExperience is one entry of the work history. It describes the work
|
|
// by its specialization and tasks rather than by a job title. EmployerName
|
|
// and Summary are "" when not given; StartedOn and EndedOn are YYYY-MM months
|
|
// and EndedOn is "" for a job that continues. The entry is personal data:
|
|
// String, GoString, Format, and LogValue redact it.
|
|
type ProfileExperience struct {
|
|
EmployerName string
|
|
Specialization SpecializationCode
|
|
StartedOn string
|
|
EndedOn string
|
|
Summary string
|
|
}
|
|
|
|
func (ProfileExperience) String() string { return redactedProfile }
|
|
func (ProfileExperience) GoString() string { return redactedProfile }
|
|
func (ProfileExperience) LogValue() slog.Value {
|
|
return slog.StringValue(redactedProfile)
|
|
}
|
|
func (ProfileExperience) Format(state fmt.State, _ rune) { writeRedacted(state, redactedProfile) }
|
|
|
|
// ProfileExperiencePeriod is the exact month range used to acknowledge
|
|
// overlapping work. Its dates are personal data, so formatting redacts them.
|
|
type ProfileExperiencePeriod struct {
|
|
StartedOn string `json:"started_on"`
|
|
EndedOn string `json:"ended_on"`
|
|
}
|
|
|
|
func (ProfileExperiencePeriod) String() string { return redactedProfile }
|
|
func (ProfileExperiencePeriod) GoString() string { return redactedProfile }
|
|
func (ProfileExperiencePeriod) LogValue() slog.Value {
|
|
return slog.StringValue(redactedProfile)
|
|
}
|
|
func (ProfileExperiencePeriod) Format(state fmt.State, _ rune) { writeRedacted(state, redactedProfile) }
|
|
|
|
// ProfileParallelPeriodAcknowledgement records that the candidate reviewed
|
|
// the exact dates of two overlapping experience entries at their indices.
|
|
// Employer names and summaries are not part of the decision.
|
|
type ProfileParallelPeriodAcknowledgement struct {
|
|
FirstIndex int `json:"first_index"`
|
|
SecondIndex int `json:"second_index"`
|
|
FirstPeriod ProfileExperiencePeriod `json:"first_period"`
|
|
SecondPeriod ProfileExperiencePeriod `json:"second_period"`
|
|
}
|
|
|
|
func (ProfileParallelPeriodAcknowledgement) String() string { return redactedProfile }
|
|
func (ProfileParallelPeriodAcknowledgement) GoString() string { return redactedProfile }
|
|
func (ProfileParallelPeriodAcknowledgement) LogValue() slog.Value {
|
|
return slog.StringValue(redactedProfile)
|
|
}
|
|
func (ProfileParallelPeriodAcknowledgement) Format(state fmt.State, _ rune) {
|
|
writeRedacted(state, redactedProfile)
|
|
}
|
|
|
|
// ProfileExperienceOverlapStatus reports whether the candidate acknowledged
|
|
// an overlapping pair of periods in the current profile version.
|
|
type ProfileExperienceOverlapStatus string
|
|
|
|
const (
|
|
ProfileExperienceOverlapNeedsConfirmation ProfileExperienceOverlapStatus = "needs_confirmation"
|
|
ProfileExperienceOverlapConfirmed ProfileExperienceOverlapStatus = "confirmed"
|
|
)
|
|
|
|
// ProfileExperienceOverlap identifies two entries whose inclusive month
|
|
// ranges overlap. Indices refer to one profile version's experience list.
|
|
type ProfileExperienceOverlap struct {
|
|
FirstIndex int
|
|
SecondIndex int
|
|
Status ProfileExperienceOverlapStatus
|
|
}
|
|
|
|
// ProfileTaxBasis is the tax basis of a salary amount.
|
|
type ProfileTaxBasis string
|
|
|
|
const (
|
|
ProfileTaxNet ProfileTaxBasis = "net"
|
|
ProfileTaxGross ProfileTaxBasis = "gross"
|
|
)
|
|
|
|
// ProfileSalaryMinimum is the lowest salary that the candidate accepts, in
|
|
// whole roubles per month with an explicit tax basis. It is private to the
|
|
// candidate: no organization reads it. It is personal data: String,
|
|
// GoString, Format, and LogValue redact it.
|
|
type ProfileSalaryMinimum struct {
|
|
Amount int64
|
|
TaxBasis ProfileTaxBasis
|
|
}
|
|
|
|
func (ProfileSalaryMinimum) String() string { return redactedProfile }
|
|
func (ProfileSalaryMinimum) GoString() string { return redactedProfile }
|
|
func (ProfileSalaryMinimum) LogValue() slog.Value {
|
|
return slog.StringValue(redactedProfile)
|
|
}
|
|
func (ProfileSalaryMinimum) Format(state fmt.State, _ rune) { writeRedacted(state, redactedProfile) }
|
|
|
|
// ProfileClaimInput is the decision of a request about one value: the value
|
|
// and whether the candidate confirms it or keeps it as an unconfirmed
|
|
// suggestion.
|
|
type ProfileClaimInput[V comparable] struct {
|
|
Value V
|
|
Status ProfileClaimStatus
|
|
}
|
|
|
|
// CandidateProfileInput is the complete new state of a profile as a request
|
|
// gave it. A nil single field is unknown and removes the stored value; a list
|
|
// replaces the stored list. It holds personal data: never log it.
|
|
type CandidateProfileInput struct {
|
|
FullName *ProfileClaimInput[string]
|
|
Email *ProfileClaimInput[string]
|
|
Phone *ProfileClaimInput[string]
|
|
Telegram *ProfileClaimInput[string]
|
|
Stack []ProfileClaimInput[string]
|
|
Roles []ProfileClaimInput[ProfileRole]
|
|
Experience []ProfileClaimInput[ProfileExperience]
|
|
// ParallelPeriodAcknowledgements contains explicit acknowledgements for
|
|
// the exact periods and indices in Experience.
|
|
ParallelPeriodAcknowledgements []ProfileParallelPeriodAcknowledgement
|
|
SoftSkills []ProfileClaimInput[string]
|
|
// Projects replaces the stored projects; nil keeps them, so a client
|
|
// that does not know the section never deletes it.
|
|
Projects *[]ProfileClaimInput[ProfileProject]
|
|
Location *ProfileClaimInput[string]
|
|
Relocation *ProfileClaimInput[bool]
|
|
SalaryMinimum *ProfileClaimInput[ProfileSalaryMinimum]
|
|
}
|
|
|
|
// CandidateProfileContent is the validated content of a profile: every claim
|
|
// that exists. A field that is not set has no claim. It holds no confirmed
|
|
// grade or category, so no request and no import can write one through it,
|
|
// and no reference to a file, the ML service, or an FSP account. It is
|
|
// personal data: String, GoString, Format, and LogValue redact it.
|
|
type CandidateProfileContent struct {
|
|
fullName *ProfileClaim[string]
|
|
email *ProfileClaim[string]
|
|
phone *ProfileClaim[string]
|
|
telegram *ProfileClaim[string]
|
|
stack []ProfileClaim[string]
|
|
roles []ProfileClaim[ProfileRole]
|
|
experience []ProfileClaim[ProfileExperience]
|
|
parallelPeriodAcknowledgements []ProfileParallelPeriodAcknowledgement
|
|
softSkills []ProfileClaim[string]
|
|
projects []ProfileClaim[ProfileProject]
|
|
location *ProfileClaim[string]
|
|
relocation *ProfileClaim[bool]
|
|
salaryMinimum *ProfileClaim[ProfileSalaryMinimum]
|
|
}
|
|
|
|
func optionalClaim[V comparable](claim *ProfileClaim[V]) (ProfileClaim[V], bool) {
|
|
if claim == nil {
|
|
return ProfileClaim[V]{}, false
|
|
}
|
|
return *claim, true
|
|
}
|
|
|
|
// FullName returns the claim of the full name and whether it is set.
|
|
func (content CandidateProfileContent) FullName() (ProfileClaim[string], bool) {
|
|
return optionalClaim(content.fullName)
|
|
}
|
|
|
|
// Email returns the claim of the contact email and whether it is set.
|
|
func (content CandidateProfileContent) Email() (ProfileClaim[string], bool) {
|
|
return optionalClaim(content.email)
|
|
}
|
|
|
|
// Phone returns the claim of the E.164 phone number and whether it is set.
|
|
func (content CandidateProfileContent) Phone() (ProfileClaim[string], bool) {
|
|
return optionalClaim(content.phone)
|
|
}
|
|
|
|
// Telegram returns the claim of the Telegram username and whether it is set.
|
|
func (content CandidateProfileContent) Telegram() (ProfileClaim[string], bool) {
|
|
return optionalClaim(content.telegram)
|
|
}
|
|
|
|
// Location returns the claim of the place and whether it is set.
|
|
func (content CandidateProfileContent) Location() (ProfileClaim[string], bool) {
|
|
return optionalClaim(content.location)
|
|
}
|
|
|
|
// Relocation returns the claim of readiness to relocate and whether it is set.
|
|
func (content CandidateProfileContent) Relocation() (ProfileClaim[bool], bool) {
|
|
return optionalClaim(content.relocation)
|
|
}
|
|
|
|
// SalaryMinimum returns the claim of the lowest salary and whether it is set.
|
|
func (content CandidateProfileContent) SalaryMinimum() (ProfileClaim[ProfileSalaryMinimum], bool) {
|
|
return optionalClaim(content.salaryMinimum)
|
|
}
|
|
|
|
// Stack returns a copy of the stack tags in the order the candidate gave them.
|
|
func (content CandidateProfileContent) Stack() []ProfileClaim[string] {
|
|
return slices.Clone(content.stack)
|
|
}
|
|
|
|
// Roles returns a copy of the roles in the order the candidate gave them.
|
|
func (content CandidateProfileContent) Roles() []ProfileClaim[ProfileRole] {
|
|
return slices.Clone(content.roles)
|
|
}
|
|
|
|
// Experience returns a copy of the work history in the order the candidate
|
|
// gave it.
|
|
func (content CandidateProfileContent) Experience() []ProfileClaim[ProfileExperience] {
|
|
return slices.Clone(content.experience)
|
|
}
|
|
|
|
// ParallelPeriodAcknowledgements returns a copy of the stored date-pair
|
|
// decisions for this profile version.
|
|
func (content CandidateProfileContent) ParallelPeriodAcknowledgements() []ProfileParallelPeriodAcknowledgement {
|
|
return slices.Clone(content.parallelPeriodAcknowledgements)
|
|
}
|
|
|
|
// ExperienceOverlaps returns every overlapping pair in index order. A pair's
|
|
// status is derived from an acknowledgement that still matches both periods.
|
|
func (content CandidateProfileContent) ExperienceOverlaps() []ProfileExperienceOverlap {
|
|
var overlaps []ProfileExperienceOverlap
|
|
acknowledged := make(map[experiencePair]struct{}, len(content.parallelPeriodAcknowledgements))
|
|
for _, acknowledgement := range content.parallelPeriodAcknowledgements {
|
|
acknowledged[experiencePair{first: acknowledgement.FirstIndex, second: acknowledgement.SecondIndex}] = struct{}{}
|
|
}
|
|
for first := range content.experience {
|
|
for second := first + 1; second < len(content.experience); second++ {
|
|
if !experiencePeriodsOverlap(content.experience[first].value, content.experience[second].value) {
|
|
continue
|
|
}
|
|
status := ProfileExperienceOverlapNeedsConfirmation
|
|
if _, ok := acknowledged[experiencePair{first: first, second: second}]; ok {
|
|
status = ProfileExperienceOverlapConfirmed
|
|
}
|
|
overlaps = append(overlaps, ProfileExperienceOverlap{FirstIndex: first, SecondIndex: second, Status: status})
|
|
}
|
|
}
|
|
return overlaps
|
|
}
|
|
|
|
// SoftSkills returns a copy of the soft skills in the order the candidate
|
|
// gave them.
|
|
func (content CandidateProfileContent) SoftSkills() []ProfileClaim[string] {
|
|
return slices.Clone(content.softSkills)
|
|
}
|
|
|
|
// Projects returns a copy of the projects in the order the candidate gave
|
|
// them.
|
|
func (content CandidateProfileContent) Projects() []ProfileClaim[ProfileProject] {
|
|
return slices.Clone(content.projects)
|
|
}
|
|
|
|
// Equal reports whether both contents hold the same claims with the same
|
|
// provenance, which tells a change from a body that changes nothing.
|
|
func (content CandidateProfileContent) Equal(other CandidateProfileContent) bool {
|
|
return optionalClaimsEqual(content.fullName, other.fullName) &&
|
|
optionalClaimsEqual(content.email, other.email) &&
|
|
optionalClaimsEqual(content.phone, other.phone) &&
|
|
optionalClaimsEqual(content.telegram, other.telegram) &&
|
|
optionalClaimsEqual(content.location, other.location) &&
|
|
optionalClaimsEqual(content.relocation, other.relocation) &&
|
|
optionalClaimsEqual(content.salaryMinimum, other.salaryMinimum) &&
|
|
slices.EqualFunc(content.stack, other.stack, claimsEqual) &&
|
|
slices.EqualFunc(content.roles, other.roles, claimsEqual) &&
|
|
slices.EqualFunc(content.experience, other.experience, claimsEqual) &&
|
|
slices.Equal(content.parallelPeriodAcknowledgements, other.parallelPeriodAcknowledgements) &&
|
|
slices.EqualFunc(content.softSkills, other.softSkills, claimsEqual) &&
|
|
slices.EqualFunc(content.projects, other.projects, claimsEqual)
|
|
}
|
|
|
|
func (CandidateProfileContent) String() string { return redactedProfile }
|
|
func (CandidateProfileContent) GoString() string { return redactedProfile }
|
|
func (CandidateProfileContent) LogValue() slog.Value {
|
|
return slog.StringValue(redactedProfile)
|
|
}
|
|
func (CandidateProfileContent) Format(state fmt.State, _ rune) { writeRedacted(state, redactedProfile) }
|
|
|
|
// claimRules holds what the resolution of one kind of value needs. The
|
|
// validate function returns the normalized value, the pointer of the part
|
|
// that broke a rule relative to the value (empty for the value itself), and
|
|
// the rule, or an empty rule when the value is valid.
|
|
type claimRules[V comparable] struct {
|
|
validate func(V) (normalized V, subPointer, reason string)
|
|
// valueRoot is the pointer of the value inside a decision: "/value" for
|
|
// a single field, and "/tag" or "/skill" for the scalar item that carries
|
|
// it in the contract. A structured item has its fields next to `status`,
|
|
// so its root is empty.
|
|
valueRoot string
|
|
// key identifies an item for the repeat rule, with keyPointer as the
|
|
// pointer of the repeated part of the item. A nil key allows repeats.
|
|
key func(V) string
|
|
keyPointer string
|
|
}
|
|
|
|
// resolve decides what a request does to one value. The value is normalized
|
|
// and validated first. A confirmed decision for a stored suggestion with the
|
|
// same value confirms it and keeps its origin and quote; any other confirmed
|
|
// decision is a manual value, except that re-sending a confirmed value
|
|
// unchanged keeps the stored claim and its confirmation time. An extracted
|
|
// decision keeps a stored suggestion unconfirmed and is accepted only for the
|
|
// same value, because a client must not mark a value it made up as imported.
|
|
func (rules claimRules[V]) resolve(
|
|
location, pointer string, input ProfileClaimInput[V], stored []ProfileClaim[V], at time.Time,
|
|
) (ProfileClaim[V], error) {
|
|
value, subPointer, reason := rules.validate(input.Value)
|
|
if reason != "" {
|
|
return ProfileClaim[V]{}, invalidProfileField(location, pointer+rules.valueRoot+subPointer, reason)
|
|
}
|
|
index := slices.IndexFunc(stored, func(claim ProfileClaim[V]) bool { return claim.value == value })
|
|
switch input.Status {
|
|
case ProfileClaimConfirmed:
|
|
if index >= 0 {
|
|
existing := stored[index]
|
|
if existing.status == ProfileClaimConfirmed {
|
|
return existing, nil
|
|
}
|
|
return ProfileClaim[V]{value: value, status: ProfileClaimConfirmed, source: existing.source.confirm(at)}, nil
|
|
}
|
|
source, err := NewManualProfileClaimSource(at)
|
|
if err != nil {
|
|
return ProfileClaim[V]{}, fmt.Errorf("%s - %w", location, err)
|
|
}
|
|
return ProfileClaim[V]{value: value, status: ProfileClaimConfirmed, source: source}, nil
|
|
case ProfileClaimExtracted:
|
|
if index >= 0 && stored[index].status == ProfileClaimExtracted {
|
|
return stored[index], nil
|
|
}
|
|
return ProfileClaim[V]{}, invalidStateDependentProfileField(location, pointer+"/status", "must be extracted only for a stored suggestion with the same value")
|
|
default:
|
|
return ProfileClaim[V]{}, invalidProfileField(location, pointer+"/status", "must be confirmed or extracted")
|
|
}
|
|
}
|
|
|
|
// resolveOptional resolves a single field. A nil decision is an unknown
|
|
// field and returns nil.
|
|
func resolveOptional[V comparable](
|
|
rules claimRules[V], location, pointer string, input *ProfileClaimInput[V], stored *ProfileClaim[V], at time.Time,
|
|
) (*ProfileClaim[V], error) {
|
|
if input == nil {
|
|
return nil, nil
|
|
}
|
|
var existing []ProfileClaim[V]
|
|
if stored != nil {
|
|
existing = []ProfileClaim[V]{*stored}
|
|
}
|
|
claim, err := rules.resolve(location, pointer, *input, existing, at)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &claim, nil
|
|
}
|
|
|
|
// resolveItems resolves a list. It rejects a list over limit and, when the
|
|
// rules have a key, an item that repeats an earlier one.
|
|
func resolveItems[V comparable](
|
|
rules claimRules[V], location, pointer string, inputs []ProfileClaimInput[V], stored []ProfileClaim[V], limit int, at time.Time,
|
|
) ([]ProfileClaim[V], error) {
|
|
if len(inputs) > limit {
|
|
return nil, invalidProfileField(location, pointer, fmt.Sprintf("must have at most %d items", limit))
|
|
}
|
|
claims := make([]ProfileClaim[V], 0, len(inputs))
|
|
seen := make(map[string]struct{}, len(inputs))
|
|
for index, input := range inputs {
|
|
itemPointer := fmt.Sprintf("%s/%d", pointer, index)
|
|
claim, err := rules.resolve(location, itemPointer, input, stored, at)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if rules.key != nil {
|
|
key := rules.key(claim.value)
|
|
if _, repeated := seen[key]; repeated {
|
|
return nil, invalidProfileField(location, itemPointer+rules.keyPointer, "must not repeat an earlier item")
|
|
}
|
|
seen[key] = struct{}{}
|
|
}
|
|
claims = append(claims, claim)
|
|
}
|
|
return claims, nil
|
|
}
|
|
|
|
func singleLineRules(maxRunes int) func(string) (string, string, string) {
|
|
return func(value string) (string, string, string) {
|
|
return value, "", singleLineTextProblem(value, maxRunes)
|
|
}
|
|
}
|
|
|
|
func patternRules(pattern *regexp.Regexp, reason string) func(string) (string, string, string) {
|
|
return func(value string) (string, string, string) {
|
|
if !pattern.MatchString(value) {
|
|
return value, "", reason
|
|
}
|
|
return value, "", ""
|
|
}
|
|
}
|
|
|
|
func emailRules(value string) (string, string, string) {
|
|
email, err := NewEmailAddress(value)
|
|
if err != nil {
|
|
return value, "", "must be an email address"
|
|
}
|
|
return email.Address(), "", ""
|
|
}
|
|
|
|
func caseInsensitiveKey(value string) string { return strings.ToLower(value) }
|
|
|
|
func relocationRules(value bool) (bool, string, string) { return value, "", "" }
|
|
|
|
func salaryRules(value ProfileSalaryMinimum) (ProfileSalaryMinimum, string, string) {
|
|
switch {
|
|
case value.Amount < minProfileSalaryAmount || value.Amount > maxProfileSalaryAmount || value.Amount%minProfileSalaryAmount != 0:
|
|
return value, "/amount", fmt.Sprintf("must be a multiple of %d from %d to %d", minProfileSalaryAmount, minProfileSalaryAmount, maxProfileSalaryAmount)
|
|
case value.TaxBasis != ProfileTaxNet && value.TaxBasis != ProfileTaxGross:
|
|
return value, "/tax_basis", "must be net or gross"
|
|
default:
|
|
return value, "", ""
|
|
}
|
|
}
|
|
|
|
func roleRules(value ProfileRole) (ProfileRole, string, string) {
|
|
switch {
|
|
case !value.Specialization.IsKnown():
|
|
return value, "/specialization", "must be a specialization of the catalog"
|
|
case value.SelfAssessedGrade != "" && !value.SelfAssessedGrade.IsKnown():
|
|
return value, "/self_assessed_grade", "must be a grade of the scale"
|
|
default:
|
|
return value, "", ""
|
|
}
|
|
}
|
|
|
|
// experienceRules checks one work history entry. A month later than the month
|
|
// of now is in the future; a zero now disables that check, which a restore
|
|
// uses because a stored entry never becomes a future one.
|
|
func experienceRules(now time.Time) func(ProfileExperience) (ProfileExperience, string, string) {
|
|
latest := ""
|
|
if !now.IsZero() {
|
|
latest = now.UTC().Format("2006-01")
|
|
}
|
|
problemOfMonth := func(month string) string {
|
|
switch {
|
|
case !profileMonthPattern.MatchString(month):
|
|
return "must be a month in the YYYY-MM format"
|
|
case latest != "" && month > latest:
|
|
return "must not be in the future"
|
|
default:
|
|
return ""
|
|
}
|
|
}
|
|
return func(value ProfileExperience) (ProfileExperience, string, string) {
|
|
value.Summary = strings.ReplaceAll(value.Summary, "\r\n", "\n")
|
|
switch {
|
|
case value.EmployerName != "" && singleLineTextProblem(value.EmployerName, maxProfileEmployerRunes) != "":
|
|
return value, "/employer_name", singleLineTextProblem(value.EmployerName, maxProfileEmployerRunes)
|
|
case !value.Specialization.IsKnown():
|
|
return value, "/specialization", "must be a specialization of the catalog"
|
|
case problemOfMonth(value.StartedOn) != "":
|
|
return value, "/started_on", problemOfMonth(value.StartedOn)
|
|
case value.EndedOn != "" && problemOfMonth(value.EndedOn) != "":
|
|
return value, "/ended_on", problemOfMonth(value.EndedOn)
|
|
case value.EndedOn != "" && value.EndedOn < value.StartedOn:
|
|
return value, "/ended_on", "must not be earlier than started_on"
|
|
case value.Summary != "" && multiLineTextProblem(value.Summary, maxProfileSummaryRunes) != "":
|
|
return value, "/summary", multiLineTextProblem(value.Summary, maxProfileSummaryRunes)
|
|
default:
|
|
return value, "", ""
|
|
}
|
|
}
|
|
}
|
|
|
|
// profileRules gathers the rules of every kind of value.
|
|
type profileRules struct {
|
|
fullName claimRules[string]
|
|
email claimRules[string]
|
|
phone claimRules[string]
|
|
telegram claimRules[string]
|
|
location claimRules[string]
|
|
relocation claimRules[bool]
|
|
salaryMinimum claimRules[ProfileSalaryMinimum]
|
|
stack claimRules[string]
|
|
softSkills claimRules[string]
|
|
roles claimRules[ProfileRole]
|
|
experience claimRules[ProfileExperience]
|
|
projects claimRules[ProfileProject]
|
|
}
|
|
|
|
func newProfileRules(now time.Time) profileRules {
|
|
return profileRules{
|
|
fullName: claimRules[string]{validate: singleLineRules(maxProfileFullNameRunes), valueRoot: "/value"},
|
|
email: claimRules[string]{validate: emailRules, valueRoot: "/value"},
|
|
phone: claimRules[string]{
|
|
validate: patternRules(organizationPhonePattern, "must be an E.164 phone number"), valueRoot: "/value",
|
|
},
|
|
telegram: claimRules[string]{
|
|
validate: patternRules(organizationTelegramPattern, "must be a Telegram username with the leading @"), valueRoot: "/value",
|
|
},
|
|
location: claimRules[string]{validate: singleLineRules(maxProfileLocationRunes), valueRoot: "/value"},
|
|
relocation: claimRules[bool]{validate: relocationRules, valueRoot: "/value"},
|
|
salaryMinimum: claimRules[ProfileSalaryMinimum]{validate: salaryRules, valueRoot: "/value"},
|
|
stack: claimRules[string]{
|
|
validate: singleLineRules(maxProfileTagRunes), valueRoot: "/tag", key: caseInsensitiveKey, keyPointer: "/tag",
|
|
},
|
|
softSkills: claimRules[string]{
|
|
validate: singleLineRules(maxProfileTagRunes), valueRoot: "/skill", key: caseInsensitiveKey, keyPointer: "/skill",
|
|
},
|
|
roles: claimRules[ProfileRole]{
|
|
validate: roleRules, key: func(role ProfileRole) string { return string(role.Specialization) }, keyPointer: "/specialization",
|
|
},
|
|
experience: claimRules[ProfileExperience]{validate: experienceRules(now)},
|
|
projects: claimRules[ProfileProject]{validate: projectRules, key: projectKey, keyPointer: "/repository_url"},
|
|
}
|
|
}
|
|
|
|
type experiencePair struct {
|
|
first int
|
|
second int
|
|
}
|
|
|
|
func experiencePeriod(value ProfileExperience) ProfileExperiencePeriod {
|
|
return ProfileExperiencePeriod{StartedOn: value.StartedOn, EndedOn: value.EndedOn}
|
|
}
|
|
|
|
func experiencePeriodsOverlap(first, second ProfileExperience) bool {
|
|
return (first.EndedOn == "" || second.StartedOn <= first.EndedOn) &&
|
|
(second.EndedOn == "" || first.StartedOn <= second.EndedOn)
|
|
}
|
|
|
|
func invalidParallelPeriodField(location string, index int, pointer, reason string) error {
|
|
return invalidProfileField(location, fmt.Sprintf("/confirmed_parallel_periods/%d/%s", index, pointer), reason)
|
|
}
|
|
|
|
func resolveParallelPeriodAcknowledgements(
|
|
stored CandidateProfileContent,
|
|
experiences []ProfileClaim[ProfileExperience],
|
|
requested []ProfileParallelPeriodAcknowledgement,
|
|
location string,
|
|
) ([]ProfileParallelPeriodAcknowledgement, error) {
|
|
const maxPairs = maxProfileExperienceItems * (maxProfileExperienceItems - 1) / 2
|
|
if len(requested) > maxPairs {
|
|
return nil, invalidProfileField(location, "/confirmed_parallel_periods", "must not contain more pairs than the experience list allows")
|
|
}
|
|
|
|
acknowledgements := make(map[experiencePair]ProfileParallelPeriodAcknowledgement, len(requested)+len(stored.parallelPeriodAcknowledgements))
|
|
requestedPairs := make(map[experiencePair]struct{}, len(requested))
|
|
for index, acknowledgement := range requested {
|
|
if err := addRequestedParallelPeriodAcknowledgement(
|
|
acknowledgement, experiences, index, location, requestedPairs, acknowledgements,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
previousOverlaps := overlappingExperiencePairs(stored.experience)
|
|
carryMatchingParallelPeriodAcknowledgements(stored.parallelPeriodAcknowledgements, experiences, acknowledgements)
|
|
return resolveCurrentExperienceOverlaps(experiences, previousOverlaps, acknowledgements, location)
|
|
}
|
|
|
|
func addRequestedParallelPeriodAcknowledgement(
|
|
acknowledgement ProfileParallelPeriodAcknowledgement,
|
|
experiences []ProfileClaim[ProfileExperience],
|
|
index int,
|
|
location string,
|
|
requestedPairs map[experiencePair]struct{},
|
|
acknowledgements map[experiencePair]ProfileParallelPeriodAcknowledgement,
|
|
) error {
|
|
pair := experiencePair{first: acknowledgement.FirstIndex, second: acknowledgement.SecondIndex}
|
|
if pair.first < 0 || pair.first >= len(experiences) {
|
|
return invalidParallelPeriodField(location, index, "first_index", "must refer to an experience entry")
|
|
}
|
|
if pair.second <= pair.first || pair.second >= len(experiences) {
|
|
return invalidParallelPeriodField(location, index, "second_index", "must refer to a later experience entry")
|
|
}
|
|
if _, duplicate := requestedPairs[pair]; duplicate {
|
|
return invalidParallelPeriodField(location, index, "second_index", "must not repeat a pair")
|
|
}
|
|
requestedPairs[pair] = struct{}{}
|
|
first := experiences[pair.first].value
|
|
second := experiences[pair.second].value
|
|
firstPeriod := experiencePeriod(first)
|
|
secondPeriod := experiencePeriod(second)
|
|
if acknowledgement.FirstPeriod.StartedOn != firstPeriod.StartedOn {
|
|
return invalidParallelPeriodField(location, index, "first_period/started_on", "must match the indexed experience period")
|
|
}
|
|
if acknowledgement.FirstPeriod.EndedOn != firstPeriod.EndedOn {
|
|
return invalidParallelPeriodField(location, index, "first_period/ended_on", "must match the indexed experience period")
|
|
}
|
|
if acknowledgement.SecondPeriod.StartedOn != secondPeriod.StartedOn {
|
|
return invalidParallelPeriodField(location, index, "second_period/started_on", "must match the indexed experience period")
|
|
}
|
|
if acknowledgement.SecondPeriod.EndedOn != secondPeriod.EndedOn {
|
|
return invalidParallelPeriodField(location, index, "second_period/ended_on", "must match the indexed experience period")
|
|
}
|
|
if !experiencePeriodsOverlap(first, second) {
|
|
return invalidParallelPeriodField(location, index, "second_index", "must identify an overlapping period")
|
|
}
|
|
acknowledgements[pair] = ProfileParallelPeriodAcknowledgement{
|
|
FirstIndex: pair.first, SecondIndex: pair.second, FirstPeriod: firstPeriod, SecondPeriod: secondPeriod,
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func overlappingExperiencePairs(experiences []ProfileClaim[ProfileExperience]) map[experiencePair]ProfileParallelPeriodAcknowledgement {
|
|
previous := make(map[experiencePair]ProfileParallelPeriodAcknowledgement)
|
|
for first := range experiences {
|
|
for second := first + 1; second < len(experiences); second++ {
|
|
firstValue := experiences[first].value
|
|
secondValue := experiences[second].value
|
|
if !experiencePeriodsOverlap(firstValue, secondValue) {
|
|
continue
|
|
}
|
|
previous[experiencePair{first: first, second: second}] = ProfileParallelPeriodAcknowledgement{
|
|
FirstIndex: first, SecondIndex: second,
|
|
FirstPeriod: experiencePeriod(firstValue), SecondPeriod: experiencePeriod(secondValue),
|
|
}
|
|
}
|
|
}
|
|
return previous
|
|
}
|
|
|
|
func carryMatchingParallelPeriodAcknowledgements(
|
|
stored []ProfileParallelPeriodAcknowledgement,
|
|
experiences []ProfileClaim[ProfileExperience],
|
|
acknowledgements map[experiencePair]ProfileParallelPeriodAcknowledgement,
|
|
) {
|
|
for _, previous := range stored {
|
|
pair := experiencePair{first: previous.FirstIndex, second: previous.SecondIndex}
|
|
if pair.first < 0 || pair.second < 0 || pair.first >= len(experiences) || pair.second >= len(experiences) {
|
|
continue
|
|
}
|
|
first := experiences[pair.first].value
|
|
second := experiences[pair.second].value
|
|
if experiencePeriod(first) != previous.FirstPeriod || experiencePeriod(second) != previous.SecondPeriod ||
|
|
!experiencePeriodsOverlap(first, second) {
|
|
continue
|
|
}
|
|
if _, explicitlyAcknowledged := acknowledgements[pair]; !explicitlyAcknowledged {
|
|
acknowledgements[pair] = previous
|
|
}
|
|
}
|
|
}
|
|
|
|
func resolveCurrentExperienceOverlaps(
|
|
experiences []ProfileClaim[ProfileExperience],
|
|
previousOverlaps map[experiencePair]ProfileParallelPeriodAcknowledgement,
|
|
acknowledgements map[experiencePair]ProfileParallelPeriodAcknowledgement,
|
|
location string,
|
|
) ([]ProfileParallelPeriodAcknowledgement, error) {
|
|
resolved := make([]ProfileParallelPeriodAcknowledgement, 0, len(acknowledgements))
|
|
for first := range experiences {
|
|
for second := first + 1; second < len(experiences); second++ {
|
|
firstValue := experiences[first].value
|
|
secondValue := experiences[second].value
|
|
if !experiencePeriodsOverlap(firstValue, secondValue) {
|
|
continue
|
|
}
|
|
pair := experiencePair{first: first, second: second}
|
|
if acknowledgement, ok := acknowledgements[pair]; ok {
|
|
resolved = append(resolved, acknowledgement)
|
|
continue
|
|
}
|
|
previous, existed := previousOverlaps[pair]
|
|
if existed && previous.FirstPeriod == experiencePeriod(firstValue) && previous.SecondPeriod == experiencePeriod(secondValue) {
|
|
continue
|
|
}
|
|
return nil, invalidStateDependentProfileField(location,
|
|
fmt.Sprintf("/experience/%d/started_on", second),
|
|
"overlaps another period and needs an explicit confirmation",
|
|
)
|
|
}
|
|
}
|
|
return resolved, nil
|
|
}
|
|
|
|
// ResolveCandidateProfileContent applies a request to the stored content and
|
|
// returns the new content. It validates every value, resolves each decision
|
|
// against the stored claim (see claimRules.resolve), and keeps a stored claim
|
|
// whose value is sent again unchanged. The first rule that fails returns an
|
|
// error matching ErrInvalidCandidateProfile with a *CandidateProfileFieldError
|
|
// that names the field. The zero CandidateProfileContent is the empty stored
|
|
// state of a first save. Every new claim has trust level 0.
|
|
func ResolveCandidateProfileContent(stored CandidateProfileContent, input CandidateProfileInput, at time.Time) (CandidateProfileContent, error) {
|
|
const location = "domain.ResolveCandidateProfileContent"
|
|
if at.IsZero() {
|
|
return CandidateProfileContent{}, fmt.Errorf("%s - time must be set: %w", location, ErrInvalidCandidateProfile)
|
|
}
|
|
rules := newProfileRules(at)
|
|
var (
|
|
content CandidateProfileContent
|
|
err error
|
|
)
|
|
steps := []func() error{
|
|
func() (err error) {
|
|
content.fullName, err = resolveOptional(rules.fullName, location, "/full_name", input.FullName, stored.fullName, at)
|
|
return err
|
|
},
|
|
func() (err error) {
|
|
content.email, err = resolveOptional(rules.email, location, "/contacts/email", input.Email, stored.email, at)
|
|
return err
|
|
},
|
|
func() (err error) {
|
|
content.phone, err = resolveOptional(rules.phone, location, "/contacts/phone", input.Phone, stored.phone, at)
|
|
return err
|
|
},
|
|
func() (err error) {
|
|
content.telegram, err = resolveOptional(rules.telegram, location, "/contacts/telegram", input.Telegram, stored.telegram, at)
|
|
return err
|
|
},
|
|
func() (err error) {
|
|
content.stack, err = resolveItems(rules.stack, location, "/stack", input.Stack, stored.stack, maxProfileStackItems, at)
|
|
return err
|
|
},
|
|
func() (err error) {
|
|
content.roles, err = resolveItems(rules.roles, location, "/roles", input.Roles, stored.roles, len(specializationCodes), at)
|
|
return err
|
|
},
|
|
func() (err error) {
|
|
content.experience, err = resolveItems(rules.experience, location, "/experience", input.Experience, stored.experience, maxProfileExperienceItems, at)
|
|
return err
|
|
},
|
|
func() (err error) {
|
|
content.softSkills, err = resolveItems(rules.softSkills, location, "/soft_skills", input.SoftSkills, stored.softSkills, maxProfileSoftSkills, at)
|
|
return err
|
|
},
|
|
func() (err error) {
|
|
if input.Projects == nil {
|
|
content.projects = slices.Clone(stored.projects)
|
|
return nil
|
|
}
|
|
content.projects, err = resolveItems(rules.projects, location, "/projects", *input.Projects, stored.projects, maxProfileProjects, at)
|
|
return err
|
|
},
|
|
func() (err error) {
|
|
content.location, err = resolveOptional(rules.location, location, "/terms/location", input.Location, stored.location, at)
|
|
return err
|
|
},
|
|
func() (err error) {
|
|
content.relocation, err = resolveOptional(rules.relocation, location, "/terms/relocation", input.Relocation, stored.relocation, at)
|
|
return err
|
|
},
|
|
func() (err error) {
|
|
content.salaryMinimum, err = resolveOptional(rules.salaryMinimum, location, "/terms/salary_minimum", input.SalaryMinimum, stored.salaryMinimum, at)
|
|
return err
|
|
},
|
|
}
|
|
for _, step := range steps {
|
|
if err = step(); err != nil {
|
|
return CandidateProfileContent{}, err
|
|
}
|
|
}
|
|
content.parallelPeriodAcknowledgements, err = resolveParallelPeriodAcknowledgements(
|
|
stored, content.experience, input.ParallelPeriodAcknowledgements, location,
|
|
)
|
|
if err != nil {
|
|
return CandidateProfileContent{}, fmt.Errorf("%s - resolve parallel period acknowledgements: %w", location, err)
|
|
}
|
|
return content, nil
|
|
}
|
|
|
|
// CandidateProfile is the private profile of one candidate account: its
|
|
// content and the optimistic concurrency version. Version 0 is the profile
|
|
// that was never saved. It is personal data: String, GoString, Format, and
|
|
// LogValue redact the content; LogValue logs only the account and the
|
|
// version.
|
|
type CandidateProfile struct {
|
|
userID uuid.UUID
|
|
// version is the optimistic concurrency version. Storage checks it as the
|
|
// expected version and advances it in the same statement, so a domain
|
|
// method never changes it.
|
|
version int64
|
|
content CandidateProfileContent
|
|
createdAt time.Time
|
|
updatedAt time.Time
|
|
}
|
|
|
|
// EmptyCandidateProfile returns the profile of an account that has not saved
|
|
// one: version 0, no claim, and no times.
|
|
func EmptyCandidateProfile(userID uuid.UUID) (CandidateProfile, error) {
|
|
if userID == uuid.Nil {
|
|
return CandidateProfile{}, fmt.Errorf("domain.EmptyCandidateProfile - user ID must not be nil: %w", ErrInvalidCandidateProfile)
|
|
}
|
|
return CandidateProfile{userID: userID}, nil
|
|
}
|
|
|
|
func (profile CandidateProfile) UserID() uuid.UUID { return profile.userID }
|
|
func (profile CandidateProfile) Version() int64 { return profile.version }
|
|
func (profile CandidateProfile) Content() CandidateProfileContent { return profile.content }
|
|
func (profile CandidateProfile) CreatedAt() time.Time { return profile.createdAt }
|
|
func (profile CandidateProfile) UpdatedAt() time.Time { return profile.updatedAt }
|
|
|
|
// IsZero reports a CandidateProfile not built by EmptyCandidateProfile or
|
|
// RestoreCandidateProfile.
|
|
func (profile CandidateProfile) IsZero() bool { return profile.userID == uuid.Nil }
|
|
|
|
// Replace applies a request to the profile and reports whether anything
|
|
// changed. expectedVersion is the version the client read. The order is:
|
|
//
|
|
// 1. A version above the current one never existed, so it is a conflict.
|
|
// 2. A rule that depends on the body alone fails with
|
|
// ErrInvalidCandidateProfile whatever the version.
|
|
// 3. A decision rule that depends on the stored claims, such as extracted,
|
|
// judged against a stale version is a conflict: another save may have
|
|
// confirmed the value, and the client must read the profile again.
|
|
// 4. A request that leaves every claim as stored changes nothing and
|
|
// returns the profile as it is, even with an older version, so a retry
|
|
// of a save that already succeeded is harmless.
|
|
// 5. Any other change over a stale version is a conflict.
|
|
//
|
|
// A change returns the new content and the update time with the version
|
|
// unchanged, because storage advances it. A time before the last update,
|
|
// from clock skew between instances, is stored as the last update.
|
|
func (profile CandidateProfile) Replace(input CandidateProfileInput, expectedVersion int64, at time.Time) (CandidateProfile, bool, error) {
|
|
const location = "CandidateProfile.Replace"
|
|
if profile.IsZero() {
|
|
return CandidateProfile{}, false, fmt.Errorf("%s - profile was not built by EmptyCandidateProfile: %w", location, ErrInvalidCandidateProfile)
|
|
}
|
|
conflict := fmt.Errorf("%s - expected version is not current: %w", location, ErrCandidateProfileVersionConflict)
|
|
if expectedVersion > profile.version || expectedVersion < 0 {
|
|
return CandidateProfile{}, false, conflict
|
|
}
|
|
content, err := ResolveCandidateProfileContent(profile.content, input, at)
|
|
if err != nil {
|
|
var fieldError *CandidateProfileFieldError
|
|
if expectedVersion != profile.version && errors.As(err, &fieldError) && fieldError.stateDependent {
|
|
return CandidateProfile{}, false, conflict
|
|
}
|
|
return CandidateProfile{}, false, fmt.Errorf("%s - resolve content: %w", location, err)
|
|
}
|
|
if content.Equal(profile.content) {
|
|
return profile, false, nil
|
|
}
|
|
if err := requireConfirmedExperienceOverlaps(content, location); err != nil {
|
|
if expectedVersion != profile.version {
|
|
return CandidateProfile{}, false, conflict
|
|
}
|
|
return CandidateProfile{}, false, err
|
|
}
|
|
if expectedVersion != profile.version {
|
|
return CandidateProfile{}, false, conflict
|
|
}
|
|
updated := profile
|
|
updated.content = content
|
|
updated.updatedAt = at
|
|
if at.Before(profile.updatedAt) {
|
|
updated.updatedAt = profile.updatedAt
|
|
}
|
|
if updated.createdAt.IsZero() {
|
|
updated.createdAt = updated.updatedAt
|
|
}
|
|
return updated, true, nil
|
|
}
|
|
|
|
func requireConfirmedExperienceOverlaps(content CandidateProfileContent, location string) error {
|
|
for _, overlap := range content.ExperienceOverlaps() {
|
|
if overlap.Status == ProfileExperienceOverlapNeedsConfirmation {
|
|
return invalidStateDependentProfileField(location,
|
|
fmt.Sprintf("/experience/%d/started_on", overlap.SecondIndex),
|
|
"overlaps another period and needs an explicit confirmation",
|
|
)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (CandidateProfile) String() string { return redactedProfile }
|
|
func (CandidateProfile) GoString() string { return redactedProfile }
|
|
func (CandidateProfile) Format(state fmt.State, _ rune) {
|
|
writeRedacted(state, redactedProfile)
|
|
}
|
|
|
|
// LogValue logs the account identifier and the version only.
|
|
func (profile CandidateProfile) LogValue() slog.Value {
|
|
return slog.GroupValue(
|
|
slog.String("user_id", profile.userID.String()),
|
|
slog.Int64("version", profile.version),
|
|
)
|
|
}
|
|
|
|
// Stored claim kinds. They are the values of candidate_profile_claims.kind
|
|
// and are fixed by its CHECK constraints.
|
|
const (
|
|
profileKindFullName = "full_name"
|
|
profileKindEmail = "contact_email"
|
|
profileKindPhone = "contact_phone"
|
|
profileKindTelegram = "contact_telegram"
|
|
profileKindStack = "stack"
|
|
profileKindRole = "role"
|
|
profileKindExperience = "experience"
|
|
profileKindSoftSkill = "soft_skill"
|
|
profileKindLocation = "terms_location"
|
|
profileKindRelocation = "terms_relocation"
|
|
profileKindSalaryMinimum = "terms_salary_minimum"
|
|
profileKindProject = "project"
|
|
)
|
|
|
|
// StoredProfileClaim is a claim as the claims table holds it: the kind, the
|
|
// position, the canonical JSON of the value, and the provenance columns. The
|
|
// value and the quote are personal data: never log the struct. The zero
|
|
// ConfirmedAt is a NULL column, and an empty Quote or ExtractionVersion is a
|
|
// NULL one.
|
|
type StoredProfileClaim struct {
|
|
Kind string `json:"kind"`
|
|
Ordinal int `json:"ordinal"`
|
|
Value []byte `json:"value"`
|
|
Status string `json:"status"`
|
|
Origin string `json:"origin"`
|
|
TrustLevel int `json:"trust_level"`
|
|
Quote string `json:"quote"`
|
|
ExtractionVersion string `json:"extraction_version"`
|
|
ConfirmedAt time.Time `json:"confirmed_at"`
|
|
}
|
|
|
|
// The JSON shapes of structured values. Their keys are the ones that the
|
|
// CHECK constraints of candidate_profile_claims require, and a nullable part
|
|
// is JSON null, never absent.
|
|
type (
|
|
storedRoleValue struct {
|
|
Specialization string `json:"specialization"`
|
|
SelfAssessedGrade *string `json:"self_assessed_grade"`
|
|
}
|
|
storedExperienceValue struct {
|
|
EmployerName *string `json:"employer_name"`
|
|
Specialization string `json:"specialization"`
|
|
StartedOn string `json:"started_on"`
|
|
EndedOn *string `json:"ended_on"`
|
|
Summary *string `json:"summary"`
|
|
}
|
|
storedSalaryValue struct {
|
|
Amount int64 `json:"amount"`
|
|
Currency string `json:"currency"`
|
|
Period string `json:"period"`
|
|
TaxBasis string `json:"tax_basis"`
|
|
}
|
|
)
|
|
|
|
func optionalString(value string) *string {
|
|
if value == "" {
|
|
return nil
|
|
}
|
|
return &value
|
|
}
|
|
|
|
func stringOrEmpty(value *string) string {
|
|
if value == nil {
|
|
return ""
|
|
}
|
|
return *value
|
|
}
|
|
|
|
// claimEntry is one claim on its way to a stored row: the value is already
|
|
// in the JSON shape that the CHECK constraints require.
|
|
type claimEntry struct {
|
|
kind string
|
|
ordinal int
|
|
value any
|
|
status ProfileClaimStatus
|
|
source ProfileClaimSource
|
|
}
|
|
|
|
func plainValue[V any](value V) any { return value }
|
|
|
|
func roleStoredValue(role ProfileRole) any {
|
|
return storedRoleValue{Specialization: string(role.Specialization), SelfAssessedGrade: optionalString(string(role.SelfAssessedGrade))}
|
|
}
|
|
|
|
func experienceStoredValue(entry ProfileExperience) any {
|
|
return storedExperienceValue{
|
|
EmployerName: optionalString(entry.EmployerName), Specialization: string(entry.Specialization),
|
|
StartedOn: entry.StartedOn, EndedOn: optionalString(entry.EndedOn), Summary: optionalString(entry.Summary),
|
|
}
|
|
}
|
|
|
|
func salaryStoredValue(salary ProfileSalaryMinimum) any {
|
|
return storedSalaryValue{Amount: salary.Amount, Currency: profileCurrency, Period: profilePeriod, TaxBasis: string(salary.TaxBasis)}
|
|
}
|
|
|
|
func appendSingle[V comparable](entries []claimEntry, kind string, claim *ProfileClaim[V], encode func(V) any) []claimEntry {
|
|
if claim == nil {
|
|
return entries
|
|
}
|
|
return append(entries, claimEntry{kind: kind, value: encode(claim.value), status: claim.status, source: claim.source})
|
|
}
|
|
|
|
func appendList[V comparable](entries []claimEntry, kind string, claims []ProfileClaim[V], encode func(V) any) []claimEntry {
|
|
for index, claim := range claims {
|
|
entries = append(entries, claimEntry{kind: kind, ordinal: index, value: encode(claim.value), status: claim.status, source: claim.source})
|
|
}
|
|
return entries
|
|
}
|
|
|
|
// StoredClaims returns every claim of the content as rows of the claims
|
|
// table, in a stable order: single fields first, then each list in position
|
|
// order. The rows hold personal data.
|
|
func (content CandidateProfileContent) StoredClaims() ([]StoredProfileClaim, error) {
|
|
const location = "CandidateProfileContent.StoredClaims"
|
|
var entries []claimEntry
|
|
entries = appendSingle(entries, profileKindFullName, content.fullName, plainValue[string])
|
|
entries = appendSingle(entries, profileKindEmail, content.email, plainValue[string])
|
|
entries = appendSingle(entries, profileKindPhone, content.phone, plainValue[string])
|
|
entries = appendSingle(entries, profileKindTelegram, content.telegram, plainValue[string])
|
|
entries = appendSingle(entries, profileKindLocation, content.location, plainValue[string])
|
|
entries = appendSingle(entries, profileKindRelocation, content.relocation, plainValue[bool])
|
|
entries = appendSingle(entries, profileKindSalaryMinimum, content.salaryMinimum, salaryStoredValue)
|
|
entries = appendList(entries, profileKindStack, content.stack, plainValue[string])
|
|
entries = appendList(entries, profileKindRole, content.roles, roleStoredValue)
|
|
entries = appendList(entries, profileKindExperience, content.experience, experienceStoredValue)
|
|
entries = appendList(entries, profileKindSoftSkill, content.softSkills, plainValue[string])
|
|
entries = appendList(entries, profileKindProject, content.projects, projectStoredValue)
|
|
|
|
rows := make([]StoredProfileClaim, 0, len(entries))
|
|
for _, entry := range entries {
|
|
encoded, err := json.Marshal(entry.value)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s - encode %s: %w", location, entry.kind, err)
|
|
}
|
|
rows = append(rows, StoredProfileClaim{
|
|
Kind: entry.kind, Ordinal: entry.ordinal, Value: encoded, Status: string(entry.status), Origin: string(entry.source.origin),
|
|
TrustLevel: ProfileClaimTrustLevel, Quote: entry.source.quote, ExtractionVersion: entry.source.extractionVersion,
|
|
ConfirmedAt: entry.source.confirmedAt,
|
|
})
|
|
}
|
|
return rows, nil
|
|
}
|
|
|
|
// RestoreCandidateProfileContent builds the content from stored rows. It
|
|
// validates each value with the rules of ResolveCandidateProfileContent and
|
|
// each provenance with RestoreProfileClaimSource, so a row changed outside
|
|
// the application fails with ErrInvalidCandidateProfile. The rows may come in
|
|
// any order; a list is ordered by Ordinal and must have no gap, and a single
|
|
// field must appear once. The error never quotes a value.
|
|
func RestoreCandidateProfileContent(rows []StoredProfileClaim) (CandidateProfileContent, error) {
|
|
return RestoreCandidateProfileContentWithParallelPeriods(rows, nil)
|
|
}
|
|
|
|
// RestoreCandidateProfileContentWithParallelPeriods also restores the
|
|
// explicit date-pair decisions stored for this profile. Existing profiles may
|
|
// contain unresolved overlaps, which are returned for the owner to resolve.
|
|
func RestoreCandidateProfileContentWithParallelPeriods(
|
|
rows []StoredProfileClaim,
|
|
acknowledgements []ProfileParallelPeriodAcknowledgement,
|
|
) (CandidateProfileContent, error) {
|
|
const location = "domain.RestoreCandidateProfileContent"
|
|
rules := newProfileRules(time.Time{})
|
|
fail := func(row StoredProfileClaim, reason string) error {
|
|
return fmt.Errorf("%s - claim %s/%d %s: %w", location, row.Kind, row.Ordinal, reason, ErrInvalidCandidateProfile)
|
|
}
|
|
var (
|
|
content CandidateProfileContent
|
|
err error
|
|
)
|
|
sorted := slices.Clone(rows)
|
|
slices.SortStableFunc(sorted, func(left, right StoredProfileClaim) int { return left.Ordinal - right.Ordinal })
|
|
for _, row := range sorted {
|
|
source, sourceErr := RestoreProfileClaimSource(ProfileClaimOrigin(row.Origin), row.TrustLevel, row.Quote, row.ExtractionVersion, row.ConfirmedAt)
|
|
if sourceErr != nil {
|
|
return CandidateProfileContent{}, fail(row, "has invalid provenance")
|
|
}
|
|
status := ProfileClaimStatus(row.Status)
|
|
err = restoreCandidateProfileClaim(&content, rules, row, status, source)
|
|
if err != nil {
|
|
return CandidateProfileContent{}, fail(row, err.Error())
|
|
}
|
|
}
|
|
content.parallelPeriodAcknowledgements = slices.Clone(acknowledgements)
|
|
if err := validateStoredParallelPeriodAcknowledgements(content.experience, content.parallelPeriodAcknowledgements); err != nil {
|
|
return CandidateProfileContent{}, fmt.Errorf("%s - validate parallel period acknowledgements: %w", location, err)
|
|
}
|
|
return content, nil
|
|
}
|
|
|
|
func restoreCandidateProfileClaim(
|
|
content *CandidateProfileContent,
|
|
rules profileRules,
|
|
row StoredProfileClaim,
|
|
status ProfileClaimStatus,
|
|
source ProfileClaimSource,
|
|
) error {
|
|
switch row.Kind {
|
|
case profileKindFullName:
|
|
return restoreSingle(&content.fullName, rules.fullName, row, status, source)
|
|
case profileKindEmail:
|
|
return restoreSingle(&content.email, rules.email, row, status, source)
|
|
case profileKindPhone:
|
|
return restoreSingle(&content.phone, rules.phone, row, status, source)
|
|
case profileKindTelegram:
|
|
return restoreSingle(&content.telegram, rules.telegram, row, status, source)
|
|
case profileKindLocation:
|
|
return restoreSingle(&content.location, rules.location, row, status, source)
|
|
case profileKindRelocation:
|
|
return restoreSingle(&content.relocation, rules.relocation, row, status, source)
|
|
case profileKindSalaryMinimum:
|
|
return restoreSingle(&content.salaryMinimum, rules.salaryMinimum, row, status, source)
|
|
case profileKindStack:
|
|
return restoreItem(&content.stack, rules.stack, row, status, source)
|
|
case profileKindSoftSkill:
|
|
return restoreItem(&content.softSkills, rules.softSkills, row, status, source)
|
|
case profileKindRole:
|
|
return restoreItem(&content.roles, rules.roles, row, status, source)
|
|
case profileKindExperience:
|
|
return restoreItem(&content.experience, rules.experience, row, status, source)
|
|
case profileKindProject:
|
|
return restoreItem(&content.projects, rules.projects, row, status, source)
|
|
default:
|
|
return errors.New("kind is unknown")
|
|
}
|
|
}
|
|
|
|
func validateStoredParallelPeriodAcknowledgements(
|
|
experiences []ProfileClaim[ProfileExperience],
|
|
acknowledgements []ProfileParallelPeriodAcknowledgement,
|
|
) error {
|
|
const location = "domain.validateStoredParallelPeriodAcknowledgements"
|
|
seen := make(map[experiencePair]struct{}, len(acknowledgements))
|
|
for _, acknowledgement := range acknowledgements {
|
|
pair := experiencePair{first: acknowledgement.FirstIndex, second: acknowledgement.SecondIndex}
|
|
if pair.first < 0 || pair.second <= pair.first || pair.second >= len(experiences) {
|
|
return fmt.Errorf("%s - pair indices are invalid: %w", location, ErrInvalidCandidateProfile)
|
|
}
|
|
if _, duplicate := seen[pair]; duplicate {
|
|
return fmt.Errorf("%s - pair is duplicated: %w", location, ErrInvalidCandidateProfile)
|
|
}
|
|
seen[pair] = struct{}{}
|
|
first := experiences[pair.first].value
|
|
second := experiences[pair.second].value
|
|
if experiencePeriod(first) != acknowledgement.FirstPeriod ||
|
|
experiencePeriod(second) != acknowledgement.SecondPeriod || !experiencePeriodsOverlap(first, second) {
|
|
return fmt.Errorf("%s - pair does not match the stored experience periods: %w", location, ErrInvalidCandidateProfile)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// decodeStoredValue decodes the canonical JSON of a stored value into V.
|
|
func decodeStoredValue[V comparable](row StoredProfileClaim) (V, error) {
|
|
var value V
|
|
switch target := any(&value).(type) {
|
|
case *ProfileRole:
|
|
var stored storedRoleValue
|
|
if err := decodeStrictJSON(row.Value, &stored); err != nil {
|
|
return value, err
|
|
}
|
|
*target = ProfileRole{Specialization: SpecializationCode(stored.Specialization), SelfAssessedGrade: GradeCode(stringOrEmpty(stored.SelfAssessedGrade))}
|
|
case *ProfileExperience:
|
|
var stored storedExperienceValue
|
|
if err := decodeStrictJSON(row.Value, &stored); err != nil {
|
|
return value, err
|
|
}
|
|
*target = ProfileExperience{
|
|
EmployerName: stringOrEmpty(stored.EmployerName), Specialization: SpecializationCode(stored.Specialization),
|
|
StartedOn: stored.StartedOn, EndedOn: stringOrEmpty(stored.EndedOn), Summary: stringOrEmpty(stored.Summary),
|
|
}
|
|
case *ProfileProject:
|
|
var stored storedProjectValue
|
|
if err := decodeStrictJSON(row.Value, &stored); err != nil {
|
|
return value, err
|
|
}
|
|
if stored.Stack == nil {
|
|
return value, errors.New("value has an unexpected shape")
|
|
}
|
|
*target = NewProfileProject(stored.Title, stringOrEmpty(stored.Description), stored.Stack, stringOrEmpty(stored.RepositoryURL))
|
|
case *ProfileSalaryMinimum:
|
|
var stored storedSalaryValue
|
|
if err := decodeStrictJSON(row.Value, &stored); err != nil {
|
|
return value, err
|
|
}
|
|
if stored.Currency != profileCurrency || stored.Period != profilePeriod {
|
|
return value, errors.New("value has an unsupported currency or period")
|
|
}
|
|
*target = ProfileSalaryMinimum{Amount: stored.Amount, TaxBasis: ProfileTaxBasis(stored.TaxBasis)}
|
|
default:
|
|
if err := decodeStrictJSON(row.Value, &value); err != nil {
|
|
return value, err
|
|
}
|
|
}
|
|
return value, nil
|
|
}
|
|
|
|
func decodeStrictJSON(data []byte, target any) error {
|
|
decoder := json.NewDecoder(bytes.NewReader(data))
|
|
decoder.DisallowUnknownFields()
|
|
if err := decoder.Decode(target); err != nil {
|
|
return errors.New("value has an unexpected shape")
|
|
}
|
|
if decoder.More() {
|
|
return errors.New("value has an unexpected shape")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func restoreClaim[V comparable](rules claimRules[V], row StoredProfileClaim, status ProfileClaimStatus, source ProfileClaimSource) (ProfileClaim[V], error) {
|
|
value, err := decodeStoredValue[V](row)
|
|
if err != nil {
|
|
return ProfileClaim[V]{}, err
|
|
}
|
|
normalized, _, reason := rules.validate(value)
|
|
if reason != "" || normalized != value {
|
|
return ProfileClaim[V]{}, errors.New("value breaks a rule of the contract")
|
|
}
|
|
claim, err := RestoreProfileClaim(value, status, source)
|
|
if err != nil {
|
|
return ProfileClaim[V]{}, errors.New("status does not agree with the provenance")
|
|
}
|
|
return claim, nil
|
|
}
|
|
|
|
func restoreSingle[V comparable](
|
|
target **ProfileClaim[V], rules claimRules[V], row StoredProfileClaim, status ProfileClaimStatus, source ProfileClaimSource,
|
|
) error {
|
|
if *target != nil || row.Ordinal != 0 {
|
|
return errors.New("single field appears more than once or has a position")
|
|
}
|
|
claim, err := restoreClaim(rules, row, status, source)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
*target = &claim
|
|
return nil
|
|
}
|
|
|
|
func restoreItem[V comparable](
|
|
target *[]ProfileClaim[V], rules claimRules[V], row StoredProfileClaim, status ProfileClaimStatus, source ProfileClaimSource,
|
|
) error {
|
|
if row.Ordinal != len(*target) {
|
|
return errors.New("list has a gap or a repeated position")
|
|
}
|
|
claim, err := restoreClaim(rules, row, status, source)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if rules.key != nil {
|
|
for _, existing := range *target {
|
|
if rules.key(existing.value) == rules.key(claim.value) {
|
|
return errors.New("list repeats an item")
|
|
}
|
|
}
|
|
}
|
|
*target = append(*target, claim)
|
|
return nil
|
|
}
|
|
|
|
// StoredCandidateProfile carries the profile row, claims, and acknowledged
|
|
// overlapping date pairs.
|
|
type StoredCandidateProfile struct {
|
|
UserID uuid.UUID
|
|
Version int64
|
|
CreatedAt time.Time
|
|
UpdatedAt time.Time
|
|
Claims []StoredProfileClaim
|
|
ParallelPeriodAcknowledgements []ProfileParallelPeriodAcknowledgement
|
|
}
|
|
|
|
// RestoreCandidateProfile validates a stored profile with the rules of the
|
|
// contract, so a row changed outside the application fails with
|
|
// ErrInvalidCandidateProfile.
|
|
func RestoreCandidateProfile(stored StoredCandidateProfile) (CandidateProfile, error) {
|
|
const location = "domain.RestoreCandidateProfile"
|
|
switch {
|
|
case stored.UserID == uuid.Nil:
|
|
return CandidateProfile{}, fmt.Errorf("%s - user ID must not be nil: %w", location, ErrInvalidCandidateProfile)
|
|
case stored.Version < 1:
|
|
return CandidateProfile{}, fmt.Errorf("%s - version must be positive: %w", location, ErrInvalidCandidateProfile)
|
|
case stored.CreatedAt.IsZero() || stored.UpdatedAt.Before(stored.CreatedAt):
|
|
return CandidateProfile{}, fmt.Errorf("%s - times must be set and ordered: %w", location, ErrInvalidCandidateProfile)
|
|
}
|
|
content, err := RestoreCandidateProfileContentWithParallelPeriods(stored.Claims, stored.ParallelPeriodAcknowledgements)
|
|
if err != nil {
|
|
return CandidateProfile{}, fmt.Errorf("%s - restore content: %w", location, err)
|
|
}
|
|
return CandidateProfile{
|
|
userID: stored.UserID, version: stored.Version, content: content,
|
|
createdAt: stored.CreatedAt, updatedAt: stored.UpdatedAt,
|
|
}, nil
|
|
}
|