diff --git a/app/controllers/api/school_classes_controller.rb b/app/controllers/api/school_classes_controller.rb index 01db66c3f..bc0984873 100644 --- a/app/controllers/api/school_classes_controller.rb +++ b/app/controllers/api/school_classes_controller.rb @@ -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 diff --git a/app/controllers/api/user_jobs_controller.rb b/app/controllers/api/user_jobs_controller.rb index 802dd7ea6..b288a2d55 100644 --- a/app/controllers/api/user_jobs_controller.rb +++ b/app/controllers/api/user_jobs_controller.rb @@ -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. diff --git a/app/jobs/create_and_assign_students_job.rb b/app/jobs/create_and_assign_students_job.rb new file mode 100644 index 000000000..f7ace46a7 --- /dev/null +++ b/app/jobs/create_and_assign_students_job.rb @@ -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 + + 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) + 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 diff --git a/app/models/class_student.rb b/app/models/class_student.rb index 8de36adbd..a438308bd 100644 --- a/app/models/class_student.rb +++ b/app/models/class_student.rb @@ -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 diff --git a/app/models/role.rb b/app/models/role.rb index ac9d9c19e..42e2b3218 100644 --- a/app/models/role.rb +++ b/app/models/role.rb @@ -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 diff --git a/app/views/api/school_classes/import.json.jbuilder b/app/views/api/school_classes/import.json.jbuilder index c7dfda175..76ba04edc 100644 --- a/app/views/api/school_classes/import.json.jbuilder +++ b/app/views/api/school_classes/import.json.jbuilder @@ -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) diff --git a/spec/features/school_class/importing_a_school_class_async_spec.rb b/spec/features/school_class/importing_a_school_class_async_spec.rb new file mode 100644 index 000000000..a6dbc128e --- /dev/null +++ b/spec/features/school_class/importing_a_school_class_async_spec.rb @@ -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 diff --git a/spec/features/user_job/showing_user_jobs_spec.rb b/spec/features/user_job/showing_user_jobs_spec.rb index d93b57481..021a3085f 100644 --- a/spec/features/user_job/showing_user_jobs_spec.rb +++ b/spec/features/user_job/showing_user_jobs_spec.rb @@ -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) diff --git a/spec/jobs/create_and_assign_students_job_spec.rb b/spec/jobs/create_and_assign_students_job_spec.rb new file mode 100644 index 000000000..707deece3 --- /dev/null +++ b/spec/jobs/create_and_assign_students_job_spec.rb @@ -0,0 +1,90 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe CreateAndAssignStudentsJob do + let(:school) { create(:verified_school) } + let(:current_user) { create(:teacher, school:, token: UserProfileMock::TOKEN) } + let(:school_class) { create(:school_class, school:, teacher_ids: [current_user.id]) } + let(:student_ids) { [SecureRandom.uuid, SecureRandom.uuid] } + + let(:students) do + [ + { name: 'Jane Student', email: 'jane.student@example.com' }, + { name: 'John Student', email: 'john.student@example.com' } + ] + end + + before do + stub_profile_api_create_safeguarding_flag + stub_profile_api_create_school_students_sso(user_ids: student_ids) + end + + after do + GoodJob::Job.delete_all + end + + describe '#perform' do + it 'creates the students in Profile' do + described_class.perform_now(school_class_id: school_class.id, students:, creator_id: current_user.id, token: current_user.token) + + expect(ProfileApiClient).to have_received(:create_school_students_sso) + .with(token: current_user.token, students:, school_id: school.id) + end + + it 'gives the students a role in the school and adds them to the class' do + described_class.perform_now(school_class_id: school_class.id, students:, creator_id: current_user.id, token: current_user.token) + + expect(Role.student.where(school:, user_id: student_ids).count).to eq(2) + expect(school_class.students.pluck(:student_id)).to match_array(student_ids) + end + + it 'reports students that could not be created to Sentry' do + allow(ProfileApiClient).to receive(:create_school_students_sso) + .and_return([{ name: 'Jane Student', success: false, error: 'unknown error' }]) + allow(Sentry).to receive(:capture_message) + + described_class.perform_now(school_class_id: school_class.id, students:, creator_id: current_user.id, token: current_user.token) + + expect(Sentry).to have_received(:capture_message) + .with('Student creation failed in Profile', extra: 'unknown error') + end + end + + describe 'batch progress', :inline_jobs do + it 'records the number of students to process on the batch' do + batch = described_class.enqueue_batches(school_class:, students:, current_user:) + + expect(batch.properties).to include(total: 2) + end + + it 'counts the students off as each job performs' do + batch = described_class.enqueue_batches(school_class:, students:, current_user:) + expect(batch.reload.properties).to include(processed: 2) + end + end + + describe 'concurrency' do + it 'allows only one job to perform at a time per school class' do + job = described_class.new(school_class_id: school_class.id, students:, creator_id: current_user.id, token: current_user.token) + + expect(job.good_job_labels).to eq(["create-and-assign-students-school-#{school_class.id}"]) + expect(described_class.good_job_concurrency_rules.first.perform_limit).to eq(1) + end + end + + describe '.enqueue_batches' do + it 'creates a safeguarding flag for the user' do + described_class.enqueue_batches(school_class:, students:, current_user:) + + expect(ProfileApiClient).to have_received(:create_safeguarding_flag) + .with(token: current_user.token, flag: 'school:teacher', email: current_user.email, school_id: school.id) + end + + it 'records the batch against the user' do + batch = described_class.enqueue_batches(school_class:, students:, current_user:) + + expect(UserJob.find_by(user_id: current_user.id)).to have_attributes(good_job_batch_id: batch.id) + end + end +end diff --git a/spec/jobs/create_students_job_spec.rb b/spec/jobs/create_students_job_spec.rb index f515bd475..b5848ab26 100644 --- a/spec/jobs/create_students_job_spec.rb +++ b/spec/jobs/create_students_job_spec.rb @@ -2,7 +2,7 @@ require 'rails_helper' -RSpec.describe CreateStudentsJob do +RSpec.describe CreateStudentsJob, :inline_jobs do include ActiveJob::TestHelper let(:token) { UserProfileMock::TOKEN } @@ -18,14 +18,6 @@ }] end - around do |example| - original = ActiveJob::Base.queue_adapter - ActiveJob::Base.queue_adapter = :good_job - example.run - ensure - ActiveJob::Base.queue_adapter = original - end - before do stub_profile_api_create_school_students(user_ids: [user_id]) allow(SafeguardingFlagService).to receive(:create_for_token) diff --git a/spec/models/class_student_spec.rb b/spec/models/class_student_spec.rb index cf9cf9e32..ebb366f71 100644 --- a/spec/models/class_student_spec.rb +++ b/spec/models/class_student_spec.rb @@ -62,6 +62,36 @@ end end + describe '.create_with_tracking!' do + let(:creator_id) { SecureRandom.uuid } + + it 'adds the student to the class' do + described_class.create_with_tracking!(school_class:, student_id: student.id, creator_id:) + + expect(described_class.find_by(school_class:, student_id: student.id)).to be_present + end + + it 'records a class student added event' do + described_class.create_with_tracking!(school_class:, student_id: student.id, creator_id:) + + expect(Event.last).to have_attributes( + name: 'Class - Student added', + user_id: creator_id, + properties: { + 'school_id' => school.id, + 'class_id' => school_class.id, + 'student_id' => student.id + } + ) + end + + it 'does not raise when the student is already in the class' do + described_class.create_with_tracking!(school_class:, student_id: student.id, creator_id:) + + expect { described_class.create_with_tracking!(school_class:, student_id: student.id, creator_id:) }.not_to raise_error + end + end + describe 'auditing' do subject(:class_student) { create(:class_student, student_id: student.id, school_class:) } diff --git a/spec/models/role_spec.rb b/spec/models/role_spec.rb index fc7ea4595..633d86ed5 100644 --- a/spec/models/role_spec.rb +++ b/spec/models/role_spec.rb @@ -166,6 +166,34 @@ end end + describe '.create_student_with_tracking!' do + let(:school) { create(:school) } + let(:student_id) { SecureRandom.uuid } + let(:creator_id) { SecureRandom.uuid } + + it 'creates a student role for the school' do + described_class.create_student_with_tracking!(school:, creator_id:, student_id:) + + expect(described_class.student.find_by(school:, user_id: student_id)).to be_present + end + + it 'records a student created event' do + described_class.create_student_with_tracking!(school:, creator_id:, student_id:) + + expect(Event.last).to have_attributes( + name: 'Student - Created', + user_id: creator_id, + properties: { 'school_id' => school.id, 'student_id' => student_id } + ) + end + + it 'does not raise when the student role already exists' do + described_class.create_student_with_tracking!(school:, creator_id:, student_id:) + + expect { described_class.create_student_with_tracking!(school:, creator_id:, student_id:) }.not_to raise_error + end + end + describe 'salesforce sync' do around do |example| ClimateControl.modify(SALESFORCE_ENABLED: 'true') { example.run } diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index 528fd668d..ffc624633 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -103,6 +103,13 @@ driven_by :rack_test end + config.around(:each, :inline_jobs) do |example| + original = ActiveJob::Base.queue_adapter + ActiveJob::Base.queue_adapter = :good_job + example.run + ActiveJob::Base.queue_adapter = original + end + config.around(type: :task) do |example| DatabaseCleaner.clean_with(:truncation) DatabaseCleaner.strategy = :truncation