687 lines
26 KiB
Go
687 lines
26 KiB
Go
// Package demoseed builds the small reproducible demonstration world of an
|
|
// isolated demo stand: synthetic accounts of both roles that are confirmed
|
|
// without mail, two organizations with different permissions, a candidate
|
|
// without an FSP ID, the express training bank apart from the full bank, and
|
|
// prepared full attempts that run through the ordinary attempt operations.
|
|
//
|
|
// The seed is idempotent: a second run finds every record and creates
|
|
// nothing. It never changes or removes a record it did not create, and it
|
|
// refuses a stand that holds accounts of other people but none of its own.
|
|
package demoseed
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
"lincodex/backend/internal/usecase/assessment"
|
|
"lincodex/backend/internal/usecase/candidateprivacy"
|
|
"lincodex/backend/internal/usecase/consent"
|
|
"lincodex/backend/internal/usecase/policy"
|
|
"lincodex/backend/internal/usecase/profile"
|
|
"lincodex/backend/internal/usecase/questionnaire"
|
|
)
|
|
|
|
var (
|
|
// ErrStandNotFresh reports a stand that holds ordinary accounts and no
|
|
// account of the seed. The seed never mixes demo records with them.
|
|
ErrStandNotFresh = errors.New("the stand holds ordinary accounts and was never seeded")
|
|
// ErrForeignPolicy reports a product policy that the seed did not expect:
|
|
// neither the initial demo version nor the demo version the seed publishes.
|
|
ErrForeignPolicy = errors.New("the product policy is not the initial or the seeded demo policy")
|
|
// ErrAccountConflict reports an address of the seed that belongs to an
|
|
// account in another state, for example an unconfirmed registration.
|
|
ErrAccountConflict = errors.New("a demo address belongs to an account the seed did not create")
|
|
// ErrPreparedAttemptFailed reports a prepared attempt that did not end
|
|
// with an assigned synthetic demonstration category.
|
|
ErrPreparedAttemptFailed = errors.New("the prepared attempt did not assign its demonstration category")
|
|
)
|
|
|
|
// seedPolicy is the demo product policy version the seed publishes: the
|
|
// explicit demo_basic attempt settings, the separate express training mode,
|
|
// the review band, and the matching section.
|
|
func seedPolicy() domain.ProductPolicy { return domain.DemoProductPolicyV4() }
|
|
|
|
// Dependencies are the product services and ports the seed drives.
|
|
type Dependencies struct {
|
|
Transactor outbound.Transactor
|
|
Store outbound.DemoSeedStore
|
|
Hasher outbound.PasswordHasher
|
|
Consents *consent.Service
|
|
Profiles *profile.Service
|
|
Questionnaires *questionnaire.Service
|
|
Privacy *candidateprivacy.Service
|
|
Attempts *assessment.AttemptService
|
|
Bank *assessment.Bank
|
|
Attestor *assessment.CategoryAttestor
|
|
Clock func() time.Time
|
|
}
|
|
|
|
// Seeder runs the demo seed.
|
|
type Seeder struct {
|
|
deps Dependencies
|
|
}
|
|
|
|
// NewSeeder fails when a dependency is missing.
|
|
func NewSeeder(deps Dependencies) (*Seeder, error) {
|
|
if deps.Transactor == nil || deps.Store == nil || deps.Hasher == nil || deps.Consents == nil ||
|
|
deps.Profiles == nil || deps.Questionnaires == nil || deps.Privacy == nil || deps.Attempts == nil ||
|
|
deps.Bank == nil || deps.Attestor == nil || deps.Clock == nil {
|
|
return nil, errors.New("demoseed.NewSeeder - every dependency must be set")
|
|
}
|
|
return &Seeder{deps: deps}, nil
|
|
}
|
|
|
|
// Input is a validated seed request. Password is the shared password of the
|
|
// synthetic accounts; it is set only when an account is created.
|
|
type Input struct {
|
|
Actor domain.AssessmentOperator
|
|
Password domain.Password
|
|
}
|
|
|
|
// Report lists what one run created and what it found. It holds addresses
|
|
// of synthetic accounts and identifiers only.
|
|
type Report struct {
|
|
PolicyVersion int32
|
|
Created []string
|
|
Present []string
|
|
Logins []Login
|
|
PreparedAttempts []PreparedAttempt
|
|
}
|
|
|
|
// Login is one synthetic account the operator hands out.
|
|
type Login struct {
|
|
Email string
|
|
Role string
|
|
}
|
|
|
|
// PreparedAttempt identifies one prepared full attempt.
|
|
type PreparedAttempt struct {
|
|
Email string
|
|
AttemptID domain.AssessmentAttemptID
|
|
}
|
|
|
|
func (report *Report) record(created bool, item string) {
|
|
if created {
|
|
report.Created = append(report.Created, item)
|
|
return
|
|
}
|
|
report.Present = append(report.Present, item)
|
|
}
|
|
|
|
// Seed builds the demo world or finds it complete.
|
|
func (seeder *Seeder) Seed(ctx context.Context, input Input) (Report, error) {
|
|
const location = "Seeder.Seed"
|
|
if _, err := domain.ParseAssessmentOperator(string(input.Actor)); err != nil {
|
|
return Report{}, fmt.Errorf("%s - validate actor: %w", location, err)
|
|
}
|
|
census, err := seeder.deps.Store.CountAccounts(ctx, SyntheticDomain)
|
|
if err != nil {
|
|
return Report{}, fmt.Errorf("%s - count accounts: %w", location, err)
|
|
}
|
|
if census.Synthetic == 0 && census.Ordinary() > 0 {
|
|
return Report{}, fmt.Errorf("%s - check the stand: %w", location, ErrStandNotFresh)
|
|
}
|
|
var report Report
|
|
productPolicy, err := seeder.ensurePolicy(ctx, input.Actor, &report)
|
|
if err != nil {
|
|
return Report{}, err
|
|
}
|
|
report.PolicyVersion = productPolicy.Version()
|
|
if err := seeder.ensureFullBank(ctx, input.Actor, productPolicy, &report); err != nil {
|
|
return Report{}, err
|
|
}
|
|
if err := seeder.ensureTrainingBank(ctx, input.Actor, productPolicy, &report); err != nil {
|
|
return Report{}, err
|
|
}
|
|
users, err := seeder.ensureAccounts(ctx, input.Password, &report)
|
|
if err != nil {
|
|
return Report{}, err
|
|
}
|
|
for _, spec := range organizations() {
|
|
if err := seeder.ensureOrganization(ctx, spec, users, &report); err != nil {
|
|
return Report{}, err
|
|
}
|
|
}
|
|
if err := seeder.ensureCandidates(ctx, users, &report); err != nil {
|
|
return Report{}, err
|
|
}
|
|
return report, nil
|
|
}
|
|
|
|
// ensureAccounts creates or finds every synthetic account, keyed by its
|
|
// local part.
|
|
func (seeder *Seeder) ensureAccounts(ctx context.Context, password domain.Password, report *Report) (map[string]domain.User, error) {
|
|
users := make(map[string]domain.User)
|
|
for _, spec := range accounts() {
|
|
user, err := seeder.ensureAccount(ctx, spec, password, report)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
users[spec.local] = user
|
|
report.Logins = append(report.Logins, Login{Email: spec.email(), Role: roleLabel(spec.role)})
|
|
}
|
|
return users, nil
|
|
}
|
|
|
|
// ensureCandidates completes every candidate account.
|
|
func (seeder *Seeder) ensureCandidates(ctx context.Context, users map[string]domain.User, report *Report) error {
|
|
for _, spec := range accounts() {
|
|
if spec.role == roleEmployer {
|
|
continue
|
|
}
|
|
attemptID, err := seeder.ensureCandidate(ctx, spec, users[spec.local], report)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !attemptID.IsZero() {
|
|
report.PreparedAttempts = append(report.PreparedAttempts, PreparedAttempt{Email: spec.email(), AttemptID: attemptID})
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func roleLabel(role accountRole) string {
|
|
switch role {
|
|
case roleEmployer:
|
|
return "employer"
|
|
case rolePrepared:
|
|
return "candidate with a prepared full attempt"
|
|
case roleSelfService:
|
|
return "candidate for the express and the full test"
|
|
}
|
|
return "account"
|
|
}
|
|
|
|
// ensurePolicy publishes the seed policy over the initial demo version or
|
|
// finds it already published. It refuses any other latest version, so an
|
|
// operator-owned policy is never replaced.
|
|
func (seeder *Seeder) ensurePolicy(ctx context.Context, actor domain.AssessmentOperator, report *Report) (domain.PolicyVersion, error) {
|
|
const location = "Seeder.ensurePolicy"
|
|
initial, err := demoDraft(domain.DemoProductPolicyV1(), domain.DemoPolicySeedAuthor)
|
|
if err != nil {
|
|
return domain.PolicyVersion{}, fmt.Errorf("%s - build initial draft: %w", location, err)
|
|
}
|
|
author, err := domain.ParsePolicyAuthor(string(actor))
|
|
if err != nil {
|
|
return domain.PolicyVersion{}, fmt.Errorf("%s - validate author: %w", location, err)
|
|
}
|
|
target, err := demoDraft(seedPolicy(), author)
|
|
if err != nil {
|
|
return domain.PolicyVersion{}, fmt.Errorf("%s - build seed draft: %w", location, err)
|
|
}
|
|
var version domain.PolicyVersion
|
|
created := false
|
|
err = seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
latest, err := unit.Policies().GetLatest(ctx, domain.ProductPolicyKey)
|
|
if err != nil {
|
|
return fmt.Errorf("read latest product policy: %w", err)
|
|
}
|
|
now, err := unit.AssessmentBank().DatabaseTime(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("read database time: %w", err)
|
|
}
|
|
effective, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, now)
|
|
if err != nil {
|
|
return fmt.Errorf("read effective product policy: %w", err)
|
|
}
|
|
if effective.ID() != latest.ID() || latest.Kind() != domain.PolicyKindDemo {
|
|
return ErrForeignPolicy
|
|
}
|
|
if latest.DocumentHash() == target.DocumentHash() {
|
|
version = latest
|
|
return nil
|
|
}
|
|
if latest.Version() != 1 || latest.DocumentHash() != initial.DocumentHash() {
|
|
return ErrForeignPolicy
|
|
}
|
|
version, err = policy.NewPublisher(unit.Policies(), func() time.Time { return now }).Publish(ctx, policy.PublishInput{
|
|
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: author, Policy: seedPolicy(),
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("publish seed policy: %w", err)
|
|
}
|
|
created = true
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
|
|
return domain.PolicyVersion{}, fmt.Errorf("%s - the stand has no product policy yet: %w", location, err)
|
|
}
|
|
return domain.PolicyVersion{}, fmt.Errorf("%s - transaction: %w", location, err)
|
|
}
|
|
report.record(created, fmt.Sprintf("product policy version %d", version.Version()))
|
|
return version, nil
|
|
}
|
|
|
|
func demoDraft(product domain.ProductPolicy, author domain.PolicyAuthor) (domain.PolicyVersionDraft, error) {
|
|
return domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
|
|
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: author, Policy: product,
|
|
})
|
|
}
|
|
|
|
// ensureFullBank imports and publishes the families of the full category,
|
|
// opens it under the seed policy with its catalog mapping, and attests the
|
|
// opening as a source of synthetic demonstration categories.
|
|
func (seeder *Seeder) ensureFullBank(
|
|
ctx context.Context,
|
|
actor domain.AssessmentOperator,
|
|
productPolicy domain.PolicyVersion,
|
|
report *Report,
|
|
) error {
|
|
const location = "Seeder.ensureFullBank"
|
|
required, err := domain.RequiredPublishedAssessmentFamilies(productPolicy.Policy())
|
|
if err != nil {
|
|
return fmt.Errorf("%s - read family requirement: %w", location, err)
|
|
}
|
|
bundle, err := syntheticBundle(fullBundleName, string(FullCategory), fullFamilyStem, int(required))
|
|
if err != nil {
|
|
return fmt.Errorf("%s - build bundle: %w", location, err)
|
|
}
|
|
if err := seeder.publishBundle(ctx, bundle, actor, report); err != nil {
|
|
return fmt.Errorf("%s - %w", location, err)
|
|
}
|
|
opening, err := seeder.deps.Bank.CategoryAvailability(ctx, FullCategory)
|
|
if err != nil || opening.PolicyVersionID != productPolicy.ID() {
|
|
metadata, err := domain.NewAssessmentCategoryCatalogMetadata(
|
|
fullSpecialization, fullGrade, []domain.TaskLanguageCode{fullTaskLanguage},
|
|
)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - build catalog mapping: %w", location, err)
|
|
}
|
|
if _, err := seeder.deps.Bank.OpenCategory(ctx, assessment.OpenCategoryInput{
|
|
Category: FullCategory, GradingPolicyID: productPolicy.ID(), OpenedBy: actor, CatalogMetadata: &metadata,
|
|
}); err != nil {
|
|
return fmt.Errorf("%s - open category: %w", location, err)
|
|
}
|
|
report.record(true, "opening of category "+string(FullCategory))
|
|
} else {
|
|
report.record(false, "opening of category "+string(FullCategory))
|
|
}
|
|
language := fullTaskLanguage
|
|
attestation, err := seeder.deps.Attestor.Attest(ctx, fullSpecialization, fullGrade, &language, string(actor))
|
|
if err != nil {
|
|
return fmt.Errorf("%s - attest category: %w", location, err)
|
|
}
|
|
report.record(attestation.Created, "synthetic demonstration attestation of "+string(FullCategory))
|
|
return nil
|
|
}
|
|
|
|
// ensureTrainingBank publishes the express families and binds them to the
|
|
// seed policy. The training category never gets a real opening.
|
|
func (seeder *Seeder) ensureTrainingBank(
|
|
ctx context.Context,
|
|
actor domain.AssessmentOperator,
|
|
productPolicy domain.PolicyVersion,
|
|
report *Report,
|
|
) error {
|
|
const location = "Seeder.ensureTrainingBank"
|
|
training := productPolicy.Policy().Assessment.Training
|
|
if training == nil {
|
|
return fmt.Errorf("%s - the seed policy has no express training mode", location)
|
|
}
|
|
bundle, err := syntheticBundle(trainingBundleName, TrainingCategory, trainingFamilyStem, int(training.DemoExpressItemCount))
|
|
if err != nil {
|
|
return fmt.Errorf("%s - build bundle: %w", location, err)
|
|
}
|
|
if err := seeder.publishBundle(ctx, bundle, actor, report); err != nil {
|
|
return fmt.Errorf("%s - %w", location, err)
|
|
}
|
|
exists, err := seeder.deps.Store.TrainingBindingExists(ctx, TrainingCategory, productPolicy.ID())
|
|
if err != nil {
|
|
return fmt.Errorf("%s - read binding: %w", location, err)
|
|
}
|
|
if !exists {
|
|
if err := seeder.deps.Store.BindTrainingBank(ctx, outbound.DemoTrainingBinding{
|
|
Category: TrainingCategory, PolicyVersionID: productPolicy.ID(),
|
|
ItemCount: int(training.DemoExpressItemCount), ReviewedBy: actor,
|
|
}); err != nil {
|
|
return fmt.Errorf("%s - bind training bank: %w", location, err)
|
|
}
|
|
}
|
|
report.record(!exists, "express training binding of "+TrainingCategory)
|
|
return nil
|
|
}
|
|
|
|
// publishBundle imports the bundle, which leaves stored versions unchanged,
|
|
// and publishes every family that has no published version yet.
|
|
func (seeder *Seeder) publishBundle(ctx context.Context, bundle assessment.Bundle, actor domain.AssessmentOperator, report *Report) error {
|
|
if _, err := seeder.deps.Bank.ImportBundle(ctx, bundle); err != nil {
|
|
return fmt.Errorf("import bundle %s: %w", bundle.Name, err)
|
|
}
|
|
published := 0
|
|
for _, family := range bundle.Families {
|
|
key := domain.AssessmentFamilyKey(family.Key)
|
|
if _, err := seeder.deps.Bank.ActiveFamily(ctx, key); err == nil {
|
|
continue
|
|
} else if !errors.Is(err, outbound.ErrAssessmentFamilyNotFound) {
|
|
return fmt.Errorf("read family %s: %w", family.Key, err)
|
|
}
|
|
if _, err := seeder.deps.Bank.PublishFamily(ctx, key, family.Version, actor); err != nil {
|
|
return fmt.Errorf("publish family %s: %w", family.Key, err)
|
|
}
|
|
published++
|
|
}
|
|
report.record(published > 0, fmt.Sprintf("%d published families of %s", len(bundle.Families), bundle.Category))
|
|
return nil
|
|
}
|
|
|
|
// ensureAccount creates a confirmed synthetic account with the C1 grant of a
|
|
// registration, or finds it. The address is on the reserved domain, so no
|
|
// mail is sent and ordinary registration keeps its email check.
|
|
func (seeder *Seeder) ensureAccount(ctx context.Context, spec accountSpec, password domain.Password, report *Report) (domain.User, error) {
|
|
const location = "Seeder.ensureAccount"
|
|
email, err := domain.NewEmailAddress(spec.email())
|
|
if err != nil {
|
|
return domain.User{}, fmt.Errorf("%s - build address: %w", location, err)
|
|
}
|
|
existing, found, err := seeder.readAccount(ctx, email)
|
|
if err != nil {
|
|
return domain.User{}, fmt.Errorf("%s - read account: %w", location, err)
|
|
}
|
|
if found {
|
|
if !existing.EmailVerified() || existing.Scenario != spec.scenario() {
|
|
return domain.User{}, fmt.Errorf("%s - %s: %w", location, spec.email(), ErrAccountConflict)
|
|
}
|
|
report.record(false, "account "+spec.email())
|
|
return existing, nil
|
|
}
|
|
if password.IsZero() {
|
|
return domain.User{}, fmt.Errorf("%s - a password is required to create %s", location, spec.email())
|
|
}
|
|
passwordHash, err := seeder.deps.Hasher.Hash(ctx, password)
|
|
if err != nil {
|
|
return domain.User{}, fmt.Errorf("%s - hash password: %w", location, err)
|
|
}
|
|
now := seeder.now()
|
|
user, err := domain.NewUser(domain.Registration{
|
|
Email: email, PasswordHash: passwordHash, Scenario: spec.scenario(), RegisteredAt: now,
|
|
})
|
|
if err != nil {
|
|
return domain.User{}, fmt.Errorf("%s - build account: %w", location, err)
|
|
}
|
|
var verified domain.User
|
|
err = seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
if err := unit.Users().Create(ctx, user); err != nil {
|
|
return fmt.Errorf("create account: %w", err)
|
|
}
|
|
text, err := unit.ConsentTexts().Current(ctx, domain.ConsentPurposePersonalData, now)
|
|
if err != nil {
|
|
return fmt.Errorf("read C1 text: %w", err)
|
|
}
|
|
if _, err := seeder.deps.Consents.GrantAtRegistration(ctx, unit, user.ID, user.RegistrationVersion, text.Version()); err != nil {
|
|
return fmt.Errorf("grant C1: %w", err)
|
|
}
|
|
verified, err = unit.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, now)
|
|
if err != nil {
|
|
return fmt.Errorf("confirm address: %w", err)
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
if errors.Is(err, outbound.ErrEmailTaken) {
|
|
return domain.User{}, fmt.Errorf("%s - %s: %w", location, spec.email(), ErrAccountConflict)
|
|
}
|
|
return domain.User{}, fmt.Errorf("%s - transaction: %w", location, err)
|
|
}
|
|
report.record(true, "account "+spec.email())
|
|
return verified, nil
|
|
}
|
|
|
|
func (seeder *Seeder) readAccount(ctx context.Context, email domain.EmailAddress) (domain.User, bool, error) {
|
|
var user domain.User
|
|
found := false
|
|
err := seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
stored, err := unit.Users().GetByEmail(ctx, email)
|
|
if errors.Is(err, outbound.ErrUserNotFound) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
user, found = stored, true
|
|
return nil
|
|
})
|
|
return user, found, err
|
|
}
|
|
|
|
// ensureOrganization finds the organization by name among the organizations
|
|
// its owner owns, or creates it with the owner, and adds the second member.
|
|
func (seeder *Seeder) ensureOrganization(
|
|
ctx context.Context,
|
|
spec organizationSpec,
|
|
users map[string]domain.User,
|
|
report *Report,
|
|
) error {
|
|
const location = "Seeder.ensureOrganization"
|
|
owner := users[spec.ownerLocal]
|
|
organizationID, found, err := seeder.findOwnedOrganization(ctx, owner.ID, spec.name)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - list organizations: %w", location, err)
|
|
}
|
|
if !found {
|
|
organizationID, err = seeder.createOrganization(ctx, spec, owner.ID)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - %w", location, err)
|
|
}
|
|
}
|
|
report.record(!found, "organization "+spec.name)
|
|
if spec.memberLocal == "" {
|
|
return nil
|
|
}
|
|
member := users[spec.memberLocal]
|
|
created, err := seeder.ensureMembership(ctx, organizationID, member.ID, spec.memberRole)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - %w", location, err)
|
|
}
|
|
report.record(created, fmt.Sprintf("%s membership of %s in %s", spec.memberRole, spec.memberLocal+"@"+SyntheticDomain, spec.name))
|
|
return nil
|
|
}
|
|
|
|
func (seeder *Seeder) findOwnedOrganization(ctx context.Context, ownerID uuid.UUID, name string) (uuid.UUID, bool, error) {
|
|
var organizationID uuid.UUID
|
|
found := false
|
|
err := seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
var after *outbound.OrganizationListPosition
|
|
for {
|
|
page, err := unit.Organizations().ListForUser(ctx, outbound.OrganizationListQuery{
|
|
UserID: ownerID, After: after, Limit: outbound.MaxOrganizationPageSize,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, item := range page.Items {
|
|
if item.Organization.Name() == name && item.Membership.Role() == domain.OrganizationRoleOwner {
|
|
organizationID, found = item.Organization.ID(), true
|
|
return nil
|
|
}
|
|
}
|
|
if !page.HasMore || len(page.Items) == 0 {
|
|
return nil
|
|
}
|
|
position := outbound.OrganizationPositionOf(page.Items[len(page.Items)-1])
|
|
after = &position
|
|
}
|
|
})
|
|
return organizationID, found, err
|
|
}
|
|
|
|
func (seeder *Seeder) createOrganization(ctx context.Context, spec organizationSpec, ownerID uuid.UUID) (uuid.UUID, error) {
|
|
profileValue, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{
|
|
Name: spec.name, Description: spec.description, Sphere: spec.sphere,
|
|
})
|
|
if err != nil {
|
|
return uuid.Nil, fmt.Errorf("build organization profile: %w", err)
|
|
}
|
|
now := seeder.now()
|
|
organization, err := domain.NewOrganization(profileValue, now)
|
|
if err != nil {
|
|
return uuid.Nil, fmt.Errorf("build organization: %w", err)
|
|
}
|
|
ownerMembership, err := domain.NewOwnerMembership(organization.ID(), ownerID, now)
|
|
if err != nil {
|
|
return uuid.Nil, fmt.Errorf("build owner membership: %w", err)
|
|
}
|
|
err = seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
return unit.Organizations().CreateWithOwner(ctx, organization, ownerMembership)
|
|
})
|
|
if err != nil {
|
|
return uuid.Nil, fmt.Errorf("create organization: %w", err)
|
|
}
|
|
return organization.ID(), nil
|
|
}
|
|
|
|
func (seeder *Seeder) ensureMembership(ctx context.Context, organizationID, userID uuid.UUID, role domain.OrganizationRole) (bool, error) {
|
|
created := false
|
|
err := seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
existing, err := unit.Memberships().Get(ctx, organizationID, userID)
|
|
if err == nil {
|
|
if existing.Role() != role {
|
|
return fmt.Errorf("membership has role %s, want %s: %w", existing.Role(), role, ErrAccountConflict)
|
|
}
|
|
return nil
|
|
}
|
|
if !errors.Is(err, outbound.ErrMembershipNotFound) {
|
|
return fmt.Errorf("read membership: %w", err)
|
|
}
|
|
membership, err := domain.NewMembership(domain.MembershipInput{
|
|
OrganizationID: organizationID, UserID: userID, Role: role, At: seeder.now(),
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("build membership: %w", err)
|
|
}
|
|
if err := unit.Memberships().Insert(ctx, membership); err != nil {
|
|
return fmt.Errorf("insert membership: %w", err)
|
|
}
|
|
created = true
|
|
return nil
|
|
})
|
|
return created, err
|
|
}
|
|
|
|
// ensureCandidate gives a candidate its consents, manual profile, and
|
|
// questionnaire; a prepared candidate also gets the prepared full attempt and
|
|
// a published card. It returns the prepared attempt, or a zero ID.
|
|
func (seeder *Seeder) ensureCandidate(
|
|
ctx context.Context,
|
|
spec accountSpec,
|
|
user domain.User,
|
|
report *Report,
|
|
) (domain.AssessmentAttemptID, error) {
|
|
const location = "Seeder.ensureCandidate"
|
|
purposes := []domain.ConsentPurpose{domain.ConsentPurposeAutoCategorization}
|
|
if spec.role == rolePrepared {
|
|
purposes = append(purposes, domain.ConsentPurposePublication)
|
|
}
|
|
for _, purpose := range purposes {
|
|
if err := seeder.grantConsent(ctx, user.ID, purpose); err != nil {
|
|
return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %s: %w", location, purpose, err)
|
|
}
|
|
}
|
|
created, err := seeder.ensureProfile(ctx, spec, user.ID)
|
|
if err != nil {
|
|
return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %w", location, err)
|
|
}
|
|
report.record(created, "profile of "+spec.email())
|
|
created, err = seeder.ensureQuestionnaire(ctx, user.ID)
|
|
if err != nil {
|
|
return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %w", location, err)
|
|
}
|
|
report.record(created, "questionnaire of "+spec.email())
|
|
if spec.role != rolePrepared {
|
|
return domain.AssessmentAttemptID{}, nil
|
|
}
|
|
attemptID, created, err := seeder.ensurePreparedAttempt(ctx, user.ID)
|
|
if err != nil {
|
|
return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %s: %w", location, spec.email(), err)
|
|
}
|
|
report.record(created, "prepared full attempt of "+spec.email())
|
|
created, err = seeder.ensurePublication(ctx, user.ID)
|
|
if err != nil {
|
|
return domain.AssessmentAttemptID{}, fmt.Errorf("%s - %w", location, err)
|
|
}
|
|
report.record(created, "published card of "+spec.email())
|
|
return attemptID, nil
|
|
}
|
|
|
|
// grantConsent grants the current text of the purpose; a repeat of the same
|
|
// version is idempotent in the ledger.
|
|
func (seeder *Seeder) grantConsent(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) error {
|
|
var version domain.ConsentTextVersion
|
|
err := seeder.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
text, err := unit.ConsentTexts().Current(ctx, purpose, seeder.now())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
version = text.Version()
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("read current text: %w", err)
|
|
}
|
|
if _, err := seeder.deps.Consents.GrantInSettingsInNewTransaction(ctx, consent.SettingsGrantInput{
|
|
SubjectID: subjectID, Purpose: purpose, TextVersion: version,
|
|
}); err != nil {
|
|
return fmt.Errorf("grant: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ensureProfile saves the manual profile once. A profile that exists is left
|
|
// as it is, also when a visitor edited it; a reset restores it.
|
|
func (seeder *Seeder) ensureProfile(ctx context.Context, spec accountSpec, userID uuid.UUID) (bool, error) {
|
|
current, err := seeder.deps.Profiles.GetMyProfile(ctx, userID)
|
|
if err != nil {
|
|
return false, fmt.Errorf("read profile: %w", err)
|
|
}
|
|
if current.Profile.Version() > 0 {
|
|
return false, nil
|
|
}
|
|
if _, err := seeder.deps.Profiles.SaveMyProfile(ctx, userID, current.Profile.Version(), profileInput(spec)); err != nil {
|
|
return false, fmt.Errorf("save profile: %w", err)
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
// ensureQuestionnaire saves the questionnaire once, after the bank is open,
|
|
// because the questionnaire accepts only available task languages.
|
|
func (seeder *Seeder) ensureQuestionnaire(ctx context.Context, userID uuid.UUID) (bool, error) {
|
|
current, err := seeder.deps.Questionnaires.GetMyQuestionnaire(ctx, userID)
|
|
if err != nil {
|
|
return false, fmt.Errorf("read questionnaire: %w", err)
|
|
}
|
|
if current.Version() > 0 {
|
|
return false, nil
|
|
}
|
|
if _, err := seeder.deps.Questionnaires.SaveMyQuestionnaire(ctx, userID, current.Version(), questionnaireInput()); err != nil {
|
|
return false, fmt.Errorf("save questionnaire: %w", err)
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
// ensurePublication publishes the card once with the cohort fields.
|
|
func (seeder *Seeder) ensurePublication(ctx context.Context, userID uuid.UUID) (bool, error) {
|
|
settings, err := seeder.deps.Privacy.GetMyPrivacySettings(ctx, userID)
|
|
if err != nil {
|
|
return false, fmt.Errorf("read privacy settings: %w", err)
|
|
}
|
|
if settings.Publication.Version() > 0 {
|
|
return false, nil
|
|
}
|
|
if _, err := seeder.deps.Privacy.SetMyPublication(
|
|
ctx, userID, settings.Publication.Version(), domain.PublicationPublished, publishedFields(),
|
|
); err != nil {
|
|
return false, fmt.Errorf("publish card: %w", err)
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
func (seeder *Seeder) now() time.Time {
|
|
return seeder.deps.Clock().UTC().Truncate(time.Microsecond)
|
|
}
|