@@ -176,42 +176,25 @@ def self.extract_date_field(assignment_data, field_name)
176176 end
177177 end
178178
179- # Fetch users for a course from Canvas API
180- # TODO: Replace with call to Canvas Facade
181- def fetch_users_from_canvas ( token , enrollment_type = nil )
182- url = "#{ ENV . fetch ( 'CANVAS_URL' ) } /api/v1/courses/#{ canvas_id } /users"
183- response = Faraday . get ( url ) do |req |
184- req . headers [ 'Authorization' ] = "Bearer #{ token } "
185- req . headers [ 'Content-Type' ] = 'application/json'
186- req . params [ 'enrollment_type' ] = enrollment_type if enrollment_type . present?
187- end
188-
189- if response . success?
190- JSON . parse ( response . body )
191- else
192- Rails . logger . error "Failed to fetch users: #{ response . status } - #{ response . body } "
193- [ ]
194- end
195- end
196-
197179 # Fetch users for a course and create/find their User and UserToCourse records
180+ # TODO: This may need to become a background job
198181 def sync_users_from_canvas ( token , role )
199182 # Fetch all users for the course from Canvas
200- users_data = fetch_users_from_canvas ( token , role )
183+ canvas_users = CanvasFacade . new ( token ) . get_all_course_users ( self , role )
201184
202185 # Extract the Canvas user IDs from the fetched data
203- current_canvas_user_ids = users_data . pluck ( 'id' )
186+ current_canvas_user_ids = canvas_users . pluck ( 'id' )
204187
188+ # Delete UserToCourse records for users no longer in the course
205189 # Find all UserToCourse records for this course and role
206190 existing_user_to_courses = UserToCourse . where ( course_id : id , role : role )
207-
208- # Delete UserToCourse records for users no longer in the course
209- existing_user_to_courses . each do |user_to_course |
210- user_to_course . destroy unless current_canvas_user_ids . include? ( user_to_course . user . canvas_uid )
211- end
191+ user_ids_to_remove = existing_user_to_courses . reject do |utc |
192+ current_canvas_user_ids . include? ( utc . user . canvas_uid )
193+ end . map ( &:id )
194+ UserToCourse . where ( id : user_ids_to_remove ) . destroy_all if user_ids_to_remove . any?
212195
213196 # Create or update User and UserToCourse records for current users
214- users_data . each do |user_data |
197+ canvas_users . each do |user_data |
215198 # this line skips importing a user if the api doesn't return their email
216199 # one case this is happening if the user was invited to the course but hasn't accepted
217200 next if user_data [ 'email' ] . blank?
@@ -230,9 +213,9 @@ def sync_users_from_canvas(token, role)
230213 end
231214
232215 def sync_enrollments_from_canvas ( token )
233- sync_users_from_canvas ( token , 'student' )
234216 sync_users_from_canvas ( token , 'teacher' )
235217 sync_users_from_canvas ( token , 'ta' )
218+ sync_users_from_canvas ( token , 'student' )
236219 end
237220
238221 def regenerate_readonly_api_token_if_blank
0 commit comments