def enroll_student_section()

in microservices/lms/src/routes/student.py [0:0]


def enroll_student_section(section_id: str, input_data: AddStudentModel,
                           request: Request):
  """
  Args:
    input_data(AddStudentModel):
      An AddStudentToSectionModel object which contains email and credentials
  Raises:
    InternalServerError: 500 Internal Server Error if something fails
    ResourceNotFound : 404 if the section or classroom does not exist
    Conflict: 409 if the student already exists
  Returns:
    AddStudentResponseModel: if the student successfully added,
    NotFoundErrorResponseModel: if the section and course not found,
    ConflictResponseModel: if any conflict occurs,
    InternalServerErrorResponseModel: if the add student raises an exception
  """
  cohort_id = None
  try:
    section = Section.find_by_id(section_id)
    headers = {"Authorization": request.headers.get("Authorization")}
    section_service.validate_section(section)
    cohort = section.cohort
    cohort_id = cohort.id
    if cohort.enrolled_students_count >= cohort.max_students:
      raise ValidationError("Cohort Max count reached hence student cannot" +
            "be erolled in this cohort")
    if section.enrolled_students_count >= section.max_students:
      raise ValidationError("Section Max count reached hence student cannot" +
            "be erolled in this cohort")
    sections = Section.collection.filter("cohort", "==", cohort.key).filter(
        "deleted_at_timestamp", "==", None).fetch()
    sections = list(sections)
    if not student_service.check_student_can_enroll_in_cohort(
    email=input_data.email, headers=headers, sections=sections):
      raise Conflict(f"User {input_data.email} is already\
                      registered for cohort {section.cohort.id}")

    Logger.info(f"Section {section.id},\
                enroll student intiated for {input_data.email}")
    user_object = classroom_crud.enroll_student(
        headers=headers,
        access_token=input_data.access_token,
        student_email=input_data.email,
        course_id=section.classroom_id,
        course_code=section.classroom_code)
    latest_section = Section.find_by_id(section.id)
    latest_cohort = latest_section.cohort
    latest_cohort.enrolled_students_count += 1
    latest_cohort.update()
    latest_section.enrolled_students_count += 1
    latest_section.update()
    course_enrollment_mapping = CourseEnrollmentMapping()
    course_enrollment_mapping.section = section
    course_enrollment_mapping.user = User.find_by_user_id(
        user_object["user_id"])
    course_enrollment_mapping.status = "active"
    course_enrollment_mapping.role = "learner"
    course_enrollment_id = course_enrollment_mapping.save().id
    response_dict = {}
    response_dict = {
        "course_enrollment_id": course_enrollment_id,
        "student_email": input_data.email,
        "section_id": section.id,
        "cohort_id": section.cohort.id,
        "classroom_id": section.classroom_id,
        "classroom_url": section.classroom_url
    }
    section_service.insert_section_enrollment_to_bq(
      course_enrollment_mapping, section)
    return {
        "message":
        f"Successfully Added the Student with email {input_data.email}",
        "data": response_dict
    }
  except InvalidTokenError as ive:
    err = traceback.format_exc().replace("\n", " ")
    student_service.insert_failure_log(input_data.email, section_id,
                            cohort_id, err, "InvalidTokenError")
    Logger.error(err)
    raise InvalidToken(str(ive)) from ive
  except ResourceNotFoundException as err:
    er = traceback.format_exc().replace("\n", " ")
    student_service.insert_failure_log(input_data.email, section_id,
                            cohort_id, er, "ResourceNotFound")
    Logger.error(err)
    raise ResourceNotFound(str(err)) from err
  except Conflict as conflict:
    Logger.error(conflict)
    err = traceback.format_exc().replace("\n", " ")
    student_service.insert_failure_log(input_data.email, section_id,
                            cohort_id, err, "Conflict")
    Logger.error(err)
    raise Conflict(str(conflict)) from conflict
  except HttpError as ae:
    err = traceback.format_exc().replace("\n", " ")
    student_service.insert_failure_log(input_data.email, section_id,
                            cohort_id, err, "ClassroomHttpException")
    Logger.error(err)
    # if ae.resp.status == 409:
    #   raise ClassroomHttpException(status_code=ae.resp.status,
    # message="Student already exist in classroom") from ae
    # else :
    raise ClassroomHttpException(status_code=ae.resp.status,
                                 message="Can't enroll student to classroom,\
  Please check organizations policy or authentication scopes") from ae
  except ValidationError as ve:
    err = traceback.format_exc().replace("\n", " ")
    student_service.insert_failure_log(input_data.email, section_id,
                            cohort_id, err, "BadRequest")
    Logger.error(ve)
    raise BadRequest(str(ve)) from ve
  except Exception as e:
    Logger.error(e)
    err = traceback.format_exc().replace("\n", " ")
    student_service.insert_failure_log(input_data.email, section_id,
                            cohort_id, err, "InternalServerError")
    Logger.error(err)
    raise InternalServerError(str(e)) from e