feat: add assessment, privacy and support flows

This commit is contained in:
TakuyaYagam1 committed 2026-10-08 08:08:25 +03:00
1 parent ee3738ee73
commit e4f24fa202
339 files changed
+56454 -1126

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,365 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: assessment_availability.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getAssessmentAvailabilityActiveAttempt = `-- name: GetAssessmentAvailabilityActiveAttempt :one
SELECT id, expires_at
FROM assessment_attempts
WHERE user_id = $1
AND specialization = $2
AND kind IN ('root', 'corrective')
AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize')
ORDER BY created_at DESC, id DESC
LIMIT 1
`
type GetAssessmentAvailabilityActiveAttemptParams struct {
UserID pgtype.UUID
Specialization pgtype.Text
}
type GetAssessmentAvailabilityActiveAttemptRow struct {
ID pgtype.UUID
ExpiresAt pgtype.Timestamptz
}
// Reads an active real attempt without taking the write lock used by create.
// The availability GET never expires or otherwise mutates this row.
func (q *Queries) GetAssessmentAvailabilityActiveAttempt(ctx context.Context, arg GetAssessmentAvailabilityActiveAttemptParams) (GetAssessmentAvailabilityActiveAttemptRow, error) {
row := q.db.QueryRow(ctx, getAssessmentAvailabilityActiveAttempt, arg.UserID, arg.Specialization)
var i GetAssessmentAvailabilityActiveAttemptRow
err := row.Scan(&i.ID, &i.ExpiresAt)
return i, err
}
const getAssessmentRootQuotaAvailability = `-- name: GetAssessmentRootQuotaAvailability :one
WITH eligible AS (
SELECT attempt.id, attempt.created_at
FROM assessment_attempts AS attempt
LEFT JOIN assessment_attempt_results AS result
ON result.attempt_id = attempt.id AND result.user_id = attempt.user_id
WHERE attempt.user_id = $3
AND attempt.kind = 'root'
AND attempt.state <> 'insufficient_bank'
AND attempt.created_at >= $4::timestamptz
AND attempt.created_at <= $5::timestamptz
AND COALESCE(result.result_snapshot->>'not_determined_reason', '')
NOT IN ('insufficient_bank', 'sandbox_unavailable')
), total AS (
SELECT count(*)::bigint AS attempt_count FROM eligible
)
SELECT
total.attempt_count,
CASE WHEN total.attempt_count >= $1::bigint THEN (
SELECT eligible.created_at
+ make_interval(secs => $2::double precision)
+ interval '1 microsecond'
FROM eligible
ORDER BY eligible.created_at, eligible.id
LIMIT 1
OFFSET (total.attempt_count - $1::bigint)
) ELSE NULL::timestamptz END AS available_at
FROM total
`
type GetAssessmentRootQuotaAvailabilityParams struct {
MaxAttempts int64
WindowSeconds float64
UserID pgtype.UUID
Since pgtype.Timestamptz
AsOf pgtype.Timestamptz
}
type GetAssessmentRootQuotaAvailabilityRow struct {
AttemptCount int64
AvailableAt pgtype.Timestamptz
}
// Counts eligible root attempts in a policy window and computes the instant
// at which one additional root slot opens. The microsecond adjustment matches
// the creation predicate created_at >= since at PostgreSQL timestamp precision.
func (q *Queries) GetAssessmentRootQuotaAvailability(ctx context.Context, arg GetAssessmentRootQuotaAvailabilityParams) (GetAssessmentRootQuotaAvailabilityRow, error) {
row := q.db.QueryRow(ctx, getAssessmentRootQuotaAvailability,
arg.MaxAttempts,
arg.WindowSeconds,
arg.UserID,
arg.Since,
arg.AsOf,
)
var i GetAssessmentRootQuotaAvailabilityRow
err := row.Scan(&i.AttemptCount, &i.AvailableAt)
return i, err
}
const listAssessmentAvailabilityRootSummaries = `-- name: ListAssessmentAvailabilityRootSummaries :many
SELECT
root.target_grade AS root_target_grade,
root.created_at AS root_created_at,
root.updated_at AS root_updated_at,
root.expires_at AS root_expires_at,
root.state AS root_state,
root.outcome AS root_outcome,
root.chain_deadline AS root_chain_deadline,
latest.target_grade AS latest_target_grade,
latest.updated_at AS latest_updated_at,
latest.expires_at AS latest_expires_at,
latest.state AS latest_state,
latest.outcome AS latest_outcome,
latest.chain_deadline AS latest_chain_deadline,
COALESCE(latest_result.result_snapshot->>'not_determined_reason', '')::text AS latest_platform_error
FROM assessment_attempts AS root
JOIN LATERAL (
SELECT attempt.id, attempt.user_id, attempt.kind, attempt.mode, attempt.state, attempt.outcome, attempt.bank_category, attempt.specialization, attempt.target_grade, attempt.task_language, attempt.root_attempt_id, attempt.product_policy_version_id, attempt.product_policy_version, attempt.grading_policy_version_id, attempt.opening_id, attempt.opening_manifest_sha256, attempt.training_binding_id, attempt.training_manifest_sha256, attempt.bank_version, attempt.algorithm_version, attempt.created_at, attempt.updated_at, attempt.expires_at, attempt.chain_deadline, attempt.idle_timeout_seconds, attempt.max_sessions, attempt.sessions_used, attempt.session_started_at, attempt.last_activity_at, attempt.version, attempt.ended_at
FROM assessment_attempts AS attempt
WHERE attempt.user_id = root.user_id
AND attempt.root_attempt_id = root.id
AND attempt.kind IN ('root', 'corrective')
ORDER BY attempt.created_at DESC, attempt.id DESC
LIMIT 1
) AS latest ON true
LEFT JOIN assessment_attempt_results AS root_result
ON root_result.attempt_id = root.id AND root_result.user_id = root.user_id
LEFT JOIN assessment_attempt_results AS latest_result
ON latest_result.attempt_id = latest.id AND latest_result.user_id = latest.user_id
WHERE root.user_id = $1
AND root.specialization = $2
AND root.kind = 'root'
AND root.created_at >= $3::timestamptz
AND root.state <> 'insufficient_bank'
AND COALESCE(root_result.result_snapshot->>'not_determined_reason', '')
NOT IN ('insufficient_bank', 'sandbox_unavailable')
ORDER BY root.created_at DESC, root.id DESC
`
type ListAssessmentAvailabilityRootSummariesParams struct {
UserID pgtype.UUID
Specialization pgtype.Text
Since pgtype.Timestamptz
}
type ListAssessmentAvailabilityRootSummariesRow struct {
RootTargetGrade pgtype.Text
RootCreatedAt pgtype.Timestamptz
RootUpdatedAt pgtype.Timestamptz
RootExpiresAt pgtype.Timestamptz
RootState string
RootOutcome pgtype.Text
RootChainDeadline pgtype.Timestamptz
LatestTargetGrade pgtype.Text
LatestUpdatedAt pgtype.Timestamptz
LatestExpiresAt pgtype.Timestamptz
LatestState string
LatestOutcome pgtype.Text
LatestChainDeadline pgtype.Timestamptz
LatestPlatformError string
}
// Reads roots within the policy horizon and the last header in each correction
// chain. It deliberately omits frozen items, answers, and row locks.
func (q *Queries) ListAssessmentAvailabilityRootSummaries(ctx context.Context, arg ListAssessmentAvailabilityRootSummariesParams) ([]ListAssessmentAvailabilityRootSummariesRow, error) {
rows, err := q.db.Query(ctx, listAssessmentAvailabilityRootSummaries, arg.UserID, arg.Specialization, arg.Since)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListAssessmentAvailabilityRootSummariesRow
for rows.Next() {
var i ListAssessmentAvailabilityRootSummariesRow
if err := rows.Scan(
&i.RootTargetGrade,
&i.RootCreatedAt,
&i.RootUpdatedAt,
&i.RootExpiresAt,
&i.RootState,
&i.RootOutcome,
&i.RootChainDeadline,
&i.LatestTargetGrade,
&i.LatestUpdatedAt,
&i.LatestExpiresAt,
&i.LatestState,
&i.LatestOutcome,
&i.LatestChainDeadline,
&i.LatestPlatformError,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAssessmentDisclosedFamilyKeys = `-- name: ListAssessmentDisclosedFamilyKeys :many
WITH progress AS (
SELECT
attempt.id AS attempt_id,
attempt.created_at,
COALESCE(max(item.ordinal) FILTER (WHERE item.answered_at IS NOT NULL), 0) + 1 AS last_disclosed_ordinal
FROM assessment_attempts AS attempt
JOIN assessment_attempt_items AS item ON item.attempt_id = attempt.id
WHERE attempt.user_id = $2
AND attempt.kind IN ('root', 'corrective')
AND attempt.expires_at > $1::timestamptz
GROUP BY attempt.id
), disclosed AS (
SELECT
item.family_key,
CASE
WHEN item.ordinal = 1 THEN progress.created_at
ELSE previous.answered_at
END AS disclosed_at
FROM progress
JOIN assessment_attempt_items AS item ON item.attempt_id = progress.attempt_id
LEFT JOIN assessment_attempt_items AS previous
ON previous.attempt_id = item.attempt_id AND previous.ordinal = item.ordinal - 1
WHERE item.ordinal <= progress.last_disclosed_ordinal
)
SELECT DISTINCT disclosed.family_key
FROM disclosed
WHERE disclosed.disclosed_at > $1::timestamptz
ORDER BY disclosed.family_key
`
type ListAssessmentDisclosedFamilyKeysParams struct {
Since pgtype.Timestamptz
UserID pgtype.UUID
}
// Counts family instances disclosed after the non-repeat boundary. The first
// item is disclosed when the attempt is created; each later item is disclosed
// when the preceding answer is accepted. This per-item timestamp prevents a
// long-running attempt from making later items appear older than they are.
// Counting the first unanswered item after expiry is conservative when the
// final response was lost, while frozen future items remain excluded.
func (q *Queries) ListAssessmentDisclosedFamilyKeys(ctx context.Context, arg ListAssessmentDisclosedFamilyKeysParams) ([]string, error) {
rows, err := q.db.Query(ctx, listAssessmentDisclosedFamilyKeys, arg.Since, arg.UserID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []string
for rows.Next() {
var family_key string
if err := rows.Scan(&family_key); err != nil {
return nil, err
}
items = append(items, family_key)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listCurrentAssessmentAvailabilitySelections = `-- name: ListCurrentAssessmentAvailabilitySelections :many
WITH current_policy AS (
SELECT id, version
FROM policy_versions
WHERE policy_key = 'product' AND effective_at <= $1::timestamptz
ORDER BY version DESC
LIMIT 1
), current_openings AS (
SELECT DISTINCT ON (category)
id,
category,
policy_version_id,
required_families,
opened_at
FROM assessment_category_openings
ORDER BY category, opened_at DESC, id DESC
)
SELECT
opening.id AS opening_id,
opening.category,
opening.policy_version_id,
opening.required_families,
COALESCE((
SELECT count(DISTINCT family.family_key)::integer
FROM assessment_families AS family
WHERE family.category = opening.category AND family.lifecycle = 'published'
), 0)::integer AS published_count,
policy.id AS effective_policy_id,
policy.version AS effective_policy_version,
binding.specialization,
binding.grade,
binding.task_languages,
binding.published_manifest_sha256,
COALESCE((
SELECT jsonb_agg(
jsonb_build_object(
'family_key', family.family_key,
'version', family.version,
'content_sha256', encode(family.content_sha256, 'hex')
) ORDER BY family.family_key, family.version
)
FROM assessment_families AS family
WHERE family.category = opening.category AND family.lifecycle = 'published'
), '[]'::jsonb)::text AS published_manifest
FROM current_openings AS opening
JOIN assessment_category_catalog_bindings AS binding
ON binding.opening_id = opening.id
LEFT JOIN current_policy AS policy ON true
ORDER BY binding.specialization, binding.grade, binding.task_languages, opening.category
`
type ListCurrentAssessmentAvailabilitySelectionsRow struct {
OpeningID pgtype.UUID
Category string
PolicyVersionID pgtype.UUID
RequiredFamilies int32
PublishedCount int32
EffectivePolicyID pgtype.UUID
EffectivePolicyVersion pgtype.Int4
Specialization string
Grade string
TaskLanguages []string
PublishedManifestSha256 []byte
PublishedManifest string
}
// Returns current reviewed grade/language bindings and the live published
// family manifest at one caller-supplied database time. The adapter verifies
// the pinned manifest hash before exposing only family keys.
func (q *Queries) ListCurrentAssessmentAvailabilitySelections(ctx context.Context, asOf pgtype.Timestamptz) ([]ListCurrentAssessmentAvailabilitySelectionsRow, error) {
rows, err := q.db.Query(ctx, listCurrentAssessmentAvailabilitySelections, asOf)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListCurrentAssessmentAvailabilitySelectionsRow
for rows.Next() {
var i ListCurrentAssessmentAvailabilitySelectionsRow
if err := rows.Scan(
&i.OpeningID,
&i.Category,
&i.PolicyVersionID,
&i.RequiredFamilies,
&i.PublishedCount,
&i.EffectivePolicyID,
&i.EffectivePolicyVersion,
&i.Specialization,
&i.Grade,
&i.TaskLanguages,
&i.PublishedManifestSha256,
&i.PublishedManifest,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -0,0 +1,201 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: assessment_signals.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const countAssessmentSignalEvents = `-- name: CountAssessmentSignalEvents :one
SELECT count(*)::bigint AS event_count
FROM assessment_signal_events
WHERE attempt_id = $1
`
// Count events only for the already owner-locked attempt.
func (q *Queries) CountAssessmentSignalEvents(ctx context.Context, attemptID pgtype.UUID) (int64, error) {
row := q.db.QueryRow(ctx, countAssessmentSignalEvents, attemptID)
var event_count int64
err := row.Scan(&event_count)
return event_count, err
}
const countRecentAssessmentSignalOutcomes = `-- name: CountRecentAssessmentSignalOutcomes :one
SELECT
count(*)::bigint AS outcome_count,
COALESCE(min(received_at), $1::timestamptz) AS oldest_at
FROM assessment_signal_idempotency_outcomes
WHERE
attempt_id = $2
AND received_at > $1
`
type CountRecentAssessmentSignalOutcomesParams struct {
Since pgtype.Timestamptz
AttemptID pgtype.UUID
}
type CountRecentAssessmentSignalOutcomesRow struct {
OutcomeCount int64
OldestAt interface{}
}
// New outcomes share the generic idempotency row and are counted for the
// attempt's rolling receipt window. Replays bypass this query in the usecase.
func (q *Queries) CountRecentAssessmentSignalOutcomes(ctx context.Context, arg CountRecentAssessmentSignalOutcomesParams) (CountRecentAssessmentSignalOutcomesRow, error) {
row := q.db.QueryRow(ctx, countRecentAssessmentSignalOutcomes, arg.Since, arg.AttemptID)
var i CountRecentAssessmentSignalOutcomesRow
err := row.Scan(&i.OutcomeCount, &i.OldestAt)
return i, err
}
const deleteExpiredAssessmentSignalOutcome = `-- name: DeleteExpiredAssessmentSignalOutcome :exec
DELETE FROM assessment_signal_idempotency_outcomes
WHERE scope_hash = $1
`
// The generic reservation has already established that a previous outcome is
// expired before this child is removed and replaced in the same transaction.
func (q *Queries) DeleteExpiredAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) error {
_, err := q.db.Exec(ctx, deleteExpiredAssessmentSignalOutcome, scopeHash)
return err
}
const getAssessmentSignalOutcome = `-- name: GetAssessmentSignalOutcome :one
SELECT status, accepted_events, received_at
FROM assessment_signal_idempotency_outcomes
WHERE scope_hash = $1
`
type GetAssessmentSignalOutcomeRow struct {
Status string
AcceptedEvents int32
ReceivedAt pgtype.Timestamptz
}
// Read only the receipt associated with the reserved idempotency scope.
func (q *Queries) GetAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentSignalOutcomeRow, error) {
row := q.db.QueryRow(ctx, getAssessmentSignalOutcome, scopeHash)
var i GetAssessmentSignalOutcomeRow
err := row.Scan(&i.Status, &i.AcceptedEvents, &i.ReceivedAt)
return i, err
}
const insertAssessmentSignalBatch = `-- name: InsertAssessmentSignalBatch :exec
INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count)
VALUES (
$1,
$2,
$3,
$4
)
`
type InsertAssessmentSignalBatchParams struct {
ID pgtype.UUID
AttemptID pgtype.UUID
ReceivedAt pgtype.Timestamptz
EventCount int32
}
// The attempt row is already locked by the caller. Store a parent before its
// bounded child events, in the same transaction as the immutable receipt.
func (q *Queries) InsertAssessmentSignalBatch(ctx context.Context, arg InsertAssessmentSignalBatchParams) error {
_, err := q.db.Exec(ctx, insertAssessmentSignalBatch,
arg.ID,
arg.AttemptID,
arg.ReceivedAt,
arg.EventCount,
)
return err
}
const insertAssessmentSignalEvent = `-- name: InsertAssessmentSignalEvent :exec
INSERT INTO assessment_signal_events (
batch_id,
attempt_id,
ordinal,
item_instance_id,
kind,
occurred_at,
duration_ms,
size_bytes
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7::integer,
$8::integer
)
`
type InsertAssessmentSignalEventParams struct {
BatchID pgtype.UUID
AttemptID pgtype.UUID
Ordinal int32
ItemInstanceID pgtype.UUID
Kind string
OccurredAt pgtype.Timestamptz
DurationMs pgtype.Int4
SizeBytes pgtype.Int4
}
// Each inserted event is checked by the database guard against attempt state
// and the aggregate capacity as a second line of defense.
func (q *Queries) InsertAssessmentSignalEvent(ctx context.Context, arg InsertAssessmentSignalEventParams) error {
_, err := q.db.Exec(ctx, insertAssessmentSignalEvent,
arg.BatchID,
arg.AttemptID,
arg.Ordinal,
arg.ItemInstanceID,
arg.Kind,
arg.OccurredAt,
arg.DurationMs,
arg.SizeBytes,
)
return err
}
const insertAssessmentSignalOutcome = `-- name: InsertAssessmentSignalOutcome :exec
INSERT INTO assessment_signal_idempotency_outcomes (
scope_hash,
attempt_id,
status,
accepted_events,
received_at
) VALUES (
$1,
$2,
$3,
$4,
$5
)
`
type InsertAssessmentSignalOutcomeParams struct {
ScopeHash []byte
AttemptID pgtype.UUID
Status string
AcceptedEvents int32
ReceivedAt pgtype.Timestamptz
}
// Save exactly one immutable response receipt for each live idempotency scope.
func (q *Queries) InsertAssessmentSignalOutcome(ctx context.Context, arg InsertAssessmentSignalOutcomeParams) error {
_, err := q.db.Exec(ctx, insertAssessmentSignalOutcome,
arg.ScopeHash,
arg.AttemptID,
arg.Status,
arg.AcceptedEvents,
arg.ReceivedAt,
)
return err
}
@@ -871,6 +871,79 @@ func (q *Queries) ListCurrentContactConsentRecords(ctx context.Context, arg List
return items, nil
}
const lockCurrentConsentForUse = `-- name: LockCurrentConsentForUse :one
SELECT
id,
subject_id,
purpose,
text_version,
text_hash,
source,
registration_version,
organization_id,
organization_name,
field_set,
invitation_id,
invitation_terms_version,
granted_at,
revoked_at,
revocation_source,
'active'::text AS state
FROM consent_records
WHERE
subject_id = $1
AND purpose = 'c3'
AND revoked_at IS NULL
ORDER BY granted_at DESC, id DESC
LIMIT 1
FOR SHARE
`
type LockCurrentConsentForUseRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
RegistrationVersion pgtype.Int8
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
InvitationID pgtype.UUID
InvitationTermsVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
State string
}
// Keeps the current C3 grant stable through a real assessment transaction.
// Revocation updates this row and therefore waits until the caller commits.
func (q *Queries) LockCurrentConsentForUse(ctx context.Context, subjectID pgtype.UUID) (LockCurrentConsentForUseRow, error) {
row := q.db.QueryRow(ctx, lockCurrentConsentForUse, subjectID)
var i LockCurrentConsentForUseRow
err := row.Scan(
&i.ID,
&i.SubjectID,
&i.Purpose,
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.RegistrationVersion,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
&i.InvitationID,
&i.InvitationTermsVersion,
&i.GrantedAt,
&i.RevokedAt,
&i.RevocationSource,
&i.State,
)
return i, err
}
const lockRegistrationConsentRecord = `-- name: LockRegistrationConsentRecord :one
SELECT
id,
@@ -16,6 +16,89 @@ type AccountDeletionRequest struct {
CompletedAt pgtype.Timestamptz
}
type AssessmentAttempt struct {
ID pgtype.UUID
UserID pgtype.UUID
Kind string
Mode string
State string
Outcome pgtype.Text
BankCategory string
Specialization pgtype.Text
TargetGrade pgtype.Text
TaskLanguage pgtype.Text
RootAttemptID pgtype.UUID
ProductPolicyVersionID pgtype.UUID
ProductPolicyVersion int32
GradingPolicyVersionID pgtype.UUID
OpeningID pgtype.UUID
OpeningManifestSha256 []byte
TrainingBindingID pgtype.UUID
TrainingManifestSha256 []byte
BankVersion string
AlgorithmVersion string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
ChainDeadline pgtype.Timestamptz
IdleTimeoutSeconds int32
MaxSessions int32
SessionsUsed int32
SessionStartedAt pgtype.Timestamptz
LastActivityAt pgtype.Timestamptz
Version int64
EndedAt pgtype.Timestamptz
}
type AssessmentAttemptIdempotencyOutcome struct {
ScopeHash []byte
Operation string
StatusCode int16
ProblemCode pgtype.Text
ResponseSnapshot []byte
ResponseSchemaVersion int16
CreatedAt pgtype.Timestamptz
PendingItemIds []pgtype.UUID
}
type AssessmentAttemptItem struct {
ID pgtype.UUID
AttemptID pgtype.UUID
Ordinal int32
FamilyID pgtype.UUID
FamilyKey string
FamilyVersion int32
FamilyContentSha256 []byte
Variant []byte
Answer []byte
AnsweredAt pgtype.Timestamptz
}
type AssessmentAttemptResult struct {
AttemptID pgtype.UUID
UserID pgtype.UUID
ResultSnapshot []byte
SchemaVersion int16
Kind string
Mode string
Outcome string
ProductPolicyVersionID pgtype.UUID
ProductPolicyVersion int32
GradingPolicyVersionID pgtype.UUID
OpeningID pgtype.UUID
OpeningManifestSha256 []byte
TrainingBindingID pgtype.UUID
TrainingManifestSha256 []byte
BankVersion string
AlgorithmVersion string
RationaleRule string
PassMarkBasisPoints pgtype.Int4
ScoredItems pgtype.Int2
RawScore pgtype.Int2
PassPoints pgtype.Int2
DecidedAt pgtype.Timestamptz
}
type AssessmentCategoryCatalogBinding struct {
OpeningID pgtype.UUID
Specialization string
@@ -60,6 +143,62 @@ type AssessmentFamily struct {
RetiredBy pgtype.Text
}
type AssessmentSignalBatch struct {
ID pgtype.UUID
AttemptID pgtype.UUID
ReceivedAt pgtype.Timestamptz
EventCount int32
}
type AssessmentSignalEvent struct {
BatchID pgtype.UUID
AttemptID pgtype.UUID
Ordinal int32
ItemInstanceID pgtype.UUID
Kind string
OccurredAt pgtype.Timestamptz
DurationMs pgtype.Int4
SizeBytes pgtype.Int4
}
type AssessmentSignalIdempotencyOutcome struct {
ScopeHash []byte
AttemptID pgtype.UUID
Status string
AcceptedEvents int32
ReceivedAt pgtype.Timestamptz
}
type AssessmentTrainingBankBinding struct {
ID pgtype.UUID
Category string
ProductPolicyVersionID pgtype.UUID
ItemCount int32
ManifestSha256 []byte
FamilyManifest []byte
ReviewedBy string
CreatedAt pgtype.Timestamptz
}
type AssessmentTrainingBankBindingFamily struct {
BindingID pgtype.UUID
Ordinal int32
FamilyID pgtype.UUID
FamilyKey string
FamilyVersion int32
ContentSha256 []byte
}
type CandidateCardAccessEvent struct {
ID pgtype.UUID
CandidateID pgtype.UUID
OrganizationID pgtype.UUID
ActorID pgtype.UUID
Kind string
FieldCodes []string
OccurredAt pgtype.Timestamptz
}
type CandidateEffectivePublication struct {
UserID pgtype.UUID
Fields []string
@@ -405,6 +544,11 @@ type OrganizationNeed struct {
UpdatedAt pgtype.Timestamptz
}
type OrganizationNeedCreationResult struct {
ScopeHash []byte
Snapshot []byte
}
type OrganizationNeedVersion struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
@@ -472,6 +616,57 @@ type Session struct {
RevokedAt pgtype.Timestamptz
}
type SupportCase struct {
ID pgtype.UUID
CaseNumber string
OwnerID pgtype.UUID
CaseType string
Status string
Description string
ObjectType pgtype.Text
ObjectID pgtype.UUID
AssessmentSpecialization pgtype.Text
AssessmentGrade pgtype.Text
ComplaintReason pgtype.Text
RubricVersion pgtype.Int4
RubricOpeningID pgtype.UUID
RubricPolicyVersionID pgtype.UUID
TargetBusinessDays int32
TargetDueAt pgtype.Timestamptz
TargetAnsweredAt pgtype.Timestamptz
TargetPolicyVersion int32
TargetCalendarVersion int32
DecisionOutcome pgtype.Text
DecisionReason pgtype.Text
DecisionAt pgtype.Timestamptz
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type SupportCaseCreateOutcome struct {
ScopeHash []byte
OutcomeKind string
CaseSnapshot []byte
TargetWasLate pgtype.Bool
CreatedAt pgtype.Timestamptz
}
type SupportCaseEvent struct {
CaseID pgtype.UUID
Sequence int32
EventKind string
ActorKind string
OccurredAt pgtype.Timestamptz
Status pgtype.Text
Message pgtype.Text
}
type SupportCaseRequestEvent struct {
ID int64
OwnerID pgtype.UUID
RequestedAt pgtype.Timestamptz
}
type User struct {
ID pgtype.UUID
Email string
@@ -80,6 +80,21 @@ func (q *Queries) AdvanceOrganizationNeed(ctx context.Context, arg AdvanceOrgani
return snapshot, err
}
const getOrganizationNeedCreationResult = `-- name: GetOrganizationNeedCreationResult :one
SELECT snapshot::text AS snapshot
FROM organization_need_creation_results
WHERE scope_hash = $1
`
// Read only the immutable original response. The current need may have moved
// to a later version since this result was created.
func (q *Queries) GetOrganizationNeedCreationResult(ctx context.Context, scopeHash []byte) (string, error) {
row := q.db.QueryRow(ctx, getOrganizationNeedCreationResult, scopeHash)
var snapshot string
err := row.Scan(&snapshot)
return snapshot, err
}
const insertOrganizationNeed = `-- name: InsertOrganizationNeed :exec
INSERT INTO organization_needs (
id,
@@ -152,6 +167,85 @@ func (q *Queries) InsertOrganizationNeedVersion(ctx context.Context, arg InsertO
return err
}
const listOrganizationNeeds = `-- name: ListOrganizationNeeds :many
SELECT
need.organization_id,
need.id AS need_id,
need.current_version,
need.requirements_version,
need.created_at,
need.updated_at,
version.snapshot::text AS snapshot
FROM organization_needs AS need
INNER JOIN organization_need_versions AS version
ON version.organization_id = need.organization_id
AND version.need_id = need.id
AND version.version = need.current_version
WHERE
need.organization_id = $1
AND (
$2::timestamptz IS NULL
OR (need.created_at, need.id) < (
$2::timestamptz,
$3::uuid
)
)
ORDER BY need.created_at DESC, need.id DESC
LIMIT $4
`
type ListOrganizationNeedsParams struct {
OrganizationID pgtype.UUID
AfterCreatedAt pgtype.Timestamptz
AfterNeedID pgtype.UUID
RowLimit int32
}
type ListOrganizationNeedsRow struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
CurrentVersion int64
RequirementsVersion int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Snapshot string
}
// Read one bounded newest-first page of current needs. Both the organization
// scope and the tuple cursor are applied before the limit.
func (q *Queries) ListOrganizationNeeds(ctx context.Context, arg ListOrganizationNeedsParams) ([]ListOrganizationNeedsRow, error) {
rows, err := q.db.Query(ctx, listOrganizationNeeds,
arg.OrganizationID,
arg.AfterCreatedAt,
arg.AfterNeedID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListOrganizationNeedsRow
for rows.Next() {
var i ListOrganizationNeedsRow
if err := rows.Scan(
&i.OrganizationID,
&i.NeedID,
&i.CurrentVersion,
&i.RequirementsVersion,
&i.CreatedAt,
&i.UpdatedAt,
&i.Snapshot,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const readCurrentOrganizationNeed = `-- name: ReadCurrentOrganizationNeed :one
SELECT
need.organization_id,
@@ -224,3 +318,23 @@ func (q *Queries) ReadOrganizationNeedVersion(ctx context.Context, arg ReadOrgan
err := row.Scan(&snapshot)
return snapshot, err
}
const saveOrganizationNeedCreationResult = `-- name: SaveOrganizationNeedCreationResult :exec
INSERT INTO organization_need_creation_results (scope_hash, snapshot)
VALUES ($1, $2::jsonb)
ON CONFLICT (scope_hash) DO UPDATE
SET snapshot = excluded.snapshot
`
type SaveOrganizationNeedCreationResultParams struct {
ScopeHash []byte
Snapshot []byte
}
// The generic idempotency scope serializes retries. Replacing the child row
// is safe only in the transaction that reserves an expired scope for a new
// create; live retries read and return the stored response without writing.
func (q *Queries) SaveOrganizationNeedCreationResult(ctx context.Context, arg SaveOrganizationNeedCreationResultParams) error {
_, err := q.db.Exec(ctx, saveOrganizationNeedCreationResult, arg.ScopeHash, arg.Snapshot)
return err
}
@@ -405,6 +405,63 @@ func (q *Queries) ListOrganizationsForUser(ctx context.Context, arg ListOrganiza
return items, nil
}
const lockActiveMembership = `-- name: LockActiveMembership :one
WITH locked_organization AS MATERIALIZED (
SELECT organizations.id
FROM organizations
WHERE organizations.id = $2
FOR SHARE
)
SELECT
membership.id AS membership_id,
membership.organization_id,
membership.user_id,
membership.role,
membership.state,
membership.created_at,
membership.updated_at
FROM memberships AS membership
INNER JOIN locked_organization ON locked_organization.id = membership.organization_id
WHERE
membership.user_id = $1
AND membership.state = 'active'
FOR SHARE OF membership
`
type LockActiveMembershipParams struct {
UserID pgtype.UUID
OrganizationID pgtype.UUID
}
type LockActiveMembershipRow struct {
MembershipID pgtype.UUID
OrganizationID pgtype.UUID
UserID pgtype.UUID
Role string
State string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Locks the organization first and then the active membership, using the
// same order as organization profile writes. A company operation keeps both
// share locks until its transaction commits, so a concurrent revocation
// cannot authorize a write after it has committed.
func (q *Queries) LockActiveMembership(ctx context.Context, arg LockActiveMembershipParams) (LockActiveMembershipRow, error) {
row := q.db.QueryRow(ctx, lockActiveMembership, arg.UserID, arg.OrganizationID)
var i LockActiveMembershipRow
err := row.Scan(
&i.MembershipID,
&i.OrganizationID,
&i.UserID,
&i.Role,
&i.State,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const saveOrganizationCreationResult = `-- name: SaveOrganizationCreationResult :exec
INSERT INTO organization_creation_results (scope_hash, snapshot)
VALUES ($1, $2)
@@ -11,6 +11,44 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const candidateCanSeeOrganization = `-- name: CandidateCanSeeOrganization :one
SELECT organizations.id, organizations.name
FROM organizations
WHERE organizations.id = $1
AND (
EXISTS (
SELECT 1 FROM candidate_card_access_events
WHERE candidate_card_access_events.candidate_id = $2
AND candidate_card_access_events.organization_id = organizations.id
)
OR EXISTS (
SELECT 1 FROM candidate_hidden_organizations
WHERE candidate_hidden_organizations.user_id = $2
AND candidate_hidden_organizations.organization_id = organizations.id
)
)
`
type CandidateCanSeeOrganizationParams struct {
OrganizationID pgtype.UUID
UserID pgtype.UUID
}
type CandidateCanSeeOrganizationRow struct {
ID pgtype.UUID
Name string
}
// The candidate may name an organization in privacy settings only if that
// organization already appears in their own access history or is already
// hidden. Unknown and unseen organizations produce the same no-row result.
func (q *Queries) CandidateCanSeeOrganization(ctx context.Context, arg CandidateCanSeeOrganizationParams) (CandidateCanSeeOrganizationRow, error) {
row := q.db.QueryRow(ctx, candidateCanSeeOrganization, arg.OrganizationID, arg.UserID)
var i CandidateCanSeeOrganizationRow
err := row.Scan(&i.ID, &i.Name)
return i, err
}
const countCandidateHiddenOrganizations = `-- name: CountCandidateHiddenOrganizations :one
SELECT count(*) AS total
FROM candidate_hidden_organizations
@@ -79,6 +117,52 @@ func (q *Queries) GetCandidateHiddenOrganization(ctx context.Context, arg GetCan
return i, err
}
const insertCandidateCardAccessEvent = `-- name: InsertCandidateCardAccessEvent :exec
INSERT INTO candidate_card_access_events (
id,
candidate_id,
organization_id,
actor_id,
kind,
field_codes,
occurred_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7
)
`
type InsertCandidateCardAccessEventParams struct {
ID pgtype.UUID
CandidateID pgtype.UUID
OrganizationID pgtype.UUID
ActorID pgtype.UUID
Kind string
FieldCodes []string
OccurredAt pgtype.Timestamptz
}
// Records a successfully authorized view after visibility and quota checks.
// The audit contains only identities, the access kind, published field codes,
// and time; it never receives the projection content, ranking, or filters.
func (q *Queries) InsertCandidateCardAccessEvent(ctx context.Context, arg InsertCandidateCardAccessEventParams) error {
_, err := q.db.Exec(ctx, insertCandidateCardAccessEvent,
arg.ID,
arg.CandidateID,
arg.OrganizationID,
arg.ActorID,
arg.Kind,
arg.FieldCodes,
arg.OccurredAt,
)
return err
}
const insertCandidateHiddenOrganization = `-- name: InsertCandidateHiddenOrganization :one
INSERT INTO candidate_hidden_organizations (
user_id,
@@ -272,6 +356,88 @@ func (q *Queries) InsertCandidateSearchStatus(ctx context.Context, arg InsertCan
return i, err
}
const listCandidateCardAccessEvents = `-- name: ListCandidateCardAccessEvents :many
SELECT
candidate_card_access_events.id,
candidate_card_access_events.candidate_id,
candidate_card_access_events.organization_id,
candidate_card_access_events.actor_id,
candidate_card_access_events.kind,
candidate_card_access_events.field_codes,
candidate_card_access_events.occurred_at,
organizations.name AS organization_name
FROM candidate_card_access_events
INNER JOIN organizations
ON organizations.id = candidate_card_access_events.organization_id
WHERE
candidate_card_access_events.candidate_id = $1
AND (
$2::timestamptz IS NULL
OR (candidate_card_access_events.occurred_at, candidate_card_access_events.id) < (
$2::timestamptz,
$3::uuid
)
)
ORDER BY candidate_card_access_events.occurred_at DESC, candidate_card_access_events.id DESC
LIMIT $4
`
type ListCandidateCardAccessEventsParams struct {
CandidateID pgtype.UUID
AfterOccurredAt pgtype.Timestamptz
AfterID pgtype.UUID
RowLimit int32
}
type ListCandidateCardAccessEventsRow struct {
ID pgtype.UUID
CandidateID pgtype.UUID
OrganizationID pgtype.UUID
ActorID pgtype.UUID
Kind string
FieldCodes []string
OccurredAt pgtype.Timestamptz
OrganizationName string
}
// 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
// access relation, which is already visible to the candidate.
func (q *Queries) ListCandidateCardAccessEvents(ctx context.Context, arg ListCandidateCardAccessEventsParams) ([]ListCandidateCardAccessEventsRow, error) {
rows, err := q.db.Query(ctx, listCandidateCardAccessEvents,
arg.CandidateID,
arg.AfterOccurredAt,
arg.AfterID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListCandidateCardAccessEventsRow
for rows.Next() {
var i ListCandidateCardAccessEventsRow
if err := rows.Scan(
&i.ID,
&i.CandidateID,
&i.OrganizationID,
&i.ActorID,
&i.Kind,
&i.FieldCodes,
&i.OccurredAt,
&i.OrganizationName,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listCandidateHiddenOrganizations = `-- name: ListCandidateHiddenOrganizations :many
SELECT
candidate_hidden_organizations.organization_id,
@@ -480,8 +646,88 @@ func (q *Queries) LockCurrentC2Record(ctx context.Context, subjectID pgtype.UUID
return id, err
}
const readCandidatePublication = `-- name: ReadCandidatePublication :one
const readCandidatePrivacySettings = `-- name: ReadCandidatePrivacySettings :one
SELECT
users.id AS user_id,
candidate_publications.state AS publication_state,
candidate_publications.fields AS publication_fields,
candidate_publications.consent_record_id AS publication_consent_record_id,
candidate_publications.published_at AS publication_published_at,
candidate_publications.closed_at AS publication_closed_at,
candidate_publications.version AS publication_version,
consent_records.revoked_at AS publication_consent_revoked_at,
candidate_search_statuses.status AS search_status,
candidate_search_statuses.confirmed_at AS search_confirmed_at,
candidate_search_statuses.lapses_at AS search_lapses_at,
candidate_search_statuses.policy_version_id AS search_policy_version_id,
candidate_search_statuses.version AS search_version,
(
SELECT count(*)
FROM candidate_hidden_organizations
WHERE candidate_hidden_organizations.user_id = users.id
) AS hidden_count
FROM users
LEFT JOIN candidate_publications
ON candidate_publications.user_id = users.id
LEFT JOIN consent_records
ON consent_records.id = candidate_publications.consent_record_id
LEFT JOIN candidate_search_statuses
ON candidate_search_statuses.user_id = users.id
WHERE users.id = $1
`
type ReadCandidatePrivacySettingsRow struct {
UserID pgtype.UUID
PublicationState pgtype.Text
PublicationFields []string
PublicationConsentRecordID pgtype.UUID
PublicationPublishedAt pgtype.Timestamptz
PublicationClosedAt pgtype.Timestamptz
PublicationVersion pgtype.Int8
PublicationConsentRevokedAt pgtype.Timestamptz
SearchStatus pgtype.Text
SearchConfirmedAt pgtype.Timestamptz
SearchLapsesAt pgtype.Timestamptz
SearchPolicyVersionID pgtype.UUID
SearchVersion pgtype.Int8
HiddenCount int64
}
// Queries of the candidate visibility settings: the publication of
// the card, the search status, the hidden organizations, and the history of
// these settings. Every statement is scoped by the candidate's user_id, and
// no statement selects another account's row. No statement reads or writes a
// profile value, a name, or a contact. A candidate with no row is closed, not
// looking, and hides nobody; no statement creates a row except an explicit
// act of the candidate.
// Reads the candidate-owned settings and hidden count from one statement
// snapshot. Missing setting rows are restored as the closed/not-looking
// defaults in the adapter. The account row scopes the result but does not
// expose private profile values.
func (q *Queries) ReadCandidatePrivacySettings(ctx context.Context, userID pgtype.UUID) (ReadCandidatePrivacySettingsRow, error) {
row := q.db.QueryRow(ctx, readCandidatePrivacySettings, userID)
var i ReadCandidatePrivacySettingsRow
err := row.Scan(
&i.UserID,
&i.PublicationState,
&i.PublicationFields,
&i.PublicationConsentRecordID,
&i.PublicationPublishedAt,
&i.PublicationClosedAt,
&i.PublicationVersion,
&i.PublicationConsentRevokedAt,
&i.SearchStatus,
&i.SearchConfirmedAt,
&i.SearchLapsesAt,
&i.SearchPolicyVersionID,
&i.SearchVersion,
&i.HiddenCount,
)
return i, err
}
const readCandidatePublication = `-- name: ReadCandidatePublication :one
SELECT
candidate_publications.user_id,
candidate_publications.state,
@@ -512,13 +758,6 @@ type ReadCandidatePublicationRow struct {
ConsentRevokedAt pgtype.Timestamptz
}
// Queries of the candidate visibility settings: the publication of
// the card, the search status, the hidden organizations, and the history of
// these settings. Every statement is scoped by the candidate's user_id, and
// no statement selects another account's row. No statement reads or writes a
// profile value, a name, or a contact. A candidate with no row is closed, not
// looking, and hides nobody; no statement creates a row except an explicit
// act of the candidate.
// Reads the publication with the revocation state of the C2 record behind it
// in one statement, so the stored setting and the ledger come from one
// snapshot. The effective state is computed from them: published only while
@@ -0,0 +1,330 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: privacy_cohort.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const listVisibleCandidateViewSources = `-- name: ListVisibleCandidateViewSources :many
SELECT
effective.user_id,
effective.fields,
claim.kind,
claim.ordinal,
CASE
WHEN claim.kind = 'experience' THEN jsonb_build_object(
'employer_name', NULL::text,
'specialization', claim.value ->> 'specialization',
'started_on', claim.value ->> 'started_on',
'ended_on', claim.value -> 'ended_on',
'summary', NULL::text
)
ELSE claim.value
END AS safe_value,
claim.status,
claim.origin,
claim.trust_level,
claim.extraction_version,
claim.confirmed_at,
COALESCE(questionnaire.work_formats, '{}'::text[]) AS work_formats,
COALESCE(
(
SELECT jsonb_agg(
jsonb_build_object(
'first_index', overlap.first_index,
'second_index', overlap.second_index,
'first_period', jsonb_build_object(
'started_on', overlap.first_started_on,
'ended_on', overlap.first_ended_on
),
'second_period', jsonb_build_object(
'started_on', overlap.second_started_on,
'ended_on', overlap.second_ended_on
)
) ORDER BY overlap.first_index, overlap.second_index
)::text
FROM candidate_profile_overlap_confirmations AS overlap
WHERE overlap.user_id = effective.user_id
),
'[]'::text
) AS parallel_period_acknowledgements
FROM candidate_effective_publications AS effective
LEFT JOIN candidate_profile_claims AS claim
ON claim.user_id = effective.user_id
AND claim.kind IN ('stack', 'role', 'experience')
LEFT JOIN candidate_questionnaires AS questionnaire
ON questionnaire.user_id = effective.user_id
WHERE NOT EXISTS (
SELECT 1
FROM candidate_hidden_organizations AS hidden
WHERE hidden.user_id = effective.user_id
AND hidden.organization_id = $1
)
ORDER BY effective.user_id, claim.kind, claim.ordinal
`
type ListVisibleCandidateViewSourcesRow struct {
UserID pgtype.UUID
Fields []string
Kind pgtype.Text
Ordinal pgtype.Int2
SafeValue interface{}
Status pgtype.Text
Origin pgtype.Text
TrustLevel pgtype.Int2
ExtractionVersion pgtype.Text
ConfirmedAt pgtype.Timestamptz
WorkFormats []string
ParallelPeriodAcknowledgements interface{}
}
// Organization-facing anonymous candidate projection inputs. The calling
// usecase has already authorized the active organization membership. This
// single statement snapshot filters both revoked/unpublished C2 states and
// 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.
func (q *Queries) ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error) {
rows, err := q.db.Query(ctx, listVisibleCandidateViewSources, organizationID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListVisibleCandidateViewSourcesRow
for rows.Next() {
var i ListVisibleCandidateViewSourcesRow
if err := rows.Scan(
&i.UserID,
&i.Fields,
&i.Kind,
&i.Ordinal,
&i.SafeValue,
&i.Status,
&i.Origin,
&i.TrustLevel,
&i.ExtractionVersion,
&i.ConfirmedAt,
&i.WorkFormats,
&i.ParallelPeriodAcknowledgements,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockCandidateAccountForView = `-- name: LockCandidateAccountForView :one
SELECT users.id
FROM users
WHERE users.id = $1
FOR SHARE
`
// Lock the account before an organization checks candidate visibility. The
// hidden-organization insert trigger takes FOR NO KEY UPDATE on this row, so
// a hide either commits before the later visibility recheck or waits for the
// read transaction to finish.
func (q *Queries) LockCandidateAccountForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockCandidateAccountForView, candidateID)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const lockCurrentC2ForView = `-- name: LockCurrentC2ForView :one
SELECT consent_records.id
FROM consent_records
WHERE
consent_records.subject_id = $1
AND consent_records.purpose = 'c2'
AND consent_records.revoked_at IS NULL
ORDER BY consent_records.granted_at DESC, consent_records.id DESC
LIMIT 1
FOR SHARE
`
// Lock the current C2 before locking the publication. C2 revocation updates
// this row before it locks the publication, so preserving this order avoids
// a lock inversion and makes the current consent stable through the read.
func (q *Queries) LockCurrentC2ForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockCurrentC2ForView, candidateID)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const lockPublicationForCandidatePreview = `-- name: LockPublicationForCandidatePreview :one
SELECT candidate_publications.user_id
FROM candidate_publications
INNER JOIN consent_records
ON consent_records.id = candidate_publications.consent_record_id
WHERE
candidate_publications.user_id = $1
AND candidate_publications.state = 'published'
AND consent_records.subject_id = candidate_publications.user_id
AND consent_records.purpose = 'c2'
AND consent_records.revoked_at IS NULL
FOR SHARE OF candidate_publications, consent_records
`
// Lock a candidate's current publication for the private preview. This has
// no organization context and never enters the employer read quota or audit.
func (q *Queries) LockPublicationForCandidatePreview(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockPublicationForCandidatePreview, candidateID)
var user_id pgtype.UUID
err := row.Scan(&user_id)
return user_id, err
}
const lockVisiblePublicationForView = `-- name: LockVisiblePublicationForView :one
SELECT candidate_publications.user_id
FROM candidate_publications
INNER JOIN consent_records
ON consent_records.id = candidate_publications.consent_record_id
WHERE
candidate_publications.user_id = $1
AND candidate_publications.state = 'published'
AND candidate_publications.consent_record_id = $2
AND consent_records.subject_id = candidate_publications.user_id
AND consent_records.purpose = 'c2'
AND consent_records.revoked_at IS NULL
AND NOT EXISTS (
SELECT 1
FROM candidate_hidden_organizations AS hidden
WHERE
hidden.user_id = candidate_publications.user_id
AND hidden.organization_id = $3
)
FOR SHARE OF candidate_publications, consent_records
`
type LockVisiblePublicationForViewParams struct {
CandidateID pgtype.UUID
ConsentRecordID pgtype.UUID
OrganizationID pgtype.UUID
}
// Lock and recheck one candidate's exact current publication only after the
// active C2 row is share-locked. No row includes unpublished, revoked, stale
// publication, and organization-hidden states.
func (q *Queries) LockVisiblePublicationForView(ctx context.Context, arg LockVisiblePublicationForViewParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockVisiblePublicationForView, arg.CandidateID, arg.ConsentRecordID, arg.OrganizationID)
var user_id pgtype.UUID
err := row.Scan(&user_id)
return user_id, err
}
const readCandidateViewSourceForPreview = `-- name: ReadCandidateViewSourceForPreview :many
SELECT
effective.user_id,
effective.fields,
claim.kind,
claim.ordinal,
CASE
WHEN claim.kind = 'experience' THEN jsonb_build_object(
'employer_name', NULL::text,
'specialization', claim.value ->> 'specialization',
'started_on', claim.value ->> 'started_on',
'ended_on', claim.value -> 'ended_on',
'summary', NULL::text
)
ELSE claim.value
END AS safe_value,
claim.status,
claim.origin,
claim.trust_level,
claim.extraction_version,
claim.confirmed_at,
COALESCE(questionnaire.work_formats, '{}'::text[]) AS work_formats,
COALESCE(
(
SELECT jsonb_agg(
jsonb_build_object(
'first_index', overlap.first_index,
'second_index', overlap.second_index,
'first_period', jsonb_build_object(
'started_on', overlap.first_started_on,
'ended_on', overlap.first_ended_on
),
'second_period', jsonb_build_object(
'started_on', overlap.second_started_on,
'ended_on', overlap.second_ended_on
)
) ORDER BY overlap.first_index, overlap.second_index
)::text
FROM candidate_profile_overlap_confirmations AS overlap
WHERE overlap.user_id = effective.user_id
),
'[]'::text
) AS parallel_period_acknowledgements
FROM candidate_effective_publications AS effective
LEFT JOIN candidate_profile_claims AS claim
ON claim.user_id = effective.user_id
AND claim.kind IN ('stack', 'role', 'experience')
LEFT JOIN candidate_questionnaires AS questionnaire
ON questionnaire.user_id = effective.user_id
WHERE effective.user_id = $1
ORDER BY effective.user_id, claim.kind, claim.ordinal
`
type ReadCandidateViewSourceForPreviewRow struct {
UserID pgtype.UUID
Fields []string
Kind pgtype.Text
Ordinal pgtype.Int2
SafeValue interface{}
Status pgtype.Text
Origin pgtype.Text
TrustLevel pgtype.Int2
ExtractionVersion pgtype.Text
ConfirmedAt pgtype.Timestamptz
WorkFormats []string
ParallelPeriodAcknowledgements interface{}
}
// Read the candidate's current private projection inputs after the caller
// locks its active C2 and publication. It selects only fields allowed in the
// anonymous-card projection and is never used for employer visibility.
func (q *Queries) ReadCandidateViewSourceForPreview(ctx context.Context, candidateID pgtype.UUID) ([]ReadCandidateViewSourceForPreviewRow, error) {
rows, err := q.db.Query(ctx, readCandidateViewSourceForPreview, candidateID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ReadCandidateViewSourceForPreviewRow
for rows.Next() {
var i ReadCandidateViewSourceForPreviewRow
if err := rows.Scan(
&i.UserID,
&i.Fields,
&i.Kind,
&i.Ordinal,
&i.SafeValue,
&i.Status,
&i.Origin,
&i.TrustLevel,
&i.ExtractionVersion,
&i.ConfirmedAt,
&i.WorkFormats,
&i.ParallelPeriodAcknowledgements,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -60,6 +60,10 @@ type Querier interface {
// redacts the bodies of a token mail like any other cancellation. now is the
// application clock.
CancelUnreadableDelivery(ctx context.Context, arg CancelUnreadableDeliveryParams) (int64, error)
// The candidate may name an organization in privacy settings only if that
// organization already appears in their own access history or is already
// hidden. Unknown and unseen organizations produce the same no-row result.
CandidateCanSeeOrganization(ctx context.Context, arg CandidateCanSeeOrganizationParams) (CandidateCanSeeOrganizationRow, error)
// Claims the most overdue delivery that the sending worker may send, in one
// statement: a pending, waiting_quota, or scheduled unknown delivery of the service mail kinds
// (the literals match the predicate of deliveries_due_idx, so an idle poll
@@ -118,6 +122,8 @@ type Querier interface {
// returned registration version in the same transaction, rolled back when it
// matches no row.
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, error)
// Count events only for the already owner-locked attempt.
CountAssessmentSignalEvents(ctx context.Context, attemptID pgtype.UUID) (int64, error)
// Counts the hiding records of one candidate for the settings read.
CountCandidateHiddenOrganizations(ctx context.Context, userID pgtype.UUID) (int64, error)
CountCompanyCardViewQuotaWindow(ctx context.Context, arg CountCompanyCardViewQuotaWindowParams) (CountCompanyCardViewQuotaWindowRow, error)
@@ -125,10 +131,22 @@ type Querier interface {
// Counts the families of a category that have at least one published
// version, however many versions each has.
CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error)
// New outcomes share the generic idempotency row and are counted for the
// attempt's rolling receipt window. Replays bypass this query in the usecase.
CountRecentAssessmentSignalOutcomes(ctx context.Context, arg CountRecentAssessmentSignalOutcomesParams) (CountRecentAssessmentSignalOutcomesRow, error)
// Counts root attempts only; the caller applies the effective policy's
// configured window and the product's approved accounting scope.
CountRootAssessmentAttemptsSince(ctx context.Context, arg CountRootAssessmentAttemptsSinceParams) (int64, error)
// The strict lower boundary means an event exactly one window old no longer
// counts. The use case derives Retry-After from first_in_window.
CountSupportCaseRequestEvents(ctx context.Context, arg CountSupportCaseRequestEventsParams) (CountSupportCaseRequestEventsRow, error)
// Creates one durable deletion request per subject until a worker completes it.
// The caller appends the matching outbox intent in the same transaction only
// when this insert returns a row.
CreateAccountDeletionRequest(ctx context.Context, arg CreateAccountDeletionRequestParams) (CreateAccountDeletionRequestRow, error)
// A newly reserved generic idempotency window can replace an expired typed
// outcome before the new immutable response is inserted.
DeleteAssessmentAttemptIdempotencyOutcome(ctx context.Context, scopeHash []byte) error
// Lifts one hiding. No row returns when the organization was not hidden, so
// the caller writes the history event only for a real deletion and answers
// 204 either way.
@@ -142,9 +160,15 @@ type Querier interface {
// Replaces all specialization answers after the version row advanced in the
// same transaction.
DeleteCandidateQuestionnaireSpecializations(ctx context.Context, userID pgtype.UUID) error
// The generic reservation has already established that a previous outcome is
// expired before this child is removed and replaced in the same transaction.
DeleteExpiredAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) error
DeleteExpiredCompanyCardViewQuotaUsage(ctx context.Context, arg DeleteExpiredCompanyCardViewQuotaUsageParams) (int64, error)
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error
// No raw Idempotency-Key or request body reaches these statements. Failure
// responses pass {} as case_snapshot and the CASE stores SQL NULL instead.
DeleteSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) error
// Deletes one batch of accounts that stayed unverified since before cutoff,
// oldest first, with their tokens, sessions, mail requests, mail deliveries
// (and through the deliveries their attempts), and consent records. The
@@ -190,9 +214,30 @@ type Querier interface {
// Reads the durable active deletion request when an earlier request already
// exists. A completed request does not suppress a later explicit request.
GetActiveAccountDeletionRequest(ctx context.Context, subjectID pgtype.UUID) (GetActiveAccountDeletionRequestRow, error)
// Locks the active real attempt after LockAssessmentAttemptScope.
GetActiveAssessmentAttemptForSpecialization(ctx context.Context, arg GetActiveAssessmentAttemptForSpecializationParams) (AssessmentAttempt, error)
GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error)
// Locks the one active express attempt after LockAssessmentAttemptScope.
GetActiveTrainingAssessmentAttempt(ctx context.Context, userID pgtype.UUID) (AssessmentAttempt, error)
// Returns a full private attempt only to its candidate.
GetAssessmentAttemptForCandidate(ctx context.Context, arg GetAssessmentAttemptForCandidateParams) (AssessmentAttempt, error)
GetAssessmentAttemptIdempotencyOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentAttemptIdempotencyOutcomeRow, error)
// Reads the immutable attempt kind without locking the row. Session commands
// use this only to decide whether C3 applies before acquiring the row lock.
GetAssessmentAttemptKindForCandidate(ctx context.Context, arg GetAssessmentAttemptKindForCandidateParams) (string, error)
// Reads a result only for the owning candidate.
GetAssessmentAttemptResult(ctx context.Context, arg GetAssessmentAttemptResultParams) (string, error)
// Reads an active real attempt without taking the write lock used by create.
// The availability GET never expires or otherwise mutates this row.
GetAssessmentAvailabilityActiveAttempt(ctx context.Context, arg GetAssessmentAvailabilityActiveAttemptParams) (GetAssessmentAvailabilityActiveAttemptRow, error)
GetAssessmentFamilyByID(ctx context.Context, id pgtype.UUID) (AssessmentFamily, error)
GetAssessmentFamilyVersion(ctx context.Context, arg GetAssessmentFamilyVersionParams) (AssessmentFamily, error)
// Counts eligible root attempts in a policy window and computes the instant
// at which one additional root slot opens. The microsecond adjustment matches
// the creation predicate created_at >= since at PostgreSQL timestamp precision.
GetAssessmentRootQuotaAvailability(ctx context.Context, arg GetAssessmentRootQuotaAvailabilityParams) (GetAssessmentRootQuotaAvailabilityRow, error)
// Read only the receipt associated with the reserved idempotency scope.
GetAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentSignalOutcomeRow, error)
// Reads one hiding of the candidate with the current name of the
// organization.
GetCandidateHiddenOrganization(ctx context.Context, arg GetCandidateHiddenOrganizationParams) (GetCandidateHiddenOrganizationRow, error)
@@ -236,6 +281,8 @@ type Querier interface {
// resend, which issues its token with the same credentials.
GetLatestPendingRegistration(ctx context.Context, arg GetLatestPendingRegistrationParams) (GetLatestPendingRegistrationRow, error)
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
// Reads the latest root in a specialization, optionally restricted to grade.
GetLatestRootAssessmentAttempt(ctx context.Context, arg GetLatestRootAssessmentAttemptParams) (AssessmentAttempt, error)
GetLiveIdempotencyRecord(ctx context.Context, arg GetLiveIdempotencyRecordParams) (IdempotencyRecord, error)
// Reads the usage of the day and the month window without locking.
GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error)
@@ -250,6 +297,9 @@ type Querier interface {
// unknown organization, an account that is no member, and a suspended,
// removed, or left member all return no row and cannot be told apart.
GetOrganizationForMember(ctx context.Context, arg GetOrganizationForMemberParams) (GetOrganizationForMemberRow, error)
// Read only the immutable original response. The current need may have moved
// to a later version since this result was created.
GetOrganizationNeedCreationResult(ctx context.Context, scopeHash []byte) (string, error)
// Reads the relay backlog for metrics without locking. Both subqueries use
// the partial index on unpublished positions, so the cost follows the backlog
// size, not the table size. The age comes from the database clock, the same
@@ -278,6 +328,15 @@ type Querier interface {
GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error)
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
// Inserts the attempt header. The database guard rechecks the current policy,
// opening or disjoint training binding, and immutable pins.
InsertAssessmentAttempt(ctx context.Context, arg InsertAssessmentAttemptParams) error
InsertAssessmentAttemptIdempotencyOutcome(ctx context.Context, arg InsertAssessmentAttemptIdempotencyOutcomeParams) error
// Stores the immutable generated variant and empty answer slot.
InsertAssessmentAttemptItem(ctx context.Context, arg InsertAssessmentAttemptItemParams) error
// 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 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.
@@ -292,6 +351,18 @@ type Querier interface {
// returns no row instead of an error, so a conflict does not abort the
// surrounding transaction.
InsertAssessmentFamily(ctx context.Context, arg InsertAssessmentFamilyParams) (AssessmentFamily, error)
// The attempt row is already locked by the caller. Store a parent before its
// bounded child events, in the same transaction as the immutable receipt.
InsertAssessmentSignalBatch(ctx context.Context, arg InsertAssessmentSignalBatchParams) error
// Each inserted event is checked by the database guard against attempt state
// and the aggregate capacity as a second line of defense.
InsertAssessmentSignalEvent(ctx context.Context, arg InsertAssessmentSignalEventParams) error
// Save exactly one immutable response receipt for each live idempotency scope.
InsertAssessmentSignalOutcome(ctx context.Context, arg InsertAssessmentSignalOutcomeParams) error
// Records a successfully authorized view after visibility and quota checks.
// The audit contains only identities, the access kind, published field codes,
// and time; it never receives the projection content, ranking, or filters.
InsertCandidateCardAccessEvent(ctx context.Context, arg InsertCandidateCardAccessEventParams) error
// Hides one organization. No row returns when the pair already exists, and
// the caller reads the existing record with its original time. The foreign key
// refuses an unknown organization (SQLSTATE 23503); the caller answers it
@@ -390,12 +461,44 @@ type Querier interface {
// transaction and then inserts nothing, or inserts after its rollback.
InsertScheduledJob(ctx context.Context, arg InsertScheduledJobParams) (int64, error)
InsertSession(ctx context.Context, arg InsertSessionParams) error
// The initial public history is inserted in the caller's case transaction.
// Any unique business conflict leaves the transaction usable so the caller can
// store the immutable 409 outcome under the request's idempotency key.
InsertSupportCase(ctx context.Context, arg InsertSupportCaseParams) (int64, error)
InsertSupportCaseCreateOutcome(ctx context.Context, arg InsertSupportCaseCreateOutcomeParams) error
InsertSupportCaseEvent(ctx context.Context, arg InsertSupportCaseEventParams) error
InsertSupportCaseRequestEvent(ctx context.Context, arg InsertSupportCaseRequestEventParams) 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
// clock cannot make the next request fall before an event already counted.
LatestSupportCaseRequestEvent(ctx context.Context, ownerID pgtype.UUID) (pgtype.Timestamptz, error)
// Reads chain headers in creation order. The use case verifies root eligibility
// and descending target grades in the domain before it creates a correction.
ListAssessmentAttemptChain(ctx context.Context, arg ListAssessmentAttemptChainParams) ([]AssessmentAttempt, error)
// Reads private frozen variants and candidate answer bytes in stable order.
ListAssessmentAttemptItems(ctx context.Context, attemptID pgtype.UUID) ([]ListAssessmentAttemptItemsRow, error)
// Reads roots within the policy horizon and the last header in each correction
// chain. It deliberately omits frozen items, answers, and row locks.
ListAssessmentAvailabilityRootSummaries(ctx context.Context, arg ListAssessmentAvailabilityRootSummariesParams) ([]ListAssessmentAvailabilityRootSummariesRow, error)
// Counts family instances disclosed after the non-repeat boundary. The first
// item is disclosed when the attempt is created; each later item is disclosed
// when the preceding answer is accepted. This per-item timestamp prevents a
// long-running attempt from making later items appear older than they are.
// Counting the first unanswered item after expiry is conservative when the
// final response was lost, while frozen future items remain excluded.
ListAssessmentDisclosedFamilyKeys(ctx context.Context, arg ListAssessmentDisclosedFamilyKeysParams) ([]string, error)
// One page of the versions of a category in key and version order, after the
// given position; an empty key and version 0 start at the beginning. The
// (family_key, version) unique index serves the scan.
ListAssessmentFamiliesByCategory(ctx context.Context, arg ListAssessmentFamiliesByCategoryParams) ([]AssessmentFamily, error)
// Reads the exact family membership pinned by a training binding.
ListAssessmentTrainingBindingFamilies(ctx context.Context, bindingID pgtype.UUID) ([]ListAssessmentTrainingBindingFamiliesRow, 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
// access relation, which is already visible to the candidate.
ListCandidateCardAccessEvents(ctx context.Context, arg ListCandidateCardAccessEventsParams) ([]ListCandidateCardAccessEventsRow, 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
@@ -414,12 +517,22 @@ type Querier interface {
// whose records are scoped by invitation); active otherwise. The page continues after the (granted_at, id) position of
// the last record of the previous page.
ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, error)
// Returns current reviewed grade/language bindings and the live published
// family manifest at one caller-supplied database time. The adapter verifies
// the pinned manifest hash before exposing only family keys.
ListCurrentAssessmentAvailabilitySelections(ctx context.Context, asOf pgtype.Timestamptz) ([]ListCurrentAssessmentAvailabilitySelectionsRow, error)
// Lists explicit immutable training bindings for the effective product
// policy. Callers reject more than one matching active binding as ambiguous.
ListCurrentAssessmentTrainingBindings(ctx context.Context) ([]ListCurrentAssessmentTrainingBindingsRow, error)
ListCurrentContactConsentRecords(ctx context.Context, arg ListCurrentContactConsentRecordsParams) ([]ListCurrentContactConsentRecordsRow, error)
// Produces current catalog availability in one PostgreSQL statement snapshot.
// The adapter compares the ordered live family manifest with the pinned
// fingerprint; stale bindings are omitted fail-closed.
ListCurrentSpecializationAvailability(ctx context.Context) ([]ListCurrentSpecializationAvailabilityRow, error)
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
// 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)
// 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
@@ -428,10 +541,36 @@ type Querier interface {
// Lists the other accounts of a provider that have usage in a month, so
// startup can warn about a renamed EMAIL_ACCOUNT.
ListOtherMailQuotaAccounts(ctx context.Context, arg ListOtherMailQuotaAccountsParams) ([]string, error)
// Owner-scoped newest-first list. It omits descriptions, complaint reason,
// and event history. The tuple cursor matches the composite sort key.
ListOwnedSupportCases(ctx context.Context, arg ListOwnedSupportCasesParams) ([]ListOwnedSupportCasesRow, error)
// Organization-facing anonymous candidate projection inputs. The calling
// usecase has already authorized the active organization membership. This
// single statement snapshot filters both revoked/unpublished C2 states and
// 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.
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
// share locks until its transaction commits, so a concurrent revocation
// cannot authorize a write after it has committed.
LockActiveMembership(ctx context.Context, arg LockActiveMembershipParams) (LockActiveMembershipRow, error)
// Locks one owner-scoped attempt while a session command performs its CAS.
LockAssessmentAttemptForCandidate(ctx context.Context, arg LockAssessmentAttemptForCandidateParams) (AssessmentAttempt, error)
// Serializes root quota checks for one candidate before taking its optional
// specialization or training lock. All callers acquire these locks in order.
LockAssessmentAttemptScope(ctx context.Context, arg LockAssessmentAttemptScopeParams) error
// Serializes the operations that change which versions of a category are
// published or open the category, until the transaction ends. The key is
// namespaced, so it cannot collide with another use of advisory locks.
LockAssessmentCategory(ctx context.Context, category string) error
// Lock the account before an organization checks candidate visibility. The
// hidden-organization insert trigger takes FOR NO KEY UPDATE on this row, so
// 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)
// 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
@@ -452,6 +591,10 @@ type Querier interface {
// finally usage rows. The organization lock serializes quota decisions for
// the tenant and makes the subsequent count and insert atomic.
LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error)
// Lock the current C2 before locking the publication. C2 revocation updates
// this row before it locks the publication, so preserving this order avoids
// a lock inversion and makes the current consent stable through the read.
LockCurrentC2ForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
// Takes the candidate's current unrevoked C2 record for a publication and
// keeps it locked until the transaction ends. The share lock conflicts with
// the revocation stamp (an UPDATE of the row), so a revocation either commits
@@ -461,6 +604,9 @@ type Querier interface {
// publication and must re-read the effective state (ReadCandidatePublication)
// in that transaction to build its response.
LockCurrentC2Record(ctx context.Context, subjectID pgtype.UUID) (pgtype.UUID, error)
// Keeps the current C3 grant stable through a real assessment transaction.
// Revocation updates this row and therefore waits until the caller commits.
LockCurrentConsentForUse(ctx context.Context, subjectID pgtype.UUID) (LockCurrentConsentForUseRow, error)
// Locks the listed window rows until the transaction ends, in
// (period_kind, period_start) order, the same order for every caller, and
// returns their usage. Under READ COMMITTED a waiting caller reads the usage
@@ -482,8 +628,17 @@ type Querier interface {
// because aggregate writers check the expected version, so scanning without a
// position watermark cannot overtake an earlier version.
LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error)
// Lock a candidate's current publication for the private preview. This has
// no organization context and never enters the employer read quota or audit.
LockPublicationForCandidatePreview(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
// Locks the active registration C1 while its pending registration is applied.
LockRegistrationConsentRecord(ctx context.Context, arg LockRegistrationConsentRecordParams) (LockRegistrationConsentRecordRow, error)
// Serialize per-owner budget checks even before the first event exists.
LockSupportCaseRequestBudget(ctx context.Context, ownerID pgtype.UUID) error
// Lock and recheck one candidate's exact current publication only after the
// active C2 row is share-locked. No row includes unpublished, revoked, stale
// publication, and organization-hidden states.
LockVisiblePublicationForView(ctx context.Context, arg LockVisiblePublicationForViewParams) (pgtype.UUID, error)
// Notes that a request is about to start, by the database clock, and clears
// the count of worker failures. For an operator-authorized send, this sets
// its single-use marker without overwriting the original first-send time. The
@@ -504,10 +659,16 @@ type Querier interface {
// Verifies the email only for the registration version the consumed token
// was issued for.
MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVerifiedParams) (User, error)
// Case numbers are monotonic and never reused. Sequence gaps on a rolled-back
// request are expected and do not expose request contents.
NextSupportCaseNumber(ctx context.Context, utcYear string) (interface{}, error)
Ping(ctx context.Context) (int32, error)
// Reports whether a family has any version without reading a document, so a
// caller that only needs presence never depends on decoding.
PolicyVersionExists(ctx context.Context, policyKey string) (bool, error)
// Keep up to the maximum supported window, regardless of the current policy.
// The bounded delete prevents one create from doing unbounded cleanup work.
PruneSupportCaseRequestEvents(ctx context.Context, arg PruneSupportCaseRequestEventsParams) (int64, error)
// Moves a draft to published by the named operator and returns the row with
// the publication time set by the guard trigger. No row means the version
// was not a draft any more.
@@ -515,6 +676,18 @@ type Querier interface {
// Deletes at most batch_limit expired records. Locked rows are skipped, so
// the statement never waits for a concurrent reservation.
PurgeExpiredIdempotencyRecords(ctx context.Context, arg PurgeExpiredIdempotencyRecordsParams) (int64, error)
// Queries of the candidate visibility settings: the publication of
// the card, the search status, the hidden organizations, and the history of
// these settings. Every statement is scoped by the candidate's user_id, and
// no statement selects another account's row. No statement reads or writes a
// profile value, a name, or a contact. A candidate with no row is closed, not
// looking, and hides nobody; no statement creates a row except an explicit
// act of the candidate.
// Reads the candidate-owned settings and hidden count from one statement
// snapshot. Missing setting rows are restored as the closed/not-looking
// defaults in the adapter. The account row scopes the result but does not
// expose private profile values.
ReadCandidatePrivacySettings(ctx context.Context, userID pgtype.UUID) (ReadCandidatePrivacySettingsRow, error)
// Reads the profile row of an account together with every claim in one
// statement, so the version and the claims come from one snapshot: a save that
// commits between two separate reads could pair version N with the claims of
@@ -523,13 +696,6 @@ type Querier interface {
// 0). Claims come in a stable order: single fields by kind, list items by
// position. Never replace this with two statements.
ReadCandidateProfile(ctx context.Context, userID pgtype.UUID) ([]ReadCandidateProfileRow, error)
// Queries of the candidate visibility settings: the publication of
// the card, the search status, the hidden organizations, and the history of
// these settings. Every statement is scoped by the candidate's user_id, and
// no statement selects another account's row. No statement reads or writes a
// profile value, a name, or a contact. A candidate with no row is closed, not
// looking, and hides nobody; no statement creates a row except an explicit
// act of the candidate.
// Reads the publication with the revocation state of the C2 record behind it
// in one statement, so the stored setting and the ledger come from one
// snapshot. The effective state is computed from them: published only while
@@ -542,10 +708,16 @@ type Querier interface {
// lapse is computed by the caller from lapses_at and its clock and is never
// written.
ReadCandidateSearchStatus(ctx context.Context, userID pgtype.UUID) (CandidateSearchStatus, error)
// Read the candidate's current private projection inputs after the caller
// locks its active C2 and publication. It selects only fields allowed in the
// anonymous-card projection and is never used for employer visibility.
ReadCandidateViewSourceForPreview(ctx context.Context, candidateID pgtype.UUID) ([]ReadCandidateViewSourceForPreviewRow, error)
// Read one current version with its organization-scoped parent metadata.
ReadCurrentOrganizationNeed(ctx context.Context, arg ReadCurrentOrganizationNeedParams) (ReadCurrentOrganizationNeedRow, error)
// Read one historical version without exposing another organization's record.
ReadOrganizationNeedVersion(ctx context.Context, arg ReadOrganizationNeedVersionParams) (string, error)
// Reads a full owner-scoped record. Object values are identifiers only.
ReadOwnedSupportCase(ctx context.Context, arg ReadOwnedSupportCaseParams) (SupportCase, error)
// The organization-facing read of a candidate's publication: the effective
// view (published and backed by an unrevoked C2) and no hiding of the reading
// organization. No row means the organization reads nothing, whichever of
@@ -557,6 +729,9 @@ type Querier interface {
// held by OpenCategory. Published families have passed the independent-review
// constraint before this read.
ReadPublishedAssessmentCategoryManifest(ctx context.Context, category string) ([]ReadPublishedAssessmentCategoryManifestRow, error)
ReadSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) (ReadSupportCaseCreateOutcomeRow, error)
// Reads the immutable public history only after the case owner has matched.
ReadSupportCaseEvents(ctx context.Context, caseID pgtype.UUID) ([]ReadSupportCaseEventsRow, error)
// Advances a delivery past one attempt and appends the attempt in one
// statement, so both happen or neither does, inside or outside a
// transaction. The update applies only while the stored version still
@@ -609,6 +784,14 @@ type Querier interface {
// with GetLiveIdempotencyRecord. Concurrent callers with the same scope wait
// on the row of the first one until its transaction ends.
ReserveIdempotencyRecord(ctx context.Context, arg ReserveIdempotencyRecordParams) (IdempotencyRecord, error)
// Finds candidate-requested selections across currently opened categories.
// The adapter validates policy and manifest freshness, locks the category,
// then runs this query again before it returns any pinned families.
ResolveCurrentAssessmentSelection(ctx context.Context, arg ResolveCurrentAssessmentSelectionParams) ([]ResolveCurrentAssessmentSelectionRow, error)
// Lists every current reviewed category binding for one exact public target.
// Manual support cases have no task-language selector, so the use case must
// accept a rubric only when one distinct current opening matches.
ResolveCurrentSupportCaseRubrics(ctx context.Context, arg ResolveCurrentSupportCaseRubricsParams) ([]ResolveCurrentSupportCaseRubricsRow, error)
RetireAssessmentFamily(ctx context.Context, arg RetireAssessmentFamilyParams) (AssessmentFamily, error)
// Revokes every unrevoked record of a purpose other than C4, superseded ones
// included, and returns them. A revocation time before the grant time, from
@@ -625,6 +808,10 @@ type Querier interface {
// and owner membership. A reused expired scope replaces the snapshot in the
// same transaction as the new organization.
SaveOrganizationCreationResult(ctx context.Context, arg SaveOrganizationCreationResultParams) error
// The generic idempotency scope serializes retries. Replacing the child row
// is safe only in the transaction that reserves an expired scope for a new
// create; live retries read and return the stored response without writing.
SaveOrganizationNeedCreationResult(ctx context.Context, arg SaveOrganizationNeedCreationResultParams) error
// Bounds a consumer transaction on the server, local to the transaction.
// statement_timeout stops a slow statement; idle_in_transaction_session_timeout
// ends the session of a process that froze or lost the network inside the
@@ -661,6 +848,14 @@ type Querier interface {
// revoked, expired, or idle session is not revived; the update re-checks
// those conditions against a concurrent change.
TouchSession(ctx context.Context, arg TouchSessionParams) (TouchSessionRow, error)
// Stores one final answer before advancing the enclosing attempt version.
// The caller holds the owner-scoped attempt row lock for the surrounding unit.
UpdateAssessmentAttemptItemAnswer(ctx context.Context, arg UpdateAssessmentAttemptItemAnswerParams) (pgtype.UUID, error)
// Applies a versioned session transition after the attempt row is locked.
UpdateAssessmentAttemptSession(ctx context.Context, arg UpdateAssessmentAttemptSessionParams) (AssessmentAttempt, error)
// Applies an answer, expiry, or finalization transition after the attempt row
// is locked. Session limits and all immutable pins remain unchanged.
UpdateAssessmentAttemptTransition(ctx context.Context, arg UpdateAssessmentAttemptTransitionParams) (AssessmentAttempt, error)
// Replaces the publication over the version the caller read and advances the
// version in the same statement. No row returns for a stale version, which
// the caller answers as a version conflict. The update time never moves back,
@@ -0,0 +1,502 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: support_cases.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const countSupportCaseRequestEvents = `-- name: CountSupportCaseRequestEvents :one
SELECT count(*)::bigint AS event_count, min(requested_at) AS first_in_window
FROM support_case_request_events
WHERE owner_id = $1
AND requested_at > $2::timestamptz
AND requested_at <= $3::timestamptz
`
type CountSupportCaseRequestEventsParams struct {
OwnerID pgtype.UUID
WindowStart pgtype.Timestamptz
At pgtype.Timestamptz
}
type CountSupportCaseRequestEventsRow struct {
EventCount int64
FirstInWindow interface{}
}
// The strict lower boundary means an event exactly one window old no longer
// counts. The use case derives Retry-After from first_in_window.
func (q *Queries) CountSupportCaseRequestEvents(ctx context.Context, arg CountSupportCaseRequestEventsParams) (CountSupportCaseRequestEventsRow, error) {
row := q.db.QueryRow(ctx, countSupportCaseRequestEvents, arg.OwnerID, arg.WindowStart, arg.At)
var i CountSupportCaseRequestEventsRow
err := row.Scan(&i.EventCount, &i.FirstInWindow)
return i, err
}
const deleteSupportCaseCreateOutcome = `-- name: DeleteSupportCaseCreateOutcome :exec
DELETE FROM support_case_create_outcomes
WHERE scope_hash = $1
`
// No raw Idempotency-Key or request body reaches these statements. Failure
// responses pass {} as case_snapshot and the CASE stores SQL NULL instead.
func (q *Queries) DeleteSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) error {
_, err := q.db.Exec(ctx, deleteSupportCaseCreateOutcome, scopeHash)
return err
}
const insertSupportCase = `-- name: InsertSupportCase :execrows
INSERT INTO support_cases (
id, case_number, owner_id, case_type, status, description,
object_type, object_id, assessment_specialization, assessment_grade,
complaint_reason, rubric_version, rubric_opening_id, rubric_policy_version_id,
target_business_days, target_due_at,
target_answered_at, target_policy_version, target_calendar_version,
decision_outcome, decision_reason, decision_at, created_at, updated_at
) VALUES (
$1, $2, $3, $4,
$5, $6, $7, $8,
$9, $10,
$11, $12, $13,
$14, $15,
$16, $17, $18,
$19, $20, $21,
$22, $23, $24
)
ON CONFLICT DO NOTHING
`
type InsertSupportCaseParams struct {
ID pgtype.UUID
CaseNumber string
OwnerID pgtype.UUID
CaseType string
Status string
Description string
ObjectType pgtype.Text
ObjectID pgtype.UUID
AssessmentSpecialization pgtype.Text
AssessmentGrade pgtype.Text
ComplaintReason pgtype.Text
RubricVersion pgtype.Int4
RubricOpeningID pgtype.UUID
RubricPolicyVersionID pgtype.UUID
TargetBusinessDays int32
TargetDueAt pgtype.Timestamptz
TargetAnsweredAt pgtype.Timestamptz
TargetPolicyVersion int32
TargetCalendarVersion int32
DecisionOutcome pgtype.Text
DecisionReason pgtype.Text
DecisionAt pgtype.Timestamptz
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// The initial public history is inserted in the caller's case transaction.
// Any unique business conflict leaves the transaction usable so the caller can
// store the immutable 409 outcome under the request's idempotency key.
func (q *Queries) InsertSupportCase(ctx context.Context, arg InsertSupportCaseParams) (int64, error) {
result, err := q.db.Exec(ctx, insertSupportCase,
arg.ID,
arg.CaseNumber,
arg.OwnerID,
arg.CaseType,
arg.Status,
arg.Description,
arg.ObjectType,
arg.ObjectID,
arg.AssessmentSpecialization,
arg.AssessmentGrade,
arg.ComplaintReason,
arg.RubricVersion,
arg.RubricOpeningID,
arg.RubricPolicyVersionID,
arg.TargetBusinessDays,
arg.TargetDueAt,
arg.TargetAnsweredAt,
arg.TargetPolicyVersion,
arg.TargetCalendarVersion,
arg.DecisionOutcome,
arg.DecisionReason,
arg.DecisionAt,
arg.CreatedAt,
arg.UpdatedAt,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const insertSupportCaseCreateOutcome = `-- name: InsertSupportCaseCreateOutcome :exec
INSERT INTO support_case_create_outcomes (
scope_hash, outcome_kind, case_snapshot, target_was_late, created_at
) VALUES (
$1, $2,
CASE WHEN $2::text = 'created' THEN $3::jsonb END,
CASE WHEN $2::text = 'created' THEN $4::boolean END,
$5
)
`
type InsertSupportCaseCreateOutcomeParams struct {
ScopeHash []byte
OutcomeKind string
CaseSnapshot []byte
TargetWasLate bool
CreatedAt pgtype.Timestamptz
}
func (q *Queries) InsertSupportCaseCreateOutcome(ctx context.Context, arg InsertSupportCaseCreateOutcomeParams) error {
_, err := q.db.Exec(ctx, insertSupportCaseCreateOutcome,
arg.ScopeHash,
arg.OutcomeKind,
arg.CaseSnapshot,
arg.TargetWasLate,
arg.CreatedAt,
)
return err
}
const insertSupportCaseEvent = `-- name: InsertSupportCaseEvent :exec
INSERT INTO support_case_events (
case_id, sequence, event_kind, actor_kind, occurred_at, status, message
) VALUES (
$1, $2, $3, $4,
$5, $6, $7
)
`
type InsertSupportCaseEventParams struct {
CaseID pgtype.UUID
Sequence int32
EventKind string
ActorKind string
OccurredAt pgtype.Timestamptz
Status pgtype.Text
Message pgtype.Text
}
func (q *Queries) InsertSupportCaseEvent(ctx context.Context, arg InsertSupportCaseEventParams) error {
_, err := q.db.Exec(ctx, insertSupportCaseEvent,
arg.CaseID,
arg.Sequence,
arg.EventKind,
arg.ActorKind,
arg.OccurredAt,
arg.Status,
arg.Message,
)
return err
}
const insertSupportCaseRequestEvent = `-- name: InsertSupportCaseRequestEvent :exec
INSERT INTO support_case_request_events (owner_id, requested_at)
VALUES ($1, $2)
`
type InsertSupportCaseRequestEventParams struct {
OwnerID pgtype.UUID
RequestedAt pgtype.Timestamptz
}
func (q *Queries) InsertSupportCaseRequestEvent(ctx context.Context, arg InsertSupportCaseRequestEventParams) error {
_, err := q.db.Exec(ctx, insertSupportCaseRequestEvent, arg.OwnerID, arg.RequestedAt)
return err
}
const latestSupportCaseRequestEvent = `-- name: LatestSupportCaseRequestEvent :one
SELECT requested_at
FROM support_case_request_events
WHERE owner_id = $1
ORDER BY requested_at DESC, id DESC
LIMIT 1
`
// Read the latest serialized event so a temporarily regressing application
// clock cannot make the next request fall before an event already counted.
func (q *Queries) LatestSupportCaseRequestEvent(ctx context.Context, ownerID pgtype.UUID) (pgtype.Timestamptz, error) {
row := q.db.QueryRow(ctx, latestSupportCaseRequestEvent, ownerID)
var requested_at pgtype.Timestamptz
err := row.Scan(&requested_at)
return requested_at, err
}
const listOwnedSupportCases = `-- name: ListOwnedSupportCases :many
WITH cursor_input AS MATERIALIZED (
SELECT
$3::timestamptz AS after_created_at,
$4::uuid AS after_id
)
SELECT
id, case_number, case_type, status, object_type, object_id,
assessment_specialization, assessment_grade, target_business_days,
target_due_at, target_answered_at, target_policy_version,
target_calendar_version, decision_outcome, created_at, updated_at
FROM support_cases
CROSS JOIN cursor_input
WHERE owner_id = $1
AND (
cursor_input.after_created_at IS NULL
OR (created_at, id) < (
cursor_input.after_created_at,
cursor_input.after_id
)
)
ORDER BY created_at DESC, id DESC
LIMIT $2
`
type ListOwnedSupportCasesParams struct {
OwnerID pgtype.UUID
RowLimit int32
AfterCreatedAt pgtype.Timestamptz
AfterID pgtype.UUID
}
type ListOwnedSupportCasesRow struct {
ID pgtype.UUID
CaseNumber string
CaseType string
Status string
ObjectType pgtype.Text
ObjectID pgtype.UUID
AssessmentSpecialization pgtype.Text
AssessmentGrade pgtype.Text
TargetBusinessDays int32
TargetDueAt pgtype.Timestamptz
TargetAnsweredAt pgtype.Timestamptz
TargetPolicyVersion int32
TargetCalendarVersion int32
DecisionOutcome pgtype.Text
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Owner-scoped newest-first list. It omits descriptions, complaint reason,
// and event history. The tuple cursor matches the composite sort key.
func (q *Queries) ListOwnedSupportCases(ctx context.Context, arg ListOwnedSupportCasesParams) ([]ListOwnedSupportCasesRow, error) {
rows, err := q.db.Query(ctx, listOwnedSupportCases,
arg.OwnerID,
arg.RowLimit,
arg.AfterCreatedAt,
arg.AfterID,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListOwnedSupportCasesRow
for rows.Next() {
var i ListOwnedSupportCasesRow
if err := rows.Scan(
&i.ID,
&i.CaseNumber,
&i.CaseType,
&i.Status,
&i.ObjectType,
&i.ObjectID,
&i.AssessmentSpecialization,
&i.AssessmentGrade,
&i.TargetBusinessDays,
&i.TargetDueAt,
&i.TargetAnsweredAt,
&i.TargetPolicyVersion,
&i.TargetCalendarVersion,
&i.DecisionOutcome,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockSupportCaseRequestBudget = `-- name: LockSupportCaseRequestBudget :exec
SELECT pg_advisory_xact_lock(
hashtextextended('lincodex.support.case.requests:' || $1::uuid::text, 0)
)
`
// Serialize per-owner budget checks even before the first event exists.
func (q *Queries) LockSupportCaseRequestBudget(ctx context.Context, ownerID pgtype.UUID) error {
_, err := q.db.Exec(ctx, lockSupportCaseRequestBudget, ownerID)
return err
}
const nextSupportCaseNumber = `-- name: NextSupportCaseNumber :one
WITH next_value AS MATERIALIZED (
SELECT nextval('support_case_number_seq') AS value
)
SELECT
'SC-' || $1::text || '-' ||
CASE
WHEN next_value.value < 1000000 THEN lpad(next_value.value::text, 6, '0')
ELSE next_value.value::text
END::text AS case_number
FROM next_value
`
// Case numbers are monotonic and never reused. Sequence gaps on a rolled-back
// request are expected and do not expose request contents.
func (q *Queries) NextSupportCaseNumber(ctx context.Context, utcYear string) (interface{}, error) {
row := q.db.QueryRow(ctx, nextSupportCaseNumber, utcYear)
var case_number interface{}
err := row.Scan(&case_number)
return case_number, err
}
const pruneSupportCaseRequestEvents = `-- name: PruneSupportCaseRequestEvents :execrows
WITH expired AS MATERIALIZED (
SELECT source.id
FROM support_case_request_events AS source
WHERE source.owner_id = $1
AND source.requested_at <= $2::timestamptz - interval '24 hours'
ORDER BY source.requested_at, source.id
LIMIT 100
FOR UPDATE SKIP LOCKED
)
DELETE FROM support_case_request_events AS event
USING expired
WHERE event.id = expired.id
`
type PruneSupportCaseRequestEventsParams struct {
OwnerID pgtype.UUID
At pgtype.Timestamptz
}
// Keep up to the maximum supported window, regardless of the current policy.
// The bounded delete prevents one create from doing unbounded cleanup work.
func (q *Queries) PruneSupportCaseRequestEvents(ctx context.Context, arg PruneSupportCaseRequestEventsParams) (int64, error) {
result, err := q.db.Exec(ctx, pruneSupportCaseRequestEvents, arg.OwnerID, arg.At)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const readOwnedSupportCase = `-- name: ReadOwnedSupportCase :one
SELECT
id, case_number, owner_id, case_type, status, description,
object_type, object_id, assessment_specialization, assessment_grade,
complaint_reason, rubric_version, rubric_opening_id, rubric_policy_version_id,
target_business_days, target_due_at,
target_answered_at, target_policy_version, target_calendar_version,
decision_outcome, decision_reason, decision_at, created_at, updated_at
FROM support_cases
WHERE id = $1 AND owner_id = $2
`
type ReadOwnedSupportCaseParams struct {
CaseID pgtype.UUID
OwnerID pgtype.UUID
}
// Reads a full owner-scoped record. Object values are identifiers only.
func (q *Queries) ReadOwnedSupportCase(ctx context.Context, arg ReadOwnedSupportCaseParams) (SupportCase, error) {
row := q.db.QueryRow(ctx, readOwnedSupportCase, arg.CaseID, arg.OwnerID)
var i SupportCase
err := row.Scan(
&i.ID,
&i.CaseNumber,
&i.OwnerID,
&i.CaseType,
&i.Status,
&i.Description,
&i.ObjectType,
&i.ObjectID,
&i.AssessmentSpecialization,
&i.AssessmentGrade,
&i.ComplaintReason,
&i.RubricVersion,
&i.RubricOpeningID,
&i.RubricPolicyVersionID,
&i.TargetBusinessDays,
&i.TargetDueAt,
&i.TargetAnsweredAt,
&i.TargetPolicyVersion,
&i.TargetCalendarVersion,
&i.DecisionOutcome,
&i.DecisionReason,
&i.DecisionAt,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const readSupportCaseCreateOutcome = `-- name: ReadSupportCaseCreateOutcome :one
SELECT outcome_kind, coalesce(case_snapshot::text, '') AS case_snapshot, target_was_late
FROM support_case_create_outcomes
WHERE scope_hash = $1
`
type ReadSupportCaseCreateOutcomeRow struct {
OutcomeKind string
CaseSnapshot interface{}
TargetWasLate pgtype.Bool
}
func (q *Queries) ReadSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) (ReadSupportCaseCreateOutcomeRow, error) {
row := q.db.QueryRow(ctx, readSupportCaseCreateOutcome, scopeHash)
var i ReadSupportCaseCreateOutcomeRow
err := row.Scan(&i.OutcomeKind, &i.CaseSnapshot, &i.TargetWasLate)
return i, err
}
const readSupportCaseEvents = `-- name: ReadSupportCaseEvents :many
SELECT sequence, event_kind, actor_kind, occurred_at, status, message
FROM support_case_events
WHERE case_id = $1
ORDER BY sequence
`
type ReadSupportCaseEventsRow struct {
Sequence int32
EventKind string
ActorKind string
OccurredAt pgtype.Timestamptz
Status pgtype.Text
Message pgtype.Text
}
// Reads the immutable public history only after the case owner has matched.
func (q *Queries) ReadSupportCaseEvents(ctx context.Context, caseID pgtype.UUID) ([]ReadSupportCaseEventsRow, error) {
rows, err := q.db.Query(ctx, readSupportCaseEvents, caseID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ReadSupportCaseEventsRow
for rows.Next() {
var i ReadSupportCaseEventsRow
if err := rows.Scan(
&i.Sequence,
&i.EventKind,
&i.ActorKind,
&i.OccurredAt,
&i.Status,
&i.Message,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -0,0 +1,120 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: support_rubrics.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const resolveCurrentSupportCaseRubrics = `-- name: ResolveCurrentSupportCaseRubrics :many
WITH current_openings AS (
SELECT DISTINCT ON (category)
id,
category,
policy_version_id,
required_families
FROM assessment_category_openings
ORDER BY category, opened_at DESC, id DESC
), current_policy AS (
SELECT id, version
FROM policy_versions
WHERE policy_key = 'product' AND effective_at <= statement_timestamp()
ORDER BY version DESC
LIMIT 1
)
SELECT
opening.id AS opening_id,
opening.category,
opening.policy_version_id,
opening.required_families,
COALESCE((
SELECT count(DISTINCT family.family_key)::integer
FROM assessment_families AS family
WHERE family.category = opening.category AND family.lifecycle = 'published'
), 0)::integer AS published_count,
policy.id AS effective_policy_id,
policy.version AS effective_policy_version,
binding.specialization,
binding.grade,
binding.task_languages,
binding.published_manifest_sha256,
COALESCE((
SELECT jsonb_agg(
jsonb_build_object(
'family_key', family.family_key,
'version', family.version,
'content_sha256', encode(family.content_sha256, 'hex')
) ORDER BY family.family_key, family.version
)
FROM assessment_families AS family
WHERE family.category = opening.category AND family.lifecycle = 'published'
), '[]'::jsonb)::text AS published_manifest
FROM current_openings AS opening
JOIN assessment_category_catalog_bindings AS binding
ON binding.opening_id = opening.id
LEFT JOIN current_policy AS policy ON true
WHERE binding.specialization = $1
AND binding.grade = $2
ORDER BY opening.category
`
type ResolveCurrentSupportCaseRubricsParams struct {
Specialization string
Grade string
}
type ResolveCurrentSupportCaseRubricsRow struct {
OpeningID pgtype.UUID
Category string
PolicyVersionID pgtype.UUID
RequiredFamilies int32
PublishedCount int32
EffectivePolicyID pgtype.UUID
EffectivePolicyVersion pgtype.Int4
Specialization string
Grade string
TaskLanguages []string
PublishedManifestSha256 []byte
PublishedManifest string
}
// Lists every current reviewed category binding for one exact public target.
// Manual support cases have no task-language selector, so the use case must
// accept a rubric only when one distinct current opening matches.
func (q *Queries) ResolveCurrentSupportCaseRubrics(ctx context.Context, arg ResolveCurrentSupportCaseRubricsParams) ([]ResolveCurrentSupportCaseRubricsRow, error) {
rows, err := q.db.Query(ctx, resolveCurrentSupportCaseRubrics, arg.Specialization, arg.Grade)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ResolveCurrentSupportCaseRubricsRow
for rows.Next() {
var i ResolveCurrentSupportCaseRubricsRow
if err := rows.Scan(
&i.OpeningID,
&i.Category,
&i.PolicyVersionID,
&i.RequiredFamilies,
&i.PublishedCount,
&i.EffectivePolicyID,
&i.EffectivePolicyVersion,
&i.Specialization,
&i.Grade,
&i.TaskLanguages,
&i.PublishedManifestSha256,
&i.PublishedManifest,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}