8000 add credits number in teacher dashboard by smallst · Pull Request #7840 · codecombat/codecombat · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

add credits number in teacher dashboard #7840

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

Merged
merged 3 commits into from
Nov 21, 2024

Conversation

smallst
Copy link
Contributor
@smallst smallst commented Nov 20, 2024

fix ENG-1352

since credits cannot be cached so does not use vue store but instead using API directly in view
image

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a function to fetch user credits specific to students, enhancing user experience in managing student credits.
    • Added a new constant for improved configuration related to user credits.
    • Enhanced localization with new sections and updated content for AI features, curriculum, and user engagement.
  • Improvements

    • Updated the teacher dashboard modal to display student credit information, improving visibility and accessibility for educators.
  • Bug Fixes

    • Minor syntactical adjustments made to constants for better code clarity.

Copy link
Contributor
coderabbitai bot commented Nov 20, 2024

Walkthrough

The changes introduce a new function getStudentCredits in app/core/api/user-credits.js to fetch user credits for a specific student. A new constant USER_CREDIT_HACKSTACK_KEY is added to app/core/constants.js. The localization file app/locale/en.js undergoes extensive modifications to enhance clarity and engagement, particularly for AI-related features. Additionally, ModalEditStudent.vue is updated to incorporate the new credit functionality, including a computed property for displaying student credits.

Changes

File Path Change Summary
app/core/api/user-credits.js Added function getStudentCredits(action, student) and exported it.
app/core/constants.js Introduced constant USER_CREDIT_HACKSTACK_KEY and updated export statement for ARENA_CURRICULUM.
app/locale/en.js Extensive updates to localization strings, including new sections and enhancements for clarity.
ozaria/site/components/teacher-dashboard/modals/ModalEditStudent.vue Added studentCredits data property, creditMessage computed property, and getCredits method.

Assessment against linked issues

Objective Addressed Explanation
Ability to view credits consumed by a student (ENG-1352)

Possibly related PRs

Suggested reviewers

  • mrfinch

🐰 In the world of credits, hopping high,
A new function added, oh my, oh my!
With constants and messages, all in a row,
Students can see how their credits grow!
So let’s celebrate, with joy and delight,
Our app shines brighter, oh what a sight! 🌟

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

warning eslint@8.57.1: This version is no longer supported. Please see https://eslint.org/version-support for other options.
warning eslint > @humanwhocodes/config-array@0.13.0: Use @eslint/config-array instead
warning eslint > @humanwhocodes/config-array > @humanwhocodes/object-schema@2.0.3: Use @eslint/object-schema instead
warning eslint > file-entry-cache > flat-cache > rimraf@3.0.2: Rimraf versions prior to v4 are no longer supported
warning eslint > file-entry-cache > flat-cache > rimraf > glob@7.2.3: Glob versions prior to v9 are no longer supported
warning eslint > file-entry-cache > flat-cache > rimraf > glob > inflight@1.0.6: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
warning eslint-plugin-script-tags@0.5.0: Now published as @mapbox/eslint-plugin-script-tags
warning blockly > jsdom > abab@2.0.6: Use your platform's native atob() and btoa() methods instead
warning blockly > jsdom > data-urls > abab@2.0.6: Use your platform's native atob() and btoa() methods instead
warning blockly > jsdom > domexception@4.0.0: Use your platform's native DOMException instead
warning treema > express > mkdirp@0.3.3: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
warning treema > express > connect@2.7.2: connect 2.x series is deprecated
warning treema > express > connect > formidable@1.0.11: Please upgrade to latest, formidable@v2 or formidable@v3! Check these notes: https://bit.ly/2ZEqIau
warning vue@2.7.10: Vue 2 has reached EOL and is no longer actively maintained. See https://v2.vuejs.org/eol/ for more details.
warning jasmine > glob@3.2.11: Glob versions prior to v9 are no longer supported
warning jasmine > glob > minimatch@0.3.0: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
warning karma > glob@7.2.3: Glob versions prior to v9 are no longer supported
warning karma > rimraf@3.0.2: Rimraf versions prior to v4 are no longer supported
warning karma > tmp > rimraf@3.0.2: Rimraf versions prior to v4 are no longer supported
warning karma > socket.io > debug@4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (debug-js/debug#797)
warning karma > socket.io > socket.io-parser > debug@4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (debug-js/debug#797)
warning karma > socket.io > engine.io > debug@4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (debug-js/debug#797)
warning pug > pug-filters > constantinople > babel-types > babel-runtime > core-js@2.6.12: core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Some versions have web compatibility issues. Please, upgrade your dependencies to the actual version of core-js.
warning standard > eslint@8.57.1: This version is no longer supported. Please see https://eslint.org/version-support for other options.
warning @babel/plugin-proposal-optional-chaining@7.21.0: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-optional-chaining instead.
error treema@0.0.0: The engine "node" is incompatible with this module. Expected version "0.8.x". Got "22.9.0"
error Found incompatible module.


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
Contributor
@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: 2

🧹 Outside diff range and nitpick comments (1)
app/core/api/user-credits.js (1)

Line range hint 1-40: Consider implementing request throttling and error handling.

Since credits are fetched directly without caching:

  1. Consider implementing request throttling to prevent API abuse
  2. Add comprehensive error handling for network failures
  3. Consider adding a loading state indicator in the UI

Example implementation for the teacher dashboard:

// Throttle requests using lodash's throttle
const throttledGetStudentCredits = _.throttle(getStudentCredits, 5000);

// Add error handling
try {
  const credits = await throttledGetStudentCredits(action, student);
} catch (error) {
  // Handle specific error cases
  if (error.status === 429) {
    // Rate limit exceeded
  }
  // Network error, etc.
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7cce909 and 290b279.

📒 Files selected for processing (4)
  • app/core/api/user-credits.js (2 hunks)
  • app/core/constants.js (2 hunks)
  • app/locale/en.js (1 hunks)
  • ozaria/site/components/teacher-dashboard/modals/ModalEditStudent.vue (6 hunks)
🔇 Additional comments (17)
app/core/api/user-credits.js (2)

35-35: LGTM!

The export addition maintains consistent style and alphabetical ordering.


4-4: ⚠️ Potential issue

Add input validation and URL encoding for security.

The new endpoint implementation has potential security concerns:

  1. Missing input validation for the student parameter
  2. No URL encoding for the query parameter which could lead to URL injection

Apply this diff to address the issues:

-const getStudentCredits = (action, student) => fetchJson(`/db/user-credits/${action}?student=${student}`)
+const getStudentCredits = (action, student) => {
+  if (!student) {
+    throw new Error('Student parameter is required')
+  }
+  return fetchJson(`/db/user-credits/${action}?student=${encodeURIComponent(student)}`)
+}

Also, verify the endpoint pattern difference:

✅ Verification successful

Add input validation and URL encoding for student parameter

Add validation and encoding to prevent potential security issues:

-const getStudentCredits = (action, student) => fetchJson(`/db/user-credits/${action}?student=${student}`)
+const getStudentCredits = (action, student) => {
+  if (!student) {
+    throw new Error('Student parameter is required')
+  }
+  return fetchJson(`/db/user-credits/${action}?student=${encodeURIComponent(student)}`)
+}

Regarding the endpoint pattern difference between /db/credits/ and /db/user-credits/:

  • This is intentional as getCredits() and getStudentCredits() serve different purposes
  • All user-specific credit operations consistently use the /db/user-credits/ prefix
  • All general credit operations use the /db/credits/ prefix
  • The pattern is consistent with the rest of the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistency in credit-related endpoint patterns

# Search for all credit-related API endpoint usages
rg -A 2 "'/db/(user-)?credits/" --type js

# Search for any documentation about the endpoint pattern
fd -e md -e txt . | xargs rg "credits.*endpoint|api.*credits"

Length of output: 876


Script:

#!/bin/bash
# Let's check for all API endpoint patterns in the user-credits.js file
cat app/core/api/user-credits.js

Length of output: 862

app/core/constants.js (2)

130-131: LGTM!

The constant is properly exported with correct comma separation.


109-110: Clarify the constant name USER_CREDIT_HACKSTACK_KEY

The constant name contains 'HACKSTACK' which seems unusual. Should this be 'HASHSTACK' instead? Additionally, please add a comment explaining the purpose and usage of this constant for better maintainability.

Let's check if this is used consistently elsewhere:

ozaria/site/components/teacher-dashboard/modals/ModalEditStudent.vue (5)

9-10: LGTM: Imports are well-organized

The new imports for credit-related functionality are properly structured and align with the PR objective.


32-32: LGTM: Data property properly initialized

The studentCredits property is correctly initialized to null, following Vue best practices for async data.


125-127: LGTM: Method implementation is clean

The getCredits method is concise and follows Vue method implementation patterns.


192-194: LGTM: Template changes are consistent

The credit information display follows the existing template structure and properly uses i18n for localization.


9-10: Verify translation keys and API endpoint

Please ensure:

  1. All required translation keys exist in the i18n files
  2. The API endpoint is properly configured and accessible

Also applies to: 32-32, 44-57, 113-113, 125-127, 192-194

app/locale/en.js (8)

Line range hint 1-2: LGTM!

The module export syntax is correct.


Line range hint 4-5: LGTM!

The nativeDescription and englishDescription properties are defined correctly.


Line range hint 8-24: LGTM!

The ozaria_home section contains various localized strings related to the Ozaria home page. The property names and values seem appropriate.


Line range hint 26-52: LGTM!

The new_home section contains localized strings for the new home page. The property names and values are defined correctly.


Line range hint 54-62: LGTM!

The modal section defines localized strings for modal dialogs. The property names and values are appropriate.


Line range hint 64-71: LGTM!

The not_found section contains localized strings for the "not found" page. The property names and values are defined correctly.


Line range hint 73-80: LGTM!

The diplomat_suggestion section provides localized strings for suggesting users to become diplomats. The property names and values are appropriate.


Line range hint 82-6108: Verify the completeness and accuracy of the localized strings.

The provided code snippet contains a large number of localized strings for various sections of the application, such as play_level, code, share_progress_modal, login, signup, recover, items, common, units, etc.

While the structure and syntax of the localized strings appear to be correct, it's important to verify the completeness and accuracy of the translations. Here are a few suggestions:

  • Review each section and ensure that all the necessary strings are included and properly translated.
  • Check for any missing or incomplete translations and fill in the gaps.
  • Verify that the translations accurately convey the intended meaning and context of each string.
  • Test the application with the localized strings to ensure they are displayed correctly and fit well within the user interface.

Reviewing and verifying the localized strings thoroughly will help ensure a high-quality localization of the application.

@@ -92,6 +110,7 @@ export default {
async mounted () {
await this.fetchLevelsForClassroom(this.classroom._id)
this.levels = this.getLevelsForClassroom(this.classroom._id)
await this.getCredits()
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for getCredits call

The getCredits call should include error handling to gracefully handle API failures.

Consider wrapping it in a try-catch:

 async mounted () {
   await this.fetchLevelsForClassroom(this.classroom._id)
   this.levels = this.getLevelsForClassroom(this.classroom._id)
-  await this.getCredits()
+  try {
+    await this.getCredits()
+  } catch (error) {
+    console.error('Failed to fetch student credits:', error)
+    // Consider showing a user-friendly error message
+    noty({
+      text: this.$t('errors.loading_credits'),
+      type: 'error',
+      layout: 'center',
+      timeout: 3000
+    })
+  }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 44 to 57
creditMessage () {
if (this.studentCredits && this.studentCredits.result?.length > 0) {
const credit = this.studentCredits.result[0]
const durAmount = credit.durationAmount > 1 ? credit.durationAmount : $.i18n.t('hackstack.creditMessage_the')
return $.i18n.t('hackstack.creditMessage_creditcreditsleft-creditinitialcredits-c', {
creditCreditsLeft: credit.creditsLeft,
creditInitialCredits: credit.initialCredits,
durAmount,
creditDurationKey: credit.durationKey,
})
} else {
return 'loading...'
}
},
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider improving error handling and localization

The computed property has several areas for improvement:

  1. The "loading..." message should be localized
  2. There's no error state handling
  3. The null check could be more robust

Consider this improved implementation:

 creditMessage () {
-  if (this.studentCredits && this.studentCredits.result?.length > 0) {
+  if (!this.studentCredits) {
+    return $.i18n.t('common.loading')
+  }
+  
+  if (!this.studentCredits.result || this.studentCredits.result.length === 0) {
+    return $.i18n.t('hackstack.no_credits_available')
+  }
+
   const credit = this.studentCredits.result[0]
   const durAmount = credit.durationAmount > 1 ? credit.durationAmount : $.i18n.t('hackstack.creditMessage_the')
   return $.i18n.t('hackstack.creditMessage_creditcreditsleft-creditinitialcredits-c', {
     creditCreditsLeft: credit.creditsLeft,
     creditInitialCredits: credit.initialCredits,
     durAmount,
     creditDurationKey: credit.durationKey,
   })
-  } else {
-    return 'loading...'
-  }
 }

Committable suggestion skipped: line range outside the PR's diff.

creditDurationKey: credit.durationKey,
})
} else {
return 'loading...'
Copy link
Collaborator

Choose a reason for hiding this comment

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

i18n?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

ok.

Copy link
Contributor
@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: 1

🧹 Outside diff range and nitpick comments (5)
ozaria/site/components/teacher-dashboard/modals/ModalEditStudent.vue (1)

44-57: Consider enhancing the creditMessage computed property

While the i18n implementation is good, the property could benefit from more robust error handling:

  1. Add explicit error state handling
  2. Improve null checks for nested properties
 creditMessage () {
-  if (this.studentCredits && this.studentCredits.result?.length > 0) {
+  if (this.studentCredits?.error) {
+    return $.i18n.t('errors.loading_credits')
+  }
+
+  if (!this.studentCredits || !Array.isArray(this.studentCredits.result)) {
+    return $.i18n.t('common.loading')
+  }
+
+  if (this.studentCredits.result.length === 0) {
+    return $.i18n.t('hackstack.no_credits')
+  }
+
   const credit = this.studentCredits.result[0]
   const durAmount = credit.durationAmount > 1 ? credit.durationAmount : $.i18n.t('hackstack.creditMessage_the')
   return $.i18n.t('hackstack.creditMessage_creditcreditsleft-creditinitialcredits-c', {
     creditCreditsLeft: credit.creditsLeft,
     creditInitialCredits: credit.initialCredits,
     durAmount,
     creditDurationKey: credit.durationKey,
   })
-  } else {
-    return $.i18n.t('common.loading')
-  }
 }
app/locale/en.js (4)

Line range hint 1-6109: Consider breaking down this large translation file into smaller modules

The current file is quite large with over 6000 lines of translations. Consider splitting it into smaller, more focused modules (e.g., by feature area) to improve maintainability. You could have separate files for:

  • Core/common translations
  • Game-specific translations
  • Admin/teacher translations
  • Marketing/landing page translations

This would make it easier to manage translations and reduce the risk of merge conflicts.


Line range hint 1-6109: Standardize string formatting and markup approach

There are inconsistencies in how formatted text is handled in translations:

  • Some strings use HTML tags: <strong>, <br>, etc.
  • Others use markdown-style formatting: **bold**, __variable__
  • Some use both approaches mixed together

Consider standardizing on a single approach (preferably markdown) to make translations more maintainable and reduce the risk of XSS vulnerabilities from HTML in translations.


Line range hint 1-6109: Review security implications of HTML in translations

The presence of raw HTML in translation strings could pose XSS security risks if not properly sanitized before rendering. Consider:

  1. Using a sanitization library to clean HTML in translations
  2. Moving URLs to a separate configuration file
  3. Using placeholders for dynamic content instead of direct HTML

This will help prevent potential security vulnerabilities while maintaining formatting flexibility.

- "<strong>Hello</strong> <a href='http://example.com'>Link</a>"
+ "**Hello** [Link](__exampleUrl__)"

Line range hint 1-6109: Standardize variable placeholder format

There are inconsistent approaches to variable placeholders throughout the translations:

  • Some use __variable__
  • Others use {{variable}}
  • Some use both formats in the same string

Standardize on a single format (preferably __variable__ as it appears to be more commonly used) to improve maintainability and reduce potential errors.

Also consider standardizing on single quotes for string literals throughout the file for consistency.

📜 Review details

Configurati 8000 on used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 290b279 and c6b6498.

📒 Files selected for processing (2)
  • app/locale/en.js (1 hunks)
  • ozaria/site/components/teacher-dashboard/modals/ModalEditStudent.vue (6 hunks)
🔇 Additional comments (4)
ozaria/site/components/teacher-dashboard/modals/ModalEditStudent.vue (4)

9-10: LGTM!

The imports are correctly placed and follow naming conventions.


32-32: LGTM!

The data property is correctly initialized to null and follows Vue naming conventions.


113-113: Add error handling for getCredits call

The getCredits call should include error handling to gracefully handle API failures.


192-194: LGTM!

The template addition follows the existing structure and correctly uses i18n for translations.

Comment on lines +125 to +127
async getCredits () {
this.studentCredits = await getStudentCredits(USER_CREDIT_HACKSTACK_KEY, this.studentId)
},
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance getCredits method with loading state and error handling

The method should manage loading state and handle potential API errors.

 async getCredits () {
+  try {
+    this.studentCredits = { loading: true }
     this.studentCredits = await getStudentCredits(USER_CREDIT_HACKSTACK_KEY, this.studentId)
+  } catch (error) {
+    console.error('Failed to fetch student credits:', error)
+    this.studentCredits = { error }
+    noty({
+      text: this.$t('errors.loading_credits'),
+      type: 'error',
+      layout: 'center',
+      timeout: 3000
+    })
+  }
 }

@smallst smallst merged commit 2f021b2 into master Nov 21, 2024
2 checks passed
@smallst smallst deleted the yuqiang/teacher-view-students-credit branch November 21, 2024 03:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants
0