Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Learning insights dash #624

Merged
merged 15 commits into from
Jan 13, 2025
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions backend/src/database/activity.go
PThorpe92 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -356,3 +356,98 @@ func (db *DB) GetAdminDashboardInfo(facilityID uint) (models.AdminDashboardJoin,

return dashboard, nil
}

func (db *DB) GetAdminLayer2Info(facilityID *uint) (models.AdminLayer2Join, error) {
corypride marked this conversation as resolved.
Show resolved Hide resolved
var adminLayer2 models.AdminLayer2Join

// total courses
subQry := db.Table("courses c").
Select("COUNT(DISTINCT c.id) as total_courses_offered").
Joins("INNER JOIN user_enrollments ue on c.id = ue.course_id").
Joins("INNER JOIN users u on ue.user_id = u.id")
corypride marked this conversation as resolved.
Show resolved Hide resolved

if facilityID != nil {
subQry = subQry.Where("u.facility_id = ?", facilityID)
subQry = subQry.Group("u.facility_id")
}

err := db.Table("(?) as sub", subQry).
Find(&adminLayer2.TotalCoursesOffered).Error

if err != nil {
return adminLayer2, NewDBError(err, "error getting admin dashboard info")
}

// total_students_enrolled
subQry = db.Table("courses c").
Select("COUNT(DISTINCT m.user_id) AS students_enrolled, c.name").
Joins("LEFT JOIN milestones m ON m.course_id = c.id").
Joins("INNER JOIN users u on m.user_id = u.id").
Where("u.role = ?", "student")

if facilityID != nil {
subQry = subQry.Where(" u.facility_id = ?", facilityID)
}

subQry = subQry.Group("c.name")

err = db.Table("(?) as sub", subQry).
Select("CASE WHEN SUM(students_enrolled) IS NULL THEN 0 ELSE SUM(students_enrolled) end AS students_enrolled").
Scan(&adminLayer2.TotalStudentsEnrolled).Debug().Error
corypride marked this conversation as resolved.
Show resolved Hide resolved

if err != nil {
return adminLayer2, NewDBError(err, "error getting total_students_enrolled dashboard info")
}

// total_hourly_activity
subQry = db.Table("users u").
Select("CASE WHEN SUM(a.total_time) IS NULL THEN 0 ELSE ROUND(SUM(a.total_time)/3600, 0) END AS total_time").
Joins("LEFT JOIN activities a ON u.id = a.user_id").
Where("u.role = ?", "student")

if facilityID != nil {
subQry = subQry.Where(" u.facility_id = ?", facilityID)
}
subQry = subQry.Group("u.id")

err = subQry.Find(&adminLayer2.TotalHourlyActivity).Error

if err != nil {
return adminLayer2, NewDBError(err, "error getting admin dashboard info")
}

// learning_insights
subQry = db.Table("outcomes o").
Select("o.course_id, COUNT(o.id) AS outcome_count").
Group("o.course_id")

subQry2 := db.Table("courses c").
Select(`
c.name AS course_name,
COUNT(DISTINCT u.id) AS total_students_enrolled,
CASE
WHEN MAX(subqry.outcome_count) > 0 THEN
COUNT(DISTINCT u.id) / NULLIF(CAST(MAX(c.total_progress_milestones) AS float), 0) * 100.0
ELSE 0
END AS completion_rate,
COALESCE(ROUND(SUM(a.total_time) / 3600, 0), 0) AS activity_hours
`).
Joins("LEFT JOIN milestones m ON m.course_id = c.id").
Joins("LEFT JOIN users u ON m.user_id = u.id").
Joins("LEFT JOIN activities a ON u.id = a.user_id").
Joins("INNER JOIN (?) AS subqry ON m.course_id = subqry.course_id", subQry).
Where("u.role = ?", "student")

if facilityID != nil {
subQry2 = subQry2.Where("u.facility_id = ?", facilityID)
}

err = subQry2.Group("c.name, c.total_progress_milestones").
Find(&adminLayer2.LearningInsights).Error

if err != nil {
return adminLayer2, NewDBError(err, "error getting learning insight table info")
}

return adminLayer2, nil
}
2 changes: 1 addition & 1 deletion backend/src/database/helpful_links.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func (db *DB) GetHelpfulLinks(page, perPage int, search, orderBy string, onlyVis

func (db *DB) AddHelpfulLink(link *models.HelpfulLink) error {
if db.Where("url = ?", link.Url).First(&models.HelpfulLink{}).RowsAffected > 0 {
return NewDBError(fmt.Errorf("Link already exists"), "helpful_links")
return NewDBError(fmt.Errorf("link already exists"), "helpful_links")
}
if err := db.Create(link).Error; err != nil {
return newCreateDBError(err, "helpful_links")
Expand Down
29 changes: 29 additions & 0 deletions backend/src/handlers/dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ func (srv *Server) registerDashboardRoutes() []routeDef {
{"GET /api/login-metrics", srv.handleLoginMetrics, true, models.Feature()},
{"GET /api/users/{id}/student-dashboard", srv.handleStudentDashboard, false, models.Feature()},
{"GET /api/users/{id}/admin-dashboard", srv.handleAdminDashboard, true, models.Feature()},
{"GET /api/users/{id}/admin-layer2", srv.handleAdminLayer2, true, models.Feature()},
{"GET /api/users/{id}/catalog", srv.handleUserCatalog, false, axx},
{"GET /api/users/{id}/courses", srv.handleUserCourses, false, axx},
}
Expand Down Expand Up @@ -48,6 +49,34 @@ func (srv *Server) handleAdminDashboard(w http.ResponseWriter, r *http.Request,
return writeJsonResponse(w, http.StatusOK, adminDashboard)
}

func (srv *Server) handleAdminLayer2(w http.ResponseWriter, r *http.Request, log sLog) error {
facility := r.URL.Query().Get("facility")
claims := r.Context().Value(ClaimsKey).(*Claims)
var facilityId *uint
// Logic goes here for facility
corypride marked this conversation as resolved.
Show resolved Hide resolved
switch facility {
case "all":
facilityId = nil
case "":
facilityId = &claims.FacilityID
default:
facilityIdInt, err := strconv.Atoi(facility)
if err != nil {
return newInvalidIdServiceError(err, "facility")
}
ref := uint(facilityIdInt)
facilityId = &ref
}

adminDashboard, err := srv.Db.GetAdminLayer2Info(facilityId)
if err != nil {
log.add("facilityId", claims.FacilityID)
return newDatabaseServiceError(err)
}

return writeJsonResponse(w, http.StatusOK, adminDashboard)
}

func (srv *Server) handleLoginMetrics(w http.ResponseWriter, r *http.Request, log sLog) error {
facility := r.URL.Query().Get("facility")
claims := r.Context().Value(ClaimsKey).(*Claims)
Expand Down
35 changes: 35 additions & 0 deletions backend/src/handlers/dashboard_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,41 @@ func TestHandleAdminDashboard(t *testing.T) {
}
}

func TestHandleAdminLayer2(t *testing.T) {
httpTests := []httpTest{
{"TestAdminDashboardAsAdmin", "admin", map[string]any{"id": "1"}, http.StatusOK, ""},
{"TestAdminDashboardAsUser", "student", map[string]any{"id": "4"}, http.StatusUnauthorized, ""},
}
for _, test := range httpTests {
t.Run(test.testName, func(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, "/api/users/{id}/admin-layer2", nil)
if err != nil {
t.Fatalf("unable to create new request, error is %v", err)
}
req.SetPathValue("id", test.mapKeyValues["id"].(string))
handler := getHandlerByRoleWithMiddleware(server.handleAdminLayer2, test.role)
rr := executeRequest(t, req, handler, test)
id, _ := strconv.Atoi(test.mapKeyValues["id"].(string))
if test.expectedStatusCode == http.StatusOK {

id := uint(id)
dashboard, err := server.Db.GetAdminLayer2Info(&id)
if err != nil {
t.Fatalf("unable to get admin-layer-2, error is %v", err)
}
received := rr.Body.String()
resource := models.Resource[models.AdminLayer2Join]{}
if err := json.Unmarshal([]byte(received), &resource); err != nil {
t.Errorf("failed to unmarshal resource, error is %v", err)
}
if diff := cmp.Diff(&dashboard, &resource.Data); diff != "" {
t.Errorf("handler returned unexpected response body: %v", diff)
}
}
})
}
}

func TestHandleUserCatalog(t *testing.T) {
httpTests := []httpTest{
{"TestGetAllUserCatalogAsAdmin", "admin", getUserCatalogSearch(4, nil, "", ""), http.StatusOK, ""},
Expand Down
14 changes: 14 additions & 0 deletions backend/src/models/course.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,20 @@ type AdminDashboardJoin struct {
TopCourseActivity []CourseActivity `json:"top_course_activity"`
}

type LearningInsight struct {
CourseName string `json:"course_name"`
TotalStudentsEnrolled int64 `json:"total_students_enrolled"`
CompletionRate float32 `json:"completion_rate"`
ActivityHours int64 `json:"activity_hours"`
}

type AdminLayer2Join struct {
TotalCoursesOffered int64 `json:"total_courses_offered"`
TotalStudentsEnrolled int64 `json:"total_students_enrolled"`
TotalHourlyActivity int64 `json:"total_hourly_activity"`
LearningInsights []LearningInsight `json:"learning_insights"`
}

type CourseMilestones struct {
Name string `json:"name"`
Milestones int `json:"milestones"`
Expand Down
Loading
Loading