Skip to content

Changing the manage submissions button to be ajax requests #2271

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 4 commits into from
Apr 14, 2025

Conversation

dwang3851
Copy link
Contributor

Description

  • Changed the regrade selected, delete selected, and excuse buttons to be ajax post requests
  • Can't do this for download selected because it is a get request, and we shouldn't pass data in request body for get requests

Motivation and Context

How Has This Been Tested?

  • Tested in local env in manage submissions

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist:

  • I have run rubocop and erblint for style check. If you haven't, run overcommit --install && overcommit --sign to use pre-commit hook for linting
  • My change requires a change to the documentation, which is located at Autolab Docs
  • I have updated the documentation accordingly, included in this PR

Other issues / help required

  • I am not sure why only the download selected button is properly disabled, when I console.log, the other buttons are the correct class
  • Not sure if this is that user friendly, any input would be appreciated

If unsure, feel free to submit first and we'll help you along.

@dwang3851 dwang3851 requested a review from coder6583 February 23, 2025 19:00
Copy link
Contributor

coderabbitai bot commented Feb 23, 2025

📝 Walkthrough

Walkthrough

This pull request introduces several improvements for managing submissions. In the JavaScript file, new endpoints for deletion, downloading, and excusing submissions are added, and the button state logic is enhanced with detailed event handling and AJAX calls. The Ruby controllers are updated to parse submission IDs from the request body (ensuring array format) and to handle responses via respond_to blocks for HTML and JSON. The view has been modified to replace link_to helpers with basic anchor tags with unique IDs for further JavaScript integration. The route for download_batch has been changed to require a POST request.

Changes

File(s) Summary
app/assets/.../manage_submissions.js Added new endpoints ('delete-selected', 'download-selected', 'excuse-selected') and updated changeButtonStates with enhanced logging, disabling logic, click event management, and AJAX request handling for submissions management.
app/controllers/assessment/autograde.rb
app/controllers/submissions_controller.rb
Modified batch processing methods. In autograde.rb, regradeBatch now reads submission IDs from the request body and handles responses via respond_to. In submissions_controller.rb, both destroy_batch and excuse_batch now parse submission IDs from JSON, convert them to an array, and structure responses for HTML and JSON requests.
app/views/submissions/index.html.erb Replaced Rails link_to helper calls with standard <a> tags that include unique IDs, removing preconfigured HTTP method and paths to rely on front-end handling.
config/routes.rb Updated the download_batch route method from GET to POST, altering how clients interact with this endpoint.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Browser
    participant JS
    participant Server

    User->>Browser: Click on action button (delete, download, excuse)
    Browser->>JS: Trigger changeButtonStates logic
    JS->>Browser: Disable button and log action
    alt Delete Action
        JS->>User: Display confirmation prompt
    end
    JS->>Server: Send AJAX request to appropriate endpoint
    Server-->>JS: Return response (JSON/redirect URL)
    JS->>Browser: Update UI based on server response
Loading

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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: 1

🧹 Nitpick comments (4)
app/controllers/assessment/autograde.rb (2)

89-93: Consider adding validation and error handling when parsing submission IDs.

If submission_ids are missing or invalid in the JSON payload, this code may throw an error or fail silently. It would be safer to check for nil or an unexpected type before proceeding. For instance, returning a user-friendly error if no valid submission IDs are found could improve reliability.


130-133: Provide richer JSON responses for asynchronous flows.

The respond_to block works well for redirection, but consider returning additional information (e.g., success or error messages) in the JSON response to better support asynchronous UI actions and partial success scenarios.

app/views/submissions/index.html.erb (1)

91-93: Ensure graceful fallback for regrade if JavaScript is disabled.

Replacing link_to with a plain <a> that relies on JavaScript can leave no fallback route if JS is turned off. If this is intentional, no changes are required, but a progressive enhancement approach may be beneficial, offering a non-JS alternative.

app/controllers/submissions_controller.rb (1)

203-249: Consider adding request body validation.

While the implementation works, it would be more robust to add validation for the request body format and handle potential JSON parsing errors.

Consider adding error handling:

 def destroy_batch
   request_body = request.body.read
+  if request_body.blank?
+    respond_to do |format|
+      format.html do
+        flash[:error] = "No submission IDs provided"
+        redirect_to [@course, @assessment, :submissions]
+      end
+      format.json { render json: { error: "No submission IDs provided" }, status: :bad_request }
+    end
+    return
+  end
+
+  begin
   submission_ids = JSON.parse(request_body)['submission_ids']
+  rescue JSON::ParserError
+    respond_to do |format|
+      format.html do
+        flash[:error] = "Invalid JSON in request body"
+        redirect_to [@course, @assessment, :submissions]
+      end
+      format.json { render json: { error: "Invalid JSON in request body" }, status: :bad_request }
+    end
+    return
+  end
+
   submission_ids = Array(submission_ids)

Apply similar changes to the excuse_batch method as well.

Also applies to: 391-446

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9e96814 and 290342c.

📒 Files selected for processing (4)
  • app/assets/javascripts/manage_submissions.js (2 hunks)
  • app/controllers/assessment/autograde.rb (2 hunks)
  • app/controllers/submissions_controller.rb (4 hunks)
  • app/views/submissions/index.html.erb (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (7)
app/views/submissions/index.html.erb (2)

97-99: Looks good for async deletion handling.

These lines align with the new AJAX-driven design. The plain anchor setup is consistent with the other buttons, and the JavaScript logic takes over seamlessly. No immediate issues here.


111-113: Consistent approach for excuse action.

The excuse button follows the same pattern as regrade and delete. Just ensure that users understand there's no direct link if JavaScript is disabled, which may be acceptable for this management tool.

app/assets/javascripts/manage_submissions.js (1)

3-5: Validate endpoint consistency for download requests.

While 'download-selected' is listed as 'submissions/download_batch', be sure this endpoint is indeed intended for a GET request. The code appends query parameters for submission IDs, which should align with the server-side route’s expected method.

app/controllers/submissions_controller.rb (4)

203-205: LGTM: Proper handling of request body data.

The implementation correctly reads and parses the submission IDs from the request body, ensuring array format with Array().


246-249: LGTM: Proper response format handling.

The implementation correctly handles both HTML and JSON responses using Rails' respond_to block, providing appropriate redirects for each format.


391-393: LGTM: Consistent implementation with destroy_batch.

The implementation mirrors the approach used in destroy_batch, maintaining consistency in how request body data is handled.


443-446: LGTM: Consistent response format handling.

The implementation mirrors the approach used in destroy_batch, maintaining consistency in how responses are formatted.

@KesterTan KesterTan requested review from KesterTan and removed request for coder6583 February 24, 2025 21:11
@KesterTan
Copy link
Contributor

Are the buttons visibility toggle broken? If no checkboxes are selected, buttons should be disabled?

Screenshot 2025-03-16 at 12 25 41 PM

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

♻️ Duplicate comments (1)
app/assets/javascripts/manage_submissions.js (1)

313-379: ⚠️ Potential issue

Prevent infinite page reload loop on AJAX errors.

Currently, setInterval is cleared only on success, causing repeated page reloads every 5 seconds if an error occurs. To avoid trapping users in a reload loop, remember to clear the interval upon error:

  error: function (error) {
+    clearInterval(refreshInterval);
    alert("An error occurred while processing the request.");
  },
🧹 Nitpick comments (1)
app/assets/javascripts/manage_submissions.js (1)

357-375: Add visual feedback during AJAX processing.

To improve user experience, add loading indicators and disable buttons during AJAX requests to prevent multiple submissions:

$(document).off("click", id).on("click", id, function (event) {
  console.log(`${id} button clicked`);
  event.preventDefault();
  
  // Show loading state
+ const button = $(id);
+ button.addClass("processing");
+ button.prop("disabled", true);
  
  // Ajax request...
  
  success: function (response) {
    clearInterval(refreshInterval);
+   button.removeClass("processing");
    // rest of success handler
  },
  error: function (error) {
    clearInterval(refreshInterval);
+   button.removeClass("processing");
+   button.prop("disabled", false);
    alert("An error occurred while processing the request.");
  },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 290342c and a6f9f7a.

📒 Files selected for processing (3)
  • app/assets/javascripts/manage_submissions.js (2 hunks)
  • app/views/submissions/index.html.erb (1 hunks)
  • config/routes.rb (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/views/submissions/index.html.erb
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: test
🔇 Additional comments (2)
config/routes.rb (1)

181-181: Route method change aligns with PR objectives.

Changing download_batch from GET to POST is appropriate when moving from URL parameters to request body for submission IDs. This supports the PR's goal of handling large requests more efficiently.

app/assets/javascripts/manage_submissions.js (1)

3-5: LGTM: New endpoints support AJAX implementation.

The new endpoint definitions for delete, download, and excuse operations align with the backend routes and enable the AJAX functionality described in the PR objectives.

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

♻️ Duplicate comments (1)
app/assets/javascripts/manage_submissions.js (1)

323-330: ⚠️ Potential issue

Fix early return that skips button event handlers.

The current implementation has a return statement on line 329 that exits the function early after setting up the download URL, preventing other buttons from getting their event handlers. This logic needs to be restructured.

if (id == "#download-selected") {
  var urlParam = $.param({'submission_ids': selectedSubmissions});
  buttonIDs.forEach(function(id) {
    var newHref = baseURLs[id] + '?' + urlParam;
    $(id).prop('href', newHref);
  });
- return;
}
🧹 Nitpick comments (1)
app/controllers/assessment/autograde.rb (1)

89-101: Implement robust request parsing for submission IDs.

The code now properly extracts submission IDs from either the JSON request body or parameters, with good defensive programming to handle various edge cases.

There's an unused e variable in the rescue block:

-                     rescue JSON::ParserError => e
+                     rescue JSON::ParserError
                       params[:submission_ids] || []
🧰 Tools
🪛 RuboCop (1.73)

[warning] 96-96: Useless assignment to variable - e.

(Lint/UselessAssignment)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a6f9f7a and 74964a4.

📒 Files selected for processing (2)
  • app/assets/javascripts/manage_submissions.js (2 hunks)
  • app/controllers/assessment/autograde.rb (2 hunks)
🧰 Additional context used
🪛 RuboCop (1.73)
app/controllers/assessment/autograde.rb

[warning] 96-96: Useless assignment to variable - e.

(Lint/UselessAssignment)

🔇 Additional comments (4)
app/controllers/assessment/autograde.rb (1)

138-141: Good implementation of format-specific responses.

The respond_to block enhances flexibility by supporting both HTML redirects for browser clients and JSON responses for AJAX requests.

app/assets/javascripts/manage_submissions.js (3)

3-5: Good addition of endpoints for AJAX operations.

These endpoint definitions properly align with the controller actions that have been modified to accept POST requests.


331-377: Well-implemented AJAX submission handling.

The event handlers for the buttons correctly implement AJAX POST requests with appropriate CSRF protection, error handling, and success responses. The code also properly clears the refresh interval in both success and error cases to prevent infinite reload loops.


313-380: Verify button state toggle behavior on selection changes.

According to the PR comments, there's a concern about buttons not being properly disabled when no checkboxes are selected. This implementation should theoretically work, but consider testing it thoroughly on edge cases such as:

  • Selecting and then deselecting all checkboxes
  • Navigating between pages with selections
  • Handling the "Select All" checkbox interaction

You can manually verify this by:

  1. Loading the manage submissions page
  2. Selecting a few checkboxes and confirming all buttons are enabled
  3. Deselecting all checkboxes and confirming all buttons are disabled
  4. Using "Select All" and confirming all buttons are enabled

Copy link
Contributor

@KesterTan KesterTan left a comment

Choose a reason for hiding this comment

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

Buttons work as expected, LGTM

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

♻️ Duplicate comments (1)
app/assets/javascripts/manage_submissions.js (1)

343-350: ⚠️ Potential issue

Fix early return that skips button event handlers.

The current implementation has a return statement on line 350 that exits the function early after setting up the download URL, preventing other buttons from getting their event handlers.

if (id == "#download-selected") {
  var urlParam = $.param({'submission_ids': selectedSubmissions});
  buttonIDs.forEach(function(id) {
    var newHref = baseURLs[id] + '?' + urlParam;
    $(id).prop('href', newHref);
  });
- return;
}
🧹 Nitpick comments (3)
app/controllers/assessment/autograde.rb (2)

90-99: Improve error handling for JSON parsing.

The code successfully reads submission IDs from the request body, but there's a useless variable assignment to e in the rescue block which is never used.

-                     rescue JSON::ParserError => e
+                     rescue JSON::ParserError
                       params[:submission_ids] || []
🧰 Tools
🪛 RuboCop (1.73)

[warning] 97-97: Useless assignment to variable - e.

(Lint/UselessAssignment)


90-102: Consider adding logging for JSON parse errors.

When JSON parsing fails, the code silently falls back to params without logging the error, which could make debugging difficult in production.

                     rescue JSON::ParserError => e
+                       Rails.logger.warn "JSON parse error in regradeBatch: #{e.message}"
                       params[:submission_ids] || []
🧰 Tools
🪛 RuboCop (1.73)

[warning] 97-97: Useless assignment to variable - e.

(Lint/UselessAssignment)

app/assets/javascripts/manage_submissions.js (1)

365-367: Consider using a more user-friendly approach than automatic page reload.

The current implementation uses a setInterval to reload the page every 5 seconds while waiting for AJAX requests to complete. This might be disruptive to users, especially for long-running operations.

Consider replacing the automatic page reload with a loading indicator and only refreshing the page once the operation completes:

- let refreshInterval = setInterval(() => {
-   location.reload();
- }, 5000);
+ // Show loading state
+ button.addClass("loading").prop("disabled", true);
+ // Add a spinner or other loading indicator
+ const loadingIndicator = $("<span class='spinner'></span>");
+ $(id).append(loadingIndicator);

Then in the success/error handlers:

 success: function (response) {
-  clearInterval(refreshInterval);
+  // Remove loading indicator
+  $(id).find('.spinner').remove();
+  button.removeClass("loading");
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 74964a4 and ccee62b.

📒 Files selected for processing (3)
  • app/assets/javascripts/manage_submissions.js (2 hunks)
  • app/controllers/assessment/autograde.rb (2 hunks)
  • app/views/submissions/index.html.erb (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/views/submissions/index.html.erb
🧰 Additional context used
🪛 RuboCop (1.73)
app/controllers/assessment/autograde.rb

[warning] 97-97: Useless assignment to variable - e.

(Lint/UselessAssignment)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (4)
app/controllers/assessment/autograde.rb (1)

144-147: Good use of respond_to block for AJAX support.

The implementation correctly handles both HTML and JSON responses, which aligns with the PR objective of using AJAX requests.

app/assets/javascripts/manage_submissions.js (3)

1-7: Endpoints added appropriately for AJAX functionality.

The new endpoints for delete, download, and excuse operations are consistent with the PR's objective to use AJAX requests instead of URL parameters.


351-397: Well-implemented AJAX request handling with proper error management.

The code correctly sets up AJAX requests with appropriate headers, error handling, and clearing of refresh intervals in both success and error cases.


333-399:

❓ Verification inconclusive

Implement consistent button state visibility across all buttons.

Based on the PR objectives, there's a concern about why only the download button is properly disabled. The current implementation may not be consistent in how it visually indicates disabled states across all buttons.

Could you verify that all buttons show a consistent disabled state by checking their CSS classes and appearance when no selections are made?


🏁 Script executed:

#!/bin/bash
# Check for consistent button styling and disabled state indicators
fd -e scss -e css | rg -A 2 "disabled|\.btn|\.button"

Length of output: 55


Action Required: Manual Verification for Consistent Button Disabled Styling

The current implementation toggles the .disabled class across buttons, but automated searches for relevant CSS rules returned no evidence. Please double-check manually that all buttons—especially the download button versus the others—exhibit a consistent disabled appearance when no selections are made. Verify both the applied CSS rules (in your CSS/SCSS files) and the actual rendered state in the browser.

@KesterTan KesterTan added this pull request to the merge queue Apr 14, 2025
Merged via the queue into master with commit a8f07e8 Apr 14, 2025
6 checks passed
@KesterTan KesterTan deleted the ajaxRequests branch April 14, 2025 03:57
NicholasMy pushed a commit to UB-CSE-IT/Autolab that referenced this pull request Jun 3, 2025
)

* fixing request bodies

* fixed disable buttons

* Fixing bugs

---------

Co-authored-by: Kester <kestertan040@gmail.com>
(cherry picked from commit a8f07e8)
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.

2 participants