feat(profile): persist candidate edits and enforce company access
This commit is contained in:
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
|
||||
|
||||
Reference in new issue
Block a user