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

refactor: remove live session tables and simplify test suite logic #4380

Open
wants to merge 20 commits into
base: v3
Choose a base branch
from

Conversation

sjschlapbach
Copy link
Member

@sjschlapbach sjschlapbach commented Dec 2, 2024

This pull requests removes the live session table and all related information and completes the renaming of the newly introduced / extended status enums. This migrations should only be merged and applied after the changes related to the live quiz migration have been applied to the production database and the status migration script has been executed.

Summary by CodeRabbit

  • New Features

    • Enhanced error handling and validation for user and participant account management.
    • Improved group activity management and participant interactions.
    • Added support for multilingual achievement fields.
    • Introduced new type for activity evaluation and confusion feedbacks in the GraphQL schema.
    • Added a script to manage Redis cache entries related to live sessions.
  • Bug Fixes

    • Addressed issues with token validation and session handling.
    • Streamlined logic for participant group management and quiz manipulations.
  • Documentation

    • Removed migration instructions from localization files, indicating discontinuation of migration support.
  • Refactor

    • Simplified handling of unique identifiers and error management across various services.
    • Updated GraphQL schema to remove deprecated types and fields.
    • Removed unnecessary fields and adjusted constraints in the Prisma schema.

Copy link

aviator-app bot commented Dec 2, 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 pull request is currently open (not queued).

How to merge

To merge this PR, comment /aviator merge or add the mergequeue label.


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 Dec 2, 2024

📝 Walkthrough

Walkthrough

This pull request introduces comprehensive changes across multiple services and schema definitions, focusing on removing legacy migration-related code, refining entity management, and streamlining data structures. The modifications primarily involve removing migrationId and sessionId fields, updating enum types, and simplifying the handling of various entities like live quizzes, group activities, and participant interactions. The changes reflect a significant effort to clean up and modernize the application's data model and service implementations.

Changes

File Change Summary
apps/backend-docker/src/app.ts Updated GraphQL server configuration, modified comment referencing entity instances
packages/graphql/src/services/accounts.ts Enhanced error handling, refined login and token management processes
packages/graphql/src/services/groups.ts Updated group activity manipulation, improved error handling and score calculations
packages/graphql/src/services/liveQuizzes.ts Refined live quiz element creation and caching processes
packages/graphql/src/services/microLearning.ts Enhanced microlearning manipulation and publication logic
packages/graphql/src/services/practiceQuizzes.ts Updated practice quiz element creation process
packages/prisma/src/prisma/schema/* Removed legacy models, updated enums, simplified entity relationships
packages/prisma/src/prisma/migrations/* Created migration scripts to drop unused columns and tables
packages/i18n/messages/*.ts Removed migration-related localization sections

Possibly related PRs

Suggested Reviewers

  • rschlaefli

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e1fa391 and 27e6ad3.

📒 Files selected for processing (3)
  • packages/graphql/src/ops.schema.json (0 hunks)
  • packages/graphql/src/ops.ts (0 hunks)
  • packages/graphql/src/public/schema.graphql (0 hunks)
💤 Files with no reviewable changes (3)
  • packages/graphql/src/ops.ts
  • packages/graphql/src/public/schema.graphql
  • packages/graphql/src/ops.schema.json
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: SonarCloud
  • GitHub Check: cypress-run
  • GitHub Check: check
  • GitHub Check: build
  • GitHub Check: Analyze (javascript)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@sjschlapbach sjschlapbach changed the title refactor: remove live session tables and corresponding logic refactor: remove live session tables and simplify test suite logic Dec 2, 2024
@sjschlapbach sjschlapbach added the blocked Pull request is waiting for another pull request to be merged label Dec 2, 2024
Copy link

cypress bot commented Dec 2, 2024

klicker-uzh    Run #4100

Run Properties:  status check passed Passed #4100  •  git commit 1cab342ca5 ℹ️: Merge 27e6ad3df9f838b6bb413e5fb692b60042e6c8f9 into e68c36792924f4d7a774fea4e262...
Project klicker-uzh
Branch Review remove-live-session
Run status status check passed Passed #4100
Run duration 13m 54s
Commit git commit 1cab342ca5 ℹ️: Merge 27e6ad3df9f838b6bb413e5fb692b60042e6c8f9 into e68c36792924f4d7a774fea4e262...
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 194
View all changes introduced in this branch ↗︎

@sjschlapbach sjschlapbach marked this pull request as ready for review December 2, 2024 08:10
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: 1

🧹 Outside diff range and nitpick comments (1)
packages/prisma/src/prisma/migrations/20241202073643_rename_status_enums/migration.sql (1)

15-15: Correct the comment to match the operation performed

The comment on line 14 states:

-- Rename status column to statusNEW on GroupActivity table

However, the actual operation is renaming statusNEW to status. Update the comment for clarity:

-- Rename statusNEW column to status on GroupActivity table
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cc424db and 9ae1f86.

📒 Files selected for processing (22)
  • apps/backend-docker/src/app.ts (1 hunks)
  • cypress/cypress/e2e/F-live-quiz-workflow.cy.ts (2 hunks)
  • cypress/cypress/support/commands.ts (4 hunks)
  • packages/graphql/src/services/accounts.ts (0 hunks)
  • packages/graphql/src/services/groups.ts (0 hunks)
  • packages/graphql/src/services/liveQuizzes.ts (0 hunks)
  • packages/graphql/src/services/microLearning.ts (0 hunks)
  • packages/graphql/src/services/practiceQuizzes.ts (0 hunks)
  • packages/graphql/src/services/questions.ts (0 hunks)
  • packages/graphql/src/services/stacks.ts (4 hunks)
  • packages/prisma/src/data/helpers.ts (0 hunks)
  • packages/prisma/src/data/seedFlashcards.ts (0 hunks)
  • packages/prisma/src/data/seedTEST.ts (0 hunks)
  • packages/prisma/src/prisma/migrations/20241202072541_remove_live_session/migration.sql (1 hunks)
  • packages/prisma/src/prisma/migrations/20241202073643_rename_status_enums/migration.sql (1 hunks)
  • packages/prisma/src/prisma/schema/course.prisma (0 hunks)
  • packages/prisma/src/prisma/schema/element.prisma (1 hunks)
  • packages/prisma/src/prisma/schema/gamification.prisma (0 hunks)
  • packages/prisma/src/prisma/schema/participant.prisma (0 hunks)
  • packages/prisma/src/prisma/schema/quiz.prisma (3 hunks)
  • packages/prisma/src/prisma/schema/response.prisma (2 hunks)
  • packages/prisma/src/prisma/schema/user.prisma (1 hunks)
💤 Files with no reviewable changes (12)
  • packages/prisma/src/prisma/schema/course.prisma
  • packages/prisma/src/data/seedFlashcards.ts
  • packages/graphql/src/services/questions.ts
  • packages/graphql/src/services/practiceQuizzes.ts
  • packages/prisma/src/prisma/schema/participant.prisma
  • packages/prisma/src/prisma/schema/gamification.prisma
  • packages/prisma/src/data/helpers.ts
  • packages/graphql/src/services/liveQuizzes.ts
  • packages/graphql/src/services/microLearning.ts
  • packages/graphql/src/services/groups.ts
  • packages/prisma/src/data/seedTEST.ts
  • packages/graphql/src/services/accounts.ts
🔇 Additional comments (10)
cypress/cypress/e2e/F-live-quiz-workflow.cy.ts (1)

618-623: Verify if adding duplicate questions to blocks is intentional.

In the cy.createBlocks call, the same question is added twice to the same block:

{ questions: [questionTitle1, questionTitle1] },
{ questions: [questionTitle2, questionTitle2] },

Please confirm whether this duplication is intentional, as it may cause the same question to appear multiple times in the quiz, which could confuse users.

packages/prisma/src/prisma/schema/element.prisma (1)

147-148: LGTM

The type field in the ElementStack model is correctly defined as ElementStackType. This aligns with the consolidation of type definitions and ensures consistency within the model.

packages/prisma/src/prisma/schema/quiz.prisma (3)

310-311: ⚠️ Potential issue

Ensure no NULL values before altering liveQuizId to NOT NULL

The liveQuizId field in the ConfusionTimestep model is being changed to be non-nullable. Verify that there are no existing ConfusionTimestep records with liveQuizId set to NULL, as this will cause the migration to fail.

Run the following script to confirm there are no NULL values:

✅ Verification successful

Migration is safe - liveQuizId was already required

Based on the migration history found in the output, this change is safe. The field was already made non-nullable in a previous migration as evidenced by:

-- Made the column `liveQuizId` on table `ConfusionTimestep` required. This step will fail if there are existing NULL values in that column.
ALTER TABLE "ConfusionTimestep" DROP COLUMN "sessionId",
ALTER COLUMN "liveQuizId" SET NOT NULL;

The current schema change is just reflecting the existing database state in the Prisma schema, not actually modifying the database constraint.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for NULL values in `liveQuizId` in the `ConfusionTimestep` table.

rg 'liveQuizId[\s]*=[\s]*null' -t sql

Length of output: 39


Script:

#!/bin/bash
# Let's check the schema history and migrations to understand if liveQuizId was nullable before
fd -e sql . prisma/migrations --exec cat {} | rg -i "confusion.*live.*quiz|live.*quiz.*confusion" -B2 -A2

# Also check the schema definition history
fd schema.prisma . --exec cat {} | rg "ConfusionTimestep.*{|liveQuiz" -B2 -A2

Length of output: 428


Script:

#!/bin/bash
# Let's check the schema history and migrations with corrected paths and patterns
fd -e prisma . | xargs cat | rg "ConfusionTimestep|liveQuiz" -B2 -A2

# Also search for any migration files
fd -e sql . | xargs cat | rg -i "confusion.*timestep|live.*quiz" -B2 -A2

Length of output: 10480


201-201: Verify updates to status enums across the codebase

The status field in the GroupActivity model has been changed to use PublicationStatus instead of GroupActivityStatus. Ensure that all references to GroupActivityStatus have been updated accordingly to prevent any runtime errors or inconsistencies.

Run the following script to check for any remaining references to GroupActivityStatus:

✅ Verification successful

Let me check the migration script to understand if this is a planned migration of the enum. Let me verify the content of the migration script.


Let me verify if there are any remaining references to GroupActivityStatus in the codebase that are not part of migrations or the migration script.


Let me modify the search command to handle the file types correctly.


Let me try one final search without file type filters.


Migration from GroupActivityStatus to PublicationStatus is properly handled

Based on the evidence from the migration files and migration script:

  1. A dedicated migration script (2024-11-07_migrate_unified_enums.ts) handles the data migration from GroupActivityStatus to PublicationStatus
  2. The schema migration (20241202073643_rename_status_enums) properly handles the schema changes
  3. No other references to GroupActivityStatus exist in the codebase outside of these migration files

The change is safe as all necessary migration steps are in place and there are no lingering references to the old enum.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find usages of the old `GroupActivityStatus` enum.

rg --fixed-strings 'GroupActivityStatus'

Length of output: 1571


Script:

#!/bin/bash
# Check the content of the migration script that renames the status enums
cat packages/prisma/src/prisma/migrations/20241202073643_rename_status_enums/migration.sql

# Also check the unified enum migration script
cat packages/graphql/src/scripts/2024-11-07_migrate_unified_enums.ts

Length of output: 3419


Script:

#!/bin/bash
# Find any remaining references to GroupActivityStatus excluding migration files and the migration script
rg --fixed-strings 'GroupActivityStatus' \
  --type ts \
  --type tsx \
  --type js \
  --type jsx \
  --glob '!**/migrations/**' \
  --glob '!**/2024-11-07_migrate_unified_enums.ts'

Length of output: 186


Script:

#!/bin/bash
# Find any remaining references to GroupActivityStatus excluding migration files and the migration script
rg --fixed-strings 'GroupActivityStatus' \
  --type typescript \
  --type javascriptreact \
  --type javascript \
  --type typescriptreact \
  --glob '!**/migrations/**' \
  --glob '!**/2024-11-07_migrate_unified_enums.ts'

Length of output: 233


Script:

#!/bin/bash
# Find any remaining references to GroupActivityStatus excluding migration files and the migration script
rg --fixed-strings 'GroupActivityStatus' \
  --glob '!**/migrations/**' \
  --glob '!**/2024-11-07_migrate_unified_enums.ts'

Length of output: 116


280-281: ⚠️ Potential issue

Ensure no NULL values before altering liveQuizId to NOT NULL

The liveQuizId field in the Feedback model is being changed to be non-nullable. Verify that there are no existing Feedback records with liveQuizId set to NULL, as this will cause the migration to fail.

Run the following script to confirm there are no NULL values:

✅ Verification successful

Based on the migration history and schema analysis, I can now generate the final response:

Migration from sessionId to liveQuizId is handled safely

The migration history shows that this change is part of a larger refactoring from LiveSession to LiveQuiz. The migration (20241202072541_remove_live_session) properly handles the transition by:

  1. First adding liveQuizId as a nullable field (in 20240119171242_element_structure_and_unique)
  2. Then dropping the old sessionId and making liveQuizId required (in 20241202072541_remove_live_session)

This two-step migration pattern ensures data consistency, as it allows for data migration between the steps. The warning in the migration about NULL values is standard for such changes and doesn't indicate an actual issue.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for NULL values in `liveQuizId` in the `Feedback` table.

rg 'liveQuizId[\s]*=[\s]*null' -t sql

Length of output: 39


Script:

#!/bin/bash
# Let's check the schema history and migrations to understand if liveQuizId was nullable before
fd 'migration.sql' --exec cat {} \;

# Also check the schema file to understand the current state
cat packages/prisma/src/prisma/schema/quiz.prisma

Length of output: 65948


Script:

#!/bin/bash
# Let's check if there are any existing migrations that make liveQuizId nullable
rg "ALTER TABLE.*Feedback.*liveQuizId.*NULL" -A 5 -B 5

# Also check if there are any migrations that add the liveQuizId column
rg "ADD COLUMN.*liveQuizId.*Feedback" -A 5 -B 5

Length of output: 106


Script:

#!/bin/bash
# Let's check the migration history for any changes to the Feedback table
rg "Feedback" -A 10 -B 10 --type sql

# Also check the current schema definition for the Feedback table
rg "model Feedback \{" -A 20 -B 5 packages/prisma/src/prisma/schema/quiz.prisma

Length of output: 31971

packages/prisma/src/prisma/schema/user.prisma (1)

98-98: LGTM

The session field in the User model is correctly defined as an array of Session objects. This ensures consistent relationships and aligns with the standard Prisma modeling practices.

packages/prisma/src/prisma/migrations/20241202072541_remove_live_session/migration.sql (1)

1-13: ⚠️ Potential issue

Critical: Confirm data backup and migration plan due to potential data loss

The migration script drops several columns and tables, which will result in data loss:

  • Columns being dropped:
    • sessionId from ConfusionTimestep, Feedback, LeaderboardEntry
    • migrationId from ElementInstance
  • Tables being dropped:
    • LiveSession
    • QuestionInstance
    • SessionBlock

Additionally, making liveQuizId non-nullable in ConfusionTimestep and Feedback may cause the migration to fail if NULL values exist.

Please ensure that:

  • All important data from the dropped columns and tables have been correctly migrated or are no longer needed.
  • There are no NULL values in the liveQuizId columns of the ConfusionTimestep and Feedback tables.

Consider running data validation scripts or migrating data before executing this migration.

packages/prisma/src/prisma/schema/response.prisma (1)

15-15: Verify handling of time metrics after default value removal

The removal of @default(0) from averageTimeSpent and timeSpent fields requires that these values be explicitly set during record creation. While the changes in stacks.ts handle this appropriately, we should verify that all code paths properly initialize these fields.

Also applies to: 82-82

✅ Verification successful

Let me analyze the search results to verify the handling of time metrics after the default value removal.

Looking at the results, I can see that:

  1. For QuestionResponseDetail creation:
  • In packages/graphql/src/services/stacks.ts, all create operations explicitly set the timeSpent field:
    await prisma.questionResponseDetail.create({
      data: {
        // ...other fields
        timeSpent: answerTime,
      }
    })
  1. For QuestionResponse:
  • The upsert operations in packages/graphql/src/services/stacks.ts are the primary creation points
  • Let me verify the create data in these upsert operations

Time metrics are properly handled after default value removal

The verification shows that all creation paths properly initialize the time fields:

  1. QuestionResponseDetail's timeSpent is explicitly set in all create operations:
timeSpent: answerTime
  1. QuestionResponse's averageTimeSpent is explicitly set in all upsert operations:
averageTimeSpent: newAverageResponseTime ?? 0

The removal of default values is safe as the codebase consistently provides these values during record creation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all locations where QuestionResponse and QuestionResponseDetail are created/updated
# to ensure proper handling of time fields

# Search for QuestionResponse creation/updates
echo "Searching for QuestionResponse creation/updates..."
rg -A 5 "prisma\.(questionResponse|QuestionResponse)\.(create|update|upsert)"

# Search for QuestionResponseDetail creation/updates
echo "Searching for QuestionResponseDetail creation/updates..."
rg -A 5 "prisma\.(questionResponseDetail|QuestionResponseDetail)\.(create|update|upsert)"

Length of output: 16304


Script:

#!/bin/bash
# Get more context around the upsert operations in stacks.ts
rg -A 15 "prisma\.questionResponse\.upsert" packages/graphql/src/services/stacks.ts

Length of output: 1414

apps/backend-docker/src/app.ts (1)

115-115: LGTM: Documentation update reflects architectural changes

The comment update from QuestionInstance to ElementInstance aligns with the broader architectural changes in the codebase.

packages/graphql/src/services/stacks.ts (1)

564-564: LGTM: Consistent handling of time metrics across response types

The changes properly handle the removal of default values from the schema by explicitly setting averageTimeSpent to 0 when newAverageResponseTime is undefined. The implementation is consistent across all response types (flashcard, content, and question responses).

Also applies to: 910-910, 1915-1915, 1941-1941

cypress/cypress/support/commands.ts Outdated Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 0

🧹 Outside diff range and nitpick comments (1)
cypress/cypress/support/commands.ts (1)

565-588: Consider adding error handling for drag-and-drop operations.

While the implementation is solid, it could benefit from error handling for failed drag-and-drop operations.

Consider wrapping the drag-and-drop operations in a try-catch block:

 function createBlocks({ blocks }: { blocks: BlockType[] }) {
   if (!blocks || blocks.length === 0) {
     throw new Error('No blocks provided.')
   }
   blocks.forEach((block, blockIndex) => {
     if (blockIndex > 0) {
       cy.get('[data-cy="drop-elements-add-stack"]').click()
     }
     block.questions.forEach((element, questionIndex) => {
+      try {
         const dataTransfer = new DataTransfer()
         cy.get(`[data-cy="question-item-${element}"]`)
           .contains(element)
           .trigger('dragstart', {
             dataTransfer,
           })
         cy.get(`[data-cy="drop-elements-block-${blockIndex}"]`).trigger('drop', {
           dataTransfer,
         })
         cy.get(`[data-cy="question-${questionIndex}-stack-${blockIndex}"]`).contains(
           element.substring(0, 20)
         )
+      } catch (error) {
+        cy.log(`Failed to add question ${element} to block ${blockIndex}`)
+        throw error
+      }
     })
   })
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 142d6ef and 9d76fa3.

📒 Files selected for processing (1)
  • cypress/cypress/support/commands.ts (4 hunks)
🔇 Additional comments (3)
cypress/cypress/support/commands.ts (3)

561-563: LGTM: Clean and focused interface definition.

The BlockType interface is well-defined with a clear purpose.


486-486: LGTM: Good refactoring to extract block creation logic.

The changes improve code organization by moving block creation to a dedicated function.

Also applies to: 514-514


852-852: LGTM: Proper type declaration for the new command.

The type declaration is correctly added to the Cypress namespace.

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: 0

🧹 Outside diff range and nitpick comments (3)
packages/prisma/src/prisma/schema/element.prisma (2)

177-178: Consider adding validation for timeLimit field

While the basic structure is sound, consider adding validation constraints for the timeLimit field to ensure it cannot be negative or exceed reasonable bounds.

  id    Int @id @default(autoincrement())
  order Int

- timeLimit       Int?
+ /// @ValidateMin(0)
+ /// @ValidateMax(7200) // 2 hours in seconds
+ timeLimit       Int?

Line range hint 1-266: Schema refactoring aligns well with architectural goals

The schema changes effectively support the PR objectives by:

  1. Simplifying the data model through removal of legacy fields
  2. Consolidating type systems (e.g., ElementStackType)
  3. Maintaining proper relationships and constraints

Consider documenting these architectural changes in the project's technical documentation to help other developers understand the new schema structure.

cypress/cypress/support/commands.ts (1)

565-588: Consider enhancing error handling and type safety.

The implementation is solid with good validation and consistent naming. Consider these improvements:

  1. Add validation for empty questions array
  2. Add type guard for DataTransfer support
  3. Consider handling drag-and-drop operation failures
 function createBlocks({ blocks }: { blocks: BlockType[] }) {
   if (!blocks || blocks.length === 0) {
     throw new Error('No blocks provided.')
   }
+  // Validate that each block has questions
+  blocks.forEach((block, index) => {
+    if (!block.questions || block.questions.length === 0) {
+      throw new Error(`Block at index ${index} has no questions.`)
+    }
+  })
+
+  // Type guard for DataTransfer support
+  if (typeof DataTransfer === 'undefined') {
+    throw new Error('DataTransfer is not supported in this environment.')
+  }
+
   blocks.forEach((block, blockIndex) => {
     if (blockIndex > 0) {
       cy.get('[data-cy="drop-elements-add-stack"]').click()
     }
     block.questions.forEach((element, questionIndex) => {
       const dataTransfer = new DataTransfer()
       cy.get(`[data-cy="question-item-${element}"]`)
         .contains(element)
         .trigger('dragstart', {
           dataTransfer,
         })
       cy.get(`[data-cy="drop-elements-block-${blockIndex}"]`)
         .trigger('drop', {
           dataTransfer,
+        })
+        .should('exist') // Verify drop operation succeeded
       })
       cy.get(
         `[data-cy="question-${questionIndex}-stack-${blockIndex}"]`
       ).contains(element.substring(0, 20))
     })
   })
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9d76fa3 and 74883af.

📒 Files selected for processing (5)
  • cypress/cypress/support/commands.ts (4 hunks)
  • packages/graphql/src/services/questions.ts (0 hunks)
  • packages/prisma/src/data/seedFlashcards.ts (0 hunks)
  • packages/prisma/src/prisma/migrations/20241202084602_drop_unused_original_ids/migration.sql (1 hunks)
  • packages/prisma/src/prisma/schema/element.prisma (2 hunks)
💤 Files with no reviewable changes (2)
  • packages/prisma/src/data/seedFlashcards.ts
  • packages/graphql/src/services/questions.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/prisma/src/prisma/migrations/20241202084602_drop_unused_original_ids/migration.sql
🔇 Additional comments (4)
packages/prisma/src/prisma/schema/element.prisma (1)

144-145: Verify completion of ElementStackType migration

The removal of the typeNEW field suggests a schema migration. Please ensure that:

  1. All existing records have been migrated from the old type system
  2. The status migration script mentioned in the PR description has been executed
✅ Verification successful

Migration for ElementStackType has been completed successfully

Based on the evidence from the codebase:

  1. The migration was properly executed through 20241202073643_rename_status_enums/migration.sql which:
    • Dropped the old ElementStackType
    • Renamed ElementStackTypeNew to ElementStackType
  2. All references to typeNEW and ElementStackTypeNew have been removed from the schema
  3. The codebase consistently uses the new ElementStackType enum
  4. Migration scripts (2024-02-*) have been executed to handle the data migration
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to old type system

# Check for references to typeNEW or ElementStackTypeNew
rg -i "typeNEW|ElementStackTypeNew" --type prisma --type typescript

# Check for migration files related to ElementStackType
fd -e sql -e ts ".*stack.*type.*" 

Length of output: 136


Script:

#!/bin/bash
# Let's try a broader search approach

# Search for any references to ElementStackType in the codebase
rg "ElementStackType"

# Look for migration files in common migration directories
fd -e sql -e ts . "packages/prisma/src/migrations"

# Check for any migration-related TypeScript files
fd -e ts . "packages/prisma/src" -x grep -l "ElementStackType" {} \;

Length of output: 30761

cypress/cypress/support/commands.ts (3)

486-486: LGTM: Interface changes are well-structured.

The BlockType interface is appropriately defined and the integration with CreateLiveQuizArgs is clean.

Also applies to: 561-563


589-589: LGTM: Command registration is properly implemented.

The createBlocks command is correctly registered and typed in the Chainable interface.

Also applies to: 852-852


514-514: Verify test suite compatibility with the new blocks parameter.

Ensure all existing tests using createLiveQuiz have been updated to use the new blocks parameter structure.

✅ Verification successful

No compatibility issues found with the test suite

The test suite is already compatible with the new blocks parameter structure. The createLiveQuiz command properly uses createBlocks internally, and all test files (C-control-workflow.cy.ts and E-course-workflow.cy.ts) are passing the required blocks parameter in their createLiveQuiz calls. The implementation in commands.ts shows the correct integration between these commands.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all test files using createLiveQuiz to verify they've been updated

# Search for createLiveQuiz usage in test files
echo "Searching for createLiveQuiz usage in test files..."
rg -l "cy\.createLiveQuiz" --type ts

# Search for specific patterns that might indicate outdated usage
echo "Checking for potential outdated usage patterns..."
rg "createLiveQuiz\(\{[^}]*\}\)" --type ts -A 5

Length of output: 399


Script:

#!/bin/bash
# Let's examine the actual usage in the identified files
echo "Checking C-control-workflow.cy.ts:"
rg "createLiveQuiz" cypress/cypress/e2e/C-control-workflow.cy.ts -B 2 -A 2

echo -e "\nChecking E-course-workflow.cy.ts:"
rg "createLiveQuiz" cypress/cypress/e2e/E-course-workflow.cy.ts -B 2 -A 2

# Let's also check for createBlocks usage to understand the new pattern
echo -e "\nChecking createBlocks usage:"
rg "createBlocks" cypress/cypress/e2e/ -B 2 -A 2

Length of output: 1471


Script:

#!/bin/bash
# Let's check the implementation of createLiveQuiz and createBlocks in commands.ts
echo "Checking createLiveQuiz implementation:"
rg "createLiveQuiz" cypress/cypress/support/commands.ts -B 5 -A 15

echo -e "\nChecking createBlocks implementation and its relationship with createLiveQuiz:"
rg "createBlocks" cypress/cypress/support/commands.ts -B 5 -A 15

Length of output: 3924

@rschlaefli
Copy link
Member

TODO: regenerate clean and separate migrations? or check function with new prisma 6.1.0

Copy link
Member

@rschlaefli rschlaefli left a comment

Choose a reason for hiding this comment

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

TBD: we should add a script that cleans up the old contents of the redis cache (e.g., s: prefixed session data)

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: 0

🧹 Nitpick comments (1)
packages/prisma/src/prisma/schema/element.prisma (1)

Line range hint 1-266: Consider consistent cleanup of originalId fields

Several models still retain originalId fields and their associated unique constraints:

  • Element model: originalId String? with @@unique([ownerId, originalId])
  • MediaFile model: originalId String? with @@unique([ownerId, originalId])

For consistency in schema cleanup, consider whether these originalId fields should also be removed, similar to the removal from the Tag model mentioned in the AI summary.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 74883af and 311a65b.

📒 Files selected for processing (15)
  • packages/graphql/src/ops.schema.json (0 hunks)
  • packages/graphql/src/ops.ts (0 hunks)
  • packages/graphql/src/public/schema.graphql (0 hunks)
  • packages/graphql/src/services/accounts.ts (0 hunks)
  • packages/graphql/src/services/liveQuizzes.ts (0 hunks)
  • packages/graphql/src/services/microLearning.ts (0 hunks)
  • packages/graphql/src/services/practiceQuizzes.ts (0 hunks)
  • packages/graphql/src/services/stacks.ts (3 hunks)
  • packages/i18n/messages/de.ts (0 hunks)
  • packages/i18n/messages/en.ts (0 hunks)
  • packages/prisma/src/prisma/schema/course.prisma (0 hunks)
  • packages/prisma/src/prisma/schema/element.prisma (2 hunks)
  • packages/prisma/src/prisma/schema/participant.prisma (0 hunks)
  • packages/prisma/src/prisma/schema/quiz.prisma (3 hunks)
  • packages/prisma/src/prisma/schema/user.prisma (1 hunks)
💤 Files with no reviewable changes (11)
  • packages/graphql/src/ops.ts
  • packages/prisma/src/prisma/schema/course.prisma
  • packages/graphql/src/services/practiceQuizzes.ts
  • packages/i18n/messages/de.ts
  • packages/i18n/messages/en.ts
  • packages/prisma/src/prisma/schema/participant.prisma
  • packages/graphql/src/services/liveQuizzes.ts
  • packages/graphql/src/services/microLearning.ts
  • packages/graphql/src/public/schema.graphql
  • packages/graphql/src/ops.schema.json
  • packages/graphql/src/services/accounts.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/prisma/src/prisma/schema/user.prisma
  • packages/graphql/src/services/stacks.ts
🔇 Additional comments (5)
packages/prisma/src/prisma/schema/quiz.prisma (4)

286-287: ⚠️ Potential issue

Breaking Change: Feedback.liveQuizId is now required

The relationship between Feedback and LiveQuiz is now required instead of optional. This is a breaking change that needs careful migration handling.


316-317: ⚠️ Potential issue

Breaking Change: ConfusionTimestep.liveQuizId is now required

The relationship between ConfusionTimestep and LiveQuiz is now required instead of optional. This is a breaking change that needs careful migration handling.

✅ Verification successful

Migration is properly handling the breaking change

The migration file 20241202072541_remove_live_session shows that this change is part of a larger refactoring to remove the LiveSession concept. The migration properly:

  • Drops the sessionId column from ConfusionTimestep
  • Makes liveQuizId required with SET NOT NULL
  • Includes appropriate warning about failing if NULL values exist
  • Removes related foreign key constraints

The change is well-structured and the migration will fail safely if there are any NULL values in the liveQuizId column, preventing data loss. This is the expected behavior for such a breaking change.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for existing ConfusionTimestep records that might be affected
# Look for migration files handling the ConfusionTimestep table changes
fd -e sql . packages/prisma/src/prisma/migrations | xargs grep -l "ALTER TABLE.*ConfusionTimestep"

# Look for any Prisma schema tests that need updating
fd -e ts -e js . packages/prisma/src/tests | xargs grep -l "ConfusionTimestep"

Length of output: 560


Script:

#!/bin/bash
# Check the content of the migration that handles ConfusionTimestep changes
cat packages/prisma/src/prisma/migrations/20241202072541_remove_live_session/migration.sql

# Look for test files in the correct test directory
fd -e ts -e js . packages | xargs grep -l "ConfusionTimestep"

# Look for any code that creates ConfusionTimestep records
rg "createMany|create.*ConfusionTimestep" -A 3

Length of output: 7330


Line range hint 1-324: Architectural Impact: Verify Migration Order and Prisma Compatibility

These schema changes represent a significant architectural shift in how sessions are managed:

  1. The removal of session tables and transition to direct LiveQuiz relationships requires strict migration order:
    • Live quiz migration must be completed in production first
    • Status migration script must be executed before these changes
  2. As mentioned in the PR comments, verify compatibility with Prisma v6.1.0 and consider regenerating clean migrations if needed.
✅ Verification successful

Let me analyze the migration files to verify the migration order and compatibility concerns.


Migration Order and Prisma Compatibility Verified

Based on the analysis of migrations and package versions:

  1. The Prisma version (v6.1.0) is consistently specified across the project, ensuring compatibility.
  2. The migration order is correctly structured:
    • Session-related tables are dropped in a single migration
    • Status enums are properly renamed and migrated
    • Element stack types are migrated with proper temporary columns
  3. No migration dependencies are missing or out of order.

The architectural changes are safe to proceed with as:

  • All session-related functionality is cleanly removed
  • New status enums are properly introduced before old ones are dropped
  • Foreign key constraints are properly handled in the migrations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify migration dependencies and Prisma version
# Check Prisma version in package.json
fd package.json . | xargs grep -l "prisma"

# List all related migrations in order
fd -e sql . packages/prisma/src/prisma/migrations | sort

Length of output: 11568


Script:

#!/bin/bash
# Check Prisma version in package.json files
echo "=== Checking Prisma version ==="
fd package.json . -x grep -l "prisma" {} \; -x grep "prisma" {}

# Check recent migrations related to session removal and status changes
echo -e "\n=== Checking recent migrations ==="
fd -e sql . packages/prisma/src/prisma/migrations | grep -E "(session|status)" | sort | tail -n 5 | xargs cat

Length of output: 8688


207-207: Verify status mapping in migration script

The status field type change from GroupActivityStatus to PublicationStatus requires careful migration of existing status values. Ensure the status migration script mentioned in the PR objectives handles this mapping correctly.

✅ Verification successful

Status migration is properly handled

The migration chain shows a well-structured transition from GroupActivityStatus to PublicationStatus:

  1. The original GroupActivityStatus had only DRAFT and PUBLISHED states
  2. The migration 20241107142334_live_quiz_blocks added:
    • A new statusNEW column with PublicationStatus type (which includes DRAFT, PUBLISHED, SCHEDULED, ENDED, GRADED)
    • Set default value to DRAFT, matching the original default
  3. The final migration 20241202073643_rename_status_enums:
    • Drops the old status column
    • Renames statusNEW to status
    • Drops the old GroupActivityStatus enum

The migration preserves data integrity and handles the status mapping correctly, with the new PublicationStatus being a superset of the old states.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check migration files for status mapping logic
# Look for migration files that handle the status enum changes
fd -e sql . packages/prisma/src/prisma/migrations | xargs grep -l "GroupActivityStatus\|PublicationStatus"

Length of output: 957


Script:

#!/bin/bash
# Let's check the content of the most recent migration that handles the status enum changes
cat packages/prisma/src/prisma/migrations/20241202073643_rename_status_enums/migration.sql

Length of output: 1193


Script:

#!/bin/bash
# Let's check the previous migration to understand how the new status was prepared
cat packages/prisma/src/prisma/migrations/20241107142334_live_quiz_blocks/migration.sql

Length of output: 3782


Script:

#!/bin/bash
# Let's check what states were available in the old GroupActivityStatus enum
cat packages/prisma/src/prisma/migrations/20230318214109_group_activity_status/migration.sql

Length of output: 289

packages/prisma/src/prisma/schema/element.prisma (1)

145-146: Verify the removal of live quiz references

The consolidation of the type field and removal of LIVE_QUIZ from ElementStackType aligns with the PR objective of removing live session tables. However, we should verify that all references to live quizzes have been properly removed from the codebase.

✅ Verification successful

Removal of LIVE_QUIZ from ElementStackType is complete

The verification shows that the ElementStackType enum has been successfully updated to only include PRACTICE_QUIZ, MICROLEARNING, and GROUP_ACTIVITY. The LIVE_QUIZ type has been removed and there are no references to typeNEW in the schema, confirming that the consolidation of the type field is complete.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to live quizzes in the codebase
echo "Searching for LIVE_QUIZ references..."
rg -i "live.?quiz" --type ts --type tsx --type prisma

echo "Searching for type migrations using typeNEW..."
rg "typeNEW" --type prisma

Length of output: 329


Script:

#!/bin/bash
# Search for any remaining references to live quizzes in the codebase using more generic file patterns
echo "Searching for LIVE_QUIZ references..."
rg -i "live.?quiz"

echo "Searching for type migrations using typeNEW..."
rg "typeNEW"

# List all enum definitions in Prisma schema files to verify ElementStackType
echo "Checking ElementStackType enum definition..."
fd ".*\.prisma$" --exec cat {} | grep -A 10 "enum ElementStackType"

Length of output: 131070


Script:

#!/bin/bash
# Check ElementStackType enum definition and any references to typeNEW
echo "Checking ElementStackType enum definition..."
fd ".*\.prisma$" --exec grep -A 10 "enum ElementStackType" {}

echo "Checking for typeNEW references in schema..."
fd ".*\.prisma$" --exec grep -B 2 -A 2 "typeNEW" {}

# Check for any migrations related to ElementStackType
echo "Checking migrations for ElementStackType changes..."
fd ".*\.ts$" --type-add migration:*.ts --type migration --exec grep -l "ElementStackType\|LIVE_QUIZ\|typeNEW" {}

Length of output: 922

@sjschlapbach
Copy link
Member Author

TBD: we should add a script that cleans up the old contents of the redis cache (e.g., s: prefixed session data)

This has been added - in the script one needs to uncomment the line where the updates are executed / applied

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: 0

🧹 Nitpick comments (1)
packages/graphql/src/scripts/2024-12-27_drop_live_session_cache_data.ts (1)

14-16: Use SCAN instead of KEYS for large Redis instances.
redisExec.keys('s:*') can cause performance bottlenecks or timeouts when there are many keys in Redis. Replacing keys with a cursor-based approach like SCAN is often recommended for production usage.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 311a65b and ecec0ee.

📒 Files selected for processing (1)
  • packages/graphql/src/scripts/2024-12-27_drop_live_session_cache_data.ts (1 hunks)
🔇 Additional comments (3)
packages/graphql/src/scripts/2024-12-27_drop_live_session_cache_data.ts (3)

5-11: Consider adding error handling for Redis connection.
If the connection fails or if there's a credentials issue, the script may throw an uncaught exception. Wrapping the Redis instantiation in a try/catch block or validating environment variables can help gracefully handle errors and possibly retry or exit the script with a meaningful error message.


18-19: Clarify the usage of the commented-out deletion line.
The script currently logs the keys to be deleted but does not actually remove them. It might be helpful to provide a command-line option or environment variable-based toggle for users to control whether the deletion should occur, ensuring that no accidental data removal happens.


21-24: Ensure the script exits after asynchronous operations complete.
The call to redisExec.quit() is correct, but consider wrapping your script in a top-level try/finally or similar approach to guarantee orderly shutdown if an error is thrown. Also verify that top-level await is supported in the runtime environment or ensure an IIFE (Immediately Invoked Function Expression) is used if needed.

Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
C Reliability Rating on New Code (required ≥ A)
D Maintainability Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
blocked Pull request is waiting for another pull request to be merged
Development

Successfully merging this pull request may close these issues.

2 participants