feat(evidence): project skill evidence from confirmed assessments

This commit is contained in:
shira committed 2026-10-09 11:25:19 +03:00
1 parent 4761508f13
commit c2a8d17195
94 files changed
+10077 -151

No files matched your search

@@ -0,0 +1,189 @@
package postgres
import (
"context"
"fmt"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var _ outbound.EvidenceRepository = evidenceRepository{}
func (unit *UnitOfWork) Evidence() outbound.EvidenceRepository {
return evidenceRepository{queries: unit.queries}
}
type evidenceRepository struct {
queries *sqlc.Queries
}
func (repository evidenceRepository) ListCandidateFacts(
ctx context.Context,
query outbound.EvidenceListQuery,
) (outbound.EvidenceFactPage, error) {
const location = "evidenceRepository.ListCandidateFacts"
if query.CandidateID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxEvidencePageSize {
return outbound.EvidenceFactPage{}, fmt.Errorf("%s - query is invalid: %w", location, domain.ErrInvalidEvidence)
}
// The statement fetches one extra row to learn whether another page follows.
params := sqlc.ListCandidateEvidenceFactsParams{CandidateID: pgUUID(query.CandidateID), RowLimit: query.Limit + 1}
if query.After != nil {
if query.After.ID == uuid.Nil || query.After.OccurredAt.IsZero() {
return outbound.EvidenceFactPage{}, fmt.Errorf("%s - continuation position is invalid: %w", location, domain.ErrInvalidEvidence)
}
params.AfterOccurredAt = pgTime(query.After.OccurredAt)
params.AfterID = pgUUID(query.After.ID)
}
rows, err := repository.queries.ListCandidateEvidenceFacts(ctx, params)
if err != nil {
return outbound.EvidenceFactPage{}, fmt.Errorf("%s - select facts: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
page := outbound.EvidenceFactPage{Items: make([]domain.EvidenceFact, 0, min(len(rows), int(query.Limit)))}
if len(rows) > int(query.Limit) {
page.HasMore = true
rows = rows[:query.Limit]
}
for _, row := range rows {
fact, err := restoreEvidenceFactRow(query.CandidateID, row)
if err != nil {
return outbound.EvidenceFactPage{}, fmt.Errorf("%s - restore fact: %w", location, err)
}
page.Items = append(page.Items, fact)
}
return page, nil
}
func restoreEvidenceFactRow(candidateID uuid.UUID, row sqlc.ListCandidateEvidenceFactsRow) (domain.EvidenceFact, error) {
const location = "restoreEvidenceFactRow"
skills := make([]domain.EvidenceSkillCode, 0, len(row.Skills))
for _, code := range row.Skills {
skills = append(skills, domain.EvidenceSkillCode(code))
}
trust, err := evidenceTrust(row.Trust)
if err != nil {
return domain.EvidenceFact{}, fmt.Errorf("%s - %w", location, err)
}
fact, err := domain.RestoreEvidenceFact(domain.EvidenceFactSnapshot{
ID: optionalUUID(row.ID), CandidateID: candidateID, Kind: domain.EvidenceKind(row.Kind),
SourceType: domain.EvidenceSourceType(row.SourceType), EventID: optionalUUID(row.EventID),
ResultID: optionalUUID(row.ResultID), Skills: skills,
Result: domain.EvidenceResult{
Grade: domain.GradeCode(row.Grade), Basis: domain.AssessmentCategorySource(row.Basis),
CalibrationStatus: domain.AssessmentCategoryCalibrationStatus(row.CalibrationStatus),
},
Attribution: domain.EvidenceAttribution(row.Attribution), Trust: trust,
OccurredAt: timeValueOrZero(row.OccurredAt), Visibility: domain.EvidenceVisibility(row.Visibility),
})
if err != nil {
return domain.EvidenceFact{}, fmt.Errorf("%s - stored fact is invalid: %w", location, err)
}
return fact, nil
}
func (repository evidenceRepository) ListOrganizationFacts(
ctx context.Context,
organizationID, candidateID uuid.UUID,
categories []domain.CandidateViewCategory,
) ([]domain.EvidenceOrganizationFact, error) {
const location = "evidenceRepository.ListOrganizationFacts"
if organizationID == uuid.Nil || candidateID == uuid.Nil {
return nil, fmt.Errorf("%s - identifiers must be set: %w", location, domain.ErrInvalidEvidence)
}
pairs, err := evidenceCategoryPairs(categories)
if err != nil {
return nil, fmt.Errorf("%s - %w", location, err)
}
if len(pairs) == 0 {
return []domain.EvidenceOrganizationFact{}, nil
}
rows, err := repository.queries.ListOrganizationVisibleEvidence(ctx, sqlc.ListOrganizationVisibleEvidenceParams{
Categories: pairs, CandidateID: pgUUID(candidateID), OrganizationID: pgUUID(organizationID),
})
if err != nil {
return nil, fmt.Errorf("%s - select permitted facts: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
facts := make([]domain.EvidenceOrganizationFact, 0, len(rows))
for _, row := range rows {
fact, err := restoreEvidenceOrganizationFact(row.Skill, row.Grade, row.Trust, row.Basis, row.CalibrationStatus, row.ObservedYear)
if err != nil {
return nil, fmt.Errorf("%s - %w", location, err)
}
facts = append(facts, fact)
}
return facts, nil
}
func (repository evidenceRepository) ListPreviewFacts(
ctx context.Context,
candidateID uuid.UUID,
categories []domain.CandidateViewCategory,
) ([]domain.EvidenceOrganizationFact, error) {
const location = "evidenceRepository.ListPreviewFacts"
if candidateID == uuid.Nil {
return nil, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidEvidence)
}
pairs, err := evidenceCategoryPairs(categories)
if err != nil {
return nil, fmt.Errorf("%s - %w", location, err)
}
if len(pairs) == 0 {
return []domain.EvidenceOrganizationFact{}, nil
}
rows, err := repository.queries.ListCandidatePreviewEvidence(ctx, sqlc.ListCandidatePreviewEvidenceParams{
Categories: pairs, CandidateID: pgUUID(candidateID),
})
if err != nil {
return nil, fmt.Errorf("%s - select preview facts: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
facts := make([]domain.EvidenceOrganizationFact, 0, len(rows))
for _, row := range rows {
fact, err := restoreEvidenceOrganizationFact(row.Skill, row.Grade, row.Trust, row.Basis, row.CalibrationStatus, row.ObservedYear)
if err != nil {
return nil, fmt.Errorf("%s - %w", location, err)
}
facts = append(facts, fact)
}
return facts, nil
}
// evidenceCategoryPairs renders the categories of a card as the
// "specialization/grade" keys that the statements match against a fact.
func evidenceCategoryPairs(categories []domain.CandidateViewCategory) ([]string, error) {
pairs := make([]string, 0, len(categories))
for _, category := range categories {
if !category.Specialization.IsKnown() || !category.Grade.IsKnown() {
return nil, fmt.Errorf("category is not known: %w", domain.ErrInvalidEvidence)
}
pairs = append(pairs, string(domain.EvidenceSkillOfSpecialization(category.Specialization))+"/"+string(category.Grade))
}
return pairs, nil
}
func restoreEvidenceOrganizationFact(skill, grade string, trust int16, basis, calibration string, year int32) (domain.EvidenceOrganizationFact, error) {
level, err := evidenceTrust(trust)
if err != nil {
return domain.EvidenceOrganizationFact{}, err
}
fact, err := domain.NewEvidenceOrganizationFact(domain.EvidenceOrganizationFactInput{
Skill: domain.EvidenceSkillCode(skill), Grade: domain.GradeCode(grade), Trust: level,
Basis: domain.AssessmentCategorySource(basis), CalibrationStatus: domain.AssessmentCategoryCalibrationStatus(calibration),
ObservedYear: year,
})
if err != nil {
return domain.EvidenceOrganizationFact{}, fmt.Errorf("restore permitted fact: %w", err)
}
return fact, nil
}
// evidenceTrust narrows the stored smallint after checking the range that the
// table constraint already guarantees.
func evidenceTrust(value int16) (domain.EvidenceTrust, error) {
if value < int16(domain.EvidenceTrustStated) || value > int16(domain.EvidenceTrustInPerson) {
return 0, fmt.Errorf("stored trust level is out of range: %w", domain.ErrInvalidEvidence)
}
return domain.EvidenceTrust(value), nil
}
@@ -0,0 +1,266 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: evidence.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const listCandidateEvidenceFacts = `-- name: ListCandidateEvidenceFacts :many
SELECT
fact.id,
fact.kind,
fact.source_type,
fact.event_id,
fact.result_id,
fact.attribution,
fact.trust,
fact.grade,
fact.basis,
fact.calibration_status,
fact.occurred_at,
fact.visibility,
COALESCE(
(
SELECT array_agg(skill.skill_code ORDER BY skill.skill_code)
FROM skill_evidence_skills AS skill
WHERE skill.fact_id = fact.id
),
'{}'::text []
)::text [] AS skills
FROM skill_evidence_facts AS fact
WHERE
fact.candidate_id = $1
AND (
$2::timestamptz IS NULL
OR (fact.occurred_at, fact.id) < (
$2::timestamptz,
$3::uuid
)
)
ORDER BY fact.occurred_at DESC, fact.id DESC
LIMIT $4
`
type ListCandidateEvidenceFactsParams struct {
CandidateID pgtype.UUID
AfterOccurredAt pgtype.Timestamptz
AfterID pgtype.UUID
RowLimit int32
}
type ListCandidateEvidenceFactsRow struct {
ID pgtype.UUID
Kind string
SourceType string
EventID pgtype.UUID
ResultID pgtype.UUID
Attribution string
Trust int16
Grade string
Basis string
CalibrationStatus string
OccurredAt pgtype.Timestamptz
Visibility string
Skills []string
}
// Skill evidence reads. The projection tables hold no answer, score, item,
// failure, or anti-cheat data, and none of these statements names the result,
// attempt, or review tables: evidence is read from its own facts only.
// The candidate's own facts, hidden ones included, newest event first. Every
// statement is scoped by the owner; the caller passes the continuation
// position of the previous page, if any, and fetches one extra row.
func (q *Queries) ListCandidateEvidenceFacts(ctx context.Context, arg ListCandidateEvidenceFactsParams) ([]ListCandidateEvidenceFactsRow, error) {
rows, err := q.db.Query(ctx, listCandidateEvidenceFacts,
arg.CandidateID,
arg.AfterOccurredAt,
arg.AfterID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListCandidateEvidenceFactsRow
for rows.Next() {
var i ListCandidateEvidenceFactsRow
if err := rows.Scan(
&i.ID,
&i.Kind,
&i.SourceType,
&i.EventID,
&i.ResultID,
&i.Attribution,
&i.Trust,
&i.Grade,
&i.Basis,
&i.CalibrationStatus,
&i.OccurredAt,
&i.Visibility,
&i.Skills,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listCandidatePreviewEvidence = `-- name: ListCandidatePreviewEvidence :many
SELECT DISTINCT ON (skill.skill_code)
skill.skill_code AS skill,
fact.grade,
fact.trust,
fact.basis,
fact.calibration_status,
extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year
FROM skill_evidence_facts AS fact
INNER JOIN skill_evidence_skills AS skill
ON fact.id = skill.fact_id
WHERE
fact.candidate_id = $1
AND (skill.skill_code || '/' || fact.grade) = any($2::text [])
AND fact.kind = 'measurement'
AND fact.visibility = 'visible'
ORDER BY skill.skill_code, fact.occurred_at, fact.id
`
type ListCandidatePreviewEvidenceParams struct {
CandidateID pgtype.UUID
Categories []string
}
type ListCandidatePreviewEvidenceRow struct {
Skill string
Grade string
Trust int16
Basis string
CalibrationStatus string
ObservedYear int32
}
// The same selection for the candidate's own card preview, so the candidate
// sees what an organization would read. It is scoped by the owner and runs
// after the caller locked the effective C2 and publication; it does not apply
// an organization or a cohort.
func (q *Queries) ListCandidatePreviewEvidence(ctx context.Context, arg ListCandidatePreviewEvidenceParams) ([]ListCandidatePreviewEvidenceRow, error) {
rows, err := q.db.Query(ctx, listCandidatePreviewEvidence, arg.CandidateID, arg.Categories)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListCandidatePreviewEvidenceRow
for rows.Next() {
var i ListCandidatePreviewEvidenceRow
if err := rows.Scan(
&i.Skill,
&i.Grade,
&i.Trust,
&i.Basis,
&i.CalibrationStatus,
&i.ObservedYear,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listOrganizationVisibleEvidence = `-- name: ListOrganizationVisibleEvidence :many
SELECT DISTINCT ON (skill.skill_code)
skill.skill_code AS skill,
fact.grade,
fact.trust,
fact.basis,
fact.calibration_status,
extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year
FROM candidate_effective_publications AS effective
INNER JOIN skill_evidence_facts AS fact
ON effective.user_id = fact.candidate_id
INNER JOIN skill_evidence_skills AS skill
ON fact.id = skill.fact_id
WHERE
effective.user_id = $1
AND 'categories' = any(effective.fields)
AND (skill.skill_code || '/' || fact.grade) = any($2::text [])
AND fact.kind = 'measurement'
AND fact.visibility = 'visible'
AND NOT EXISTS (
SELECT 1
FROM candidate_hidden_organizations AS hidden
WHERE
hidden.user_id = effective.user_id
AND hidden.organization_id = $3
)
ORDER BY skill.skill_code, fact.occurred_at, fact.id
`
type ListOrganizationVisibleEvidenceParams struct {
CandidateID pgtype.UUID
Categories []string
OrganizationID pgtype.UUID
}
type ListOrganizationVisibleEvidenceRow struct {
Skill string
Grade string
Trust int16
Basis string
CalibrationStatus string
ObservedYear int32
}
// The evidence that one organization may read about one candidate: one fact
// for each category of the card, the fact that supports the confirmed grade
// of that category (the earliest one that passed exactly that grade, so a
// lower grade or a retake adds nothing). The statement selects from the
// effective publication view (published and backed by an unrevoked C2) and
// excludes the candidates that hide the reading organization, so no row means
// nothing to read, whatever the reason. The card must publish the categories
// field and only visible measurements qualify. The categories come from the
// caller as "specialization/grade" pairs taken from the card that was just
// projected, so the answer never names a skill the card does not show. The columns are
// an allowlist: no identifier of the fact, the event, the result, or the
// candidate leaves, the instant is cut to the year, and the basis and the
// calibration (the same for every candidate) say that the fact is a synthetic
// demonstration.
func (q *Queries) ListOrganizationVisibleEvidence(ctx context.Context, arg ListOrganizationVisibleEvidenceParams) ([]ListOrganizationVisibleEvidenceRow, error) {
rows, err := q.db.Query(ctx, listOrganizationVisibleEvidence, arg.CandidateID, arg.Categories, arg.OrganizationID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListOrganizationVisibleEvidenceRow
for rows.Next() {
var i ListOrganizationVisibleEvidenceRow
if err := rows.Scan(
&i.Skill,
&i.Grade,
&i.Trust,
&i.Basis,
&i.CalibrationStatus,
&i.ObservedYear,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -729,6 +729,29 @@ type Session struct {
RevokedAt pgtype.Timestamptz
}
type SkillEvidenceFact struct {
ID pgtype.UUID
CandidateID pgtype.UUID
Kind string
SourceType string
EventID pgtype.UUID
ResultID pgtype.UUID
Attribution string
Trust int16
Grade string
Basis string
CalibrationStatus string
OccurredAt pgtype.Timestamptz
Visibility string
RecordedAt pgtype.Timestamptz
CreatedTxid int64
}
type SkillEvidenceSkill struct {
FactID pgtype.UUID
SkillCode string
}
type SupportCase struct {
ID pgtype.UUID
CaseNumber string
@@ -550,11 +550,23 @@ type Querier interface {
// read adapter resolves an organization name only through this recorded
// access relation, which is already visible to the candidate.
ListCandidateCardAccessEvents(ctx context.Context, arg ListCandidateCardAccessEventsParams) ([]ListCandidateCardAccessEventsRow, error)
// Skill evidence reads. The projection tables hold no answer, score, item,
// failure, or anti-cheat data, and none of these statements names the result,
// attempt, or review tables: evidence is read from its own facts only.
// The candidate's own facts, hidden ones included, newest event first. Every
// statement is scoped by the owner; the caller passes the continuation
// position of the previous page, if any, and fetches one extra row.
ListCandidateEvidenceFacts(ctx context.Context, arg ListCandidateEvidenceFactsParams) ([]ListCandidateEvidenceFactsRow, error)
// One page of the candidate's hidden organizations, newest first with the
// organization identifier as the tie-breaker. The page continues after the
// (hidden_at, organization_id) position of the last record of the previous
// page.
ListCandidateHiddenOrganizations(ctx context.Context, arg ListCandidateHiddenOrganizationsParams) ([]ListCandidateHiddenOrganizationsRow, error)
// The same selection for the candidate's own card preview, so the candidate
// sees what an organization would read. It is scoped by the owner and runs
// after the caller locked the effective C2 and publication; it does not apply
// an organization or a cohort.
ListCandidatePreviewEvidence(ctx context.Context, arg ListCandidatePreviewEvidenceParams) ([]ListCandidatePreviewEvidenceRow, error)
// One page of the candidate's settings history, newest first with the event
// identifier as the tie-breaker. The organization name is resolved here, at
// read time, and is the current name. The page continues after the
@@ -588,6 +600,21 @@ type Querier interface {
// 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)
// The evidence that one organization may read about one candidate: one fact
// for each category of the card, the fact that supports the confirmed grade
// of that category (the earliest one that passed exactly that grade, so a
// lower grade or a retake adds nothing). The statement selects from the
// effective publication view (published and backed by an unrevoked C2) and
// excludes the candidates that hide the reading organization, so no row means
// nothing to read, whatever the reason. The card must publish the categories
// field and only visible measurements qualify. The categories come from the
// caller as "specialization/grade" pairs taken from the card that was just
// projected, so the answer never names a skill the card does not show. The columns are
// an allowlist: no identifier of the fact, the event, the result, or the
// candidate leaves, the instant is cut to the year, and the basis and the
// calibration (the same for every candidate) say that the fact is a synthetic
// demonstration.
ListOrganizationVisibleEvidence(ctx context.Context, arg ListOrganizationVisibleEvidenceParams) ([]ListOrganizationVisibleEvidenceRow, error)
// Lists the organizations where an account has an active membership,
// newest membership first. The page continues after the (membership
// creation time, organization ID) position of the last item of the