@@ -32,17 +32,36 @@ def call(school:, school_students_params:, current_user:)
3232 private
3333
3434 def create_batch_sso ( school , students , token )
35+ students = normalize_student_params ( students )
36+ responses = ProfileApiClient . create_school_students_sso ( token :, students :, school_id : school . id )
37+
38+ create_student_roles ( school , responses )
39+ format_student_responses ( responses )
40+ rescue ProfileApiClient ::Student422Error => e
41+ handle_validations ( e . errors )
42+ end
43+
44+ def normalize_student_params ( students )
3545 # Ensure that nil values are empty strings, else Profile will swallow validations
36- students = students . map do |student |
46+ students . map do |student |
3747 student . transform_values { |value | value . nil? ? '' : value }
3848 end
49+ end
3950
40- responses = ProfileApiClient . create_school_students_sso ( token :, students :, school_id : school . id )
51+ def create_student_roles ( school , responses )
52+ # Bulk check which roles already exist to avoid N+1 queries
53+ user_ids = responses . pluck ( :id )
54+ existing_roles = Role . student . where ( school_id : school . id , user_id : user_ids ) . index_by ( &:user_id )
55+
56+ # Create only the missing roles
57+ user_ids . each do |user_id |
58+ next if existing_roles [ user_id ]
4159
42- responses . each do |student |
43- Role . student . find_or_create_by ( school_id : school . id , user_id : student [ :id ] )
60+ Role . create! ( role : :student , school_id : school . id , user_id : user_id )
4461 end
62+ end
4563
64+ def format_student_responses ( responses )
4665 # Convert hash responses to User objects with separate metadata
4766 # This separates student data from metadata (success, error, created flags)
4867 responses . map do |student_data |
@@ -53,8 +72,6 @@ def create_batch_sso(school, students, token)
5372 created : student_data [ :created ]
5473 }
5574 end
56- rescue ProfileApiClient ::Student422Error => e
57- handle_validations ( e . errors )
5875 end
5976
6077 def handle_validations ( errors )
0 commit comments