From d3b9cbf204dd09f3b43c57b78e82024a5be40391 Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Sun, 14 Jun 2026 04:33:46 -0700 Subject: [PATCH] feat: add admin user subscriptions and learning activity endpoints Expose GET /admin/users/:user_id/subscriptions with full plan history and payments, and GET /admin/users/:user_id/learning-activity with LMS and exam-prep progress, completions, and recent timeline. Co-authored-by: Cursor --- .../000086_subscriptions_get_by_user.down.sql | 8 + .../000086_subscriptions_get_by_user.up.sql | 14 + db/query/exam_prep_admin_activity.sql | 47 +++ db/query/subscriptions.sql | 31 ++ gen/db/exam_prep_admin_activity.sql.go | 115 +++++ gen/db/subscriptions.sql.go | 155 +++++++ .../domain/admin_user_learning_activity.go | 97 +++++ .../domain/admin_user_subscription_details.go | 52 +++ internal/domain/subscriptions.go | 1 + internal/ports/subscriptions.go | 2 + .../repository/exam_prep_admin_activity.go | 11 + internal/repository/subscriptions.go | 121 ++++-- .../lmsprogress/admin_exam_prep_learning.go | 167 ++++++++ internal/services/rbac/seeds.go | 3 +- internal/services/subscriptions/service.go | 106 +++++ .../handlers/admin_user_detail_handler.go | 395 ++++++++++++++++++ internal/web_server/routes.go | 2 + 17 files changed, 1289 insertions(+), 38 deletions(-) create mode 100644 db/migrations/000086_subscriptions_get_by_user.down.sql create mode 100644 db/migrations/000086_subscriptions_get_by_user.up.sql create mode 100644 db/query/exam_prep_admin_activity.sql create mode 100644 gen/db/exam_prep_admin_activity.sql.go create mode 100644 internal/domain/admin_user_learning_activity.go create mode 100644 internal/domain/admin_user_subscription_details.go create mode 100644 internal/repository/exam_prep_admin_activity.go create mode 100644 internal/services/lmsprogress/admin_exam_prep_learning.go create mode 100644 internal/web_server/handlers/admin_user_detail_handler.go diff --git a/db/migrations/000086_subscriptions_get_by_user.down.sql b/db/migrations/000086_subscriptions_get_by_user.down.sql new file mode 100644 index 00000000..99501b5f --- /dev/null +++ b/db/migrations/000086_subscriptions_get_by_user.down.sql @@ -0,0 +1,8 @@ +DELETE FROM role_permissions rp +USING roles r, permissions p +WHERE rp.role_id = r.id + AND rp.permission_id = p.id + AND r.name = 'ADMIN' + AND p.key = 'subscriptions.get_by_user'; + +DELETE FROM permissions WHERE key = 'subscriptions.get_by_user'; diff --git a/db/migrations/000086_subscriptions_get_by_user.up.sql b/db/migrations/000086_subscriptions_get_by_user.up.sql new file mode 100644 index 00000000..3cb80c5d --- /dev/null +++ b/db/migrations/000086_subscriptions_get_by_user.up.sql @@ -0,0 +1,14 @@ +INSERT INTO permissions (key, name, description, group_name) VALUES + ('subscriptions.get_by_user', 'Get User Subscriptions (Admin)', 'Get full subscription details for a user', 'Subscriptions') +ON CONFLICT (key) DO UPDATE SET + name = EXCLUDED.name, + description = EXCLUDED.description, + group_name = EXCLUDED.group_name; + +INSERT INTO role_permissions (role_id, permission_id) +SELECT r.id, p.id +FROM roles r +CROSS JOIN permissions p +WHERE r.name = 'ADMIN' + AND p.key = 'subscriptions.get_by_user' +ON CONFLICT DO NOTHING; diff --git a/db/query/exam_prep_admin_activity.sql b/db/query/exam_prep_admin_activity.sql new file mode 100644 index 00000000..3f7fc189 --- /dev/null +++ b/db/query/exam_prep_admin_activity.sql @@ -0,0 +1,47 @@ +-- Exam-prep learning activity for admin: completed published practices grouped by hierarchy. + +-- name: ListUserExamPrepFlatLearningActivityByUser :many +SELECT + cc.id AS catalog_course_id, + cc.name AS catalog_course_name, + cc.sort_order AS catalog_course_sort_order, + u.id AS unit_id, + u.name AS unit_name, + u.sort_order AS unit_sort_order, + m.id AS module_id, + m.name AS module_name, + m.sort_order AS module_sort_order, + l.id AS lesson_id, + l.title AS lesson_title, + l.sort_order AS lesson_sort_order, + p.id AS exam_prep_practice_id, + p.title AS practice_title, + upp.completed_at AS activity_at +FROM + user_practice_progress upp + INNER JOIN exam_prep.lesson_practices p ON p.question_set_id = upp.question_set_id + AND p.publish_status = 'PUBLISHED' + INNER JOIN question_sets qs ON qs.id = p.question_set_id + AND qs.set_type = 'PRACTICE' + AND qs.status = 'PUBLISHED' + INNER JOIN exam_prep.unit_module_lessons l ON l.id = p.unit_module_lesson_id + AND l.publish_status = 'PUBLISHED' + INNER JOIN exam_prep.unit_modules m ON m.id = l.unit_module_id + AND m.publish_status = 'PUBLISHED' + INNER JOIN exam_prep.units u ON u.id = m.unit_id + AND u.publish_status = 'PUBLISHED' + INNER JOIN exam_prep.catalog_courses cc ON cc.id = u.catalog_course_id + AND cc.publish_status = 'PUBLISHED' +WHERE + upp.user_id = $1 + AND upp.completed_at IS NOT NULL +ORDER BY + cc.sort_order, + cc.id, + u.sort_order, + u.id, + m.sort_order, + m.id, + l.sort_order, + l.id, + upp.completed_at; diff --git a/db/query/subscriptions.sql b/db/query/subscriptions.sql index 4944f45c..7ae74795 100644 --- a/db/query/subscriptions.sql +++ b/db/query/subscriptions.sql @@ -115,6 +115,7 @@ LIMIT 1; SELECT us.*, sp.name AS plan_name, + sp.category AS plan_category, sp.duration_value, sp.duration_unit, sp.price, @@ -126,6 +127,36 @@ ORDER BY us.created_at DESC LIMIT sqlc.narg('limit')::INT OFFSET sqlc.narg('offset')::INT; +-- name: ListAllUserSubscriptionsByUserID :many +SELECT + us.*, + sp.name AS plan_name, + sp.category AS plan_category, + sp.duration_value, + sp.duration_unit, + sp.price, + sp.currency +FROM user_subscriptions us +JOIN subscription_plans sp ON sp.id = us.plan_id +WHERE us.user_id = $1 +ORDER BY us.created_at DESC; + +-- name: ListActiveSubscriptionsByUserID :many +SELECT + us.*, + sp.name AS plan_name, + sp.category AS plan_category, + sp.duration_value, + sp.duration_unit, + sp.price, + sp.currency +FROM user_subscriptions us +JOIN subscription_plans sp ON sp.id = us.plan_id +WHERE us.user_id = $1 + AND us.status = 'ACTIVE' + AND us.expires_at > CURRENT_TIMESTAMP +ORDER BY us.expires_at DESC; + -- name: CountUserSubscriptions :one SELECT COUNT(*) FROM user_subscriptions WHERE user_id = $1; diff --git a/gen/db/exam_prep_admin_activity.sql.go b/gen/db/exam_prep_admin_activity.sql.go new file mode 100644 index 00000000..cce1b16e --- /dev/null +++ b/gen/db/exam_prep_admin_activity.sql.go @@ -0,0 +1,115 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.30.0 +// source: exam_prep_admin_activity.sql + +package dbgen + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const ListUserExamPrepFlatLearningActivityByUser = `-- name: ListUserExamPrepFlatLearningActivityByUser :many + +SELECT + cc.id AS catalog_course_id, + cc.name AS catalog_course_name, + cc.sort_order AS catalog_course_sort_order, + u.id AS unit_id, + u.name AS unit_name, + u.sort_order AS unit_sort_order, + m.id AS module_id, + m.name AS module_name, + m.sort_order AS module_sort_order, + l.id AS lesson_id, + l.title AS lesson_title, + l.sort_order AS lesson_sort_order, + p.id AS exam_prep_practice_id, + p.title AS practice_title, + upp.completed_at AS activity_at +FROM + user_practice_progress upp + INNER JOIN exam_prep.lesson_practices p ON p.question_set_id = upp.question_set_id + AND p.publish_status = 'PUBLISHED' + INNER JOIN question_sets qs ON qs.id = p.question_set_id + AND qs.set_type = 'PRACTICE' + AND qs.status = 'PUBLISHED' + INNER JOIN exam_prep.unit_module_lessons l ON l.id = p.unit_module_lesson_id + AND l.publish_status = 'PUBLISHED' + INNER JOIN exam_prep.unit_modules m ON m.id = l.unit_module_id + AND m.publish_status = 'PUBLISHED' + INNER JOIN exam_prep.units u ON u.id = m.unit_id + AND u.publish_status = 'PUBLISHED' + INNER JOIN exam_prep.catalog_courses cc ON cc.id = u.catalog_course_id + AND cc.publish_status = 'PUBLISHED' +WHERE + upp.user_id = $1 + AND upp.completed_at IS NOT NULL +ORDER BY + cc.sort_order, + cc.id, + u.sort_order, + u.id, + m.sort_order, + m.id, + l.sort_order, + l.id, + upp.completed_at +` + +type ListUserExamPrepFlatLearningActivityByUserRow struct { + CatalogCourseID int64 `json:"catalog_course_id"` + CatalogCourseName string `json:"catalog_course_name"` + CatalogCourseSortOrder int32 `json:"catalog_course_sort_order"` + UnitID int64 `json:"unit_id"` + UnitName string `json:"unit_name"` + UnitSortOrder int32 `json:"unit_sort_order"` + ModuleID int64 `json:"module_id"` + ModuleName string `json:"module_name"` + ModuleSortOrder int32 `json:"module_sort_order"` + LessonID int64 `json:"lesson_id"` + LessonTitle string `json:"lesson_title"` + LessonSortOrder int32 `json:"lesson_sort_order"` + ExamPrepPracticeID int64 `json:"exam_prep_practice_id"` + PracticeTitle string `json:"practice_title"` + ActivityAt pgtype.Timestamptz `json:"activity_at"` +} + +// Exam-prep learning activity for admin: completed published practices grouped by hierarchy. +func (q *Queries) ListUserExamPrepFlatLearningActivityByUser(ctx context.Context, userID int64) ([]ListUserExamPrepFlatLearningActivityByUserRow, error) { + rows, err := q.db.Query(ctx, ListUserExamPrepFlatLearningActivityByUser, userID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListUserExamPrepFlatLearningActivityByUserRow + for rows.Next() { + var i ListUserExamPrepFlatLearningActivityByUserRow + if err := rows.Scan( + &i.CatalogCourseID, + &i.CatalogCourseName, + &i.CatalogCourseSortOrder, + &i.UnitID, + &i.UnitName, + &i.UnitSortOrder, + &i.ModuleID, + &i.ModuleName, + &i.ModuleSortOrder, + &i.LessonID, + &i.LessonTitle, + &i.LessonSortOrder, + &i.ExamPrepPracticeID, + &i.PracticeTitle, + &i.ActivityAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/gen/db/subscriptions.sql.go b/gen/db/subscriptions.sql.go index b8dc4b98..8575469d 100644 --- a/gen/db/subscriptions.sql.go +++ b/gen/db/subscriptions.sql.go @@ -476,6 +476,7 @@ const GetUserSubscriptionHistory = `-- name: GetUserSubscriptionHistory :many SELECT us.id, us.user_id, us.plan_id, us.starts_at, us.expires_at, us.status, us.payment_reference, us.payment_method, us.auto_renew, us.cancelled_at, us.created_at, us.updated_at, sp.name AS plan_name, + sp.category AS plan_category, sp.duration_value, sp.duration_unit, sp.price, @@ -508,6 +509,7 @@ type GetUserSubscriptionHistoryRow struct { CreatedAt pgtype.Timestamptz `json:"created_at"` UpdatedAt pgtype.Timestamptz `json:"updated_at"` PlanName string `json:"plan_name"` + PlanCategory string `json:"plan_category"` DurationValue int32 `json:"duration_value"` DurationUnit string `json:"duration_unit"` Price pgtype.Numeric `json:"price"` @@ -537,6 +539,7 @@ func (q *Queries) GetUserSubscriptionHistory(ctx context.Context, arg GetUserSub &i.CreatedAt, &i.UpdatedAt, &i.PlanName, + &i.PlanCategory, &i.DurationValue, &i.DurationUnit, &i.Price, @@ -630,6 +633,158 @@ func (q *Queries) ListActiveSubscriptionPlans(ctx context.Context) ([]Subscripti return items, nil } +const ListActiveSubscriptionsByUserID = `-- name: ListActiveSubscriptionsByUserID :many +SELECT + us.id, us.user_id, us.plan_id, us.starts_at, us.expires_at, us.status, us.payment_reference, us.payment_method, us.auto_renew, us.cancelled_at, us.created_at, us.updated_at, + sp.name AS plan_name, + sp.category AS plan_category, + sp.duration_value, + sp.duration_unit, + sp.price, + sp.currency +FROM user_subscriptions us +JOIN subscription_plans sp ON sp.id = us.plan_id +WHERE us.user_id = $1 + AND us.status = 'ACTIVE' + AND us.expires_at > CURRENT_TIMESTAMP +ORDER BY us.expires_at DESC +` + +type ListActiveSubscriptionsByUserIDRow struct { + ID int64 `json:"id"` + UserID int64 `json:"user_id"` + PlanID int64 `json:"plan_id"` + StartsAt pgtype.Timestamptz `json:"starts_at"` + ExpiresAt pgtype.Timestamptz `json:"expires_at"` + Status string `json:"status"` + PaymentReference pgtype.Text `json:"payment_reference"` + PaymentMethod pgtype.Text `json:"payment_method"` + AutoRenew bool `json:"auto_renew"` + CancelledAt pgtype.Timestamptz `json:"cancelled_at"` + CreatedAt pgtype.Timestamptz `json:"created_at"` + UpdatedAt pgtype.Timestamptz `json:"updated_at"` + PlanName string `json:"plan_name"` + PlanCategory string `json:"plan_category"` + DurationValue int32 `json:"duration_value"` + DurationUnit string `json:"duration_unit"` + Price pgtype.Numeric `json:"price"` + Currency string `json:"currency"` +} + +func (q *Queries) ListActiveSubscriptionsByUserID(ctx context.Context, userID int64) ([]ListActiveSubscriptionsByUserIDRow, error) { + rows, err := q.db.Query(ctx, ListActiveSubscriptionsByUserID, userID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListActiveSubscriptionsByUserIDRow + for rows.Next() { + var i ListActiveSubscriptionsByUserIDRow + if err := rows.Scan( + &i.ID, + &i.UserID, + &i.PlanID, + &i.StartsAt, + &i.ExpiresAt, + &i.Status, + &i.PaymentReference, + &i.PaymentMethod, + &i.AutoRenew, + &i.CancelledAt, + &i.CreatedAt, + &i.UpdatedAt, + &i.PlanName, + &i.PlanCategory, + &i.DurationValue, + &i.DurationUnit, + &i.Price, + &i.Currency, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const ListAllUserSubscriptionsByUserID = `-- name: ListAllUserSubscriptionsByUserID :many +SELECT + us.id, us.user_id, us.plan_id, us.starts_at, us.expires_at, us.status, us.payment_reference, us.payment_method, us.auto_renew, us.cancelled_at, us.created_at, us.updated_at, + sp.name AS plan_name, + sp.category AS plan_category, + sp.duration_value, + sp.duration_unit, + sp.price, + sp.currency +FROM user_subscriptions us +JOIN subscription_plans sp ON sp.id = us.plan_id +WHERE us.user_id = $1 +ORDER BY us.created_at DESC +` + +type ListAllUserSubscriptionsByUserIDRow struct { + ID int64 `json:"id"` + UserID int64 `json:"user_id"` + PlanID int64 `json:"plan_id"` + StartsAt pgtype.Timestamptz `json:"starts_at"` + ExpiresAt pgtype.Timestamptz `json:"expires_at"` + Status string `json:"status"` + PaymentReference pgtype.Text `json:"payment_reference"` + PaymentMethod pgtype.Text `json:"payment_method"` + AutoRenew bool `json:"auto_renew"` + CancelledAt pgtype.Timestamptz `json:"cancelled_at"` + CreatedAt pgtype.Timestamptz `json:"created_at"` + UpdatedAt pgtype.Timestamptz `json:"updated_at"` + PlanName string `json:"plan_name"` + PlanCategory string `json:"plan_category"` + DurationValue int32 `json:"duration_value"` + DurationUnit string `json:"duration_unit"` + Price pgtype.Numeric `json:"price"` + Currency string `json:"currency"` +} + +func (q *Queries) ListAllUserSubscriptionsByUserID(ctx context.Context, userID int64) ([]ListAllUserSubscriptionsByUserIDRow, error) { + rows, err := q.db.Query(ctx, ListAllUserSubscriptionsByUserID, userID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListAllUserSubscriptionsByUserIDRow + for rows.Next() { + var i ListAllUserSubscriptionsByUserIDRow + if err := rows.Scan( + &i.ID, + &i.UserID, + &i.PlanID, + &i.StartsAt, + &i.ExpiresAt, + &i.Status, + &i.PaymentReference, + &i.PaymentMethod, + &i.AutoRenew, + &i.CancelledAt, + &i.CreatedAt, + &i.UpdatedAt, + &i.PlanName, + &i.PlanCategory, + &i.DurationValue, + &i.DurationUnit, + &i.Price, + &i.Currency, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const ListLearnEnglishSubscriptionsExpiringInSevenDays = `-- name: ListLearnEnglishSubscriptionsExpiringInSevenDays :many SELECT us.id, diff --git a/internal/domain/admin_user_learning_activity.go b/internal/domain/admin_user_learning_activity.go new file mode 100644 index 00000000..e1ee600c --- /dev/null +++ b/internal/domain/admin_user_learning_activity.go @@ -0,0 +1,97 @@ +package domain + +import "time" + +// AdminUserLearningActivityDetails is the full learning picture for a learner (LMS + exam prep + timeline). +type AdminUserLearningActivityDetails struct { + UserID int64 `json:"user_id"` + LMS AdminUserLMSLearningSection `json:"lms"` + ExamPrep AdminUserExamPrepLearningSection `json:"exam_prep"` + RecentActivity UserRecentActivityFeed `json:"recent_activity"` +} + +type AdminUserLMSLearningSection struct { + CompletedIDs LMSUserProgress `json:"completed_ids"` + Progress LMSProgressSummary `json:"progress"` + Completions AdminLMSUserLearningActivityTree `json:"completions"` +} + +type AdminUserExamPrepLearningSection struct { + Progress ExamPrepProgressSummary `json:"progress"` + Completions AdminExamPrepUserLearningActivityTree `json:"completions"` +} + +// ExamPrepProgressSummary mirrors LMSProgressSummary for exam-prep catalog hierarchy. +type ExamPrepProgressSummary struct { + CatalogCourses []ExamPrepProgressSummaryCatalogCourse `json:"catalog_courses"` +} + +type ExamPrepProgressSummaryCatalogCourse struct { + ID int64 `json:"id"` + Name string `json:"name"` + Access *LMSEntityAccess `json:"access,omitempty"` + Units []ExamPrepProgressSummaryUnit `json:"units"` +} + +type ExamPrepProgressSummaryUnit struct { + ID int64 `json:"id"` + CatalogCourseID int64 `json:"catalog_course_id"` + Name string `json:"name"` + Access *LMSEntityAccess `json:"access,omitempty"` + Modules []ExamPrepProgressSummaryModule `json:"modules"` +} + +type ExamPrepProgressSummaryModule struct { + ID int64 `json:"id"` + UnitID int64 `json:"unit_id"` + Name string `json:"name"` + Access *LMSEntityAccess `json:"access,omitempty"` + Lessons []ExamPrepProgressSummaryLesson `json:"lessons"` +} + +type ExamPrepProgressSummaryLesson struct { + ID int64 `json:"id"` + ModuleID int64 `json:"module_id"` + Title string `json:"title"` + Access *LMSEntityAccess `json:"access,omitempty"` +} + +// AdminExamPrepUserLearningActivityTree is nested catalog course → unit → module → lesson → practice completions. +type AdminExamPrepUserLearningActivityTree struct { + UserID int64 `json:"user_id"` + CatalogCourses []AdminExamPrepCatalogCourseLearningEntry `json:"catalog_courses"` +} + +type AdminExamPrepCatalogCourseLearningEntry struct { + ID int64 `json:"id"` + Name string `json:"name"` + SortOrder int32 `json:"sort_order"` + Units []AdminExamPrepUnitLearningEntry `json:"units"` +} + +type AdminExamPrepUnitLearningEntry struct { + ID int64 `json:"id"` + Name string `json:"name"` + SortOrder int32 `json:"sort_order"` + Modules []AdminExamPrepModuleLearningEntry `json:"modules"` +} + +type AdminExamPrepModuleLearningEntry struct { + ID int64 `json:"id"` + Name string `json:"name"` + SortOrder int32 `json:"sort_order"` + Lessons []AdminExamPrepLessonLearningEntry `json:"lessons"` +} + +type AdminExamPrepLessonLearningEntry struct { + ID int64 `json:"id"` + Title string `json:"title"` + SortOrder int32 `json:"sort_order"` + Practices []AdminExamPrepPracticeLearningEntry `json:"practices"` +} + +type AdminExamPrepPracticeLearningEntry struct { + ExamPrepPracticeID int64 `json:"exam_prep_practice_id"` + Title string `json:"title"` + CompletedAt time.Time `json:"completed_at"` +} diff --git a/internal/domain/admin_user_subscription_details.go b/internal/domain/admin_user_subscription_details.go new file mode 100644 index 00000000..317cc089 --- /dev/null +++ b/internal/domain/admin_user_subscription_details.go @@ -0,0 +1,52 @@ +package domain + +import "time" + +// AdminUserSubscriptionDetails aggregates subscription and payment data for admin user profile views. +type AdminUserSubscriptionDetails struct { + UserID int64 `json:"user_id"` + DisplayStatus string `json:"display_status"` + HasActiveSubscription bool `json:"has_active_subscription"` + ActiveByCategory map[string]bool `json:"active_by_category"` + ActiveSubscriptions []AdminUserSubscriptionRecord `json:"active_subscriptions"` + Subscriptions []AdminUserSubscriptionRecord `json:"subscriptions"` + Payments []AdminUserSubscriptionPayment `json:"payments"` +} + +// AdminUserSubscriptionRecord is one user_subscriptions row with joined plan metadata. +type AdminUserSubscriptionRecord struct { + ID int64 `json:"id"` + UserID int64 `json:"user_id"` + PlanID int64 `json:"plan_id"` + PlanName string `json:"plan_name"` + PlanCategory string `json:"plan_category"` + StartsAt time.Time `json:"starts_at"` + ExpiresAt time.Time `json:"expires_at"` + Status string `json:"status"` + PaymentReference *string `json:"payment_reference,omitempty"` + PaymentMethod *string `json:"payment_method,omitempty"` + AutoRenew bool `json:"auto_renew"` + CancelledAt *time.Time `json:"cancelled_at,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + DurationValue int32 `json:"duration_value"` + DurationUnit string `json:"duration_unit"` + Price float64 `json:"price"` + Currency string `json:"currency"` + IsCurrentlyActive bool `json:"is_currently_active"` +} + +// AdminUserSubscriptionPayment is a payment row linked to subscription checkout. +type AdminUserSubscriptionPayment struct { + ID int64 `json:"id"` + PlanID *int64 `json:"plan_id,omitempty"` + PlanName *string `json:"plan_name,omitempty"` + SubscriptionID *int64 `json:"subscription_id,omitempty"` + Amount float64 `json:"amount"` + Currency string `json:"currency"` + PaymentMethod *string `json:"payment_method,omitempty"` + Status string `json:"status"` + PaidAt *time.Time `json:"paid_at,omitempty"` + ExpiresAt *time.Time `json:"expires_at,omitempty"` + CreatedAt time.Time `json:"created_at"` +} diff --git a/internal/domain/subscriptions.go b/internal/domain/subscriptions.go index 22dd166c..ecfcd0be 100644 --- a/internal/domain/subscriptions.go +++ b/internal/domain/subscriptions.go @@ -115,6 +115,7 @@ type UserSubscription struct { UpdatedAt *time.Time // Joined fields from plan PlanName *string + PlanCategory *string DurationValue *int32 DurationUnit *string Price *float64 diff --git a/internal/ports/subscriptions.go b/internal/ports/subscriptions.go index 27611c9a..75d74fd8 100644 --- a/internal/ports/subscriptions.go +++ b/internal/ports/subscriptions.go @@ -21,6 +21,8 @@ type SubscriptionStore interface { ListSubscriptionDisplayStatusesByUserIDs(ctx context.Context, userIDs []int64) (map[int64]string, error) GetSubscriptionDisplayStatusByUserID(ctx context.Context, userID int64) (string, error) GetUserSubscriptionHistory(ctx context.Context, userID int64, limit, offset int32) ([]domain.UserSubscription, error) + ListAllUserSubscriptionsByUserID(ctx context.Context, userID int64) ([]domain.UserSubscription, error) + ListActiveSubscriptionsByUserID(ctx context.Context, userID int64) ([]domain.UserSubscription, error) HasActiveSubscription(ctx context.Context, userID int64) (bool, error) HasActiveSubscriptionByCategory(ctx context.Context, userID int64, category string) (bool, error) CancelUserSubscription(ctx context.Context, id int64) error diff --git a/internal/repository/exam_prep_admin_activity.go b/internal/repository/exam_prep_admin_activity.go new file mode 100644 index 00000000..fb691830 --- /dev/null +++ b/internal/repository/exam_prep_admin_activity.go @@ -0,0 +1,11 @@ +package repository + +import ( + "context" + + dbgen "Yimaru-Backend/gen/db" +) + +func (s *Store) ListUserExamPrepFlatLearningActivity(ctx context.Context, userID int64) ([]dbgen.ListUserExamPrepFlatLearningActivityByUserRow, error) { + return s.queries.ListUserExamPrepFlatLearningActivityByUser(ctx, userID) +} diff --git a/internal/repository/subscriptions.go b/internal/repository/subscriptions.go index a4142628..c5ebd3c0 100644 --- a/internal/repository/subscriptions.go +++ b/internal/repository/subscriptions.go @@ -190,25 +190,46 @@ func (s *Store) GetUserSubscriptionHistory(ctx context.Context, userID int64, li result := make([]domain.UserSubscription, len(subs)) for i, sub := range subs { - result[i] = domain.UserSubscription{ - ID: sub.ID, - UserID: sub.UserID, - PlanID: sub.PlanID, - StartsAt: sub.StartsAt.Time, - ExpiresAt: sub.ExpiresAt.Time, - Status: sub.Status, - PaymentReference: fromPgText(sub.PaymentReference), - PaymentMethod: fromPgText(sub.PaymentMethod), - AutoRenew: sub.AutoRenew, - CancelledAt: timePtr(sub.CancelledAt), - CreatedAt: sub.CreatedAt.Time, - UpdatedAt: timePtr(sub.UpdatedAt), - PlanName: &sub.PlanName, - DurationValue: &sub.DurationValue, - DurationUnit: &sub.DurationUnit, - Price: float64Ptr(fromPgNumeric(sub.Price)), - Currency: &sub.Currency, - } + result[i] = mapUserSubscriptionPlanJoinRow( + sub.ID, sub.UserID, sub.PlanID, sub.StartsAt, sub.ExpiresAt, sub.Status, + sub.PaymentReference, sub.PaymentMethod, sub.AutoRenew, sub.CancelledAt, + sub.CreatedAt, sub.UpdatedAt, sub.PlanName, sub.PlanCategory, + sub.DurationValue, sub.DurationUnit, sub.Price, sub.Currency, + ) + } + return result, nil +} + +func (s *Store) ListAllUserSubscriptionsByUserID(ctx context.Context, userID int64) ([]domain.UserSubscription, error) { + subs, err := s.queries.ListAllUserSubscriptionsByUserID(ctx, userID) + if err != nil { + return nil, err + } + result := make([]domain.UserSubscription, len(subs)) + for i, sub := range subs { + result[i] = mapUserSubscriptionPlanJoinRow( + sub.ID, sub.UserID, sub.PlanID, sub.StartsAt, sub.ExpiresAt, sub.Status, + sub.PaymentReference, sub.PaymentMethod, sub.AutoRenew, sub.CancelledAt, + sub.CreatedAt, sub.UpdatedAt, sub.PlanName, sub.PlanCategory, + sub.DurationValue, sub.DurationUnit, sub.Price, sub.Currency, + ) + } + return result, nil +} + +func (s *Store) ListActiveSubscriptionsByUserID(ctx context.Context, userID int64) ([]domain.UserSubscription, error) { + subs, err := s.queries.ListActiveSubscriptionsByUserID(ctx, userID) + if err != nil { + return nil, err + } + result := make([]domain.UserSubscription, len(subs)) + for i, sub := range subs { + result[i] = mapUserSubscriptionPlanJoinRow( + sub.ID, sub.UserID, sub.PlanID, sub.StartsAt, sub.ExpiresAt, sub.Status, + sub.PaymentReference, sub.PaymentMethod, sub.AutoRenew, sub.CancelledAt, + sub.CreatedAt, sub.UpdatedAt, sub.PlanName, sub.PlanCategory, + sub.DurationValue, sub.DurationUnit, sub.Price, sub.Currency, + ) } return result, nil } @@ -285,25 +306,51 @@ func userSubscriptionToDomain(s dbgen.UserSubscription) *domain.UserSubscription } func userSubscriptionWithPlanToDomain(s dbgen.GetUserSubscriptionByIDRow) *domain.UserSubscription { - return &domain.UserSubscription{ - ID: s.ID, - UserID: s.UserID, - PlanID: s.PlanID, - StartsAt: s.StartsAt.Time, - ExpiresAt: s.ExpiresAt.Time, - Status: s.Status, - PaymentReference: fromPgText(s.PaymentReference), - PaymentMethod: fromPgText(s.PaymentMethod), - AutoRenew: s.AutoRenew, - CancelledAt: timePtr(s.CancelledAt), - CreatedAt: s.CreatedAt.Time, - UpdatedAt: timePtr(s.UpdatedAt), - PlanName: &s.PlanName, - DurationValue: &s.DurationValue, - DurationUnit: &s.DurationUnit, - Price: float64Ptr(fromPgNumeric(s.Price)), - Currency: &s.Currency, + out := mapUserSubscriptionPlanJoinRow( + s.ID, s.UserID, s.PlanID, s.StartsAt, s.ExpiresAt, s.Status, + s.PaymentReference, s.PaymentMethod, s.AutoRenew, s.CancelledAt, + s.CreatedAt, s.UpdatedAt, s.PlanName, "", + s.DurationValue, s.DurationUnit, s.Price, s.Currency, + ) + return &out +} + +func mapUserSubscriptionPlanJoinRow( + id, userID, planID int64, + startsAt, expiresAt pgtype.Timestamptz, + status string, + paymentReference, paymentMethod pgtype.Text, + autoRenew bool, + cancelledAt, createdAt, updatedAt pgtype.Timestamptz, + planName, planCategory string, + durationValue int32, + durationUnit string, + price pgtype.Numeric, + currency string, +) domain.UserSubscription { + out := domain.UserSubscription{ + ID: id, + UserID: userID, + PlanID: planID, + StartsAt: startsAt.Time, + ExpiresAt: expiresAt.Time, + Status: status, + PaymentReference: fromPgText(paymentReference), + PaymentMethod: fromPgText(paymentMethod), + AutoRenew: autoRenew, + CancelledAt: timePtr(cancelledAt), + CreatedAt: createdAt.Time, + UpdatedAt: timePtr(updatedAt), + PlanName: &planName, + DurationValue: &durationValue, + DurationUnit: &durationUnit, + Price: float64Ptr(fromPgNumeric(price)), + Currency: ¤cy, } + if planCategory != "" { + out.PlanCategory = &planCategory + } + return out } func optionalInt4(v *int32) pgtype.Int4 { diff --git a/internal/services/lmsprogress/admin_exam_prep_learning.go b/internal/services/lmsprogress/admin_exam_prep_learning.go new file mode 100644 index 00000000..605f5391 --- /dev/null +++ b/internal/services/lmsprogress/admin_exam_prep_learning.go @@ -0,0 +1,167 @@ +package lmsprogress + +import ( + "context" + + dbgen "Yimaru-Backend/gen/db" + "Yimaru-Backend/internal/domain" +) + +// AdminUserExamPrepLearningActivityTree returns nested catalog course → unit → module → lesson → practice completions. +func (s *Service) AdminUserExamPrepLearningActivityTree(ctx context.Context, userID int64) (domain.AdminExamPrepUserLearningActivityTree, error) { + rows, err := s.store.ListUserExamPrepFlatLearningActivity(ctx, userID) + if err != nil { + return domain.AdminExamPrepUserLearningActivityTree{}, err + } + return buildAdminExamPrepLearningActivityTree(userID, rows), nil +} + +type epLessonAccum struct { + id int64 + title string + sortOrder int32 + practices []domain.AdminExamPrepPracticeLearningEntry + seen map[int64]struct{} +} + +type epModuleAccum struct { + id int64 + name string + sortOrder int32 + lessons map[int64]*epLessonAccum + order []int64 +} + +type epUnitAccum struct { + id int64 + name string + sortOrder int32 + modules map[int64]*epModuleAccum + order []int64 +} + +type epCatalogAccum struct { + id int64 + name string + sortOrder int32 + units map[int64]*epUnitAccum + order []int64 +} + +type examPrepActivityTreeBuilder struct { + catalogs map[int64]*epCatalogAccum + order []int64 +} + +func newExamPrepActivityTreeBuilder() *examPrepActivityTreeBuilder { + return &examPrepActivityTreeBuilder{catalogs: make(map[int64]*epCatalogAccum)} +} + +func (b *examPrepActivityTreeBuilder) ensureCatalog(row dbgen.ListUserExamPrepFlatLearningActivityByUserRow) *epCatalogAccum { + if c, ok := b.catalogs[row.CatalogCourseID]; ok { + return c + } + c := &epCatalogAccum{ + id: row.CatalogCourseID, name: row.CatalogCourseName, sortOrder: row.CatalogCourseSortOrder, + units: make(map[int64]*epUnitAccum), + } + b.catalogs[row.CatalogCourseID] = c + b.order = append(b.order, row.CatalogCourseID) + return c +} + +func (ca *epCatalogAccum) ensureUnit(row dbgen.ListUserExamPrepFlatLearningActivityByUserRow) *epUnitAccum { + if u, ok := ca.units[row.UnitID]; ok { + return u + } + u := &epUnitAccum{ + id: row.UnitID, name: row.UnitName, sortOrder: row.UnitSortOrder, + modules: make(map[int64]*epModuleAccum), + } + ca.units[row.UnitID] = u + ca.order = append(ca.order, row.UnitID) + return u +} + +func (ua *epUnitAccum) ensureModule(row dbgen.ListUserExamPrepFlatLearningActivityByUserRow) *epModuleAccum { + if m, ok := ua.modules[row.ModuleID]; ok { + return m + } + m := &epModuleAccum{ + id: row.ModuleID, name: row.ModuleName, sortOrder: row.ModuleSortOrder, + lessons: make(map[int64]*epLessonAccum), + } + ua.modules[row.ModuleID] = m + ua.order = append(ua.order, row.ModuleID) + return m +} + +func (ma *epModuleAccum) ensureLesson(row dbgen.ListUserExamPrepFlatLearningActivityByUserRow) *epLessonAccum { + if l, ok := ma.lessons[row.LessonID]; ok { + return l + } + l := &epLessonAccum{ + id: row.LessonID, title: row.LessonTitle, sortOrder: row.LessonSortOrder, + seen: make(map[int64]struct{}), + } + ma.lessons[row.LessonID] = l + ma.order = append(ma.order, row.LessonID) + return l +} + +func (b *examPrepActivityTreeBuilder) ingest(row dbgen.ListUserExamPrepFlatLearningActivityByUserRow) { + c := b.ensureCatalog(row) + u := c.ensureUnit(row) + m := u.ensureModule(row) + l := m.ensureLesson(row) + if _, ok := l.seen[row.ExamPrepPracticeID]; ok { + return + } + l.seen[row.ExamPrepPracticeID] = struct{}{} + l.practices = append(l.practices, domain.AdminExamPrepPracticeLearningEntry{ + ExamPrepPracticeID: row.ExamPrepPracticeID, + Title: row.PracticeTitle, + CompletedAt: row.ActivityAt.Time, + }) +} + +func buildAdminExamPrepLearningActivityTree(userID int64, rows []dbgen.ListUserExamPrepFlatLearningActivityByUserRow) domain.AdminExamPrepUserLearningActivityTree { + b := newExamPrepActivityTreeBuilder() + for _, row := range rows { + b.ingest(row) + } + + catalogs := make([]domain.AdminExamPrepCatalogCourseLearningEntry, 0, len(b.order)) + for _, catalogID := range b.order { + ca := b.catalogs[catalogID] + units := make([]domain.AdminExamPrepUnitLearningEntry, 0, len(ca.order)) + for _, unitID := range ca.order { + ua := ca.units[unitID] + modules := make([]domain.AdminExamPrepModuleLearningEntry, 0, len(ua.order)) + for _, moduleID := range ua.order { + ma := ua.modules[moduleID] + lessons := make([]domain.AdminExamPrepLessonLearningEntry, 0, len(ma.order)) + for _, lessonID := range ma.order { + la := ma.lessons[lessonID] + lessons = append(lessons, domain.AdminExamPrepLessonLearningEntry{ + ID: la.id, Title: la.title, SortOrder: la.sortOrder, Practices: la.practices, + }) + } + modules = append(modules, domain.AdminExamPrepModuleLearningEntry{ + ID: ma.id, Name: ma.name, SortOrder: ma.sortOrder, Lessons: lessons, + }) + } + units = append(units, domain.AdminExamPrepUnitLearningEntry{ + ID: ua.id, Name: ua.name, SortOrder: ua.sortOrder, Modules: modules, + }) + } + catalogs = append(catalogs, domain.AdminExamPrepCatalogCourseLearningEntry{ + ID: ca.id, Name: ca.name, SortOrder: ca.sortOrder, Units: units, + }) + } + + if catalogs == nil { + catalogs = []domain.AdminExamPrepCatalogCourseLearningEntry{} + } + return domain.AdminExamPrepUserLearningActivityTree{UserID: userID, CatalogCourses: catalogs} +} diff --git a/internal/services/rbac/seeds.go b/internal/services/rbac/seeds.go index 4495e9cc..5cefcee5 100644 --- a/internal/services/rbac/seeds.go +++ b/internal/services/rbac/seeds.go @@ -160,6 +160,7 @@ var AllPermissions = []domain.PermissionSeed{ {Key: "subscriptions.create", Name: "Create Subscription", Description: "Create subscription (admin)", GroupName: "Subscriptions"}, {Key: "subscriptions.checkout", Name: "Checkout Subscription", Description: "Initiate subscription payment", GroupName: "Subscriptions"}, {Key: "subscriptions.get_mine", Name: "Get My Subscription", Description: "Get own subscription", GroupName: "Subscriptions"}, + {Key: "subscriptions.get_by_user", Name: "Get User Subscriptions (Admin)", Description: "Get full subscription details for a user", GroupName: "Subscriptions"}, {Key: "subscriptions.history", Name: "Subscription History", Description: "Get subscription history", GroupName: "Subscriptions"}, {Key: "subscriptions.status", Name: "Check Subscription Status", Description: "Check subscription status", GroupName: "Subscriptions"}, {Key: "subscriptions.cancel", Name: "Cancel Subscription", Description: "Cancel a subscription", GroupName: "Subscriptions"}, @@ -445,7 +446,7 @@ var DefaultRolePermissions = map[string][]string{ // Subscriptions & Payments (full access) "subscription_plans.create", "subscription_plans.update", "subscription_plans.delete", - "subscriptions.create", "subscriptions.checkout", "subscriptions.get_mine", "subscriptions.history", + "subscriptions.create", "subscriptions.checkout", "subscriptions.get_mine", "subscriptions.get_by_user", "subscriptions.history", "subscriptions.status", "subscriptions.cancel", "subscriptions.set_auto_renew", "payments.initiate", "payments.verify", "payments.list_mine", "payments.get", "payments.cancel", "payments.direct_initiate", "payments.direct_verify_otp", "payments.list_all", diff --git a/internal/services/subscriptions/service.go b/internal/services/subscriptions/service.go index 22e4daf7..b8701122 100644 --- a/internal/services/subscriptions/service.go +++ b/internal/services/subscriptions/service.go @@ -198,6 +198,112 @@ func (s *Service) ListLearnEnglishSubscriptionsExpiringInSevenDays(ctx context.C return s.store.ListLearnEnglishSubscriptionsExpiringInSevenDays(ctx) } +// GetAdminUserSubscriptionDetails returns full subscription history and active plans for admin user views. +// Payment rows are attached by the handler. +func (s *Service) GetAdminUserSubscriptionDetails(ctx context.Context, userID int64) (domain.AdminUserSubscriptionDetails, error) { + displayStatus, err := s.store.GetSubscriptionDisplayStatusByUserID(ctx, userID) + if err != nil { + return domain.AdminUserSubscriptionDetails{}, err + } + + all, err := s.store.ListAllUserSubscriptionsByUserID(ctx, userID) + if err != nil { + return domain.AdminUserSubscriptionDetails{}, err + } + + active, err := s.store.ListActiveSubscriptionsByUserID(ctx, userID) + if err != nil { + return domain.AdminUserSubscriptionDetails{}, err + } + + hasActive, err := s.store.HasActiveSubscription(ctx, userID) + if err != nil { + return domain.AdminUserSubscriptionDetails{}, err + } + + activeByCategory := map[string]bool{ + string(domain.SubscriptionCategoryLearnEnglish): false, + string(domain.SubscriptionCategoryIELTS): false, + string(domain.SubscriptionCategoryDuolingo): false, + } + for category := range activeByCategory { + ok, err := s.store.HasActiveSubscriptionByCategory(ctx, userID, category) + if err != nil { + return domain.AdminUserSubscriptionDetails{}, err + } + activeByCategory[category] = ok + } + + now := time.Now() + subscriptions := make([]domain.AdminUserSubscriptionRecord, 0, len(all)) + for _, sub := range all { + subscriptions = append(subscriptions, toAdminUserSubscriptionRecord(sub, now)) + } + activeSubscriptions := make([]domain.AdminUserSubscriptionRecord, 0, len(active)) + for _, sub := range active { + activeSubscriptions = append(activeSubscriptions, toAdminUserSubscriptionRecord(sub, now)) + } + + return domain.AdminUserSubscriptionDetails{ + UserID: userID, + DisplayStatus: displayStatus, + HasActiveSubscription: hasActive, + ActiveByCategory: activeByCategory, + ActiveSubscriptions: activeSubscriptions, + Subscriptions: subscriptions, + Payments: []domain.AdminUserSubscriptionPayment{}, + }, nil +} + +func toAdminUserSubscriptionRecord(sub domain.UserSubscription, now time.Time) domain.AdminUserSubscriptionRecord { + planName := "" + if sub.PlanName != nil { + planName = *sub.PlanName + } + planCategory := "" + if sub.PlanCategory != nil { + planCategory = *sub.PlanCategory + } + durationValue := int32(0) + if sub.DurationValue != nil { + durationValue = *sub.DurationValue + } + durationUnit := "" + if sub.DurationUnit != nil { + durationUnit = *sub.DurationUnit + } + price := float64(0) + if sub.Price != nil { + price = *sub.Price + } + currency := "" + if sub.Currency != nil { + currency = *sub.Currency + } + isActive := sub.Status == string(domain.SubscriptionStatusActive) && sub.ExpiresAt.After(now) + return domain.AdminUserSubscriptionRecord{ + ID: sub.ID, + UserID: sub.UserID, + PlanID: sub.PlanID, + PlanName: planName, + PlanCategory: planCategory, + StartsAt: sub.StartsAt, + ExpiresAt: sub.ExpiresAt, + Status: sub.Status, + PaymentReference: sub.PaymentReference, + PaymentMethod: sub.PaymentMethod, + AutoRenew: sub.AutoRenew, + CancelledAt: sub.CancelledAt, + CreatedAt: sub.CreatedAt, + UpdatedAt: sub.UpdatedAt, + DurationValue: durationValue, + DurationUnit: durationUnit, + Price: price, + Currency: currency, + IsCurrentlyActive: isActive, + } +} + // Helper functions func strPtr(s string) *string { return &s diff --git a/internal/web_server/handlers/admin_user_detail_handler.go b/internal/web_server/handlers/admin_user_detail_handler.go new file mode 100644 index 00000000..ea11a11a --- /dev/null +++ b/internal/web_server/handlers/admin_user_detail_handler.go @@ -0,0 +1,395 @@ +package handlers + +import ( + "context" + "errors" + "strconv" + + "Yimaru-Backend/internal/domain" + + "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 LMS and exam-prep completion trees, progress summaries, completed ID snapshots, and recent activity timeline +// @Tags lms +// @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" + + completedIDs, err := h.lmsProgressSvc.GetMyProgress(c.Context(), targetID) + if err != nil { + return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ + Message: "Failed to load LMS completed IDs", + Error: err.Error(), + }) + } + + lmsProgress, err := h.buildLMSProgressSummary(c.Context(), domain.RoleStudent, targetID, true) + if err != nil { + return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ + Message: "Failed to load LMS progress summary", + Error: err.Error(), + }) + } + + lmsCompletions, err := h.lmsProgressSvc.AdminUserLearningActivityTree(c.Context(), targetID) + if err != nil { + return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ + Message: "Failed to load LMS completion tree", + Error: err.Error(), + }) + } + + examPrepProgress, err := h.buildExamPrepProgressSummary(c.Context(), 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, + LMS: domain.AdminUserLMSLearningSection{ + CompletedIDs: completedIDs, + Progress: lmsProgress, + Completions: lmsCompletions, + }, + 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) { + 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 + } +} diff --git a/internal/web_server/routes.go b/internal/web_server/routes.go index f94a14b5..b958dd46 100644 --- a/internal/web_server/routes.go +++ b/internal/web_server/routes.go @@ -338,6 +338,8 @@ func (a *App) initAppRoutes() { groupV1.Get("/admin/users/deletion-requests", a.authMiddleware, a.RequirePermission("users.deletion_requests.list"), h.ListAccountDeletionRequests) groupV1.Get("/admin/users/:user_id/lms-learning-activity", a.authMiddleware, a.RequirePermission("progress.get_any_user"), h.AdminGetUserLMSLearningActivity) groupV1.Get("/admin/users/:user_id/recent-activity", a.authMiddleware, a.RequirePermission("progress.get_any_user"), h.AdminGetUserRecentActivity) + groupV1.Get("/admin/users/:user_id/learning-activity", a.authMiddleware, a.RequirePermission("progress.get_any_user"), h.AdminGetUserLearningActivityDetails) + groupV1.Get("/admin/users/:user_id/subscriptions", a.authMiddleware, a.RequirePermission("subscriptions.get_by_user"), h.AdminGetUserSubscriptions) groupV1.Get("/users/summary", a.authMiddleware, a.RequirePermission("users.summary"), h.GetUserSummary) groupV1.Put("/user", a.authMiddleware, a.RequirePermission("users.update_self"), h.UpdateUser) groupV1.Patch("/user/status", a.authMiddleware, a.RequirePermission("users.update_status"), h.UpdateUserStatus)