I need to get the customers associated with a company. I have the company ID. Is it possible to get the customers of a company?
2 Answers
Load company and use getSuperUserId to get company admin $company->getSuperUserId()
. Or can get company admin using this
Magento\Company\Model\CompanyManagement $companyManagement;
$this->companyManagement->getAdminByCompanyId($companyId);
To get all users it is more complicated.
Magento\Company\Model\Company\Structure $structureManager
$tree = $this->structureManager->getTreeById($companyId);
This will load all tree structure. After that just check which method in $tree to use, there is lots of different data to get and load it.
-
-
1
Here, Is the code working for me. Posting here for helping the community. This code will check if the customer is a company admin and then it will return an array of company users' Ids. In case someone has any query please feel free to add a comment.
use Magento\Company\Api\CompanyHierarchyInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Company\Api\CompanyRepositoryInterface;
use Magento\Company\Api\Data\HierarchyInterface;
class example extends AbstractClass
{
/** @var CompanyHierarchyInterface */
protected $companyHierarchy;
/**
* @var CustomerRepositoryInterface
*/
protected $customerRepository;
/**
* @var CompanyRepositoryInterface
*/
protected $companyRepository;
/**
* @param CompanyHierarchyInterface $companyHierarchy
* @param CustomerRepositoryInterface $customerRepository
* @param CompanyRepositoryInterface $companyRepository
*/
public function __construct(
CompanyHierarchyInterface $companyHierarchy,
CustomerRepositoryInterface $customerRepository,
CompanyRepositoryInterface $companyRepository
)
{
$this->companyHierarchy = $companyHierarchy;
$this->customerRepository = $customerRepository;
$this->companyRepository = $companyRepository;
}
public function getCompanyCustomerIds($customerId)
{
$customerData = $this->customerRepository->getById($customerId);
if($customerData->getExtensionAttributes()){
if ($customerData->getExtensionAttributes()->getCompanyAttributes()
&& $customerData->getExtensionAttributes()->getCompanyAttributes()->getCompanyId() != 0) {
$companyId = $customerData->getExtensionAttributes()->getCompanyAttributes()->getCompanyId();
$companyAdmin = $this->companyRepository->get($companyId)->getSuperUserId();
if($companyAdmin == $customerData->getId()) {
$customerIds = [];
$hierarchy = $this->companyHierarchy->getCompanyHierarchy($companyId);
foreach ($hierarchy as $item) {
if ($item->getEntityType() == HierarchyInterface::TYPE_CUSTOMER) {
$customerIds[] = $item->getEntityId();
}
}
return $customerIds;
}
}
}
return $customerId;
}
}