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

fix(apps/frontend-manage): ensure that course dates can be modified despite missing activities #4336

Merged
merged 4 commits into from
Oct 24, 2024

Conversation

sjschlapbach
Copy link
Member

@sjschlapbach sjschlapbach commented Oct 24, 2024

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Improved handling of default values for grading calculations and visual components to ensure robustness against null and undefined values across various components.
  • New Features

    • Enhanced score calculation logic across various components, ensuring accurate handling of pointsMultiplier and date calculations in course settings.
    • Updated rendering logic for displaying solution ranges in evaluation components, improving clarity for end-users.
  • Documentation

    • Updated comments and explanations to reflect changes in logic and handling of default values.

These updates enhance the overall stability and user experience of the grading and evaluation features.

Copy link

aviator-app bot commented Oct 24, 2024

Current Aviator status

Aviator will automatically update this comment as the status of the PR changes.
Comment /aviator refresh to force Aviator to re-examine your PR (or learn about other /aviator commands).

This PR was merged manually (without Aviator). Merging manually can negatively impact the performance of the queue. Consider using Aviator next time.


See the real-time status of this PR on the Aviator webapp.
Use the Aviator Chrome Extension to see the status of your PR within GitHub.

Copy link

coderabbitai bot commented Oct 24, 2024

📝 Walkthrough

Walkthrough

This pull request introduces several modifications across various components and hooks within the frontend application. The primary focus is on improving the handling of default values using the nullish coalescing operator (??) instead of the logical OR operator (||). This change ensures that default values are only applied when dealing with null or undefined, enhancing the robustness of calculations related to scores, date handling, and rendering logic. Overall, the structure and functionality of the components remain intact, with no new features introduced.

Changes

File Path Change Summary
apps/frontend-manage/src/components/courses/groupActivity/GroupActivityGradingStack.tsx Updated pointsMultiplier handling to use ?? for defaulting to 1.
apps/frontend-manage/src/components/evaluation/elements/NumericalSidebar.tsx Changed range.min and range.max to use ?? for defaulting to '-∞' and '+∞'.
apps/frontend-manage/src/components/evaluation/hooks/useEvaluationHistogramData.tsx Updated fallback for min and max values to use ?? instead of `
apps/frontend-manage/src/components/questions/manipulation/StudentElementPreview.tsx Changed handling of pointsMultiplier to use ?? for defaulting to '1'.
apps/frontend-manage/src/components/questions/manipulation/helpers.ts Enhanced checks for min, max, and maxLength in prepareNumericalArgs and prepareFreeTextArgs.
apps/frontend-manage/src/components/sessions/cockpit/SessionTimeline.tsx Updated activeBlockId determination to use ?? for defaulting to -1.
apps/frontend-manage/src/components/sessions/creation/liveQuiz/AdvancedLiveQuizSettings.tsx Changed calculations for maxBonusValue and timeToZeroValue to use ?? for defaulting to 0.
apps/frontend-manage/src/components/sessions/evaluation/QuestionEvaluation.tsx Updated solutionRanges min/max display to use ?? for defaulting to '-∞' and '+∞'.
apps/frontend-manage/src/lib/hooks/useEarliestLatestCourseDates.ts Enhanced date calculations with checks for empty arrays to prevent errors.
apps/frontend-manage/src/pages/courses/grading/groupActivity/[id].tsx Modified maxPoints calculation to use ?? for pointsMultiplier.
apps/frontend-pwa/src/components/practiceQuiz/ElementSummary.tsx Updated stacks type to any and changed calculations for totalPointsAwarded and totalXpAwarded to use ??.
packages/grading/src/index.ts Updated default value handling in computeAwardedPoints to use ?? instead of `
packages/graphql/src/services/practiceQuizzes.ts Adjusted response handling to use ?? for default values in several functions.
packages/prisma/src/data/seedTEST.ts Updated seeding logic to use ?? for maxPoints and added new group activities and microlearning entries.
packages/shared-components/src/Histogram.tsx Changed min/max value handling to use ?? for defaulting to 0.

Possibly related PRs

Suggested reviewers

  • rschlaefli

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7953cdd and 96f16dd.

📒 Files selected for processing (15)
  • apps/frontend-manage/src/components/courses/groupActivity/GroupActivityGradingStack.tsx (2 hunks)
  • apps/frontend-manage/src/components/evaluation/elements/NumericalSidebar.tsx (1 hunks)
  • apps/frontend-manage/src/components/evaluation/hooks/useEvaluationHistogramData.tsx (1 hunks)
  • apps/frontend-manage/src/components/questions/manipulation/StudentElementPreview.tsx (1 hunks)
  • apps/frontend-manage/src/components/questions/manipulation/helpers.ts (1 hunks)
  • apps/frontend-manage/src/components/sessions/cockpit/SessionTimeline.tsx (1 hunks)
  • apps/frontend-manage/src/components/sessions/creation/liveQuiz/AdvancedLiveQuizSettings.tsx (1 hunks)
  • apps/frontend-manage/src/components/sessions/evaluation/QuestionEvaluation.tsx (1 hunks)
  • apps/frontend-manage/src/lib/hooks/useEarliestLatestCourseDates.ts (1 hunks)
  • apps/frontend-manage/src/pages/courses/grading/groupActivity/[id].tsx (1 hunks)
  • apps/frontend-pwa/src/components/practiceQuiz/ElementSummary.tsx (1 hunks)
  • packages/grading/src/index.ts (2 hunks)
  • packages/graphql/src/services/practiceQuizzes.ts (4 hunks)
  • packages/prisma/src/data/seedTEST.ts (2 hunks)
  • packages/shared-components/src/Histogram.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/frontend-manage/src/components/sessions/evaluation/QuestionEvaluation.tsx
🔇 Additional comments (19)
apps/frontend-manage/src/components/evaluation/hooks/useEvaluationHistogramData.tsx (1)

30-30: LGTM! Improved handling of zero values in responses.

The switch from logical OR (||) to nullish coalescing (??) operator is a good improvement. This ensures that valid zero values in responses are preserved rather than being replaced with the fallback value, which is crucial for accurate histogram generation.

Also applies to: 34-34

apps/frontend-manage/src/lib/hooks/useEarliestLatestCourseDates.ts (1)

54-57: LGTM! Robust handling of empty group activity dates.

The empty array check before calculating earliestGroupDeadline prevents potential issues with Math.min when no group activities are present.

apps/frontend-manage/src/components/evaluation/elements/NumericalSidebar.tsx (1)

71-71: LGTM! Improved handling of edge cases with nullish coalescing.

The change from logical OR to nullish coalescing operator is correct as it ensures that valid numerical values like 0 are properly displayed instead of being replaced with infinity symbols.

apps/frontend-manage/src/components/questions/manipulation/helpers.ts (1)

119-127: Verify consistent validation patterns across the codebase.

Let's ensure that similar validation patterns are consistently implemented across the codebase, particularly in date-related components mentioned in the PR objective.

apps/frontend-manage/src/components/questions/manipulation/StudentElementPreview.tsx (1)

48-48: LGTM! Improved handling of default values.

The change from || to ?? for pointsMultiplier is a good improvement. The nullish coalescing operator ensures that only null or undefined values default to '1', while preserving other valid values (including '0') that would have been coerced by the logical OR operator.

packages/grading/src/index.ts (2)

165-167: LGTM! Improved handling of zero points.

The change from || to ?? ensures that legitimate zero point values are preserved rather than being converted to the default. This is more accurate for grading calculations.


170-172: LGTM! Consistent handling of default values.

The change maintains consistency with the previous improvement, ensuring accurate point calculations when maximum points are awarded.

apps/frontend-manage/src/pages/courses/grading/groupActivity/[id].tsx (1)

53-53: Improved handling of default points multiplier.

The change from || to ?? operator is a good improvement. It ensures that a pointsMultiplier of 0 is respected rather than being replaced with the default value of 1. This makes the points calculation more accurate when an activity is intentionally configured with zero points.

Let's verify if there are any activities with zero points that might have been affected:

apps/frontend-pwa/src/components/practiceQuiz/ElementSummary.tsx (2)

48-49: LGTM! Good use of the nullish coalescing operator.

The change from || to ?? operator is a good practice as it only falls back to the default value when the left operand is null or undefined, not for all falsy values.


Line range hint 13-201: Verify the status of commented code.

A significant portion of the component is commented out. This could indicate incomplete changes or debugging leftovers.

Let's check if this is intentional:

✅ Verification successful

The git history shows that this file was created in commit b25feb1 as part of a larger refactoring effort titled "refactor: remove or rename code related to learning elements and add scripts to fix db inconsistencies (#4037)". Let me verify if this is part of an ongoing refactoring by checking related files.


Let me check one more thing to see how ElementSummary is being used in the practice quiz components:


Based on the evidence gathered, I can now provide a final response:

The commented code is part of an intentional refactoring

The commented code in ElementSummary.tsx is part of a planned refactoring effort, as evidenced by:

  1. The comment "TODO: re-introduce summary page for practice quiz" in PracticeQuiz.tsx
  2. ElementSummary component is commented out in PracticeQuiz.tsx's render logic
  3. The file was introduced in commit b25feb1 as part of a larger refactoring effort to "remove or rename code related to learning elements"

The code is intentionally commented out as a temporary state while the summary page functionality is being reworked, and should not be removed as it will be re-introduced in a future update.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for similar patterns of commented code in the codebase
# and recent commit history to understand if this is part of a larger refactor.

# Check for other files with large commented sections
echo "Checking for other files with large commented sections..."
rg -l "\/\*[\s\S]{500,}\*\/" || rg -l "\/\/[\s\S]{500,}"

# Check git history for this file
echo "Checking recent changes to this file..."
git log -p -- apps/frontend-pwa/src/components/practiceQuiz/ElementSummary.tsx

Length of output: 11281


Script:

#!/bin/bash
# Check for other files in the practice quiz directory
echo "Checking practice quiz components..."
fd . apps/frontend-pwa/src/components/practiceQuiz/

# Check for references to ElementSummary
echo -e "\nChecking for references to ElementSummary..."
rg "ElementSummary" --type ts --type tsx

Length of output: 764


Script:

#!/bin/bash
# Check content of PracticeQuiz.tsx which likely imports ElementSummary
echo "Checking PracticeQuiz.tsx for ElementSummary usage..."
cat apps/frontend-pwa/src/components/practiceQuiz/PracticeQuiz.tsx

# Check if ElementSummary was recently modified in other commits
echo -e "\nChecking recent commits mentioning ElementSummary..."
git log --grep="ElementSummary" --since="3 months ago"

Length of output: 4671

packages/shared-components/src/Histogram.tsx (1)

85-85: LGTM! Improved handling of zero values in domain calculation.

The switch to the nullish coalescing operator (??) is a good improvement as it properly handles zero values in the dataset. The previous implementation using || would have ignored valid zero values, while this change ensures they're respected when calculating the histogram's domain.

Also applies to: 90-90

apps/frontend-manage/src/components/sessions/cockpit/SessionTimeline.tsx (1)

96-96: LGTM! Improved handling of falsy block IDs.

The change from || to ?? operator is correct here. This ensures that only null or undefined values from the find operation will default to -1, while preserving other falsy values (like 0) that could be valid block IDs.

Let's verify if there are any other similar patterns in the codebase that might need the same improvement:

✅ Verification successful

Let me try a different search strategy to verify this pattern.

The first command will help us find any remaining instances of the old pattern with ||. The second command will show us if this new pattern with ?? is consistently used elsewhere. The third command will give us context about block status checks in the codebase.


The change to use ?? operator is isolated and correct

The search results confirm that:

  1. There are no remaining instances of the old pattern using || with find() and -1
  2. The new pattern using ?? is only present in this file
  3. The block status check for 'ACTIVE' is uniquely used in this context

This validates that the change is appropriate for this specific use case and there are no other similar patterns in the codebase that would need the same treatment.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potential similar patterns in other files where block IDs might be handled with ||
rg -U "find\(.+\)\s*\|\|\s*-1" --type typescript

Length of output: 85


Script:

#!/bin/bash
# Search for similar patterns with ripgrep, without type specification
rg -U "find\(.+\)\s*\|\|\s*-1"

# Also search for the current pattern using nullish coalescing
rg -U "find\(.+\)\s*\?\?\s*-1"

# Search for block status checks
rg -U "block\.status\s*===\s*['\"](ACTIVE|DONE|PENDING)['\"]"

Length of output: 274

apps/frontend-manage/src/components/courses/groupActivity/GroupActivityGradingStack.tsx (3)

281-283: LGTM! Improved handling of default points multiplier.

The use of the nullish coalescing operator (??) is more appropriate here as it only applies the default value of 1 when pointsMultiplier is null or undefined, preserving other valid values including 0.


291-293: LGTM! Consistent handling of points multiplier in display.

This change maintains consistency with the validation logic, ensuring that the displayed maximum points always matches the validation constraint.


Line range hint 281-293: Verify similar default value patterns in date-related components.

Given that this PR aims to fix course date modifications, and these changes improve default value handling, we should verify similar patterns in date-related components.

✅ Verification successful

Based on the search results, I can now generate a final response since I have enough information about the usage of default value patterns in the codebase.

No changes needed in other date-related components

The search results show that the codebase consistently uses the nullish coalescing operator (??) for handling default values in date-related components, particularly in the hooks and form components. The || operator is primarily used for:

  • Boolean conditions in control flow (if statements)
  • Providing empty arrays/strings as fallbacks
  • Component prop default values

The changes in GroupActivityGradingStack.tsx align with the codebase's patterns, and there are no similar patterns in date-related components that need updating.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar patterns of || being used with dates or numeric values
# that might benefit from using ?? instead

# Look for date-related files with || operator
echo "Checking date-related files for || operator usage:"
rg -l "date|Date" apps/frontend-manage/src | xargs rg "\|\|" -A 2 -B 2

# Look for numeric value handling with || operator
echo -e "\nChecking numeric value handling with || operator:"
rg "(\d+\s*\|\|\s*\d+)|(\w+\s*\|\|\s*\d+)" apps/frontend-manage/src

Length of output: 50183

packages/graphql/src/services/practiceQuizzes.ts (3)

859-861: Improved default value handling in spaced repetition parameters.

The change from logical OR (||) to nullish coalescing (??) operator is appropriate here as it:

  1. Only falls back to default values when existingResponse properties are null or undefined
  2. Preserves falsy values like 0 which are valid in this context

1114-1116: Consistent use of nullish coalescing for content response parameters.

The changes align with the spaced repetition parameter handling in other functions, ensuring consistent behavior across the codebase.


1926-1928: Consistent default value handling in question response logic.

The changes maintain consistency with other spaced repetition parameter handling, correctly preserving falsy values.

Let's verify the consistency of this pattern across the codebase:

packages/prisma/src/data/seedTEST.ts (1)

980-980: Approve the use of ?? for default value handling

Using the nullish coalescing operator ?? ensures that pointsMultiplier values of 0 are correctly handled, while still providing a default of 1 when pointsMultiplier is null or undefined. This enhances the robustness of the maxPoints calculation.


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

cypress bot commented Oct 24, 2024

klicker-uzh    Run #3407

Run Properties:  status check passed Passed #3407  •  git commit 290e454a2d ℹ️: Merge 238f49828d3645bf46e99bbff8ef79c0d3275008 into 4e83d7d626ee5409169f910a9540...
Project klicker-uzh
Branch Review FixCourseManipulationModal
Run status status check passed Passed #3407
Run duration 10m 43s
Commit git commit 290e454a2d ℹ️: Merge 238f49828d3645bf46e99bbff8ef79c0d3275008 into 4e83d7d626ee5409169f910a9540...
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 133
View all changes introduced in this branch ↗︎

@sjschlapbach sjschlapbach marked this pull request as ready for review October 24, 2024 13:46
@sjschlapbach sjschlapbach merged commit 2a12e2c into v3 Oct 24, 2024
11 of 12 checks passed
@sjschlapbach sjschlapbach deleted the FixCourseManipulationModal branch October 24, 2024 14:04
Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
3.7% Duplication on New Code (required ≤ 3%)

See analysis details on SonarCloud

Copy link

cypress bot commented Oct 24, 2024

klicker-uzh    Run #3408

Run Properties:  status check passed Passed #3408  •  git commit 2a12e2c60d: fix(apps/frontend-manage): ensure that course dates can be modified independent ...
Project klicker-uzh
Branch Review v3
Run status status check passed Passed #3408
Run duration 10m 37s
Commit git commit 2a12e2c60d: fix(apps/frontend-manage): ensure that course dates can be modified independent ...
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 133
View all changes introduced in this branch ↗︎

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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (12)
apps/frontend-manage/src/components/evaluation/hooks/useEvaluationHistogramData.tsx (1)

30-34: Consider adding tests for edge cases.

The min/max calculations handle several cases (configured values, computed values, fallbacks). To ensure robustness, consider adding tests for edge cases:

  • Responses containing zero values
  • Empty response sets
  • Single response sets
  • Responses with all same values

Would you like me to help generate comprehensive test cases for these scenarios?

apps/frontend-manage/src/components/evaluation/elements/NumericalSidebar.tsx (1)

Line range hint 27-54: Consider removing commented-out statistics code.

The TODO comment and large block of commented code could be removed to improve code maintainability. If this feature is planned for the future, it would be better tracked in a separate issue.

Would you like me to help create a GitHub issue to track the reintroduction of statistics functionality?

apps/frontend-manage/src/components/questions/manipulation/helpers.ts (2)

119-120: LGTM! Consider DRY refactor for validation logic.

The explicit null and undefined checks improve the robustness of the validation logic. However, since this validation pattern is repeated for both min and max, consider extracting it into a helper function.

+const isEmptyRestriction = (value: any) =>
+  value === null ||
+  typeof value === 'undefined' ||
+  value === '';

 restrictions: {
   min:
     !values.options.restrictions ||
-    values.options.restrictions.min === null ||
-    typeof values.options.restrictions.min === 'undefined' ||
-    values.options.restrictions.min === ''
+    isEmptyRestriction(values.options.restrictions.min)
       ? undefined
       : parseFloat(String(values.options.restrictions.min)),
   max:
     !values.options.restrictions ||
-    values.options.restrictions.max === null ||
-    typeof values.options.restrictions.max === 'undefined' ||
-    values.options.restrictions.max === ''
+    isEmptyRestriction(values.options.restrictions.max)
       ? undefined
       : parseFloat(String(values.options.restrictions.max)),

Also applies to: 126-127


Line range hint 177-182: Fix duplicate condition in maxLength validation.

There's a duplicated condition in the maxLength validation. Additionally, consider using the same explicit validation pattern as used in numerical restrictions for consistency.

 restrictions: {
   maxLength:
-    !values.options.restrictions?.maxLength ||
-    !values.options.restrictions?.maxLength ||
+    !values.options.restrictions?.maxLength ||
+    values.options.restrictions.maxLength === null ||
+    typeof values.options.restrictions.maxLength === 'undefined' ||
     values.options.restrictions.maxLength === ''
       ? undefined
       : parseInt(String(values.options.restrictions.maxLength)),
 },
packages/grading/src/index.ts (2)

179-179: Consider adding input validation and bounds checking.

While the change to ?? operator is good, this function could benefit from additional safeguards:

  1. Input validation for negative values
  2. Bounds checking for the final result
  3. Documentation of expected value ranges

Consider adding validation:

 export function computeAwardedPoints({
   firstResponseReceivedAt,
   responseTimestamp,
   maxBonus,
   timeToZeroBonus,
   getsMaxPoints,
   defaultPoints,
   defaultCorrectPoints,
   pointsPercentage,
   pointsMultiplier,
 }: ComputeAwardedPointsArgs): number {
+  // Validate inputs
+  if (maxBonus < 0) throw new Error('maxBonus must be non-negative')
+  if (defaultPoints !== undefined && defaultPoints < 0) 
+    throw new Error('defaultPoints must be non-negative')
+  if (defaultCorrectPoints !== undefined && defaultCorrectPoints < 0)
+    throw new Error('defaultCorrectPoints must be non-negative')
+
   const slope = maxBonus / (timeToZeroBonus ?? 20)
   let awardedPoints = 0
   // ... existing code ...
   awardedPoints += defaultPoints ?? 0

-  return Math.round(awardedPoints)
+  // Ensure final result is non-negative
+  return Math.max(0, Math.round(awardedPoints))
 }

Line range hint 165-179: Consider adding unit tests for edge cases.

The changes to default value handling are good, but they highlight the need for comprehensive testing of edge cases, particularly:

  • Zero point values
  • Null/undefined inputs
  • Boundary conditions for time-based calculations
  • Combinations of different point types (default, correct, bonus)

Consider adding test cases that verify:

  1. Zero points are preserved and calculated correctly
  2. Time-based bonus calculations handle edge cases
  3. Point multipliers work correctly with zero and null values
  4. Rounding behavior maintains consistency across calculations
apps/frontend-pwa/src/components/practiceQuiz/ElementSummary.tsx (1)

Line range hint 6-6: Avoid using any type as it bypasses TypeScript's type checking.

Using any type reduces type safety and could lead to runtime errors. Consider using a more specific type or interface that accurately represents the expected stack structure.

Could you share the original stack type? This would help in suggesting a proper type definition that maintains type safety while addressing your needs.

packages/shared-components/src/Histogram.tsx (3)

85-85: Consider extracting domain padding values to constants.

The magic numbers -10 and +10 used for padding the domain could be extracted into named constants to improve maintainability and make the padding configurable.

+const DOMAIN_PADDING = 10
 const min: number =
   questionData.options.restrictions &&
   typeof questionData.options.restrictions['min'] === 'number'
     ? questionData.options.restrictions['min']
-    : (minBy(mappedData, 'value')?.value ?? 0) - 10
+    : (minBy(mappedData, 'value')?.value ?? 0) - DOMAIN_PADDING
 const max: number =
   questionData.options.restrictions &&
   typeof questionData.options.restrictions['max'] === 'number'
     ? questionData.options.restrictions['max']
-    : (maxBy(mappedData, 'value')?.value ?? 0) + 10
+    : (maxBy(mappedData, 'value')?.value ?? 0) + DOMAIN_PADDING

Also applies to: 90-90


Line range hint 91-114: Consider memoizing bin calculations for better performance.

The bin calculations in this section are performed on every render. Consider memoizing the dataArray calculations using useMemo to optimize performance, especially for large datasets.

-let dataArray = Array.from({ length: binCount }, (_, i) => ({
+const dataArray = useMemo(() => {
+ const initial = Array.from({ length: binCount }, (_, i) => ({
   value: min + (max - min) * (i / binCount) + (max - min) / (2 * binCount),
-}))
+ }));
 
-dataArray = dataArray.map((bin) => {
+ return initial.map((bin) => {
   const binWidth =
-    dataArray.length > 1 ? dataArray[1]!.value - dataArray[0]!.value : 1
+    initial.length > 1 ? initial[1]!.value - initial[0]!.value : 1
   const count = sumBy(
     mappedData.filter((result) => {
       return (
         result.value >= bin.value - binWidth / 2 &&
         (bin.value + binWidth / 2 === max
           ? result.value <= max
           : result.value < bin.value + binWidth / 2)
       )
     }),
     'count'
   )
   return {
     value: round(bin.value, 2),
     count,
     label: `${round(bin.value - binWidth / 2, 1)} - ${round(
       bin.value + binWidth / 2,
       1
     )}`,
   }
-})
+});
+}, [binCount, min, max, mappedData]);

Line range hint 249-277: Address the TODO comment regarding exact solutions support.

There's a TODO comment indicating pending migration work for exact solutions support on numerical questions. This technical debt should be tracked and addressed.

Would you like me to help create a GitHub issue to track this migration work? I can provide a detailed description of the required changes and implementation approach.

apps/frontend-manage/src/components/sessions/cockpit/SessionTimeline.tsx (1)

Line range hint 91-143: Consider optimizing state updates to prevent potential re-renders.

The useEffect hook's dependency on activeBlockId while also setting it within the effect could lead to unnecessary re-renders. Consider:

  1. Combining related state updates using a reducer
  2. Moving the activeBlockId calculation outside the effect

Here's a suggested refactor using useReducer:

interface TimelineState {
  activeBlockId: number;
  lastActiveBlockId: number;
  buttonState: 'firstBlock' | 'blockActive' | 'nextBlock' | 'endSession';
  inCooldown: boolean;
}

type TimelineAction = 
  | { type: 'UPDATE_BLOCKS'; blocks: SessionTimelineBlock[] }
  | { type: 'SET_COOLDOWN'; value: boolean };

function timelineReducer(state: TimelineState, action: TimelineAction): TimelineState {
  switch (action.type) {
    case 'UPDATE_BLOCKS': {
      const activeBlockId = action.blocks.find((block) => block.status === 'ACTIVE')?.id ?? -1;
      const lastActiveBlockId = calculateLastActiveBlockId(action.blocks);
      
      return {
        ...state,
        activeBlockId,
        lastActiveBlockId,
        buttonState: calculateButtonState(activeBlockId, lastActiveBlockId, action.blocks),
        inCooldown: activeBlockId === -1 ? false : state.inCooldown,
      };
    }
    case 'SET_COOLDOWN':
      return { ...state, inCooldown: action.value };
  }
}
packages/graphql/src/services/practiceQuizzes.ts (1)

Line range hint 1750-1754: Consider using optional chaining with nullish coalescing.

The score assignment could be simplified using optional chaining with nullish coalescing.

Consider this more concise version:

-  const score = evaluation?.score ?? 0
+  let xp: number | null
+  if (
+    elementData.type === ElementType.CONTENT ||
+    elementData.type === ElementType.FLASHCARD
+  ) {
+    xp = 0
+  } else {
+    xp = elementData.options.hasSampleSolution ? evaluation?.xp ?? 0 : 0
+  }
🛑 Comments failed to post (6)
apps/frontend-manage/src/lib/hooks/useEarliestLatestCourseDates.ts (2)

58-65: 🛠️ Refactor suggestion

Consider extracting the date calculation pattern.

The pattern for safe date calculations is repeated three times. Consider extracting it into a utility function for better maintainability.

const getSafeDate = (
  dates: number[],
  operation: 'min' | 'max'
): string | undefined => {
  if (dates.length === 0) return undefined
  const fn = operation === 'min' ? Math.min : Math.max
  return dayjs(fn.apply(null, dates)).toString()
}

// Usage in return object:
return {
  earliestGroupDeadline: getSafeDate(groupActivityStartDates, 'min'),
  earliestStartDate: getSafeDate(startDates, 'min'),
  latestEndDate: getSafeDate(endDates, 'max'),
}

This refactor would:

  1. Reduce code duplication
  2. Make the pattern more maintainable
  3. Centralize the date calculation logic

40-46: 🛠️ Refactor suggestion

Simplify the practice quiz filtering logic.

The null/undefined check can be simplified while maintaining type safety.

-        ...(practiceQuizzes
-          ?.filter(
-            (pq) =>
-              pq.availableFrom !== null &&
-              typeof pq.availableFrom !== 'undefined'
-          )
-          .map((pq) => Date.parse(pq.availableFrom)) ?? []),
+        ...(practiceQuizzes?.filter((pq) => pq.availableFrom != null)
+          .map((pq) => Date.parse(pq.availableFrom)) ?? []),

The != null check in JavaScript handles both null and undefined cases, making the explicit checks redundant.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        ...(practiceQuizzes?.filter((pq) => pq.availableFrom != null)
          .map((pq) => Date.parse(pq.availableFrom)) ?? []),
apps/frontend-manage/src/components/sessions/creation/liveQuiz/AdvancedLiveQuizSettings.tsx (3)

89-96: 🛠️ Refactor suggestion

Consider refactoring repeated number parsing logic.

The component has multiple instances of number parsing with similar validation needs. This could be simplified and made more maintainable.

Consider these improvements:

  1. Create a utility function for safe number parsing:
const safeParseInt = (value: string, fallback = 0): number => {
  const parsed = parseInt(value, 10);
  return Number.isNaN(parsed) ? fallback : parsed;
};
  1. Memoize the chart data to prevent unnecessary recalculations:
const chartData = useMemo(() => [
  {
    time: 0,
    points: SUMMED_CORRECT_PTS + safeParseInt(maxBonusValue),
  },
  {
    time: safeParseInt(timeToZeroValue),
    points: SUMMED_CORRECT_PTS,
  },
  {
    time: 2 * safeParseInt(timeToZeroValue),
    points: SUMMED_CORRECT_PTS,
  },
], [maxBonusValue, timeToZeroValue]);

89-89: ⚠️ Potential issue

Add validation for non-numeric input.

The current implementation doesn't handle invalid numeric inputs properly. If maxBonusValue is not a valid number, parseInt will return NaN which won't be caught by the nullish coalescing operator.

Consider using a more robust number parsing approach:

-SUMMED_CORRECT_PTS + (parseInt(maxBonusValue, 10) ?? 0),
+SUMMED_CORRECT_PTS + (Number.isNaN(parseInt(maxBonusValue, 10)) ? 0 : parseInt(maxBonusValue, 10)),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

                    SUMMED_CORRECT_PTS + (Number.isNaN(parseInt(maxBonusValue, 10)) ? 0 : parseInt(maxBonusValue, 10)),

92-96: ⚠️ Potential issue

Add validation for non-numeric input and ensure consistent null safety.

Similar to the bonus points calculation, the time calculations don't handle invalid numeric inputs properly. Additionally, the XAxis domain calculation at line 111 is missing the same null safety.

Apply the same robust number parsing approach:

-time: parseInt(timeToZeroValue, 10) ?? 0,
+time: Number.isNaN(parseInt(timeToZeroValue, 10)) ? 0 : parseInt(timeToZeroValue, 10),

-time: 2 * (parseInt(timeToZeroValue, 10) ?? 0),
+time: 2 * (Number.isNaN(parseInt(timeToZeroValue, 10)) ? 0 : parseInt(timeToZeroValue, 10)),

Also update the XAxis domain:

-domain={[0, 2 * parseInt(timeToZeroValue)]}
+domain={[0, 2 * (Number.isNaN(parseInt(timeToZeroValue, 10)) ? 0 : parseInt(timeToZeroValue, 10))]}

Committable suggestion was skipped due to low confidence.

packages/prisma/src/data/seedTEST.ts (1)

980-980: 🛠️ Refactor suggestion

Refactor duplicated maxPoints calculation into a helper function

The calculation of maxPoints in lines 980 and 1024 is identical. To adhere to the DRY (Don't Repeat Yourself) principle and improve maintainability, consider extracting this logic into a helper function.

Define a helper function:

function calculateMaxPoints(element) {
  return (element.options?.pointsMultiplier ?? 1) * 25; // default: 25 points
}

Then, update the lines to use the helper function:

- const maxPoints = (element.options.pointsMultiplier ?? 1) * 25 // default: 25 points
+ const maxPoints = calculateMaxPoints(element);

Also applies to: 1024-1024

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