feat: add assessment, privacy and support flows
This commit is contained in:
1 parent
ee3738ee73
commit
e4f24fa202
339 files changed
+56454
-1126
No files matched your search
@@ -0,0 +1,449 @@
|
||||
-- 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.
|
||||
-- name: ResolveCurrentAssessmentSelection :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 = sqlc.arg(specialization)
|
||||
AND binding.grade = sqlc.arg(grade)
|
||||
AND (
|
||||
(sqlc.narg(task_language)::text IS NULL AND cardinality(binding.task_languages) = 0)
|
||||
OR sqlc.narg(task_language)::text = ANY(binding.task_languages)
|
||||
)
|
||||
ORDER BY opening.category;
|
||||
|
||||
-- Serializes root quota checks for one candidate before taking its optional
|
||||
-- specialization or training lock. All callers acquire these locks in order.
|
||||
-- name: LockAssessmentAttemptScope :exec
|
||||
WITH candidate_lock AS MATERIALIZED (
|
||||
SELECT pg_advisory_xact_lock(hashtextextended(
|
||||
'lincodex.assessment.attempt:user:' || sqlc.arg(user_id)::text,
|
||||
0
|
||||
))
|
||||
)
|
||||
SELECT pg_advisory_xact_lock(hashtextextended(
|
||||
'lincodex.assessment.attempt:track:' || sqlc.arg(user_id)::text || ':' ||
|
||||
COALESCE(sqlc.narg(specialization)::text, 'training'),
|
||||
0
|
||||
))
|
||||
FROM candidate_lock;
|
||||
|
||||
-- Locks the active real attempt after LockAssessmentAttemptScope.
|
||||
-- name: GetActiveAssessmentAttemptForSpecialization :one
|
||||
SELECT
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at
|
||||
FROM assessment_attempts
|
||||
WHERE user_id = sqlc.arg(user_id)
|
||||
AND specialization = sqlc.arg(specialization)
|
||||
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
|
||||
FOR UPDATE;
|
||||
|
||||
-- Locks the one active express attempt after LockAssessmentAttemptScope.
|
||||
-- name: GetActiveTrainingAssessmentAttempt :one
|
||||
SELECT
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at
|
||||
FROM assessment_attempts
|
||||
WHERE user_id = sqlc.arg(user_id)
|
||||
AND kind = 'demo_express'
|
||||
AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize')
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT 1
|
||||
FOR UPDATE;
|
||||
|
||||
-- Reads the latest root in a specialization, optionally restricted to grade.
|
||||
-- name: GetLatestRootAssessmentAttempt :one
|
||||
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
|
||||
LEFT JOIN assessment_attempt_results AS result
|
||||
ON result.attempt_id = attempt.id AND result.user_id = attempt.user_id
|
||||
WHERE attempt.user_id = sqlc.arg(user_id)
|
||||
AND attempt.specialization = sqlc.arg(specialization)
|
||||
AND attempt.kind = 'root'
|
||||
AND (sqlc.narg(target_grade)::text IS NULL OR attempt.target_grade = sqlc.narg(target_grade)::text)
|
||||
AND attempt.state <> 'insufficient_bank'
|
||||
AND COALESCE(result.result_snapshot->>'not_determined_reason', '')
|
||||
NOT IN ('insufficient_bank', 'sandbox_unavailable')
|
||||
ORDER BY attempt.created_at DESC, attempt.id DESC
|
||||
LIMIT 1
|
||||
FOR SHARE OF attempt;
|
||||
|
||||
-- Counts root attempts only; the caller applies the effective policy's
|
||||
-- configured window and the product's approved accounting scope.
|
||||
-- name: CountRootAssessmentAttemptsSince :one
|
||||
SELECT count(*)::bigint
|
||||
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 = sqlc.arg(user_id)
|
||||
AND attempt.kind = 'root'
|
||||
AND attempt.created_at >= sqlc.arg(since)::timestamptz
|
||||
AND (sqlc.narg(specialization)::text IS NULL OR attempt.specialization = sqlc.narg(specialization)::text)
|
||||
AND attempt.state <> 'insufficient_bank'
|
||||
AND COALESCE(result.result_snapshot->>'not_determined_reason', '')
|
||||
NOT IN ('insufficient_bank', 'sandbox_unavailable');
|
||||
|
||||
-- Lists explicit immutable training bindings for the effective product
|
||||
-- policy. Callers reject more than one matching active binding as ambiguous.
|
||||
-- name: ListCurrentAssessmentTrainingBindings :many
|
||||
SELECT
|
||||
binding.id,
|
||||
binding.category,
|
||||
binding.product_policy_version_id,
|
||||
binding.item_count,
|
||||
binding.manifest_sha256,
|
||||
binding.family_manifest,
|
||||
policy.version AS product_policy_version
|
||||
FROM assessment_training_bank_bindings AS binding
|
||||
JOIN policy_versions AS policy ON policy.id = binding.product_policy_version_id
|
||||
WHERE policy.policy_key = 'product'
|
||||
AND policy.effective_at <= statement_timestamp()
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM policy_versions AS newer
|
||||
WHERE newer.policy_key = 'product'
|
||||
AND newer.effective_at <= statement_timestamp()
|
||||
AND newer.version > policy.version
|
||||
)
|
||||
ORDER BY binding.category, binding.created_at DESC, binding.id;
|
||||
|
||||
-- Reads the exact family membership pinned by a training binding.
|
||||
-- name: ListAssessmentTrainingBindingFamilies :many
|
||||
SELECT
|
||||
family_id,
|
||||
ordinal,
|
||||
family_key,
|
||||
family_version,
|
||||
content_sha256
|
||||
FROM assessment_training_bank_binding_families
|
||||
WHERE binding_id = sqlc.arg(binding_id)
|
||||
ORDER BY ordinal;
|
||||
|
||||
-- Inserts the attempt header. The database guard rechecks the current policy,
|
||||
-- opening or disjoint training binding, and immutable pins.
|
||||
-- name: InsertAssessmentAttempt :exec
|
||||
INSERT INTO assessment_attempts (
|
||||
id,
|
||||
user_id,
|
||||
kind,
|
||||
mode,
|
||||
state,
|
||||
outcome,
|
||||
bank_category,
|
||||
specialization,
|
||||
target_grade,
|
||||
task_language,
|
||||
root_attempt_id,
|
||||
product_policy_version_id,
|
||||
product_policy_version,
|
||||
grading_policy_version_id,
|
||||
opening_id,
|
||||
opening_manifest_sha256,
|
||||
training_binding_id,
|
||||
training_manifest_sha256,
|
||||
bank_version,
|
||||
algorithm_version,
|
||||
created_at,
|
||||
updated_at,
|
||||
expires_at,
|
||||
chain_deadline,
|
||||
idle_timeout_seconds,
|
||||
max_sessions,
|
||||
sessions_used,
|
||||
session_started_at,
|
||||
last_activity_at,
|
||||
version,
|
||||
ended_at
|
||||
) VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(user_id),
|
||||
sqlc.arg(kind),
|
||||
sqlc.arg(mode),
|
||||
sqlc.arg(state),
|
||||
sqlc.narg(outcome),
|
||||
sqlc.arg(bank_category),
|
||||
sqlc.narg(specialization),
|
||||
sqlc.narg(target_grade),
|
||||
sqlc.narg(task_language),
|
||||
sqlc.arg(root_attempt_id),
|
||||
sqlc.arg(product_policy_version_id),
|
||||
sqlc.arg(product_policy_version),
|
||||
sqlc.narg(grading_policy_version_id),
|
||||
sqlc.narg(opening_id),
|
||||
sqlc.narg(opening_manifest_sha256),
|
||||
sqlc.narg(training_binding_id),
|
||||
sqlc.narg(training_manifest_sha256),
|
||||
sqlc.arg(bank_version),
|
||||
sqlc.arg(algorithm_version),
|
||||
sqlc.arg(created_at),
|
||||
sqlc.arg(updated_at),
|
||||
sqlc.arg(expires_at),
|
||||
sqlc.narg(chain_deadline),
|
||||
sqlc.arg(idle_timeout_seconds),
|
||||
sqlc.arg(max_sessions),
|
||||
sqlc.arg(sessions_used),
|
||||
sqlc.arg(session_started_at),
|
||||
sqlc.arg(last_activity_at),
|
||||
sqlc.arg(version),
|
||||
sqlc.narg(ended_at)
|
||||
);
|
||||
|
||||
-- Stores the immutable generated variant and empty answer slot.
|
||||
-- name: InsertAssessmentAttemptItem :exec
|
||||
INSERT INTO assessment_attempt_items (
|
||||
id,
|
||||
attempt_id,
|
||||
ordinal,
|
||||
family_id,
|
||||
family_key,
|
||||
family_version,
|
||||
family_content_sha256,
|
||||
variant,
|
||||
answer,
|
||||
answered_at
|
||||
) VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(attempt_id),
|
||||
sqlc.arg(ordinal),
|
||||
sqlc.arg(family_id),
|
||||
sqlc.arg(family_key),
|
||||
sqlc.arg(family_version),
|
||||
sqlc.arg(family_content_sha256),
|
||||
sqlc.arg(variant),
|
||||
sqlc.narg(answer),
|
||||
sqlc.narg(answered_at)
|
||||
);
|
||||
|
||||
-- Returns a full private attempt only to its candidate.
|
||||
-- name: GetAssessmentAttemptForCandidate :one
|
||||
SELECT
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at
|
||||
FROM assessment_attempts
|
||||
WHERE id = sqlc.arg(id) AND user_id = sqlc.arg(user_id)
|
||||
FOR SHARE;
|
||||
|
||||
-- Reads the immutable attempt kind without locking the row. Session commands
|
||||
-- use this only to decide whether C3 applies before acquiring the row lock.
|
||||
-- name: GetAssessmentAttemptKindForCandidate :one
|
||||
SELECT kind
|
||||
FROM assessment_attempts
|
||||
WHERE id = sqlc.arg(id) AND user_id = sqlc.arg(user_id);
|
||||
|
||||
-- Locks one owner-scoped attempt while a session command performs its CAS.
|
||||
-- name: LockAssessmentAttemptForCandidate :one
|
||||
SELECT
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at
|
||||
FROM assessment_attempts
|
||||
WHERE id = sqlc.arg(id) AND user_id = sqlc.arg(user_id)
|
||||
FOR UPDATE;
|
||||
|
||||
-- Reads chain headers in creation order. The use case verifies root eligibility
|
||||
-- and descending target grades in the domain before it creates a correction.
|
||||
-- name: ListAssessmentAttemptChain :many
|
||||
SELECT
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at
|
||||
FROM assessment_attempts
|
||||
WHERE user_id = sqlc.arg(user_id)
|
||||
AND specialization = sqlc.arg(specialization)
|
||||
AND (id = sqlc.arg(root_attempt_id) OR root_attempt_id = sqlc.arg(root_attempt_id))
|
||||
ORDER BY created_at, id
|
||||
FOR SHARE;
|
||||
|
||||
-- Reads private frozen variants and candidate answer bytes in stable order.
|
||||
-- name: ListAssessmentAttemptItems :many
|
||||
SELECT
|
||||
id, attempt_id, ordinal, family_id, family_key, family_version,
|
||||
family_content_sha256, variant::text AS variant, answer, answered_at
|
||||
FROM assessment_attempt_items
|
||||
WHERE attempt_id = sqlc.arg(attempt_id)
|
||||
ORDER BY ordinal;
|
||||
|
||||
-- Applies a versioned session transition after the attempt row is locked.
|
||||
-- name: UpdateAssessmentAttemptSession :one
|
||||
UPDATE assessment_attempts
|
||||
SET
|
||||
state = sqlc.arg(state),
|
||||
outcome = sqlc.narg(outcome),
|
||||
updated_at = sqlc.arg(updated_at),
|
||||
sessions_used = sqlc.arg(sessions_used),
|
||||
session_started_at = sqlc.arg(session_started_at),
|
||||
last_activity_at = sqlc.arg(last_activity_at),
|
||||
version = sqlc.arg(version),
|
||||
ended_at = sqlc.narg(ended_at)
|
||||
WHERE id = sqlc.arg(id)
|
||||
AND user_id = sqlc.arg(user_id)
|
||||
AND version = sqlc.arg(expected_version)
|
||||
RETURNING
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at;
|
||||
|
||||
-- Stores one final answer before advancing the enclosing attempt version.
|
||||
-- The caller holds the owner-scoped attempt row lock for the surrounding unit.
|
||||
-- name: UpdateAssessmentAttemptItemAnswer :one
|
||||
UPDATE assessment_attempt_items
|
||||
SET answer = sqlc.arg(answer), answered_at = sqlc.arg(answered_at)
|
||||
WHERE attempt_id = sqlc.arg(attempt_id)
|
||||
AND id = sqlc.arg(item_id)
|
||||
AND answer IS NULL
|
||||
RETURNING id;
|
||||
|
||||
-- Applies an answer, expiry, or finalization transition after the attempt row
|
||||
-- is locked. Session limits and all immutable pins remain unchanged.
|
||||
-- name: UpdateAssessmentAttemptTransition :one
|
||||
UPDATE assessment_attempts
|
||||
SET
|
||||
state = sqlc.arg(state),
|
||||
outcome = sqlc.narg(outcome),
|
||||
updated_at = sqlc.arg(updated_at),
|
||||
last_activity_at = sqlc.arg(last_activity_at),
|
||||
version = sqlc.arg(version),
|
||||
ended_at = sqlc.narg(ended_at)
|
||||
WHERE id = sqlc.arg(id)
|
||||
AND user_id = sqlc.arg(user_id)
|
||||
AND version = sqlc.arg(expected_version)
|
||||
RETURNING
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at;
|
||||
|
||||
-- A newly reserved generic idempotency window can replace an expired typed
|
||||
-- outcome before the new immutable response is inserted.
|
||||
-- name: DeleteAssessmentAttemptIdempotencyOutcome :exec
|
||||
DELETE FROM assessment_attempt_idempotency_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
|
||||
-- name: InsertAssessmentAttemptIdempotencyOutcome :exec
|
||||
INSERT INTO assessment_attempt_idempotency_outcomes (
|
||||
scope_hash, operation, status_code, problem_code, response_snapshot,
|
||||
response_schema_version, pending_item_ids, created_at
|
||||
) VALUES (
|
||||
sqlc.arg(scope_hash), sqlc.arg(operation), sqlc.arg(status_code),
|
||||
sqlc.narg(problem_code), sqlc.narg(response_snapshot), 1,
|
||||
sqlc.arg(pending_item_ids)::uuid[], transaction_timestamp()
|
||||
);
|
||||
|
||||
-- name: GetAssessmentAttemptIdempotencyOutcome :one
|
||||
SELECT operation, status_code, problem_code,
|
||||
CAST(COALESCE(response_snapshot::text, ''::text) AS text) AS response_snapshot,
|
||||
pending_item_ids
|
||||
FROM assessment_attempt_idempotency_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
|
||||
-- Stores one immutable candidate-visible result with the decision rationale
|
||||
-- and source versions used by its finalized attempt.
|
||||
-- name: InsertAssessmentAttemptResult :exec
|
||||
INSERT INTO assessment_attempt_results (
|
||||
attempt_id, user_id, result_snapshot, schema_version, kind, mode, outcome,
|
||||
product_policy_version_id, product_policy_version,
|
||||
grading_policy_version_id, opening_id, opening_manifest_sha256,
|
||||
training_binding_id, training_manifest_sha256, bank_version, algorithm_version,
|
||||
rationale_rule, pass_mark_basis_points, scored_items, raw_score, pass_points, decided_at
|
||||
)
|
||||
VALUES (
|
||||
sqlc.arg(attempt_id), sqlc.arg(user_id), sqlc.arg(result_snapshot)::jsonb, 1,
|
||||
sqlc.arg(kind), sqlc.arg(mode), sqlc.arg(outcome),
|
||||
sqlc.arg(product_policy_version_id), sqlc.arg(product_policy_version),
|
||||
sqlc.narg(grading_policy_version_id), sqlc.narg(opening_id), sqlc.narg(opening_manifest_sha256),
|
||||
sqlc.narg(training_binding_id), sqlc.narg(training_manifest_sha256),
|
||||
sqlc.arg(bank_version), sqlc.arg(algorithm_version), sqlc.arg(rationale_rule),
|
||||
sqlc.narg(pass_mark_basis_points), sqlc.narg(scored_items), sqlc.narg(raw_score),
|
||||
sqlc.narg(pass_points), sqlc.arg(decided_at)
|
||||
);
|
||||
|
||||
-- Reads a result only for the owning candidate.
|
||||
-- name: GetAssessmentAttemptResult :one
|
||||
SELECT result_snapshot::text AS result_snapshot
|
||||
FROM assessment_attempt_results
|
||||
WHERE user_id = sqlc.arg(user_id) AND attempt_id = sqlc.arg(attempt_id);
|
||||
@@ -0,0 +1,173 @@
|
||||
-- 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.
|
||||
-- name: ListCurrentAssessmentAvailabilitySelections :many
|
||||
WITH current_policy AS (
|
||||
SELECT id, version
|
||||
FROM policy_versions
|
||||
WHERE policy_key = 'product' AND effective_at <= sqlc.arg(as_of)::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;
|
||||
|
||||
-- Reads an active real attempt without taking the write lock used by create.
|
||||
-- The availability GET never expires or otherwise mutates this row.
|
||||
-- name: GetAssessmentAvailabilityActiveAttempt :one
|
||||
SELECT id, expires_at
|
||||
FROM assessment_attempts
|
||||
WHERE user_id = sqlc.arg(user_id)
|
||||
AND specialization = sqlc.arg(specialization)
|
||||
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;
|
||||
|
||||
-- Reads roots within the policy horizon and the last header in each correction
|
||||
-- chain. It deliberately omits frozen items, answers, and row locks.
|
||||
-- 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.*
|
||||
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 = sqlc.arg(user_id)
|
||||
AND root.specialization = sqlc.arg(specialization)
|
||||
AND root.kind = 'root'
|
||||
AND root.created_at >= sqlc.arg(since)::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;
|
||||
|
||||
-- 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.
|
||||
-- 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 = sqlc.arg(user_id)
|
||||
AND attempt.kind = 'root'
|
||||
AND attempt.state <> 'insufficient_bank'
|
||||
AND attempt.created_at >= sqlc.arg(since)::timestamptz
|
||||
AND attempt.created_at <= sqlc.arg(as_of)::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 >= sqlc.arg(max_attempts)::bigint THEN (
|
||||
SELECT eligible.created_at
|
||||
+ make_interval(secs => sqlc.arg(window_seconds)::double precision)
|
||||
+ interval '1 microsecond'
|
||||
FROM eligible
|
||||
ORDER BY eligible.created_at, eligible.id
|
||||
LIMIT 1
|
||||
OFFSET (total.attempt_count - sqlc.arg(max_attempts)::bigint)
|
||||
) ELSE NULL::timestamptz END AS available_at
|
||||
FROM total;
|
||||
|
||||
-- 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.
|
||||
-- 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 = sqlc.arg(user_id)
|
||||
AND attempt.kind IN ('root', 'corrective')
|
||||
AND attempt.expires_at > sqlc.arg(since)::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 > sqlc.arg(since)::timestamptz
|
||||
ORDER BY disclosed.family_key;
|
||||
@@ -0,0 +1,78 @@
|
||||
-- New outcomes share the generic idempotency row and are counted for the
|
||||
-- attempt's rolling receipt window. Replays bypass this query in the usecase.
|
||||
-- name: CountRecentAssessmentSignalOutcomes :one
|
||||
SELECT
|
||||
count(*)::bigint AS outcome_count,
|
||||
COALESCE(min(received_at), sqlc.arg(since)::timestamptz) AS oldest_at
|
||||
FROM assessment_signal_idempotency_outcomes
|
||||
WHERE
|
||||
attempt_id = sqlc.arg(attempt_id)
|
||||
AND received_at > sqlc.arg(since);
|
||||
|
||||
-- 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.
|
||||
-- name: InsertAssessmentSignalBatch :exec
|
||||
INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count)
|
||||
VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(attempt_id),
|
||||
sqlc.arg(received_at),
|
||||
sqlc.arg(event_count)
|
||||
);
|
||||
|
||||
-- Each inserted event is checked by the database guard against attempt state
|
||||
-- and the aggregate capacity as a second line of defense.
|
||||
-- name: InsertAssessmentSignalEvent :exec
|
||||
INSERT INTO assessment_signal_events (
|
||||
batch_id,
|
||||
attempt_id,
|
||||
ordinal,
|
||||
item_instance_id,
|
||||
kind,
|
||||
occurred_at,
|
||||
duration_ms,
|
||||
size_bytes
|
||||
) VALUES (
|
||||
sqlc.arg(batch_id),
|
||||
sqlc.arg(attempt_id),
|
||||
sqlc.arg(ordinal),
|
||||
sqlc.arg(item_instance_id),
|
||||
sqlc.arg(kind),
|
||||
sqlc.arg(occurred_at),
|
||||
sqlc.narg(duration_ms)::integer,
|
||||
sqlc.narg(size_bytes)::integer
|
||||
);
|
||||
|
||||
-- Count events only for the already owner-locked attempt.
|
||||
-- name: CountAssessmentSignalEvents :one
|
||||
SELECT count(*)::bigint AS event_count
|
||||
FROM assessment_signal_events
|
||||
WHERE attempt_id = sqlc.arg(attempt_id);
|
||||
|
||||
-- The generic reservation has already established that a previous outcome is
|
||||
-- expired before this child is removed and replaced in the same transaction.
|
||||
-- name: DeleteExpiredAssessmentSignalOutcome :exec
|
||||
DELETE FROM assessment_signal_idempotency_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
|
||||
-- Save exactly one immutable response receipt for each live idempotency scope.
|
||||
-- name: InsertAssessmentSignalOutcome :exec
|
||||
INSERT INTO assessment_signal_idempotency_outcomes (
|
||||
scope_hash,
|
||||
attempt_id,
|
||||
status,
|
||||
accepted_events,
|
||||
received_at
|
||||
) VALUES (
|
||||
sqlc.arg(scope_hash),
|
||||
sqlc.arg(attempt_id),
|
||||
sqlc.arg(status),
|
||||
sqlc.arg(accepted_events),
|
||||
sqlc.arg(received_at)
|
||||
);
|
||||
|
||||
-- Read only the receipt associated with the reserved idempotency scope.
|
||||
-- name: GetAssessmentSignalOutcome :one
|
||||
SELECT status, accepted_events, received_at
|
||||
FROM assessment_signal_idempotency_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
@@ -229,6 +229,35 @@ WHERE
|
||||
ORDER BY granted_at DESC, id DESC
|
||||
LIMIT 1;
|
||||
|
||||
-- Keeps the current C3 grant stable through a real assessment transaction.
|
||||
-- Revocation updates this row and therefore waits until the caller commits.
|
||||
-- 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 = sqlc.arg(subject_id)
|
||||
AND purpose = 'c3'
|
||||
AND revoked_at IS NULL
|
||||
ORDER BY granted_at DESC, id DESC
|
||||
LIMIT 1
|
||||
FOR SHARE;
|
||||
|
||||
-- Locks the active registration C1 while its pending registration is applied.
|
||||
-- name: LockRegistrationConsentRecord :one
|
||||
SELECT
|
||||
|
||||
@@ -58,6 +58,34 @@ WHERE
|
||||
AND need_id = sqlc.arg(need_id)
|
||||
AND version = sqlc.arg(version);
|
||||
|
||||
-- Read one bounded newest-first page of current needs. Both the organization
|
||||
-- scope and the tuple cursor are applied before the limit.
|
||||
-- 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 = sqlc.arg(organization_id)
|
||||
AND (
|
||||
sqlc.narg(after_created_at)::timestamptz IS NULL
|
||||
OR (need.created_at, need.id) < (
|
||||
sqlc.narg(after_created_at)::timestamptz,
|
||||
sqlc.narg(after_need_id)::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY need.created_at DESC, need.id DESC
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- The conditional parent update is the compare-and-swap. Appending the
|
||||
-- snapshot is part of the same SQL statement, so a failed insert leaves the
|
||||
-- parent pointer unchanged even before the surrounding transaction rolls
|
||||
@@ -100,3 +128,19 @@ WITH advanced AS (
|
||||
)
|
||||
SELECT appended.snapshot
|
||||
FROM appended;
|
||||
|
||||
-- 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.
|
||||
-- name: SaveOrganizationNeedCreationResult :exec
|
||||
INSERT INTO organization_need_creation_results (scope_hash, snapshot)
|
||||
VALUES (sqlc.arg(scope_hash), sqlc.arg(snapshot)::jsonb)
|
||||
ON CONFLICT (scope_hash) DO UPDATE
|
||||
SET snapshot = excluded.snapshot;
|
||||
|
||||
-- Read only the immutable original response. The current need may have moved
|
||||
-- to a later version since this result was created.
|
||||
-- name: GetOrganizationNeedCreationResult :one
|
||||
SELECT snapshot::text AS snapshot
|
||||
FROM organization_need_creation_results
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
@@ -97,6 +97,32 @@ WHERE
|
||||
AND membership.user_id = sqlc.arg(user_id)
|
||||
AND membership.state = 'active';
|
||||
|
||||
-- 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.
|
||||
-- name: LockActiveMembership :one
|
||||
WITH locked_organization AS MATERIALIZED (
|
||||
SELECT organizations.id
|
||||
FROM organizations
|
||||
WHERE organizations.id = sqlc.arg(organization_id)
|
||||
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 = sqlc.arg(user_id)
|
||||
AND membership.state = 'active'
|
||||
FOR SHARE OF membership;
|
||||
|
||||
-- Changes the profile of an organization over the version the caller read
|
||||
-- and advances the version in the same statement. It names no verification
|
||||
-- column, so a profile update cannot move the trust level. The change
|
||||
|
||||
@@ -6,6 +6,39 @@
|
||||
-- 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.
|
||||
-- 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 = sqlc.arg(user_id);
|
||||
|
||||
-- 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
|
||||
@@ -319,3 +352,74 @@ WHERE
|
||||
hidden.user_id = effective.user_id
|
||||
AND hidden.organization_id = sqlc.arg(organization_id)
|
||||
);
|
||||
|
||||
-- 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.
|
||||
-- name: InsertCandidateCardAccessEvent :exec
|
||||
INSERT INTO candidate_card_access_events (
|
||||
id,
|
||||
candidate_id,
|
||||
organization_id,
|
||||
actor_id,
|
||||
kind,
|
||||
field_codes,
|
||||
occurred_at
|
||||
) VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(candidate_id),
|
||||
sqlc.arg(organization_id),
|
||||
sqlc.narg(actor_id),
|
||||
sqlc.arg(kind),
|
||||
sqlc.arg(field_codes),
|
||||
sqlc.arg(occurred_at)
|
||||
);
|
||||
|
||||
-- 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.
|
||||
-- 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 = sqlc.arg(candidate_id)
|
||||
AND (
|
||||
sqlc.narg(after_occurred_at)::timestamptz IS NULL
|
||||
OR (candidate_card_access_events.occurred_at, candidate_card_access_events.id) < (
|
||||
sqlc.narg(after_occurred_at)::timestamptz,
|
||||
sqlc.narg(after_id)::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY candidate_card_access_events.occurred_at DESC, candidate_card_access_events.id DESC
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- 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.
|
||||
-- name: CandidateCanSeeOrganization :one
|
||||
SELECT organizations.id, organizations.name
|
||||
FROM organizations
|
||||
WHERE organizations.id = sqlc.arg(organization_id)
|
||||
AND (
|
||||
EXISTS (
|
||||
SELECT 1 FROM candidate_card_access_events
|
||||
WHERE candidate_card_access_events.candidate_id = sqlc.arg(user_id)
|
||||
AND candidate_card_access_events.organization_id = organizations.id
|
||||
)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM candidate_hidden_organizations
|
||||
WHERE candidate_hidden_organizations.user_id = sqlc.arg(user_id)
|
||||
AND candidate_hidden_organizations.organization_id = organizations.id
|
||||
)
|
||||
);
|
||||
@@ -0,0 +1,181 @@
|
||||
-- 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.
|
||||
-- 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 = sqlc.arg(organization_id)
|
||||
)
|
||||
ORDER BY effective.user_id, claim.kind, claim.ordinal;
|
||||
|
||||
-- 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.
|
||||
-- name: LockCandidateAccountForView :one
|
||||
SELECT users.id
|
||||
FROM users
|
||||
WHERE users.id = sqlc.arg(candidate_id)
|
||||
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.
|
||||
-- name: LockCurrentC2ForView :one
|
||||
SELECT consent_records.id
|
||||
FROM consent_records
|
||||
WHERE
|
||||
consent_records.subject_id = sqlc.arg(candidate_id)
|
||||
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 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.
|
||||
-- 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 = sqlc.arg(candidate_id)
|
||||
AND candidate_publications.state = 'published'
|
||||
AND candidate_publications.consent_record_id = sqlc.arg(consent_record_id)
|
||||
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 = sqlc.arg(organization_id)
|
||||
)
|
||||
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.
|
||||
-- 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 = sqlc.arg(candidate_id)
|
||||
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;
|
||||
|
||||
-- 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.
|
||||
-- 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 = sqlc.arg(candidate_id)
|
||||
ORDER BY effective.user_id, claim.kind, claim.ordinal;
|
||||
@@ -0,0 +1,154 @@
|
||||
-- Case numbers are monotonic and never reused. Sequence gaps on a rolled-back
|
||||
-- request are expected and do not expose request contents.
|
||||
-- name: NextSupportCaseNumber :one
|
||||
WITH next_value AS MATERIALIZED (
|
||||
SELECT nextval('support_case_number_seq') AS value
|
||||
)
|
||||
SELECT
|
||||
'SC-' || sqlc.arg(utc_year)::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;
|
||||
|
||||
-- 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.
|
||||
-- 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 (
|
||||
sqlc.arg(id), sqlc.arg(case_number), sqlc.arg(owner_id), sqlc.arg(case_type),
|
||||
sqlc.arg(status), sqlc.arg(description), sqlc.narg(object_type), sqlc.narg(object_id),
|
||||
sqlc.narg(assessment_specialization), sqlc.narg(assessment_grade),
|
||||
sqlc.narg(complaint_reason), sqlc.narg(rubric_version), sqlc.narg(rubric_opening_id),
|
||||
sqlc.narg(rubric_policy_version_id), sqlc.arg(target_business_days),
|
||||
sqlc.arg(target_due_at), sqlc.narg(target_answered_at), sqlc.arg(target_policy_version),
|
||||
sqlc.arg(target_calendar_version), sqlc.narg(decision_outcome), sqlc.narg(decision_reason),
|
||||
sqlc.narg(decision_at), sqlc.arg(created_at), sqlc.arg(updated_at)
|
||||
)
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- name: InsertSupportCaseEvent :exec
|
||||
INSERT INTO support_case_events (
|
||||
case_id, sequence, event_kind, actor_kind, occurred_at, status, message
|
||||
) VALUES (
|
||||
sqlc.arg(case_id), sqlc.arg(sequence), sqlc.arg(event_kind), sqlc.arg(actor_kind),
|
||||
sqlc.arg(occurred_at), sqlc.narg(status), sqlc.narg(message)
|
||||
);
|
||||
|
||||
-- Reads a full owner-scoped record. Object values are identifiers only.
|
||||
-- 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 = sqlc.arg(case_id) AND owner_id = sqlc.arg(owner_id);
|
||||
|
||||
-- Reads the immutable public history only after the case owner has matched.
|
||||
-- name: ReadSupportCaseEvents :many
|
||||
SELECT sequence, event_kind, actor_kind, occurred_at, status, message
|
||||
FROM support_case_events
|
||||
WHERE case_id = sqlc.arg(case_id)
|
||||
ORDER BY sequence;
|
||||
|
||||
-- Owner-scoped newest-first list. It omits descriptions, complaint reason,
|
||||
-- and event history. The tuple cursor matches the composite sort key.
|
||||
-- name: ListOwnedSupportCases :many
|
||||
WITH cursor_input AS MATERIALIZED (
|
||||
SELECT
|
||||
sqlc.narg(after_created_at)::timestamptz AS after_created_at,
|
||||
sqlc.narg(after_id)::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 = sqlc.arg(owner_id)
|
||||
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 sqlc.arg(row_limit);
|
||||
|
||||
-- No raw Idempotency-Key or request body reaches these statements. Failure
|
||||
-- responses pass {} as case_snapshot and the CASE stores SQL NULL instead.
|
||||
-- name: DeleteSupportCaseCreateOutcome :exec
|
||||
DELETE FROM support_case_create_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
|
||||
-- name: InsertSupportCaseCreateOutcome :exec
|
||||
INSERT INTO support_case_create_outcomes (
|
||||
scope_hash, outcome_kind, case_snapshot, target_was_late, created_at
|
||||
) VALUES (
|
||||
sqlc.arg(scope_hash), sqlc.arg(outcome_kind),
|
||||
CASE WHEN sqlc.arg(outcome_kind)::text = 'created' THEN sqlc.arg(case_snapshot)::jsonb END,
|
||||
CASE WHEN sqlc.arg(outcome_kind)::text = 'created' THEN sqlc.arg(target_was_late)::boolean END,
|
||||
sqlc.arg(created_at)
|
||||
);
|
||||
|
||||
-- name: ReadSupportCaseCreateOutcome :one
|
||||
SELECT outcome_kind, coalesce(case_snapshot::text, '') AS case_snapshot, target_was_late
|
||||
FROM support_case_create_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
|
||||
-- Serialize per-owner budget checks even before the first event exists.
|
||||
-- name: LockSupportCaseRequestBudget :exec
|
||||
SELECT pg_advisory_xact_lock(
|
||||
hashtextextended('lincodex.support.case.requests:' || sqlc.arg(owner_id)::uuid::text, 0)
|
||||
);
|
||||
|
||||
-- Read the latest serialized event so a temporarily regressing application
|
||||
-- clock cannot make the next request fall before an event already counted.
|
||||
-- name: LatestSupportCaseRequestEvent :one
|
||||
SELECT requested_at
|
||||
FROM support_case_request_events
|
||||
WHERE owner_id = sqlc.arg(owner_id)
|
||||
ORDER BY requested_at DESC, id DESC
|
||||
LIMIT 1;
|
||||
|
||||
-- Keep up to the maximum supported window, regardless of the current policy.
|
||||
-- The bounded delete prevents one create from doing unbounded cleanup work.
|
||||
-- name: PruneSupportCaseRequestEvents :execrows
|
||||
WITH expired AS MATERIALIZED (
|
||||
SELECT source.id
|
||||
FROM support_case_request_events AS source
|
||||
WHERE source.owner_id = sqlc.arg(owner_id)
|
||||
AND source.requested_at <= sqlc.arg(at)::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;
|
||||
|
||||
-- The strict lower boundary means an event exactly one window old no longer
|
||||
-- counts. The use case derives Retry-After from first_in_window.
|
||||
-- name: CountSupportCaseRequestEvents :one
|
||||
SELECT count(*)::bigint AS event_count, min(requested_at) AS first_in_window
|
||||
FROM support_case_request_events
|
||||
WHERE owner_id = sqlc.arg(owner_id)
|
||||
AND requested_at > sqlc.arg(window_start)::timestamptz
|
||||
AND requested_at <= sqlc.arg(at)::timestamptz;
|
||||
|
||||
-- name: InsertSupportCaseRequestEvent :exec
|
||||
INSERT INTO support_case_request_events (owner_id, requested_at)
|
||||
VALUES (sqlc.arg(owner_id), sqlc.arg(requested_at));
|
||||
@@ -0,0 +1,53 @@
|
||||
-- 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.
|
||||
-- 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 = sqlc.arg(specialization)
|
||||
AND binding.grade = sqlc.arg(grade)
|
||||
ORDER BY opening.category;
|
||||
Reference in new issue
Block a user