Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/controllers/courses_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def show
if @course.staff_user?(current_user)
@assignments = @course.assignments
@assignments_last_synced_at = assignments_last_synced_at
@stale_extension_totals = @course.stale_extension_totals
render :instructor_show
elsif @course.student_user?(current_user)
return redirect_to courses_path, alert: 'Extensions are not enabled for this course.' unless @course.requests_enabled?
Expand Down
31 changes: 25 additions & 6 deletions app/controllers/requests_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def index

def show
@assignment = @request.assignment
@number_of_days = @request.calculate_days_difference if @request.requested_due_date.present? && @assignment&.due_date.present?
@number_of_days = @request.extension_days
if @course.staff_user?(current_user)
@review = RequestReviewPresenter.new(@request)
@student_enrollment = @review.enrollment
Expand Down Expand Up @@ -73,8 +73,9 @@ def create_for_student

Request.merge_date_and_time!(params[:request])
@request = @course.requests.new(request_params.merge(user: student))
return render_new_for_student_error unless assignment_in_course?(@request.assignment_id)
return render_new_for_student_error unless assignment_in_course?(@request.assignment_id) && @request.valid?

# Only after validating, so a rejected date doesn't cost the student their other requests.
reject_other_student_requests(student, @request.assignment_id)

if @request.save
Expand All @@ -93,7 +94,9 @@ def update
result = @request.process_update(current_user)
redirect_to result[:redirect_to], notice: result[:notice]
else
flash.now[:alert] = 'There was a problem updating the request.'
flash.now[:alert] = request_error_message('There was a problem updating the request.')
@selected_assignment = @request.assignment
@assignments = [ @selected_assignment ]
render :edit
end
end
Expand Down Expand Up @@ -166,12 +169,18 @@ def requests_visible_to_user
end

def handle_request_error
flash.now[:alert] = 'There was a problem submitting your request.'
flash.now[:alert] = request_error_message('There was a problem submitting your request.')
@assignments = @course.enabled_assignments.order(:name)
@selected_assignment = Assignment.find_by(id: params[:assignment_id]) if params[:assignment_id]
render :new
end

# Adds the reason a requested date was refused, which people can act on.
def request_error_message(message)
date_errors = @request.errors.full_messages_for(:requested_due_date)
date_errors.empty? ? message : "#{message} #{date_errors.to_sentence}."
end

def set_form_settings
@form_settings = @course.form_setting
end
Expand Down Expand Up @@ -285,8 +294,10 @@ def handle_successful_student_request(student)
end

def render_new_for_student_error
# Before the form setup below, which replaces @request and its errors.
alert = request_error_message('There was a problem submitting the request.')
prepare_instructor_new_request
flash.now[:alert] = 'There was a problem submitting the request.'
flash.now[:alert] = alert
render :new_for_student
end

Expand Down Expand Up @@ -332,7 +343,7 @@ def process_mass_action(action)
"#{processed_count} request#{'s' unless processed_count == 1} #{action_label} successfully."
else
"#{processed_count} request#{'s' unless processed_count == 1} #{action_label}. "\
"#{failed_count} failed."
"#{failed_count} failed.#{stale_requests_note(requests, failed_ids)}"
end

render_mass_action_response(
Expand All @@ -345,6 +356,14 @@ def process_mass_action(action)
)
end

# Tells staff why these requests failed, since nothing else on the page does.
def stale_requests_note(requests, failed_ids)
stale_count = requests.count { |request| failed_ids.include?(request.id) && !request.extends_current_deadline? }
return '' if stale_count.zero?

" #{stale_count} of these #{stale_count == 1 ? 'asks' : 'ask'} for a date that is not later than the current due date."
end

def render_mass_action_response(success:, message:, processed_ids:, failed_ids:, new_status:, status:)
pending_count = @course.requests.pending.count
respond_to do |format|
Expand Down
36 changes: 36 additions & 0 deletions app/facades/canvas_facade.rb
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,42 @@ def provision_extension(course_id, student_id, assignment_id, new_due_date, new_
end
end

# See LmsFacade#student_identifier.
def student_identifier(user)
user.canvas_uid.to_i
end

##
# See LmsFacade#extension_due_dates. Section overrides have no student_ids, so
# only overrides that name individual students are included.
def extension_due_dates(course_id, assignment_id)
list_override_structs(course_id, assignment_id).each_with_object({}) do |override, due_dates|
next if override.due_at.blank?

override.student_ids&.each { |id| due_dates[id.to_i] = Time.zone.parse(override.due_at.to_s) }
end
end

##
# See LmsFacade#remove_extension. An override shared with other students stays
# in place for them. The overrides are read fresh for each removal because a
# shared override's student list is rewritten in full: a stale list would put
# back a student who was removed a moment ago.
def remove_extension(course_id, student_id, assignment_id)
override = find_student_override(list_override_structs(course_id, assignment_id), student_id)
return false unless override

if override.student_ids.length == 1
response = delete_assignment_override(course_id, assignment_id, override.id)
unless (200..299).cover?(response.status)
raise CanvasAPIError, "Canvas could not delete the extension (HTTP #{response.status})"
end
else
remove_student_from_override(course_id, override, student_id)
end
true
end

private

##
Expand Down
69 changes: 69 additions & 0 deletions app/facades/gradescope_facade.rb
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,77 @@ def provision_extension(course_id, student_email, assignment_id, new_due_date, n
end
end

# See LmsFacade#student_identifier.
def student_identifier(user)
user.email
end

# See LmsFacade#extension_due_dates. Overrides identify students by their
# Gradescope id, so these are matched to emails using the page's student list.
def extension_due_dates(course_id, assignment_id)
ensure_authenticated!
html = extensions_page(course_id, assignment_id)
emails = student_emails_by_id(html)

extension_overrides(html).each_with_object({}) do |override, due_dates|
email = emails[override.student_id.to_s]
due_date = parse_extension_date(override.override_due_date)
due_dates[email] = due_date if email && due_date
end
end

# See LmsFacade#remove_extension. Reads the page again afterwards because a
# rejected delete can still return a successful status.
def remove_extension(course_id, student_email, assignment_id)
ensure_authenticated!
html = extensions_page(course_id, assignment_id)
student_id = student_emails_by_id(html).key(student_email)
override = find_extension_override(html, student_id)
return false unless override

@gradescope_conn.delete("/courses/#{course_id}/assignments/#{assignment_id}/extensions/#{override.id}")

if find_extension_override(extensions_page(course_id, assignment_id), student_id)
raise GradescopeAPIError, "Gradescope did not remove the extension for #{student_email}"
end
true
end

private

# Unlike get_assignment_overrides, this raises on failure: callers must be
# able to tell "no extensions" apart from "could not read the extensions".
def extensions_page(course_id, assignment_id)
html = @gradescope_conn.get("/courses/#{course_id}/assignments/#{assignment_id}/extensions")
raise GradescopeAPIError, 'Failed to fetch assignment extensions: No response' if html.blank?

html
end

def extension_overrides(html)
@gradescope_conn.extract_all_react_props(html, 'EditExtension')
.map { |data| Lmss::Gradescope::Override.new(data) }
end

def find_extension_override(html, student_id)
return if student_id.nil?

extension_overrides(html).find { |override| override.student_id.to_s == student_id }
end

def student_emails_by_id(html)
students = @gradescope_conn.extract_react_props(html, 'AddExtension')&.fetch('students', nil) || []
students.to_h { |student| [ student['id'].to_s, student['email'] ] }
end

# An extension can hold a relative value rather than a date, which isn't one
# Flextensions created, so anything unreadable is treated as having no date.
def parse_extension_date(value)
Time.zone.parse(value.to_s)
rescue ArgumentError
nil
end

# Performs authentication to Gradescope if not already authenticated.
def ensure_authenticated!
return if @gradescope_conn
Expand Down
33 changes: 33 additions & 0 deletions app/facades/lms_facade.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,37 @@ def get_assignment_overrides(external_course_id, external_assignment_id)
def provision_extension(course_id, student_id, assignment_id, new_due_date)
raise NotImplementedError
end

##
# The value this LMS uses to identify a student in the extension methods.
#
# @param [User] user the student.
# @return [Object] the identifier passed as student_id to the extension methods.
def student_identifier(user)
raise NotImplementedError
end

##
# Reads the due date of every student-specific extension on an assignment.
#
# @param [String] course_id the course the assignment belongs to.
# @param [String] assignment_id the assignment to read extensions from.
# @return [Hash{Object => Time}] due dates, keyed by student_identifier.
# @raises [StandardError] if the extensions could not be read, so that a
# failure is never mistaken for an assignment with no extensions.
def extension_due_dates(course_id, assignment_id)
raise NotImplementedError
end

##
# Removes a student's extension, so the assignment's own dates apply to them.
#
# @param [String] course_id the course the assignment belongs to.
# @param [Object] student_id the student, as given by student_identifier.
# @param [String] assignment_id the assignment to remove the extension from.
# @return [Boolean] true if an extension was removed, false if there was none.
# @raises [StandardError] if the extension could not be removed.
def remove_extension(course_id, student_id, assignment_id)
raise NotImplementedError
end
end
4 changes: 3 additions & 1 deletion app/javascript/controllers/assignment_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,9 @@ export default class extends Controller {

if (!response.ok) throw new Error(`Failed to sync assignments. ${response.status}`);

await pollUntilDone(courseId, "assignments", statusBefore);
// Allow extra time: the first sync after a deadline moves may need to remove
// many outdated extensions from the LMS, one student at a time.
await pollUntilDone(courseId, "assignments", statusBefore, 1000, 300000);

flash("notice", "Assignments synced successfully.");
location.reload();
Expand Down
3 changes: 2 additions & 1 deletion app/javascript/controllers/extension_form_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ export default class extends Controller {
this.originalDueDateStr.split(" at ")[0]
);
} else {
this.originalDueDateStr = this.dueDateInputTarget.value;
// The field's value is the suggested date, a day after the due date.
this.originalDueDateStr = this.originalDueDateStr || this.dueDateInputTarget.value;
this.originalDueDate = new Date(this.originalDueDateStr);
}
if (this.originalDueDateStr) {
Expand Down
4 changes: 4 additions & 0 deletions app/jobs/sync_all_course_assignments_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ def perform(course_to_lms_id, sync_user_id)
# rubocop:enable Rails/SkipsModelValidations
end

# Runs on every sync rather than only when a date changes, so existing bad
# overrides get repaired and failed removals get retried.
results[:stale_extensions] = StaleExtensionRemover.new(course_to_lms, facade).call(external_assignment_ids)

results[:synced_at] = Time.current

course_to_lms.recent_assignment_sync = results
Expand Down
11 changes: 11 additions & 0 deletions app/models/assignment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,17 @@ def has_pending_request_for_user?(user, course)
requests.exists?(user: user, course: course, status: 'pending')
end

# The deadline that applies to this user right now: their approved extension
# when it is still later than the class deadline, otherwise the class deadline.
# The class deadline can move past an extension after it was approved.
#
# Only the most recent approval counts, even if an earlier one ended later,
# because each approval replaces the student's previous override in the LMS.
def current_due_date_for(user)
latest_extension = requests.where(user: user, status: 'approved').order(:updated_at).last
[ due_date, latest_extension&.requested_due_date ].compact.max
end

def set_course_from_course_to_lms
self.course ||= course_to_lms&.course
end
Expand Down
10 changes: 10 additions & 0 deletions app/models/course.rb
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,16 @@ def sync_assignments(sync_user)
end
end

# What the latest assignment syncs did about outdated extensions, added up
# across this course's LMSs: { 'removed' => 0, 'skipped' => 0, 'failed' => 0 }.
def stale_extension_totals
totals = { 'removed' => 0, 'skipped' => 0, 'failed' => 0 }
all_linked_lmss.filter_map { |link| link.recent_assignment_sync&.dig('stale_extensions') }.each do |results|
results.each { |outcome, count| totals[outcome] += count if totals.key?(outcome) }
end
totals
end

# Creates an enrollment for the user's highest-ranked role among the given
# Canvas enrollment hashes (from the Canvas courses API). No-op when none of
# the Canvas enrollments map to a role we know.
Expand Down
Loading
Loading