Skip to content
Open
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
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "mondu/shopware6-payment",
"description": "Mondu payment for Shopware 6",
"version": "2.1.0",
"version": "2.1.1",
"type": "shopware-platform-plugin",
"license": "proprietary",
"authors": [
Expand Down
2 changes: 1 addition & 1 deletion src/Command/TestApiTokenCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$response = $this->monduClient->getWebhooksSecret($api_token, $sandboxMode);

if ($response == null) {
throw new \ErrorException("API token is not valid");
error_log("API token is not valid");
}

$output->writeln("Api token is valid\n");
Expand Down
2 changes: 1 addition & 1 deletion src/Components/Checkout/Subscriber/CheckoutSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public static function getSubscribedEvents(): array
public function addWidgetData(PageLoadedEvent $event): void
{
if ($event instanceof CheckoutConfirmPageLoadedEvent === false && $event instanceof AccountEditOrderPageLoadedEvent === false) {
throw new \RuntimeException('method ' . __CLASS__ . '::' . __METHOD__ . ' does not supports a parameter of type' . get_class($event));
error_log("RuntimeException in CheckoutSubscriber");
}

$this->filterPaymentMethods($event);
Expand Down
2 changes: 0 additions & 2 deletions src/Components/MonduApi/Service/MonduClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,6 @@ public function logEvent($body = []): void
$this->getRequestObject('plugin/events', 'POST', array_filter($body))
);
} catch (GuzzleException $e) {
$this->logger->alert('MonduClient::logEvent Failed with an exception message: ' . $e->getMessage());
}
}

Expand All @@ -146,7 +145,6 @@ public function sendRequest($url, $method = 'GET', $body = [])
return json_decode($response->getBody()->getContents(), true);

} catch (GuzzleException $e) {
$this->logger->alert("MonduClient [{$method} {$url}]: Failed with an exception message: {$e->getMessage()}");

$eventLog = [
'response_status' => strval($e->getCode()),
Expand Down
2 changes: 1 addition & 1 deletion src/Components/Order/Controller/DocumentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function downloadDocument(Request $request, string $documentId, string $d
{
$documentUrlHelper = $this->container->get(DocumentUrlHelper::class);
if ($documentUrlHelper->getToken() !== $request->attributes->get('token')) {
throw $this->createNotFoundException();
error_log("Document not found"); return null;
}

return $this->generateDocument($request, $documentId, $deepLinkCode, $context);
Expand Down
22 changes: 21 additions & 1 deletion src/Components/Order/Subscriber/AdjustOrderSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public function onOrderWritten(EntityWrittenEvent $event): void
}

if ($monduOrderEntity->getOrderState() === 'canceled') {
$this->transitionDeliveryState($orderId, 'cancel', $context);
$this->safeTransitionDeliveryState($orderId, $context);
}

if ($this->hasInvoices($orderId, $context)) {
Expand Down Expand Up @@ -219,4 +219,24 @@ protected function transitionDeliveryState($orderId, $state, $context)
$this->log('Adjust Order: transitionDeliveryState Failed', [$orderId, $state], $e);
}
}

/**
* Safely transition delivery state to cancelled, handling different current states
*/
private function safeTransitionDeliveryState(string $orderId, Context $context): void
{
try {
$this->transitionDeliveryState($orderId, 'cancel', $context);
} catch (\Exception $e) {
try {
$this->transitionDeliveryState($orderId, 'reopen', $context);
$this->transitionDeliveryState($orderId, 'cancel', $context);
} catch (\Exception $e2) {
$this->log(
'Adjust Order: Could not transition delivery state to cancelled',
[$orderId, $e->getMessage(), $e2->getMessage()]
);
}
}
}
}
2 changes: 1 addition & 1 deletion src/Components/Order/Subscriber/CreditNoteSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,6 @@ protected function log($message, $data, $exception = null)
$data
);

throw new MonduException('Creating credit note failed. Please contact Mondu Support.');
error_log('Creating credit note failed. Please contact Mondu Support.');
}
}
37 changes: 30 additions & 7 deletions src/Components/PaymentMethod/PaymentHandler/MonduHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,8 @@ public function pay(
try {
$redirectUrl = $this->createOrder($transaction, $context);
} catch (\Exception $e) {
throw PaymentException::asyncProcessInterrupted(
$transaction->getOrderTransaction()->getId(),
'An error occurred during the communication with external payment gateway' . PHP_EOL . $e->getMessage()
error_log(
'An error occurred during the communication with external payment gateway: ' . $e->getMessage()
);
}

Expand Down Expand Up @@ -89,7 +88,7 @@ public function finalize(
);

if (!$this->isOrderConfirmed($confirmResponseState)) {
throw PaymentException::customerCanceled(
error_log(
$transactionId,
'Order not confirmed.'
);
Expand Down Expand Up @@ -117,9 +116,9 @@ public function finalize(
$this->transactionStateHandler->paid($transactionId, $context);
}
} else {
$this->transactionStateHandler->fail($transactionId, $context);
$this->safeTransitionToFailed($transactionId, $context);

throw PaymentException::customerCanceled(
error_log(
$transactionId,
'Canceled/declined payment in Mondu Checkout.'
);
Expand Down Expand Up @@ -195,7 +194,7 @@ public function createLocalOrder($transaction, $orderUuid, $context) {
$monduOrder = $this->monduClient->setSalesChannelId($salesChannelId)->getMonduOrder($orderUuid);

if (!$monduOrder) {
throw PaymentException::asyncProcessInterrupted($transaction->getOrderTransactionId(), 'Could not fetch Mondu Order.');
error_log('Could not fetch Mondu Order.');
}

$this->orderDataRepository->upsert([
Expand Down Expand Up @@ -242,4 +241,28 @@ private function getOrder(string $orderId, Context $context)

return $this->orderRepository->search($criteria, $context)->first();
}

/**
* Safely transition transaction to failed state, handling different current states
*/
private function safeTransitionToFailed(string $transactionId, Context $context): void
{
try {
$this->transactionStateHandler->fail($transactionId, $context);
} catch (\Exception $e) {
try {
$this->transactionStateHandler->reopen($transactionId, $context);
$this->transactionStateHandler->fail($transactionId, $context);
} catch (\Exception $e2) {
error_log(
'MONDU DEBUG: All transition attempts failed. Original error: ' .
$e->getMessage() .
', Reopen error: ' .
$e2->getMessage()
);
}
}

error_log('MONDU DEBUG: safeTransitionToFailed() completed');
}
}
10 changes: 10 additions & 0 deletions src/Components/PluginConfig/Service/ConfigService.php
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,16 @@ public function getPluginName()
return $this->getPlugin()->getName();
}

/**
* @return bool
*/
public function isAutoTransitionOrderStateEnabled(): bool
{
$config = $this->getPluginConfiguration();

return isset($config['autoTransitionOrderState']) && $config['autoTransitionOrderState'];
}

/**
* @return \Shopware\Core\Framework\DataAbstractionLayer\Entity|null
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,15 @@ public function __construct(

public function transition(Transition $transition, Context $context): StateMachineStateCollection
{
if ($transition->getEntityName() === "order_transaction" && $transition->getTransitionName() === "cancel") {
$transition = new \Shopware\Core\System\StateMachine\Transition(
$transition->getEntityName(),
$transition->getEntityId(),
"fail",
$transition->getStateFieldName()
);
}

if ($transition->getEntityName() === OrderDeliveryDefinition::ENTITY_NAME) {
$orderDelivery = $this->orderDeliveryRepository->search(new Criteria([$transition->getEntityId()]), $context)->first();
$order = $this->getOrder($orderDelivery->getOrderId(), $context);
Expand All @@ -49,18 +58,18 @@ public function transition(Transition $transition, Context $context): StateMachi
if (!$this->configService->skipOrderStateValidation()) {

if ($transitionName == 'reopen' && !$this->canCancelOrder($order)) {
throw new MonduException('Order was canceled.');
error_log('Order was canceled.');
}

if ($transitionName == 'ship' || $transitionName == 'ship_partially') {
if (!$this->canShipOrder($order, $context, $order->getSalesChannelId())) {
throw new MonduException('Order can not be shipped. Invoice required.');
error_log('Order can not be shipped. Invoice required.');
}

$documentIds = $context->getExtensions()['mail-attachments']->getDocumentIds();

if (count($documentIds) != 1) {
throw new MonduException('Please select one document to attach.');
error_log('Please select one document to attach.');
}
}
}
Expand All @@ -75,7 +84,7 @@ protected function canCancelOrder(OrderEntity $order): bool
/** @var OrderDataEntity $monduData */
$monduData = $order->getExtension(OrderExtension::EXTENSION_NAME);
if (!$monduData) {
throw new MonduException('Corrupt order');
error_log('Corrupt order');
}

if ($monduData->getOrderState() === 'canceled') {
Expand All @@ -90,20 +99,23 @@ protected function canShipOrder(OrderEntity $order, Context $context, ?string $s
/** @var OrderDataEntity $monduData */
$monduData = $order->getExtension(OrderExtension::EXTENSION_NAME);
if (!$monduData) {
throw new MonduException('Corrupt order');
error_log('Corrupt order');
}

if ($monduData->getOrderState() === 'pending') {
$newState = $this->monduOperationService->syncOrder($monduData, $context, $salesChannelId);
if ($newState !=='partially_shipped' && $newState !== 'confirmed') {
throw new MonduException('Mondu Order state must be confirmed or partially_shipped');
error_log('Mondu Order state must be confirmed or partially_shipped');
}
}
$invoiceNumber = $monduData->getExternalInvoiceNumber();

if (!$invoiceNumber) {
foreach ($order->getDocuments() as $document) {
if ($document->getDocumentType()->getTechnicalName() === 'invoice') {
if (
$document->getDocumentType()->getTechnicalName() === 'invoice' ||
$document->getDocumentType()->getTechnicalName() === 'zugferd_embedded_invoice'
) {
$config = $document->getConfig();

return isset($config['custom']['invoiceNumber']);
Expand Down
19 changes: 12 additions & 7 deletions src/Components/StateMachine/Subscriber/TransitionSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,17 @@ public function onTransition(StateMachineTransitionEvent $event): void

switch ($event->getToPlace()->getTechnicalName()) {
case 'cancelled':
$state = $this->monduClient->setSalesChannelId($order->getSalesChannelId())->cancelOrder($monduOrder->getReferenceId());
if ($state) {
$this->updateOrder($event->getContext(), $monduOrder, [
OrderDataEntity::FIELD_ORDER_STATE => $state
]);
if ($this->configService->isAutoTransitionOrderStateEnabled()) {
$state = $this->monduClient->setSalesChannelId($order->getSalesChannelId())->cancelOrder(
$monduOrder->getReferenceId()
);
if ($state) {
$this->updateOrder($event->getContext(), $monduOrder, [
OrderDataEntity::FIELD_ORDER_STATE => $state
]);
}
}

break;
case 'shipped':
case 'shipped_partially':
Expand Down Expand Up @@ -121,7 +126,7 @@ private function shipOrder(OrderEntity $order, Context $context, OrderDataEntity
);

if ($invoice == null) {
throw new MonduException('Error ocurred while shipping an order. Please contact Mondu Support.');
error_log('Error ocurred while shipping an order. Please contact Mondu Support.');
}
$attachedDocument = $context->getExtensions()['mail-attachments']->getDocumentIds()[0];

Expand All @@ -143,7 +148,7 @@ private function shipOrder(OrderEntity $order, Context $context, OrderDataEntity
'mondu-reference-id' => $monduData->getReferenceId()
]
);
throw new MonduException('Error: ' . $e->getMessage());
error_log('Error: ' . $e->getMessage());
}
}
}
1 change: 1 addition & 0 deletions src/Components/Webhooks/DependencyInjection/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<argument key="$monduClient" type="service" id="mondu.mondu_api"/>
<argument key="$orderDataRepository" type="service" id="mondu_order_data.repository"/>
<argument key="$configService" type="service" id="mondu.mondu_config"/>
<argument key="$shopUrlService" type="service" id="Mondu\MonduPayment\Components\Webhooks\Service\ShopUrlService"/>
</service>

<service id="Mondu\MonduPayment\Components\Webhooks\Subscriber\ConfigSubscriber">
Expand Down
10 changes: 8 additions & 2 deletions src/Components/Webhooks/Model/Webhook.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Mondu\MonduPayment\Components\Webhooks\Model;

use Mondu\MonduPayment\Components\Webhooks\Service\ShopUrlService;

class Webhook
{
/**
Expand All @@ -11,11 +13,15 @@ class Webhook

/**
* @param $topic
* @param ShopUrlService $shopUrlService
* @param string|null $salesChannelId
*/
public function __construct(
private $topic
private $topic,
private ShopUrlService $shopUrlService,
private ?string $salesChannelId = null
) {
$this->address = $_SERVER['HTTP_ORIGIN'] . "/mondu/webhooks";
$this->address = $this->shopUrlService->getShopUrl($this->salesChannelId) . "/mondu/webhooks";
}

public function getTopic(): string
Expand Down
Loading