From 91e715b3f7ee9e783b1cc0165c02c1dbcfa094dd Mon Sep 17 00:00:00 2001 From: mandan2 Date: Mon, 28 Aug 2023 16:20:06 +0300 Subject: [PATCH 1/9] PIPRES-261: New order split into separate subscription order --- src/Handler/Order/OrderCreationHandler.php | 3 +- .../Factory/CreateSubscriptionDataFactory.php | 30 ++++-- .../Handler/RecurringOrderHandler.php | 98 +++++++++++++------ .../Handler/SubscriptionCreationHandler.php | 23 ++++- .../CanProductBeAddedToCartValidator.php | 42 +++++--- .../Validator/SubscriptionOrderValidator.php | 9 +- 6 files changed, 142 insertions(+), 63 deletions(-) diff --git a/src/Handler/Order/OrderCreationHandler.php b/src/Handler/Order/OrderCreationHandler.php index 4f21ab40b..e09f39690 100644 --- a/src/Handler/Order/OrderCreationHandler.php +++ b/src/Handler/Order/OrderCreationHandler.php @@ -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; } diff --git a/subscription/Factory/CreateSubscriptionDataFactory.php b/subscription/Factory/CreateSubscriptionDataFactory.php index 60433bc2d..f3e0c3c15 100644 --- a/subscription/Factory/CreateSubscriptionDataFactory.php +++ b/subscription/Factory/CreateSubscriptionDataFactory.php @@ -15,6 +15,7 @@ use Mollie\Subscription\Provider\SubscriptionIntervalProvider; use Mollie\Subscription\Repository\CombinationRepository; use Mollie\Subscription\Repository\CurrencyRepository as CurrencyAdapter; +use Mollie\Subscription\Validator\SubscriptionProductValidator; use Mollie\Utility\SecureKeyUtility; use Order; use Product; @@ -42,6 +43,8 @@ class CreateSubscriptionDataFactory private $link; /** @var Mollie */ private $module; + /** @var SubscriptionProductValidator */ + private $subscriptionProductValidator; public function __construct( MolCustomerRepository $customerRepository, @@ -51,7 +54,8 @@ public function __construct( CombinationRepository $combination, PaymentMethodRepositoryInterface $methodRepository, Link $link, - Mollie $module + Mollie $module, + SubscriptionProductValidator $subscriptionProductValidator ) { $this->customerRepository = $customerRepository; $this->subscriptionInterval = $subscriptionInterval; @@ -61,6 +65,7 @@ public function __construct( $this->methodRepository = $methodRepository; $this->link = $link; $this->module = $module; + $this->subscriptionProductValidator = $subscriptionProductValidator; } public function build(Order $order): SubscriptionDataDTO @@ -71,20 +76,29 @@ public function build(Order $order): SubscriptionDataDTO $molCustomer = $this->customerRepository->findOneBy(['email' => $customer->email]); $products = $order->getCartProducts(); + $subscriptionProduct = []; - // 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); + // TODO add shipping option that is selected in BO + + foreach ($products as $product) { + if (!$this->subscriptionProductValidator->validate((int) $product['id_product_attribute'])) { + continue; + } + + $subscriptionProduct = $product; + + break; } - /** @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); + // TODO if we decide to include shipping, add it here (new cart instance is needed) + + $orderAmount = new Amount((float) $subscriptionProduct['total_price_tax_incl'], $currency->iso_code); $subscriptionData = new SubscriptionDataDTO( $molCustomer->customer_id, $orderAmount, diff --git a/subscription/Handler/RecurringOrderHandler.php b/subscription/Handler/RecurringOrderHandler.php index 757dad853..451aacf05 100644 --- a/subscription/Handler/RecurringOrderHandler.php +++ b/subscription/Handler/RecurringOrderHandler.php @@ -32,6 +32,7 @@ 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; @@ -72,6 +73,8 @@ class RecurringOrderHandler private $createOrderPaymentFeeAction; /** @var ConfigurationAdapter */ private $configuration; + /** @var RecurringOrdersProductRepositoryInterface */ + private $recurringOrdersProductRepository; public function __construct( SubscriptionApi $subscriptionApi, @@ -88,7 +91,8 @@ public function __construct( MolOrderPaymentFeeRepositoryInterface $molOrderPaymentFeeRepository, UpdateOrderTotalsAction $updateOrderTotalsAction, CreateOrderPaymentFeeAction $createOrderPaymentFeeAction, - ConfigurationAdapter $configuration + ConfigurationAdapter $configuration, + RecurringOrdersProductRepositoryInterface $recurringOrdersProductRepository ) { $this->subscriptionApi = $subscriptionApi; $this->subscriptionDataFactory = $subscriptionDataFactory; @@ -105,6 +109,7 @@ public function __construct( $this->updateOrderTotalsAction = $updateOrderTotalsAction; $this->createOrderPaymentFeeAction = $createOrderPaymentFeeAction; $this->configuration = $configuration; + $this->recurringOrdersProductRepository = $recurringOrdersProductRepository; } public function handle(string $transactionId): string @@ -168,6 +173,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 */ @@ -181,6 +204,17 @@ private function createSubscription(Payment $transaction, MolRecurringOrder $rec $specificPrice = $this->createSpecificPrice($recurringOrderProduct, $recurringOrder); + // TODO set delivery option from back office settings + $newCart->setDeliveryOption([(int) $recurringOrder->id_address_delivery => sprintf('%d,', 8)]); + $newCart->update(); + + $newCart->getDeliveryOption(null, false, false)[$cart->id_address_delivery]; + +// $this->assertNotEquals( +// sprintf('%d,', (int) $carrier->id), +// $this->contextBuilder->getContext()->cart->getDeliveryOption(null, false, false)[$cart->id_address_delivery] +// ); + $this->mollie->validateOrder( (int) $newCart->id, (int) $this->configuration->get(Config::MOLLIE_STATUS_AWAITING), @@ -200,36 +234,38 @@ 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); - } - } + // TODO let's not set payment fee for subscription + +// /** @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]); } diff --git a/subscription/Handler/SubscriptionCreationHandler.php b/subscription/Handler/SubscriptionCreationHandler.php index f0b90816d..8354c39e3 100644 --- a/subscription/Handler/SubscriptionCreationHandler.php +++ b/subscription/Handler/SubscriptionCreationHandler.php @@ -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; @@ -22,15 +23,19 @@ 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) @@ -39,9 +44,19 @@ public function handle(Order $order, string $method) $subscription = $this->subscriptionApi->subscribeOrder($subscriptionData); $products = $order->getProducts(); - $product = reset($products); + $subscriptionProduct = []; - $recurringOrdersProduct = $this->createRecurringOrdersProduct($product); + foreach ($products as $product) { + if (!$this->subscriptionProductValidator->validate((int) $product['product_attribute_id'])) { + continue; + } + + $subscriptionProduct = $product; + + break; + } + + $recurringOrdersProduct = $this->createRecurringOrdersProduct($subscriptionProduct); $this->createRecurringOrder($recurringOrdersProduct, $order, $subscription, $method); } @@ -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; diff --git a/subscription/Validator/CanProductBeAddedToCartValidator.php b/subscription/Validator/CanProductBeAddedToCartValidator.php index d7102e684..5fdd828cd 100644 --- a/subscription/Validator/CanProductBeAddedToCartValidator.php +++ b/subscription/Validator/CanProductBeAddedToCartValidator.php @@ -53,7 +53,9 @@ public function validate(int $productAttributeId): bool return $this->validateIfSubscriptionProductCanBeAdded($productAttributeId); } - return $this->validateIfProductCanBeAdded(); + return true; +// +// return $this->validateIfProductCanBeAdded(); } /** @@ -66,23 +68,37 @@ public function validate(int $productAttributeId): bool private function validateIfSubscriptionProductCanBeAdded(int $productAttributeId): bool { $cartProducts = $this->cart->getProducts(); - $numberOfProductsInCart = count($cartProducts); - // we can only have 1 product in cart if its subscription product - if ($numberOfProductsInCart > 1) { - throw new SubscriptionProductValidationException('Cart has multiple products', SubscriptionProductValidationException::MULTTIPLE_PRODUCTS_IN_CART); - } - // if it's the same product we can add more of the same product - if ($numberOfProductsInCart === 1) { - $cartProduct = reset($cartProducts); - - $isTheSameProduct = $productAttributeId === (int) $cartProduct['id_product_attribute']; + foreach ($cartProducts as $cartProduct) { + if (!$this->subscriptionProduct->validate((int) $cartProduct['id_product_attribute'])) { + continue; + } - if (!$isTheSameProduct) { - throw new SubscriptionProductValidationException('Cart has multiple products', SubscriptionProductValidationException::MULTTIPLE_PRODUCTS_IN_CART); + if ((int) $cartProduct['id_product_attribute'] === $productAttributeId) { + continue; } + + // TODO new exception to show that only single subscription product can be added + throw new SubscriptionProductValidationException('Cart has multiple products', SubscriptionProductValidationException::MULTTIPLE_PRODUCTS_IN_CART); } +// $numberOfProductsInCart = count($cartProducts); +// // we can only have 1 product in cart if its subscription product +// if ($numberOfProductsInCart > 1) { +// throw new SubscriptionProductValidationException('Cart has multiple products', SubscriptionProductValidationException::MULTTIPLE_PRODUCTS_IN_CART); +// } +// +// // if it's the same product we can add more of the same product +// if ($numberOfProductsInCart === 1) { +// $cartProduct = reset($cartProducts); +// +// $isTheSameProduct = $productAttributeId === (int) $cartProduct['id_product_attribute']; +// +// if (!$isTheSameProduct) { +// throw new SubscriptionProductValidationException('Cart has multiple products', SubscriptionProductValidationException::MULTTIPLE_PRODUCTS_IN_CART); +// } +// } + return true; } diff --git a/subscription/Validator/SubscriptionOrderValidator.php b/subscription/Validator/SubscriptionOrderValidator.php index 100dbe24c..33bdea498 100644 --- a/subscription/Validator/SubscriptionOrderValidator.php +++ b/subscription/Validator/SubscriptionOrderValidator.php @@ -20,13 +20,10 @@ public function __construct(SubscriptionProductValidator $subscriptionProduct) public function validate(Cart $cart): bool { $products = $cart->getProducts(); - // only one product can be subscribed at a time - if (count($products) !== 1) { - return false; - } - // checks if product is subscription product - // foreach is not necessary but might need to add more possible products for subscription in later updates + // TODO add exception handling scenario where subscription fails to be created due to multiple subscription products but flow continues + + // checks if one of cart products is subscription product foreach ($products as $product) { if ($this->subscriptionProduct->validate((int) $product['id_product_attribute'])) { return true; From 02baa7252cff2e1194a0aea90c238003efe67f9c Mon Sep 17 00:00:00 2001 From: mandan2 Date: Mon, 28 Aug 2023 16:22:06 +0300 Subject: [PATCH 2/9] csfixer --- subscription/Factory/CreateSubscriptionDataFactory.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/subscription/Factory/CreateSubscriptionDataFactory.php b/subscription/Factory/CreateSubscriptionDataFactory.php index f3e0c3c15..b0d052ac3 100644 --- a/subscription/Factory/CreateSubscriptionDataFactory.php +++ b/subscription/Factory/CreateSubscriptionDataFactory.php @@ -10,7 +10,6 @@ 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; @@ -18,7 +17,6 @@ use Mollie\Subscription\Validator\SubscriptionProductValidator; use Mollie\Utility\SecureKeyUtility; use Order; -use Product; class CreateSubscriptionDataFactory { From e7ea2eb1ec60edc6066663029dc6348d5b126fe2 Mon Sep 17 00:00:00 2001 From: mandan2 Date: Mon, 28 Aug 2023 16:27:40 +0300 Subject: [PATCH 3/9] stan --- subscription/Handler/RecurringOrderHandler.php | 7 ------- 1 file changed, 7 deletions(-) diff --git a/subscription/Handler/RecurringOrderHandler.php b/subscription/Handler/RecurringOrderHandler.php index 451aacf05..8a8e2582b 100644 --- a/subscription/Handler/RecurringOrderHandler.php +++ b/subscription/Handler/RecurringOrderHandler.php @@ -208,13 +208,6 @@ private function createSubscription(Payment $transaction, MolRecurringOrder $rec $newCart->setDeliveryOption([(int) $recurringOrder->id_address_delivery => sprintf('%d,', 8)]); $newCart->update(); - $newCart->getDeliveryOption(null, false, false)[$cart->id_address_delivery]; - -// $this->assertNotEquals( -// sprintf('%d,', (int) $carrier->id), -// $this->contextBuilder->getContext()->cart->getDeliveryOption(null, false, false)[$cart->id_address_delivery] -// ); - $this->mollie->validateOrder( (int) $newCart->id, (int) $this->configuration->get(Config::MOLLIE_STATUS_AWAITING), From f2d71bff20cd033a861cd40cdab24817644109cf Mon Sep 17 00:00:00 2001 From: mandan2 Date: Mon, 28 Aug 2023 16:54:04 +0300 Subject: [PATCH 4/9] improved validations --- controllers/front/ajax.php | 4 -- mollie.php | 5 -- subscription/Exception/ExceptionCode.php | 4 ++ .../Exception/ProductValidationException.php | 10 ---- ...SubscriptionProductValidationException.php | 1 - .../Factory/CreateSubscriptionDataFactory.php | 2 - .../CanProductBeAddedToCartValidator.php | 50 ++----------------- .../Validator/SubscriptionOrderValidator.php | 6 +-- .../SubscriptionProductValidator.php | 1 + ... CanProductBeAddedToCartValidatorTest.php} | 15 +++--- ...php => SubscriptionOrderValidatorTest.php} | 10 ++-- ...p => SubscriptionProductValidatorTest.php} | 9 ++-- 12 files changed, 33 insertions(+), 84 deletions(-) delete mode 100644 subscription/Exception/ProductValidationException.php rename tests/Integration/Subscription/Validator/{SubscriptionCartTest.php => CanProductBeAddedToCartValidatorTest.php} (93%) rename tests/Integration/Subscription/Validator/{SubscriptionOrderTest.php => SubscriptionOrderValidatorTest.php} (94%) rename tests/Integration/Subscription/Validator/{SubscriptionProductTest.php => SubscriptionProductValidatorTest.php} (93%) diff --git a/controllers/front/ajax.php b/controllers/front/ajax.php index 6c6ff8376..cc93f30a7 100644 --- a/controllers/front/ajax.php +++ b/controllers/front/ajax.php @@ -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; @@ -192,9 +191,6 @@ 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); diff --git a/mollie.php b/mollie.php index 58e6542db..0b419b8d2 100755 --- a/mollie.php +++ b/mollie.php @@ -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; @@ -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; } } diff --git a/subscription/Exception/ExceptionCode.php b/subscription/Exception/ExceptionCode.php index 2fabb1bcd..7820f0276 100644 --- a/subscription/Exception/ExceptionCode.php +++ b/subscription/Exception/ExceptionCode.php @@ -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; } diff --git a/subscription/Exception/ProductValidationException.php b/subscription/Exception/ProductValidationException.php deleted file mode 100644 index 52b90e556..000000000 --- a/subscription/Exception/ProductValidationException.php +++ /dev/null @@ -1,10 +0,0 @@ -getCartProducts(); $subscriptionProduct = []; - // TODO add shipping option that is selected in BO - foreach ($products as $product) { if (!$this->subscriptionProductValidator->validate((int) $product['id_product_attribute'])) { continue; diff --git a/subscription/Validator/CanProductBeAddedToCartValidator.php b/subscription/Validator/CanProductBeAddedToCartValidator.php index 5fdd828cd..94382bc21 100644 --- a/subscription/Validator/CanProductBeAddedToCartValidator.php +++ b/subscription/Validator/CanProductBeAddedToCartValidator.php @@ -6,7 +6,7 @@ use Mollie\Adapter\CartAdapter; use Mollie\Adapter\ToolsAdapter; -use Mollie\Subscription\Exception\ProductValidationException; +use Mollie\Subscription\Exception\ExceptionCode; use Mollie\Subscription\Exception\SubscriptionProductValidationException; class CanProductBeAddedToCartValidator @@ -38,6 +38,8 @@ public function __construct( * @param int $productAttributeId * * @return bool + * + * @throws SubscriptionProductValidationException */ public function validate(int $productAttributeId): bool { @@ -49,13 +51,7 @@ public function validate(int $productAttributeId): bool $isNewSubscriptionProduct = $this->subscriptionProduct->validate($productAttributeId); - if ($isNewSubscriptionProduct) { - return $this->validateIfSubscriptionProductCanBeAdded($productAttributeId); - } - - return true; -// -// return $this->validateIfProductCanBeAdded(); + return !$isNewSubscriptionProduct || $this->validateIfSubscriptionProductCanBeAdded($productAttributeId); } /** @@ -78,43 +74,7 @@ private function validateIfSubscriptionProductCanBeAdded(int $productAttributeId continue; } - // TODO new exception to show that only single subscription product can be added - throw new SubscriptionProductValidationException('Cart has multiple products', SubscriptionProductValidationException::MULTTIPLE_PRODUCTS_IN_CART); - } - -// $numberOfProductsInCart = count($cartProducts); -// // we can only have 1 product in cart if its subscription product -// if ($numberOfProductsInCart > 1) { -// throw new SubscriptionProductValidationException('Cart has multiple products', SubscriptionProductValidationException::MULTTIPLE_PRODUCTS_IN_CART); -// } -// -// // if it's the same product we can add more of the same product -// if ($numberOfProductsInCart === 1) { -// $cartProduct = reset($cartProducts); -// -// $isTheSameProduct = $productAttributeId === (int) $cartProduct['id_product_attribute']; -// -// if (!$isTheSameProduct) { -// throw new SubscriptionProductValidationException('Cart has multiple products', SubscriptionProductValidationException::MULTTIPLE_PRODUCTS_IN_CART); -// } -// } - - return true; - } - - /** - * @return bool - * - * @throws ProductValidationException - */ - private function validateIfProductCanBeAdded(): bool - { - $cartProducts = $this->cart->getProducts(); - foreach ($cartProducts as $cartProduct) { - $isSubscriptionProduct = $this->subscriptionProduct->validate((int) $cartProduct['id_product_attribute']); - if ($isSubscriptionProduct) { - throw new ProductValidationException('Cart has subscription products', ProductValidationException::SUBSCRIPTTION_PRODUCTS_IN_CART); - } + throw new SubscriptionProductValidationException('Cart already has subscription product', ExceptionCode::CART_ALREADY_HAS_SUBSCRIPTION_PRODUCT); } return true; diff --git a/subscription/Validator/SubscriptionOrderValidator.php b/subscription/Validator/SubscriptionOrderValidator.php index 33bdea498..7adb56572 100644 --- a/subscription/Validator/SubscriptionOrderValidator.php +++ b/subscription/Validator/SubscriptionOrderValidator.php @@ -21,15 +21,15 @@ public function validate(Cart $cart): bool { $products = $cart->getProducts(); - // TODO add exception handling scenario where subscription fails to be created due to multiple subscription products but flow continues + $subscriptionProductCount = 0; // checks if one of cart products is subscription product foreach ($products as $product) { if ($this->subscriptionProduct->validate((int) $product['id_product_attribute'])) { - return true; + ++$subscriptionProductCount; } } - return false; + return $subscriptionProductCount > 0 && $subscriptionProductCount < 2; } } diff --git a/subscription/Validator/SubscriptionProductValidator.php b/subscription/Validator/SubscriptionProductValidator.php index 3c24ec80a..e00f345f2 100644 --- a/subscription/Validator/SubscriptionProductValidator.php +++ b/subscription/Validator/SubscriptionProductValidator.php @@ -43,6 +43,7 @@ public function validate(int $productAttributeId): bool { $combination = $this->combination->getById($productAttributeId); $attributeIds = $this->combinationRepository->getIds((int) $combination->id); + foreach ($attributeIds as $attributeId) { if ($this->isSubscriptionAttribute((int) $attributeId['id_attribute'])) { return true; diff --git a/tests/Integration/Subscription/Validator/SubscriptionCartTest.php b/tests/Integration/Subscription/Validator/CanProductBeAddedToCartValidatorTest.php similarity index 93% rename from tests/Integration/Subscription/Validator/SubscriptionCartTest.php rename to tests/Integration/Subscription/Validator/CanProductBeAddedToCartValidatorTest.php index 248217403..319709425 100644 --- a/tests/Integration/Subscription/Validator/SubscriptionCartTest.php +++ b/tests/Integration/Subscription/Validator/CanProductBeAddedToCartValidatorTest.php @@ -1,9 +1,10 @@ randomAttributeId = self::NORMAL_PRODUCT_ATTRIBUTE_ID; @@ -58,7 +60,6 @@ protected function setUp(): void */ public function testValidate(string $combinationReference, bool $hasExtraAttribute, array $cartProducts, $expectedResult): void { - $language = new Language(1); $cartAdapterMock = $this->createMock(CartAdapter::class); $cartProducts = array_map(function (array $product) { @@ -114,7 +115,7 @@ public function productDataProvider(): array 'id_product_attribute' => self::NORMAL_PRODUCT_ATTRIBUTE_ID, ], ], - 'expected result' => SubscriptionProductValidationException::class, + 'expected result' => true, ], 'Add subscription product but already have another subscription product in cart' => [ 'subscription reference' => Config::SUBSCRIPTION_ATTRIBUTE_DAILY, @@ -134,7 +135,7 @@ public function productDataProvider(): array 'id_product_attribute' => Config::SUBSCRIPTION_ATTRIBUTE_MONTHLY, ], ], - 'expected result' => ProductValidationException::class, + 'expected result' => true, ], 'Add normal product but already have another normal product in cart' => [ 'subscription reference' => '', @@ -159,6 +160,6 @@ private function getCombination(string $combinationReference, bool $hasExtraAttr ]) : $this->randomAttributeId; } - return (int) Combination::getIdByReference(1, $reference); + return (int) \Combination::getIdByReference(1, $reference); } } diff --git a/tests/Integration/Subscription/Validator/SubscriptionOrderTest.php b/tests/Integration/Subscription/Validator/SubscriptionOrderValidatorTest.php similarity index 94% rename from tests/Integration/Subscription/Validator/SubscriptionOrderTest.php rename to tests/Integration/Subscription/Validator/SubscriptionOrderValidatorTest.php index df246ecc5..dd2467b2d 100644 --- a/tests/Integration/Subscription/Validator/SubscriptionOrderTest.php +++ b/tests/Integration/Subscription/Validator/SubscriptionOrderValidatorTest.php @@ -1,19 +1,21 @@ randomAttributeId = self::NORMAL_PRODUCT_ATTRIBUTE_ID; @@ -64,7 +66,7 @@ public function testValidate(array $orderProducts, $expectedResult): void $combinationMock = $this->createMock(CombinationAdapter::class); $combinationMock ->method('getById') - ->willReturn(new Combination(1)); + ->willReturn(new \Combination(1)); $subscriptionProductMock = $this->createMock(SubscriptionProductValidator::class); $mockedValidation = [ @@ -106,7 +108,7 @@ public function productDataProvider(): array Config::SUBSCRIPTION_ATTRIBUTE_DAILY, self::NORMAL_PRODUCT_ATTRIBUTE_ID, ], - 'expected result' => false, + 'expected result' => true, ], 'Only normal product' => [ 'order products' => [ diff --git a/tests/Integration/Subscription/Validator/SubscriptionProductTest.php b/tests/Integration/Subscription/Validator/SubscriptionProductValidatorTest.php similarity index 93% rename from tests/Integration/Subscription/Validator/SubscriptionProductTest.php rename to tests/Integration/Subscription/Validator/SubscriptionProductValidatorTest.php index 0b50b6c68..7448e07cb 100644 --- a/tests/Integration/Subscription/Validator/SubscriptionProductTest.php +++ b/tests/Integration/Subscription/Validator/SubscriptionProductValidatorTest.php @@ -1,15 +1,18 @@ randomAttributeId = 1; @@ -90,6 +93,6 @@ private function getCombination(string $combinationReference, bool $hasExtraAttr ]) : $this->randomAttributeId; } - return (int) Combination::getIdByReference(1, $reference); + return (int) \Combination::getIdByReference(1, $reference); } } From 536ddd90c0de3df6873ca10acb1ce7af7abffb34 Mon Sep 17 00:00:00 2001 From: mandan2 Date: Mon, 28 Aug 2023 16:56:10 +0300 Subject: [PATCH 5/9] removed commented code --- .../Handler/RecurringOrderHandler.php | 53 ------------------- 1 file changed, 53 deletions(-) diff --git a/subscription/Handler/RecurringOrderHandler.php b/subscription/Handler/RecurringOrderHandler.php index 8a8e2582b..6e8a268ee 100644 --- a/subscription/Handler/RecurringOrderHandler.php +++ b/subscription/Handler/RecurringOrderHandler.php @@ -6,8 +6,6 @@ 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; @@ -15,14 +13,9 @@ 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; @@ -35,7 +28,6 @@ use Mollie\Subscription\Repository\RecurringOrdersProductRepositoryInterface; use Mollie\Subscription\Utility\ClockInterface; use Mollie\Utility\SecureKeyUtility; -use MolOrderPaymentFee; use MolRecurringOrder; use MolRecurringOrdersProduct; use Order; @@ -65,12 +57,6 @@ 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 */ @@ -88,9 +74,6 @@ public function __construct( ClockInterface $clock, Shop $shop, MailService $mailService, - MolOrderPaymentFeeRepositoryInterface $molOrderPaymentFeeRepository, - UpdateOrderTotalsAction $updateOrderTotalsAction, - CreateOrderPaymentFeeAction $createOrderPaymentFeeAction, ConfigurationAdapter $configuration, RecurringOrdersProductRepositoryInterface $recurringOrdersProductRepository ) { @@ -105,9 +88,6 @@ 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; } @@ -227,39 +207,6 @@ private function createSubscription(Payment $transaction, MolRecurringOrder $rec $this->mollieOrderCreationService->createMolliePayment($transaction, (int) $newCart->id, $order->reference, (int) $orderId, PaymentStatus::STATUS_PAID); - // TODO let's not set payment fee for subscription - -// /** @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]); } From 21edfe5516a3e298203ac9ad97218917110c6329 Mon Sep 17 00:00:00 2001 From: mandan2 Date: Mon, 11 Sep 2023 11:28:39 +0300 Subject: [PATCH 6/9] note fixes --- controllers/front/ajax.php | 2 +- controllers/front/subscriptionWebhook.php | 2 +- controllers/front/webhook.php | 8 ++++---- subscription/Factory/CreateSubscriptionDataFactory.php | 5 +++-- subscription/Handler/RecurringOrderHandler.php | 4 ---- .../Validator/CanProductBeAddedToCartValidator.php | 3 +-- subscription/Validator/SubscriptionOrderValidator.php | 2 +- 7 files changed, 11 insertions(+), 15 deletions(-) diff --git a/controllers/front/ajax.php b/controllers/front/ajax.php index cc93f30a7..42a85cd38 100644 --- a/controllers/front/ajax.php +++ b/controllers/front/ajax.php @@ -193,7 +193,7 @@ private function validateProduct(): void $cartValidation->validate((int) $product['id_product_attribute']); } 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( diff --git a/controllers/front/subscriptionWebhook.php b/controllers/front/subscriptionWebhook.php index e01c99c98..0fe91601f 100644 --- a/controllers/front/subscriptionWebhook.php +++ b/controllers/front/subscriptionWebhook.php @@ -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); diff --git a/controllers/front/webhook.php b/controllers/front/webhook.php index 6b2e86d01..699298883 100644 --- a/controllers/front/webhook.php +++ b/controllers/front/webhook.php @@ -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; @@ -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'); @@ -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()); } diff --git a/subscription/Factory/CreateSubscriptionDataFactory.php b/subscription/Factory/CreateSubscriptionDataFactory.php index 7dd1b8d78..16aea2474 100644 --- a/subscription/Factory/CreateSubscriptionDataFactory.php +++ b/subscription/Factory/CreateSubscriptionDataFactory.php @@ -92,8 +92,9 @@ public function build(Order $order): SubscriptionDataDTO $currency = $this->currencyAdapter->getById((int) $order->id_currency); $description = $this->subscriptionDescription->getSubscriptionDescription($order); - // TODO if we decide to include shipping, add it here (new cart instance is needed) - + /** + * 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, diff --git a/subscription/Handler/RecurringOrderHandler.php b/subscription/Handler/RecurringOrderHandler.php index 6e8a268ee..7d4ac50da 100644 --- a/subscription/Handler/RecurringOrderHandler.php +++ b/subscription/Handler/RecurringOrderHandler.php @@ -184,10 +184,6 @@ private function createSubscription(Payment $transaction, MolRecurringOrder $rec $specificPrice = $this->createSpecificPrice($recurringOrderProduct, $recurringOrder); - // TODO set delivery option from back office settings - $newCart->setDeliveryOption([(int) $recurringOrder->id_address_delivery => sprintf('%d,', 8)]); - $newCart->update(); - $this->mollie->validateOrder( (int) $newCart->id, (int) $this->configuration->get(Config::MOLLIE_STATUS_AWAITING), diff --git a/subscription/Validator/CanProductBeAddedToCartValidator.php b/subscription/Validator/CanProductBeAddedToCartValidator.php index 94382bc21..1060d0139 100644 --- a/subscription/Validator/CanProductBeAddedToCartValidator.php +++ b/subscription/Validator/CanProductBeAddedToCartValidator.php @@ -32,8 +32,7 @@ public function __construct( /** * Validates if product can be added to the cart. - * Only 1 subscription product can be in cart and no other products can be added if there are subscription products - * For now we only allow one subscription product with any quantities, later might need to add logic to allow more products + * Only 1 subscription product can be to the cart * * @param int $productAttributeId * diff --git a/subscription/Validator/SubscriptionOrderValidator.php b/subscription/Validator/SubscriptionOrderValidator.php index 7adb56572..d6948f6aa 100644 --- a/subscription/Validator/SubscriptionOrderValidator.php +++ b/subscription/Validator/SubscriptionOrderValidator.php @@ -16,7 +16,7 @@ public function __construct(SubscriptionProductValidator $subscriptionProduct) $this->subscriptionProduct = $subscriptionProduct; } - /** Returns true if cart has subscription products */ + /** Returns true if cart has subscription product */ public function validate(Cart $cart): bool { $products = $cart->getProducts(); From 439a37973bdf1f5c31859cfce5c33235c62f5e27 Mon Sep 17 00:00:00 2001 From: mandan2 Date: Mon, 11 Sep 2023 11:33:54 +0300 Subject: [PATCH 7/9] test fix --- tests/Unit/Factory/SubscriptionDataTest.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/Unit/Factory/SubscriptionDataTest.php b/tests/Unit/Factory/SubscriptionDataTest.php index f133fdaf7..cbfbf74da 100644 --- a/tests/Unit/Factory/SubscriptionDataTest.php +++ b/tests/Unit/Factory/SubscriptionDataTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Mollie\Subscription\Tests\Unit\Factory; +namespace Mollie\Tests\Unit\Factory; use Mollie; use Mollie\Adapter\Link; @@ -17,6 +17,7 @@ use Mollie\Subscription\Provider\SubscriptionIntervalProvider; use Mollie\Subscription\Repository\CombinationRepository; use Mollie\Subscription\Repository\CurrencyRepository; +use Mollie\Subscription\Validator\SubscriptionProductValidator; use Mollie\Utility\SecureKeyUtility; use PHPUnit\Framework\TestCase; @@ -58,6 +59,9 @@ public function testBuildSubscriptionData(string $customerId, float $totalAmount ] ); + $subscriptionProductValidator = $this->createMock(SubscriptionProductValidator::class); + $subscriptionProductValidator->method('validate')->willReturn(true); + $subscriptionDataFactory = new CreateSubscriptionDataFactory( $customerRepositoryMock, $subscriptionIntervalProviderMock, @@ -66,7 +70,8 @@ public function testBuildSubscriptionData(string $customerId, float $totalAmount new CombinationRepository(), $paymentMethodRepositoryMock, new Link(), - new Mollie() + new Mollie(), + $subscriptionProductValidator ); $customerMock = $this->createMock('Customer'); @@ -77,6 +82,7 @@ public function testBuildSubscriptionData(string $customerId, float $totalAmount $order->method('getCartProducts')->willReturn([ [ 'id_product_attribute' => 1, + 'total_price_tax_incl' => 19.99, ], ]); $order->id = self::TEST_ORDER_ID; From c79a3694e4ba9b550b46e5259a1f1c2a4e11f923 Mon Sep 17 00:00:00 2001 From: mandan2 Date: Mon, 11 Sep 2023 11:35:15 +0300 Subject: [PATCH 8/9] stan fix --- src/Handler/ErrorHandler/ErrorHandler.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Handler/ErrorHandler/ErrorHandler.php b/src/Handler/ErrorHandler/ErrorHandler.php index ff701502c..e5c51bd69 100644 --- a/src/Handler/ErrorHandler/ErrorHandler.php +++ b/src/Handler/ErrorHandler/ErrorHandler.php @@ -13,7 +13,6 @@ namespace Mollie\Handler\ErrorHandler; use Configuration; -use Exception; use Mollie; use Mollie\Config\Config; use Mollie\Config\Env; @@ -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); From 1e48bb84bbdb1b793ceaaa139a68c20c3401dad9 Mon Sep 17 00:00:00 2001 From: mandan2 Date: Mon, 11 Sep 2023 12:02:13 +0300 Subject: [PATCH 9/9] reduced redundant code --- .../Factory/CreateSubscriptionDataFactory.php | 22 ++----------------- .../Handler/SubscriptionCreationHandler.php | 6 ++--- .../Factory/TestCreateSubscriptionData.php | 7 +++++- tests/Unit/Factory/SubscriptionDataTest.php | 20 ++++++----------- 4 files changed, 18 insertions(+), 37 deletions(-) diff --git a/subscription/Factory/CreateSubscriptionDataFactory.php b/subscription/Factory/CreateSubscriptionDataFactory.php index 16aea2474..109774f7b 100644 --- a/subscription/Factory/CreateSubscriptionDataFactory.php +++ b/subscription/Factory/CreateSubscriptionDataFactory.php @@ -14,7 +14,6 @@ use Mollie\Subscription\Provider\SubscriptionIntervalProvider; use Mollie\Subscription\Repository\CombinationRepository; use Mollie\Subscription\Repository\CurrencyRepository as CurrencyAdapter; -use Mollie\Subscription\Validator\SubscriptionProductValidator; use Mollie\Utility\SecureKeyUtility; use Order; @@ -41,8 +40,6 @@ class CreateSubscriptionDataFactory private $link; /** @var Mollie */ private $module; - /** @var SubscriptionProductValidator */ - private $subscriptionProductValidator; public function __construct( MolCustomerRepository $customerRepository, @@ -52,8 +49,7 @@ public function __construct( CombinationRepository $combination, PaymentMethodRepositoryInterface $methodRepository, Link $link, - Mollie $module, - SubscriptionProductValidator $subscriptionProductValidator + Mollie $module ) { $this->customerRepository = $customerRepository; $this->subscriptionInterval = $subscriptionInterval; @@ -63,29 +59,15 @@ public function __construct( $this->methodRepository = $methodRepository; $this->link = $link; $this->module = $module; - $this->subscriptionProductValidator = $subscriptionProductValidator; } - 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(); - $subscriptionProduct = []; - - foreach ($products as $product) { - if (!$this->subscriptionProductValidator->validate((int) $product['id_product_attribute'])) { - continue; - } - - $subscriptionProduct = $product; - - break; - } - $combination = $this->combination->getById((int) $subscriptionProduct['id_product_attribute']); $interval = $this->subscriptionInterval->getSubscriptionInterval($combination); diff --git a/subscription/Handler/SubscriptionCreationHandler.php b/subscription/Handler/SubscriptionCreationHandler.php index 8354c39e3..87f5f8d6a 100644 --- a/subscription/Handler/SubscriptionCreationHandler.php +++ b/subscription/Handler/SubscriptionCreationHandler.php @@ -40,9 +40,6 @@ public function __construct( public function handle(Order $order, string $method) { - $subscriptionData = $this->createSubscriptionDataFactory->build($order); - $subscription = $this->subscriptionApi->subscribeOrder($subscriptionData); - $products = $order->getProducts(); $subscriptionProduct = []; @@ -56,6 +53,9 @@ public function handle(Order $order, string $method) break; } + $subscriptionData = $this->createSubscriptionDataFactory->build($order, $subscriptionProduct); + $subscription = $this->subscriptionApi->subscribeOrder($subscriptionData); + $recurringOrdersProduct = $this->createRecurringOrdersProduct($subscriptionProduct); $this->createRecurringOrder($recurringOrdersProduct, $order, $subscription, $method); diff --git a/tests/Integration/Subscription/Factory/TestCreateSubscriptionData.php b/tests/Integration/Subscription/Factory/TestCreateSubscriptionData.php index c70d746c7..a3f3b0a2f 100644 --- a/tests/Integration/Subscription/Factory/TestCreateSubscriptionData.php +++ b/tests/Integration/Subscription/Factory/TestCreateSubscriptionData.php @@ -103,7 +103,12 @@ public function testBuild() ] ); - $subscriptionData = $createSubscriptionData->build($orderMock); + $subscriptionProduct = [ + 'id_product_attribute' => 999, + 'total_price_tax_incl' => 19.99, + ]; + + $subscriptionData = $createSubscriptionData->build($orderMock, $subscriptionProduct); $this->assertEquals(self::CUSTOMER_ID, $subscriptionData->getCustomerId()); $this->assertEquals( diff --git a/tests/Unit/Factory/SubscriptionDataTest.php b/tests/Unit/Factory/SubscriptionDataTest.php index cbfbf74da..edbe8e30c 100644 --- a/tests/Unit/Factory/SubscriptionDataTest.php +++ b/tests/Unit/Factory/SubscriptionDataTest.php @@ -17,7 +17,6 @@ use Mollie\Subscription\Provider\SubscriptionIntervalProvider; use Mollie\Subscription\Repository\CombinationRepository; use Mollie\Subscription\Repository\CurrencyRepository; -use Mollie\Subscription\Validator\SubscriptionProductValidator; use Mollie\Utility\SecureKeyUtility; use PHPUnit\Framework\TestCase; @@ -59,9 +58,6 @@ public function testBuildSubscriptionData(string $customerId, float $totalAmount ] ); - $subscriptionProductValidator = $this->createMock(SubscriptionProductValidator::class); - $subscriptionProductValidator->method('validate')->willReturn(true); - $subscriptionDataFactory = new CreateSubscriptionDataFactory( $customerRepositoryMock, $subscriptionIntervalProviderMock, @@ -70,8 +66,7 @@ public function testBuildSubscriptionData(string $customerId, float $totalAmount new CombinationRepository(), $paymentMethodRepositoryMock, new Link(), - new Mollie(), - $subscriptionProductValidator + new Mollie() ); $customerMock = $this->createMock('Customer'); @@ -79,12 +74,6 @@ public function testBuildSubscriptionData(string $customerId, float $totalAmount $order = $this->createMock('Order'); $order->method('getCustomer')->willReturn($customerMock); - $order->method('getCartProducts')->willReturn([ - [ - 'id_product_attribute' => 1, - 'total_price_tax_incl' => 19.99, - ], - ]); $order->id = self::TEST_ORDER_ID; $order->reference = self::TEST_ORDER_REFERENCE; $order->id_cart = self::TEST_CART_ID; @@ -92,7 +81,12 @@ public function testBuildSubscriptionData(string $customerId, float $totalAmount $order->id_currency = 1; $order->total_paid_tax_incl = $totalAmount; - $subscriptionData = $subscriptionDataFactory->build($order); + $subscriptionProduct = [ + 'id_product_attribute' => 1, + 'total_price_tax_incl' => 19.99, + ]; + + $subscriptionData = $subscriptionDataFactory->build($order, $subscriptionProduct); $this->assertEquals($expectedResult, $subscriptionData); }