diff --git a/app/controllers/api/class_members_controller.rb b/app/controllers/api/class_members_controller.rb index df0a9311b..7d79da10c 100644 --- a/app/controllers/api/class_members_controller.rb +++ b/app/controllers/api/class_members_controller.rb @@ -22,28 +22,28 @@ def index end def create - user_ids = [class_member_params[:user_id]] - user_type = class_member_params[:type] + user_id, user_type = class_member_params.require(%i[user_id type]) owners = SchoolOwner::List.call(school: @school).fetch(:school_owners, []) @school_owner_ids = owners.map(&:id) if user_type == 'student' - teachers = { school_teachers: [] } - students = SchoolStudent::List.call(school: @school, token: current_user.token, student_ids: user_ids) + teachers = [] + students = SchoolStudent::List.call(school: @school, token: current_user.token, student_ids: [user_id])[:school_students] else - teachers = SchoolTeacher::List.call(school: @school, teacher_ids: user_ids) - students = { school_students: [] } + teachers = SchoolTeacher::List.call(school: @school, teacher_ids: [user_id])[:school_teachers] + students = [] end - result = ClassMember::Create.call(school_class: @school_class, students: students[:school_students], teachers: teachers[:school_teachers]) - if result.success? + result = ClassMember::Create.call(school_class: @school_class, students: students, teachers: teachers) + + if students.blank? && teachers.blank? + render json: { error: 'No valid school members provided' }, status: :unprocessable_content + elsif result.success? @class_member = result[:class_members].first track_class_students_added([@class_member]) render :show, formats: [:json], status: :created else render json: result.slice(:error, :errors), status: :unprocessable_content end - rescue ArgumentError => e - render json: { error: e.message }, status: :unprocessable_content end def create_batch diff --git a/app/controllers/api/school_classes_controller.rb b/app/controllers/api/school_classes_controller.rb index 22e5469e5..01db66c3f 100644 --- a/app/controllers/api/school_classes_controller.rb +++ b/app/controllers/api/school_classes_controller.rb @@ -37,21 +37,14 @@ def create def import school_class_params = import_school_class_params school_students_params = import_school_students_params - - # Find or create the school class school_class_result = find_or_create_school_class(school_class_params) if school_class_result.success? school_class = school_class_result[:school_class] @school_class_with_teachers = school_class.with_teachers - # Create students if class exists - school_students_result = create_school_students(school_students_params, school_class) - @school_students = school_students_result[:school_students] - @school_students_errors = school_students_result[:errors] - - # Assign students to class - @class_members = assign_students_to_class(school_class, @school_students) + school_students = create_school_students(school_students_params, school_class) + assign_students_to_class(school_class, school_students) render :import, formats: [:json], status: :created else @@ -146,34 +139,20 @@ def accessible_school_classes end def create_school_students(school_students_params, school_class) - return { school_students: [], errors: nil } unless school_class.present? && school_students_params.present? - school_students_result = SchoolStudent::CreateBatchSSO.call( school: @school, school_students_params: school_students_params, current_user: ) - { - school_students: school_students_result[:school_students], - errors: school_students_result[:errors] - }.tap { track_created_school_students(school_students_result[:school_students], class_id: school_class.id) } + school_students_result[:school_students].tap { track_created_school_students(school_students_result[:school_students], class_id: school_class.id) } end def assign_students_to_class(school_class, school_students) - return [] unless school_class.present? && school_students.present? && school_students.any? - - # Extract the student objects for class member creation students = school_students.pluck(:student) class_members_result = ClassMember::Create.call(school_class:, students:, teachers: []) - # Put the errors in a more useful format for the response - class_members_errors = class_members_result[:errors].map do |user_id, error| - { success: false, student_id: user_id, school_class_id: school_class.id, error: error } - end - track_imported_class_students_added(school_class, class_members_result[:class_members]) - class_members_result[:class_members] + class_members_errors end def load_and_authorize_school @@ -209,8 +188,7 @@ def import_school_class_params end def import_school_students_params - school_students_data = params[:school_students] - return [] if school_students_data.blank? + school_students_data = Array(params[:school_students]) school_students_data.filter_map do |student| next if student.blank? diff --git a/app/views/api/school_classes/import.json.jbuilder b/app/views/api/school_classes/import.json.jbuilder index ac055a35c..c7dfda175 100644 --- a/app/views/api/school_classes/import.json.jbuilder +++ b/app/views/api/school_classes/import.json.jbuilder @@ -20,32 +20,3 @@ json.school_class do json.partial! '/api/school_teachers/school_teacher', teacher:, include_email: false end end - -# Students section -if @school_students_errors.present? - # This is the validation error case - json.students do - json.errors @school_students_errors - end -else - json.students(@school_students) do |student_item| - json.partial! '/api/school_students/school_student', student: student_item[:student] - - # Add the metadata - json.success student_item[:success] - json.error student_item[:error] - json.created student_item[:created] - end -end - -# Class members section -json.class_members(@class_members) do |class_member| - if class_member.is_a?(Hash) && class_member.key?(:success) && !class_member[:success] - # Add errors to the response - json.merge! class_member - else - json.partial! '/api/class_members/class_member', class_member: class_member - json.success true - json.error nil - end -end diff --git a/lib/concepts/class_member/operations/create.rb b/lib/concepts/class_member/operations/create.rb index ec0477cf5..e7a746d0c 100644 --- a/lib/concepts/class_member/operations/create.rb +++ b/lib/concepts/class_member/operations/create.rb @@ -7,14 +7,9 @@ def call(school_class:, students: [], teachers: []) response = OperationResponse.new response[:class_members] = [] response[:errors] = {} - raise ArgumentError, 'No valid school members provided' if students.blank? && teachers.blank? - create_class_teachers(school_class:, teachers:, response:) - create_class_students(school_class:, students:, response:) - response - rescue StandardError => e - Sentry.capture_exception(e) - response[:error] = "Error creating class members: #{e.message}" + create_class_teachers(school_class:, teachers: Array(teachers), response:) + create_class_students(school_class:, students: Array(students), response:) response end diff --git a/lib/profile_api_client.rb b/lib/profile_api_client.rb index d02119fad..66e255f03 100644 --- a/lib/profile_api_client.rb +++ b/lib/profile_api_client.rb @@ -142,6 +142,7 @@ def create_school_students(token:, students:, school_id:, preflight: false) end def create_school_students_sso(token:, students:, school_id:) + return [] if students.blank? return nil if token.blank? students = Array(students) diff --git a/spec/concepts/class_member/create_spec.rb b/spec/concepts/class_member/create_spec.rb index de9081c70..1cacce7db 100644 --- a/spec/concepts/class_member/create_spec.rb +++ b/spec/concepts/class_member/create_spec.rb @@ -75,21 +75,6 @@ it 'does not create a class teacher' do expect { described_class.call(school_class:, students:, teachers:) }.not_to change(ClassTeacher, :count) end - - it 'returns a failed operation response' do - response = described_class.call(school_class:, students:, teachers:) - expect(response.failure?).to be(true) - end - - it 'returns the error message in the operation response' do - response = described_class.call(school_class:, students:, teachers:) - expect(response[:error]).to include('No valid school members provided') - end - - it 'sent the exception to Sentry' do - described_class.call(school_class:, students:, teachers:) - expect(Sentry).to have_received(:capture_exception).with(kind_of(StandardError)) - end end context 'with a student from a different school' do diff --git a/spec/features/class_member/creating_a_batch_of_class_members_spec.rb b/spec/features/class_member/creating_a_batch_of_class_members_spec.rb index 19ef87eea..123c5c5c5 100644 --- a/spec/features/class_member/creating_a_batch_of_class_members_spec.rb +++ b/spec/features/class_member/creating_a_batch_of_class_members_spec.rb @@ -200,15 +200,9 @@ stub_user_info_api_for_unknown_users(user_id: unknown_user_id) end - it 'responds 422 Unprocessable Entity' do + it 'skips over unknown users' do post("/api/schools/#{school.id}/classes/#{school_class.id}/members/batch", headers:, params: invalid_params) - expect(response).to have_http_status(:unprocessable_content) - end - - it 'returns the error message in the operation response' do - post("/api/schools/#{school.id}/classes/#{school_class.id}/members/batch", headers:, params: invalid_params) - data = JSON.parse(response.body, symbolize_names: true) - expect(data[:error]).to include('No valid school members provided') + expect(response).to have_http_status(:ok) end end diff --git a/spec/features/class_member/creating_a_class_member_spec.rb b/spec/features/class_member/creating_a_class_member_spec.rb index 27a3acf7f..b318bfee7 100644 --- a/spec/features/class_member/creating_a_class_member_spec.rb +++ b/spec/features/class_member/creating_a_class_member_spec.rb @@ -218,7 +218,7 @@ end context 'with invalid params' do - let(:invalid_params) { { class_member: { user_id: SecureRandom.uuid } } } + let(:invalid_params) { { class_member: { user_id: nil, type: nil } } } before do stub_user_info_api_for_unknown_users(user_id: invalid_params[:class_member][:user_id]) @@ -229,16 +229,23 @@ expect(response).to have_http_status(:bad_request) end - it 'responds 422 Unprocessable Entity when params are invalid' do + it 'responds 400 Bad Request when params are invalid' do post("/api/schools/#{school.id}/classes/#{school_class.id}/members", headers:, params: invalid_params) - expect(response).to have_http_status(:unprocessable_content) + expect(response).to have_http_status(:bad_request) end + end - it 'returns the error message in the operation response' do - post("/api/schools/#{school.id}/classes/#{school_class.id}/members", headers:, params: invalid_params) - data = JSON.parse(response.body, symbolize_names: true) + context 'when the user has no role in the school' do + let(:user_without_role) { create(:user) } + let(:params_for_user_without_role) { { class_member: { user_id: user_without_role.id, type: 'student' } } } - expect(data[:error]).to include('No valid school members provided') + before do + stub_profile_api_list_school_students(school:, student_attributes: []) + end + + it 'responds 422 Unprocessable Content' do + post("/api/schools/#{school.id}/classes/#{school_class.id}/members", headers:, params: params_for_user_without_role) + expect(response).to have_http_status(:unprocessable_content) end end diff --git a/spec/features/school_class/importing_a_school_class_spec.rb b/spec/features/school_class/importing_a_school_class_spec.rb index 28a2c15ae..06998f2a7 100644 --- a/spec/features/school_class/importing_a_school_class_spec.rb +++ b/spec/features/school_class/importing_a_school_class_spec.rb @@ -97,159 +97,7 @@ end end - describe 'Student creation errors' do - before do - # Mock student creation to return errors - student_creation_error_result = OperationResponse.new - student_creation_error_result[:school_students] = [] - student_creation_error_result[:errors] = { - 'jane.student@example.com' => 'Email already exists', - 'john.student@example.com' => 'Invalid email format' - } - allow(SchoolStudent::CreateBatchSSO).to receive(:call).and_return(student_creation_error_result) - end - - it 'returns 201 with plural [:errors] in students section when student creation fails' do - 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) - - # School class should be created successfully - expect(response_data[:school_class][:name]).to eq('Imported Class') - expect(response_data[:school_class][:description]).to eq('Imported Description') - - # Students section should contain errors - expect(response_data[:students]).to have_key(:errors) - expect(response_data[:students][:errors]).to include( - 'jane.student@example.com': 'Email already exists', - 'john.student@example.com': 'Invalid email format' - ) - - # Class members should be empty since no students were created - expect(response_data[:class_members]).to eq([]) - end - end - - describe 'Class member creation errors' do - let(:mock_students) do - [ - { id: 'student-1-id', name: 'Jane Student', email: 'jane.student@example.com' }, - { id: 'student-2-id', name: 'John Student', email: 'john.student@example.com' } - ].map do |student_data| - # Create the new structure with User objects and metadata using factories - { - student: build_stubbed(:student, student_data), - success: true, - error: nil, - created: true - } - end - end - - before do - # Mock successful student creation - # Mock successful student creation but failed class assignment - student_creation_result = OperationResponse.new - student_creation_result[:school_students] = [ - { - student: build_stubbed(:student, id: 'student-1-id', name: 'Jane Student', email: 'jane.student@example.com'), - success: true, - error: nil, - created: true - }, - { - student: build_stubbed(:student, id: 'student-2-id', name: 'John Student', email: 'john.student@example.com'), - success: true, - error: nil, - created: true - } - ] - student_creation_result[:errors] = nil - allow(SchoolStudent::CreateBatchSSO).to receive(:call).and_return(student_creation_result) - - # Mock class member creation to return errors - class_member_creation_result = OperationResponse.new - class_member_creation_result[:class_members] = [] - class_member_creation_result[:errors] = { - 'aa7b5a78-2bd7-4676-8184-318f09a7c494' => 'Error creating class member' - } - allow(ClassMember::Create).to receive(:call).and_return(class_member_creation_result) - end - - it 'returns 201 errors in class_members section when assignment fails' do - 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) - - # School class should be created successfully - expect(response_data[:school_class][:name]).to eq('Imported Class') - - # Students should be created successfully - expect(response_data[:students]).to be_an(Array) - expect(response_data[:students].length).to eq(2) - - # Class members section should contain errors - expect(response_data[:class_members]).to be_an(Array) - expect(response_data[:class_members].length).to eq(1) - expect(response_data[:class_members].first[:success]).to be(false) - expect(response_data[:class_members].first[:student_id]).to eq('aa7b5a78-2bd7-4676-8184-318f09a7c494') - expect(response_data[:class_members].first[:error]).to eq('Error creating class member') - end - end - describe 'Successful import scenarios' do - let(:mock_successful_students) do - [ - { - student: build_stubbed(:student, id: 'student-1-id', name: 'Jane Student', email: 'jane.student@example.com'), - success: true, - error: nil, - created: true - }, - { - student: build_stubbed(:student, id: 'student-2-id', name: 'John Student', email: 'john.student@example.com'), - success: true, - error: nil, - created: true - } - ] - end - - let(:mock_successful_class_members) do - # Use factories to create proper test objects without database persistence - student_1 = build_stubbed(:student, id: 'student-1-id', name: 'Jane Student', username: 'jane.student', email: 'jane@example.com') - student_2 = build_stubbed(:student, id: 'student-2-id', name: 'John Student', username: 'john.student', email: 'john@example.com') - - [ - build_stubbed(:class_student, - id: 'member-1-id', - school_class_id: 'class-1-id', - student_id: 'student-1-id', - student: student_1), - build_stubbed(:class_student, - id: 'member-2-id', - school_class_id: 'class-1-id', - student_id: 'student-2-id', - student: student_2) - ] - end - - before do - # Mock successful student creation with new structure - student_success_result = OperationResponse.new - student_success_result[:school_students] = mock_successful_students - student_success_result[:errors] = nil - allow(SchoolStudent::CreateBatchSSO).to receive(:call).and_return(student_success_result) - - # Mock successful class member creation - class_member_success_result = OperationResponse.new - class_member_success_result[:class_members] = mock_successful_class_members - class_member_success_result[:errors] = {} - allow(ClassMember::Create).to receive(:call).and_return(class_member_success_result) - end - it 'successfully imports a class without students' do post(import_url, headers:, params: base_import_params) @@ -268,18 +116,22 @@ expect(response_data[:school_class][:teachers]).to be_an(Array) expect(response_data[:school_class][:teachers].first[:name]).to eq('School Teacher') - # Students and class_members should be empty arrays - expect(response_data[:students]).to eq([]) - expect(response_data[:class_members]).to eq([]) + 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) - # School class should be created expect(response_data[:school_class]).to include( name: 'Imported Class', description: 'Imported Description', @@ -287,34 +139,10 @@ import_id: 'classroom_123' ) - # Students should be created successfully - expect(response_data[:students]).to be_an(Array) - expect(response_data[:students].length).to eq(2) - response_data[:students].each do |student| - expect(student).to include( - success: true, - created: true - ) - expect(student[:error]).to be_nil - end - - # Class members should be assigned successfully - expect(response_data[:class_members]).to be_an(Array) - expect(response_data[:class_members].length).to eq(2) - - student_events = Event.where(name: 'Student - Created') - expect(student_events.map(&:properties)).to contain_exactly( - { 'school_id' => school.id, 'class_id' => response_data[:school_class][:id], 'student_id' => 'student-1-id' }, - { 'school_id' => school.id, 'class_id' => response_data[:school_class][:id], 'student_id' => 'student-2-id' } - ) - expect(student_events).to all(have_attributes(user_id: teacher.id, time: be_within(1.second).of(Time.current))) - - class_member_events = Event.where(name: 'Class - Student added') - expect(class_member_events.map(&:properties)).to contain_exactly( - { 'school_id' => school.id, 'class_id' => response_data[:school_class][:id], 'student_id' => 'student-1-id' }, - { 'school_id' => school.id, 'class_id' => response_data[:school_class][:id], 'student_id' => 'student-2-id' } - ) - expect(class_member_events).to all(have_attributes(user_id: teacher.id, time: be_within(1.second).of(Time.current))) + 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 @@ -334,27 +162,19 @@ end it 'returns the correct JSON structure for successful import' do - post(import_url, headers:, params: import_params_with_students) + 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) - expect(response_data).to have_key(:students) - expect(response_data).to have_key(:class_members) # 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 ) - - # Students structure (array when successful) - expect(response_data[:students]).to be_an(Array) - - # Class members structure (array when successful) - expect(response_data[:class_members]).to be_an(Array) end end @@ -368,8 +188,6 @@ response_data = JSON.parse(response.body, symbolize_names: true) expect(response_data[:school_class][:name]).to eq('Imported Class') - expect(response_data[:students]).to eq([]) - expect(response_data[:class_members]).to eq([]) end it 'handles nil students gracefully' do @@ -382,8 +200,6 @@ # Should still create the class successfully expect(response_data[:school_class][:name]).to eq('Imported Class') - expect(response_data[:students]).to eq([]) - expect(response_data[:class_members]).to eq([]) end end end