75 lines
2.8 KiB
PHP
75 lines
2.8 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Esun\CustomerCoupon\Controller\Adminhtml\Customer;
|
|
|
|
use Magento\Backend\App\Action;
|
|
use Magento\Backend\App\Action\Context;
|
|
use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory;
|
|
use Magento\Framework\Controller\Result\Json;
|
|
use Magento\Framework\Controller\Result\JsonFactory;
|
|
use Magento\SalesRule\Model\RuleFactory;
|
|
|
|
class Search extends Action
|
|
{
|
|
public const ADMIN_RESOURCE = 'Magento_SalesRule::quote';
|
|
|
|
public function __construct(
|
|
Context $context,
|
|
private readonly JsonFactory $jsonFactory,
|
|
private readonly CollectionFactory $customerCollectionFactory,
|
|
private readonly RuleFactory $ruleFactory
|
|
) {
|
|
parent::__construct($context);
|
|
}
|
|
|
|
public function execute(): Json
|
|
{
|
|
$searchKey = trim((string)$this->getRequest()->getParam('searchKey', ''));
|
|
$page = max(1, (int)$this->getRequest()->getParam('page', 1));
|
|
$limit = min(50, max(1, (int)$this->getRequest()->getParam('limit', 20)));
|
|
$ruleId = (int)$this->getRequest()->getParam('rule_id');
|
|
|
|
$collection = $this->customerCollectionFactory->create();
|
|
$collection->addAttributeToSelect(['firstname', 'lastname', 'email']);
|
|
|
|
if ($ruleId) {
|
|
$rule = $this->ruleFactory->create()->load($ruleId);
|
|
if ($rule->getId()) {
|
|
$collection->addFieldToFilter('website_id', ['in' => array_map('intval', $rule->getWebsiteIds())]);
|
|
$collection->addFieldToFilter('group_id', ['in' => array_map('intval', $rule->getCustomerGroupIds())]);
|
|
}
|
|
}
|
|
|
|
if ($searchKey !== '') {
|
|
$like = '%' . addcslashes($searchKey, '%_') . '%';
|
|
$conditions = [
|
|
['attribute' => 'email', 'like' => $like],
|
|
['attribute' => 'firstname', 'like' => $like],
|
|
['attribute' => 'lastname', 'like' => $like],
|
|
];
|
|
if (ctype_digit($searchKey)) {
|
|
$conditions[] = ['attribute' => 'entity_id', 'eq' => (int)$searchKey];
|
|
}
|
|
$collection->addAttributeToFilter($conditions, null, 'left');
|
|
}
|
|
|
|
$collection->setOrder('entity_id', 'DESC')->setPageSize($limit)->setCurPage($page);
|
|
$options = [];
|
|
foreach ($collection as $customer) {
|
|
$name = trim((string)$customer->getFirstname() . ' ' . (string)$customer->getLastname());
|
|
$options[] = [
|
|
'value' => (int)$customer->getId(),
|
|
'label' => sprintf('%s <%s> (#%d)', $name ?: __('Customer'), $customer->getEmail(), $customer->getId()),
|
|
'path' => '',
|
|
'level' => 0,
|
|
];
|
|
}
|
|
|
|
return $this->jsonFactory->create()->setData([
|
|
'options' => $options,
|
|
'total' => (int)$collection->getSize(),
|
|
]);
|
|
}
|
|
}
|