feat: persist candidate questionnaires and enforce company quotas
This commit is contained in:
1 parent
73c7caa225
commit
3a61a8e8bb
51 files changed
+6280
-38
No files matched your search
@@ -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})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user