feat(assessment): assign the demonstration category and keep result history
This commit is contained in:
1 parent
b3c6dc870b
commit
8277133712
61 files changed
+4338
-268
No files matched your search
@@ -0,0 +1,151 @@
|
||||
// Package categoryattest implements the local operator command that attests the
|
||||
// current opening of an assessment category as a source of synthetic
|
||||
// demonstration categories. It is meant for isolated synthetic stands: a
|
||||
// category is assigned only when the runtime gate
|
||||
// ASSESSMENT_DEMO_CATEGORIES_ENABLED is also on.
|
||||
package categoryattest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
// syntheticOnlyWarning is printed before any work, also when the command fails.
|
||||
const syntheticOnlyWarning = "warning: synthetic demonstration categories are enabled by this attestation; never on a production stand\n"
|
||||
|
||||
const usage = "usage: assessment-category-attest attest --specialization <code> --grade <code> [--task-language <code>] --actor operator:<handle>"
|
||||
|
||||
// Command is a parsed, validated attestation request.
|
||||
type Command struct {
|
||||
Specialization domain.SpecializationCode
|
||||
Grade domain.GradeCode
|
||||
TaskLanguage *domain.TaskLanguageCode
|
||||
Actor string
|
||||
}
|
||||
|
||||
// Attestor stores an attestation.
|
||||
type Attestor interface {
|
||||
Attest(
|
||||
ctx context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
language *domain.TaskLanguageCode,
|
||||
actor string,
|
||||
) (assessment.CategoryAttestation, error)
|
||||
}
|
||||
|
||||
// Parse validates every argument before Run reads configuration or connects
|
||||
// to PostgreSQL.
|
||||
func Parse(args []string) (Command, error) {
|
||||
if len(args) == 0 || args[0] != "attest" {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
flags := flag.NewFlagSet("assessment-category-attest attest", flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard)
|
||||
specialization := flags.String("specialization", "", "specialization code")
|
||||
grade := flags.String("grade", "", "grade code")
|
||||
language := flags.String("task-language", "", "task language code")
|
||||
actor := flags.String("actor", "", "operator handle")
|
||||
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
command := Command{
|
||||
Specialization: domain.SpecializationCode(strings.TrimSpace(*specialization)),
|
||||
Grade: domain.GradeCode(strings.TrimSpace(*grade)),
|
||||
Actor: strings.TrimSpace(*actor),
|
||||
}
|
||||
if !command.Specialization.IsKnown() {
|
||||
return Command{}, errors.New("specialization must be a known specialization code")
|
||||
}
|
||||
if !command.Grade.IsKnown() {
|
||||
return Command{}, errors.New("grade must be intern, junior, middle, or senior")
|
||||
}
|
||||
if trimmed := strings.TrimSpace(*language); trimmed != "" {
|
||||
taskLanguage := domain.TaskLanguageCode(trimmed)
|
||||
if !taskLanguage.IsKnown() {
|
||||
return Command{}, errors.New("task language must be a known task language code")
|
||||
}
|
||||
command.TaskLanguage = &taskLanguage
|
||||
}
|
||||
if _, err := domain.ParseAssessmentOperator(command.Actor); err != nil {
|
||||
return Command{}, errors.New("actor must be operator:<handle>")
|
||||
}
|
||||
return command, nil
|
||||
}
|
||||
|
||||
// Run parses the command, loads only DATABASE_URL from the supplied
|
||||
// environment, and executes the attestation. It does not load dotenv files.
|
||||
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer) error {
|
||||
command, err := Parse(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if lookup == nil || output == nil {
|
||||
return errors.New("category attestation command dependencies are required")
|
||||
}
|
||||
databaseURL := config.DatabaseURLFromEnv(lookup)
|
||||
if databaseURL == "" {
|
||||
return errors.New("DATABASE_URL is not set")
|
||||
}
|
||||
pool, err := postgres.NewPool(ctx, databaseURL)
|
||||
if err != nil {
|
||||
return errors.New("database configuration is invalid")
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
return errors.New("database is unavailable")
|
||||
}
|
||||
attestor, err := assessment.NewCategoryAttestor(postgres.NewTransactor(pool))
|
||||
if err != nil {
|
||||
return errors.New("category attestation is unavailable")
|
||||
}
|
||||
return Execute(ctx, command, attestor, output)
|
||||
}
|
||||
|
||||
// Execute stores the attestation and prints identifiers and versions only; it
|
||||
// prints no candidate, answer, or contact data.
|
||||
func Execute(ctx context.Context, command Command, attestor Attestor, output io.Writer) error {
|
||||
if attestor == nil || output == nil {
|
||||
return errors.New("category attestation command dependencies are required")
|
||||
}
|
||||
if _, err := io.WriteString(output, syntheticOnlyWarning); err != nil {
|
||||
return errors.New("could not write the result")
|
||||
}
|
||||
attestation, err := attestor.Attest(ctx, command.Specialization, command.Grade, command.TaskLanguage, command.Actor)
|
||||
if err != nil {
|
||||
return safeOperationError(err)
|
||||
}
|
||||
status := "already attested"
|
||||
if attestation.Created {
|
||||
status = "attested"
|
||||
}
|
||||
if _, err := fmt.Fprintf(output,
|
||||
"%s: category %s, opening %s, review %s, policy_version %d, by %s\n"+
|
||||
"note: synthetic demonstration only; categories are assigned only while ASSESSMENT_DEMO_CATEGORIES_ENABLED is true on this stand\n",
|
||||
status, attestation.Category, attestation.OpeningID, attestation.ReviewID, attestation.ProductPolicyVersion, attestation.ReviewedBy,
|
||||
); err != nil {
|
||||
return errors.New("could not write the result")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeOperationError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, outbound.ErrAssessmentSelectionUnavailable), errors.Is(err, outbound.ErrAssessmentSelectionAmbiguous):
|
||||
return errors.New("no single current reviewed category matches the request")
|
||||
case errors.Is(err, domain.ErrInvalidAssessmentCategory):
|
||||
return errors.New("the request is invalid or the current policy is not the explicit demo_basic demonstration policy")
|
||||
default:
|
||||
return errors.New("category attestation failed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package categoryattest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
type attestorFake struct {
|
||||
attestation assessment.CategoryAttestation
|
||||
err error
|
||||
calls int
|
||||
command Command
|
||||
}
|
||||
|
||||
func (attestor *attestorFake) Attest(
|
||||
_ context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
language *domain.TaskLanguageCode,
|
||||
actor string,
|
||||
) (assessment.CategoryAttestation, error) {
|
||||
attestor.calls++
|
||||
attestor.command = Command{Specialization: specialization, Grade: grade, TaskLanguage: language, Actor: actor}
|
||||
return attestor.attestation, attestor.err
|
||||
}
|
||||
|
||||
func TestParseRequiresATrackAndAnOperatorHandle(t *testing.T) {
|
||||
command, err := Parse([]string{"attest", "--specialization", "backend", "--grade", "intern", "--task-language", "go", "--actor", "operator:night"})
|
||||
if err != nil || command.Specialization != domain.SpecializationBackend || command.Grade != domain.GradeIntern ||
|
||||
command.TaskLanguage == nil || *command.TaskLanguage != domain.TaskLanguageGo || command.Actor != "operator:night" {
|
||||
t.Fatalf("Parse(valid) = %+v, %v", command, err)
|
||||
}
|
||||
if command, err := Parse([]string{"attest", "--specialization", "backend", "--grade", "junior", "--actor", "operator:night"}); err != nil || command.TaskLanguage != nil {
|
||||
t.Fatalf("Parse(without language) = %+v, %v", command, err)
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
nil,
|
||||
{"list"},
|
||||
{"attest"},
|
||||
{"attest", "--specialization", "backend", "--grade", "junior"},
|
||||
{"attest", "--specialization", "backend", "--grade", "junior", "--actor", "alice"},
|
||||
{"attest", "--specialization", "chef", "--grade", "junior", "--actor", "operator:night"},
|
||||
{"attest", "--specialization", "backend", "--grade", "lead", "--actor", "operator:night"},
|
||||
{"attest", "--specialization", "backend", "--grade", "junior", "--task-language", "cobol", "--actor", "operator:night"},
|
||||
{"attest", "--specialization", "backend", "--grade", "junior", "--actor", "operator:night", "extra"},
|
||||
} {
|
||||
if _, err := Parse(args); err == nil {
|
||||
t.Errorf("Parse(%v) accepted invalid arguments", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunValidatesArgumentsBeforeReadingTheEnvironment(t *testing.T) {
|
||||
lookup := func(string) (string, bool) {
|
||||
t.Fatal("environment read before arguments were validated")
|
||||
return "", false
|
||||
}
|
||||
if err := Run(context.Background(), []string{"attest"}, lookup, &bytes.Buffer{}); err == nil {
|
||||
t.Fatal("Run(invalid arguments) succeeded")
|
||||
}
|
||||
var noDatabase config.LookupEnv = func(string) (string, bool) { return "", false }
|
||||
err := Run(context.Background(), []string{"attest", "--specialization", "backend", "--grade", "intern", "--actor", "operator:night"}, noDatabase, &bytes.Buffer{})
|
||||
if err == nil || !strings.Contains(err.Error(), "DATABASE_URL") {
|
||||
t.Fatalf("Run(no database) error = %v, want a DATABASE_URL message", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutePrintsIdentifiersAndTheSyntheticOnlyNote(t *testing.T) {
|
||||
attestor := &attestorFake{attestation: assessment.CategoryAttestation{
|
||||
ReviewID: uuid.New(), OpeningID: uuid.New(), Category: "backend-intern", ProductPolicyVersion: 2,
|
||||
ReviewedBy: "operator:night", Created: true,
|
||||
}}
|
||||
var output bytes.Buffer
|
||||
command := Command{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern, Actor: "operator:night"}
|
||||
if err := Execute(context.Background(), command, attestor, &output); err != nil {
|
||||
t.Fatalf("Execute() error = %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(output.String(), "warning: synthetic demonstration categories are enabled by this attestation; never on a production stand") {
|
||||
t.Errorf("output does not start with the synthetic-only warning:\n%s", output.String())
|
||||
}
|
||||
for _, want := range []string{"attested: category backend-intern", attestor.attestation.ReviewID.String(), "policy_version 2", "by operator:night", "synthetic demonstration only", "ASSESSMENT_DEMO_CATEGORIES_ENABLED"} {
|
||||
if !strings.Contains(output.String(), want) {
|
||||
t.Errorf("output lacks %q:\n%s", want, output.String())
|
||||
}
|
||||
}
|
||||
attestor.attestation.Created = false
|
||||
output.Reset()
|
||||
if err := Execute(context.Background(), command, attestor, &output); err != nil || !strings.Contains(output.String(), "\nalready attested") {
|
||||
t.Fatalf("Execute(repeat) = %v, %q, want an already attested line", err, output.String())
|
||||
}
|
||||
if attestor.calls != 2 || attestor.command.Actor != "operator:night" || attestor.command.Grade != domain.GradeIntern {
|
||||
t.Fatalf("attestor calls/command = %d/%+v, want the parsed request", attestor.calls, attestor.command)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteMapsFailuresToSafeMessages(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
{outbound.ErrAssessmentSelectionUnavailable, "no single current reviewed category"},
|
||||
{domain.ErrInvalidAssessmentCategory, "demo_basic"},
|
||||
{errors.New("pq: password authentication failed for user lincodex at 10.0.0.5"), "attestation failed"},
|
||||
} {
|
||||
err := Execute(context.Background(), Command{}, &attestorFake{err: test.err}, &bytes.Buffer{})
|
||||
if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "10.0.0.5") {
|
||||
t.Errorf("Execute(%v) error = %v, want a safe %q message", test.err, err, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -302,6 +302,9 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
continue
|
||||
}
|
||||
for reached := range reachableSchemas(index, mustJSONValue(t, schema)) {
|
||||
if searchResultMayReachCardBand(name, reached) {
|
||||
continue
|
||||
}
|
||||
if isPrivacySchema(reached) && reached != "AnonymousCardContent" && reached != "CardCategory" && reached != "CardField" && reached != "CardFieldSet" {
|
||||
t.Errorf("%s reaches the candidate-private schema %s", name, reached)
|
||||
}
|
||||
@@ -320,6 +323,9 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
}, reached) {
|
||||
continue
|
||||
}
|
||||
if path == "/api/v1/organizations/{org_id}/matches" && searchResultMayReachCardBand("Match", reached) {
|
||||
continue
|
||||
}
|
||||
if isPrivacySchema(reached) {
|
||||
t.Errorf("%s reaches the candidate-private schema %s", path, reached)
|
||||
}
|
||||
@@ -332,6 +338,18 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// searchResultMayReachCardBand reports whether a match search schema reaches
|
||||
// one of the two coarse leaves that the anonymous card itself carries: the
|
||||
// salary compatibility (a compatible or not_compatible verdict, never an
|
||||
// amount) and the experience band (a coarse bucket, never a date). The search
|
||||
// contract reuses the card content, so its filters and results legitimately
|
||||
// name these leaves. Only match schemas get this allowance; no other
|
||||
// organization-visible schema may reach a privacy schema.
|
||||
func searchResultMayReachCardBand(schema, reached string) bool {
|
||||
return strings.HasPrefix(schema, "Match") &&
|
||||
(reached == "CandidateSalaryCompatibility" || reached == "CandidateExperienceBand")
|
||||
}
|
||||
|
||||
// The generated request DTOs carry only what the candidate may choose: no
|
||||
// consent identifier, time, interval, or policy version.
|
||||
func TestGeneratedPrivacyDTOsCarryNoServerOwnedFields(t *testing.T) {
|
||||
|
||||
@@ -36,6 +36,10 @@ var ownerCompanyOperations = map[apiadapter.OperationName]struct{}{
|
||||
apiadapter.GetOrganizationInvitationContactsOperation: {},
|
||||
apiadapter.WithdrawOrganizationInvitationOperation: {},
|
||||
apiadapter.RaiseOrganizationInvitationSalaryOperation: {},
|
||||
// The match search contract requires an active owner membership. The
|
||||
// operation has no handler yet; classifying it here keeps it closed to
|
||||
// every other role when the handler arrives.
|
||||
apiadapter.SearchOrganizationMatchesOperation: {},
|
||||
}
|
||||
|
||||
// NewCompanyContextMiddleware verifies every owner-scoped company operation
|
||||
|
||||
@@ -124,8 +124,8 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
|
||||
if err := yaml.Unmarshal(data, &document); err != nil {
|
||||
t.Fatalf("decode OpenAPI bundle: %v", err)
|
||||
}
|
||||
if len(ownerCompanyOperations) != 14 {
|
||||
t.Fatalf("owner operation inventory has %d entries, want 14", len(ownerCompanyOperations))
|
||||
if len(ownerCompanyOperations) != 15 {
|
||||
t.Fatalf("owner operation inventory has %d entries, want 15", len(ownerCompanyOperations))
|
||||
}
|
||||
candidateExceptions := map[string]string{
|
||||
"HideOrganization": "/api/v1/me/privacy/hidden-organizations/{org_id}",
|
||||
|
||||
@@ -507,25 +507,40 @@ func assessmentResultResponse(result assessmentusecase.AssessmentAttemptResult)
|
||||
NextSteps: []api.AssessmentNextStep{}, Summary: result.Summary, DecidedAt: api.Timestamp(result.DecidedAt),
|
||||
}), nil
|
||||
}
|
||||
if result.Attempt.Kind != domain.AssessmentAttemptKindRoot && result.Attempt.Kind != domain.AssessmentAttemptKindCorrective {
|
||||
return api.AssessmentResult{}, errors.New("real result kind is invalid")
|
||||
}
|
||||
if result.Attempt.Specialization == nil || result.Attempt.TargetGrade == nil || result.DecidedAt.IsZero() {
|
||||
return api.AssessmentResult{}, errors.New("real result track or decision time is incomplete")
|
||||
}
|
||||
fields, err := assessmentRealResultFields(result)
|
||||
realResult, err := assessmentRealResultResponse(result)
|
||||
if err != nil {
|
||||
return api.AssessmentResult{}, err
|
||||
}
|
||||
if realResult.Type == api.AssessmentQualifiedResultAssessmentRealResult {
|
||||
return api.NewAssessmentQualifiedResultAssessmentResult(realResult.AssessmentQualifiedResult), nil
|
||||
}
|
||||
return api.NewAssessmentCorrectiveResultAssessmentResult(realResult.AssessmentCorrectiveResult), nil
|
||||
}
|
||||
|
||||
// assessmentRealResultResponse maps a completed root or corrective result. It
|
||||
// serves both the single result read and the owner's history, so the two never
|
||||
// describe the same stored result differently.
|
||||
func assessmentRealResultResponse(result assessmentusecase.AssessmentAttemptResult) (api.AssessmentRealResult, error) {
|
||||
if result.Attempt.Kind != domain.AssessmentAttemptKindRoot && result.Attempt.Kind != domain.AssessmentAttemptKindCorrective {
|
||||
return api.AssessmentRealResult{}, errors.New("real result kind is invalid")
|
||||
}
|
||||
if result.Attempt.Specialization == nil || result.Attempt.TargetGrade == nil || result.DecidedAt.IsZero() {
|
||||
return api.AssessmentRealResult{}, errors.New("real result track or decision time is incomplete")
|
||||
}
|
||||
fields, err := assessmentRealResultFields(result)
|
||||
if err != nil {
|
||||
return api.AssessmentRealResult{}, err
|
||||
}
|
||||
if result.Attempt.Kind == domain.AssessmentAttemptKindRoot {
|
||||
return api.NewAssessmentQualifiedResultAssessmentResult(api.AssessmentQualifiedResult{
|
||||
return api.NewAssessmentQualifiedResultAssessmentRealResult(api.AssessmentQualifiedResult{
|
||||
AttemptID: result.Attempt.ID.UUID(), Specialization: api.SpecializationCode(*result.Attempt.Specialization),
|
||||
TargetGrade: api.GradeCode(*result.Attempt.TargetGrade), RootAttemptID: fields.rootAttemptID,
|
||||
ChainDeadline: fields.chainDeadline, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentQualifiedResultKindRoot, Mode: api.AssessmentQualifiedResultMode(result.Attempt.Mode),
|
||||
Versions: assessmentResultVersions(result.Attempt), Outcome: fields.outcome,
|
||||
NotDeterminedReason: fields.reason, ConfirmedGrade: fields.confirmedGrade,
|
||||
PreviousConfirmedGrade: fields.previousGrade, Strength: fields.strength,
|
||||
PreviousConfirmedGrade: fields.previousGrade, CategoryDecision: fields.categoryDecision,
|
||||
Strength: fields.strength,
|
||||
CalibrationStatus: api.CalibrationStatusUncalibrated, Limitations: fields.limitations,
|
||||
Uncertainty: fields.uncertainty, BasicScore: fields.basicScore, Practices: []api.AssessmentPracticeResult{},
|
||||
Gaps: []api.AssessmentGap{}, Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
|
||||
@@ -533,16 +548,17 @@ func assessmentResultResponse(result assessmentusecase.AssessmentAttemptResult)
|
||||
}), nil
|
||||
}
|
||||
if result.Attempt.RootAttemptID == nil || result.Attempt.ChainDeadline == nil {
|
||||
return api.AssessmentResult{}, errors.New("corrective result chain is incomplete")
|
||||
return api.AssessmentRealResult{}, errors.New("corrective result chain is incomplete")
|
||||
}
|
||||
return api.NewAssessmentCorrectiveResultAssessmentResult(api.AssessmentCorrectiveResult{
|
||||
return api.NewAssessmentCorrectiveResultAssessmentRealResult(api.AssessmentCorrectiveResult{
|
||||
AttemptID: result.Attempt.ID.UUID(), Specialization: api.SpecializationCode(*result.Attempt.Specialization),
|
||||
TargetGrade: api.GradeCode(*result.Attempt.TargetGrade), RootAttemptID: fields.rootAttemptID,
|
||||
ChainDeadline: fields.chainDeadline, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentCorrectiveResultKindCorrective, Mode: api.AssessmentCorrectiveResultMode(result.Attempt.Mode),
|
||||
Versions: assessmentResultVersions(result.Attempt), Outcome: fields.outcome,
|
||||
NotDeterminedReason: fields.reason, ConfirmedGrade: fields.confirmedGrade,
|
||||
PreviousConfirmedGrade: fields.previousGrade, Strength: fields.strength,
|
||||
PreviousConfirmedGrade: fields.previousGrade, CategoryDecision: fields.categoryDecision,
|
||||
Strength: fields.strength,
|
||||
CalibrationStatus: api.CalibrationStatusUncalibrated, Limitations: fields.limitations,
|
||||
Uncertainty: fields.uncertainty, BasicScore: fields.basicScore, Practices: []api.AssessmentPracticeResult{},
|
||||
Gaps: []api.AssessmentGap{}, Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
|
||||
@@ -558,10 +574,13 @@ type assessmentRealResultResponseFields struct {
|
||||
reason api.NilAssessmentNotDeterminedReason
|
||||
confirmedGrade api.NilGradeCode
|
||||
previousGrade api.NilGradeCode
|
||||
strength api.NilAssessmentStrength
|
||||
limitations []api.AssessmentLimitation
|
||||
uncertainty api.NilAssessmentUncertainty
|
||||
basicScore api.NilBasicScore
|
||||
// categoryDecision is absent for a legacy result stored before category
|
||||
// decisions existed; its grade is never inferred from the current state.
|
||||
categoryDecision api.OptAssessmentCategoryDecisionView
|
||||
strength api.NilAssessmentStrength
|
||||
limitations []api.AssessmentLimitation
|
||||
uncertainty api.NilAssessmentUncertainty
|
||||
basicScore api.NilBasicScore
|
||||
}
|
||||
|
||||
func assessmentRealResultFields(result assessmentusecase.AssessmentAttemptResult) (assessmentRealResultResponseFields, error) {
|
||||
@@ -588,8 +607,7 @@ func assessmentRealResultFields(result assessmentusecase.AssessmentAttemptResult
|
||||
} else {
|
||||
fields.reason.SetTo(api.AssessmentNotDeterminedReason(result.NotDeterminedReason))
|
||||
}
|
||||
fields.confirmedGrade.SetToNull()
|
||||
fields.previousGrade.SetToNull()
|
||||
setAssessmentCategoryFields(&fields, result.CategoryDecision)
|
||||
fields.strength.SetToNull()
|
||||
fields.uncertainty.SetToNull()
|
||||
if result.BasicScore == nil {
|
||||
@@ -605,6 +623,45 @@ func assessmentRealResultFields(result assessmentusecase.AssessmentAttemptResult
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
// setAssessmentCategoryFields copies the stored category decision. A result
|
||||
// confirms its target grade only when a reviewed synthetic source accepted the
|
||||
// outcome (assigned, or unchanged because the grade was not higher); a passing
|
||||
// score without such a source claims no category.
|
||||
func setAssessmentCategoryFields(fields *assessmentRealResultResponseFields, decision *domain.AssessmentCategoryDecisionSnapshot) {
|
||||
fields.confirmedGrade.SetToNull()
|
||||
fields.previousGrade.SetToNull()
|
||||
if decision == nil {
|
||||
return
|
||||
}
|
||||
view := api.AssessmentCategoryDecisionView{Status: api.AssessmentCategoryDecisionViewStatus(decision.Status)}
|
||||
view.PreviousConfirmedGrade.SetToNull()
|
||||
view.CurrentConfirmedGrade.SetToNull()
|
||||
view.Method.SetToNull()
|
||||
view.Source.SetToNull()
|
||||
view.CalibrationStatus.SetToNull()
|
||||
if decision.PreviousGrade != nil {
|
||||
fields.previousGrade.SetTo(api.GradeCode(*decision.PreviousGrade))
|
||||
view.PreviousConfirmedGrade.SetTo(api.GradeCode(*decision.PreviousGrade))
|
||||
}
|
||||
if decision.CurrentGrade != nil {
|
||||
view.CurrentConfirmedGrade.SetTo(api.GradeCode(*decision.CurrentGrade))
|
||||
}
|
||||
if decision.Method != "" {
|
||||
view.Method.SetTo(api.AssessmentCategoryDecisionViewMethod(decision.Method))
|
||||
}
|
||||
if decision.Source != "" {
|
||||
view.Source.SetTo(api.AssessmentCategoryDecisionViewSource(decision.Source))
|
||||
}
|
||||
if decision.CalibrationStatus != "" {
|
||||
view.CalibrationStatus.SetTo(api.CalibrationStatus(decision.CalibrationStatus))
|
||||
}
|
||||
if (decision.Status == domain.AssessmentCategoryDecisionAssigned || decision.Status == domain.AssessmentCategoryDecisionUnchanged) &&
|
||||
decision.AttemptedGrade != nil {
|
||||
fields.confirmedGrade.SetTo(api.GradeCode(*decision.AttemptedGrade))
|
||||
}
|
||||
fields.categoryDecision.SetTo(view)
|
||||
}
|
||||
|
||||
func assessmentResultVersions(snapshot domain.AssessmentAttemptPublicSnapshot) api.AssessmentVersions {
|
||||
return api.AssessmentVersions{
|
||||
PolicyVersion: snapshot.PolicyVersion, BankVersion: api.AssessmentVersionLabel(snapshot.BankVersion),
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
assessmentusecase "lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
// AssessmentResultOperations reads the candidate's immutable result history.
|
||||
// An employer has no operation here; the current category reaches an employer
|
||||
// only through the anonymous card.
|
||||
type AssessmentResultOperations interface {
|
||||
ListMyResults(ctx context.Context, userID uuid.UUID, cursor string, limit int32) (assessmentusecase.AssessmentResultHistoryPage, error)
|
||||
}
|
||||
|
||||
func (handler *Handler) ListMyAssessmentResults(
|
||||
ctx context.Context,
|
||||
params api.ListMyAssessmentResultsParams,
|
||||
) (api.ListMyAssessmentResultsRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.ListMyAssessmentResults(ctx, params)
|
||||
}
|
||||
return handler.assessment.ListMyAssessmentResults(ctx, params)
|
||||
}
|
||||
|
||||
// ListMyAssessmentResults serves the owner-only history. The operations of
|
||||
// AssessmentHandler provide it as an optional capability, like GetMyResult.
|
||||
func (handler *AssessmentHandler) ListMyAssessmentResults(
|
||||
ctx context.Context,
|
||||
params api.ListMyAssessmentResultsParams,
|
||||
) (api.ListMyAssessmentResultsRes, error) {
|
||||
const location = "AssessmentHandler.ListMyAssessmentResults"
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListMyAssessmentResultsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
operations, ok := handler.operations.(AssessmentResultOperations)
|
||||
if !ok {
|
||||
return nil, errors.New(location + " - result history operation is unavailable")
|
||||
}
|
||||
// The generated validator has already bounded limit to the contract range.
|
||||
page, err := operations.ListMyResults(ctx, principal.UserID, params.Cursor.Or(""), params.Limit.Or(0))
|
||||
if err != nil {
|
||||
return assessmentResultsFailure(ctx, err)
|
||||
}
|
||||
items := make([]api.AssessmentRealResult, 0, len(page.Entries))
|
||||
for _, entry := range page.Entries {
|
||||
item, err := assessmentRealResultResponse(assessmentusecase.AssessmentAttemptResultFromHistoryEntry(entry))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - map stored result: %w", location, err)
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
next := api.NilString{}
|
||||
if page.NextCursor == "" {
|
||||
next.SetToNull()
|
||||
} else {
|
||||
next.SetTo(page.NextCursor)
|
||||
}
|
||||
return &api.AssessmentResultHistoryPageHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.AssessmentResultHistoryPage{Items: items, Page: api.PageInfo{HasMore: page.NextCursor != "", NextCursor: next}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func assessmentResultsFailure(ctx context.Context, err error) (api.ListMyAssessmentResultsRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAssessmentResultHistoryRequest):
|
||||
return (*api.ListMyAssessmentResultsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/cursor").Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified):
|
||||
return (*api.ListMyAssessmentResultsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
func gradePtr(grade domain.GradeCode) *domain.GradeCode { return &grade }
|
||||
|
||||
func TestAssessmentCategoryFieldsClaimAGradeOnlyForAReviewedConfirmation(t *testing.T) {
|
||||
specialization := domain.SpecializationBackend
|
||||
reviewed := func(status domain.AssessmentCategoryDecisionStatus, attempted domain.GradeCode, previous, current *domain.GradeCode) *domain.AssessmentCategoryDecisionSnapshot {
|
||||
return &domain.AssessmentCategoryDecisionSnapshot{
|
||||
AttemptID: domain.AssessmentAttemptID(uuid.New()), Specialization: &specialization, AttemptedGrade: gradePtr(attempted),
|
||||
PreviousGrade: previous, CurrentGrade: current, Status: status,
|
||||
Method: domain.AssessmentCategoryDecisionDemoBasicPassMark, Source: domain.AssessmentCategorySourceSyntheticDemo,
|
||||
CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated, DecidedAt: time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC),
|
||||
}
|
||||
}
|
||||
notEligible := &domain.AssessmentCategoryDecisionSnapshot{
|
||||
AttemptID: domain.AssessmentAttemptID(uuid.New()), Specialization: &specialization, AttemptedGrade: gradePtr(domain.GradeJunior),
|
||||
PreviousGrade: gradePtr(domain.GradeIntern), CurrentGrade: gradePtr(domain.GradeIntern),
|
||||
Status: domain.AssessmentCategoryDecisionNotEligible,
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
decision *domain.AssessmentCategoryDecisionSnapshot
|
||||
wantConfirmed string
|
||||
wantPrevious string
|
||||
wantView bool
|
||||
}{
|
||||
{name: "legacy result without a decision", decision: nil},
|
||||
{name: "assigned", decision: reviewed(domain.AssessmentCategoryDecisionAssigned, domain.GradeJunior, gradePtr(domain.GradeIntern), gradePtr(domain.GradeJunior)),
|
||||
wantConfirmed: "junior", wantPrevious: "intern", wantView: true},
|
||||
{name: "unchanged", decision: reviewed(domain.AssessmentCategoryDecisionUnchanged, domain.GradeIntern, gradePtr(domain.GradeMiddle), gradePtr(domain.GradeMiddle)),
|
||||
wantConfirmed: "intern", wantPrevious: "middle", wantView: true},
|
||||
{name: "not confirmed keeps the previous grade", decision: reviewed(domain.AssessmentCategoryDecisionNotConfirmed, domain.GradeJunior, gradePtr(domain.GradeIntern), gradePtr(domain.GradeIntern)),
|
||||
wantPrevious: "intern", wantView: true},
|
||||
{name: "not eligible claims no grade", decision: notEligible, wantPrevious: "intern", wantView: true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var fields assessmentRealResultResponseFields
|
||||
setAssessmentCategoryFields(&fields, test.decision)
|
||||
confirmed, confirmedSet := fields.confirmedGrade.Get()
|
||||
previous, previousSet := fields.previousGrade.Get()
|
||||
if (test.wantConfirmed == "") == confirmedSet || confirmedSet && string(confirmed) != test.wantConfirmed {
|
||||
t.Fatalf("confirmed_grade = %q (set %v), want %q", confirmed, confirmedSet, test.wantConfirmed)
|
||||
}
|
||||
if (test.wantPrevious == "") == previousSet || previousSet && string(previous) != test.wantPrevious {
|
||||
t.Fatalf("previous_confirmed_grade = %q (set %v), want %q", previous, previousSet, test.wantPrevious)
|
||||
}
|
||||
if fields.categoryDecision.IsSet() != test.wantView {
|
||||
t.Fatalf("category_decision present = %v, want %v", fields.categoryDecision.IsSet(), test.wantView)
|
||||
}
|
||||
if view, ok := fields.categoryDecision.Get(); ok && test.decision.Status == domain.AssessmentCategoryDecisionNotEligible {
|
||||
_, hasMethod := view.Method.Get()
|
||||
_, hasSource := view.Source.Get()
|
||||
if hasMethod || hasSource {
|
||||
t.Fatalf("not eligible view names a method or source: %+v", view)
|
||||
}
|
||||
}
|
||||
if view, ok := fields.categoryDecision.Get(); ok && string(view.Status) != string(test.decision.Status) {
|
||||
t.Fatalf("view status = %s, want %s", view.Status, test.decision.Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -566,50 +566,20 @@ func (repository assessmentAttemptRepository) SaveResult(
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - encode result snapshot: %w", location, err)
|
||||
}
|
||||
var gradingPolicyID, openingID, trainingBindingID pgtype.UUID
|
||||
var openingHash, trainingHash []byte
|
||||
if validated.Pins.GradingPolicyVersionID != domain.PolicyVersionID(uuid.Nil) {
|
||||
gradingPolicyID = pgUUID(uuid.UUID(validated.Pins.GradingPolicyVersionID))
|
||||
}
|
||||
if validated.Pins.OpeningID != uuid.Nil {
|
||||
openingID = pgUUID(validated.Pins.OpeningID)
|
||||
}
|
||||
if validated.Pins.TrainingBindingID != uuid.Nil {
|
||||
trainingBindingID = pgUUID(validated.Pins.TrainingBindingID)
|
||||
}
|
||||
if validated.Pins.OpeningManifestHash != [sha256.Size]byte{} {
|
||||
openingHash = bytes.Clone(validated.Pins.OpeningManifestHash[:])
|
||||
}
|
||||
if validated.Pins.TrainingManifestHash != [sha256.Size]byte{} {
|
||||
trainingHash = bytes.Clone(validated.Pins.TrainingManifestHash[:])
|
||||
}
|
||||
var passMark pgtype.Int4
|
||||
var scoredItems, rawScore, passPoints pgtype.Int2
|
||||
if score := validated.BasicScore; score != nil {
|
||||
scoredItems, err = assessmentSmallint(validated.Rationale.ScoredItems)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - scored item count exceeds storage range: %w", location, err)
|
||||
}
|
||||
rawScore, err = assessmentSmallint(score.Points)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - raw score exceeds storage range: %w", location, err)
|
||||
}
|
||||
passPoints, err = assessmentSmallint(score.PassPoints)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - pass points exceed storage range: %w", location, err)
|
||||
}
|
||||
passMark = pgtype.Int4{Int32: validated.Rationale.PassMarkBasisPoints, Valid: true}
|
||||
columns, err := newAssessmentResultColumns(validated)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build result columns: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
if err := repository.queries.InsertAssessmentAttemptResult(ctx, sqlc.InsertAssessmentAttemptResultParams{
|
||||
AttemptID: pgUUID(validated.Attempt.ID.UUID()), UserID: pgUUID(userID),
|
||||
ResultSnapshot: encoded, Kind: string(validated.Attempt.Kind), Mode: string(validated.Attempt.Mode),
|
||||
Outcome: string(validated.Outcome), ProductPolicyVersionID: pgUUID(uuid.UUID(validated.Pins.ProductPolicyVersionID)),
|
||||
ProductPolicyVersion: validated.Pins.ProductPolicyVersion, GradingPolicyVersionID: gradingPolicyID,
|
||||
OpeningID: openingID, OpeningManifestSha256: openingHash, TrainingBindingID: trainingBindingID,
|
||||
TrainingManifestSha256: trainingHash, BankVersion: validated.Pins.BankVersion,
|
||||
ProductPolicyVersion: validated.Pins.ProductPolicyVersion, GradingPolicyVersionID: columns.gradingPolicyID,
|
||||
OpeningID: columns.openingID, OpeningManifestSha256: columns.openingHash, TrainingBindingID: columns.trainingBindingID,
|
||||
TrainingManifestSha256: columns.trainingHash, BankVersion: validated.Pins.BankVersion,
|
||||
AlgorithmVersion: validated.Pins.AlgorithmVersion, RationaleRule: validated.Rationale.Rule,
|
||||
PassMarkBasisPoints: passMark, ScoredItems: scoredItems, RawScore: rawScore,
|
||||
PassPoints: passPoints, DecidedAt: pgTime(validated.DecidedAt),
|
||||
PassMarkBasisPoints: columns.passMark, ScoredItems: columns.scoredItems, RawScore: columns.rawScore,
|
||||
PassPoints: columns.passPoints, DecidedAt: pgTime(validated.DecidedAt),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert immutable result: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const maxAssessmentCategoryDecisionBytes = 4096
|
||||
|
||||
// assessmentCategoryDecisionDocument is the stored category extension of one
|
||||
// result. The key names are read by the migration constraints and triggers, so
|
||||
// they are part of the storage contract. Optional review fields are omitted,
|
||||
// not written as null, for decisions that have no reviewed source.
|
||||
type assessmentCategoryDecisionDocument struct {
|
||||
AttemptID uuid.UUID `json:"attempt_id"`
|
||||
BankCategory domain.AssessmentCategory `json:"bank_category"`
|
||||
Specialization domain.SpecializationCode `json:"specialization"`
|
||||
AttemptedGrade domain.GradeCode `json:"attempted_grade"`
|
||||
PreviousGrade *domain.GradeCode `json:"previous_grade"`
|
||||
CurrentGrade *domain.GradeCode `json:"current_grade"`
|
||||
Status domain.AssessmentCategoryDecisionStatus `json:"status"`
|
||||
Method domain.AssessmentCategoryDecisionMethod `json:"method,omitempty"`
|
||||
ProductPolicyVersionID uuid.UUID `json:"product_policy_version_id"`
|
||||
ProductPolicyVersion int32 `json:"product_policy_version"`
|
||||
GradingPolicyVersionID uuid.UUID `json:"grading_policy_version_id"`
|
||||
OpeningID uuid.UUID `json:"opening_id"`
|
||||
OpeningManifestHash string `json:"opening_manifest_sha256"`
|
||||
ReviewID *uuid.UUID `json:"review_id,omitempty"`
|
||||
Source domain.AssessmentCategorySource `json:"source,omitempty"`
|
||||
CalibrationStatus domain.AssessmentCategoryCalibrationStatus `json:"calibration_status,omitempty"`
|
||||
DecidedAt time.Time `json:"decided_at"`
|
||||
}
|
||||
|
||||
func marshalAssessmentCategoryDecision(decision domain.AssessmentCategoryDecisionSnapshot) ([]byte, error) {
|
||||
const location = "postgres.marshalAssessmentCategoryDecision"
|
||||
if decision.Specialization == nil || decision.AttemptedGrade == nil {
|
||||
return nil, fmt.Errorf("%s - decision has no track: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
document := assessmentCategoryDecisionDocument{
|
||||
AttemptID: decision.AttemptID.UUID(), BankCategory: decision.BankCategory,
|
||||
Specialization: *decision.Specialization, AttemptedGrade: *decision.AttemptedGrade,
|
||||
PreviousGrade: decision.PreviousGrade, CurrentGrade: decision.CurrentGrade,
|
||||
Status: decision.Status, Method: decision.Method,
|
||||
ProductPolicyVersionID: uuid.UUID(decision.ProductPolicyVersionID),
|
||||
ProductPolicyVersion: decision.ProductPolicyVersion,
|
||||
GradingPolicyVersionID: uuid.UUID(decision.GradingPolicyVersionID),
|
||||
OpeningID: decision.OpeningID, OpeningManifestHash: hex.EncodeToString(decision.OpeningManifestHash[:]),
|
||||
Source: decision.Source, CalibrationStatus: decision.CalibrationStatus, DecidedAt: decision.DecidedAt.UTC(),
|
||||
}
|
||||
if decision.ReviewID != uuid.Nil {
|
||||
reviewID := decision.ReviewID
|
||||
document.ReviewID = &reviewID
|
||||
}
|
||||
encoded, err := json.Marshal(document)
|
||||
if err != nil || len(encoded) > maxAssessmentCategoryDecisionBytes {
|
||||
return nil, fmt.Errorf("%s - encode bounded decision: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
func decodeAssessmentCategoryDecision(encoded string) (domain.AssessmentCategoryDecisionSnapshot, error) {
|
||||
const location = "postgres.decodeAssessmentCategoryDecision"
|
||||
if encoded == "" || len(encoded) > maxAssessmentCategoryDecisionBytes {
|
||||
return domain.AssessmentCategoryDecisionSnapshot{}, fmt.Errorf("%s - stored decision size is invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader([]byte(encoded)))
|
||||
decoder.DisallowUnknownFields()
|
||||
var document assessmentCategoryDecisionDocument
|
||||
if err := decoder.Decode(&document); err != nil {
|
||||
return domain.AssessmentCategoryDecisionSnapshot{}, fmt.Errorf("%s - decode stored decision: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return domain.AssessmentCategoryDecisionSnapshot{}, fmt.Errorf("%s - stored decision has trailing data: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
manifestHash, err := restoreOptionalAssessmentDigest(&document.OpeningManifestHash)
|
||||
if err != nil {
|
||||
return domain.AssessmentCategoryDecisionSnapshot{}, fmt.Errorf("%s - stored manifest digest is invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
specialization, attempted := document.Specialization, document.AttemptedGrade
|
||||
snapshot := domain.AssessmentCategoryDecisionSnapshot{
|
||||
AttemptID: domain.AssessmentAttemptID(document.AttemptID), BankCategory: document.BankCategory,
|
||||
Specialization: &specialization, AttemptedGrade: &attempted,
|
||||
PreviousGrade: document.PreviousGrade, CurrentGrade: document.CurrentGrade,
|
||||
Status: document.Status, Method: document.Method,
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(document.ProductPolicyVersionID),
|
||||
ProductPolicyVersion: document.ProductPolicyVersion,
|
||||
GradingPolicyVersionID: domain.PolicyVersionID(document.GradingPolicyVersionID),
|
||||
OpeningID: document.OpeningID, OpeningManifestHash: manifestHash,
|
||||
Source: document.Source, CalibrationStatus: document.CalibrationStatus, DecidedAt: document.DecidedAt,
|
||||
}
|
||||
if document.ReviewID != nil {
|
||||
snapshot.ReviewID = *document.ReviewID
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
// assessmentResultColumns are the denormalized, query-visible copies of a
|
||||
// result document that the table constraints compare with the snapshot.
|
||||
type assessmentResultColumns struct {
|
||||
gradingPolicyID, openingID, trainingBindingID pgtype.UUID
|
||||
openingHash, trainingHash []byte
|
||||
passMark pgtype.Int4
|
||||
scoredItems, rawScore, passPoints pgtype.Int2
|
||||
}
|
||||
|
||||
func newAssessmentResultColumns(result domain.AssessmentAttemptResultSnapshot) (assessmentResultColumns, error) {
|
||||
var columns assessmentResultColumns
|
||||
pins := result.Pins
|
||||
if pins.GradingPolicyVersionID != domain.PolicyVersionID(uuid.Nil) {
|
||||
columns.gradingPolicyID = pgUUID(uuid.UUID(pins.GradingPolicyVersionID))
|
||||
}
|
||||
if pins.OpeningID != uuid.Nil {
|
||||
columns.openingID = pgUUID(pins.OpeningID)
|
||||
}
|
||||
if pins.TrainingBindingID != uuid.Nil {
|
||||
columns.trainingBindingID = pgUUID(pins.TrainingBindingID)
|
||||
}
|
||||
if pins.OpeningManifestHash != [sha256.Size]byte{} {
|
||||
columns.openingHash = bytes.Clone(pins.OpeningManifestHash[:])
|
||||
}
|
||||
if pins.TrainingManifestHash != [sha256.Size]byte{} {
|
||||
columns.trainingHash = bytes.Clone(pins.TrainingManifestHash[:])
|
||||
}
|
||||
score := result.BasicScore
|
||||
if score == nil {
|
||||
return columns, nil
|
||||
}
|
||||
var err error
|
||||
if columns.scoredItems, err = assessmentSmallint(result.Rationale.ScoredItems); err != nil {
|
||||
return assessmentResultColumns{}, fmt.Errorf("scored item count exceeds storage range: %w", err)
|
||||
}
|
||||
if columns.rawScore, err = assessmentSmallint(score.Points); err != nil {
|
||||
return assessmentResultColumns{}, fmt.Errorf("raw score exceeds storage range: %w", err)
|
||||
}
|
||||
if columns.passPoints, err = assessmentSmallint(score.PassPoints); err != nil {
|
||||
return assessmentResultColumns{}, fmt.Errorf("pass points exceed storage range: %w", err)
|
||||
}
|
||||
columns.passMark = pgtype.Int4{Int32: result.Rationale.PassMarkBasisPoints, Valid: true}
|
||||
return columns, nil
|
||||
}
|
||||
|
||||
// SaveResultHistoryEntry stores a legacy v1 result unchanged or a v2 result
|
||||
// with its category decision in one immutable row.
|
||||
func (repository assessmentAttemptRepository) SaveResultHistoryEntry(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
entry domain.AssessmentAttemptResultHistoryEntry,
|
||||
) error {
|
||||
const location = "assessmentAttemptRepository.SaveResultHistoryEntry"
|
||||
if userID == uuid.Nil {
|
||||
return fmt.Errorf("%s - owner ID is required: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
validated, err := domain.RestoreAssessmentAttemptResultHistoryEntry(entry)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - result history entry is invalid: %w", location, err)
|
||||
}
|
||||
if validated.SchemaVersion == domain.AssessmentAttemptResultHistorySchemaV1 {
|
||||
if err := repository.SaveResult(ctx, userID, validated.Result); err != nil {
|
||||
return fmt.Errorf("%s - store legacy result: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
result := validated.Result
|
||||
encodedResult, err := marshalAssessmentAttemptResultDocument(result)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - encode result snapshot: %w", location, err)
|
||||
}
|
||||
encodedDecision, err := marshalAssessmentCategoryDecision(*validated.CategoryDecision)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - encode category decision: %w", location, err)
|
||||
}
|
||||
columns, err := newAssessmentResultColumns(result)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build result columns: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
if err := repository.queries.InsertAssessmentAttemptResultV2(ctx, sqlc.InsertAssessmentAttemptResultV2Params{
|
||||
AttemptID: pgUUID(result.Attempt.ID.UUID()), UserID: pgUUID(userID),
|
||||
ResultSnapshot: encodedResult, CategoryDecision: encodedDecision,
|
||||
CurrentConfirmedGrade: pgNullableAttemptText(validated.CurrentConfirmedGrade),
|
||||
Kind: string(result.Attempt.Kind), Mode: string(result.Attempt.Mode),
|
||||
Outcome: string(result.Outcome),
|
||||
ProductPolicyVersionID: pgUUID(uuid.UUID(result.Pins.ProductPolicyVersionID)),
|
||||
ProductPolicyVersion: result.Pins.ProductPolicyVersion, GradingPolicyVersionID: columns.gradingPolicyID,
|
||||
OpeningID: columns.openingID, OpeningManifestSha256: columns.openingHash,
|
||||
BankVersion: result.Pins.BankVersion, AlgorithmVersion: result.Pins.AlgorithmVersion,
|
||||
RationaleRule: result.Rationale.Rule, PassMarkBasisPoints: columns.passMark,
|
||||
ScoredItems: columns.scoredItems, RawScore: columns.rawScore, PassPoints: columns.passPoints,
|
||||
DecidedAt: pgTime(result.DecidedAt),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert immutable category result: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetResultHistoryEntry returns the exact stored record; a v1 row carries no
|
||||
// category data and none is reconstructed from the current category.
|
||||
func (repository assessmentAttemptRepository) GetResultHistoryEntry(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
) (domain.AssessmentAttemptResultHistoryEntry, error) {
|
||||
const location = "assessmentAttemptRepository.GetResultHistoryEntry"
|
||||
if userID == uuid.Nil || attemptID.IsZero() {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - owner and attempt IDs are required: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
row, err := repository.queries.GetAssessmentAttemptResultHistoryEntry(ctx, sqlc.GetAssessmentAttemptResultHistoryEntryParams{
|
||||
UserID: pgUUID(userID), AttemptID: pgUUID(attemptID.UUID()),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - immutable result is missing: %w", location, outbound.ErrAssessmentAttemptResultNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - select immutable result: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
entry, err := restoreStoredResultHistoryEntry(row.SchemaVersion, row.ResultSnapshot, row.CategoryDecision, row.CurrentConfirmedGrade)
|
||||
if err != nil || entry.Result.Attempt.ID != attemptID {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - stored result is invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
// ListCandidateAssessmentResults reads one owner-scoped keyset page. It asks
|
||||
// for one row more than limit and reports that row as HasMore.
|
||||
func (repository assessmentAttemptRepository) ListCandidateAssessmentResults(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
cursor *outbound.AssessmentAttemptResultCursor,
|
||||
limit int32,
|
||||
) (outbound.AssessmentAttemptResultPage, error) {
|
||||
const location = "assessmentAttemptRepository.ListCandidateAssessmentResults"
|
||||
if userID == uuid.Nil || limit < 1 || cursor != nil && (cursor.AttemptID.IsZero() || cursor.DecidedAt.IsZero()) {
|
||||
return outbound.AssessmentAttemptResultPage{}, fmt.Errorf("%s - owner, limit or cursor is invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
params := sqlc.ListCandidateAssessmentResultsParams{UserID: pgUUID(userID), LimitCount: limit}
|
||||
if cursor != nil {
|
||||
params.CursorDecidedAt = pgTime(cursor.DecidedAt)
|
||||
params.CursorAttemptID = pgUUID(cursor.AttemptID.UUID())
|
||||
}
|
||||
rows, err := repository.queries.ListCandidateAssessmentResults(ctx, params)
|
||||
if err != nil {
|
||||
return outbound.AssessmentAttemptResultPage{}, fmt.Errorf("%s - select result history: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
page := outbound.AssessmentAttemptResultPage{HasMore: len(rows) > int(limit)}
|
||||
if page.HasMore {
|
||||
rows = rows[:limit]
|
||||
}
|
||||
page.Records = make([]outbound.AssessmentAttemptResultRecord, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
entry, err := restoreStoredResultHistoryEntry(row.SchemaVersion, row.ResultSnapshot, row.CategoryDecision, row.CurrentConfirmedGrade)
|
||||
if err != nil || !row.AttemptID.Valid || !row.UserID.Valid || entry.Result.Attempt.ID.UUID() != row.AttemptID.Bytes {
|
||||
return outbound.AssessmentAttemptResultPage{}, fmt.Errorf("%s - stored result is invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
page.Records = append(page.Records, outbound.AssessmentAttemptResultRecord{UserID: row.UserID.Bytes, Entry: entry})
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func restoreStoredResultHistoryEntry(
|
||||
schemaVersion int16,
|
||||
resultSnapshot, categoryDecision string,
|
||||
currentGrade pgtype.Text,
|
||||
) (domain.AssessmentAttemptResultHistoryEntry, error) {
|
||||
result, err := decodeAssessmentAttemptResultDocument([]byte(resultSnapshot))
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, err
|
||||
}
|
||||
entry := domain.AssessmentAttemptResultHistoryEntry{SchemaVersion: int32(schemaVersion), Result: result}
|
||||
if categoryDecision != "" {
|
||||
decision, err := decodeAssessmentCategoryDecision(categoryDecision)
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, err
|
||||
}
|
||||
entry.CategoryDecision = &decision
|
||||
}
|
||||
if currentGrade.Valid {
|
||||
grade := domain.GradeCode(currentGrade.String)
|
||||
entry.CurrentConfirmedGrade = &grade
|
||||
}
|
||||
return domain.RestoreAssessmentAttemptResultHistoryEntry(entry)
|
||||
}
|
||||
|
||||
// LockCandidateCategory serializes category upgrades of one candidate and
|
||||
// specialization for the rest of the transaction.
|
||||
func (repository assessmentAttemptRepository) LockCandidateCategory(
|
||||
ctx context.Context,
|
||||
candidateID uuid.UUID,
|
||||
specialization domain.SpecializationCode,
|
||||
) error {
|
||||
const location = "assessmentAttemptRepository.LockCandidateCategory"
|
||||
if candidateID == uuid.Nil || !specialization.IsKnown() {
|
||||
return fmt.Errorf("%s - candidate scope is invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
if err := repository.queries.LockCandidateAssessmentCategory(ctx, sqlc.LockCandidateAssessmentCategoryParams{
|
||||
CandidateID: candidateID.String(), Specialization: string(specialization),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - lock candidate category: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository assessmentAttemptRepository) GetCandidateCategory(
|
||||
ctx context.Context,
|
||||
candidateID uuid.UUID,
|
||||
specialization domain.SpecializationCode,
|
||||
) (domain.CandidateAssessmentCategory, bool, error) {
|
||||
const location = "assessmentAttemptRepository.GetCandidateCategory"
|
||||
if candidateID == uuid.Nil || !specialization.IsKnown() {
|
||||
return domain.CandidateAssessmentCategory{}, false, fmt.Errorf("%s - candidate scope is invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
row, err := repository.queries.GetCandidateAssessmentCategory(ctx, sqlc.GetCandidateAssessmentCategoryParams{
|
||||
CandidateID: pgUUID(candidateID), Specialization: string(specialization),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.CandidateAssessmentCategory{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return domain.CandidateAssessmentCategory{}, false, fmt.Errorf("%s - select current category: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
category, err := restoreCandidateAssessmentCategory(row)
|
||||
if err != nil {
|
||||
return domain.CandidateAssessmentCategory{}, false, fmt.Errorf("%s - stored category is invalid: %w", location, err)
|
||||
}
|
||||
return category, true, nil
|
||||
}
|
||||
|
||||
func restoreCandidateAssessmentCategory(row sqlc.CandidateAssessmentCategory) (domain.CandidateAssessmentCategory, error) {
|
||||
manifestHash, err := assessmentManifestHash(row.OpeningManifestSha256)
|
||||
if err != nil || !row.CandidateID.Valid || !row.SourceAttemptID.Valid || !row.SourceReviewID.Valid ||
|
||||
!row.ProductPolicyVersionID.Valid || !row.OpeningID.Valid || !row.AssignedAt.Valid {
|
||||
return domain.CandidateAssessmentCategory{}, domain.ErrInvalidAssessmentCategory
|
||||
}
|
||||
return domain.RestoreCandidateAssessmentCategory(domain.CandidateAssessmentCategorySnapshot{
|
||||
CandidateID: row.CandidateID.Bytes, Specialization: domain.SpecializationCode(row.Specialization),
|
||||
Grade: domain.GradeCode(row.Grade), SourceAttemptID: domain.AssessmentAttemptID(row.SourceAttemptID.Bytes),
|
||||
SourceReviewID: row.SourceReviewID.Bytes,
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(row.ProductPolicyVersionID.Bytes),
|
||||
ProductPolicyVersion: row.ProductPolicyVersion, OpeningID: row.OpeningID.Bytes,
|
||||
OpeningManifestHash: manifestHash, Source: domain.AssessmentCategorySource(row.Source),
|
||||
CalibrationStatus: domain.AssessmentCategoryCalibrationStatus(row.CalibrationStatus),
|
||||
AssignedAt: row.AssignedAt.Time,
|
||||
})
|
||||
}
|
||||
|
||||
func assessmentManifestHash(value []byte) ([sha256.Size]byte, error) {
|
||||
var hash [sha256.Size]byte
|
||||
if len(value) != sha256.Size {
|
||||
return hash, domain.ErrInvalidAssessmentCategory
|
||||
}
|
||||
copy(hash[:], value)
|
||||
return hash, nil
|
||||
}
|
||||
|
||||
// GetSyntheticCategoryReview finds the attestation that matches the exact
|
||||
// opening, manifest, product policy and the opening's grading policy.
|
||||
func (repository assessmentAttemptRepository) GetSyntheticCategoryReview(
|
||||
ctx context.Context,
|
||||
openingID uuid.UUID,
|
||||
category domain.AssessmentCategory,
|
||||
openingManifestHash [32]byte,
|
||||
productPolicyID domain.PolicyVersionID,
|
||||
productPolicyVersion int32,
|
||||
gradingPolicyID domain.PolicyVersionID,
|
||||
) (domain.AssessmentSyntheticCategoryReview, bool, error) {
|
||||
const location = "assessmentAttemptRepository.GetSyntheticCategoryReview"
|
||||
if openingID == uuid.Nil || openingManifestHash == [32]byte{} || productPolicyID.IsZero() ||
|
||||
productPolicyVersion <= 0 || gradingPolicyID.IsZero() {
|
||||
return domain.AssessmentSyntheticCategoryReview{}, false, fmt.Errorf("%s - review pins are invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
row, err := repository.queries.GetSyntheticCategoryReview(ctx, sqlc.GetSyntheticCategoryReviewParams{
|
||||
OpeningID: pgUUID(openingID), Category: string(category),
|
||||
OpeningManifestSha256: bytes.Clone(openingManifestHash[:]),
|
||||
ProductPolicyVersionID: pgUUID(productPolicyID.UUID()), ProductPolicyVersion: productPolicyVersion,
|
||||
GradingPolicyVersionID: pgUUID(gradingPolicyID.UUID()),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AssessmentSyntheticCategoryReview{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentSyntheticCategoryReview{}, false, fmt.Errorf("%s - select review: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
manifestHash, err := assessmentManifestHash(row.OpeningManifestSha256)
|
||||
if err != nil || !row.ID.Valid || !row.OpeningID.Valid || !row.ProductPolicyVersionID.Valid || !row.ReviewedAt.Valid {
|
||||
return domain.AssessmentSyntheticCategoryReview{}, false, fmt.Errorf("%s - stored review is invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
review, err := domain.RestoreAssessmentSyntheticCategoryReview(domain.AssessmentSyntheticCategoryReviewSnapshot{
|
||||
ID: row.ID.Bytes, OpeningID: row.OpeningID.Bytes, Category: domain.AssessmentCategory(row.Category),
|
||||
Source: domain.AssessmentCategorySource(row.Source), OpeningManifestHash: manifestHash,
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(row.ProductPolicyVersionID.Bytes),
|
||||
ProductPolicyVersion: row.ProductPolicyVersion, ReviewedBy: domain.AssessmentOperator(row.ReviewedBy),
|
||||
ReviewedAt: row.ReviewedAt.Time,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentSyntheticCategoryReview{}, false, fmt.Errorf("%s - restore review: %w", location, err)
|
||||
}
|
||||
return review, true, nil
|
||||
}
|
||||
|
||||
// CreateSyntheticCategoryReview stores one attestation. The database stamps the
|
||||
// review time and re-checks the opening, manifest and policy it names. A
|
||||
// duplicate of the same exact source stores nothing and reports false.
|
||||
func (repository assessmentAttemptRepository) CreateSyntheticCategoryReview(
|
||||
ctx context.Context,
|
||||
review domain.AssessmentSyntheticCategoryReview,
|
||||
) (bool, error) {
|
||||
const location = "assessmentAttemptRepository.CreateSyntheticCategoryReview"
|
||||
if review.IsZero() {
|
||||
return false, fmt.Errorf("%s - review is required: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
snapshot := review.Snapshot()
|
||||
rows, err := repository.queries.InsertSyntheticCategoryReview(ctx, sqlc.InsertSyntheticCategoryReviewParams{
|
||||
ID: pgUUID(snapshot.ID), OpeningID: pgUUID(snapshot.OpeningID), Category: string(snapshot.Category),
|
||||
Source: string(snapshot.Source), OpeningManifestSha256: bytes.Clone(snapshot.OpeningManifestHash[:]),
|
||||
ProductPolicyVersionID: pgUUID(snapshot.ProductPolicyVersionID.UUID()),
|
||||
ProductPolicyVersion: snapshot.ProductPolicyVersion, ReviewedBy: string(snapshot.ReviewedBy),
|
||||
ReviewedAt: pgTime(snapshot.ReviewedAt),
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s - insert review: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
return rows == 1, nil
|
||||
}
|
||||
|
||||
// SaveCandidateAssessmentCategory writes a strict upgrade. Zero affected rows
|
||||
// mean the stored grade is not lower than the new one, which the caller's
|
||||
// category lock should have made impossible.
|
||||
func (repository assessmentAttemptRepository) SaveCandidateAssessmentCategory(
|
||||
ctx context.Context,
|
||||
category domain.CandidateAssessmentCategory,
|
||||
) error {
|
||||
const location = "assessmentAttemptRepository.SaveCandidateAssessmentCategory"
|
||||
if category.IsZero() {
|
||||
return fmt.Errorf("%s - category is required: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
snapshot := category.Snapshot()
|
||||
rows, err := repository.queries.SaveCandidateAssessmentCategory(ctx, sqlc.SaveCandidateAssessmentCategoryParams{
|
||||
CandidateID: pgUUID(snapshot.CandidateID), Specialization: string(snapshot.Specialization),
|
||||
Grade: string(snapshot.Grade), SourceAttemptID: pgUUID(snapshot.SourceAttemptID.UUID()),
|
||||
SourceReviewID: pgUUID(snapshot.SourceReviewID),
|
||||
ProductPolicyVersionID: pgUUID(snapshot.ProductPolicyVersionID.UUID()),
|
||||
ProductPolicyVersion: snapshot.ProductPolicyVersion, OpeningID: pgUUID(snapshot.OpeningID),
|
||||
OpeningManifestSha256: bytes.Clone(snapshot.OpeningManifestHash[:]), Source: string(snapshot.Source),
|
||||
CalibrationStatus: string(snapshot.CalibrationStatus), AssignedAt: pgTime(snapshot.AssignedAt),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - upsert current category: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
if rows != 1 {
|
||||
return fmt.Errorf("%s - category was not upgraded: %w", location, outbound.ErrAssessmentCategoryConflict)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -184,21 +184,9 @@ func notificationInboxOptionalUUID(value *uuid.UUID) pgtype.UUID {
|
||||
return pgUUID(*value)
|
||||
}
|
||||
|
||||
func notificationInboxEntryFromRow(row sqlc.GetNotificationInboxEventRow) (domain.NotificationInboxEntry, error) {
|
||||
return restoreNotificationInboxEntryRow(
|
||||
row.RecipientUserID, row.EventID, row.OrganizationID, row.EventType,
|
||||
row.SchemaVersion, row.SourceType, row.SourceID, row.OccurredAt, row.ReadAt,
|
||||
)
|
||||
}
|
||||
|
||||
func notificationInboxEntryFromListRow(row sqlc.ListNotificationInboxEventsRow) (domain.NotificationInboxEntry, error) {
|
||||
return restoreNotificationInboxEntryRow(
|
||||
row.RecipientUserID, row.EventID, row.OrganizationID, row.EventType,
|
||||
row.SchemaVersion, row.SourceType, row.SourceID, row.OccurredAt, row.ReadAt,
|
||||
)
|
||||
}
|
||||
|
||||
func notificationInboxEntryFromReadRow(row sqlc.MarkNotificationInboxEventReadRow) (domain.NotificationInboxEntry, error) {
|
||||
// The three inbox queries select every column of the table in table order, so
|
||||
// sqlc returns the shared model type for all of them.
|
||||
func notificationInboxEntryFromRow(row sqlc.NotificationInboxEvent) (domain.NotificationInboxEntry, error) {
|
||||
return restoreNotificationInboxEntryRow(
|
||||
row.RecipientUserID, row.EventID, row.OrganizationID, row.EventType,
|
||||
row.SchemaVersion, row.SourceType, row.SourceID, row.OccurredAt, row.ReadAt,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -55,6 +56,7 @@ type privacyCohortCandidate struct {
|
||||
claims []domain.StoredProfileClaim
|
||||
acknowledgements []domain.ProfileParallelPeriodAcknowledgement
|
||||
workFormats []domain.QuestionnaireWorkFormat
|
||||
categories []domain.CandidateViewConfirmedCategoryInput
|
||||
}
|
||||
|
||||
func (repository privacyCohortRepository) ListVisibleCandidateViewSources(
|
||||
@@ -88,7 +90,7 @@ func (repository privacyCohortRepository) ListVisibleCandidateViewSources(
|
||||
current = privacyCohortCandidate{}
|
||||
}
|
||||
if current.id == uuid.Nil {
|
||||
current, err = newPrivacyCohortCandidate(candidateID, row.Fields, row.WorkFormats, row.ParallelPeriodAcknowledgements)
|
||||
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)
|
||||
}
|
||||
@@ -114,6 +116,7 @@ func newPrivacyCohortCandidate(
|
||||
fieldCodes []string,
|
||||
workFormatCodes []string,
|
||||
acknowledgementsValue any,
|
||||
confirmedCategoriesValue any,
|
||||
) (privacyCohortCandidate, error) {
|
||||
fields := make([]domain.CardField, 0, len(fieldCodes))
|
||||
for _, code := range fieldCodes {
|
||||
@@ -135,12 +138,47 @@ func newPrivacyCohortCandidate(
|
||||
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,
|
||||
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: only a specialization and a grade of each, never the
|
||||
// attempt, score, policy, or review that produced it.
|
||||
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"`
|
||||
}
|
||||
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 {
|
||||
categories = append(categories, domain.CandidateViewConfirmedCategoryInput{
|
||||
Specialization: category.Specialization, Grade: category.Grade, Strength: privacyCohortCategoryStrength,
|
||||
})
|
||||
}
|
||||
return categories, nil
|
||||
}
|
||||
|
||||
func privacyCohortStoredClaim(row sqlc.ListVisibleCandidateViewSourcesRow) (domain.StoredProfileClaim, error) {
|
||||
value, err := privacyCohortJSONBytes(row.SafeValue)
|
||||
if err != nil {
|
||||
@@ -166,7 +204,7 @@ func buildPrivacyCohortSource(candidate privacyCohortCandidate) (domain.Candidat
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("validate safe profile claims: %w", domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
return domain.NewCandidateViewSource(
|
||||
candidate.id, candidate.fields, domain.CandidateViewProfileFromContent(content), nil,
|
||||
candidate.id, candidate.fields, domain.CandidateViewProfileFromContent(content), candidate.categories,
|
||||
candidate.workFormats, nil,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ func buildPreviewCandidateViewSource(
|
||||
if got, err := privacyCohortUUID(first.UserID); err != nil || got != candidateID {
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("%s - projection identity is invalid: %w", location, domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
candidate, err := newPrivacyCohortCandidate(candidateID, first.Fields, first.WorkFormats, first.ParallelPeriodAcknowledgements)
|
||||
candidate, err := newPrivacyCohortCandidate(candidateID, first.Fields, first.WorkFormats, first.ParallelPeriodAcknowledgements, first.ConfirmedCategories)
|
||||
if err != nil {
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("%s - restore candidate input: %w", location, err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: assessment_results.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const getAssessmentAttemptResultHistoryEntry = `-- name: GetAssessmentAttemptResultHistoryEntry :one
|
||||
SELECT schema_version, result_snapshot::text,
|
||||
COALESCE(category_decision::text, '')::text AS category_decision, current_confirmed_grade
|
||||
FROM assessment_attempt_results
|
||||
WHERE user_id = $1 AND attempt_id = $2
|
||||
`
|
||||
|
||||
type GetAssessmentAttemptResultHistoryEntryParams struct {
|
||||
UserID pgtype.UUID
|
||||
AttemptID pgtype.UUID
|
||||
}
|
||||
|
||||
type GetAssessmentAttemptResultHistoryEntryRow struct {
|
||||
SchemaVersion int16
|
||||
ResultSnapshot string
|
||||
CategoryDecision string
|
||||
CurrentConfirmedGrade pgtype.Text
|
||||
}
|
||||
|
||||
// Returns both immutable result versions. NULL category fields identify a
|
||||
// legacy v1 record and must not be reconstructed from current state.
|
||||
func (q *Queries) GetAssessmentAttemptResultHistoryEntry(ctx context.Context, arg GetAssessmentAttemptResultHistoryEntryParams) (GetAssessmentAttemptResultHistoryEntryRow, error) {
|
||||
row := q.db.QueryRow(ctx, getAssessmentAttemptResultHistoryEntry, arg.UserID, arg.AttemptID)
|
||||
var i GetAssessmentAttemptResultHistoryEntryRow
|
||||
err := row.Scan(
|
||||
&i.SchemaVersion,
|
||||
&i.ResultSnapshot,
|
||||
&i.CategoryDecision,
|
||||
&i.CurrentConfirmedGrade,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getCandidateAssessmentCategory = `-- name: GetCandidateAssessmentCategory :one
|
||||
SELECT candidate_id, specialization, grade, source_attempt_id, source_review_id,
|
||||
product_policy_version_id, product_policy_version, grading_policy_version_id,
|
||||
opening_id, opening_manifest_sha256, source, calibration_status, assigned_at
|
||||
FROM candidate_assessment_categories
|
||||
WHERE candidate_id = $1 AND specialization = $2
|
||||
`
|
||||
|
||||
type GetCandidateAssessmentCategoryParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
Specialization string
|
||||
}
|
||||
|
||||
func (q *Queries) GetCandidateAssessmentCategory(ctx context.Context, arg GetCandidateAssessmentCategoryParams) (CandidateAssessmentCategory, error) {
|
||||
row := q.db.QueryRow(ctx, getCandidateAssessmentCategory, arg.CandidateID, arg.Specialization)
|
||||
var i CandidateAssessmentCategory
|
||||
err := row.Scan(
|
||||
&i.CandidateID,
|
||||
&i.Specialization,
|
||||
&i.Grade,
|
||||
&i.SourceAttemptID,
|
||||
&i.SourceReviewID,
|
||||
&i.ProductPolicyVersionID,
|
||||
&i.ProductPolicyVersion,
|
||||
&i.GradingPolicyVersionID,
|
||||
&i.OpeningID,
|
||||
&i.OpeningManifestSha256,
|
||||
&i.Source,
|
||||
&i.CalibrationStatus,
|
||||
&i.AssignedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getSyntheticCategoryReview = `-- name: GetSyntheticCategoryReview :one
|
||||
SELECT review.id, review.opening_id, review.category, review.source,
|
||||
review.opening_manifest_sha256, review.product_policy_version_id,
|
||||
review.product_policy_version, review.reviewed_by, review.reviewed_at
|
||||
FROM assessment_synthetic_category_reviews AS review
|
||||
JOIN assessment_category_openings AS opening ON opening.id = review.opening_id
|
||||
WHERE review.opening_id = $1
|
||||
AND review.category = $2
|
||||
AND review.source = 'synthetic_demo'
|
||||
AND review.opening_manifest_sha256 = $3
|
||||
AND review.product_policy_version_id = $4
|
||||
AND review.product_policy_version = $5
|
||||
AND opening.policy_version_id = $6
|
||||
`
|
||||
|
||||
type GetSyntheticCategoryReviewParams struct {
|
||||
OpeningID pgtype.UUID
|
||||
Category string
|
||||
OpeningManifestSha256 []byte
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
GradingPolicyVersionID pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetSyntheticCategoryReview(ctx context.Context, arg GetSyntheticCategoryReviewParams) (AssessmentSyntheticCategoryReview, error) {
|
||||
row := q.db.QueryRow(ctx, getSyntheticCategoryReview,
|
||||
arg.OpeningID,
|
||||
arg.Category,
|
||||
arg.OpeningManifestSha256,
|
||||
arg.ProductPolicyVersionID,
|
||||
arg.ProductPolicyVersion,
|
||||
arg.GradingPolicyVersionID,
|
||||
)
|
||||
var i AssessmentSyntheticCategoryReview
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OpeningID,
|
||||
&i.Category,
|
||||
&i.Source,
|
||||
&i.OpeningManifestSha256,
|
||||
&i.ProductPolicyVersionID,
|
||||
&i.ProductPolicyVersion,
|
||||
&i.ReviewedBy,
|
||||
&i.ReviewedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertAssessmentAttemptResultV2 = `-- name: InsertAssessmentAttemptResultV2 :exec
|
||||
INSERT INTO assessment_attempt_results (
|
||||
attempt_id, user_id, result_snapshot, schema_version, category_decision,
|
||||
current_confirmed_grade, kind, mode, outcome, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, rationale_rule, pass_mark_basis_points,
|
||||
scored_items, raw_score, pass_points, decided_at
|
||||
) VALUES (
|
||||
$1, $2, $3, 2,
|
||||
$4::jsonb, $5,
|
||||
$6, $7, $8, $9,
|
||||
$10, $11, $12,
|
||||
$13, NULL, NULL, $14,
|
||||
$15, $16, $17,
|
||||
$18, $19, $20, $21
|
||||
)
|
||||
`
|
||||
|
||||
type InsertAssessmentAttemptResultV2Params struct {
|
||||
AttemptID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
ResultSnapshot []byte
|
||||
CategoryDecision []byte
|
||||
CurrentConfirmedGrade pgtype.Text
|
||||
Kind string
|
||||
Mode string
|
||||
Outcome string
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
GradingPolicyVersionID pgtype.UUID
|
||||
OpeningID pgtype.UUID
|
||||
OpeningManifestSha256 []byte
|
||||
BankVersion string
|
||||
AlgorithmVersion string
|
||||
RationaleRule string
|
||||
PassMarkBasisPoints pgtype.Int4
|
||||
ScoredItems pgtype.Int2
|
||||
RawScore pgtype.Int2
|
||||
PassPoints pgtype.Int2
|
||||
DecidedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Stores the category decision and current grade captured at real-attempt
|
||||
// finalization. The base result document remains its original v1 shape.
|
||||
func (q *Queries) InsertAssessmentAttemptResultV2(ctx context.Context, arg InsertAssessmentAttemptResultV2Params) error {
|
||||
_, err := q.db.Exec(ctx, insertAssessmentAttemptResultV2,
|
||||
arg.AttemptID,
|
||||
arg.UserID,
|
||||
arg.ResultSnapshot,
|
||||
arg.CategoryDecision,
|
||||
arg.CurrentConfirmedGrade,
|
||||
arg.Kind,
|
||||
arg.Mode,
|
||||
arg.Outcome,
|
||||
arg.ProductPolicyVersionID,
|
||||
arg.ProductPolicyVersion,
|
||||
arg.GradingPolicyVersionID,
|
||||
arg.OpeningID,
|
||||
arg.OpeningManifestSha256,
|
||||
arg.BankVersion,
|
||||
arg.AlgorithmVersion,
|
||||
arg.RationaleRule,
|
||||
arg.PassMarkBasisPoints,
|
||||
arg.ScoredItems,
|
||||
arg.RawScore,
|
||||
arg.PassPoints,
|
||||
arg.DecidedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertSyntheticCategoryReview = `-- name: InsertSyntheticCategoryReview :execrows
|
||||
INSERT INTO assessment_synthetic_category_reviews (
|
||||
id, opening_id, category, source, opening_manifest_sha256,
|
||||
product_policy_version_id, product_policy_version, reviewed_by, reviewed_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4,
|
||||
$5, $6,
|
||||
$7, $8, $9
|
||||
)
|
||||
ON CONFLICT ON CONSTRAINT assessment_synthetic_category_reviews_exact_source_key DO NOTHING
|
||||
`
|
||||
|
||||
type InsertSyntheticCategoryReviewParams struct {
|
||||
ID pgtype.UUID
|
||||
OpeningID pgtype.UUID
|
||||
Category string
|
||||
Source string
|
||||
OpeningManifestSha256 []byte
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
ReviewedBy string
|
||||
ReviewedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// The application accepts only a validated immutable review snapshot. The
|
||||
// trigger independently checks the source opening, manifest and policy. A
|
||||
// concurrent or repeated attestation of the same exact source inserts nothing,
|
||||
// and the caller reads the stored one.
|
||||
func (q *Queries) InsertSyntheticCategoryReview(ctx context.Context, arg InsertSyntheticCategoryReviewParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, insertSyntheticCategoryReview,
|
||||
arg.ID,
|
||||
arg.OpeningID,
|
||||
arg.Category,
|
||||
arg.Source,
|
||||
arg.OpeningManifestSha256,
|
||||
arg.ProductPolicyVersionID,
|
||||
arg.ProductPolicyVersion,
|
||||
arg.ReviewedBy,
|
||||
arg.ReviewedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const listCandidateAssessmentResults = `-- name: ListCandidateAssessmentResults :many
|
||||
SELECT attempt_id, user_id, schema_version, result_snapshot::text,
|
||||
COALESCE(category_decision::text, '')::text AS category_decision, current_confirmed_grade, decided_at
|
||||
FROM assessment_attempt_results
|
||||
WHERE user_id = $1
|
||||
AND kind IN ('root', 'corrective')
|
||||
AND ($2::timestamptz IS NULL OR
|
||||
(decided_at, attempt_id) <
|
||||
($2::timestamptz, $3::uuid))
|
||||
ORDER BY decided_at DESC, attempt_id DESC
|
||||
LIMIT $4::integer + 1
|
||||
`
|
||||
|
||||
type ListCandidateAssessmentResultsParams struct {
|
||||
UserID pgtype.UUID
|
||||
CursorDecidedAt pgtype.Timestamptz
|
||||
CursorAttemptID pgtype.UUID
|
||||
LimitCount int32
|
||||
}
|
||||
|
||||
type ListCandidateAssessmentResultsRow struct {
|
||||
AttemptID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
SchemaVersion int16
|
||||
ResultSnapshot string
|
||||
CategoryDecision string
|
||||
CurrentConfirmedGrade pgtype.Text
|
||||
DecidedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// The caller validates and signs an opaque owner-bound cursor. This query
|
||||
// applies the keyset to the same stable order and fetches one extra row.
|
||||
func (q *Queries) ListCandidateAssessmentResults(ctx context.Context, arg ListCandidateAssessmentResultsParams) ([]ListCandidateAssessmentResultsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listCandidateAssessmentResults,
|
||||
arg.UserID,
|
||||
arg.CursorDecidedAt,
|
||||
arg.CursorAttemptID,
|
||||
arg.LimitCount,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListCandidateAssessmentResultsRow
|
||||
for rows.Next() {
|
||||
var i ListCandidateAssessmentResultsRow
|
||||
if err := rows.Scan(
|
||||
&i.AttemptID,
|
||||
&i.UserID,
|
||||
&i.SchemaVersion,
|
||||
&i.ResultSnapshot,
|
||||
&i.CategoryDecision,
|
||||
&i.CurrentConfirmedGrade,
|
||||
&i.DecidedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockCandidateAssessmentCategory = `-- name: LockCandidateAssessmentCategory :exec
|
||||
SELECT pg_advisory_xact_lock(hashtextextended(
|
||||
'lincodex.assessment.category:candidate:' || $1::text || ':' || $2::text,
|
||||
0
|
||||
))
|
||||
`
|
||||
|
||||
type LockCandidateAssessmentCategoryParams struct {
|
||||
CandidateID string
|
||||
Specialization string
|
||||
}
|
||||
|
||||
// Acquired after C3, candidate/specialization scope, and attempt row locks.
|
||||
// This independent lock serializes current category upgrades for one scope.
|
||||
func (q *Queries) LockCandidateAssessmentCategory(ctx context.Context, arg LockCandidateAssessmentCategoryParams) error {
|
||||
_, err := q.db.Exec(ctx, lockCandidateAssessmentCategory, arg.CandidateID, arg.Specialization)
|
||||
return err
|
||||
}
|
||||
|
||||
const saveCandidateAssessmentCategory = `-- name: SaveCandidateAssessmentCategory :execrows
|
||||
INSERT INTO candidate_assessment_categories (
|
||||
candidate_id, specialization, grade, source_attempt_id, source_review_id,
|
||||
product_policy_version_id, product_policy_version, grading_policy_version_id,
|
||||
opening_id, opening_manifest_sha256, source, calibration_status, assigned_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4,
|
||||
$5, $6, $7,
|
||||
(
|
||||
SELECT opening.policy_version_id
|
||||
FROM assessment_category_openings AS opening
|
||||
WHERE opening.id = $8
|
||||
),
|
||||
$8, $9,
|
||||
$10, $11, $12
|
||||
)
|
||||
ON CONFLICT (candidate_id, specialization) DO UPDATE SET
|
||||
grade = EXCLUDED.grade,
|
||||
source_attempt_id = EXCLUDED.source_attempt_id,
|
||||
source_review_id = EXCLUDED.source_review_id,
|
||||
product_policy_version_id = EXCLUDED.product_policy_version_id,
|
||||
product_policy_version = EXCLUDED.product_policy_version,
|
||||
grading_policy_version_id = EXCLUDED.grading_policy_version_id,
|
||||
opening_id = EXCLUDED.opening_id,
|
||||
opening_manifest_sha256 = EXCLUDED.opening_manifest_sha256,
|
||||
source = EXCLUDED.source,
|
||||
calibration_status = EXCLUDED.calibration_status,
|
||||
assigned_at = EXCLUDED.assigned_at
|
||||
WHERE CASE candidate_assessment_categories.grade
|
||||
WHEN 'intern' THEN 0 WHEN 'junior' THEN 1 WHEN 'middle' THEN 2 WHEN 'senior' THEN 3 ELSE -1 END
|
||||
< CASE EXCLUDED.grade
|
||||
WHEN 'intern' THEN 0 WHEN 'junior' THEN 1 WHEN 'middle' THEN 2 WHEN 'senior' THEN 3 ELSE -1 END
|
||||
`
|
||||
|
||||
type SaveCandidateAssessmentCategoryParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
Specialization string
|
||||
Grade string
|
||||
SourceAttemptID pgtype.UUID
|
||||
SourceReviewID pgtype.UUID
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
OpeningID pgtype.UUID
|
||||
OpeningManifestSha256 []byte
|
||||
Source string
|
||||
CalibrationStatus string
|
||||
AssignedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Only strict grade upgrades replace the current row. The trigger enforces
|
||||
// the same monotonic rule as a final guard against adapter mistakes. The
|
||||
// grading policy is read from the immutable opening, and the guard trigger
|
||||
// compares it with the policy captured in the assigned result.
|
||||
func (q *Queries) SaveCandidateAssessmentCategory(ctx context.Context, arg SaveCandidateAssessmentCategoryParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, saveCandidateAssessmentCategory,
|
||||
arg.CandidateID,
|
||||
arg.Specialization,
|
||||
arg.Grade,
|
||||
arg.SourceAttemptID,
|
||||
arg.SourceReviewID,
|
||||
arg.ProductPolicyVersionID,
|
||||
arg.ProductPolicyVersion,
|
||||
arg.OpeningID,
|
||||
arg.OpeningManifestSha256,
|
||||
arg.Source,
|
||||
arg.CalibrationStatus,
|
||||
arg.AssignedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
@@ -134,6 +134,8 @@ type AssessmentAttemptResult struct {
|
||||
RawScore pgtype.Int2
|
||||
PassPoints pgtype.Int2
|
||||
DecidedAt pgtype.Timestamptz
|
||||
CategoryDecision []byte
|
||||
CurrentConfirmedGrade pgtype.Text
|
||||
}
|
||||
|
||||
type AssessmentAttemptReview struct {
|
||||
@@ -240,6 +242,18 @@ type AssessmentSignalNoticeAcknowledgement struct {
|
||||
AcknowledgedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AssessmentSyntheticCategoryReview struct {
|
||||
ID pgtype.UUID
|
||||
OpeningID pgtype.UUID
|
||||
Category string
|
||||
Source string
|
||||
OpeningManifestSha256 []byte
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
ReviewedBy string
|
||||
ReviewedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AssessmentTrainingBankBinding struct {
|
||||
ID pgtype.UUID
|
||||
Category string
|
||||
@@ -260,6 +274,22 @@ type AssessmentTrainingBankBindingFamily struct {
|
||||
ContentSha256 []byte
|
||||
}
|
||||
|
||||
type CandidateAssessmentCategory struct {
|
||||
CandidateID pgtype.UUID
|
||||
Specialization string
|
||||
Grade string
|
||||
SourceAttemptID pgtype.UUID
|
||||
SourceReviewID pgtype.UUID
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
GradingPolicyVersionID pgtype.UUID
|
||||
OpeningID pgtype.UUID
|
||||
OpeningManifestSha256 []byte
|
||||
Source string
|
||||
CalibrationStatus string
|
||||
AssignedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type CandidateCardAccessEvent struct {
|
||||
ID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
@@ -584,6 +614,18 @@ type Membership struct {
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type NotificationInboxEvent struct {
|
||||
RecipientUserID pgtype.UUID
|
||||
EventID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
EventType string
|
||||
SchemaVersion int32
|
||||
SourceType string
|
||||
SourceID pgtype.UUID
|
||||
OccurredAt pgtype.Timestamptz
|
||||
ReadAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type Organization struct {
|
||||
ID pgtype.UUID
|
||||
Name string
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: notification_inbox.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const getNotificationInboxEvent = `-- name: GetNotificationInboxEvent :one
|
||||
SELECT
|
||||
recipient_user_id,
|
||||
event_id,
|
||||
organization_id,
|
||||
event_type,
|
||||
schema_version,
|
||||
source_type,
|
||||
source_id,
|
||||
occurred_at,
|
||||
read_at
|
||||
FROM notification_inbox_events
|
||||
WHERE recipient_user_id = $1
|
||||
AND event_id = $2
|
||||
`
|
||||
|
||||
type GetNotificationInboxEventParams struct {
|
||||
RecipientUserID pgtype.UUID
|
||||
EventID pgtype.UUID
|
||||
}
|
||||
|
||||
// Read the existing row after a duplicate insert so the repository can reject
|
||||
// an event ID whose immutable metadata changed on redelivery.
|
||||
func (q *Queries) GetNotificationInboxEvent(ctx context.Context, arg GetNotificationInboxEventParams) (NotificationInboxEvent, error) {
|
||||
row := q.db.QueryRow(ctx, getNotificationInboxEvent, arg.RecipientUserID, arg.EventID)
|
||||
var i NotificationInboxEvent
|
||||
err := row.Scan(
|
||||
&i.RecipientUserID,
|
||||
&i.EventID,
|
||||
&i.OrganizationID,
|
||||
&i.EventType,
|
||||
&i.SchemaVersion,
|
||||
&i.SourceType,
|
||||
&i.SourceID,
|
||||
&i.OccurredAt,
|
||||
&i.ReadAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertNotificationInboxEvent = `-- name: InsertNotificationInboxEvent :execrows
|
||||
INSERT INTO notification_inbox_events (
|
||||
recipient_user_id,
|
||||
event_id,
|
||||
organization_id,
|
||||
event_type,
|
||||
schema_version,
|
||||
source_type,
|
||||
source_id,
|
||||
occurred_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7,
|
||||
$8
|
||||
)
|
||||
ON CONFLICT (recipient_user_id, event_id) DO NOTHING
|
||||
`
|
||||
|
||||
type InsertNotificationInboxEventParams struct {
|
||||
RecipientUserID pgtype.UUID
|
||||
EventID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
EventType string
|
||||
SchemaVersion int32
|
||||
SourceType string
|
||||
SourceID pgtype.UUID
|
||||
OccurredAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Store one recipient's reference to a delivered invitation event. The
|
||||
// unique key absorbs at-least-once redelivery without copying event content.
|
||||
func (q *Queries) InsertNotificationInboxEvent(ctx context.Context, arg InsertNotificationInboxEventParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, insertNotificationInboxEvent,
|
||||
arg.RecipientUserID,
|
||||
arg.EventID,
|
||||
arg.OrganizationID,
|
||||
arg.EventType,
|
||||
arg.SchemaVersion,
|
||||
arg.SourceType,
|
||||
arg.SourceID,
|
||||
arg.OccurredAt,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const listNotificationInboxEvents = `-- name: ListNotificationInboxEvents :many
|
||||
SELECT
|
||||
recipient_user_id,
|
||||
event_id,
|
||||
organization_id,
|
||||
event_type,
|
||||
schema_version,
|
||||
source_type,
|
||||
source_id,
|
||||
occurred_at,
|
||||
read_at
|
||||
FROM notification_inbox_events
|
||||
WHERE recipient_user_id = $1
|
||||
AND (
|
||||
$2::uuid IS NULL
|
||||
OR organization_id = $2::uuid
|
||||
)
|
||||
AND (
|
||||
$3::timestamptz IS NULL
|
||||
OR (occurred_at, event_id) < (
|
||||
$3::timestamptz,
|
||||
$4::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY occurred_at DESC, event_id DESC
|
||||
LIMIT $5
|
||||
`
|
||||
|
||||
type ListNotificationInboxEventsParams struct {
|
||||
RecipientUserID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
AfterOccurredAt pgtype.Timestamptz
|
||||
AfterEventID pgtype.UUID
|
||||
PageLimit int32
|
||||
}
|
||||
|
||||
// List only the authenticated recipient's rows, optionally narrowed to one
|
||||
// organization context. The caller resolves current source visibility before
|
||||
// returning content.
|
||||
func (q *Queries) ListNotificationInboxEvents(ctx context.Context, arg ListNotificationInboxEventsParams) ([]NotificationInboxEvent, error) {
|
||||
rows, err := q.db.Query(ctx, listNotificationInboxEvents,
|
||||
arg.RecipientUserID,
|
||||
arg.OrganizationID,
|
||||
arg.AfterOccurredAt,
|
||||
arg.AfterEventID,
|
||||
arg.PageLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []NotificationInboxEvent
|
||||
for rows.Next() {
|
||||
var i NotificationInboxEvent
|
||||
if err := rows.Scan(
|
||||
&i.RecipientUserID,
|
||||
&i.EventID,
|
||||
&i.OrganizationID,
|
||||
&i.EventType,
|
||||
&i.SchemaVersion,
|
||||
&i.SourceType,
|
||||
&i.SourceID,
|
||||
&i.OccurredAt,
|
||||
&i.ReadAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const markNotificationInboxEventRead = `-- name: MarkNotificationInboxEventRead :one
|
||||
UPDATE notification_inbox_events
|
||||
SET read_at = COALESCE(read_at, $1::timestamptz)
|
||||
WHERE recipient_user_id = $2
|
||||
AND organization_id = $3
|
||||
AND event_id = $4
|
||||
RETURNING
|
||||
recipient_user_id,
|
||||
event_id,
|
||||
organization_id,
|
||||
event_type,
|
||||
schema_version,
|
||||
source_type,
|
||||
source_id,
|
||||
occurred_at,
|
||||
read_at
|
||||
`
|
||||
|
||||
type MarkNotificationInboxEventReadParams struct {
|
||||
ReadAt pgtype.Timestamptz
|
||||
RecipientUserID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
EventID pgtype.UUID
|
||||
}
|
||||
|
||||
// Persist the first read time under exact recipient and organization scope.
|
||||
// Repeated calls preserve the original read timestamp.
|
||||
func (q *Queries) MarkNotificationInboxEventRead(ctx context.Context, arg MarkNotificationInboxEventReadParams) (NotificationInboxEvent, error) {
|
||||
row := q.db.QueryRow(ctx, markNotificationInboxEventRead,
|
||||
arg.ReadAt,
|
||||
arg.RecipientUserID,
|
||||
arg.OrganizationID,
|
||||
arg.EventID,
|
||||
)
|
||||
var i NotificationInboxEvent
|
||||
err := row.Scan(
|
||||
&i.RecipientUserID,
|
||||
&i.EventID,
|
||||
&i.OrganizationID,
|
||||
&i.EventType,
|
||||
&i.SchemaVersion,
|
||||
&i.SourceType,
|
||||
&i.SourceID,
|
||||
&i.OccurredAt,
|
||||
&i.ReadAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -53,7 +53,18 @@ SELECT
|
||||
WHERE overlap.user_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS parallel_period_acknowledgements
|
||||
) AS parallel_period_acknowledgements,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object('specialization', category.specialization, 'grade', category.grade)
|
||||
ORDER BY category.specialization
|
||||
)::text
|
||||
FROM candidate_assessment_categories AS category
|
||||
WHERE category.candidate_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS confirmed_categories
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
@@ -82,6 +93,7 @@ type ListVisibleCandidateViewSourcesRow struct {
|
||||
ConfirmedAt pgtype.Timestamptz
|
||||
WorkFormats []string
|
||||
ParallelPeriodAcknowledgements interface{}
|
||||
ConfirmedCategories interface{}
|
||||
}
|
||||
|
||||
// Organization-facing anonymous candidate projection inputs. The calling
|
||||
@@ -90,7 +102,9 @@ type ListVisibleCandidateViewSourcesRow struct {
|
||||
// candidates hidden from this organization before any profile value is read.
|
||||
// The projection reads only stack, declared role, and experience dates. It
|
||||
// deliberately excludes names, contacts, salary, location, soft skills,
|
||||
// employer names, summaries, and imported excerpts.
|
||||
// employer names, summaries, and imported excerpts. The only assessment data
|
||||
// is the current category (specialization and grade) of the separate current
|
||||
// category table; it carries no attempt, score, review, policy, or history.
|
||||
func (q *Queries) ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error) {
|
||||
rows, err := q.db.Query(ctx, listVisibleCandidateViewSources, organizationID)
|
||||
if err != nil {
|
||||
@@ -113,6 +127,7 @@ func (q *Queries) ListVisibleCandidateViewSources(ctx context.Context, organizat
|
||||
&i.ConfirmedAt,
|
||||
&i.WorkFormats,
|
||||
&i.ParallelPeriodAcknowledgements,
|
||||
&i.ConfirmedCategories,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -267,7 +282,18 @@ SELECT
|
||||
WHERE overlap.user_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS parallel_period_acknowledgements
|
||||
) AS parallel_period_acknowledgements,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object('specialization', category.specialization, 'grade', category.grade)
|
||||
ORDER BY category.specialization
|
||||
)::text
|
||||
FROM candidate_assessment_categories AS category
|
||||
WHERE category.candidate_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS confirmed_categories
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
@@ -291,6 +317,7 @@ type ReadCandidateViewSourceForPreviewRow struct {
|
||||
ConfirmedAt pgtype.Timestamptz
|
||||
WorkFormats []string
|
||||
ParallelPeriodAcknowledgements interface{}
|
||||
ConfirmedCategories interface{}
|
||||
}
|
||||
|
||||
// Read the candidate's current private projection inputs after the caller
|
||||
@@ -318,6 +345,7 @@ func (q *Queries) ReadCandidateViewSourceForPreview(ctx context.Context, candida
|
||||
&i.ConfirmedAt,
|
||||
&i.WorkFormats,
|
||||
&i.ParallelPeriodAcknowledgements,
|
||||
&i.ConfirmedCategories,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -227,6 +227,9 @@ type Querier interface {
|
||||
GetAssessmentAttemptKindForCandidate(ctx context.Context, arg GetAssessmentAttemptKindForCandidateParams) (string, error)
|
||||
// Reads a result only for the owning candidate.
|
||||
GetAssessmentAttemptResult(ctx context.Context, arg GetAssessmentAttemptResultParams) (string, error)
|
||||
// Returns both immutable result versions. NULL category fields identify a
|
||||
// legacy v1 record and must not be reconstructed from current state.
|
||||
GetAssessmentAttemptResultHistoryEntry(ctx context.Context, arg GetAssessmentAttemptResultHistoryEntryParams) (GetAssessmentAttemptResultHistoryEntryRow, error)
|
||||
GetAssessmentAttemptReview(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentAttemptReviewRow, error)
|
||||
// Reads an active real attempt without taking the write lock used by create.
|
||||
// The availability GET never expires or otherwise mutates this row.
|
||||
@@ -245,6 +248,7 @@ type Querier interface {
|
||||
GetAssessmentSignalNoticeAcknowledgement(ctx context.Context, arg GetAssessmentSignalNoticeAcknowledgementParams) (pgtype.Timestamptz, error)
|
||||
// Read only the receipt associated with the reserved idempotency scope.
|
||||
GetAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentSignalOutcomeRow, error)
|
||||
GetCandidateAssessmentCategory(ctx context.Context, arg GetCandidateAssessmentCategoryParams) (CandidateAssessmentCategory, error)
|
||||
// Reads one hiding of the candidate with the current name of the
|
||||
// organization.
|
||||
GetCandidateHiddenOrganization(ctx context.Context, arg GetCandidateHiddenOrganizationParams) (GetCandidateHiddenOrganizationRow, error)
|
||||
@@ -297,6 +301,9 @@ type Querier interface {
|
||||
GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error)
|
||||
// Reads the membership of one account in one organization, in any state.
|
||||
GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error)
|
||||
// Read the existing row after a duplicate insert so the repository can reject
|
||||
// an event ID whose immutable metadata changed on redelivery.
|
||||
GetNotificationInboxEvent(ctx context.Context, arg GetNotificationInboxEventParams) (NotificationInboxEvent, error)
|
||||
// Reads only the historical result. It intentionally does not join the live
|
||||
// organization or membership, whose profile and state may have since changed.
|
||||
GetOrganizationCreationResult(ctx context.Context, scopeHash []byte) ([]byte, error)
|
||||
@@ -334,6 +341,7 @@ type Querier interface {
|
||||
// selects no token hash. A missing binding or token row gives NULL token
|
||||
// columns.
|
||||
GetServiceMailState(ctx context.Context, id pgtype.UUID) (GetServiceMailStateRow, error)
|
||||
GetSyntheticCategoryReview(ctx context.Context, arg GetSyntheticCategoryReviewParams) (AssessmentSyntheticCategoryReview, error)
|
||||
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)
|
||||
@@ -347,6 +355,9 @@ type Querier interface {
|
||||
// Stores one immutable candidate-visible result with the decision rationale
|
||||
// and source versions used by its finalized attempt.
|
||||
InsertAssessmentAttemptResult(ctx context.Context, arg InsertAssessmentAttemptResultParams) error
|
||||
// Stores the category decision and current grade captured at real-attempt
|
||||
// finalization. The base result document remains its original v1 shape.
|
||||
InsertAssessmentAttemptResultV2(ctx context.Context, arg InsertAssessmentAttemptResultV2Params) 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.
|
||||
@@ -439,6 +450,9 @@ type Querier interface {
|
||||
InsertMailQuotaReservation(ctx context.Context, arg InsertMailQuotaReservationParams) error
|
||||
InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error
|
||||
InsertMembership(ctx context.Context, arg InsertMembershipParams) error
|
||||
// Store one recipient's reference to a delivered invitation event. The
|
||||
// unique key absorbs at-least-once redelivery without copying event content.
|
||||
InsertNotificationInboxEvent(ctx context.Context, arg InsertNotificationInboxEventParams) (int64, error)
|
||||
// Stores a new organization with the verification level that the domain
|
||||
// gave it. The deferred constraint organizations_owner_required fails the
|
||||
// transaction at commit unless an active owner membership was inserted in
|
||||
@@ -483,6 +497,11 @@ type Querier interface {
|
||||
InsertSupportCaseCreateOutcome(ctx context.Context, arg InsertSupportCaseCreateOutcomeParams) error
|
||||
InsertSupportCaseEvent(ctx context.Context, arg InsertSupportCaseEventParams) error
|
||||
InsertSupportCaseRequestEvent(ctx context.Context, arg InsertSupportCaseRequestEventParams) error
|
||||
// The application accepts only a validated immutable review snapshot. The
|
||||
// trigger independently checks the source opening, manifest and policy. A
|
||||
// concurrent or repeated attestation of the same exact source inserts nothing,
|
||||
// and the caller reads the stored one.
|
||||
InsertSyntheticCategoryReview(ctx context.Context, arg InsertSyntheticCategoryReviewParams) (int64, error)
|
||||
InsertUser(ctx context.Context, arg InsertUserParams) error
|
||||
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
|
||||
// Read the latest serialized event so a temporarily regressing application
|
||||
@@ -523,6 +542,9 @@ type Querier interface {
|
||||
ListAssessmentOriginMarks(ctx context.Context, attemptID pgtype.UUID) ([]AssessmentAttemptOriginMark, error)
|
||||
// Reads the exact family membership pinned by a training binding.
|
||||
ListAssessmentTrainingBindingFamilies(ctx context.Context, bindingID pgtype.UUID) ([]ListAssessmentTrainingBindingFamiliesRow, error)
|
||||
// The caller validates and signs an opaque owner-bound cursor. This query
|
||||
// applies the keyset to the same stable order and fetches one extra row.
|
||||
ListCandidateAssessmentResults(ctx context.Context, arg ListCandidateAssessmentResultsParams) ([]ListCandidateAssessmentResultsRow, error)
|
||||
// Lists only the current candidate's own access history. It deliberately
|
||||
// omits the employee, requested card fields, and search context. The privacy
|
||||
// read adapter resolves an organization name only through this recorded
|
||||
@@ -559,6 +581,10 @@ type Querier interface {
|
||||
// fingerprint; stale bindings are omitted fail-closed.
|
||||
ListCurrentSpecializationAvailability(ctx context.Context) ([]ListCurrentSpecializationAvailabilityRow, error)
|
||||
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
|
||||
// List only the authenticated recipient's rows, optionally narrowed to one
|
||||
// organization context. The caller resolves current source visibility before
|
||||
// returning content.
|
||||
ListNotificationInboxEvents(ctx context.Context, arg ListNotificationInboxEventsParams) ([]NotificationInboxEvent, error)
|
||||
// Read one bounded newest-first page of current needs. Both the organization
|
||||
// scope and the tuple cursor are applied before the limit.
|
||||
ListOrganizationNeeds(ctx context.Context, arg ListOrganizationNeedsParams) ([]ListOrganizationNeedsRow, error)
|
||||
@@ -579,7 +605,9 @@ type Querier interface {
|
||||
// candidates hidden from this organization before any profile value is read.
|
||||
// The projection reads only stack, declared role, and experience dates. It
|
||||
// deliberately excludes names, contacts, salary, location, soft skills,
|
||||
// employer names, summaries, and imported excerpts.
|
||||
// employer names, summaries, and imported excerpts. The only assessment data
|
||||
// is the current category (specialization and grade) of the separate current
|
||||
// category table; it carries no attempt, score, review, policy, or history.
|
||||
ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error)
|
||||
// Locks the organization first and then the active membership, using the
|
||||
// same order as organization profile writes. A company operation keeps both
|
||||
@@ -604,6 +632,9 @@ type Querier interface {
|
||||
// a hide either commits before the later visibility recheck or waits for the
|
||||
// read transaction to finish.
|
||||
LockCandidateAccountForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
|
||||
// Acquired after C3, candidate/specialization scope, and attempt row locks.
|
||||
// This independent lock serializes current category upgrades for one scope.
|
||||
LockCandidateAssessmentCategory(ctx context.Context, arg LockCandidateAssessmentCategoryParams) error
|
||||
// Locks the candidate's published row only when it refers to a C2 record
|
||||
// revoked by this transaction. The setting remains linked to that immutable
|
||||
// record; ReadCandidatePublication computes the effective closed state and
|
||||
@@ -685,6 +716,9 @@ type Querier interface {
|
||||
// gate stops admitting sends until the window resets or an operator raises
|
||||
// the limit. The caller holds the row lock.
|
||||
MarkMailQuotaExhausted(ctx context.Context, arg MarkMailQuotaExhaustedParams) (int64, error)
|
||||
// Persist the first read time under exact recipient and organization scope.
|
||||
// Repeated calls preserve the original read timestamp.
|
||||
MarkNotificationInboxEventRead(ctx context.Context, arg MarkNotificationInboxEventReadParams) (NotificationInboxEvent, error)
|
||||
// Marks the events that the broker acknowledged. The relay passes only IDs
|
||||
// whose rows its own transaction locked, so the statement never waits and the
|
||||
// count equals the number of distinct IDs.
|
||||
@@ -835,6 +869,11 @@ 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)
|
||||
// Only strict grade upgrades replace the current row. The trigger enforces
|
||||
// the same monotonic rule as a final guard against adapter mistakes. The
|
||||
// grading policy is read from the immutable opening, and the guard trigger
|
||||
// compares it with the policy captured in the assigned result.
|
||||
SaveCandidateAssessmentCategory(ctx context.Context, arg SaveCandidateAssessmentCategoryParams) (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
|
||||
|
||||
Reference in new issue
Block a user