Skip to content
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
58 changes: 44 additions & 14 deletions Classes/Controller/Order/PaymentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,18 @@
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;
use Extcode\CartGirosolution\Event\Order\FinishEvent;
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;
Expand All @@ -36,6 +40,8 @@

class PaymentController extends ActionController
{
private const INITIATOR = 'cart_girosolution';

protected ?Cart $cart = null;

protected array $cartPluginSettings;
Expand All @@ -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
Expand Down Expand Up @@ -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);
Expand All @@ -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();

Expand Down Expand Up @@ -128,15 +136,15 @@ 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();
$finishEvent = new FinishEvent($this->cart->getCart(), $orderItem, $this->cartPluginSettings);
$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();
Expand All @@ -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;
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -85,6 +86,7 @@ protected function setUp(): void
]);

EventRecorder::reset();
ConcurrentPaymentStatusChange::changeStatusTo(null);
}

/**
Expand Down Expand Up @@ -165,6 +167,21 @@ protected function getTransaction(): array
return $this->getRecord('tx_cart_domain_model_order_transaction', ['status', 'external_status_code', 'note']);
}

/**
* @return list<array<string, mixed>>
*/
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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

declare(strict_types=1);

namespace Extcode\GirosolutionTest\EventListener;

/*
* This file is part of the package extcode/cart-girosolution.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/

use Extcode\Cart\Domain\Model\Order\Payment;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Extbase\Event\Persistence\AfterObjectThawedEvent;

/**
* Simulates a concurrent request, e.g. the notification of Girosolution while
* the customer is redirected back: after a payment has been loaded, its stored
* status is changed to the given status.
*
* The status is stored statically, as frontend requests in functional tests
* use their own instance of the listener.
*/
final class ConcurrentPaymentStatusChange
{
private static ?string $status = null;

public function __construct(
private readonly ConnectionPool $connectionPool,
) {}

public function __invoke(AfterObjectThawedEvent $event): void
{
if (self::$status === null || !$event->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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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,
]);
};
Loading