diff --git a/Classes/Controller/Order/PaymentController.php b/Classes/Controller/Order/PaymentController.php index 5f6f7b3..131fad5 100644 --- a/Classes/Controller/Order/PaymentController.php +++ b/Classes/Controller/Order/PaymentController.php @@ -17,7 +17,10 @@ use Extcode\Cart\Domain\Repository\CartRepository; use Extcode\Cart\Domain\Repository\Order\ItemRepository as OrderItemRepository; use Extcode\Cart\Domain\Repository\Order\PaymentRepository; +use Extcode\Cart\OrderHistory\OrderChangeSource; use Extcode\Cart\OrderStatus\PaymentStatus; +use Extcode\Cart\OrderStatus\StatusChangeOutcome; +use Extcode\Cart\OrderStatus\StatusChangeService; use Extcode\Cart\Service\SessionHandler; use Extcode\CartGirosolution\Configuration\CredentialLoaderRegistry; use Extcode\CartGirosolution\Event\Order\CancelEvent; @@ -25,6 +28,7 @@ use girosolution\GiroCheckout_SDK\GiroCheckout_SDK_Notify; use InvalidArgumentException; use Psr\Http\Message\ResponseInterface; +use Psr\Log\LoggerInterface; use TYPO3\CMS\Core\Messaging\FlashMessage; use TYPO3\CMS\Core\Messaging\FlashMessageService; use TYPO3\CMS\Core\Type\ContextualFeedbackSeverity; @@ -36,6 +40,8 @@ class PaymentController extends ActionController { + private const INITIATOR = 'cart_girosolution'; + protected ?Cart $cart = null; protected array $cartPluginSettings; @@ -51,6 +57,8 @@ public function __construct( private readonly OrderItemRepository $orderItemRepository, private readonly PaymentRepository $paymentRepository, public readonly CredentialLoaderRegistry $credentialLoaderRegistry, + private readonly StatusChangeService $statusChangeService, + private readonly LoggerInterface $logger, ) {} protected function initializeAction(): void @@ -81,7 +89,7 @@ public function redirectAction(): ResponseInterface $notify = $this->getParsedNotify($clearingType); if ($notify->paymentSuccessful()) { - $dispatchEvent = $this->updatePaymentAndTransaction($notify, $orderItem, PaymentStatus::PAID); + $dispatchEvent = $this->updatePaymentAndTransaction($notify, $orderItem, PaymentStatus::PAID, OrderChangeSource::Frontend); if ($dispatchEvent) { $finishEvent = new FinishEvent($this->cart->getCart(), $orderItem, $this->cartPluginSettings); @@ -98,7 +106,7 @@ public function redirectAction(): ResponseInterface ); } - $dispatchEvent = $this->updatePaymentAndTransaction($notify, $orderItem, PaymentStatus::CANCELED); + $dispatchEvent = $this->updatePaymentAndTransaction($notify, $orderItem, PaymentStatus::CANCELED, OrderChangeSource::Frontend); $this->restoreCartSession(); @@ -128,7 +136,7 @@ public function notifyAction(): ResponseInterface $notify = $this->getParsedNotify($clearingType); if ($notify->paymentSuccessful()) { - $dispatchEvent = $this->updatePaymentAndTransaction($notify, $orderItem, PaymentStatus::PAID); + $dispatchEvent = $this->updatePaymentAndTransaction($notify, $orderItem, PaymentStatus::PAID, OrderChangeSource::Api); if ($dispatchEvent) { $orderItem = $this->cart->getOrderItem(); @@ -136,7 +144,7 @@ public function notifyAction(): ResponseInterface $this->eventDispatcher->dispatch($finishEvent); } } else { - $dispatchEvent = $this->updatePaymentAndTransaction($notify, $orderItem, PaymentStatus::CANCELED); + $dispatchEvent = $this->updatePaymentAndTransaction($notify, $orderItem, PaymentStatus::CANCELED, OrderChangeSource::Api); if ($dispatchEvent) { $orderItem = $this->cart->getOrderItem(); @@ -149,10 +157,18 @@ public function notifyAction(): ResponseInterface return $this->htmlResponse(''); } - private function updatePaymentAndTransaction($notify, Item $orderItem, string $status): bool - { - $dispatchEvent = false; - + /** + * 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, + OrderChangeSource $source + ): bool { $payment = $orderItem->getPayment(); $transaction = null; @@ -173,15 +189,29 @@ 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; + // changes the status only if no other request has changed it since the payment was loaded + $result = $this->statusChangeService->change( + $payment, + $status, + $payment->getStatus(), + self::INITIATOR, + null, + $source + ); + + if (!$result->isChanged() && $result->outcome !== StatusChangeOutcome::Unchanged) { + $this->logger->error('The status of a payment paid with Girosolution could not be changed.', [ + 'payment' => $payment->getUid(), + 'toStatus' => $status, + 'outcome' => $result->outcome->name, + 'vetoReason' => $result->vetoReason, + ]); + } + + return $result->isChanged(); } private function addFlashMessageToCartCart(string $translationKey): void diff --git a/Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php b/Tests/Functional/Controller/Order/AbstractPaymentControllerTestCase.php index 425b5d0..9a7d4ba 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; @@ -85,6 +86,7 @@ protected function setUp(): void ]); EventRecorder::reset(); + ConcurrentPaymentStatusChange::changeStatusTo(null); } /** @@ -165,6 +167,21 @@ protected function getTransaction(): array return $this->getRecord('tx_cart_domain_model_order_transaction', ['status', 'external_status_code', 'note']); } + /** + * @return list> + */ + protected function getOrderChanges(): array + { + return $this->get(ConnectionPool::class) + ->getConnectionForTable('tx_cart_domain_model_order_change') + ->select( + ['type', 'old_value', 'new_value', 'source', 'initiator'], + 'tx_cart_domain_model_order_change', + ['item' => 1] + ) + ->fetchAllAssociative(); + } + private function getRecord(string $table, array $fields): array { $record = $this->get(ConnectionPool::class) diff --git a/Tests/Functional/Controller/Order/PaymentControllerNotifyActionTest.php b/Tests/Functional/Controller/Order/PaymentControllerNotifyActionTest.php index 895ffe0..2fee1c4 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,53 @@ 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 successfulPaymentIsWrittenToTheOrderHistory(): void + { + $this->sendNotification(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + + self::assertSame( + [ + [ + 'type' => 'payment_status', + 'old_value' => 'open', + 'new_value' => 'paid', + 'source' => 'api', + 'initiator' => 'cart_girosolution', + ], + ], + $this->getOrderChanges() + ); + } + #[Test] public function notificationWithWrongHashIsRejected(): void { diff --git a/Tests/Functional/Controller/Order/PaymentControllerRedirectActionTest.php b/Tests/Functional/Controller/Order/PaymentControllerRedirectActionTest.php index 5002198..984c315 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; @@ -94,6 +95,43 @@ 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'); + + $response = $this->sendRedirect(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + + self::assertSame(303, $response->getStatusCode()); + self::assertSame('paid', $this->getPayment()['status']); + self::assertSame([], array_map(count(...), EventRecorder::getEvents())); + } + + #[Test] + public function successfulPaymentIsWrittenToTheOrderHistory(): void + { + $this->sendRedirect(self::RESULT_PAYMENT_SUCCESSFUL, self::TYPOSCRIPT_SECRET); + + self::assertSame( + [ + [ + 'type' => 'payment_status', + 'old_value' => 'open', + 'new_value' => 'paid', + 'source' => 'frontend', + 'initiator' => 'cart_girosolution', + ], + ], + $this->getOrderChanges() + ); + } + #[Test] public function canceledPaymentRedirectsToTheCart(): 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, + ]); };