Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NTR: expire order task #814

Merged
merged 2 commits into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@
<argument type="service" id="Kiener\MolliePayments\Service\Transition\OrderTransitionService"/>
</service>

<service id="Kiener\MolliePayments\Service\Order\OrderExpireService">
<argument type="service" id="Kiener\MolliePayments\Service\Order\OrderStatusUpdater"/>
<argument type="service" id="Kiener\MolliePayments\Service\Order\OrderTimeService"/>
<argument type="service" id="Kiener\MolliePayments\Service\SettingsService"/>
<argument type="service" id="mollie_payments.logger"/>
</service>


<service id="kiener.mollie_payments.http.client.factory" class="Kiener\MolliePayments\Service\HttpClient\PluginHttpClientFactory"/>

Expand Down
15 changes: 15 additions & 0 deletions src/Resources/config/services/scheduled_tasks.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,20 @@
<tag name="messenger.message_handler"/>
</service>


<service id="Kiener\MolliePayments\ScheduledTask\OrderStatus\ExpireOrderTask">
<tag name="shopware.scheduled.task"/>
</service>

<service id="Kiener\MolliePayments\ScheduledTask\OrderStatus\ExpireOrderTaskHandler">
<argument type="service" id="Kiener\MolliePayments\Repository\ScheduledTask\ScheduledTaskRepository"/>
<argument type="service" id="Kiener\MolliePayments\Repository\Order\OrderRepository"/>
<argument type="service" id="Kiener\MolliePayments\Service\Order\OrderExpireService"/>
<argument type="service" id="mollie_payments.logger"/>
<tag name="messenger.message_handler"/>
</service>



</services>
</container>
4 changes: 1 addition & 3 deletions src/Resources/config/services/subscriber.xml
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,7 @@
</service>

<service id="Kiener\MolliePayments\Subscriber\OrderEditSubscriber">
<argument type="service" id="Kiener\MolliePayments\Service\Order\OrderStatusUpdater"/>
<argument type="service" id="Kiener\MolliePayments\Service\Order\OrderTimeService"/>
<argument type="service" id="Kiener\MolliePayments\Service\SettingsService"/>
<argument type="service" id="Kiener\MolliePayments\Service\Order\OrderExpireService"/>
<tag name="kernel.event_subscriber" />
</service>

Expand Down
19 changes: 19 additions & 0 deletions src/ScheduledTask/OrderStatus/ExpireOrderTask.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);

namespace Kiener\MolliePayments\ScheduledTask\OrderStatus;

use Shopware\Core\Framework\MessageQueue\ScheduledTask\ScheduledTask;

class ExpireOrderTask extends ScheduledTask
{
public static function getTaskName(): string
{
return 'mollie.order_status.expire';
}

public static function getDefaultInterval(): int
{
return 60;
}
}
72 changes: 72 additions & 0 deletions src/ScheduledTask/OrderStatus/ExpireOrderTaskHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);

namespace Kiener\MolliePayments\ScheduledTask\OrderStatus;

use Kiener\MolliePayments\Repository\Order\OrderRepositoryInterface;
use Kiener\MolliePayments\Repository\ScheduledTask\ScheduledTaskRepositoryInterface;
use Kiener\MolliePayments\Service\Order\OrderExpireService;
use Psr\Log\LoggerInterface;
use Shopware\Core\Checkout\Order\OrderCollection;
use Shopware\Core\Checkout\Order\OrderStates;
use Shopware\Core\Framework\Api\Context\SystemSource;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\MessageQueue\ScheduledTask\ScheduledTaskHandler;

#[\Symfony\Component\Messenger\Attribute\AsMessageHandler(handles: ExpireOrderTask::class)]
class ExpireOrderTaskHandler extends ScheduledTaskHandler
{
private LoggerInterface $logger;
private OrderRepositoryInterface $orderRepository;
private OrderExpireService $orderExpireService;

public function __construct(ScheduledTaskRepositoryInterface $scheduledTaskRepository, OrderRepositoryInterface $orderRepository, OrderExpireService $orderExpireService, LoggerInterface $logger)
{
/** @phpstan-ignore-next-line */
parent::__construct($scheduledTaskRepository->getRepository(), $logger);
$this->logger = $logger;
$this->orderRepository = $orderRepository;
$this->orderExpireService = $orderExpireService;
}

public function run(): void
{
$this->logger->info('Start resetting in_progress orders');

$context = new Context(new SystemSource());

$criteria = new Criteria();
$criteria->addAssociation('transactions.stateMachineState');
$criteria->getAssociation('transactions.stateMachineState')->addFilter(new EqualsFilter('technicalName', OrderStates::STATE_IN_PROGRESS));

$this->logger->debug('Search for orders which are in progress state');

$searchResult = $this->orderRepository->search($criteria, $context);
if ($searchResult->count() === 0) {
$this->logger->debug('No in progress orders found');
return;
}

$this->logger->info('Found orders which are in progress', ['foundOrders' => $searchResult->count()]);

/**
* @var OrderCollection $orders
*/
$orders = $searchResult->getEntities();
$resetted = $this->orderExpireService->cancelExpiredOrders($orders, $context);

$this->logger->info('Rested expired orders', ['restedOrders' => $resetted]);
}

/**
* @return iterable<mixed>
*/
public static function getHandledMessages(): iterable
{
return [
ExpireOrderTask::class
];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\MessageQueue\ScheduledTask\ScheduledTaskHandler;

#[\Symfony\Component\Messenger\Attribute\AsMessageHandler(handles: RenewalReminderTask::class)]
#[\Symfony\Component\Messenger\Attribute\AsMessageHandler(handles: RenewalReminderTaskDev::class)]
class RenewalReminderTaskHandler extends ScheduledTaskHandler
{
/**
Expand All @@ -28,7 +30,8 @@ class RenewalReminderTaskHandler extends ScheduledTaskHandler
*/
public function __construct(ScheduledTaskRepositoryInterface $scheduledTaskRepository, SubscriptionManager $subscriptionManager, LoggerInterface $logger)
{
parent::__construct($scheduledTaskRepository->getRepository());
/** @phpstan-ignore-next-line */
parent::__construct($scheduledTaskRepository->getRepository(), $logger);

$this->subscriptionManager = $subscriptionManager;
$this->logger = $logger;
Expand Down
144 changes: 144 additions & 0 deletions src/Service/Order/OrderExpireService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
<?php
declare(strict_types=1);

namespace Kiener\MolliePayments\Service\Order;

use Kiener\MolliePayments\Handler\Method\BankTransferPayment;
use Kiener\MolliePayments\Service\Mollie\MolliePaymentStatus;
use Kiener\MolliePayments\Service\SettingsService;
use Kiener\MolliePayments\Struct\Order\OrderAttributes;
use Psr\Log\LoggerInterface;
use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity;
use Shopware\Core\Checkout\Order\OrderCollection;
use Shopware\Core\Checkout\Order\OrderEntity;
use Shopware\Core\Checkout\Order\OrderStates;
use Shopware\Core\Framework\Context;

class OrderExpireService
{

/**
* @var OrderStatusUpdater
*/
private $orderStatusUpdater;

/**
* @var OrderTimeService
*/
private $orderTimeService;

/**
* @var SettingsService
*/
private $settingsService;

/**
* @var LoggerInterface
*/
private $logger;

public function __construct(
OrderStatusUpdater $orderStatusUpdater,
OrderTimeService $orderTimeService,
SettingsService $settingsService,
LoggerInterface $logger
) {
$this->orderStatusUpdater = $orderStatusUpdater;
$this->orderTimeService = $orderTimeService;
$this->settingsService = $settingsService;
$this->logger = $logger;
}

/**
* If an order is "in progress" but the payment link is already expired, the order is changed to cannceled
* @param OrderCollection $orders
* @param Context $context
* @return int
*/
public function cancelExpiredOrders(OrderCollection $orders, Context $context): int
{
$resetted = 0;
/** @var OrderEntity $order */
foreach ($orders as $order) {
if (! $order instanceof OrderEntity) {
continue;
}

$orderAttributes = new OrderAttributes($order);

if (strlen($orderAttributes->getMollieOrderId()) === 0) {
continue;
}

$transactions = $order->getTransactions();

if ($transactions === null || $transactions->count() === 0) {
continue;
}

$transactions->sort(function (OrderTransactionEntity $a, OrderTransactionEntity $b) {
return $a->getCreatedAt() <=> $b->getCreatedAt();
});

/** @var OrderTransactionEntity $lastTransaction */
$lastTransaction = $transactions->last();

$stateMachineState = $lastTransaction->getStateMachineState();
if ($stateMachineState === null) {
continue;
}

$lastStatus = $stateMachineState->getTechnicalName();

// disregard any orders that are not in progress
if ($lastStatus !== OrderStates::STATE_IN_PROGRESS) {
continue;
}

$settings = $this->settingsService->getSettings();
$finalizeTransactionTimeInMinutes = $settings->getPaymentFinalizeTransactionTime();

if ($this->orderUsesSepaPayment($lastTransaction)) {
$finalizeTransactionTimeInMinutes = (int)ceil($settings->getPaymentMethodBankTransferDueDateDays() / 24 / 60);
}

if ($this->orderTimeService->isOrderAgeGreaterThan($order, $finalizeTransactionTimeInMinutes) === false) {
continue;
}

// orderStatusUpdater needs the order to be set on the transaction
$lastTransaction->setOrder($order);

// this forces the order to be open again
$context->addState(OrderStatusUpdater::ORDER_STATE_FORCE_OPEN);

try {
$this->orderStatusUpdater->updatePaymentStatus($lastTransaction, MolliePaymentStatus::MOLLIE_PAYMENT_CANCELED, $context);
$resetted++;
} catch (\Exception $exception) {
$this->logger->error('Failed to update payment status for transaction', [
'transaction' => $lastTransaction->getId(),
'order' => $order->getOrderNumber()
]);
}
}

return $resetted;
}

/**
* @param OrderTransactionEntity $transaction
* @return bool
* @todo refactor once php8.0 is minimum version. Use Null-safe operator
*/
private function orderUsesSepaPayment(OrderTransactionEntity $transaction): bool
{
$paymentMethod = $transaction->getPaymentMethod();

if ($paymentMethod === null) {
return false;
}

return $paymentMethod->getHandlerIdentifier() === BankTransferPayment::class;
}
}
Loading
Loading