// Package demoseed installs an isolated, repeatable pre-production fixture. package demoseed import ( "context" "fmt" "strings" "Rezina-Backend/internal/services/rbac" "github.com/jackc/pgx/v5" "golang.org/x/crypto/bcrypt" ) const DefaultPassword = "RezinaDemo!2026" type Account struct{ Email, Role, Audience string } var Accounts = []Account{ {"superadmin@demo.rezina.test", "SUPER_ADMIN", "staff"}, {"admin@demo.rezina.test", "ADMIN", "staff"}, {"contentmanager@demo.rezina.test", "CONTENT_MANAGER", "staff"}, {"student@demo.rezina.test", "STUDENT", "customer"}, {"premium@demo.rezina.test", "STUDENT", "customer"}, {"openlearner@demo.rezina.test", "OPEN_LEARNER", "customer"}, } type Course struct { Key, Name, Description, Tier string Chapters []Chapter } type Chapter struct { Name string Lessons []string } var Courses = []Course{ {"everyday-english", "Everyday English", "Build confidence with introductions, daily conversations, and practical vocabulary.", "FREE", []Chapter{ {"Meet and greet", []string{"Introduce yourself", "Ask friendly questions", "Start a conversation"}}, {"Everyday situations", []string{"Order food and drinks", "Ask for directions", "Make simple plans"}}, }}, {"workplace-communication", "Workplace Communication", "Communicate clearly in meetings, write effective messages, and present your ideas.", "PREMIUM", []Chapter{ {"Working together", []string{"Write a clear email", "Join a team meeting", "Give useful feedback"}}, {"Present with confidence", []string{"Structure your message", "Explain an idea", "Answer audience questions"}}, }}, {"digital-skills", "Digital Skills Essentials", "Learn practical habits for working online, organizing information, and collaborating safely.", "FREE", []Chapter{ {"Digital foundations", []string{"Organize files and folders", "Search with purpose", "Protect your accounts"}}, {"Online collaboration", []string{"Share documents", "Work in a shared workspace", "Communicate online"}}, }}, } // ValidateEnvironment requires an explicit non-production target and refuses any // production environment setting, even when the command flag says development. func ValidateEnvironment(target string, settings ...string) error { switch strings.ToLower(strings.TrimSpace(target)) { case "development", "test", "staging": default: return fmt.Errorf("use -environment development, test, or staging; demo accounts are not production data") } for _, value := range settings { value = strings.ToLower(strings.TrimSpace(value)) if value == "production" || value == "prod" { return fmt.Errorf("demo seeding is disabled in production") } } return nil } type seed struct { tx pgx.Tx ctx context.Context } // entity records seed-owned IDs, avoiding fixed IDs and destructive truncation. // Re-running keeps authored content intact and recreates a deleted fixture row. func (s seed) entity(kind, key, table, insert string, args ...any) (int64, error) { var id int64 err := s.tx.QueryRow(s.ctx, `SELECT entity_id FROM demo_seed_entities WHERE kind=$1 AND seed_key=$2`, kind, key).Scan(&id) if err == nil { var exists bool if err = s.tx.QueryRow(s.ctx, `SELECT EXISTS(SELECT 1 FROM `+table+` WHERE id=$1)`, id).Scan(&exists); err != nil { return 0, err } if exists { return id, nil } } else if err != pgx.ErrNoRows { return 0, err } if err = s.tx.QueryRow(s.ctx, insert, args...).Scan(&id); err != nil { return 0, fmt.Errorf("seed %s/%s: %w", kind, key, err) } _, err = s.tx.Exec(s.ctx, `INSERT INTO demo_seed_entities(kind,seed_key,entity_id) VALUES($1,$2,$3) ON CONFLICT(kind,seed_key) DO UPDATE SET entity_id=EXCLUDED.entity_id`, kind, key, id) return id, err } func Run(ctx context.Context, conn *pgx.Conn, password, videoURL string) error { if len(password) < 12 || len(password) > 72 { return fmt.Errorf("demo password must be 12-72 bytes") } hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { return err } tx, err := conn.Begin(ctx) if err != nil { return err } defer tx.Rollback(ctx) s := seed{tx: tx, ctx: ctx} if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(74203119)`); err != nil { return err } var ready bool if err = tx.QueryRow(ctx, `SELECT to_regclass('exam_prep.chapter_lesson_containers') IS NOT NULL`).Scan(&ready); err != nil { return err } if !ready { return fmt.Errorf("apply migrations through 000003_chapters_and_quizzes before seeding") } if _, err = tx.Exec(ctx, `CREATE TABLE IF NOT EXISTS demo_seed_entities(kind text NOT NULL,seed_key text NOT NULL,entity_id bigint NOT NULL,PRIMARY KEY(kind,seed_key))`); err != nil { return err } userIDs := map[string]int64{} for _, a := range Accounts { var id int64 if a.Audience == "staff" { err = tx.QueryRow(ctx, `INSERT INTO team_members(first_name,last_name,email,password,team_role,status,email_verified,employment_type) VALUES('Demo',$1,$2,$3,$4,'active',true,'full_time') ON CONFLICT(email) DO UPDATE SET password=EXCLUDED.password,team_role=EXCLUDED.team_role,status='active',email_verified=true RETURNING id`, a.Role, a.Email, hash, a.Role).Scan(&id) } else { err = tx.QueryRow(ctx, `INSERT INTO users(first_name,last_name,email,password,role,status,email_verified,phone_verified,profile_completed,preferred_language) VALUES('Demo',$1,$2,$3,$4,'ACTIVE',true,false,true,'en') ON CONFLICT(lower(email)) WHERE email IS NOT NULL DO UPDATE SET password=EXCLUDED.password,role=EXCLUDED.role,status='ACTIVE',email_verified=true,profile_completed=true RETURNING id`, a.Role, a.Email, hash, a.Role).Scan(&id) userIDs[a.Email] = id } if err != nil { return fmt.Errorf("seed demo account %s: %w", a.Email, err) } } // Seed standard RBAC grants, rather than granting every permission to every role. for _, p := range rbac.AllPermissions { if _, err = tx.Exec(ctx, `INSERT INTO permissions(key,name,description,group_name) VALUES($1,$2,$3,$4) ON CONFLICT(key) DO NOTHING`, p.Key, p.Name, p.Description, p.GroupName); err != nil { return err } } for _, role := range []string{"SUPER_ADMIN", "ADMIN", "CONTENT_MANAGER", "STUDENT", "OPEN_LEARNER"} { if _, err = tx.Exec(ctx, `INSERT INTO roles(name,description,is_system) VALUES($1,'System role',true) ON CONFLICT(name) DO NOTHING`, role); err != nil { return err } for _, key := range rbac.DefaultRolePermissions[role] { if _, err = tx.Exec(ctx, `INSERT INTO role_permissions(role_id,permission_id) SELECT r.id,p.id FROM roles r,permissions p WHERE r.name=$1 AND p.key=$2 ON CONFLICT DO NOTHING`, role, key); err != nil { return err } } } for _, course := range Courses { courseID, err := s.entity("course", course.Key, "exam_prep.catalog_courses", `INSERT INTO exam_prep.catalog_courses(name,description,category,sort_order,publish_status,access_tier,thumbnail) SELECT $1,$2,'EDUCATION',COALESCE(MAX(sort_order),0)+1,'PUBLISHED',$3,'/static/demo/course-cover.svg' FROM exam_prep.catalog_courses RETURNING id`, course.Name, course.Description, course.Tier) if err != nil { return err } for ci, chapter := range course.Chapters { key := fmt.Sprintf("%s/chapter-%d", course.Key, ci+1) chapterID, err := s.entity("chapter", key, "exam_prep.units", `INSERT INTO exam_prep.units(catalog_course_id,name,description,sort_order,publish_status,access_tier) VALUES($1,$2,$3,$4,'PUBLISHED','FREE') RETURNING id`, courseID, chapter.Name, "Practice the key ideas through short lessons and a chapter review quiz.", ci+1) if err != nil { return err } var moduleID int64 err = tx.QueryRow(ctx, `SELECT module_id FROM exam_prep.chapter_lesson_containers WHERE chapter_id=$1`, chapterID).Scan(&moduleID) if err == pgx.ErrNoRows { err = tx.QueryRow(ctx, `INSERT INTO exam_prep.unit_modules(unit_id,name,sort_order,publish_status,access_tier) VALUES($1,'__chapter_lessons__',1,'PUBLISHED','FREE') RETURNING id`, chapterID).Scan(&moduleID) if err == nil { _, err = tx.Exec(ctx, `INSERT INTO exam_prep.chapter_lesson_containers(chapter_id,module_id) VALUES($1,$2)`, chapterID, moduleID) } } if err != nil { return err } for li, title := range chapter.Lessons { _, err = s.entity("lesson", fmt.Sprintf("%s/lesson-%d", key, li+1), "exam_prep.unit_module_lessons", `INSERT INTO exam_prep.unit_module_lessons(unit_module_id,title,description,sort_order,publish_status,access_tier,video_url,thumbnail) SELECT $1,$2,$3,COALESCE(MAX(sort_order),0)+1,'PUBLISHED','FREE',NULLIF($4,''),'/static/demo/course-cover.svg' FROM exam_prep.unit_module_lessons WHERE unit_module_id=$1 RETURNING id`, moduleID, title, "In this demo lesson, explore how to "+strings.ToLower(title)+". Review the examples, try it yourself, and complete the chapter quiz. The video is sample media for testing playback.", videoURL) if err != nil { return err } } setID, err := s.entity("question_set", key, "question_sets", `INSERT INTO question_sets(title,description,set_type,status,passing_score,shuffle_questions) VALUES($1,'Demo chapter review','QUIZ','PUBLISHED',60,false) RETURNING id`, chapter.Name+" review") if err != nil { return err } quizID, err := s.entity("quiz", key, "exam_prep.lesson_practices", `INSERT INTO exam_prep.lesson_practices(title,question_set_id,publish_status) VALUES($1,$2,'PUBLISHED') RETURNING id`, chapter.Name+" review", setID) if err != nil { return err } if _, err = tx.Exec(ctx, `INSERT INTO exam_prep.practice_parents(practice_id,parent_kind,parent_id) VALUES($1,'UNIT',$2) ON CONFLICT DO NOTHING`, quizID, chapterID); err != nil { return err } for qi, title := range chapter.Lessons { questionID, err := s.entity("question", fmt.Sprintf("%s/question-%d", key, qi+1), "questions", `INSERT INTO questions(question_text,question_type,difficulty_level,points,explanation,status) VALUES($1,'MCQ','EASY',1,'Small, deliberate practice helps you apply what you learned.','PUBLISHED') RETURNING id`, "After the lesson '"+title+"', what is the best way to improve?") if err != nil { return err } for oi, option := range []string{"Try a small real-world example and reflect on it", "Skip practice entirely", "Avoid asking questions"} { var exists bool if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM question_options WHERE question_id=$1 AND option_order=$2)`, questionID, oi+1).Scan(&exists); err != nil { return err } if !exists { if _, err = tx.Exec(ctx, `INSERT INTO question_options(question_id,option_text,option_order,is_correct) VALUES($1,$2,$3,$4)`, questionID, option, oi+1, oi == 0); err != nil { return err } } } if _, err = tx.Exec(ctx, `INSERT INTO question_set_items(set_id,question_id,display_order) VALUES($1,$2,$3) ON CONFLICT(set_id,question_id) DO NOTHING`, setID, questionID, qi+1); err != nil { return err } } } } // A draft fixture verifies that public browsing cannot reveal unpublished content. if _, err = s.entity("course", "draft", "exam_prep.catalog_courses", `INSERT INTO exam_prep.catalog_courses(name,description,category,sort_order,publish_status,access_tier) SELECT '[Demo draft] Coming soon','Unpublished fixture: must not appear in the public catalog.','EDUCATION',COALESCE(MAX(sort_order),0)+1,'DRAFT','FREE' FROM exam_prep.catalog_courses RETURNING id`); err != nil { return err } planID, err := s.entity("plan", "education-demo", "subscription_plans", `INSERT INTO subscription_plans(name,description,duration_value,duration_unit,price,currency,is_active,category,is_free) VALUES('[Demo] Education access','Testing only: grants premium learning access for 30 days.',1,'MONTH',0,'ETB',false,'EDUCATION',true) RETURNING id`) if err != nil { return err } _, err = s.entity("subscription", "premium-student", "user_subscriptions", `INSERT INTO user_subscriptions(user_id,plan_id,starts_at,expires_at,status,payment_method,auto_renew) VALUES($1,$2,NOW(),NOW()+INTERVAL '30 days','ACTIVE','DEMO',false) RETURNING id`, userIDs["premium@demo.rezina.test"], planID) if err != nil { return err } // Refresh only this seed-owned subscription when rerunning the demo fixture. if _, err = tx.Exec(ctx, `UPDATE user_subscriptions SET status='ACTIVE',starts_at=NOW(),expires_at=NOW()+INTERVAL '30 days' WHERE id=(SELECT entity_id FROM demo_seed_entities WHERE kind='subscription' AND seed_key='premium-student')`); err != nil { return err } return tx.Commit(ctx) }