Migrate production catalog to makeup curriculum and archive legacy fixtures

This commit is contained in:
Yared Yemane 2026-11-03 12:17:16 +03:00
parent fa646a6243
commit be6ba7c676
12 changed files with 536 additions and 7 deletions

View File

@ -0,0 +1,9 @@
BEGIN;
DROP TRIGGER prevent_archived_course_publication ON exam_prep.catalog_courses;
DROP FUNCTION prevent_archived_course_publication();
-- Restore only records still in the exact state written by this migration.
UPDATE exam_prep.catalog_courses c SET publish_status=a.previous_publish_status,updated_at=a.previous_updated_at
FROM academy_archived_courses a WHERE a.course_id=c.id AND c.publish_status='DRAFT' AND c.updated_at=a.archived_at;
DROP TABLE academy_archived_courses;
-- Keep starter drafts and provenance: deleting them could erase subsequent authored work or progress.
COMMIT;

View File

@ -0,0 +1,403 @@
BEGIN;
-- Preserve legacy fixtures and learner progress rather than deleting their trees.
CREATE TABLE academy_archived_courses (
course_id BIGINT PRIMARY KEY REFERENCES exam_prep.catalog_courses(id) ON DELETE CASCADE,
previous_publish_status TEXT NOT NULL,
previous_updated_at TIMESTAMPTZ,
archived_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
reason TEXT NOT NULL
);
-- Original defaults have empty CEFR chapter shells; retain any authored lessons or practices.
-- Ignore root updated_at: reordering also updates it without changing course content.
INSERT INTO academy_archived_courses(course_id,previous_publish_status,previous_updated_at,reason)
SELECT c.id,c.publish_status,c.updated_at,'Original non-artistry default program'
FROM exam_prep.catalog_courses c
WHERE EXISTS(SELECT 1 FROM lms_exam_prep_migration_map mm WHERE mm.entity_kind='CATALOG_COURSE' AND mm.migrated_id=c.id)
AND (c.name,c.description) IN (
('Beginner','Default program for the beginner level.'),
('Intermediate','Default program for the intermediate level.'),
('Advanced','Default program for the advanced level.'))
AND NOT EXISTS(SELECT 1 FROM exam_prep.units u WHERE u.catalog_course_id=c.id AND (u.updated_at IS NOT NULL OR u.created_at>c.created_at))
AND NOT EXISTS(SELECT 1 FROM exam_prep.unit_modules m JOIN exam_prep.units u ON u.id=m.unit_id WHERE u.catalog_course_id=c.id AND m.updated_at IS NOT NULL)
AND NOT EXISTS(SELECT 1 FROM exam_prep.unit_module_lessons l JOIN exam_prep.unit_modules m ON m.id=l.unit_module_id JOIN exam_prep.units u ON u.id=m.unit_id WHERE u.catalog_course_id=c.id)
AND NOT EXISTS(SELECT 1 FROM exam_prep.practice_parents pp WHERE (pp.parent_kind='CATALOG_COURSE' AND pp.parent_id=c.id)
OR (pp.parent_kind='UNIT' AND pp.parent_id IN(SELECT id FROM exam_prep.units WHERE catalog_course_id=c.id)));
DO $archive$
BEGIN
IF to_regclass('public.demo_seed_entities') IS NOT NULL THEN
INSERT INTO academy_archived_courses(course_id,previous_publish_status,previous_updated_at,reason)
SELECT c.id,c.publish_status,c.updated_at,'Retired general-learning demo fixture'
FROM exam_prep.catalog_courses c JOIN demo_seed_entities d ON d.entity_id=c.id AND d.kind='course'
WHERE (d.seed_key,c.name,c.description) IN (
('everyday-english','Everyday English','Build confidence with introductions, daily conversations, and practical vocabulary.'),
('workplace-communication','Workplace Communication','Communicate clearly in meetings, write effective messages, and present your ideas.'),
('digital-skills','Digital Skills Essentials','Learn practical habits for working online, organizing information, and collaborating safely.'),
('draft','[Demo draft] Coming soon','Unpublished fixture: must not appear in the public catalog.'))
AND NOT EXISTS(SELECT 1 FROM exam_prep.units u WHERE u.catalog_course_id=c.id AND (u.updated_at IS NOT NULL OR u.created_at>c.created_at))
AND NOT EXISTS(SELECT 1 FROM exam_prep.unit_modules m JOIN exam_prep.units u ON u.id=m.unit_id WHERE u.catalog_course_id=c.id AND (m.updated_at IS NOT NULL OR m.created_at>c.created_at))
AND NOT EXISTS(SELECT 1 FROM exam_prep.unit_module_lessons l JOIN exam_prep.unit_modules m ON m.id=l.unit_module_id JOIN exam_prep.units u ON u.id=m.unit_id WHERE u.catalog_course_id=c.id AND (l.updated_at IS NOT NULL OR l.created_at>c.created_at))
AND NOT EXISTS(SELECT 1 FROM exam_prep.lesson_practices p JOIN exam_prep.practice_parents pp ON pp.practice_id=p.id JOIN question_sets qs ON qs.id=p.question_set_id
WHERE ((pp.parent_kind='CATALOG_COURSE' AND pp.parent_id=c.id)
OR (pp.parent_kind='UNIT' AND pp.parent_id IN(SELECT id FROM exam_prep.units WHERE catalog_course_id=c.id))
OR (pp.parent_kind='LESSON' AND pp.parent_id IN(SELECT l.id FROM exam_prep.unit_module_lessons l JOIN exam_prep.unit_modules m ON m.id=l.unit_module_id JOIN exam_prep.units u ON u.id=m.unit_id WHERE u.catalog_course_id=c.id)))
AND (p.updated_at IS NOT NULL OR p.created_at>c.created_at OR qs.updated_at IS NOT NULL OR qs.created_at>c.created_at
OR EXISTS(SELECT 1 FROM question_set_items i JOIN questions q ON q.id=i.question_id WHERE i.set_id=qs.id
AND (q.updated_at IS NOT NULL OR q.created_at>c.created_at OR EXISTS(SELECT 1 FROM question_options o WHERE o.question_id=q.id AND o.created_at>c.created_at)))))
ON CONFLICT DO NOTHING;
END IF;
END $archive$;
UPDATE exam_prep.catalog_courses c SET publish_status='DRAFT',updated_at=a.archived_at
FROM academy_archived_courses a WHERE a.course_id=c.id;
CREATE FUNCTION prevent_archived_course_publication() RETURNS trigger AS $guard$
BEGIN
IF NEW.publish_status='PUBLISHED' AND EXISTS(SELECT 1 FROM academy_archived_courses WHERE course_id=NEW.id) THEN
RAISE EXCEPTION 'Archived legacy courses cannot be published' USING ERRCODE='23514';
END IF;
RETURN NEW;
END $guard$ LANGUAGE plpgsql;
CREATE TRIGGER prevent_archived_course_publication BEFORE UPDATE ON exam_prep.catalog_courses
FOR EACH ROW EXECUTE FUNCTION prevent_archived_course_publication();
-- Production-safe starter content: drafts only, no accounts, subscriptions or fake teaching videos.
CREATE TABLE IF NOT EXISTS academy_curriculum_courses (
seed_key TEXT PRIMARY KEY,
course_id BIGINT NOT NULL UNIQUE REFERENCES exam_prep.catalog_courses(id) ON DELETE CASCADE
);
-- Share fixture identities with the optional non-production seeder so it reuses
-- these drafts instead of creating duplicate courses. No demo accounts are created.
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));
DO $curriculum$
DECLARE curriculum JSONB := $data$
[
{
"Key": "makeup-foundations",
"Name": "Makeup Artistry Foundations",
"Description": "Build a professional toolkit, prepare a clean workstation, and create a balanced everyday complexion.",
"Tier": "FREE",
"Chapters": [
{
"Name": "Your kit and studio",
"Description": "Get to know core tools and organize a thoughtful makeup practice routine.",
"Lessons": [
{
"Title": "Build your first makeup kit",
"Description": "Identify complexion, eye, and lip essentials. Organize products by purpose and create a kit checklist for a simple everyday look.",
"Question": "Which kit is the best starting point for practicing a complete everyday look?",
"Explanation": "A balanced starter kit covers the main areas of the face and includes tools for controlled application.",
"Options": [
"Only several shades of glitter",
"Complexion products, eye and lip basics, and suitable brushes",
"Only one foundation and no tools"
],
"CorrectIndex": 1
},
{
"Title": "Choose and control your brushes",
"Description": "Compare dense and fluffy brushes. Practice light pressure and use separate tools to place, blend, and refine product.",
"Question": "Which brush is best suited to softly blending the edges of powder eyeshadow?",
"Explanation": "A fluffy blending brush helps diffuse powder edges using light pressure.",
"Options": [
"A fluffy blending brush",
"A rigid spatula",
"A large body brush"
],
"CorrectIndex": 0
},
{
"Title": "Set up a clean workstation",
"Description": "Separate clean tools from used tools. Practice dispensing products onto a palette and using disposable applicators without returning them to the product.",
"Question": "After using a disposable lip applicator on a client, what should you do?",
"Explanation": "A used disposable applicator should not be returned to a shared product or reused on another person.",
"Options": [
"Return it to the shared lip product",
"Save it for the next client",
"Discard it and use a fresh applicator when more product is needed"
],
"CorrectIndex": 2
}
]
},
{
"Name": "Complexion essentials",
"Description": "Explore shade matching, controlled coverage, and a natural-looking finish.",
"Lessons": [
{
"Title": "Match foundation and undertone",
"Description": "Compare foundation swatches near the jawline in even light. Observe how each shade relates to both face and neck before choosing a match.",
"Question": "What is the most useful way to compare foundation shades for a face-and-neck match?",
"Explanation": "Jawline swatches help compare the foundation with the surrounding face and neck.",
"Options": [
"Choose the lightest shade in the range",
"Compare jawline swatches in even light",
"Choose from the color of the bottle alone"
],
"CorrectIndex": 1
},
{
"Title": "Build a thin, even base",
"Description": "Apply a small amount of foundation first. Blend the edges and add coverage only where the look calls for it.",
"Question": "How can you build coverage while retaining control of the finish?",
"Explanation": "Thin layers make it easier to assess coverage, texture, and blending before adding more.",
"Options": [
"Apply several thick coats at once",
"Leave product edges unblended",
"Apply thin layers and assess each layer"
],
"CorrectIndex": 2
},
{
"Title": "Balance blush and powder",
"Description": "Practice placing blush with a light hand. Apply powder selectively and review the finished look in consistent lighting.",
"Question": "How should you approach blush when learning placement and intensity?",
"Explanation": "Gradual application gives you control of intensity and allows you to adjust placement.",
"Options": [
"Start lightly and build the color gradually",
"Apply the maximum amount immediately",
"Avoid checking the result in a mirror"
],
"CorrectIndex": 0
}
]
}
]
},
{
"Key": "makeup-bridal",
"Name": "Bridal and Occasion Makeup",
"Description": "Plan a client-focused bridal look with refined eyes, balanced lips, and a repeatable finishing routine.",
"Tier": "PREMIUM",
"Chapters": [
{
"Name": "Design the bridal look",
"Description": "Translate a consultation into a cohesive look and practice polished eye techniques.",
"Lessons": [
{
"Title": "Run a bridal consultation",
"Description": "Discuss the client's preferred finish, reference images, event schedule, and styling. Record the agreed look and the products used during the trial.",
"Question": "What is the purpose of a bridal makeup trial record?",
"Explanation": "A trial record helps the artist and client agree on the design and reproduce it consistently.",
"Options": [
"To replace the client's preferences with a fixed look",
"To record agreed choices and help reproduce the look",
"To avoid discussing the event"
],
"CorrectIndex": 1
},
{
"Title": "Create a soft neutral eye",
"Description": "Place transition, depth, and lid shades deliberately. Blend the borders and compare the balance of both eyes as you work.",
"Question": "What should you check while developing a balanced eye look?",
"Explanation": "Checking both eyes during application makes it easier to notice and refine differences.",
"Options": [
"Only the brush handle color",
"Only one eye until the entire look is finished",
"Both eyes in consistent lighting"
],
"CorrectIndex": 2
},
{
"Title": "Refine brows and liner",
"Description": "Practice short, controlled strokes for brows and liner. Step back to compare shape and definition with the rest of the look.",
"Question": "Which approach provides control when refining a brow?",
"Explanation": "Short strokes allow the artist to build definition gradually and reassess the shape.",
"Options": [
"Use short strokes and review the shape often",
"Fill the entire area with one heavy stroke",
"Choose the darkest possible product for every client"
],
"CorrectIndex": 0
}
]
},
{
"Name": "Finish and document",
"Description": "Balance the final details and prepare a clear record for an occasion look.",
"Lessons": [
{
"Title": "Shape a balanced lip",
"Description": "Outline a lip shape with controlled placement. Add color in thin layers and refine the edges with a clean detail brush.",
"Question": "Which tool can help refine an uneven lip-color edge?",
"Explanation": "A clean detail brush gives controlled access to the edge of the lip color.",
"Options": [
"A used mascara wand",
"A clean detail brush",
"A large powder puff"
],
"CorrectIndex": 1
},
{
"Title": "Check the look on camera",
"Description": "Photograph the finished look in even light. Compare the image with the mirror view and note any visible color or blending differences.",
"Question": "Why review both a photograph and the mirror view of an occasion look?",
"Explanation": "Comparing views helps identify details that may read differently on camera.",
"Options": [
"To guarantee identical results under every light",
"To avoid asking the client for feedback",
"To evaluate how the look reads in each view"
],
"CorrectIndex": 2
},
{
"Title": "Plan a touch-up kit",
"Description": "Choose touch-up items that match the products and finish of the agreed look. Label the kit and record concise application notes for the client.",
"Question": "What makes a useful touch-up kit for a bridal look?",
"Explanation": "A look-specific kit and clear notes make it easier to maintain the agreed finish.",
"Options": [
"Items selected for the agreed look with clear application notes",
"A random set of unrelated colors",
"Unlabeled products without instructions"
],
"CorrectIndex": 0
}
]
}
]
},
{
"Key": "makeup-editorial",
"Name": "Creative and Editorial Makeup",
"Description": "Develop a visual concept, explore color and texture, and document a cohesive makeup portfolio.",
"Tier": "FREE",
"Chapters": [
{
"Name": "Color and concept",
"Description": "Build a mood board and use color relationships to plan an intentional design.",
"Lessons": [
{
"Title": "Build an editorial mood board",
"Description": "Collect references for color, shape, texture, and styling. Choose a clear focal point and sketch a face chart before application.",
"Question": "What should a useful makeup mood board communicate?",
"Explanation": "A focused mood board gives the team a shared visual direction for the makeup design.",
"Options": [
"Only the price of the products",
"A coherent direction for color, shape, and texture",
"Unrelated images with no design direction"
],
"CorrectIndex": 1
},
{
"Title": "Work with color relationships",
"Description": "Compare neighboring and complementary colors on a color wheel. Make swatches and choose a limited palette for a creative look.",
"Question": "Which pair is complementary on a traditional artist's color wheel?",
"Explanation": "Blue and orange sit opposite each other on a traditional artist's color wheel.",
"Options": [
"Blue and orange",
"Blue and green",
"Red and orange"
],
"CorrectIndex": 0
},
{
"Title": "Create a statement eye",
"Description": "Sketch a graphic eye shape on a face chart. Practice placement with controlled strokes and refine the outline before adding more detail.",
"Question": "What is a useful first step when planning a graphic eye design?",
"Explanation": "Planning the shape and focal point gives the artist a clear structure for application.",
"Options": [
"Add every available color immediately",
"Ignore the intended shape",
"Sketch the shape and choose a focal point"
],
"CorrectIndex": 2
}
]
},
{
"Name": "Portfolio practice",
"Description": "Coordinate textures, capture consistent images, and reflect on the finished work.",
"Lessons": [
{
"Title": "Combine matte and luminous textures",
"Description": "Swatch matte and luminous finishes side by side. Place them intentionally so the texture supports the chosen focal point.",
"Question": "Why swatch different finishes before applying an editorial look?",
"Explanation": "Swatching makes differences in finish visible before committing them to the full look.",
"Options": [
"To make all products look identical",
"To compare how their textures support the design",
"To replace a design plan with random choices"
],
"CorrectIndex": 1
},
{
"Title": "Photograph your finished look",
"Description": "Use consistent lighting, framing, and a simple background. Capture front and detail views that accurately show your blending and color choices.",
"Question": "Which practice makes a makeup portfolio easier to compare across looks?",
"Explanation": "Consistent presentation makes it easier to compare the makeup work itself.",
"Options": [
"Use consistent lighting and framing",
"Change the lighting dramatically for every image",
"Hide all close-up details"
],
"CorrectIndex": 0
},
{
"Title": "Review and improve your technique",
"Description": "Compare the finished look with your face chart and references. Record one successful technique and one specific adjustment for your next practice.",
"Question": "Which reflection is the most actionable after completing a practice look?",
"Explanation": "A specific observation creates a practical goal for the next attempt.",
"Options": [
"There is nothing to review",
"I should change everything without choosing a goal",
"I will refine one specific blending edge in my next practice"
],
"CorrectIndex": 2
}
]
}
]
}
]
$data$::jsonb;
c JSONB; ch JSONB; l JSONB; opt TEXT;
course_id BIGINT; chapter_id BIGINT; module_id BIGINT; set_id BIGINT; quiz_id BIGINT; question_id BIGINT; lesson_id BIGINT;
chapter_order INTEGER; lesson_order INTEGER; option_order INTEGER;
BEGIN
FOR c IN SELECT value FROM jsonb_array_elements(curriculum) LOOP
-- Never overwrite an existing authored or demo makeup course.
IF EXISTS(SELECT 1 FROM exam_prep.catalog_courses cc WHERE cc.name=c->>'Name' OR cc.id IN(SELECT d.entity_id FROM demo_seed_entities d WHERE d.kind='course' AND d.seed_key=c->>'Key')) THEN CONTINUE; END IF;
INSERT INTO exam_prep.catalog_courses(name,description,category,sort_order,publish_status,access_tier)
SELECT c->>'Name',c->>'Description','EDUCATION',COALESCE(MAX(sort_order),0)+1,'DRAFT',c->>'Tier'
FROM exam_prep.catalog_courses RETURNING id INTO course_id;
INSERT INTO academy_curriculum_courses VALUES(c->>'Key',course_id);
INSERT INTO demo_seed_entities VALUES('course',c->>'Key',course_id) ON CONFLICT DO NOTHING;
chapter_order := 0;
FOR ch IN SELECT value FROM jsonb_array_elements(c->'Chapters') LOOP
chapter_order := chapter_order+1;
INSERT INTO exam_prep.units(catalog_course_id,name,description,sort_order,publish_status,access_tier)
VALUES(course_id,ch->>'Name',ch->>'Description',chapter_order,'DRAFT','FREE') RETURNING id INTO chapter_id;
INSERT INTO demo_seed_entities VALUES('chapter',(c->>'Key')||'/chapter-'||chapter_order,chapter_id) ON CONFLICT DO NOTHING;
INSERT INTO exam_prep.unit_modules(unit_id,name,sort_order,publish_status,access_tier)
VALUES(chapter_id,'__chapter_lessons__',1,'PUBLISHED','FREE') RETURNING id INTO module_id;
INSERT INTO exam_prep.chapter_lesson_containers VALUES(chapter_id,module_id);
INSERT INTO question_sets(title,description,set_type,status,passing_score,shuffle_questions)
VALUES((ch->>'Name')||' review','Makeup artistry knowledge check','QUIZ','DRAFT',60,false) RETURNING id INTO set_id;
INSERT INTO demo_seed_entities VALUES('question_set',(c->>'Key')||'/chapter-'||chapter_order,set_id) ON CONFLICT DO NOTHING;
INSERT INTO exam_prep.lesson_practices(title,question_set_id,publish_status)
VALUES((ch->>'Name')||' review',set_id,'DRAFT') RETURNING id INTO quiz_id;
INSERT INTO demo_seed_entities VALUES('quiz',(c->>'Key')||'/chapter-'||chapter_order,quiz_id) ON CONFLICT DO NOTHING;
INSERT INTO exam_prep.practice_parents(practice_id,parent_kind,parent_id) VALUES(quiz_id,'UNIT',chapter_id);
lesson_order := 0;
FOR l IN SELECT value FROM jsonb_array_elements(ch->'Lessons') LOOP
lesson_order := lesson_order+1;
INSERT INTO exam_prep.unit_module_lessons(unit_module_id,title,description,sort_order,publish_status,access_tier)
VALUES(module_id,l->>'Title',l->>'Description',lesson_order,'DRAFT','FREE') RETURNING id INTO lesson_id;
INSERT INTO demo_seed_entities VALUES('lesson',(c->>'Key')||'/chapter-'||chapter_order||'/lesson-'||lesson_order,lesson_id) ON CONFLICT DO NOTHING;
INSERT INTO questions(question_text,question_type,difficulty_level,points,explanation,status)
VALUES(l->>'Question','MCQ','EASY',1,l->>'Explanation','DRAFT') RETURNING id INTO question_id;
INSERT INTO demo_seed_entities VALUES('question',(c->>'Key')||'/chapter-'||chapter_order||'/question-'||lesson_order,question_id) ON CONFLICT DO NOTHING;
option_order := 0;
FOR opt IN SELECT value FROM jsonb_array_elements_text(l->'Options') LOOP
option_order := option_order+1;
INSERT INTO question_options(question_id,option_text,option_order,is_correct)
VALUES(question_id,opt,option_order,option_order-1=(l->>'CorrectIndex')::integer);
END LOOP;
INSERT INTO question_set_items(set_id,question_id,display_order) VALUES(set_id,question_id,lesson_order);
END LOOP;
END LOOP;
END LOOP;
END $curriculum$;
COMMIT;

View File

@ -129,7 +129,7 @@ FROM exam_prep.catalog_courses c
LEFT JOIN catalog_course_counts cc ON cc.catalog_course_id = c.id
WHERE (
sqlc.arg('published_only')::boolean = FALSE
OR c.publish_status = 'PUBLISHED'::TEXT
OR (c.publish_status = 'PUBLISHED'::TEXT AND NOT EXISTS(SELECT 1 FROM academy_archived_courses a WHERE a.course_id=c.id))
)
ORDER BY c.sort_order ASC, c.id ASC
LIMIT $1 OFFSET $2;

View File

@ -163,3 +163,11 @@ That test writes demo data, runs the seed twice, checks login password hashes,
and verifies unpublished-course/descendant filtering. It is skipped unless
`DEMO_TEST_DB_URL` is explicitly provided and never reads application `DB_URL`.
In `RezinaLMS-Admin`, run `npm run test:learning` and `npm run build`.
### Production curriculum versus optional demo fixtures
Migration `000006_makeup_course_catalog` installs makeup starter drafts without test accounts
or sample video fixtures and archives untouched legacy course fixtures. It runs even when the
production demo-seed command is skipped. See [the catalog conversion notes](makeup-artistry-backend.md#production-course-catalog-conversion).
The demo seeder reuses these course/chapter/lesson/quiz IDs and does not automatically publish
existing starter drafts; publish reviewed content explicitly in the admin.

View File

@ -68,3 +68,26 @@ Custom and historical values are preserved in analytics; historical courses rema
New subscription plans use EDUCATION, displayed as Makeup Artistry. Historical subscription categories
remain available in reports, while plan creation offers only the supported makeup category.
The embedded demo seed adds the new choices and fills only empty demo profile fields.
## Production course catalog conversion
Apply `000006_makeup_course_catalog` before deploying the updated backend, then deploy the admin.
Unlike the optional demo command, this migration runs in production and creates no accounts,
passwords, payments, or subscriptions. It archives original empty CEFR/default program shells
and unchanged, seed-owned general-learning courses. Existing authored changes are retained;
course IDs, descendants, enrollments, and progress are not deleted.
The admin's Academy courses view excludes archived fixtures; Legacy archive retains access to
those historical records. Archived courses are unpublished and cannot be republished while
archived. Public catalog queries also exclude them explicitly.
Three makeup starter courses contain six chapters, eighteen lesson outlines, and six quizzes
with eighteen subject-specific MCQs. They are drafts for educator review, with no sample cartoon
videos or invented instructional recordings. Add teaching media and review/publish lessons,
quizzes, chapters, and courses through the existing authoring workflow. Existing makeup courses
are not overwritten or duplicated. Shared fixture identity metadata lets the development demo
seeder reuse these same IDs and preserves their publication status.
Rollback restores only unchanged archived publication states. It retains starter drafts and their
identity metadata to preserve later instructor edits and learner records. Reapplying the migration
does not duplicate these courses.

View File

@ -248,7 +248,7 @@ FROM exam_prep.catalog_courses c
LEFT JOIN catalog_course_counts cc ON cc.catalog_course_id = c.id
WHERE (
$3::boolean = FALSE
OR c.publish_status = 'PUBLISHED'::TEXT
OR (c.publish_status = 'PUBLISHED'::TEXT AND NOT EXISTS(SELECT 1 FROM academy_archived_courses a WHERE a.course_id=c.id))
)
ORDER BY c.sort_order ASC, c.id ASC
LIMIT $1 OFFSET $2

View File

@ -0,0 +1,30 @@
package demoseed
import (
"encoding/json"
"os"
"reflect"
"strings"
"testing"
)
func TestProductionMakeupCurriculumMatchesFixture(t *testing.T) {
data, err := os.ReadFile("../../db/migrations/000006_makeup_course_catalog.up.sql")
if err != nil {
t.Fatal(err)
}
parts := strings.Split(string(data), "$data$")
if len(parts) != 3 {
t.Fatal("missing curriculum payload")
}
var courses []Course
if err := json.Unmarshal([]byte(parts[1]), &courses); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(courses, Courses) {
t.Fatal("production starter curriculum differs from makeup fixture")
}
if err := validateCurriculum(courses); err != nil {
t.Fatal(err)
}
}

View File

@ -31,6 +31,20 @@ func TestDemoSeedAndPublicCatalogIntegration(t *testing.T) {
t.Fatal(err)
}
}
// Migration 6 installs the same curriculum as drafts. Publication is explicit
// in this disposable test database; the seeder itself preserves authored status.
for _, stmt := range []string{
`UPDATE exam_prep.catalog_courses SET publish_status='PUBLISHED' WHERE id IN(SELECT entity_id FROM demo_seed_entities WHERE kind='course' AND seed_key LIKE 'makeup-%')`,
`UPDATE exam_prep.units SET publish_status='PUBLISHED' WHERE id IN(SELECT entity_id FROM demo_seed_entities WHERE kind='chapter' AND seed_key LIKE 'makeup-%')`,
`UPDATE exam_prep.unit_module_lessons SET publish_status='PUBLISHED' WHERE id IN(SELECT entity_id FROM demo_seed_entities WHERE kind='lesson' AND seed_key LIKE 'makeup-%')`,
`UPDATE exam_prep.lesson_practices SET publish_status='PUBLISHED' WHERE id IN(SELECT entity_id FROM demo_seed_entities WHERE kind='quiz' AND seed_key LIKE 'makeup-%')`,
`UPDATE question_sets SET status='PUBLISHED' WHERE id IN(SELECT entity_id FROM demo_seed_entities WHERE kind='question_set' AND seed_key LIKE 'makeup-%')`,
`UPDATE questions SET status='PUBLISHED' WHERE id IN(SELECT entity_id FROM demo_seed_entities WHERE kind='question' AND seed_key LIKE 'makeup-%')`,
} {
if _, err = conn.Exec(ctx, stmt); err != nil {
t.Fatal(err)
}
}
var courses, lessons, quizzes int
if err = conn.QueryRow(ctx, `SELECT COUNT(*) FILTER(WHERE kind='course'),COUNT(*) FILTER(WHERE kind='lesson'),COUNT(*) FILTER(WHERE kind='quiz') FROM demo_seed_entities WHERE seed_key LIKE 'makeup-%' OR seed_key='draft'`).Scan(&courses, &lessons, &quizzes); err != nil {
t.Fatal(err)

View File

@ -0,0 +1,14 @@
package domain
import "testing"
func TestArchivedCatalogCoursesAreNeverLearnerVisible(t *testing.T) {
for _, status := range []ContentPublishStatus{ContentPublishPublished, ContentPublishDraft} {
if (ExamPrepCatalogCourse{IsArchived: true, PublishStatus: status}).VisibleToLearners() {
t.Fatal("archived course leaked to learners")
}
}
if !(ExamPrepCatalogCourse{PublishStatus: ContentPublishPublished}).VisibleToLearners() {
t.Fatal("active published course should remain visible")
}
}

View File

@ -4,6 +4,7 @@ import "time"
// ExamPrepCatalogCourse stores the makeup academy catalog under the legacy exam_prep schema.
type ExamPrepCatalogCourse struct {
IsArchived bool `json:"is_archived"`
ID int64 `json:"id"`
Name string `json:"name"`
Description *string `json:"description,omitempty"`
@ -24,7 +25,7 @@ type ExamPrepCatalogCourse struct {
// VisibleToLearners is true when the catalog course appears in student/learner exam-prep APIs.
func (c ExamPrepCatalogCourse) VisibleToLearners() bool {
return c.PublishStatus == ContentPublishPublished
return !c.IsArchived && c.PublishStatus == ContentPublishPublished
}
type CreateExamPrepCatalogCourseInput struct {

View File

@ -66,6 +66,9 @@ func (s *Store) GetExamPrepCatalogCourseByID(ctx context.Context, id int64) (dom
AccessTier: c.AccessTier,
})
out.HasPractice = c.HasPractice
if err := s.conn.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM academy_archived_courses WHERE course_id=$1)`, id).Scan(&out.IsArchived); err != nil {
return domain.ExamPrepCatalogCourse{}, err
}
return out, nil
}
@ -105,6 +108,30 @@ func (s *Store) ListExamPrepCatalogCourses(ctx context.Context, publishedOnly bo
item.HasPractice = r.HasPractice
out = append(out, item)
}
// Archive metadata is read in one batch, preserving pagination and total counts.
ids := make([]int64, 0, len(out))
for _, item := range out {
ids = append(ids, item.ID)
}
archived, err := s.conn.Query(ctx, `SELECT course_id FROM academy_archived_courses WHERE course_id=ANY($1::bigint[])`, ids)
if err != nil {
return nil, 0, err
}
defer archived.Close()
archivedIDs := map[int64]bool{}
for archived.Next() {
var id int64
if err := archived.Scan(&id); err != nil {
return nil, 0, err
}
archivedIDs[id] = true
}
if err := archived.Err(); err != nil {
return nil, 0, err
}
for i := range out {
out[i].IsArchived = archivedIDs[out[i].ID]
}
return out, total, nil
}

View File

@ -17,7 +17,7 @@ const publicCourseColumns = `c.id,c.name,COALESCE(c.description,''),COALESCE(c.t
func (s *Store) PublicCatalogCourses(ctx context.Context, search string, limit, offset int32) (domain.PublicCatalogPage, error) {
out := domain.PublicCatalogPage{Courses: []domain.PublicCourse{}, Limit: limit, Offset: offset}
const filter = ` FROM exam_prep.catalog_courses c WHERE c.publish_status='PUBLISHED'
const filter = ` FROM exam_prep.catalog_courses c WHERE c.publish_status='PUBLISHED' AND NOT EXISTS(SELECT 1 FROM academy_archived_courses a WHERE a.course_id=c.id)
AND ($1='' OR c.name ILIKE '%' || $1 || '%' OR c.description ILIKE '%' || $1 || '%')`
if err := s.conn.QueryRow(ctx, `SELECT COUNT(*)`+filter, search).Scan(&out.TotalCount); err != nil {
return out, err
@ -39,7 +39,7 @@ func (s *Store) PublicCatalogCourses(ctx context.Context, search string, limit,
func (s *Store) PublicCatalogCourse(ctx context.Context, id int64) (domain.PublicCourseOutline, error) {
out := domain.PublicCourseOutline{Chapters: []domain.PublicChapter{}}
err := s.conn.QueryRow(ctx, `SELECT `+publicCourseColumns+` FROM exam_prep.catalog_courses c WHERE c.id=$1 AND c.publish_status='PUBLISHED'`, id).
err := s.conn.QueryRow(ctx, `SELECT `+publicCourseColumns+` FROM exam_prep.catalog_courses c WHERE c.id=$1 AND c.publish_status='PUBLISHED' AND NOT EXISTS(SELECT 1 FROM academy_archived_courses a WHERE a.course_id=c.id)`, id).
Scan(&out.ID, &out.Name, &out.Description, &out.Thumbnail, &out.AccessTier, &out.ChapterCount, &out.LessonCount, &out.QuizCount)
if err != nil {
return out, err
@ -70,7 +70,7 @@ func (s *Store) PublicCatalogCourse(ctx context.Context, id int64) (domain.Publi
CASE WHEN c.access_tier='PREMIUM' OR u.access_tier='PREMIUM' OR m.access_tier='PREMIUM' OR l.access_tier='PREMIUM' THEN 'PREMIUM' ELSE 'FREE' END
FROM exam_prep.unit_module_lessons l JOIN exam_prep.unit_modules m ON m.id=l.unit_module_id
JOIN exam_prep.units u ON u.id=m.unit_id JOIN exam_prep.catalog_courses c ON c.id=u.catalog_course_id
WHERE c.id=$1 AND c.publish_status='PUBLISHED' AND u.publish_status='PUBLISHED' AND m.publish_status='PUBLISHED' AND l.publish_status='PUBLISHED'
WHERE c.id=$1 AND c.publish_status='PUBLISHED' AND NOT EXISTS(SELECT 1 FROM academy_archived_courses a WHERE a.course_id=c.id) AND u.publish_status='PUBLISHED' AND m.publish_status='PUBLISHED' AND l.publish_status='PUBLISHED'
ORDER BY u.sort_order,u.id,m.sort_order,m.id,l.sort_order,l.id`, id)
if err != nil {
return out, err
@ -95,7 +95,7 @@ func (s *Store) PublicCatalogCourse(ctx context.Context, id int64) (domain.Publi
FROM exam_prep.lesson_practices p JOIN question_sets qs ON qs.id=p.question_set_id
JOIN exam_prep.practice_parents pp ON pp.practice_id=p.id AND pp.parent_kind='UNIT'
JOIN exam_prep.units u ON u.id=pp.parent_id JOIN exam_prep.catalog_courses c ON c.id=u.catalog_course_id
WHERE c.id=$1 AND c.publish_status='PUBLISHED' AND u.publish_status='PUBLISHED' AND p.publish_status='PUBLISHED' AND qs.status='PUBLISHED' AND qs.set_type='QUIZ'
WHERE c.id=$1 AND c.publish_status='PUBLISHED' AND NOT EXISTS(SELECT 1 FROM academy_archived_courses a WHERE a.course_id=c.id) AND u.publish_status='PUBLISHED' AND p.publish_status='PUBLISHED' AND qs.status='PUBLISHED' AND qs.set_type='QUIZ'
ORDER BY u.sort_order,u.id,p.id`, id)
if err != nil {
return out, err