package postgres import ( "context" "encoding/hex" "encoding/json" "errors" "fmt" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) // DemoSeedStore implements outbound.DemoSeedStore on a pool. Its statements // read counts and identifiers only. type DemoSeedStore struct { pool *pgxpool.Pool } var _ outbound.DemoSeedStore = (*DemoSeedStore)(nil) // NewDemoSeedStore returns the store of the demo seed operator command. func NewDemoSeedStore(pool *pgxpool.Pool) *DemoSeedStore { return &DemoSeedStore{pool: pool} } // CountAccounts counts every account and those on the synthetic domain. The // domain is compared on the normalized address, so letter case does not // matter. func (store *DemoSeedStore) CountAccounts(ctx context.Context, syntheticDomain string) (outbound.DemoAccountCensus, error) { const location = "DemoSeedStore.CountAccounts" var census outbound.DemoAccountCensus if err := store.pool.QueryRow(ctx, ` SELECT count(*), count(*) FILTER (WHERE right(email_normalized, char_length($1::text) + 1) = '@' || $1::text) FROM users`, syntheticDomain).Scan(&census.Total, &census.Synthetic); err != nil { return outbound.DemoAccountCensus{}, fmt.Errorf("%s - count accounts: %w", location, sanitizeConnectError(err)) } return census, nil } // CurrentCategoryAttempt returns the source attempt of the candidate's // current category of the specialization. func (store *DemoSeedStore) CurrentCategoryAttempt( ctx context.Context, candidateID uuid.UUID, specialization domain.SpecializationCode, ) (domain.AssessmentAttemptID, bool, error) { const location = "DemoSeedStore.CurrentCategoryAttempt" var attemptID uuid.UUID err := store.pool.QueryRow(ctx, ` SELECT source_attempt_id FROM candidate_assessment_categories WHERE candidate_id = $1 AND specialization = $2`, candidateID, string(specialization)).Scan(&attemptID) if errors.Is(err, pgx.ErrNoRows) { return domain.AssessmentAttemptID{}, false, nil } if err != nil { return domain.AssessmentAttemptID{}, false, fmt.Errorf("%s - read current category: %w", location, sanitizeConnectError(err)) } return domain.AssessmentAttemptID(attemptID), true, nil } // TrainingBindingExists reports whether the category has a binding for the // policy version. func (store *DemoSeedStore) TrainingBindingExists( ctx context.Context, category string, policyVersionID domain.PolicyVersionID, ) (bool, error) { const location = "DemoSeedStore.TrainingBindingExists" var exists bool if err := store.pool.QueryRow(ctx, ` SELECT EXISTS ( SELECT 1 FROM assessment_training_bank_bindings WHERE category = $1 AND product_policy_version_id = $2 )`, category, uuid.UUID(policyVersionID)).Scan(&exists); err != nil { return false, fmt.Errorf("%s - read training binding: %w", location, sanitizeConnectError(err)) } return exists, nil } type demoTrainingFamily struct { id uuid.UUID key string version int32 hash []byte } type demoTrainingManifestEntry struct { FamilyKey string `json:"family_key"` Version int32 `json:"version"` ContentSHA256 string `json:"content_sha256"` } // BindTrainingBank pins every published family of the training category in // one transaction. The binding triggers check that the category has no real // opening, that the item count matches the policy, and that the policy is // the one in force. func (store *DemoSeedStore) BindTrainingBank(ctx context.Context, binding outbound.DemoTrainingBinding) error { const location = "DemoSeedStore.BindTrainingBank" if binding.Category == "" || binding.ItemCount < 1 || binding.PolicyVersionID == (domain.PolicyVersionID{}) { return fmt.Errorf("%s - binding is incomplete: %w", location, outbound.ErrDemoTrainingBindingMismatch) } if _, err := domain.ParseAssessmentOperator(string(binding.ReviewedBy)); err != nil { return fmt.Errorf("%s - validate reviewer: %w", location, err) } tx, err := store.pool.BeginTx(ctx, transactionOptions) if err != nil { return fmt.Errorf("%s - begin transaction: %w", location, sanitizeConnectError(err)) } finished := false defer func() { if !finished { _ = rollback(ctx, tx) } }() families, err := readPublishedTrainingFamilies(ctx, tx, binding.Category) if err != nil { return fmt.Errorf("%s - %w", location, err) } if len(families) != binding.ItemCount { return fmt.Errorf("%s - %d published families for %d items: %w", location, len(families), binding.ItemCount, outbound.ErrDemoTrainingBindingMismatch) } if err := insertTrainingBinding(ctx, tx, binding, families); err != nil { return fmt.Errorf("%s - %w", location, err) } finished = true if err := tx.Commit(ctx); err != nil { return fmt.Errorf("%s - commit transaction: %w", location, markTransactionConflict(err)) } return nil } func readPublishedTrainingFamilies(ctx context.Context, tx pgx.Tx, category string) ([]demoTrainingFamily, error) { rows, err := tx.Query(ctx, ` SELECT id, family_key, version, content_sha256 FROM assessment_families WHERE category = $1 AND lifecycle = 'published' ORDER BY family_key, version`, category) if err != nil { return nil, fmt.Errorf("read published families: %w", sanitizeConnectError(err)) } defer rows.Close() var families []demoTrainingFamily for rows.Next() { var family demoTrainingFamily if err := rows.Scan(&family.id, &family.key, &family.version, &family.hash); err != nil { return nil, fmt.Errorf("scan published family: %w", err) } families = append(families, family) } if err := rows.Err(); err != nil { return nil, fmt.Errorf("iterate published families: %w", sanitizeConnectError(err)) } return families, nil } // insertTrainingBinding stores the binding with the JSON manifest and the // same canonical manifest hash that a category opening uses. func insertTrainingBinding(ctx context.Context, tx pgx.Tx, binding outbound.DemoTrainingBinding, families []demoTrainingFamily) error { entries := make([]demoTrainingManifestEntry, len(families)) canonical := make([]domain.AssessmentCategoryManifestEntry, len(families)) for index, family := range families { entries[index] = demoTrainingManifestEntry{ FamilyKey: family.key, Version: family.version, ContentSHA256: hex.EncodeToString(family.hash), } canonical[index] = domain.AssessmentCategoryManifestEntry{ FamilyKey: domain.AssessmentFamilyKey(family.key), Version: family.version, ContentSHA256: family.hash, } } manifest, err := json.Marshal(entries) if err != nil { return fmt.Errorf("encode manifest: %w", err) } manifestHash, err := assessmentCategoryManifestFingerprint(canonical) if err != nil { return fmt.Errorf("hash manifest: %w", err) } bindingID, err := uuid.NewV7() if err != nil { return fmt.Errorf("generate binding ID: %w", err) } if _, err := tx.Exec(ctx, ` INSERT INTO assessment_training_bank_bindings ( id, category, product_policy_version_id, item_count, manifest_sha256, family_manifest, reviewed_by, created_at ) VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, clock_timestamp())`, bindingID, binding.Category, uuid.UUID(binding.PolicyVersionID), binding.ItemCount, manifestHash[:], manifest, string(binding.ReviewedBy)); err != nil { return fmt.Errorf("insert binding: %w", sanitizeConnectError(err)) } for index, family := range families { if _, err := tx.Exec(ctx, ` INSERT INTO assessment_training_bank_binding_families ( binding_id, ordinal, family_id, family_key, family_version, content_sha256 ) VALUES ($1, $2, $3, $4, $5, $6)`, bindingID, index+1, family.id, family.key, family.version, family.hash); err != nil { return fmt.Errorf("insert binding family: %w", sanitizeConnectError(err)) } } return nil } // AdvanceCandidateOnboarding moves a verified candidate with a saved // questionnaire from an earlier candidate step to candidate_assessment. The // statement is the questionnaire transition of the product repository, // widened to the earlier steps, and it touches no later step. It bumps the // account version as the product transitions do. func (store *DemoSeedStore) AdvanceCandidateOnboarding(ctx context.Context, userID uuid.UUID, at time.Time) (bool, error) { const location = "DemoSeedStore.AdvanceCandidateOnboarding" result, err := store.pool.Exec(ctx, ` UPDATE users SET onboarding_step = 'candidate_assessment', version = users.version + 1, updated_at = GREATEST(users.updated_at, $2::timestamptz) WHERE users.id = $1 AND users.scenario = 'candidate' AND users.email_verified_at IS NOT NULL AND users.onboarding_step IN ('candidate_consents', 'candidate_profile', 'candidate_questionnaire') AND EXISTS ( SELECT 1 FROM candidate_questionnaires AS questionnaire WHERE questionnaire.user_id = users.id )`, userID, at) if err != nil { return false, fmt.Errorf("%s - advance onboarding: %w", location, sanitizeConnectError(err)) } return result.RowsAffected() == 1, nil } // Inventory counts the records of synthetic accounts and of the seed's bank // categories in one read-only statement. func (store *DemoSeedStore) Inventory( ctx context.Context, syntheticDomain string, categories []string, ) (outbound.DemoInventory, error) { const location = "DemoSeedStore.Inventory" inventory := outbound.DemoInventory{SyntheticAccountDomain: syntheticDomain} if err := store.pool.QueryRow(ctx, ` WITH synthetic AS ( SELECT id, email_verified_at FROM users WHERE right(email_normalized, char_length($1::text) + 1) = '@' || $1::text ) SELECT (SELECT count(*) FROM synthetic), (SELECT count(*) FROM synthetic WHERE email_verified_at IS NOT NULL), (SELECT count(DISTINCT organization_id) FROM memberships WHERE user_id IN (SELECT id FROM synthetic)), (SELECT count(*) FROM memberships WHERE user_id IN (SELECT id FROM synthetic)), (SELECT count(*) FROM consent_records WHERE subject_id IN (SELECT id FROM synthetic)), (SELECT count(*) FROM candidate_profiles WHERE user_id IN (SELECT id FROM synthetic)), (SELECT count(*) FROM candidate_questionnaires WHERE user_id IN (SELECT id FROM synthetic)), (SELECT count(*) FROM assessment_attempts WHERE user_id IN (SELECT id FROM synthetic)), (SELECT count(*) FROM assessment_attempt_results WHERE user_id IN (SELECT id FROM synthetic)), (SELECT count(*) FROM candidate_assessment_categories WHERE candidate_id IN (SELECT id FROM synthetic)), (SELECT count(*) FROM skill_evidence_facts WHERE candidate_id IN (SELECT id FROM synthetic)), (SELECT count(*) FROM candidate_effective_publications WHERE user_id IN (SELECT id FROM synthetic)), (SELECT count(*) FROM policy_versions WHERE policy_key = 'product'), (SELECT count(*) FROM assessment_families WHERE category = ANY($2::text[]) AND lifecycle = 'published'), (SELECT count(*) FROM assessment_category_openings WHERE category = ANY($2::text[])), (SELECT count(*) FROM assessment_synthetic_category_reviews WHERE category = ANY($2::text[])), (SELECT count(*) FROM assessment_training_bank_bindings WHERE category = ANY($2::text[])), (SELECT count(*) FROM users)`, syntheticDomain, categories, ).Scan( &inventory.SyntheticAccounts, &inventory.VerifiedSynthetic, &inventory.Organizations, &inventory.Memberships, &inventory.ConsentRecords, &inventory.CandidateProfiles, &inventory.Questionnaires, &inventory.Attempts, &inventory.AttemptResults, &inventory.CurrentCategories, &inventory.EvidenceFacts, &inventory.PublishedCards, &inventory.ProductPolicyVersions, &inventory.PublishedFamilies, &inventory.CategoryOpenings, &inventory.CategoryAttestations, &inventory.TrainingBindings, &inventory.TotalAccounts, ); err != nil { return outbound.DemoInventory{}, fmt.Errorf("%s - count records: %w", location, sanitizeConnectError(err)) } inventory.OrdinaryAccounts = inventory.TotalAccounts - inventory.SyntheticAccounts return inventory, nil }