def add_instructors()

in microservices/user_management/src/routes/learner_association_group.py [0:0]


def add_instructors(uuid: str,
                    input_data: AddInstructorToLearnerAssociationGroup) -> dict:
  """
  Endpoint to add instructor to learner association group

  Parameters
  ----------
  uuid: str
  input_data: PydanticModel

  Returns
  -------
  AddInstructorToLearnerAssociationGroupResponseModel: dict

  Raise:
  -----
  404: raise Resource Not Found Error
  400: raise Bad Request Error
  500: raise Internal Server Error
  """
  try:
    data = {**input_data.dict()}
    association_group = AssociationGroup.find_by_uuid(uuid=uuid)
    group_fields = association_group.get_fields(reformat_datetime=True)


    # validating given UUID is learner type
    if not is_learner_association_group(
      association_group_fields=group_fields):
      raise ValidationError(f"AssociationGroup for given uuid: {uuid} "
                            "is not learner type")

    if len(data["instructors"]) > 1:
      raise ValidationError("Only one instructor can be assigned to a "
                            "discipline/curriculum pathway in a learner "
                            "association group")

    # adding the validation for the instructor discipline
    disciplines = []
    disciplines = get_all_discipline_for_given_program(
      association_group.associations["curriculum_pathway_id"],disciplines)

    if data["curriculum_pathway_id"] not in disciplines:
      discipline_id = data["curriculum_pathway_id"]
      program_id = association_group.associations["curriculum_pathway_id"]
      raise ValidationError(f"The given curriculum_pathway_id {discipline_id} "\
                            f"doesn't belong to the program {program_id} "\
                              "tagged to the learner association group")

    user_group = UserGroup.find_by_name("instructor")

    for input_instructor in data["instructors"]:
      user = User.find_by_user_id(input_instructor)

      instructor_fields = user.get_fields(reformat_datetime=True)

      if user_group.uuid not in instructor_fields["user_groups"]:
        raise ValidationError(f"User for given user_id {input_instructor} "
                              "is not of instructor type")

    # validating the curriculum pathway id
    CurriculumPathway.find_by_uuid(uuid=data["curriculum_pathway_id"])

    instructor_list = [{"instructor": i, "curriculum_pathway_id": data[
      "curriculum_pathway_id"], "status": data["status"]} for i in data[
      "instructors"]]
    # The condition is true when the instructor list is not empty
    if "instructors" in association_group.associations.keys():

      # Finding index of the existing curriculum pathway instructor
      instructors = [i for i, _ in enumerate(association_group.associations[
                    "instructors"]) if _["curriculum_pathway_id"] ==
                     data["curriculum_pathway_id"]]

      # condition true when the index is found
      if instructors:
        raise ValidationError("Only one instructor can be associated with "
                              "the Learner Association Group")
      else:
        association_group.associations["instructors"].extend(instructor_list)
    else:
      association_group.associations["instructors"] = instructor_list

    # Logic to check if given instructors are actively associated to the
    # curriculum_pathway in Discipline Association Groups

    # Fetch all discipline association groups
    discipline_groups = AssociationGroup.collection.filter(
                  "association_type", "==", "discipline").fetch()
    discipline_group_fields = [i.get_fields() for i in \
                               discipline_groups]

    # Identify instructors given in request body that are not associated to
    # given curriculum_pathway_id in Discipline Association Groups
    non_associated_instructors = []
    for instructor_dict in instructor_list:
      if not check_instructor_discipline_association(
                                              instructor_dict["instructor"],
                                              data["curriculum_pathway_id"],
                                              discipline_group_fields):
        non_associated_instructors.append(instructor_dict["instructor"])

    if non_associated_instructors:
      curriculum_pathway_id = data["curriculum_pathway_id"]
      raise ValidationError("Instructors for given instructor_ids " +
        f"{non_associated_instructors} are not actively associated with the " +
        f"given curriculum_pathway_id {curriculum_pathway_id} in " +
        "discipline association group")

    association_group.update()
    group_fields = association_group.get_fields(reformat_datetime=True)

    Logger.info(f"Successfully the list of instructors {data['instructors']} "
                f"are added in the Learning Association Group")
    return {
      "success": True,
      "message": "Successfully added the instructors to the learner "
                 "association group",
      "data": group_fields
    }

  except ResourceNotFoundException as e:
    Logger.error(f"Add Instructor Resource Not Found Error Occurred: {e}")
    Logger.error(print_exc())
    raise ResourceNotFound(str(e)) from e
  except ValidationError as e:
    Logger.error(f"Add Instructor Validation Error Occurred: {e}")
    Logger.error(print_exc())
    raise BadRequest(str(e)) from e
  except InternalServerError as e:
    Logger.error(f"Add Instructor Internal Server Error Occurred: {e}")
    Logger.error(print_exc())
    raise InternalServerError(str(e)) from e