@@ -105,7 +105,9 @@ def create_run_enrollments( # noqa: C901
105105):
106106 """
107107 Creates local records of a user's enrollment in course runs, and attempts to enroll them
108- in edX via API
108+ in edX via API.
109+ Updates the enrollment mode and change_status if the user is already enrolled in the course run
110+ and now is changing the enrollment mode, (e.g. pays or re-enrolls again or getting deferred)
109111
110112 Args:
111113 user (User): The user to enroll
@@ -168,6 +170,7 @@ def _enroll_learner_into_associated_programs():
168170 else :
169171 edx_request_success = True
170172
173+ is_enrollment_downgraded = False
171174 for run in runs :
172175 try :
173176 enrollment , created = CourseRunEnrollment .all_objects .get_or_create (
@@ -189,8 +192,16 @@ def _enroll_learner_into_associated_programs():
189192 enrollment .change_status = change_status
190193 enrollment .save_and_log (None )
191194 # Case (Upgrade): When user was enrolled in free mode and now enrolls in paid mode (e.g. Verified)
195+ # Case (Downgrade): When user was enrolled in paid mode and downgrades to a free mode in case
196+ # of deferral(e.g. Audit)
192197 # So, User has an active enrollment and the only changing thing is going to be enrollment mode
193198 if enrollment .active and enrollment_mode_changed :
199+ if (
200+ mode == EDX_ENROLLMENT_AUDIT_MODE
201+ and enrollment .enrollment_mode == EDX_ENROLLMENT_VERIFIED_MODE
202+ ):
203+ # Downgrade the enrollment
204+ is_enrollment_downgraded = True
194205 enrollment .update_mode_and_save (mode = mode )
195206
196207 elif not enrollment .active :
@@ -207,7 +218,8 @@ def _enroll_learner_into_associated_programs():
207218 )
208219 else :
209220 successful_enrollments .append (enrollment )
210- if enrollment .edx_enrolled :
221+ if enrollment .edx_enrolled and not is_enrollment_downgraded :
222+ # Do not send enrollment email if the user was downgraded.
211223 mail_api .send_course_run_enrollment_email (enrollment )
212224 return successful_enrollments , edx_request_success
213225
0 commit comments