88 lines
3.1 KiB
PHP
88 lines
3.1 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Esun\LegacyOrder\Controller\Adminhtml\Order;
|
|
|
|
use Esun\LegacyOrder\Model\ResourceModel\Order\CollectionFactory;
|
|
use Magento\Backend\App\Action;
|
|
use Magento\Framework\App\Action\HttpPostActionInterface;
|
|
use Magento\Framework\App\ResourceConnection;
|
|
use Magento\Framework\Controller\ResultFactory;
|
|
use Magento\Ui\Component\MassAction\Filter;
|
|
|
|
class MassLink extends Action implements HttpPostActionInterface
|
|
{
|
|
public const ADMIN_RESOURCE = 'Esun_LegacyOrder::orders';
|
|
|
|
public function __construct(
|
|
Action\Context $context,
|
|
private readonly Filter $filter,
|
|
private readonly CollectionFactory $collectionFactory,
|
|
private readonly ResourceConnection $resource
|
|
) {
|
|
parent::__construct($context);
|
|
}
|
|
|
|
public function execute()
|
|
{
|
|
$query = trim((string)$this->getRequest()->getParam('customer'));
|
|
if ($query === '') {
|
|
$this->messageManager->addErrorMessage(__('Enter a customer ID or email.'));
|
|
return $this->redirectToGrid();
|
|
}
|
|
|
|
try {
|
|
$collection = $this->filter->getCollection($this->collectionFactory->create());
|
|
$connection = $this->resource->getConnection();
|
|
$ordersTable = $this->resource->getTableName('esun_legacy_order');
|
|
$customersTable = $this->resource->getTableName('customer_entity');
|
|
$linked = 0;
|
|
$skipped = 0;
|
|
|
|
foreach ($collection as $order) {
|
|
$select = $connection->select()
|
|
->from($customersTable, ['entity_id', 'email'])
|
|
->where('website_id = ?', (int)$order->getData('website_id'));
|
|
|
|
if (ctype_digit($query)) {
|
|
$select->where('entity_id = ?', (int)$query);
|
|
} else {
|
|
$select->where('LOWER(TRIM(email)) = ?', strtolower($query));
|
|
}
|
|
|
|
$customers = $connection->fetchAll($select);
|
|
if (count($customers) !== 1) {
|
|
$skipped++;
|
|
continue;
|
|
}
|
|
|
|
$connection->update(
|
|
$ordersTable,
|
|
['customer_id' => (int)$customers[0]['entity_id'], 'link_status' => 'linked'],
|
|
['legacy_order_id = ?' => (int)$order->getId()]
|
|
);
|
|
$linked++;
|
|
}
|
|
|
|
if ($linked > 0) {
|
|
$this->messageManager->addSuccessMessage(__('%1 legacy order(s) were linked.', $linked));
|
|
}
|
|
if ($skipped > 0) {
|
|
$this->messageManager->addWarningMessage(
|
|
__('%1 order(s) were skipped because the customer did not uniquely match the order website.', $skipped)
|
|
);
|
|
}
|
|
} catch (\Throwable $exception) {
|
|
$this->messageManager->addErrorMessage($exception->getMessage());
|
|
}
|
|
|
|
return $this->redirectToGrid();
|
|
}
|
|
|
|
private function redirectToGrid()
|
|
{
|
|
return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)
|
|
->setPath('*/*/index');
|
|
}
|
|
}
|