From 8b6c6ea17fdb9649655f4e8dadc6f0a60c1830a3 Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Fri, 19 Jun 2026 01:48:06 -0700 Subject: [PATCH] feat: add global GET /api/v1/practices list endpoint Co-authored-by: Cursor --- db/query/lms_practices.sql | 29 ++++++ gen/db/lms_practices.sql.go | 88 +++++++++++++++++++ internal/ports/lms_practice.go | 1 + internal/repository/lms_practices.go | 32 +++++++ internal/services/practices/service.go | 5 ++ internal/services/rbac/seeds.go | 2 +- .../web_server/handlers/practice_handler.go | 35 ++++++++ internal/web_server/routes.go | 1 + 8 files changed, 192 insertions(+), 1 deletion(-) diff --git a/db/query/lms_practices.sql b/db/query/lms_practices.sql index 152cedd2..7bb256fe 100644 --- a/db/query/lms_practices.sql +++ b/db/query/lms_practices.sql @@ -88,6 +88,35 @@ WHERE lpp.parent_kind = 'LESSON' ORDER BY p.created_at DESC LIMIT $2 OFFSET $3; +-- name: ListAllLmsPractices :many +SELECT + COUNT(*) OVER () AS total_count, + p.id, + p.title, + p.story_description, + p.story_image, + p.persona_id, + p.question_set_id, + p.quick_tips, + p.publish_status, + p.created_at, + p.updated_at +FROM lms_practices p +WHERE ( + sqlc.arg('published_only')::boolean = FALSE + OR p.publish_status = 'PUBLISHED'::TEXT + ) + AND ( + sqlc.arg('unlinked_only')::boolean = FALSE + OR NOT EXISTS ( + SELECT 1 + FROM lms_practice_parents lpp + WHERE lpp.practice_id = p.id + ) + ) +ORDER BY p.created_at DESC +LIMIT $1 OFFSET $2; + -- name: UpdateLmsPractice :one UPDATE lms_practices SET diff --git a/gen/db/lms_practices.sql.go b/gen/db/lms_practices.sql.go index db0afbea..01ea080a 100644 --- a/gen/db/lms_practices.sql.go +++ b/gen/db/lms_practices.sql.go @@ -156,6 +156,94 @@ func (q *Queries) GetLmsPracticeByQuestionSetID(ctx context.Context, questionSet return i, err } +const ListAllLmsPractices = `-- name: ListAllLmsPractices :many +SELECT + COUNT(*) OVER () AS total_count, + p.id, + p.title, + p.story_description, + p.story_image, + p.persona_id, + p.question_set_id, + p.quick_tips, + p.publish_status, + p.created_at, + p.updated_at +FROM lms_practices p +WHERE ( + $3::boolean = FALSE + OR p.publish_status = 'PUBLISHED'::TEXT + ) + AND ( + $4::boolean = FALSE + OR NOT EXISTS ( + SELECT 1 + FROM lms_practice_parents lpp + WHERE lpp.practice_id = p.id + ) + ) +ORDER BY p.created_at DESC +LIMIT $1 OFFSET $2 +` + +type ListAllLmsPracticesParams struct { + Limit int32 `json:"limit"` + Offset int32 `json:"offset"` + PublishedOnly bool `json:"published_only"` + UnlinkedOnly bool `json:"unlinked_only"` +} + +type ListAllLmsPracticesRow struct { + TotalCount int64 `json:"total_count"` + ID int64 `json:"id"` + Title string `json:"title"` + StoryDescription pgtype.Text `json:"story_description"` + StoryImage pgtype.Text `json:"story_image"` + PersonaID pgtype.Int8 `json:"persona_id"` + QuestionSetID int64 `json:"question_set_id"` + QuickTips pgtype.Text `json:"quick_tips"` + PublishStatus string `json:"publish_status"` + CreatedAt pgtype.Timestamptz `json:"created_at"` + UpdatedAt pgtype.Timestamptz `json:"updated_at"` +} + +func (q *Queries) ListAllLmsPractices(ctx context.Context, arg ListAllLmsPracticesParams) ([]ListAllLmsPracticesRow, error) { + rows, err := q.db.Query(ctx, ListAllLmsPractices, + arg.Limit, + arg.Offset, + arg.PublishedOnly, + arg.UnlinkedOnly, + ) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListAllLmsPracticesRow + for rows.Next() { + var i ListAllLmsPracticesRow + if err := rows.Scan( + &i.TotalCount, + &i.ID, + &i.Title, + &i.StoryDescription, + &i.StoryImage, + &i.PersonaID, + &i.QuestionSetID, + &i.QuickTips, + &i.PublishStatus, + &i.CreatedAt, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const ListLmsPracticesByCourseID = `-- name: ListLmsPracticesByCourseID :many SELECT COUNT(*) OVER () AS total_count, diff --git a/internal/ports/lms_practice.go b/internal/ports/lms_practice.go index bc20a7b9..90b6b71f 100644 --- a/internal/ports/lms_practice.go +++ b/internal/ports/lms_practice.go @@ -23,6 +23,7 @@ type LmsPracticeStore interface { ListLmsPracticesByCourseID(ctx context.Context, courseID int64, publishedOnly bool, limit, offset int32) ([]domain.Practice, int64, error) ListLmsPracticesByModuleID(ctx context.Context, moduleID int64, publishedOnly bool, limit, offset int32) ([]domain.Practice, int64, error) ListLmsPracticesByLessonID(ctx context.Context, lessonID int64, publishedOnly bool, limit, offset int32) ([]domain.Practice, int64, error) + ListAllLmsPractices(ctx context.Context, publishedOnly, unlinkedOnly bool, limit, offset int32) ([]domain.Practice, int64, error) UpdateLmsPractice(ctx context.Context, id int64, input domain.UpdatePracticeInput) (domain.Practice, error) ReplaceLmsPracticeParents(ctx context.Context, practiceID int64, parents []domain.PracticeParent) error DeleteLmsPractice(ctx context.Context, id int64) error diff --git a/internal/repository/lms_practices.go b/internal/repository/lms_practices.go index d105b707..2867ad60 100644 --- a/internal/repository/lms_practices.go +++ b/internal/repository/lms_practices.go @@ -299,6 +299,38 @@ func (s *Store) ListLmsPracticesByLessonID(ctx context.Context, lessonID int64, return out, total, nil } +func (s *Store) ListAllLmsPractices(ctx context.Context, publishedOnly, unlinkedOnly bool, limit, offset int32) ([]domain.Practice, int64, error) { + rows, err := s.queries.ListAllLmsPractices(ctx, dbgen.ListAllLmsPracticesParams{ + PublishedOnly: publishedOnly, + UnlinkedOnly: unlinkedOnly, + Limit: limit, + Offset: offset, + }) + if err != nil { + return nil, 0, err + } + if len(rows) == 0 { + return []domain.Practice{}, 0, nil + } + var total int64 + out := make([]domain.Practice, 0, len(rows)) + for i, r := range rows { + if i == 0 { + total = r.TotalCount + } + out = append(out, lmsPracticeFromListRow( + r.ID, r.QuestionSetID, r.PublishStatus, r.Title, + r.StoryDescription, r.StoryImage, r.QuickTips, + r.PersonaID, r.CreatedAt, r.UpdatedAt, + )) + } + out, err = s.attachParentsToPractices(ctx, out) + if err != nil { + return nil, 0, err + } + return out, total, nil +} + func (s *Store) UpdateLmsPractice(ctx context.Context, id int64, input domain.UpdatePracticeInput) (domain.Practice, error) { var titleText pgtype.Text if input.Title != nil { diff --git a/internal/services/practices/service.go b/internal/services/practices/service.go index 1ff7fcb3..7d0e3330 100644 --- a/internal/services/practices/service.go +++ b/internal/services/practices/service.go @@ -215,6 +215,11 @@ func (s *Service) ListByLesson(ctx context.Context, lessonID int64, publishedOnl return s.practices.ListLmsPracticesByLessonID(ctx, lessonID, publishedOnly, limit, offset) } +func (s *Service) ListAll(ctx context.Context, publishedOnly, unlinkedOnly bool, limit, offset int32) ([]domain.Practice, int64, error) { + limit, offset = clampPracticePage(limit, offset) + return s.practices.ListAllLmsPractices(ctx, publishedOnly, unlinkedOnly, limit, offset) +} + func (s *Service) Update(ctx context.Context, id int64, input domain.UpdatePracticeInput) (domain.Practice, error) { if input.QuestionSetID != nil { if err := s.validateQuestionSet(ctx, *input.QuestionSetID); err != nil { diff --git a/internal/services/rbac/seeds.go b/internal/services/rbac/seeds.go index 5cefcee5..609039a9 100644 --- a/internal/services/rbac/seeds.go +++ b/internal/services/rbac/seeds.go @@ -83,7 +83,7 @@ var AllPermissions = []domain.PermissionSeed{ // Practices (LMS, scoped to course, module, or lesson) {Key: "practices.create", Name: "Create Practice", Description: "Create a practice", GroupName: "Practices"}, {Key: "practices.get", Name: "Get Practice", Description: "Get a practice by ID", GroupName: "Practices"}, - {Key: "practices.list", Name: "List Practices", Description: "List practices by course, module, or lesson", GroupName: "Practices"}, + {Key: "practices.list", Name: "List Practices", Description: "List practices globally or by course, module, or lesson", GroupName: "Practices"}, {Key: "practices.update", Name: "Update Practice", Description: "Update a practice", GroupName: "Practices"}, {Key: "practices.delete", Name: "Delete Practice", Description: "Delete a practice", GroupName: "Practices"}, diff --git a/internal/web_server/handlers/practice_handler.go b/internal/web_server/handlers/practice_handler.go index 0bf23cbe..ee046c42 100644 --- a/internal/web_server/handlers/practice_handler.go +++ b/internal/web_server/handlers/practice_handler.go @@ -71,6 +71,41 @@ func (h *Handler) CreatePractice(c *fiber.Ctx) error { }) } +// ListPractices godoc +// @Tags practices +// @Param limit query int false "Page size (default 20, max 200)" +// @Param offset query int false "Page offset (default 0)" +// @Param unlinked_only query bool false "When true, return only practices with no parent links (admin)" +// @Router /api/v1/practices [get] +func (h *Handler) ListPractices(c *fiber.Ctx) error { + limit, _ := strconv.Atoi(c.Query("limit", "20")) + offset, _ := strconv.Atoi(c.Query("offset", "0")) + role, _ := c.Locals("role").(domain.Role) + publishedOnly := role.IsCustomerLearnerRole() || !h.canManageLMSPractices(c) + unlinkedOnly := false + if h.canManageLMSPractices(c) { + unlinkedOnly, _ = strconv.ParseBool(c.Query("unlinked_only", "false")) + } + items, total, err := h.practiceSvc.ListAll(c.Context(), publishedOnly, unlinkedOnly, int32(limit), int32(offset)) + if err != nil { + return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to list practices", Error: err.Error()}) + } + if err := h.applyPracticeAccess(c.Context(), c, items); err != nil { + return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to build practices", Error: err.Error()}) + } + return c.JSON(domain.Response{ + Message: "Practices retrieved successfully", + Data: fiber.Map{ + "practices": items, + "total_count": total, + "limit": limit, + "offset": offset, + }, + Success: true, + StatusCode: fiber.StatusOK, + }) +} + // ListPracticesByCourse godoc // @Tags practices // @Param id path int true "Course ID" diff --git a/internal/web_server/routes.go b/internal/web_server/routes.go index 3cf3ac02..d2277579 100644 --- a/internal/web_server/routes.go +++ b/internal/web_server/routes.go @@ -160,6 +160,7 @@ func (a *App) initAppRoutes() { groupV1.Delete("/lessons/:id", a.authMiddleware, a.RequirePermission("lessons.delete"), h.DeleteLesson) groupV1.Post("/practices", a.authMiddleware, a.RequirePermission("practices.create"), h.CreatePractice) + groupV1.Get("/practices", a.authMiddleware, a.RequirePermission("practices.list"), h.ListPractices) groupV1.Get("/practices/:id", a.authMiddleware, a.RequireLMSSubscriptionUnlessFree(), a.RequirePermission("practices.get"), h.GetPractice) groupV1.Get("/practices/:id/full", a.authMiddleware, a.RequireLMSSubscriptionUnlessFree(), a.RequirePermission("practices.get"), h.GetLmsPracticeFull) groupV1.Put("/practices/:id/parents", a.authMiddleware, a.RequirePermission("practices.update"), h.UpdatePracticeParents)