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

Changing the manage submissions button to be ajax requests #2271

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

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. In the Ruby controllers, methods in both the autograde and submissions 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.

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.

Sequence Diagram(s)

Loading
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

Possibly related PRs

  • Second Batch of Submissions Tests #2132: Involved modifications to the SubmissionsController, specifically testing deletion actions and handling submission IDs, which share similarities with the changes introduced here.

Suggested reviewers

  • KesterTan
  • evanyeyeye

Warning

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

🔧 RuboCop (1.69.1)
app/controllers/assessment/autograde.rb

Error: No such file or directory: /app/controllers/assessment/autograde.rb
{"metadata":{"rubocop_version":"1.69.1","ruby_engine":"ruby","ruby_version":"3.1.2","ruby_patchlevel":"20","ruby_platform":"x86_64-linux-gnu"},"files":[{"path":"app/controllers/assessment/autograde.rb","offenses":[]}],"summary":{"offense_count":0,"target_file_count":1,"inspected_file_count":0}}

app/controllers/submissions_controller.rb

Error: No such file or directory: /app/controllers/submissions_controller.rb
{"metadata":{"rubocop_version":"1.69.1","ruby_engine":"ruby","ruby_version":"3.1.2","ruby_patchlevel":"20","ruby_platform":"x86_64-linux-gnu"},"files":[{"path":"app/controllers/submissions_controller.rb","offenses":[]}],"summary":{"offense_count":0,"target_file_count":1,"inspected_file_count":0}}

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

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.

Comment on lines +313 to 380
buttonIDs.forEach((id) => {
const button = $(id);
if (state) {
console.log(`Disabling: ${id}`, button);
if (id === "#download-selected") {
$(id).prop('href', baseURLs[id]);
}
button.addClass("disabled");
button.off("click").prop("disabled", true);
} else {
button.removeClass("disabled").prop("disabled", false);
if (id == "#download-selected") {
var urlParam = $.param({'submission_ids': selectedSubmissions});
buttonIDs.forEach(function(id) {
var newHref = baseURLs[id] + '?' + urlParam;
$(id).prop('href', newHref);
});
return;
}
$(document).off("click", id).on("click", id, function (event) {
console.log(`${id} button clicked`);
event.preventDefault();
if (selectedSubmissions.length === 0) {
alert("No submissions selected.");
return;
}
const endpoint = manage_submissions_endpoints[id.replace("#", "")];
const requestData = { submission_ids: selectedSubmissions };
if (id === "#delete-selected") {
if (!confirm("Deleting will delete all checked submissions and cannot be undone. Are you sure you want to delete these submissions?")) {
return;
}
}
let refreshInterval = setInterval(() => {
location.reload();
}, 5000);
$.ajax({
url: endpoint,
type: "POST",
contentType: "application/json",
data: JSON.stringify(requestData),
dataType: "json",
headers: {
"X-CSRF-Token": $('meta[name="csrf-token"]').attr("content"),
},
success: function (response) {
clearInterval(refreshInterval);
if (response.redirect) {
window.location.href = response.redirect;
return;
}
if (response.error) {
alert(response.error);
}
if (response.success) {
alert(response.success);
}
selectedSubmissions = [];
changeButtonStates(true);
},
error: function (error) {
alert("An error occurred while processing the request.");
},
});
});
}
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ 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.");
  },
...
📝 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.

Suggested change
buttonIDs.forEach((id) => {
const button = $(id);
if (state) {
console.log(`Disabling: ${id}`, button);
if (id === "#download-selected") {
$(id).prop('href', baseURLs[id]);
}
button.addClass("disabled");
button.off("click").prop("disabled", true);
} else {
button.removeClass("disabled").prop("disabled", false);
if (id == "#download-selected") {
var urlParam = $.param({'submission_ids': selectedSubmissions});
buttonIDs.forEach(function(id) {
var newHref = baseURLs[id] + '?' + urlParam;
$(id).prop('href', newHref);
});
return;
}
$(document).off("click", id).on("click", id, function (event) {
console.log(`${id} button clicked`);
event.preventDefault();
if (selectedSubmissions.length === 0) {
alert("No submissions selected.");
return;
}
const endpoint = manage_submissions_endpoints[id.replace("#", "")];
const requestData = { submission_ids: selectedSubmissions };
if (id === "#delete-selected") {
if (!confirm("Deleting will delete all checked submissions and cannot be undone. Are you sure you want to delete these submissions?")) {
return;
}
}
let refreshInterval = setInterval(() => {
location.reload();
}, 5000);
$.ajax({
url: endpoint,
type: "POST",
contentType: "application/json",
data: JSON.stringify(requestData),
dataType: "json",
headers: {
"X-CSRF-Token": $('meta[name="csrf-token"]').attr("content"),
},
success: function (response) {
clearInterval(refreshInterval);
if (response.redirect) {
window.location.href = response.redirect;
return;
}
if (response.error) {
alert(response.error);
}
if (response.success) {
alert(response.success);
}
selectedSubmissions = [];
changeButtonStates(true);
},
error: function (error) {
alert("An error occurred while processing the request.");
},
});
});
}
});
}
buttonIDs.forEach((id) => {
const button = $(id);
if (state) {
console.log(`Disabling: ${id}`, button);
if (id === "#download-selected") {
$(id).prop('href', baseURLs[id]);
}
button.addClass("disabled");
button.off("click").prop("disabled", true);
} else {
button.removeClass("disabled").prop("disabled", false);
if (id == "#download-selected") {
var urlParam = $.param({'submission_ids': selectedSubmissions});
buttonIDs.forEach(function(id) {
var newHref = baseURLs[id] + '?' + urlParam;
$(id).prop('href', newHref);
});
return;
}
$(document).off("click", id).on("click", id, function (event) {
console.log(`${id} button clicked`);
event.preventDefault();
if (selectedSubmissions.length === 0) {
alert("No submissions selected.");
return;
}
const endpoint = manage_submissions_endpoints[id.replace("#", "")];
const requestData = { submission_ids: selectedSubmissions };
if (id === "#delete-selected") {
if (!confirm("Deleting will delete all checked submissions and cannot be undone. Are you sure you want to delete these submissions?")) {
return;
}
}
let refreshInterval = setInterval(() => {
location.reload();
}, 5000);
$.ajax({
url: endpoint,
type: "POST",
contentType: "application/json",
data: JSON.stringify(requestData),
dataType: "json",
headers: {
"X-CSRF-Token": $('meta[name="csrf-token"]').attr("content"),
},
success: function (response) {
clearInterval(refreshInterval);
if (response.redirect) {
window.location.href = response.redirect;
return;
}
if (response.error) {
alert(response.error);
}
if (response.success) {
alert(response.success);
}
selectedSubmissions = [];
changeButtonStates(true);
},
error: function (error) {
clearInterval(refreshInterval);
alert("An error occurred while processing the request.");
},
});
});
}
});
}

@KesterTan KesterTan requested review from KesterTan and removed request for coder6583 February 24, 2025 21:11
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.

1 participant