/** * {@inheritDoc} * * @param int $cartId The cart ID. * @return Totals Quote totals data. */ public function get($cartId) { /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); if ($quote->isVirtual()) { $addressTotalsData = $quote->getBillingAddress()->getData(); $addressTotals = $quote->getBillingAddress()->getTotals(); } else { $addressTotalsData = $quote->getShippingAddress()->getData(); $addressTotals = $quote->getShippingAddress()->getTotals(); } /** @var \Magento\Quote\Api\Data\TotalsInterface $quoteTotals */ $quoteTotals = $this->totalsFactory->create(); $this->dataObjectHelper->populateWithArray($quoteTotals, $addressTotalsData, '\\Magento\\Quote\\Api\\Data\\TotalsInterface'); $items = []; foreach ($quote->getAllVisibleItems() as $index => $item) { $items[$index] = $this->itemConverter->modelToDataObject($item); } $calculatedTotals = $this->totalsConverter->process($addressTotals); $quoteTotals->setTotalSegments($calculatedTotals); $amount = $quoteTotals->getGrandTotal() - $quoteTotals->getTaxAmount(); $amount = $amount > 0 ? $amount : 0; $quoteTotals->setCouponCode($this->couponService->get($cartId)); $quoteTotals->setGrandTotal($amount); $quoteTotals->setItems($items); $quoteTotals->setItemsQty($quote->getItemsQty()); $quoteTotals->setBaseCurrencyCode($quote->getBaseCurrencyCode()); $quoteTotals->setQuoteCurrencyCode($quote->getQuoteCurrencyCode()); return $quoteTotals; }
/** * {@inheritDoc} */ public function savePaymentInformation($cartId, $email, \Magento\Quote\Api\Data\PaymentInterface $paymentMethod, \Magento\Quote\Api\Data\AddressInterface $billingAddress = null) { if ($billingAddress) { $billingAddress->setEmail($email); $this->billingAddressManagement->assign($cartId, $billingAddress); } else { $quoteIdMask = $this->quoteIdMaskFactory->create()->load($cartId, 'masked_id'); $this->cartRepository->getActive($quoteIdMask->getQuoteId())->getBillingAddress()->setEmail($email); } $this->paymentMethodManagement->set($cartId, $paymentMethod); return true; }
/** * {@inheritdoc} */ public function placeOrder($cartId, PaymentInterface $paymentMethod = null) { $quote = $this->quoteRepository->getActive($cartId); if ($paymentMethod) { $paymentMethod->setChecks([\Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_CHECKOUT, \Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_FOR_COUNTRY, \Magento\Payment\Model\Method\AbstractMethod::CHECK_USE_FOR_CURRENCY, \Magento\Payment\Model\Method\AbstractMethod::CHECK_ORDER_TOTAL_MIN_MAX, \Magento\Payment\Model\Method\AbstractMethod::CHECK_ZERO_TOTAL]); $quote->getPayment()->setQuote($quote); $data = $paymentMethod->getData(); $quote->getPayment()->importData($data); } if ($quote->getCheckoutMethod() === self::METHOD_GUEST) { $quote->setCustomerId(null); $quote->setCustomerEmail($quote->getBillingAddress()->getEmail()); $quote->setCustomerIsGuest(true); $quote->setCustomerGroupId(\Magento\Customer\Api\Data\GroupInterface::NOT_LOGGED_IN_ID); } $this->eventManager->dispatch('checkout_submit_before', ['quote' => $quote]); $order = $this->submit($quote); if (null == $order) { throw new LocalizedException(__('Unable to place order. Please try again later.')); } $this->checkoutSession->setLastQuoteId($quote->getId()); $this->checkoutSession->setLastSuccessQuoteId($quote->getId()); $this->checkoutSession->setLastOrderId($order->getId()); $this->checkoutSession->setLastRealOrderId($order->getIncrementId()); $this->checkoutSession->setLastOrderStatus($order->getStatus()); $this->eventManager->dispatch('checkout_submit_all_after', ['order' => $order, 'quote' => $quote]); return $order->getId(); }
/** * {@inheritDoc} */ public function saveAddressInformation($cartId, \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation) { $address = $addressInformation->getShippingAddress(); $billingAddress = $addressInformation->getBillingAddress(); $carrierCode = $addressInformation->getShippingCarrierCode(); $methodCode = $addressInformation->getShippingMethodCode(); if (!$address->getCountryId()) { throw new StateException(__('Shipping address is not set')); } /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); $quote = $this->prepareShippingAssignment($quote, $address, $carrierCode . '_' . $methodCode); $this->validateQuote($quote); $quote->setIsMultiShipping(false); if ($billingAddress) { $quote->setBillingAddress($billingAddress); } try { $this->quoteRepository->save($quote); } catch (\Exception $e) { $this->logger->critical($e); throw new InputException(__('Unable to save shipping information. Please check input data.')); } $shippingAddress = $quote->getShippingAddress(); if (!$shippingAddress->getShippingRateByCode($shippingAddress->getShippingMethod())) { throw new NoSuchEntityException(__('Carrier with such method not found: %1, %2', $carrierCode, $methodCode)); } /** @var \Magento\Checkout\Api\Data\PaymentDetailsInterface $paymentDetails */ $paymentDetails = $this->paymentDetailsFactory->create(); $paymentDetails->setPaymentMethods($this->paymentMethodManagement->getList($cartId)); $paymentDetails->setTotals($this->cartTotalsRepository->get($cartId)); return $paymentDetails; }
/** * {@inheritDoc} */ public function getPaymentMethods($quoteId, $country = null) { // get quote from quoteId $quote = $this->_quoteRepository->getActive($quoteId); $store = $quote->getStore(); $paymentMethods = $this->_addHppMethodsToConfig($store, $country); return $paymentMethods; }
/** * {@inheritDoc} * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function saveAddressInformation($cartId, \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation) { $address = $addressInformation->getShippingAddress(); $carrierCode = $addressInformation->getShippingCarrierCode(); $methodCode = $addressInformation->getShippingMethodCode(); /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); $this->validateQuote($quote); $quote->setIsMultiShipping(false); $saveInAddressBook = $address->getSaveInAddressBook() ? 1 : 0; $sameAsBilling = $address->getSameAsBilling() ? 1 : 0; $customerAddressId = $address->getCustomerAddressId(); $this->addressValidator->validate($address); $quote->setShippingAddress($address); $address = $quote->getShippingAddress(); if ($customerAddressId) { $addressData = $this->addressRepository->getById($customerAddressId); $address = $quote->getShippingAddress()->importCustomerAddressData($addressData); } $billingAddress = $addressInformation->getBillingAddress(); if ($billingAddress) { $quote->setBillingAddress($billingAddress); } $address->setSaveInAddressBook($saveInAddressBook); $address->setSameAsBilling($sameAsBilling); $address->setCollectShippingRates(true); if (!$address->getCountryId()) { throw new StateException(__('Shipping address is not set')); } $address->setShippingMethod($carrierCode . '_' . $methodCode); try { $this->totalsCollector->collectAddressTotals($quote, $address); } catch (\Exception $e) { $this->logger->critical($e); throw new InputException(__('Unable to save address. Please check input data.')); } if (!$address->getShippingRateByCode($address->getShippingMethod())) { throw new NoSuchEntityException(__('Carrier with such method not found: %1, %2', $carrierCode, $methodCode)); } if (!$quote->validateMinimumAmount($quote->getIsMultiShipping())) { throw new InputException($this->scopeConfig->getValue('sales/minimum_order/error_message', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $quote->getStoreId())); } try { $address->save(); $quote->collectTotals(); $this->quoteRepository->save($quote); } catch (\Exception $e) { $this->logger->critical($e); throw new InputException(__('Unable to save shipping information. Please check input data.')); } /** @var \Magento\Checkout\Api\Data\PaymentDetailsInterface $paymentDetails */ $paymentDetails = $this->paymentDetailsFactory->create(); $paymentDetails->setPaymentMethods($this->paymentMethodManagement->getList($cartId)); $paymentDetails->setTotals($this->cartTotalsRepository->get($cartId)); return $paymentDetails; }
/** * {@inheritdoc} */ public function remove($cartId) { /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); if (!$quote->getItemsCount()) { throw new NoSuchEntityException(__('Cart %1 doesn\'t contain products', $cartId)); } $quote->getShippingAddress()->setCollectShippingRates(true); try { $quote->setCouponCode(''); $this->quoteRepository->save($quote->collectTotals()); } catch (\Exception $e) { throw new CouldNotDeleteException(__('Could not delete coupon code')); } if ($quote->getCouponCode() != '') { throw new CouldNotDeleteException(__('Could not delete coupon code')); } return true; }
/** * {@inheritDoc} */ public function get($cartId) { /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); if ($quote->isVirtual()) { throw new NoSuchEntityException(__('Cart contains virtual product(s) only. Shipping address is not applicable.')); } /** @var \Magento\Quote\Model\Quote\Address $address */ return $quote->getShippingAddress(); }
/** * {@inheritDoc} */ public function estimateByAddressId($cartId, $addressId) { /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); // no methods applicable for empty carts or carts with virtual products if ($quote->isVirtual() || 0 == $quote->getItemsCount()) { return []; } $address = $this->addressRepository->getById($addressId); return $this->getEstimatedRates($quote, $address->getCountryId(), $address->getPostcode(), $address->getRegionId(), $address->getRegion()); }
/** * {@inheritDoc} */ public function save($cartId, \Magento\GiftMessage\Api\Data\MessageInterface $giftMessage) { /** * Quote. * * @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); if (0 == $quote->getItemsCount()) { throw new InputException(__('Gift Messages is not applicable for empty cart')); } if ($quote->isVirtual()) { throw new InvalidTransitionException(__('Gift Messages is not applicable for virtual products')); } $messageText = $giftMessage->getMessage(); if ($messageText && !$this->helper->isMessagesAllowed('quote', $quote, $this->storeManager->getStore())) { throw new CouldNotSaveException(__('Gift Message is not available')); } $this->giftMessageManager->setMessage($quote, 'quote', $giftMessage); return true; }
public function testGetActiveWithSharedStoreIds() { $cartId = 16; $sharedStoreIds = [1, 2]; $this->quoteFactoryMock->expects($this->once())->method('create')->willReturn($this->quoteMock); $this->storeManagerMock->expects($this->once())->method('getStore')->willReturn($this->storeMock); $this->storeMock->expects($this->once())->method('getId')->willReturn(1); $this->quoteMock->expects($this->once())->method('setSharedStoreIds')->with($sharedStoreIds)->willReturnSelf(); $this->quoteMock->expects($this->once())->method('load')->with($cartId)->willReturn($this->storeMock); $this->quoteMock->expects($this->once())->method('getId')->willReturn($cartId); $this->quoteMock->expects($this->exactly(2))->method('getIsActive')->willReturn(1); $this->assertEquals($this->quoteMock, $this->model->getActive($cartId, $sharedStoreIds)); $this->assertEquals($this->quoteMock, $this->model->getActive($cartId, $sharedStoreIds)); }
protected function saveShippingAddress($cartId) { $quote = $this->quoteRepository->getActive($cartId); $address = $quote->getShippingAddress(); $region = $address->getRegion(); if (!is_null($region) && $region instanceof \Magento\Customer\Model\Data\Region) { $regionString = $region->getRegion(); $address->setRegion($regionString); } try { $address->save(); } catch (\Exception $e) { $this->shipperLogger->postCritical('Shipperhq_Shipper', 'Exception raised whilst saving shipping address', $e->getMessage()); } }
/** *Set additional information for shipping address * * @param \Magento\Checkout\Model\ShippingInformationManagement $subject * @param callable $proceed * * @return \Magento\Checkout\Api\Data\PaymentDetailsInterface $paymentDetails * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function aroundSaveAddressInformation(\Magento\Checkout\Model\ShippingInformationManagement $subject, $proceed, $cartId, \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation) { try { $carrierCode = $addressInformation->getShippingCarrierCode(); $methodCode = $addressInformation->getShippingMethodCode(); $shippingMethod = $carrierCode . '_' . $methodCode; $quote = $this->quoteRepository->getActive($cartId); $address = $quote->getShippingAddress(); $validation = $this->checkoutSession->getShipAddressValidation(); if (is_array($validation) && isset($validation['key'])) { if (isset($validation['validation_status'])) { $additionalDetail['address_valid'] = $validation['validation_status']; $address->setValidationStatus($validation['validation_status']); } if (isset($validation['destination_type'])) { $additionalDetail['destination_type'] = $validation['destination_type']; $address->setDestinationType($validation['destination_type']); } $this->checkoutSession->setShipAddressValidation(null); } $address->save(); $additionalDetail = new \Magento\Framework\DataObject(); $extAttributes = $addressInformation->getShippingAddress()->getExtensionAttributes(); //push out event so other modules can save their data TODO add carrier_group_id $this->eventManager->dispatch('shipperhq_additional_detail_checkout', ['address_extn_attributes' => $extAttributes, 'additional_detail' => $additionalDetail, 'carrier_code' => $carrierCode]); $additionalDetailArray = $additionalDetail->convertToArray(); $this->shipperLogger->postDebug('ShipperHQ Shipper', 'processing additional detail ', $additionalDetail); $this->carrierGroupHelper->saveCarrierGroupInformation($address, $shippingMethod, $additionalDetailArray); } catch (\Exception $e) { $this->shipperLogger->postCritical('Shipperhq_Shipper', 'Shipping Information Plugin', 'Exception raised ' . $e->getMessage()); } $result = $proceed($cartId, $addressInformation); if ($address->getCustomerId()) { $customerAddresses = $quote->getCustomer()->getAddresses(); foreach ($customerAddresses as $oneAddress) { if ($oneAddress->getId() == $address->getCustomerAddressId()) { if ($address->getValidationStatus()) { $oneAddress->setCustomAttribute('validation_status', $address->getValidationStatus()); } if ($address->getDestinationType()) { $oneAddress->setCustomAttribute('destination_type', $address->getDestinationType()); } $this->addressRepository->save($oneAddress); } } } return $result; }
/** * {@inheritdoc} */ public function deleteById($cartId, $itemId) { /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); $quoteItem = $quote->getItemById($itemId); if (!$quoteItem) { throw new NoSuchEntityException(__('Cart %1 doesn\'t contain item %2', $cartId, $itemId)); } try { $quote->removeItem($itemId); $this->quoteRepository->save($quote->collectTotals()); } catch (\Exception $e) { throw new CouldNotSaveException(__('Could not remove item from quote')); } return true; }
/** * {@inheritDoc} */ public function save($cartId, \Magento\GiftMessage\Api\Data\MessageInterface $giftMessage, $itemId) { /** * Quote. * * @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); if (!($item = $quote->getItemById($itemId))) { throw new NoSuchEntityException(__('There is no product with provided itemId: %1 in the cart', $itemId)); } if ($item->getIsVirtual()) { throw new InvalidTransitionException(__('Gift Messages is not applicable for virtual products')); } $messageText = $giftMessage->getMessage(); if ($messageText && !$this->helper->isMessagesAllowed('items', $quote, $this->storeManager->getStore())) { throw new CouldNotSaveException(__('Gift Message is not available')); } $this->giftMessageManager->setMessage($quote, 'quote_item', $giftMessage, $itemId); return true; }
public function aroundSaveAddressInformation(\Magento\Checkout\Model\ShippingInformationManagement $subject, \Closure $proceed, $cartId, ShippingInformationInterface $addressInformation) { // Only validate address if module is enabled $quote = $this->quoteRepository->getActive($cartId); $storeId = $quote->getStoreId(); if (!$this->config->isModuleEnabled($storeId)) { $paymentDetails = $proceed($cartId, $addressInformation); $this->ensureTaxCalculationSuccess($storeId); return $paymentDetails; } // Only validate address if address validation is enabled if (!$this->config->isAddressValidationEnabled($storeId)) { $paymentDetails = $proceed($cartId, $addressInformation); $this->ensureTaxCalculationSuccess($storeId); return $paymentDetails; } // If quote is virtual, getShippingAddress will return billing address, so no need to check if quote is virtual $shippingAddress = $addressInformation->getShippingAddress(); $shippingInformationExtension = $addressInformation->getExtensionAttributes(); $errorMessage = null; $validAddress = null; $customerAddress = null; $quoteAddress = null; $shouldValidateAddress = true; if (!is_null($shippingInformationExtension)) { $shouldValidateAddress = $shippingInformationExtension->getShouldValidateAddress(); } $customerAddressId = $shippingAddress->getCustomerAddressId(); $enabledAddressValidationCountries = explode(',', $this->config->getAddressValidationCountriesEnabled($storeId)); if (!in_array($shippingAddress->getCountryId(), $enabledAddressValidationCountries)) { $shouldValidateAddress = false; } if ($shouldValidateAddress) { try { $validAddress = $this->validationInteraction->validateAddress($shippingAddress, $storeId); } catch (AddressValidateException $e) { $errorMessage = $e->getMessage(); } catch (\SoapFault $e) { // If there is a SoapFault, it will have already been logged, so just disable address validation, as we // don't want to display SoapFault error message to user $shouldValidateAddress = false; } catch (\Exception $e) { $this->avaTaxLogger->error('Error in validating address in aroundSaveAddressInformation: ' . $e->getMessage()); // Continue without address validation $shouldValidateAddress = false; } } // Determine which address to save to the customer or shipping addresses if (!is_null($validAddress)) { $quoteAddress = $validAddress; } else { $quoteAddress = $shippingAddress; } try { /* * Regardless of whether address was validated by AvaTax, if the address is a customer address then we need * to save that address on the customer record. The reason for this is that when a user is on the "Review * & Payments" step and they are selecting between "Valid" and "Original" address options, the selected * address information is submitted to this API so that the customer address is updated and tax * calculation is affected accordingly. */ if ($customerAddressId) { // Update the customer address $customerAddress = $this->customerAddressRepository->getById($customerAddressId); $mergedCustomerAddress = $this->addressInteraction->copyQuoteAddressToCustomerAddress($quoteAddress, $customerAddress); $this->customerAddressRepository->save($mergedCustomerAddress); } else { // Update the shipping address $addressInformation->setShippingAddress($quoteAddress); } } catch (\Exception $e) { // There may be scenarios in which the above address updating may fail, in which case we should just do // nothing $this->avaTaxLogger->error('Error in saving address: ' . $e->getMessage()); // Continue without address validation $shouldValidateAddress = false; } $returnValue = $proceed($cartId, $addressInformation); $this->ensureTaxCalculationSuccess($storeId); if (!$shouldValidateAddress) { return $returnValue; } $paymentDetailsExtension = $returnValue->getExtensionAttributes(); if (is_null($paymentDetailsExtension)) { $paymentDetailsExtension = $this->paymentDetailsExtensionFactory->create(); } if (!is_null($validAddress)) { $paymentDetailsExtension->setValidAddress($validAddress); } else { $paymentDetailsExtension->setErrorMessage($errorMessage); } $paymentDetailsExtension->setOriginalAddress($shippingAddress); $returnValue->setExtensionAttributes($paymentDetailsExtension); return $returnValue; }
/** * {@inheritDoc} */ public function get($cartId) { $cart = $this->quoteRepository->getActive($cartId); return $cart->getBillingAddress(); }
/** * Get checkout quote instance by current session * * @return Quote * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function getQuote() { $this->_eventManager->dispatch('custom_quote_process', ['checkout_session' => $this]); if ($this->_quote === null) { $quote = $this->quoteFactory->create(); if ($this->getQuoteId()) { try { if ($this->_loadInactive) { $quote = $this->quoteRepository->get($this->getQuoteId()); } else { $quote = $this->quoteRepository->getActive($this->getQuoteId()); } /** * If current currency code of quote is not equal current currency code of store, * need recalculate totals of quote. It is possible if customer use currency switcher or * store switcher. */ if ($quote->getQuoteCurrencyCode() != $this->_storeManager->getStore()->getCurrentCurrencyCode()) { $quote->setStore($this->_storeManager->getStore()); $this->quoteRepository->save($quote->collectTotals()); /* * We mast to create new quote object, because collectTotals() * can to create links with other objects. */ $quote = $this->quoteRepository->get($this->getQuoteId()); } } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { $this->setQuoteId(null); } } if (!$this->getQuoteId()) { if ($this->_customerSession->isLoggedIn() || $this->_customer) { $customerId = $this->_customer ? $this->_customer->getId() : $this->_customerSession->getCustomerId(); try { $quote = $this->quoteRepository->getActiveForCustomer($customerId); $this->setQuoteId($quote->getId()); } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { } } else { $quote->setIsCheckoutCart(true); $this->_eventManager->dispatch('checkout_quote_init', ['quote' => $quote]); } } if ($this->_customer) { $quote->setCustomer($this->_customer); } elseif ($this->_customerSession->isLoggedIn()) { $quote->setCustomer($this->customerRepository->getById($this->_customerSession->getCustomerId())); } $quote->setStore($this->_storeManager->getStore()); $this->_quote = $quote; } if (!$this->isQuoteMasked() && !$this->_customerSession->isLoggedIn() && $this->getQuoteId()) { $quoteId = $this->getQuoteId(); /** @var $quoteIdMask \Magento\Quote\Model\QuoteIdMask */ $quoteIdMask = $this->quoteIdMaskFactory->create()->load($quoteId, 'quote_id'); if ($quoteIdMask->getMaskedId() === null) { $quoteIdMask->setQuoteId($quoteId)->save(); } $this->setIsQuoteMasked(true); } $remoteAddress = $this->_remoteAddress->getRemoteAddress(); if ($remoteAddress) { $this->_quote->setRemoteIp($remoteAddress); $xForwardIp = $this->request->getServer('HTTP_X_FORWARDED_FOR'); $this->_quote->setXForwardedFor($xForwardIp); } return $this->_quote; }