RezinaLMS-BackEnd/internal/web_server/handlers/admin_user_detail_handler.go

370 lines
12 KiB
Go

package handlers
import (
"context"
"errors"
"strconv"
"Rezina-Backend/internal/domain"
lmsprogress "Rezina-Backend/internal/services/lmsprogress"
"github.com/gofiber/fiber/v2"
)
const adminUserDetailPageSize int32 = 200
// AdminGetUserSubscriptions godoc
// @Summary Get all subscription details for a user (admin)
// @Description Returns display status, active plans by category, full subscription history, and related payments
// @Tags subscriptions
// @Produce json
// @Security Bearer
// @Param user_id path int true "Target user ID"
// @Success 200 {object} domain.Response{data=domain.AdminUserSubscriptionDetails}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/users/{user_id}/subscriptions [get]
func (h *Handler) AdminGetUserSubscriptions(c *fiber.Ctx) error {
targetID, err := parseAdminTargetUserID(c)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid user ID",
Error: "user ID must be a valid positive integer",
})
}
if _, err := h.userSvc.GetUserByID(c.Context(), targetID); err != nil {
if errors.Is(err, domain.ErrUserNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "User not found",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to load user",
Error: err.Error(),
})
}
details, err := h.subscriptionsSvc.GetAdminUserSubscriptionDetails(c.Context(), targetID)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to load subscription details",
Error: err.Error(),
})
}
payments, err := h.chapaSvc.GetPaymentsByUser(c.Context(), targetID, 500, 0)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to load payment history",
Error: err.Error(),
})
}
details.Payments = mapAdminUserSubscriptionPayments(payments)
return c.JSON(domain.Response{
Message: "User subscription details retrieved successfully",
Data: details,
Success: true,
StatusCode: fiber.StatusOK,
})
}
// AdminGetUserLearningActivityDetails godoc
// @Summary Get full learning activity for a user (admin)
// @Description Returns the unified catalog-course learning tree, progress summary, and recent activity timeline
// @Tags exam-prep
// @Produce json
// @Security Bearer
// @Param user_id path int true "Target user ID"
// @Param limit query int false "Max recent-activity items (default 40, max 120)"
// @Param include_practices query bool false "Include practice completions in recent-activity feed"
// @Success 200 {object} domain.Response{data=domain.AdminUserLearningActivityDetails}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/users/{user_id}/learning-activity [get]
func (h *Handler) AdminGetUserLearningActivityDetails(c *fiber.Ctx) error {
targetID, err := parseAdminTargetUserID(c)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid user ID",
Error: "user ID must be a valid positive integer",
})
}
if _, err := h.userSvc.GetUserByID(c.Context(), targetID); err != nil {
if errors.Is(err, domain.ErrUserNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "User not found",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to load user",
Error: err.Error(),
})
}
limit := 40
if ls := c.Query("limit"); ls != "" {
n, err := strconv.Atoi(ls)
if err != nil || n < 1 {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid limit",
Error: "limit must be a positive integer",
})
}
limit = n
}
includePractices := c.Query("include_practices") == "true" || c.Query("include_practices") == "1"
ctx := lmsprogress.WithRequestMemo(c.Context())
examPrepProgress, err := h.buildExamPrepProgressSummary(ctx, domain.RoleStudent, targetID, true)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to load exam prep progress summary",
Error: err.Error(),
})
}
examPrepCompletions, err := h.lmsProgressSvc.AdminUserExamPrepLearningActivityTree(c.Context(), targetID)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to load exam prep completion tree",
Error: err.Error(),
})
}
recentActivity, err := h.lmsProgressSvc.AdminUserRecentActivity(c.Context(), targetID, limit, includePractices)
if err != nil {
if errors.Is(err, domain.ErrUserNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "User not found",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to load recent activity",
Error: err.Error(),
})
}
return c.JSON(domain.Response{
Message: "User learning activity retrieved successfully",
Data: domain.AdminUserLearningActivityDetails{
UserID: targetID,
ExamPrep: domain.AdminUserExamPrepLearningSection{
Progress: examPrepProgress,
Completions: examPrepCompletions,
},
RecentActivity: recentActivity,
},
Success: true,
StatusCode: fiber.StatusOK,
})
}
func parseAdminTargetUserID(c *fiber.Ctx) (int64, error) {
targetIDStr := c.Params("user_id")
targetID, err := strconv.ParseInt(targetIDStr, 10, 64)
if err != nil {
return 0, err
}
if targetID <= 0 {
return 0, strconv.ErrRange
}
return targetID, nil
}
func mapAdminUserSubscriptionPayments(payments []domain.Payment) []domain.AdminUserSubscriptionPayment {
if len(payments) == 0 {
return []domain.AdminUserSubscriptionPayment{}
}
out := make([]domain.AdminUserSubscriptionPayment, len(payments))
for i, p := range payments {
out[i] = domain.AdminUserSubscriptionPayment{
ID: p.ID,
PlanID: p.PlanID,
PlanName: p.PlanName,
SubscriptionID: p.SubscriptionID,
Amount: p.Amount,
Currency: p.Currency,
PaymentMethod: p.PaymentMethod,
Status: p.Status,
PaidAt: p.PaidAt,
ExpiresAt: p.ExpiresAt,
CreatedAt: p.CreatedAt,
}
}
return out
}
func (h *Handler) buildExamPrepProgressSummary(ctx context.Context, role domain.Role, userID int64, publishedOnly bool) (domain.ExamPrepProgressSummary, error) {
ctx = lmsprogress.WithRequestMemo(ctx)
catalogCourses, err := h.listAllExamPrepCatalogCourses(ctx, publishedOnly)
if err != nil {
return domain.ExamPrepProgressSummary{}, err
}
summary := domain.ExamPrepProgressSummary{
CatalogCourses: make([]domain.ExamPrepProgressSummaryCatalogCourse, 0, len(catalogCourses)),
}
for i := range catalogCourses {
if err := h.lmsProgressSvc.ApplyExamPrepAccessCatalogCourse(ctx, role, userID, &catalogCourses[i]); err != nil {
return domain.ExamPrepProgressSummary{}, err
}
units, err := h.listAllExamPrepUnitsByCatalogCourse(ctx, catalogCourses[i].ID, publishedOnly)
if err != nil {
return domain.ExamPrepProgressSummary{}, err
}
courseSummary := domain.ExamPrepProgressSummaryCatalogCourse{
ID: catalogCourses[i].ID,
Name: catalogCourses[i].Name,
Access: catalogCourses[i].Access,
Units: make([]domain.ExamPrepProgressSummaryUnit, 0, len(units)),
}
for j := range units {
if err := h.lmsProgressSvc.ApplyExamPrepAccessUnit(ctx, role, userID, &units[j]); err != nil {
return domain.ExamPrepProgressSummary{}, err
}
modules, err := h.listAllExamPrepModulesByUnit(ctx, units[j].ID, publishedOnly)
if err != nil {
return domain.ExamPrepProgressSummary{}, err
}
unitSummary := domain.ExamPrepProgressSummaryUnit{
ID: units[j].ID,
CatalogCourseID: units[j].CatalogCourseID,
Name: units[j].Name,
Access: units[j].Access,
Modules: make([]domain.ExamPrepProgressSummaryModule, 0, len(modules)),
}
for k := range modules {
if err := h.lmsProgressSvc.ApplyExamPrepAccessModule(ctx, role, userID, &modules[k]); err != nil {
return domain.ExamPrepProgressSummary{}, err
}
lessons, err := h.listAllExamPrepLessonsByModule(ctx, modules[k].ID, publishedOnly)
if err != nil {
return domain.ExamPrepProgressSummary{}, err
}
moduleSummary := domain.ExamPrepProgressSummaryModule{
ID: modules[k].ID,
UnitID: modules[k].UnitID,
Name: modules[k].Name,
Access: modules[k].Access,
Lessons: make([]domain.ExamPrepProgressSummaryLesson, 0, len(lessons)),
}
for m := range lessons {
if err := h.lmsProgressSvc.ApplyExamPrepAccessLesson(ctx, role, userID, &lessons[m]); err != nil {
return domain.ExamPrepProgressSummary{}, err
}
moduleSummary.Lessons = append(moduleSummary.Lessons, domain.ExamPrepProgressSummaryLesson{
ID: lessons[m].ID,
ModuleID: lessons[m].UnitModuleID,
Title: lessons[m].Title,
Access: lessons[m].Access,
})
}
unitSummary.Modules = append(unitSummary.Modules, moduleSummary)
}
courseSummary.Units = append(courseSummary.Units, unitSummary)
}
summary.CatalogCourses = append(summary.CatalogCourses, courseSummary)
}
return summary, nil
}
func (h *Handler) listAllExamPrepCatalogCourses(ctx context.Context, publishedOnly bool) ([]domain.ExamPrepCatalogCourse, error) {
var (
all []domain.ExamPrepCatalogCourse
offset int32
)
for {
items, total, err := h.examPrepSvc.ListCatalogCourses(ctx, publishedOnly, adminUserDetailPageSize, offset)
if err != nil {
return nil, err
}
all = append(all, items...)
if len(items) == 0 || int64(len(all)) >= total {
if all == nil {
return []domain.ExamPrepCatalogCourse{}, nil
}
return all, nil
}
offset += adminUserDetailPageSize
}
}
func (h *Handler) listAllExamPrepUnitsByCatalogCourse(ctx context.Context, catalogCourseID int64, publishedOnly bool) ([]domain.ExamPrepUnit, error) {
var (
all []domain.ExamPrepUnit
offset int32
)
for {
items, total, err := h.examPrepSvc.ListUnitsByCatalogCourse(ctx, catalogCourseID, publishedOnly, adminUserDetailPageSize, offset)
if err != nil {
return nil, err
}
all = append(all, items...)
if len(items) == 0 || int64(len(all)) >= total {
if all == nil {
return []domain.ExamPrepUnit{}, nil
}
return all, nil
}
offset += adminUserDetailPageSize
}
}
func (h *Handler) listAllExamPrepModulesByUnit(ctx context.Context, unitID int64, publishedOnly bool) ([]domain.ExamPrepModule, error) {
var (
all []domain.ExamPrepModule
offset int32
)
for {
items, total, err := h.examPrepSvc.ListModulesByUnit(ctx, unitID, publishedOnly, adminUserDetailPageSize, offset)
if err != nil {
return nil, err
}
all = append(all, items...)
if len(items) == 0 || int64(len(all)) >= total {
if all == nil {
return []domain.ExamPrepModule{}, nil
}
return all, nil
}
offset += adminUserDetailPageSize
}
}
func (h *Handler) listAllExamPrepLessonsByModule(ctx context.Context, moduleID int64, publishedOnly bool) ([]domain.ExamPrepLesson, error) {
var (
all []domain.ExamPrepLesson
offset int32
)
for {
items, total, err := h.examPrepSvc.ListLessonsByUnitModule(ctx, moduleID, publishedOnly, adminUserDetailPageSize, offset)
if err != nil {
return nil, err
}
all = append(all, items...)
if len(items) == 0 || int64(len(all)) >= total {
if all == nil {
return []domain.ExamPrepLesson{}, nil
}
return all, nil
}
offset += adminUserDetailPageSize
}
}