// GetSubOrganizations returns all organizations which have {globalID} as parent (including the organization with {globalID} as globalid)
// TODO: validate globalID since it is appended in the query
508548
func (m *Manager) GetSubOrganizations(globalID string) ([]Organization, error) {
	var organizations = make([]Organization, 0, 0)
	var qry = bson.M{"globalid": bson.M{"$regex": bson.RegEx{"^" + globalID + `\.`, ""}}}
	if err := m.collection.Find(qry).All(&organizations); err != nil {
		return nil, err
	}

	return organizations, nil
}
312634
func (api OrganizationsAPI) AddIncludeSubOrgsOf(w http.ResponseWriter, r *http.Request) {
	globalID := mux.Vars(r)["globalid"]

	includeSubOrgOf := struct {
		GlobalID string
	}{}

	if err := json.NewDecoder(r.Body).Decode(&includeSubOrgOf); err != nil {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	orgMgr := organization.NewManager(r)
	org, err := orgMgr.GetByName(globalID)
	if err != nil {
		if err == mgo.ErrNotFound {
			writeErrorResponse(w, http.StatusNotFound, "organization_not_found")
		} else {
			handleServerError(w, "getting organization", err)
		}
		return
	}

	if !orgMgr.Exists(includeSubOrgOf.GlobalID) {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	// check if the organization to add is already in the list
	for _, orgMembers := range org.IncludeSubOrgsOf {
		if orgMembers == includeSubOrgOf.GlobalID {
			http.Error(w, http.StatusText(http.StatusConflict), http.StatusConflict)
			return
		}
	}

	// add the organization to the list
	err = orgMgr.AddIncludeSubOrgOf(org.Globalid, includeSubOrgOf.GlobalID)
	if handleServerError(w, "adding organization to 'includesuborgsof' list", err) {
		return
	}

	org, err = orgMgr.GetByName(globalID)
	if handleServerError(w, "getting organization", err) {
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(org)
}
1316972
func (s *Service) FindOrganizationByName(ctx context.Context, n string) (*influxdb.Organization, error) {
	span, ctx := tracing.StartSpanFromContext(ctx)
	defer span.Finish()

	var o *influxdb.Organization

	err := s.kv.View(ctx, func(tx Tx) error {
		org, err := s.findOrganizationByName(ctx, tx, n)
		if err != nil {
			return err
		}
		o = org
		return nil
	})

	return o, err
}
323358
func (actor Actor) GetOrganizations() ([]Organization, Warnings, error) {
	var returnedOrgs []Organization
	orgs, warnings, err := actor.CloudControllerClient.GetOrganizations()
	for _, org := range orgs {
		returnedOrgs = append(returnedOrgs, Organization(org))
	}
	return returnedOrgs, Warnings(warnings), err
}
939049
func (m *Manager) CountByOrganization(organization string) (int, error) {
	qry := bson.M{"orgowners": organization}
	return m.collection.Find(qry).Count()
}
1265917
func NewOrganizations(dir string, logger chronograf.Logger) chronograf.OrganizationsStore {
	return &Organizations{
		Dir:     dir,
		Load:    load,
		ReadDir: ioutil.ReadDir,
		Logger:  logger,
	}
}
520978
func (actor Actor) GetOrganizationDomains(orgGUID string) ([]Domain, Warnings, error) {
	var (
		allWarnings Warnings
		allDomains  []Domain
	)

	domains, warnings, err := actor.CloudControllerClient.GetSharedDomains()
	allWarnings = append(allWarnings, warnings...)

	if err != nil {
		return []Domain{}, allWarnings, err
	}
	for _, domain := range domains {
		allDomains = append(allDomains, Domain(domain))
	}

	domains, warnings, err = actor.CloudControllerClient.GetOrganizationPrivateDomains(orgGUID)
	allWarnings = append(allWarnings, warnings...)

	if err != nil {
		return []Domain{}, allWarnings, err
	}
	for _, domain := range domains {
		allDomains = append(allDomains, Domain(domain))
	}

	return allDomains, allWarnings, nil
}
85651
func (s *OrganizationService) FindOrganizations(ctx context.Context, filter platform.OrganizationFilter, opt ...platform.FindOptions) ([]*platform.Organization, int, error) {
	url, err := newURL(s.Addr, organizationPath)
	if err != nil {
		return nil, 0, err
	}
	qp := url.Query()

	if filter.Name != nil {
		qp.Add("name", *filter.Name)
	}
	if filter.ID != nil {
		qp.Add("id", filter.ID.String())
	}
	url.RawQuery = qp.Encode()

	req, err := http.NewRequest("GET", url.String(), nil)
	if err != nil {
		return nil, 0, err
	}

	SetToken(s.Token, req)
	hc := newClient(url.Scheme, s.InsecureSkipVerify)

	resp, err := hc.Do(req)
	if err != nil {
		return nil, 0, err
	}

	if err := CheckError(resp, true); err != nil {
		return nil, 0, err
	}

	var os orgsResponse
	if err := json.NewDecoder(resp.Body).Decode(&os); err != nil {
		return nil, 0, err
	}

	orgs := os.ToPlatform()
	return orgs, len(orgs), nil

}
963255
func (m *Manager) AddIncludeSubOrgOf(globalId, orgMemberId string) error {
	return m.collection.Update(
		bson.M{"globalid": globalId},
		bson.M{"$addToSet": bson.M{"includesuborgsof": orgMemberId}})
}
789837
func (u *User) GetOwnedOrganizations() (err error) {
	u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
	return err
}
862937
func (m *Manager) AllByOrgs(globalIDs []string) ([]Organization, error) {
	var organizations []Organization

	condition := []interface{}{
		bson.M{"orgmembers": bson.M{"$in": globalIDs}},
		bson.M{"orgowners": bson.M{"$in": globalIDs}},
	}

	err := m.collection.Find(bson.M{"$or": condition}).All(&organizations)

	return organizations, err
}
963218
func (api OrganizationsAPI) DeleteOrganizationDns(w http.ResponseWriter, r *http.Request) {
	globalid := mux.Vars(r)["globalid"]
	dnsName := mux.Vars(r)["dnsname"]

	orgMgr := organization.NewManager(r)
	organisation, err := orgMgr.GetByName(globalid)
	if err != nil {
		if err == mgo.ErrNotFound {
			http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		} else {
			handleServerError(w, "getting organization", err)
		}
		return
	}
	sort.Strings(organisation.DNS)
	if sort.SearchStrings(organisation.DNS, dnsName) == len(organisation.DNS) {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	err = orgMgr.RemoveDNS(organisation, dnsName)

	if err != nil {
		log.Error("Error removing DNS name", err.Error())
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")

	w.WriteHeader(http.StatusNoContent)
}
1292427
func (s *Service) OrganizationAddOnListForOrganization(ctx context.Context, organizationIdentity string, lr *ListRange) (OrganizationAddOnListForOrganizationResult, error) {
	var organizationAddOn OrganizationAddOnListForOrganizationResult
	return organizationAddOn, s.Get(ctx, &organizationAddOn, fmt.Sprintf("/organizations/%v/addons", organizationIdentity), nil, lr)
}
256772
func (client *Client) GetOrganizationDefaultIsolationSegment(orgGUID string) (Relationship, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetOrganizationRelationshipDefaultIsolationSegmentRequest,
		URIParams:   internal.Params{"organization_guid": orgGUID},
	})
	if err != nil {
		return Relationship{}, nil, err
	}

	var relationship Relationship
	response := cloudcontroller.Response{
		DecodeJSONResponseInto: &relationship,
	}

	err = client.connection.Make(request, &response)
	return relationship, response.Warnings, err
}
325541
func (api OrganizationsAPI) GetOrganizationLogo(w http.ResponseWriter, r *http.Request) {
	globalid := mux.Vars(r)["globalid"]
	logoMgr := organization.NewLogoManager(r)

	logo, err := logoMgr.GetLogo(globalid)

	if err != nil && err != mgo.ErrNotFound {
		log.Error("Error getting logo", err.Error())
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	response := struct {
		Logo string `json:"logo"`
	}{
		Logo: logo,
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
}
1591
func (o *InvitationManager) CountByOrganization(globalid string) (int, error) {
	count, err := o.collection.Find(bson.M{"organization": globalid}).Count()
	return count, err
}
739271
func (api OrganizationsAPI) GetOrganizationTree(w http.ResponseWriter, r *http.Request) {
	var requestedOrganization = mux.Vars(r)["globalid"]
	//TODO: validate input
	parentGlobalID := ""
	var parentGlobalIDs = make([]string, 0, 1)
	for _, localParentID := range strings.Split(requestedOrganization, ".") {
		if parentGlobalID == "" {
			parentGlobalID = localParentID
		} else {
			parentGlobalID = parentGlobalID + "." + localParentID
		}

		parentGlobalIDs = append(parentGlobalIDs, parentGlobalID)
	}

	orgMgr := organization.NewManager(r)

	parentOrganizations, err := orgMgr.GetOrganizations(parentGlobalIDs)

	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	suborganizations, err := orgMgr.GetSubOrganizations(requestedOrganization)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	allOrganizations := append(parentOrganizations, suborganizations...)

	sort.Sort(byGlobalID(allOrganizations))

	//Build a treestructure
	var orgTree *OrganizationTreeItem
	orgTreeIndex := make(map[string]*OrganizationTreeItem)
	for _, org := range allOrganizations {
		newTreeItem := &OrganizationTreeItem{GlobalID: org.Globalid, Children: make([]*OrganizationTreeItem, 0, 0)}
		orgTreeIndex[org.Globalid] = newTreeItem
		if orgTree == nil {
			orgTree = newTreeItem
		} else {
			path := strings.Split(org.Globalid, ".")
			localName := path[len(path)-1]
			parentTreeItem := orgTreeIndex[strings.TrimSuffix(org.Globalid, "."+localName)]
			parentTreeItem.Children = append(parentTreeItem.Children, newTreeItem)
		}
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(orgTree)
}