package console import ( "context" "fmt" "git.golem15.com/golem15/sm-user-plugin/classes" "git.golem15.com/golem15/sm-user-plugin/models" "git.golem15.com/golem15/summercms/modules/backpack" "git.golem15.com/golem15/summercms/modules/bonfire" "git.golem15.com/golem15/summercms/modules/lagoon" "gorm.io/gorm" ) // BackfillHandles fills a unique handle on every user row that still has none. // It uses the database the serve command published or, when it runs as a // console command, opens one from the config for the duration of the run, // as the plugin's other commands do. func BackfillHandles(app *backpack.App) bonfire.Command { return bonfire.Command{ Name: "user:backfill-handles", Description: "Assign unique handles to users that do not have one", Long: `Gives every user without a handle a unique one, derived the same way as for a new registration, with a progress bar over the users (hidden under -q). Users that already have a handle are not touched, so running it again changes nothing. Run it once after copying users from WinterCMS, which had no handles. It ends with "Assigned handles to N user(s)".`, Examples: []bonfire.Example{ {Command: "user:backfill-handles", Description: "Assign a handle to every user that has none"}, {Command: "user:backfill-handles -q", Description: "Run it quietly, printing only the result line"}, }, Run: func(ctx context.Context, _ bonfire.Input, out bonfire.Output) error { if app == nil { return fmt.Errorf("user:backfill-handles: app is nil") } gdb, ok := app.Lookup[*gorm.DB]() if !ok || gdb == nil { sqlDB, opened, err := lagoon.OpenFromApp(ctx, app) if err != nil { return fmt.Errorf("user:backfill-handles: %w", err) } defer sqlDB.Close() gdb = opened } var users []models.User if err := gdb.WithContext(ctx).Where("handle IS NULL OR handle = ''").Find(&users).Error; err != nil { return err } n := 0 if len(users) > 0 { err := out.Progress(len(users), func(p bonfire.Progress) error { for i := range users { if err := classes.AssignHandle(ctx, gdb, &users[i]); err != nil { return err } n++ p.Advance(1) } return nil }) if err != nil { return err } } out.Success(fmt.Sprintf("Assigned handles to %d user(s)", n)) return nil }, } }