Skip to content

Commit

Permalink
Merge pull request #64 from mollie/release/1.12.0
Browse files Browse the repository at this point in the history
Release/1.12.0
  • Loading branch information
Marvin-Magmodules authored Jul 12, 2023
2 parents 065ec02 + a3eaf39 commit 7264fb2
Show file tree
Hide file tree
Showing 13 changed files with 580 additions and 171 deletions.
44 changes: 44 additions & 0 deletions Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
class Config
{
const EXTENSION_CODE = 'Mollie_Subscriptions';
const XML_PATH_DEBUG_ERROR_EMAIL_TEMPLATE = 'mollie_subscriptions/debug/error_email_template';
const XML_PATH_DEBUG_ENABLE_ERROR_EMAILS = 'mollie_subscriptions/debug/enable_error_emails';
const XML_PATH_DEBUG_ERROR_SENDER_EMAIL = 'mollie_subscriptions/debug/error_sender_email';
const XML_PATH_DEBUG_ERROR_RECEIVER_EMAIL = 'mollie_subscriptions/debug/error_receiver_email';
const XML_PATH_EXTENSION_VERSION = 'mollie_subscriptions/general/version';
const XML_PATH_EXTENSION_ENABLE = 'mollie_subscriptions/general/enable';
const XML_PATH_EXTENSION_SHIPPING_METHOD = 'mollie_subscriptions/general/shipping_method';
Expand Down Expand Up @@ -157,6 +161,36 @@ public function isEnabled(int $storeId = null): bool
return $this->getFlag(self::XML_PATH_EXTENSION_ENABLE, $storeId);
}

/**
* @param int $storeId
* @param string $scope
* @return bool
*/
public function isErrorEmailEnabled(int $storeId = null, string $scope = ScopeInterface::SCOPE_STORE): bool
{
return $this->getFlag(self::XML_PATH_DEBUG_ENABLE_ERROR_EMAILS, $storeId, $scope);
}

/**
* @param int|null $storeId
* @param string $scope
* @return string
*/
public function errorEmailSender(int $storeId = null, string $scope = ScopeInterface::SCOPE_STORE): string
{
return $this->getStoreValue(self::XML_PATH_DEBUG_ERROR_SENDER_EMAIL, $storeId, $scope);
}

/**
* @param int|null $storeId
* @param string $scope
* @return string
*/
public function errorEmailReceiver(int $storeId = null, string $scope = ScopeInterface::SCOPE_STORE): string
{
return $this->getStoreValue(self::XML_PATH_DEBUG_ERROR_RECEIVER_EMAIL, $storeId, $scope);
}

/**
* @param int|null $storeId
* @return string
Expand Down Expand Up @@ -229,6 +263,16 @@ public function allowOneTimePurchase($storeId = null, $scope = ScopeInterface::S
return $this->getFlag(static::XML_PATH_ALLOW_ONE_TIME_PURCHASE, $storeId, $scope);
}

/**
* @param int $storeId
* @param string $scope
* @return null|string
*/
public function subscriptionErrorAdminNotificationTemplate(int $storeId = null, string $scope = ScopeInterface::SCOPE_STORE): ?string
{
return $this->getStoreValue(static::XML_PATH_DEBUG_ERROR_EMAIL_TEMPLATE, $storeId, $scope);
}

/**
* @param null|int|string $storeId
* @param string $scope
Expand Down
185 changes: 22 additions & 163 deletions Controller/Api/Webhook.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,16 @@

namespace Mollie\Subscriptions\Controller\Api;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\Request\InvalidRequestException;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Exception\NotFoundException;
use Magento\Quote\Api\CartManagementInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Api\Data\AddressInterface;
use Magento\Quote\Api\Data\AddressInterfaceFactory;
use Magento\Quote\Api\Data\CartInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Mollie\Api\Exceptions\ApiException;
use Mollie\Api\MollieApiClient;
use Mollie\Api\Resources\Payment;
use Mollie\Api\Resources\Subscription;
use Mollie\Payment\Api\MollieCustomerRepositoryInterface;
use Mollie\Payment\Logger\MollieLogger;
use Mollie\Payment\Model\Client\Payments;
use Mollie\Payment\Model\Mollie;
Expand All @@ -37,7 +25,9 @@
use Mollie\Payment\Service\Order\SendOrderEmails;
use Mollie\Subscriptions\Config;
use Mollie\Subscriptions\Service\Mollie\MollieSubscriptionApi;
use Mollie\Subscriptions\Service\Magento\CreateOrderFromSubscription;
use Mollie\Subscriptions\Service\Mollie\RetryUsingOtherStoreViews;
use Mollie\Subscriptions\Service\Mollie\SendAdminNotification;

class Webhook extends Action implements CsrfAwareActionInterface
{
Expand All @@ -56,46 +46,6 @@ class Webhook extends Action implements CsrfAwareActionInterface
*/
private $mollieSubscriptionApi;

/**
* @var MollieCustomerRepositoryInterface
*/
private $mollieCustomerRepository;

/**
* @var CartManagementInterface
*/
private $cartManagement;

/**
* @var CartRepositoryInterface
*/
private $cartRepository;

/**
* @var ProductRepositoryInterface
*/
private $productRepository;

/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;

/**
* @var AddressInterfaceFactory
*/
private $addressFactory;

/**
* @var AddressRepositoryInterface
*/
private $addressRepository;

/**
* @var OrderRepositoryInterface
*/
private $orderRepository;

/**
* @var MollieLogger
*/
Expand All @@ -120,6 +70,15 @@ class Webhook extends Action implements CsrfAwareActionInterface
* @var ValidateMetadata
*/
private $validateMetadata;
/**
* @var SendAdminNotification
*/
private $sendAdminNotification;

/**
* @var CreateOrderFromSubscription
*/
private $createOrderFromSubscription;

/**
* @var LinkTransactionToOrder
Expand All @@ -136,40 +95,28 @@ public function __construct(
Config $config,
Mollie $mollie,
MollieSubscriptionApi $mollieSubscriptionApi,
MollieCustomerRepositoryInterface $mollieCustomerRepository,
CartManagementInterface $cartManagement,
CartRepositoryInterface $cartRepository,
ProductRepositoryInterface $productRepository,
CustomerRepositoryInterface $customerRepository,
AddressInterfaceFactory $addressFactory,
AddressRepositoryInterface $addressRepository,
OrderRepositoryInterface $orderRepository,
MollieLogger $mollieLogger,
SendOrderEmails $sendOrderEmails,
RetryUsingOtherStoreViews $retryUsingOtherStoreViews,
ValidateMetadata $validateMetadata,
LinkTransactionToOrder $linkTransactionToOrder,
OrderCommentHistory $orderCommentHistory
OrderCommentHistory $orderCommentHistory,
SendAdminNotification $sendAdminNotification,
CreateOrderFromSubscription $createOrderFromSubscription
) {
parent::__construct($context);

$this->config = $config;
$this->mollie = $mollie;
$this->mollieSubscriptionApi = $mollieSubscriptionApi;
$this->mollieCustomerRepository = $mollieCustomerRepository;
$this->cartManagement = $cartManagement;
$this->cartRepository = $cartRepository;
$this->productRepository = $productRepository;
$this->customerRepository = $customerRepository;
$this->addressFactory = $addressFactory;
$this->addressRepository = $addressRepository;
$this->orderRepository = $orderRepository;
$this->mollieLogger = $mollieLogger;
$this->sendOrderEmails = $sendOrderEmails;
$this->retryUsingOtherStoreViews = $retryUsingOtherStoreViews;
$this->validateMetadata = $validateMetadata;
$this->linkTransactionToOrder = $linkTransactionToOrder;
$this->orderCommentHistory = $orderCommentHistory;
$this->sendAdminNotification = $sendAdminNotification;
$this->createOrderFromSubscription = $createOrderFromSubscription;
}

public function execute()
Expand Down Expand Up @@ -199,40 +146,19 @@ public function execute()
$molliePayment = $this->getPayment($id);
$subscription = $this->api->subscriptions->getForId($molliePayment->customerId, $molliePayment->subscriptionId);

$mollieCustomer = $this->mollieCustomerRepository->getByMollieCustomerId($molliePayment->customerId);
if (!$mollieCustomer) {
throw new \Exception(
'Mollie customer with ID ' . $molliePayment->customerId . ' not found in database'
);
}

$customerId = $mollieCustomer->getCustomerId();
$customer = $this->customerRepository->getById($customerId);

$cart = $this->getCart($customer);
$this->addProduct($molliePayment, $cart, $subscription->metadata->quantity ?? 1);

$cart->setBillingAddress($this->formatAddress($this->addressRepository->getById($customer->getDefaultBilling())));
$this->setShippingAddress($customer, $cart);

$cart->getPayment()->addData(['method' => 'mollie_methods_' . $molliePayment->method]);

$cart->collectTotals();
$this->cartRepository->save($cart);

$order = $this->cartManagement->submit($cart);
$order->setMollieTransactionId($molliePayment->id);
$order->getPayment()->setAdditionalInformation('subscription_created', $subscription->createdAt);
$this->orderRepository->save($order);
$order = $this->createOrderFromSubscription->execute($this->api, $molliePayment, $subscription);

$this->orderCommentHistory->add($order, __('Order created by Mollie subscription %1', $molliePayment->id));

$this->linkTransactionToOrder->execute($molliePayment->id, $order);

$this->mollie->processTransactionForOrder($order, Payments::TRANSACTION_TYPE_SUBSCRIPTION);

return $this->returnOkResponse();
} catch (ApiException $exception) {
$this->mollieLogger->addErrorLog('ApiException occured while checking transaction', [
} catch (\Throwable $exception) {
$this->sendAdminNotification->send($id, $exception);

$this->mollieLogger->addInfoLog('Error occurred while processing subscription', [
'id' => $id,
'exception' => $exception->__toString()
]);
Expand All @@ -241,73 +167,6 @@ public function execute()
}
}

private function formatAddress(\Magento\Customer\Api\Data\AddressInterface $customerAddress): AddressInterface
{
$address = $this->addressFactory->create();
$address->setFirstname($customerAddress->getFirstName());
$address->setMiddlename($customerAddress->getMiddlename());
$address->setLastname($customerAddress->getLastname());
$address->setStreet($customerAddress->getStreet());
$address->setPostcode($customerAddress->getPostcode());
$address->setCity($customerAddress->getCity());
$address->setCountryId($customerAddress->getCountryId());
$address->setCompany($customerAddress->getCompany());
$address->setTelephone($customerAddress->getTelephone());
$address->setFax($customerAddress->getFax());
$address->setVatId($customerAddress->getVatId());
$address->setSuffix($customerAddress->getSuffix());
$address->setPrefix($customerAddress->getPrefix());
$address->setRegionId($customerAddress->getRegionId());

return $address;
}

private function addProduct(Payment $mollieOrder, CartInterface $cart, float $quantity)
{
/** @var Subscription $subscription */
$subscription = $this->api->performHttpCallToFullUrl(MollieApiClient::HTTP_GET, $mollieOrder->_links->subscription->href);
$sku = $subscription->metadata->sku;
$product = $this->productRepository->get($sku);

$cart->addProduct($product, $quantity);
}

private function setShippingAddress(CustomerInterface $customer, CartInterface $cart)
{
$shippingAddress = $this->formatAddress($this->addressRepository->getById($customer->getDefaultShipping()));
$cart->setShippingAddress($shippingAddress);

$shippingAddress = $cart->getShippingAddress();
$shippingAddress->setCollectShippingRates(true);
$shippingAddress->collectShippingRates();
$shippingAddress->setShippingMethod($this->config->getShippingMethod());

// There are no rates available. Switch to the first available shipping method.
if ($shippingAddress->getShippingRateByCode($this->config->getShippingMethod()) === false &&
count($shippingAddress->getShippingRatesCollection()->getItems()) > 0
) {
$newMethod = $shippingAddress->getShippingRatesCollection()->getFirstItem()->getCode();
$shippingAddress->setShippingMethod($newMethod);

$this->mollieLogger->addInfoLog(
'subscriptions',
'No rates available for ' . $this->config->getShippingMethod() .
', switched to ' . $newMethod
);
}
}

private function getCart(CustomerInterface $customer): CartInterface
{
$cartId = $this->cartManagement->createEmptyCart();
$cart = $this->cartRepository->get($cartId);
$cart->setStoreId($customer->getStoreId());
$cart->setCustomer($customer);
$cart->setCustomerIsGuest(0);

return $cart;
}

private function returnOkResponse()
{
$result = $this->resultFactory->create(ResultFactory::TYPE_RAW);
Expand Down
7 changes: 6 additions & 1 deletion Model/MollieSubscriptionsListing.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,14 @@ public function getDataSourceData()
$api = $this->mollieSubscriptionApi->loadByStore($storeId);
$paging = $this->getContext()->getRequestParam('paging');

$pageSize = $paging['pageSize'] ?? 20;
if ($pageSize > 250) {
$pageSize = 250;
}

$result = $api->subscriptions->page(
$this->getContext()->getRequestParam('offsetID'),
$paging['pageSize'] ?? 20
$pageSize
);

$this->preloadCustomers((array)$result);
Expand Down
Loading

0 comments on commit 7264fb2

Please sign in to comment.