feat(profile): persist candidate edits and enforce company access

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 14:15:16 +03:00
1 parent 3ab6bd91a3
commit 73c7caa225
67 files changed
+5286 -229

No files matched your search

@@ -4903,6 +4903,10 @@ func (s *Server) handleGetMyPrivacySettingsRequest(args [0]string, argsEscaped b
// establish and which no request writes. The profile needs no file, no ML extraction, and no FSP
// account.
//
// `experience_overlaps` lists every pair of entries whose inclusive month ranges overlap. Its indices
// refer to this response's `experience` array and are scoped to the same `version`; each pair is
// either `needs_confirmation` or `confirmed`.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
//
@@ -5497,9 +5501,9 @@ func (s *Server) handleGetMySupportCaseRequest(args [1]string, argsEscaped bool,
// handleGetOrganizationRequest handles GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
// Requires the session cookie of a verified employer account with an active owner membership in
// `org_id`. The organization comes from the path and is checked against the membership that the server
// holds for the session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
@@ -5507,15 +5511,11 @@ func (s *Server) handleGetMySupportCaseRequest(args [1]string, argsEscaped bool,
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
// not_found, so organizations cannot be enumerated. An active member whose role is not `owner` answers
// 403 forbidden. A malformed `org_id` answers 400 validation_failed with the path pointer.
//
// GET /api/v1/organizations/{org_id}
func (s *Server) handleGetOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
@@ -5653,7 +5653,7 @@ func (s *Server) handleGetOrganizationRequest(args [1]string, argsEscaped bool,
mreq := middleware.Request{
Context: ctx,
OperationName: GetOrganizationOperation,
OperationSummary: "Read an organization of which the caller is a member.",
OperationSummary: "Read an organization managed by the caller.",
OperationID: "GetOrganization",
Body: nil,
RawBody: rawBody,
@@ -10710,9 +10710,9 @@ func (s *Server) handleRevokeMyOrganizationContactConsentRequest(args [1]string,
//
// Every field is optional in substance: a profile can be saved with any subset filled and the rest
// null or empty, so no value requires a resume, the ML service, an FSP account, or any other file or
// link. Which fields are needed to leave the onboarding step candidate_profile is an open product
// question that this contract does not decide; a save on that step advancing the account to
// candidate_questionnaire is planned.
// link. A successful save advances an account whose current onboarding step is candidate_profile to
// candidate_questionnaire, including a no-op save; it never moves a later step backwards. This update
// is atomic with the profile and its history.
//
// Provenance is the server's: a value typed in the form is `manual`, confirming a stored suggestion
// keeps its origin, and every claim keeps trust level 0. The body has no origin, trust level,
@@ -10737,6 +10737,17 @@ func (s *Server) handleRevokeMyOrganizationContactConsentRequest(args [1]string,
// therefore sends every suggestion that it received, and a client that read an older version gets 412
// instead of silently dropping a suggestion it never saw.
//
// Experience periods use inclusive calendar months. An overlap is allowed only when
// `confirmed_parallel_periods` explicitly acknowledges that the two date ranges are genuine parallel
// work. Each acknowledgement names two distinct experience indices and repeats their exact normalized
// `started_on` and `ended_on` values; both indices and periods must match the submitted array and
// `expected_version`. A new or changed period needs an acknowledgement in that PUT. The server carries
// an earlier acknowledgement only when the same two indices still contain the same dates; reordering
// or changing either date requires a new acknowledgement. Editing other experience fields does not
// invalidate a matching date-pair acknowledgement. A missing acknowledgement answers 400 with pointers
// to the period fields and changes nothing. Duplicate, out-of-range, self, and non-overlapping
// acknowledgements are invalid.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for an employer), a version above the current one (412), domain
// rules that depend on the body alone (400), then the rules that depend on the stored claims against
@@ -10747,9 +10758,9 @@ func (s *Server) handleRevokeMyOrganizationContactConsentRequest(args [1]string,
// without the leading @, an email that is not an address, a month outside `YYYY-MM`, a salary that is
// not a positive multiple of 1000, and more items than a list allows. The server also rejects a
// repeated tag, skill, or role specialization, a period that ends before it starts or lies in the
// future, and a decision `extracted` for a value that is not a stored suggestion, with 400
// validation_failed and pointers to the items, for example `/roles/1/specialization` or
// `/stack/1/status`. Error bodies never repeat a submitted value.
// future, a changed overlap without explicit confirmation, and a decision `extracted` for a value that
// is not a stored suggestion, with 400 validation_failed and pointers to the items, for example
// `/roles/1/specialization` or `/stack/1/status`. Error bodies never repeat a submitted value.
//
// PUT /api/v1/me/profile
func (s *Server) handleSaveMyProfileRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
@@ -9819,6 +9819,14 @@ func (s *CandidateProfile) encodeFields(e *jx.Encoder) {
}
e.ArrEnd()
}
{
e.FieldStart("experience_overlaps")
e.ArrStart()
for _, elem := range s.ExperienceOverlaps {
elem.Encode(e)
}
e.ArrEnd()
}
{
e.FieldStart("soft_skills")
e.ArrStart()
@@ -9845,17 +9853,18 @@ func (s *CandidateProfile) encodeFields(e *jx.Encoder) {
}
}
var jsonFieldsNameOfCandidateProfile = [10]string{
0: "version",
1: "full_name",
2: "contacts",
3: "stack",
4: "roles",
5: "experience",
6: "soft_skills",
7: "terms",
8: "confirmed_categories",
9: "updated_at",
var jsonFieldsNameOfCandidateProfile = [11]string{
0: "version",
1: "full_name",
2: "contacts",
3: "stack",
4: "roles",
5: "experience",
6: "experience_overlaps",
7: "soft_skills",
8: "terms",
9: "confirmed_categories",
10: "updated_at",
}
// Decode decodes CandidateProfile from json.
@@ -9951,8 +9960,26 @@ func (s *CandidateProfile) Decode(d *jx.Decoder) error {
}(); err != nil {
return errors.Wrap(err, "decode field \"experience\"")
}
case "soft_skills":
case "experience_overlaps":
requiredBitSet[0] |= 1 << 6
if err := func() error {
s.ExperienceOverlaps = make([]ProfileExperienceOverlap, 0)
if err := d.Arr(func(d *jx.Decoder) error {
var elem ProfileExperienceOverlap
if err := elem.Decode(d); err != nil {
return err
}
s.ExperienceOverlaps = append(s.ExperienceOverlaps, elem)
return nil
}); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"experience_overlaps\"")
}
case "soft_skills":
requiredBitSet[0] |= 1 << 7
if err := func() error {
s.SoftSkills = make([]ProfileSoftSkillItem, 0)
if err := d.Arr(func(d *jx.Decoder) error {
@@ -9970,7 +9997,7 @@ func (s *CandidateProfile) Decode(d *jx.Decoder) error {
return errors.Wrap(err, "decode field \"soft_skills\"")
}
case "terms":
requiredBitSet[0] |= 1 << 7
requiredBitSet[1] |= 1 << 0
if err := func() error {
if err := s.Terms.Decode(d); err != nil {
return err
@@ -9980,7 +10007,7 @@ func (s *CandidateProfile) Decode(d *jx.Decoder) error {
return errors.Wrap(err, "decode field \"terms\"")
}
case "confirmed_categories":
requiredBitSet[1] |= 1 << 0
requiredBitSet[1] |= 1 << 1
if err := func() error {
s.ConfirmedCategories = make([]ProfileConfirmedCategory, 0)
if err := d.Arr(func(d *jx.Decoder) error {
@@ -9998,7 +10025,7 @@ func (s *CandidateProfile) Decode(d *jx.Decoder) error {
return errors.Wrap(err, "decode field \"confirmed_categories\"")
}
case "updated_at":
requiredBitSet[1] |= 1 << 1
requiredBitSet[1] |= 1 << 2
if err := func() error {
if err := s.UpdatedAt.Decode(d); err != nil {
return err
@@ -10018,7 +10045,7 @@ func (s *CandidateProfile) Decode(d *jx.Decoder) error {
var failures []validate.FieldError
for i, mask := range [2]uint8{
0b11111111,
0b00000011,
0b00000111,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
@@ -10109,6 +10136,16 @@ func (s *CandidateProfileUpdate) encodeFields(e *jx.Encoder) {
}
e.ArrEnd()
}
{
if s.ConfirmedParallelPeriods != nil {
e.FieldStart("confirmed_parallel_periods")
e.ArrStart()
for _, elem := range s.ConfirmedParallelPeriods {
elem.Encode(e)
}
e.ArrEnd()
}
}
{
e.FieldStart("soft_skills")
e.ArrStart()
@@ -10123,15 +10160,16 @@ func (s *CandidateProfileUpdate) encodeFields(e *jx.Encoder) {
}
}
var jsonFieldsNameOfCandidateProfileUpdate = [8]string{
var jsonFieldsNameOfCandidateProfileUpdate = [9]string{
0: "expected_version",
1: "full_name",
2: "contacts",
3: "stack",
4: "roles",
5: "experience",
6: "soft_skills",
7: "terms",
6: "confirmed_parallel_periods",
7: "soft_skills",
8: "terms",
}
// Decode decodes CandidateProfileUpdate from json.
@@ -10139,7 +10177,7 @@ func (s *CandidateProfileUpdate) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode CandidateProfileUpdate to nil")
}
var requiredBitSet [1]uint8
var requiredBitSet [2]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
@@ -10227,8 +10265,25 @@ func (s *CandidateProfileUpdate) Decode(d *jx.Decoder) error {
}(); err != nil {
return errors.Wrap(err, "decode field \"experience\"")
}
case "confirmed_parallel_periods":
if err := func() error {
s.ConfirmedParallelPeriods = make([]ProfileParallelPeriodConfirmation, 0)
if err := d.Arr(func(d *jx.Decoder) error {
var elem ProfileParallelPeriodConfirmation
if err := elem.Decode(d); err != nil {
return err
}
s.ConfirmedParallelPeriods = append(s.ConfirmedParallelPeriods, elem)
return nil
}); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"confirmed_parallel_periods\"")
}
case "soft_skills":
requiredBitSet[0] |= 1 << 6
requiredBitSet[0] |= 1 << 7
if err := func() error {
s.SoftSkills = make([]ProfileSoftSkillItemInput, 0)
if err := d.Arr(func(d *jx.Decoder) error {
@@ -10246,7 +10301,7 @@ func (s *CandidateProfileUpdate) Decode(d *jx.Decoder) error {
return errors.Wrap(err, "decode field \"soft_skills\"")
}
case "terms":
requiredBitSet[0] |= 1 << 7
requiredBitSet[1] |= 1 << 0
if err := func() error {
if err := s.Terms.Decode(d); err != nil {
return err
@@ -10264,8 +10319,9 @@ func (s *CandidateProfileUpdate) Decode(d *jx.Decoder) error {
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b11111111,
for i, mask := range [2]uint8{
0b10111111,
0b00000001,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
@@ -40269,6 +40325,283 @@ func (s *ProfileExperienceItemInput) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *ProfileExperienceOverlap) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *ProfileExperienceOverlap) encodeFields(e *jx.Encoder) {
{
e.FieldStart("first_index")
e.Int(s.FirstIndex)
}
{
e.FieldStart("second_index")
e.Int(s.SecondIndex)
}
{
e.FieldStart("status")
s.Status.Encode(e)
}
}
var jsonFieldsNameOfProfileExperienceOverlap = [3]string{
0: "first_index",
1: "second_index",
2: "status",
}
// Decode decodes ProfileExperienceOverlap from json.
func (s *ProfileExperienceOverlap) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ProfileExperienceOverlap to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "first_index":
requiredBitSet[0] |= 1 << 0
if err := func() error {
v, err := d.Int()
s.FirstIndex = int(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"first_index\"")
}
case "second_index":
requiredBitSet[0] |= 1 << 1
if err := func() error {
v, err := d.Int()
s.SecondIndex = int(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"second_index\"")
}
case "status":
requiredBitSet[0] |= 1 << 2
if err := func() error {
if err := s.Status.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"status\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode ProfileExperienceOverlap")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000111,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfProfileExperienceOverlap) {
name = jsonFieldsNameOfProfileExperienceOverlap[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *ProfileExperienceOverlap) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ProfileExperienceOverlap) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ProfileExperienceOverlapStatus as json.
func (s ProfileExperienceOverlapStatus) Encode(e *jx.Encoder) {
e.Str(string(s))
}
// Decode decodes ProfileExperienceOverlapStatus from json.
func (s *ProfileExperienceOverlapStatus) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ProfileExperienceOverlapStatus to nil")
}
v, err := d.StrBytes()
if err != nil {
return err
}
// Try to use constant string.
switch ProfileExperienceOverlapStatus(v) {
case ProfileExperienceOverlapStatusNeedsConfirmation:
*s = ProfileExperienceOverlapStatusNeedsConfirmation
case ProfileExperienceOverlapStatusConfirmed:
*s = ProfileExperienceOverlapStatusConfirmed
default:
*s = ProfileExperienceOverlapStatus(v)
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s ProfileExperienceOverlapStatus) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ProfileExperienceOverlapStatus) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *ProfileExperiencePeriod) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *ProfileExperiencePeriod) encodeFields(e *jx.Encoder) {
{
e.FieldStart("started_on")
s.StartedOn.Encode(e)
}
{
e.FieldStart("ended_on")
s.EndedOn.Encode(e)
}
}
var jsonFieldsNameOfProfileExperiencePeriod = [2]string{
0: "started_on",
1: "ended_on",
}
// Decode decodes ProfileExperiencePeriod from json.
func (s *ProfileExperiencePeriod) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ProfileExperiencePeriod to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "started_on":
requiredBitSet[0] |= 1 << 0
if err := func() error {
if err := s.StartedOn.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"started_on\"")
}
case "ended_on":
requiredBitSet[0] |= 1 << 1
if err := func() error {
if err := s.EndedOn.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"ended_on\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode ProfileExperiencePeriod")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000011,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfProfileExperiencePeriod) {
name = jsonFieldsNameOfProfileExperiencePeriod[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *ProfileExperiencePeriod) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ProfileExperiencePeriod) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ProfileExperienceSummary as json.
func (s ProfileExperienceSummary) Encode(e *jx.Encoder) {
unwrapped := string(s)
@@ -40855,6 +41188,149 @@ func (s *ProfileLocationName) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *ProfileParallelPeriodConfirmation) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *ProfileParallelPeriodConfirmation) encodeFields(e *jx.Encoder) {
{
e.FieldStart("first_index")
e.Int(s.FirstIndex)
}
{
e.FieldStart("second_index")
e.Int(s.SecondIndex)
}
{
e.FieldStart("first_period")
s.FirstPeriod.Encode(e)
}
{
e.FieldStart("second_period")
s.SecondPeriod.Encode(e)
}
}
var jsonFieldsNameOfProfileParallelPeriodConfirmation = [4]string{
0: "first_index",
1: "second_index",
2: "first_period",
3: "second_period",
}
// Decode decodes ProfileParallelPeriodConfirmation from json.
func (s *ProfileParallelPeriodConfirmation) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ProfileParallelPeriodConfirmation to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "first_index":
requiredBitSet[0] |= 1 << 0
if err := func() error {
v, err := d.Int()
s.FirstIndex = int(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"first_index\"")
}
case "second_index":
requiredBitSet[0] |= 1 << 1
if err := func() error {
v, err := d.Int()
s.SecondIndex = int(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"second_index\"")
}
case "first_period":
requiredBitSet[0] |= 1 << 2
if err := func() error {
if err := s.FirstPeriod.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"first_period\"")
}
case "second_period":
requiredBitSet[0] |= 1 << 3
if err := func() error {
if err := s.SecondPeriod.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"second_period\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode ProfileParallelPeriodConfirmation")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00001111,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfProfileParallelPeriodConfirmation) {
name = jsonFieldsNameOfProfileParallelPeriodConfirmation[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *ProfileParallelPeriodConfirmation) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ProfileParallelPeriodConfirmation) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *ProfilePhoneClaim) Encode(e *jx.Encoder) {
e.ObjStart()
@@ -3261,7 +3261,7 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
switch method {
case "GET":
r.name = GetOrganizationOperation
r.summary = "Read an organization of which the caller is a member."
r.summary = "Read an organization managed by the caller."
r.operationID = "GetOrganization"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}"
@@ -5097,6 +5097,9 @@ type CandidateProfile struct {
Roles []ProfileRoleItem `json:"roles"`
// Work history entries in the order the candidate gave them.
Experience []ProfileExperienceItem `json:"experience"`
// Every pair of overlapping experience periods, with its confirmation status. The indices refer to
// this version's experience array.
ExperienceOverlaps []ProfileExperienceOverlap `json:"experience_overlaps"`
// Soft skills in the order the candidate gave them, each skill at most once without regard to letter
// case.
SoftSkills []ProfileSoftSkillItem `json:"soft_skills"`
@@ -5138,6 +5141,11 @@ func (s *CandidateProfile) GetExperience() []ProfileExperienceItem {
return s.Experience
}
// GetExperienceOverlaps returns the value of ExperienceOverlaps.
func (s *CandidateProfile) GetExperienceOverlaps() []ProfileExperienceOverlap {
return s.ExperienceOverlaps
}
// GetSoftSkills returns the value of SoftSkills.
func (s *CandidateProfile) GetSoftSkills() []ProfileSoftSkillItem {
return s.SoftSkills
@@ -5188,6 +5196,11 @@ func (s *CandidateProfile) SetExperience(val []ProfileExperienceItem) {
s.Experience = val
}
// SetExperienceOverlaps sets the value of ExperienceOverlaps.
func (s *CandidateProfile) SetExperienceOverlaps(val []ProfileExperienceOverlap) {
s.ExperienceOverlaps = val
}
// SetSoftSkills sets the value of SoftSkills.
func (s *CandidateProfile) SetSoftSkills(val []ProfileSoftSkillItem) {
s.SoftSkills = val
@@ -5259,6 +5272,11 @@ type CandidateProfileUpdate struct {
Roles []ProfileRoleItemInput `json:"roles"`
// Work history entries.
Experience []ProfileExperienceItemInput `json:"experience"`
// Explicit acknowledgements for overlapping periods. Each pair must use distinct in-range indices and
// repeat the exact normalized started_on and ended_on values of those entries in this body. A changed
// or reordered period needs a new acknowledgement. The server retains a previous acknowledgement only
// for the same indices and dates. Duplicate pairs and pairs that do not overlap are rejected.
ConfirmedParallelPeriods []ProfileParallelPeriodConfirmation `json:"confirmed_parallel_periods"`
// Soft skills. The server answers 400 with the pointer of a skill that repeats an earlier one without
// regard to letter case.
SoftSkills []ProfileSoftSkillItemInput `json:"soft_skills"`
@@ -5295,6 +5313,11 @@ func (s *CandidateProfileUpdate) GetExperience() []ProfileExperienceItemInput {
return s.Experience
}
// GetConfirmedParallelPeriods returns the value of ConfirmedParallelPeriods.
func (s *CandidateProfileUpdate) GetConfirmedParallelPeriods() []ProfileParallelPeriodConfirmation {
return s.ConfirmedParallelPeriods
}
// GetSoftSkills returns the value of SoftSkills.
func (s *CandidateProfileUpdate) GetSoftSkills() []ProfileSoftSkillItemInput {
return s.SoftSkills
@@ -5335,6 +5358,11 @@ func (s *CandidateProfileUpdate) SetExperience(val []ProfileExperienceItemInput)
s.Experience = val
}
// SetConfirmedParallelPeriods sets the value of ConfirmedParallelPeriods.
func (s *CandidateProfileUpdate) SetConfirmedParallelPeriods(val []ProfileParallelPeriodConfirmation) {
s.ConfirmedParallelPeriods = val
}
// SetSoftSkills sets the value of SoftSkills.
func (s *CandidateProfileUpdate) SetSoftSkills(val []ProfileSoftSkillItemInput) {
s.SoftSkills = val
@@ -21066,6 +21094,117 @@ func (s *ProfileExperienceItemInput) SetStatus(val ProfileItemStatus) {
s.Status = val
}
// One pair of work history entries whose inclusive month ranges overlap. The indices refer to the
// experience array in this profile version. `confirmed` records an explicit acknowledgement for this
// pair of dates; otherwise the pair needs confirmation before a changed profile can be saved.
// Ref: #/components/schemas/ProfileExperienceOverlap
type ProfileExperienceOverlap struct {
FirstIndex int `json:"first_index"`
SecondIndex int `json:"second_index"`
Status ProfileExperienceOverlapStatus `json:"status"`
}
// GetFirstIndex returns the value of FirstIndex.
func (s *ProfileExperienceOverlap) GetFirstIndex() int {
return s.FirstIndex
}
// GetSecondIndex returns the value of SecondIndex.
func (s *ProfileExperienceOverlap) GetSecondIndex() int {
return s.SecondIndex
}
// GetStatus returns the value of Status.
func (s *ProfileExperienceOverlap) GetStatus() ProfileExperienceOverlapStatus {
return s.Status
}
// SetFirstIndex sets the value of FirstIndex.
func (s *ProfileExperienceOverlap) SetFirstIndex(val int) {
s.FirstIndex = val
}
// SetSecondIndex sets the value of SecondIndex.
func (s *ProfileExperienceOverlap) SetSecondIndex(val int) {
s.SecondIndex = val
}
// SetStatus sets the value of Status.
func (s *ProfileExperienceOverlap) SetStatus(val ProfileExperienceOverlapStatus) {
s.Status = val
}
// Whether the candidate confirmed that two overlapping periods are genuine parallel work.
// Ref: #/components/schemas/ProfileExperienceOverlapStatus
type ProfileExperienceOverlapStatus string
const (
ProfileExperienceOverlapStatusNeedsConfirmation ProfileExperienceOverlapStatus = "needs_confirmation"
ProfileExperienceOverlapStatusConfirmed ProfileExperienceOverlapStatus = "confirmed"
)
// AllValues returns all ProfileExperienceOverlapStatus values.
func (ProfileExperienceOverlapStatus) AllValues() []ProfileExperienceOverlapStatus {
return []ProfileExperienceOverlapStatus{
ProfileExperienceOverlapStatusNeedsConfirmation,
ProfileExperienceOverlapStatusConfirmed,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s ProfileExperienceOverlapStatus) MarshalText() ([]byte, error) {
switch s {
case ProfileExperienceOverlapStatusNeedsConfirmation:
return []byte(s), nil
case ProfileExperienceOverlapStatusConfirmed:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *ProfileExperienceOverlapStatus) UnmarshalText(data []byte) error {
switch ProfileExperienceOverlapStatus(data) {
case ProfileExperienceOverlapStatusNeedsConfirmation:
*s = ProfileExperienceOverlapStatusNeedsConfirmation
return nil
case ProfileExperienceOverlapStatusConfirmed:
*s = ProfileExperienceOverlapStatusConfirmed
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// The exact month range of an experience entry, copied into a confirmation.
// Ref: #/components/schemas/ProfileExperiencePeriod
type ProfileExperiencePeriod struct {
StartedOn ProfileYearMonth `json:"started_on"`
// Last month of work, or null when the period is open-ended.
EndedOn NilProfileYearMonth `json:"ended_on"`
}
// GetStartedOn returns the value of StartedOn.
func (s *ProfileExperiencePeriod) GetStartedOn() ProfileYearMonth {
return s.StartedOn
}
// GetEndedOn returns the value of EndedOn.
func (s *ProfileExperiencePeriod) GetEndedOn() NilProfileYearMonth {
return s.EndedOn
}
// SetStartedOn sets the value of StartedOn.
func (s *ProfileExperiencePeriod) SetStartedOn(val ProfileYearMonth) {
s.StartedOn = val
}
// SetEndedOn sets the value of EndedOn.
func (s *ProfileExperiencePeriod) SetEndedOn(val NilProfileYearMonth) {
s.EndedOn = val
}
type ProfileExperienceSummary string
// Full name of the candidate with its confirmation state and provenance. The value is personal data.
@@ -21260,6 +21399,57 @@ func (s *ProfileLocationInput) SetStatus(val ProfileItemStatus) {
type ProfileLocationName string
// Explicit acknowledgement that the two indexed experience periods are genuine parallel work. The
// indices and exact ranges must match the submitted experience array; expected_version binds the
// acknowledgement to the profile version the candidate read.
// Ref: #/components/schemas/ProfileParallelPeriodConfirmation
type ProfileParallelPeriodConfirmation struct {
FirstIndex int `json:"first_index"`
SecondIndex int `json:"second_index"`
FirstPeriod ProfileExperiencePeriod `json:"first_period"`
SecondPeriod ProfileExperiencePeriod `json:"second_period"`
}
// GetFirstIndex returns the value of FirstIndex.
func (s *ProfileParallelPeriodConfirmation) GetFirstIndex() int {
return s.FirstIndex
}
// GetSecondIndex returns the value of SecondIndex.
func (s *ProfileParallelPeriodConfirmation) GetSecondIndex() int {
return s.SecondIndex
}
// GetFirstPeriod returns the value of FirstPeriod.
func (s *ProfileParallelPeriodConfirmation) GetFirstPeriod() ProfileExperiencePeriod {
return s.FirstPeriod
}
// GetSecondPeriod returns the value of SecondPeriod.
func (s *ProfileParallelPeriodConfirmation) GetSecondPeriod() ProfileExperiencePeriod {
return s.SecondPeriod
}
// SetFirstIndex sets the value of FirstIndex.
func (s *ProfileParallelPeriodConfirmation) SetFirstIndex(val int) {
s.FirstIndex = val
}
// SetSecondIndex sets the value of SecondIndex.
func (s *ProfileParallelPeriodConfirmation) SetSecondIndex(val int) {
s.SecondIndex = val
}
// SetFirstPeriod sets the value of FirstPeriod.
func (s *ProfileParallelPeriodConfirmation) SetFirstPeriod(val ProfileExperiencePeriod) {
s.FirstPeriod = val
}
// SetSecondPeriod sets the value of SecondPeriod.
func (s *ProfileParallelPeriodConfirmation) SetSecondPeriod(val ProfileExperiencePeriod) {
s.SecondPeriod = val
}
// Contact phone number of the candidate with its confirmation state and provenance. It is personal
// data, stored in the E.164 format of the contact disclosure. `value` and `source` are null exactly
// when `status` is `unknown`.
@@ -700,6 +700,10 @@ type Handler interface {
// establish and which no request writes. The profile needs no file, no ML extraction, and no FSP
// account.
//
// `experience_overlaps` lists every pair of entries whose inclusive month ranges overlap. Its indices
// refer to this response's `experience` array and are scoped to the same `version`; each pair is
// either `needs_confirmation` or `confirmed`.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
//
@@ -742,9 +746,9 @@ type Handler interface {
GetMySupportCase(ctx context.Context, params GetMySupportCaseParams) (GetMySupportCaseRes, error)
// GetOrganization implements GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
// Requires the session cookie of a verified employer account with an active owner membership in
// `org_id`. The organization comes from the path and is checked against the membership that the server
// holds for the session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
@@ -752,15 +756,11 @@ type Handler interface {
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
// not_found, so organizations cannot be enumerated. An active member whose role is not `owner` answers
// 403 forbidden. A malformed `org_id` answers 400 validation_failed with the path pointer.
//
// GET /api/v1/organizations/{org_id}
GetOrganization(ctx context.Context, params GetOrganizationParams) (GetOrganizationRes, error)
@@ -1293,9 +1293,9 @@ type Handler interface {
//
// Every field is optional in substance: a profile can be saved with any subset filled and the rest
// null or empty, so no value requires a resume, the ML service, an FSP account, or any other file or
// link. Which fields are needed to leave the onboarding step candidate_profile is an open product
// question that this contract does not decide; a save on that step advancing the account to
// candidate_questionnaire is planned.
// link. A successful save advances an account whose current onboarding step is candidate_profile to
// candidate_questionnaire, including a no-op save; it never moves a later step backwards. This update
// is atomic with the profile and its history.
//
// Provenance is the server's: a value typed in the form is `manual`, confirming a stored suggestion
// keeps its origin, and every claim keeps trust level 0. The body has no origin, trust level,
@@ -1320,6 +1320,17 @@ type Handler interface {
// therefore sends every suggestion that it received, and a client that read an older version gets 412
// instead of silently dropping a suggestion it never saw.
//
// Experience periods use inclusive calendar months. An overlap is allowed only when
// `confirmed_parallel_periods` explicitly acknowledges that the two date ranges are genuine parallel
// work. Each acknowledgement names two distinct experience indices and repeats their exact normalized
// `started_on` and `ended_on` values; both indices and periods must match the submitted array and
// `expected_version`. A new or changed period needs an acknowledgement in that PUT. The server carries
// an earlier acknowledgement only when the same two indices still contain the same dates; reordering
// or changing either date requires a new acknowledgement. Editing other experience fields does not
// invalidate a matching date-pair acknowledgement. A missing acknowledgement answers 400 with pointers
// to the period fields and changes nothing. Duplicate, out-of-range, self, and non-overlapping
// acknowledgements are invalid.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for an employer), a version above the current one (412), domain
// rules that depend on the body alone (400), then the rules that depend on the stored claims against
@@ -1330,9 +1341,9 @@ type Handler interface {
// without the leading @, an email that is not an address, a month outside `YYYY-MM`, a salary that is
// not a positive multiple of 1000, and more items than a list allows. The server also rejects a
// repeated tag, skill, or role specialization, a period that ends before it starts or lies in the
// future, and a decision `extracted` for a value that is not a stored suggestion, with 400
// validation_failed and pointers to the items, for example `/roles/1/specialization` or
// `/stack/1/status`. Error bodies never repeat a submitted value.
// future, a changed overlap without explicit confirmation, and a decision `extracted` for a value that
// is not a stored suggestion, with 400 validation_failed and pointers to the items, for example
// `/roles/1/specialization` or `/stack/1/status`. Error bodies never repeat a submitted value.
//
// PUT /api/v1/me/profile
SaveMyProfile(ctx context.Context, req *CandidateProfileUpdate) (SaveMyProfileRes, error)
@@ -768,6 +768,10 @@ func (UnimplementedHandler) GetMyPrivacySettings(ctx context.Context) (r GetMyPr
// establish and which no request writes. The profile needs no file, no ML extraction, and no FSP
// account.
//
// `experience_overlaps` lists every pair of entries whose inclusive month ranges overlap. Its indices
// refer to this response's `experience` array and are scoped to the same `version`; each pair is
// either `needs_confirmation` or `confirmed`.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
//
@@ -819,9 +823,9 @@ func (UnimplementedHandler) GetMySupportCase(ctx context.Context, params GetMySu
// GetOrganization implements GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
// Requires the session cookie of a verified employer account with an active owner membership in
// `org_id`. The organization comes from the path and is checked against the membership that the server
// holds for the session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
@@ -829,15 +833,11 @@ func (UnimplementedHandler) GetMySupportCase(ctx context.Context, params GetMySu
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
// not_found, so organizations cannot be enumerated. An active member whose role is not `owner` answers
// 403 forbidden. A malformed `org_id` answers 400 validation_failed with the path pointer.
//
// GET /api/v1/organizations/{org_id}
func (UnimplementedHandler) GetOrganization(ctx context.Context, params GetOrganizationParams) (r GetOrganizationRes, _ error) {
@@ -1442,9 +1442,9 @@ func (UnimplementedHandler) RevokeMyOrganizationContactConsent(ctx context.Conte
//
// Every field is optional in substance: a profile can be saved with any subset filled and the rest
// null or empty, so no value requires a resume, the ML service, an FSP account, or any other file or
// link. Which fields are needed to leave the onboarding step candidate_profile is an open product
// question that this contract does not decide; a save on that step advancing the account to
// candidate_questionnaire is planned.
// link. A successful save advances an account whose current onboarding step is candidate_profile to
// candidate_questionnaire, including a no-op save; it never moves a later step backwards. This update
// is atomic with the profile and its history.
//
// Provenance is the server's: a value typed in the form is `manual`, confirming a stored suggestion
// keeps its origin, and every claim keeps trust level 0. The body has no origin, trust level,
@@ -1469,6 +1469,17 @@ func (UnimplementedHandler) RevokeMyOrganizationContactConsent(ctx context.Conte
// therefore sends every suggestion that it received, and a client that read an older version gets 412
// instead of silently dropping a suggestion it never saw.
//
// Experience periods use inclusive calendar months. An overlap is allowed only when
// `confirmed_parallel_periods` explicitly acknowledges that the two date ranges are genuine parallel
// work. Each acknowledgement names two distinct experience indices and repeats their exact normalized
// `started_on` and `ended_on` values; both indices and periods must match the submitted array and
// `expected_version`. A new or changed period needs an acknowledgement in that PUT. The server carries
// an earlier acknowledgement only when the same two indices still contain the same dates; reordering
// or changing either date requires a new acknowledgement. Editing other experience fields does not
// invalidate a matching date-pair acknowledgement. A missing acknowledgement answers 400 with pointers
// to the period fields and changes nothing. Duplicate, out-of-range, self, and non-overlapping
// acknowledgements are invalid.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for an employer), a version above the current one (412), domain
// rules that depend on the body alone (400), then the rules that depend on the stored claims against
@@ -1479,9 +1490,9 @@ func (UnimplementedHandler) RevokeMyOrganizationContactConsent(ctx context.Conte
// without the leading @, an email that is not an address, a month outside `YYYY-MM`, a salary that is
// not a positive multiple of 1000, and more items than a list allows. The server also rejects a
// repeated tag, skill, or role specialization, a period that ends before it starts or lies in the
// future, and a decision `extracted` for a value that is not a stored suggestion, with 400
// validation_failed and pointers to the items, for example `/roles/1/specialization` or
// `/stack/1/status`. Error bodies never repeat a submitted value.
// future, a changed overlap without explicit confirmation, and a decision `extracted` for a value that
// is not a stored suggestion, with 400 validation_failed and pointers to the items, for example
// `/roles/1/specialization` or `/stack/1/status`. Error bodies never repeat a submitted value.
//
// PUT /api/v1/me/profile
func (UnimplementedHandler) SaveMyProfile(ctx context.Context, req *CandidateProfileUpdate) (r SaveMyProfileRes, _ error) {
@@ -4553,6 +4553,42 @@ func (s *CandidateProfile) Validate() error {
Error: err,
})
}
if err := func() error {
if s.ExperienceOverlaps == nil {
return errors.New("nil is invalid value")
}
if err := (validate.Array{
MinLength: 0,
MinLengthSet: false,
MaxLength: 190,
MaxLengthSet: true,
}).ValidateLength(len(s.ExperienceOverlaps)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.ExperienceOverlaps {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "experience_overlaps",
Error: err,
})
}
if err := func() error {
if s.SoftSkills == nil {
return errors.New("nil is invalid value")
@@ -4830,6 +4866,42 @@ func (s *CandidateProfileUpdate) Validate() error {
Error: err,
})
}
if err := func() error {
if s.ConfirmedParallelPeriods == nil {
return nil // optional
}
if err := (validate.Array{
MinLength: 0,
MinLengthSet: false,
MaxLength: 190,
MaxLengthSet: true,
}).ValidateLength(len(s.ConfirmedParallelPeriods)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.ConfirmedParallelPeriods {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "confirmed_parallel_periods",
Error: err,
})
}
if err := func() error {
if s.SoftSkills == nil {
return errors.New("nil is invalid value")
@@ -16144,6 +16216,123 @@ func (s *ProfileExperienceItemInput) Validate() error {
return nil
}
func (s *ProfileExperienceOverlap) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 0,
MaxSet: true,
Max: 19,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(s.FirstIndex)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "first_index",
Error: err,
})
}
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 19,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(s.SecondIndex)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "second_index",
Error: err,
})
}
if err := func() error {
if err := s.Status.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "status",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s ProfileExperienceOverlapStatus) Validate() error {
switch s {
case "needs_confirmation":
return nil
case "confirmed":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *ProfileExperiencePeriod) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.StartedOn.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "started_on",
Error: err,
})
}
if err := func() error {
if value, ok := s.EndedOn.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "ended_on",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s ProfileExperienceSummary) Validate() error {
alias := (string)(s)
if err := (validate.String{
@@ -16381,6 +16570,82 @@ func (s ProfileLocationName) Validate() error {
return nil
}
func (s *ProfileParallelPeriodConfirmation) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 0,
MaxSet: true,
Max: 19,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(s.FirstIndex)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "first_index",
Error: err,
})
}
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 19,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(s.SecondIndex)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "second_index",
Error: err,
})
}
if err := func() error {
if err := s.FirstPeriod.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "first_period",
Error: err,
})
}
if err := func() error {
if err := s.SecondPeriod.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "second_period",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *ProfilePhoneClaim) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -106,10 +106,18 @@ func TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory(t *test
t.Error("the profile does not state confirmed categories apart from the claims")
}
update := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CandidateProfileUpdate"})
wantUpdate := []string{"contacts", "expected_version", "experience", "full_name", "roles", "soft_skills", "stack", "terms"}
wantUpdate := []string{"confirmed_parallel_periods", "contacts", "expected_version", "experience", "full_name", "roles", "soft_skills", "stack", "terms"}
if got := propertyNames(update); !slices.Equal(got, wantUpdate) {
t.Errorf("CandidateProfileUpdate properties = %v, want %v", got, wantUpdate)
}
profile = resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CandidateProfile"})
if !slices.Contains(profile.Required, "experience_overlaps") {
t.Error("CandidateProfile does not report every overlapping experience pair")
}
confirmation := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileParallelPeriodConfirmation"})
if got := propertyNames(confirmation); !slices.Equal(got, []string{"first_index", "first_period", "second_index", "second_period"}) {
t.Errorf("ProfileParallelPeriodConfirmation properties = %v, want indices and exact periods only", got)
}
role := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileRoleItemInput"})
if got := propertyNames(role); !slices.Equal(got, []string{"self_assessed_grade", "specialization", "status"}) {
@@ -0,0 +1,97 @@
package httpadapter
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
ogenmiddleware "github.com/ogen-go/ogen/middleware"
apiadapter "lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/organization"
)
// CompanyAuthorizer checks the current authenticated account against a
// company's active owner membership.
type CompanyAuthorizer interface {
AuthorizeCompany(ctx context.Context, actorID, organizationID uuid.UUID) (organization.CompanyAccess, error)
}
var ownerCompanyOperations = map[apiadapter.OperationName]struct{}{
apiadapter.GetOrganizationOperation: {},
apiadapter.UpdateOrganizationOperation: {},
apiadapter.ListOrganizationNeedsOperation: {},
apiadapter.CreateOrganizationNeedOperation: {},
apiadapter.GetOrganizationNeedOperation: {},
apiadapter.UpdateOrganizationNeedOperation: {},
apiadapter.ListOrganizationInvitationsOperation: {},
apiadapter.CreateOrganizationInvitationOperation: {},
apiadapter.GetOrganizationInvitationOperation: {},
apiadapter.UpdateOrganizationInvitationOperation: {},
apiadapter.SendOrganizationInvitationOperation: {},
apiadapter.GetOrganizationInvitationContactsOperation: {},
apiadapter.WithdrawOrganizationInvitationOperation: {},
apiadapter.RaiseOrganizationInvitationSalaryOperation: {},
}
// NewCompanyContextMiddleware verifies every owner-scoped company operation
// after generated security and parameter decoding, then attaches the request
// capability. Operations outside the explicit map pass through unchanged.
func NewCompanyContextMiddleware(authorizer CompanyAuthorizer) apiadapter.Middleware {
return func(request ogenmiddleware.Request, next ogenmiddleware.Next) (ogenmiddleware.Response, error) {
if _, required := ownerCompanyOperations[request.OperationName]; !required {
return next(request)
}
if authorizer == nil {
return ogenmiddleware.Response{}, errors.New("httpadapter.NewCompanyContextMiddleware - company authorizer is not configured")
}
principal, ok := v1.PrincipalFromContext(request.Context)
if !ok {
return ogenmiddleware.Response{}, problem.New(request.Context, apiadapter.ProblemCodeUnauthenticated)
}
organizationID, ok := companyPathID(request)
if !ok {
return ogenmiddleware.Response{}, errors.New("httpadapter.NewCompanyContextMiddleware - decoded organization identifier has an unexpected type")
}
access, err := authorizer.AuthorizeCompany(request.Context, principal.UserID, organizationID)
if err != nil {
if response := companyAuthorizationProblem(request.Context, err); response != nil {
return ogenmiddleware.Response{}, response
}
return ogenmiddleware.Response{}, fmt.Errorf("httpadapter.NewCompanyContextMiddleware - authorize company: %w", err)
}
if !access.Matches(principal.UserID, organizationID) {
return ogenmiddleware.Response{}, errors.New("httpadapter.NewCompanyContextMiddleware - authorizer returned a mismatched company capability")
}
request.SetContext(organization.WithCompanyAccess(request.Context, access))
return next(request)
}
}
func companyPathID(request ogenmiddleware.Request) (uuid.UUID, bool) {
value, ok := request.Params.Path("org_id")
if !ok {
return uuid.Nil, false
}
organizationID, ok := value.(uuid.UUID)
return organizationID, ok && organizationID != uuid.Nil
}
func companyAuthorizationProblem(ctx context.Context, err error) *apiadapter.ProblemStatusCode {
switch {
case errors.Is(err, organization.ErrEmailNotVerified):
return problem.New(ctx, apiadapter.ProblemCodeEmailNotVerified)
case errors.Is(err, organization.ErrForbidden), errors.Is(err, outbound.ErrOrganizationManagerRequired):
return problem.New(ctx, apiadapter.ProblemCodeForbidden)
case errors.Is(err, outbound.ErrOrganizationNotFound):
return problem.New(ctx, apiadapter.ProblemCodeNotFound)
default:
return nil
}
}
var _ CompanyAuthorizer = (*v1.OrganizationHandler)(nil)
@@ -0,0 +1,205 @@
package httpadapter
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/google/uuid"
ogenmiddleware "github.com/ogen-go/ogen/middleware"
"github.com/ogen-go/ogen/openapi"
"go.yaml.in/yaml/v3"
apiadapter "lincodex/backend/internal/adapter/primary/http/api"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/organization"
)
type companyAuthorizerFunc func(context.Context, uuid.UUID, uuid.UUID) (organization.CompanyAccess, error)
type requestContextRecorder struct {
context context.Context
}
func (recorder *requestContextRecorder) ServeHTTP(_ http.ResponseWriter, request *http.Request) {
recorder.context = request.Context()
}
func (authorizer companyAuthorizerFunc) AuthorizeCompany(ctx context.Context, actorID, organizationID uuid.UUID) (organization.CompanyAccess, error) {
return authorizer(ctx, actorID, organizationID)
}
func TestCompanyContextMiddlewareFailsClosedAndExcludesCandidateScopes(t *testing.T) {
organizationID := uuid.New()
request := ownerCompanyMiddlewareRequest(t, uuid.New(), apiadapter.GetOrganizationOperation, organizationID)
if _, err := NewCompanyContextMiddleware(nil)(request, func(ogenmiddleware.Request) (ogenmiddleware.Response, error) {
t.Fatal("owner operation reached next without an authorizer")
return ogenmiddleware.Response{}, nil
}); err == nil {
t.Fatal("owner operation passed without an authorizer")
}
for _, operation := range []apiadapter.OperationName{
apiadapter.HideOrganizationOperation,
apiadapter.UnhideOrganizationOperation,
apiadapter.RevokeMyOrganizationContactConsentOperation,
apiadapter.ListMyOrganizationsOperation,
} {
t.Run(operation, func(t *testing.T) {
called := false
_, err := NewCompanyContextMiddleware(nil)(ownerCompanyMiddlewareRequest(t, uuid.New(), operation, organizationID),
func(ogenmiddleware.Request) (ogenmiddleware.Response, error) {
called = true
return ogenmiddleware.Response{}, nil
})
if err != nil || !called {
t.Fatalf("candidate/self-scoped operation: called=%v err=%v; want pass-through", called, err)
}
})
}
}
func TestCompanyContextMiddlewareMapsMembershipFailuresToPublicProblems(t *testing.T) {
for _, test := range []struct {
name string
err error
code apiadapter.ProblemCode
}{
{name: "candidate", err: organization.ErrForbidden, code: apiadapter.ProblemCodeForbidden},
{name: "unverified employer", err: organization.ErrEmailNotVerified, code: apiadapter.ProblemCodeEmailNotVerified},
{name: "other role", err: outbound.ErrOrganizationManagerRequired, code: apiadapter.ProblemCodeForbidden},
{name: "missing or inactive membership", err: outbound.ErrOrganizationNotFound, code: apiadapter.ProblemCodeNotFound},
} {
t.Run(test.name, func(t *testing.T) {
request := ownerCompanyMiddlewareRequest(t, uuid.New(), apiadapter.GetOrganizationOperation, uuid.New())
authorizer := companyAuthorizerFunc(func(context.Context, uuid.UUID, uuid.UUID) (organization.CompanyAccess, error) {
return organization.CompanyAccess{}, test.err
})
called := false
_, err := NewCompanyContextMiddleware(authorizer)(request, func(ogenmiddleware.Request) (ogenmiddleware.Response, error) {
called = true
return ogenmiddleware.Response{}, nil
})
var response *apiadapter.ProblemStatusCode
if !errors.As(err, &response) || response.Response.Code != test.code || called {
t.Fatalf("middleware error=%v response=%+v called=%v; want %s and no next call", err, response, called, test.code)
}
})
}
request := ownerCompanyMiddlewareRequest(t, uuid.New(), apiadapter.GetOrganizationOperation, uuid.New())
if _, err := NewCompanyContextMiddleware(companyAuthorizerFunc(func(context.Context, uuid.UUID, uuid.UUID) (organization.CompanyAccess, error) {
return organization.CompanyAccess{}, nil
}))(request, func(ogenmiddleware.Request) (ogenmiddleware.Response, error) {
t.Fatal("mismatched capability reached next")
return ogenmiddleware.Response{}, nil
}); err == nil {
t.Fatal("mismatched capability was accepted")
}
}
func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
const bundlePath = "../../../../../api/core/openapi.bundle.yml"
data, err := os.ReadFile(bundlePath)
if err != nil {
t.Fatalf("read OpenAPI bundle: %v", err)
}
var document struct {
Paths map[string]map[string]struct {
OperationID string `yaml:"operationId"`
} `yaml:"paths"`
}
if err := yaml.Unmarshal(data, &document); err != nil {
t.Fatalf("decode OpenAPI bundle: %v", err)
}
if len(ownerCompanyOperations) != 14 {
t.Fatalf("owner operation inventory has %d entries, want 14", len(ownerCompanyOperations))
}
candidateExceptions := map[string]string{
"HideOrganization": "/api/v1/me/privacy/hidden-organizations/{org_id}",
"UnhideOrganization": "/api/v1/me/privacy/hidden-organizations/{org_id}",
"RevokeMyOrganizationContactConsent": "/api/v1/me/consents/c4/organizations/{org_id}",
}
seen := make(map[string]string, len(ownerCompanyOperations))
seenExceptions := make(map[string]bool, len(candidateExceptions))
for path, methods := range document.Paths {
for _, operation := range methods {
if operation.OperationID == "" {
continue
}
_, ownerScoped := ownerCompanyOperations[operation.OperationID]
if ownerScoped {
if !strings.HasPrefix(path, "/api/v1/organizations/") || !strings.Contains(path, "{org_id}") {
t.Errorf("owner operation %s is at unexpected path %s", operation.OperationID, path)
}
if previous, exists := seen[operation.OperationID]; exists {
t.Errorf("owner operation %s appears at both %s and %s", operation.OperationID, previous, path)
}
seen[operation.OperationID] = path
continue
}
if !strings.Contains(path, "{org_id}") {
continue
}
expectedPath, candidateOperation := candidateExceptions[operation.OperationID]
if candidateOperation && expectedPath == path && strings.HasPrefix(path, "/api/v1/me/") {
seenExceptions[operation.OperationID] = true
continue
}
t.Errorf("unclassified organization-scoped operation %s at %s", operation.OperationID, path)
}
}
for operation := range ownerCompanyOperations {
if _, ok := seen[operation]; !ok {
t.Errorf("owner operation %s is absent from the organization-scoped API contract", operation)
}
}
for operation := range candidateExceptions {
if !seenExceptions[operation] {
t.Errorf("candidate exception %s is absent or moved without updating the explicit exception", operation)
}
}
}
type companyContextAuthenticator struct {
session identity.AuthenticatedSession
}
func (authenticator companyContextAuthenticator) Authenticate(context.Context, string) (identity.AuthenticatedSession, error) {
return authenticator.session, nil
}
func ownerCompanyMiddlewareRequest(t *testing.T, actorID uuid.UUID, operation apiadapter.OperationName, organizationID uuid.UUID) ogenmiddleware.Request {
t.Helper()
token, err := domain.NewSecretToken()
if err != nil {
t.Fatalf("NewSecretToken() error = %v", err)
}
verifiedAt := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
request := httptest.NewRequest(http.MethodGet, "https://api.example.test/api/v1/organizations/"+organizationID.String(), nil)
request.AddCookie(&http.Cookie{Name: httpmiddleware.SessionCookieName, Value: token.Reveal()})
metadata := &requestContextRecorder{}
httpmiddleware.SessionRequestMetadata()(metadata).ServeHTTP(httptest.NewRecorder(), request)
metadataContext := metadata.context
security := v1.NewSessionSecurity(companyContextAuthenticator{session: identity.AuthenticatedSession{
User: domain.User{ID: actorID, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verifiedAt},
SessionID: uuid.New(), CSRFToken: "company-context-test-csrf",
}}, "https://api.example.test")
ctx, err := security.HandleSessionCookie(metadataContext, operation, apiadapter.SessionCookie{APIKey: token.Reveal()})
if err != nil {
t.Fatalf("HandleSessionCookie() error = %v", err)
}
return ogenmiddleware.Request{
Context: ctx, OperationName: operation,
Params: ogenmiddleware.Parameters{{Name: "org_id", In: openapi.LocationPath}: organizationID},
}
}
@@ -39,6 +39,7 @@ func NewRouter(
collector httpmiddleware.RequestMetrics,
logger *slog.Logger,
trustedProxies []netip.Prefix,
operationMiddleware ...apiadapter.Middleware,
) (http.Handler, error) {
apiServer, err := apiadapter.NewServer(
apiHandler,
@@ -46,6 +47,7 @@ func NewRouter(
apiadapter.WithErrorHandler(problems.HandleServerError),
apiadapter.WithNotFound(problems.NotFound),
apiadapter.WithMethodNotAllowed(problems.MethodNotAllowed),
apiadapter.WithMiddleware(operationMiddleware...),
)
if err != nil {
return nil, fmt.Errorf("httpadapter.NewRouter - create API server: %w", err)
@@ -20,6 +20,7 @@ type Handler struct {
health *HealthHandler
identity *IdentityHandler
consent *ConsentHandler
profile *ProfileHandler
organization *OrganizationHandler
problems *problem.Responder
}
@@ -39,6 +40,11 @@ func WithConsent(consent *ConsentHandler) HandlerOption {
return func(handler *Handler) { handler.consent = consent }
}
// WithProfile serves the candidate's private profile.
func WithProfile(profile *ProfileHandler) HandlerOption {
return func(handler *Handler) { handler.profile = profile }
}
// WithOrganization serves company profiles and owner operations.
func WithOrganization(organization *OrganizationHandler) HandlerOption {
return func(handler *Handler) { handler.organization = organization }
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
@@ -19,6 +20,8 @@ import (
type OrganizationOperations interface {
Create(ctx context.Context, command organization.CreateCommand) (organization.CreateResult, error)
Get(ctx context.Context, actorID, organizationID uuid.UUID) (domain.Organization, error)
AuthorizeCompany(ctx context.Context, actorID, organizationID uuid.UUID) (organization.CompanyAccess, error)
ListMyOrganizations(ctx context.Context, command organization.OrganizationListCommand) (outbound.OrganizationPage, error)
Update(ctx context.Context, command organization.UpdateCommand) (domain.Organization, error)
}
@@ -45,6 +48,18 @@ func (handler *Handler) GetOrganization(
return handler.organization.GetOrganization(ctx, params)
}
// ListMyOrganizations delegates the session-scoped company directory to its
// business-area handler.
func (handler *Handler) ListMyOrganizations(
ctx context.Context,
params api.ListMyOrganizationsParams,
) (api.ListMyOrganizationsRes, error) {
if handler.organization == nil {
return handler.UnimplementedHandler.ListMyOrganizations(ctx, params)
}
return handler.organization.ListMyOrganizations(ctx, params)
}
// UpdateOrganization delegates company edits to their business-area handler.
func (handler *Handler) UpdateOrganization(
ctx context.Context,
@@ -68,6 +83,17 @@ func NewOrganizationHandler(operations OrganizationOperations, publicOrigin stri
return &OrganizationHandler{operations: operations, publicOrigin: publicOrigin}
}
// AuthorizeCompany delegates current owner membership checks to the use case.
func (handler *OrganizationHandler) AuthorizeCompany(
ctx context.Context,
actorID, organizationID uuid.UUID,
) (organization.CompanyAccess, error) {
if handler == nil || handler.operations == nil {
return organization.CompanyAccess{}, errors.New("OrganizationHandler.AuthorizeCompany - organization operations are not configured")
}
return handler.operations.AuthorizeCompany(ctx, actorID, organizationID)
}
func (handler *OrganizationHandler) CreateOrganization(
ctx context.Context,
request *api.OrganizationCreate,
@@ -146,6 +172,53 @@ func (handler *OrganizationHandler) UpdateOrganization(
}, nil
}
func (handler *OrganizationHandler) ListMyOrganizations(
ctx context.Context,
params api.ListMyOrganizationsParams,
) (api.ListMyOrganizationsRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListMyOrganizationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
command, paramErr := organizationListCommand(principal.UserID, params)
if paramErr != nil {
return organizationListInvalid(ctx, paramErr.pointer), nil
}
page, err := handler.operations.ListMyOrganizations(ctx, command)
if err != nil {
switch {
case errors.Is(err, organization.ErrForbidden):
return (*api.ListMyOrganizationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, organization.ErrEmailNotVerified):
return (*api.ListMyOrganizationsForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
case errors.Is(err, domain.ErrInvalidMembership):
return organizationListInvalid(ctx, "cursor"), nil
default:
return nil, err
}
}
items := make([]api.MyOrganization, 0, len(page.Items))
for _, item := range page.Items {
items = append(items, myOrganizationFromDomain(item))
}
var nextCursor api.NilString
nextCursor.SetToNull()
if page.HasMore && len(page.Items) > 0 {
cursor, err := encodeOrganizationCursor(principal.UserID, outbound.OrganizationPositionOf(page.Items[len(page.Items)-1]))
if err != nil {
return nil, fmt.Errorf("OrganizationHandler.ListMyOrganizations - encode cursor: %w", err)
}
nextCursor.SetTo(cursor)
}
return &api.MyOrganizationListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.MyOrganizationList{
Items: items,
Page: api.PageInfo{HasMore: page.HasMore, NextCursor: nextCursor},
},
}, nil
}
func createProfileInput(request *api.OrganizationCreate) domain.OrganizationProfileInput {
contacts := request.Contacts.Or(api.OrganizationContactChannels{})
description, _ := request.Description.Get()
@@ -321,7 +394,7 @@ func createOrganizationFailure(ctx context.Context, err error) (api.CreateOrgani
func getOrganizationFailure(ctx context.Context, err error) (api.GetOrganizationRes, error) {
switch {
case errors.Is(err, organization.ErrForbidden):
case errors.Is(err, organization.ErrForbidden), errors.Is(err, outbound.ErrOrganizationManagerRequired):
return (*api.GetOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, organization.ErrEmailNotVerified):
return (*api.GetOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
@@ -0,0 +1,105 @@
package v1
import (
"context"
"encoding/base64"
"encoding/binary"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/organization"
)
const (
organizationCursorVersion = 1
organizationCursorBytes = 45
defaultOrganizationLimit = 20
maxOrganizationCursorTime = uint64(1<<63 - 1)
)
type organizationListParamError struct {
pointer string
}
func organizationListCommand(actorID uuid.UUID, params api.ListMyOrganizationsParams) (organization.OrganizationListCommand, *organizationListParamError) {
limit, ok := params.Limit.Get()
if !ok {
limit = defaultOrganizationLimit
}
if limit < 1 || limit > outbound.MaxOrganizationPageSize {
return organization.OrganizationListCommand{}, &organizationListParamError{pointer: "limit"}
}
command := organization.OrganizationListCommand{ActorID: actorID, Limit: limit}
if cursor, ok := params.Cursor.Get(); ok {
position, err := decodeOrganizationCursor(cursor, actorID)
if err != nil {
return organization.OrganizationListCommand{}, &organizationListParamError{pointer: "cursor"}
}
command.After = &position
}
return command, nil
}
func encodeOrganizationCursor(actorID uuid.UUID, position outbound.OrganizationListPosition) (string, error) {
seconds := position.JoinedAt.Unix()
nanos := position.JoinedAt.Nanosecond()
if actorID == uuid.Nil || position.OrganizationID == uuid.Nil || position.JoinedAt.IsZero() || seconds < 0 || nanos < 0 || nanos >= 1_000_000_000 {
return "", errors.New("organization cursor requires an actor and a valid page position")
}
var value [organizationCursorBytes]byte
value[0] = organizationCursorVersion
copy(value[1:17], actorID[:])
binary.BigEndian.PutUint64(value[17:25], uint64(seconds))
binary.BigEndian.PutUint32(value[25:29], uint32(nanos))
copy(value[29:45], position.OrganizationID[:])
return base64.RawURLEncoding.EncodeToString(value[:]), nil
}
func decodeOrganizationCursor(cursor string, actorID uuid.UUID) (outbound.OrganizationListPosition, error) {
value, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil || len(value) != organizationCursorBytes || actorID == uuid.Nil ||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != organizationCursorVersion ||
uuid.UUID(value[1:17]) != actorID {
return outbound.OrganizationListPosition{}, errors.New("organization cursor is invalid")
}
nanos := binary.BigEndian.Uint32(value[25:29])
organizationID := uuid.UUID(value[29:45])
if nanos >= 1_000_000_000 || organizationID == uuid.Nil {
return outbound.OrganizationListPosition{}, errors.New("organization cursor position is invalid")
}
seconds := binary.BigEndian.Uint64(value[17:25])
if seconds > maxOrganizationCursorTime {
return outbound.OrganizationListPosition{}, errors.New("organization cursor timestamp is invalid")
}
joinedAt := time.Unix(int64(seconds), int64(nanos)).UTC()
if joinedAt.IsZero() {
return outbound.OrganizationListPosition{}, errors.New("organization cursor timestamp is invalid")
}
return outbound.OrganizationListPosition{JoinedAt: joinedAt, OrganizationID: organizationID}, nil
}
func organizationListInvalid(ctx context.Context, pointer string) *api.ListMyOrganizationsBadRequest {
return (*api.ListMyOrganizationsBadRequest)(
&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response,
)
}
func myOrganizationFromDomain(item outbound.MemberOrganization) api.MyOrganization {
organization := item.Organization
membership := item.Membership
return api.MyOrganization{
Organization: api.OrganizationSummary{
ID: organization.ID(), Name: api.OrganizationName(organization.Name()),
VerificationLevel: api.OrganizationVerificationLevel(organization.VerificationLevel()),
},
Membership: api.OrganizationMembership{
OrganizationID: membership.OrganizationID(), Role: api.OrganizationRole(membership.Role()),
State: api.MembershipState(membership.State()), JoinedAt: api.Timestamp(membership.CreatedAt()),
},
}
}
@@ -0,0 +1,76 @@
package v1
import (
"encoding/base64"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/port/outbound"
)
func TestOrganizationCursorRoundTripAndPrincipalBinding(t *testing.T) {
actorID := uuid.New()
position := outbound.OrganizationListPosition{
JoinedAt: time.Date(2026, 8, 15, 10, 30, 0, 123456000, time.UTC), OrganizationID: uuid.New(),
}
cursor, err := encodeOrganizationCursor(actorID, position)
if err != nil {
t.Fatalf("encodeOrganizationCursor() error = %v", err)
}
decoded, err := decodeOrganizationCursor(cursor, actorID)
if err != nil || decoded != position {
t.Fatalf("decodeOrganizationCursor() = %+v, %v; want %+v", decoded, err, position)
}
if _, err := decodeOrganizationCursor(cursor, uuid.New()); err == nil {
t.Fatal("decodeOrganizationCursor accepted a cursor from another principal")
}
if _, err := decodeOrganizationCursor(cursor+"A", actorID); err == nil {
t.Fatal("decodeOrganizationCursor accepted a non-canonical cursor")
}
encoded, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
t.Fatalf("decode cursor bytes: %v", err)
}
encoded[17] = 0x80
if _, err := decodeOrganizationCursor(base64.RawURLEncoding.EncodeToString(encoded), actorID); err == nil {
t.Fatal("decodeOrganizationCursor accepted a timestamp outside the int64 range")
}
if _, err := encodeOrganizationCursor(actorID, outbound.OrganizationListPosition{
JoinedAt: time.Unix(-1, 0), OrganizationID: position.OrganizationID,
}); err == nil {
t.Fatal("encodeOrganizationCursor accepted a negative timestamp")
}
}
func TestOrganizationListCommandValidatesPagination(t *testing.T) {
actorID := uuid.New()
for _, test := range []struct {
name string
params api.ListMyOrganizationsParams
pointer string
}{
{name: "default limit", params: api.ListMyOrganizationsParams{}},
{name: "smallest limit", params: api.ListMyOrganizationsParams{Limit: api.NewOptInt32(1)}},
{name: "largest limit", params: api.ListMyOrganizationsParams{Limit: api.NewOptInt32(100)}},
{name: "zero limit", params: api.ListMyOrganizationsParams{Limit: api.NewOptInt32(0)}, pointer: "limit"},
{name: "oversized limit", params: api.ListMyOrganizationsParams{Limit: api.NewOptInt32(101)}, pointer: "limit"},
{name: "malformed cursor", params: api.ListMyOrganizationsParams{Limit: api.NewOptInt32(20), Cursor: api.NewOptString(strings.Repeat("x", 512))}, pointer: "cursor"},
} {
t.Run(test.name, func(t *testing.T) {
command, paramErr := organizationListCommand(actorID, test.params)
if test.pointer != "" {
if paramErr == nil || paramErr.pointer != test.pointer {
t.Fatalf("organizationListCommand() error = %+v, want pointer %q", paramErr, test.pointer)
}
return
}
if paramErr != nil || command.ActorID != actorID || command.Limit < 1 || command.Limit > 100 {
t.Fatalf("organizationListCommand() = %+v, %+v; want bounded actor-scoped command", command, paramErr)
}
})
}
}
@@ -0,0 +1,415 @@
package v1
import (
"context"
"errors"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/profile"
)
// ProfileOperations reads and version-saves the authenticated candidate's
// private manual profile.
type ProfileOperations interface {
GetMyProfile(ctx context.Context, userID uuid.UUID) (domain.CandidateProfile, error)
SaveMyProfile(ctx context.Context, userID uuid.UUID, expectedVersion int64, input domain.CandidateProfileInput) (domain.CandidateProfile, error)
}
// ProfileHandler serves the candidate's own profile operations.
type ProfileHandler struct {
operations ProfileOperations
}
func NewProfileHandler(operations ProfileOperations) *ProfileHandler {
if operations == nil {
panic("v1.NewProfileHandler - profile operations must not be nil")
}
return &ProfileHandler{operations: operations}
}
func (handler *Handler) GetMyProfile(ctx context.Context) (api.GetMyProfileRes, error) {
if handler.profile == nil {
return handler.UnimplementedHandler.GetMyProfile(ctx)
}
return handler.profile.GetMyProfile(ctx)
}
func (handler *Handler) SaveMyProfile(ctx context.Context, request *api.CandidateProfileUpdate) (api.SaveMyProfileRes, error) {
if handler.profile == nil {
return handler.UnimplementedHandler.SaveMyProfile(ctx, request)
}
return handler.profile.SaveMyProfile(ctx, request)
}
func (handler *ProfileHandler) GetMyProfile(ctx context.Context) (api.GetMyProfileRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetMyProfileUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
profile, err := handler.operations.GetMyProfile(ctx, principal.UserID)
if err != nil {
return profileReadFailure(ctx, err)
}
return &api.CandidateProfileHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: candidateProfileResponse(profile),
}, nil
}
func (handler *ProfileHandler) SaveMyProfile(ctx context.Context, request *api.CandidateProfileUpdate) (api.SaveMyProfileRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.SaveMyProfileUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return (*api.SaveMyProfileBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
profile, err := handler.operations.SaveMyProfile(ctx, principal.UserID, int64(request.ExpectedVersion), candidateProfileInput(request))
if err != nil {
return profileSaveFailure(ctx, err)
}
return &api.CandidateProfileHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: candidateProfileResponse(profile),
}, nil
}
func profileReadFailure(ctx context.Context, err error) (api.GetMyProfileRes, error) {
if errors.Is(err, profile.ErrForbidden) {
return (*api.GetMyProfileForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
if errors.Is(err, profile.ErrEmailNotVerified) {
return (*api.GetMyProfileForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
if errors.Is(err, outbound.ErrUserNotFound) {
return (*api.GetMyProfileUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
return nil, err
}
func profileSaveFailure(ctx context.Context, err error) (api.SaveMyProfileRes, error) {
switch {
case errors.Is(err, domain.ErrCandidateProfileVersionConflict), errors.Is(err, outbound.ErrCandidateProfileVersionConflict):
return (*api.SaveMyProfilePreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case errors.Is(err, profile.ErrForbidden), errors.Is(err, profile.ErrEmailNotVerified):
return (*api.SaveMyProfileForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrUserNotFound):
return (*api.SaveMyProfileUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
case errors.Is(err, domain.ErrInvalidCandidateProfile):
field, ok := errors.AsType[*domain.CandidateProfileFieldError](err)
if !ok {
return (*api.SaveMyProfileBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
return (*api.SaveMyProfileBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, field.Pointer).Response), nil
default:
return nil, err
}
}
func candidateProfileInput(request *api.CandidateProfileUpdate) domain.CandidateProfileInput {
input := domain.CandidateProfileInput{
Stack: make([]domain.ProfileClaimInput[string], 0, len(request.Stack)),
Roles: make([]domain.ProfileClaimInput[domain.ProfileRole], 0, len(request.Roles)),
Experience: make([]domain.ProfileClaimInput[domain.ProfileExperience], 0, len(request.Experience)),
ParallelPeriodAcknowledgements: make([]domain.ProfileParallelPeriodAcknowledgement, 0, len(request.ConfirmedParallelPeriods)),
SoftSkills: make([]domain.ProfileClaimInput[string], 0, len(request.SoftSkills)),
}
if value, ok := request.FullName.Get(); ok {
input.FullName = profileStringInput(string(value.Value), value.Status)
}
if value, ok := request.Contacts.Email.Get(); ok {
input.Email = profileStringInput(string(value.Value), value.Status)
}
if value, ok := request.Contacts.Phone.Get(); ok {
input.Phone = profileStringInput(string(value.Value), value.Status)
}
if value, ok := request.Contacts.Telegram.Get(); ok {
input.Telegram = profileStringInput(string(value.Value), value.Status)
}
for _, item := range request.Stack {
input.Stack = append(input.Stack, domain.ProfileClaimInput[string]{Value: string(item.Tag), Status: domain.ProfileClaimStatus(item.Status)})
}
for _, item := range request.Roles {
grade, _ := item.SelfAssessedGrade.Get()
input.Roles = append(input.Roles, domain.ProfileClaimInput[domain.ProfileRole]{
Value: domain.ProfileRole{Specialization: domain.SpecializationCode(item.Specialization), SelfAssessedGrade: domain.GradeCode(grade)},
Status: domain.ProfileClaimStatus(item.Status),
})
}
for _, item := range request.Experience {
employer, _ := item.EmployerName.Get()
endedOn := profileYearMonth(item.EndedOn)
summary, _ := item.Summary.Get()
input.Experience = append(input.Experience, domain.ProfileClaimInput[domain.ProfileExperience]{
Value: domain.ProfileExperience{
EmployerName: string(employer), Specialization: domain.SpecializationCode(item.Specialization),
StartedOn: string(item.StartedOn), EndedOn: endedOn, Summary: string(summary),
},
Status: domain.ProfileClaimStatus(item.Status),
})
}
for _, item := range request.ConfirmedParallelPeriods {
input.ParallelPeriodAcknowledgements = append(input.ParallelPeriodAcknowledgements, domain.ProfileParallelPeriodAcknowledgement{
FirstIndex: item.FirstIndex, SecondIndex: item.SecondIndex,
FirstPeriod: domain.ProfileExperiencePeriod{
StartedOn: string(item.FirstPeriod.StartedOn), EndedOn: profileYearMonth(item.FirstPeriod.EndedOn),
},
SecondPeriod: domain.ProfileExperiencePeriod{
StartedOn: string(item.SecondPeriod.StartedOn), EndedOn: profileYearMonth(item.SecondPeriod.EndedOn),
},
})
}
for _, item := range request.SoftSkills {
input.SoftSkills = append(input.SoftSkills, domain.ProfileClaimInput[string]{Value: string(item.Skill), Status: domain.ProfileClaimStatus(item.Status)})
}
if value, ok := request.Terms.Location.Get(); ok {
input.Location = profileStringInput(string(value.Value), value.Status)
}
if value, ok := request.Terms.Relocation.Get(); ok {
input.Relocation = &domain.ProfileClaimInput[bool]{Value: value.Value, Status: domain.ProfileClaimStatus(value.Status)}
}
if value, ok := request.Terms.SalaryMinimum.Get(); ok {
input.SalaryMinimum = &domain.ProfileClaimInput[domain.ProfileSalaryMinimum]{
Value: domain.ProfileSalaryMinimum{Amount: int64(value.Value.Amount), TaxBasis: domain.ProfileTaxBasis(value.Value.TaxBasis)},
Status: domain.ProfileClaimStatus(value.Status),
}
}
return input
}
func profileStringInput(value string, status api.ProfileItemStatus) *domain.ProfileClaimInput[string] {
return &domain.ProfileClaimInput[string]{Value: value, Status: domain.ProfileClaimStatus(status)}
}
func profileYearMonth(value api.NilProfileYearMonth) string {
month, ok := value.Get()
if !ok {
return ""
}
return string(month)
}
func candidateProfileResponse(profile domain.CandidateProfile) api.CandidateProfile {
content := profile.Content()
response := api.CandidateProfile{
Version: api.ProfileVersion(profile.Version()),
ExperienceOverlaps: make([]api.ProfileExperienceOverlap, 0),
Stack: make([]api.ProfileStackItem, 0),
Roles: make([]api.ProfileRoleItem, 0),
Experience: make([]api.ProfileExperienceItem, 0),
SoftSkills: make([]api.ProfileSoftSkillItem, 0),
ConfirmedCategories: make([]api.ProfileConfirmedCategory, 0),
}
if name, ok := content.FullName(); ok {
response.FullName = profileFullNameClaim(name)
} else {
response.FullName = profileFullNameClaim(domain.ProfileClaim[string]{}, false)
}
contacts := api.ProfileContacts{}
if email, ok := content.Email(); ok {
contacts.Email = profileEmailClaim(email)
} else {
contacts.Email = profileEmailClaim(domain.ProfileClaim[string]{}, false)
}
if phone, ok := content.Phone(); ok {
contacts.Phone = profilePhoneClaim(phone)
} else {
contacts.Phone = profilePhoneClaim(domain.ProfileClaim[string]{}, false)
}
if telegram, ok := content.Telegram(); ok {
contacts.Telegram = profileTelegramClaim(telegram)
} else {
contacts.Telegram = profileTelegramClaim(domain.ProfileClaim[string]{}, false)
}
response.Contacts = contacts
for _, item := range content.Stack() {
response.Stack = append(response.Stack, api.ProfileStackItem{Tag: api.StackTag(item.Value()), Status: api.ProfileItemStatus(item.Status()), Source: profileClaimSourceResponse(item.Source())})
}
for _, item := range content.Roles() {
grade := api.NilGradeCode{}
if item.Value().SelfAssessedGrade == "" {
grade.SetToNull()
} else {
grade.SetTo(api.GradeCode(item.Value().SelfAssessedGrade))
}
response.Roles = append(response.Roles, api.ProfileRoleItem{
Specialization: api.SpecializationCode(item.Value().Specialization), SelfAssessedGrade: grade,
Status: api.ProfileItemStatus(item.Status()), Source: profileClaimSourceResponse(item.Source()),
})
}
for _, item := range content.Experience() {
value := item.Value()
employer := api.NilProfileEmployerName{}
if value.EmployerName == "" {
employer.SetToNull()
} else {
employer.SetTo(api.ProfileEmployerName(value.EmployerName))
}
endedOn := api.NilProfileYearMonth{}
if value.EndedOn == "" {
endedOn.SetToNull()
} else {
endedOn.SetTo(api.ProfileYearMonth(value.EndedOn))
}
summary := api.NilProfileExperienceSummary{}
if value.Summary == "" {
summary.SetToNull()
} else {
summary.SetTo(api.ProfileExperienceSummary(value.Summary))
}
response.Experience = append(response.Experience, api.ProfileExperienceItem{
EmployerName: employer, Specialization: api.SpecializationCode(value.Specialization), StartedOn: api.ProfileYearMonth(value.StartedOn),
EndedOn: endedOn, Summary: summary, Status: api.ProfileItemStatus(item.Status()), Source: profileClaimSourceResponse(item.Source()),
})
}
for _, item := range content.ExperienceOverlaps() {
response.ExperienceOverlaps = append(response.ExperienceOverlaps, api.ProfileExperienceOverlap{
FirstIndex: item.FirstIndex, SecondIndex: item.SecondIndex, Status: api.ProfileExperienceOverlapStatus(item.Status),
})
}
for _, item := range content.SoftSkills() {
response.SoftSkills = append(response.SoftSkills, api.ProfileSoftSkillItem{
Skill: api.ProfileSoftSkill(item.Value()), Status: api.ProfileItemStatus(item.Status()), Source: profileClaimSourceResponse(item.Source()),
})
}
response.Terms = candidateProfileTerms(content)
updatedAt := api.NilTimestamp{}
if profile.UpdatedAt().IsZero() {
updatedAt.SetToNull()
} else {
updatedAt.SetTo(api.Timestamp(profile.UpdatedAt()))
}
response.UpdatedAt = updatedAt
return response
}
func candidateProfileTerms(content domain.CandidateProfileContent) api.ProfileTerms {
terms := api.ProfileTerms{}
if location, ok := content.Location(); ok {
terms.Location = api.ProfileLocationClaim{
Status: api.ProfileClaimStatus(location.Status()), Value: api.NewNilProfileLocationName(api.ProfileLocationName(location.Value())),
Source: api.NewNilProfileClaimSource(profileClaimSourceResponse(location.Source())),
}
} else {
terms.Location = unknownProfileLocationClaim()
}
if relocation, ok := content.Relocation(); ok {
terms.Relocation = api.ProfileRelocationClaim{
Status: api.ProfileClaimStatus(relocation.Status()), Value: api.NewNilBool(relocation.Value()),
Source: api.NewNilProfileClaimSource(profileClaimSourceResponse(relocation.Source())),
}
} else {
terms.Relocation = unknownProfileRelocationClaim()
}
if salary, ok := content.SalaryMinimum(); ok {
terms.SalaryMinimum = api.ProfileSalaryMinimumClaim{
Status: api.ProfileClaimStatus(salary.Status()),
Value: api.NewNilProfileSalaryMinimum(api.ProfileSalaryMinimum{
Amount: api.RubAmount(salary.Value().Amount), Currency: api.CurrencyCodeRUB, Period: api.SalaryPeriodMonth,
TaxBasis: api.SalaryTaxBasis(salary.Value().TaxBasis),
}),
Source: api.NewNilProfileClaimSource(profileClaimSourceResponse(salary.Source())),
}
} else {
terms.SalaryMinimum = unknownProfileSalaryClaim()
}
return terms
}
func profileFullNameClaim(claim domain.ProfileClaim[string], exists ...bool) api.ProfileFullNameClaim {
if len(exists) > 0 && !exists[0] {
value := api.NilContactFullName{}
value.SetToNull()
source := api.NilProfileClaimSource{}
source.SetToNull()
return api.ProfileFullNameClaim{Status: api.ProfileClaimStatusUnknown, Value: value, Source: source}
}
return api.ProfileFullNameClaim{Status: api.ProfileClaimStatus(claim.Status()), Value: api.NewNilContactFullName(api.ContactFullName(claim.Value())), Source: api.NewNilProfileClaimSource(profileClaimSourceResponse(claim.Source()))}
}
func profileEmailClaim(claim domain.ProfileClaim[string], exists ...bool) api.ProfileEmailClaim {
if len(exists) > 0 && !exists[0] {
value := api.NilEmailAddress{}
value.SetToNull()
source := api.NilProfileClaimSource{}
source.SetToNull()
return api.ProfileEmailClaim{Status: api.ProfileClaimStatusUnknown, Value: value, Source: source}
}
return api.ProfileEmailClaim{Status: api.ProfileClaimStatus(claim.Status()), Value: api.NewNilEmailAddress(api.EmailAddress(claim.Value())), Source: api.NewNilProfileClaimSource(profileClaimSourceResponse(claim.Source()))}
}
func profilePhoneClaim(claim domain.ProfileClaim[string], exists ...bool) api.ProfilePhoneClaim {
if len(exists) > 0 && !exists[0] {
value := api.NilContactPhoneNumber{}
value.SetToNull()
source := api.NilProfileClaimSource{}
source.SetToNull()
return api.ProfilePhoneClaim{Status: api.ProfileClaimStatusUnknown, Value: value, Source: source}
}
return api.ProfilePhoneClaim{Status: api.ProfileClaimStatus(claim.Status()), Value: api.NewNilContactPhoneNumber(api.ContactPhoneNumber(claim.Value())), Source: api.NewNilProfileClaimSource(profileClaimSourceResponse(claim.Source()))}
}
func profileTelegramClaim(claim domain.ProfileClaim[string], exists ...bool) api.ProfileTelegramClaim {
if len(exists) > 0 && !exists[0] {
value := api.NilContactTelegramUsername{}
value.SetToNull()
source := api.NilProfileClaimSource{}
source.SetToNull()
return api.ProfileTelegramClaim{Status: api.ProfileClaimStatusUnknown, Value: value, Source: source}
}
return api.ProfileTelegramClaim{Status: api.ProfileClaimStatus(claim.Status()), Value: api.NewNilContactTelegramUsername(api.ContactTelegramUsername(claim.Value())), Source: api.NewNilProfileClaimSource(profileClaimSourceResponse(claim.Source()))}
}
func unknownProfileLocationClaim() api.ProfileLocationClaim {
value := api.NilProfileLocationName{}
value.SetToNull()
source := api.NilProfileClaimSource{}
source.SetToNull()
return api.ProfileLocationClaim{Status: api.ProfileClaimStatusUnknown, Value: value, Source: source}
}
func unknownProfileRelocationClaim() api.ProfileRelocationClaim {
value := api.NilBool{}
value.SetToNull()
source := api.NilProfileClaimSource{}
source.SetToNull()
return api.ProfileRelocationClaim{Status: api.ProfileClaimStatusUnknown, Value: value, Source: source}
}
func unknownProfileSalaryClaim() api.ProfileSalaryMinimumClaim {
value := api.NilProfileSalaryMinimum{}
value.SetToNull()
source := api.NilProfileClaimSource{}
source.SetToNull()
return api.ProfileSalaryMinimumClaim{Status: api.ProfileClaimStatusUnknown, Value: value, Source: source}
}
func profileClaimSourceResponse(source domain.ProfileClaimSource) api.ProfileClaimSource {
quote := api.NilProfileClaimQuote{}
if source.Quote() == "" {
quote.SetToNull()
} else {
quote.SetTo(api.ProfileClaimQuote(source.Quote()))
}
extractionVersion := api.NilNeedVersionLabel{}
if source.ExtractionVersion() == "" {
extractionVersion.SetToNull()
} else {
extractionVersion.SetTo(api.NeedVersionLabel(source.ExtractionVersion()))
}
confirmedAt := api.NilTimestamp{}
if source.ConfirmedAt().IsZero() {
confirmedAt.SetToNull()
} else {
confirmedAt.SetTo(api.Timestamp(source.ConfirmedAt()))
}
return api.ProfileClaimSource{
Origin: api.ProfileClaimOrigin(source.Origin()), TrustLevel: api.ProfileClaimTrustLevel(domain.ProfileClaimTrustLevel),
Quote: quote, ExtractionVersion: extractionVersion, ConfirmedAt: confirmedAt,
}
}
@@ -0,0 +1,301 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"slices"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const maxCandidateProfileHistorySnapshotBytes = 262144
var _ outbound.CandidateProfileRepositories = (*UnitOfWork)(nil)
func (unit *UnitOfWork) CandidateProfiles() outbound.CandidateProfileRepository {
return candidateProfileRepository{queries: unit.queries}
}
type candidateProfileRepository struct {
queries *sqlc.Queries
}
type candidateProfileHistoryClaim struct {
Kind string `json:"kind"`
Ordinal int `json:"ordinal"`
Value json.RawMessage `json:"value"`
Status string `json:"status"`
Origin string `json:"origin"`
TrustLevel int `json:"trust_level"`
Quote *string `json:"quote,omitempty"`
ExtractionVersion *string `json:"extraction_version,omitempty"`
ConfirmedAt *time.Time `json:"confirmed_at,omitempty"`
}
type candidateProfileHistorySnapshot struct {
Version int64 `json:"version"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Claims []candidateProfileHistoryClaim `json:"claims"`
ParallelPeriodAcknowledgements []domain.ProfileParallelPeriodAcknowledgement `json:"parallel_period_acknowledgements"`
}
func (repository candidateProfileRepository) Get(ctx context.Context, userID uuid.UUID) (domain.CandidateProfile, error) {
const location = "candidateProfileRepository.Get"
if userID == uuid.Nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile)
}
rows, err := repository.queries.ReadCandidateProfile(ctx, pgUUID(userID))
if err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - select profile: %w", location, mapCandidateProfileError(err))
}
if len(rows) == 0 {
profile, err := domain.EmptyCandidateProfile(userID)
if err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - create empty profile: %w", location, err)
}
return profile, nil
}
stored := domain.StoredCandidateProfile{
UserID: userID, Version: rows[0].Version,
CreatedAt: rows[0].CreatedAt.Time, UpdatedAt: rows[0].UpdatedAt.Time,
}
if err := json.Unmarshal([]byte(rows[0].ParallelPeriodAcknowledgements), &stored.ParallelPeriodAcknowledgements); err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - decode stored period confirmations: %w", location, domain.ErrInvalidCandidateProfile)
}
for _, row := range rows {
if !row.Kind.Valid {
continue
}
stored.Claims = append(stored.Claims, domain.StoredProfileClaim{
Kind: row.Kind.String, Ordinal: int(row.Ordinal.Int16), Value: row.Value,
Status: row.Status.String, Origin: row.Origin.String, TrustLevel: int(row.TrustLevel.Int16),
Quote: row.Quote.String, ExtractionVersion: row.ExtractionVersion.String,
ConfirmedAt: row.ConfirmedAt.Time,
})
}
profile, err := domain.RestoreCandidateProfile(stored)
if err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - restore profile: %w", location, err)
}
return profile, nil
}
func (repository candidateProfileRepository) Save(
ctx context.Context,
expectedVersion int64,
profile domain.CandidateProfile,
) (domain.CandidateProfile, error) {
const location = "candidateProfileRepository.Save"
if profile.IsZero() || expectedVersion < 0 || profile.Version() != expectedVersion || profile.UpdatedAt().IsZero() {
return domain.CandidateProfile{}, fmt.Errorf("%s - profile and expected version are inconsistent: %w", location, domain.ErrInvalidCandidateProfile)
}
claims, err := profile.Content().StoredClaims()
if err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - encode profile claims: %w", location, err)
}
snapshot, err := candidateProfileSnapshot(profile, claims)
if err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - encode profile history: %w", location, err)
}
if len(snapshot) > maxCandidateProfileHistorySnapshotBytes {
return domain.CandidateProfile{}, fmt.Errorf("%s - history snapshot exceeds its storage bound: %w", location, outbound.ErrCandidateProfileHistoryTooLarge)
}
userID := pgUUID(profile.UserID())
stored, err := repository.advanceProfileVersion(ctx, userID, expectedVersion, profile.UpdatedAt())
if err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - advance profile version: %w", location, mapCandidateProfileError(err))
}
if err := repository.replaceProfileClaims(ctx, userID, claims); err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - replace claims: %w", location, err)
}
if err := repository.replaceProfilePeriodConfirmations(ctx, userID, profile.Content().ParallelPeriodAcknowledgements()); err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - replace period confirmations: %w", location, err)
}
if err := repository.queries.AppendCandidateProfileHistory(ctx, sqlc.AppendCandidateProfileHistoryParams{
UserID: userID, Version: stored.Version, ChangedAt: stored.UpdatedAt, Snapshot: snapshot,
}); err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - append profile history: %w", location, mapCandidateProfileError(err))
}
return domain.RestoreCandidateProfile(domain.StoredCandidateProfile{
UserID: profile.UserID(), Version: stored.Version, CreatedAt: stored.CreatedAt.Time, UpdatedAt: stored.UpdatedAt.Time,
Claims: claims, ParallelPeriodAcknowledgements: profile.Content().ParallelPeriodAcknowledgements(),
})
}
func (repository candidateProfileRepository) advanceProfileVersion(
ctx context.Context,
userID pgtype.UUID,
expectedVersion int64,
at time.Time,
) (sqlc.CandidateProfile, error) {
var stored sqlc.CandidateProfile
var err error
if expectedVersion == 0 {
stored, err = repository.queries.InsertCandidateProfile(ctx, sqlc.InsertCandidateProfileParams{
UserID: userID, At: pgTime(at),
})
} else {
stored, err = repository.queries.AdvanceCandidateProfileVersion(ctx, sqlc.AdvanceCandidateProfileVersionParams{
UserID: userID, ExpectedVersion: expectedVersion, At: pgTime(at),
})
}
if errors.Is(err, pgx.ErrNoRows) {
return sqlc.CandidateProfile{}, outbound.ErrCandidateProfileVersionConflict
}
if err != nil {
return sqlc.CandidateProfile{}, mapCandidateProfileError(err)
}
return stored, nil
}
func (repository candidateProfileRepository) replaceProfileClaims(
ctx context.Context,
userID pgtype.UUID,
claims []domain.StoredProfileClaim,
) error {
if err := repository.queries.DeleteCandidateProfileClaims(ctx, userID); err != nil {
return mapCandidateProfileError(err)
}
for _, claim := range claims {
ordinal, err := candidateProfileOrdinal(claim.Ordinal)
if err != nil {
return err
}
var confirmedAt *time.Time
if !claim.ConfirmedAt.IsZero() {
confirmedAt = &claim.ConfirmedAt
}
if err := repository.queries.InsertCandidateProfileClaim(ctx, sqlc.InsertCandidateProfileClaimParams{
UserID: userID, Kind: claim.Kind, Ordinal: ordinal, Value: claim.Value,
Status: claim.Status, Origin: claim.Origin, Quote: pgOptionalText(claim.Quote),
ExtractionVersion: pgOptionalText(claim.ExtractionVersion), ConfirmedAt: pgOptionalTime(confirmedAt),
}); err != nil {
return mapCandidateProfileError(err)
}
}
return nil
}
func (repository candidateProfileRepository) replaceProfilePeriodConfirmations(
ctx context.Context,
userID pgtype.UUID,
confirmations []domain.ProfileParallelPeriodAcknowledgement,
) error {
if err := repository.queries.DeleteCandidateProfileOverlapConfirmations(ctx, userID); err != nil {
return mapCandidateProfileError(err)
}
for _, confirmation := range confirmations {
if confirmation.FirstIndex >= confirmation.SecondIndex {
return fmt.Errorf("postgres.replaceProfilePeriodConfirmations - pair indices are invalid: %w", domain.ErrInvalidCandidateProfile)
}
firstIndex, err := candidateProfilePeriodIndex(confirmation.FirstIndex)
if err != nil {
return err
}
secondIndex, err := candidateProfilePeriodIndex(confirmation.SecondIndex)
if err != nil {
return err
}
if err := repository.queries.InsertCandidateProfileOverlapConfirmation(ctx, sqlc.InsertCandidateProfileOverlapConfirmationParams{
UserID: userID, FirstIndex: firstIndex, SecondIndex: secondIndex,
FirstStartedOn: confirmation.FirstPeriod.StartedOn, FirstEndedOn: pgOptionalText(confirmation.FirstPeriod.EndedOn),
SecondStartedOn: confirmation.SecondPeriod.StartedOn, SecondEndedOn: pgOptionalText(confirmation.SecondPeriod.EndedOn),
}); err != nil {
return mapCandidateProfileError(err)
}
}
return nil
}
func candidateProfileOrdinal(value int) (int16, error) {
if value < 0 || value > math.MaxInt16 {
return 0, fmt.Errorf("postgres.candidateProfileOrdinal - ordinal is outside the storage range: %w", domain.ErrInvalidCandidateProfile)
}
return int16(value), nil
}
func candidateProfilePeriodIndex(value int) (int16, error) {
if value < 0 || value > 19 || value > math.MaxInt16 {
return 0, fmt.Errorf("postgres.candidateProfilePeriodIndex - index is outside the storage range: %w", domain.ErrInvalidCandidateProfile)
}
return int16(value), nil
}
func candidateProfileSnapshot(profile domain.CandidateProfile, claims []domain.StoredProfileClaim) ([]byte, error) {
encodedClaims := make([]candidateProfileHistoryClaim, 0, len(claims))
for _, claim := range claims {
item := candidateProfileHistoryClaim{
Kind: claim.Kind, Ordinal: claim.Ordinal, Value: json.RawMessage(claim.Value),
Status: claim.Status, Origin: claim.Origin, TrustLevel: claim.TrustLevel,
}
if claim.Quote != "" {
item.Quote = &claim.Quote
}
if claim.ExtractionVersion != "" {
item.ExtractionVersion = &claim.ExtractionVersion
}
if !claim.ConfirmedAt.IsZero() {
confirmedAt := claim.ConfirmedAt
item.ConfirmedAt = &confirmedAt
}
encodedClaims = append(encodedClaims, item)
}
return json.Marshal(candidateProfileHistorySnapshot{
Version: profile.Version() + 1, CreatedAt: profile.CreatedAt().UTC().Truncate(time.Microsecond),
UpdatedAt: profile.UpdatedAt().UTC().Truncate(time.Microsecond),
Claims: encodedClaims, ParallelPeriodAcknowledgements: profile.Content().ParallelPeriodAcknowledgements(),
})
}
func (repository candidateProfileRepository) AdvanceOnboarding(ctx context.Context, userID uuid.UUID, at time.Time) error {
const location = "candidateProfileRepository.AdvanceOnboarding"
if userID == uuid.Nil || at.IsZero() {
return fmt.Errorf("%s - user ID and time must be set: %w", location, domain.ErrInvalidCandidateProfile)
}
if err := repository.queries.AdvanceCandidateOnboardingAfterProfile(ctx, sqlc.AdvanceCandidateOnboardingAfterProfileParams{
UserID: pgUUID(userID), At: pgTime(at),
}); err != nil {
return fmt.Errorf("%s - advance candidate step: %w", location, mapCandidateProfileError(err))
}
return nil
}
func mapCandidateProfileError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
switch {
case pgError.Code == foreignKeyViolationCode && slices.Contains([]string{
"candidate_profiles_user_id_fkey", "candidate_profile_claims_user_id_fkey",
"candidate_profile_overlap_confirmations_profile_fkey", "candidate_profile_history_profile_fkey",
}, pgError.ConstraintName):
return fmt.Errorf("postgres.mapCandidateProfileError - violate constraint %s: %w", pgError.ConstraintName, outbound.ErrUserNotFound)
case pgError.Code == checkViolationCode && pgError.ConstraintName == "candidate_profile_history_snapshot_bounded":
return outbound.ErrCandidateProfileHistoryTooLarge
case pgError.Code == checkViolationCode && slices.Contains([]string{
"candidate_profiles_version_positive", "candidate_profile_claims_kind_ordinal",
"candidate_profile_claims_status_known", "candidate_profile_claims_origin_known",
"candidate_profile_claims_trust_level_zero", "candidate_profile_claims_confirmation",
"candidate_profile_claims_origin_provenance", "candidate_profile_claims_quote_format",
"candidate_profile_claims_extraction_version_format", "candidate_profile_overlap_confirmations_indices",
"candidate_profile_overlap_confirmations_months",
}, pgError.ConstraintName):
return fmt.Errorf("postgres.mapCandidateProfileError - violate constraint %s: %w", pgError.ConstraintName, domain.ErrInvalidCandidateProfile)
default:
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
}
@@ -11,6 +11,31 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const advanceCandidateOnboardingAfterProfile = `-- name: AdvanceCandidateOnboardingAfterProfile :exec
UPDATE users
SET
onboarding_step = 'candidate_questionnaire',
version = users.version + 1,
updated_at = GREATEST(users.updated_at, $1::timestamptz)
WHERE
users.id = $2
AND users.scenario = 'candidate'
AND users.email_verified_at IS NOT NULL
AND users.onboarding_step = 'candidate_profile'
`
type AdvanceCandidateOnboardingAfterProfileParams struct {
At pgtype.Timestamptz
UserID pgtype.UUID
}
// Saving a profile advances onboarding only from that exact step. A retry or
// a save after a later step is already stored never regresses onboarding.
func (q *Queries) AdvanceCandidateOnboardingAfterProfile(ctx context.Context, arg AdvanceCandidateOnboardingAfterProfileParams) error {
_, err := q.db.Exec(ctx, advanceCandidateOnboardingAfterProfile, arg.At, arg.UserID)
return err
}
const advanceCandidateProfileVersion = `-- name: AdvanceCandidateProfileVersion :one
UPDATE candidate_profiles
SET
@@ -47,6 +72,39 @@ func (q *Queries) AdvanceCandidateProfileVersion(ctx context.Context, arg Advanc
return i, err
}
const appendCandidateProfileHistory = `-- name: AppendCandidateProfileHistory :exec
INSERT INTO candidate_profile_history (
user_id,
version,
changed_at,
snapshot
) VALUES (
$1,
$2,
$3,
$4::jsonb
)
`
type AppendCandidateProfileHistoryParams struct {
UserID pgtype.UUID
Version int64
ChangedAt pgtype.Timestamptz
Snapshot []byte
}
// Every changed version appends exactly one private snapshot. The unique
// key prevents a second snapshot for the same profile version.
func (q *Queries) AppendCandidateProfileHistory(ctx context.Context, arg AppendCandidateProfileHistoryParams) error {
_, err := q.db.Exec(ctx, appendCandidateProfileHistory,
arg.UserID,
arg.Version,
arg.ChangedAt,
arg.Snapshot,
)
return err
}
const deleteCandidateProfileClaims = `-- name: DeleteCandidateProfileClaims :exec
DELETE FROM candidate_profile_claims
WHERE user_id = $1
@@ -59,6 +117,18 @@ func (q *Queries) DeleteCandidateProfileClaims(ctx context.Context, userID pgtyp
return err
}
const deleteCandidateProfileOverlapConfirmations = `-- name: DeleteCandidateProfileOverlapConfirmations :exec
DELETE FROM candidate_profile_overlap_confirmations
WHERE user_id = $1
`
// Replaces the current explicit decisions with those in the new profile.
// The versioned profile row is advanced first in this same transaction.
func (q *Queries) DeleteCandidateProfileOverlapConfirmations(ctx context.Context, userID pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteCandidateProfileOverlapConfirmations, userID)
return err
}
const insertCandidateProfile = `-- name: InsertCandidateProfile :one
INSERT INTO candidate_profiles (
@@ -157,6 +227,49 @@ func (q *Queries) InsertCandidateProfileClaim(ctx context.Context, arg InsertCan
return err
}
const insertCandidateProfileOverlapConfirmation = `-- name: InsertCandidateProfileOverlapConfirmation :exec
INSERT INTO candidate_profile_overlap_confirmations (
user_id,
first_index,
second_index,
first_started_on,
first_ended_on,
second_started_on,
second_ended_on
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7
)
`
type InsertCandidateProfileOverlapConfirmationParams struct {
UserID pgtype.UUID
FirstIndex int16
SecondIndex int16
FirstStartedOn string
FirstEndedOn pgtype.Text
SecondStartedOn string
SecondEndedOn pgtype.Text
}
func (q *Queries) InsertCandidateProfileOverlapConfirmation(ctx context.Context, arg InsertCandidateProfileOverlapConfirmationParams) error {
_, err := q.db.Exec(ctx, insertCandidateProfileOverlapConfirmation,
arg.UserID,
arg.FirstIndex,
arg.SecondIndex,
arg.FirstStartedOn,
arg.FirstEndedOn,
arg.SecondStartedOn,
arg.SecondEndedOn,
)
return err
}
const readCandidateProfile = `-- name: ReadCandidateProfile :many
SELECT
candidate_profiles.user_id,
@@ -171,7 +284,28 @@ SELECT
candidate_profile_claims.trust_level,
candidate_profile_claims.quote,
candidate_profile_claims.extraction_version,
candidate_profile_claims.confirmed_at
candidate_profile_claims.confirmed_at,
COALESCE(
(
SELECT jsonb_agg(
jsonb_build_object(
'first_index', confirmations.first_index,
'second_index', confirmations.second_index,
'first_period', jsonb_build_object(
'started_on', confirmations.first_started_on,
'ended_on', confirmations.first_ended_on
),
'second_period', jsonb_build_object(
'started_on', confirmations.second_started_on,
'ended_on', confirmations.second_ended_on
)
) ORDER BY confirmations.first_index, confirmations.second_index
)::text
FROM candidate_profile_overlap_confirmations AS confirmations
WHERE confirmations.user_id = candidate_profiles.user_id
),
'[]'::text
)::text AS parallel_period_acknowledgements
FROM candidate_profiles
LEFT JOIN candidate_profile_claims
ON candidate_profile_claims.user_id = candidate_profiles.user_id
@@ -180,19 +314,20 @@ ORDER BY candidate_profile_claims.kind, candidate_profile_claims.ordinal
`
type ReadCandidateProfileRow struct {
UserID pgtype.UUID
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Kind pgtype.Text
Ordinal pgtype.Int2
Value []byte
Status pgtype.Text
Origin pgtype.Text
TrustLevel pgtype.Int2
Quote pgtype.Text
ExtractionVersion pgtype.Text
ConfirmedAt pgtype.Timestamptz
UserID pgtype.UUID
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Kind pgtype.Text
Ordinal pgtype.Int2
Value []byte
Status pgtype.Text
Origin pgtype.Text
TrustLevel pgtype.Int2
Quote pgtype.Text
ExtractionVersion pgtype.Text
ConfirmedAt pgtype.Timestamptz
ParallelPeriodAcknowledgements string
}
// Reads the profile row of an account together with every claim in one
@@ -225,6 +360,7 @@ func (q *Queries) ReadCandidateProfile(ctx context.Context, userID pgtype.UUID)
&i.Quote,
&i.ExtractionVersion,
&i.ConfirmedAt,
&i.ParallelPeriodAcknowledgements,
); err != nil {
return nil, err
}
@@ -94,6 +94,23 @@ type CandidateProfileClaim struct {
ConfirmedAt pgtype.Timestamptz
}
type CandidateProfileHistory struct {
UserID pgtype.UUID
Version int64
ChangedAt pgtype.Timestamptz
Snapshot []byte
}
type CandidateProfileOverlapConfirmation struct {
UserID pgtype.UUID
FirstIndex int16
SecondIndex int16
FirstStartedOn string
FirstEndedOn pgtype.Text
SecondStartedOn string
SecondEndedOn pgtype.Text
}
type CandidatePublication struct {
UserID pgtype.UUID
State string
@@ -14,6 +14,9 @@ type Querier interface {
// Adds recipients to the day and the month row. The caller holds their
// locks from LockMailQuotaRows and has checked both limits.
AddMailQuotaUsage(ctx context.Context, arg AddMailQuotaUsageParams) (int64, error)
// Saving a profile advances onboarding only from that exact step. A retry or
// a save after a later step is already stored never regresses onboarding.
AdvanceCandidateOnboardingAfterProfile(ctx context.Context, arg AdvanceCandidateOnboardingAfterProfileParams) error
// Advances the version over the one the caller read, in the same statement.
// The row lock it takes serializes concurrent saves of one profile. The update
// time never moves back: an application clock behind the stored time (clock
@@ -28,6 +31,9 @@ type Querier interface {
// ends every earlier token, and deletes the registration C1 of the earlier
// registrant like UpdateUserRegistration does.
AdvanceUserRegistration(ctx context.Context, arg AdvanceUserRegistrationParams) (AdvanceUserRegistrationRow, error)
// Every changed version appends exactly one private snapshot. The unique
// key prevents a second snapshot for the same profile version.
AppendCandidateProfileHistory(ctx context.Context, arg AppendCandidateProfileHistoryParams) error
// Authorizes one retry of a terminal unknown delivery. The update and append-
// only decision share one statement and lock the current row, so a second or
// concurrent operator decision cannot schedule another send for the same
@@ -118,6 +124,9 @@ type Querier interface {
// Removes the claims that a save replaces. The adapter calls it after the
// version advanced and before it inserts the new set, in one transaction.
DeleteCandidateProfileClaims(ctx context.Context, userID pgtype.UUID) error
// Replaces the current explicit decisions with those in the new profile.
// The versioned profile row is advanced first in this same transaction.
DeleteCandidateProfileOverlapConfirmations(ctx context.Context, userID pgtype.UUID) error
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error
// Deletes one batch of accounts that stayed unverified since before cutoff,
@@ -286,6 +295,7 @@ type Querier interface {
// statement never takes a trust level from the caller, because every claim
// has level 0.
InsertCandidateProfileClaim(ctx context.Context, arg InsertCandidateProfileClaimParams) error
InsertCandidateProfileOverlapConfirmation(ctx context.Context, arg InsertCandidateProfileOverlapConfirmationParams) error
// Stores the first publication at version 1. No row returns when the account
// already has a row, so a first publication that lost a race with another
// one is answered as a version conflict. The foreign key refuses a record
+2
View File
@@ -36,11 +36,13 @@ func newAPIHandler(
problems *problem.Responder,
identityHandler *v1.IdentityHandler,
consentHandler *v1.ConsentHandler,
profileHandler *v1.ProfileHandler,
organizationHandler *v1.OrganizationHandler,
) *v1.Handler {
return v1.NewHandler(health, problems,
v1.WithIdentity(identityHandler),
v1.WithConsent(consentHandler),
v1.WithProfile(profileHandler),
v1.WithOrganization(organizationHandler),
)
}
+27
View File
@@ -0,0 +1,27 @@
package bootstrap
import (
"context"
"log/slog"
"time"
"lincodex/backend/config"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/postgres"
profileusecase "lincodex/backend/internal/usecase/profile"
)
const profilePoolMaxConns = 8
func newProfileHandler(ctx context.Context, settings config.Config, logger *slog.Logger) (*v1.ProfileHandler, func(), error) {
if settings.DatabaseURL == "" {
logger.Warn("candidate profile operations are not served because DATABASE_URL is not set")
return nil, func() {}, nil
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, profilePoolMaxConns)
if err != nil {
return nil, nil, err
}
service := profileusecase.NewService(postgres.NewTransactor(pool), time.Now)
return v1.NewProfileHandler(service), pool.Close, nil
}
+32
View File
@@ -0,0 +1,32 @@
package bootstrap
import (
"log/slog"
"net/http"
"net/netip"
httpadapter "lincodex/backend/internal/adapter/primary/http"
apiadapter "lincodex/backend/internal/adapter/primary/http/api"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
)
// newRouter installs company authorization even when its database is unavailable.
func newRouter(
health *v1.HealthHandler,
apiHandler apiadapter.Handler,
security apiadapter.SecurityHandler,
problems *problem.Responder,
collector httpmiddleware.RequestMetrics,
logger *slog.Logger,
trustedProxies []netip.Prefix,
organizationHandler *v1.OrganizationHandler,
) (http.Handler, error) {
var authorizer httpadapter.CompanyAuthorizer
if organizationHandler != nil {
authorizer = organizationHandler
}
return httpadapter.NewRouter(health, apiHandler, security, problems,
collector, logger, trustedProxies, httpadapter.NewCompanyContextMiddleware(authorizer))
}
+2 -2
View File
@@ -9,7 +9,6 @@ import (
"github.com/goforj/wire"
"lincodex/backend/config"
httpadapter "lincodex/backend/internal/adapter/primary/http"
apiadapter "lincodex/backend/internal/adapter/primary/http/api"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
"lincodex/backend/internal/adapter/primary/http/problem"
@@ -49,9 +48,10 @@ func initialize(
newIdentityHandler,
newIdentityKeyring,
newConsentHandler,
newProfileHandler,
newOrganizationHandler,
newSessionSecurity,
httpadapter.NewRouter,
newRouter,
newOutboxRelay,
newEventConsumers,
newJobWorker,
+43 -27
View File
@@ -9,7 +9,6 @@ package bootstrap
import (
"context"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/primary/http"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/postgres"
@@ -68,7 +67,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
organizationHandler, cleanup6, err := newOrganizationHandler(ctx, config2, logger, keyring)
profileHandler, cleanup6, err := newProfileHandler(ctx, config2, logger)
if err != nil {
cleanup5()
cleanup4()
@@ -77,30 +76,20 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, organizationHandler)
organizationHandler, cleanup7, err := newOrganizationHandler(ctx, config2, logger, keyring)
if err != nil {
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, organizationHandler)
sessionSecurity := newSessionSecurity(identityHandler)
v := newTrustedProxies(config2)
httpHandler, err := httpadapter.NewRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v)
if err != nil {
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
relay, cleanup7, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup8, err := newEventConsumers(ctx, config2, logger, metrics)
httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler)
if err != nil {
cleanup7()
cleanup6()
@@ -111,7 +100,18 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
worker, cleanup9, err := newJobWorker(ctx, config2, logger, metrics)
relay, cleanup8, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup9, err := newEventConsumers(ctx, config2, logger, metrics)
if err != nil {
cleanup8()
cleanup7()
@@ -123,7 +123,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
mailsenderWorker, cleanup10, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
worker, cleanup10, err := newJobWorker(ctx, config2, logger, metrics)
if err != nil {
cleanup9()
cleanup8()
@@ -136,7 +136,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup11, err := newDeliveryMetrics(ctx, config2, logger, metrics)
mailsenderWorker, cleanup11, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
if err != nil {
cleanup10()
cleanup9()
@@ -150,8 +150,24 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup12, err := newDeliveryMetrics(ctx, config2, logger, metrics)
if err != nil {
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler)
return application, func() {
cleanup12()
cleanup11()
cleanup10()
cleanup9()
+383 -64
View File
@@ -343,6 +343,56 @@ func (ProfileExperience) LogValue() slog.Value {
}
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
@@ -379,17 +429,20 @@ type ProfileClaimInput[V comparable] struct {
// 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]
SoftSkills []ProfileClaimInput[string]
Location *ProfileClaimInput[string]
Relocation *ProfileClaimInput[bool]
SalaryMinimum *ProfileClaimInput[ProfileSalaryMinimum]
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]
Location *ProfileClaimInput[string]
Relocation *ProfileClaimInput[bool]
SalaryMinimum *ProfileClaimInput[ProfileSalaryMinimum]
}
// CandidateProfileContent is the validated content of a profile: every claim
@@ -398,17 +451,18 @@ type CandidateProfileInput struct {
// 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]
softSkills []ProfileClaim[string]
location *ProfileClaim[string]
relocation *ProfileClaim[bool]
salaryMinimum *ProfileClaim[ProfileSalaryMinimum]
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]
location *ProfileClaim[string]
relocation *ProfileClaim[bool]
salaryMinimum *ProfileClaim[ProfileSalaryMinimum]
}
func optionalClaim[V comparable](claim *ProfileClaim[V]) (ProfileClaim[V], bool) {
@@ -469,6 +523,35 @@ func (content CandidateProfileContent) Experience() []ProfileClaim[ProfileExperi
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] {
@@ -488,6 +571,7 @@ func (content CandidateProfileContent) Equal(other CandidateProfileContent) bool
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)
}
@@ -730,6 +814,166 @@ func newProfileRules(now time.Time) profileRules {
}
}
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
@@ -798,6 +1042,12 @@ func ResolveCandidateProfileContent(stored CandidateProfileContent, input Candid
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
}
@@ -873,6 +1123,12 @@ func (profile CandidateProfile) Replace(input CandidateProfileInput, expectedVer
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
}
@@ -888,6 +1144,18 @@ func (profile CandidateProfile) Replace(input CandidateProfileInput, expectedVer
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) {
@@ -924,15 +1192,15 @@ const (
// ConfirmedAt is a NULL column, and an empty Quote or ExtractionVersion is a
// NULL one.
type StoredProfileClaim struct {
Kind string
Ordinal int
Value []byte
Status string
Origin string
TrustLevel int
Quote string
ExtractionVersion string
ConfirmedAt time.Time
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
@@ -1053,6 +1321,16 @@ func (content CandidateProfileContent) StoredClaims() ([]StoredProfileClaim, err
// 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 {
@@ -1070,39 +1348,78 @@ func RestoreCandidateProfileContent(rows []StoredProfileClaim) (CandidateProfile
return CandidateProfileContent{}, fail(row, "has invalid provenance")
}
status := ProfileClaimStatus(row.Status)
switch row.Kind {
case profileKindFullName:
err = restoreSingle(&content.fullName, rules.fullName, row, status, source)
case profileKindEmail:
err = restoreSingle(&content.email, rules.email, row, status, source)
case profileKindPhone:
err = restoreSingle(&content.phone, rules.phone, row, status, source)
case profileKindTelegram:
err = restoreSingle(&content.telegram, rules.telegram, row, status, source)
case profileKindLocation:
err = restoreSingle(&content.location, rules.location, row, status, source)
case profileKindRelocation:
err = restoreSingle(&content.relocation, rules.relocation, row, status, source)
case profileKindSalaryMinimum:
err = restoreSingle(&content.salaryMinimum, rules.salaryMinimum, row, status, source)
case profileKindStack:
err = restoreItem(&content.stack, rules.stack, row, status, source)
case profileKindSoftSkill:
err = restoreItem(&content.softSkills, rules.softSkills, row, status, source)
case profileKindRole:
err = restoreItem(&content.roles, rules.roles, row, status, source)
case profileKindExperience:
err = restoreItem(&content.experience, rules.experience, row, status, source)
default:
err = errors.New("kind is unknown")
}
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)
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
@@ -1202,13 +1519,15 @@ func restoreItem[V comparable](
return nil
}
// StoredCandidateProfile carries the profile row and its claims.
// 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
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
@@ -1224,7 +1543,7 @@ func RestoreCandidateProfile(stored StoredCandidateProfile) (CandidateProfile, e
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 := RestoreCandidateProfileContent(stored.Claims)
content, err := RestoreCandidateProfileContentWithParallelPeriods(stored.Claims, stored.ParallelPeriodAcknowledgements)
if err != nil {
return CandidateProfile{}, fmt.Errorf("%s - restore content: %w", location, err)
}
+195
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"log/slog"
"reflect"
"slices"
"strings"
"testing"
"time"
@@ -283,6 +284,200 @@ func TestResolveCandidateProfileContentNormalizesValues(t *testing.T) {
}
}
func TestResolveCandidateProfileContentRequiresExplicitParallelPeriodAcknowledgements(t *testing.T) {
input := CandidateProfileInput{Experience: confirmedItems(
ProfileExperience{EmployerName: "First employer", Specialization: SpecializationBackend, StartedOn: "2020-01", EndedOn: "2021-06"},
ProfileExperience{EmployerName: "Second employer", Specialization: SpecializationQA, StartedOn: "2021-06", EndedOn: "2022-01"},
)}
assertProfileFieldError(t, resolveErr(CandidateProfileContent{}, input, candidateTestTime), "/experience/1/started_on")
input.ParallelPeriodAcknowledgements = []ProfileParallelPeriodAcknowledgement{{
FirstIndex: 0, SecondIndex: 1,
FirstPeriod: ProfileExperiencePeriod{StartedOn: "2020-01", EndedOn: "2021-06"},
SecondPeriod: ProfileExperiencePeriod{StartedOn: "2021-06", EndedOn: "2022-01"},
}}
content := mustCandidateContent(t, CandidateProfileContent{}, input, candidateTestTime)
overlaps := content.ExperienceOverlaps()
if len(overlaps) != 1 || overlaps[0].FirstIndex != 0 || overlaps[0].SecondIndex != 1 || overlaps[0].Status != ProfileExperienceOverlapConfirmed {
t.Fatalf("overlaps = %+v, want the acknowledged pair at indices 0 and 1", overlaps)
}
}
func TestResolveCandidateProfileContentRejectsInvalidParallelPeriodAcknowledgements(t *testing.T) {
base := CandidateProfileInput{Experience: confirmedItems(
ProfileExperience{EmployerName: "First employer", Specialization: SpecializationBackend, StartedOn: "2020-01", EndedOn: "2020-05"},
ProfileExperience{EmployerName: "Second employer", Specialization: SpecializationQA, StartedOn: "2020-06", EndedOn: "2021-01"},
)}
period := func(startedOn, endedOn string) ProfileExperiencePeriod {
return ProfileExperiencePeriod{StartedOn: startedOn, EndedOn: endedOn}
}
tests := []struct {
name string
confirm ProfileParallelPeriodAcknowledgement
pointer string
}{
{
name: "first period does not match the submitted entry",
confirm: ProfileParallelPeriodAcknowledgement{
FirstIndex: 0, SecondIndex: 1, FirstPeriod: period("2020-02", "2020-05"), SecondPeriod: period("2020-06", "2021-01"),
},
pointer: "/confirmed_parallel_periods/0/first_period/started_on",
},
{
name: "second period does not match the submitted entry",
confirm: ProfileParallelPeriodAcknowledgement{
FirstIndex: 0, SecondIndex: 1, FirstPeriod: period("2020-01", "2020-05"), SecondPeriod: period("2020-05", "2021-01"),
},
pointer: "/confirmed_parallel_periods/0/second_period/started_on",
},
{
name: "self pair",
confirm: ProfileParallelPeriodAcknowledgement{
FirstIndex: 0, SecondIndex: 0, FirstPeriod: period("2020-01", "2020-05"), SecondPeriod: period("2020-01", "2020-05"),
},
pointer: "/confirmed_parallel_periods/0/second_index",
},
{
name: "reversed indices",
confirm: ProfileParallelPeriodAcknowledgement{
FirstIndex: 1, SecondIndex: 0, FirstPeriod: period("2020-06", "2021-01"), SecondPeriod: period("2020-01", "2020-05"),
},
pointer: "/confirmed_parallel_periods/0/second_index",
},
{
name: "out-of-range index",
confirm: ProfileParallelPeriodAcknowledgement{
FirstIndex: 0, SecondIndex: 2, FirstPeriod: period("2020-01", "2020-05"), SecondPeriod: period("2020-06", "2021-01"),
},
pointer: "/confirmed_parallel_periods/0/second_index",
},
{
name: "periods do not overlap",
confirm: ProfileParallelPeriodAcknowledgement{
FirstIndex: 0, SecondIndex: 1, FirstPeriod: period("2020-01", "2020-05"), SecondPeriod: period("2020-06", "2021-01"),
},
pointer: "/confirmed_parallel_periods/0/second_index",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
input := base
input.ParallelPeriodAcknowledgements = []ProfileParallelPeriodAcknowledgement{test.confirm}
assertProfileFieldError(t, resolveErr(CandidateProfileContent{}, input, candidateTestTime), test.pointer)
})
}
}
func TestCandidateProfileReplaceCarriesParallelPeriodAcknowledgementsOnlyForTheSameIndexedDates(t *testing.T) {
userID := uuid.Must(uuid.NewV7())
profile, err := EmptyCandidateProfile(userID)
if err != nil {
t.Fatalf("EmptyCandidateProfile() error = %v", err)
}
input := CandidateProfileInput{Experience: confirmedItems(
ProfileExperience{EmployerName: "First employer", Specialization: SpecializationBackend, StartedOn: "2020-01", EndedOn: "2021-06", Summary: "First"},
ProfileExperience{EmployerName: "Second employer", Specialization: SpecializationQA, StartedOn: "2021-06", EndedOn: "2022-01", Summary: "Second"},
)}
input.ParallelPeriodAcknowledgements = []ProfileParallelPeriodAcknowledgement{{
FirstIndex: 0, SecondIndex: 1,
FirstPeriod: ProfileExperiencePeriod{StartedOn: "2020-01", EndedOn: "2021-06"},
SecondPeriod: ProfileExperiencePeriod{StartedOn: "2021-06", EndedOn: "2022-01"},
}}
profile, changed, err := profile.Replace(input, 0, candidateTestTime)
if err != nil || !changed {
t.Fatalf("Replace(first save) = changed %v, %v, want a confirmed change", changed, err)
}
t.Run("unrelated experience fields preserve acknowledgement", func(t *testing.T) {
edited := input
edited.ParallelPeriodAcknowledgements = nil
edited.Experience = slices.Clone(input.Experience)
edited.Experience[0].Value.Summary = "Updated work"
updated, changed, err := profile.Replace(edited, 0, candidateTestTime.Add(time.Hour))
if err != nil || !changed || updated.Content().ExperienceOverlaps()[0].Status != ProfileExperienceOverlapConfirmed {
t.Fatalf("Replace(summary edit) = changed %v, overlaps %+v, error %v", changed, updated.Content().ExperienceOverlaps(), err)
}
})
t.Run("changed period requires a fresh acknowledgement", func(t *testing.T) {
edited := input
edited.ParallelPeriodAcknowledgements = nil
edited.Experience = slices.Clone(input.Experience)
edited.Experience[0].Value.EndedOn = "2021-07"
assertProfileFieldError(t, errOnly(profile.Replace(edited, 0, candidateTestTime.Add(time.Hour))), "/experience/1/started_on")
})
t.Run("reordered periods require a fresh acknowledgement", func(t *testing.T) {
edited := input
edited.ParallelPeriodAcknowledgements = nil
edited.Experience = []ProfileClaimInput[ProfileExperience]{input.Experience[1], input.Experience[0]}
assertProfileFieldError(t, errOnly(profile.Replace(edited, 0, candidateTestTime.Add(time.Hour))), "/experience/1/started_on")
})
t.Run("changed period can be explicitly acknowledged", func(t *testing.T) {
edited := input
edited.Experience = slices.Clone(input.Experience)
edited.Experience[0].Value.EndedOn = "2021-07"
edited.ParallelPeriodAcknowledgements = []ProfileParallelPeriodAcknowledgement{{
FirstIndex: 0, SecondIndex: 1,
FirstPeriod: ProfileExperiencePeriod{StartedOn: "2020-01", EndedOn: "2021-07"},
SecondPeriod: ProfileExperiencePeriod{StartedOn: "2021-06", EndedOn: "2022-01"},
}}
updated, changed, err := profile.Replace(edited, 0, candidateTestTime.Add(time.Hour))
if err != nil || !changed || updated.Content().ExperienceOverlaps()[0].Status != ProfileExperienceOverlapConfirmed {
t.Fatalf("Replace(confirmed period edit) = changed %v, overlaps %+v, error %v", changed, updated.Content().ExperienceOverlaps(), err)
}
})
}
func TestCandidateProfileWithStoredUnconfirmedOverlapOnlyAllowsNoOpOrExplicitConfirmation(t *testing.T) {
profile, err := RestoreCandidateProfile(StoredCandidateProfile{
UserID: uuid.Must(uuid.NewV7()), Version: 1,
CreatedAt: candidateTestTime, UpdatedAt: candidateTestTime,
Claims: []StoredProfileClaim{
{
Kind: profileKindExperience, Ordinal: 0,
Value: []byte(`{"employer_name":"First","specialization":"backend","started_on":"2020-01","ended_on":"2021-06","summary":null}`),
Status: string(ProfileClaimConfirmed), Origin: string(ProfileOriginManual), TrustLevel: 0, ConfirmedAt: candidateTestTime,
},
{
Kind: profileKindExperience, Ordinal: 1,
Value: []byte(`{"employer_name":"Second","specialization":"qa","started_on":"2021-06","ended_on":"2022-01","summary":null}`),
Status: string(ProfileClaimConfirmed), Origin: string(ProfileOriginManual), TrustLevel: 0, ConfirmedAt: candidateTestTime,
},
},
})
if err != nil {
t.Fatalf("RestoreCandidateProfile() error = %v", err)
}
input := CandidateProfileInput{Experience: confirmedItems(
ProfileExperience{EmployerName: "First", Specialization: SpecializationBackend, StartedOn: "2020-01", EndedOn: "2021-06"},
ProfileExperience{EmployerName: "Second", Specialization: SpecializationQA, StartedOn: "2021-06", EndedOn: "2022-01"},
)}
if unchanged, changed, err := profile.Replace(input, 0, candidateTestTime.Add(time.Hour)); err != nil || changed || unchanged.Version() != profile.Version() {
t.Fatalf("Replace(no-op retry) = version %d, changed %v, error %v", unchanged.Version(), changed, err)
}
changedName := input
changedName.FullName = confirmed("Anna Sokolova")
assertProfileFieldError(t, errOnly(profile.Replace(changedName, 1, candidateTestTime.Add(time.Hour))), "/experience/1/started_on")
if _, _, err := profile.Replace(changedName, 0, candidateTestTime.Add(time.Hour)); !errors.Is(err, ErrCandidateProfileVersionConflict) {
t.Fatalf("Replace(stale changed profile) error = %v, want version conflict", err)
}
input.ParallelPeriodAcknowledgements = []ProfileParallelPeriodAcknowledgement{{
FirstIndex: 0, SecondIndex: 1,
FirstPeriod: ProfileExperiencePeriod{StartedOn: "2020-01", EndedOn: "2021-06"},
SecondPeriod: ProfileExperiencePeriod{StartedOn: "2021-06", EndedOn: "2022-01"},
}}
confirmedProfile, changed, err := profile.Replace(input, 1, candidateTestTime.Add(time.Hour))
if err != nil || !changed || confirmedProfile.Content().ExperienceOverlaps()[0].Status != ProfileExperienceOverlapConfirmed {
t.Fatalf("Replace(explicit confirmation) = changed %v, error %v", changed, err)
}
}
func TestCandidateProfileReplaceTellsAChangeFromANoOp(t *testing.T) {
userID := uuid.Must(uuid.NewV7())
empty, err := EmptyCandidateProfile(userID)
@@ -0,0 +1,42 @@
package outbound
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
// ErrCandidateProfileVersionConflict reports a stale expected version.
ErrCandidateProfileVersionConflict = errors.New("candidate profile changed concurrently")
// ErrCandidateProfileHistoryTooLarge reports a snapshot that exceeds the
// private history table's fixed storage bound.
ErrCandidateProfileHistoryTooLarge = errors.New("candidate profile history snapshot exceeds its bound")
)
// CandidateProfileRepositories exposes the candidate profile repository.
// UnitOfWork binds it to the transaction that also records profile history
// and advances onboarding.
type CandidateProfileRepositories interface {
CandidateProfiles() CandidateProfileRepository
}
// CandidateProfileRepository reads and replaces only the profile identified
// by userID. A missing profile row is the version-0 empty profile.
type CandidateProfileRepository interface {
Get(ctx context.Context, userID uuid.UUID) (domain.CandidateProfile, error)
// Save writes a changed profile only when its stored version equals
// expectedVersion. It replaces claims and period acknowledgements and
// appends the bounded immutable snapshot in the same transaction.
Save(ctx context.Context, expectedVersion int64, profile domain.CandidateProfile) (domain.CandidateProfile, error)
// AdvanceOnboarding advances a verified candidate only from
// candidate_profile to candidate_questionnaire. A later step is left alone.
AdvanceOnboarding(ctx context.Context, userID uuid.UUID, at time.Time) error
}
@@ -50,6 +50,7 @@ type Transactor interface {
type UnitOfWork interface {
IdentityRepositories
ConsentRepositories
CandidateProfileRepositories
AccountDeletionRequests() AccountDeletionRequests
ConsentRevocationEffects() ConsentRevocationEffects
OrganizationRepositories
@@ -0,0 +1,44 @@
package organization
import (
"context"
"github.com/google/uuid"
)
// CompanyAccess is a request-scoped capability issued after the current
// account has been checked as an active owner. Business operations still
// repeat authorization inside their transaction before reading or writing.
type CompanyAccess struct {
actorID uuid.UUID
organizationID uuid.UUID
membershipID uuid.UUID
}
// Matches reports whether this capability was issued for actorID and
// organizationID.
func (access CompanyAccess) Matches(actorID, organizationID uuid.UUID) bool {
return access.actorID != uuid.Nil && access.organizationID != uuid.Nil && access.membershipID != uuid.Nil &&
access.actorID == actorID && access.organizationID == organizationID
}
type companyAccessContextKey struct{}
// WithCompanyAccess attaches a validated company capability to a request
// context. An empty capability is ignored.
func WithCompanyAccess(ctx context.Context, access CompanyAccess) context.Context {
if !access.Matches(access.actorID, access.organizationID) {
return ctx
}
return context.WithValue(ctx, companyAccessContextKey{}, access)
}
// CompanyAccessFromContext returns the capability attached by the HTTP
// boundary, if one is present and valid.
func CompanyAccessFromContext(ctx context.Context) (CompanyAccess, bool) {
access, ok := ctx.Value(companyAccessContextKey{}).(CompanyAccess)
if !ok || !access.Matches(access.actorID, access.organizationID) {
return CompanyAccess{}, false
}
return access, true
}
@@ -252,6 +252,9 @@ func (service *Service) Update(ctx context.Context, command UpdateCommand) (doma
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil {
return domain.Organization{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
}
if err := matchCompanyContext(ctx, command.ActorID, command.OrganizationID, location); err != nil {
return domain.Organization{}, err
}
if command.ExpectedVersion < 1 {
return domain.Organization{}, fmt.Errorf("%s - expected version must be positive: %w", location, domain.ErrInvalidOrganization)
}
@@ -299,13 +302,16 @@ func (service *Service) Update(ctx context.Context, command UpdateCommand) (doma
return result, nil
}
// Get reads an organization only for an active member of the employer
// account. The membership is checked in the same transaction as the account.
// Get reads an organization only for its active owner. The membership is
// checked in the same transaction as the account.
func (service *Service) Get(ctx context.Context, actorID, organizationID uuid.UUID) (domain.Organization, error) {
const location = "organization.Service.Get"
if actorID == uuid.Nil || organizationID == uuid.Nil {
return domain.Organization{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
}
if err := matchCompanyContext(ctx, actorID, organizationID, location); err != nil {
return domain.Organization{}, err
}
var result domain.Organization
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireEmployer(ctx, unit, actorID, location); err != nil {
@@ -318,6 +324,9 @@ func (service *Service) Get(ctx context.Context, actorID, organizationID uuid.UU
if !membership.GrantsAccess() {
return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound)
}
if membership.Role() != domain.OrganizationRoleOwner {
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
}
result = organization
return nil
})
@@ -327,6 +336,82 @@ func (service *Service) Get(ctx context.Context, actorID, organizationID uuid.UU
return result, nil
}
// AuthorizeCompany verifies the current verified employer account, active
// membership, and owner role before issuing a request-scoped capability.
func (service *Service) AuthorizeCompany(ctx context.Context, actorID, organizationID uuid.UUID) (CompanyAccess, error) {
const location = "organization.Service.AuthorizeCompany"
if actorID == uuid.Nil || organizationID == uuid.Nil {
return CompanyAccess{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
}
var access CompanyAccess
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireEmployer(ctx, unit, actorID, location); err != nil {
return fmt.Errorf("%s - authorize company actor: %w", location, err)
}
_, membership, err := unit.Organizations().GetForMember(ctx, organizationID, actorID)
if err != nil {
return fmt.Errorf("%s - read active company membership: %w", location, err)
}
if !membership.GrantsAccess() {
return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound)
}
if membership.Role() != domain.OrganizationRoleOwner {
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
}
access = CompanyAccess{actorID: actorID, organizationID: organizationID, membershipID: membership.ID()}
return nil
})
if err != nil {
return CompanyAccess{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return access, nil
}
// ListMyOrganizations returns active organization memberships for one
// verified employer. The actor always comes from the authenticated session.
func (service *Service) ListMyOrganizations(ctx context.Context, command OrganizationListCommand) (outbound.OrganizationPage, error) {
const location = "organization.Service.ListMyOrganizations"
if command.ActorID == uuid.Nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - actor ID must be set: %w", location, ErrForbidden)
}
if command.Limit < 1 || command.Limit > outbound.MaxOrganizationPageSize {
return outbound.OrganizationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxOrganizationPageSize, domain.ErrInvalidMembership)
}
var result outbound.OrganizationPage
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireEmployer(ctx, unit, command.ActorID, location); err != nil {
return fmt.Errorf("%s - authorize list actor: %w", location, err)
}
page, err := unit.Organizations().ListForUser(ctx, outbound.OrganizationListQuery{
UserID: command.ActorID, After: command.After, Limit: command.Limit,
})
if err != nil {
return fmt.Errorf("%s - list active memberships: %w", location, err)
}
result = page
return nil
})
if err != nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
// OrganizationListCommand selects a page of the actor's own memberships.
type OrganizationListCommand struct {
ActorID uuid.UUID
After *outbound.OrganizationListPosition
Limit int32
}
func matchCompanyContext(ctx context.Context, actorID, organizationID uuid.UUID, location string) error {
access, ok := CompanyAccessFromContext(ctx)
if ok && !access.Matches(actorID, organizationID) {
return fmt.Errorf("%s - company context does not match the operation: %w", location, ErrForbidden)
}
return nil
}
func applyPatch(current domain.OrganizationProfile, patch ProfilePatch) (domain.OrganizationProfile, error) {
contacts := current.Contacts()
input := domain.OrganizationProfileInput{
@@ -22,6 +22,7 @@ type organizationTestState struct {
memberships map[organizationTestMembershipKey]domain.Membership
idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord
results map[[outbound.IdempotencyDigestSize]byte]outbound.OrganizationCreationResult
lastListQuery *outbound.OrganizationListQuery
}
type organizationTestMembershipKey struct {
@@ -56,6 +57,14 @@ func (state organizationTestState) clone() organizationTestState {
for scope, result := range state.results {
cloned.results[scope] = result
}
if state.lastListQuery != nil {
query := *state.lastListQuery
if query.After != nil {
position := *query.After
query.After = &position
}
cloned.lastListQuery = &query
}
return cloned
}
@@ -227,9 +236,10 @@ func (repository organizationTestOrganizations) GetForMember(
}
func (repository organizationTestOrganizations) ListForUser(
context.Context,
outbound.OrganizationListQuery,
_ context.Context,
query outbound.OrganizationListQuery,
) (outbound.OrganizationPage, error) {
repository.state.lastListQuery = &query
return outbound.OrganizationPage{}, nil
}
@@ -550,6 +560,93 @@ func TestUpdateRequiresOwnerAndPreservesVerification(t *testing.T) {
}
}
func TestAuthorizeCompanyIssuesContextCapabilityOnlyToActiveOwner(t *testing.T) {
ctx := t.Context()
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
tx := newOrganizationTestTransactor()
ownerID, recruiterID, candidateID, unverifiedID, foreignID := uuid.New(), uuid.New(), uuid.New(), uuid.New(), uuid.New()
tx.state.users[ownerID] = verifiedEmployer(ownerID, now)
tx.state.users[recruiterID] = verifiedEmployer(recruiterID, now)
tx.state.users[candidateID] = domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
tx.state.users[unverifiedID] = domain.User{ID: unverifiedID, Scenario: domain.ScenarioEmployer}
tx.state.users[foreignID] = verifiedEmployer(foreignID, now)
service := newOrganizationTestService(t, tx, func() time.Time { return now })
profile := organizationProfile("ООО Пример", "Данные")
created, err := service.Create(ctx, CreateCommand{
ActorID: ownerID, IdempotencyKey: "company-access-01", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile,
})
if err != nil {
t.Fatalf("Create() error = %v", err)
}
organizationID := created.Organization.ID()
for _, input := range []domain.MembershipInput{
{OrganizationID: organizationID, UserID: recruiterID, Role: domain.OrganizationRoleRecruiter, At: now.Add(time.Second)},
{OrganizationID: organizationID, UserID: candidateID, Role: domain.OrganizationRoleOwner, At: now.Add(time.Second)},
{OrganizationID: organizationID, UserID: unverifiedID, Role: domain.OrganizationRoleOwner, At: now.Add(time.Second)},
} {
membership, err := domain.NewMembership(input)
if err != nil {
t.Fatalf("NewMembership() error = %v", err)
}
tx.state.memberships[organizationTestMembershipKey{organizationID, input.UserID}] = membership
}
access, err := service.AuthorizeCompany(ctx, ownerID, organizationID)
if err != nil || !access.Matches(ownerID, organizationID) {
t.Fatalf("AuthorizeCompany(owner) = %+v, %v; want matching capability", access, err)
}
if access.Matches(foreignID, organizationID) || access.Matches(ownerID, uuid.New()) {
t.Fatal("CompanyAccess matched a different actor or organization")
}
for _, test := range []struct {
name string
user uuid.UUID
want error
}{
{name: "recruiter role", user: recruiterID, want: outbound.ErrOrganizationManagerRequired},
{name: "candidate even with owner membership", user: candidateID, want: ErrForbidden},
{name: "unverified employer", user: unverifiedID, want: ErrEmailNotVerified},
{name: "no membership", user: foreignID, want: outbound.ErrOrganizationNotFound},
} {
t.Run(test.name, func(t *testing.T) {
if _, err := service.AuthorizeCompany(ctx, test.user, organizationID); !errors.Is(err, test.want) {
t.Fatalf("AuthorizeCompany() error = %v, want %v", err, test.want)
}
})
}
if _, err := service.Get(ctx, recruiterID, organizationID); !errors.Is(err, outbound.ErrOrganizationManagerRequired) {
t.Fatalf("Get(recruiter) error = %v, want ErrOrganizationManagerRequired", err)
}
if _, err := service.Get(WithCompanyAccess(ctx, access), ownerID, uuid.New()); !errors.Is(err, ErrForbidden) {
t.Fatalf("Get(mismatched company context) error = %v, want ErrForbidden", err)
}
}
func TestListMyOrganizationsUsesOnlyVerifiedEmployerActorAndBoundedPage(t *testing.T) {
ctx := t.Context()
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
tx := newOrganizationTestTransactor()
employerID, candidateID := uuid.New(), uuid.New()
tx.state.users[employerID] = verifiedEmployer(employerID, now)
tx.state.users[candidateID] = domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
service := newOrganizationTestService(t, tx, func() time.Time { return now })
position := outbound.OrganizationListPosition{JoinedAt: now.Add(-time.Minute), OrganizationID: uuid.New()}
page, err := service.ListMyOrganizations(ctx, OrganizationListCommand{ActorID: employerID, After: &position, Limit: 8})
if err != nil || len(page.Items) != 0 || page.HasMore {
t.Fatalf("ListMyOrganizations() = %+v, %v; want empty page", page, err)
}
query := tx.snapshot().lastListQuery
if query == nil || query.UserID != employerID || query.Limit != 8 || query.After == nil || *query.After != position {
t.Fatalf("ListForUser query = %+v, want principal-scoped cursor and limit", query)
}
if _, err := service.ListMyOrganizations(ctx, OrganizationListCommand{ActorID: candidateID, Limit: 8}); !errors.Is(err, ErrForbidden) {
t.Fatalf("ListMyOrganizations(candidate) error = %v, want ErrForbidden", err)
}
if _, err := service.ListMyOrganizations(ctx, OrganizationListCommand{ActorID: employerID, Limit: outbound.MaxOrganizationPageSize + 1}); !errors.Is(err, domain.ErrInvalidMembership) {
t.Fatalf("ListMyOrganizations(oversized limit) error = %v, want ErrInvalidMembership", err)
}
}
func TestConcurrentCreateWithSameKeyReturnsOneCompany(t *testing.T) {
ctx := t.Context()
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
+135
View File
@@ -0,0 +1,135 @@
// Package profile reads and version-saves a candidate's private manual profile.
package profile
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var (
// ErrForbidden reports an account that cannot use the candidate profile.
ErrForbidden = errors.New("candidate profile operation forbidden")
// ErrEmailNotVerified reports an account whose current email is not confirmed.
ErrEmailNotVerified = errors.New("candidate profile requires a confirmed email")
)
// Service is stateless between calls. Profile data, its history, and onboarding
// movement are written through one transaction.
type Service struct {
transactor outbound.Transactor
clock func() time.Time
}
// NewService takes the transaction boundary and application clock. A nil
// dependency is a wiring error and panics at construction.
func NewService(transactor outbound.Transactor, clock func() time.Time) *Service {
if transactor == nil {
panic("profile.NewService - transactor must not be nil")
}
if clock == nil {
panic("profile.NewService - clock must not be nil")
}
return &Service{transactor: transactor, clock: clock}
}
// GetMyProfile reads only the profile owned by userID. Version zero means the
// candidate has not saved a profile yet.
func (service *Service) GetMyProfile(ctx context.Context, userID uuid.UUID) (domain.CandidateProfile, error) {
const location = "Service.GetMyProfile"
if userID == uuid.Nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile)
}
var result domain.CandidateProfile
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireCandidate(ctx, unit, userID, location); err != nil {
return err
}
var err error
result, err = unit.CandidateProfiles().Get(ctx, userID)
if err != nil {
return fmt.Errorf("%s - read profile: %w", location, err)
}
return nil
})
if err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
// SaveMyProfile replaces the candidate's manual profile when expectedVersion
// is current. Identical retries remain no-ops, while every successful request
// advances onboarding only from candidate_profile.
func (service *Service) SaveMyProfile(
ctx context.Context,
userID uuid.UUID,
expectedVersion int64,
input domain.CandidateProfileInput,
) (domain.CandidateProfile, error) {
const location = "Service.SaveMyProfile"
if userID == uuid.Nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile)
}
at := service.clock().UTC()
if at.IsZero() {
return domain.CandidateProfile{}, fmt.Errorf("%s - application clock returned zero: %w", location, domain.ErrInvalidCandidateProfile)
}
var result domain.CandidateProfile
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireCandidate(ctx, unit, userID, location); err != nil {
return err
}
repository := unit.CandidateProfiles()
current, err := repository.Get(ctx, userID)
if err != nil {
return fmt.Errorf("%s - read profile: %w", location, err)
}
updated, changed, err := current.Replace(input, expectedVersion, at)
if err != nil {
return fmt.Errorf("%s - apply profile: %w", location, err)
}
if changed {
updated, err = repository.Save(ctx, expectedVersion, updated)
if err != nil {
return fmt.Errorf("%s - save profile: %w", location, err)
}
}
if err := repository.AdvanceOnboarding(ctx, userID, at); err != nil {
return fmt.Errorf("%s - advance onboarding: %w", location, err)
}
result = updated
return nil
})
if err != nil {
if errors.Is(err, outbound.ErrCandidateProfileVersionConflict) || errors.Is(err, domain.ErrCandidateProfileVersionConflict) {
return domain.CandidateProfile{}, fmt.Errorf("%s - transaction: %w", location, domain.ErrCandidateProfileVersionConflict)
}
return domain.CandidateProfile{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
func requireCandidate(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, location string) error {
user, err := unit.Users().GetByID(ctx, userID)
if err != nil {
if errors.Is(err, outbound.ErrUserNotFound) {
return ErrForbidden
}
return fmt.Errorf("%s - read account: %w", location, err)
}
if !user.EmailVerified() {
return ErrEmailNotVerified
}
if user.Scenario != domain.ScenarioCandidate {
return ErrForbidden
}
return nil
}
@@ -0,0 +1,184 @@
package profile
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
type profileTestTransactor struct {
unit outbound.UnitOfWork
}
func (transactor profileTestTransactor) WithinTransaction(
ctx context.Context,
fn func(context.Context, outbound.UnitOfWork) error,
) error {
return fn(ctx, transactor.unit)
}
type profileTestUnit struct {
outbound.UnitOfWork
users outbound.UserRepository
profiles outbound.CandidateProfileRepository
}
func (unit profileTestUnit) Users() outbound.UserRepository { return unit.users }
func (unit profileTestUnit) CandidateProfiles() outbound.CandidateProfileRepository {
return unit.profiles
}
type profileTestUsers struct {
outbound.UserRepository
user domain.User
err error
getCalls int
}
func (users *profileTestUsers) GetByID(_ context.Context, userID uuid.UUID) (domain.User, error) {
users.getCalls++
if users.err != nil {
return domain.User{}, users.err
}
if userID != users.user.ID {
return domain.User{}, outbound.ErrUserNotFound
}
return users.user, nil
}
type profileTestRepository struct {
profile domain.CandidateProfile
getCalls int
saveCalls int
advanceCalls int
saveErr error
advanceErr error
}
func (repository *profileTestRepository) Get(_ context.Context, _ uuid.UUID) (domain.CandidateProfile, error) {
repository.getCalls++
return repository.profile, nil
}
func (repository *profileTestRepository) Save(
_ context.Context,
expectedVersion int64,
profile domain.CandidateProfile,
) (domain.CandidateProfile, error) {
repository.saveCalls++
if repository.saveErr != nil {
return domain.CandidateProfile{}, repository.saveErr
}
claims, err := profile.Content().StoredClaims()
if err != nil {
return domain.CandidateProfile{}, err
}
repository.profile, err = domain.RestoreCandidateProfile(domain.StoredCandidateProfile{
UserID: profile.UserID(), Version: expectedVersion + 1,
CreatedAt: profile.CreatedAt(), UpdatedAt: profile.UpdatedAt(), Claims: claims,
ParallelPeriodAcknowledgements: profile.Content().ParallelPeriodAcknowledgements(),
})
return repository.profile, err
}
func (repository *profileTestRepository) AdvanceOnboarding(_ context.Context, _ uuid.UUID, _ time.Time) error {
repository.advanceCalls++
return repository.advanceErr
}
func TestServiceRequiresVerifiedCandidateBeforeReadingOrWritingProfile(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
tests := []struct {
name string
scenario domain.Scenario
verified bool
wantErr error
}{
{name: "verified candidate", scenario: domain.ScenarioCandidate, verified: true},
{name: "unverified candidate", scenario: domain.ScenarioCandidate, wantErr: ErrEmailNotVerified},
{name: "verified employer", scenario: domain.ScenarioEmployer, verified: true, wantErr: ErrForbidden},
{name: "unverified employer", scenario: domain.ScenarioEmployer, wantErr: ErrEmailNotVerified},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
id := uuid.Must(uuid.NewV7())
user := domain.User{ID: id, Scenario: test.scenario}
if test.verified {
user.EmailVerifiedAt = &now
}
users := &profileTestUsers{user: user}
profiles := &profileTestRepository{}
profiles.profile, _ = domain.EmptyCandidateProfile(id)
service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles}}, func() time.Time { return now })
_, readErr := service.GetMyProfile(context.Background(), id)
if !errors.Is(readErr, test.wantErr) {
t.Fatalf("GetMyProfile() error = %v, want %v", readErr, test.wantErr)
}
_, saveErr := service.SaveMyProfile(context.Background(), id, 0, domain.CandidateProfileInput{})
if !errors.Is(saveErr, test.wantErr) {
t.Fatalf("SaveMyProfile() error = %v, want %v", saveErr, test.wantErr)
}
wantProfileReads := 0
wantAdvances := 0
if test.wantErr == nil {
wantProfileReads = 2
wantAdvances = 1
}
if profiles.getCalls != wantProfileReads || profiles.saveCalls != 0 || profiles.advanceCalls != wantAdvances {
t.Fatalf("profile calls = get %d, save %d, advance %d; want %d, 0, %d", profiles.getCalls, profiles.saveCalls, profiles.advanceCalls, wantProfileReads, wantAdvances)
}
})
}
}
func TestSaveMyProfileWritesOnlyChangedVersionsAndAdvancesOnNoOp(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
id := uuid.Must(uuid.NewV7())
user := domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
users := &profileTestUsers{user: user}
profiles := &profileTestRepository{}
profiles.profile, _ = domain.EmptyCandidateProfile(id)
service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles}}, func() time.Time { return now })
input := domain.CandidateProfileInput{FullName: &domain.ProfileClaimInput[string]{Value: "Anna Sokolova", Status: domain.ProfileClaimConfirmed}}
if _, err := service.SaveMyProfile(context.Background(), id, 0, input); err != nil {
t.Fatalf("SaveMyProfile(first save) error = %v", err)
}
if profiles.saveCalls != 1 || profiles.advanceCalls != 1 || profiles.profile.Version() != 1 {
t.Fatalf("first save calls = save %d, advance %d, version %d", profiles.saveCalls, profiles.advanceCalls, profiles.profile.Version())
}
if _, err := service.SaveMyProfile(context.Background(), id, 1, input); err != nil {
t.Fatalf("SaveMyProfile(no-op retry) error = %v", err)
}
if profiles.saveCalls != 1 || profiles.advanceCalls != 2 {
t.Fatalf("no-op calls = save %d, advance %d, want one saved version and two onboarding checks", profiles.saveCalls, profiles.advanceCalls)
}
}
func TestSaveMyProfileDoesNotAdvanceAfterProfileWriteFailure(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
id := uuid.Must(uuid.NewV7())
user := domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
users := &profileTestUsers{user: user}
profiles := &profileTestRepository{saveErr: outbound.ErrTransactionConflict}
profiles.profile, _ = domain.EmptyCandidateProfile(id)
service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles}}, func() time.Time { return now })
input := domain.CandidateProfileInput{FullName: &domain.ProfileClaimInput[string]{Value: "Anna Sokolova", Status: domain.ProfileClaimConfirmed}}
if _, err := service.SaveMyProfile(context.Background(), id, 0, input); !errors.Is(err, outbound.ErrTransactionConflict) {
t.Fatalf("SaveMyProfile() error = %v, want transaction conflict", err)
}
if profiles.advanceCalls != 0 {
t.Fatalf("onboarding advances %d times after a failed write, want 0", profiles.advanceCalls)
}
}