init
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\OrderCleanup\Cron;
|
||||
|
||||
use Esun\OrderCleanup\Model\Config;
|
||||
use Magento\Framework\Lock\LockManagerInterface;
|
||||
use Magento\Framework\Stdlib\DateTime\DateTime;
|
||||
use Magento\Sales\Api\OrderManagementInterface;
|
||||
use Magento\Sales\Api\OrderRepositoryInterface;
|
||||
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class CancelExpiredPendingOrders
|
||||
{
|
||||
private const LOCK_NAME = 'esun_cancel_expired_pending_orders';
|
||||
private const BATCH_SIZE = 100;
|
||||
private const ORDER_STATUS_PENDING = 'pending';
|
||||
|
||||
/**
|
||||
* @param Config $config
|
||||
* @param CollectionFactory $orderCollectionFactory
|
||||
* @param OrderRepositoryInterface $orderRepository
|
||||
* @param OrderManagementInterface $orderManagement
|
||||
* @param DateTime $dateTime
|
||||
* @param LockManagerInterface $lockManager
|
||||
* @param LoggerInterface $logger
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly CollectionFactory $orderCollectionFactory,
|
||||
private readonly OrderRepositoryInterface $orderRepository,
|
||||
private readonly OrderManagementInterface $orderManagement,
|
||||
private readonly DateTime $dateTime,
|
||||
private readonly LockManagerInterface $lockManager,
|
||||
private readonly LoggerInterface $logger
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel globally configured expired pending orders.
|
||||
*/
|
||||
public function execute(): void
|
||||
{
|
||||
// Read on every run so an Admin configuration change applies to the next cron execution.
|
||||
$lifetimeMinutes = $this->config->getCancellationLifetimeMinutes();
|
||||
if ($lifetimeMinutes === 0 || !$this->lockManager->lock(self::LOCK_NAME, 0)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$expiredAt = $this->dateTime->gmtDate(
|
||||
'Y-m-d H:i:s',
|
||||
$this->dateTime->gmtTimestamp() - ($lifetimeMinutes * 60)
|
||||
);
|
||||
$this->cancelExpiredOrders($expiredAt, $lifetimeMinutes);
|
||||
} finally {
|
||||
$this->lockManager->unlock(self::LOCK_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process candidates in stable ID batches.
|
||||
*
|
||||
* @param string $expiredAt
|
||||
* @param int $lifetimeMinutes
|
||||
*/
|
||||
private function cancelExpiredOrders(string $expiredAt, int $lifetimeMinutes): void
|
||||
{
|
||||
$lastEntityId = 0;
|
||||
$canceledCount = 0;
|
||||
|
||||
do {
|
||||
$collection = $this->orderCollectionFactory->create();
|
||||
$collection->addFieldToSelect('entity_id');
|
||||
$collection->addFieldToFilter('entity_id', ['gt' => $lastEntityId]);
|
||||
$collection->addFieldToFilter('store_id', ['notnull' => true]);
|
||||
$collection->addFieldToFilter('status', self::ORDER_STATUS_PENDING);
|
||||
$collection->addFieldToFilter('created_at', ['lteq' => $expiredAt]);
|
||||
$collection->addFieldToFilter('total_paid', [['null' => true], ['lteq' => 0]]);
|
||||
$collection->setOrder('entity_id', 'asc');
|
||||
$collection->setPageSize(self::BATCH_SIZE);
|
||||
$collection->setCurPage(1);
|
||||
|
||||
$orderIds = array_map('intval', $collection->getColumnValues('entity_id'));
|
||||
foreach ($orderIds as $orderId) {
|
||||
$lastEntityId = $orderId;
|
||||
if ($this->cancelIfStillEligible($orderId)) {
|
||||
++$canceledCount;
|
||||
}
|
||||
}
|
||||
} while (count($orderIds) === self::BATCH_SIZE);
|
||||
|
||||
if ($canceledCount > 0) {
|
||||
$this->logger->info('Expired pending orders were canceled.', [
|
||||
'canceled_count' => $canceledCount,
|
||||
'lifetime_minutes' => $lifetimeMinutes,
|
||||
'expired_at' => $expiredAt,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reload and validate an order immediately before cancellation.
|
||||
*
|
||||
* @param int $orderId
|
||||
*/
|
||||
private function cancelIfStillEligible(int $orderId): bool
|
||||
{
|
||||
try {
|
||||
$order = $this->orderRepository->get($orderId);
|
||||
|
||||
// Recheck mutable conditions after the candidate query to reduce callback/cron races.
|
||||
if ((string)$order->getStatus() !== self::ORDER_STATUS_PENDING
|
||||
|| (float)$order->getTotalPaid() > 0.0
|
||||
|| $order->hasInvoices()
|
||||
|| !$order->canCancel()
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->orderManagement->cancel($orderId);
|
||||
} catch (\Throwable $exception) {
|
||||
$this->logger->error('An expired pending order could not be canceled.', [
|
||||
'order_id' => $orderId,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\OrderCleanup\Model;
|
||||
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
|
||||
class Config
|
||||
{
|
||||
public const XML_PATH_CANCEL_PENDING_AFTER = 'sales/orders/cancel_pending_after';
|
||||
|
||||
/**
|
||||
* @param ScopeConfigInterface $scopeConfig
|
||||
*/
|
||||
public function __construct(private readonly ScopeConfigInterface $scopeConfig)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the global pending-order cancellation lifetime.
|
||||
*/
|
||||
public function getCancellationLifetimeMinutes(): int
|
||||
{
|
||||
return max(
|
||||
0,
|
||||
(int)$this->scopeConfig->getValue(
|
||||
self::XML_PATH_CANCEL_PENDING_AFTER,
|
||||
ScopeConfigInterface::SCOPE_TYPE_DEFAULT
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\OrderCleanup\Test\Unit\Model;
|
||||
|
||||
use Esun\OrderCleanup\Model\Config;
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class ConfigTest extends TestCase
|
||||
{
|
||||
public function testReadsLifetimeFromDefaultScope(): void
|
||||
{
|
||||
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
|
||||
$scopeConfig->expects(self::once())
|
||||
->method('getValue')
|
||||
->with(Config::XML_PATH_CANCEL_PENDING_AFTER, ScopeConfigInterface::SCOPE_TYPE_DEFAULT)
|
||||
->willReturn('45');
|
||||
|
||||
self::assertSame(45, (new Config($scopeConfig))->getCancellationLifetimeMinutes());
|
||||
}
|
||||
|
||||
public function testNegativeLifetimeDisablesCancellation(): void
|
||||
{
|
||||
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
|
||||
$scopeConfig->method('getValue')->willReturn('-10');
|
||||
|
||||
self::assertSame(0, (new Config($scopeConfig))->getCancellationLifetimeMinutes());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
|
||||
<system>
|
||||
<section id="sales">
|
||||
<group id="orders">
|
||||
<field id="cancel_pending_after" translate="label comment" type="text" sortOrder="7"
|
||||
showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Pending Order Cancellation Lifetime (minutes)</label>
|
||||
<comment>Automatically cancels unpaid orders with status Pending after this many minutes. Set to 0 to disable.</comment>
|
||||
<validate>validate-digits validate-zero-or-greater</validate>
|
||||
</field>
|
||||
</group>
|
||||
</section>
|
||||
</system>
|
||||
</config>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
|
||||
<default>
|
||||
<sales>
|
||||
<orders>
|
||||
<cancel_pending_after>0</cancel_pending_after>
|
||||
</orders>
|
||||
</sales>
|
||||
</default>
|
||||
</config>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
|
||||
<group id="default">
|
||||
<job name="esun_cancel_expired_pending_orders"
|
||||
instance="Esun\OrderCleanup\Cron\CancelExpiredPendingOrders"
|
||||
method="execute">
|
||||
<schedule>* * * * *</schedule>
|
||||
</job>
|
||||
</group>
|
||||
</config>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
|
||||
<module name="Esun_OrderCleanup">
|
||||
<sequence>
|
||||
<module name="Magento_Backend"/>
|
||||
<module name="Magento_Config"/>
|
||||
<module name="Magento_Cron"/>
|
||||
<module name="Magento_Sales"/>
|
||||
</sequence>
|
||||
</module>
|
||||
</config>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
use Magento\Framework\Component\ComponentRegistrar;
|
||||
|
||||
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Esun_OrderCleanup', __DIR__);
|
||||
Reference in New Issue
Block a user