diff --git a/Classes/Controller/Order/PaymentController.php b/Classes/Controller/Order/PaymentController.php index 933fe67..8536329 100644 --- a/Classes/Controller/Order/PaymentController.php +++ b/Classes/Controller/Order/PaymentController.php @@ -14,6 +14,7 @@ use Exception; use Extcode\Cart\Domain\Model\Cart; use Extcode\Cart\Domain\Model\Order\Item; +use Extcode\Cart\Domain\Model\Order\Payment; use Extcode\Cart\Domain\Repository\CartRepository; use Extcode\Cart\Domain\Repository\Order\ItemRepository as OrderItemRepository; use Extcode\Cart\Domain\Repository\Order\PaymentRepository; @@ -24,6 +25,9 @@ use girosolution\GiroCheckout_SDK\GiroCheckout_SDK_Notify; use InvalidArgumentException; use Psr\Http\Message\ResponseInterface; +use Psr\Log\LoggerInterface; +use TYPO3\CMS\Core\Database\Connection; +use TYPO3\CMS\Core\Database\ConnectionPool; use TYPO3\CMS\Core\Messaging\FlashMessage; use TYPO3\CMS\Core\Messaging\FlashMessageService; use TYPO3\CMS\Core\Type\ContextualFeedbackSeverity; @@ -35,6 +39,8 @@ class PaymentController extends ActionController { + private const PAYMENT_TABLE = 'tx_cart_domain_model_order_payment'; + protected ?Cart $cart = null; protected array $cartPluginSettings; @@ -50,6 +56,8 @@ public function __construct( private readonly OrderItemRepository $orderItemRepository, private readonly PaymentRepository $paymentRepository, public readonly CredentialLoaderRegistry $credentialLoaderRegistry, + private readonly ConnectionPool $connectionPool, + private readonly LoggerInterface $logger, ) {} protected function initializeAction(): void @@ -148,10 +156,14 @@ public function notifyAction(): ResponseInterface return $this->htmlResponse(''); } - private function updatePaymentAndTransaction($notify, Item $orderItem, string $status): bool + /** + * Returns true if this request has changed the status of the payment. + * Only this request may dispatch the events, otherwise the redirect of the + * customer and the notification, which arrive at about the same time, + * both send the emails of the order. + */ + private function updatePaymentAndTransaction(GiroCheckout_SDK_Notify $notify, Item $orderItem, string $status): bool { - $dispatchEvent = false; - $payment = $orderItem->getPayment(); $transaction = null; @@ -172,15 +184,73 @@ private function updatePaymentAndTransaction($notify, Item $orderItem, string $s $transaction->setStatus($status); } - if ($payment->getStatus() !== $status) { - $payment->setStatus($status); - $dispatchEvent = true; - } - $this->paymentRepository->update($payment); $this->persistenceManager->persistAll(); - return $dispatchEvent; + return $this->changePaymentStatus($payment, $status); + } + + /** + * Changes the status only if no other request has changed it since the + * payment was loaded. cart 11 has no StatusChangeService, the status is + * changed with a conditional update. + */ + private function changePaymentStatus(Payment $payment, string $status): bool + { + $fromStatus = $payment->getStatus(); + if ($fromStatus === $status) { + return false; + } + + $affectedRows = $this->connectionPool + ->getConnectionForTable(self::PAYMENT_TABLE) + ->update( + self::PAYMENT_TABLE, + [ + 'status' => $status, + 'tstamp' => time(), + ], + [ + 'uid' => (int)$payment->getUid(), + 'status' => $fromStatus, + ], + [ + 'tstamp' => Connection::PARAM_INT, + 'uid' => Connection::PARAM_INT, + ] + ); + + if ($affectedRows === 0) { + $storedStatus = $this->getStoredPaymentStatus($payment); + if ($storedStatus !== $status) { + $this->logger->error('The status of a payment paid with Girosolution could not be changed.', [ + 'payment' => $payment->getUid(), + 'toStatus' => $status, + 'storedStatus' => $storedStatus, + ]); + } + + return false; + } + + $payment->setStatus($status); + + return true; + } + + private function getStoredPaymentStatus(Payment $payment): string + { + $queryBuilder = $this->connectionPool->getQueryBuilderForTable(self::PAYMENT_TABLE); + $queryBuilder->getRestrictions()->removeAll(); + + return (string)$queryBuilder + ->select('status') + ->from(self::PAYMENT_TABLE) + ->where( + $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter((int)$payment->getUid(), Connection::PARAM_INT)) + ) + ->executeQuery() + ->fetchOne(); } private function addFlashMessageToCartCart(string $translationKey): void diff --git a/Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php b/Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php index ffaa220..e407ba7 100644 --- a/Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php +++ b/Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php @@ -13,6 +13,7 @@ use Codappix\Typo3PhpDatasets\TestingFramework; use Extcode\Cart\Domain\Model\Cart\Cart; +use Extcode\GirosolutionTest\EventListener\ConcurrentPaymentStatusChange; use Extcode\GirosolutionTest\EventListener\EventRecorder; use Psr\Http\Message\ResponseInterface; use TYPO3\CMS\Core\Database\ConnectionPool; @@ -80,6 +81,7 @@ protected function setUp(): void ]); EventRecorder::reset(); + ConcurrentPaymentStatusChange::changeStatusTo(null); } /** diff --git a/Tests/Functional/Controller/Order/PaymentControllerNotifyActionTest.php b/Tests/Functional/Controller/Order/PaymentControllerNotifyActionTest.php index 895ffe0..de8311d 100644 --- a/Tests/Functional/Controller/Order/PaymentControllerNotifyActionTest.php +++ b/Tests/Functional/Controller/Order/PaymentControllerNotifyActionTest.php @@ -14,6 +14,7 @@ use Extcode\CartGirosolution\Controller\Order\PaymentController; use Extcode\CartGirosolution\Event\Order\CancelEvent; use Extcode\CartGirosolution\Event\Order\FinishEvent; +use Extcode\GirosolutionTest\EventListener\ConcurrentPaymentStatusChange; use Extcode\GirosolutionTest\EventListener\EventRecorder; use girosolution\GiroCheckout_SDK\helper\GiroCheckout_SDK_Exception_helper; use PHPUnit\Framework\Attributes\CoversClass; @@ -92,6 +93,34 @@ public function repeatedNotificationDoesNotDispatchTheEventAgain(): void self::assertCount(1, EventRecorder::getEvents()[FinishEvent::class] ?? []); } + /** + * The customer is redirected back while the notification is handled. If + * the redirect has marked the payment as paid in the meantime, only the + * redirect may dispatch the event, otherwise the order emails are sent + * twice. + */ + #[Test] + public function notificationDoesNotDispatchTheEventIfAConcurrentRequestHasMarkedThePaymentAsPaid(): void + { + ConcurrentPaymentStatusChange::changeStatusTo('paid'); + + $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + + self::assertSame('paid', $this->getPayment()['status']); + self::assertSame([], array_map(count(...), EventRecorder::getEvents())); + } + + #[Test] + public function notificationDoesNotOverwriteTheStatusSetByAConcurrentRequest(): void + { + ConcurrentPaymentStatusChange::changeStatusTo('canceled'); + + $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + + self::assertSame('canceled', $this->getPayment()['status']); + self::assertSame([], array_map(count(...), EventRecorder::getEvents())); + } + #[Test] public function notificationWithWrongHashIsRejected(): void { diff --git a/Tests/Functional/Controller/Order/PaymentControllerRedirectActionTest.php b/Tests/Functional/Controller/Order/PaymentControllerRedirectActionTest.php index 104cd9a..2a07e38 100644 --- a/Tests/Functional/Controller/Order/PaymentControllerRedirectActionTest.php +++ b/Tests/Functional/Controller/Order/PaymentControllerRedirectActionTest.php @@ -15,6 +15,7 @@ use Extcode\CartGirosolution\Controller\Order\PaymentController; use Extcode\CartGirosolution\Event\Order\CancelEvent; use Extcode\CartGirosolution\Event\Order\FinishEvent; +use Extcode\GirosolutionTest\EventListener\ConcurrentPaymentStatusChange; use Extcode\GirosolutionTest\EventListener\EventRecorder; use girosolution\GiroCheckout_SDK\helper\GiroCheckout_SDK_Exception_helper; use PHPUnit\Framework\Attributes\CoversClass; @@ -80,6 +81,23 @@ public function redirectAfterNotificationDoesNotDispatchTheEventAgain(): void self::assertCount(1, EventRecorder::getEvents()[FinishEvent::class] ?? []); } + /** + * The notification is handled while the customer is redirected back. If + * the notification has marked the payment as paid in the meantime, only + * the notification may dispatch the event, otherwise the order emails are + * sent twice. + */ + #[Test] + public function redirectDoesNotDispatchTheEventIfAConcurrentRequestHasMarkedThePaymentAsPaid(): void + { + ConcurrentPaymentStatusChange::changeStatusTo('paid'); + + $this->sendRedirect(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + + self::assertSame('paid', $this->getPayment()['status']); + self::assertSame([], array_map(count(...), EventRecorder::getEvents())); + } + #[Test] public function canceledPaymentMarksPaymentAndTransactionAsCanceled(): void { diff --git a/Tests/Functional/Fixtures/Extensions/girosolution_test/Classes/EventListener/ConcurrentPaymentStatusChange.php b/Tests/Functional/Fixtures/Extensions/girosolution_test/Classes/EventListener/ConcurrentPaymentStatusChange.php new file mode 100644 index 0000000..56643af --- /dev/null +++ b/Tests/Functional/Fixtures/Extensions/girosolution_test/Classes/EventListener/ConcurrentPaymentStatusChange.php @@ -0,0 +1,53 @@ +getObject() instanceof Payment) { + return; + } + + $this->connectionPool + ->getConnectionForTable('tx_cart_domain_model_order_payment') + ->update( + 'tx_cart_domain_model_order_payment', + ['status' => self::$status], + ['uid' => $event->getObject()->getUid()] + ); + } + + public static function changeStatusTo(?string $status): void + { + self::$status = $status; + } +} diff --git a/Tests/Functional/Fixtures/Extensions/girosolution_test/Configuration/Services.php b/Tests/Functional/Fixtures/Extensions/girosolution_test/Configuration/Services.php index acf5c45..eeadffa 100644 --- a/Tests/Functional/Fixtures/Extensions/girosolution_test/Configuration/Services.php +++ b/Tests/Functional/Fixtures/Extensions/girosolution_test/Configuration/Services.php @@ -4,8 +4,10 @@ use Extcode\CartGirosolution\Event\Order\CancelEvent; use Extcode\CartGirosolution\Event\Order\FinishEvent; +use Extcode\GirosolutionTest\EventListener\ConcurrentPaymentStatusChange; use Extcode\GirosolutionTest\EventListener\EventRecorder; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; +use TYPO3\CMS\Extbase\Event\Persistence\AfterObjectThawedEvent; return static function (ContainerConfigurator $containerConfigurator): void { $services = $containerConfigurator->services(); @@ -25,4 +27,10 @@ 'identifier' => 'girosolution-test--order--cancel--event-recorder', 'event' => CancelEvent::class, ]); + + $services->set(ConcurrentPaymentStatusChange::class) + ->tag('event.listener', [ + 'identifier' => 'girosolution-test--persistence--concurrent-payment-status-change', + 'event' => AfterObjectThawedEvent::class, + ]); };