Skip to content
Merged
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
9 changes: 6 additions & 3 deletions app/controllers/api/school_classes_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,12 @@ def import
school_class = school_class_result[:school_class]
@school_class_with_teachers = school_class.with_teachers

school_students = create_school_students(school_students_params, school_class)
assign_students_to_class(school_class, school_students)

if params.key?(:async)
@batch = CreateAndAssignStudentsJob.enqueue_batches(school_class:, students: school_students_params, current_user:)
else
school_students = create_school_students(school_students_params, school_class)
assign_students_to_class(school_class, school_students)
end
render :import, formats: [:json], status: :created
else
render json: { error: school_class_result[:error] }, status: :unprocessable_content
Expand Down
8 changes: 7 additions & 1 deletion app/controllers/api/user_jobs_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,18 @@ def batch_attributes_for(user_job)
end

def batch_attributes(batch)
{
attributes = {
id: batch.id,
concurrency_key: batch.description,
status: batch_status(batch),
finished_at: batch.finished_at
}
attributes[:progress] = batch_progress(batch) if batch.properties[:total]
attributes
end

def batch_progress(batch)
{ total: batch.properties[:total], processed: batch.properties[:processed].to_i }
end

# Try to emulate a Job's .status field for a batch.
Expand Down
82 changes: 82 additions & 0 deletions app/jobs/create_and_assign_students_job.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# frozen_string_literal: true

class CreateAndAssignStudentsJob < ApplicationJob
include GoodJob::ActiveJobExtensions::Batches

retry_on StandardError, attempts: 3 do |_job, e|
Sentry.capture_exception(e)
end
Comment thread
macroscopeapp[bot] marked this conversation as resolved.
Resolved

include GoodJob::ActiveJobExtensions::Concurrency

BATCH_SIZE = 20

good_job_concurrency_rule(
label: -> { "create-and-assign-students-school-#{arguments.first[:school_class_id]}" },
apply_label: true,
perform_limit: 1
)

def self.enqueue_batches(school_class:, students:, current_user:)
school = school_class.school
SafeguardingFlagService.create_for_school_roles(user: current_user, school:)
students = StudentHelpers.normalise_nil_values_to_empty_strings(students)
batch = GoodJob::Batch.new(
description: "Creating and assigning students for #{school_class.school.name}",
total: students.size,
processed: 0
)
batch.add do
students.each_slice(BATCH_SIZE) do |student_batch|
CreateAndAssignStudentsJob.perform_later(
school_class_id: school_class.id,
students: student_batch,
creator_id: current_user.id,
token: current_user.token
)
end
end

batch.enqueue
UserJob.create!(user_id: current_user.id, good_job_batch_id: batch.id)
batch
end

def perform(school_class_id:, students:, creator_id:, token:)
school_class = SchoolClass.find(school_class_id)
responses = ProfileApiClient.create_school_students_sso(token:, students: students, school_id: school_class.school_id)

successful_responses, failed_responses = responses.partition { |response| response[:success] }

create_student_roles(school: school_class.school, students: successful_responses, creator_id: creator_id)
create_class_students(school_class:, students: successful_responses, creator_id: creator_id)

report_failures(failed_responses)
Comment thread
macroscopeapp[bot] marked this conversation as resolved.
Resolved
record_progress(students.size)
end

def record_progress(students_processed)
return if batch.nil?

batch.properties[:processed] = batch.properties[:processed].to_i + students_processed
batch.save
end

def create_student_roles(school:, students:, creator_id:)
students.each do |student|
Role.create_student_with_tracking!(school: school, creator_id:, student_id: student[:id])
end
end

def create_class_students(school_class:, students:, creator_id:)
students.each do |student|
ClassStudent.create_with_tracking!(school_class: school_class, student_id: student[:id], creator_id: creator_id)
end
end

def report_failures(responses)
responses.each do |response|
Sentry.capture_message('Student creation failed in Profile', extra: response[:error])
end
end
end
14 changes: 14 additions & 0 deletions app/models/class_student.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,20 @@ class ClassStudent < ApplicationRecord

after_commit :do_salesforce_sync, on: %i[create destroy], if: -> { FeatureFlags.salesforce_sync? }

def self.create_with_tracking!(school_class:, student_id:, creator_id:)
create!(school_class:, student_id:)

EventTracker.track!(
user_id: creator_id,
name: 'Class - Student added',
properties: { school_id: school_class.school_id, student_id:, class_id: school_class.id }
)
rescue ActiveRecord::RecordNotUnique
nil
rescue ActiveRecord::RecordInvalid => e
raise unless e.record.errors.of_kind?(:student_id, :taken)
end

def user_id
student_id
end
Expand Down
10 changes: 10 additions & 0 deletions app/models/role.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ class Role < ApplicationRecord

after_commit :do_salesforce_sync, on: %i[create update], if: -> { FeatureFlags.salesforce_sync? && !student? }

def self.create_student_with_tracking!(school:, creator_id:, student_id:)
create!(school_id: school.id, user_id: student_id, role: :student)

EventTracker.track!(user_id: creator_id, name: 'Student - Created', properties: { school_id: school.id, student_id: })
rescue ActiveRecord::RecordNotUnique
nil
rescue ActiveRecord::RecordInvalid => e
raise unless e.record.errors.of_kind?(:role, :taken)
end

def archive!
update!(archived_at: Time.zone.now)
end
Expand Down
2 changes: 2 additions & 0 deletions app/views/api/school_classes/import.json.jbuilder
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,5 @@ json.school_class do
json.partial! '/api/school_teachers/school_teacher', teacher:, include_email: false
end
end

json.job_id @batch.id if defined?(@batch)
205 changes: 205 additions & 0 deletions spec/features/school_class/importing_a_school_class_async_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
# frozen_string_literal: true

require 'rails_helper'

RSpec.describe 'Importing a school class', :inline_jobs, type: :request do
before do
authenticated_in_hydra_as(teacher)
stub_user_info_api_for(teacher)
stub_profile_api_create_safeguarding_flag
end

let(:headers) { { Authorization: UserProfileMock::TOKEN } }
let(:school) { create(:school) }
let(:teacher) { create(:teacher, school:, name: 'School Teacher') }

let(:import_url) { "/api/schools/#{school.id}/classes/import" }
let(:base_import_params) do
{
school_class: {
name: 'Imported Class',
description: 'Imported Description',
import_origin: 'google_classroom',
import_id: 'classroom_123'
},
async: '1'
}
end

let(:import_params_with_students) do
base_import_params.merge(
school_students: [
{ name: 'Jane Student', email: 'jane.student@example.com' },
{ name: 'John Student', email: 'john.student@example.com' }
]
)
end

describe 'School class creation errors' do
it 'returns 422 if import_origin is missing' do
params_missing_origin = base_import_params.deep_dup
params_missing_origin[:school_class].delete(:import_origin)

post(import_url, headers:, params: params_missing_origin)

expect(response).to have_http_status(:unprocessable_content)
error_response = JSON.parse(response.body)
expect(error_response).to have_key('error')
expect(error_response['error']).to include("Import origin can't be blank")
end

it 'returns 422 if import_id is missing' do
params_missing_id = base_import_params.deep_dup
params_missing_id[:school_class].delete(:import_id)

post(import_url, headers:, params: params_missing_id)

expect(response).to have_http_status(:unprocessable_content)
error_response = JSON.parse(response.body)
expect(error_response).to have_key('error')
expect(error_response['error']).to include("Import id can't be blank")
end

it 'returns 422 if both import_origin and import_id are missing' do
params_missing_both = base_import_params.deep_dup
params_missing_both[:school_class].delete(:import_origin)
params_missing_both[:school_class].delete(:import_id)

post(import_url, headers:, params: params_missing_both)

expect(response).to have_http_status(:unprocessable_content)
error_response = JSON.parse(response.body)
expect(error_response).to have_key('error')
expect(error_response['error']).to include("Import origin can't be blank")
end

it 'returns 422 if import_origin is invalid' do
params_invalid_enum = base_import_params.deep_dup
params_invalid_enum[:school_class][:import_origin] = 'not_a_valid_origin'

post(import_url, headers:, params: params_invalid_enum)

expect(response).to have_http_status(:unprocessable_content)
error_response = JSON.parse(response.body)
expect(error_response).to have_key('error')
expect(error_response['error']).to include('Import origin is not included in the list')
end

it 'returns 422 if class name is missing' do
params_missing_name = base_import_params.deep_dup
params_missing_name[:school_class].delete(:name)

post(import_url, headers:, params: params_missing_name)

expect(response).to have_http_status(:unprocessable_content)
error_response = JSON.parse(response.body)
expect(error_response).to have_key('error')
expect(error_response['error']).to include("Name can't be blank")
end
end

describe 'Successful import scenarios' do
it 'successfully imports a class without students' do
post(import_url, headers:, params: base_import_params)

expect(response).to have_http_status(:created)
response_data = JSON.parse(response.body, symbolize_names: true)

# School class should be created
expect(response_data[:school_class]).to include(
name: 'Imported Class',
description: 'Imported Description',
import_origin: 'google_classroom',
import_id: 'classroom_123'
)

# Teachers should be included
expect(response_data[:school_class][:teachers]).to be_an(Array)
expect(response_data[:school_class][:teachers].first[:name]).to eq('School Teacher')

expect(school.roles.student.count).to eq(0)
end

it 'successfully imports a class with students and assigns them' do
student_1_id = SecureRandom.uuid
student_2_id = SecureRandom.uuid
profile_response = [
{ id: student_1_id, name: 'Jane Student', success: true },
{ id: student_2_id, name: 'John Student', success: true }
]
allow(ProfileApiClient).to receive(:create_school_students_sso).and_return(profile_response)
post(import_url, headers:, params: import_params_with_students)

expect(response).to have_http_status(:created)
response_data = JSON.parse(response.body, symbolize_names: true)

expect(response_data[:school_class]).to include(
name: 'Imported Class',
description: 'Imported Description',
import_origin: 'google_classroom',
import_id: 'classroom_123'
)
school_class = SchoolClass.find_by(import_id: 'classroom_123')
students = school_class.students
expect(school_class.students.count).to eq(2)
expect(students.map(&:student_id)).to contain_exactly(student_1_id, student_2_id)
end

it 'allows re-importing the same class (finds existing class)' do
# First import should create the class
post(import_url, headers:, params: base_import_params)
expect(response).to have_http_status(:created)
first_response_data = JSON.parse(response.body, symbolize_names: true)

# Second import with the same import_id should find the existing class
post(import_url, headers:, params: base_import_params)
expect(response).to have_http_status(:created)
second_response_data = JSON.parse(response.body, symbolize_names: true)

# Should return the same class
expect(second_response_data[:school_class][:id]).to eq(first_response_data[:school_class][:id])
expect(second_response_data[:school_class][:name]).to eq('Imported Class')
end

it 'returns the correct JSON structure for successful import' do
post(import_url, headers:, params: base_import_params)

expect(response).to have_http_status(:created)
response_data = JSON.parse(response.body, symbolize_names: true)

# Verify the complete structure matches the import template
expect(response_data).to have_key(:school_class)

# School class structure
expect(response_data[:school_class]).to include(
:id, :name, :description, :school_id, :code,
:created_at, :updated_at, :import_origin, :import_id, :teachers
)
end
end

describe 'Edge cases' do
it 'handles empty students array gracefully' do
params_with_empty_students = base_import_params.merge(school_students: [])

post(import_url, headers:, params: params_with_empty_students)

expect(response).to have_http_status(:created)
response_data = JSON.parse(response.body, symbolize_names: true)

expect(response_data[:school_class][:name]).to eq('Imported Class')
end

it 'handles nil students gracefully' do
params_with_nil_students = base_import_params.merge(school_students: nil)

post(import_url, headers:, params: params_with_nil_students)

expect(response).to have_http_status(:created)
response_data = JSON.parse(response.body, symbolize_names: true)

# Should still create the class successfully
expect(response_data[:school_class][:name]).to eq('Imported Class')
end
end
end
10 changes: 10 additions & 0 deletions spec/features/user_job/showing_user_jobs_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@
expect(data[:job][:id]).to eq(job_id)
end

it 'responds with the progress of a job that tracks it' do
progress_batch = GoodJob::BatchRecord.create!(description: school.id, properties: { total: 10, processed: 4 })
create(:user_job, good_job_batch_id: progress_batch.id, user_id: owner.id)

get("/api/user_jobs/#{progress_batch.id}", headers:)
data = JSON.parse(response.body, symbolize_names: true)

expect(data[:job][:progress]).to eq(total: 10, processed: 4)
end

it 'responds 404 Not Found when the job belongs to another user' do
other_batch = GoodJob::BatchRecord.create!(description: 'other-user-job')
other_user_job = create(:user_job, good_job_batch_id: other_batch.id, user_id: other_user.id)
Expand Down
Loading
Loading