package store import ( "context" "database/sql" "encoding/json" "errors" "strings" "speech-learning-api/internal/domain" ) func (s *PostgresStore) CourseModules(ctx context.Context, userID, language, level string) ([]domain.CourseModule, error) { rows, err := s.db.QueryContext(ctx, `SELECT id FROM course_modules WHERE target_language=$1 AND cefr_level=$2 ORDER BY sort_order, id`, language, level) if err != nil { return nil, err } var ids []string for rows.Next() { var id string if err := rows.Scan(&id); err != nil { rows.Close() return nil, err } ids = append(ids, id) } if err := rows.Err(); err != nil { rows.Close() return nil, err } rows.Close() modules := make([]domain.CourseModule, 0, len(ids)) for _, id := range ids { detail, err := s.CourseModule(ctx, userID, language, level, id) if err != nil { return nil, err } modules = append(modules, detail.Module) } return modules, nil } func (s *PostgresStore) CourseModule(ctx context.Context, userID, language, level, id string) (domain.CourseModuleDetail, error) { var detail domain.CourseModuleDetail err := s.db.QueryRowContext(ctx, `SELECT id, title, description, target_language, cefr_level, version FROM course_modules WHERE id=$1 AND target_language=$2 AND cefr_level=$3`, id, language, level). Scan(&detail.Module.ID, &detail.Module.Title, &detail.Module.Description, &detail.Module.TargetLanguage, &detail.Module.CEFRLevel, &detail.Module.Version) if errors.Is(err, sql.ErrNoRows) { return detail, ErrNotFound } if err != nil { return detail, err } rows, err := s.db.QueryContext(ctx, ` SELECT t.id, t.skill, t.kind, t.prompt, t.passage, t.options_json, t.pronunciation_exercise_id, EXISTS(SELECT 1 FROM course_attempts a WHERE a.task_id=t.id AND a.user_id=$2) OR (t.pronunciation_exercise_id IS NOT NULL AND EXISTS(SELECT 1 FROM attempts a WHERE a.exercise_id=t.pronunciation_exercise_id AND a.user_id=$2)), EXISTS(SELECT 1 FROM course_attempts a WHERE a.task_id=t.id AND a.user_id=$2 AND a.correct) OR (t.pronunciation_exercise_id IS NOT NULL AND EXISTS(SELECT 1 FROM attempts a WHERE a.exercise_id=t.pronunciation_exercise_id AND a.user_id=$2 AND a.overall_score>=75)) FROM course_tasks t WHERE t.module_id=$1 AND t.source='seed' ORDER BY t.sort_order, t.id`, id, userID) if err != nil { return detail, err } tasks := make([]domain.CourseTask, 0) var pronunciationIDs []string for rows.Next() { var task domain.CourseTask var options []byte var exerciseID sql.NullString if err := rows.Scan(&task.ID, &task.Skill, &task.Kind, &task.Prompt, &task.Passage, &options, &exerciseID, &task.Attempted, &task.Correct); err != nil { rows.Close() return detail, err } if err := json.Unmarshal(options, &task.Options); err != nil { rows.Close() return detail, err } task.ModuleID = id task.Source = "seed" if exerciseID.Valid { pronunciationIDs = append(pronunciationIDs, exerciseID.String) } else { pronunciationIDs = append(pronunciationIDs, "") } tasks = append(tasks, task) } if err := rows.Err(); err != nil { rows.Close() return detail, err } rows.Close() for i := range tasks { if pronunciationIDs[i] != "" { exercise, err := s.GetExercise(ctx, pronunciationIDs[i], userID) if err != nil { return detail, err } tasks[i].PronunciationExercise = &exercise } if tasks[i].Attempted { detail.Module.AttemptedCount++ } if tasks[i].Correct { detail.Module.CorrectCount++ } } detail.Module.TaskCount = len(tasks) detail.Tasks = tasks return detail, nil } func (s *PostgresStore) CourseTaskKey(ctx context.Context, taskID, userID, language, level string) (domain.CourseTaskKey, error) { var key domain.CourseTaskKey var answers []byte err := s.db.QueryRowContext(ctx, `SELECT t.id, t.module_id, t.skill, t.kind, t.audio_text, t.accepted_answers_json, t.solution, t.explanation FROM course_tasks t JOIN course_modules m ON m.id=t.module_id WHERE t.id=$1 AND m.target_language=$2 AND m.cefr_level=$3 AND (t.owner_user_id IS NULL OR t.owner_user_id=$4)`, taskID, language, level, userID). Scan(&key.ID, &key.ModuleID, &key.Skill, &key.Kind, &key.AudioText, &answers, &key.Solution, &key.Explanation) if errors.Is(err, sql.ErrNoRows) { return key, ErrNotFound } if err != nil { return key, err } if err := json.Unmarshal(answers, &key.AcceptedAnswers); err != nil { return key, err } return key, nil } func (s *PostgresStore) SaveCourseAttempt(ctx context.Context, userID, taskID, answer string, correct bool) (string, error) { id := NewID("cat") result, err := s.db.ExecContext(ctx, `INSERT INTO course_attempts (id,user_id,task_id,answer,correct) SELECT $1,$2,t.id,$4,$5 FROM course_tasks t WHERE t.id=$3 AND (t.owner_user_id IS NULL OR t.owner_user_id=$2)`, id, userID, taskID, strings.TrimSpace(answer), correct) if err != nil { return "", err } count, err := result.RowsAffected() if err != nil { return "", err } if count != 1 { return "", ErrNotFound } return id, nil } const courseSchemaSQL = ` CREATE TABLE IF NOT EXISTS course_modules ( id TEXT PRIMARY KEY, title TEXT NOT NULL, description TEXT NOT NULL, target_language TEXT NOT NULL, cefr_level TEXT NOT NULL, version INT NOT NULL, sort_order INT NOT NULL ); CREATE TABLE IF NOT EXISTS course_tasks ( id TEXT PRIMARY KEY, module_id TEXT NOT NULL REFERENCES course_modules(id), skill TEXT NOT NULL CHECK (skill IN ('vocabulary','listening','reading','grammar','writing','pronunciation')), kind TEXT NOT NULL CHECK (kind IN ('choice','short_text','pronunciation')), prompt TEXT NOT NULL, passage TEXT NOT NULL DEFAULT '', audio_text TEXT NOT NULL DEFAULT '', options_json JSONB NOT NULL DEFAULT '[]'::jsonb, accepted_answers_json JSONB NOT NULL DEFAULT '[]'::jsonb, solution TEXT NOT NULL DEFAULT '', explanation TEXT NOT NULL DEFAULT '', pronunciation_exercise_id TEXT REFERENCES exercises(id), sort_order INT NOT NULL ); ALTER TABLE course_tasks ADD COLUMN IF NOT EXISTS source TEXT NOT NULL DEFAULT 'seed' CHECK (source IN ('seed','flowise')); ALTER TABLE course_tasks ADD COLUMN IF NOT EXISTS owner_user_id TEXT REFERENCES users(id); ALTER TABLE course_tasks ADD COLUMN IF NOT EXISTS learning_goal_id TEXT NOT NULL DEFAULT ''; ALTER TABLE course_tasks ADD COLUMN IF NOT EXISTS schema_version INT NOT NULL DEFAULT 1; ALTER TABLE course_tasks ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now(); ALTER TABLE course_tasks ADD COLUMN IF NOT EXISTS generation_request_id TEXT; ALTER TABLE course_tasks ADD COLUMN IF NOT EXISTS prompt_fingerprint TEXT; DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='course_tasks_source_owner_check' AND conrelid='course_tasks'::regclass) THEN ALTER TABLE course_tasks ADD CONSTRAINT course_tasks_source_owner_check CHECK ( (source='seed' AND owner_user_id IS NULL) OR (source='flowise' AND owner_user_id IS NOT NULL AND generation_request_id IS NOT NULL AND prompt_fingerprint IS NOT NULL) ); END IF; END $$; CREATE UNIQUE INDEX IF NOT EXISTS idx_course_generation_request ON course_tasks(owner_user_id,generation_request_id); CREATE UNIQUE INDEX IF NOT EXISTS idx_course_generation_prompt ON course_tasks(owner_user_id,module_id,prompt_fingerprint); CREATE INDEX IF NOT EXISTS idx_course_tasks_owner_module ON course_tasks(owner_user_id,module_id,created_at); CREATE TABLE IF NOT EXISTS course_attempts ( id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, task_id TEXT NOT NULL REFERENCES course_tasks(id), answer TEXT NOT NULL, correct BOOLEAN NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX IF NOT EXISTS idx_course_attempts_user_task ON course_attempts(user_id,task_id); ` // Seed IDs include the content version. Existing task answers remain immutable // so attempts always refer to the exact exercise that was answered. var courseSeedSQL = []string{ `INSERT INTO course_modules (id,title,description,target_language,cefr_level,version,sort_order) VALUES ('a1_introductions_v1','Sich vorstellen','Name, Herkunft und einfache persönliche Angaben','en-US','A1',1,1) ON CONFLICT (id) DO NOTHING`, `INSERT INTO course_tasks (id,module_id,skill,kind,prompt,passage,audio_text,options_json,accepted_answers_json,solution,explanation,pronunciation_exercise_id,sort_order) VALUES ('a1i_v1_vocab_1','a1_introductions_v1','vocabulary','choice','Was bedeutet „name“?','','','["Name","Wohnort","Alter"]','["Name"]','Name','„Name“ ist auf Englisch „name“.',NULL,10), ('a1i_v1_vocab_2','a1_introductions_v1','vocabulary','choice','Was bedeutet „from“ in „I am from Berlin“?','','','["aus","mit","bei"]','["aus"]','aus','„From“ nennt hier die Herkunft.',NULL,20), ('a1i_v1_listen_1','a1_introductions_v1','listening','choice','Wie heißt die Person?','','Hello, my name is Anna.','["Anna","Emma","Maria"]','["Anna"]','Anna','Du hörst: „My name is Anna.“',NULL,30), ('a1i_v1_listen_2','a1_introductions_v1','listening','choice','Woher kommt Ben?','','My name is Ben. I am from London.','["Berlin","London","Paris"]','["London"]','London','Du hörst: „I am from London.“',NULL,40), ('a1i_v1_read_1','a1_introductions_v1','reading','choice','Wie heißt die Person?','Hello! My name is Mia. I am from Berlin.','','["Mia","Anna","Ben"]','["Mia"]','Mia','Im Text steht: „My name is Mia.“',NULL,50), ('a1i_v1_read_2','a1_introductions_v1','reading','choice','Woher kommt Sam?','Hi, I am Sam. I am from Hamburg.','','["London","Hamburg","Berlin"]','["Hamburg"]','Hamburg','Im Text steht: „I am from Hamburg.“',NULL,60), ('a1i_v1_grammar_1','a1_introductions_v1','grammar','choice','Ergänze: I ___ from Berlin.','','','["am","is","are"]','["am"]','am','Nach „I“ steht „am“.',NULL,70), ('a1i_v1_grammar_2','a1_introductions_v1','grammar','choice','Ergänze: My name ___ Anna.','','','["am","is","are"]','["is"]','is','„My name“ steht mit „is“.',NULL,80), ('a1i_v1_write_1','a1_introductions_v1','writing','short_text','Schreibe auf Englisch: Ich heiße Anna.','','','[]','["My name is Anna","I am Anna","I’m Anna"]','My name is Anna.','„My name is Anna“ ist eine einfache Vorstellung.',NULL,90), ('a1i_v1_write_2','a1_introductions_v1','writing','short_text','Schreibe auf Englisch: Ich komme aus Berlin.','','','[]','["I am from Berlin","I’m from Berlin"]','I am from Berlin.','„I am from“ nennt die Herkunft.',NULL,100), ('a1i_v1_speak_1','a1_introductions_v1','pronunciation','pronunciation','Sprich den Satz nach.','','','[]','[]','','', 'ex_a1_hello',110), ('a1i_v1_speak_2','a1_introductions_v1','pronunciation','pronunciation','Sprich den Satz nach.','','','[]','[]','','', 'ex_a1_from',120) ON CONFLICT (id) DO NOTHING`, }