def get_users_by_usertype()

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


def get_users_by_usertype(user_type: str, uuid: str):
  """The endpoint returns a list of users for the given user_type which
  are not part of given association group.

  ### Args:
    user_type(str) : user type of user
    association_group_id(str) : association group id

  ### Raises:
      Exception: 500 Internal Server Error if something went wrong

  ### Returns:
      Array of users
  """
  try:
    user_collections = User.collection.filter(
      "user_type", "==", user_type).filter(
      "is_deleted", "==", False).filter(
      "status", "==", "active"
      ).fetch()
    users = [i.get_fields(reformat_datetime=True) for i \
             in user_collections]

    existing_association_group = AssociationGroup.find_by_uuid(
      uuid)
    group_fields = existing_association_group.get_fields()

    existing_users = []

    if group_fields["association_type"] == "learner":
      if user_type == "learner":
        existing_users = [i["user"] for i in group_fields["users"]]
      if user_type == "coach":
        existing_users = [i["coach"] for i in \
                          group_fields["associations"]["coaches"]]
      if user_type == "instructor":
        existing_users = [i["instructor"] for i in \
                          group_fields["associations"]["instructors"]]
    elif group_fields["association_type"] == "discipline":
      if user_type in ["assessor", "instructor"]:
        existing_users = [i["user"] for i in group_fields["users"] if \
                          i["user_type"] == user_type]
    users = [user for user in users if user["user_id"] not in existing_users]

    if user_type == "learner":
      learner_association_groups = AssociationGroup.collection.filter(
        "association_type", "==", "learner").fetch()
      learner_associations = [i.get_fields(reformat_datetime=True) for i \
                              in learner_association_groups]
      existing_learners = []
      for learners in learner_associations:
        if learners["users"] is not None:
          for i in learners["users"]:
            existing_learners.append(i["user"])

      users = [user for user in users if \
               user["user_id"] not in existing_learners]

    return {
      "success": True,
      "message": "Successfully fetched users",
      "data": users
    }
  except ValidationError as e:
    raise BadRequest(str(e)) from e
  except ResourceNotFoundException as e:
    raise ResourceNotFound(str(e)) from e
  except Exception as e:
    raise InternalServerError(str(e)) from e