feat: persist candidate questionnaires and enforce company quotas

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 15:47:10 +03:00
1 parent 73c7caa225
commit 3a61a8e8bb
51 files changed
+6280 -38

No files matched your search

@@ -16292,9 +16292,9 @@ func (s *NumberItemContentFormat) UnmarshalText(data []byte) error {
// - candidate_profile: candidate profile.
// - candidate_questionnaire: candidate questionnaire.
// - candidate_assessment: the assessment. The expected grade is the `self_assessed_grade` saved in
// the questionnaire, and this step offers it first; only an assessment result confirms a grade. The
// first successful SaveMyQuestionnaire moves the account from candidate_questionnaire to this step
// (planned).
// the questionnaire, and this step offers it first; only an assessment result confirms a grade. A
// successful SaveMyQuestionnaire moves the account from candidate_questionnaire to this step and
// leaves every other saved step unchanged.
// - employer_company: company profile of the employer.
// - completed: onboarding is finished; the client opens the scenario home.
//
@@ -17,12 +17,14 @@ import (
type Handler struct {
api.UnimplementedHandler
health *HealthHandler
identity *IdentityHandler
consent *ConsentHandler
profile *ProfileHandler
organization *OrganizationHandler
problems *problem.Responder
health *HealthHandler
identity *IdentityHandler
consent *ConsentHandler
profile *ProfileHandler
questionnaire *QuestionnaireHandler
catalog *CatalogHandler
organization *OrganizationHandler
problems *problem.Responder
}
var _ api.Handler = (*Handler)(nil)
@@ -45,6 +47,16 @@ func WithProfile(profile *ProfileHandler) HandlerOption {
return func(handler *Handler) { handler.profile = profile }
}
// WithQuestionnaire serves the candidate's questionnaire and self-assessment.
func WithQuestionnaire(questionnaire *QuestionnaireHandler) HandlerOption {
return func(handler *Handler) { handler.questionnaire = questionnaire }
}
// WithCatalog serves the public specialization catalog and bank availability.
func WithCatalog(catalog *CatalogHandler) HandlerOption {
return func(handler *Handler) { handler.catalog = catalog }
}
// WithOrganization serves company profiles and owner operations.
func WithOrganization(organization *OrganizationHandler) HandlerOption {
return func(handler *Handler) { handler.organization = organization }
@@ -0,0 +1,183 @@
package v1
import (
"context"
"fmt"
"slices"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
)
// CatalogOperations reads current assessment availability for the public
// specialization catalog.
type CatalogOperations interface {
SpecializationAvailability(ctx context.Context) ([]domain.SpecializationAvailability, error)
}
// CatalogHandler serves the public, non-personal specialization catalog.
type CatalogHandler struct {
operations CatalogOperations
}
func NewCatalogHandler(operations CatalogOperations) *CatalogHandler {
if operations == nil {
panic("v1.NewCatalogHandler - catalog operations must not be nil")
}
return &CatalogHandler{operations: operations}
}
func (handler *Handler) GetSpecializationCatalog(ctx context.Context) (*api.SpecializationCatalog, error) {
if handler.catalog == nil {
return handler.UnimplementedHandler.GetSpecializationCatalog(ctx)
}
return handler.catalog.GetSpecializationCatalog(ctx)
}
func (handler *CatalogHandler) GetSpecializationCatalog(ctx context.Context) (*api.SpecializationCatalog, error) {
availability, err := handler.operations.SpecializationAvailability(ctx)
if err != nil {
return nil, fmt.Errorf("CatalogHandler.GetSpecializationCatalog - read availability: %w", err)
}
catalog, err := buildSpecializationCatalog(availability)
if err != nil {
return nil, fmt.Errorf("CatalogHandler.GetSpecializationCatalog - build catalog: %w", err)
}
return catalog, nil
}
type catalogSpecializationDefinition struct {
code domain.SpecializationCode
title string
}
type catalogDirectionDefinition struct {
code api.DirectionCode
title string
specializations []catalogSpecializationDefinition
}
var catalogDirectionDefinitions = []catalogDirectionDefinition{
{
code: api.DirectionCodeDevelopment, title: "Разработка",
specializations: []catalogSpecializationDefinition{
{code: domain.SpecializationBackend, title: "Backend"},
{code: domain.SpecializationFrontend, title: "Frontend"},
{code: domain.SpecializationMobile, title: "Mobile"},
},
},
{
code: api.DirectionCodeInfrastructure, title: "Инфраструктура",
specializations: []catalogSpecializationDefinition{
{code: domain.SpecializationNetworkEngineer, title: "Сетевой инженер"},
{code: domain.SpecializationDevopsSRE, title: "DevOps/SRE"},
},
},
{
code: api.DirectionCodeData, title: "Данные",
specializations: []catalogSpecializationDefinition{
{code: domain.SpecializationDataAnalyst, title: "Аналитик данных"},
{code: domain.SpecializationDSML, title: "DS/ML"},
},
},
{
code: api.DirectionCodeSecurity, title: "Безопасность",
specializations: []catalogSpecializationDefinition{
{code: domain.SpecializationInformationSecurity, title: "Информационная безопасность"},
},
},
{
code: api.DirectionCodeQuality, title: "Качество",
specializations: []catalogSpecializationDefinition{
{code: domain.SpecializationQA, title: "QA"},
},
},
}
var catalogGradeDefinitions = []api.CatalogGrade{
{Code: api.GradeCodeIntern, Title: "Стажер"},
{Code: api.GradeCodeJunior, Title: "Junior"},
{Code: api.GradeCodeMiddle, Title: "Middle"},
{Code: api.GradeCodeSenior, Title: "Senior"},
}
func buildSpecializationCatalog(availability []domain.SpecializationAvailability) (*api.SpecializationCatalog, error) {
bySpecialization := make(map[domain.SpecializationCode]domain.SpecializationAvailability, len(availability))
for _, item := range availability {
if !item.Specialization.IsKnown() {
return nil, fmt.Errorf("buildSpecializationCatalog - availability has an unknown specialization")
}
if _, exists := bySpecialization[item.Specialization]; exists {
return nil, fmt.Errorf("buildSpecializationCatalog - availability repeats a specialization")
}
if err := validateCatalogAvailability(item); err != nil {
return nil, err
}
bySpecialization[item.Specialization] = item
}
directions := make([]api.CatalogDirection, 0, len(catalogDirectionDefinitions))
for _, definition := range catalogDirectionDefinitions {
items := make([]api.CatalogSpecialization, 0, len(definition.specializations))
for _, specialization := range definition.specializations {
items = append(items, catalogSpecializationResponse(specialization, bySpecialization[specialization.code]))
}
directions = append(directions, api.CatalogDirection{
Code: definition.code, Title: definition.title, Specializations: items,
})
}
return &api.SpecializationCatalog{Directions: directions, Grades: slices.Clone(catalogGradeDefinitions)}, nil
}
func validateCatalogAvailability(item domain.SpecializationAvailability) error {
if len(item.Grades) == 0 && len(item.TaskLanguages) > 0 {
return fmt.Errorf("validateCatalogAvailability - unavailable specialization has task languages")
}
seenGrades := make(map[domain.GradeCode]struct{}, len(item.Grades))
for _, grade := range item.Grades {
if !grade.IsKnown() {
return fmt.Errorf("validateCatalogAvailability - availability has an unknown grade")
}
if _, exists := seenGrades[grade]; exists {
return fmt.Errorf("validateCatalogAvailability - availability repeats a grade")
}
seenGrades[grade] = struct{}{}
}
seenLanguages := make(map[domain.TaskLanguageCode]struct{}, len(item.TaskLanguages))
for _, language := range item.TaskLanguages {
if !language.IsKnown() {
return fmt.Errorf("validateCatalogAvailability - availability has an unknown task language")
}
if _, exists := seenLanguages[language]; exists {
return fmt.Errorf("validateCatalogAvailability - availability repeats a task language")
}
seenLanguages[language] = struct{}{}
}
return nil
}
func catalogSpecializationResponse(
definition catalogSpecializationDefinition,
availability domain.SpecializationAvailability,
) api.CatalogSpecialization {
grades := make([]api.GradeCode, 0, len(availability.Grades))
for _, grade := range availability.Grades {
grades = append(grades, api.GradeCode(grade))
}
languages := make([]api.TaskLanguage, 0, len(availability.TaskLanguages))
for _, language := range availability.TaskLanguages {
languages = append(languages, api.TaskLanguage(language))
}
status := api.TestAvailabilityStatusInDevelopment
note := api.NewNilString("Тест в разработке.")
if len(grades) > 0 {
status = api.TestAvailabilityStatusAvailable
note.SetToNull()
}
return api.CatalogSpecialization{
Code: api.SpecializationCode(definition.code), Title: definition.title,
TestAvailability: api.TestAvailability{
Status: status, Grades: grades, TaskLanguages: languages, Note: note,
},
}
}
@@ -0,0 +1,98 @@
package v1
import (
"context"
"errors"
"testing"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
)
type catalogTestOperations struct {
availability []domain.SpecializationAvailability
err error
}
func (operations catalogTestOperations) SpecializationAvailability(context.Context) ([]domain.SpecializationAvailability, error) {
return operations.availability, operations.err
}
func TestCatalogHandlerBuildsStaticCatalogFromCurrentBankAvailability(t *testing.T) {
handler := NewCatalogHandler(catalogTestOperations{availability: []domain.SpecializationAvailability{{
Specialization: domain.SpecializationBackend,
Grades: []domain.GradeCode{domain.GradeJunior, domain.GradeSenior},
TaskLanguages: []domain.TaskLanguageCode{domain.TaskLanguageGo},
}}})
catalog, err := handler.GetSpecializationCatalog(context.Background())
if err != nil {
t.Fatalf("GetSpecializationCatalog() error = %v", err)
}
if len(catalog.Directions) != 5 || len(catalog.Grades) != 4 {
t.Fatalf("catalog has %d directions and %d grades, want 5 and 4", len(catalog.Directions), len(catalog.Grades))
}
backend := catalog.Directions[0].Specializations[0]
if backend.Code != api.SpecializationCodeBackend || backend.TestAvailability.Status != api.TestAvailabilityStatusAvailable ||
len(backend.TestAvailability.Grades) != 2 || backend.TestAvailability.Grades[0] != api.GradeCodeJunior ||
len(backend.TestAvailability.TaskLanguages) != 1 || backend.TestAvailability.TaskLanguages[0] != api.TaskLanguageGo ||
!backend.TestAvailability.Note.IsNull() {
t.Fatalf("Backend availability = %+v, want live junior/senior Go bank", backend.TestAvailability)
}
dsml := catalog.Directions[2].Specializations[1]
if dsml.Code != api.SpecializationCodeDsMl || dsml.TestAvailability.Status != api.TestAvailabilityStatusInDevelopment ||
len(dsml.TestAvailability.Grades) != 0 || dsml.TestAvailability.Grades == nil ||
len(dsml.TestAvailability.TaskLanguages) != 0 || dsml.TestAvailability.TaskLanguages == nil {
t.Fatalf("DS/ML availability = %+v, want in-development with empty arrays", dsml.TestAvailability)
}
if note, ok := dsml.TestAvailability.Note.Get(); !ok || note != "Тест в разработке." {
t.Fatalf("DS/ML note = %q, set %v; want fixed development note", note, ok)
}
}
func TestCatalogHandlerReturnsOperationFailure(t *testing.T) {
wantErr := errors.New("catalog unavailable")
handler := NewCatalogHandler(catalogTestOperations{err: wantErr})
if _, err := handler.GetSpecializationCatalog(context.Background()); !errors.Is(err, wantErr) {
t.Fatalf("GetSpecializationCatalog() error = %v, want wrapped operation error", err)
}
}
func TestBuildSpecializationCatalogFailsClosedOnMalformedAvailability(t *testing.T) {
tests := []struct {
name string
availability []domain.SpecializationAvailability
}{
{
name: "unknown specialization",
availability: []domain.SpecializationAvailability{{
Specialization: "unknown", Grades: []domain.GradeCode{domain.GradeJunior},
}},
},
{
name: "duplicate specialization",
availability: []domain.SpecializationAvailability{
{Specialization: domain.SpecializationBackend},
{Specialization: domain.SpecializationBackend},
},
},
{
name: "unknown grade",
availability: []domain.SpecializationAvailability{{
Specialization: domain.SpecializationBackend, Grades: []domain.GradeCode{"lead"},
}},
},
{
name: "language without published grade",
availability: []domain.SpecializationAvailability{{
Specialization: domain.SpecializationBackend, TaskLanguages: []domain.TaskLanguageCode{domain.TaskLanguageGo},
}},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if _, err := buildSpecializationCatalog(test.availability); err == nil {
t.Fatal("buildSpecializationCatalog() error = nil, want malformed availability error")
}
})
}
}
@@ -0,0 +1,189 @@
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"
questionnaireusecase "lincodex/backend/internal/usecase/questionnaire"
)
// QuestionnaireOperations reads and version-saves the authenticated
// candidate's private questionnaire.
type QuestionnaireOperations interface {
GetMyQuestionnaire(ctx context.Context, userID uuid.UUID) (domain.CandidateQuestionnaire, error)
SaveMyQuestionnaire(ctx context.Context, userID uuid.UUID, expectedVersion int64, input domain.CandidateQuestionnaireInput) (domain.CandidateQuestionnaire, error)
}
// QuestionnaireHandler serves a candidate's own questionnaire operations.
type QuestionnaireHandler struct {
operations QuestionnaireOperations
}
func NewQuestionnaireHandler(operations QuestionnaireOperations) *QuestionnaireHandler {
if operations == nil {
panic("v1.NewQuestionnaireHandler - questionnaire operations must not be nil")
}
return &QuestionnaireHandler{operations: operations}
}
func (handler *Handler) GetMyQuestionnaire(ctx context.Context) (api.GetMyQuestionnaireRes, error) {
if handler.questionnaire == nil {
return handler.UnimplementedHandler.GetMyQuestionnaire(ctx)
}
return handler.questionnaire.GetMyQuestionnaire(ctx)
}
func (handler *Handler) SaveMyQuestionnaire(ctx context.Context, request *api.CandidateQuestionnaireUpdate) (api.SaveMyQuestionnaireRes, error) {
if handler.questionnaire == nil {
return handler.UnimplementedHandler.SaveMyQuestionnaire(ctx, request)
}
return handler.questionnaire.SaveMyQuestionnaire(ctx, request)
}
func (handler *QuestionnaireHandler) GetMyQuestionnaire(ctx context.Context) (api.GetMyQuestionnaireRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetMyQuestionnaireUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
questionnaire, err := handler.operations.GetMyQuestionnaire(ctx, principal.UserID)
if err != nil {
return questionnaireReadFailure(ctx, err)
}
return &api.CandidateQuestionnaireHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: candidateQuestionnaireResponse(questionnaire),
}, nil
}
func (handler *QuestionnaireHandler) SaveMyQuestionnaire(
ctx context.Context,
request *api.CandidateQuestionnaireUpdate,
) (api.SaveMyQuestionnaireRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.SaveMyQuestionnaireUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return (*api.SaveMyQuestionnaireBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
questionnaire, err := handler.operations.SaveMyQuestionnaire(
ctx, principal.UserID, int64(request.ExpectedVersion), candidateQuestionnaireInput(request),
)
if err != nil {
return questionnaireSaveFailure(ctx, err)
}
return &api.CandidateQuestionnaireHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: candidateQuestionnaireResponse(questionnaire),
}, nil
}
func questionnaireReadFailure(ctx context.Context, err error) (api.GetMyQuestionnaireRes, error) {
switch {
case errors.Is(err, questionnaireusecase.ErrForbidden), errors.Is(err, questionnaireusecase.ErrEmailNotVerified):
return (*api.GetMyQuestionnaireForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrUserNotFound):
return (*api.GetMyQuestionnaireUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
default:
return nil, err
}
}
func questionnaireSaveFailure(ctx context.Context, err error) (api.SaveMyQuestionnaireRes, error) {
switch {
case errors.Is(err, domain.ErrCandidateQuestionnaireVersionConflict), errors.Is(err, outbound.ErrCandidateQuestionnaireVersionConflict):
return (*api.SaveMyQuestionnairePreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case errors.Is(err, questionnaireusecase.ErrForbidden), errors.Is(err, questionnaireusecase.ErrEmailNotVerified):
return (*api.SaveMyQuestionnaireForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrUserNotFound):
return (*api.SaveMyQuestionnaireUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
case errors.Is(err, domain.ErrInvalidCandidateQuestionnaire):
fieldError, ok := errors.AsType[*domain.CandidateQuestionnaireFieldError](err)
if !ok {
return (*api.SaveMyQuestionnaireBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
return (*api.SaveMyQuestionnaireBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, fieldError.Pointer).Response), nil
default:
return nil, err
}
}
func candidateQuestionnaireInput(request *api.CandidateQuestionnaireUpdate) domain.CandidateQuestionnaireInput {
input := domain.CandidateQuestionnaireInput{
Specializations: make([]domain.QuestionnaireSpecialization, 0, len(request.Specializations)),
WorkFormats: make([]domain.QuestionnaireWorkFormat, 0, len(request.WorkContext.WorkFormats)),
}
for _, format := range request.WorkContext.WorkFormats {
input.WorkFormats = append(input.WorkFormats, domain.QuestionnaireWorkFormat(format))
}
for _, answer := range request.Specializations {
item := domain.QuestionnaireSpecialization{
Specialization: domain.SpecializationCode(answer.Specialization),
SelfAssessedGrade: domain.GradeCode(answer.SelfAssessedGrade),
TaskLanguages: make([]domain.TaskLanguageCode, 0, len(answer.TaskLanguages)),
Stack: make([]string, 0, len(answer.Stack)),
}
for _, language := range answer.TaskLanguages {
item.TaskLanguages = append(item.TaskLanguages, domain.TaskLanguageCode(language))
}
for _, tag := range answer.Stack {
item.Stack = append(item.Stack, string(tag))
}
if experience, ok := answer.Experience.Get(); ok {
item.Experience = &domain.QuestionnaireExperience{
CommercialMonths: experience.CommercialMonths,
AcademicMonths: experience.AcademicMonths,
}
}
input.Specializations = append(input.Specializations, item)
}
return input
}
func candidateQuestionnaireResponse(questionnaire domain.CandidateQuestionnaire) api.CandidateQuestionnaire {
answers := questionnaire.Specializations()
response := api.CandidateQuestionnaire{
Version: api.QuestionnaireVersion(questionnaire.Version()),
Specializations: make([]api.QuestionnaireSpecialization, 0, len(answers)),
}
response.WorkContext.SetToNull()
response.UpdatedAt.SetToNull()
if questionnaire.Version() > 0 {
workContext := api.WorkContext{WorkFormats: make([]api.WorkFormat, 0, len(questionnaire.WorkFormats()))}
for _, format := range questionnaire.WorkFormats() {
workContext.WorkFormats = append(workContext.WorkFormats, api.WorkFormat(format))
}
response.WorkContext.SetTo(workContext)
response.UpdatedAt.SetTo(api.Timestamp(questionnaire.UpdatedAt()))
}
for _, answer := range answers {
item := api.QuestionnaireSpecialization{
Specialization: api.SpecializationCode(answer.Specialization),
SelfAssessedGrade: api.GradeCode(answer.SelfAssessedGrade),
TaskLanguages: make([]api.TaskLanguage, 0, len(answer.TaskLanguages)),
Stack: make([]api.StackTag, 0, len(answer.Stack)),
}
for _, language := range answer.TaskLanguages {
item.TaskLanguages = append(item.TaskLanguages, api.TaskLanguage(language))
}
for _, tag := range answer.Stack {
item.Stack = append(item.Stack, api.StackTag(tag))
}
if answer.Experience == nil {
item.Experience.SetToNull()
} else {
item.Experience.SetTo(api.CandidateExperience{
CommercialMonths: answer.Experience.CommercialMonths,
AcademicMonths: answer.Experience.AcademicMonths,
})
}
response.Specializations = append(response.Specializations, item)
}
return response
}
@@ -0,0 +1,293 @@
package postgres
import (
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"slices"
"sort"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const assessmentCategoryManifestDomain = "lincodex.assessment.category-manifest.v1\x00"
type assessmentCatalogManifestJSONEntry struct {
FamilyKey string `json:"family_key"`
Version int32 `json:"version"`
ContentSHA256 string `json:"content_sha256"`
}
type assessmentCatalogAggregate struct {
grades map[domain.GradeCode]struct{}
taskLanguages map[domain.TaskLanguageCode]struct{}
}
func (repository assessmentBankRepository) BindCategoryCatalog(
ctx context.Context,
opening domain.AssessmentCategoryOpening,
metadata domain.AssessmentCategoryCatalogMetadata,
) error {
const location = "assessmentBankRepository.BindCategoryCatalog"
if opening.ID == uuid.Nil || metadata.IsZero() {
return fmt.Errorf("%s - opening and reviewed metadata must be set: %w", location, domain.ErrInvalidAssessmentFamily)
}
rows, err := repository.queries.ReadPublishedAssessmentCategoryManifest(ctx, string(opening.Category))
if err != nil {
return fmt.Errorf("%s - read published manifest: %w", location, mapAssessmentError(err))
}
entries := make([]domain.AssessmentCategoryManifestEntry, 0, len(rows))
for _, row := range rows {
key, err := domain.ParseAssessmentFamilyKey(row.FamilyKey)
if err != nil || row.Version < 1 || len(row.ContentSha256) != sha256.Size {
return fmt.Errorf("%s - published manifest row is invalid: %w", location, domain.ErrInvalidAssessmentFamily)
}
entries = append(entries, domain.AssessmentCategoryManifestEntry{
FamilyKey: key, Version: row.Version, ContentSHA256: slices.Clone(row.ContentSha256),
})
}
fingerprint, err := assessmentCategoryManifestFingerprint(entries)
if err != nil {
return fmt.Errorf("%s - fingerprint published manifest: %w", location, err)
}
if len(entries) < int(opening.RequiredFamilies) {
return fmt.Errorf("%s - published manifest no longer meets opening coverage: %w", location, outbound.ErrAssessmentCoverageInsufficient)
}
if err := repository.queries.InsertAssessmentCategoryCatalogBinding(ctx, sqlc.InsertAssessmentCategoryCatalogBindingParams{
OpeningID: pgUUID(opening.ID), Specialization: string(metadata.Specialization()),
Grade: string(metadata.Grade()), TaskLanguages: questionnaireTaskLanguageStrings(metadata.TaskLanguages()),
PublishedManifestSha256: fingerprint[:], ReviewedBy: string(opening.OpenedBy),
}); err != nil {
return fmt.Errorf("%s - insert reviewed binding: %w", location, mapAssessmentCatalogError(err))
}
return nil
}
func (repository assessmentBankRepository) ListCurrentSpecializationAvailability(
ctx context.Context,
) ([]domain.SpecializationAvailability, error) {
const location = "assessmentBankRepository.ListCurrentSpecializationAvailability"
rows, err := repository.queries.ListCurrentSpecializationAvailability(ctx)
if err != nil {
return nil, fmt.Errorf("%s - select current bank projection: %w", location, mapAssessmentError(err))
}
aggregates := make(map[domain.SpecializationCode]*assessmentCatalogAggregate)
for _, row := range rows {
metadata, available, err := currentAssessmentCatalogMetadata(row)
if err != nil {
return nil, fmt.Errorf("%s - validate current binding: %w", location, err)
}
if !available {
continue
}
addAssessmentCatalogMetadata(aggregates, metadata)
}
return buildAssessmentCatalogAvailability(aggregates), nil
}
func currentAssessmentCatalogMetadata(
row sqlc.ListCurrentSpecializationAvailabilityRow,
) (domain.AssessmentCategoryCatalogMetadata, bool, error) {
if !row.EffectivePolicyID.Valid || row.EffectivePolicyID.Bytes != row.PolicyVersionID.Bytes ||
row.PublishedCount < row.RequiredFamilies {
return domain.AssessmentCategoryCatalogMetadata{}, false, nil
}
entries, err := decodeAssessmentCategoryManifest(row.PublishedManifest)
if err != nil {
return domain.AssessmentCategoryCatalogMetadata{}, false, fmt.Errorf("decode published manifest: %w", err)
}
if len(entries) != int(row.PublishedCount) {
return domain.AssessmentCategoryCatalogMetadata{}, false, fmt.Errorf("published manifest count is inconsistent: %w", domain.ErrInvalidAssessmentFamily)
}
fingerprint, err := assessmentCategoryManifestFingerprint(entries)
if err != nil {
return domain.AssessmentCategoryCatalogMetadata{}, false, fmt.Errorf("fingerprint published manifest: %w", err)
}
if !slices.Equal(fingerprint[:], row.PublishedManifestSha256) {
return domain.AssessmentCategoryCatalogMetadata{}, false, nil
}
metadata, err := domain.NewAssessmentCategoryCatalogMetadata(
domain.SpecializationCode(row.Specialization), domain.GradeCode(row.Grade), questionnaireTaskLanguages(row.TaskLanguages),
)
if err != nil {
return domain.AssessmentCategoryCatalogMetadata{}, false, fmt.Errorf("restore reviewed catalog binding: %w", err)
}
return metadata, true, nil
}
func addAssessmentCatalogMetadata(
aggregates map[domain.SpecializationCode]*assessmentCatalogAggregate,
metadata domain.AssessmentCategoryCatalogMetadata,
) {
aggregate := aggregates[metadata.Specialization()]
if aggregate == nil {
aggregate = &assessmentCatalogAggregate{
grades: make(map[domain.GradeCode]struct{}), taskLanguages: make(map[domain.TaskLanguageCode]struct{}),
}
aggregates[metadata.Specialization()] = aggregate
}
aggregate.grades[metadata.Grade()] = struct{}{}
for _, language := range metadata.TaskLanguages() {
aggregate.taskLanguages[language] = struct{}{}
}
}
func buildAssessmentCatalogAvailability(
aggregates map[domain.SpecializationCode]*assessmentCatalogAggregate,
) []domain.SpecializationAvailability {
availability := make([]domain.SpecializationAvailability, 0, len(aggregates))
for specialization, aggregate := range aggregates {
grades := make([]domain.GradeCode, 0, len(aggregate.grades))
for grade := range aggregate.grades {
grades = append(grades, grade)
}
sort.Slice(grades, func(i, j int) bool {
return questionnaireGradeRank(grades[i]) < questionnaireGradeRank(grades[j])
})
languages := make([]domain.TaskLanguageCode, 0, len(aggregate.taskLanguages))
for language := range aggregate.taskLanguages {
languages = append(languages, language)
}
sort.Slice(languages, func(i, j int) bool {
return questionnaireTaskLanguageRank(languages[i]) < questionnaireTaskLanguageRank(languages[j])
})
availability = append(availability, domain.SpecializationAvailability{
Specialization: specialization, Grades: grades, TaskLanguages: languages,
})
}
sort.Slice(availability, func(i, j int) bool {
return availability[i].Specialization < availability[j].Specialization
})
return availability
}
func decodeAssessmentCategoryManifest(encoded string) ([]domain.AssessmentCategoryManifestEntry, error) {
var rows []assessmentCatalogManifestJSONEntry
if err := json.Unmarshal([]byte(encoded), &rows); err != nil {
return nil, fmt.Errorf("postgres.decodeAssessmentCategoryManifest - decode JSON: %w", domain.ErrInvalidAssessmentFamily)
}
entries := make([]domain.AssessmentCategoryManifestEntry, 0, len(rows))
for _, row := range rows {
key, err := domain.ParseAssessmentFamilyKey(row.FamilyKey)
if err != nil || row.Version < 1 {
return nil, fmt.Errorf("postgres.decodeAssessmentCategoryManifest - manifest identity is invalid: %w", domain.ErrInvalidAssessmentFamily)
}
digest, err := hex.DecodeString(row.ContentSHA256)
if err != nil || len(digest) != sha256.Size {
return nil, fmt.Errorf("postgres.decodeAssessmentCategoryManifest - content hash is invalid: %w", domain.ErrInvalidAssessmentFamily)
}
entries = append(entries, domain.AssessmentCategoryManifestEntry{
FamilyKey: key, Version: row.Version, ContentSHA256: digest,
})
}
return entries, nil
}
func assessmentCategoryManifestFingerprint(entries []domain.AssessmentCategoryManifestEntry) ([sha256.Size]byte, error) {
const location = "postgres.assessmentCategoryManifestFingerprint"
if len(entries) == 0 {
return [sha256.Size]byte{}, fmt.Errorf("%s - manifest must contain a published family: %w", location, domain.ErrInvalidAssessmentFamily)
}
ordered := slices.Clone(entries)
sort.Slice(ordered, func(i, j int) bool {
if ordered[i].FamilyKey == ordered[j].FamilyKey {
return ordered[i].Version < ordered[j].Version
}
return ordered[i].FamilyKey < ordered[j].FamilyKey
})
canonical := []byte(assessmentCategoryManifestDomain)
for index, entry := range ordered {
if entry.Version < 1 || len(entry.ContentSHA256) != sha256.Size {
return [sha256.Size]byte{}, fmt.Errorf("%s - entry identity or hash is invalid: %w", location, domain.ErrInvalidAssessmentFamily)
}
if index > 0 && ordered[index-1].FamilyKey == entry.FamilyKey {
return [sha256.Size]byte{}, fmt.Errorf("%s - a family appears more than once: %w", location, domain.ErrInvalidAssessmentFamily)
}
key := []byte(entry.FamilyKey)
keyLength := uint64(len(key))
if len(key) > 64 || keyLength > uint64(^uint32(0)) {
return [sha256.Size]byte{}, fmt.Errorf("%s - family key exceeds its validated bound: %w", location, domain.ErrInvalidAssessmentFamily)
}
canonical = binary.BigEndian.AppendUint32(canonical, uint32(keyLength))
canonical = append(canonical, key...)
canonical = binary.BigEndian.AppendUint32(canonical, uint32(entry.Version))
canonical = append(canonical, entry.ContentSHA256...)
}
return sha256.Sum256(canonical), nil
}
func questionnaireTaskLanguageStrings(languages []domain.TaskLanguageCode) []string {
values := make([]string, len(languages))
for index, language := range languages {
values[index] = string(language)
}
return values
}
func questionnaireTaskLanguages(values []string) []domain.TaskLanguageCode {
languages := make([]domain.TaskLanguageCode, len(values))
for index, language := range values {
languages[index] = domain.TaskLanguageCode(language)
}
return languages
}
func questionnaireGradeRank(grade domain.GradeCode) int {
switch grade {
case domain.GradeIntern:
return 0
case domain.GradeJunior:
return 1
case domain.GradeMiddle:
return 2
case domain.GradeSenior:
return 3
default:
return 4
}
}
func questionnaireTaskLanguageRank(language domain.TaskLanguageCode) int {
switch language {
case domain.TaskLanguagePython:
return 0
case domain.TaskLanguageGo:
return 1
default:
return 2
}
}
func mapAssessmentCatalogError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
switch {
case pgError.Code == checkViolationCode && slices.Contains([]string{
"assessment_category_catalog_bindings_specialization", "assessment_category_catalog_bindings_grade",
"assessment_category_catalog_bindings_languages", "assessment_category_catalog_bindings_reviewer",
"assessment_category_catalog_bindings_manifest_hash", "assessment_category_catalog_bindings_current_opening",
"assessment_category_catalog_bindings_policy_current",
"assessment_category_catalog_bindings_coverage",
}, pgError.ConstraintName):
return fmt.Errorf("postgres.mapAssessmentCatalogError - violate constraint %s: %w", pgError.ConstraintName, domain.ErrInvalidAssessmentFamily)
case pgError.Code == foreignKeyViolationCode && slices.Contains([]string{
"assessment_category_catalog_bindings_opening", "assessment_category_catalog_bindings_opening_fkey",
}, pgError.ConstraintName):
return fmt.Errorf("postgres.mapAssessmentCatalogError - violate constraint %s: %w", pgError.ConstraintName, outbound.ErrAssessmentCategoryNotOpen)
case pgError.Code == integrityConstraintViolationCode && pgError.ConstraintName == "assessment_category_catalog_bindings_immutable":
return fmt.Errorf("postgres.mapAssessmentCatalogError - violate constraint %s: %w", pgError.ConstraintName, outbound.ErrAssessmentCatalogBindingImmutable)
default:
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
}
@@ -0,0 +1,268 @@
package postgres
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"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"
)
var _ outbound.CandidateQuestionnaireRepository = candidateQuestionnaireRepository{}
func (unit *UnitOfWork) CandidateQuestionnaires() outbound.CandidateQuestionnaireRepository {
return candidateQuestionnaireRepository{queries: unit.queries}
}
type candidateQuestionnaireRepository struct {
queries *sqlc.Queries
}
type storedQuestionnaireSpecialization struct {
Ordinal int16 `json:"ordinal"`
Specialization string `json:"specialization"`
SelfAssessedGrade string `json:"self_assessed_grade"`
TaskLanguages []string `json:"task_languages"`
Stack []string `json:"stack"`
CommercialMonths *int32 `json:"commercial_months"`
AcademicMonths *int32 `json:"academic_months"`
}
func (repository candidateQuestionnaireRepository) Get(ctx context.Context, userID uuid.UUID) (domain.CandidateQuestionnaire, error) {
const location = "candidateQuestionnaireRepository.Get"
if userID == uuid.Nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateQuestionnaire)
}
row, err := repository.queries.ReadCandidateQuestionnaire(ctx, pgUUID(userID))
if errors.Is(err, pgx.ErrNoRows) {
questionnaire, err := domain.EmptyCandidateQuestionnaire(userID)
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - create empty questionnaire: %w", location, err)
}
return questionnaire, nil
}
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - select questionnaire: %w", location, mapCandidateQuestionnaireError(err))
}
answers, err := decodeStoredQuestionnaireSpecializations(row.Specializations)
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - restore stored answers: %w", location, err)
}
stored := domain.StoredCandidateQuestionnaire{
UserID: row.UserID.Bytes, Version: row.Version, Specializations: answers,
WorkFormats: questionnaireWorkFormats(row.WorkFormats), CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time,
}
questionnaire, err := domain.RestoreCandidateQuestionnaire(stored)
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - restore questionnaire: %w", location, err)
}
return questionnaire, nil
}
func (repository candidateQuestionnaireRepository) Save(
ctx context.Context,
expectedVersion int64,
questionnaire domain.CandidateQuestionnaire,
) (domain.CandidateQuestionnaire, error) {
const location = "candidateQuestionnaireRepository.Save"
if questionnaire.IsZero() || questionnaire.UserID() == uuid.Nil || questionnaire.Version() != expectedVersion ||
expectedVersion < 0 || questionnaire.UpdatedAt().IsZero() {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - questionnaire or expected version is invalid: %w", location, domain.ErrInvalidCandidateQuestionnaire)
}
row, err := repository.advanceQuestionnaireVersion(ctx, expectedVersion, questionnaire)
if errors.Is(err, pgx.ErrNoRows) {
return repository.readQuestionnaireWinner(ctx, questionnaire)
}
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - advance version: %w", location, mapCandidateQuestionnaireError(err))
}
return repository.replaceQuestionnaireAnswers(ctx, questionnaire, row)
}
func (repository candidateQuestionnaireRepository) advanceQuestionnaireVersion(
ctx context.Context,
expectedVersion int64,
questionnaire domain.CandidateQuestionnaire,
) (sqlc.CandidateQuestionnaire, error) {
workFormats := questionnaireWorkFormatStrings(questionnaire.WorkFormats())
if expectedVersion == 0 {
return repository.queries.InsertCandidateQuestionnaire(ctx, sqlc.InsertCandidateQuestionnaireParams{
UserID: pgUUID(questionnaire.UserID()), WorkFormats: workFormats, At: pgTime(questionnaire.UpdatedAt()),
})
}
return repository.queries.AdvanceCandidateQuestionnaireVersion(ctx, sqlc.AdvanceCandidateQuestionnaireVersionParams{
UserID: pgUUID(questionnaire.UserID()), ExpectedVersion: expectedVersion,
WorkFormats: workFormats, At: pgTime(questionnaire.UpdatedAt()),
})
}
func (repository candidateQuestionnaireRepository) readQuestionnaireWinner(
ctx context.Context,
questionnaire domain.CandidateQuestionnaire,
) (domain.CandidateQuestionnaire, error) {
const location = "candidateQuestionnaireRepository.readQuestionnaireWinner"
winner, err := repository.Get(ctx, questionnaire.UserID())
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - read winner after compare-and-swap loss: %w", location, err)
}
if !winner.SameContent(questionnaire) {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - another questionnaire content won the version: %w", location, outbound.ErrCandidateQuestionnaireVersionConflict)
}
return winner, nil
}
func (repository candidateQuestionnaireRepository) replaceQuestionnaireAnswers(
ctx context.Context,
questionnaire domain.CandidateQuestionnaire,
row sqlc.CandidateQuestionnaire,
) (domain.CandidateQuestionnaire, error) {
const location = "candidateQuestionnaireRepository.replaceQuestionnaireAnswers"
if err := repository.queries.DeleteCandidateQuestionnaireSpecializations(ctx, pgUUID(questionnaire.UserID())); err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - delete old specialization answers: %w", location, mapCandidateQuestionnaireError(err))
}
answers := questionnaire.Specializations()
for index, answer := range answers {
ordinal, err := questionnaireSpecializationOrdinal(index)
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - encode answer order: %w", location, err)
}
commercialMonths, academicMonths := questionnaireExperienceMonths(answer.Experience)
if err := repository.queries.InsertCandidateQuestionnaireSpecialization(ctx, sqlc.InsertCandidateQuestionnaireSpecializationParams{
UserID: pgUUID(questionnaire.UserID()), Ordinal: ordinal,
Specialization: string(answer.Specialization), SelfAssessedGrade: string(answer.SelfAssessedGrade),
TaskLanguages: questionnaireTaskLanguageStrings(answer.TaskLanguages), Stack: slices.Clone(answer.Stack),
CommercialMonths: commercialMonths, AcademicMonths: academicMonths,
}); err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - insert specialization answer: %w", location, mapCandidateQuestionnaireError(err))
}
}
stored := domain.StoredCandidateQuestionnaire{
UserID: questionnaire.UserID(), Version: row.Version,
Specializations: answers, WorkFormats: questionnaire.WorkFormats(),
CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time,
}
result, err := domain.RestoreCandidateQuestionnaire(stored)
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - restore saved questionnaire: %w", location, err)
}
return result, nil
}
func (repository candidateQuestionnaireRepository) AdvanceOnboarding(ctx context.Context, userID uuid.UUID, at time.Time) error {
const location = "candidateQuestionnaireRepository.AdvanceOnboarding"
if userID == uuid.Nil || at.IsZero() {
return fmt.Errorf("%s - user ID and time must be set: %w", location, domain.ErrInvalidCandidateQuestionnaire)
}
if err := repository.queries.AdvanceCandidateOnboardingAfterQuestionnaire(ctx, sqlc.AdvanceCandidateOnboardingAfterQuestionnaireParams{
UserID: pgUUID(userID), At: pgTime(at),
}); err != nil {
return fmt.Errorf("%s - update onboarding: %w", location, mapCandidateQuestionnaireError(err))
}
return nil
}
func decodeStoredQuestionnaireSpecializations(encoded string) ([]domain.QuestionnaireSpecialization, error) {
const location = "postgres.decodeStoredQuestionnaireSpecializations"
decoder := json.NewDecoder(bytes.NewBufferString(encoded))
decoder.DisallowUnknownFields()
var rows []storedQuestionnaireSpecialization
if err := decoder.Decode(&rows); err != nil {
return nil, fmt.Errorf("%s - stored answers have an unexpected shape: %w", location, domain.ErrInvalidCandidateQuestionnaire)
}
if err := decoder.Decode(new(any)); !errors.Is(err, io.EOF) {
return nil, fmt.Errorf("%s - stored answers have trailing data: %w", location, domain.ErrInvalidCandidateQuestionnaire)
}
answers := make([]domain.QuestionnaireSpecialization, 0, len(rows))
for index, row := range rows {
if int(row.Ordinal) != index || (row.CommercialMonths == nil) != (row.AcademicMonths == nil) {
return nil, fmt.Errorf("%s - stored answer order or experience is invalid: %w", location, domain.ErrInvalidCandidateQuestionnaire)
}
answer := domain.QuestionnaireSpecialization{
Specialization: domain.SpecializationCode(row.Specialization),
SelfAssessedGrade: domain.GradeCode(row.SelfAssessedGrade),
TaskLanguages: questionnaireTaskLanguages(row.TaskLanguages),
Stack: slices.Clone(row.Stack),
}
if row.CommercialMonths != nil {
answer.Experience = &domain.QuestionnaireExperience{
CommercialMonths: *row.CommercialMonths,
AcademicMonths: *row.AcademicMonths,
}
}
answers = append(answers, answer)
}
return answers, nil
}
func questionnaireExperienceMonths(experience *domain.QuestionnaireExperience) (pgtype.Int4, pgtype.Int4) {
if experience == nil {
return pgtype.Int4{}, pgtype.Int4{}
}
return pgtype.Int4{Int32: experience.CommercialMonths, Valid: true},
pgtype.Int4{Int32: experience.AcademicMonths, Valid: true}
}
func questionnaireSpecializationOrdinal(index int) (int16, error) {
if index < 0 || index >= 2 {
return 0, fmt.Errorf("postgres.questionnaireSpecializationOrdinal - order is outside the storage range: %w", domain.ErrInvalidCandidateQuestionnaire)
}
return int16(index), nil
}
func questionnaireWorkFormats(values []string) []domain.QuestionnaireWorkFormat {
formats := make([]domain.QuestionnaireWorkFormat, len(values))
for index, value := range values {
formats[index] = domain.QuestionnaireWorkFormat(value)
}
return formats
}
func questionnaireWorkFormatStrings(values []domain.QuestionnaireWorkFormat) []string {
formats := make([]string, len(values))
for index, value := range values {
formats[index] = string(value)
}
return formats
}
func mapCandidateQuestionnaireError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
switch {
case pgError.Code == foreignKeyViolationCode && slices.Contains([]string{
"candidate_questionnaires_user_fkey", "candidate_questionnaire_specializations_user_fkey",
}, pgError.ConstraintName):
return fmt.Errorf("postgres.mapCandidateQuestionnaireError - violate constraint %s: %w", pgError.ConstraintName, outbound.ErrUserNotFound)
case pgError.Code == checkViolationCode && slices.Contains([]string{
"candidate_questionnaires_version_positive", "candidate_questionnaires_work_formats", "candidate_questionnaires_times_ordered",
"candidate_questionnaire_specializations_ordinal",
"candidate_questionnaire_specializations_code", "candidate_questionnaire_specializations_grade",
"candidate_questionnaire_specializations_languages", "candidate_questionnaire_specializations_stack",
"candidate_questionnaire_specializations_experience",
}, pgError.ConstraintName):
return fmt.Errorf("postgres.mapCandidateQuestionnaireError - violate constraint %s: %w", pgError.ConstraintName, domain.ErrInvalidCandidateQuestionnaire)
case pgError.Code == uniqueViolationCode && slices.Contains([]string{
"candidate_questionnaires_pkey", "candidate_questionnaire_specializations_unique_code",
}, pgError.ConstraintName):
if pgError.ConstraintName == "candidate_questionnaire_specializations_unique_code" {
return fmt.Errorf("postgres.mapCandidateQuestionnaireError - violate constraint %s: %w", pgError.ConstraintName, domain.ErrInvalidCandidateQuestionnaire)
}
return outbound.ErrCandidateQuestionnaireVersionConflict
default:
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
}
@@ -0,0 +1,302 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const companyQuotaViewCleanupBatchSize int32 = 100
func (unit *UnitOfWork) CompanyQuotas() outbound.CompanyQuotaRepository {
return companyQuotaRepository{queries: unit.queries}
}
type companyQuotaRepository struct {
queries *sqlc.Queries
}
var _ outbound.CompanyQuotaRepository = companyQuotaRepository{}
func (repository companyQuotaRepository) ReserveInvitation(
ctx context.Context,
quota domain.CompanyQuota,
invitationID uuid.UUID,
) (outbound.CompanyQuotaDecision, error) {
const location = "companyQuotaRepository.ReserveInvitation"
if err := validateCompanyQuota(location, quota); err != nil {
return outbound.CompanyQuotaDecision{}, err
}
if invitationID == uuid.Nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation ID must be set: %w", location, domain.ErrInvalidCompanyQuota)
}
if err := repository.lockAndCheckSnapshot(ctx, location, quota); err != nil {
return outbound.CompanyQuotaDecision{}, err
}
organizationID := pgUUID(quota.OrganizationID())
invitation, err := repository.queries.FindCompanyInvitationQuotaUsage(ctx, sqlc.FindCompanyInvitationQuotaUsageParams{
OrganizationID: organizationID,
InvitationID: pgUUID(invitationID),
})
if err == nil {
if !invitation.Valid || invitation.Bytes != invitationID {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - existing invitation usage did not match its key", location)
}
return outbound.CompanyQuotaDecision{Allowed: true, Reused: true}, nil
}
if !errors.Is(err, pgx.ErrNoRows) {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read invitation usage: %w", location, mapOrganizationError(err))
}
usage, err := repository.queries.CountCompanyInvitationQuotaWindow(ctx, sqlc.CountCompanyInvitationQuotaWindowParams{
OrganizationID: organizationID,
WindowStart: pgTime(quota.InvitationWindowStart()),
})
if err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - count invitation usage: %w", location, mapOrganizationError(err))
}
if usage.UsageCount < 0 {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation usage count is negative", location)
}
if usage.UsageCount >= quota.InvitationLimit() {
earliest, err := quotaWindowEarliest(usage.EarliestAt)
if err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read earliest invitation expiry: %w", location, err)
}
return outbound.CompanyQuotaDecision{RetryAt: earliest.Add(quota.InvitationWindow()).UTC()}, nil
}
if err := repository.queries.InsertCompanyInvitationQuotaUsage(ctx, companyInvitationUsageParams(quota, invitationID)); err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - insert invitation usage: %w", location, mapOrganizationError(err))
}
return outbound.CompanyQuotaDecision{Allowed: true}, nil
}
func (repository companyQuotaRepository) ReserveCardView(
ctx context.Context,
quota domain.CompanyQuota,
candidateID uuid.UUID,
) (outbound.CompanyQuotaDecision, error) {
const location = "companyQuotaRepository.ReserveCardView"
if err := validateCompanyQuota(location, quota); err != nil {
return outbound.CompanyQuotaDecision{}, err
}
if candidateID == uuid.Nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCompanyQuota)
}
if err := repository.lockAndCheckSnapshot(ctx, location, quota); err != nil {
return outbound.CompanyQuotaDecision{}, err
}
organizationID := quota.OrganizationID()
decision, handled, err := repository.reserveExistingCardView(ctx, location, quota, organizationID, candidateID)
if err != nil || handled {
return decision, err
}
return repository.reserveNewCardView(ctx, location, quota, candidateID, organizationID)
}
func (repository companyQuotaRepository) reserveExistingCardView(
ctx context.Context,
location string,
quota domain.CompanyQuota,
organizationID uuid.UUID,
candidateID uuid.UUID,
) (outbound.CompanyQuotaDecision, bool, error) {
existing, findErr := repository.queries.FindCompanyCardViewQuotaUsage(ctx, sqlc.FindCompanyCardViewQuotaUsageParams{
OrganizationID: pgUUID(organizationID),
CandidateID: pgUUID(candidateID),
})
if errors.Is(findErr, pgx.ErrNoRows) {
return outbound.CompanyQuotaDecision{}, false, nil
}
if findErr != nil {
return outbound.CompanyQuotaDecision{}, false, fmt.Errorf("%s - read card-view usage: %w", location, mapOrganizationError(findErr))
}
if !existing.Valid {
return outbound.CompanyQuotaDecision{}, false, fmt.Errorf("%s - existing card-view timestamp is invalid", location)
}
if !existing.Time.After(quota.CardViewWindowStart()) {
return outbound.CompanyQuotaDecision{}, false, nil
}
decision, err := repository.refreshActiveCardView(ctx, location, quota, organizationID, candidateID)
return decision, true, err
}
func (repository companyQuotaRepository) refreshActiveCardView(
ctx context.Context,
location string,
quota domain.CompanyQuota,
organizationID uuid.UUID,
candidateID uuid.UUID,
) (outbound.CompanyQuotaDecision, error) {
updated, err := repository.queries.RefreshCompanyCardViewQuotaUsage(ctx, sqlc.RefreshCompanyCardViewQuotaUsageParams{
LastSeenAt: pgTime(quota.At()),
PolicyVersionID: pgUUID(quota.PolicyVersionID().UUID()),
VerificationLevel: string(quota.VerificationLevel()),
VerificationBasis: string(quota.VerificationBasis()),
VerificationChangedAt: pgTime(quota.VerificationChangedAt()),
QuotaTier: string(quota.Tier()),
OrganizationID: pgUUID(organizationID),
CandidateID: pgUUID(candidateID),
WindowStart: pgTime(quota.CardViewWindowStart()),
})
if err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - refresh card-view usage: %w", location, mapOrganizationError(err))
}
if updated != 1 {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - active card-view usage changed while organization was locked", location)
}
if err := repository.cleanupExpiredCardViews(ctx, location, quota); err != nil {
return outbound.CompanyQuotaDecision{}, err
}
return outbound.CompanyQuotaDecision{Allowed: true, Reused: true}, nil
}
func (repository companyQuotaRepository) reserveNewCardView(
ctx context.Context,
location string,
quota domain.CompanyQuota,
candidateID uuid.UUID,
organizationID uuid.UUID,
) (outbound.CompanyQuotaDecision, error) {
usage, err := repository.queries.CountCompanyCardViewQuotaWindow(ctx, sqlc.CountCompanyCardViewQuotaWindowParams{
OrganizationID: pgUUID(organizationID),
WindowStart: pgTime(quota.CardViewWindowStart()),
})
if err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - count card-view usage: %w", location, mapOrganizationError(err))
}
if usage.UsageCount < 0 {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - card-view usage count is negative", location)
}
if usage.UsageCount >= quota.CardViewLimit() {
earliest, err := quotaWindowEarliest(usage.EarliestAt)
if err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read earliest card-view expiry: %w", location, err)
}
return outbound.CompanyQuotaDecision{RetryAt: earliest.Add(quota.CardViewWindow()).UTC()}, nil
}
if err := repository.queries.SaveCompanyCardViewQuotaUsage(ctx, companyCardViewUsageParams(quota, candidateID)); err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - save card-view usage: %w", location, mapOrganizationError(err))
}
if err := repository.cleanupExpiredCardViews(ctx, location, quota); err != nil {
return outbound.CompanyQuotaDecision{}, err
}
return outbound.CompanyQuotaDecision{Allowed: true}, nil
}
func (repository companyQuotaRepository) lockAndCheckSnapshot(
ctx context.Context,
location string,
quota domain.CompanyQuota,
) error {
organizationID := pgUUID(quota.OrganizationID())
organization, err := repository.queries.LockCompanyQuotaOrganization(ctx, organizationID)
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%s - organization was removed after quota resolution: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
}
if err != nil {
return fmt.Errorf("%s - lock organization: %w", location, mapOrganizationError(err))
}
if !organization.ID.Valid || organization.ID.Bytes != quota.OrganizationID() ||
!organization.VerificationChangedAt.Valid ||
organization.VerificationLevel != string(quota.VerificationLevel()) ||
organization.VerificationBasis != string(quota.VerificationBasis()) ||
!organization.VerificationChangedAt.Time.Equal(quota.VerificationChangedAt()) {
return fmt.Errorf("%s - stored organization trust changed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
}
policy, err := repository.queries.GetEffectivePolicyVersion(ctx, sqlc.GetEffectivePolicyVersionParams{
PolicyKey: string(domain.ProductPolicyKey),
At: pgTime(quota.At()),
})
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%s - no effective product policy remains: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
}
if err != nil {
return fmt.Errorf("%s - recheck effective product policy: %w", location, mapPolicyError(err))
}
if !policy.ID.Valid || policy.ID.Bytes != quota.PolicyVersionID().UUID() || policy.PolicyKey != string(domain.ProductPolicyKey) {
return fmt.Errorf("%s - effective product policy changed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
}
return nil
}
func (repository companyQuotaRepository) cleanupExpiredCardViews(
ctx context.Context,
location string,
quota domain.CompanyQuota,
) error {
_, err := repository.queries.DeleteExpiredCompanyCardViewQuotaUsage(ctx, sqlc.DeleteExpiredCompanyCardViewQuotaUsageParams{
OrganizationID: pgUUID(quota.OrganizationID()),
WindowStart: pgTime(quota.CardViewWindowStart()),
RowLimit: companyQuotaViewCleanupBatchSize,
})
if err != nil {
return fmt.Errorf("%s - clean expired card-view usage: %w", location, mapOrganizationError(err))
}
return nil
}
func validateCompanyQuota(location string, quota domain.CompanyQuota) error {
if quota.IsZero() || quota.OrganizationID() == uuid.Nil || quota.PolicyVersionID().UUID() == uuid.Nil ||
quota.At().IsZero() || quota.At().Unix() < 0 ||
quota.InvitationWindow() <= 0 || quota.InvitationLimit() <= 0 ||
quota.CardViewWindow() <= 0 || quota.CardViewLimit() <= 0 ||
quota.InvitationWindowStart().IsZero() || quota.CardViewWindowStart().IsZero() {
return fmt.Errorf("%s - quota snapshot was not built from an active policy and stored organization: %w", location, domain.ErrInvalidCompanyQuota)
}
return nil
}
func quotaWindowEarliest(value interface{}) (time.Time, error) {
switch timestamp := value.(type) {
case time.Time:
if timestamp.IsZero() {
return time.Time{}, errors.New("window timestamp is zero")
}
return timestamp.UTC(), nil
case *time.Time:
if timestamp == nil || timestamp.IsZero() {
return time.Time{}, errors.New("window timestamp is missing")
}
return timestamp.UTC(), nil
default:
return time.Time{}, errors.New("window timestamp has an unexpected database value")
}
}
func companyInvitationUsageParams(quota domain.CompanyQuota, invitationID uuid.UUID) sqlc.InsertCompanyInvitationQuotaUsageParams {
return sqlc.InsertCompanyInvitationQuotaUsageParams{
OrganizationID: pgUUID(quota.OrganizationID()),
InvitationID: pgUUID(invitationID),
ReservedAt: pgTime(quota.At()),
PolicyVersionID: pgUUID(quota.PolicyVersionID().UUID()),
VerificationLevel: string(quota.VerificationLevel()),
VerificationBasis: string(quota.VerificationBasis()),
VerificationChangedAt: pgTime(quota.VerificationChangedAt()),
QuotaTier: string(quota.Tier()),
}
}
func companyCardViewUsageParams(quota domain.CompanyQuota, candidateID uuid.UUID) sqlc.SaveCompanyCardViewQuotaUsageParams {
return sqlc.SaveCompanyCardViewQuotaUsageParams{
OrganizationID: pgUUID(quota.OrganizationID()),
CandidateID: pgUUID(candidateID),
LastSeenAt: pgTime(quota.At()),
PolicyVersionID: pgUUID(quota.PolicyVersionID().UUID()),
VerificationLevel: string(quota.VerificationLevel()),
VerificationBasis: string(quota.VerificationBasis()),
VerificationChangedAt: pgTime(quota.VerificationChangedAt()),
QuotaTier: string(quota.Tier()),
}
}
@@ -0,0 +1,323 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: company_quota.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const countCompanyCardViewQuotaWindow = `-- name: CountCompanyCardViewQuotaWindow :one
SELECT
count(*)::bigint AS usage_count,
min(last_seen_at) AS earliest_at
FROM company_card_view_quota_usage
WHERE
organization_id = $1
AND last_seen_at > $2
`
type CountCompanyCardViewQuotaWindowParams struct {
OrganizationID pgtype.UUID
WindowStart pgtype.Timestamptz
}
type CountCompanyCardViewQuotaWindowRow struct {
UsageCount int64
EarliestAt interface{}
}
func (q *Queries) CountCompanyCardViewQuotaWindow(ctx context.Context, arg CountCompanyCardViewQuotaWindowParams) (CountCompanyCardViewQuotaWindowRow, error) {
row := q.db.QueryRow(ctx, countCompanyCardViewQuotaWindow, arg.OrganizationID, arg.WindowStart)
var i CountCompanyCardViewQuotaWindowRow
err := row.Scan(&i.UsageCount, &i.EarliestAt)
return i, err
}
const countCompanyInvitationQuotaWindow = `-- name: CountCompanyInvitationQuotaWindow :one
SELECT
count(*)::bigint AS usage_count,
min(reserved_at) AS earliest_at
FROM company_invitation_quota_usage
WHERE
organization_id = $1
AND reserved_at > $2
`
type CountCompanyInvitationQuotaWindowParams struct {
OrganizationID pgtype.UUID
WindowStart pgtype.Timestamptz
}
type CountCompanyInvitationQuotaWindowRow struct {
UsageCount int64
EarliestAt interface{}
}
func (q *Queries) CountCompanyInvitationQuotaWindow(ctx context.Context, arg CountCompanyInvitationQuotaWindowParams) (CountCompanyInvitationQuotaWindowRow, error) {
row := q.db.QueryRow(ctx, countCompanyInvitationQuotaWindow, arg.OrganizationID, arg.WindowStart)
var i CountCompanyInvitationQuotaWindowRow
err := row.Scan(&i.UsageCount, &i.EarliestAt)
return i, err
}
const deleteExpiredCompanyCardViewQuotaUsage = `-- name: DeleteExpiredCompanyCardViewQuotaUsage :execrows
WITH expired AS (
SELECT quota_usage.organization_id, quota_usage.candidate_id
FROM company_card_view_quota_usage AS quota_usage
WHERE
quota_usage.organization_id = $1
AND quota_usage.last_seen_at <= $2
ORDER BY quota_usage.last_seen_at, quota_usage.candidate_id
LIMIT $3::integer
)
DELETE FROM company_card_view_quota_usage AS usage
USING expired
WHERE
usage.organization_id = expired.organization_id
AND usage.candidate_id = expired.candidate_id
`
type DeleteExpiredCompanyCardViewQuotaUsageParams struct {
OrganizationID pgtype.UUID
WindowStart pgtype.Timestamptz
RowLimit int32
}
func (q *Queries) DeleteExpiredCompanyCardViewQuotaUsage(ctx context.Context, arg DeleteExpiredCompanyCardViewQuotaUsageParams) (int64, error) {
result, err := q.db.Exec(ctx, deleteExpiredCompanyCardViewQuotaUsage, arg.OrganizationID, arg.WindowStart, arg.RowLimit)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const findCompanyCardViewQuotaUsage = `-- name: FindCompanyCardViewQuotaUsage :one
SELECT last_seen_at
FROM company_card_view_quota_usage
WHERE
organization_id = $1
AND candidate_id = $2
FOR UPDATE
`
type FindCompanyCardViewQuotaUsageParams struct {
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
}
func (q *Queries) FindCompanyCardViewQuotaUsage(ctx context.Context, arg FindCompanyCardViewQuotaUsageParams) (pgtype.Timestamptz, error) {
row := q.db.QueryRow(ctx, findCompanyCardViewQuotaUsage, arg.OrganizationID, arg.CandidateID)
var last_seen_at pgtype.Timestamptz
err := row.Scan(&last_seen_at)
return last_seen_at, err
}
const findCompanyInvitationQuotaUsage = `-- name: FindCompanyInvitationQuotaUsage :one
SELECT invitation_id
FROM company_invitation_quota_usage
WHERE
organization_id = $1
AND invitation_id = $2
FOR UPDATE
`
type FindCompanyInvitationQuotaUsageParams struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
}
func (q *Queries) FindCompanyInvitationQuotaUsage(ctx context.Context, arg FindCompanyInvitationQuotaUsageParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, findCompanyInvitationQuotaUsage, arg.OrganizationID, arg.InvitationID)
var invitation_id pgtype.UUID
err := row.Scan(&invitation_id)
return invitation_id, err
}
const insertCompanyInvitationQuotaUsage = `-- name: InsertCompanyInvitationQuotaUsage :exec
INSERT INTO company_invitation_quota_usage (
organization_id,
invitation_id,
reserved_at,
policy_version_id,
verification_level,
verification_basis,
verification_changed_at,
quota_tier
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8
)
`
type InsertCompanyInvitationQuotaUsageParams struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
ReservedAt pgtype.Timestamptz
PolicyVersionID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
QuotaTier string
}
func (q *Queries) InsertCompanyInvitationQuotaUsage(ctx context.Context, arg InsertCompanyInvitationQuotaUsageParams) error {
_, err := q.db.Exec(ctx, insertCompanyInvitationQuotaUsage,
arg.OrganizationID,
arg.InvitationID,
arg.ReservedAt,
arg.PolicyVersionID,
arg.VerificationLevel,
arg.VerificationBasis,
arg.VerificationChangedAt,
arg.QuotaTier,
)
return err
}
const lockCompanyQuotaOrganization = `-- name: LockCompanyQuotaOrganization :one
SELECT
id,
verification_level,
verification_basis,
verification_changed_at
FROM organizations
WHERE id = $1
FOR UPDATE
`
type LockCompanyQuotaOrganizationRow struct {
ID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
}
// Writers lock the organization first, then invitation/card-view state, and
// finally usage rows. The organization lock serializes quota decisions for
// the tenant and makes the subsequent count and insert atomic.
func (q *Queries) LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error) {
row := q.db.QueryRow(ctx, lockCompanyQuotaOrganization, organizationID)
var i LockCompanyQuotaOrganizationRow
err := row.Scan(
&i.ID,
&i.VerificationLevel,
&i.VerificationBasis,
&i.VerificationChangedAt,
)
return i, err
}
const refreshCompanyCardViewQuotaUsage = `-- name: RefreshCompanyCardViewQuotaUsage :execrows
UPDATE company_card_view_quota_usage
SET
last_seen_at = greatest(last_seen_at, $1),
policy_version_id = $2,
verification_level = $3,
verification_basis = $4,
verification_changed_at = $5,
quota_tier = $6
WHERE
organization_id = $7
AND candidate_id = $8
AND last_seen_at > $9
`
type RefreshCompanyCardViewQuotaUsageParams struct {
LastSeenAt pgtype.Timestamptz
PolicyVersionID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
QuotaTier string
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
WindowStart pgtype.Timestamptz
}
func (q *Queries) RefreshCompanyCardViewQuotaUsage(ctx context.Context, arg RefreshCompanyCardViewQuotaUsageParams) (int64, error) {
result, err := q.db.Exec(ctx, refreshCompanyCardViewQuotaUsage,
arg.LastSeenAt,
arg.PolicyVersionID,
arg.VerificationLevel,
arg.VerificationBasis,
arg.VerificationChangedAt,
arg.QuotaTier,
arg.OrganizationID,
arg.CandidateID,
arg.WindowStart,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const saveCompanyCardViewQuotaUsage = `-- name: SaveCompanyCardViewQuotaUsage :exec
INSERT INTO company_card_view_quota_usage (
organization_id,
candidate_id,
last_seen_at,
policy_version_id,
verification_level,
verification_basis,
verification_changed_at,
quota_tier
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8
)
ON CONFLICT (organization_id, candidate_id)
DO UPDATE SET
last_seen_at = greatest(
company_card_view_quota_usage.last_seen_at,
EXCLUDED.last_seen_at
),
policy_version_id = EXCLUDED.policy_version_id,
verification_level = EXCLUDED.verification_level,
verification_basis = EXCLUDED.verification_basis,
verification_changed_at = EXCLUDED.verification_changed_at,
quota_tier = EXCLUDED.quota_tier
`
type SaveCompanyCardViewQuotaUsageParams struct {
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
LastSeenAt pgtype.Timestamptz
PolicyVersionID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
QuotaTier string
}
func (q *Queries) SaveCompanyCardViewQuotaUsage(ctx context.Context, arg SaveCompanyCardViewQuotaUsageParams) error {
_, err := q.db.Exec(ctx, saveCompanyCardViewQuotaUsage,
arg.OrganizationID,
arg.CandidateID,
arg.LastSeenAt,
arg.PolicyVersionID,
arg.VerificationLevel,
arg.VerificationBasis,
arg.VerificationChangedAt,
arg.QuotaTier,
)
return err
}
@@ -16,6 +16,16 @@ type AccountDeletionRequest struct {
CompletedAt pgtype.Timestamptz
}
type AssessmentCategoryCatalogBinding struct {
OpeningID pgtype.UUID
Specialization string
Grade string
TaskLanguages []string
PublishedManifestSha256 []byte
ReviewedBy string
ReviewedAt pgtype.Timestamptz
}
type AssessmentCategoryOpening struct {
ID pgtype.UUID
Category string
@@ -124,6 +134,25 @@ type CandidatePublication struct {
UpdatedAt pgtype.Timestamptz
}
type CandidateQuestionnaire struct {
UserID pgtype.UUID
Version int64
WorkFormats []string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type CandidateQuestionnaireSpecialization struct {
UserID pgtype.UUID
Ordinal int16
Specialization string
SelfAssessedGrade string
TaskLanguages []string
Stack []string
CommercialMonths pgtype.Int4
AcademicMonths pgtype.Int4
}
type CandidateSearchStatus struct {
UserID pgtype.UUID
Status string
@@ -135,6 +164,28 @@ type CandidateSearchStatus struct {
UpdatedAt pgtype.Timestamptz
}
type CompanyCardViewQuotaUsage struct {
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
LastSeenAt pgtype.Timestamptz
PolicyVersionID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
QuotaTier string
}
type CompanyInvitationQuotaUsage struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
ReservedAt pgtype.Timestamptz
PolicyVersionID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
QuotaTier string
}
type ConsentRecord struct {
ID pgtype.UUID
SubjectID pgtype.UUID
@@ -17,6 +17,8 @@ type Querier interface {
// 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
// A questionnaire save advances onboarding only from its own step.
AdvanceCandidateOnboardingAfterQuestionnaire(ctx context.Context, arg AdvanceCandidateOnboardingAfterQuestionnaireParams) 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
@@ -25,6 +27,9 @@ type Querier interface {
// returns for a stale version or for an account without a profile, which the
// caller answers as a version conflict.
AdvanceCandidateProfileVersion(ctx context.Context, arg AdvanceCandidateProfileVersionParams) (CandidateProfile, error)
// Advances an existing questionnaire only at the version read by the caller.
// The row lock serializes saves for one user; a stale writer returns no row.
AdvanceCandidateQuestionnaireVersion(ctx context.Context, arg AdvanceCandidateQuestionnaireVersionParams) (CandidateQuestionnaire, error)
// Starts a new registration of an unverified account without touching its
// credentials, scenario, or onboarding step: the new registration carries
// them on its verification token. Advances the registration version, which
@@ -110,6 +115,8 @@ type Querier interface {
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, error)
// Counts the hiding records of one candidate for the settings read.
CountCandidateHiddenOrganizations(ctx context.Context, userID pgtype.UUID) (int64, error)
CountCompanyCardViewQuotaWindow(ctx context.Context, arg CountCompanyCardViewQuotaWindowParams) (CountCompanyCardViewQuotaWindowRow, error)
CountCompanyInvitationQuotaWindow(ctx context.Context, arg CountCompanyInvitationQuotaWindowParams) (CountCompanyInvitationQuotaWindowRow, error)
// Counts the families of a category that have at least one published
// version, however many versions each has.
CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error)
@@ -127,6 +134,10 @@ type Querier interface {
// 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
// Replaces all specialization answers after the version row advanced in the
// same transaction.
DeleteCandidateQuestionnaireSpecializations(ctx context.Context, userID pgtype.UUID) error
DeleteExpiredCompanyCardViewQuotaUsage(ctx context.Context, arg DeleteExpiredCompanyCardViewQuotaUsageParams) (int64, 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,
@@ -165,6 +176,8 @@ type Querier interface {
// NULL retry_at. due_at keeps the deadline. The same guard as the
// completion applies.
FailScheduledJob(ctx context.Context, arg FailScheduledJobParams) (int64, error)
FindCompanyCardViewQuotaUsage(ctx context.Context, arg FindCompanyCardViewQuotaUsageParams) (pgtype.Timestamptz, error)
FindCompanyInvitationQuotaUsage(ctx context.Context, arg FindCompanyInvitationQuotaUsageParams) (pgtype.UUID, error)
// Returns the newest open reservation of a delivery under a provider account
// made at or after reserved_since. A retry of the delivery inside the
// provider's idempotency window reuses it instead of counting again.
@@ -260,6 +273,10 @@ type Querier interface {
GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error)
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
// Stores an explicit mapping against a newly-created immutable opening. The
// insert trigger checks the opening, declared reviewer, current policy, and
// live coverage; the adapter supplies the fingerprint of the published set.
InsertAssessmentCategoryCatalogBinding(ctx context.Context, arg InsertAssessmentCategoryCatalogBindingParams) error
// Stores an opening. The insert trigger derives required_families from the
// policy document and counts the published families, and the coverage CHECK
// refuses the row when they are fewer; both numbers from the caller are
@@ -301,8 +318,13 @@ type Querier interface {
// one is answered as a version conflict. The foreign key refuses a record
// that is not a C2 record of this account.
InsertCandidatePublication(ctx context.Context, arg InsertCandidatePublicationParams) (InsertCandidatePublicationRow, error)
// Creates the first saved questionnaire. A missing row is version zero;
// concurrent first saves race on the primary key and exactly one returns a row.
InsertCandidateQuestionnaire(ctx context.Context, arg InsertCandidateQuestionnaireParams) (CandidateQuestionnaire, error)
InsertCandidateQuestionnaireSpecialization(ctx context.Context, arg InsertCandidateQuestionnaireSpecializationParams) error
// Stores the first status at version 1; no row returns when one exists.
InsertCandidateSearchStatus(ctx context.Context, arg InsertCandidateSearchStatusParams) (InsertCandidateSearchStatusRow, error)
InsertCompanyInvitationQuotaUsage(ctx context.Context, arg InsertCompanyInvitationQuotaUsageParams) error
// Records a grant of C1, C2, C3, or C5. An unrevoked record of the same
// subject, purpose, and text version already exists when no row returns;
// the insert then changes nothing and does not abort the transaction.
@@ -384,6 +406,10 @@ type Querier interface {
// the last record of the previous page.
ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, error)
ListCurrentContactConsentRecords(ctx context.Context, arg ListCurrentContactConsentRecordsParams) ([]ListCurrentContactConsentRecordsRow, error)
// Produces current catalog availability in one PostgreSQL statement snapshot.
// The adapter compares the ordered live family manifest with the pinned
// fingerprint; stale bindings are omitted fail-closed.
ListCurrentSpecializationAvailability(ctx context.Context) ([]ListCurrentSpecializationAvailabilityRow, error)
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
// Lists the organizations where an account has an active membership,
// newest membership first. The page continues after the (membership
@@ -413,6 +439,10 @@ type Querier interface {
// canceled, or reclaimed after the lease expired. While the lock is held,
// other workers skip the row, so the handler never runs twice at once.
LockClaimedScheduledJob(ctx context.Context, arg LockClaimedScheduledJobParams) (int64, error)
// Writers lock the organization first, then invitation/card-view state, and
// finally usage rows. The organization lock serializes quota decisions for
// the tenant and makes the subsequent count and insert atomic.
LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error)
// Takes the candidate's current unrevoked C2 record for a publication and
// keeps it locked until the transaction ends. The share lock conflicts with
// the revocation stamp (an UPDATE of the row), so a revocation either commits
@@ -496,6 +526,9 @@ type Querier interface {
// snapshot. The effective state is computed from them: published only while
// consent_revoked_at is NULL. No row means the candidate never published.
ReadCandidatePublication(ctx context.Context, userID pgtype.UUID) (ReadCandidatePublicationRow, error)
// Reads the aggregate and its ordered specializations in one statement so a
// response never pairs a version with another version's answers.
ReadCandidateQuestionnaire(ctx context.Context, userID pgtype.UUID) (ReadCandidateQuestionnaireRow, error)
// No row means the status was never set, which reads as not looking. The
// lapse is computed by the caller from lapses_at and its clock and is never
// written.
@@ -507,6 +540,10 @@ type Querier interface {
// unpublished one. Every organization-facing read of a publication starts
// from this shape.
ReadPublicationVisibleToOrganization(ctx context.Context, arg ReadPublicationVisibleToOrganizationParams) (ReadPublicationVisibleToOrganizationRow, error)
// Lists the exact published bank manifest while the category advisory lock is
// held by OpenCategory. Published families have passed the independent-review
// constraint before this read.
ReadPublishedAssessmentCategoryManifest(ctx context.Context, category string) ([]ReadPublishedAssessmentCategoryManifestRow, error)
// Advances a delivery past one attempt and appends the attempt in one
// statement, so both happen or neither does, inside or outside a
// transaction. The update applies only while the stored version still
@@ -534,6 +571,7 @@ type Querier interface {
RecordDeliveryFailure(ctx context.Context, arg RecordDeliveryFailureParams) (string, error)
// Records the latest settled outcome of a send under the reservation.
RecordMailQuotaOutcome(ctx context.Context, arg RecordMailQuotaOutcomeParams) (int64, error)
RefreshCompanyCardViewQuotaUsage(ctx context.Context, arg RefreshCompanyCardViewQuotaUsageParams) (int64, error)
// Gives a claimed delivery back without changing it, so the next pass may
// claim it. It matches only the lease of lease_owner: a delivery that another
// worker took over after the lease expired is left alone.
@@ -568,6 +606,7 @@ type Querier interface {
RevokeContactConsentRecords(ctx context.Context, arg RevokeContactConsentRecordsParams) ([]RevokeContactConsentRecordsRow, error)
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
SaveCompanyCardViewQuotaUsage(ctx context.Context, arg SaveCompanyCardViewQuotaUsageParams) error
// Stores the immutable domain snapshot of a successful create command. The
// generic idempotency row and this result are committed with the organization
// and owner membership. A reused expired scope replaces the snapshot in the
@@ -0,0 +1,403 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: questionnaire.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const advanceCandidateOnboardingAfterQuestionnaire = `-- name: AdvanceCandidateOnboardingAfterQuestionnaire :exec
UPDATE users
SET
onboarding_step = 'candidate_assessment',
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_questionnaire'
`
type AdvanceCandidateOnboardingAfterQuestionnaireParams struct {
At pgtype.Timestamptz
UserID pgtype.UUID
}
// A questionnaire save advances onboarding only from its own step.
func (q *Queries) AdvanceCandidateOnboardingAfterQuestionnaire(ctx context.Context, arg AdvanceCandidateOnboardingAfterQuestionnaireParams) error {
_, err := q.db.Exec(ctx, advanceCandidateOnboardingAfterQuestionnaire, arg.At, arg.UserID)
return err
}
const advanceCandidateQuestionnaireVersion = `-- name: AdvanceCandidateQuestionnaireVersion :one
UPDATE candidate_questionnaires
SET
version = candidate_questionnaires.version + 1,
work_formats = $1,
updated_at = GREATEST(candidate_questionnaires.updated_at, $2::timestamptz)
WHERE
candidate_questionnaires.user_id = $3
AND candidate_questionnaires.version = $4
RETURNING user_id, version, work_formats, created_at, updated_at
`
type AdvanceCandidateQuestionnaireVersionParams struct {
WorkFormats []string
At pgtype.Timestamptz
UserID pgtype.UUID
ExpectedVersion int64
}
// Advances an existing questionnaire only at the version read by the caller.
// The row lock serializes saves for one user; a stale writer returns no row.
func (q *Queries) AdvanceCandidateQuestionnaireVersion(ctx context.Context, arg AdvanceCandidateQuestionnaireVersionParams) (CandidateQuestionnaire, error) {
row := q.db.QueryRow(ctx, advanceCandidateQuestionnaireVersion,
arg.WorkFormats,
arg.At,
arg.UserID,
arg.ExpectedVersion,
)
var i CandidateQuestionnaire
err := row.Scan(
&i.UserID,
&i.Version,
&i.WorkFormats,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const deleteCandidateQuestionnaireSpecializations = `-- name: DeleteCandidateQuestionnaireSpecializations :exec
DELETE FROM candidate_questionnaire_specializations
WHERE user_id = $1
`
// Replaces all specialization answers after the version row advanced in the
// same transaction.
func (q *Queries) DeleteCandidateQuestionnaireSpecializations(ctx context.Context, userID pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteCandidateQuestionnaireSpecializations, userID)
return err
}
const insertAssessmentCategoryCatalogBinding = `-- name: InsertAssessmentCategoryCatalogBinding :exec
INSERT INTO assessment_category_catalog_bindings (
opening_id,
specialization,
grade,
task_languages,
published_manifest_sha256,
reviewed_by,
reviewed_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
clock_timestamp()
)
`
type InsertAssessmentCategoryCatalogBindingParams struct {
OpeningID pgtype.UUID
Specialization string
Grade string
TaskLanguages []string
PublishedManifestSha256 []byte
ReviewedBy string
}
// Stores an explicit mapping against a newly-created immutable opening. The
// insert trigger checks the opening, declared reviewer, current policy, and
// live coverage; the adapter supplies the fingerprint of the published set.
func (q *Queries) InsertAssessmentCategoryCatalogBinding(ctx context.Context, arg InsertAssessmentCategoryCatalogBindingParams) error {
_, err := q.db.Exec(ctx, insertAssessmentCategoryCatalogBinding,
arg.OpeningID,
arg.Specialization,
arg.Grade,
arg.TaskLanguages,
arg.PublishedManifestSha256,
arg.ReviewedBy,
)
return err
}
const insertCandidateQuestionnaire = `-- name: InsertCandidateQuestionnaire :one
INSERT INTO candidate_questionnaires (
user_id,
version,
work_formats,
created_at,
updated_at
) VALUES (
$1,
1,
$2,
$3::timestamptz,
$3::timestamptz
)
ON CONFLICT (user_id) DO NOTHING
RETURNING user_id, version, work_formats, created_at, updated_at
`
type InsertCandidateQuestionnaireParams struct {
UserID pgtype.UUID
WorkFormats []string
At pgtype.Timestamptz
}
// Creates the first saved questionnaire. A missing row is version zero;
// concurrent first saves race on the primary key and exactly one returns a row.
func (q *Queries) InsertCandidateQuestionnaire(ctx context.Context, arg InsertCandidateQuestionnaireParams) (CandidateQuestionnaire, error) {
row := q.db.QueryRow(ctx, insertCandidateQuestionnaire, arg.UserID, arg.WorkFormats, arg.At)
var i CandidateQuestionnaire
err := row.Scan(
&i.UserID,
&i.Version,
&i.WorkFormats,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const insertCandidateQuestionnaireSpecialization = `-- name: InsertCandidateQuestionnaireSpecialization :exec
INSERT INTO candidate_questionnaire_specializations (
user_id,
ordinal,
specialization,
self_assessed_grade,
task_languages,
stack,
commercial_months,
academic_months
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8
)
`
type InsertCandidateQuestionnaireSpecializationParams struct {
UserID pgtype.UUID
Ordinal int16
Specialization string
SelfAssessedGrade string
TaskLanguages []string
Stack []string
CommercialMonths pgtype.Int4
AcademicMonths pgtype.Int4
}
func (q *Queries) InsertCandidateQuestionnaireSpecialization(ctx context.Context, arg InsertCandidateQuestionnaireSpecializationParams) error {
_, err := q.db.Exec(ctx, insertCandidateQuestionnaireSpecialization,
arg.UserID,
arg.Ordinal,
arg.Specialization,
arg.SelfAssessedGrade,
arg.TaskLanguages,
arg.Stack,
arg.CommercialMonths,
arg.AcademicMonths,
)
return err
}
const listCurrentSpecializationAvailability = `-- name: ListCurrentSpecializationAvailability :many
WITH current_policy AS (
SELECT id
FROM policy_versions
WHERE policy_key = 'product' AND effective_at <= statement_timestamp()
ORDER BY version DESC
LIMIT 1
), current_openings AS (
SELECT DISTINCT ON (category)
id,
category,
policy_version_id,
required_families,
opened_at
FROM assessment_category_openings
ORDER BY category, opened_at DESC, id DESC
)
SELECT
opening.id AS opening_id,
opening.category,
opening.policy_version_id,
opening.required_families,
COALESCE((
SELECT count(DISTINCT family.family_key)::integer
FROM assessment_families AS family
WHERE family.category = opening.category AND family.lifecycle = 'published'
), 0)::integer AS published_count,
policy.id AS effective_policy_id,
binding.specialization,
binding.grade,
binding.task_languages,
binding.published_manifest_sha256,
COALESCE((
SELECT jsonb_agg(
jsonb_build_object(
'family_key', family.family_key,
'version', family.version,
'content_sha256', encode(family.content_sha256, 'hex')
) ORDER BY family.family_key, family.version
)
FROM assessment_families AS family
WHERE family.category = opening.category AND family.lifecycle = 'published'
), '[]'::jsonb)::text AS published_manifest
FROM current_openings AS opening
JOIN assessment_category_catalog_bindings AS binding
ON binding.opening_id = opening.id
LEFT JOIN current_policy AS policy ON true
ORDER BY opening.category
`
type ListCurrentSpecializationAvailabilityRow struct {
OpeningID pgtype.UUID
Category string
PolicyVersionID pgtype.UUID
RequiredFamilies int32
PublishedCount int32
EffectivePolicyID pgtype.UUID
Specialization string
Grade string
TaskLanguages []string
PublishedManifestSha256 []byte
PublishedManifest string
}
// Produces current catalog availability in one PostgreSQL statement snapshot.
// The adapter compares the ordered live family manifest with the pinned
// fingerprint; stale bindings are omitted fail-closed.
func (q *Queries) ListCurrentSpecializationAvailability(ctx context.Context) ([]ListCurrentSpecializationAvailabilityRow, error) {
rows, err := q.db.Query(ctx, listCurrentSpecializationAvailability)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListCurrentSpecializationAvailabilityRow
for rows.Next() {
var i ListCurrentSpecializationAvailabilityRow
if err := rows.Scan(
&i.OpeningID,
&i.Category,
&i.PolicyVersionID,
&i.RequiredFamilies,
&i.PublishedCount,
&i.EffectivePolicyID,
&i.Specialization,
&i.Grade,
&i.TaskLanguages,
&i.PublishedManifestSha256,
&i.PublishedManifest,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const readCandidateQuestionnaire = `-- name: ReadCandidateQuestionnaire :one
SELECT
questionnaire.user_id,
questionnaire.version,
questionnaire.work_formats,
questionnaire.created_at,
questionnaire.updated_at,
COALESCE((
SELECT jsonb_agg(
jsonb_build_object(
'ordinal', specialization.ordinal,
'specialization', specialization.specialization,
'self_assessed_grade', specialization.self_assessed_grade,
'task_languages', specialization.task_languages,
'stack', specialization.stack,
'commercial_months', specialization.commercial_months,
'academic_months', specialization.academic_months
) ORDER BY specialization.ordinal
)
FROM candidate_questionnaire_specializations AS specialization
WHERE specialization.user_id = questionnaire.user_id
), '[]'::jsonb)::text AS specializations
FROM candidate_questionnaires AS questionnaire
WHERE questionnaire.user_id = $1
`
type ReadCandidateQuestionnaireRow struct {
UserID pgtype.UUID
Version int64
WorkFormats []string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Specializations string
}
// Reads the aggregate and its ordered specializations in one statement so a
// response never pairs a version with another version's answers.
func (q *Queries) ReadCandidateQuestionnaire(ctx context.Context, userID pgtype.UUID) (ReadCandidateQuestionnaireRow, error) {
row := q.db.QueryRow(ctx, readCandidateQuestionnaire, userID)
var i ReadCandidateQuestionnaireRow
err := row.Scan(
&i.UserID,
&i.Version,
&i.WorkFormats,
&i.CreatedAt,
&i.UpdatedAt,
&i.Specializations,
)
return i, err
}
const readPublishedAssessmentCategoryManifest = `-- name: ReadPublishedAssessmentCategoryManifest :many
SELECT family_key, version, content_sha256
FROM assessment_families
WHERE category = $1 AND lifecycle = 'published'
ORDER BY family_key, version
`
type ReadPublishedAssessmentCategoryManifestRow struct {
FamilyKey string
Version int32
ContentSha256 []byte
}
// Lists the exact published bank manifest while the category advisory lock is
// held by OpenCategory. Published families have passed the independent-review
// constraint before this read.
func (q *Queries) ReadPublishedAssessmentCategoryManifest(ctx context.Context, category string) ([]ReadPublishedAssessmentCategoryManifestRow, error) {
rows, err := q.db.Query(ctx, readPublishedAssessmentCategoryManifest, category)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ReadPublishedAssessmentCategoryManifestRow
for rows.Next() {
var i ReadPublishedAssessmentCategoryManifestRow
if err := rows.Scan(&i.FamilyKey, &i.Version, &i.ContentSha256); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
+26
View File
@@ -0,0 +1,26 @@
package bootstrap
import (
"context"
"log/slog"
"lincodex/backend/config"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/usecase/assessment"
)
const catalogPoolMaxConns = 4
func newCatalogHandler(ctx context.Context, settings config.Config, logger *slog.Logger) (*v1.CatalogHandler, func(), error) {
if settings.DatabaseURL == "" {
logger.Warn("specialization catalog is not served because DATABASE_URL is not set")
return nil, func() {}, nil
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, catalogPoolMaxConns)
if err != nil {
return nil, nil, err
}
bank := assessment.NewBank(postgres.NewTransactor(pool))
return v1.NewCatalogHandler(bank), pool.Close, nil
}
+4
View File
@@ -37,12 +37,16 @@ func newAPIHandler(
identityHandler *v1.IdentityHandler,
consentHandler *v1.ConsentHandler,
profileHandler *v1.ProfileHandler,
questionnaireHandler *v1.QuestionnaireHandler,
catalogHandler *v1.CatalogHandler,
organizationHandler *v1.OrganizationHandler,
) *v1.Handler {
return v1.NewHandler(health, problems,
v1.WithIdentity(identityHandler),
v1.WithConsent(consentHandler),
v1.WithProfile(profileHandler),
v1.WithQuestionnaire(questionnaireHandler),
v1.WithCatalog(catalogHandler),
v1.WithOrganization(organizationHandler),
)
}
@@ -0,0 +1,27 @@
package bootstrap
import (
"context"
"log/slog"
"time"
"lincodex/backend/config"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/usecase/questionnaire"
)
const questionnairePoolMaxConns = 8
func newQuestionnaireHandler(ctx context.Context, settings config.Config, logger *slog.Logger) (*v1.QuestionnaireHandler, func(), error) {
if settings.DatabaseURL == "" {
logger.Warn("candidate questionnaire operations are not served because DATABASE_URL is not set")
return nil, func() {}, nil
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, questionnairePoolMaxConns)
if err != nil {
return nil, nil, err
}
service := questionnaire.NewService(postgres.NewTransactor(pool), time.Now)
return v1.NewQuestionnaireHandler(service), pool.Close, nil
}
+2
View File
@@ -49,6 +49,8 @@ func initialize(
newIdentityKeyring,
newConsentHandler,
newProfileHandler,
newQuestionnaireHandler,
newCatalogHandler,
newOrganizationHandler,
newSessionSecurity,
newRouter,
+57 -20
View File
@@ -76,7 +76,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
organizationHandler, cleanup7, err := newOrganizationHandler(ctx, config2, logger, keyring)
questionnaireHandler, cleanup7, err := newQuestionnaireHandler(ctx, config2, logger)
if err != nil {
cleanup6()
cleanup5()
@@ -86,10 +86,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, organizationHandler)
sessionSecurity := newSessionSecurity(identityHandler)
v := newTrustedProxies(config2)
httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler)
catalogHandler, cleanup8, err := newCatalogHandler(ctx, config2, logger)
if err != nil {
cleanup7()
cleanup6()
@@ -100,18 +97,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
relay, cleanup8, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup9, err := newEventConsumers(ctx, config2, logger, metrics)
organizationHandler, cleanup9, err := newOrganizationHandler(ctx, config2, logger, keyring)
if err != nil {
cleanup8()
cleanup7()
@@ -123,7 +109,10 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
worker, cleanup10, err := newJobWorker(ctx, config2, logger, metrics)
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler)
sessionSecurity := newSessionSecurity(identityHandler)
v := newTrustedProxies(config2)
httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler)
if err != nil {
cleanup9()
cleanup8()
@@ -136,7 +125,20 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
mailsenderWorker, cleanup11, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
relay, cleanup10, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup11, err := newEventConsumers(ctx, config2, logger, metrics)
if err != nil {
cleanup10()
cleanup9()
@@ -150,7 +152,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup12, err := newDeliveryMetrics(ctx, config2, logger, metrics)
worker, cleanup12, err := newJobWorker(ctx, config2, logger, metrics)
if err != nil {
cleanup11()
cleanup10()
@@ -165,8 +167,43 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
mailsenderWorker, cleanup13, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
if err != nil {
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
sampler, cleanup14, err := newDeliveryMetrics(ctx, config2, logger, metrics)
if err != nil {
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler)
return application, func() {
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
@@ -0,0 +1,71 @@
package domain
import (
"fmt"
"slices"
)
// AssessmentCategoryCatalogMetadata is the explicit public-catalog mapping
// reviewed for a published bank category before it is opened. It does not
// derive public specialization from an assessment family's internal topic.
type AssessmentCategoryCatalogMetadata struct {
specialization SpecializationCode
grade GradeCode
taskLanguages []TaskLanguageCode
}
// NewAssessmentCategoryCatalogMetadata validates the mapping attached to a
// reviewed category opening.
func NewAssessmentCategoryCatalogMetadata(
specialization SpecializationCode,
grade GradeCode,
taskLanguages []TaskLanguageCode,
) (AssessmentCategoryCatalogMetadata, error) {
const location = "domain.NewAssessmentCategoryCatalogMetadata"
if !specialization.IsKnown() {
return AssessmentCategoryCatalogMetadata{}, fmt.Errorf("%s - specialization is not in the public catalog: %w", location, ErrInvalidAssessmentFamily)
}
if !grade.IsKnown() {
return AssessmentCategoryCatalogMetadata{}, fmt.Errorf("%s - grade is not in the public catalog: %w", location, ErrInvalidAssessmentFamily)
}
if len(taskLanguages) > maxQuestionnaireTaskLanguages {
return AssessmentCategoryCatalogMetadata{}, fmt.Errorf("%s - at most two task languages are allowed: %w", location, ErrInvalidAssessmentFamily)
}
seen := make(map[TaskLanguageCode]struct{}, len(taskLanguages))
for _, language := range taskLanguages {
if !language.IsKnown() {
return AssessmentCategoryCatalogMetadata{}, fmt.Errorf("%s - task language is not in the public catalog: %w", location, ErrInvalidAssessmentFamily)
}
if _, exists := seen[language]; exists {
return AssessmentCategoryCatalogMetadata{}, fmt.Errorf("%s - task languages must be unique: %w", location, ErrInvalidAssessmentFamily)
}
seen[language] = struct{}{}
}
return AssessmentCategoryCatalogMetadata{
specialization: specialization,
grade: grade,
taskLanguages: slices.Clone(taskLanguages),
}, nil
}
func (metadata AssessmentCategoryCatalogMetadata) Specialization() SpecializationCode {
return metadata.specialization
}
func (metadata AssessmentCategoryCatalogMetadata) Grade() GradeCode { return metadata.grade }
func (metadata AssessmentCategoryCatalogMetadata) TaskLanguages() []TaskLanguageCode {
return slices.Clone(metadata.taskLanguages)
}
func (metadata AssessmentCategoryCatalogMetadata) IsZero() bool {
return metadata.specialization == "" || metadata.grade == ""
}
// AssessmentCategoryManifestEntry is an immutable published family identity
// used to pin public catalog metadata to one reviewed bank composition.
type AssessmentCategoryManifestEntry struct {
FamilyKey AssessmentFamilyKey
Version int32
ContentSHA256 []byte
}
+133
View File
@@ -0,0 +1,133 @@
package domain
import (
"errors"
"fmt"
"time"
"github.com/google/uuid"
)
var (
// ErrInvalidCompanyQuota reports a quota request that has incomplete or
// inconsistent trusted inputs.
ErrInvalidCompanyQuota = errors.New("invalid company quota")
// ErrCompanyQuotaDenied reports an organization level that has no active
// quota tier. Callers must refuse the action instead of falling back.
ErrCompanyQuotaDenied = errors.New("company quota denied")
)
// CompanyQuota is an immutable snapshot of the limits that apply to one
// organization at one instant. It carries the stored verification and
// effective policy identities so the transactional repository can verify
// that neither changed before it reserves usage.
type CompanyQuota struct {
organizationID uuid.UUID
policyVersionID PolicyVersionID
verificationLevel OrganizationVerificationLevel
verificationBasis OrganizationVerificationBasis
verificationChanged time.Time
tier OrganizationTier
at time.Time
invitationWindow time.Duration
invitationLimit int64
cardViewWindow time.Duration
cardViewLimit int64
}
// NewCompanyQuota resolves the organization's trusted verification against
// an effective product policy. at is the application clock snapshot for the
// whole operation; a request from before the organization or its current
// verification record is rejected so a stale timestamp cannot use older
// trust.
func NewCompanyQuota(organization Organization, version PolicyVersion, at time.Time) (CompanyQuota, error) {
const location = "domain.NewCompanyQuota"
if organization.IsZero() {
return CompanyQuota{}, fmt.Errorf("%s - organization must be restored from trusted storage: %w", location, ErrInvalidCompanyQuota)
}
if version.IsZero() || version.Key() != ProductPolicyKey {
return CompanyQuota{}, fmt.Errorf("%s - an effective product policy is required: %w", location, ErrInvalidCompanyQuota)
}
if at.IsZero() || at.Unix() < 0 {
return CompanyQuota{}, fmt.Errorf("%s - application time must be set and non-negative: %w", location, ErrInvalidCompanyQuota)
}
at = at.UTC()
verification := organization.Verification()
if at.Before(organization.CreatedAt()) || at.Before(verification.ChangedAt()) {
return CompanyQuota{}, fmt.Errorf("%s - application time predates organization trust: %w", location, ErrInvalidCompanyQuota)
}
if version.EffectiveAt().After(at) {
return CompanyQuota{}, fmt.Errorf("%s - policy is not effective at application time: %w", location, ErrInvalidCompanyQuota)
}
tier, ok := verification.Level().QuotaTier()
if !ok {
return CompanyQuota{}, fmt.Errorf("%s - verification level has no quota tier: %w", location, ErrCompanyQuotaDenied)
}
policy := version.Policy().OrganizationQuotas
tierPolicy, err := policy.Tier(tier)
if err != nil {
return CompanyQuota{}, fmt.Errorf("%s - read the organization tier: %w", location, err)
}
if !tierPolicy.Active {
return CompanyQuota{}, fmt.Errorf("%s - organization tier is not active: %w", location, ErrCompanyQuotaDenied)
}
return CompanyQuota{
organizationID: organization.ID(),
policyVersionID: version.ID(),
verificationLevel: verification.Level(),
verificationBasis: verification.Basis(),
verificationChanged: verification.ChangedAt().UTC(),
tier: tier,
at: at,
invitationWindow: policy.InvitationWindow.Duration(),
invitationLimit: int64(tierPolicy.InvitationsPerWindow),
cardViewWindow: policy.CardViewWindow.Duration(),
cardViewLimit: int64(tierPolicy.DistinctCardViewsPerWindow),
}, nil
}
func (quota CompanyQuota) OrganizationID() uuid.UUID { return quota.organizationID }
func (quota CompanyQuota) PolicyVersionID() PolicyVersionID { return quota.policyVersionID }
func (quota CompanyQuota) VerificationLevel() OrganizationVerificationLevel {
return quota.verificationLevel
}
func (quota CompanyQuota) VerificationBasis() OrganizationVerificationBasis {
return quota.verificationBasis
}
func (quota CompanyQuota) VerificationChangedAt() time.Time { return quota.verificationChanged }
func (quota CompanyQuota) Tier() OrganizationTier { return quota.tier }
func (quota CompanyQuota) At() time.Time { return quota.at }
func (quota CompanyQuota) InvitationWindow() time.Duration { return quota.invitationWindow }
func (quota CompanyQuota) InvitationWindowStart() time.Time {
if quota.invitationWindow <= 0 {
return time.Time{}
}
return quota.at.Add(-quota.invitationWindow)
}
func (quota CompanyQuota) InvitationLimit() int64 { return quota.invitationLimit }
func (quota CompanyQuota) CardViewWindow() time.Duration { return quota.cardViewWindow }
func (quota CompanyQuota) CardViewWindowStart() time.Time {
if quota.cardViewWindow <= 0 {
return time.Time{}
}
return quota.at.Add(-quota.cardViewWindow)
}
func (quota CompanyQuota) CardViewLimit() int64 { return quota.cardViewLimit }
// IsZero reports a snapshot that was not built by NewCompanyQuota.
func (quota CompanyQuota) IsZero() bool { return quota.organizationID == uuid.Nil }
@@ -0,0 +1,146 @@
package domain
import (
"errors"
"testing"
"time"
"github.com/google/uuid"
)
func TestNewCompanyQuotaUsesStoredVerificationAndEffectivePolicy(t *testing.T) {
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.FixedZone("owner", 3*60*60))
createdAt := at.Add(-30 * 24 * time.Hour).UTC()
organization := companyQuotaTestOrganization(t, string(OrganizationVerificationE0), string(OrganizationBasisConfirmedEmail), createdAt, createdAt)
policy := companyQuotaTestPolicy(t, at.UTC().Add(-time.Hour), false)
quota, err := NewCompanyQuota(organization, policy, at)
if err != nil {
t.Fatalf("NewCompanyQuota() error = %v", err)
}
if quota.OrganizationID() != organization.ID() || quota.PolicyVersionID() != policy.ID() ||
quota.Tier() != OrganizationTierE0 || quota.VerificationLevel() != OrganizationVerificationE0 ||
quota.VerificationBasis() != OrganizationBasisConfirmedEmail || !quota.VerificationChangedAt().Equal(createdAt) {
t.Fatalf("quota identity = org %s, policy %s, tier %s, verification %s/%s at %s", quota.OrganizationID(), quota.PolicyVersionID(), quota.Tier(), quota.VerificationLevel(), quota.VerificationBasis(), quota.VerificationChangedAt())
}
if !quota.At().Equal(at.UTC()) || quota.At().Location() != time.UTC {
t.Fatalf("At() = %s, want %s in UTC", quota.At(), at.UTC())
}
if quota.InvitationLimit() != 10 || quota.CardViewLimit() != 50 ||
quota.InvitationWindow() != 7*24*time.Hour || quota.CardViewWindow() != 24*time.Hour {
t.Fatalf("quota limits/windows = %d/%s and %d/%s", quota.InvitationLimit(), quota.InvitationWindow(), quota.CardViewLimit(), quota.CardViewWindow())
}
if want := at.UTC().Add(-7 * 24 * time.Hour); !quota.InvitationWindowStart().Equal(want) {
t.Fatalf("InvitationWindowStart() = %s, want %s", quota.InvitationWindowStart(), want)
}
if want := at.UTC().Add(-24 * time.Hour); !quota.CardViewWindowStart().Equal(want) {
t.Fatalf("CardViewWindowStart() = %s, want %s", quota.CardViewWindowStart(), want)
}
}
func TestNewCompanyQuotaRequiresBothStoredE2VerificationAndActivePolicyTier(t *testing.T) {
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
organization := companyQuotaTestOrganization(t, string(OrganizationVerificationE2), string(OrganizationBasisRequisitesAndAuthority), at.Add(-time.Hour), at.Add(-time.Hour))
if _, err := NewCompanyQuota(organization, companyQuotaTestPolicy(t, at.Add(-time.Hour), false), at); !errors.Is(err, ErrCompanyQuotaDenied) {
t.Fatalf("NewCompanyQuota(E2, inactive policy tier) error = %v, want ErrCompanyQuotaDenied", err)
}
quota, err := NewCompanyQuota(organization, companyQuotaTestPolicy(t, at.Add(-time.Hour), true), at)
if err != nil {
t.Fatalf("NewCompanyQuota(E2, active policy tier) error = %v", err)
}
if quota.Tier() != OrganizationTierE2 || quota.InvitationLimit() != 100 || quota.CardViewLimit() != 400 {
t.Fatalf("E2 quota = tier %s, limits %d/%d", quota.Tier(), quota.InvitationLimit(), quota.CardViewLimit())
}
}
func TestNewCompanyQuotaDeniesE3WithoutFallingBackToE0(t *testing.T) {
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
organization := companyQuotaTestOrganization(t, string(OrganizationVerificationE3), string(OrganizationBasisManualReview), at.Add(-time.Hour), at.Add(-time.Hour))
if _, err := NewCompanyQuota(organization, companyQuotaTestPolicy(t, at.Add(-time.Hour), true), at); !errors.Is(err, ErrCompanyQuotaDenied) {
t.Fatalf("NewCompanyQuota(E3) error = %v, want ErrCompanyQuotaDenied", err)
}
}
func TestNewCompanyQuotaRejectsUntrustedOrBackdatedInputs(t *testing.T) {
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
organization := companyQuotaTestOrganization(t, string(OrganizationVerificationE0), string(OrganizationBasisConfirmedEmail), at.Add(-time.Hour), at.Add(-time.Hour))
policy := companyQuotaTestPolicy(t, at.Add(-time.Hour), false)
futurePolicy := companyQuotaTestPolicy(t, at.Add(time.Hour), false)
beforeEpoch := time.Date(1969, 12, 31, 23, 59, 59, 0, time.UTC)
createdInFuture := companyQuotaTestOrganization(t, string(OrganizationVerificationE0), string(OrganizationBasisConfirmedEmail), at.Add(time.Hour), at.Add(time.Hour))
verifiedInFuture := companyQuotaTestOrganization(t, string(OrganizationVerificationE1), string(OrganizationBasisCorporateDomain), at.Add(-time.Hour), at.Add(time.Hour))
tests := []struct {
name string
organization Organization
policy PolicyVersion
at time.Time
want error
}{
{name: "zero organization", organization: Organization{}, policy: policy, at: at, want: ErrInvalidCompanyQuota},
{name: "zero policy", organization: organization, policy: PolicyVersion{}, at: at, want: ErrInvalidCompanyQuota},
{name: "zero application time", organization: organization, policy: policy, want: ErrInvalidCompanyQuota},
{name: "negative application time", organization: organization, policy: policy, at: beforeEpoch, want: ErrInvalidCompanyQuota},
{name: "organization created after request time", organization: createdInFuture, policy: policy, at: at, want: ErrInvalidCompanyQuota},
{name: "verification changed after request time", organization: verifiedInFuture, policy: policy, at: at, want: ErrInvalidCompanyQuota},
{name: "policy effective after request time", organization: organization, policy: futurePolicy, at: at, want: ErrInvalidCompanyQuota},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if _, err := NewCompanyQuota(test.organization, test.policy, test.at); !errors.Is(err, test.want) {
t.Fatalf("NewCompanyQuota() error = %v, want %v", err, test.want)
}
})
}
}
func companyQuotaTestOrganization(t *testing.T, level, basis string, createdAt, changedAt time.Time) Organization {
t.Helper()
updatedAt := createdAt
if changedAt.After(updatedAt) {
updatedAt = changedAt
}
organization, err := RestoreOrganization(StoredOrganization{
ID: uuid.New(),
Name: "Example Company",
VerificationLevel: level,
VerificationBasis: basis,
VerificationChangedAt: changedAt,
Version: 1,
CreatedAt: createdAt,
UpdatedAt: updatedAt,
})
if err != nil {
t.Fatalf("RestoreOrganization() error = %v", err)
}
return organization
}
func companyQuotaTestPolicy(t *testing.T, effectiveAt time.Time, activateE2 bool) PolicyVersion {
t.Helper()
policy := DemoProductPolicyV1()
policy.OrganizationQuotas.TierE2.Active = activateE2
draft, err := NewPolicyVersionDraft(NewPolicyVersionDraftInput{
Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor, Policy: policy,
})
if err != nil {
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
}
numbered, err := draft.WithVersion(1)
if err != nil {
t.Fatalf("WithVersion() error = %v", err)
}
hash := numbered.DocumentHash()
version, err := RestorePolicyVersion(StoredPolicyVersion{
ID: numbered.ID(), Key: string(numbered.Key()), Version: numbered.Version(), Kind: string(numbered.Kind()),
Author: string(numbered.Author()), EffectiveAt: effectiveAt, CreatedAt: effectiveAt,
Document: numbered.Document(), DocumentHash: hash[:],
})
if err != nil {
t.Fatalf("RestorePolicyVersion() error = %v", err)
}
return version
}
+486
View File
@@ -0,0 +1,486 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"slices"
"strings"
"time"
"github.com/google/uuid"
)
var (
// ErrInvalidCandidateQuestionnaire reports a questionnaire value that
// breaks its contract or cannot be restored from storage.
ErrInvalidCandidateQuestionnaire = errors.New("invalid candidate questionnaire")
// ErrCandidateQuestionnaireVersionConflict reports that the saved
// questionnaire changed after the caller read it.
ErrCandidateQuestionnaireVersionConflict = errors.New("candidate questionnaire changed concurrently")
)
const (
maxQuestionnaireSpecializations = 2
maxQuestionnaireTaskLanguages = 2
maxQuestionnaireStackItems = 20
maxQuestionnaireStackTagRunes = 50
maxQuestionnaireExperienceMonth = 600
)
const redactedQuestionnaire = "[redacted candidate questionnaire]"
// CandidateQuestionnaireFieldError describes one invalid request field. The
// reason is fixed text and never includes the submitted value.
type CandidateQuestionnaireFieldError struct {
Pointer string
Reason string
}
func (fieldError *CandidateQuestionnaireFieldError) Error() string {
return "candidate questionnaire field " + fieldError.Pointer + " " + fieldError.Reason
}
func (fieldError *CandidateQuestionnaireFieldError) Unwrap() error {
return ErrInvalidCandidateQuestionnaire
}
func invalidQuestionnaireField(location, pointer, reason string) error {
return fmt.Errorf("%s - %w", location, &CandidateQuestionnaireFieldError{Pointer: pointer, Reason: reason})
}
// TaskLanguageCode identifies a language actually offered by a published
// assessment bank. The catalog projection, not this enum, decides which one
// is currently valid for a specialization.
type TaskLanguageCode string
const (
TaskLanguagePython TaskLanguageCode = "python"
TaskLanguageGo TaskLanguageCode = "go"
)
func (language TaskLanguageCode) IsKnown() bool {
return language == TaskLanguagePython || language == TaskLanguageGo
}
// QuestionnaireWorkFormat is an acceptable work format.
type QuestionnaireWorkFormat string
const (
QuestionnaireWorkFormatRemote QuestionnaireWorkFormat = "remote"
QuestionnaireWorkFormatOffice QuestionnaireWorkFormat = "office"
QuestionnaireWorkFormatHybrid QuestionnaireWorkFormat = "hybrid"
)
func (format QuestionnaireWorkFormat) IsKnown() bool {
switch format {
case QuestionnaireWorkFormatRemote, QuestionnaireWorkFormatOffice, QuestionnaireWorkFormatHybrid:
return true
default:
return false
}
}
// QuestionnaireExperience contains self-reported month totals. It does not
// contribute assessment points and has no field for a confirmed grade.
type QuestionnaireExperience struct {
CommercialMonths int32
AcademicMonths int32
}
func (QuestionnaireExperience) String() string { return redactedQuestionnaire }
func (QuestionnaireExperience) GoString() string { return redactedQuestionnaire }
func (QuestionnaireExperience) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedQuestionnaire)
}
func (QuestionnaireExperience) LogValue() slog.Value {
return slog.StringValue(redactedQuestionnaire)
}
// QuestionnaireSpecialization is one self-assessed specialization. Its grade
// is a candidate claim, never a confirmed grade or category.
type QuestionnaireSpecialization struct {
Specialization SpecializationCode
SelfAssessedGrade GradeCode
TaskLanguages []TaskLanguageCode
Stack []string
Experience *QuestionnaireExperience
}
func (QuestionnaireSpecialization) String() string { return redactedQuestionnaire }
func (QuestionnaireSpecialization) GoString() string { return redactedQuestionnaire }
func (QuestionnaireSpecialization) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedQuestionnaire)
}
func (QuestionnaireSpecialization) LogValue() slog.Value {
return slog.StringValue(redactedQuestionnaire)
}
// CandidateQuestionnaireInput is the complete replacement sent by a
// candidate. It contains personal data and must not be logged.
type CandidateQuestionnaireInput struct {
Specializations []QuestionnaireSpecialization
WorkFormats []QuestionnaireWorkFormat
}
func (CandidateQuestionnaireInput) String() string { return redactedQuestionnaire }
func (CandidateQuestionnaireInput) GoString() string { return redactedQuestionnaire }
func (CandidateQuestionnaireInput) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedQuestionnaire)
}
func (CandidateQuestionnaireInput) LogValue() slog.Value {
return slog.StringValue(redactedQuestionnaire)
}
// SpecializationAvailability is the current published-bank projection shared
// by the public catalog and questionnaire validation. Empty grades and
// languages mean that the specialization is not currently available.
type SpecializationAvailability struct {
Specialization SpecializationCode
Grades []GradeCode
TaskLanguages []TaskLanguageCode
}
// CandidateQuestionnaire is the private questionnaire of one candidate.
// Version zero means no questionnaire has been saved yet.
type CandidateQuestionnaire struct {
userID uuid.UUID
version int64
specializations []QuestionnaireSpecialization
workFormats []QuestionnaireWorkFormat
createdAt time.Time
updatedAt time.Time
}
// EmptyCandidateQuestionnaire returns the unsaved questionnaire of userID.
func EmptyCandidateQuestionnaire(userID uuid.UUID) (CandidateQuestionnaire, error) {
if userID == uuid.Nil {
return CandidateQuestionnaire{}, fmt.Errorf("domain.EmptyCandidateQuestionnaire - user ID must not be nil: %w", ErrInvalidCandidateQuestionnaire)
}
return CandidateQuestionnaire{userID: userID}, nil
}
func (questionnaire CandidateQuestionnaire) UserID() uuid.UUID { return questionnaire.userID }
func (questionnaire CandidateQuestionnaire) Version() int64 { return questionnaire.version }
func (questionnaire CandidateQuestionnaire) CreatedAt() time.Time {
return questionnaire.createdAt
}
func (questionnaire CandidateQuestionnaire) UpdatedAt() time.Time {
return questionnaire.updatedAt
}
func (questionnaire CandidateQuestionnaire) Specializations() []QuestionnaireSpecialization {
return cloneQuestionnaireSpecializations(questionnaire.specializations)
}
func (questionnaire CandidateQuestionnaire) WorkFormats() []QuestionnaireWorkFormat {
return slices.Clone(questionnaire.workFormats)
}
func (questionnaire CandidateQuestionnaire) IsZero() bool { return questionnaire.userID == uuid.Nil }
// SameContent reports whether two questionnaires for the same candidate have
// identical validated answers, without comparing versions or timestamps.
func (questionnaire CandidateQuestionnaire) SameContent(other CandidateQuestionnaire) bool {
return !questionnaire.IsZero() && questionnaire.userID == other.userID &&
equalQuestionnaireContent(questionnaire.specializations, questionnaire.workFormats, questionnaireContent{
specializations: other.specializations,
workFormats: other.workFormats,
})
}
func (questionnaire CandidateQuestionnaire) String() string { return redactedQuestionnaire }
func (questionnaire CandidateQuestionnaire) GoString() string { return redactedQuestionnaire }
func (questionnaire CandidateQuestionnaire) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedQuestionnaire)
}
func (questionnaire CandidateQuestionnaire) LogValue() slog.Value {
return slog.GroupValue(
slog.String("user_id", questionnaire.userID.String()),
slog.Int64("version", questionnaire.version),
)
}
// StoredCandidateQuestionnaire is the database projection used to restore a
// saved questionnaire. A missing row is represented by EmptyCandidateQuestionnaire.
type StoredCandidateQuestionnaire struct {
UserID uuid.UUID
Version int64
Specializations []QuestionnaireSpecialization
WorkFormats []QuestionnaireWorkFormat
CreatedAt time.Time
UpdatedAt time.Time
}
// RestoreCandidateQuestionnaire validates a saved questionnaire before it is
// exposed to a usecase. Current bank availability is intentionally not part
// of restoration; a later bank change must not make saved answers unreadable.
func RestoreCandidateQuestionnaire(stored StoredCandidateQuestionnaire) (CandidateQuestionnaire, error) {
const location = "domain.RestoreCandidateQuestionnaire"
if stored.UserID == uuid.Nil || stored.Version < 1 || stored.CreatedAt.IsZero() || stored.UpdatedAt.Before(stored.CreatedAt) {
return CandidateQuestionnaire{}, fmt.Errorf("%s - stored identity, version, or time is invalid: %w", location, ErrInvalidCandidateQuestionnaire)
}
content, err := validateQuestionnaireInput(CandidateQuestionnaireInput{
Specializations: stored.Specializations,
WorkFormats: stored.WorkFormats,
}, location)
if err != nil {
return CandidateQuestionnaire{}, fmt.Errorf("%s - validate stored content: %w", location, err)
}
return CandidateQuestionnaire{
userID: stored.UserID, version: stored.Version,
specializations: content.specializations, workFormats: content.workFormats,
createdAt: stored.CreatedAt, updatedAt: stored.UpdatedAt,
}, nil
}
// Replace validates a complete replacement and reports whether it changes
// the current questionnaire. Identical retries are no-ops even with an older
// expected version; a changed stale request conflicts.
func (questionnaire CandidateQuestionnaire) Replace(
input CandidateQuestionnaireInput,
expectedVersion int64,
at time.Time,
availability []SpecializationAvailability,
) (CandidateQuestionnaire, bool, error) {
const location = "CandidateQuestionnaire.Replace"
if questionnaire.IsZero() {
return CandidateQuestionnaire{}, false, fmt.Errorf("%s - questionnaire was not built by EmptyCandidateQuestionnaire or RestoreCandidateQuestionnaire: %w", location, ErrInvalidCandidateQuestionnaire)
}
conflict := fmt.Errorf("%s - expected version is not current: %w", location, ErrCandidateQuestionnaireVersionConflict)
if expectedVersion < 0 || expectedVersion > questionnaire.version {
return CandidateQuestionnaire{}, false, conflict
}
if at.IsZero() {
return CandidateQuestionnaire{}, false, fmt.Errorf("%s - time must be set: %w", location, ErrInvalidCandidateQuestionnaire)
}
content, err := validateQuestionnaireInput(input, location)
if err != nil {
return CandidateQuestionnaire{}, false, fmt.Errorf("%s - validate content: %w", location, err)
}
if equalQuestionnaireContent(questionnaire.specializations, questionnaire.workFormats, content) {
return questionnaire, false, nil
}
if expectedVersion != questionnaire.version {
return CandidateQuestionnaire{}, false, conflict
}
if err := validateQuestionnaireTaskLanguages(content.specializations, availability, location); err != nil {
return CandidateQuestionnaire{}, false, err
}
updated := questionnaire
updated.specializations = content.specializations
updated.workFormats = content.workFormats
updated.updatedAt = at
if at.Before(questionnaire.updatedAt) {
updated.updatedAt = questionnaire.updatedAt
}
if updated.createdAt.IsZero() {
updated.createdAt = updated.updatedAt
}
return updated, true, nil
}
type questionnaireContent struct {
specializations []QuestionnaireSpecialization
workFormats []QuestionnaireWorkFormat
}
func validateQuestionnaireInput(input CandidateQuestionnaireInput, location string) (questionnaireContent, error) {
if len(input.Specializations) < 1 || len(input.Specializations) > maxQuestionnaireSpecializations {
return questionnaireContent{}, invalidQuestionnaireField(location, "/specializations", "must contain one or two items")
}
if len(input.WorkFormats) < 1 || len(input.WorkFormats) > 3 {
return questionnaireContent{}, invalidQuestionnaireField(location, "/work_context/work_formats", "must contain one to three items")
}
content := questionnaireContent{
specializations: make([]QuestionnaireSpecialization, 0, len(input.Specializations)),
workFormats: slices.Clone(input.WorkFormats),
}
var err error
content.specializations, err = validateQuestionnaireSpecializations(input.Specializations, location)
if err != nil {
return questionnaireContent{}, err
}
if err := validateQuestionnaireWorkFormats(content.workFormats, location); err != nil {
return questionnaireContent{}, err
}
return content, nil
}
func validateQuestionnaireSpecializations(
answers []QuestionnaireSpecialization,
location string,
) ([]QuestionnaireSpecialization, error) {
validated := make([]QuestionnaireSpecialization, 0, len(answers))
seenSpecializations := make(map[SpecializationCode]struct{}, len(answers))
for index, answer := range answers {
pointer := fmt.Sprintf("/specializations/%d", index)
if !answer.Specialization.IsKnown() {
return nil, invalidQuestionnaireField(location, pointer+"/specialization", "must be a specialization of the catalog")
}
if _, exists := seenSpecializations[answer.Specialization]; exists {
return nil, invalidQuestionnaireField(location, pointer+"/specialization", "must not repeat an earlier item")
}
seenSpecializations[answer.Specialization] = struct{}{}
validatedAnswer, err := validateQuestionnaireSpecialization(answer, pointer, location)
if err != nil {
return nil, err
}
validated = append(validated, validatedAnswer)
}
return validated, nil
}
func validateQuestionnaireSpecialization(
answer QuestionnaireSpecialization,
pointer, location string,
) (QuestionnaireSpecialization, error) {
if !answer.SelfAssessedGrade.IsKnown() {
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/self_assessed_grade", "must be a grade of the catalog")
}
if len(answer.TaskLanguages) > maxQuestionnaireTaskLanguages {
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/task_languages", "must have at most two items")
}
if len(answer.Stack) > maxQuestionnaireStackItems {
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/stack", "must have at most twenty items")
}
answer.TaskLanguages = slices.Clone(answer.TaskLanguages)
if err := validateQuestionnaireTaskLanguageInputs(answer.TaskLanguages, pointer, location); err != nil {
return QuestionnaireSpecialization{}, err
}
answer.Stack = slices.Clone(answer.Stack)
if err := validateQuestionnaireStack(answer.Stack, pointer, location); err != nil {
return QuestionnaireSpecialization{}, err
}
if answer.Experience != nil {
experience := *answer.Experience
if experience.CommercialMonths < 0 || experience.CommercialMonths > maxQuestionnaireExperienceMonth {
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/experience/commercial_months", "must be between zero and 600")
}
if experience.AcademicMonths < 0 || experience.AcademicMonths > maxQuestionnaireExperienceMonth {
return QuestionnaireSpecialization{}, invalidQuestionnaireField(location, pointer+"/experience/academic_months", "must be between zero and 600")
}
answer.Experience = &experience
}
return answer, nil
}
func validateQuestionnaireTaskLanguageInputs(languages []TaskLanguageCode, pointer, location string) error {
seen := make(map[TaskLanguageCode]struct{}, len(languages))
for index, language := range languages {
languagePointer := fmt.Sprintf("%s/task_languages/%d", pointer, index)
if !language.IsKnown() {
return invalidQuestionnaireField(location, languagePointer, "must be a task language of the catalog")
}
if _, exists := seen[language]; exists {
return invalidQuestionnaireField(location, languagePointer, "must not repeat an earlier item")
}
seen[language] = struct{}{}
}
return nil
}
func validateQuestionnaireStack(tags []string, pointer, location string) error {
seen := make(map[string]struct{}, len(tags))
for index, tag := range tags {
tagPointer := fmt.Sprintf("%s/stack/%d", pointer, index)
if reason := singleLineTextProblem(tag, maxQuestionnaireStackTagRunes); reason != "" {
return invalidQuestionnaireField(location, tagPointer, reason)
}
key := strings.ToLower(tag)
if _, exists := seen[key]; exists {
return invalidQuestionnaireField(location, tagPointer, "must not repeat an earlier item")
}
seen[key] = struct{}{}
}
return nil
}
func validateQuestionnaireWorkFormats(formats []QuestionnaireWorkFormat, location string) error {
seen := make(map[QuestionnaireWorkFormat]struct{}, len(formats))
for index, format := range formats {
pointer := fmt.Sprintf("/work_context/work_formats/%d", index)
if !format.IsKnown() {
return invalidQuestionnaireField(location, pointer, "must be remote, office, or hybrid")
}
if _, exists := seen[format]; exists {
return invalidQuestionnaireField(location, pointer, "must not repeat an earlier item")
}
seen[format] = struct{}{}
}
return nil
}
func validateQuestionnaireTaskLanguages(
answers []QuestionnaireSpecialization,
availability []SpecializationAvailability,
location string,
) error {
allowed := make(map[SpecializationCode]map[TaskLanguageCode]struct{}, len(availability))
for _, item := range availability {
if !item.Specialization.IsKnown() {
return fmt.Errorf("%s - availability contains an unknown specialization: %w", location, ErrInvalidCandidateQuestionnaire)
}
languages := make(map[TaskLanguageCode]struct{}, len(item.TaskLanguages))
for _, language := range item.TaskLanguages {
if !language.IsKnown() {
return fmt.Errorf("%s - availability contains an unknown task language: %w", location, ErrInvalidCandidateQuestionnaire)
}
languages[language] = struct{}{}
}
allowed[item.Specialization] = languages
}
for specializationIndex, answer := range answers {
for languageIndex, language := range answer.TaskLanguages {
if _, exists := allowed[answer.Specialization][language]; !exists {
pointer := fmt.Sprintf("/specializations/%d/task_languages/%d", specializationIndex, languageIndex)
return invalidQuestionnaireField(location, pointer, "must be offered by the current published bank for this specialization")
}
}
}
return nil
}
func equalQuestionnaireContent(
leftSpecializations []QuestionnaireSpecialization,
leftFormats []QuestionnaireWorkFormat,
right questionnaireContent,
) bool {
if !slices.Equal(leftFormats, right.workFormats) || len(leftSpecializations) != len(right.specializations) {
return false
}
for index, left := range leftSpecializations {
right := right.specializations[index]
if left.Specialization != right.Specialization || left.SelfAssessedGrade != right.SelfAssessedGrade ||
!slices.Equal(left.TaskLanguages, right.TaskLanguages) || !slices.Equal(left.Stack, right.Stack) ||
!equalQuestionnaireExperience(left.Experience, right.Experience) {
return false
}
}
return true
}
func equalQuestionnaireExperience(left, right *QuestionnaireExperience) bool {
if left == nil || right == nil {
return left == right
}
return *left == *right
}
func cloneQuestionnaireSpecializations(items []QuestionnaireSpecialization) []QuestionnaireSpecialization {
if items == nil {
return nil
}
cloned := make([]QuestionnaireSpecialization, len(items))
for index, item := range items {
cloned[index] = item
cloned[index].TaskLanguages = slices.Clone(item.TaskLanguages)
cloned[index].Stack = slices.Clone(item.Stack)
if item.Experience != nil {
experience := *item.Experience
cloned[index].Experience = &experience
}
}
return cloned
}
@@ -0,0 +1,232 @@
package domain
import (
"errors"
"fmt"
"reflect"
"slices"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
func TestCandidateQuestionnaireReplaceValidatesCurrentTaskLanguages(t *testing.T) {
id := uuid.Must(uuid.NewV7())
questionnaire, err := EmptyCandidateQuestionnaire(id)
if err != nil {
t.Fatalf("EmptyCandidateQuestionnaire() error = %v", err)
}
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
input := validQuestionnaireInput()
availability := []SpecializationAvailability{{
Specialization: SpecializationBackend,
Grades: []GradeCode{GradeJunior},
TaskLanguages: []TaskLanguageCode{TaskLanguageGo},
}}
updated, changed, err := questionnaire.Replace(input, 0, now, availability)
if err != nil || !changed {
t.Fatalf("Replace(valid) = changed %v, error %v; want changed", changed, err)
}
if updated.Version() != 0 || !updated.CreatedAt().Equal(now) || !updated.UpdatedAt().Equal(now) {
t.Fatalf("updated version/times = %d %s %s, want version 0 and application time", updated.Version(), updated.CreatedAt(), updated.UpdatedAt())
}
if got := updated.Specializations()[0].SelfAssessedGrade; got != GradeJunior {
t.Fatalf("self-assessed grade = %q, want junior", got)
}
badInput := validQuestionnaireInput()
badInput.Specializations[0].TaskLanguages = []TaskLanguageCode{TaskLanguagePython}
_, _, err = questionnaire.Replace(badInput, 0, now, availability)
if !errors.Is(err, ErrInvalidCandidateQuestionnaire) {
t.Fatalf("Replace(unoffered language) error = %v, want invalid questionnaire", err)
}
fieldError, ok := errors.AsType[*CandidateQuestionnaireFieldError](err)
if !ok || fieldError.Pointer != "/specializations/0/task_languages/0" || strings.Contains(err.Error(), "python") {
t.Fatalf("unoffered language error = %v, want fixed field error without submitted value", err)
}
}
func TestCandidateQuestionnaireAllowsInDevelopmentSpecializationWithoutLanguages(t *testing.T) {
questionnaire, err := EmptyCandidateQuestionnaire(uuid.Must(uuid.NewV7()))
if err != nil {
t.Fatal(err)
}
input := validQuestionnaireInput()
input.Specializations[0].Specialization = SpecializationDSML
input.Specializations[0].TaskLanguages = nil
_, changed, err := questionnaire.Replace(input, 0, time.Now().UTC(), nil)
if err != nil || !changed {
t.Fatalf("Replace(in-development specialization) = changed %v, error %v; want success with empty languages", changed, err)
}
}
func TestCandidateQuestionnaireNoOpAndVersionConflict(t *testing.T) {
id := uuid.Must(uuid.NewV7())
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
stored, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
UserID: id, Version: 2, Specializations: validQuestionnaireInput().Specializations,
WorkFormats: validQuestionnaireInput().WorkFormats, CreatedAt: now, UpdatedAt: now,
})
if err != nil {
t.Fatalf("RestoreCandidateQuestionnaire() error = %v", err)
}
input := validQuestionnaireInput()
noOp, changed, err := stored.Replace(input, 1, now.Add(time.Hour), nil)
if err != nil || changed || noOp.Version() != 2 || !noOp.UpdatedAt().Equal(now) {
t.Fatalf("Replace(stale no-op) = changed %v, version %d, time %s, error %v; want unchanged version 2", changed, noOp.Version(), noOp.UpdatedAt(), err)
}
input.WorkFormats = []QuestionnaireWorkFormat{QuestionnaireWorkFormatOffice}
_, _, err = stored.Replace(input, 1, now.Add(time.Hour), nil)
if !errors.Is(err, ErrCandidateQuestionnaireVersionConflict) {
t.Fatalf("Replace(stale changed) error = %v, want version conflict", err)
}
}
func TestCandidateQuestionnaireSameContentIgnoresVersionAndTimes(t *testing.T) {
id := uuid.Must(uuid.NewV7())
input := validQuestionnaireInput()
firstAt := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
first, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
UserID: id, Version: 2, Specializations: input.Specializations,
WorkFormats: input.WorkFormats, CreatedAt: firstAt, UpdatedAt: firstAt,
})
if err != nil {
t.Fatalf("RestoreCandidateQuestionnaire(first) error = %v", err)
}
secondAt := firstAt.Add(time.Hour)
second, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
UserID: id, Version: 3, Specializations: input.Specializations,
WorkFormats: input.WorkFormats, CreatedAt: firstAt, UpdatedAt: secondAt,
})
if err != nil {
t.Fatalf("RestoreCandidateQuestionnaire(second) error = %v", err)
}
if !first.SameContent(second) || !second.SameContent(first) {
t.Fatal("SameContent() must ignore version and timestamps but require the same user")
}
otherUser, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
UserID: uuid.Must(uuid.NewV7()), Version: 3, Specializations: input.Specializations,
WorkFormats: input.WorkFormats, CreatedAt: firstAt, UpdatedAt: secondAt,
})
if err != nil {
t.Fatalf("RestoreCandidateQuestionnaire(other user) error = %v", err)
}
if first.SameContent(otherUser) {
t.Fatal("SameContent() treated another user's questionnaire as identical")
}
changedInput := input
changedInput.Specializations = slices.Clone(input.Specializations)
changedInput.Specializations[0].Stack = []string{"gRPC"}
changed, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
UserID: id, Version: 3, Specializations: changedInput.Specializations,
WorkFormats: input.WorkFormats, CreatedAt: firstAt, UpdatedAt: secondAt,
})
if err != nil {
t.Fatalf("RestoreCandidateQuestionnaire(changed) error = %v", err)
}
if first.SameContent(changed) {
t.Fatal("SameContent() ignored a changed answer")
}
}
func TestCandidateQuestionnaireRejectsDuplicateAndMalformedValues(t *testing.T) {
tests := []struct {
name string
mutate func(*CandidateQuestionnaireInput)
pointer string
}{
{
name: "repeated specialization",
mutate: func(input *CandidateQuestionnaireInput) {
input.Specializations = append(input.Specializations, input.Specializations[0])
},
pointer: "/specializations/1/specialization",
},
{
name: "case insensitive stack duplicate",
mutate: func(input *CandidateQuestionnaireInput) {
input.Specializations[0].Stack = []string{"PostgreSQL", "postgresql"}
},
pointer: "/specializations/0/stack/1",
},
{
name: "experience above bound",
mutate: func(input *CandidateQuestionnaireInput) {
input.Specializations[0].Experience = &QuestionnaireExperience{CommercialMonths: 601}
},
pointer: "/specializations/0/experience/commercial_months",
},
{
name: "duplicate work format",
mutate: func(input *CandidateQuestionnaireInput) {
input.WorkFormats = []QuestionnaireWorkFormat{QuestionnaireWorkFormatRemote, QuestionnaireWorkFormatRemote}
},
pointer: "/work_context/work_formats/1",
},
}
questionnaire, err := EmptyCandidateQuestionnaire(uuid.Must(uuid.NewV7()))
if err != nil {
t.Fatal(err)
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
input := validQuestionnaireInput()
test.mutate(&input)
_, _, err := questionnaire.Replace(input, 0, time.Now().UTC(), []SpecializationAvailability{{
Specialization: SpecializationBackend, TaskLanguages: []TaskLanguageCode{TaskLanguageGo},
}})
fieldError, ok := errors.AsType[*CandidateQuestionnaireFieldError](err)
if !ok || fieldError.Pointer != test.pointer {
t.Fatalf("Replace() error = %v, want field pointer %s", err, test.pointer)
}
})
}
}
func TestCandidateQuestionnaireCopiesSensitiveCollectionsAndRedacts(t *testing.T) {
input := validQuestionnaireInput()
questionnaire, err := RestoreCandidateQuestionnaire(StoredCandidateQuestionnaire{
UserID: uuid.Must(uuid.NewV7()), Version: 1, Specializations: input.Specializations,
WorkFormats: input.WorkFormats, CreatedAt: time.Now().UTC(), UpdatedAt: time.Now().UTC(),
})
if err != nil {
t.Fatalf("RestoreCandidateQuestionnaire() error = %v", err)
}
items := questionnaire.Specializations()
items[0].Stack[0] = "changed"
items[0].Experience.CommercialMonths = 0
if questionnaire.Specializations()[0].Stack[0] != "PostgreSQL" || questionnaire.Specializations()[0].Experience.CommercialMonths != 12 {
t.Fatal("Specializations() exposed mutable internal data")
}
for _, formatted := range []string{fmt.Sprint(questionnaire), fmt.Sprintf("%+v", input.Specializations[0]), fmt.Sprint(input)} {
if strings.Contains(formatted, "PostgreSQL") || strings.Contains(formatted, "12") {
t.Fatalf("formatted questionnaire data leaked personal values: %s", formatted)
}
}
for _, typ := range []reflect.Type{
reflect.TypeFor[CandidateQuestionnaire](),
reflect.TypeFor[QuestionnaireSpecialization](),
} {
for index := range typ.NumField() {
name := strings.ToLower(typ.Field(index).Name)
if strings.Contains(name, "confirmed") || name == "category" {
t.Errorf("%s has forbidden field %q", typ.Name(), typ.Field(index).Name)
}
}
}
}
func validQuestionnaireInput() CandidateQuestionnaireInput {
return CandidateQuestionnaireInput{
Specializations: []QuestionnaireSpecialization{{
Specialization: SpecializationBackend, SelfAssessedGrade: GradeJunior,
TaskLanguages: []TaskLanguageCode{TaskLanguageGo}, Stack: []string{"PostgreSQL"},
Experience: &QuestionnaireExperience{CommercialMonths: 12, AcademicMonths: 4},
}},
WorkFormats: []QuestionnaireWorkFormat{QuestionnaireWorkFormatRemote},
}
}
@@ -47,6 +47,10 @@ var (
// ErrAssessmentCategoryNotOpen reports that the category has no opening.
ErrAssessmentCategoryNotOpen = errors.New("assessment category is not open")
// ErrAssessmentCatalogBindingImmutable reports an attempt to edit or remove
// an immutable reviewed catalog binding.
ErrAssessmentCatalogBindingImmutable = errors.New("assessment catalog binding is immutable")
)
// MaxAssessmentFamilyPageSize is the largest page that ListFamilies returns.
@@ -126,6 +130,15 @@ type AssessmentBankRepository interface {
// the draft's own numbers are not stored.
CreateCategoryOpening(ctx context.Context, draft domain.AssessmentCategoryOpeningDraft) (domain.AssessmentCategoryOpening, error)
// BindCategoryCatalog attaches reviewed public metadata to an opening. The
// adapter pins it to the exact currently published family manifest.
BindCategoryCatalog(ctx context.Context, opening domain.AssessmentCategoryOpening, metadata domain.AssessmentCategoryCatalogMetadata) error
// ListCurrentSpecializationAvailability returns ready public specializations
// from one database snapshot. Legacy openings or bindings whose policy,
// coverage, or published-family manifest changed are omitted.
ListCurrentSpecializationAvailability(ctx context.Context) ([]domain.SpecializationAvailability, error)
// DatabaseTime returns the database clock. It stamps the effective time
// of a policy version, so the version in force now is judged against it
// and not against the application clock.
@@ -0,0 +1,61 @@
package outbound
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var ErrCompanyQuotaSnapshotChanged = errors.New("company quota snapshot changed")
// CompanyQuotaDecision is the result of an atomic invitation or card-view
// reservation. Reused means the same invitation or a recent view already
// counted, so it is allowed without another usage charge. A denied decision
// has Reused false and RetryAt set to the earliest expiry that can free room,
// in UTC.
type CompanyQuotaDecision struct {
Allowed bool
Reused bool
RetryAt time.Time
}
// CompanyQuotaRepository atomically reserves per-organization invitation and
// candidate-card usage. Implementations are transaction-bound: a caller
// creates the invitation or applies the visibility change in the same
// transaction, so a failed business operation cannot leave quota charged.
//
// Writers lock rows in this order: organization, active membership,
// invitation or visibility record, then quota usage. A repository may take an
// organization lock again inside the same transaction, but must not invert
// this order. Each method rechecks the organization's stored verification
// level, basis, and changed_at against the snapshot in CompanyQuota before it
// writes; a caller cannot grant itself a tier by supplying a different level.
//
// Invitation usage is keyed by organization and invitation ID and remains
// until the organization is deleted. The unique key makes retries idempotent
// even when they arrive with a different request idempotency key; pruning by
// the rolling quota window would allow an old invitation to count again.
// Card-view usage is keyed by organization and candidate, counts only when
// last_seen is strictly after the rolling-window cutoff, and expires
// logically at that boundary. Bounded cleanup is opportunistic after a
// successful reservation, so physical row removal has no exact-time promise.
// Repeated views update last_seen monotonically with the greater of the
// stored and current times.
type CompanyQuotaRepository interface {
// ReserveInvitation counts a new invitation against the current policy
// limit. An existing invitation ID is returned as allowed and reused
// without a second charge, regardless of its age or the request key. A
// denied new invitation writes no usage and reports RetryAt after the
// earliest currently counted invitation expires.
ReserveInvitation(ctx context.Context, quota domain.CompanyQuota, invitationID uuid.UUID) (CompanyQuotaDecision, error)
// ReserveCardView counts a distinct candidate within the rolling card-view
// window. A repeat while the prior view is active is allowed and reused,
// and refreshes last_seen with a monotonic update. A denied new view writes
// no usage and reports RetryAt after the earliest active view expires.
ReserveCardView(ctx context.Context, quota domain.CompanyQuota, candidateID uuid.UUID) (CompanyQuotaDecision, error)
}
@@ -0,0 +1,34 @@
package outbound
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var ErrCandidateQuestionnaireVersionConflict = errors.New("candidate questionnaire changed concurrently")
// CandidateQuestionnaireRepositories exposes the questionnaire repository
// bound to a UnitOfWork transaction.
type CandidateQuestionnaireRepositories interface {
CandidateQuestionnaires() CandidateQuestionnaireRepository
}
// CandidateQuestionnaireRepository reads and replaces only the questionnaire
// owned by userID. A missing row is the version-0 empty questionnaire.
type CandidateQuestionnaireRepository interface {
Get(ctx context.Context, userID uuid.UUID) (domain.CandidateQuestionnaire, error)
// Save atomically advances the expected version and replaces the answer
// rows. A concurrent identical winner is returned as an idempotent success;
// a different winner returns ErrCandidateQuestionnaireVersionConflict.
Save(ctx context.Context, expectedVersion int64, questionnaire domain.CandidateQuestionnaire) (domain.CandidateQuestionnaire, error)
// AdvanceOnboarding advances only candidate_questionnaire to
// candidate_assessment; later onboarding steps are left unchanged.
AdvanceOnboarding(ctx context.Context, userID uuid.UUID, at time.Time) error
}
@@ -51,9 +51,11 @@ type UnitOfWork interface {
IdentityRepositories
ConsentRepositories
CandidateProfileRepositories
CandidateQuestionnaireRepositories
AccountDeletionRequests() AccountDeletionRequests
ConsentRevocationEffects() ConsentRevocationEffects
OrganizationRepositories
CompanyQuotas() CompanyQuotaRepository
AssessmentBankRepositories
Policies() PolicyRepository
Deliveries() DeliveryRepository
@@ -333,6 +333,10 @@ type OpenCategoryInput struct {
// is not the one in force are refused.
GradingPolicyID domain.PolicyVersionID
OpenedBy domain.AssessmentOperator
// CatalogMetadata is the explicit public mapping reviewed for this exact
// published bank opening. An opening without it is not exposed in the
// public specialization catalog.
CatalogMetadata *domain.AssessmentCategoryCatalogMetadata
}
// OpenCategory makes a category available. It reads the referenced policy
@@ -370,6 +374,14 @@ func (bank *Bank) OpenCategory(ctx context.Context, input OpenCategoryInput) (do
if err != nil {
return storageRefusal(fmt.Errorf("store opening: %w", err), domain.RefusalNotDraft)
}
if input.CatalogMetadata != nil {
if input.CatalogMetadata.IsZero() {
return fmt.Errorf("bind public catalog metadata: %w", domain.ErrInvalidAssessmentFamily)
}
if err := repository.BindCategoryCatalog(ctx, opening, *input.CatalogMetadata); err != nil {
return fmt.Errorf("bind public catalog metadata: %w", err)
}
}
return nil
})
if err != nil {
@@ -378,6 +390,24 @@ func (bank *Bank) OpenCategory(ctx context.Context, input OpenCategoryInput) (do
return opening, nil
}
// SpecializationAvailability returns only catalog mappings whose opening,
// current policy, live coverage, and published-family manifest still match.
func (bank *Bank) SpecializationAvailability(ctx context.Context) ([]domain.SpecializationAvailability, error) {
var availability []domain.SpecializationAvailability
err := bank.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
availability, err = unit.AssessmentBank().ListCurrentSpecializationAvailability(ctx)
if err != nil {
return fmt.Errorf("read current bank availability: %w", err)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("Bank.SpecializationAvailability - read catalog: %w", err)
}
return availability, nil
}
// readGradingPolicy reads the referenced policy version and requires it to
// be the version of the product policy in force now.
func readGradingPolicy(ctx context.Context, unit outbound.UnitOfWork, id domain.PolicyVersionID) (domain.PolicyVersion, error) {
@@ -104,6 +104,16 @@ func (bank *fakeBank) CreateCategoryOpening(context.Context, domain.AssessmentCa
return domain.AssessmentCategoryOpening{}, bank.openErr
}
func (bank *fakeBank) BindCategoryCatalog(context.Context, domain.AssessmentCategoryOpening, domain.AssessmentCategoryCatalogMetadata) error {
bank.calls = append(bank.calls, "bind_catalog")
return nil
}
func (bank *fakeBank) ListCurrentSpecializationAvailability(context.Context) ([]domain.SpecializationAvailability, error) {
bank.calls = append(bank.calls, "availability")
return nil, nil
}
func (bank *fakeBank) GetCurrentCategoryOpening(context.Context, domain.AssessmentCategory) (domain.AssessmentCategoryOpening, error) {
if bank.opening == nil {
return domain.AssessmentCategoryOpening{}, outbound.ErrAssessmentCategoryNotOpen
@@ -0,0 +1,147 @@
// Package companyquota resolves current organization limits and reserves
// invitation or candidate-card usage in the caller's transaction.
package companyquota
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var (
ErrQuotaRepositoriesMissing = errors.New("company quota repositories are missing")
ErrQuotaServiceUnavailable = errors.New("company quota service is unavailable")
)
// Repositories is the transaction-scoped surface needed for one quota
// operation. The service does not retain it, because the repositories are
// bound to the caller's transaction.
type Repositories interface {
Policies() outbound.PolicyRepository
CompanyQuotas() outbound.CompanyQuotaRepository
}
// Service reads the current policy and delegates the atomic reservation. It
// stores only the application clock and is safe to reuse between calls.
type Service struct {
clock func() time.Time
}
// NewService takes the application clock used once per operation. A nil
// clock is a wiring error and panics at construction.
func NewService(clock func() time.Time) *Service {
if clock == nil {
panic("companyquota.NewService - clock must not be nil")
}
return &Service{clock: clock}
}
// ReserveInvitation atomically records a new invitation against the policy
// effective at the operation's clock snapshot. Repeating invitationID is
// idempotent even when the caller uses a different request key.
func (service *Service) ReserveInvitation(
ctx context.Context,
repositories Repositories,
organization domain.Organization,
invitationID uuid.UUID,
) (outbound.CompanyQuotaDecision, error) {
const location = "Service.ReserveInvitation"
if invitationID == uuid.Nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation ID must be set: %w", location, domain.ErrInvalidCompanyQuota)
}
quota, repository, err := service.resolve(ctx, repositories, organization, location)
if err != nil {
return outbound.CompanyQuotaDecision{}, err
}
decision, err := repository.ReserveInvitation(ctx, quota, invitationID)
if err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - reserve invitation usage: %w", location, err)
}
if !decision.RetryAt.IsZero() {
decision.RetryAt = decision.RetryAt.UTC()
}
if err := validateDecision(quota, decision); err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - validate reservation result: %w", location, err)
}
return decision, nil
}
// ReserveCardView atomically counts a distinct candidate in the organization's
// rolling view window. A repeat within the window refreshes the stored time
// without charging another distinct view.
func (service *Service) ReserveCardView(
ctx context.Context,
repositories Repositories,
organization domain.Organization,
candidateID uuid.UUID,
) (outbound.CompanyQuotaDecision, error) {
const location = "Service.ReserveCardView"
if candidateID == uuid.Nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCompanyQuota)
}
quota, repository, err := service.resolve(ctx, repositories, organization, location)
if err != nil {
return outbound.CompanyQuotaDecision{}, err
}
decision, err := repository.ReserveCardView(ctx, quota, candidateID)
if err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - reserve card-view usage: %w", location, err)
}
if !decision.RetryAt.IsZero() {
decision.RetryAt = decision.RetryAt.UTC()
}
if err := validateDecision(quota, decision); err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - validate reservation result: %w", location, err)
}
return decision, nil
}
func (service *Service) resolve(
ctx context.Context,
repositories Repositories,
organization domain.Organization,
location string,
) (domain.CompanyQuota, outbound.CompanyQuotaRepository, error) {
if service == nil || service.clock == nil {
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - service clock is missing: %w", location, ErrQuotaServiceUnavailable)
}
if repositories == nil {
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - transaction repositories are missing: %w", location, ErrQuotaRepositoriesMissing)
}
policies := repositories.Policies()
quotaRepository := repositories.CompanyQuotas()
if policies == nil || quotaRepository == nil {
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - transaction repository is missing: %w", location, ErrQuotaRepositoriesMissing)
}
now := service.clock().UTC()
if now.IsZero() || now.Unix() < 0 {
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - application clock must be set and non-negative: %w", location, domain.ErrInvalidCompanyQuota)
}
version, err := policies.GetEffective(ctx, domain.ProductPolicyKey, now)
if err != nil {
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - read effective product policy: %w", location, err)
}
quota, err := domain.NewCompanyQuota(organization, version, now)
if err != nil {
return domain.CompanyQuota{}, nil, fmt.Errorf("%s - resolve organization quota: %w", location, err)
}
return quota, quotaRepository, nil
}
func validateDecision(quota domain.CompanyQuota, decision outbound.CompanyQuotaDecision) error {
switch {
case decision.Allowed && !decision.RetryAt.IsZero():
return errors.New("an allowed reservation cannot have a retry time")
case decision.Reused && !decision.Allowed:
return errors.New("a reused reservation must be allowed")
case !decision.Allowed && (decision.Reused || decision.RetryAt.IsZero() || !decision.RetryAt.After(quota.At())):
return errors.New("a denied reservation must be new and have a future retry time")
}
return nil
}
@@ -0,0 +1,292 @@
package companyquota
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
type quotaTestPolicies struct {
outbound.PolicyRepository
version domain.PolicyVersion
err error
calls int
key domain.PolicyKey
at time.Time
}
func (policies *quotaTestPolicies) GetEffective(_ context.Context, key domain.PolicyKey, at time.Time) (domain.PolicyVersion, error) {
policies.calls++
policies.key = key
policies.at = at
return policies.version, policies.err
}
type quotaTestRepository struct {
decision outbound.CompanyQuotaDecision
err error
invitationCalls int
cardViewCalls int
invitationID uuid.UUID
candidateID uuid.UUID
invitationQuota domain.CompanyQuota
cardViewQuota domain.CompanyQuota
}
func (repository *quotaTestRepository) ReserveInvitation(_ context.Context, quota domain.CompanyQuota, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
repository.invitationCalls++
repository.invitationQuota = quota
repository.invitationID = invitationID
return repository.decision, repository.err
}
func (repository *quotaTestRepository) ReserveCardView(_ context.Context, quota domain.CompanyQuota, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
repository.cardViewCalls++
repository.cardViewQuota = quota
repository.candidateID = candidateID
return repository.decision, repository.err
}
type quotaTestRepositories struct {
policies *quotaTestPolicies
quotas *quotaTestRepository
}
func (repositories *quotaTestRepositories) Policies() outbound.PolicyRepository {
return repositories.policies
}
func (repositories *quotaTestRepositories) CompanyQuotas() outbound.CompanyQuotaRepository {
return repositories.quotas
}
func TestReserveInvitationReadsOneEffectivePolicySnapshotAndDelegates(t *testing.T) {
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.FixedZone("owner", 3*60*60))
policy := quotaTestPolicyVersion(t, at.UTC().Add(-time.Hour))
organization := quotaTestOrganization(t, domain.OrganizationVerificationE0, domain.OrganizationBasisConfirmedEmail, at.Add(-24*time.Hour), at.Add(-24*time.Hour))
decision := outbound.CompanyQuotaDecision{Allowed: true}
repositories := &quotaTestRepositories{
policies: &quotaTestPolicies{version: policy},
quotas: &quotaTestRepository{decision: decision},
}
clockCalls := 0
service := NewService(func() time.Time {
clockCalls++
return at
})
invitationID := uuid.New()
got, err := service.ReserveInvitation(context.Background(), repositories, organization, invitationID)
if err != nil {
t.Fatalf("ReserveInvitation() error = %v", err)
}
if got != decision || clockCalls != 1 || repositories.policies.calls != 1 ||
repositories.policies.key != domain.ProductPolicyKey || !repositories.policies.at.Equal(at.UTC()) ||
repositories.policies.at.Location() != time.UTC {
t.Fatalf("decision=%+v clockCalls=%d policyReads=%d key=%s at=%s", got, clockCalls, repositories.policies.calls, repositories.policies.key, repositories.policies.at)
}
if repositories.quotas.invitationCalls != 1 || repositories.quotas.cardViewCalls != 0 || repositories.quotas.invitationID != invitationID {
t.Fatalf("quota calls: invitations=%d views=%d invitationID=%s", repositories.quotas.invitationCalls, repositories.quotas.cardViewCalls, repositories.quotas.invitationID)
}
quota := repositories.quotas.invitationQuota
if quota.OrganizationID() != organization.ID() || quota.PolicyVersionID() != policy.ID() || quota.Tier() != domain.OrganizationTierE0 ||
quota.InvitationLimit() != 10 || quota.CardViewLimit() != 50 || !quota.At().Equal(at.UTC()) {
t.Fatalf("reservation snapshot = org %s policy %s tier %s limits %d/%d at %s", quota.OrganizationID(), quota.PolicyVersionID(), quota.Tier(), quota.InvitationLimit(), quota.CardViewLimit(), quota.At())
}
}
func TestReserveCardViewReturnsAtomicReuseOrDenialDecision(t *testing.T) {
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
policy := quotaTestPolicyVersion(t, at.Add(-time.Hour))
organization := quotaTestOrganization(t, domain.OrganizationVerificationE1, domain.OrganizationBasisCorporateDomain, at.Add(-24*time.Hour), at.Add(-time.Hour))
candidateID := uuid.New()
ownerZone := time.FixedZone("owner", 3*60*60)
for _, test := range []struct {
name string
decision outbound.CompanyQuotaDecision
}{
{name: "repeat is allowed without another charge", decision: outbound.CompanyQuotaDecision{Allowed: true, Reused: true}},
{name: "denied includes the earliest expiry", decision: outbound.CompanyQuotaDecision{RetryAt: at.Add(time.Hour).In(ownerZone)}},
} {
t.Run(test.name, func(t *testing.T) {
repositories := &quotaTestRepositories{
policies: &quotaTestPolicies{version: policy},
quotas: &quotaTestRepository{decision: test.decision},
}
service := NewService(func() time.Time { return at })
got, err := service.ReserveCardView(context.Background(), repositories, organization, candidateID)
if err != nil {
t.Fatalf("ReserveCardView() error = %v", err)
}
if got.Allowed != test.decision.Allowed || got.Reused != test.decision.Reused ||
!got.RetryAt.Equal(test.decision.RetryAt) || repositories.quotas.cardViewCalls != 1 || repositories.quotas.invitationCalls != 0 ||
repositories.quotas.candidateID != candidateID {
t.Fatalf("decision=%+v calls=%d/%d candidateID=%s", got, repositories.quotas.cardViewCalls, repositories.quotas.invitationCalls, repositories.quotas.candidateID)
}
if !got.RetryAt.IsZero() && got.RetryAt.Location() != time.UTC {
t.Fatalf("RetryAt() location = %s, want UTC", got.RetryAt.Location())
}
quota := repositories.quotas.cardViewQuota
if quota.Tier() != domain.OrganizationTierE1 || quota.CardViewLimit() != 150 || quota.InvitationLimit() != 40 {
t.Fatalf("E1 quota = tier %s limits %d/%d", quota.Tier(), quota.InvitationLimit(), quota.CardViewLimit())
}
})
}
}
func TestQuotaServiceFailsClosedBeforeReservation(t *testing.T) {
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
policy := quotaTestPolicyVersion(t, at.Add(-time.Hour))
organization := quotaTestOrganization(t, domain.OrganizationVerificationE0, domain.OrganizationBasisConfirmedEmail, at.Add(-24*time.Hour), at.Add(-24*time.Hour))
policyFailure := errors.New("policy store unavailable")
tests := []struct {
name string
organization domain.Organization
policyError error
clock time.Time
want error
}{
{name: "policy unavailable", organization: organization, policyError: policyFailure, clock: at, want: policyFailure},
{name: "clock is zero", organization: organization, clock: time.Time{}, want: domain.ErrInvalidCompanyQuota},
{name: "clock predates organization trust", organization: organization, clock: at.Add(-48 * time.Hour), want: domain.ErrInvalidCompanyQuota},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
repositories := &quotaTestRepositories{
policies: &quotaTestPolicies{version: policy, err: test.policyError},
quotas: &quotaTestRepository{decision: outbound.CompanyQuotaDecision{Allowed: true}},
}
service := NewService(func() time.Time { return test.clock })
_, err := service.ReserveInvitation(context.Background(), repositories, test.organization, uuid.New())
if !errors.Is(err, test.want) {
t.Fatalf("ReserveInvitation() error = %v, want %v", err, test.want)
}
if repositories.quotas.invitationCalls != 0 || repositories.quotas.cardViewCalls != 0 {
t.Fatalf("quota repository was called: invitation=%d view=%d", repositories.quotas.invitationCalls, repositories.quotas.cardViewCalls)
}
})
}
}
func TestQuotaServiceDeniesE3AndInactiveE2WithoutFallback(t *testing.T) {
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
policy := quotaTestPolicyVersion(t, at.Add(-time.Hour))
for _, test := range []struct {
name string
level domain.OrganizationVerificationLevel
basis domain.OrganizationVerificationBasis
}{
{name: "E3", level: domain.OrganizationVerificationE3, basis: domain.OrganizationBasisManualReview},
{name: "E2 inactive in policy", level: domain.OrganizationVerificationE2, basis: domain.OrganizationBasisRequisitesAndAuthority},
} {
t.Run(test.name, func(t *testing.T) {
organization := quotaTestOrganization(t, test.level, test.basis, at.Add(-24*time.Hour), at.Add(-time.Hour))
repositories := &quotaTestRepositories{
policies: &quotaTestPolicies{version: policy},
quotas: &quotaTestRepository{decision: outbound.CompanyQuotaDecision{Allowed: true}},
}
service := NewService(func() time.Time { return at })
_, err := service.ReserveCardView(context.Background(), repositories, organization, uuid.New())
if !errors.Is(err, domain.ErrCompanyQuotaDenied) {
t.Fatalf("ReserveCardView() error = %v, want ErrCompanyQuotaDenied", err)
}
if repositories.quotas.cardViewCalls != 0 {
t.Fatalf("quota repository calls = %d, want 0", repositories.quotas.cardViewCalls)
}
})
}
}
func TestQuotaServiceRejectsInconsistentRepositoryDecisions(t *testing.T) {
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
policy := quotaTestPolicyVersion(t, at.Add(-time.Hour))
organization := quotaTestOrganization(t, domain.OrganizationVerificationE0, domain.OrganizationBasisConfirmedEmail, at.Add(-24*time.Hour), at.Add(-24*time.Hour))
for _, decision := range []outbound.CompanyQuotaDecision{
{Allowed: true, RetryAt: at.Add(time.Hour)},
{Reused: true},
{RetryAt: at},
} {
repositories := &quotaTestRepositories{
policies: &quotaTestPolicies{version: policy},
quotas: &quotaTestRepository{decision: decision},
}
service := NewService(func() time.Time { return at })
if _, err := service.ReserveInvitation(context.Background(), repositories, organization, uuid.New()); err == nil {
t.Fatalf("ReserveInvitation(decision=%+v) succeeded, want invalid result", decision)
}
}
}
func TestQuotaServiceRejectsMissingIDsBeforeReadingPolicy(t *testing.T) {
at := time.Date(2026, 10, 7, 12, 30, 0, 0, time.UTC)
policy := quotaTestPolicyVersion(t, at.Add(-time.Hour))
organization := quotaTestOrganization(t, domain.OrganizationVerificationE0, domain.OrganizationBasisConfirmedEmail, at.Add(-24*time.Hour), at.Add(-24*time.Hour))
repositories := &quotaTestRepositories{policies: &quotaTestPolicies{version: policy}, quotas: &quotaTestRepository{}}
service := NewService(func() time.Time { return at })
if _, err := service.ReserveInvitation(context.Background(), repositories, organization, uuid.Nil); !errors.Is(err, domain.ErrInvalidCompanyQuota) {
t.Fatalf("ReserveInvitation(zero ID) error = %v, want ErrInvalidCompanyQuota", err)
}
if _, err := service.ReserveCardView(context.Background(), repositories, organization, uuid.Nil); !errors.Is(err, domain.ErrInvalidCompanyQuota) {
t.Fatalf("ReserveCardView(zero ID) error = %v, want ErrInvalidCompanyQuota", err)
}
if repositories.policies.calls != 0 || repositories.quotas.invitationCalls != 0 || repositories.quotas.cardViewCalls != 0 {
t.Fatalf("repositories called for invalid IDs: policies=%d invitation=%d view=%d", repositories.policies.calls, repositories.quotas.invitationCalls, repositories.quotas.cardViewCalls)
}
}
func quotaTestOrganization(
t *testing.T,
level domain.OrganizationVerificationLevel,
basis domain.OrganizationVerificationBasis,
createdAt, changedAt time.Time,
) domain.Organization {
t.Helper()
updatedAt := createdAt
if changedAt.After(updatedAt) {
updatedAt = changedAt
}
organization, err := domain.RestoreOrganization(domain.StoredOrganization{
ID: uuid.New(), Name: "Example Company", VerificationLevel: string(level), VerificationBasis: string(basis),
VerificationChangedAt: changedAt, Version: 1, CreatedAt: createdAt, UpdatedAt: updatedAt,
})
if err != nil {
t.Fatalf("RestoreOrganization() error = %v", err)
}
return organization
}
func quotaTestPolicyVersion(t *testing.T, effectiveAt time.Time) domain.PolicyVersion {
t.Helper()
policy := domain.DemoProductPolicyV1()
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: policy,
})
if err != nil {
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
}
numbered, err := draft.WithVersion(1)
if err != nil {
t.Fatalf("WithVersion() error = %v", err)
}
hash := numbered.DocumentHash()
version, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{
ID: numbered.ID(), Key: string(numbered.Key()), Version: numbered.Version(), Kind: string(numbered.Kind()),
Author: string(numbered.Author()), EffectiveAt: effectiveAt, CreatedAt: effectiveAt,
Document: numbered.Document(), DocumentHash: hash[:],
})
if err != nil {
t.Fatalf("RestorePolicyVersion() error = %v", err)
}
return version
}
@@ -0,0 +1,134 @@
// Package questionnaire reads and version-saves a candidate's private questionnaire.
package questionnaire
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var (
ErrForbidden = errors.New("candidate questionnaire operation forbidden")
ErrEmailNotVerified = errors.New("candidate questionnaire requires a confirmed email")
)
// Service keeps questionnaire answers and onboarding movement in one
// transaction.
type Service struct {
transactor outbound.Transactor
clock func() time.Time
}
func NewService(transactor outbound.Transactor, clock func() time.Time) *Service {
if transactor == nil {
panic("questionnaire.NewService - transactor must not be nil")
}
if clock == nil {
panic("questionnaire.NewService - clock must not be nil")
}
return &Service{transactor: transactor, clock: clock}
}
// GetMyQuestionnaire reads only the questionnaire owned by the verified
// candidate userID. Version zero means no questionnaire has been saved.
func (service *Service) GetMyQuestionnaire(ctx context.Context, userID uuid.UUID) (domain.CandidateQuestionnaire, error) {
const location = "Service.GetMyQuestionnaire"
if userID == uuid.Nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateQuestionnaire)
}
var result domain.CandidateQuestionnaire
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireCandidate(ctx, unit, userID, location); err != nil {
return err
}
var err error
result, err = unit.CandidateQuestionnaires().Get(ctx, userID)
if err != nil {
return fmt.Errorf("%s - read questionnaire: %w", location, err)
}
return nil
})
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
// SaveMyQuestionnaire replaces the complete questionnaire at expectedVersion.
// A changed stale save fails; an identical retry is a no-op. The first valid
// save advances onboarding only from candidate_questionnaire.
func (service *Service) SaveMyQuestionnaire(
ctx context.Context,
userID uuid.UUID,
expectedVersion int64,
input domain.CandidateQuestionnaireInput,
) (domain.CandidateQuestionnaire, error) {
const location = "Service.SaveMyQuestionnaire"
if userID == uuid.Nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateQuestionnaire)
}
at := service.clock().UTC()
if at.IsZero() {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - application clock returned zero: %w", location, domain.ErrInvalidCandidateQuestionnaire)
}
var result domain.CandidateQuestionnaire
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireCandidate(ctx, unit, userID, location); err != nil {
return err
}
repository := unit.CandidateQuestionnaires()
current, err := repository.Get(ctx, userID)
if err != nil {
return fmt.Errorf("%s - read questionnaire: %w", location, err)
}
availability, err := unit.AssessmentBank().ListCurrentSpecializationAvailability(ctx)
if err != nil {
return fmt.Errorf("%s - read current task language availability: %w", location, err)
}
updated, changed, err := current.Replace(input, expectedVersion, at, availability)
if err != nil {
return fmt.Errorf("%s - apply replacement: %w", location, err)
}
if changed {
updated, err = repository.Save(ctx, expectedVersion, updated)
if err != nil {
return fmt.Errorf("%s - save replacement: %w", location, err)
}
}
if err := repository.AdvanceOnboarding(ctx, userID, at); err != nil {
return fmt.Errorf("%s - advance onboarding: %w", location, err)
}
result = updated
return nil
})
if err != nil {
if errors.Is(err, outbound.ErrCandidateQuestionnaireVersionConflict) || errors.Is(err, domain.ErrCandidateQuestionnaireVersionConflict) {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - transaction: %w", location, domain.ErrCandidateQuestionnaireVersionConflict)
}
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
func requireCandidate(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, location string) error {
user, err := unit.Users().GetByID(ctx, userID)
if err != nil {
if errors.Is(err, outbound.ErrUserNotFound) {
return ErrForbidden
}
return fmt.Errorf("%s - read account: %w", location, err)
}
if !user.EmailVerified() {
return ErrEmailNotVerified
}
if user.Scenario != domain.ScenarioCandidate {
return ErrForbidden
}
return nil
}
@@ -0,0 +1,232 @@
package questionnaire
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
type questionnaireTestTransactor struct{ unit outbound.UnitOfWork }
func (transactor questionnaireTestTransactor) WithinTransaction(
ctx context.Context,
fn func(context.Context, outbound.UnitOfWork) error,
) error {
return fn(ctx, transactor.unit)
}
type questionnaireTestUnit struct {
outbound.UnitOfWork
users outbound.UserRepository
questionnaire outbound.CandidateQuestionnaireRepository
bank outbound.AssessmentBankRepository
}
func (unit questionnaireTestUnit) Users() outbound.UserRepository { return unit.users }
func (unit questionnaireTestUnit) CandidateQuestionnaires() outbound.CandidateQuestionnaireRepository {
return unit.questionnaire
}
func (unit questionnaireTestUnit) AssessmentBank() outbound.AssessmentBankRepository {
return unit.bank
}
type questionnaireTestUsers struct {
outbound.UserRepository
user domain.User
err error
getCalls int
}
func (users *questionnaireTestUsers) GetByID(_ context.Context, userID uuid.UUID) (domain.User, error) {
users.getCalls++
if users.err != nil {
return domain.User{}, users.err
}
if users.user.ID != userID {
return domain.User{}, outbound.ErrUserNotFound
}
return users.user, nil
}
type questionnaireTestRepository struct {
questionnaire domain.CandidateQuestionnaire
getCalls int
saveCalls int
advanceCalls int
saveErr error
advanceErr error
}
func (repository *questionnaireTestRepository) Get(_ context.Context, userID uuid.UUID) (domain.CandidateQuestionnaire, error) {
repository.getCalls++
if repository.questionnaire.IsZero() {
return domain.EmptyCandidateQuestionnaire(userID)
}
return repository.questionnaire, nil
}
func (repository *questionnaireTestRepository) Save(
_ context.Context,
expectedVersion int64,
questionnaire domain.CandidateQuestionnaire,
) (domain.CandidateQuestionnaire, error) {
repository.saveCalls++
if repository.saveErr != nil {
return domain.CandidateQuestionnaire{}, repository.saveErr
}
repository.questionnaire, _ = domain.RestoreCandidateQuestionnaire(domain.StoredCandidateQuestionnaire{
UserID: questionnaire.UserID(), Version: expectedVersion + 1,
Specializations: questionnaire.Specializations(), WorkFormats: questionnaire.WorkFormats(),
CreatedAt: questionnaire.CreatedAt(), UpdatedAt: questionnaire.UpdatedAt(),
})
return repository.questionnaire, nil
}
func (repository *questionnaireTestRepository) AdvanceOnboarding(context.Context, uuid.UUID, time.Time) error {
repository.advanceCalls++
return repository.advanceErr
}
type questionnaireTestBank struct {
outbound.AssessmentBankRepository
availability []domain.SpecializationAvailability
err error
}
func (bank questionnaireTestBank) ListCurrentSpecializationAvailability(context.Context) ([]domain.SpecializationAvailability, error) {
return bank.availability, bank.err
}
func TestServiceRequiresVerifiedCandidateBeforeQuestionnaireAccess(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
tests := []struct {
name string
scenario domain.Scenario
verified bool
wantErr error
}{
{name: "verified candidate", scenario: domain.ScenarioCandidate, verified: true},
{name: "unverified candidate", scenario: domain.ScenarioCandidate, wantErr: ErrEmailNotVerified},
{name: "verified employer", scenario: domain.ScenarioEmployer, verified: true, wantErr: ErrForbidden},
{name: "unverified employer", scenario: domain.ScenarioEmployer, wantErr: ErrEmailNotVerified},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
id := uuid.Must(uuid.NewV7())
user := domain.User{ID: id, Scenario: test.scenario}
if test.verified {
user.EmailVerifiedAt = &now
}
users := &questionnaireTestUsers{user: user}
questionnaires := &questionnaireTestRepository{}
bank := questionnaireTestBank{availability: []domain.SpecializationAvailability{{
Specialization: domain.SpecializationBackend,
TaskLanguages: []domain.TaskLanguageCode{domain.TaskLanguageGo},
}}}
service := NewService(questionnaireTestTransactor{unit: questionnaireTestUnit{
users: users, questionnaire: questionnaires, bank: bank,
}}, func() time.Time { return now })
_, readErr := service.GetMyQuestionnaire(context.Background(), id)
if !errors.Is(readErr, test.wantErr) {
t.Fatalf("GetMyQuestionnaire() error = %v, want %v", readErr, test.wantErr)
}
_, saveErr := service.SaveMyQuestionnaire(context.Background(), id, 0, validQuestionnaireInput())
if !errors.Is(saveErr, test.wantErr) {
t.Fatalf("SaveMyQuestionnaire() error = %v, want %v", saveErr, test.wantErr)
}
wantReads, wantSaves, wantAdvances := 0, 0, 0
if test.wantErr == nil {
wantReads, wantSaves, wantAdvances = 2, 1, 1
}
if questionnaires.getCalls != wantReads || questionnaires.saveCalls != wantSaves || questionnaires.advanceCalls != wantAdvances {
t.Fatalf("questionnaire calls = get %d, save %d, advance %d; want %d, %d, %d", questionnaires.getCalls, questionnaires.saveCalls, questionnaires.advanceCalls, wantReads, wantSaves, wantAdvances)
}
})
}
}
func TestSaveMyQuestionnairePersistsChangesAndAdvancesAfterNoOp(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
id := uuid.Must(uuid.NewV7())
user := domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
users := &questionnaireTestUsers{user: user}
questionnaires := &questionnaireTestRepository{}
bank := questionnaireTestBank{availability: []domain.SpecializationAvailability{{
Specialization: domain.SpecializationBackend,
Grades: []domain.GradeCode{domain.GradeJunior},
TaskLanguages: []domain.TaskLanguageCode{domain.TaskLanguageGo},
}}}
service := NewService(questionnaireTestTransactor{unit: questionnaireTestUnit{
users: users, questionnaire: questionnaires, bank: bank,
}}, func() time.Time { return now })
input := validQuestionnaireInput()
first, err := service.SaveMyQuestionnaire(context.Background(), id, 0, input)
if err != nil {
t.Fatalf("SaveMyQuestionnaire(first) error = %v", err)
}
if first.Version() != 1 || questionnaires.saveCalls != 1 || questionnaires.advanceCalls != 1 {
t.Fatalf("first save version/calls = %d/%d/%d; want 1/1/1", first.Version(), questionnaires.saveCalls, questionnaires.advanceCalls)
}
input.Specializations[0].SelfAssessedGrade = domain.GradeSenior
second, err := service.SaveMyQuestionnaire(context.Background(), id, 1, input)
if err != nil {
t.Fatalf("SaveMyQuestionnaire(self-assessed senior) error = %v", err)
}
if second.Version() != 2 || second.Specializations()[0].SelfAssessedGrade != domain.GradeSenior {
t.Fatalf("saved self-assessment = version %d grade %q; want version 2 senior", second.Version(), second.Specializations()[0].SelfAssessedGrade)
}
if _, err := service.SaveMyQuestionnaire(context.Background(), id, 1, input); err != nil {
t.Fatalf("SaveMyQuestionnaire(stale identical retry) error = %v", err)
}
if questionnaires.saveCalls != 2 || questionnaires.advanceCalls != 3 {
t.Fatalf("save/onboarding calls = %d/%d; want 2/3", questionnaires.saveCalls, questionnaires.advanceCalls)
}
}
func TestSaveMyQuestionnaireRejectsUnavailableLanguageBeforeMutation(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
id := uuid.Must(uuid.NewV7())
user := domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
users := &questionnaireTestUsers{user: user}
questionnaires := &questionnaireTestRepository{}
bank := questionnaireTestBank{availability: []domain.SpecializationAvailability{{
Specialization: domain.SpecializationBackend,
TaskLanguages: []domain.TaskLanguageCode{domain.TaskLanguagePython},
}}}
service := NewService(questionnaireTestTransactor{unit: questionnaireTestUnit{
users: users, questionnaire: questionnaires, bank: bank,
}}, func() time.Time { return now })
_, err := service.SaveMyQuestionnaire(context.Background(), id, 0, validQuestionnaireInput())
fieldError, ok := errors.AsType[*domain.CandidateQuestionnaireFieldError](err)
if !ok || fieldError.Pointer != "/specializations/0/task_languages/0" {
t.Fatalf("SaveMyQuestionnaire(unavailable language) error = %v; want task-language field error", err)
}
if questionnaires.saveCalls != 0 || questionnaires.advanceCalls != 0 {
t.Fatalf("mutation calls after invalid language = save %d advance %d; want 0/0", questionnaires.saveCalls, questionnaires.advanceCalls)
}
}
func validQuestionnaireInput() domain.CandidateQuestionnaireInput {
return domain.CandidateQuestionnaireInput{
Specializations: []domain.QuestionnaireSpecialization{{
Specialization: domain.SpecializationBackend,
SelfAssessedGrade: domain.GradeJunior,
TaskLanguages: []domain.TaskLanguageCode{domain.TaskLanguageGo},
}},
WorkFormats: []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatRemote},
}
}