63 lines
2.5 KiB
PHP
63 lines
2.5 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Esun\Customer\Controller\Order;
|
|
|
|
use Magento\Customer\Controller\AbstractAccount;
|
|
use Magento\Customer\Model\Session as CustomerSession;
|
|
use Magento\Framework\App\Action\Context;
|
|
use Magento\Framework\App\Action\HttpPostActionInterface;
|
|
use Magento\Framework\Controller\Result\Redirect;
|
|
use Magento\Framework\Exception\LocalizedException;
|
|
use Magento\Sales\Api\OrderManagementInterface;
|
|
use Magento\Sales\Api\OrderRepositoryInterface;
|
|
use Psr\Log\LoggerInterface;
|
|
|
|
class Cancel extends AbstractAccount implements HttpPostActionInterface
|
|
{
|
|
public function __construct(
|
|
Context $context,
|
|
private readonly CustomerSession $customerSession,
|
|
private readonly OrderRepositoryInterface $orderRepository,
|
|
private readonly OrderManagementInterface $orderManagement,
|
|
private readonly LoggerInterface $logger
|
|
) {
|
|
parent::__construct($context);
|
|
}
|
|
|
|
public function execute(): Redirect
|
|
{
|
|
/** @var Redirect $result */
|
|
$result = $this->resultRedirectFactory->create();
|
|
$orderId = (int)$this->getRequest()->getParam('order_id');
|
|
|
|
try {
|
|
$order = $this->orderRepository->get($orderId);
|
|
if ((int)$order->getCustomerId() !== (int)$this->customerSession->getCustomerId()) {
|
|
throw new LocalizedException(__('The requested order is not available.'));
|
|
}
|
|
if ((string)$order->getStatus() !== 'pending' || !$order->canCancel()) {
|
|
throw new LocalizedException(__('This order can no longer be canceled.'));
|
|
}
|
|
if (!$this->orderManagement->cancel($orderId)) {
|
|
throw new LocalizedException(__('The order could not be canceled.'));
|
|
}
|
|
|
|
$this->messageManager->addSuccessMessage(__('The order has been canceled.'));
|
|
} catch (LocalizedException $exception) {
|
|
$this->messageManager->addErrorMessage($exception->getMessage());
|
|
} catch (\Throwable $exception) {
|
|
$this->logger->error('Customer order cancellation failed', [
|
|
'order_id' => $orderId,
|
|
'customer_id' => (int)$this->customerSession->getCustomerId(),
|
|
'exception' => $exception,
|
|
]);
|
|
$this->messageManager->addErrorMessage(
|
|
__('The order could not be canceled. Please contact customer service.')
|
|
);
|
|
}
|
|
|
|
return $result->setPath('sales/order/history', ['status' => 'pending']);
|
|
}
|
|
}
|