Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PIPRES-261: Mixed cart checkout for subscriptions #803

Merged
merged 9 commits into from
Sep 11, 2023
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
6 changes: 1 addition & 5 deletions controllers/front/ajax.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
use Mollie\Exception\FailedToProvidePaymentFeeException;
use Mollie\Provider\PaymentFeeProviderInterface;
use Mollie\Repository\CurrencyRepositoryInterface;
use Mollie\Subscription\Exception\ProductValidationException;
use Mollie\Subscription\Exception\SubscriptionProductValidationException;
use Mollie\Subscription\Validator\CanProductBeAddedToCartValidator;
use Mollie\Utility\NumberUtility;
Expand Down Expand Up @@ -192,12 +191,9 @@ private function validateProduct(): void

try {
$cartValidation->validate((int) $product['id_product_attribute']);
} catch (ProductValidationException $e) {
$productCanBeAdded = false;
$message = $this->module->l('Product cannot be added because you have subscription product in your cart', self::FILE_NAME);
} catch (SubscriptionProductValidationException $e) {
$productCanBeAdded = false;
$message = $this->module->l('Subscription product cannot be added if you have other products in your cart', self::FILE_NAME);
$message = $this->module->l('Please note: Only one subscription product can be added to the cart at a time.', self::FILE_NAME);
}

$this->ajaxRender(
Expand Down
2 changes: 1 addition & 1 deletion controllers/front/subscriptionWebhook.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ protected function executeWebhook()

try {
$recurringOrderHandler->handle($transactionId);
} catch (Exception $exception) {
} catch (\Throwable $exception) {
$errorHandler->handle($exception, null, false);

$this->respond('failed', HttpStatusCode::HTTP_BAD_REQUEST);
Expand Down
8 changes: 4 additions & 4 deletions controllers/front/webhook.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
use Mollie\Config\Config;
use Mollie\Controller\AbstractMollieController;
use Mollie\Errors\Http\HttpStatusCode;
use Mollie\Exception\TransactionException;
use Mollie\Handler\ErrorHandler\ErrorHandler;
use Mollie\Service\TransactionService;
use Mollie\Utility\TransactionUtility;
Expand Down Expand Up @@ -73,6 +72,9 @@ protected function executeWebhook()
/** @var TransactionService $transactionService */
$transactionService = $this->module->getService(TransactionService::class);

/** @var ErrorHandler $errorHandler */
$errorHandler = $this->module->getService(ErrorHandler::class);

$transactionId = Tools::getValue('id');
if (!$transactionId) {
$this->respond('failed', HttpStatusCode::HTTP_UNPROCESSABLE_ENTITY, 'Missing transaction id');
Expand All @@ -95,9 +97,7 @@ protected function executeWebhook()
$cartId = $metaData->cart_id ?? 0;
$this->setContext($cartId);
$payment = $transactionService->processTransaction($transaction);
} catch (TransactionException $e) {
/** @var ErrorHandler $errorHandler */
$errorHandler = $this->module->getService(ErrorHandler::class);
} catch (\Throwable $e) {
$errorHandler->handle($e, $e->getCode(), false);
$this->respond('failed', $e->getCode(), $e->getMessage());
}
Expand Down
5 changes: 0 additions & 5 deletions mollie.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
use Mollie\Repository\PaymentMethodRepositoryInterface;
use Mollie\Service\ExceptionService;
use Mollie\ServiceProvider\LeagueServiceContainerProvider;
use Mollie\Subscription\Exception\ProductValidationException;
use Mollie\Subscription\Exception\SubscriptionProductValidationException;
use Mollie\Subscription\Handler\CustomerAddressUpdateHandler;
use Mollie\Subscription\Install\AttributeInstaller;
Expand Down Expand Up @@ -999,10 +998,6 @@ public function hookActionCartUpdateQuantityBefore($params)
} catch (SubscriptionProductValidationException $e) {
$product = $this->makeProductNotOrderable($params['product']);

$params['product'] = $product;
} catch (ProductValidationException $e) {
$product = $this->makeProductNotOrderable($params['product']);

$params['product'] = $product;
}
}
Expand Down
5 changes: 2 additions & 3 deletions src/Handler/ErrorHandler/ErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
namespace Mollie\Handler\ErrorHandler;

use Configuration;
use Exception;
use Mollie;
use Mollie\Config\Config;
use Mollie\Config\Env;
Expand Down Expand Up @@ -94,9 +93,9 @@ public function __construct(Mollie $module, Env $env = null)
}

/**
* @throws Exception
* @throws \Throwable
*/
public function handle(Exception $error, ?int $code = null, ?bool $throw = true): void
public function handle(\Throwable $error, ?int $code = null, ?bool $throw = true): void
{
$this->client->captureException($error, $this->exceptionContext);

Expand Down
3 changes: 2 additions & 1 deletion src/Handler/Order/OrderCreationHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -278,9 +278,10 @@ public function createBankTransferOrder($paymentData, Cart $cart)
return $paymentData;
}

private function createRecurringOrderEntity(Order $order, string $method)
private function createRecurringOrderEntity(Order $order, string $method): void
{
$cart = new Cart($order->id_cart);

if (!$this->subscriptionOrder->validate($cart)) {
return;
}
Expand Down
4 changes: 4 additions & 0 deletions subscription/Exception/ExceptionCode.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,8 @@ class ExceptionCode

public const ORDER_FAILED_TO_CREATE_ORDER_PAYMENT_FEE = 1001;
public const ORDER_FAILED_TO_UPDATE_ORDER_TOTAL_WITH_PAYMENT_FEE = 1002;

//Cart error codes starts from 2000

public const CART_ALREADY_HAS_SUBSCRIPTION_PRODUCT = 2001;
}
10 changes: 0 additions & 10 deletions subscription/Exception/ProductValidationException.php

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,4 @@

class SubscriptionProductValidationException extends MollieSubscriptionException
{
const MULTTIPLE_PRODUCTS_IN_CART = 0;
}
19 changes: 6 additions & 13 deletions subscription/Factory/CreateSubscriptionDataFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,12 @@
use Mollie\Repository\PaymentMethodRepositoryInterface;
use Mollie\Subscription\DTO\CreateSubscriptionData as SubscriptionDataDTO;
use Mollie\Subscription\DTO\Object\Amount;
use Mollie\Subscription\Exception\SubscriptionProductValidationException;
use Mollie\Subscription\Provider\SubscriptionDescriptionProvider;
use Mollie\Subscription\Provider\SubscriptionIntervalProvider;
use Mollie\Subscription\Repository\CombinationRepository;
use Mollie\Subscription\Repository\CurrencyRepository as CurrencyAdapter;
use Mollie\Utility\SecureKeyUtility;
use Order;
use Product;

class CreateSubscriptionDataFactory
{
Expand Down Expand Up @@ -63,28 +61,23 @@ public function __construct(
$this->module = $module;
}

public function build(Order $order): SubscriptionDataDTO
public function build(Order $order, array $subscriptionProduct): SubscriptionDataDTO
{
$customer = $order->getCustomer();
/** @var \MolCustomer $molCustomer */
//todo: will need to improve mollie module logic to have shop id or card it so that multishop doesn't break
$molCustomer = $this->customerRepository->findOneBy(['email' => $customer->email]);

$products = $order->getCartProducts();

// only one product is expected to be in order for subscription, if there are more than validation failed.
if (count($products) !== 1) {
throw new SubscriptionProductValidationException('Invalid amount of products for subscription', SubscriptionProductValidationException::MULTTIPLE_PRODUCTS_IN_CART);
}
/** @var Product $product */
$product = reset($products);
$combination = $this->combination->getById((int) $product['id_product_attribute']);
$combination = $this->combination->getById((int) $subscriptionProduct['id_product_attribute']);
$interval = $this->subscriptionInterval->getSubscriptionInterval($combination);

$currency = $this->currencyAdapter->getById((int) $order->id_currency);
$description = $this->subscriptionDescription->getSubscriptionDescription($order);

$orderAmount = new Amount((float) $order->total_paid_tax_incl, $currency->iso_code);
/**
* NOTE: we will only send product price as total for subscriptions
*/
$orderAmount = new Amount((float) $subscriptionProduct['total_price_tax_incl'], $currency->iso_code);
$subscriptionData = new SubscriptionDataDTO(
$molCustomer->customer_id,
$orderAmount,
Expand Down
76 changes: 24 additions & 52 deletions subscription/Handler/RecurringOrderHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,16 @@

use Cart;
use Mollie;
use Mollie\Action\CreateOrderPaymentFeeAction;
use Mollie\Action\UpdateOrderTotalsAction;
use Mollie\Adapter\ConfigurationAdapter;
use Mollie\Adapter\Shop;
use Mollie\Api\Resources\Payment;
use Mollie\Api\Resources\Subscription as MollieSubscription;
use Mollie\Api\Types\PaymentStatus;
use Mollie\Api\Types\SubscriptionStatus;
use Mollie\Config\Config;
use Mollie\DTO\CreateOrderPaymentFeeActionData;
use Mollie\DTO\UpdateOrderTotalsData;
use Mollie\Errors\Http\HttpStatusCode;
use Mollie\Exception\CouldNotCreateOrderPaymentFee;
use Mollie\Exception\CouldNotUpdateOrderTotals;
use Mollie\Exception\OrderCreationException;
use Mollie\Exception\TransactionException;
use Mollie\Repository\MolOrderPaymentFeeRepositoryInterface;
use Mollie\Repository\PaymentMethodRepositoryInterface;
use Mollie\Service\MailService;
use Mollie\Service\MollieOrderCreationService;
Expand All @@ -32,9 +25,9 @@
use Mollie\Subscription\Exception\CouldNotHandleRecurringOrder;
use Mollie\Subscription\Factory\GetSubscriptionDataFactory;
use Mollie\Subscription\Repository\RecurringOrderRepositoryInterface;
use Mollie\Subscription\Repository\RecurringOrdersProductRepositoryInterface;
use Mollie\Subscription\Utility\ClockInterface;
use Mollie\Utility\SecureKeyUtility;
use MolOrderPaymentFee;
use MolRecurringOrder;
use MolRecurringOrdersProduct;
use Order;
Expand Down Expand Up @@ -64,14 +57,10 @@ class RecurringOrderHandler
private $shop;
/** @var MailService */
private $mailService;
/** @var MolOrderPaymentFeeRepositoryInterface */
private $molOrderPaymentFeeRepository;
/** @var UpdateOrderTotalsAction */
private $updateOrderTotalsAction;
/** @var CreateOrderPaymentFeeAction */
private $createOrderPaymentFeeAction;
/** @var ConfigurationAdapter */
private $configuration;
/** @var RecurringOrdersProductRepositoryInterface */
private $recurringOrdersProductRepository;

public function __construct(
SubscriptionApi $subscriptionApi,
Expand All @@ -85,10 +74,8 @@ public function __construct(
ClockInterface $clock,
Shop $shop,
MailService $mailService,
MolOrderPaymentFeeRepositoryInterface $molOrderPaymentFeeRepository,
UpdateOrderTotalsAction $updateOrderTotalsAction,
CreateOrderPaymentFeeAction $createOrderPaymentFeeAction,
ConfigurationAdapter $configuration
ConfigurationAdapter $configuration,
RecurringOrdersProductRepositoryInterface $recurringOrdersProductRepository
) {
$this->subscriptionApi = $subscriptionApi;
$this->subscriptionDataFactory = $subscriptionDataFactory;
Expand All @@ -101,10 +88,8 @@ public function __construct(
$this->clock = $clock;
$this->shop = $shop;
$this->mailService = $mailService;
$this->molOrderPaymentFeeRepository = $molOrderPaymentFeeRepository;
$this->updateOrderTotalsAction = $updateOrderTotalsAction;
$this->createOrderPaymentFeeAction = $createOrderPaymentFeeAction;
$this->configuration = $configuration;
$this->recurringOrdersProductRepository = $recurringOrdersProductRepository;
}

public function handle(string $transactionId): string
Expand Down Expand Up @@ -168,6 +153,24 @@ private function createSubscription(Payment $transaction, MolRecurringOrder $rec
/** @var Cart $newCart */
$newCart = $newCart['cart'];

/** @var MolRecurringOrdersProduct $subscriptionProduct */
$subscriptionProduct = $this->recurringOrdersProductRepository->findOneBy([
'id_mol_recurring_orders_product' => $recurringOrder->id_mol_recurring_orders_product,
]);

$cartProducts = $newCart->getProducts();

foreach ($cartProducts as $cartProduct) {
if (
(int) $cartProduct['id_product'] === (int) $subscriptionProduct->id_product &&
(int) $cartProduct['id_product_attribute'] === (int) $subscriptionProduct->id_product_attribute
) {
continue;
}

$newCart->deleteProduct((int) $cartProduct['id_product'], (int) $cartProduct['id_product_attribute']);
}

/**
* NOTE: New order can't have soft deleted delivery address
*/
Expand Down Expand Up @@ -200,37 +203,6 @@ private function createSubscription(Payment $transaction, MolRecurringOrder $rec

$this->mollieOrderCreationService->createMolliePayment($transaction, (int) $newCart->id, $order->reference, (int) $orderId, PaymentStatus::STATUS_PAID);

/** @var MolOrderPaymentFee|null $molOrderPaymentFee */
$molOrderPaymentFee = $this->molOrderPaymentFeeRepository->findOneBy([
'id_order' => $recurringOrder->id_order,
]);

if ($molOrderPaymentFee) {
try {
$this->createOrderPaymentFeeAction->run(CreateOrderPaymentFeeActionData::create(
$orderId,
(int) $newCart->id,
(float) $molOrderPaymentFee->fee_tax_incl,
(float) $molOrderPaymentFee->fee_tax_excl
));
} catch (CouldNotCreateOrderPaymentFee $exception) {
throw CouldNotHandleRecurringOrder::failedToCreateOrderPaymentFee($exception);
}

try {
$this->updateOrderTotalsAction->run(UpdateOrderTotalsData::create(
$orderId,
(float) $molOrderPaymentFee->fee_tax_incl,
(float) $molOrderPaymentFee->fee_tax_excl,
(float) $transaction->amount->value,
(float) $cart->getOrderTotal(true, Cart::BOTH),
(float) $cart->getOrderTotal(false, Cart::BOTH)
));
} catch (CouldNotUpdateOrderTotals $exception) {
throw CouldNotHandleRecurringOrder::failedToUpdateOrderTotalWithPaymentFee($exception);
}
}

$this->orderStatusService->setOrderStatus($orderId, (int) Config::getStatuses()[$transaction->status]);
}

Expand Down
29 changes: 22 additions & 7 deletions subscription/Handler/SubscriptionCreationHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Mollie\Subscription\Api\SubscriptionApi;
use Mollie\Subscription\Factory\CreateSubscriptionDataFactory;
use Mollie\Subscription\Utility\ClockInterface;
use Mollie\Subscription\Validator\SubscriptionProductValidator;
use MolRecurringOrder;
use MolRecurringOrdersProduct;
use Order;
Expand All @@ -22,26 +23,40 @@ class SubscriptionCreationHandler

/** @var CreateSubscriptionDataFactory */
private $createSubscriptionDataFactory;
/** @var SubscriptionProductValidator */
private $subscriptionProductValidator;

public function __construct(
ClockInterface $clock,
SubscriptionApi $subscriptionApi,
CreateSubscriptionDataFactory $subscriptionDataFactory
CreateSubscriptionDataFactory $subscriptionDataFactory,
SubscriptionProductValidator $subscriptionProductValidator
) {
$this->clock = $clock;
$this->subscriptionApi = $subscriptionApi;
$this->createSubscriptionDataFactory = $subscriptionDataFactory;
$this->subscriptionProductValidator = $subscriptionProductValidator;
}

public function handle(Order $order, string $method)
{
$subscriptionData = $this->createSubscriptionDataFactory->build($order);
$subscription = $this->subscriptionApi->subscribeOrder($subscriptionData);

$products = $order->getProducts();
$product = reset($products);
$subscriptionProduct = [];

foreach ($products as $product) {
if (!$this->subscriptionProductValidator->validate((int) $product['product_attribute_id'])) {
continue;
}

$subscriptionProduct = $product;

break;
}

$subscriptionData = $this->createSubscriptionDataFactory->build($order, $subscriptionProduct);
$subscription = $this->subscriptionApi->subscribeOrder($subscriptionData);

$recurringOrdersProduct = $this->createRecurringOrdersProduct($product);
$recurringOrdersProduct = $this->createRecurringOrdersProduct($subscriptionProduct);

$this->createRecurringOrder($recurringOrdersProduct, $order, $subscription, $method);
}
Expand All @@ -52,7 +67,7 @@ private function createRecurringOrdersProduct(array $product): MolRecurringOrder
$recurringOrdersProduct->id_product = $product['id_product'];
$recurringOrdersProduct->id_product_attribute = $product['product_attribute_id'];
$recurringOrdersProduct->quantity = $product['product_quantity'];
$recurringOrdersProduct->unit_price = $product['price'];
$recurringOrdersProduct->unit_price = $product['unit_price_tax_excl'];
$recurringOrdersProduct->add();

return $recurringOrdersProduct;
Expand Down
Loading
Loading