Implement chapter-based learning, public catalog, and demo fixtures

This commit is contained in:
Yared Yemane 2026-11-01 13:38:28 +03:00
parent 3ab841c869
commit c87ef35390
71 changed files with 17378 additions and 11290 deletions

View File

@ -6,12 +6,15 @@ COPY go.mod go.sum ./
# RUN go mod download command # RUN go mod download command
COPY . . COPY . .
RUN go build -ldflags="-s -w" -o ./bin/web ./cmd/main.go RUN go build -ldflags="-s -w" -o ./bin/web ./cmd/main.go
RUN go build -ldflags="-s -w" -o ./bin/demo-seed ./cmd/demo-seed
# Runner stage # Runner stage
FROM alpine:3.21 AS runner FROM alpine:3.21 AS runner
WORKDIR /app WORKDIR /app
COPY .env . COPY .env .
COPY --from=builder /app/bin/web /app/bin/web COPY --from=builder /app/bin/web /app/bin/web
COPY --from=builder /app/bin/demo-seed /app/bin/demo-seed
COPY --from=builder /app/static /app/static
RUN apk add --no-cache ca-certificates RUN apk add --no-cache ca-certificates
EXPOSE ${PORT} EXPOSE ${PORT}
CMD ["/app/bin/web"] CMD ["/app/bin/web"]

View File

@ -124,9 +124,9 @@ cp .env .env.local # or create .env from the table below
# 2. Infrastructure # 2. Infrastructure
make db-up # Postgres + migrate + Mongo (detached) make db-up # Postgres + migrate + Mongo (detached)
# 3. Seed (optional, after migrations) # 3. Demo seed (optional, non-production only, after all migrations)
make seed_data # db/data/*.sql go run ./cmd/demo-seed -environment development
# make seed_dev_data # db/dev_data/*.sql (dev only) # See docs/demo-and-public-catalog.md for role credentials and fixture details.
# 4. Run API with live reload # 4. Run API with live reload
make air make air
@ -260,9 +260,14 @@ Entry point: `cmd/main.go` (wires config, stores, services, Fiber, cron).
| Target | Source | | Target | Source |
|--------|--------| |--------|--------|
| `make seed_demo` | Current course/chapter/lesson demo, chapter quizzes, and role test accounts (`cmd/demo-seed`) |
| `make seed_data` | `db/data/*.sql` | | `make seed_data` | `db/data/*.sql` |
| `make seed_dev_data` | `db/dev_data/*.sql` (+ sequence fix script) | | `make seed_dev_data` | `db/dev_data/*.sql` (+ sequence fix script) |
Use `seed_demo` for the current hierarchy. The older SQL seed collections target
historical schemas. [Public catalog and demo setup](docs/demo-and-public-catalog.md)
documents anonymous browsing, test credentials, and database setup.
### Backup / restore ### Backup / restore
```bash ```bash

53
cmd/demo-seed/main.go Normal file
View File

@ -0,0 +1,53 @@
package main
import (
"context"
"flag"
"fmt"
"os"
"time"
"Rezina-Backend/internal/demoseed"
"github.com/jackc/pgx/v5"
"github.com/joho/godotenv"
)
func main() {
environment := flag.String("environment", "", "Required: development, test, or staging")
flag.Parse()
_ = godotenv.Load()
if err := demoseed.ValidateEnvironment(*environment, os.Getenv("APP_ENV"), os.Getenv("ENVIRONMENT"), os.Getenv("GO_ENV")); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
url := os.Getenv("DB_URL")
if url == "" {
fmt.Fprintln(os.Stderr, "DB_URL is required")
os.Exit(1)
}
password := os.Getenv("DEMO_SEED_PASSWORD")
if password == "" {
password = demoseed.DefaultPassword
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
conn, err := pgx.Connect(ctx, url)
if err != nil {
fmt.Fprintln(os.Stderr, "Cannot connect to the demo database. Check DB_URL and start PostgreSQL.")
os.Exit(1)
}
defer conn.Close(ctx)
video := os.Getenv("DEMO_VIDEO_URL")
if video == "" {
video = "https://storage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
}
if err = demoseed.Run(ctx, conn, password, video); err != nil {
fmt.Fprintln(os.Stderr, "Demo seed failed:", err)
os.Exit(1)
}
fmt.Println("Demo seed complete: 3 published courses, 6 chapters, 18 lessons, 6 quizzes, 18 questions, and 1 hidden draft course.")
fmt.Println("Test accounts (password: DEMO_SEED_PASSWORD, or RezinaDemo!2026 when unset):")
for _, a := range demoseed.Accounts {
fmt.Printf(" %-36s %-16s %s\n", a.Email, a.Role, a.Audience)
}
}

View File

@ -62,7 +62,7 @@ import (
// @title Rezina API // @title Rezina API
// @version 1.0.1 // @version 1.0.1
// @description Rezina LMS API. Admin panel endpoints use /api/v1/admin; customer web and mobile endpoints retain /api/v1. Use the audience-specific Swagger pages to browse each API. For protected endpoints, enter Bearer followed by a space and the access token in Authorize. // @description Rezina LMS API. Learning content follows course -> chapter -> lesson with chapter-only quizzes and no course category selection. Admin panel endpoints use /api/v1/admin; customer web and mobile endpoints retain /api/v1. Use the audience-specific Swagger pages to browse each API. For protected endpoints, enter Bearer followed by a space and the access token in Authorize.
// @contact.name API Support // @contact.name API Support
// @SecurityDefinitions.apiKey Bearer // @SecurityDefinitions.apiKey Bearer
// @in header // @in header

View File

@ -0,0 +1,20 @@
BEGIN;
DROP TRIGGER delete_chapter_quizzes ON exam_prep.units;
DROP FUNCTION exam_prep.delete_chapter_quizzes();
DROP TRIGGER protect_learning_question_set_type ON question_sets;
DROP FUNCTION exam_prep.protect_quiz_question_set_type();
DROP TRIGGER chapter_quiz_parent ON exam_prep.practice_parents;
DROP TRIGGER chapter_quiz_shell_parent ON exam_prep.lesson_practices;
DROP FUNCTION exam_prep.check_chapter_quiz_parent();
-- Restore pre-migration lessons; newly authored lessons remain in their container.
UPDATE exam_prep.unit_module_lessons l
SET unit_module_id = b.unit_module_id, sort_order = b.sort_order,
publish_status = b.publish_status, access_tier = b.access_tier
FROM exam_prep.chapter_lesson_migration_backup b WHERE b.id = l.id;
DROP TABLE exam_prep.chapter_lesson_migration_backup;
DROP TABLE exam_prep.chapter_lesson_containers;
UPDATE exam_prep.catalog_courses c SET category = b.category
FROM exam_prep.course_category_migration_backup b WHERE c.id = b.id;
DROP TABLE exam_prep.course_category_migration_backup;
COMMIT;

View File

@ -0,0 +1,111 @@
BEGIN;
CREATE TABLE exam_prep.course_category_migration_backup AS
SELECT id, category FROM exam_prep.catalog_courses;
UPDATE exam_prep.catalog_courses SET category = 'EDUCATION';
-- Keep the legacy module storage as an implementation detail. Each chapter
-- (formerly a unit) has one lesson container; public APIs never expose it.
CREATE TABLE exam_prep.chapter_lesson_containers (
chapter_id BIGINT PRIMARY KEY REFERENCES exam_prep.units(id) ON DELETE CASCADE,
module_id BIGINT NOT NULL UNIQUE REFERENCES exam_prep.unit_modules(id) ON DELETE CASCADE
);
-- Retain the original placement for a data-preserving rollback.
CREATE TABLE exam_prep.chapter_lesson_migration_backup AS
SELECT id, unit_module_id, sort_order, publish_status, access_tier
FROM exam_prep.unit_module_lessons;
WITH containers AS (
INSERT INTO exam_prep.unit_modules (unit_id, name, sort_order, publish_status, access_tier)
SELECT u.id, '__chapter_lessons__',
COALESCE((SELECT MAX(m.sort_order) FROM exam_prep.unit_modules m WHERE m.unit_id = u.id), 0) + 1,
'PUBLISHED', 'FREE'
FROM exam_prep.units u
RETURNING id, unit_id
)
INSERT INTO exam_prep.chapter_lesson_containers (chapter_id, module_id)
SELECT unit_id, id FROM containers;
-- Preserve module restrictions on each lesson when removing that public level.
WITH placement AS (
SELECT l.id, c.module_id,
ROW_NUMBER() OVER (PARTITION BY m.unit_id ORDER BY m.sort_order, m.id, l.sort_order, l.id)::integer AS position,
CASE WHEN m.publish_status = 'PUBLISHED' THEN l.publish_status ELSE 'DRAFT' END AS publish_status,
CASE WHEN m.access_tier = 'PREMIUM' OR l.access_tier = 'PREMIUM' THEN 'PREMIUM' ELSE 'FREE' END AS access_tier
FROM exam_prep.unit_module_lessons l
JOIN exam_prep.unit_modules m ON m.id = l.unit_module_id
JOIN exam_prep.chapter_lesson_containers c ON c.chapter_id = m.unit_id
)
UPDATE exam_prep.unit_module_lessons l
SET unit_module_id = p.module_id, sort_order = p.position,
publish_status = p.publish_status, access_tier = p.access_tier
FROM placement p WHERE p.id = l.id;
-- Quiz shells use existing question authoring, publication and scoped progress.
-- Their parent is always exactly one chapter (legacy parent_kind UNIT).
CREATE FUNCTION exam_prep.check_chapter_quiz_parent() RETURNS trigger AS $$
DECLARE p_id bigint; p_ids bigint[]; qs_type text; parent_count bigint; chapter_count bigint;
BEGIN
IF TG_TABLE_NAME = 'practice_parents' THEN
p_ids := ARRAY[CASE WHEN TG_OP = 'DELETE' THEN OLD.practice_id ELSE NEW.practice_id END];
IF TG_OP = 'UPDATE' THEN
p_ids := array_append(p_ids, OLD.practice_id);
END IF;
ELSE
p_ids := ARRAY[NEW.id];
END IF;
FOREACH p_id IN ARRAY p_ids LOOP
SELECT qs.set_type INTO qs_type
FROM exam_prep.lesson_practices p JOIN question_sets qs ON qs.id = p.question_set_id
WHERE p.id = p_id;
IF qs_type = 'QUIZ' THEN
SELECT COUNT(*), COUNT(*) FILTER (WHERE pp.parent_kind = 'UNIT' AND u.id IS NOT NULL)
INTO parent_count, chapter_count
FROM exam_prep.practice_parents pp LEFT JOIN exam_prep.units u ON u.id = pp.parent_id
WHERE pp.practice_id = p_id;
IF parent_count <> 1 OR chapter_count <> 1 THEN
RAISE EXCEPTION 'a quiz must belong to exactly one chapter' USING ERRCODE = '23514';
END IF;
END IF;
END LOOP;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE CONSTRAINT TRIGGER chapter_quiz_shell_parent
AFTER INSERT OR UPDATE ON exam_prep.lesson_practices
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION exam_prep.check_chapter_quiz_parent();
CREATE CONSTRAINT TRIGGER chapter_quiz_parent
AFTER INSERT OR UPDATE OR DELETE ON exam_prep.practice_parents
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION exam_prep.check_chapter_quiz_parent();
-- Parent links are polymorphic and have no foreign key to units. Remove quiz
-- shells while their chapter still exists, including cascading course deletes.
CREATE FUNCTION exam_prep.delete_chapter_quizzes() RETURNS trigger AS $$
BEGIN
DELETE FROM exam_prep.lesson_practices p
USING exam_prep.practice_parents pp, question_sets qs
WHERE pp.practice_id = p.id AND qs.id = p.question_set_id
AND qs.set_type = 'QUIZ' AND pp.parent_kind = 'UNIT'
AND pp.parent_id = OLD.id;
RETURN OLD;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER delete_chapter_quizzes BEFORE DELETE ON exam_prep.units
FOR EACH ROW EXECUTE FUNCTION exam_prep.delete_chapter_quizzes();
CREATE FUNCTION exam_prep.protect_quiz_question_set_type() RETURNS trigger AS $$
BEGIN
IF NEW.set_type IS DISTINCT FROM OLD.set_type AND EXISTS (
SELECT 1 FROM exam_prep.lesson_practices WHERE question_set_id = NEW.id
) THEN
RAISE EXCEPTION 'unlink learning content before changing its question set type' USING ERRCODE = '23514';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER protect_learning_question_set_type BEFORE UPDATE OF set_type ON question_sets
FOR EACH ROW EXECUTE FUNCTION exam_prep.protect_quiz_question_set_type();
COMMIT;

View File

@ -31,7 +31,7 @@ FROM
INNER JOIN exam_prep.lesson_practices p ON p.question_set_id = upp.question_set_id INNER JOIN exam_prep.lesson_practices p ON p.question_set_id = upp.question_set_id
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
INNER JOIN question_sets qs ON qs.id = p.question_set_id INNER JOIN question_sets qs ON qs.id = p.question_set_id
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
INNER JOIN exam_prep.practice_parents pp ON pp.practice_id = p.id INNER JOIN exam_prep.practice_parents pp ON pp.practice_id = p.id
AND upp.content_domain = 'EXAM_PREP' AND upp.content_domain = 'EXAM_PREP'

View File

@ -8,7 +8,7 @@ FROM
WHERE WHERE
pp.parent_kind = 'LESSON' pp.parent_kind = 'LESSON'
AND pp.parent_id = $1 AND pp.parent_id = $1
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED'; AND p.publish_status = 'PUBLISHED';
@ -28,7 +28,7 @@ FROM
WHERE WHERE
pp.parent_kind = 'LESSON' pp.parent_kind = 'LESSON'
AND pp.parent_id = $1 AND pp.parent_id = $1
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED'; AND p.publish_status = 'PUBLISHED';
@ -42,7 +42,7 @@ FROM
WHERE WHERE
pp.parent_kind = 'UNIT' pp.parent_kind = 'UNIT'
AND pp.parent_id = $1 AND pp.parent_id = $1
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED'; AND p.publish_status = 'PUBLISHED';
@ -62,7 +62,7 @@ FROM
WHERE WHERE
pp.parent_kind = 'UNIT' pp.parent_kind = 'UNIT'
AND pp.parent_id = $1 AND pp.parent_id = $1
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED'; AND p.publish_status = 'PUBLISHED';
@ -76,7 +76,7 @@ FROM
WHERE WHERE
pp.parent_kind = 'CATALOG_COURSE' pp.parent_kind = 'CATALOG_COURSE'
AND pp.parent_id = $1 AND pp.parent_id = $1
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED'; AND p.publish_status = 'PUBLISHED';
@ -96,7 +96,7 @@ FROM
WHERE WHERE
pp.parent_kind = 'CATALOG_COURSE' pp.parent_kind = 'CATALOG_COURSE'
AND pp.parent_id = $1 AND pp.parent_id = $1
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED'; AND p.publish_status = 'PUBLISHED';
@ -112,7 +112,7 @@ FROM
WHERE WHERE
l.unit_module_id = $1 l.unit_module_id = $1
AND l.publish_status = 'PUBLISHED' AND l.publish_status = 'PUBLISHED'
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED'; AND p.publish_status = 'PUBLISHED';
@ -134,7 +134,7 @@ FROM
WHERE WHERE
l.unit_module_id = $1 l.unit_module_id = $1
AND l.publish_status = 'PUBLISHED' AND l.publish_status = 'PUBLISHED'
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED'; AND p.publish_status = 'PUBLISHED';
@ -149,7 +149,7 @@ FROM
AND l.id = pp.parent_id AND l.id = pp.parent_id
LEFT JOIN exam_prep.unit_modules m ON l.unit_module_id = m.id LEFT JOIN exam_prep.unit_modules m ON l.unit_module_id = m.id
WHERE WHERE
qs.set_type = 'PRACTICE' qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
AND ( AND (
@ -182,7 +182,7 @@ FROM
AND l.id = pp.parent_id AND l.id = pp.parent_id
LEFT JOIN exam_prep.unit_modules m ON l.unit_module_id = m.id LEFT JOIN exam_prep.unit_modules m ON l.unit_module_id = m.id
WHERE WHERE
qs.set_type = 'PRACTICE' qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
AND ( AND (
@ -206,7 +206,7 @@ FROM
INNER JOIN exam_prep.practice_parents pp ON pp.practice_id = p.id INNER JOIN exam_prep.practice_parents pp ON pp.practice_id = p.id
INNER JOIN question_sets qs ON qs.id = p.question_set_id INNER JOIN question_sets qs ON qs.id = p.question_set_id
WHERE WHERE
qs.set_type = 'PRACTICE' qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
AND ( AND (
@ -254,7 +254,7 @@ FROM
AND upp.parent_id = pp.parent_id AND upp.parent_id = pp.parent_id
AND upp.completed_at IS NOT NULL AND upp.completed_at IS NOT NULL
WHERE WHERE
qs.set_type = 'PRACTICE' qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
AND ( AND (
@ -429,7 +429,7 @@ WITH target AS (
AND pp.parent_kind = @parent_kind::VARCHAR AND pp.parent_kind = @parent_kind::VARCHAR
AND pp.parent_id = @parent_id::BIGINT AND pp.parent_id = @parent_id::BIGINT
AND lp.publish_status = 'PUBLISHED' AND lp.publish_status = 'PUBLISHED'
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
), ),
candidates AS ( candidates AS (
@ -448,7 +448,7 @@ candidates AS (
AND pp.parent_id = t.parent_id AND pp.parent_id = t.parent_id
WHERE WHERE
lp.publish_status = 'PUBLISHED' lp.publish_status = 'PUBLISHED'
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND ( AND (
lp.created_at < t.created_at lp.created_at < t.created_at

View File

@ -12,7 +12,7 @@ candidates AS (
JOIN target t JOIN target t
ON qs.owner_type = t.owner_type ON qs.owner_type = t.owner_type
AND qs.owner_id = t.owner_id AND qs.owner_id = t.owner_id
WHERE qs.set_type = 'PRACTICE' WHERE qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND COALESCE(qs.display_order, 0) < t.display_order AND COALESCE(qs.display_order, 0) < t.display_order
) )

View File

@ -106,7 +106,7 @@ FROM (
AND upp.parent_kind = lpp.parent_kind AND upp.parent_kind = lpp.parent_kind
AND upp.parent_id = lpp.parent_id AND upp.parent_id = lpp.parent_id
INNER JOIN question_sets qs ON qs.id = upp.question_set_id INNER JOIN question_sets qs ON qs.id = upp.question_set_id
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
INNER JOIN lessons l ON l.id = lpp.parent_id INNER JOIN lessons l ON l.id = lpp.parent_id
INNER JOIN modules m ON m.id = l.module_id INNER JOIN modules m ON m.id = l.module_id
@ -141,7 +141,7 @@ FROM (
AND upp.parent_kind = lpp.parent_kind AND upp.parent_kind = lpp.parent_kind
AND upp.parent_id = lpp.parent_id AND upp.parent_id = lpp.parent_id
INNER JOIN question_sets qs ON qs.id = upp.question_set_id INNER JOIN question_sets qs ON qs.id = upp.question_set_id
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
INNER JOIN modules m ON m.id = lpp.parent_id INNER JOIN modules m ON m.id = lpp.parent_id
INNER JOIN courses c ON c.id = m.course_id INNER JOIN courses c ON c.id = m.course_id
@ -175,7 +175,7 @@ FROM (
AND upp.parent_kind = lpp.parent_kind AND upp.parent_kind = lpp.parent_kind
AND upp.parent_id = lpp.parent_id AND upp.parent_id = lpp.parent_id
INNER JOIN question_sets qs ON qs.id = upp.question_set_id INNER JOIN question_sets qs ON qs.id = upp.question_set_id
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
INNER JOIN courses c ON c.id = lpp.parent_id INNER JOIN courses c ON c.id = lpp.parent_id
INNER JOIN programs p ON p.id = c.program_id INNER JOIN programs p ON p.id = c.program_id

View File

@ -5,7 +5,7 @@ services:
container_name: rezina-backend-postgres-1 container_name: rezina-backend-postgres-1
image: postgres:16-alpine image: postgres:16-alpine
ports: ports:
- "5592:5422" - "5592:5432"
environment: environment:
- POSTGRES_PASSWORD=secret - POSTGRES_PASSWORD=secret
- POSTGRES_USER=root - POSTGRES_USER=root

View File

@ -0,0 +1,131 @@
# Public discovery and pre-production demo
## Browse without signing in
The web app exposes `/catalog` and `/catalog/courses/:id` outside the authenticated
admin layout. Visitors to `/` see the catalog; signed-in staff retain their usual
dashboard redirect. The staff login page also links to the catalog.
Anonymous APIs:
| Endpoint | Result |
| --- | --- |
| `GET /api/v1/catalog/courses?q=&limit=20&offset=0` | Searchable published course highlights, access tiers, chapter/lesson/quiz counts and pagination |
| `GET /api/v1/catalog/courses/:id` | Published course outline with chapter descriptions, lesson highlights, and quiz titles/question counts |
These endpoints accept no authentication requirement and never expand their
visibility for staff tokens. Draft courses return 404; draft chapters, lessons,
quiz shells and question sets are excluded. Public DTOs contain no video URLs,
questions, correct answers, author identities, or learner progress. Playback,
question delivery, and completion remain behind the existing learning endpoints
and their authentication/subscription rules. Previewing a premium lesson does not
grant access to it.
The web app uses `VITE_API_BASE_URL` with a trailing `/admin` removed for catalog
requests. Requests omit cookies and staff authorization. Optionally set
`VITE_LEARNER_APP_URL` to your customer web/mobile sign-in destination to display
a **Sign in to learn** link. Without it, the page directs visitors to their
learning app. The staff login continues to be labeled **Staff sign in**.
## Install the demo fixture
Apply database migrations through `000003_chapters_and_quizzes`, then run from
the backend directory:
```powershell
go run ./cmd/demo-seed -environment development
```
The command reads `DB_URL` from the environment or the backend `.env`. It needs
only PostgreSQL; it does not start the application or require payment, email,
SMS, or storage provider credentials. `-environment` must explicitly be
`development`, `test`, or `staging`. `APP_ENV`, `ENVIRONMENT`, or `GO_ENV` set to
`production`/`prod` prevents seeding.
For the repository's Docker PostgreSQL:
```powershell
docker compose up -d postgres
docker compose run --rm migrate
$env:DB_URL = 'postgresql://root:secret@localhost:5592/gh?sslmode=disable'
go run ./cmd/demo-seed -environment development
```
The Docker host mapping is `5592:5432`. Use your actual database credentials when
connecting to another development or staging database. A Docker app image also
contains `/app/bin/demo-seed` for explicitly running the same command; it never
runs automatically on application startup. Do not use the older broad
`db/data`/`db/dev_data` scripts for this new hierarchy fixture.
Optional settings:
| Variable | Default / purpose |
| --- | --- |
| `DEMO_SEED_PASSWORD` | `RezinaDemo!2026`; set a custom password of 12–72 bytes for every demo account |
| `DEMO_VIDEO_URL` | Public Big Buck Bunny sample clip for testing playback; replace with your own media URL for realistic lesson videos |
| `DEMO_TEST_DB_URL` | Disposable, fully migrated PostgreSQL database used only by the opt-in integration test |
The supplied videos are playback fixtures, not instructional recordings for the
lesson subjects. A local SVG course cover is included in the backend image.
## Demo accounts
All accounts use **`RezinaDemo!2026`** unless `DEMO_SEED_PASSWORD` is set.
| Email | Role | Login endpoint | Expected access |
| --- | --- | --- | --- |
| `superadmin@demo.rezina.test` | `SUPER_ADMIN` | `POST /api/v1/admin/team/login` | Full staff permissions, including team invitations |
| `admin@demo.rezina.test` | `ADMIN` | `POST /api/v1/admin/team/login` | Administrative permissions under existing role rules |
| `contentmanager@demo.rezina.test` | `CONTENT_MANAGER` | `POST /api/v1/admin/team/login` | Content management permissions and restricted admin navigation |
| `student@demo.rezina.test` | `STUDENT` | `POST /api/v1/auth/customer-login` | Unsubscribed learner; verifies premium restrictions |
| `premium@demo.rezina.test` | `STUDENT` | `POST /api/v1/auth/customer-login` | 30-day Education subscription, refreshed on seed rerun |
| `openlearner@demo.rezina.test` | `OPEN_LEARNER` | `POST /api/v1/auth/customer-login` | Existing unrestricted learner access rules |
Both login endpoints accept `{"email":"...","password":"..."}`. Staff sign in
through the admin web app. Customer accounts use the customer API or learning
app; they do not sign in through the staff form. Accounts are active, email
verified, and use bcrypt password hashes compatible with the real login paths.
No email delivery or invitation acceptance is required for these fixtures.
These cover all currently assignable staff roles and both customer learner roles.
Legacy names such as Instructor, Support Agent, Finance, HR, and Analyst are not
seeded as team accounts: the current database and team service allow only Super
Admin, Admin, and Content Manager. The seeder does not change role restrictions
or grant every role administrator permissions. Standard RBAC seeds are applied;
restart a running backend after seeding so its permission cache reloads.
## Included learning data and reruns
- Everyday English: 2 chapters, 6 lessons, 2 quizzes; free course.
- Workplace Communication: 2 chapters, 6 lessons, 2 quizzes; premium course.
- Digital Skills Essentials: 2 chapters, 6 lessons, 2 quizzes; free course.
- Each quiz contains 3 published multiple-choice questions with correct answers.
- One unpublished course verifies that public discovery hides drafts.
- One inactive demo subscription plan provides the premium test account access
without appearing as a purchasable production plan.
The fixture runs in one transaction under an advisory lock. It uses generated
IDs and the `demo_seed_entities` ownership map rather than fixed IDs or table
truncation. Reruns reuse existing content, preserve edits to it, reset the six
demo account passwords/statuses to the configured test credentials, and refresh
the seed-owned premium subscription. Existing unrelated accounts and learning
content are not deleted. Keep these fixtures in a separate pre-production
database; this command is not part of production migration or startup.
## Verification
```powershell
go test ./internal/demoseed ./internal/services/examprep ./internal/web_server/... ./internal/apidocs/...
```
For the database-backed seed and catalog test, use a disposable migrated database:
```powershell
$env:DEMO_TEST_DB_URL = '<disposable migrated PostgreSQL URL>'
go test ./internal/demoseed -run TestDemoSeedAndPublicCatalogIntegration -count=1 -v
```
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`.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,296 @@
# LMS external services, API keys, and environment setup
This guide identifies the external infrastructure and third-party APIs used by the Rezina LMS: what each service provides, what you need to provision, and which credentials belong in `.env`. The environment-variable reference follows the service overview. It reflects the current Go implementation in `internal/config/config.go`, `cmd/main.go`, and the integration services. Examples contain placeholders only.
## External services required by the LMS
For anonymous course previews, demo learning content, and role-specific test
credentials, see [Public catalog and demo setup](demo-and-public-catalog.md).
For the course → chapter → lesson structure, chapter quizzes, and database rollout,
see [Learning hierarchy](learning-hierarchy.md). Apply migration
`000003_chapters_and_quizzes` before starting the updated backend.
Not every integration is mandatory for every deployment. PostgreSQL and MongoDB support the running backend. AfroMessage and Resend credentials are required by the current startup validation. MinIO, video hosting, conversion, payments, social login, and push notifications are needed when their corresponding LMS features are used.
| External service | Role in this LMS | Requirement | What to provision / obtain |
| --- | --- | --- | --- |
| PostgreSQL | Stores LMS application data, including users, learning content, progress, subscriptions, and payments. | Core infrastructure. | A PostgreSQL database with the application schema, database user/password, and a reachable connection URL. |
| MongoDB | Stores backend application/activity logs. | Initialized during startup; logger initialization failure stops startup. | A reachable MongoDB deployment and connection URI, with access to the logging database. Can be self-hosted or managed. |
| MinIO | Object storage for uploaded files and media; supplies signed upload/download URLs. | Required for the MinIO-backed file features; optional at startup when disabled. | A running MinIO deployment or compatible storage endpoint, bucket, access identity, and secret. This is a storage service you provision, not an API key alone. |
| AfroMessage | Sends SMS messages for backend messaging flows. | API key required at startup; working sender configuration required for delivery. | Provider account, API bearer token, authorized sender name, and sender identifier if applicable. |
| Resend | Sends email, including team invitations and password reset messages. | API key and sender required at startup. | Provider account, API key, and an authorized sender email/domain. |
| Vimeo | Hosts and manages learning videos through the backend video integration. | Feature dependent. | A Vimeo account with API access appropriate to the video operations used by the LMS, and an access token. |
| CloudConvert | Optimizes images and compresses videos. | Feature dependent. | A CloudConvert account and API key for conversion jobs. |
| Chapa | Processes subscription/payment flows, direct charges, and payment callbacks/webhooks. | Required when exposing Chapa payment features. | Merchant account, secret key, webhook secret, other keys required by the selected payment flow, and callback/return URLs. |
| ArifPay | Supports direct/legacy payment flows. | Required when exposing ArifPay payment features. | Merchant API key, API endpoint, beneficiary bank/account information, and notification/outcome URLs. |
| Google OAuth | Allows learners to sign in with Google. | Feature dependent. | OAuth application credentials: allowed client ID(s), plus client secret and registered redirect URL for the code flow. |
| Apple Sign In | Validates Apple sign-in identity tokens. | Feature dependent. | Apple application identifiers matching the allowed token audiences, such as the bundle ID or Services ID. |
| Firebase Cloud Messaging (FCM) | Sends push notifications to registered learner devices. | Feature dependent. | Firebase project and server service-account JSON; client apps must use the corresponding project. |
Redis, Kafka, Fixer, SantimPay, and Telebirr have configuration or legacy code, but they are **not initialized as active integrations by the current application entrypoint**. They are not additional services you need to provision simply to run this backend. See the caveats below before planning to use them.
## What to prepare for each service
### Database services
For PostgreSQL, provision the database, apply the repository's database migrations/setup, and set `DB_URL`. For MongoDB, set `MONGODB_URL`; the logger uses database `logdb` and collection `applogs`. These are separate database services with different purposes. Neither requires a third-party SaaS subscription if self-hosted.
### MinIO file storage
Provision the storage service before enabling the integration. The backend connects to the **object storage API endpoint**, such as `storage.example.com:9000`, rather than the MinIO browser console. Set the following:
```dotenv
MINIO_ENABLED=true
MINIO_ENDPOINT=storage.example.com:9000
MINIO_ROOT_USER=REPLACE_WITH_STORAGE_ACCESS_ID
MINIO_ROOT_PASSWORD=REPLACE_WITH_STORAGE_SECRET
MINIO_BUCKET_NAME=rezina
MINIO_USE_SSL=true
```
The backend checks for the bucket and creates it when absent. The supplied identity needs permission for the bucket operations used by the application; bucket initialization failure stops startup. Signed URLs are returned to clients, so the configured endpoint must also be reachable by the clients that upload/download files. Set `MINIO_USE_SSL` to match the endpoint's TLS configuration. The variable names above are what the current backend loads; legacy aliases are listed later.
### Communication services: AfroMessage and Resend
Obtain the AfroMessage API token and sender details from the account used to send LMS SMS messages. Configure `AFRO_SMS_API_KEY`, `AFRO_SMS_BASE_URL`, `AFRO_SMS_SENDER_NAME`, and, when applicable, `AFRO_SMS_IDENTIFIER_ID`.
Obtain a Resend API key and authorized email sender for LMS emails. Configure `RESEND_API_KEY` and `RESEND_SENDER_EMAIL`. Invitation and password reset emails also need the frontend page URLs listed in the application-links section below. A valid API key alone does not configure those destinations.
### Media services: Vimeo and CloudConvert
Configure `VIMEO_ENABLED=true` with `VIMEO_ACCESS_TOKEN` to initialize video hosting. Configure `CLOUDCONVERT_ENABLED=true` with `CLOUDCONVERT_API_KEY` to initialize image/video processing. These are separate services from MinIO: MinIO stores objects, Vimeo supplies video hosting, and CloudConvert performs conversion/optimization jobs. The entrypoint leaves Vimeo or CloudConvert disabled if its key is missing, even when its enable flag is set.
### Payment providers: Chapa and ArifPay
Prepare merchant credentials for each payment provider whose flows the LMS will expose. Configure the provider API endpoint, authentication keys, and the backend notification/callback URLs. Configure the user-facing success, cancellation, or return URLs separately. The complete variable lists are in the payments section below. The code initializes both Chapa and ArifPay services, but does not validate their credentials during configuration loading; exercise the intended payment flow before treating the integration as ready.
### Identity providers and mobile push
For Google sign-in, configure the client IDs accepted by the backend and the OAuth code-flow credentials when that flow is used. For Apple sign-in, configure `APPLE_SIGN_IN_CLIENT_IDS`; the current backend validates token audiences and does not load an Apple private key.
For push notifications, provide Firebase service-account JSON through `FCM_SERVICE_ACCOUNT_KEY_FILE` or `FCM_SERVICE_ACCOUNT_KEY`. This is a server credential containing a private key, rather than the Firebase API key embedded in a mobile/web client. Device registration and a matching Firebase project are also needed for delivery.
## Service setup checklist
1. Provision PostgreSQL and MongoDB, prepare the application database, and supply their connection URLs.
2. Obtain AfroMessage and Resend credentials and configure sender identities; these are enforced by startup validation.
3. Provision MinIO and enable it if the deployment needs the backend's object storage features.
4. Add Vimeo and CloudConvert accounts/keys for the video hosting and media processing features being used.
5. Add merchant credentials and public callback URLs for the payment providers being exposed.
6. Add Google/Apple identity configuration and Firebase credentials if social sign-in and push notifications are part of the deployment.
7. Supply the backend's own settings, including the JWT signing secret and frontend link URLs, using the reference below. These settings are not separate external services.
## Loading configuration
The app loads `.env` from its working directory using `godotenv.Load()`. Existing process environment variables take precedence. A missing `.env` is allowed when variables are supplied by the deployment environment. `new.env` is not loaded automatically.
**Required at startup** means the configuration loader rejects a missing value. **Feature dependent** means the value is needed when using that integration, even if the loader accepts an empty value. Successful configuration loading does not verify API credentials.
## Required startup settings
| Variable | Purpose / accepted value |
| --- | --- |
| `ENV` | Nonempty environment name. Use `development` for text logs; other values use JSON logs. |
| `PORT` | Integer from `1` to `65535`, for example `8080`. |
| `DB_URL` | PostgreSQL connection URL, including database credentials. The database must be reachable at startup. |
| `JWT_KEY` | Secret used to sign HS256 access tokens. Generate a strong random secret for each environment. |
| `ACCESS_EXPIRY` | Positive integer: access-token lifetime in **seconds**, for example `3600`. |
| `REFRESH_EXPIRY` | Positive integer: refresh-token lifetime in **seconds**, for example `604800`. |
| `LOG_LEVEL` | Exactly `debug`, `info`, `warn`, or `error`. |
| `REPORT_EXPORT_PATH` | Nonempty report export directory, for example `./exports`. Required even though report-worker initialization is currently commented out. |
| `AFRO_SMS_API_KEY` | AfroMessage API bearer token. Required even if SMS is not being used. |
| `RESEND_API_KEY` | Resend email API key. Required even if email is not being used. |
| `RESEND_SENDER_EMAIL` | Sender identity used for outgoing email. Must be nonempty; use a sender authorized for the Resend account. |
`MONGODB_URL` is read separately by the logging layer. Configure a reachable MongoDB URI; `cmd/main.go` exits if MongoDB logger initialization fails. Logs use database `logdb` and collection `applogs`.
## Third-party credential checklist
| Service | Credentials / identifiers to obtain | When needed |
| --- | --- | --- |
| AfroMessage | `AFRO_SMS_API_KEY`, sender name, and optional sender identifier | API key is startup-required; remaining settings support SMS delivery. |
| Resend | `RESEND_API_KEY`, authorized `RESEND_SENDER_EMAIL` | Startup-required; sends email, including invitations and password resets. |
| Google OAuth | OAuth client ID(s), client secret, registered redirect URL | Google sign-in. Client secret and redirect URL support the authorization-code flow. |
| Apple Sign In | Allowed bundle ID / Services ID audience values | Apple sign-in token validation; this configuration does not load an Apple private key. |
| Firebase Cloud Messaging | Firebase service-account JSON with private key | Push notifications. Use the same Firebase project as the client app. |
| Vimeo | `VIMEO_ACCESS_TOKEN` | Enabled Vimeo video integration. |
| CloudConvert | `CLOUDCONVERT_API_KEY` | Enabled media conversion integration. |
| MinIO / compatible object storage | Access identity and secret, endpoint, bucket | Enabled file storage; may be self-hosted. |
| Chapa | Secret API key and webhook secret; public/encryption keys where used | Chapa checkout, payment verification, webhooks, and direct charges. |
| ArifPay | `ARIFPAY_API_KEY`, beneficiary bank/account details | ArifPay direct/legacy payment flows. |
| SantimPay / Telebirr | Merchant credentials described below | Configuration is present, but no service is initialized for either in the current entrypoint. |
| Fixer | `FIXER_API_KEY` | Legacy currency configuration; initialization is currently commented out. |
Keep API tokens, signing keys, database passwords, storage secrets, OAuth client secrets, and Firebase JSON out of committed documentation. Use separate credentials for development and production.
## SMS and email
| Variable | Purpose / default |
| --- | --- |
| `AFRO_SMS_BASE_URL` | Base URL used by the current SMS sender, which appends `/api/send`. Set explicitly, for example `https://api.afromessage.com`. |
| `AFRO_SMS_SENDER_NAME` | Sender passed by the current SMS implementation. Set explicitly to the account's sender name. |
| `AFRO_SMS_IDENTIFIER_ID` | Optional sender identifier, sent as the `from` parameter. |
| `AFRO_SMS_HOST_URL` | Separate legacy config field; defaults to `https://api.afromessage.com`. It does **not** supply the current sender's `AFRO_SMS_BASE_URL`. |
| `AFRO_SMS_RECEIVER_PHONE_NUMBER` | Loaded receiver setting; current `SendSMS` receives the destination as a method argument. |
| `RESEND_API_KEY`, `RESEND_SENDER_EMAIL` | Required email credentials described above. |
The loader defaults the top-level SMS sender field to `Rezina`, but the active SMS sender reads the nested field, which has no such default. Set `AFRO_SMS_SENDER_NAME` explicitly.
## Authentication and application links
| Variable | Purpose / default |
| --- | --- |
| `GOOGLE_OAUTH_CLIENT_ID` | Google client ID or comma-separated allowed IDs. The first nonempty ID initializes the OAuth code flow. |
| `GOOGLE_OAUTH_WEB_CLIENT_ID` | Additional Google web client audience accepted during ID-token validation. |
| `GOOGLE_OAUTH_CLIENT_SECRET` | Secret for Google OAuth authorization-code exchange. |
| `GOOGLE_OAUTH_REDIRECT_URL` | Redirect URL registered for the Google OAuth application. |
| `APPLE_SIGN_IN_CLIENT_IDS` | Comma-separated allowed Apple token audiences, such as bundle IDs or Services IDs. |
| `TEAM_INVITE_BASE_URL` | Frontend invitation acceptance URL; required for invitation generation. |
| `TEAM_PASSWORD_RESET_BASE_URL` | Team password reset page. If empty, the service attempts to derive it from the invitation URL. |
| `TEAM_INVITE_EXPIRY_HOURS` | Positive integer hours; defaults to `168`, including for invalid input. |
| `LEARNER_APP_BASE_URL` | Learner application base URL used for notification links. Trailing slashes are trimmed. |
| `LEARNER_WEB_CHECKOUT_BASE_URL` | Learner web checkout base used when generating subscription checkout links. |
| `PASSWORD_RESET_BASE_URL` | Loaded password reset URL setting; confirm the relevant flow consumes it before relying on it. |
| `APP_VERSION` | Optional application version string. |
## Push notifications
| Variable | Purpose |
| --- | --- |
| `FCM_SERVICE_ACCOUNT_KEY` | Firebase service-account JSON, including its private key. This is JSON credential content, not a Firebase client API key. |
| `FCM_SERVICE_ACCOUNT_KEY_FILE` | Alternative path to a service-account JSON file. When nonempty, its contents override `FCM_SERVICE_ACCOUNT_KEY`. An unreadable file fails configuration loading. |
Prefer a mounted credential file to embedding multiline JSON in `.env`. Missing credentials leave push delivery unavailable without making them a required startup setting.
## Media and object storage
| Variable | Purpose / default |
| --- | --- |
| `VIMEO_ENABLED` | Enable Vimeo with exactly `true` or `1`; otherwise disabled. |
| `VIMEO_ACCESS_TOKEN` | Vimeo access token for the integration. |
| `CLOUDCONVERT_ENABLED` | Enable CloudConvert with exactly `true` or `1`; otherwise disabled. |
| `CLOUDCONVERT_API_KEY` | CloudConvert API key. |
| `MINIO_ENABLED` | Enable object storage with exactly `true` or `1`; otherwise disabled. Initialization also requires a nonempty endpoint. |
| `MINIO_ENDPOINT` | Storage host and optional port, for example `localhost:9000`; do not include a URL scheme. |
| `MINIO_ROOT_USER` | Preferred storage access identity; overrides `MINIO_ACCESS_KEY` when nonempty. |
| `MINIO_ROOT_PASSWORD` | Preferred storage secret; overrides `MINIO_SECRET_KEY` when nonempty. |
| `MINIO_BUCKET_NAME` | Preferred bucket name; overrides `MINIO_BUCKET` when nonempty. Final default: `rezina`. |
| `MINIO_ACCESS_KEY`, `MINIO_SECRET_KEY`, `MINIO_BUCKET` | Backward-compatible aliases for the settings above. |
| `MINIO_USE_SSL` | Enable TLS with exactly `true` or `1`; defaults to false. |
When enabled with an endpoint, the app checks/creates the bucket during startup; initialization failures stop the app. `MINIO_BROWSER_REDIRECT_URL` is not read by this Go backend and belongs to MinIO server/browser configuration.
## Payments
### Chapa
| Variable | Purpose / default |
| --- | --- |
| `CHAPA_SECRET_KEY` | Secret used to authorize API requests. |
| `CHAPA_WEBHOOK_SECRET` | Secret for webhook verification. |
| `CHAPA_PUBLIC_KEY` | Loaded public payment key. |
| `CHAPA_ENCRYPTION_KEY` | Key used by direct-charge encryption. |
| `CHAPA_BASE_URL` | Defaults to `https://api.chapa.co/v1`. |
| `CHAPA_CALLBACK_URL` | Backend payment callback URL. |
| `CHAPA_RETURN_URL` | User-facing return URL after payment. |
| `CHAPA_RECEIPT_URL` | Loaded receipt URL setting. |
| `CHAPA_TRANSFER_TYPE`, `CHAPA_PAYMENT_TYPE` | Loaded transfer/payment type settings. |
These values are not required by the configuration loader. Supply the credentials and URLs needed by the Chapa flows you expose. Callback URLs should target the deployed backend; return URLs should target the intended client page.
### ArifPay
| Variable | Purpose |
| --- | --- |
| `ARIFPAY_API_KEY`, `ARIFPAY_BASE_URL` | Provider API credentials and endpoint. |
| `ARIFPAY_CANCEL_URL`, `ARIFPAY_ERROR_URL`, `ARIFPAY_SUCCESS_URL` | User-facing payment outcome URLs. |
| `ARIFPAY_C2B_NOTIFY_URL`, `ARIFPAY_B2C_NOTIFY_URL` | Backend notification URLs for the respective flows. |
| `ARIFPAY_BANK`, `ARIFPAY_BENEFICIARY_ACCOUNT_NUMBER` | Beneficiary bank and account. |
| `ARIFPAY_DESCRIPTION`, `ARIFPAY_ITEM_NAME` | Payment description and item label. |
The loader sets quantity to `1`, language to `EN`, expiry to a date three hours ahead, and payment methods in code; these are not environment variables.
### SantimPay and Telebirr configuration caveats
The loader reads `SANTIMPAY_SECRET_KEY`, `SANTIMPAY_MERCHANT_ID`, `SANTIMPAY_BASE_URL`, `SANTIMPAY_NOTIFY_URL`, and `SANTIMPAY_CANCEL_URL`. Although the struct has a success URL field, no corresponding environment variable is loaded.
It also reads `TELEBIRR_BASE_URL`, `TELEBIRR_APP_SECRET`, `TELEBIRR_FABRIC_APP_ID`, `TELEBIRR_MERCHANT_CODE`, and `TELEBIRR_CALLBACK_URL`. **Current implementation issue:** `TELEBIRR_FABRIC_APP_ID` overwrites the app-secret field instead of populating the fabric-app-ID field. Setting both variables cannot fix this; code changes are needed before relying on this configuration.
Neither provider has a service initialized in the current `cmd/main.go`; obtaining their keys alone does not enable payments.
## Database pool and auxiliary infrastructure
| Variable | Purpose / default |
| --- | --- |
| `DB_MAX_CONNS` | Maximum PostgreSQL pool connections; `25`. |
| `DB_MIN_CONNS` | Minimum PostgreSQL pool connections; `5`. |
| `DB_MAX_CONN_LIFETIME_MINUTES` | Connection lifetime in minutes; `30`. |
| `DB_MAX_CONN_IDLE_MINUTES` | Idle lifetime in minutes; `5`. |
| `DB_HEALTH_CHECK_SECONDS` | Health check interval in seconds; `30`. |
| `REDIS_ADDR` | Loaded Redis address; no Redis client is initialized by the current entrypoint. |
| `KAFKA_BROKERS` | Comma-separated broker addresses; producer initialization is currently commented out. |
| `FIXER_API_KEY`, `FIXER_BASE_URL`, `BASE_CURRENCY` | Loaded currency settings; exchange-rate initialization is currently commented out. |
Pool settings fall back to defaults for missing, nonnumeric, or nonpositive values. Keep minimum connections no greater than maximum connections.
## Background workers
| Variable | Default | Purpose |
| --- | --- | --- |
| `ACCOUNT_DELETION_PURGE_ENABLED` | `true` | Purge accounts due for permanent deletion. |
| `ACCOUNT_DELETION_PURGE_INTERVAL` | `1h` | Purge interval. |
| `ACCOUNT_DELETION_PURGE_BATCH_SIZE` | `100` | Batch size; capped at `1000`. |
| `PAYMENT_EXPIRY_WORKER_ENABLED` | `true` | Expire overdue payments. |
| `PAYMENT_EXPIRY_WORKER_INTERVAL` | `15m` | Payment expiry scan interval. |
| `SUBSCRIPTION_EXPIRY_REMINDER_WORKER_ENABLED` | `true` | Send subscription expiry reminders. |
| `SUBSCRIPTION_EXPIRY_REMINDER_WORKER_INTERVAL` | `24h` | Reminder scan interval. |
| `INACTIVE_SUBMODULE_CONTENT_PURGE_ENABLED` | `false` | Permanently purge inactive submodule content after retention. |
| `INACTIVE_SUBMODULE_CONTENT_PURGE_INTERVAL` | `24h` | Content purge interval. |
| `INACTIVE_SUBMODULE_CONTENT_RETENTION_DAYS` | `30` | Positive integer retention period in days. |
For worker switches, empty values use the defaults above; explicit `true` or `1` enables them, and other nonempty values disable them. Intervals use Go duration syntax such as `30m`, `1h`, or `24h`; invalid or nonpositive durations fall back to defaults. Invalid batch sizes and retention periods also fall back to defaults.
## Minimal configuration example
This example covers startup configuration and the currently used SMS fields. Replace placeholders, prepare the PostgreSQL schema, and provide reachable databases before starting the app. It does not enable payments, social login, storage, or push notifications.
```dotenv
ENV=development
PORT=8080
DB_URL=postgres://USER:PASSWORD@localhost:5432/rezina?sslmode=disable
MONGODB_URL=mongodb://localhost:27017
JWT_KEY=REPLACE_WITH_A_STRONG_RANDOM_SECRET
ACCESS_EXPIRY=3600
REFRESH_EXPIRY=604800
LOG_LEVEL=info
REPORT_EXPORT_PATH=./exports
AFRO_SMS_API_KEY=REPLACE_WITH_AFROMESSAGE_TOKEN
AFRO_SMS_BASE_URL=https://api.afromessage.com
AFRO_SMS_SENDER_NAME=REPLACE_WITH_AUTHORIZED_SENDER
RESEND_API_KEY=REPLACE_WITH_RESEND_API_KEY
RESEND_SENDER_EMAIL=REPLACE_WITH_AUTHORIZED_EMAIL
VIMEO_ENABLED=false
CLOUDCONVERT_ENABLED=false
MINIO_ENABLED=false
```
## Legacy names and configuration limits
- `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN`, and `TWILIO_SENDER_PHONE_NUMBER` appear in `new.env` but are not read by the current Go backend. SMS uses AfroMessage.
- `ARIFPAY_NOTIFY_URL` is not loaded; use the separate `ARIFPAY_C2B_NOTIFY_URL` and `ARIFPAY_B2C_NOTIFY_URL` names.
- `SANTIMPAY_Base_URL` in `new.env` differs from the loader's `SANTIMPAY_BASE_URL`. Use the exact uppercase spelling for portable deployments.
- `DBResetReseedEnabled`, `DBResetReseedToken`, and `DBSeedDir` are assigned directly in code (`true`, empty token, and `db/data`). No environment variables control those fields in the current loader.
- Commented-out provider configuration in `config.go` is not active configuration and does not require API keys.
## Source references
- [Configuration loading and validation](../internal/config/config.go)
- [Application startup and integration initialization](../cmd/main.go)
- [PostgreSQL pool configuration](../internal/repository/store.go)
- [MongoDB logger initialization](../internal/logger/mongoLogger/init.go)
- [Active AfroMessage sender](../internal/services/messenger/sms.go)
- [Google OAuth implementation](../internal/services/authentication/google.go)
- [Push notification service](../internal/services/notification/service.go)

View File

@ -0,0 +1,78 @@
# Learning hierarchy
Learning content uses **course → chapter → lesson**. Quizzes belong to a chapter;
they cannot attach to a course, lesson, multiple chapters, or no chapter.
The admin content screen at `/new-content/courses` manages this hierarchy without
Exam Prep, Learn English, IELTS, or Duolingo category selection.
## API
Learner routes use `/api/v1`; administrative routes use `/api/v1/admin`.
| Resource | Collection | Item |
| --- | --- | --- |
| Courses | `/courses` | `/courses/:id` |
| Chapters | `/courses/:courseId/chapters` | `/chapters/:id` |
| Lessons | `/chapters/:chapterId/lessons` | `/lessons/:id` |
| Quizzes | `/chapters/:chapterId/quizzes` | `/quizzes/:id` |
Admins can create, update, delete, and publish content. Course, chapter, and lesson
collections support `PUT <collection>/reorder` with `ordered_ids` containing every
sibling ID. Lists use `limit` and `offset` and return the collection plus
`total_count`. Chapter JSON uses `course_id`; lesson JSON uses `chapter_id`.
Course categories and the intermediate module level are absent from these APIs.
Create a question set with `set_type: "QUIZ"`, then create its chapter quiz with
`question_set_id` and an optional `title`. Omit parent fields: the chapter URL
determines placement. Both the quiz and its question set must be published for
learner visibility. Learners read questions at `/quizzes/:id/questions` and submit
completion at `POST /progress/quizzes/:id/complete`. Existing subscription and
content access rules still apply.
## Admin integration and Swagger
Swagger UI is available at `/swagger/admin/index.html` and
`/swagger/client/index.html`. Their specifications are served at
`/swagger/admin/doc.json` and `/swagger/client/doc.json`. Regenerate the checked-in
Go, JSON, and YAML artifacts with `swag init -g cmd/main.go` after changing handler
annotations. `go test ./internal/web_server/... ./internal/apidocs/...` checks
registered routes, security, path and body parameters, public hierarchy schemas,
and artifact synchronization.
The admin uses its configured API root with `/admin` appended exactly once.
Its Courses screen loads courses, their chapters, and chapter lessons/quizzes.
Reordering is available within those collections; the old category and module
screens are no longer navigation targets. Practice location pickers use `COURSE`,
`CHAPTER`, and `LESSON`, resolving titles directly by ID.
Quiz titles and publication use `PUT /quizzes/:id/full` with both `practice` and
`question_set` patches. Omit `questions` when changing metadata to preserve quiz
membership; an explicit empty `questions` array removes every membership. The
quiz creation flow creates a draft QUIZ question set and links it to the chapter.
If linking fails, it attempts to clean up the unused set.
For admin question authoring, `GET /question-sets/:id/questions` returns the
questions as the response's `data` array. This differs from the paginated learner
quiz endpoint. Removing a question calls
`DELETE /question-sets/:id/questions/:questionId`, preserving the shared bank
question. Deleting a quiz also preserves its independently managed question set.
Admin learner activity consumes `learning.progress.courses[].chapters[].lessons[]`
and `learning.completions.courses`. Run `npm run test:learning` and `npm run build`
in `RezinaLMS-Admin` to check the integration.
## Database rollout
Apply `000003_chapters_and_quizzes` before running the updated backend. It removes
public category distinctions, flattens existing module lessons into chapters in
their original order, and preserves module publication and premium restrictions
on the moved lessons. IDs remain stable, preserving lesson and practice history.
It also enforces chapter-only quiz placement and deletes quizzes when their
chapter or containing course is deleted. Question sets remain independently
managed authoring resources.
The `exam_prep` schema, internal unit/module names, permission identifiers, and
historical progress discriminators remain storage details for compatibility.
Public practice parents serialize as `COURSE`, `CHAPTER`, or `LESSON`.
Migration backup tables preserve original category and lesson placement for a
rollback; newly authored lessons stay in their chapter containers on rollback.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -43,7 +43,7 @@ FROM
INNER JOIN exam_prep.lesson_practices p ON p.question_set_id = upp.question_set_id INNER JOIN exam_prep.lesson_practices p ON p.question_set_id = upp.question_set_id
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
INNER JOIN question_sets qs ON qs.id = p.question_set_id INNER JOIN question_sets qs ON qs.id = p.question_set_id
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
INNER JOIN exam_prep.practice_parents pp ON pp.practice_id = p.id INNER JOIN exam_prep.practice_parents pp ON pp.practice_id = p.id
AND upp.content_domain = 'EXAM_PREP' AND upp.content_domain = 'EXAM_PREP'

View File

@ -21,7 +21,7 @@ FROM
WHERE WHERE
pp.parent_kind = 'CATALOG_COURSE' pp.parent_kind = 'CATALOG_COURSE'
AND pp.parent_id = $1 AND pp.parent_id = $1
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
` `
@ -43,7 +43,7 @@ FROM
WHERE WHERE
pp.parent_kind = 'UNIT' pp.parent_kind = 'UNIT'
AND pp.parent_id = $1 AND pp.parent_id = $1
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
` `
@ -63,7 +63,7 @@ FROM
INNER JOIN exam_prep.practice_parents pp ON pp.practice_id = p.id INNER JOIN exam_prep.practice_parents pp ON pp.practice_id = p.id
INNER JOIN question_sets qs ON qs.id = p.question_set_id INNER JOIN question_sets qs ON qs.id = p.question_set_id
WHERE WHERE
qs.set_type = 'PRACTICE' qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
AND ( AND (
@ -115,7 +115,7 @@ FROM
WHERE WHERE
pp.parent_kind = 'LESSON' pp.parent_kind = 'LESSON'
AND pp.parent_id = $1 AND pp.parent_id = $1
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
` `
@ -139,7 +139,7 @@ FROM
WHERE WHERE
l.unit_module_id = $1 l.unit_module_id = $1
AND l.publish_status = 'PUBLISHED' AND l.publish_status = 'PUBLISHED'
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
` `
@ -162,7 +162,7 @@ FROM
AND l.id = pp.parent_id AND l.id = pp.parent_id
LEFT JOIN exam_prep.unit_modules m ON l.unit_module_id = m.id LEFT JOIN exam_prep.unit_modules m ON l.unit_module_id = m.id
WHERE WHERE
qs.set_type = 'PRACTICE' qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
AND ( AND (
@ -202,7 +202,7 @@ FROM
WHERE WHERE
pp.parent_kind = 'CATALOG_COURSE' pp.parent_kind = 'CATALOG_COURSE'
AND pp.parent_id = $1 AND pp.parent_id = $1
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
` `
@ -235,7 +235,7 @@ FROM
WHERE WHERE
pp.parent_kind = 'UNIT' pp.parent_kind = 'UNIT'
AND pp.parent_id = $1 AND pp.parent_id = $1
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
` `
@ -266,7 +266,7 @@ FROM
AND upp.parent_id = pp.parent_id AND upp.parent_id = pp.parent_id
AND upp.completed_at IS NOT NULL AND upp.completed_at IS NOT NULL
WHERE WHERE
qs.set_type = 'PRACTICE' qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
AND ( AND (
@ -329,7 +329,7 @@ FROM
WHERE WHERE
pp.parent_kind = 'LESSON' pp.parent_kind = 'LESSON'
AND pp.parent_id = $1 AND pp.parent_id = $1
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
` `
@ -364,7 +364,7 @@ FROM
WHERE WHERE
l.unit_module_id = $1 l.unit_module_id = $1
AND l.publish_status = 'PUBLISHED' AND l.publish_status = 'PUBLISHED'
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
` `
@ -398,7 +398,7 @@ FROM
AND l.id = pp.parent_id AND l.id = pp.parent_id
LEFT JOIN exam_prep.unit_modules m ON l.unit_module_id = m.id LEFT JOIN exam_prep.unit_modules m ON l.unit_module_id = m.id
WHERE WHERE
qs.set_type = 'PRACTICE' qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND p.publish_status = 'PUBLISHED' AND p.publish_status = 'PUBLISHED'
AND ( AND (
@ -444,7 +444,7 @@ WITH target AS (
AND pp.parent_kind = $3::VARCHAR AND pp.parent_kind = $3::VARCHAR
AND pp.parent_id = $4::BIGINT AND pp.parent_id = $4::BIGINT
AND lp.publish_status = 'PUBLISHED' AND lp.publish_status = 'PUBLISHED'
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
), ),
candidates AS ( candidates AS (
@ -463,7 +463,7 @@ candidates AS (
AND pp.parent_id = t.parent_id AND pp.parent_id = t.parent_id
WHERE WHERE
lp.publish_status = 'PUBLISHED' lp.publish_status = 'PUBLISHED'
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND ( AND (
lp.created_at < t.created_at lp.created_at < t.created_at

View File

@ -79,6 +79,24 @@ type ExamPrepCatalogCourse struct {
AccessTier string `json:"access_tier"` AccessTier string `json:"access_tier"`
} }
type ExamPrepChapterLessonContainer struct {
ChapterID int64 `json:"chapter_id"`
ModuleID int64 `json:"module_id"`
}
type ExamPrepChapterLessonMigrationBackup struct {
ID int64 `json:"id"`
UnitModuleID int64 `json:"unit_module_id"`
SortOrder int32 `json:"sort_order"`
PublishStatus string `json:"publish_status"`
AccessTier string `json:"access_tier"`
}
type ExamPrepCourseCategoryMigrationBackup struct {
ID int64 `json:"id"`
Category string `json:"category"`
}
type ExamPrepLessonPractice struct { type ExamPrepLessonPractice struct {
ID int64 `json:"id"` ID int64 `json:"id"`
Title string `json:"title"` Title string `json:"title"`

View File

@ -23,7 +23,7 @@ candidates AS (
JOIN target t JOIN target t
ON qs.owner_type = t.owner_type ON qs.owner_type = t.owner_type
AND qs.owner_id = t.owner_id AND qs.owner_id = t.owner_id
WHERE qs.set_type = 'PRACTICE' WHERE qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
AND COALESCE(qs.display_order, 0) < t.display_order AND COALESCE(qs.display_order, 0) < t.display_order
) )

View File

@ -229,7 +229,7 @@ FROM (
AND upp.parent_kind = lpp.parent_kind AND upp.parent_kind = lpp.parent_kind
AND upp.parent_id = lpp.parent_id AND upp.parent_id = lpp.parent_id
INNER JOIN question_sets qs ON qs.id = upp.question_set_id INNER JOIN question_sets qs ON qs.id = upp.question_set_id
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
INNER JOIN lessons l ON l.id = lpp.parent_id INNER JOIN lessons l ON l.id = lpp.parent_id
INNER JOIN modules m ON m.id = l.module_id INNER JOIN modules m ON m.id = l.module_id
@ -264,7 +264,7 @@ FROM (
AND upp.parent_kind = lpp.parent_kind AND upp.parent_kind = lpp.parent_kind
AND upp.parent_id = lpp.parent_id AND upp.parent_id = lpp.parent_id
INNER JOIN question_sets qs ON qs.id = upp.question_set_id INNER JOIN question_sets qs ON qs.id = upp.question_set_id
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
INNER JOIN modules m ON m.id = lpp.parent_id INNER JOIN modules m ON m.id = lpp.parent_id
INNER JOIN courses c ON c.id = m.course_id INNER JOIN courses c ON c.id = m.course_id
@ -298,7 +298,7 @@ FROM (
AND upp.parent_kind = lpp.parent_kind AND upp.parent_kind = lpp.parent_kind
AND upp.parent_id = lpp.parent_id AND upp.parent_id = lpp.parent_id
INNER JOIN question_sets qs ON qs.id = upp.question_set_id INNER JOIN question_sets qs ON qs.id = upp.question_set_id
AND qs.set_type = 'PRACTICE' AND qs.set_type IN ('PRACTICE', 'QUIZ')
AND qs.status = 'PUBLISHED' AND qs.status = 'PUBLISHED'
INNER JOIN courses c ON c.id = lpp.parent_id INNER JOIN courses c ON c.id = lpp.parent_id
INNER JOIN programs p ON p.id = c.program_id INNER JOIN programs p ON p.id = c.program_id

View File

@ -46,10 +46,10 @@ func Specification(audience string) (map[string]any, error) {
if info, ok := spec["info"].(map[string]any); ok { if info, ok := spec["info"].(map[string]any); ok {
if audience == "admin" { if audience == "admin" {
info["title"] = "Rezina Admin API" info["title"] = "Rezina Admin API"
info["description"] = "Admin panel operations use /api/v1/admin. Sign in through /api/v1/admin/team/login, then enter Bearer followed by a space and the access token in Authorize. Protected endpoints require a staff account and the relevant RBAC permission. WebSockets use the token query parameter." info["description"] = "Learning content follows course -> chapter -> lesson, with quizzes per chapter. Admin panel operations use /api/v1/admin. Sign in through /api/v1/admin/team/login, then enter Bearer followed by a space and the access token in Authorize. Protected endpoints require a staff account and the relevant RBAC permission. WebSockets use the token query parameter."
} else { } else {
info["title"] = "Rezina Customer API" info["title"] = "Rezina Customer API"
info["description"] = "Customer web and mobile operations retain /api/v1; there is no /client prefix. Public registration, login, and discovery endpoints do not require authorization. For protected endpoints, enter Bearer followed by a space and a customer access token in Authorize. Premium learning content requires an active EDUCATION subscription unless the account has an existing exemption. WebSockets use the token query parameter." info["description"] = "Learning content follows course -> chapter -> lesson, with quizzes per chapter. Customer web and mobile operations retain /api/v1; there is no /client prefix. Public registration, login, and discovery endpoints do not require authorization. For protected endpoints, enter Bearer followed by a space and a customer access token in Authorize. Premium learning content requires an active EDUCATION subscription unless the account has an existing exemption. WebSockets use the token query parameter."
} }
} }
definitions, _ := spec["definitions"].(map[string]any) definitions, _ := spec["definitions"].(map[string]any)

View File

@ -0,0 +1,100 @@
package demoseed_test
import (
"context"
"os"
"testing"
"time"
"Rezina-Backend/internal/demoseed"
"Rezina-Backend/internal/repository"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"golang.org/x/crypto/bcrypt"
)
// Opt in with a migrated disposable test database. Never uses application DB_URL.
func TestDemoSeedAndPublicCatalogIntegration(t *testing.T) {
url := os.Getenv("DEMO_TEST_DB_URL")
if url == "" {
t.Skip("set DEMO_TEST_DB_URL to a disposable migrated PostgreSQL database")
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
conn, err := pgx.Connect(ctx, url)
if err != nil {
t.Fatal(err)
}
defer conn.Close(ctx)
for i := 0; i < 2; i++ {
if err := demoseed.Run(ctx, conn, demoseed.DefaultPassword, ""); 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`).Scan(&courses, &lessons, &quizzes); err != nil {
t.Fatal(err)
}
if courses != 4 || lessons != 18 || quizzes != 6 {
t.Fatalf("duplicate/missing fixtures after rerun: courses=%d lessons=%d quizzes=%d", courses, lessons, quizzes)
}
for _, a := range demoseed.Accounts {
table := "users"
if a.Audience == "staff" {
table = "team_members"
}
var hash []byte
if err = conn.QueryRow(ctx, `SELECT password FROM `+table+` WHERE email=$1`, a.Email).Scan(&hash); err != nil {
t.Fatal(err)
}
if err = bcrypt.CompareHashAndPassword(hash, []byte(demoseed.DefaultPassword)); err != nil {
t.Errorf("login hash invalid for %s", a.Email)
}
}
pool, err := pgxpool.New(ctx, url)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
store := repository.NewStore(pool)
var id, draftID int64
if err = conn.QueryRow(ctx, `SELECT entity_id FROM demo_seed_entities WHERE kind='course' AND seed_key='everyday-english'`).Scan(&id); err != nil {
t.Fatal(err)
}
if err = conn.QueryRow(ctx, `SELECT entity_id FROM demo_seed_entities WHERE kind='course' AND seed_key='draft'`).Scan(&draftID); err != nil {
t.Fatal(err)
}
outline, err := store.PublicCatalogCourse(ctx, id)
if err != nil {
t.Fatal(err)
}
if outline.ChapterCount != 2 || outline.LessonCount != 6 || outline.QuizCount != 2 || len(outline.Chapters) != 2 {
t.Fatalf("outline counts=%+v", outline.PublicCourse)
}
if len(outline.Chapters[0].Lessons) != 3 || len(outline.Chapters[0].Quizzes) != 1 || outline.Chapters[0].Quizzes[0].QuestionCount != 3 {
t.Fatalf("chapter=%+v", outline.Chapters[0])
}
if _, err = store.PublicCatalogCourse(ctx, draftID); err != pgx.ErrNoRows {
t.Fatalf("draft course accessible: %v", err)
}
page, err := store.PublicCatalogCourses(ctx, "[Demo draft]", 20, 0)
if err != nil {
t.Fatal(err)
}
if page.TotalCount != 0 || len(page.Courses) != 0 {
t.Fatal("draft course leaked into search")
}
// A hidden chapter and all descendants must disappear from the public outline.
chapterID := outline.Chapters[0].ID
if _, err = conn.Exec(ctx, `UPDATE exam_prep.units SET publish_status='DRAFT' WHERE id=$1`, chapterID); err != nil {
t.Fatal(err)
}
defer conn.Exec(context.Background(), `UPDATE exam_prep.units SET publish_status='PUBLISHED' WHERE id=$1`, chapterID)
outline, err = store.PublicCatalogCourse(ctx, id)
if err != nil {
t.Fatal(err)
}
if len(outline.Chapters) != 1 || outline.LessonCount != 3 || outline.QuizCount != 1 {
t.Fatal("hidden chapter descendants leaked into preview")
}
}

243
internal/demoseed/seed.go Normal file
View File

@ -0,0 +1,243 @@
// 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)
}

View File

@ -0,0 +1,44 @@
package demoseed
import (
"Rezina-Backend/internal/domain"
"testing"
)
func TestEnvironmentGuard(t *testing.T) {
for _, tc := range []struct {
target, setting string
allowed bool
}{
{"development", "", true}, {"test", "test", true}, {"staging", "staging", true},
{"", "", false}, {"production", "", false}, {"development", "PRODUCTION", false}, {"test", "prod", false},
} {
err := ValidateEnvironment(tc.target, tc.setting)
if (err == nil) != tc.allowed {
t.Errorf("target=%q setting=%q err=%v", tc.target, tc.setting, err)
}
}
}
func TestAccountsCoverSupportedRoles(t *testing.T) {
roles := map[string]bool{}
emails := map[string]bool{}
for _, a := range Accounts {
if emails[a.Email] {
t.Fatalf("duplicate email %s", a.Email)
}
emails[a.Email] = true
roles[a.Role] = true
if a.Audience == "staff" && !domain.IsAssignableStaffTeamRole(domain.TeamRole(a.Role)) {
t.Errorf("unsupported staff role %s", a.Role)
}
if a.Audience == "customer" && !domain.Role(a.Role).IsCustomerLearnerRole() {
t.Errorf("unsupported customer role %s", a.Role)
}
}
for _, r := range []string{"SUPER_ADMIN", "ADMIN", "CONTENT_MANAGER", "STUDENT", "OPEN_LEARNER"} {
if !roles[r] {
t.Errorf("missing %s", r)
}
}
}

View File

@ -5,7 +5,7 @@ import "time"
// AdminUserLearningActivityDetails is the full learning picture for a learner in the unified hierarchy. // AdminUserLearningActivityDetails is the full learning picture for a learner in the unified hierarchy.
type AdminUserLearningActivityDetails struct { type AdminUserLearningActivityDetails struct {
UserID int64 `json:"user_id"` UserID int64 `json:"user_id"`
ExamPrep AdminUserExamPrepLearningSection `json:"exam_prep"` ExamPrep AdminUserExamPrepLearningSection `json:"learning"`
RecentActivity UserRecentActivityFeed `json:"recent_activity"` RecentActivity UserRecentActivityFeed `json:"recent_activity"`
} }
@ -16,22 +16,23 @@ type AdminUserExamPrepLearningSection struct {
// ExamPrepProgressSummary mirrors LMSProgressSummary for exam-prep catalog hierarchy. // ExamPrepProgressSummary mirrors LMSProgressSummary for exam-prep catalog hierarchy.
type ExamPrepProgressSummary struct { type ExamPrepProgressSummary struct {
CatalogCourses []ExamPrepProgressSummaryCatalogCourse `json:"catalog_courses"` CatalogCourses []ExamPrepProgressSummaryCatalogCourse `json:"courses"`
} }
type ExamPrepProgressSummaryCatalogCourse struct { type ExamPrepProgressSummaryCatalogCourse struct {
ID int64 `json:"id"` ID int64 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
Access *LMSEntityAccess `json:"access,omitempty"` Access *LMSEntityAccess `json:"access,omitempty"`
Units []ExamPrepProgressSummaryUnit `json:"units"` Units []ExamPrepProgressSummaryUnit `json:"chapters"`
} }
type ExamPrepProgressSummaryUnit struct { type ExamPrepProgressSummaryUnit struct {
ID int64 `json:"id"` ID int64 `json:"id"`
CatalogCourseID int64 `json:"catalog_course_id"` CatalogCourseID int64 `json:"course_id"`
Name string `json:"name"` Name string `json:"name"`
Access *LMSEntityAccess `json:"access,omitempty"` Access *LMSEntityAccess `json:"access,omitempty"`
Modules []ExamPrepProgressSummaryModule `json:"modules"` Lessons []ExamPrepProgressSummaryLesson `json:"lessons"`
Modules []ExamPrepProgressSummaryModule `json:"-"`
} }
type ExamPrepProgressSummaryModule struct { type ExamPrepProgressSummaryModule struct {
@ -43,16 +44,17 @@ type ExamPrepProgressSummaryModule struct {
} }
type ExamPrepProgressSummaryLesson struct { type ExamPrepProgressSummaryLesson struct {
ID int64 `json:"id"` ID int64 `json:"id"`
ModuleID int64 `json:"module_id"` ModuleID int64 `json:"-"`
Title string `json:"title"` ChapterID int64 `json:"chapter_id"`
Access *LMSEntityAccess `json:"access,omitempty"` Title string `json:"title"`
Access *LMSEntityAccess `json:"access,omitempty"`
} }
// AdminExamPrepUserLearningActivityTree is nested catalog course → unit → module → lesson → practice completions. // AdminExamPrepUserLearningActivityTree is nested catalog course → unit → module → lesson → practice completions.
type AdminExamPrepUserLearningActivityTree struct { type AdminExamPrepUserLearningActivityTree struct {
UserID int64 `json:"user_id"` UserID int64 `json:"user_id"`
CatalogCourses []AdminExamPrepCatalogCourseLearningEntry `json:"catalog_courses"` CatalogCourses []AdminExamPrepCatalogCourseLearningEntry `json:"courses"`
} }
type AdminExamPrepCatalogCourseLearningEntry struct { type AdminExamPrepCatalogCourseLearningEntry struct {
@ -60,7 +62,7 @@ type AdminExamPrepCatalogCourseLearningEntry struct {
Name string `json:"name"` Name string `json:"name"`
SortOrder int32 `json:"sort_order"` SortOrder int32 `json:"sort_order"`
Practices []AdminExamPrepPracticeLearningEntry `json:"practices"` Practices []AdminExamPrepPracticeLearningEntry `json:"practices"`
Units []AdminExamPrepUnitLearningEntry `json:"units"` Units []AdminExamPrepUnitLearningEntry `json:"chapters"`
} }
type AdminExamPrepUnitLearningEntry struct { type AdminExamPrepUnitLearningEntry struct {
@ -68,7 +70,8 @@ type AdminExamPrepUnitLearningEntry struct {
Name string `json:"name"` Name string `json:"name"`
SortOrder int32 `json:"sort_order"` SortOrder int32 `json:"sort_order"`
Practices []AdminExamPrepPracticeLearningEntry `json:"practices"` Practices []AdminExamPrepPracticeLearningEntry `json:"practices"`
Modules []AdminExamPrepModuleLearningEntry `json:"modules"` Lessons []AdminExamPrepLessonLearningEntry `json:"lessons"`
Modules []AdminExamPrepModuleLearningEntry `json:"-"`
} }
type AdminExamPrepModuleLearningEntry struct { type AdminExamPrepModuleLearningEntry struct {
@ -86,7 +89,7 @@ type AdminExamPrepLessonLearningEntry struct {
} }
type AdminExamPrepPracticeLearningEntry struct { type AdminExamPrepPracticeLearningEntry struct {
ExamPrepPracticeID int64 `json:"exam_prep_practice_id"` ExamPrepPracticeID int64 `json:"practice_id"`
Title string `json:"title"` Title string `json:"title"`
CompletedAt time.Time `json:"completed_at"` CompletedAt time.Time `json:"completed_at"`
} }

View File

@ -7,14 +7,14 @@ type ExamPrepCatalogCourse struct {
ID int64 `json:"id"` ID int64 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
Description *string `json:"description,omitempty"` Description *string `json:"description,omitempty"`
Category string `json:"category"` Category string `json:"-"`
Thumbnail *string `json:"thumbnail,omitempty"` Thumbnail *string `json:"thumbnail,omitempty"`
SortOrder int `json:"sort_order"` SortOrder int `json:"sort_order"`
PublishStatus ContentPublishStatus `json:"publish_status"` PublishStatus ContentPublishStatus `json:"publish_status"`
AccessTier ContentAccessTier `json:"access_tier"` AccessTier ContentAccessTier `json:"access_tier"`
EffectiveAccessTier ContentAccessTier `json:"effective_access_tier,omitempty"` EffectiveAccessTier ContentAccessTier `json:"effective_access_tier,omitempty"`
UnitsCount *int64 `json:"units_count,omitempty"` UnitsCount *int64 `json:"chapters_count,omitempty"`
ModulesCount *int64 `json:"modules_count,omitempty"` ModulesCount *int64 `json:"-"`
LessonsCount *int64 `json:"lessons_count,omitempty"` LessonsCount *int64 `json:"lessons_count,omitempty"`
HasPractice bool `json:"has_practice"` HasPractice bool `json:"has_practice"`
Access *LMSEntityAccess `json:"access,omitempty"` Access *LMSEntityAccess `json:"access,omitempty"`
@ -30,7 +30,7 @@ func (c ExamPrepCatalogCourse) VisibleToLearners() bool {
type CreateExamPrepCatalogCourseInput struct { type CreateExamPrepCatalogCourseInput struct {
Name string `json:"name" validate:"required"` Name string `json:"name" validate:"required"`
Description *string `json:"description,omitempty"` Description *string `json:"description,omitempty"`
Category string `json:"category" validate:"required,oneof=EDUCATION IELTS DUOLINGO"` Category string `json:"-"`
Thumbnail *string `json:"thumbnail,omitempty"` Thumbnail *string `json:"thumbnail,omitempty"`
// Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately. // Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.
PublishStatus *string `json:"publish_status,omitempty" validate:"omitempty,oneof=DRAFT draft PUBLISHED published"` PublishStatus *string `json:"publish_status,omitempty" validate:"omitempty,oneof=DRAFT draft PUBLISHED published"`
@ -40,7 +40,7 @@ type CreateExamPrepCatalogCourseInput struct {
type UpdateExamPrepCatalogCourseInput struct { type UpdateExamPrepCatalogCourseInput struct {
Name *string `json:"name,omitempty"` Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"` Description *string `json:"description,omitempty"`
Category *string `json:"category,omitempty" validate:"omitempty,oneof=EDUCATION IELTS DUOLINGO"` Category *string `json:"-"`
Thumbnail *string `json:"thumbnail,omitempty"` Thumbnail *string `json:"thumbnail,omitempty"`
SortOrder *int `json:"sort_order,omitempty"` SortOrder *int `json:"sort_order,omitempty"`
PublishStatus *string `json:"publish_status,omitempty" validate:"omitempty,oneof=DRAFT draft PUBLISHED published"` PublishStatus *string `json:"publish_status,omitempty" validate:"omitempty,oneof=DRAFT draft PUBLISHED published"`

View File

@ -4,20 +4,21 @@ import "time"
// ExamPrepLesson is a video lesson under an exam-prep unit module (exam_prep.unit_module_lessons). // ExamPrepLesson is a video lesson under an exam-prep unit module (exam_prep.unit_module_lessons).
type ExamPrepLesson struct { type ExamPrepLesson struct {
ID int64 `json:"id"` ChapterID int64 `json:"chapter_id"`
UnitModuleID int64 `json:"unit_module_id"` ID int64 `json:"id"`
Title string `json:"title"` UnitModuleID int64 `json:"-"`
VideoURL *string `json:"video_url,omitempty"` Title string `json:"title"`
Thumbnail *string `json:"thumbnail,omitempty"` VideoURL *string `json:"video_url,omitempty"`
Description *string `json:"description,omitempty"` Thumbnail *string `json:"thumbnail,omitempty"`
SortOrder int `json:"sort_order"` Description *string `json:"description,omitempty"`
SortOrder int `json:"sort_order"`
PublishStatus ContentPublishStatus `json:"publish_status"` PublishStatus ContentPublishStatus `json:"publish_status"`
AccessTier ContentAccessTier `json:"access_tier"` AccessTier ContentAccessTier `json:"access_tier"`
EffectiveAccessTier ContentAccessTier `json:"effective_access_tier,omitempty"` EffectiveAccessTier ContentAccessTier `json:"effective_access_tier,omitempty"`
HasPractice bool `json:"has_practice"` HasPractice bool `json:"has_practice"`
Access *LMSEntityAccess `json:"access,omitempty"` Access *LMSEntityAccess `json:"access,omitempty"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at,omitempty"` UpdatedAt *time.Time `json:"updated_at,omitempty"`
} }
// VisibleToLearners is true when the lesson appears in student/learner exam-prep APIs. // VisibleToLearners is true when the lesson appears in student/learner exam-prep APIs.

View File

@ -18,9 +18,9 @@ const (
// ParseExamPrepParentKind maps API/path input to a supported exam-prep parent kind. // ParseExamPrepParentKind maps API/path input to a supported exam-prep parent kind.
func ParseExamPrepParentKind(raw string) (ExamPrepParentKind, bool) { func ParseExamPrepParentKind(raw string) (ExamPrepParentKind, bool) {
switch strings.TrimSpace(strings.ToUpper(raw)) { switch strings.TrimSpace(strings.ToUpper(raw)) {
case string(ExamPrepParentKindCatalogCourse): case "COURSE", string(ExamPrepParentKindCatalogCourse):
return ExamPrepParentKindCatalogCourse, true return ExamPrepParentKindCatalogCourse, true
case string(ExamPrepParentKindUnit): case "CHAPTER", string(ExamPrepParentKindUnit):
return ExamPrepParentKindUnit, true return ExamPrepParentKindUnit, true
case string(ExamPrepParentKindLesson): case string(ExamPrepParentKindLesson):
return ExamPrepParentKindLesson, true return ExamPrepParentKindLesson, true
@ -31,25 +31,25 @@ func ParseExamPrepParentKind(raw string) (ExamPrepParentKind, bool) {
// ExamPrepPracticeParent links a practice to a catalog course, unit, or lesson. // ExamPrepPracticeParent links a practice to a catalog course, unit, or lesson.
type ExamPrepPracticeParent struct { type ExamPrepPracticeParent struct {
Kind ExamPrepParentKind `json:"parent_kind"` Kind ExamPrepParentKind `json:"parent_kind" swaggertype:"string" enums:"COURSE,CHAPTER,LESSON"`
ID int64 `json:"parent_id"` ID int64 `json:"parent_id"`
} }
// ExamPrepPractice is question-set content tied to an exam-prep parent; uses shared question_sets / questions. // ExamPrepPractice is question-set content tied to an exam-prep parent; uses shared question_sets / questions.
type ExamPrepPractice struct { type ExamPrepPractice struct {
ID int64 `json:"id"` ID int64 `json:"id"`
Parents *[]ExamPrepPracticeParent `json:"parents,omitempty"` Parents *[]ExamPrepPracticeParent `json:"parents,omitempty"`
LessonID *int64 `json:"lesson_id,omitempty"` LessonID *int64 `json:"lesson_id,omitempty"`
Title string `json:"title"` Title string `json:"title"`
StoryDescription *string `json:"story_description,omitempty"` StoryDescription *string `json:"story_description,omitempty"`
StoryImage *string `json:"story_image,omitempty"` StoryImage *string `json:"story_image,omitempty"`
PersonaID *int64 `json:"persona_id,omitempty"` PersonaID *int64 `json:"persona_id,omitempty"`
QuestionSetID int64 `json:"question_set_id"` QuestionSetID int64 `json:"question_set_id"`
PublishStatus PracticePublishStatus `json:"publish_status"` PublishStatus PracticePublishStatus `json:"publish_status"`
AuthoringProfile PracticeAuthoringProfile `json:"authoring_profile"` AuthoringProfile PracticeAuthoringProfile `json:"authoring_profile"`
QuickTips *string `json:"quick_tips,omitempty"` QuickTips *string `json:"quick_tips,omitempty"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at,omitempty"` UpdatedAt *time.Time `json:"updated_at,omitempty"`
} }
// ExamPrepPracticeParentsDeref returns parents or nil when unset. // ExamPrepPracticeParentsDeref returns parents or nil when unset.
@ -88,7 +88,7 @@ type CreateExamPrepPracticeInput struct {
// Parents optionally attaches the practice to catalog course, unit, or lesson. Omit or null to create unlinked. // Parents optionally attaches the practice to catalog course, unit, or lesson. Omit or null to create unlinked.
Parents *[]ExamPrepPracticeParent `json:"parents" validate:"omitempty,dive"` Parents *[]ExamPrepPracticeParent `json:"parents" validate:"omitempty,dive"`
// ParentKind and ParentID are accepted for backward compatibility when parents is omitted. // ParentKind and ParentID are accepted for backward compatibility when parents is omitted.
ParentKind ExamPrepParentKind `json:"parent_kind,omitempty" validate:"omitempty,oneof=CATALOG_COURSE UNIT LESSON"` ParentKind ExamPrepParentKind `json:"parent_kind,omitempty" validate:"omitempty,oneof=CATALOG_COURSE UNIT LESSON" swaggertype:"string" enums:"COURSE,CHAPTER,LESSON"`
ParentID int64 `json:"parent_id,omitempty" validate:"omitempty,gt=0"` ParentID int64 `json:"parent_id,omitempty" validate:"omitempty,gt=0"`
Title *string `json:"title,omitempty"` Title *string `json:"title,omitempty"`
StoryDescription *string `json:"story_description,omitempty"` StoryDescription *string `json:"story_description,omitempty"`

View File

@ -4,22 +4,22 @@ import "time"
// ExamPrepUnit is a chapter-like grouping under an exam-prep catalog course (schema exam_prep.units). // ExamPrepUnit is a chapter-like grouping under an exam-prep catalog course (schema exam_prep.units).
type ExamPrepUnit struct { type ExamPrepUnit struct {
ID int64 `json:"id"` ID int64 `json:"id"`
CatalogCourseID int64 `json:"catalog_course_id"` CatalogCourseID int64 `json:"course_id"`
Name string `json:"name"` Name string `json:"name"`
Description *string `json:"description,omitempty"` Description *string `json:"description,omitempty"`
Thumbnail *string `json:"thumbnail,omitempty"` Thumbnail *string `json:"thumbnail,omitempty"`
SortOrder int `json:"sort_order"` SortOrder int `json:"sort_order"`
PublishStatus ContentPublishStatus `json:"publish_status"` PublishStatus ContentPublishStatus `json:"publish_status"`
AccessTier ContentAccessTier `json:"access_tier"` AccessTier ContentAccessTier `json:"access_tier"`
EffectiveAccessTier ContentAccessTier `json:"effective_access_tier,omitempty"` EffectiveAccessTier ContentAccessTier `json:"effective_access_tier,omitempty"`
ModulesCount *int64 `json:"modules_count,omitempty"` ModulesCount *int64 `json:"-"`
LessonsCount *int64 `json:"lessons_count,omitempty"` LessonsCount *int64 `json:"lessons_count,omitempty"`
PracticesCount *int64 `json:"practices_count,omitempty"` PracticesCount *int64 `json:"practices_count,omitempty"`
HasPractice bool `json:"has_practice"` HasPractice bool `json:"has_practice"`
Access *LMSEntityAccess `json:"access,omitempty"` Access *LMSEntityAccess `json:"access,omitempty"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at,omitempty"` UpdatedAt *time.Time `json:"updated_at,omitempty"`
} }
// VisibleToLearners is true when the unit appears in student/learner exam-prep APIs. // VisibleToLearners is true when the unit appears in student/learner exam-prep APIs.

View File

@ -0,0 +1,66 @@
package domain
import (
"encoding/json"
"strings"
"testing"
)
func TestLearningHierarchyJSON(t *testing.T) {
course, _ := json.Marshal(ExamPrepCatalogCourse{Category: "IELTS"})
chapter, _ := json.Marshal(ExamPrepUnit{CatalogCourseID: 3})
lesson, _ := json.Marshal(ExamPrepLesson{UnitModuleID: 999, ChapterID: 7})
if strings.Contains(string(course), "category") || strings.Contains(string(course), "modules_count") {
t.Fatalf("legacy course fields leaked: %s", course)
}
if !strings.Contains(string(chapter), `"course_id":3`) {
t.Fatalf("chapter=%s", chapter)
}
if !strings.Contains(string(lesson), `"chapter_id":7`) || strings.Contains(string(lesson), "unit_module_id") {
t.Fatalf("lesson=%s", lesson)
}
}
func TestChapterParentJSONPreservesStorageScope(t *testing.T) {
var parent ExamPrepPracticeParent
if err := json.Unmarshal([]byte(`{"parent_kind":"CHAPTER","parent_id":7}`), &parent); err != nil {
t.Fatal(err)
}
if parent.Kind != ExamPrepParentKindUnit {
t.Fatalf("storage scope=%s", parent.Kind)
}
data, err := json.Marshal(parent)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(data), `"CHAPTER"`) {
t.Fatalf("public parent=%s", data)
}
scope, err := ResolveExamPrepPracticeCompletionScope([]ExamPrepPracticeParent{parent}, CompletePracticeInput{ParentKind: "CHAPTER", ParentID: 7})
if err != nil || scope.ParentKind != "UNIT" {
t.Fatalf("scope=%v err=%v", scope, err)
}
}
func TestLearningParentJSONNormalizesInput(t *testing.T) {
for _, tc := range []struct {
input string
want ExamPrepParentKind
}{
{" chapter ", ExamPrepParentKindUnit},
{"course", ExamPrepParentKindCatalogCourse},
{"lesson", ExamPrepParentKindLesson},
} {
var kind ExamPrepParentKind
data, err := json.Marshal(tc.input)
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(data, &kind); err != nil {
t.Fatal(err)
}
if kind != tc.want {
t.Fatalf("input=%q kind=%s want=%s", tc.input, kind, tc.want)
}
}
}

View File

@ -0,0 +1,35 @@
package domain
import (
"encoding/json"
"strings"
)
// Storage discriminators are stable so historical completion scopes stay valid.
// The API exposes only the current hierarchy vocabulary.
func (k ExamPrepParentKind) MarshalJSON() ([]byte, error) {
value := string(k)
switch k {
case ExamPrepParentKindUnit:
value = "CHAPTER"
case ExamPrepParentKindCatalogCourse:
value = "COURSE"
}
return json.Marshal(value)
}
func (k *ExamPrepParentKind) UnmarshalJSON(data []byte) error {
var value string
if err := json.Unmarshal(data, &value); err != nil {
return err
}
value = strings.ToUpper(strings.TrimSpace(value))
switch value {
case "CHAPTER":
value = "UNIT"
case "COURSE":
value = "CATALOG_COURSE"
}
*k = ExamPrepParentKind(value)
return nil
}

View File

@ -0,0 +1,47 @@
package domain
// Public catalog DTOs deliberately contain no playback URLs, answers, or user data.
type PublicCourse struct {
ID int64 `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Thumbnail string `json:"thumbnail"`
AccessTier string `json:"access_tier" enums:"FREE,PREMIUM"`
ChapterCount int64 `json:"chapter_count"`
LessonCount int64 `json:"lesson_count"`
QuizCount int64 `json:"quiz_count"`
}
type PublicCatalogPage struct {
Courses []PublicCourse `json:"courses"`
TotalCount int64 `json:"total_count"`
Limit int32 `json:"limit"`
Offset int32 `json:"offset"`
}
type PublicCourseOutline struct {
PublicCourse
Chapters []PublicChapter `json:"chapters"`
}
type PublicChapter struct {
ID int64 `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Lessons []PublicLesson `json:"lessons"`
Quizzes []PublicQuiz `json:"quizzes"`
}
type PublicLesson struct {
ID int64 `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
Thumbnail string `json:"thumbnail"`
AccessTier string `json:"access_tier" enums:"FREE,PREMIUM"`
}
type PublicQuiz struct {
ID int64 `json:"id"`
Title string `json:"title"`
QuestionCount int64 `json:"question_count"`
}

View File

@ -8,7 +8,7 @@ const (
const VideoCompletionThresholdPercent = 90 const VideoCompletionThresholdPercent = 90
type VideoEngagementHeartbeatInput struct { type VideoEngagementHeartbeatInput struct {
ContentKind string `json:"content_kind" validate:"required,oneof=lms_lesson exam_prep_lesson"` ContentKind string `json:"content_kind" validate:"required,oneof=lesson"`
ContentID int64 `json:"content_id" validate:"required,gt=0"` ContentID int64 `json:"content_id" validate:"required,gt=0"`
PositionSec int `json:"position_sec" validate:"gte=0"` PositionSec int `json:"position_sec" validate:"gte=0"`
DurationSec int `json:"duration_sec" validate:"gte=0"` DurationSec int `json:"duration_sec" validate:"gte=0"`

View File

@ -0,0 +1,44 @@
package repository
import (
"context"
"github.com/jackc/pgx/v5"
)
// GetChapterLessonContainer hides legacy module storage behind a chapter. The
// chapter row lock prevents two first lessons from creating separate containers.
func (s *Store) GetChapterLessonContainer(ctx context.Context, chapterID int64) (int64, error) {
tx, err := s.conn.Begin(ctx)
if err != nil {
return 0, err
}
defer tx.Rollback(ctx)
var id int64
if err = tx.QueryRow(ctx, `SELECT id FROM exam_prep.units WHERE id=$1 FOR UPDATE`, chapterID).Scan(&id); err != nil {
return 0, err
}
err = tx.QueryRow(ctx, `SELECT module_id FROM exam_prep.chapter_lesson_containers WHERE chapter_id=$1`, chapterID).Scan(&id)
if err == pgx.ErrNoRows {
err = tx.QueryRow(ctx, `INSERT INTO exam_prep.unit_modules (unit_id,name,sort_order,publish_status,access_tier)
SELECT $1,'__chapter_lessons__',COALESCE(MAX(sort_order),0)+1,'PUBLISHED','FREE'
FROM exam_prep.unit_modules WHERE unit_id=$1 RETURNING id`, chapterID).Scan(&id)
if err != nil {
return 0, err
}
_, err = tx.Exec(ctx, `INSERT INTO exam_prep.chapter_lesson_containers(chapter_id,module_id) VALUES($1,$2)`, chapterID, id)
}
if err != nil {
return 0, err
}
if err = tx.Commit(ctx); err != nil {
return 0, err
}
return id, nil
}
func (s *Store) lessonChapterID(ctx context.Context, moduleID int64) (int64, error) {
var id int64
err := s.conn.QueryRow(ctx, `SELECT unit_id FROM exam_prep.unit_modules WHERE id=$1`, moduleID).Scan(&id)
return id, err
}

View File

@ -0,0 +1,45 @@
package repository
import (
"Rezina-Backend/internal/domain"
"context"
)
func (s *Store) ListChapterQuizzes(ctx context.Context, chapterID int64, publishedOnly bool, limit, offset int32) ([]domain.ExamPrepPractice, int64, error) {
var total int64
const filter = ` 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
WHERE pp.parent_kind='UNIT' AND pp.parent_id=$1 AND qs.set_type='QUIZ'
AND (NOT $2 OR (p.publish_status='PUBLISHED' AND qs.status='PUBLISHED'))`
if err := s.conn.QueryRow(ctx, `SELECT COUNT(*)`+filter, chapterID, publishedOnly).Scan(&total); err != nil {
return nil, 0, err
}
rows, err := s.conn.Query(ctx, `SELECT p.id`+filter+` ORDER BY p.created_at,p.id LIMIT $3 OFFSET $4`, chapterID, publishedOnly, limit, offset)
if err != nil {
return nil, 0, err
}
ids := []int64{}
for rows.Next() {
var id int64
if err = rows.Scan(&id); err != nil {
rows.Close()
return nil, 0, err
}
ids = append(ids, id)
}
err = rows.Err()
rows.Close()
if err != nil {
return nil, 0, err
}
items := make([]domain.ExamPrepPractice, 0, len(ids))
for _, id := range ids {
p, err := s.GetExamPrepLessonPracticeByID(ctx, id)
if err != nil {
return nil, 0, err
}
items = append(items, p)
}
return items, total, nil
}

View File

@ -44,7 +44,9 @@ func (s *Store) CreateExamPrepUnitModuleLesson(ctx context.Context, unitModuleID
if err != nil { if err != nil {
return domain.ExamPrepLesson{}, err return domain.ExamPrepLesson{}, err
} }
return examPrepLessonToDomain(l), nil out := examPrepLessonToDomain(l)
out.ChapterID, err = s.lessonChapterID(ctx, out.UnitModuleID)
return out, err
} }
func (s *Store) GetExamPrepUnitModuleLessonByID(ctx context.Context, id int64) (domain.ExamPrepLesson, error) { func (s *Store) GetExamPrepUnitModuleLessonByID(ctx context.Context, id int64) (domain.ExamPrepLesson, error) {
@ -68,6 +70,10 @@ func (s *Store) GetExamPrepUnitModuleLessonByID(ctx context.Context, id int64) (
PublishStatus: l.PublishStatus, PublishStatus: l.PublishStatus,
AccessTier: l.AccessTier, AccessTier: l.AccessTier,
}) })
out.ChapterID, err = s.lessonChapterID(ctx, out.UnitModuleID)
if err != nil {
return domain.ExamPrepLesson{}, err
}
out.HasPractice = l.HasPractice out.HasPractice = l.HasPractice
return out, nil return out, nil
} }
@ -85,6 +91,10 @@ func (s *Store) ListExamPrepUnitModuleLessonsByUnitModuleID(ctx context.Context,
if len(rows) == 0 { if len(rows) == 0 {
return []domain.ExamPrepLesson{}, 0, nil return []domain.ExamPrepLesson{}, 0, nil
} }
chapterID, err := s.lessonChapterID(ctx, unitModuleID)
if err != nil {
return nil, 0, err
}
var total int64 var total int64
out := make([]domain.ExamPrepLesson, 0, len(rows)) out := make([]domain.ExamPrepLesson, 0, len(rows))
for i, r := range rows { for i, r := range rows {
@ -104,6 +114,7 @@ func (s *Store) ListExamPrepUnitModuleLessonsByUnitModuleID(ctx context.Context,
PublishStatus: r.PublishStatus, PublishStatus: r.PublishStatus,
AccessTier: r.AccessTier, AccessTier: r.AccessTier,
}) })
item.ChapterID = chapterID
item.HasPractice = r.HasPractice item.HasPractice = r.HasPractice
out = append(out, item) out = append(out, item)
} }
@ -141,7 +152,9 @@ func (s *Store) UpdateExamPrepUnitModuleLesson(ctx context.Context, id int64, in
} }
return domain.ExamPrepLesson{}, err return domain.ExamPrepLesson{}, err
} }
return examPrepLessonToDomain(l), nil out := examPrepLessonToDomain(l)
out.ChapterID, err = s.lessonChapterID(ctx, out.UnitModuleID)
return out, err
} }
func (s *Store) DeleteExamPrepUnitModuleLesson(ctx context.Context, id int64) error { func (s *Store) DeleteExamPrepUnitModuleLesson(ctx context.Context, id int64) error {

View File

@ -0,0 +1,115 @@
package repository
import (
"Rezina-Backend/internal/domain"
"context"
)
const publicCourseColumns = `c.id,c.name,COALESCE(c.description,''),COALESCE(c.thumbnail,''),c.access_tier,
(SELECT COUNT(*) FROM exam_prep.units u WHERE u.catalog_course_id=c.id AND u.publish_status='PUBLISHED'),
(SELECT COUNT(*) 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 u.publish_status='PUBLISHED'
AND m.publish_status='PUBLISHED' AND l.publish_status='PUBLISHED'),
(SELECT COUNT(*) 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 WHERE u.catalog_course_id=c.id AND u.publish_status='PUBLISHED'
AND p.publish_status='PUBLISHED' AND qs.status='PUBLISHED' AND qs.set_type='QUIZ')`
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'
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
}
rows, err := s.conn.Query(ctx, `SELECT `+publicCourseColumns+filter+` ORDER BY c.sort_order,c.id LIMIT $2 OFFSET $3`, search, limit, offset)
if err != nil {
return out, err
}
defer rows.Close()
for rows.Next() {
var c domain.PublicCourse
if err := rows.Scan(&c.ID, &c.Name, &c.Description, &c.Thumbnail, &c.AccessTier, &c.ChapterCount, &c.LessonCount, &c.QuizCount); err != nil {
return out, err
}
out.Courses = append(out.Courses, c)
}
return out, rows.Err()
}
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).
Scan(&out.ID, &out.Name, &out.Description, &out.Thumbnail, &out.AccessTier, &out.ChapterCount, &out.LessonCount, &out.QuizCount)
if err != nil {
return out, err
}
rows, err := s.conn.Query(ctx, `SELECT id,name,COALESCE(description,'') FROM exam_prep.units
WHERE catalog_course_id=$1 AND publish_status='PUBLISHED' ORDER BY sort_order,id`, id)
if err != nil {
return out, err
}
indices := map[int64]int{}
for rows.Next() {
var chapter domain.PublicChapter
if err := rows.Scan(&chapter.ID, &chapter.Name, &chapter.Description); err != nil {
rows.Close()
return out, err
}
chapter.Lessons = []domain.PublicLesson{}
chapter.Quizzes = []domain.PublicQuiz{}
indices[chapter.ID] = len(out.Chapters)
out.Chapters = append(out.Chapters, chapter)
}
err = rows.Err()
rows.Close()
if err != nil {
return out, err
}
rows, err = s.conn.Query(ctx, `SELECT u.id,l.id,l.title,COALESCE(l.description,''),COALESCE(l.thumbnail,''),
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'
ORDER BY u.sort_order,u.id,m.sort_order,m.id,l.sort_order,l.id`, id)
if err != nil {
return out, err
}
for rows.Next() {
var chapterID int64
var l domain.PublicLesson
if err := rows.Scan(&chapterID, &l.ID, &l.Title, &l.Description, &l.Thumbnail, &l.AccessTier); err != nil {
rows.Close()
return out, err
}
if index, ok := indices[chapterID]; ok {
out.Chapters[index].Lessons = append(out.Chapters[index].Lessons, l)
}
}
err = rows.Err()
rows.Close()
if err != nil {
return out, err
}
rows, err = s.conn.Query(ctx, `SELECT u.id,p.id,p.title,(SELECT COUNT(*) FROM question_set_items i JOIN questions q ON q.id=i.question_id WHERE i.set_id=qs.id AND q.status='PUBLISHED')
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'
ORDER BY u.sort_order,u.id,p.id`, id)
if err != nil {
return out, err
}
defer rows.Close()
for rows.Next() {
var chapterID int64
var q domain.PublicQuiz
if err := rows.Scan(&chapterID, &q.ID, &q.Title, &q.QuestionCount); err != nil {
return out, err
}
if index, ok := indices[chapterID]; ok {
out.Chapters[index].Quizzes = append(out.Chapters[index].Quizzes, q)
}
}
return out, rows.Err()
}

View File

@ -0,0 +1,60 @@
package examprep
import (
"Rezina-Backend/internal/domain"
"context"
)
// ValidQuizParents deliberately excludes course and lesson attachments.
func ValidQuizParents(parents []domain.ExamPrepPracticeParent) bool {
return len(parents) == 1 && parents[0].Kind == domain.ExamPrepParentKindUnit && parents[0].ID > 0
}
func (s *Service) validateQuestionSetParents(ctx context.Context, id int64, parents []domain.ExamPrepPracticeParent) error {
set, err := s.store.GetQuestionSetByID(ctx, id)
if err != nil {
return s.validateQuestionSet(ctx, id)
}
if set.SetType == string(domain.QuestionSetTypeQuiz) {
if !ValidQuizParents(parents) {
return ErrInvalidExamPrepPracticeParent
}
return nil
}
return s.validateQuestionSet(ctx, id)
}
func (s *Service) CreateChapterQuiz(ctx context.Context, chapterID int64, input domain.CreateExamPrepPracticeInput) (domain.ExamPrepPractice, error) {
set, err := s.store.GetQuestionSetByID(ctx, input.QuestionSetID)
if err != nil {
return domain.ExamPrepPractice{}, ErrQuestionSetNotFound
}
if set.SetType != string(domain.QuestionSetTypeQuiz) {
return domain.ExamPrepPractice{}, ErrExamPrepQuizRequiresQuizSet
}
// A nested URL is authoritative; callers cannot redirect the quiz elsewhere.
parents := []domain.ExamPrepPracticeParent{{Kind: domain.ExamPrepParentKindUnit, ID: chapterID}}
if input.Parents != nil || input.ParentKind != "" || input.ParentID != 0 {
return domain.ExamPrepPractice{}, ErrInvalidExamPrepPracticeParent
}
if input.PublishStatus == "" {
input.PublishStatus = "DRAFT"
}
return s.createExamPrepPractice(ctx, parents, input)
}
func (s *Service) ListChapterQuizzes(ctx context.Context, chapterID int64, publishedOnly bool, limit, offset int32) ([]domain.ExamPrepPractice, int64, error) {
if err := s.ensureUnit(ctx, chapterID); err != nil {
return nil, 0, err
}
if limit <= 0 {
limit = 20
}
if limit > 200 {
limit = 200
}
if offset < 0 {
offset = 0
}
return s.store.ListChapterQuizzes(ctx, chapterID, publishedOnly, limit, offset)
}

View File

@ -0,0 +1,93 @@
package examprep
import (
"context"
"errors"
"testing"
"Rezina-Backend/internal/domain"
"github.com/jackc/pgx/v5"
)
type quizStore struct {
examPrepStore
set domain.QuestionSet
created bool
input domain.CreateExamPrepPracticeInput
parents []domain.ExamPrepPracticeParent
}
func (s *quizStore) GetQuestionSetByID(context.Context, int64) (domain.QuestionSet, error) {
if s.set.ID == 0 {
return domain.QuestionSet{}, pgx.ErrNoRows
}
return s.set, nil
}
func (s *quizStore) GetExamPrepUnitByID(context.Context, int64) (domain.ExamPrepUnit, error) {
return domain.ExamPrepUnit{ID: 7}, nil
}
func (s *quizStore) CreateExamPrepPractice(_ context.Context, in domain.CreateExamPrepPracticeInput, parents []domain.ExamPrepPracticeParent) (domain.ExamPrepPractice, error) {
s.created = true
s.input = in
s.parents = parents
return domain.ExamPrepPractice{ID: 10, QuestionSetID: in.QuestionSetID, Parents: domain.ExamPrepPracticeParentsPtr(parents)}, nil
}
func TestChapterQuizCreation(t *testing.T) {
tests := []struct {
name string
setType string
override bool
want error
}{
{name: "quiz defaults to draft", setType: "QUIZ"},
{name: "practice is rejected", setType: "PRACTICE", want: ErrExamPrepQuizRequiresQuizSet},
{name: "exam is rejected", setType: "EXAM", want: ErrExamPrepQuizRequiresQuizSet},
{name: "URL parent cannot be overridden", setType: "QUIZ", override: true, want: ErrInvalidExamPrepPracticeParent},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
store := &quizStore{set: domain.QuestionSet{ID: 3, SetType: tc.setType}}
in := domain.CreateExamPrepPracticeInput{QuestionSetID: 3}
if tc.override {
in.ParentKind = domain.ExamPrepParentKindLesson
in.ParentID = 99
}
_, err := NewService(store).CreateChapterQuiz(context.Background(), 7, in)
if !errors.Is(err, tc.want) {
t.Fatalf("error=%v want=%v", err, tc.want)
}
if tc.want != nil {
if store.created {
t.Fatal("invalid quiz was persisted")
}
return
}
if store.input.PublishStatus != "DRAFT" {
t.Fatal("quiz should default to DRAFT")
}
if len(store.parents) != 1 || store.parents[0].Kind != domain.ExamPrepParentKindUnit || store.parents[0].ID != 7 {
t.Fatalf("parents=%v", store.parents)
}
})
}
}
func TestQuizCannotBeLinkedOutsideOneChapter(t *testing.T) {
store := &quizStore{set: domain.QuestionSet{ID: 3, SetType: "QUIZ"}}
service := NewService(store)
for _, parents := range [][]domain.ExamPrepPracticeParent{
nil,
{{Kind: domain.ExamPrepParentKindCatalogCourse, ID: 7}},
{{Kind: domain.ExamPrepParentKindLesson, ID: 7}},
{{Kind: domain.ExamPrepParentKindUnit, ID: 7}, {Kind: domain.ExamPrepParentKindUnit, ID: 8}},
} {
_, err := service.createExamPrepPractice(context.Background(), parents, domain.CreateExamPrepPracticeInput{QuestionSetID: 3})
if !errors.Is(err, ErrInvalidExamPrepPracticeParent) {
t.Fatalf("parents=%v error=%v", parents, err)
}
}
if store.created {
t.Fatal("invalid quiz was persisted")
}
}

View File

@ -0,0 +1,20 @@
package examprep
import (
"Rezina-Backend/internal/domain"
"context"
"errors"
"github.com/jackc/pgx/v5"
)
func (s *Service) PublicCatalogCourses(ctx context.Context, search string, limit, offset int32) (domain.PublicCatalogPage, error) {
return s.store.PublicCatalogCourses(ctx, search, limit, offset)
}
func (s *Service) PublicCatalogCourse(ctx context.Context, id int64) (domain.PublicCourseOutline, error) {
out, err := s.store.PublicCatalogCourse(ctx, id)
if errors.Is(err, pgx.ErrNoRows) {
return out, ErrCatalogCourseNotFound
}
return out, err
}

View File

@ -15,6 +15,7 @@ var ErrModuleNotFound = errors.New("exam prep module not found")
var ErrLessonNotFound = errors.New("exam prep lesson not found") var ErrLessonNotFound = errors.New("exam prep lesson not found")
var ErrPracticeNotFound = errors.New("exam prep practice not found") var ErrPracticeNotFound = errors.New("exam prep practice not found")
var ErrQuestionSetNotFound = errors.New("question set not found") var ErrQuestionSetNotFound = errors.New("question set not found")
var ErrExamPrepQuizRequiresQuizSet = errors.New("chapter quizzes require a QUIZ question set")
var ErrExamPrepPracticeRequiresPracticeSet = errors.New("exam-prep practice must use a PRACTICE question set") var ErrExamPrepPracticeRequiresPracticeSet = errors.New("exam-prep practice must use a PRACTICE question set")
var ErrExamPrepAssessmentRequiresExamSet = errors.New("exam-prep assessment must use an EXAM question set") var ErrExamPrepAssessmentRequiresExamSet = errors.New("exam-prep assessment must use an EXAM question set")
var ErrQuestionSetNotExamPrepAssessment = errors.New("question set is not linked as an exam-prep assessment") var ErrQuestionSetNotExamPrepAssessment = errors.New("question set is not linked as an exam-prep assessment")
@ -24,6 +25,10 @@ var ErrExamPrepPracticeParentLinkNotFound = errors.New("practice is not linked t
// examPrepStore is implemented by *repository.Store (catalog courses, units, modules, lessons, practices, personas). // examPrepStore is implemented by *repository.Store (catalog courses, units, modules, lessons, practices, personas).
type examPrepStore interface { type examPrepStore interface {
PublicCatalogCourses(context.Context, string, int32, int32) (domain.PublicCatalogPage, error)
PublicCatalogCourse(context.Context, int64) (domain.PublicCourseOutline, error)
ListChapterQuizzes(ctx context.Context, chapterID int64, publishedOnly bool, limit, offset int32) ([]domain.ExamPrepPractice, int64, error)
GetChapterLessonContainer(ctx context.Context, chapterID int64) (int64, error)
ports.ExamPrepCatalogCourseStore ports.ExamPrepCatalogCourseStore
ports.ExamPrepUnitStore ports.ExamPrepUnitStore
ports.ExamPrepModuleStore ports.ExamPrepModuleStore
@ -54,6 +59,7 @@ func (s *Service) ensurePersonaRef(ctx context.Context, id int64) error {
} }
func (s *Service) CreateCatalogCourse(ctx context.Context, input domain.CreateExamPrepCatalogCourseInput) (domain.ExamPrepCatalogCourse, error) { func (s *Service) CreateCatalogCourse(ctx context.Context, input domain.CreateExamPrepCatalogCourseInput) (domain.ExamPrepCatalogCourse, error) {
input.Category = "EDUCATION"
return s.store.CreateExamPrepCatalogCourse(ctx, input) return s.store.CreateExamPrepCatalogCourse(ctx, input)
} }
@ -416,7 +422,7 @@ func (s *Service) resolveNestedCreateParents(input domain.CreateExamPrepPractice
} }
func (s *Service) createExamPrepPractice(ctx context.Context, parents []domain.ExamPrepPracticeParent, input domain.CreateExamPrepPracticeInput) (domain.ExamPrepPractice, error) { func (s *Service) createExamPrepPractice(ctx context.Context, parents []domain.ExamPrepPracticeParent, input domain.CreateExamPrepPracticeInput) (domain.ExamPrepPractice, error) {
if err := s.validateQuestionSet(ctx, input.QuestionSetID); err != nil { if err := s.validateQuestionSetParents(ctx, input.QuestionSetID, parents); err != nil {
return domain.ExamPrepPractice{}, err return domain.ExamPrepPractice{}, err
} }
if input.PersonaID != nil { if input.PersonaID != nil {
@ -527,6 +533,13 @@ func (s *Service) UpdateExamPrepPracticeParents(ctx context.Context, id int64, i
return domain.ExamPrepPractice{}, err return domain.ExamPrepPractice{}, err
} }
parents := domain.DedupeExamPrepPracticeParents(in.Parents) parents := domain.DedupeExamPrepPracticeParents(in.Parents)
existing, err := s.GetExamPrepPracticeByID(ctx, id)
if err != nil {
return domain.ExamPrepPractice{}, err
}
if err := s.validateQuestionSetParents(ctx, existing.QuestionSetID, parents); err != nil {
return domain.ExamPrepPractice{}, err
}
if len(parents) > 0 { if len(parents) > 0 {
if err := s.validateExamPrepParentList(ctx, parents); err != nil { if err := s.validateExamPrepParentList(ctx, parents); err != nil {
return domain.ExamPrepPractice{}, err return domain.ExamPrepPractice{}, err
@ -577,7 +590,24 @@ func (s *Service) TryGetExamPrepPracticeByQuestionSetID(ctx context.Context, que
func (s *Service) UpdateExamPrepPractice(ctx context.Context, id int64, input domain.UpdateExamPrepPracticeInput) (domain.ExamPrepPractice, error) { func (s *Service) UpdateExamPrepPractice(ctx context.Context, id int64, input domain.UpdateExamPrepPracticeInput) (domain.ExamPrepPractice, error) {
if input.QuestionSetID != nil { if input.QuestionSetID != nil {
if err := s.validateQuestionSet(ctx, *input.QuestionSetID); err != nil { existing, err := s.GetExamPrepPracticeByID(ctx, id)
if err != nil {
return domain.ExamPrepPractice{}, err
}
currentSet, setErr := s.store.GetQuestionSetByID(ctx, existing.QuestionSetID)
if setErr != nil {
return domain.ExamPrepPractice{}, setErr
}
if currentSet.SetType == "QUIZ" {
nextSet, nextErr := s.store.GetQuestionSetByID(ctx, *input.QuestionSetID)
if nextErr != nil {
return domain.ExamPrepPractice{}, ErrQuestionSetNotFound
}
if nextSet.SetType != "QUIZ" {
return domain.ExamPrepPractice{}, ErrExamPrepQuizRequiresQuizSet
}
}
if err := s.validateQuestionSetParents(ctx, *input.QuestionSetID, domain.ExamPrepPracticeParentsDeref(existing.Parents)); err != nil {
return domain.ExamPrepPractice{}, err return domain.ExamPrepPractice{}, err
} }
} }
@ -678,3 +708,10 @@ func (s *Service) UnlinkExamPrepAssessment(ctx context.Context, questionSetID in
} }
return nil return nil
} }
func (s *Service) GetChapterLessonContainer(ctx context.Context, chapterID int64) (int64, error) {
if err := s.ensureUnit(ctx, chapterID); err != nil {
return 0, err
}
return s.store.GetChapterLessonContainer(ctx, chapterID)
}

View File

@ -238,8 +238,12 @@ func buildAdminExamPrepLearningActivityTree(userID int64, rows []dbgen.ListUserE
ID: ma.id, Name: ma.name, SortOrder: ma.sortOrder, Lessons: lessons, ID: ma.id, Name: ma.name, SortOrder: ma.sortOrder, Lessons: lessons,
}) })
} }
chapterLessons := make([]domain.AdminExamPrepLessonLearningEntry, 0)
for _, module := range modules {
chapterLessons = append(chapterLessons, module.Lessons...)
}
units = append(units, domain.AdminExamPrepUnitLearningEntry{ units = append(units, domain.AdminExamPrepUnitLearningEntry{
ID: ua.id, Name: ua.name, SortOrder: ua.sortOrder, Practices: ua.practices, Modules: modules, ID: ua.id, Name: ua.name, SortOrder: ua.sortOrder, Practices: ua.practices, Modules: modules, Lessons: chapterLessons,
}) })
} }
catalogs = append(catalogs, domain.AdminExamPrepCatalogCourseLearningEntry{ catalogs = append(catalogs, domain.AdminExamPrepCatalogCourseLearningEntry{

View File

@ -87,12 +87,12 @@ func TestRegisteredAPISurfaces(t *testing.T) {
routes[route.Method+" "+route.Path] = true routes[route.Method+" "+route.Path] = true
} }
} }
for _, route := range []string{"POST /api/v1/admin/exam-prep/catalog-courses", "GET /api/v1/exam-prep/catalog-courses", "POST /api/v1/admin/team/login", "POST /api/v1/user/register", "GET /api/v1/admin/users", "GET /api/v1/referrals/me", "POST /api/v1/payments/webhook", "GET /api/v1/payments/chapa/callback", "GET /api/v1/auth/google/callback"} { for _, route := range []string{"POST /api/v1/admin/courses", "GET /api/v1/courses", "GET /api/v1/courses/:courseId/chapters", "GET /api/v1/chapters/:chapterId/lessons", "POST /api/v1/admin/chapters/:chapterId/quizzes", "GET /api/v1/quizzes/:practiceId/questions", "POST /api/v1/progress/quizzes/:id/complete", "POST /api/v1/admin/team/login", "POST /api/v1/user/register", "GET /api/v1/admin/users", "GET /api/v1/referrals/me", "POST /api/v1/payments/webhook", "GET /api/v1/payments/chapa/callback", "GET /api/v1/auth/google/callback"} {
if !routes[route] { if !routes[route] {
t.Errorf("missing route %s", route) t.Errorf("missing route %s", route)
} }
} }
for _, route := range []string{"POST /api/v1/exam-prep/catalog-courses", "GET /api/v1/questions", "GET /api/v1/users", "GET /api/v1/rbac/roles", "POST /api/v1/team/login", "GET /api/v1/questions", "POST /api/v1/admin/user/register", "GET /api/v1/client/subscriptions/me", "POST /api/v1/admin/subscriptions/checkout"} { for _, route := range []string{"POST /api/v1/courses", "GET /api/v1/exam-prep/catalog-courses", "GET /api/v1/units/1", "GET /api/v1/modules/1", "GET /api/v1/questions", "GET /api/v1/users", "GET /api/v1/rbac/roles", "POST /api/v1/team/login", "GET /api/v1/questions", "POST /api/v1/admin/user/register", "GET /api/v1/client/subscriptions/me", "POST /api/v1/admin/subscriptions/checkout"} {
if routes[route] { if routes[route] {
t.Errorf("unexpected route %s", route) t.Errorf("unexpected route %s", route)
} }
@ -102,7 +102,7 @@ func TestRegisteredAPISurfaces(t *testing.T) {
role domain.Role role domain.Role
}{ }{
{"/api/v1/admin/users", domain.RoleStudent}, {"/api/v1/admin/users", domain.RoleStudent},
{"/api/v1/admin/exam-prep/catalog-courses", domain.RoleOpenLearner}, {"/api/v1/admin/courses", domain.RoleOpenLearner},
{"/api/v1/subscriptions/me", domain.RoleAdmin}, {"/api/v1/subscriptions/me", domain.RoleAdmin},
{"/api/v1/admin/ws/connect?token=", domain.RoleStudent}, {"/api/v1/admin/ws/connect?token=", domain.RoleStudent},
{"/api/v1/ws/connect?token=", domain.RoleAdmin}, {"/api/v1/ws/connect?token=", domain.RoleAdmin},

View File

@ -211,12 +211,12 @@ func (a *App) resolveExamPrepEffectiveAccessTier(c *fiber.Ctx) (domain.ContentAc
return a.examPrepEffectiveTierForLesson(ctx, input.ContentID) return a.examPrepEffectiveTierForLesson(ctx, input.ContentID)
} }
if id, ok, err := parseRouteInt64(c, "catalogCourseId"); err != nil { if id, ok, err := parseRouteInt64(c, "courseId"); err != nil {
return "", false, err return "", false, err
} else if ok { } else if ok {
return a.examPrepEffectiveTierForCatalogCourse(ctx, id) return a.examPrepEffectiveTierForCatalogCourse(ctx, id)
} }
if id, ok, err := parseRouteInt64(c, "unitId"); err != nil { if id, ok, err := parseRouteInt64(c, "chapterId"); err != nil {
return "", false, err return "", false, err
} else if ok { } else if ok {
return a.examPrepEffectiveTierForUnit(ctx, id) return a.examPrepEffectiveTierForUnit(ctx, id)
@ -239,13 +239,13 @@ func (a *App) resolveExamPrepEffectiveAccessTier(c *fiber.Ctx) (domain.ContentAc
} }
switch { switch {
case strings.Contains(routePath, "/catalog-courses/:id"): case strings.Contains(routePath, "/courses/:id"):
if id, ok, err := parseRouteInt64(c, "id"); err != nil { if id, ok, err := parseRouteInt64(c, "id"); err != nil {
return "", false, err return "", false, err
} else if ok { } else if ok {
return a.examPrepEffectiveTierForCatalogCourse(ctx, id) return a.examPrepEffectiveTierForCatalogCourse(ctx, id)
} }
case strings.Contains(routePath, "/units/:id"): case strings.Contains(routePath, "/chapters/:id"):
if id, ok, err := parseRouteInt64(c, "id"); err != nil { if id, ok, err := parseRouteInt64(c, "id"); err != nil {
return "", false, err return "", false, err
} else if ok { } else if ok {
@ -263,7 +263,7 @@ func (a *App) resolveExamPrepEffectiveAccessTier(c *fiber.Ctx) (domain.ContentAc
} else if ok { } else if ok {
return a.examPrepEffectiveTierForLesson(ctx, id) return a.examPrepEffectiveTierForLesson(ctx, id)
} }
case strings.Contains(routePath, "/practices/:id"): case (strings.Contains(routePath, "/practices/:id") || strings.Contains(routePath, "/quizzes/:id")):
if id, ok, err := parseRouteInt64(c, "id"); err != nil { if id, ok, err := parseRouteInt64(c, "id"); err != nil {
return "", false, err return "", false, err
} else if ok { } else if ok {

View File

@ -77,7 +77,7 @@ func (h *Handler) AdminGetUserSubscriptions(c *fiber.Ctx) error {
// AdminGetUserLearningActivityDetails godoc // AdminGetUserLearningActivityDetails godoc
// @Summary Get full learning activity for a user (admin) // @Summary Get full learning activity for a user (admin)
// @Description Returns the unified catalog-course learning tree, progress summary, and recent activity timeline // @Description Returns the unified catalog-course learning tree, progress summary, and recent activity timeline
// @Tags exam-prep // @Tags learning
// @Produce json // @Produce json
// @Param user_id path int true "Target user ID" // @Param user_id path int true "Target user ID"
// @Param limit query int false "Max recent-activity items (default 40, max 120)" // @Param limit query int false "Max recent-activity items (default 40, max 120)"
@ -246,6 +246,7 @@ func (h *Handler) buildExamPrepProgressSummary(ctx context.Context, role domain.
Name: units[j].Name, Name: units[j].Name,
Access: units[j].Access, Access: units[j].Access,
Modules: make([]domain.ExamPrepProgressSummaryModule, 0, len(modules)), Modules: make([]domain.ExamPrepProgressSummaryModule, 0, len(modules)),
Lessons: []domain.ExamPrepProgressSummaryLesson{},
} }
for k := range modules { for k := range modules {
@ -269,14 +270,16 @@ func (h *Handler) buildExamPrepProgressSummary(ctx context.Context, role domain.
return domain.ExamPrepProgressSummary{}, err return domain.ExamPrepProgressSummary{}, err
} }
moduleSummary.Lessons = append(moduleSummary.Lessons, domain.ExamPrepProgressSummaryLesson{ moduleSummary.Lessons = append(moduleSummary.Lessons, domain.ExamPrepProgressSummaryLesson{
ID: lessons[m].ID, ID: lessons[m].ID,
ModuleID: lessons[m].UnitModuleID, ModuleID: lessons[m].UnitModuleID,
Title: lessons[m].Title, ChapterID: units[j].ID,
Access: lessons[m].Access, Title: lessons[m].Title,
Access: lessons[m].Access,
}) })
} }
unitSummary.Modules = append(unitSummary.Modules, moduleSummary) unitSummary.Modules = append(unitSummary.Modules, moduleSummary)
unitSummary.Lessons = append(unitSummary.Lessons, moduleSummary.Lessons...)
} }
courseSummary.Units = append(courseSummary.Units, unitSummary) courseSummary.Units = append(courseSummary.Units, unitSummary)

View File

@ -0,0 +1,40 @@
package handlers
import (
"strconv"
"github.com/gofiber/fiber/v2"
)
// ResolveChapterLessonContainer adapts the legacy persistence layer to the
// public course -> chapter -> lesson hierarchy.
func (h *Handler) ResolveChapterLessonContainer(c *fiber.Ctx) error {
chapterID, err := parseAssessmentID(c.Params("chapterId"))
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, "Invalid chapter ID")
}
chapter, err := h.examPrepSvc.GetUnitByID(c.Context(), chapterID)
if err != nil {
return fiber.NewError(fiber.StatusNotFound, "Chapter not found")
}
course, err := h.examPrepSvc.GetCatalogCourseByID(c.Context(), chapter.CatalogCourseID)
if err != nil {
return fiber.NewError(fiber.StatusNotFound, "Course not found")
}
if !h.canManageExamPrepLessons(c) && (!chapter.VisibleToLearners() || !course.VisibleToLearners()) {
return fiber.NewError(fiber.StatusNotFound, "Chapter not found")
}
moduleID, err := h.examPrepSvc.GetChapterLessonContainer(c.Context(), chapterID)
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, "Failed to resolve chapter lessons")
}
c.Locals("chapter_lesson_module_id", moduleID)
return c.Next()
}
func chapterLessonModuleID(c *fiber.Ctx) (int64, error) {
if id, ok := c.Locals("chapter_lesson_module_id").(int64); ok {
return id, nil
}
return strconv.ParseInt(c.Params("moduleId"), 10, 64)
}

View File

@ -0,0 +1,135 @@
package handlers
import (
"errors"
"strconv"
"Rezina-Backend/internal/domain"
"Rezina-Backend/internal/services/examprep"
"github.com/gofiber/fiber/v2"
)
// CreateChapterQuiz godoc
// @Summary Create a chapter quiz
// @Description First create a question set with set_type QUIZ. The chapter URL determines placement; omit all parent fields. Defaults to DRAFT. Learners require both the quiz and its question set to be published.
// @Tags quizzes
// @Security Bearer
// @Accept json
// @Produce json
// @Param chapterId path int true "Chapter ID"
// @Param body body createChapterQuizRequest true "Quiz shell"
// @Success 201 {object} domain.Response{data=domain.ExamPrepPractice}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/chapters/{chapterId}/quizzes [post]
func (h *Handler) CreateChapterQuiz(c *fiber.Ctx) error {
chapterID, err := parseAssessmentID(c.Params("chapterId"))
if err != nil {
return fiber.NewError(400, "Invalid chapter ID")
}
var input domain.CreateExamPrepPracticeInput
if err = c.BodyParser(&input); err != nil {
return fiber.NewError(400, "Invalid request body")
}
if errs, ok := h.validator.Validate(c, input); !ok {
return fiber.NewError(400, firstValidationError(errs))
}
quiz, err := h.examPrepSvc.CreateChapterQuiz(c.Context(), chapterID, input)
if err != nil {
if errors.Is(err, examprep.ErrExamPrepQuizRequiresQuizSet) {
return fiber.NewError(400, err.Error())
}
switch {
case errors.Is(err, examprep.ErrInvalidExamPrepPracticeParent):
return fiber.NewError(400, err.Error())
case errors.Is(err, examprep.ErrUnitNotFound), errors.Is(err, examprep.ErrQuestionSetNotFound), errors.Is(err, domain.ErrPersonaNotFound):
return fiber.NewError(404, err.Error())
}
return fiber.NewError(500, "Failed to create quiz")
}
h.recordActivity(c, domain.ActionExamPrepPracticeCreated, domain.ResourceExamPrepPractice, &quiz.ID, "Created chapter quiz: "+quiz.Title, nil)
return c.Status(201).JSON(domain.Response{Message: "Quiz created successfully", Data: quiz, Success: true, StatusCode: 201})
}
// ListChapterQuizzes godoc
// @Summary List quizzes in a chapter
// @Description Returns quizzes and pagination. Admins see drafts; learners see published quizzes with published question sets in published chapters and courses.
// @Tags quizzes
// @Security Bearer
// @Produce json
// @Param chapterId path int true "Chapter ID"
// @Param limit query int false "Page size" default(20)
// @Param offset query int false "Offset" default(0)
// @Success 200 {object} domain.Response{data=quizListData}
// @Failure 401 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/chapters/{chapterId}/quizzes [get]
// @Router /api/v1/chapters/{chapterId}/quizzes [get]
func (h *Handler) ListChapterQuizzes(c *fiber.Ctx) error {
chapterID, err := parseAssessmentID(c.Params("chapterId"))
if err != nil {
return fiber.NewError(400, "Invalid chapter ID")
}
if err = h.visibleQuizChapter(c, chapterID); err != nil {
return err
}
limit, err := strconv.Atoi(c.Query("limit", "20"))
if err != nil || limit < 1 || limit > 200 {
return fiber.NewError(400, "limit must be between 1 and 200")
}
offset, err := strconv.Atoi(c.Query("offset", "0"))
if err != nil || offset < 0 {
return fiber.NewError(400, "offset must be non-negative")
}
items, total, err := h.examPrepSvc.ListChapterQuizzes(c.Context(), chapterID, !h.canManageExamPrepPractices(c), int32(limit), int32(offset))
if err != nil {
return fiber.NewError(500, "Failed to list quizzes")
}
return c.JSON(domain.Response{Message: "Quizzes retrieved successfully", Data: fiber.Map{"quizzes": items, "total_count": total, "limit": limit, "offset": offset}, Success: true, StatusCode: 200})
}
func (h *Handler) visibleQuizChapter(c *fiber.Ctx, chapterID int64) error {
chapter, err := h.examPrepSvc.GetUnitByID(c.Context(), chapterID)
if err != nil {
return fiber.NewError(404, "Chapter not found")
}
course, err := h.examPrepSvc.GetCatalogCourseByID(c.Context(), chapter.CatalogCourseID)
if err != nil {
return fiber.NewError(404, "Course not found")
}
if !h.canManageExamPrepPractices(c) && (!chapter.VisibleToLearners() || !course.VisibleToLearners()) {
return fiber.NewError(404, "Chapter not found")
}
return nil
}
// RequireChapterQuiz prevents practice IDs from being consumed via quiz routes.
func (h *Handler) RequireChapterQuiz(c *fiber.Ctx) error {
raw := c.Params("id", c.Params("practiceId"))
id, err := parseAssessmentID(raw)
if err != nil {
return fiber.NewError(400, "Invalid quiz ID")
}
quiz, err := h.examPrepSvc.GetExamPrepPracticeByID(c.Context(), id)
if err != nil {
return fiber.NewError(404, "Quiz not found")
}
set, err := h.questionsSvc.GetQuestionSetByID(c.Context(), quiz.QuestionSetID)
parents := domain.ExamPrepPracticeParentsDeref(quiz.Parents)
if err != nil || set.SetType != "QUIZ" || !examprep.ValidQuizParents(parents) {
return fiber.NewError(404, "Quiz not found")
}
if !h.canManageExamPrepPractices(c) && (!quiz.VisibleToLearners() || set.Status != "PUBLISHED") {
return fiber.NewError(404, "Quiz not found")
}
if err = h.visibleQuizChapter(c, parents[0].ID); err != nil {
return err
}
return c.Next()
}

View File

@ -0,0 +1,155 @@
package handlers
import (
"Rezina-Backend/internal/domain"
"github.com/gofiber/fiber/v2"
)
// GetChapterQuiz godoc
// @Summary Get a chapter quiz
// @Description Returns a quiz shell. Learners only see published quizzes with a published question set in a published chapter and course.
// @Tags quizzes
// @Security Bearer
// @Produce json
// @Param id path int true "Quiz shell ID"
// @Success 200 {object} domain.Response{data=domain.ExamPrepPractice}
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 401 {object} domain.ErrorResponse "Missing or invalid access token"
// @Failure 403 {object} domain.ErrorResponse "Permission, subscription, or sequence access denied"
// @Failure 404 {object} domain.ErrorResponse "Quiz or published parent not found"
// @Failure 500 {object} domain.ErrorResponse "Internal error"
// @Router /api/v1/admin/quizzes/{id} [get]
// @Router /api/v1/quizzes/{id} [get]
func (h *Handler) GetChapterQuiz(c *fiber.Ctx) error {
return h.GetExamPrepPracticeByID(c)
}
// GetChapterQuizFull godoc
// @Summary Get a chapter quiz with questions
// @Description Returns quiz metadata in practice, question_set settings, stimulus_blocks, and questions.
// @Tags quizzes
// @Security Bearer
// @Produce json
// @Param id path int true "Quiz shell ID"
// @Success 200 {object} domain.Response{data=quizFullData}
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 401 {object} domain.ErrorResponse "Missing or invalid access token"
// @Failure 403 {object} domain.ErrorResponse "Permission, subscription, or sequence access denied"
// @Failure 404 {object} domain.ErrorResponse "Quiz or published parent not found"
// @Failure 500 {object} domain.ErrorResponse "Internal error"
// @Router /api/v1/admin/quizzes/{id}/full [get]
func (h *Handler) GetChapterQuizFull(c *fiber.Ctx) error {
return h.GetExamPrepPracticeFull(c)
}
// UpdateChapterQuiz godoc
// @Summary Update a chapter quiz
// @Description Updates quiz metadata. A replacement question_set_id must refer to another QUIZ set. Chapter placement is immutable through this endpoint.
// @Tags quizzes
// @Security Bearer
// @Produce json
// @Param id path int true "Quiz shell ID"
// @Accept json
// @Param body body domain.UpdateExamPrepPracticeInput true "Quiz update"
// @Success 200 {object} domain.Response{data=domain.ExamPrepPractice}
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 401 {object} domain.ErrorResponse "Missing or invalid access token"
// @Failure 403 {object} domain.ErrorResponse "Permission, subscription, or sequence access denied"
// @Failure 404 {object} domain.ErrorResponse "Quiz or published parent not found"
// @Failure 500 {object} domain.ErrorResponse "Internal error"
// @Router /api/v1/admin/quizzes/{id} [put]
func (h *Handler) UpdateChapterQuiz(c *fiber.Ctx) error {
return h.UpdateExamPrepPractice(c)
}
// UpdateChapterQuizFull godoc
// @Summary Update a chapter quiz and its question set
// @Description Updates quiz metadata and question set settings. Omit questions to preserve memberships; an explicit empty array removes all memberships. Publish practice.publish_status and question_set.status together.
// @Tags quizzes
// @Security Bearer
// @Produce json
// @Param id path int true "Quiz shell ID"
// @Accept json
// @Param body body domain.FullUpdatePracticeInput true "Quiz update"
// @Success 200 {object} domain.Response{data=quizFullData}
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 401 {object} domain.ErrorResponse "Missing or invalid access token"
// @Failure 403 {object} domain.ErrorResponse "Permission, subscription, or sequence access denied"
// @Failure 404 {object} domain.ErrorResponse "Quiz or published parent not found"
// @Failure 500 {object} domain.ErrorResponse "Internal error"
// @Router /api/v1/admin/quizzes/{id}/full [put]
func (h *Handler) UpdateChapterQuizFull(c *fiber.Ctx) error {
var input domain.FullUpdatePracticeInput
if err := c.BodyParser(&input); err != nil {
return fiber.NewError(fiber.StatusBadRequest, "Invalid quiz update")
}
if input.Practice != nil && input.Practice.QuestionSetID != nil {
set, err := h.questionsSvc.GetQuestionSetByID(c.Context(), *input.Practice.QuestionSetID)
if err != nil {
return fiber.NewError(fiber.StatusNotFound, "Question set not found")
}
if set.SetType != "QUIZ" {
return fiber.NewError(fiber.StatusBadRequest, "Chapter quizzes require a QUIZ question set")
}
}
return h.UpdateExamPrepPracticeFull(c)
}
// DeleteChapterQuiz godoc
// @Summary Delete a chapter quiz
// @Description Deletes the quiz shell and chapter attachment. The question set and bank questions remain independently managed.
// @Tags quizzes
// @Security Bearer
// @Produce json
// @Param id path int true "Quiz shell ID"
// @Success 200 {object} domain.Response
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 401 {object} domain.ErrorResponse "Missing or invalid access token"
// @Failure 403 {object} domain.ErrorResponse "Permission, subscription, or sequence access denied"
// @Failure 404 {object} domain.ErrorResponse "Quiz or published parent not found"
// @Failure 500 {object} domain.ErrorResponse "Internal error"
// @Router /api/v1/admin/quizzes/{id} [delete]
func (h *Handler) DeleteChapterQuiz(c *fiber.Ctx) error {
return h.DeleteExamPrepPractice(c)
}
// GetChapterQuizQuestions godoc
// @Summary List questions in a chapter quiz
// @Description Learner endpoint. Requires a published quiz and question set, accessible chapter, subscription eligibility, and learning sequence access.
// @Tags quizzes
// @Security Bearer
// @Produce json
// @Param practiceId path int true "Quiz shell ID"
// @Param question_type query string false "Question type filter"
// @Param limit query int false "Page size (1-200)" default(10)
// @Param offset query int false "Non-negative offset" default(0)
// @Success 200 {object} domain.Response{data=paginatedQuestionSetItemsRes}
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 401 {object} domain.ErrorResponse "Missing or invalid access token"
// @Failure 403 {object} domain.ErrorResponse "Permission, subscription, or sequence access denied"
// @Failure 404 {object} domain.ErrorResponse "Quiz or published parent not found"
// @Failure 500 {object} domain.ErrorResponse "Internal error"
// @Router /api/v1/quizzes/{practiceId}/questions [get]
func (h *Handler) GetChapterQuizQuestions(c *fiber.Ctx) error {
return h.GetQuestionsByPractice(c)
}
// CompleteChapterQuiz godoc
// @Summary Complete a chapter quiz
// @Description The id is the quiz shell ID, not question_set_id. The single chapter scope is inferred; optional scope must use CHAPTER and that chapter ID. Records completion for the authenticated learner.
// @Tags quizzes
// @Security Bearer
// @Produce json
// @Param id path int true "Quiz shell ID"
// @Accept json
// @Param body body domain.CompletePracticeInput false "Optional chapter scope"
// @Success 200 {object} domain.Response
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 401 {object} domain.ErrorResponse "Missing or invalid access token"
// @Failure 403 {object} domain.ErrorResponse "Permission, subscription, or sequence access denied"
// @Failure 404 {object} domain.ErrorResponse "Quiz or published parent not found"
// @Failure 500 {object} domain.ErrorResponse "Internal error"
// @Router /api/v1/progress/quizzes/{id}/complete [post]
func (h *Handler) CompleteChapterQuiz(c *fiber.Ctx) error {
return h.CompletePractice(c)
}

View File

@ -0,0 +1,54 @@
package handlers
import (
"context"
"net/http/httptest"
"strings"
"testing"
"Rezina-Backend/internal/domain"
"Rezina-Backend/internal/ports"
"Rezina-Backend/internal/services/questions"
"github.com/gofiber/fiber/v2"
"github.com/jackc/pgx/v5"
)
type quizReplacementStore struct {
ports.QuestionStore
setType string
}
func (s quizReplacementStore) GetQuestionSetByID(context.Context, int64) (domain.QuestionSet, error) {
if s.setType == "" {
return domain.QuestionSet{}, pgx.ErrNoRows
}
return domain.QuestionSet{ID: 12, SetType: s.setType}, nil
}
func TestQuizFullUpdateRejectsInvalidReplacementBeforeWriting(t *testing.T) {
for _, tc := range []struct {
name, body, setType string
want int
}{
{"malformed request", `{`, "QUIZ", 400},
{"practice set", `{"practice":{"question_set_id":12}}`, "PRACTICE", 400},
{"exam set", `{"practice":{"question_set_id":12}}`, "EXAM", 400},
{"missing set", `{"practice":{"question_set_id":12}}`, "", 404},
} {
t.Run(tc.name, func(t *testing.T) {
h := &Handler{questionsSvc: questions.NewService(quizReplacementStore{setType: tc.setType})}
app := fiber.New()
app.Put("/quizzes/:id/full", h.UpdateChapterQuizFull)
request := httptest.NewRequest("PUT", "/quizzes/9/full", strings.NewReader(tc.body))
request.Header.Set("Content-Type", "application/json")
response, err := app.Test(request)
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
if response.StatusCode != tc.want {
t.Fatalf("status=%d want=%d", response.StatusCode, tc.want)
}
})
}
}

View File

@ -22,9 +22,9 @@ func assessmentParentFromQuery(c *fiber.Ctx) (domain.ExamPrepAssessmentParent, e
// ListExamPrepAssessments godoc // ListExamPrepAssessments godoc
// @Summary List Exam Prep Assessments // @Summary List Exam Prep Assessments
// @Tags exam-prep // @Tags learning
// @Router /api/v1/admin/exam-prep/assessments [get] // @Router /api/v1/admin/assessments [get]
// @Router /api/v1/exam-prep/assessments [get] // @Router /api/v1/assessments [get]
// @Security Bearer // @Security Bearer
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Produce json // @Produce json
@ -45,8 +45,8 @@ func (h *Handler) ListExamPrepAssessments(c *fiber.Ctx) error {
// LinkExamPrepAssessment godoc // LinkExamPrepAssessment godoc
// @Summary Link Exam Prep Assessment // @Summary Link Exam Prep Assessment
// @Tags exam-prep // @Tags learning
// @Router /api/v1/admin/exam-prep/assessments [post] // @Router /api/v1/admin/assessments [post]
// @Security Bearer // @Security Bearer
// @Accept json // @Accept json
// @Param body body domain.LinkExamPrepAssessmentInput true "Request payload" // @Param body body domain.LinkExamPrepAssessmentInput true "Request payload"
@ -73,8 +73,8 @@ func (h *Handler) LinkExamPrepAssessment(c *fiber.Ctx) error {
// UnlinkExamPrepAssessment godoc // UnlinkExamPrepAssessment godoc
// @Summary Unlink Exam Prep Assessment // @Summary Unlink Exam Prep Assessment
// @Tags exam-prep // @Tags learning
// @Router /api/v1/admin/exam-prep/assessments/{questionSetId}/parents/{parentKind}/{parentId} [delete] // @Router /api/v1/admin/assessments/{questionSetId}/parents/{parentKind}/{parentId} [delete]
// @Security Bearer // @Security Bearer
// @Param parentId path int64 true "Parent id" // @Param parentId path int64 true "Parent id"
// @Param parentKind path string true "Parent kind" // @Param parentKind path string true "Parent kind"

View File

@ -11,15 +11,15 @@ import (
) )
// CreateExamPrepCatalogCourse godoc // CreateExamPrepCatalogCourse godoc
// @Summary Create exam-prep catalog course // @Summary Create course
// @Description Top-level exam track (DET, IELTS, …) in schema exam_prep — separate from LMS programs/courses // @Description Top-level exam track (DET, IELTS, …) in schema exam_prep — separate from LMS programs/courses
// @Tags exam-prep // @Tags learning
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param body body domain.CreateExamPrepCatalogCourseInput true "Catalog course" // @Param body body domain.CreateExamPrepCatalogCourseInput true "Course"
// @Success 201 {object} domain.Response // @Success 201 {object} domain.Response{data=domain.ExamPrepCatalogCourse}
// @Failure 400 {object} domain.ErrorResponse // @Failure 400 {object} domain.ErrorResponse
// @Router /api/v1/admin/exam-prep/catalog-courses [post] // @Router /api/v1/admin/courses [post]
// @Security Bearer // @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
@ -41,13 +41,13 @@ func (h *Handler) CreateExamPrepCatalogCourse(c *fiber.Ctx) error {
out, err := h.examPrepSvc.CreateCatalogCourse(c.Context(), req) out, err := h.examPrepSvc.CreateCatalogCourse(c.Context(), req)
if err != nil { if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to create catalog course", Message: "Failed to create course",
Error: err.Error(), Error: err.Error(),
}) })
} }
h.recordActivity(c, domain.ActionExamPrepCatalogCourseCreated, domain.ResourceExamPrepCatalogCourse, &out.ID, "Created exam prep catalog course: "+out.Name, nil) h.recordActivity(c, domain.ActionExamPrepCatalogCourseCreated, domain.ResourceExamPrepCatalogCourse, &out.ID, "Created course: "+out.Name, nil)
return c.Status(fiber.StatusCreated).JSON(domain.Response{ return c.Status(fiber.StatusCreated).JSON(domain.Response{
Message: "Catalog course created successfully", Message: "Course created successfully",
Data: out, Data: out,
Success: true, Success: true,
StatusCode: fiber.StatusCreated, StatusCode: fiber.StatusCreated,
@ -55,14 +55,14 @@ func (h *Handler) CreateExamPrepCatalogCourse(c *fiber.Ctx) error {
} }
// ListExamPrepCatalogCourses godoc // ListExamPrepCatalogCourses godoc
// @Summary List exam-prep catalog courses // @Summary List courses
// @Tags exam-prep // @Tags learning
// @Produce json // @Produce json
// @Param limit query int false "Page size" default(20) // @Param limit query int false "Page size" default(20)
// @Param offset query int false "Offset" default(0) // @Param offset query int false "Offset" default(0)
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response{data=courseListData}
// @Router /api/v1/admin/exam-prep/catalog-courses [get] // @Router /api/v1/admin/courses [get]
// @Router /api/v1/exam-prep/catalog-courses [get] // @Router /api/v1/courses [get]
// @Security Bearer // @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
@ -75,24 +75,24 @@ func (h *Handler) ListExamPrepCatalogCourses(c *fiber.Ctx) error {
items, total, err := h.examPrepSvc.ListCatalogCourses(c.Context(), publishedOnly, int32(limit), int32(offset)) items, total, err := h.examPrepSvc.ListCatalogCourses(c.Context(), publishedOnly, int32(limit), int32(offset))
if err != nil { if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to list catalog courses", Message: "Failed to list courses",
Error: err.Error(), Error: err.Error(),
}) })
} }
annotateExamPrepCatalogCoursesEffectiveAccessTier(c.Locals("role").(domain.Role), items) annotateExamPrepCatalogCoursesEffectiveAccessTier(c.Locals("role").(domain.Role), items)
if err := h.applyExamPrepAccessCatalogCourses(c.Context(), c, items); err != nil { if err := h.applyExamPrepAccessCatalogCourses(c.Context(), c, items); err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to build catalog course list", Message: "Failed to build course list",
Error: err.Error(), Error: err.Error(),
}) })
} }
return c.JSON(domain.Response{ return c.JSON(domain.Response{
Message: "Catalog courses retrieved successfully", Message: "Courses retrieved successfully",
Data: fiber.Map{ Data: fiber.Map{
"catalog_courses": items, "courses": items,
"total_count": total, "total_count": total,
"limit": limit, "limit": limit,
"offset": offset, "offset": offset,
}, },
Success: true, Success: true,
StatusCode: fiber.StatusOK, StatusCode: fiber.StatusOK,
@ -100,13 +100,13 @@ func (h *Handler) ListExamPrepCatalogCourses(c *fiber.Ctx) error {
} }
// ReorderExamPrepCatalogCourses godoc // ReorderExamPrepCatalogCourses godoc
// @Summary Reorder all exam-prep catalog courses // @Summary Reorder all courses
// @Tags exam-prep // @Tags learning
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param body body domain.ReorderIDsRequest true "ordered_ids: every catalog course id exactly once" // @Param body body domain.ReorderIDsRequest true "ordered_ids: every course id exactly once"
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Router /api/v1/admin/exam-prep/catalog-courses/reorder [put] // @Router /api/v1/admin/courses/reorder [put]
// @Security Bearer // @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
@ -122,7 +122,7 @@ func (h *Handler) ReorderExamPrepCatalogCourses(c *fiber.Ctx) error {
} }
if req.OrderedIDs == nil { if req.OrderedIDs == nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "ordered_ids is required (use an empty array if there are no catalog courses)", Message: "ordered_ids is required (use an empty array if there are no courses)",
Error: "missing ordered_ids", Error: "missing ordered_ids",
}) })
} }
@ -134,11 +134,11 @@ func (h *Handler) ReorderExamPrepCatalogCourses(c *fiber.Ctx) error {
}) })
} }
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to reorder catalog courses", Message: "Failed to reorder courses",
Error: err.Error(), Error: err.Error(),
}) })
} }
h.recordActivity(c, domain.ActionExamPrepCatalogCourseReordered, domain.ResourceExamPrepCatalogCourse, nil, "Reordered exam prep catalog courses", nil) h.recordActivity(c, domain.ActionExamPrepCatalogCourseReordered, domain.ResourceExamPrepCatalogCourse, nil, "Reordered courses", nil)
return c.JSON(domain.Response{ return c.JSON(domain.Response{
Success: true, Success: true,
StatusCode: fiber.StatusOK, StatusCode: fiber.StatusOK,
@ -146,13 +146,13 @@ func (h *Handler) ReorderExamPrepCatalogCourses(c *fiber.Ctx) error {
} }
// GetExamPrepCatalogCourseByID godoc // GetExamPrepCatalogCourseByID godoc
// @Summary Get exam-prep catalog course by ID // @Summary Get course by ID
// @Tags exam-prep // @Tags learning
// @Produce json // @Produce json
// @Param id path int true "Catalog course ID" // @Param id path int true "Course ID"
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response{data=domain.ExamPrepCatalogCourse}
// @Router /api/v1/admin/exam-prep/catalog-courses/{id} [get] // @Router /api/v1/admin/courses/{id} [get]
// @Router /api/v1/exam-prep/catalog-courses/{id} [get] // @Router /api/v1/courses/{id} [get]
// @Security Bearer // @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
@ -163,7 +163,7 @@ func (h *Handler) GetExamPrepCatalogCourseByID(c *fiber.Ctx) error {
id, err := strconv.ParseInt(c.Params("id"), 10, 64) id, err := strconv.ParseInt(c.Params("id"), 10, 64)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid catalog course id", Message: "Invalid course id",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -171,30 +171,30 @@ func (h *Handler) GetExamPrepCatalogCourseByID(c *fiber.Ctx) error {
if err != nil { if err != nil {
if errors.Is(err, examprep.ErrCatalogCourseNotFound) { if errors.Is(err, examprep.ErrCatalogCourseNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Catalog course not found", Message: "Course not found",
Error: err.Error(), Error: err.Error(),
}) })
} }
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to get catalog course", Message: "Failed to get course",
Error: err.Error(), Error: err.Error(),
}) })
} }
if !out.VisibleToLearners() && !h.canManageExamPrepCatalogCourses(c) { if !out.VisibleToLearners() && !h.canManageExamPrepCatalogCourses(c) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Catalog course not found", Message: "Course not found",
Error: examprep.ErrCatalogCourseNotFound.Error(), Error: examprep.ErrCatalogCourseNotFound.Error(),
}) })
} }
applyExamPrepCatalogCourseEffectiveAccessTier(&out, c.Locals("role").(domain.Role)) applyExamPrepCatalogCourseEffectiveAccessTier(&out, c.Locals("role").(domain.Role))
if err := h.applyExamPrepAccessCatalogCourse(c.Context(), c, &out); err != nil { if err := h.applyExamPrepAccessCatalogCourse(c.Context(), c, &out); err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to build catalog course", Message: "Failed to build course",
Error: err.Error(), Error: err.Error(),
}) })
} }
return c.JSON(domain.Response{ return c.JSON(domain.Response{
Message: "Catalog course retrieved successfully", Message: "Course retrieved successfully",
Data: out, Data: out,
Success: true, Success: true,
StatusCode: fiber.StatusOK, StatusCode: fiber.StatusOK,
@ -202,14 +202,14 @@ func (h *Handler) GetExamPrepCatalogCourseByID(c *fiber.Ctx) error {
} }
// UpdateExamPrepCatalogCourse godoc // UpdateExamPrepCatalogCourse godoc
// @Summary Update exam-prep catalog course // @Summary Update course
// @Tags exam-prep // @Tags learning
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param id path int true "Catalog course ID" // @Param id path int true "Course ID"
// @Param body body domain.UpdateExamPrepCatalogCourseInput true "Fields to update" // @Param body body domain.UpdateExamPrepCatalogCourseInput true "Fields to update"
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response{data=domain.ExamPrepCatalogCourse}
// @Router /api/v1/admin/exam-prep/catalog-courses/{id} [put] // @Router /api/v1/admin/courses/{id} [put]
// @Security Bearer // @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
@ -220,7 +220,7 @@ func (h *Handler) UpdateExamPrepCatalogCourse(c *fiber.Ctx) error {
id, err := strconv.ParseInt(c.Params("id"), 10, 64) id, err := strconv.ParseInt(c.Params("id"), 10, 64)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid catalog course id", Message: "Invalid course id",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -235,18 +235,18 @@ func (h *Handler) UpdateExamPrepCatalogCourse(c *fiber.Ctx) error {
if err != nil { if err != nil {
if errors.Is(err, examprep.ErrCatalogCourseNotFound) { if errors.Is(err, examprep.ErrCatalogCourseNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Catalog course not found", Message: "Course not found",
Error: err.Error(), Error: err.Error(),
}) })
} }
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to update catalog course", Message: "Failed to update course",
Error: err.Error(), Error: err.Error(),
}) })
} }
h.recordActivity(c, domain.ActionExamPrepCatalogCourseUpdated, domain.ResourceExamPrepCatalogCourse, &out.ID, "Updated exam prep catalog course: "+out.Name, nil) h.recordActivity(c, domain.ActionExamPrepCatalogCourseUpdated, domain.ResourceExamPrepCatalogCourse, &out.ID, "Updated course: "+out.Name, nil)
return c.JSON(domain.Response{ return c.JSON(domain.Response{
Message: "Catalog course updated successfully", Message: "Course updated successfully",
Data: out, Data: out,
Success: true, Success: true,
StatusCode: fiber.StatusOK, StatusCode: fiber.StatusOK,
@ -254,11 +254,11 @@ func (h *Handler) UpdateExamPrepCatalogCourse(c *fiber.Ctx) error {
} }
// DeleteExamPrepCatalogCourse godoc // DeleteExamPrepCatalogCourse godoc
// @Summary Delete exam-prep catalog course // @Summary Delete course
// @Tags exam-prep // @Tags learning
// @Param id path int true "Catalog course ID" // @Param id path int true "Course ID"
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Router /api/v1/admin/exam-prep/catalog-courses/{id} [delete] // @Router /api/v1/admin/courses/{id} [delete]
// @Security Bearer // @Security Bearer
// @Produce json // @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
@ -270,25 +270,25 @@ func (h *Handler) DeleteExamPrepCatalogCourse(c *fiber.Ctx) error {
id, err := strconv.ParseInt(c.Params("id"), 10, 64) id, err := strconv.ParseInt(c.Params("id"), 10, 64)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid catalog course id", Message: "Invalid course id",
Error: err.Error(), Error: err.Error(),
}) })
} }
if err := h.examPrepSvc.DeleteCatalogCourse(c.Context(), id); err != nil { if err := h.examPrepSvc.DeleteCatalogCourse(c.Context(), id); err != nil {
if errors.Is(err, examprep.ErrCatalogCourseNotFound) { if errors.Is(err, examprep.ErrCatalogCourseNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Catalog course not found", Message: "Course not found",
Error: err.Error(), Error: err.Error(),
}) })
} }
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to delete catalog course", Message: "Failed to delete course",
Error: err.Error(), Error: err.Error(),
}) })
} }
h.recordActivity(c, domain.ActionExamPrepCatalogCourseDeleted, domain.ResourceExamPrepCatalogCourse, &id, fmt.Sprintf("Deleted exam prep catalog course ID: %d", id), nil) h.recordActivity(c, domain.ActionExamPrepCatalogCourseDeleted, domain.ResourceExamPrepCatalogCourse, &id, fmt.Sprintf("Deleted course ID: %d", id), nil)
return c.JSON(domain.Response{ return c.JSON(domain.Response{
Message: "Catalog course deleted successfully", Message: "Course deleted successfully",
Success: true, Success: true,
StatusCode: fiber.StatusOK, StatusCode: fiber.StatusOK,
}) })

View File

@ -11,13 +11,13 @@ import (
) )
// CreateExamPrepLesson godoc // CreateExamPrepLesson godoc
// @Summary Create exam-prep lesson (under a unit module) // @Summary Create a lesson in a chapter
// @Tags exam-prep // @Tags learning
// @Param moduleId path int true "Exam prep unit module ID" // @Param chapterId path int true "Chapter ID"
// @Param body body domain.CreateExamPrepLessonInput true "Lesson" // @Param body body domain.CreateExamPrepLessonInput true "Lesson"
// @Router /api/v1/admin/exam-prep/modules/{moduleId}/lessons [post] // @Router /api/v1/admin/chapters/{chapterId}/lessons [post]
// @Security Bearer // @Security Bearer
// @Success 201 {object} domain.Response // @Success 201 {object} domain.Response{data=domain.ExamPrepLesson}
// @Produce json // @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
@ -25,10 +25,10 @@ import (
// @Failure 404 {object} domain.ErrorResponse "Resource not found" // @Failure 404 {object} domain.ErrorResponse "Resource not found"
// @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) CreateExamPrepLesson(c *fiber.Ctx) error { func (h *Handler) CreateExamPrepLesson(c *fiber.Ctx) error {
moduleID, err := strconv.ParseInt(c.Params("moduleId"), 10, 64) moduleID, err := chapterLessonModuleID(c)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid module id", Message: "Invalid chapter id",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -49,7 +49,7 @@ func (h *Handler) CreateExamPrepLesson(c *fiber.Ctx) error {
if err != nil { if err != nil {
if errors.Is(err, examprep.ErrModuleNotFound) { if errors.Is(err, examprep.ErrModuleNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Module not found", Message: "Chapter not found",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -58,7 +58,7 @@ func (h *Handler) CreateExamPrepLesson(c *fiber.Ctx) error {
Error: err.Error(), Error: err.Error(),
}) })
} }
h.recordActivity(c, domain.ActionExamPrepLessonCreated, domain.ResourceExamPrepLesson, &les.ID, "Created exam prep lesson: "+les.Title, nil) h.recordActivity(c, domain.ActionExamPrepLessonCreated, domain.ResourceExamPrepLesson, &les.ID, "Created lesson: "+les.Title, nil)
return c.Status(fiber.StatusCreated).JSON(domain.Response{ return c.Status(fiber.StatusCreated).JSON(domain.Response{
Message: "Lesson created successfully", Message: "Lesson created successfully",
Data: les, Data: les,
@ -68,15 +68,15 @@ func (h *Handler) CreateExamPrepLesson(c *fiber.Ctx) error {
} }
// ListExamPrepLessonsByUnitModule godoc // ListExamPrepLessonsByUnitModule godoc
// @Summary List exam-prep lessons for a unit module // @Summary List lessons for a chapter
// @Tags exam-prep // @Tags learning
// @Param moduleId path int true "Exam prep unit module ID" // @Param chapterId path int true "Chapter ID"
// @Param limit query int false "Page size" default(20) // @Param limit query int false "Page size" default(20)
// @Param offset query int false "Offset" default(0) // @Param offset query int false "Offset" default(0)
// @Router /api/v1/admin/exam-prep/modules/{moduleId}/lessons [get] // @Router /api/v1/admin/chapters/{chapterId}/lessons [get]
// @Router /api/v1/exam-prep/modules/{moduleId}/lessons [get] // @Router /api/v1/chapters/{chapterId}/lessons [get]
// @Security Bearer // @Security Bearer
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response{data=lessonListData}
// @Produce json // @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
@ -84,10 +84,10 @@ func (h *Handler) CreateExamPrepLesson(c *fiber.Ctx) error {
// @Failure 404 {object} domain.ErrorResponse "Resource not found" // @Failure 404 {object} domain.ErrorResponse "Resource not found"
// @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) ListExamPrepLessonsByUnitModule(c *fiber.Ctx) error { func (h *Handler) ListExamPrepLessonsByUnitModule(c *fiber.Ctx) error {
moduleID, err := strconv.ParseInt(c.Params("moduleId"), 10, 64) moduleID, err := chapterLessonModuleID(c)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid module id", Message: "Invalid chapter id",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -99,7 +99,7 @@ func (h *Handler) ListExamPrepLessonsByUnitModule(c *fiber.Ctx) error {
m, err := h.examPrepSvc.GetModuleByID(c.Context(), moduleID) m, err := h.examPrepSvc.GetModuleByID(c.Context(), moduleID)
if err == nil && !m.VisibleToLearners() { if err == nil && !m.VisibleToLearners() {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Module not found", Message: "Chapter not found",
Error: examprep.ErrModuleNotFound.Error(), Error: examprep.ErrModuleNotFound.Error(),
}) })
} }
@ -108,7 +108,7 @@ func (h *Handler) ListExamPrepLessonsByUnitModule(c *fiber.Ctx) error {
if err != nil { if err != nil {
if errors.Is(err, examprep.ErrModuleNotFound) { if errors.Is(err, examprep.ErrModuleNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Module not found", Message: "Chapter not found",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -142,11 +142,11 @@ func (h *Handler) ListExamPrepLessonsByUnitModule(c *fiber.Ctx) error {
} }
// ReorderExamPrepLessonsInUnitModule godoc // ReorderExamPrepLessonsInUnitModule godoc
// @Summary Reorder lessons within an exam-prep unit module // @Summary Reorder lessons within a chapter
// @Tags exam-prep // @Tags learning
// @Router /api/v1/admin/exam-prep/modules/{moduleId}/lessons/reorder [put] // @Router /api/v1/admin/chapters/{chapterId}/lessons/reorder [put]
// @Security Bearer // @Security Bearer
// @Param moduleId path int64 true "Module id" // @Param chapterId path int64 true "Chapter id"
// @Accept json // @Accept json
// @Param body body domain.ReorderIDsRequest true "Request payload" // @Param body body domain.ReorderIDsRequest true "Request payload"
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
@ -157,10 +157,10 @@ func (h *Handler) ListExamPrepLessonsByUnitModule(c *fiber.Ctx) error {
// @Failure 404 {object} domain.ErrorResponse "Resource not found" // @Failure 404 {object} domain.ErrorResponse "Resource not found"
// @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) ReorderExamPrepLessonsInUnitModule(c *fiber.Ctx) error { func (h *Handler) ReorderExamPrepLessonsInUnitModule(c *fiber.Ctx) error {
moduleID, err := strconv.ParseInt(c.Params("moduleId"), 10, 64) moduleID, err := chapterLessonModuleID(c)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid module id", Message: "Invalid chapter id",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -180,7 +180,7 @@ func (h *Handler) ReorderExamPrepLessonsInUnitModule(c *fiber.Ctx) error {
if err := h.examPrepSvc.ReorderLessonsInUnitModule(c.Context(), moduleID, req.OrderedIDs); err != nil { if err := h.examPrepSvc.ReorderLessonsInUnitModule(c.Context(), moduleID, req.OrderedIDs); err != nil {
if errors.Is(err, examprep.ErrModuleNotFound) { if errors.Is(err, examprep.ErrModuleNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Module not found", Message: "Chapter not found",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -204,13 +204,13 @@ func (h *Handler) ReorderExamPrepLessonsInUnitModule(c *fiber.Ctx) error {
} }
// GetExamPrepLessonByID godoc // GetExamPrepLessonByID godoc
// @Summary Get exam-prep lesson by ID // @Summary Get lesson by ID
// @Tags exam-prep // @Tags learning
// @Router /api/v1/admin/exam-prep/lessons/{id} [get] // @Router /api/v1/admin/lessons/{id} [get]
// @Router /api/v1/exam-prep/lessons/{id} [get] // @Router /api/v1/lessons/{id} [get]
// @Security Bearer // @Security Bearer
// @Param id path int64 true "Id" // @Param id path int64 true "Id"
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response{data=domain.ExamPrepLesson}
// @Produce json // @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
@ -264,14 +264,14 @@ func (h *Handler) GetExamPrepLessonByID(c *fiber.Ctx) error {
} }
// UpdateExamPrepLesson godoc // UpdateExamPrepLesson godoc
// @Summary Update exam-prep lesson // @Summary Update lesson
// @Tags exam-prep // @Tags learning
// @Router /api/v1/admin/exam-prep/lessons/{id} [put] // @Router /api/v1/admin/lessons/{id} [put]
// @Security Bearer // @Security Bearer
// @Param id path int64 true "Id" // @Param id path int64 true "Id"
// @Accept json // @Accept json
// @Param body body domain.UpdateExamPrepLessonInput true "Request payload" // @Param body body domain.UpdateExamPrepLessonInput true "Request payload"
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response{data=domain.ExamPrepLesson}
// @Produce json // @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
@ -316,9 +316,9 @@ func (h *Handler) UpdateExamPrepLesson(c *fiber.Ctx) error {
} }
// DeleteExamPrepLesson godoc // DeleteExamPrepLesson godoc
// @Summary Delete exam-prep lesson // @Summary Delete lesson
// @Tags exam-prep // @Tags learning
// @Router /api/v1/admin/exam-prep/lessons/{id} [delete] // @Router /api/v1/admin/lessons/{id} [delete]
// @Security Bearer // @Security Bearer
// @Param id path int64 true "Id" // @Param id path int64 true "Id"
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response

View File

@ -12,10 +12,9 @@ import (
// CreateExamPrepModule godoc // CreateExamPrepModule godoc
// @Summary Create exam-prep module // @Summary Create exam-prep module
// @Tags exam-prep // @Tags learning
// @Param unitId path int true "Unit ID" // @Param unitId path int true "Chapter ID"
// @Param body body domain.CreateExamPrepModuleInput true "Module" // @Param body body domain.CreateExamPrepModuleInput true "Module"
// @Router /api/v1/admin/exam-prep/units/{unitId}/modules [post]
// @Security Bearer // @Security Bearer
// @Success 201 {object} domain.Response // @Success 201 {object} domain.Response
// @Produce json // @Produce json
@ -28,7 +27,7 @@ func (h *Handler) CreateExamPrepModule(c *fiber.Ctx) error {
unitID, err := strconv.ParseInt(c.Params("unitId"), 10, 64) unitID, err := strconv.ParseInt(c.Params("unitId"), 10, 64)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid unit id", Message: "Invalid chapter id",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -49,7 +48,7 @@ func (h *Handler) CreateExamPrepModule(c *fiber.Ctx) error {
if err != nil { if err != nil {
if errors.Is(err, examprep.ErrUnitNotFound) { if errors.Is(err, examprep.ErrUnitNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Unit not found", Message: "Chapter not found",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -69,10 +68,8 @@ func (h *Handler) CreateExamPrepModule(c *fiber.Ctx) error {
// ListExamPrepModulesByUnit godoc // ListExamPrepModulesByUnit godoc
// @Summary List exam-prep modules for a unit // @Summary List exam-prep modules for a unit
// @Tags exam-prep // @Tags learning
// @Param unitId path int true "Unit ID" // @Param unitId path int true "Chapter ID"
// @Router /api/v1/admin/exam-prep/units/{unitId}/modules [get]
// @Router /api/v1/exam-prep/units/{unitId}/modules [get]
// @Security Bearer // @Security Bearer
// @Param limit query int false "Limit" default(20) // @Param limit query int false "Limit" default(20)
// @Param offset query int false "Offset" default(0) minimum(0) // @Param offset query int false "Offset" default(0) minimum(0)
@ -87,7 +84,7 @@ func (h *Handler) ListExamPrepModulesByUnit(c *fiber.Ctx) error {
unitID, err := strconv.ParseInt(c.Params("unitId"), 10, 64) unitID, err := strconv.ParseInt(c.Params("unitId"), 10, 64)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid unit id", Message: "Invalid chapter id",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -99,7 +96,7 @@ func (h *Handler) ListExamPrepModulesByUnit(c *fiber.Ctx) error {
u, err := h.examPrepSvc.GetUnitByID(c.Context(), unitID) u, err := h.examPrepSvc.GetUnitByID(c.Context(), unitID)
if err == nil && !u.VisibleToLearners() { if err == nil && !u.VisibleToLearners() {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Unit not found", Message: "Chapter not found",
Error: examprep.ErrUnitNotFound.Error(), Error: examprep.ErrUnitNotFound.Error(),
}) })
} }
@ -108,7 +105,7 @@ func (h *Handler) ListExamPrepModulesByUnit(c *fiber.Ctx) error {
if err != nil { if err != nil {
if errors.Is(err, examprep.ErrUnitNotFound) { if errors.Is(err, examprep.ErrUnitNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Unit not found", Message: "Chapter not found",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -143,10 +140,9 @@ func (h *Handler) ListExamPrepModulesByUnit(c *fiber.Ctx) error {
// ReorderExamPrepModulesInUnit godoc // ReorderExamPrepModulesInUnit godoc
// @Summary Reorder modules within a unit // @Summary Reorder modules within a unit
// @Tags exam-prep // @Tags learning
// @Param unitId path int true "Unit ID" // @Param unitId path int true "Chapter ID"
// @Param body body domain.ReorderIDsRequest true "ordered_ids" // @Param body body domain.ReorderIDsRequest true "ordered_ids"
// @Router /api/v1/admin/exam-prep/units/{unitId}/modules/reorder [put]
// @Security Bearer // @Security Bearer
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Produce json // @Produce json
@ -159,7 +155,7 @@ func (h *Handler) ReorderExamPrepModulesInUnit(c *fiber.Ctx) error {
unitID, err := strconv.ParseInt(c.Params("unitId"), 10, 64) unitID, err := strconv.ParseInt(c.Params("unitId"), 10, 64)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid unit id", Message: "Invalid chapter id",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -179,7 +175,7 @@ func (h *Handler) ReorderExamPrepModulesInUnit(c *fiber.Ctx) error {
if err := h.examPrepSvc.ReorderModulesInUnit(c.Context(), unitID, req.OrderedIDs); err != nil { if err := h.examPrepSvc.ReorderModulesInUnit(c.Context(), unitID, req.OrderedIDs); err != nil {
if errors.Is(err, examprep.ErrUnitNotFound) { if errors.Is(err, examprep.ErrUnitNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Unit not found", Message: "Chapter not found",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -204,9 +200,7 @@ func (h *Handler) ReorderExamPrepModulesInUnit(c *fiber.Ctx) error {
// GetExamPrepModuleByID godoc // GetExamPrepModuleByID godoc
// @Summary Get exam-prep module by ID // @Summary Get exam-prep module by ID
// @Tags exam-prep // @Tags learning
// @Router /api/v1/admin/exam-prep/modules/{id} [get]
// @Router /api/v1/exam-prep/modules/{id} [get]
// @Security Bearer // @Security Bearer
// @Param id path int64 true "Id" // @Param id path int64 true "Id"
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
@ -264,8 +258,7 @@ func (h *Handler) GetExamPrepModuleByID(c *fiber.Ctx) error {
// UpdateExamPrepModule godoc // UpdateExamPrepModule godoc
// @Summary Update exam-prep module // @Summary Update exam-prep module
// @Tags exam-prep // @Tags learning
// @Router /api/v1/admin/exam-prep/modules/{id} [put]
// @Security Bearer // @Security Bearer
// @Param id path int64 true "Id" // @Param id path int64 true "Id"
// @Accept json // @Accept json
@ -316,8 +309,7 @@ func (h *Handler) UpdateExamPrepModule(c *fiber.Ctx) error {
// DeleteExamPrepModule godoc // DeleteExamPrepModule godoc
// @Summary Delete exam-prep module // @Summary Delete exam-prep module
// @Tags exam-prep // @Tags learning
// @Router /api/v1/admin/exam-prep/modules/{id} [delete]
// @Security Bearer // @Security Bearer
// @Param id path int64 true "Id" // @Param id path int64 true "Id"
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response

View File

@ -11,10 +11,10 @@ import (
) )
// CreateExamPrepPracticeFromInput godoc // CreateExamPrepPracticeFromInput godoc
// @Summary Create exam-prep practice (optional parents; link later via PUT /exam-prep/practices/:id/parents) // @Summary Create practice (optional parents; link later via PUT /practices/:id/parents)
// @Tags exam-prep // @Tags learning
// @Param body body domain.CreateExamPrepPracticeInput true "Practice" // @Param body body domain.CreateExamPrepPracticeInput true "Practice"
// @Router /api/v1/admin/exam-prep/practices [post] // @Router /api/v1/admin/practices [post]
// @Security Bearer // @Security Bearer
// @Success 201 {object} domain.Response // @Success 201 {object} domain.Response
// @Produce json // @Produce json
@ -56,13 +56,13 @@ func (h *Handler) CreateExamPrepPracticeFromInput(c *fiber.Ctx) error {
} }
// ListAllExamPrepPractices godoc // ListAllExamPrepPractices godoc
// @Summary List exam-prep practices globally // @Summary List practices globally
// @Tags exam-prep // @Tags learning
// @Param limit query int false "Page size. Omit (with offset) to return all practices." // @Param limit query int false "Page size. Omit (with offset) to return all practices."
// @Param offset query int false "Offset. Defaults to 0 when limit is provided; ignored semantics when both omitted (all rows)." // @Param offset query int false "Offset. Defaults to 0 when limit is provided; ignored semantics when both omitted (all rows)."
// @Param unlinked_only query bool false "When true, return only practices with no parent links (admin)" // @Param unlinked_only query bool false "When true, return only practices with no parent links (admin)"
// @Router /api/v1/admin/exam-prep/practices [get] // @Router /api/v1/admin/practices [get]
// @Router /api/v1/exam-prep/practices [get] // @Router /api/v1/practices [get]
// @Security Bearer // @Security Bearer
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Produce json // @Produce json
@ -94,8 +94,8 @@ func (h *Handler) ListAllExamPrepPractices(c *fiber.Ctx) error {
} }
// CreateExamPrepPractice godoc // CreateExamPrepPractice godoc
// @Summary Create exam-prep practice (under a lesson; uses shared question_sets) // @Summary Create practice (under a lesson; uses shared question_sets)
// @Tags exam-prep // @Tags learning
// @Param lessonId path int true "Exam prep lesson ID (unit_module_lessons.id)" // @Param lessonId path int true "Exam prep lesson ID (unit_module_lessons.id)"
// @Param body body domain.CreateExamPrepPracticeInput true "Practice" // @Param body body domain.CreateExamPrepPracticeInput true "Practice"
func (h *Handler) CreateExamPrepPractice(c *fiber.Ctx) error { func (h *Handler) CreateExamPrepPractice(c *fiber.Ctx) error {
@ -139,13 +139,13 @@ func (h *Handler) CreateExamPrepPractice(c *fiber.Ctx) error {
} }
// ListExamPrepPracticesByLesson godoc // ListExamPrepPracticesByLesson godoc
// @Summary List exam-prep practices for a lesson // @Summary List practices for a lesson
// @Tags exam-prep // @Tags learning
// @Param lessonId path int true "Exam prep lesson ID" // @Param lessonId path int true "Exam prep lesson ID"
// @Param limit query int false "Page size. Omit to return all practices for the lesson." // @Param limit query int false "Page size. Omit to return all practices for the lesson."
// @Param offset query int false "Offset (used when limit is provided)" // @Param offset query int false "Offset (used when limit is provided)"
// @Router /api/v1/admin/exam-prep/lessons/{lessonId}/practices [get] // @Router /api/v1/admin/lessons/{lessonId}/practices [get]
// @Router /api/v1/exam-prep/lessons/{lessonId}/practices [get] // @Router /api/v1/lessons/{lessonId}/practices [get]
// @Security Bearer // @Security Bearer
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Produce json // @Produce json
@ -183,11 +183,11 @@ func (h *Handler) ListExamPrepPracticesByLesson(c *fiber.Ctx) error {
} }
// GetExamPrepPracticeByID godoc // GetExamPrepPracticeByID godoc
// @Summary Get exam-prep practice by ID // @Summary Get practice by ID
// @Tags exam-prep // @Tags learning
// @Param id path int true "Exam prep practice ID" // @Param id path int true "Exam prep practice ID"
// @Router /api/v1/admin/exam-prep/practices/{id} [get] // @Router /api/v1/admin/practices/{id} [get]
// @Router /api/v1/exam-prep/practices/{id} [get] // @Router /api/v1/practices/{id} [get]
// @Security Bearer // @Security Bearer
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Produce json // @Produce json
@ -232,11 +232,11 @@ func (h *Handler) GetExamPrepPracticeByID(c *fiber.Ctx) error {
} }
// UpdateExamPrepPractice godoc // UpdateExamPrepPractice godoc
// @Summary Update exam-prep practice // @Summary Update practice
// @Tags exam-prep // @Tags learning
// @Param id path int true "Exam prep practice ID" // @Param id path int true "Exam prep practice ID"
// @Param body body domain.UpdateExamPrepPracticeInput true "Fields to update" // @Param body body domain.UpdateExamPrepPracticeInput true "Fields to update"
// @Router /api/v1/admin/exam-prep/practices/{id} [put] // @Router /api/v1/admin/practices/{id} [put]
// @Security Bearer // @Security Bearer
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Produce json // @Produce json
@ -292,11 +292,11 @@ func (h *Handler) UpdateExamPrepPractice(c *fiber.Ctx) error {
} }
// UpdateExamPrepPracticeParents godoc // UpdateExamPrepPracticeParents godoc
// @Summary Replace exam-prep practice parent links // @Summary Replace practice parent links
// @Tags exam-prep // @Tags learning
// @Param id path int true "Exam prep practice ID" // @Param id path int true "Exam prep practice ID"
// @Param body body domain.UpdateExamPrepPracticeParentsInput true "Parent links (replaces all; use empty array to detach)" // @Param body body domain.UpdateExamPrepPracticeParentsInput true "Parent links (replaces all; use empty array to detach)"
// @Router /api/v1/admin/exam-prep/practices/{id}/parents [put] // @Router /api/v1/admin/practices/{id}/parents [put]
// @Security Bearer // @Security Bearer
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Produce json // @Produce json
@ -334,9 +334,9 @@ func (h *Handler) UpdateExamPrepPracticeParents(c *fiber.Ctx) error {
case errors.Is(err, examprep.ErrLessonNotFound): case errors.Is(err, examprep.ErrLessonNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Lesson not found", Error: err.Error()}) return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Lesson not found", Error: err.Error()})
case errors.Is(err, examprep.ErrUnitNotFound): case errors.Is(err, examprep.ErrUnitNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Unit not found", Error: err.Error()}) return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Chapter not found", Error: err.Error()})
case errors.Is(err, examprep.ErrCatalogCourseNotFound): case errors.Is(err, examprep.ErrCatalogCourseNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Catalog course not found", Error: err.Error()}) return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Course not found", Error: err.Error()})
case errors.Is(err, examprep.ErrInvalidExamPrepPracticeParent): case errors.Is(err, examprep.ErrInvalidExamPrepPracticeParent):
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid parent", Error: err.Error()}) return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid parent", Error: err.Error()})
} }
@ -355,12 +355,12 @@ func (h *Handler) UpdateExamPrepPracticeParents(c *fiber.Ctx) error {
} }
// UnlinkExamPrepPracticeParent godoc // UnlinkExamPrepPracticeParent godoc
// @Summary Unlink one exam-prep practice parent // @Summary Unlink one practice parent
// @Tags exam-prep // @Tags learning
// @Param id path int true "Exam prep practice ID" // @Param id path int true "Exam prep practice ID"
// @Param parentKind path string true "Parent kind (CATALOG_COURSE, UNIT, LESSON)" // @Param parentKind path string true "Parent kind (CATALOG_COURSE, UNIT, LESSON)"
// @Param parentId path int true "Parent entity ID" // @Param parentId path int true "Parent entity ID"
// @Router /api/v1/admin/exam-prep/practices/{id}/parents/{parentKind}/{parentId} [delete] // @Router /api/v1/admin/practices/{id}/parents/{parentKind}/{parentId} [delete]
// @Security Bearer // @Security Bearer
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Produce json // @Produce json
@ -419,10 +419,10 @@ func (h *Handler) UnlinkExamPrepPracticeParent(c *fiber.Ctx) error {
} }
// DeleteExamPrepPractice godoc // DeleteExamPrepPractice godoc
// @Summary Delete exam-prep practice // @Summary Delete practice
// @Tags exam-prep // @Tags learning
// @Param id path int true "Exam prep practice ID" // @Param id path int true "Exam prep practice ID"
// @Router /api/v1/admin/exam-prep/practices/{id} [delete] // @Router /api/v1/admin/practices/{id} [delete]
// @Security Bearer // @Security Bearer
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Produce json // @Produce json
@ -481,9 +481,9 @@ func (h *Handler) mapCreateExamPrepPracticeError(c *fiber.Ctx, err error) error
Message: "Invalid parent", Message: "Invalid parent",
Error: err.Error(), Error: err.Error(),
}) })
case errors.Is(err, examprep.ErrExamPrepPracticeRequiresPracticeSet): case errors.Is(err, examprep.ErrExamPrepPracticeRequiresPracticeSet), errors.Is(err, examprep.ErrExamPrepQuizRequiresQuizSet):
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Exam-prep practices require a PRACTICE question set", Message: err.Error(),
Error: err.Error(), Error: err.Error(),
}) })
default: default:
@ -497,9 +497,9 @@ func (h *Handler) listExamPrepPracticesResponse(c *fiber.Ctx, items []domain.Exa
case errors.Is(notFound, examprep.ErrLessonNotFound): case errors.Is(notFound, examprep.ErrLessonNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Lesson not found", Error: notFound.Error()}) return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Lesson not found", Error: notFound.Error()})
case errors.Is(notFound, examprep.ErrUnitNotFound): case errors.Is(notFound, examprep.ErrUnitNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Unit not found", Error: notFound.Error()}) return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Chapter not found", Error: notFound.Error()})
case errors.Is(notFound, examprep.ErrCatalogCourseNotFound): case errors.Is(notFound, examprep.ErrCatalogCourseNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Catalog course not found", Error: notFound.Error()}) return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Course not found", Error: notFound.Error()})
} }
} }
return c.JSON(domain.Response{ return c.JSON(domain.Response{
@ -516,11 +516,11 @@ func (h *Handler) listExamPrepPracticesResponse(c *fiber.Ctx, items []domain.Exa
} }
// CreateExamPrepPracticeForCatalogCourse godoc // CreateExamPrepPracticeForCatalogCourse godoc
// @Summary Create exam-prep practice under a catalog course // @Summary Create practice under a course
// @Tags exam-prep // @Tags learning
// @Param catalogCourseId path int true "Exam prep catalog course ID" // @Param courseId path int true "Exam prep course ID"
// @Param body body domain.CreateExamPrepPracticeInput true "Practice" // @Param body body domain.CreateExamPrepPracticeInput true "Practice"
// @Router /api/v1/admin/exam-prep/catalog-courses/{catalogCourseId}/practices [post] // @Router /api/v1/admin/courses/{courseId}/practices [post]
// @Security Bearer // @Security Bearer
// @Success 201 {object} domain.Response // @Success 201 {object} domain.Response
// @Produce json // @Produce json
@ -529,9 +529,9 @@ func (h *Handler) listExamPrepPracticesResponse(c *fiber.Ctx, items []domain.Exa
// @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) CreateExamPrepPracticeForCatalogCourse(c *fiber.Ctx) error { func (h *Handler) CreateExamPrepPracticeForCatalogCourse(c *fiber.Ctx) error {
catalogCourseID, err := strconv.ParseInt(c.Params("catalogCourseId"), 10, 64) catalogCourseID, err := strconv.ParseInt(c.Params("courseId"), 10, 64)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid catalog course id", Error: err.Error()}) return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid course id", Error: err.Error()})
} }
var req domain.CreateExamPrepPracticeInput var req domain.CreateExamPrepPracticeInput
if err := c.BodyParser(&req); err != nil { if err := c.BodyParser(&req); err != nil {
@ -554,13 +554,13 @@ func (h *Handler) CreateExamPrepPracticeForCatalogCourse(c *fiber.Ctx) error {
} }
// ListExamPrepPracticesByCatalogCourse godoc // ListExamPrepPracticesByCatalogCourse godoc
// @Summary List exam-prep practices for a catalog course // @Summary List practices for a course
// @Tags exam-prep // @Tags learning
// @Param catalogCourseId path int true "Exam prep catalog course ID" // @Param courseId path int true "Exam prep course ID"
// @Param limit query int false "Page size. Omit to return all practices for the catalog course." // @Param limit query int false "Page size. Omit to return all practices for the course."
// @Param offset query int false "Offset (used when limit is provided)" // @Param offset query int false "Offset (used when limit is provided)"
// @Router /api/v1/admin/exam-prep/catalog-courses/{catalogCourseId}/practices [get] // @Router /api/v1/admin/courses/{courseId}/practices [get]
// @Router /api/v1/exam-prep/catalog-courses/{catalogCourseId}/practices [get] // @Router /api/v1/courses/{courseId}/practices [get]
// @Security Bearer // @Security Bearer
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Produce json // @Produce json
@ -569,9 +569,9 @@ func (h *Handler) CreateExamPrepPracticeForCatalogCourse(c *fiber.Ctx) error {
// @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) ListExamPrepPracticesByCatalogCourse(c *fiber.Ctx) error { func (h *Handler) ListExamPrepPracticesByCatalogCourse(c *fiber.Ctx) error {
catalogCourseID, err := strconv.ParseInt(c.Params("catalogCourseId"), 10, 64) catalogCourseID, err := strconv.ParseInt(c.Params("courseId"), 10, 64)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid catalog course id", Error: err.Error()}) return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid course id", Error: err.Error()})
} }
limit, offset, err := parseOptionalExamPrepPracticePagination(c) limit, offset, err := parseOptionalExamPrepPracticePagination(c)
if err != nil { if err != nil {
@ -592,11 +592,11 @@ func (h *Handler) ListExamPrepPracticesByCatalogCourse(c *fiber.Ctx) error {
} }
// CreateExamPrepPracticeForUnit godoc // CreateExamPrepPracticeForUnit godoc
// @Summary Create exam-prep practice under a unit // @Summary Create practice under a unit
// @Tags exam-prep // @Tags learning
// @Param unitId path int true "Exam prep unit ID" // @Param chapterId path int true "Exam prep unit ID"
// @Param body body domain.CreateExamPrepPracticeInput true "Practice" // @Param body body domain.CreateExamPrepPracticeInput true "Practice"
// @Router /api/v1/admin/exam-prep/units/{unitId}/practices [post] // @Router /api/v1/admin/chapters/{chapterId}/practices [post]
// @Security Bearer // @Security Bearer
// @Success 201 {object} domain.Response // @Success 201 {object} domain.Response
// @Produce json // @Produce json
@ -605,9 +605,9 @@ func (h *Handler) ListExamPrepPracticesByCatalogCourse(c *fiber.Ctx) error {
// @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) CreateExamPrepPracticeForUnit(c *fiber.Ctx) error { func (h *Handler) CreateExamPrepPracticeForUnit(c *fiber.Ctx) error {
unitID, err := strconv.ParseInt(c.Params("unitId"), 10, 64) unitID, err := strconv.ParseInt(c.Params("chapterId"), 10, 64)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid unit id", Error: err.Error()}) return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid chapter id", Error: err.Error()})
} }
var req domain.CreateExamPrepPracticeInput var req domain.CreateExamPrepPracticeInput
if err := c.BodyParser(&req); err != nil { if err := c.BodyParser(&req); err != nil {
@ -630,13 +630,13 @@ func (h *Handler) CreateExamPrepPracticeForUnit(c *fiber.Ctx) error {
} }
// ListExamPrepPracticesByUnit godoc // ListExamPrepPracticesByUnit godoc
// @Summary List exam-prep practices for a unit // @Summary List practices for a unit
// @Tags exam-prep // @Tags learning
// @Param unitId path int true "Exam prep unit ID" // @Param chapterId path int true "Exam prep unit ID"
// @Param limit query int false "Page size. Omit to return all practices for the unit." // @Param limit query int false "Page size. Omit to return all practices for the unit."
// @Param offset query int false "Offset (used when limit is provided)" // @Param offset query int false "Offset (used when limit is provided)"
// @Router /api/v1/admin/exam-prep/units/{unitId}/practices [get] // @Router /api/v1/admin/chapters/{chapterId}/practices [get]
// @Router /api/v1/exam-prep/units/{unitId}/practices [get] // @Router /api/v1/chapters/{chapterId}/practices [get]
// @Security Bearer // @Security Bearer
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Produce json // @Produce json
@ -645,9 +645,9 @@ func (h *Handler) CreateExamPrepPracticeForUnit(c *fiber.Ctx) error {
// @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) ListExamPrepPracticesByUnit(c *fiber.Ctx) error { func (h *Handler) ListExamPrepPracticesByUnit(c *fiber.Ctx) error {
unitID, err := strconv.ParseInt(c.Params("unitId"), 10, 64) unitID, err := strconv.ParseInt(c.Params("chapterId"), 10, 64)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid unit id", Error: err.Error()}) return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid chapter id", Error: err.Error()})
} }
limit, offset, err := parseOptionalExamPrepPracticePagination(c) limit, offset, err := parseOptionalExamPrepPracticePagination(c)
if err != nil { if err != nil {
@ -667,7 +667,7 @@ func (h *Handler) ListExamPrepPracticesByUnit(c *fiber.Ctx) error {
return h.listExamPrepPracticesResponse(c, items, total, int(limit), int(offset), nil) return h.listExamPrepPracticesResponse(c, items, total, int(limit), int(offset), nil)
} }
// parseOptionalExamPrepPracticePagination returns limit/offset for exam-prep practice lists. // parseOptionalExamPrepPracticePagination returns limit/offset for practice lists.
// When limit is omitted, limit=0 means "return all" (no SQL LIMIT). // When limit is omitted, limit=0 means "return all" (no SQL LIMIT).
// When offset is omitted, offset defaults to 0. // When offset is omitted, offset defaults to 0.
func parseOptionalExamPrepPracticePagination(c *fiber.Ctx) (limit, offset int32, err error) { func parseOptionalExamPrepPracticePagination(c *fiber.Ctx) (limit, offset int32, err error) {

View File

@ -11,15 +11,15 @@ import (
) )
// CreateExamPrepUnit godoc // CreateExamPrepUnit godoc
// @Summary Create exam-prep unit // @Summary Create chapter
// @Description Unit under a catalog course (e.g. chapter title). Optional sort_order assigns position within that catalog course (siblings at or after that index are shifted); omit to append after the current highest sort_order in the catalog course. // @Description Chapter under a course (e.g. chapter title). Optional sort_order assigns position within that course (siblings at or after that index are shifted); omit to append after the current highest sort_order in the course.
// @Tags exam-prep // @Tags learning
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param catalogCourseId path int true "Catalog course ID" // @Param courseId path int true "Course ID"
// @Param body body domain.CreateExamPrepUnitInput true "Unit" // @Param body body domain.CreateExamPrepUnitInput true "Chapter"
// @Success 201 {object} domain.Response // @Success 201 {object} domain.Response{data=domain.ExamPrepUnit}
// @Router /api/v1/admin/exam-prep/catalog-courses/{catalogCourseId}/units [post] // @Router /api/v1/admin/courses/{courseId}/chapters [post]
// @Security Bearer // @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
@ -27,10 +27,10 @@ import (
// @Failure 404 {object} domain.ErrorResponse "Resource not found" // @Failure 404 {object} domain.ErrorResponse "Resource not found"
// @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) CreateExamPrepUnit(c *fiber.Ctx) error { func (h *Handler) CreateExamPrepUnit(c *fiber.Ctx) error {
catalogCourseID, err := strconv.ParseInt(c.Params("catalogCourseId"), 10, 64) catalogCourseID, err := strconv.ParseInt(c.Params("courseId"), 10, 64)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid catalog course id", Message: "Invalid course id",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -51,18 +51,18 @@ func (h *Handler) CreateExamPrepUnit(c *fiber.Ctx) error {
if err != nil { if err != nil {
if errors.Is(err, examprep.ErrCatalogCourseNotFound) { if errors.Is(err, examprep.ErrCatalogCourseNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Catalog course not found", Message: "Course not found",
Error: err.Error(), Error: err.Error(),
}) })
} }
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to create unit", Message: "Failed to create chapter",
Error: err.Error(), Error: err.Error(),
}) })
} }
h.recordActivity(c, domain.ActionExamPrepUnitCreated, domain.ResourceExamPrepUnit, &out.ID, "Created exam prep unit: "+out.Name, nil) h.recordActivity(c, domain.ActionExamPrepUnitCreated, domain.ResourceExamPrepUnit, &out.ID, "Created chapter: "+out.Name, nil)
return c.Status(fiber.StatusCreated).JSON(domain.Response{ return c.Status(fiber.StatusCreated).JSON(domain.Response{
Message: "Unit created successfully", Message: "Chapter created successfully",
Data: out, Data: out,
Success: true, Success: true,
StatusCode: fiber.StatusCreated, StatusCode: fiber.StatusCreated,
@ -70,14 +70,14 @@ func (h *Handler) CreateExamPrepUnit(c *fiber.Ctx) error {
} }
// ListExamPrepUnitsByCatalogCourse godoc // ListExamPrepUnitsByCatalogCourse godoc
// @Summary List exam-prep units for a catalog course // @Summary List chapters for a course
// @Tags exam-prep // @Tags learning
// @Param catalogCourseId path int true "Catalog course ID" // @Param courseId path int true "Course ID"
// @Param limit query int false "Page size" default(20) // @Param limit query int false "Page size" default(20)
// @Param offset query int false "Offset" default(0) // @Param offset query int false "Offset" default(0)
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response{data=chapterListData}
// @Router /api/v1/admin/exam-prep/catalog-courses/{catalogCourseId}/units [get] // @Router /api/v1/admin/courses/{courseId}/chapters [get]
// @Router /api/v1/exam-prep/catalog-courses/{catalogCourseId}/units [get] // @Router /api/v1/courses/{courseId}/chapters [get]
// @Security Bearer // @Security Bearer
// @Produce json // @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
@ -86,10 +86,10 @@ func (h *Handler) CreateExamPrepUnit(c *fiber.Ctx) error {
// @Failure 404 {object} domain.ErrorResponse "Resource not found" // @Failure 404 {object} domain.ErrorResponse "Resource not found"
// @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) ListExamPrepUnitsByCatalogCourse(c *fiber.Ctx) error { func (h *Handler) ListExamPrepUnitsByCatalogCourse(c *fiber.Ctx) error {
catalogCourseID, err := strconv.ParseInt(c.Params("catalogCourseId"), 10, 64) catalogCourseID, err := strconv.ParseInt(c.Params("courseId"), 10, 64)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid catalog course id", Message: "Invalid course id",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -97,11 +97,11 @@ func (h *Handler) ListExamPrepUnitsByCatalogCourse(c *fiber.Ctx) error {
offset, _ := strconv.Atoi(c.Query("offset", "0")) offset, _ := strconv.Atoi(c.Query("offset", "0"))
publishedOnly := !h.canManageExamPrepUnits(c) publishedOnly := !h.canManageExamPrepUnits(c)
if publishedOnly { if publishedOnly {
// Draft catalog courses hide their units from non-managers. // Draft courses hide their units from non-managers.
cc, err := h.examPrepSvc.GetCatalogCourseByID(c.Context(), catalogCourseID) cc, err := h.examPrepSvc.GetCatalogCourseByID(c.Context(), catalogCourseID)
if err == nil && !cc.VisibleToLearners() { if err == nil && !cc.VisibleToLearners() {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Catalog course not found", Message: "Course not found",
Error: examprep.ErrCatalogCourseNotFound.Error(), Error: examprep.ErrCatalogCourseNotFound.Error(),
}) })
} }
@ -110,7 +110,7 @@ func (h *Handler) ListExamPrepUnitsByCatalogCourse(c *fiber.Ctx) error {
if err != nil { if err != nil {
if errors.Is(err, examprep.ErrCatalogCourseNotFound) { if errors.Is(err, examprep.ErrCatalogCourseNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Catalog course not found", Message: "Course not found",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -131,9 +131,9 @@ func (h *Handler) ListExamPrepUnitsByCatalogCourse(c *fiber.Ctx) error {
}) })
} }
return c.JSON(domain.Response{ return c.JSON(domain.Response{
Message: "Units retrieved successfully", Message: "Chapters retrieved successfully",
Data: fiber.Map{ Data: fiber.Map{
"units": items, "chapters": items,
"total_count": total, "total_count": total,
"limit": limit, "limit": limit,
"offset": offset, "offset": offset,
@ -144,11 +144,11 @@ func (h *Handler) ListExamPrepUnitsByCatalogCourse(c *fiber.Ctx) error {
} }
// ReorderExamPrepUnitsInCatalogCourse godoc // ReorderExamPrepUnitsInCatalogCourse godoc
// @Summary Reorder units within a catalog course // @Summary Reorder chapters within a course
// @Tags exam-prep // @Tags learning
// @Param catalogCourseId path int true "Catalog course ID" // @Param courseId path int true "Course ID"
// @Param body body domain.ReorderIDsRequest true "ordered_ids: every unit id in this catalog course, new order" // @Param body body domain.ReorderIDsRequest true "ordered_ids: every chapter id in this course, new order"
// @Router /api/v1/admin/exam-prep/catalog-courses/{catalogCourseId}/units/reorder [put] // @Router /api/v1/admin/courses/{courseId}/chapters/reorder [put]
// @Security Bearer // @Security Bearer
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Produce json // @Produce json
@ -158,10 +158,10 @@ func (h *Handler) ListExamPrepUnitsByCatalogCourse(c *fiber.Ctx) error {
// @Failure 404 {object} domain.ErrorResponse "Resource not found" // @Failure 404 {object} domain.ErrorResponse "Resource not found"
// @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) ReorderExamPrepUnitsInCatalogCourse(c *fiber.Ctx) error { func (h *Handler) ReorderExamPrepUnitsInCatalogCourse(c *fiber.Ctx) error {
catalogCourseID, err := strconv.ParseInt(c.Params("catalogCourseId"), 10, 64) catalogCourseID, err := strconv.ParseInt(c.Params("courseId"), 10, 64)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid catalog course id", Message: "Invalid course id",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -181,7 +181,7 @@ func (h *Handler) ReorderExamPrepUnitsInCatalogCourse(c *fiber.Ctx) error {
if err := h.examPrepSvc.ReorderUnitsInCatalogCourse(c.Context(), catalogCourseID, req.OrderedIDs); err != nil { if err := h.examPrepSvc.ReorderUnitsInCatalogCourse(c.Context(), catalogCourseID, req.OrderedIDs); err != nil {
if errors.Is(err, examprep.ErrCatalogCourseNotFound) { if errors.Is(err, examprep.ErrCatalogCourseNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Catalog course not found", Message: "Course not found",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -196,7 +196,7 @@ func (h *Handler) ReorderExamPrepUnitsInCatalogCourse(c *fiber.Ctx) error {
Error: err.Error(), Error: err.Error(),
}) })
} }
h.recordActivity(c, domain.ActionExamPrepUnitReordered, domain.ResourceExamPrepUnit, &catalogCourseID, "Reordered exam prep units in catalog course", nil) h.recordActivity(c, domain.ActionExamPrepUnitReordered, domain.ResourceExamPrepUnit, &catalogCourseID, "Reordered chapters in course", nil)
return c.JSON(domain.Response{ return c.JSON(domain.Response{
Message: "Units reordered successfully", Message: "Units reordered successfully",
Success: true, Success: true,
@ -205,13 +205,13 @@ func (h *Handler) ReorderExamPrepUnitsInCatalogCourse(c *fiber.Ctx) error {
} }
// GetExamPrepUnitByID godoc // GetExamPrepUnitByID godoc
// @Summary Get exam-prep unit by ID // @Summary Get chapter by ID
// @Tags exam-prep // @Tags learning
// @Param id path int true "Unit ID" // @Param id path int true "Chapter ID"
// @Router /api/v1/admin/exam-prep/units/{id} [get] // @Router /api/v1/admin/chapters/{id} [get]
// @Router /api/v1/exam-prep/units/{id} [get] // @Router /api/v1/chapters/{id} [get]
// @Security Bearer // @Security Bearer
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response{data=domain.ExamPrepUnit}
// @Produce json // @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
@ -222,7 +222,7 @@ func (h *Handler) GetExamPrepUnitByID(c *fiber.Ctx) error {
id, err := strconv.ParseInt(c.Params("id"), 10, 64) id, err := strconv.ParseInt(c.Params("id"), 10, 64)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid unit id", Message: "Invalid chapter id",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -230,7 +230,7 @@ func (h *Handler) GetExamPrepUnitByID(c *fiber.Ctx) error {
if err != nil { if err != nil {
if errors.Is(err, examprep.ErrUnitNotFound) { if errors.Is(err, examprep.ErrUnitNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Unit not found", Message: "Chapter not found",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -241,7 +241,7 @@ func (h *Handler) GetExamPrepUnitByID(c *fiber.Ctx) error {
} }
if !out.VisibleToLearners() && !h.canManageExamPrepUnits(c) { if !out.VisibleToLearners() && !h.canManageExamPrepUnits(c) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Unit not found", Message: "Chapter not found",
Error: examprep.ErrUnitNotFound.Error(), Error: examprep.ErrUnitNotFound.Error(),
}) })
} }
@ -265,13 +265,13 @@ func (h *Handler) GetExamPrepUnitByID(c *fiber.Ctx) error {
} }
// UpdateExamPrepUnit godoc // UpdateExamPrepUnit godoc
// @Summary Update exam-prep unit // @Summary Update chapter
// @Tags exam-prep // @Tags learning
// @Param id path int true "Unit ID" // @Param id path int true "Chapter ID"
// @Param body body domain.UpdateExamPrepUnitInput true "Fields to update" // @Param body body domain.UpdateExamPrepUnitInput true "Fields to update"
// @Router /api/v1/admin/exam-prep/units/{id} [put] // @Router /api/v1/admin/chapters/{id} [put]
// @Security Bearer // @Security Bearer
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response{data=domain.ExamPrepUnit}
// @Produce json // @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
@ -282,7 +282,7 @@ func (h *Handler) UpdateExamPrepUnit(c *fiber.Ctx) error {
id, err := strconv.ParseInt(c.Params("id"), 10, 64) id, err := strconv.ParseInt(c.Params("id"), 10, 64)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid unit id", Message: "Invalid chapter id",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -297,7 +297,7 @@ func (h *Handler) UpdateExamPrepUnit(c *fiber.Ctx) error {
if err != nil { if err != nil {
if errors.Is(err, examprep.ErrUnitNotFound) { if errors.Is(err, examprep.ErrUnitNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Unit not found", Message: "Chapter not found",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -306,9 +306,9 @@ func (h *Handler) UpdateExamPrepUnit(c *fiber.Ctx) error {
Error: err.Error(), Error: err.Error(),
}) })
} }
h.recordActivity(c, domain.ActionExamPrepUnitUpdated, domain.ResourceExamPrepUnit, &out.ID, "Updated exam prep unit: "+out.Name, nil) h.recordActivity(c, domain.ActionExamPrepUnitUpdated, domain.ResourceExamPrepUnit, &out.ID, "Updated chapter: "+out.Name, nil)
return c.JSON(domain.Response{ return c.JSON(domain.Response{
Message: "Unit updated successfully", Message: "Chapter updated successfully",
Data: out, Data: out,
Success: true, Success: true,
StatusCode: fiber.StatusOK, StatusCode: fiber.StatusOK,
@ -316,10 +316,10 @@ func (h *Handler) UpdateExamPrepUnit(c *fiber.Ctx) error {
} }
// DeleteExamPrepUnit godoc // DeleteExamPrepUnit godoc
// @Summary Delete exam-prep unit // @Summary Delete chapter
// @Tags exam-prep // @Tags learning
// @Param id path int true "Unit ID" // @Param id path int true "Chapter ID"
// @Router /api/v1/admin/exam-prep/units/{id} [delete] // @Router /api/v1/admin/chapters/{id} [delete]
// @Security Bearer // @Security Bearer
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Produce json // @Produce json
@ -332,14 +332,14 @@ func (h *Handler) DeleteExamPrepUnit(c *fiber.Ctx) error {
id, err := strconv.ParseInt(c.Params("id"), 10, 64) id, err := strconv.ParseInt(c.Params("id"), 10, 64)
if err != nil { if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid unit id", Message: "Invalid chapter id",
Error: err.Error(), Error: err.Error(),
}) })
} }
if err := h.examPrepSvc.DeleteUnit(c.Context(), id); err != nil { if err := h.examPrepSvc.DeleteUnit(c.Context(), id); err != nil {
if errors.Is(err, examprep.ErrUnitNotFound) { if errors.Is(err, examprep.ErrUnitNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Unit not found", Message: "Chapter not found",
Error: err.Error(), Error: err.Error(),
}) })
} }
@ -348,9 +348,9 @@ func (h *Handler) DeleteExamPrepUnit(c *fiber.Ctx) error {
Error: err.Error(), Error: err.Error(),
}) })
} }
h.recordActivity(c, domain.ActionExamPrepUnitDeleted, domain.ResourceExamPrepUnit, &id, fmt.Sprintf("Deleted exam prep unit ID: %d", id), nil) h.recordActivity(c, domain.ActionExamPrepUnitDeleted, domain.ResourceExamPrepUnit, &id, fmt.Sprintf("Deleted chapter ID: %d", id), nil)
return c.JSON(domain.Response{ return c.JSON(domain.Response{
Message: "Unit deleted successfully", Message: "Chapter deleted successfully",
Success: true, Success: true,
StatusCode: fiber.StatusOK, StatusCode: fiber.StatusOK,
}) })

View File

@ -0,0 +1,44 @@
package handlers
import "Rezina-Backend/internal/domain"
// These response data schemas describe the public hierarchy, including list keys.
type learningPagination struct {
TotalCount int64 `json:"total_count"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
type courseListData struct {
Courses []domain.ExamPrepCatalogCourse `json:"courses"`
learningPagination
}
type chapterListData struct {
Chapters []domain.ExamPrepUnit `json:"chapters"`
learningPagination
}
type lessonListData struct {
Lessons []domain.ExamPrepLesson `json:"lessons"`
learningPagination
}
type quizListData struct {
Quizzes []domain.ExamPrepPractice `json:"quizzes"`
learningPagination
}
// createChapterQuizRequest intentionally omits parent fields: the URL owns placement.
type createChapterQuizRequest struct {
QuestionSetID int64 `json:"question_set_id" validate:"required,gt=0" example:"12"`
Title *string `json:"title,omitempty" example:"Chapter review"`
PublishStatus string `json:"publish_status,omitempty" enums:"DRAFT,PUBLISHED" default:"DRAFT"`
}
type quizFullData struct {
Practice domain.ExamPrepPractice `json:"practice"`
QuestionSet questionSetRes `json:"question_set"`
StimulusBlocks []domain.PracticeStimulusBlock `json:"stimulus_blocks"`
Questions []questionRes `json:"questions"`
}

View File

@ -39,12 +39,12 @@ func (h *Handler) GetMyLMSProgress(c *fiber.Ctx) error {
// GetMyLMSProgressSummary godoc // GetMyLMSProgressSummary godoc
// @Summary Get my learning progress summary // @Summary Get my learning progress summary
// @Description Returns progress for the catalog course → unit → module → lesson learning hierarchy. // @Description Returns progress for the course → unit → module → lesson learning hierarchy.
// @Tags exam-prep // @Tags learning
// @Produce json // @Produce json
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Failure 500 {object} domain.ErrorResponse // @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/exam-prep/progress-summary [get] // @Router /api/v1/progress-summary [get]
// @Security Bearer // @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"

View File

@ -231,15 +231,15 @@ func (h *Handler) GetLmsPracticeFull(c *fiber.Ctx) error {
} }
// GetExamPrepPracticeFull godoc // GetExamPrepPracticeFull godoc
// @Summary Get exam-prep practice with question set and questions // @Summary Get practice with question set and questions
// @Description Returns exam-prep practice metadata, linked question set settings, and all questions in the set. // @Description Returns practice metadata, linked question set settings, and all questions in the set.
// @Tags exam-prep // @Tags learning
// @Produce json // @Produce json
// @Param id path int true "Exam prep practice ID" // @Param id path int true "Exam prep practice ID"
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Failure 400 {object} domain.ErrorResponse // @Failure 400 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse // @Failure 404 {object} domain.ErrorResponse
// @Router /api/v1/admin/exam-prep/practices/{id}/full [get] // @Router /api/v1/admin/practices/{id}/full [get]
// @Security Bearer // @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
@ -374,9 +374,9 @@ func (h *Handler) UpdateLmsPracticeFull(c *fiber.Ctx) error {
} }
// UpdateExamPrepPracticeFull godoc // UpdateExamPrepPracticeFull godoc
// @Summary Full update exam-prep practice with question set and questions // @Summary Full update practice with question set and questions
// @Description Updates exam-prep practice metadata, linked question set settings, and syncs questions in one request. // @Description Updates practice metadata, linked question set settings, and syncs questions in one request.
// @Tags exam-prep // @Tags learning
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param id path int true "Exam prep practice ID" // @Param id path int true "Exam prep practice ID"
@ -384,7 +384,7 @@ func (h *Handler) UpdateLmsPracticeFull(c *fiber.Ctx) error {
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response
// @Failure 400 {object} domain.ErrorResponse // @Failure 400 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse // @Failure 404 {object} domain.ErrorResponse
// @Router /api/v1/admin/exam-prep/practices/{id}/full [put] // @Router /api/v1/admin/practices/{id}/full [put]
// @Security Bearer // @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
@ -437,9 +437,9 @@ func (h *Handler) UpdateExamPrepPracticeFull(c *fiber.Ctx) error {
"question_set_id": result.QuestionSet.ID, "question_set_id": result.QuestionSet.ID,
"question_count": len(result.Questions), "question_count": len(result.Questions),
}) })
msg := fmt.Sprintf("Full update exam-prep practice ID: %d", id) msg := fmt.Sprintf("Full update practice ID: %d", id)
if p, ok := result.Practice.(domain.ExamPrepPractice); ok { if p, ok := result.Practice.(domain.ExamPrepPractice); ok {
msg = "Full update exam-prep practice: " + p.Title msg = "Full update practice: " + p.Title
} }
h.recordActivity(c, domain.ActionExamPrepPracticeUpdated, domain.ResourceExamPrepPractice, &id, msg, meta) h.recordActivity(c, domain.ActionExamPrepPracticeUpdated, domain.ResourceExamPrepPractice, &id, msg, meta)

View File

@ -277,7 +277,7 @@ func (h *Handler) applyPracticeAccess(ctx context.Context, c *fiber.Ctx, items [
} }
func practiceAccessForQuestionSet(set domain.QuestionSet) *domain.PracticeAccess { func practiceAccessForQuestionSet(set domain.QuestionSet) *domain.PracticeAccess {
if !strings.EqualFold(set.SetType, string(domain.QuestionSetTypePractice)) { if !strings.EqualFold(set.SetType, string(domain.QuestionSetTypePractice)) && !strings.EqualFold(set.SetType, string(domain.QuestionSetTypeQuiz)) {
return &domain.PracticeAccess{IsAccessible: false, Reason: "Question set is not a practice"} return &domain.PracticeAccess{IsAccessible: false, Reason: "Question set is not a practice"}
} }
if !strings.EqualFold(set.Status, "PUBLISHED") { if !strings.EqualFold(set.Status, "PUBLISHED") {

View File

@ -0,0 +1,68 @@
package handlers
import (
"Rezina-Backend/internal/domain"
"Rezina-Backend/internal/services/examprep"
"errors"
"github.com/gofiber/fiber/v2"
"strconv"
"strings"
)
// ListPublicCourses godoc
// @Summary Browse published course highlights without signing in
// @Description Public discovery only: titles, descriptions, thumbnails, access tiers and published content counts. Draft courses are excluded. Playback, quiz questions and progress use authenticated learning endpoints.
// @Tags public-catalog
// @Produce json
// @Param q query string false "Search course name or description (maximum 200 characters)"
// @Param limit query int false "Page size (1-100)" default(20)
// @Param offset query int false "Non-negative offset" default(0)
// @Success 200 {object} domain.Response{data=domain.PublicCatalogPage}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/catalog/courses [get]
func (h *Handler) ListPublicCourses(c *fiber.Ctx) error {
q := strings.TrimSpace(c.Query("q"))
limit, err := strconv.Atoi(c.Query("limit", "20"))
if err != nil || limit < 1 || limit > 100 {
return fiber.NewError(400, "limit must be between 1 and 100")
}
offset, err := strconv.ParseInt(c.Query("offset", "0"), 10, 32)
if err != nil || offset < 0 {
return fiber.NewError(400, "offset must be non-negative")
}
if len([]rune(q)) > 200 {
return fiber.NewError(400, "Search must be at most 200 characters")
}
page, err := h.examPrepSvc.PublicCatalogCourses(c.Context(), q, int32(limit), int32(offset))
if err != nil {
return fiber.NewError(500, "Unable to load course catalog")
}
return c.JSON(domain.Response{Success: true, StatusCode: 200, Message: "Course highlights retrieved", Data: page})
}
// GetPublicCourse godoc
// @Summary Preview a published course outline without signing in
// @Description Returns published chapters, lesson highlights and quiz titles/counts. No video URLs, questions, answers or learner information are included. Unpublished courses return 404, even for staff tokens.
// @Tags public-catalog
// @Produce json
// @Param id path int true "Published course ID"
// @Success 200 {object} domain.Response{data=domain.PublicCourseOutline}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/catalog/courses/{id} [get]
func (h *Handler) GetPublicCourse(c *fiber.Ctx) error {
id, err := parseAssessmentID(c.Params("id"))
if err != nil {
return fiber.NewError(400, "Invalid course ID")
}
out, err := h.examPrepSvc.PublicCatalogCourse(c.Context(), id)
if errors.Is(err, examprep.ErrCatalogCourseNotFound) {
return fiber.NewError(404, "Course not found")
}
if err != nil {
return fiber.NewError(500, "Unable to load course outline")
}
return c.JSON(domain.Response{Success: true, StatusCode: 200, Message: "Course outline retrieved", Data: out})
}

View File

@ -0,0 +1,75 @@
package handlers
import (
"context"
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"Rezina-Backend/internal/domain"
"Rezina-Backend/internal/repository"
"Rezina-Backend/internal/services/examprep"
"github.com/gofiber/fiber/v2"
"github.com/jackc/pgx/v5"
)
type catalogFixtureStore struct {
*repository.Store
calls int
}
func (s *catalogFixtureStore) PublicCatalogCourses(_ context.Context, q string, limit, offset int32) (domain.PublicCatalogPage, error) {
s.calls++
return domain.PublicCatalogPage{Courses: []domain.PublicCourse{{ID: 3, Name: "Public course"}}, TotalCount: 1, Limit: limit, Offset: offset}, nil
}
func (s *catalogFixtureStore) PublicCatalogCourse(_ context.Context, id int64) (domain.PublicCourseOutline, error) {
s.calls++
if id != 3 {
return domain.PublicCourseOutline{}, pgx.ErrNoRows
}
return domain.PublicCourseOutline{PublicCourse: domain.PublicCourse{ID: 3, Name: "Public course"}, Chapters: []domain.PublicChapter{{ID: 7, Name: "Chapter", Lessons: []domain.PublicLesson{{ID: 11, Title: "Lesson"}}, Quizzes: []domain.PublicQuiz{{ID: 9, Title: "Review", QuestionCount: 3}}}}}, nil
}
func TestPublicCatalogWithoutAuthentication(t *testing.T) {
store := &catalogFixtureStore{}
h := &Handler{examPrepSvc: examprep.NewService(store)}
app := fiber.New()
app.Get("/catalog/courses", h.ListPublicCourses)
app.Get("/catalog/courses/:id", h.GetPublicCourse)
for _, tc := range []struct {
path string
status int
}{
{"/catalog/courses", 200}, {"/catalog/courses?q=English&limit=10&offset=0", 200},
{"/catalog/courses?limit=101", 400}, {"/catalog/courses?offset=-1", 400}, {"/catalog/courses?offset=2147483648", 400},
{"/catalog/courses?q=" + strings.Repeat("x", 201), 400}, {"/catalog/courses/3", 200}, {"/catalog/courses/4", 404}, {"/catalog/courses/0", 400},
} {
t.Run(tc.path, func(t *testing.T) {
req := httptest.NewRequest("GET", tc.path, nil)
res, err := app.Test(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != tc.status {
t.Fatalf("status=%d want=%d", res.StatusCode, tc.status)
}
if tc.status == 200 {
var payload map[string]any
if err = json.NewDecoder(res.Body).Decode(&payload); err != nil {
t.Fatal(err)
}
if payload["success"] != true {
t.Fatalf("response=%v", payload)
}
data, _ := json.Marshal(payload["data"])
for _, private := range []string{"video_url", "question_text", "is_correct", "password", "completed_at"} {
if strings.Contains(string(data), `"`+private+`"`) {
t.Errorf("public catalog exposes %s", private)
}
}
}
})
}
}

View File

@ -1539,11 +1539,11 @@ func (h *Handler) questionSetStimulusContexts(ctx context.Context, setID int64)
// GetQuestionSetItems godoc // GetQuestionSetItems godoc
// @Summary Get questions in set // @Summary Get questions in set
// @Description Returns all questions in a question set with contextual shared stimulus data for linked LMS and exam-prep practices // @Description Returns all questions as the data array (not a paginated object). Use this admin endpoint to author quiz questions; learner quiz reads are paginated. Includes contextual shared stimulus data.
// @Tags question-set-items // @Tags question-set-items
// @Produce json // @Produce json
// @Param setId path int true "Question Set ID" // @Param setId path int true "Question Set ID"
// @Success 200 {object} domain.Response // @Success 200 {object} domain.Response{data=[]questionRes}
// @Failure 400 {object} domain.ErrorResponse // @Failure 400 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse // @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/question-sets/{setId}/questions [get] // @Router /api/v1/admin/question-sets/{setId}/questions [get]
@ -1669,7 +1669,7 @@ func (h *Handler) GetQuestionsInSet(c *fiber.Ctx) error {
// GetQuestionsByPractice godoc // GetQuestionsByPractice godoc
// @Summary Get questions by practice // @Summary Get questions by practice
// @Description Returns paginated questions for an exam-prep practice, including shared stimulus blocks and each question's effective dynamic payload // @Description Returns paginated questions for an practice, including shared stimulus blocks and each question's effective dynamic payload
// @Tags question-set-items // @Tags question-set-items
// @Produce json // @Produce json
// @Param practiceId path int true "Exam-prep practice ID" // @Param practiceId path int true "Exam-prep practice ID"
@ -1680,7 +1680,7 @@ func (h *Handler) GetQuestionsInSet(c *fiber.Ctx) error {
// @Failure 400 {object} domain.ErrorResponse // @Failure 400 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse // @Failure 404 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse // @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/exam-prep/practices/{practiceId}/questions [get] // @Router /api/v1/practices/{practiceId}/questions [get]
// @Security Bearer // @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
@ -1710,7 +1710,7 @@ func (h *Handler) GetQuestionsByPractice(c *fiber.Ctx) error {
}) })
} }
if !strings.EqualFold(set.SetType, string(domain.QuestionSetTypePractice)) { if !strings.EqualFold(set.SetType, string(domain.QuestionSetTypePractice)) && !strings.EqualFold(set.SetType, string(domain.QuestionSetTypeQuiz)) {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Question set is not a practice", Message: "Question set is not a practice",
}) })
@ -1782,7 +1782,7 @@ func (h *Handler) GetQuestionsByPractice(c *fiber.Ctx) error {
} }
// CompletePractice godoc // CompletePractice godoc
// @Summary Mark exam-prep practice as completed // @Summary Mark practice as completed
// @Description Marks a practice question set as completed for the authenticated learner in its exam-prep parent scope // @Description Marks a practice question set as completed for the authenticated learner in its exam-prep parent scope
// @Tags progression // @Tags progression
// @Produce json // @Produce json
@ -1792,7 +1792,7 @@ func (h *Handler) GetQuestionsByPractice(c *fiber.Ctx) error {
// @Failure 403 {object} domain.ErrorResponse // @Failure 403 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse // @Failure 404 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse // @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/exam-prep/progress/practices/{id}/complete [post] // @Router /api/v1/progress/practices/{id}/complete [post]
// @Security Bearer // @Security Bearer
// @Accept json // @Accept json
// @Param body body domain.CompletePracticeInput false "Optional practice parent scope" // @Param body body domain.CompletePracticeInput false "Optional practice parent scope"
@ -1818,7 +1818,7 @@ func (h *Handler) CompletePractice(c *fiber.Ctx) error {
// The exam-prep route is authoritative for the rebuilt hierarchy; legacy IDs // The exam-prep route is authoritative for the rebuilt hierarchy; legacy IDs
// may overlap while both schemas exist during migration. // may overlap while both schemas exist during migration.
isExamPrepRoute := strings.Contains(c.Route().Path, "/exam-prep/") isExamPrepRoute := true
var ( var (
lmsPractice *domain.Practice lmsPractice *domain.Practice
examPractice *domain.ExamPrepPractice examPractice *domain.ExamPrepPractice
@ -1861,7 +1861,7 @@ func (h *Handler) CompletePractice(c *fiber.Ctx) error {
Error: setErr.Error(), Error: setErr.Error(),
}) })
} }
if !strings.EqualFold(set.SetType, string(domain.QuestionSetTypePractice)) { if !strings.EqualFold(set.SetType, string(domain.QuestionSetTypePractice)) && !strings.EqualFold(set.SetType, string(domain.QuestionSetTypeQuiz)) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Practice not found"}) return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Practice not found"})
} }
if !strings.EqualFold(set.Status, "PUBLISHED") { if !strings.EqualFold(set.Status, "PUBLISHED") {

View File

@ -3,7 +3,6 @@ package handlers
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"strings"
"Rezina-Backend/internal/domain" "Rezina-Backend/internal/domain"
"Rezina-Backend/internal/repository" "Rezina-Backend/internal/repository"
@ -23,7 +22,7 @@ import (
// @Failure 400 {object} domain.ErrorResponse // @Failure 400 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse // @Failure 403 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse // @Failure 404 {object} domain.ErrorResponse
// @Router /api/v1/exam-prep/videos/engagement/heartbeat [post] // @Router /api/v1/videos/engagement/heartbeat [post]
// @Security Bearer // @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 500 {object} domain.ErrorResponse "Internal server error"
@ -44,13 +43,16 @@ func (h *Handler) RecordVideoEngagementHeartbeat(c *fiber.Ctx) error {
uid := c.Locals("user_id").(int64) uid := c.Locals("user_id").(int64)
role := c.Locals("role").(domain.Role) role := c.Locals("role").(domain.Role)
if strings.Contains(c.Route().Path, "/exam-prep/") && req.ContentKind != domain.VideoContentKindExamPrepLesson { if req.ContentKind == "lesson" {
req.ContentKind = domain.VideoContentKindExamPrepLesson
}
if req.ContentKind != domain.VideoContentKindExamPrepLesson {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Exam-prep routes accept exam-prep lesson video sessions only", Message: "Only lesson video sessions are supported",
}) })
} }
if req.ContentKind == domain.VideoContentKindLMSLesson && !strings.Contains(c.Route().Path, "/exam-prep/") { if req.ContentKind == domain.VideoContentKindLMSLesson {
les, err := h.lessonSvc.GetByID(c.Context(), req.ContentID) les, err := h.lessonSvc.GetByID(c.Context(), req.ContentID)
if err != nil { if err != nil {
if errors.Is(err, lessons.ErrLessonNotFound) { if errors.Is(err, lessons.ErrLessonNotFound) {

View File

@ -0,0 +1,66 @@
package httpserver
import (
"encoding/json"
"reflect"
"strings"
"testing"
"Rezina-Backend/docs"
)
func TestLearningSwaggerPublicHierarchy(t *testing.T) {
var spec struct {
Definitions map[string]struct {
Properties map[string]json.RawMessage `json:"properties"`
} `json:"definitions"`
Paths map[string]map[string]struct {
Tags []string `json:"tags"`
Responses map[string]json.RawMessage `json:"responses"`
} `json:"paths"`
}
if err := json.Unmarshal([]byte(docs.SwaggerInfo.ReadDoc()), &spec); err != nil {
t.Fatal(err)
}
for schema, field := range map[string]string{
"handlers.courseListData": "courses", "handlers.chapterListData": "chapters",
"handlers.lessonListData": "lessons", "handlers.quizListData": "quizzes",
} {
for _, key := range []string{field, "total_count", "limit", "offset"} {
if _, ok := spec.Definitions[schema].Properties[key]; !ok {
t.Errorf("%s missing %s", schema, key)
}
}
}
for schema, hidden := range map[string][]string{
"domain.ExamPrepCatalogCourse": {"category", "modules_count"},
"domain.ExamPrepUnit": {"catalog_course_id", "modules_count"},
"domain.ExamPrepLesson": {"unit_module_id"},
"handlers.createChapterQuizRequest": {"parents", "parent_kind", "parent_id"},
} {
for _, key := range hidden {
if _, ok := spec.Definitions[schema].Properties[key]; ok {
t.Errorf("%s exposes legacy field %s", schema, key)
}
}
}
var parentKind struct {
Enum []string `json:"enum"`
}
if err := json.Unmarshal(spec.Definitions["domain.ExamPrepPracticeParent"].Properties["parent_kind"], &parentKind); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(parentKind.Enum, []string{"COURSE", "CHAPTER", "LESSON"}) {
t.Fatalf("public parent kinds=%v", parentKind.Enum)
}
for path, operations := range spec.Paths {
if !strings.Contains(path, "/quizzes") {
continue
}
for method, operation := range operations {
if !reflect.DeepEqual(operation.Tags, []string{"quizzes"}) {
t.Errorf("%s %s is not documented as a quiz", method, path)
}
}
}
}

View File

@ -371,12 +371,12 @@ func parseRouteInt64(c *fiber.Ctx, name string) (int64, bool, error) {
} }
func (a *App) resolveExamPrepSubscriptionCategory(c *fiber.Ctx) (domain.SubscriptionCategory, bool, error) { func (a *App) resolveExamPrepSubscriptionCategory(c *fiber.Ctx) (domain.SubscriptionCategory, bool, error) {
if catalogCourseID, ok, err := parseRouteInt64(c, "catalogCourseId"); err != nil { if catalogCourseID, ok, err := parseRouteInt64(c, "courseId"); err != nil {
return "", false, err return "", false, err
} else if ok { } else if ok {
return a.examPrepCategoryByCatalogCourseID(c.Context(), catalogCourseID) return a.examPrepCategoryByCatalogCourseID(c.Context(), catalogCourseID)
} }
if unitID, ok, err := parseRouteInt64(c, "unitId"); err != nil { if unitID, ok, err := parseRouteInt64(c, "chapterId"); err != nil {
return "", false, err return "", false, err
} else if ok { } else if ok {
return a.examPrepCategoryByUnitID(c.Context(), unitID) return a.examPrepCategoryByUnitID(c.Context(), unitID)
@ -393,13 +393,13 @@ func (a *App) resolveExamPrepSubscriptionCategory(c *fiber.Ctx) (domain.Subscrip
} }
switch routePath := c.Route().Path; { switch routePath := c.Route().Path; {
case strings.Contains(routePath, "/catalog-courses/:id"): case strings.Contains(routePath, "/courses/:id"):
if id, ok, err := parseRouteInt64(c, "id"); err != nil { if id, ok, err := parseRouteInt64(c, "id"); err != nil {
return "", false, err return "", false, err
} else if ok { } else if ok {
return a.examPrepCategoryByCatalogCourseID(c.Context(), id) return a.examPrepCategoryByCatalogCourseID(c.Context(), id)
} }
case strings.Contains(routePath, "/units/:id"): case strings.Contains(routePath, "/chapters/:id"):
if id, ok, err := parseRouteInt64(c, "id"); err != nil { if id, ok, err := parseRouteInt64(c, "id"); err != nil {
return "", false, err return "", false, err
} else if ok { } else if ok {
@ -417,7 +417,7 @@ func (a *App) resolveExamPrepSubscriptionCategory(c *fiber.Ctx) (domain.Subscrip
} else if ok { } else if ok {
return a.examPrepCategoryByLessonID(c.Context(), id) return a.examPrepCategoryByLessonID(c.Context(), id)
} }
case strings.Contains(routePath, "/practices/:id"): case strings.Contains(routePath, "/practices/:id"), strings.Contains(routePath, "/quizzes/:id"):
if id, ok, err := parseRouteInt64(c, "id"); err != nil { if id, ok, err := parseRouteInt64(c, "id"); err != nil {
return "", false, err return "", false, err
} else if ok { } else if ok {

View File

@ -7,49 +7,50 @@ import (
) )
func (a *App) initAdminRoutes(api fiber.Router, h *handlers.Handler) { func (a *App) initAdminRoutes(api fiber.Router, h *handlers.Handler) {
api.Get("/chapters/:chapterId/quizzes", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_unit"), h.ListChapterQuizzes)
api.Post("/chapters/:chapterId/quizzes", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.create"), h.CreateChapterQuiz)
api.Get("/quizzes/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.get"), h.RequireChapterQuiz, h.GetChapterQuiz)
api.Get("/quizzes/:id/full", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.get"), h.RequireChapterQuiz, h.GetChapterQuizFull)
api.Put("/quizzes/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.update"), h.RequireChapterQuiz, h.UpdateChapterQuiz)
api.Put("/quizzes/:id/full", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.update"), h.RequireChapterQuiz, h.UpdateChapterQuizFull)
api.Delete("/quizzes/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.delete"), h.RequireChapterQuiz, h.DeleteChapterQuiz)
api.Get("/referrals/settings", a.adminAuthMiddleware, a.OnlyAdminAndAbove, h.GetReferralSettings) api.Get("/referrals/settings", a.adminAuthMiddleware, a.OnlyAdminAndAbove, h.GetReferralSettings)
api.Put("/referrals/settings", a.adminAuthMiddleware, a.OnlyAdminAndAbove, h.UpdateReferralSettings) api.Put("/referrals/settings", a.adminAuthMiddleware, a.OnlyAdminAndAbove, h.UpdateReferralSettings)
api.Post("/exam-prep/catalog-courses", a.adminAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.create"), h.CreateExamPrepCatalogCourse) api.Post("/courses", a.adminAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.create"), h.CreateExamPrepCatalogCourse)
api.Get("/exam-prep/catalog-courses", a.adminAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.list"), h.ListExamPrepCatalogCourses) api.Get("/courses", a.adminAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.list"), h.ListExamPrepCatalogCourses)
api.Put("/exam-prep/catalog-courses/reorder", a.adminAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.reorder"), h.ReorderExamPrepCatalogCourses) api.Put("/courses/reorder", a.adminAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.reorder"), h.ReorderExamPrepCatalogCourses)
api.Get("/exam-prep/catalog-courses/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.get"), h.GetExamPrepCatalogCourseByID) api.Get("/courses/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.get"), h.GetExamPrepCatalogCourseByID)
api.Put("/exam-prep/catalog-courses/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.update"), h.UpdateExamPrepCatalogCourse) api.Put("/courses/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.update"), h.UpdateExamPrepCatalogCourse)
api.Delete("/exam-prep/catalog-courses/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.delete"), h.DeleteExamPrepCatalogCourse) api.Delete("/courses/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.delete"), h.DeleteExamPrepCatalogCourse)
api.Post("/exam-prep/catalog-courses/:catalogCourseId/units", a.adminAuthMiddleware, a.RequirePermission("exam_prep.units.create"), h.CreateExamPrepUnit) api.Post("/courses/:courseId/chapters", a.adminAuthMiddleware, a.RequirePermission("exam_prep.units.create"), h.CreateExamPrepUnit)
api.Get("/exam-prep/catalog-courses/:catalogCourseId/units", a.adminAuthMiddleware, a.RequirePermission("exam_prep.units.list"), h.ListExamPrepUnitsByCatalogCourse) api.Get("/courses/:courseId/chapters", a.adminAuthMiddleware, a.RequirePermission("exam_prep.units.list"), h.ListExamPrepUnitsByCatalogCourse)
api.Put("/exam-prep/catalog-courses/:catalogCourseId/units/reorder", a.adminAuthMiddleware, a.RequirePermission("exam_prep.units.reorder"), h.ReorderExamPrepUnitsInCatalogCourse) api.Put("/courses/:courseId/chapters/reorder", a.adminAuthMiddleware, a.RequirePermission("exam_prep.units.reorder"), h.ReorderExamPrepUnitsInCatalogCourse)
api.Get("/exam-prep/units/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.units.get"), h.GetExamPrepUnitByID) api.Get("/chapters/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.units.get"), h.GetExamPrepUnitByID)
api.Put("/exam-prep/units/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.units.update"), h.UpdateExamPrepUnit) api.Put("/chapters/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.units.update"), h.UpdateExamPrepUnit)
api.Delete("/exam-prep/units/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.units.delete"), h.DeleteExamPrepUnit) api.Delete("/chapters/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.units.delete"), h.DeleteExamPrepUnit)
api.Post("/exam-prep/units/:unitId/modules", a.adminAuthMiddleware, a.RequirePermission("exam_prep.modules.create"), h.CreateExamPrepModule) api.Post("/chapters/:chapterId/lessons", a.adminAuthMiddleware, a.RequirePermission("exam_prep.lessons.create"), h.ResolveChapterLessonContainer, h.CreateExamPrepLesson)
api.Get("/exam-prep/units/:unitId/modules", a.adminAuthMiddleware, a.RequirePermission("exam_prep.modules.list"), h.ListExamPrepModulesByUnit) api.Get("/chapters/:chapterId/lessons", a.adminAuthMiddleware, a.RequirePermission("exam_prep.lessons.list_by_module"), h.ResolveChapterLessonContainer, h.ListExamPrepLessonsByUnitModule)
api.Put("/exam-prep/units/:unitId/modules/reorder", a.adminAuthMiddleware, a.RequirePermission("exam_prep.modules.reorder"), h.ReorderExamPrepModulesInUnit) api.Put("/chapters/:chapterId/lessons/reorder", a.adminAuthMiddleware, a.RequirePermission("exam_prep.lessons.reorder"), h.ResolveChapterLessonContainer, h.ReorderExamPrepLessonsInUnitModule)
api.Get("/exam-prep/modules/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.modules.get"), h.GetExamPrepModuleByID) api.Get("/lessons/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.lessons.get"), h.GetExamPrepLessonByID)
api.Put("/exam-prep/modules/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.modules.update"), h.UpdateExamPrepModule) api.Put("/lessons/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.lessons.update"), h.UpdateExamPrepLesson)
api.Delete("/exam-prep/modules/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.modules.delete"), h.DeleteExamPrepModule) api.Delete("/lessons/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.lessons.delete"), h.DeleteExamPrepLesson)
api.Post("/exam-prep/modules/:moduleId/lessons", a.adminAuthMiddleware, a.RequirePermission("exam_prep.lessons.create"), h.CreateExamPrepLesson) api.Get("/assessments", a.adminAuthMiddleware, a.RequirePermission("question_sets.list"), h.ListExamPrepAssessments)
api.Get("/exam-prep/modules/:moduleId/lessons", a.adminAuthMiddleware, a.RequirePermission("exam_prep.lessons.list_by_module"), h.ListExamPrepLessonsByUnitModule) api.Post("/assessments", a.adminAuthMiddleware, a.RequirePermission("question_sets.update"), h.LinkExamPrepAssessment)
api.Put("/exam-prep/modules/:moduleId/lessons/reorder", a.adminAuthMiddleware, a.RequirePermission("exam_prep.lessons.reorder"), h.ReorderExamPrepLessonsInUnitModule) api.Delete("/assessments/:questionSetId/parents/:parentKind/:parentId", a.adminAuthMiddleware, a.RequirePermission("question_sets.update"), h.UnlinkExamPrepAssessment)
api.Get("/exam-prep/lessons/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.lessons.get"), h.GetExamPrepLessonByID) api.Post("/practices", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.create"), h.CreateExamPrepPracticeFromInput)
api.Put("/exam-prep/lessons/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.lessons.update"), h.UpdateExamPrepLesson) api.Get("/practices", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.list"), h.ListAllExamPrepPractices)
api.Delete("/exam-prep/lessons/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.lessons.delete"), h.DeleteExamPrepLesson) api.Get("/courses/:courseId/practices", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_catalog_course"), h.ListExamPrepPracticesByCatalogCourse)
api.Get("/exam-prep/assessments", a.adminAuthMiddleware, a.RequirePermission("question_sets.list"), h.ListExamPrepAssessments) api.Post("/courses/:courseId/practices", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.create"), h.CreateExamPrepPracticeForCatalogCourse)
api.Post("/exam-prep/assessments", a.adminAuthMiddleware, a.RequirePermission("question_sets.update"), h.LinkExamPrepAssessment) api.Get("/chapters/:chapterId/practices", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_unit"), h.ListExamPrepPracticesByUnit)
api.Delete("/exam-prep/assessments/:questionSetId/parents/:parentKind/:parentId", a.adminAuthMiddleware, a.RequirePermission("question_sets.update"), h.UnlinkExamPrepAssessment) api.Post("/chapters/:chapterId/practices", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.create"), h.CreateExamPrepPracticeForUnit)
api.Post("/exam-prep/practices", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.create"), h.CreateExamPrepPracticeFromInput) api.Get("/lessons/:lessonId/practices", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_lesson"), h.ListExamPrepPracticesByLesson)
api.Get("/exam-prep/practices", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.list"), h.ListAllExamPrepPractices) api.Get("/practices/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.get"), h.GetExamPrepPracticeByID)
api.Get("/exam-prep/catalog-courses/:catalogCourseId/practices", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_catalog_course"), h.ListExamPrepPracticesByCatalogCourse) api.Get("/practices/:id/full", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.get"), h.GetExamPrepPracticeFull)
api.Post("/exam-prep/catalog-courses/:catalogCourseId/practices", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.create"), h.CreateExamPrepPracticeForCatalogCourse) api.Put("/practices/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPractice)
api.Get("/exam-prep/units/:unitId/practices", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_unit"), h.ListExamPrepPracticesByUnit) api.Put("/practices/:id/full", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPracticeFull)
api.Post("/exam-prep/units/:unitId/practices", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.create"), h.CreateExamPrepPracticeForUnit) api.Put("/practices/:id/parents", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPracticeParents)
api.Get("/exam-prep/lessons/:lessonId/practices", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_lesson"), h.ListExamPrepPracticesByLesson) api.Delete("/practices/:id/parents/:parentKind/:parentId", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.update"), h.UnlinkExamPrepPracticeParent)
api.Get("/exam-prep/practices/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.get"), h.GetExamPrepPracticeByID) api.Delete("/practices/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.delete"), h.DeleteExamPrepPractice)
api.Get("/exam-prep/practices/:id/full", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.get"), h.GetExamPrepPracticeFull)
api.Put("/exam-prep/practices/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPractice)
api.Put("/exam-prep/practices/:id/full", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPracticeFull)
api.Put("/exam-prep/practices/:id/parents", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPracticeParents)
api.Delete("/exam-prep/practices/:id/parents/:parentKind/:parentId", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.update"), h.UnlinkExamPrepPracticeParent)
api.Delete("/exam-prep/practices/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.delete"), h.DeleteExamPrepPractice)
api.Get("/personas", a.adminAuthMiddleware, a.RequirePermission("personas.list"), h.ListPersonas) api.Get("/personas", a.adminAuthMiddleware, a.RequirePermission("personas.list"), h.ListPersonas)
api.Post("/personas", a.adminAuthMiddleware, a.RequirePermission("personas.create"), h.CreatePersona) api.Post("/personas", a.adminAuthMiddleware, a.RequirePermission("personas.create"), h.CreatePersona)
api.Get("/personas/:id", a.adminAuthMiddleware, a.RequirePermission("personas.get"), h.GetPersona) api.Get("/personas/:id", a.adminAuthMiddleware, a.RequirePermission("personas.get"), h.GetPersona)

View File

@ -6,30 +6,34 @@ import (
) )
func (a *App) initClientRoutes(api fiber.Router, h *handlers.Handler) { func (a *App) initClientRoutes(api fiber.Router, h *handlers.Handler) {
api.Get("/catalog/courses", h.ListPublicCourses)
api.Get("/catalog/courses/:id", h.GetPublicCourse)
api.Get("/chapters/:chapterId/quizzes", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_unit"), a.RequireExamPrepSubscription(), h.ListChapterQuizzes)
api.Get("/quizzes/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.get"), a.RequireExamPrepSubscription(), h.RequireChapterQuiz, h.GetChapterQuiz)
api.Post("/progress/quizzes/:id/complete", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("progress.complete"), a.RequireExamPrepSubscription(), h.RequireChapterQuiz, h.CompleteChapterQuiz)
api.Get("/quizzes/:practiceId/questions", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("question_set_items.list"), a.RequireExamPrepSubscription(), h.RequireChapterQuiz, h.GetChapterQuizQuestions)
api.Post("/referrals/code", apiAudience("client"), a.clientAuthMiddleware, h.CreateReferralCode) api.Post("/referrals/code", apiAudience("client"), a.clientAuthMiddleware, h.CreateReferralCode)
api.Get("/referrals/code", apiAudience("client"), a.clientAuthMiddleware, h.GetReferralCode) api.Get("/referrals/code", apiAudience("client"), a.clientAuthMiddleware, h.GetReferralCode)
api.Get("/referrals/me", apiAudience("client"), a.clientAuthMiddleware, h.GetMyReferrals) api.Get("/referrals/me", apiAudience("client"), a.clientAuthMiddleware, h.GetMyReferrals)
api.Post("/referrals/apply", apiAudience("client"), a.clientAuthMiddleware, h.ApplyReferralCode) api.Post("/referrals/apply", apiAudience("client"), a.clientAuthMiddleware, h.ApplyReferralCode)
api.Get("/referrals", apiAudience("client"), a.clientAuthMiddleware, h.ListMyReferrals) api.Get("/referrals", apiAudience("client"), a.clientAuthMiddleware, h.ListMyReferrals)
api.Get("/referrals/wallet", apiAudience("client"), a.clientAuthMiddleware, h.GetReferralWallet) api.Get("/referrals/wallet", apiAudience("client"), a.clientAuthMiddleware, h.GetReferralWallet)
api.Get("/exam-prep/catalog-courses", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.list"), h.ListExamPrepCatalogCourses) api.Get("/courses", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.list"), h.ListExamPrepCatalogCourses)
api.Get("/exam-prep/catalog-courses/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.get"), h.GetExamPrepCatalogCourseByID) api.Get("/courses/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.get"), h.GetExamPrepCatalogCourseByID)
api.Get("/exam-prep/catalog-courses/:catalogCourseId/units", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.units.list"), h.ListExamPrepUnitsByCatalogCourse) api.Get("/courses/:courseId/chapters", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.units.list"), h.ListExamPrepUnitsByCatalogCourse)
api.Get("/exam-prep/units/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.units.get"), h.GetExamPrepUnitByID) api.Get("/chapters/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.units.get"), h.GetExamPrepUnitByID)
api.Get("/exam-prep/units/:unitId/modules", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.modules.list"), h.ListExamPrepModulesByUnit) api.Get("/chapters/:chapterId/lessons", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.lessons.list_by_module"), a.RequireExamPrepSubscription(), h.ResolveChapterLessonContainer, h.ListExamPrepLessonsByUnitModule)
api.Get("/exam-prep/modules/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.modules.get"), h.GetExamPrepModuleByID) api.Get("/lessons/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.lessons.get"), a.RequireExamPrepSubscription(), h.GetExamPrepLessonByID)
api.Get("/exam-prep/modules/:moduleId/lessons", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.lessons.list_by_module"), a.RequireExamPrepSubscription(), h.ListExamPrepLessonsByUnitModule) api.Get("/assessments", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("question_sets.list"), a.RequireExamPrepSubscription(), h.ListExamPrepAssessments)
api.Get("/exam-prep/lessons/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.lessons.get"), a.RequireExamPrepSubscription(), h.GetExamPrepLessonByID) api.Get("/practices", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list"), a.RequireExamPrepSubscription(), h.ListAllExamPrepPractices)
api.Get("/exam-prep/assessments", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("question_sets.list"), a.RequireExamPrepSubscription(), h.ListExamPrepAssessments) api.Get("/courses/:courseId/practices", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_catalog_course"), a.RequireExamPrepSubscription(), h.ListExamPrepPracticesByCatalogCourse)
api.Get("/exam-prep/practices", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list"), a.RequireExamPrepSubscription(), h.ListAllExamPrepPractices) api.Get("/chapters/:chapterId/practices", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_unit"), a.RequireExamPrepSubscription(), h.ListExamPrepPracticesByUnit)
api.Get("/exam-prep/catalog-courses/:catalogCourseId/practices", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_catalog_course"), a.RequireExamPrepSubscription(), h.ListExamPrepPracticesByCatalogCourse) api.Get("/lessons/:lessonId/practices", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_lesson"), a.RequireExamPrepSubscription(), h.ListExamPrepPracticesByLesson)
api.Get("/exam-prep/units/:unitId/practices", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_unit"), a.RequireExamPrepSubscription(), h.ListExamPrepPracticesByUnit) api.Get("/practices/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.get"), a.RequireExamPrepSubscription(), h.GetExamPrepPracticeByID)
api.Get("/exam-prep/lessons/:lessonId/practices", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_lesson"), a.RequireExamPrepSubscription(), h.ListExamPrepPracticesByLesson) api.Post("/progress/practices/:id/complete", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("progress.complete"), a.RequireExamPrepSubscription(), h.CompletePractice)
api.Get("/exam-prep/practices/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.get"), a.RequireExamPrepSubscription(), h.GetExamPrepPracticeByID) api.Post("/videos/engagement/heartbeat", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("videos.track_engagement"), a.RequireExamPrepSubscription(), h.RecordVideoEngagementHeartbeat)
api.Post("/exam-prep/progress/practices/:id/complete", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("progress.complete"), a.RequireExamPrepSubscription(), h.CompletePractice) api.Get("/progress-summary", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("lms.get_my_progress"), h.GetMyLMSProgressSummary)
api.Post("/exam-prep/videos/engagement/heartbeat", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("videos.track_engagement"), a.RequireExamPrepSubscription(), h.RecordVideoEngagementHeartbeat) api.Get("/practices/:practiceId/questions", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("question_set_items.list"), a.RequireExamPrepSubscription(), h.GetQuestionsByPractice)
api.Get("/exam-prep/progress-summary", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("lms.get_my_progress"), h.GetMyLMSProgressSummary)
api.Get("/exam-prep/practices/:practiceId/questions", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("question_set_items.list"), a.RequireExamPrepSubscription(), h.GetQuestionsByPractice)
api.Get("/personas", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("personas.list"), h.ListPersonas) api.Get("/personas", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("personas.list"), h.ListPersonas)
api.Get("/personas/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("personas.get"), h.GetPersona) api.Get("/personas/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("personas.get"), h.GetPersona)
api.Get("/files/url", apiAudience("client"), a.clientAuthMiddleware, h.GetFileURL) api.Get("/files/url", apiAudience("client"), a.clientAuthMiddleware, h.GetFileURL)

View File

@ -1,4 +1,8 @@
include .env include .env
.PHONY: seed_demo
seed_demo:
@go run ./cmd/demo-seed -environment development
.PHONY: test .PHONY: test
test: test:
@docker compose up -d test @docker compose up -d test

View File

@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" width="960" height="540" viewBox="0 0 960 540">
<defs><linearGradient id="bg" x2="1" y2="1"><stop stop-color="#163d35"/><stop offset="1" stop-color="#357b65"/></linearGradient></defs>
<rect width="960" height="540" fill="url(#bg)"/>
<circle cx="810" cy="90" r="220" fill="#fff" opacity=".06"/>
<circle cx="150" cy="520" r="180" fill="#e4c28f" opacity=".12"/>
<path d="M375 160q55-20 105 15q50-35 105-15v170q-55-15-105 15q-50-30-105-15z" fill="none" stroke="#e4c28f" stroke-width="9" stroke-linejoin="round"/>
<path d="M480 175v170" stroke="#e4c28f" stroke-width="7"/>
<text x="480" y="410" text-anchor="middle" font-family="sans-serif" font-size="34" fill="#fff">Learn something new with Rezina</text>
</svg>

After

Width:  |  Height:  |  Size: 763 B