feat: persist candidate questionnaires and enforce company quotas

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 15:47:10 +03:00
1 parent 73c7caa225
commit 3a61a8e8bb
51 files changed
+6280 -38

No files matched your search

@@ -0,0 +1,323 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: company_quota.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const countCompanyCardViewQuotaWindow = `-- name: CountCompanyCardViewQuotaWindow :one
SELECT
count(*)::bigint AS usage_count,
min(last_seen_at) AS earliest_at
FROM company_card_view_quota_usage
WHERE
organization_id = $1
AND last_seen_at > $2
`
type CountCompanyCardViewQuotaWindowParams struct {
OrganizationID pgtype.UUID
WindowStart pgtype.Timestamptz
}
type CountCompanyCardViewQuotaWindowRow struct {
UsageCount int64
EarliestAt interface{}
}
func (q *Queries) CountCompanyCardViewQuotaWindow(ctx context.Context, arg CountCompanyCardViewQuotaWindowParams) (CountCompanyCardViewQuotaWindowRow, error) {
row := q.db.QueryRow(ctx, countCompanyCardViewQuotaWindow, arg.OrganizationID, arg.WindowStart)
var i CountCompanyCardViewQuotaWindowRow
err := row.Scan(&i.UsageCount, &i.EarliestAt)
return i, err
}
const countCompanyInvitationQuotaWindow = `-- name: CountCompanyInvitationQuotaWindow :one
SELECT
count(*)::bigint AS usage_count,
min(reserved_at) AS earliest_at
FROM company_invitation_quota_usage
WHERE
organization_id = $1
AND reserved_at > $2
`
type CountCompanyInvitationQuotaWindowParams struct {
OrganizationID pgtype.UUID
WindowStart pgtype.Timestamptz
}
type CountCompanyInvitationQuotaWindowRow struct {
UsageCount int64
EarliestAt interface{}
}
func (q *Queries) CountCompanyInvitationQuotaWindow(ctx context.Context, arg CountCompanyInvitationQuotaWindowParams) (CountCompanyInvitationQuotaWindowRow, error) {
row := q.db.QueryRow(ctx, countCompanyInvitationQuotaWindow, arg.OrganizationID, arg.WindowStart)
var i CountCompanyInvitationQuotaWindowRow
err := row.Scan(&i.UsageCount, &i.EarliestAt)
return i, err
}
const deleteExpiredCompanyCardViewQuotaUsage = `-- name: DeleteExpiredCompanyCardViewQuotaUsage :execrows
WITH expired AS (
SELECT quota_usage.organization_id, quota_usage.candidate_id
FROM company_card_view_quota_usage AS quota_usage
WHERE
quota_usage.organization_id = $1
AND quota_usage.last_seen_at <= $2
ORDER BY quota_usage.last_seen_at, quota_usage.candidate_id
LIMIT $3::integer
)
DELETE FROM company_card_view_quota_usage AS usage
USING expired
WHERE
usage.organization_id = expired.organization_id
AND usage.candidate_id = expired.candidate_id
`
type DeleteExpiredCompanyCardViewQuotaUsageParams struct {
OrganizationID pgtype.UUID
WindowStart pgtype.Timestamptz
RowLimit int32
}
func (q *Queries) DeleteExpiredCompanyCardViewQuotaUsage(ctx context.Context, arg DeleteExpiredCompanyCardViewQuotaUsageParams) (int64, error) {
result, err := q.db.Exec(ctx, deleteExpiredCompanyCardViewQuotaUsage, arg.OrganizationID, arg.WindowStart, arg.RowLimit)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const findCompanyCardViewQuotaUsage = `-- name: FindCompanyCardViewQuotaUsage :one
SELECT last_seen_at
FROM company_card_view_quota_usage
WHERE
organization_id = $1
AND candidate_id = $2
FOR UPDATE
`
type FindCompanyCardViewQuotaUsageParams struct {
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
}
func (q *Queries) FindCompanyCardViewQuotaUsage(ctx context.Context, arg FindCompanyCardViewQuotaUsageParams) (pgtype.Timestamptz, error) {
row := q.db.QueryRow(ctx, findCompanyCardViewQuotaUsage, arg.OrganizationID, arg.CandidateID)
var last_seen_at pgtype.Timestamptz
err := row.Scan(&last_seen_at)
return last_seen_at, err
}
const findCompanyInvitationQuotaUsage = `-- name: FindCompanyInvitationQuotaUsage :one
SELECT invitation_id
FROM company_invitation_quota_usage
WHERE
organization_id = $1
AND invitation_id = $2
FOR UPDATE
`
type FindCompanyInvitationQuotaUsageParams struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
}
func (q *Queries) FindCompanyInvitationQuotaUsage(ctx context.Context, arg FindCompanyInvitationQuotaUsageParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, findCompanyInvitationQuotaUsage, arg.OrganizationID, arg.InvitationID)
var invitation_id pgtype.UUID
err := row.Scan(&invitation_id)
return invitation_id, err
}
const insertCompanyInvitationQuotaUsage = `-- name: InsertCompanyInvitationQuotaUsage :exec
INSERT INTO company_invitation_quota_usage (
organization_id,
invitation_id,
reserved_at,
policy_version_id,
verification_level,
verification_basis,
verification_changed_at,
quota_tier
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8
)
`
type InsertCompanyInvitationQuotaUsageParams struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
ReservedAt pgtype.Timestamptz
PolicyVersionID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
QuotaTier string
}
func (q *Queries) InsertCompanyInvitationQuotaUsage(ctx context.Context, arg InsertCompanyInvitationQuotaUsageParams) error {
_, err := q.db.Exec(ctx, insertCompanyInvitationQuotaUsage,
arg.OrganizationID,
arg.InvitationID,
arg.ReservedAt,
arg.PolicyVersionID,
arg.VerificationLevel,
arg.VerificationBasis,
arg.VerificationChangedAt,
arg.QuotaTier,
)
return err
}
const lockCompanyQuotaOrganization = `-- name: LockCompanyQuotaOrganization :one
SELECT
id,
verification_level,
verification_basis,
verification_changed_at
FROM organizations
WHERE id = $1
FOR UPDATE
`
type LockCompanyQuotaOrganizationRow struct {
ID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
}
// Writers lock the organization first, then invitation/card-view state, and
// finally usage rows. The organization lock serializes quota decisions for
// the tenant and makes the subsequent count and insert atomic.
func (q *Queries) LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error) {
row := q.db.QueryRow(ctx, lockCompanyQuotaOrganization, organizationID)
var i LockCompanyQuotaOrganizationRow
err := row.Scan(
&i.ID,
&i.VerificationLevel,
&i.VerificationBasis,
&i.VerificationChangedAt,
)
return i, err
}
const refreshCompanyCardViewQuotaUsage = `-- name: RefreshCompanyCardViewQuotaUsage :execrows
UPDATE company_card_view_quota_usage
SET
last_seen_at = greatest(last_seen_at, $1),
policy_version_id = $2,
verification_level = $3,
verification_basis = $4,
verification_changed_at = $5,
quota_tier = $6
WHERE
organization_id = $7
AND candidate_id = $8
AND last_seen_at > $9
`
type RefreshCompanyCardViewQuotaUsageParams struct {
LastSeenAt pgtype.Timestamptz
PolicyVersionID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
QuotaTier string
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
WindowStart pgtype.Timestamptz
}
func (q *Queries) RefreshCompanyCardViewQuotaUsage(ctx context.Context, arg RefreshCompanyCardViewQuotaUsageParams) (int64, error) {
result, err := q.db.Exec(ctx, refreshCompanyCardViewQuotaUsage,
arg.LastSeenAt,
arg.PolicyVersionID,
arg.VerificationLevel,
arg.VerificationBasis,
arg.VerificationChangedAt,
arg.QuotaTier,
arg.OrganizationID,
arg.CandidateID,
arg.WindowStart,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const saveCompanyCardViewQuotaUsage = `-- name: SaveCompanyCardViewQuotaUsage :exec
INSERT INTO company_card_view_quota_usage (
organization_id,
candidate_id,
last_seen_at,
policy_version_id,
verification_level,
verification_basis,
verification_changed_at,
quota_tier
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8
)
ON CONFLICT (organization_id, candidate_id)
DO UPDATE SET
last_seen_at = greatest(
company_card_view_quota_usage.last_seen_at,
EXCLUDED.last_seen_at
),
policy_version_id = EXCLUDED.policy_version_id,
verification_level = EXCLUDED.verification_level,
verification_basis = EXCLUDED.verification_basis,
verification_changed_at = EXCLUDED.verification_changed_at,
quota_tier = EXCLUDED.quota_tier
`
type SaveCompanyCardViewQuotaUsageParams struct {
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
LastSeenAt pgtype.Timestamptz
PolicyVersionID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
QuotaTier string
}
func (q *Queries) SaveCompanyCardViewQuotaUsage(ctx context.Context, arg SaveCompanyCardViewQuotaUsageParams) error {
_, err := q.db.Exec(ctx, saveCompanyCardViewQuotaUsage,
arg.OrganizationID,
arg.CandidateID,
arg.LastSeenAt,
arg.PolicyVersionID,
arg.VerificationLevel,
arg.VerificationBasis,
arg.VerificationChangedAt,
arg.QuotaTier,
)
return err
}
@@ -16,6 +16,16 @@ type AccountDeletionRequest struct {
CompletedAt pgtype.Timestamptz
}
type AssessmentCategoryCatalogBinding struct {
OpeningID pgtype.UUID
Specialization string
Grade string
TaskLanguages []string
PublishedManifestSha256 []byte
ReviewedBy string
ReviewedAt pgtype.Timestamptz
}
type AssessmentCategoryOpening struct {
ID pgtype.UUID
Category string
@@ -124,6 +134,25 @@ type CandidatePublication struct {
UpdatedAt pgtype.Timestamptz
}
type CandidateQuestionnaire struct {
UserID pgtype.UUID
Version int64
WorkFormats []string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type CandidateQuestionnaireSpecialization struct {
UserID pgtype.UUID
Ordinal int16
Specialization string
SelfAssessedGrade string
TaskLanguages []string
Stack []string
CommercialMonths pgtype.Int4
AcademicMonths pgtype.Int4
}
type CandidateSearchStatus struct {
UserID pgtype.UUID
Status string
@@ -135,6 +164,28 @@ type CandidateSearchStatus struct {
UpdatedAt pgtype.Timestamptz
}
type CompanyCardViewQuotaUsage struct {
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
LastSeenAt pgtype.Timestamptz
PolicyVersionID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
QuotaTier string
}
type CompanyInvitationQuotaUsage struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
ReservedAt pgtype.Timestamptz
PolicyVersionID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
QuotaTier string
}
type ConsentRecord struct {
ID pgtype.UUID
SubjectID pgtype.UUID
@@ -17,6 +17,8 @@ type Querier interface {
// Saving a profile advances onboarding only from that exact step. A retry or
// a save after a later step is already stored never regresses onboarding.
AdvanceCandidateOnboardingAfterProfile(ctx context.Context, arg AdvanceCandidateOnboardingAfterProfileParams) error
// A questionnaire save advances onboarding only from its own step.
AdvanceCandidateOnboardingAfterQuestionnaire(ctx context.Context, arg AdvanceCandidateOnboardingAfterQuestionnaireParams) error
// Advances the version over the one the caller read, in the same statement.
// The row lock it takes serializes concurrent saves of one profile. The update
// time never moves back: an application clock behind the stored time (clock
@@ -25,6 +27,9 @@ type Querier interface {
// returns for a stale version or for an account without a profile, which the
// caller answers as a version conflict.
AdvanceCandidateProfileVersion(ctx context.Context, arg AdvanceCandidateProfileVersionParams) (CandidateProfile, error)
// Advances an existing questionnaire only at the version read by the caller.
// The row lock serializes saves for one user; a stale writer returns no row.
AdvanceCandidateQuestionnaireVersion(ctx context.Context, arg AdvanceCandidateQuestionnaireVersionParams) (CandidateQuestionnaire, error)
// Starts a new registration of an unverified account without touching its
// credentials, scenario, or onboarding step: the new registration carries
// them on its verification token. Advances the registration version, which
@@ -110,6 +115,8 @@ type Querier interface {
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, 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)
CountCompanyInvitationQuotaWindow(ctx context.Context, arg CountCompanyInvitationQuotaWindowParams) (CountCompanyInvitationQuotaWindowRow, error)
// 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)
@@ -127,6 +134,10 @@ type Querier interface {
// Replaces the current explicit decisions with those in the new profile.
// The versioned profile row is advanced first in this same transaction.
DeleteCandidateProfileOverlapConfirmations(ctx context.Context, userID pgtype.UUID) error
// Replaces all specialization answers after the version row advanced in the
// same transaction.
DeleteCandidateQuestionnaireSpecializations(ctx context.Context, userID pgtype.UUID) 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
// Deletes one batch of accounts that stayed unverified since before cutoff,
@@ -165,6 +176,8 @@ type Querier interface {
// NULL retry_at. due_at keeps the deadline. The same guard as the
// completion applies.
FailScheduledJob(ctx context.Context, arg FailScheduledJobParams) (int64, error)
FindCompanyCardViewQuotaUsage(ctx context.Context, arg FindCompanyCardViewQuotaUsageParams) (pgtype.Timestamptz, error)
FindCompanyInvitationQuotaUsage(ctx context.Context, arg FindCompanyInvitationQuotaUsageParams) (pgtype.UUID, error)
// Returns the newest open reservation of a delivery under a provider account
// made at or after reserved_since. A retry of the delivery inside the
// provider's idempotency window reuses it instead of counting again.
@@ -260,6 +273,10 @@ 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)
// 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.
InsertAssessmentCategoryCatalogBinding(ctx context.Context, arg InsertAssessmentCategoryCatalogBindingParams) error
// Stores an opening. The insert trigger derives required_families from the
// policy document and counts the published families, and the coverage CHECK
// refuses the row when they are fewer; both numbers from the caller are
@@ -301,8 +318,13 @@ type Querier interface {
// one is answered as a version conflict. The foreign key refuses a record
// that is not a C2 record of this account.
InsertCandidatePublication(ctx context.Context, arg InsertCandidatePublicationParams) (InsertCandidatePublicationRow, error)
// Creates the first saved questionnaire. A missing row is version zero;
// concurrent first saves race on the primary key and exactly one returns a row.
InsertCandidateQuestionnaire(ctx context.Context, arg InsertCandidateQuestionnaireParams) (CandidateQuestionnaire, error)
InsertCandidateQuestionnaireSpecialization(ctx context.Context, arg InsertCandidateQuestionnaireSpecializationParams) error
// Stores the first status at version 1; no row returns when one exists.
InsertCandidateSearchStatus(ctx context.Context, arg InsertCandidateSearchStatusParams) (InsertCandidateSearchStatusRow, error)
InsertCompanyInvitationQuotaUsage(ctx context.Context, arg InsertCompanyInvitationQuotaUsageParams) error
// Records a grant of C1, C2, C3, or C5. An unrevoked record of the same
// subject, purpose, and text version already exists when no row returns;
// the insert then changes nothing and does not abort the transaction.
@@ -384,6 +406,10 @@ type Querier interface {
// the last record of the previous page.
ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, 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)
// Lists the organizations where an account has an active membership,
// newest membership first. The page continues after the (membership
@@ -413,6 +439,10 @@ type Querier interface {
// canceled, or reclaimed after the lease expired. While the lock is held,
// other workers skip the row, so the handler never runs twice at once.
LockClaimedScheduledJob(ctx context.Context, arg LockClaimedScheduledJobParams) (int64, error)
// Writers lock the organization first, then invitation/card-view state, and
// 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)
// 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
@@ -496,6 +526,9 @@ type Querier interface {
// snapshot. The effective state is computed from them: published only while
// consent_revoked_at is NULL. No row means the candidate never published.
ReadCandidatePublication(ctx context.Context, userID pgtype.UUID) (ReadCandidatePublicationRow, error)
// Reads the aggregate and its ordered specializations in one statement so a
// response never pairs a version with another version's answers.
ReadCandidateQuestionnaire(ctx context.Context, userID pgtype.UUID) (ReadCandidateQuestionnaireRow, error)
// No row means the status was never set, which reads as not looking. The
// lapse is computed by the caller from lapses_at and its clock and is never
// written.
@@ -507,6 +540,10 @@ type Querier interface {
// unpublished one. Every organization-facing read of a publication starts
// from this shape.
ReadPublicationVisibleToOrganization(ctx context.Context, arg ReadPublicationVisibleToOrganizationParams) (ReadPublicationVisibleToOrganizationRow, error)
// Lists the exact published bank manifest while the category advisory lock is
// held by OpenCategory. Published families have passed the independent-review
// constraint before this read.
ReadPublishedAssessmentCategoryManifest(ctx context.Context, category string) ([]ReadPublishedAssessmentCategoryManifestRow, 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
@@ -534,6 +571,7 @@ type Querier interface {
RecordDeliveryFailure(ctx context.Context, arg RecordDeliveryFailureParams) (string, error)
// Records the latest settled outcome of a send under the reservation.
RecordMailQuotaOutcome(ctx context.Context, arg RecordMailQuotaOutcomeParams) (int64, error)
RefreshCompanyCardViewQuotaUsage(ctx context.Context, arg RefreshCompanyCardViewQuotaUsageParams) (int64, error)
// Gives a claimed delivery back without changing it, so the next pass may
// claim it. It matches only the lease of lease_owner: a delivery that another
// worker took over after the lease expired is left alone.
@@ -568,6 +606,7 @@ type Querier interface {
RevokeContactConsentRecords(ctx context.Context, arg RevokeContactConsentRecordsParams) ([]RevokeContactConsentRecordsRow, error)
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
SaveCompanyCardViewQuotaUsage(ctx context.Context, arg SaveCompanyCardViewQuotaUsageParams) error
// Stores the immutable domain snapshot of a successful create command. The
// generic idempotency row and this result are committed with the organization
// and owner membership. A reused expired scope replaces the snapshot in the
@@ -0,0 +1,403 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: questionnaire.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const advanceCandidateOnboardingAfterQuestionnaire = `-- name: AdvanceCandidateOnboardingAfterQuestionnaire :exec
UPDATE users
SET
onboarding_step = 'candidate_assessment',
version = users.version + 1,
updated_at = GREATEST(users.updated_at, $1::timestamptz)
WHERE
users.id = $2
AND users.scenario = 'candidate'
AND users.email_verified_at IS NOT NULL
AND users.onboarding_step = 'candidate_questionnaire'
`
type AdvanceCandidateOnboardingAfterQuestionnaireParams struct {
At pgtype.Timestamptz
UserID pgtype.UUID
}
// A questionnaire save advances onboarding only from its own step.
func (q *Queries) AdvanceCandidateOnboardingAfterQuestionnaire(ctx context.Context, arg AdvanceCandidateOnboardingAfterQuestionnaireParams) error {
_, err := q.db.Exec(ctx, advanceCandidateOnboardingAfterQuestionnaire, arg.At, arg.UserID)
return err
}
const advanceCandidateQuestionnaireVersion = `-- name: AdvanceCandidateQuestionnaireVersion :one
UPDATE candidate_questionnaires
SET
version = candidate_questionnaires.version + 1,
work_formats = $1,
updated_at = GREATEST(candidate_questionnaires.updated_at, $2::timestamptz)
WHERE
candidate_questionnaires.user_id = $3
AND candidate_questionnaires.version = $4
RETURNING user_id, version, work_formats, created_at, updated_at
`
type AdvanceCandidateQuestionnaireVersionParams struct {
WorkFormats []string
At pgtype.Timestamptz
UserID pgtype.UUID
ExpectedVersion int64
}
// Advances an existing questionnaire only at the version read by the caller.
// The row lock serializes saves for one user; a stale writer returns no row.
func (q *Queries) AdvanceCandidateQuestionnaireVersion(ctx context.Context, arg AdvanceCandidateQuestionnaireVersionParams) (CandidateQuestionnaire, error) {
row := q.db.QueryRow(ctx, advanceCandidateQuestionnaireVersion,
arg.WorkFormats,
arg.At,
arg.UserID,
arg.ExpectedVersion,
)
var i CandidateQuestionnaire
err := row.Scan(
&i.UserID,
&i.Version,
&i.WorkFormats,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const deleteCandidateQuestionnaireSpecializations = `-- name: DeleteCandidateQuestionnaireSpecializations :exec
DELETE FROM candidate_questionnaire_specializations
WHERE user_id = $1
`
// Replaces all specialization answers after the version row advanced in the
// same transaction.
func (q *Queries) DeleteCandidateQuestionnaireSpecializations(ctx context.Context, userID pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteCandidateQuestionnaireSpecializations, userID)
return err
}
const insertAssessmentCategoryCatalogBinding = `-- name: InsertAssessmentCategoryCatalogBinding :exec
INSERT INTO assessment_category_catalog_bindings (
opening_id,
specialization,
grade,
task_languages,
published_manifest_sha256,
reviewed_by,
reviewed_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
clock_timestamp()
)
`
type InsertAssessmentCategoryCatalogBindingParams struct {
OpeningID pgtype.UUID
Specialization string
Grade string
TaskLanguages []string
PublishedManifestSha256 []byte
ReviewedBy string
}
// 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.
func (q *Queries) InsertAssessmentCategoryCatalogBinding(ctx context.Context, arg InsertAssessmentCategoryCatalogBindingParams) error {
_, err := q.db.Exec(ctx, insertAssessmentCategoryCatalogBinding,
arg.OpeningID,
arg.Specialization,
arg.Grade,
arg.TaskLanguages,
arg.PublishedManifestSha256,
arg.ReviewedBy,
)
return err
}
const insertCandidateQuestionnaire = `-- name: InsertCandidateQuestionnaire :one
INSERT INTO candidate_questionnaires (
user_id,
version,
work_formats,
created_at,
updated_at
) VALUES (
$1,
1,
$2,
$3::timestamptz,
$3::timestamptz
)
ON CONFLICT (user_id) DO NOTHING
RETURNING user_id, version, work_formats, created_at, updated_at
`
type InsertCandidateQuestionnaireParams struct {
UserID pgtype.UUID
WorkFormats []string
At pgtype.Timestamptz
}
// Creates the first saved questionnaire. A missing row is version zero;
// concurrent first saves race on the primary key and exactly one returns a row.
func (q *Queries) InsertCandidateQuestionnaire(ctx context.Context, arg InsertCandidateQuestionnaireParams) (CandidateQuestionnaire, error) {
row := q.db.QueryRow(ctx, insertCandidateQuestionnaire, arg.UserID, arg.WorkFormats, arg.At)
var i CandidateQuestionnaire
err := row.Scan(
&i.UserID,
&i.Version,
&i.WorkFormats,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const insertCandidateQuestionnaireSpecialization = `-- name: InsertCandidateQuestionnaireSpecialization :exec
INSERT INTO candidate_questionnaire_specializations (
user_id,
ordinal,
specialization,
self_assessed_grade,
task_languages,
stack,
commercial_months,
academic_months
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8
)
`
type InsertCandidateQuestionnaireSpecializationParams struct {
UserID pgtype.UUID
Ordinal int16
Specialization string
SelfAssessedGrade string
TaskLanguages []string
Stack []string
CommercialMonths pgtype.Int4
AcademicMonths pgtype.Int4
}
func (q *Queries) InsertCandidateQuestionnaireSpecialization(ctx context.Context, arg InsertCandidateQuestionnaireSpecializationParams) error {
_, err := q.db.Exec(ctx, insertCandidateQuestionnaireSpecialization,
arg.UserID,
arg.Ordinal,
arg.Specialization,
arg.SelfAssessedGrade,
arg.TaskLanguages,
arg.Stack,
arg.CommercialMonths,
arg.AcademicMonths,
)
return err
}
const listCurrentSpecializationAvailability = `-- name: ListCurrentSpecializationAvailability :many
WITH current_policy AS (
SELECT id
FROM policy_versions
WHERE policy_key = 'product' AND effective_at <= statement_timestamp()
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,
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 opening.category
`
type ListCurrentSpecializationAvailabilityRow struct {
OpeningID pgtype.UUID
Category string
PolicyVersionID pgtype.UUID
RequiredFamilies int32
PublishedCount int32
EffectivePolicyID pgtype.UUID
Specialization string
Grade string
TaskLanguages []string
PublishedManifestSha256 []byte
PublishedManifest string
}
// 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.
func (q *Queries) ListCurrentSpecializationAvailability(ctx context.Context) ([]ListCurrentSpecializationAvailabilityRow, error) {
rows, err := q.db.Query(ctx, listCurrentSpecializationAvailability)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListCurrentSpecializationAvailabilityRow
for rows.Next() {
var i ListCurrentSpecializationAvailabilityRow
if err := rows.Scan(
&i.OpeningID,
&i.Category,
&i.PolicyVersionID,
&i.RequiredFamilies,
&i.PublishedCount,
&i.EffectivePolicyID,
&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
}
const readCandidateQuestionnaire = `-- name: ReadCandidateQuestionnaire :one
SELECT
questionnaire.user_id,
questionnaire.version,
questionnaire.work_formats,
questionnaire.created_at,
questionnaire.updated_at,
COALESCE((
SELECT jsonb_agg(
jsonb_build_object(
'ordinal', specialization.ordinal,
'specialization', specialization.specialization,
'self_assessed_grade', specialization.self_assessed_grade,
'task_languages', specialization.task_languages,
'stack', specialization.stack,
'commercial_months', specialization.commercial_months,
'academic_months', specialization.academic_months
) ORDER BY specialization.ordinal
)
FROM candidate_questionnaire_specializations AS specialization
WHERE specialization.user_id = questionnaire.user_id
), '[]'::jsonb)::text AS specializations
FROM candidate_questionnaires AS questionnaire
WHERE questionnaire.user_id = $1
`
type ReadCandidateQuestionnaireRow struct {
UserID pgtype.UUID
Version int64
WorkFormats []string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Specializations string
}
// Reads the aggregate and its ordered specializations in one statement so a
// response never pairs a version with another version's answers.
func (q *Queries) ReadCandidateQuestionnaire(ctx context.Context, userID pgtype.UUID) (ReadCandidateQuestionnaireRow, error) {
row := q.db.QueryRow(ctx, readCandidateQuestionnaire, userID)
var i ReadCandidateQuestionnaireRow
err := row.Scan(
&i.UserID,
&i.Version,
&i.WorkFormats,
&i.CreatedAt,
&i.UpdatedAt,
&i.Specializations,
)
return i, err
}
const readPublishedAssessmentCategoryManifest = `-- name: ReadPublishedAssessmentCategoryManifest :many
SELECT family_key, version, content_sha256
FROM assessment_families
WHERE category = $1 AND lifecycle = 'published'
ORDER BY family_key, version
`
type ReadPublishedAssessmentCategoryManifestRow struct {
FamilyKey string
Version int32
ContentSha256 []byte
}
// Lists the exact published bank manifest while the category advisory lock is
// held by OpenCategory. Published families have passed the independent-review
// constraint before this read.
func (q *Queries) ReadPublishedAssessmentCategoryManifest(ctx context.Context, category string) ([]ReadPublishedAssessmentCategoryManifestRow, error) {
rows, err := q.db.Query(ctx, readPublishedAssessmentCategoryManifest, category)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ReadPublishedAssessmentCategoryManifestRow
for rows.Next() {
var i ReadPublishedAssessmentCategoryManifestRow
if err := rows.Scan(&i.FamilyKey, &i.Version, &i.ContentSha256); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}