252 lines
9.2 KiB
Go
252 lines
9.2 KiB
Go
package postgres
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"slices"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
var _ outbound.PrivacyCohortRepository = privacyCohortRepository{}
|
|
|
|
// PrivacyCohortStore reads the current visible candidate cohort outside a
|
|
// transaction. The single query provides one consistent publication and
|
|
// hidden-organization snapshot.
|
|
type PrivacyCohortStore struct {
|
|
queries *sqlc.Queries
|
|
}
|
|
|
|
func NewPrivacyCohortStore(pool *pgxpool.Pool) *PrivacyCohortStore {
|
|
return &PrivacyCohortStore{queries: sqlc.New(standaloneDB{pool: pool})}
|
|
}
|
|
|
|
func (unit *UnitOfWork) PrivacyCohort() outbound.PrivacyCohortRepository {
|
|
return privacyCohortRepository{queries: unit.queries}
|
|
}
|
|
|
|
func (unit *UnitOfWork) PrivacyView() outbound.PrivacyViewRepository {
|
|
return privacyCohortRepository{queries: unit.queries}
|
|
}
|
|
|
|
func (store *PrivacyCohortStore) ListVisibleCandidateViewSources(
|
|
ctx context.Context,
|
|
organizationID uuid.UUID,
|
|
) ([]domain.CandidateViewSource, error) {
|
|
return (privacyCohortRepository{queries: store.queries}).ListVisibleCandidateViewSources(ctx, organizationID)
|
|
}
|
|
|
|
type privacyCohortRepository struct {
|
|
queries *sqlc.Queries
|
|
}
|
|
|
|
type privacyCohortCandidate struct {
|
|
id uuid.UUID
|
|
fields domain.CardFieldSet
|
|
claims []domain.StoredProfileClaim
|
|
acknowledgements []domain.ProfileParallelPeriodAcknowledgement
|
|
workFormats []domain.QuestionnaireWorkFormat
|
|
categories []domain.CandidateViewConfirmedCategoryInput
|
|
}
|
|
|
|
func (repository privacyCohortRepository) ListVisibleCandidateViewSources(
|
|
ctx context.Context,
|
|
organizationID uuid.UUID,
|
|
) ([]domain.CandidateViewSource, error) {
|
|
const location = "privacyCohortRepository.ListVisibleCandidateViewSources"
|
|
if organizationID == uuid.Nil {
|
|
return nil, fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidCandidateViewSource)
|
|
}
|
|
rows, err := repository.queries.ListVisibleCandidateViewSources(ctx, pgUUID(organizationID))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s - select visible sources: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
if len(rows) == 0 {
|
|
return []domain.CandidateViewSource{}, nil
|
|
}
|
|
result := make([]domain.CandidateViewSource, 0, len(rows))
|
|
current := privacyCohortCandidate{}
|
|
for _, row := range rows {
|
|
candidateID, err := privacyCohortUUID(row.UserID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s - source identity is invalid: %w", location, domain.ErrInvalidCandidateViewSource)
|
|
}
|
|
if current.id != uuid.Nil && current.id != candidateID {
|
|
source, err := buildPrivacyCohortSource(current)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
|
|
}
|
|
result = append(result, source)
|
|
current = privacyCohortCandidate{}
|
|
}
|
|
if current.id == uuid.Nil {
|
|
current, err = newPrivacyCohortCandidate(candidateID, row.Fields, row.WorkFormats, row.ParallelPeriodAcknowledgements, row.ConfirmedCategories)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
|
|
}
|
|
}
|
|
if row.Kind.Valid {
|
|
claim, err := privacyCohortStoredClaim(row)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s - restore candidate claims: %w", location, err)
|
|
}
|
|
current.claims = append(current.claims, claim)
|
|
}
|
|
}
|
|
source, err := buildPrivacyCohortSource(current)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
|
|
}
|
|
result = append(result, source)
|
|
return result, nil
|
|
}
|
|
|
|
func newPrivacyCohortCandidate(
|
|
candidateID uuid.UUID,
|
|
fieldCodes []string,
|
|
workFormatCodes []string,
|
|
acknowledgementsValue any,
|
|
confirmedCategoriesValue any,
|
|
) (privacyCohortCandidate, error) {
|
|
fields := make([]domain.CardField, 0, len(fieldCodes))
|
|
for _, code := range fieldCodes {
|
|
fields = append(fields, domain.CardField(code))
|
|
}
|
|
fieldSet, err := domain.NewCardFieldSet(fields)
|
|
if err != nil {
|
|
return privacyCohortCandidate{}, fmt.Errorf("invalid publication fields: %w", domain.ErrInvalidCandidateViewSource)
|
|
}
|
|
workFormats := make([]domain.QuestionnaireWorkFormat, 0, len(workFormatCodes))
|
|
for _, code := range workFormatCodes {
|
|
workFormats = append(workFormats, domain.QuestionnaireWorkFormat(code))
|
|
}
|
|
acknowledgementsJSON, err := privacyCohortEncodedJSONBytes(acknowledgementsValue)
|
|
if err != nil {
|
|
return privacyCohortCandidate{}, fmt.Errorf("invalid overlap acknowledgements: %w", domain.ErrInvalidCandidateProfile)
|
|
}
|
|
var acknowledgements []domain.ProfileParallelPeriodAcknowledgement
|
|
if err := json.Unmarshal(acknowledgementsJSON, &acknowledgements); err != nil {
|
|
return privacyCohortCandidate{}, fmt.Errorf("invalid overlap acknowledgements: %w", domain.ErrInvalidCandidateProfile)
|
|
}
|
|
categories, err := privacyCohortConfirmedCategories(confirmedCategoriesValue)
|
|
if err != nil {
|
|
return privacyCohortCandidate{}, err
|
|
}
|
|
return privacyCohortCandidate{
|
|
id: candidateID, fields: fieldSet, workFormats: workFormats,
|
|
acknowledgements: acknowledgements, categories: categories,
|
|
}, nil
|
|
}
|
|
|
|
// privacyCohortCategoryStrength is the card strength of a demonstration
|
|
// category. The synthetic demo source has no adaptive confirmation, so no
|
|
// category is reported as strong.
|
|
const privacyCohortCategoryStrength = domain.CandidateViewStrengthStandard
|
|
|
|
// privacyCohortConfirmedCategories reads the current categories selected by
|
|
// the cohort query: a specialization, a grade, and the basis of each, never the
|
|
// attempt, score, policy, or review that produced it. A category without a
|
|
// known basis is rejected rather than shown as a real confirmation.
|
|
func privacyCohortConfirmedCategories(value any) ([]domain.CandidateViewConfirmedCategoryInput, error) {
|
|
encoded, err := privacyCohortEncodedJSONBytes(value)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid confirmed categories: %w", domain.ErrInvalidCandidateViewSource)
|
|
}
|
|
var stored []struct {
|
|
Specialization domain.SpecializationCode `json:"specialization"`
|
|
Grade domain.GradeCode `json:"grade"`
|
|
Source domain.AssessmentCategorySource `json:"source"`
|
|
}
|
|
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
|
decoder.DisallowUnknownFields()
|
|
if err := decoder.Decode(&stored); err != nil {
|
|
return nil, fmt.Errorf("invalid confirmed categories: %w", domain.ErrInvalidCandidateViewSource)
|
|
}
|
|
categories := make([]domain.CandidateViewConfirmedCategoryInput, 0, len(stored))
|
|
for _, category := range stored {
|
|
if !category.Source.IsKnown() {
|
|
return nil, fmt.Errorf("confirmed category has an unknown basis: %w", domain.ErrInvalidCandidateViewSource)
|
|
}
|
|
categories = append(categories, domain.CandidateViewConfirmedCategoryInput{
|
|
Specialization: category.Specialization, Grade: category.Grade,
|
|
Strength: privacyCohortCategoryStrength, Basis: category.Source,
|
|
})
|
|
}
|
|
return categories, nil
|
|
}
|
|
|
|
func privacyCohortStoredClaim(row sqlc.ListVisibleCandidateViewSourcesRow) (domain.StoredProfileClaim, error) {
|
|
value, err := privacyCohortJSONBytes(row.SafeValue)
|
|
if err != nil {
|
|
return domain.StoredProfileClaim{}, fmt.Errorf("safe JSON type %T is invalid: %w", row.SafeValue, domain.ErrInvalidCandidateProfile)
|
|
}
|
|
if !row.Ordinal.Valid || !row.Status.Valid || !row.Origin.Valid || !row.TrustLevel.Valid {
|
|
return domain.StoredProfileClaim{}, fmt.Errorf("claim metadata is incomplete: %w", domain.ErrInvalidCandidateProfile)
|
|
}
|
|
confirmedAt := time.Time{}
|
|
if row.ConfirmedAt.Valid {
|
|
confirmedAt = row.ConfirmedAt.Time.UTC()
|
|
}
|
|
return domain.StoredProfileClaim{
|
|
Kind: row.Kind.String, Ordinal: int(row.Ordinal.Int16), Value: value,
|
|
Status: row.Status.String, Origin: row.Origin.String, TrustLevel: int(row.TrustLevel.Int16),
|
|
ExtractionVersion: row.ExtractionVersion.String, ConfirmedAt: confirmedAt,
|
|
}, nil
|
|
}
|
|
|
|
func buildPrivacyCohortSource(candidate privacyCohortCandidate) (domain.CandidateViewSource, error) {
|
|
content, err := domain.RestoreCandidateProfileContentWithParallelPeriods(candidate.claims, candidate.acknowledgements)
|
|
if err != nil {
|
|
return domain.CandidateViewSource{}, fmt.Errorf("validate safe profile claims: %w", domain.ErrInvalidCandidateViewSource)
|
|
}
|
|
return domain.NewCandidateViewSource(
|
|
candidate.id, candidate.fields, domain.CandidateViewProfileFromContent(content), candidate.categories,
|
|
candidate.workFormats, nil,
|
|
)
|
|
}
|
|
|
|
func privacyCohortJSONBytes(value any) ([]byte, error) {
|
|
switch typed := value.(type) {
|
|
case []byte:
|
|
return slices.Clone(typed), nil
|
|
case json.RawMessage:
|
|
return slices.Clone(typed), nil
|
|
default:
|
|
encoded, err := json.Marshal(typed)
|
|
if err != nil {
|
|
return nil, errors.New("JSON projection has an unexpected type")
|
|
}
|
|
return encoded, nil
|
|
}
|
|
}
|
|
|
|
func privacyCohortEncodedJSONBytes(value any) ([]byte, error) {
|
|
switch typed := value.(type) {
|
|
case string:
|
|
return []byte(typed), nil
|
|
case []byte:
|
|
return slices.Clone(typed), nil
|
|
case json.RawMessage:
|
|
return slices.Clone(typed), nil
|
|
default:
|
|
return nil, errors.New("encoded JSON projection has an unexpected type")
|
|
}
|
|
}
|
|
|
|
func privacyCohortUUID(value pgtype.UUID) (uuid.UUID, error) {
|
|
if !value.Valid || value.Bytes == uuid.Nil {
|
|
return uuid.Nil, domain.ErrInvalidCandidateViewSource
|
|
}
|
|
return uuid.UUID(value.Bytes), nil
|
|
}
|