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

enhance(apps/analytics): add course data comparison for weekly student activity chart #4394

Merged
merged 3 commits into from
Dec 7, 2024

Conversation

sjschlapbach
Copy link
Member

@sjschlapbach sjschlapbach commented Dec 7, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced DailyActivityTimeSeries and WeeklyActivityTimeSeries components for enhanced visualization of daily and weekly course activity data.
    • Added SuspendedCourseComparison component for comparing course activities.
    • Implemented a new GraphQL query GetCourseWeeklyActivity for retrieving weekly activity data.
  • Enhancements

    • Improved tooltip and legend display in the ActivityTimeSeriesPlot component based on course comparisons.
    • Updated localization files to include new strings for course comparison functionality.
  • Bug Fixes

    • Refined error handling and loading states in the ActivityDashboard component.

Copy link

coderabbitai bot commented Dec 7, 2024

Warning

Rate limit exceeded

@sjschlapbach has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 45 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c91d41c and 18f4a10.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

This pull request introduces several new components and modifications to existing ones within the analytics section of the frontend application. Key changes include the addition of DailyActivityTimeSeries, WeeklyActivityTimeSeries, and SuspendedCourseComparison components, which enhance the visualization of course activity data. The ActivityTimeSeriesPlot component has been refactored to streamline its props and rendering logic. Additionally, new GraphQL queries and schema updates support the retrieval of weekly activity data for courses, enhancing data management capabilities.

Changes

File Path Change Summary
apps/frontend-manage/src/components/analytics/activity/ActivityTimeSeriesPlot.tsx Updated props and rendering logic; added conditional tooltip formatting and new Line components for activity comparison.
apps/frontend-manage/src/components/analytics/activity/DailyActivityTimeSeries.tsx New component added to visualize daily activity data, utilizing ActivityTimeSeriesPlot.
apps/frontend-manage/src/components/analytics/activity/SuspendedCourseComparison.tsx New component added for course comparison functionality with dropdown selection.
apps/frontend-manage/src/components/analytics/activity/WeeklyActivityTimeSeries.tsx New component added to visualize weekly activity data, integrating with Apollo Client for data fetching.
apps/frontend-manage/src/pages/analytics/[courseId]/activity.tsx Replaced ActivityTimeSeriesPlot with DailyActivityTimeSeries and WeeklyActivityTimeSeries.
packages/graphql/src/graphql/ops/QGetCourseWeeklyActivity.graphql New GraphQL query added to retrieve weekly activity data for a course.
packages/graphql/src/ops.schema.json Added new field getCourseWeeklyActivity to the Query type in the GraphQL schema.
packages/graphql/src/public/client.json New entry for GetCourseWeeklyActivity function added.
packages/graphql/src/public/schema.graphql New type WeeklyCourseActivities and query method getCourseWeeklyActivity added to the schema.
packages/graphql/src/public/server.json New query GetCourseWeeklyActivity added; modified GetFeedbacks query to include resolvedAt field.
packages/graphql/src/schema/analytics.ts New interface and object type for weekly course activities added.
packages/graphql/src/schema/query.ts New field getCourseWeeklyActivity added to the Query type.
packages/graphql/src/services/analytics.ts New function getCourseWeeklyActivity added to handle fetching of weekly activity data.
packages/i18n/messages/de.ts New strings added for German localization related to course comparison and quiz management.
packages/i18n/messages/en.ts New strings added for English localization related to course comparison and user interface improvements.

Possibly related PRs

Suggested reviewers

  • rschlaefli: Suggested reviewer for the changes made in this pull request.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (5)
packages/graphql/src/ops.ts (1)

4091-4091: Consider adding a comment describing the query's purpose.

While the implementation is correct and follows the established patterns, adding a brief JSDoc comment describing the query's purpose would improve maintainability.

+/**
+ * Retrieves weekly activity data for a course, including total participants
+ * and activity timestamps.
+ */
export const GetCourseWeeklyActivityDocument = {"kind":"Document",...
packages/graphql/src/schema/analytics.ts (1)

86-102: LGTM! Consider adding input validation.

The new types for weekly course activities are well-structured and consistent with the existing pattern. The reuse of ParticipantActivityTimestamp maintains consistency.

Consider adding validation to ensure totalParticipants is non-negative and weeklyActivity array is not empty:

export const WeeklyCourseActivities = builder.objectType(
  WeeklyCourseActivitiesRef,
  {
    fields: (t) => ({
-     totalParticipants: t.exposeInt('totalParticipants'),
+     totalParticipants: t.int({
+       resolve: (parent) => {
+         if (parent.totalParticipants < 0) return 0
+         return parent.totalParticipants
+       },
+     }),
      weeklyActivity: t.expose('weeklyActivity', {
        type: [ParticipantActivityTimestamp],
+       validate: { minItems: 1 },
      }),
    }),
  }
)
apps/frontend-manage/src/components/analytics/activity/WeeklyActivityTimeSeries.tsx (2)

45-72: Extract data transformation logic.

The complex data transformation logic in the render method makes the component harder to maintain and test.

Consider extracting the transformation logic into a separate utility function:

const transformActivityData = (
  activity: ParticipantActivityTimestamp[],
  courseParticipants: number,
  courseComparison?: { activity: ParticipantActivityTimestamp[], participants: number }
) => {
  if (courseComparison) {
    return activity.map((item, idx) => ({
      date: `Week ${idx + 1}`,
      activeParticipants: (item.activeParticipants / courseParticipants) * 100,
      activeParticipantsReference: courseComparison.activity[idx]
        ? (courseComparison.activity[idx].activeParticipants / courseComparison.participants) * 100
        : undefined,
    }))
  }
  
  return activity.map((item) => ({
    date: new Date(item.date).toLocaleDateString('en-GB', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    }).replace(/\//g, '-'),
    activeParticipants: (item.activeParticipants / courseParticipants) * 100,
  }))
}

77-82: Consider fallback UI for Suspense boundary.

The Suspense wrapper is missing a fallback UI which could lead to a jarring user experience during loading.

Add a fallback:

- <Suspense>
+ <Suspense fallback={<div className="w-full lg:w-1/4 animate-pulse h-32" />}>
    <SuspendedCourseComparison
      courseComparison={courseComparison}
      setCourseComparison={setCourseComparison}
    />
  </Suspense>
apps/frontend-manage/src/pages/analytics/[courseId]/activity.tsx (1)

72-75: LGTM! Consider adding prop type validation.

The integration of the new WeeklyActivityTimeSeries component looks good. Props are passed correctly and the layout is maintained.

Consider adding runtime validation for the activity data to ensure type safety:

import { z } from 'zod'

const activitySchema = z.array(z.object({
  date: z.date(),
  activeParticipants: z.number().min(0)
}))

// Validate before passing to component
const validatedActivity = activitySchema.safeParse(course.weeklyActivity)
if (!validatedActivity.success) {
  console.error('Invalid activity data:', validatedActivity.error)
  return null
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b8a134a and ac4b23d.

📒 Files selected for processing (16)
  • apps/frontend-manage/src/components/analytics/activity/ActivityTimeSeriesPlot.tsx (2 hunks)
  • apps/frontend-manage/src/components/analytics/activity/DailyActivityTimeSeries.tsx (1 hunks)
  • apps/frontend-manage/src/components/analytics/activity/SuspendedCourseComparison.tsx (1 hunks)
  • apps/frontend-manage/src/components/analytics/activity/WeeklyActivityTimeSeries.tsx (1 hunks)
  • apps/frontend-manage/src/pages/analytics/[courseId]/activity.tsx (2 hunks)
  • packages/graphql/src/graphql/ops/QGetCourseWeeklyActivity.graphql (1 hunks)
  • packages/graphql/src/ops.schema.json (2 hunks)
  • packages/graphql/src/ops.ts (5 hunks)
  • packages/graphql/src/public/client.json (1 hunks)
  • packages/graphql/src/public/schema.graphql (2 hunks)
  • packages/graphql/src/public/server.json (1 hunks)
  • packages/graphql/src/schema/analytics.ts (1 hunks)
  • packages/graphql/src/schema/query.ts (2 hunks)
  • packages/graphql/src/services/analytics.ts (1 hunks)
  • packages/i18n/messages/de.ts (2 hunks)
  • packages/i18n/messages/en.ts (1 hunks)
🔥 Files not summarized due to errors (1)
  • packages/graphql/src/ops.ts: Error: Server error: no LLM provider could handle the message
🔇 Additional comments (13)
packages/graphql/src/ops.ts (2)

2148-2150: LGTM! Well-structured type definitions.

The type definitions are clean, follow TypeScript best practices, and use proper GraphQL types (Maybe, InputMaybe). The field names are clear and descriptive.

Also applies to: 2551-2555


3594-3600: LGTM! Clean query definition.

The query definition follows GraphQL naming conventions and properly uses types. The structure is clear and consistent with other queries in the codebase.

packages/graphql/src/graphql/ops/QGetCourseWeeklyActivity.graphql (1)

1-9: LGTM!

The GraphQL query is well-defined and aligns with the expected schema structure.

packages/graphql/src/schema/query.ts (2)

14-18: LGTM: Import addition is properly organized

The WeeklyCourseActivities import is correctly grouped with other analytics-related imports.


761-770: Verify error handling for missing courseId parameter

The query field is well-structured and properly secured with user authentication. However, since courseId is optional, we should verify how AnalyticsService handles the case when it's not provided.

✅ Verification successful

Let me search for the implementation of getCourseWeeklyActivity in the AnalyticsService.


Let me try a different search pattern to locate the implementation.


Let me try one final search pattern to locate the service implementation.


I see the analytics service is likely in packages/graphql/src/services/analytics.ts. Let me check its implementation.


Error handling for missing courseId parameter is properly implemented

The implementation in analytics.ts correctly handles the case when courseId is not provided by returning null. This is consistent with the GraphQL field definition where the return type is marked as nullable. The function also includes proper authorization checks by verifying course ownership through ownerId: ctx.user.sub.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how AnalyticsService handles missing courseId

# Look for error handling in analytics service
rg -A 5 "getCourseWeeklyActivity.*ctx" 

Length of output: 366


Script:

#!/bin/bash
# Search for the implementation of getCourseWeeklyActivity
ast-grep --pattern 'getCourseWeeklyActivity($$$) {
  $$$
}'

# Also try with ripgrep to catch any other implementations
rg -A 10 "getCourseWeeklyActivity.*=.*" 

Length of output: 103


Script:

#!/bin/bash
# Search for AnalyticsService class and its methods
rg -A 20 "class AnalyticsService" 

# Also search for any file containing AnalyticsService
fd "analytics" --type f --exec rg -l "AnalyticsService"

Length of output: 89


Script:

#!/bin/bash
# Search for files with 'analytics' in their name
fd "analytics" --type f

# Search for any exports or declarations related to AnalyticsService
rg "export.*AnalyticsService|const.*AnalyticsService|class.*AnalyticsService" -A 10

Length of output: 1757


Script:

#!/bin/bash
# Check the implementation of getCourseWeeklyActivity in the analytics service
cat packages/graphql/src/services/analytics.ts

Length of output: 2364

packages/graphql/src/public/schema.graphql (1)

1244-1244: LGTM: Type definition is well-structured

The WeeklyCourseActivities type is properly defined with:

  • Non-nullable fields ensuring data consistency
  • Reuse of existing ParticipantActivityTimestamp type
  • Clear integration with the new query field

The schema changes align well with the query implementation in query.ts.

Also applies to: 1479-1481

packages/i18n/messages/en.ts (1)

1827-1831: LGTM! Localization strings for course comparison feature are well structured.

The new strings provide clear and consistent translations for the course comparison feature. The descriptions are user-friendly and maintain consistency between English and German translations.

packages/graphql/src/ops.schema.json (2)

18746-18770: LGTM! Well-structured query field addition

The new getCourseWeeklyActivity query field is well-defined with appropriate parameter and return type to support weekly activity data retrieval.


21994-22045: LGTM! Well-designed type definition

The new WeeklyCourseActivities type is well-structured with:

  • Clear field naming
  • Proper nullability constraints
  • Good reuse of existing ParticipantActivityTimestamp type for consistency
packages/graphql/src/public/client.json (1)

124-124: LGTM: New operation hash added correctly

The new hash entry for GetCourseWeeklyActivity follows the established pattern and uses a valid SHA-256 hash.

packages/graphql/src/public/server.json (1)

124-124: LGTM: New GraphQL query properly structured

The GetCourseWeeklyActivity query is well-defined with proper types, optional parameters, and follows GraphQL best practices.

packages/i18n/messages/de.ts (2)

1839-1842: LGTM: German translations added correctly

The new translations for course comparison functionality are clear, properly formatted, and correctly use string parameters where needed.


1904-1904: LGTM: Week indicator translation added

The weekN translation is properly formatted and correctly uses the {number} parameter.

Copy link

sonarqubecloud bot commented Dec 7, 2024

@sjschlapbach sjschlapbach merged commit a799972 into v3-analytics Dec 7, 2024
14 checks passed
@sjschlapbach sjschlapbach deleted the activity-comparison branch December 7, 2024 19:47
Copy link

cypress bot commented Dec 7, 2024

klicker-uzh    Run #3798

Run Properties:  status check passed Passed #3798  •  git commit 7cada6f1dd ℹ️: Merge 18f4a1029bda8b73f80e252f6b7e01f6517ceda7 into b8a134aec969f2f369a345ba71ca...
Project klicker-uzh
Branch Review activity-comparison
Run status status check passed Passed #3798
Run duration 12m 17s
Commit git commit 7cada6f1dd ℹ️: Merge 18f4a1029bda8b73f80e252f6b7e01f6517ceda7 into b8a134aec969f2f369a345ba71ca...
Committer Julius Schlapbach
View all properties for this run ↗︎

Test results
Tests that failed  Failures 0
Tests that were flaky  Flaky 0
Tests that did not run due to a developer annotating a test with .skip  Pending 0
Tests that did not run due to a failure in a mocha hook  Skipped 0
Tests that passed  Passing 148
View all changes introduced in this branch ↗︎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

1 participant