Пример #1
0
 /**
  * Initialize coupon
  *
  * @return \Magento\Framework\Controller\Result\Redirect
  * @throws \Magento\Framework\Exception\LocalizedException|\Exception
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function execute()
 {
     /**
      * No reason continue with empty shopping cart
      */
     if (!$this->cart->getQuote()->getItemsCount()) {
         return $this->_goBack();
     }
     $couponCode = $this->getRequest()->getParam('remove') == 1 ? '' : trim($this->getRequest()->getParam('coupon_code'));
     $oldCouponCode = $this->cart->getQuote()->getCouponCode();
     if (!strlen($couponCode) && !strlen($oldCouponCode)) {
         return $this->_goBack();
     }
     $codeLength = strlen($couponCode);
     $isCodeLengthValid = $codeLength && $codeLength <= \Magento\Checkout\Helper\Cart::COUPON_CODE_MAX_LENGTH;
     $this->cart->getQuote()->getShippingAddress()->setCollectShippingRates(true);
     $this->cart->getQuote()->setCouponCode($isCodeLengthValid ? $couponCode : '')->collectTotals();
     $this->quoteRepository->save($this->cart->getQuote());
     if ($codeLength) {
         if ($isCodeLengthValid && $couponCode == $this->cart->getQuote()->getCouponCode()) {
             $this->messageManager->addSuccess(__('The coupon code "%1" was applied.', $this->_objectManager->get('Magento\\Framework\\Escaper')->escapeHtml($couponCode)));
         } else {
             $this->messageManager->addError(__('The coupon code "%1" is not valid.', $this->_objectManager->get('Magento\\Framework\\Escaper')->escapeHtml($couponCode)));
             $this->cart->save();
         }
     } else {
         $this->messageManager->addSuccess(__('The coupon code was canceled.'));
     }
     return $this->_goBack();
 }
Пример #2
0
 /**
  * Set new customer group to all his quotes
  *
  * @param Observer $observer
  * @return void
  */
 public function dispatch(Observer $observer)
 {
     /** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
     $customer = $observer->getEvent()->getCustomerDataObject();
     /** @var \Magento\Customer\Api\Data\CustomerInterface $origCustomer */
     $origCustomer = $observer->getEvent()->getOrigCustomerDataObject();
     if ($customer->getGroupId() !== $origCustomer->getGroupId()) {
         /**
          * It is needed to process customer's quotes for all websites
          * if customer accounts are shared between all of them
          */
         /** @var $websites \Magento\Store\Model\Website[] */
         $websites = $this->config->isWebsiteScope() ? [$this->storeManager->getWebsite($customer->getWebsiteId())] : $this->storeManager->getWebsites();
         foreach ($websites as $website) {
             try {
                 $quote = $this->quoteRepository->getForCustomer($customer->getId());
                 $quote->setWebsite($website);
                 $quote->setCustomerGroupId($customer->getGroupId());
                 $quote->collectTotals();
                 $this->quoteRepository->save($quote);
             } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
             }
         }
     }
 }
Пример #3
0
 /**
  * Initialize shipping information
  *
  * @return \Magento\Framework\Controller\Result\Redirect
  */
 public function execute()
 {
     $country = (string) $this->getRequest()->getParam('country_id');
     $postcode = (string) $this->getRequest()->getParam('estimate_postcode');
     $city = (string) $this->getRequest()->getParam('estimate_city');
     $regionId = (string) $this->getRequest()->getParam('region_id');
     $region = (string) $this->getRequest()->getParam('region');
     $this->cart->getQuote()->getShippingAddress()->setCountryId($country)->setCity($city)->setPostcode($postcode)->setRegionId($regionId)->setRegion($region)->setCollectShippingRates(true);
     $this->quoteRepository->save($this->cart->getQuote());
     $this->cart->save();
     return $this->_goBack();
 }
Пример #4
0
 /**
  * Initialize coupon
  *
  * @return \Magento\Framework\Controller\Result\Redirect
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function execute()
 {
     $couponCode = $this->getRequest()->getParam('remove') == 1 ? '' : trim($this->getRequest()->getParam('coupon_code'));
     $cartQuote = $this->cart->getQuote();
     $oldCouponCode = $cartQuote->getCouponCode();
     $codeLength = strlen($couponCode);
     if (!$codeLength && !strlen($oldCouponCode)) {
         return $this->_goBack();
     }
     try {
         $isCodeLengthValid = $codeLength && $codeLength <= \Magento\Checkout\Helper\Cart::COUPON_CODE_MAX_LENGTH;
         $itemsCount = $cartQuote->getItemsCount();
         if ($itemsCount) {
             $cartQuote->getShippingAddress()->setCollectShippingRates(true);
             $cartQuote->setCouponCode($isCodeLengthValid ? $couponCode : '')->collectTotals();
             $this->quoteRepository->save($cartQuote);
         }
         if ($codeLength) {
             $escaper = $this->_objectManager->get('Magento\\Framework\\Escaper');
             if (!$itemsCount) {
                 if ($isCodeLengthValid) {
                     $coupon = $this->couponFactory->create();
                     $coupon->load($couponCode, 'code');
                     if ($coupon->getId()) {
                         $this->_checkoutSession->getQuote()->setCouponCode($couponCode)->save();
                         $this->messageManager->addSuccess(__('You used coupon code "%1".', $escaper->escapeHtml($couponCode)));
                     } else {
                         $this->messageManager->addError(__('The coupon code "%1" is not valid.', $escaper->escapeHtml($couponCode)));
                     }
                 } else {
                     $this->messageManager->addError(__('The coupon code "%1" is not valid.', $escaper->escapeHtml($couponCode)));
                 }
             } else {
                 if ($isCodeLengthValid && $couponCode == $cartQuote->getCouponCode()) {
                     $this->messageManager->addSuccess(__('You used coupon code "%1".', $escaper->escapeHtml($couponCode)));
                 } else {
                     $this->messageManager->addError(__('The coupon code "%1" is not valid.', $escaper->escapeHtml($couponCode)));
                     $this->cart->save();
                 }
             }
         } else {
             $this->messageManager->addSuccess(__('You canceled the coupon code.'));
         }
     } catch (\Magento\Framework\Exception\LocalizedException $e) {
         $this->messageManager->addError($e->getMessage());
     } catch (\Exception $e) {
         $this->messageManager->addError(__('We cannot apply the coupon code.'));
         $this->_objectManager->get('Psr\\Log\\LoggerInterface')->critical($e);
     }
     return $this->_goBack();
 }
 /**
  * {@inheritDoc}
  */
 public function assign($cartId, \Magento\Quote\Api\Data\AddressInterface $address)
 {
     $quote = $this->quoteRepository->getActive($cartId);
     $this->addressValidator->validate($address);
     $quote->setBillingAddress($address);
     $quote->setDataChanges(true);
     try {
         $this->quoteRepository->save($quote);
     } catch (\Exception $e) {
         $this->logger->critical($e);
         throw new InputException(__('Unable to save address. Please, check input data.'));
     }
     return $quote->getBillingAddress()->getId();
 }
 public function testSave()
 {
     $this->quoteMock->expects($this->once())->method('save');
     $this->quoteMock->expects($this->exactly(1))->method('getId')->willReturn(1);
     $this->quoteMock->expects($this->exactly(1))->method('getCustomerId')->willReturn(2);
     $this->model->save($this->quoteMock);
 }
Пример #7
0
 /**
  * {@inheritDoc}
  *
  * @param int $cartId The shopping cart ID.
  * @param string $carrierCode The carrier code.
  * @param string $methodCode The shipping method code.
  * @return bool
  * @throws \Magento\Framework\Exception\InputException The shipping method is not valid for an empty cart.
  * @throws \Magento\Framework\Exception\CouldNotSaveException The shipping method could not be saved.
  * @throws \Magento\Framework\Exception\NoSuchEntityException The specified cart contains only virtual products and the shipping method is not applicable.
  * @throws \Magento\Framework\Exception\StateException The billing or shipping address is not set.
  */
 public function set($cartId, $carrierCode, $methodCode)
 {
     /** @var \Magento\Quote\Model\Quote $quote */
     $quote = $this->quoteRepository->getActive($cartId);
     if (0 == $quote->getItemsCount()) {
         throw new InputException(__('Shipping method is not applicable for empty cart'));
     }
     if ($quote->isVirtual()) {
         throw new NoSuchEntityException(__('Cart contains virtual product(s) only. Shipping method is not applicable.'));
     }
     $shippingAddress = $quote->getShippingAddress();
     if (!$shippingAddress->getCountryId()) {
         throw new StateException(__('Shipping address is not set'));
     }
     $shippingAddress->setShippingMethod($carrierCode . '_' . $methodCode);
     if (!$shippingAddress->getShippingRateByCode($shippingAddress->getShippingMethod())) {
         throw new NoSuchEntityException(__('Carrier with such method not found: %1, %2', $carrierCode, $methodCode));
     }
     try {
         $this->quoteRepository->save($quote->collectTotals());
     } catch (\Exception $e) {
         throw new CouldNotSaveException(__('Cannot set shipping method. %1', $e->getMessage()));
     }
     return true;
 }
 /**
  * {@inheritDoc}
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 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);
     if ($quote->isVirtual()) {
         throw new NoSuchEntityException(__('Cart contains virtual product(s) only. Shipping address is not applicable.'));
     }
     if (0 == $quote->getItemsCount()) {
         throw new InputException(__('Shipping method is not applicable for empty cart'));
     }
     $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);
     }
     $address->setSameAsBilling($sameAsBilling);
     $address->setSaveInAddressBook($saveInAddressBook);
     $address->setCollectShippingRates(true);
     if (!$address->getCountryId()) {
         throw new StateException(__('Shipping address is not set'));
     }
     $address->setShippingMethod($carrierCode . '_' . $methodCode);
     try {
         $address->save();
         $address->collectTotals();
     } 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;
 }
Пример #9
0
 /**
  * {@inheritdoc}
  */
 public function save(\Magento\Quote\Api\Data\CartInterface $quote)
 {
     $pluginInfo = $this->pluginList->getNext($this->subjectType, 'save');
     if (!$pluginInfo) {
         return parent::save($quote);
     } else {
         return $this->___callPlugins('save', func_get_args(), $pluginInfo);
     }
 }
Пример #10
0
 /**
  * @param \Magento\Quote\Model\Quote $quote
  * @return void
  */
 public function collect(\Magento\Quote\Model\Quote $quote)
 {
     if ($this->customerSession->isLoggedIn()) {
         $customer = $this->customerRepository->getById($this->customerSession->getCustomerId());
         if ($defaultShipping = $customer->getDefaultShipping()) {
             $address = $this->addressRepository->getById($defaultShipping);
             if ($address) {
                 /** @var \Magento\Quote\Api\Data\EstimateAddressInterface $estimatedAddress */
                 $estimatedAddress = $this->estimatedAddressFactory->create();
                 $estimatedAddress->setCountryId($address->getCountryId());
                 $estimatedAddress->setPostcode($address->getPostcode());
                 $estimatedAddress->setRegion((string) $address->getRegion()->getRegion());
                 $estimatedAddress->setRegionId($address->getRegionId());
                 $this->shippingMethodManager->estimateByAddress($quote->getId(), $estimatedAddress);
                 $this->quoteRepository->save($quote);
             }
         }
     }
 }
Пример #11
0
 /**
  * {@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 assign($cartId, \Magento\Quote\Api\Data\AddressInterface $address)
 {
     /** @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.'));
     }
     $this->addressValidator->validate($address);
     $address->setSameAsBilling(0);
     $address->setCollectShippingRates(true);
     $quote->setShippingAddress($address);
     $quote->setDataChanges(true);
     try {
         $this->quoteRepository->save($quote);
     } catch (\Exception $e) {
         $this->logger->critical($e);
         throw new InputException(__('Unable to save address. Please, check input data.'));
     }
     return $quote->getShippingAddress()->getId();
 }
Пример #13
0
 /**
  * @{inheritdoc}
  */
 public function saveAddresses($cartId, \Magento\Quote\Api\Data\AddressInterface $billingAddress, \Magento\Quote\Api\Data\AddressInterface $shippingAddress = null, \Magento\Quote\Api\Data\AddressAdditionalDataInterface $additionalData = null, $checkoutMethod = null)
 {
     $this->billingAddressManagement->assign($cartId, $billingAddress);
     /** @var \Magento\Quote\Api\Data\AddressDetailsInterface  $addressDetails */
     $addressDetails = $this->addressDetailsFactory->create();
     if ($shippingAddress) {
         $this->shippingAddressManagement->assign($cartId, $shippingAddress);
         $addressDetails->setFormattedShippingAddress($this->shippingAddressManagement->get($cartId)->format('html'));
         $addressDetails->setShippingMethods($this->shippingMethodManagement->getList($cartId));
     }
     $addressDetails->setPaymentMethods($this->paymentMethodManagement->getList($cartId));
     if ($additionalData !== null) {
         $this->dataProcessor->process($additionalData);
     }
     if ($checkoutMethod != null) {
         $this->quoteRepository->save($this->quoteRepository->getActive($cartId)->setCheckoutMethod($checkoutMethod));
     }
     $addressDetails->setFormattedBillingAddress($this->billingAddressManagement->get($cartId)->format('html'));
     $addressDetails->setTotals($this->cartTotalsRepository->get($cartId));
     return $addressDetails;
 }
Пример #14
0
 /**
  * Make quote to be guest
  *
  * @param bool $checkQuote Check quote to be persistent (not stolen)
  * @return void
  */
 public function setGuest($checkQuote = false)
 {
     /** @var $quote \Magento\Quote\Model\Quote */
     $quote = $this->checkoutSession->getQuote();
     if ($quote && $quote->getId()) {
         if ($checkQuote && !$this->persistentData->isShoppingCartPersist() && !$quote->getIsPersistent()) {
             $this->checkoutSession->clearQuote()->clearStorage();
             return;
         }
         $quote->getPaymentsCollection()->walk('delete');
         $quote->getAddressesCollection()->walk('delete');
         $this->_setQuotePersistent = false;
         $quote->setIsActive(true)->setCustomerId(null)->setCustomerEmail(null)->setCustomerFirstname(null)->setCustomerLastname(null)->setCustomerGroupId(\Magento\Customer\Api\Data\GroupInterface::NOT_LOGGED_IN_ID)->setIsPersistent(false)->removeAllAddresses();
         //Create guest addresses
         $quote->getShippingAddress();
         $quote->getBillingAddress();
         $quote->collectTotals();
         $this->quoteRepository->save($quote);
     }
     $this->persistentSession->getSession()->removePersistentCookie();
 }
Пример #15
0
 /**
  * Save cart
  *
  * @return $this
  */
 public function save()
 {
     $this->_eventManager->dispatch('checkout_cart_save_before', ['cart' => $this]);
     $this->getQuote()->getBillingAddress();
     $this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
     $this->getQuote()->collectTotals();
     $this->quoteRepository->save($this->getQuote());
     $this->_checkoutSession->setQuoteId($this->getQuote()->getId());
     /**
      * Cart save usually called after changes with cart items.
      */
     $this->_eventManager->dispatch('checkout_cart_save_after', ['cart' => $this]);
     $this->reinitializeState();
     return $this;
 }
Пример #16
0
 /**
  * {@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;
 }
Пример #17
0
 /**
  * Restore last active quote
  *
  * @return bool True if quote restored successfully, false otherwise
  */
 public function restoreQuote()
 {
     /** @var \Magento\Sales\Model\Order $order */
     $order = $this->getLastRealOrder();
     if ($order->getId()) {
         try {
             $quote = $this->quoteRepository->get($order->getQuoteId());
             $quote->setIsActive(1)->setReservedOrderId(null);
             $this->quoteRepository->save($quote);
             $this->replaceQuote($quote)->unsLastRealOrderId();
             $this->_eventManager->dispatch('restore_quote', ['order' => $order, 'quote' => $quote]);
             return true;
         } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
         }
     }
     return false;
 }
Пример #18
0
 /**
  * Submit quote
  *
  * @param Quote $quote
  * @param array $orderData
  * @return \Magento\Framework\Model\AbstractExtensibleModel|\Magento\Sales\Api\Data\OrderInterface|object
  * @throws \Exception
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 protected function submitQuote(QuoteEntity $quote, $orderData = [])
 {
     $order = $this->orderFactory->create();
     $this->quoteValidator->validateBeforeSubmit($quote);
     if (!$quote->getCustomerIsGuest()) {
         if ($quote->getCustomerId()) {
             $this->_prepareCustomerQuote($quote);
         }
         $this->customerManagement->populateCustomerInfo($quote);
     }
     $addresses = [];
     $quote->reserveOrderId();
     if ($quote->isVirtual()) {
         $this->dataObjectHelper->mergeDataObjects('\\Magento\\Sales\\Api\\Data\\OrderInterface', $order, $this->quoteAddressToOrder->convert($quote->getBillingAddress(), $orderData));
     } else {
         $this->dataObjectHelper->mergeDataObjects('\\Magento\\Sales\\Api\\Data\\OrderInterface', $order, $this->quoteAddressToOrder->convert($quote->getShippingAddress(), $orderData));
         $shippingAddress = $this->quoteAddressToOrderAddress->convert($quote->getShippingAddress(), ['address_type' => 'shipping', 'email' => $quote->getCustomerEmail()]);
         $addresses[] = $shippingAddress;
         $order->setShippingAddress($shippingAddress);
     }
     $billingAddress = $this->quoteAddressToOrderAddress->convert($quote->getBillingAddress(), ['address_type' => 'billing', 'email' => $quote->getCustomerEmail()]);
     $addresses[] = $billingAddress;
     $order->setBillingAddress($billingAddress);
     $order->setAddresses($addresses);
     $order->setPayments([$this->quotePaymentToOrderPayment->convert($quote->getPayment())]);
     $order->setItems($this->resolveItems($quote));
     if ($quote->getCustomer()) {
         $order->setCustomerId($quote->getCustomer()->getId());
     }
     $order->setQuoteId($quote->getId());
     $order->setCustomerEmail($quote->getCustomerEmail());
     $order->setCustomerFirstname($quote->getCustomerFirstname());
     $order->setCustomerMiddlename($quote->getCustomerMiddlename());
     $order->setCustomerLastname($quote->getCustomerLastname());
     $this->eventManager->dispatch('sales_model_service_quote_submit_before', ['order' => $order, 'quote' => $quote]);
     try {
         $order = $this->orderManagement->place($order);
         $quote->setIsActive(false);
         $this->eventManager->dispatch('sales_model_service_quote_submit_success', ['order' => $order, 'quote' => $quote]);
         $this->quoteRepository->save($quote);
     } catch (\Exception $e) {
         $this->eventManager->dispatch('sales_model_service_quote_submit_failure', ['order' => $order, 'quote' => $quote]);
         throw $e;
     }
     return $order;
 }
Пример #19
0
 /**
  * Operate with order using information from silent post
  *
  * @param \Magento\Sales\Model\Order $order
  * @return void
  * @throws \Magento\Framework\Exception\LocalizedException
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 protected function _processOrder(\Magento\Sales\Model\Order $order)
 {
     $response = $this->getResponse();
     $payment = $order->getPayment();
     $payment->setTransactionId($response->getPnref())->setIsTransactionClosed(0);
     $canSendNewOrderEmail = true;
     if ($response->getResult() == self::RESPONSE_CODE_FRAUDSERVICE_FILTER || $response->getResult() == self::RESPONSE_CODE_DECLINED_BY_FILTER) {
         $canSendNewOrderEmail = false;
         $payment->setIsTransactionPending(true)->setIsFraudDetected(true);
         $fraudMessage = $response->getData('respmsg');
         if ($response->getData('fps_prexmldata')) {
             $xml = new \SimpleXMLElement($response->getData('fps_prexmldata'));
             $fraudMessage = (string) $xml->rule->triggeredMessage;
         }
         $payment->setAdditionalInformation(Info::PAYPAL_FRAUD_FILTERS, $fraudMessage);
     }
     if ($response->getData('avsdata') && strstr(substr($response->getData('avsdata'), 0, 2), 'N')) {
         $payment->setAdditionalInformation(Info::PAYPAL_AVS_CODE, substr($response->getData('avsdata'), 0, 2));
     }
     if ($response->getData('cvv2match') && $response->getData('cvv2match') != 'Y') {
         $payment->setAdditionalInformation(Info::PAYPAL_CVV_2_MATCH, $response->getData('cvv2match'));
     }
     switch ($response->getType()) {
         case self::TRXTYPE_AUTH_ONLY:
             $payment->registerAuthorizationNotification($payment->getBaseAmountAuthorized());
             break;
         case self::TRXTYPE_SALE:
             $payment->registerCaptureNotification($payment->getBaseAmountAuthorized());
             break;
         default:
             break;
     }
     $order->save();
     try {
         if ($canSendNewOrderEmail) {
             $this->orderSender->send($order);
         }
         $quote = $this->quoteRepository->get($order->getQuoteId())->setIsActive(false);
         $this->quoteRepository->save($quote);
     } catch (\Exception $e) {
         throw new \Magento\Framework\Exception\LocalizedException(__('We cannot send the new order email.'));
     }
 }
 /**
  * {@inheritDoc}
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function assign($cartId, \Magento\Quote\Api\Data\AddressInterface $address, $useForShipping = false)
 {
     $quote = $this->quoteRepository->getActive($cartId);
     $this->addressValidator->validate($address);
     $customerAddressId = $address->getCustomerAddressId();
     $shippingAddress = null;
     $addressData = [];
     if ($useForShipping) {
         $shippingAddress = $address;
     }
     $saveInAddressBook = $address->getSaveInAddressBook() ? 1 : 0;
     if ($customerAddressId) {
         try {
             $addressData = $this->addressRepository->getById($customerAddressId);
         } catch (NoSuchEntityException $e) {
             // do nothing if customer is not found by id
         }
         $address = $quote->getBillingAddress()->importCustomerAddressData($addressData);
         if ($useForShipping) {
             $shippingAddress = $quote->getShippingAddress()->importCustomerAddressData($addressData);
             $shippingAddress->setSaveInAddressBook($saveInAddressBook);
         }
     } elseif ($quote->getCustomerId()) {
         $address->setEmail($quote->getCustomerEmail());
     }
     $address->setSaveInAddressBook($saveInAddressBook);
     $quote->setBillingAddress($address);
     if ($useForShipping) {
         $shippingAddress->setSameAsBilling(1);
         $shippingAddress->setCollectShippingRates(true);
         $quote->setShippingAddress($shippingAddress);
     }
     $quote->setDataChanges(true);
     $quote->collectTotals();
     try {
         $this->quoteRepository->save($quote);
     } catch (\Exception $e) {
         $this->logger->critical($e);
         throw new InputException(__('Unable to save address. Please, check input data.'));
     }
     return $quote->getBillingAddress()->getId();
 }
Пример #21
0
 /**
  * {@inheritDoc}
  */
 protected function _beforeToHtml()
 {
     if ($this->_customerSession->isLoggedIn()) {
         $customer = $this->customerRepository->getById($this->_customerSession->getCustomerId());
         if ($defaultShipping = $customer->getDefaultShipping()) {
             $address = $this->addressRepository->getById($defaultShipping);
             if ($address) {
                 /** @var \Magento\Quote\Api\Data\EstimateAddressInterface $estimatedAddress */
                 $estimatedAddress = $this->estimatedAddressFactory->create();
                 $estimatedAddress->setCountryId($address->getCountryId());
                 $estimatedAddress->setPostcode($address->getPostcode());
                 $estimatedAddress->setRegion((string) $address->getRegion()->getRegion());
                 $estimatedAddress->setRegionId($address->getRegionId());
                 $this->shippingMethodManager->estimateByAddress($this->getQuote()->getId(), $estimatedAddress);
                 $this->quoteRepository->save($this->getQuote());
             }
         }
     }
     return parent::_beforeToHtml();
 }
Пример #22
0
 /**
  * Retrieve quote data
  *
  * @return array
  */
 private function getQuoteData()
 {
     $quoteData = [];
     if ($this->checkoutSession->getQuote()->getId()) {
         $quote = $this->quoteRepository->get($this->checkoutSession->getQuote()->getId());
         // the following condition is a legacy logic left here for compatibility
         if (!$quote->getCustomer()->getId()) {
             $this->quoteRepository->save($this->checkoutSession->getQuote()->setCheckoutMethod('guest'));
         } else {
             $this->quoteRepository->save($this->checkoutSession->getQuote()->setCheckoutMethod(null));
         }
         $quoteData = $quote->toArray();
         $quoteData['is_virtual'] = $quote->getIsVirtual();
         if (!$quote->getCustomer()->getId()) {
             /** @var $quoteIdMask \Magento\Quote\Model\QuoteIdMask */
             $quoteIdMask = $this->quoteIdMaskFactory->create();
             $quoteData['entity_id'] = $quoteIdMask->load($this->checkoutSession->getQuote()->getId(), 'quote_id')->getMaskedId();
         }
     }
     return $quoteData;
 }
Пример #23
0
 /**
  * Operate with order using information from Authorize.net.
  * Authorize order or authorize and capture it.
  *
  * @param \Magento\Sales\Model\Order $order
  * @return void
  * @throws \Magento\Framework\Exception\LocalizedException
  * @throws \Exception
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 protected function processOrder(\Magento\Sales\Model\Order $order)
 {
     try {
         $this->checkResponseCode();
         $this->checkTransId();
     } catch (\Exception $e) {
         //decline the order (in case of wrong response code) but don't return money to customer.
         $message = $e->getMessage();
         $this->declineOrder($order, $message, false);
         throw $e;
     }
     $response = $this->getResponse();
     //create transaction. need for void if amount will not match.
     $payment = $order->getPayment();
     $this->fillPaymentByResponse($payment);
     $payment->getMethodInstance()->setIsInitializeNeeded(false);
     $payment->getMethodInstance()->setResponseData($response->getData());
     $this->processPaymentFraudStatus($payment);
     $payment->place();
     $this->addStatusComment($payment);
     $order->save();
     //match amounts. should be equals for authorization.
     //decline the order if amount does not match.
     if (!$this->matchAmount($payment->getBaseAmountAuthorized())) {
         $message = __('Something went wrong: the paid amount doesn\'t match the order amount.' . ' Please correct this and try again.');
         $this->declineOrder($order, $message, true);
         throw new \Magento\Framework\Exception\LocalizedException($message);
     }
     try {
         if (!$response->hasOrderSendConfirmation() || $response->getOrderSendConfirmation()) {
             $this->orderSender->send($order);
         }
         $quote = $this->quoteRepository->get($order->getQuoteId())->setIsActive(false);
         $this->quoteRepository->save($quote);
     } catch (\Exception $e) {
         // do not cancel order if we couldn't send email
     }
 }
Пример #24
0
 /**
  * Retrieve quote model object
  *
  * @return \Magento\Quote\Model\Quote
  */
 public function getQuote()
 {
     if ($this->_quote === null) {
         $this->_quote = $this->quoteRepository->create();
         if ($this->getStoreId()) {
             if (!$this->getQuoteId()) {
                 $this->_quote->setCustomerGroupId($this->groupManagement->getDefaultGroup()->getId())->setIsActive(false)->setStoreId($this->getStoreId());
                 $this->quoteRepository->save($this->_quote);
                 $this->setQuoteId($this->_quote->getId());
             } else {
                 $this->_quote = $this->quoteRepository->get($this->getQuoteId(), [$this->getStoreId()]);
                 $this->_quote->setStoreId($this->getStoreId());
             }
             if ($this->getCustomerId()) {
                 $customer = $this->customerRepository->getById($this->getCustomerId());
                 $this->_quote->assignCustomer($customer);
             }
         }
         $this->_quote->setIgnoreOldQty(true);
         $this->_quote->setIsSuperMode(true);
     }
     return $this->_quote;
 }
Пример #25
0
 /**
  * Specify quote payment method
  *
  * @param   array $data
  * @return  array
  */
 public function savePayment($data)
 {
     if (empty($data)) {
         return ['error' => -1, 'message' => __('Invalid data')];
     }
     $quote = $this->getQuote();
     // shipping totals may be affected by payment method
     if (!$quote->isVirtual() && $quote->getShippingAddress()) {
         $quote->getShippingAddress()->setCollectShippingRates(true);
     }
     $data['checks'] = [\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];
     $payment = $quote->getPayment();
     $payment->importData($data);
     $this->quoteRepository->save($quote);
     $this->getCheckout()->setStepData('payment', 'complete', true)->setStepData('review', 'allow', true);
     return [];
 }
Пример #26
0
 /**
  * Collect quote totals and save quote object
  *
  * @return \Magento\Multishipping\Model\Checkout\Type\Multishipping
  */
 public function save()
 {
     $this->getQuote()->collectTotals();
     $this->quoteRepository->save($this->getQuote());
     return $this;
 }
Пример #27
0
 /**
  * Remove item from some of customer items storage (shopping cart, wishlist etc.)
  *
  * @param int $itemId
  * @param string $from
  * @return $this
  */
 public function removeItem($itemId, $from)
 {
     switch ($from) {
         case 'quote':
             $this->removeQuoteItem($itemId);
             break;
         case 'cart':
             $cart = $this->getCustomerCart();
             if ($cart) {
                 $cart->removeItem($itemId);
                 $cart->collectTotals();
                 $this->quoteRepository->save($cart);
             }
             break;
         case 'wishlist':
             $wishlist = $this->getCustomerWishlist();
             if ($wishlist) {
                 $item = $this->_objectManager->create('Magento\\Wishlist\\Model\\Item')->load($itemId);
                 $item->delete();
             }
             break;
         case 'compared':
             $this->_objectManager->create('Magento\\Catalog\\Model\\Product\\Compare\\Item')->load($itemId)->delete();
             break;
     }
     return $this;
 }
Пример #28
0
 /**
  * Set shipping method to quote, if needed
  *
  * @param string $methodCode
  * @return void
  */
 public function updateShippingMethod($methodCode)
 {
     $shippingAddress = $this->_quote->getShippingAddress();
     if (!$this->_quote->getIsVirtual() && $shippingAddress) {
         if ($methodCode != $shippingAddress->getShippingMethod()) {
             $this->_ignoreAddressValidation();
             $shippingAddress->setShippingMethod($methodCode)->setCollectShippingRates(true);
             $this->_quote->collectTotals();
             $this->quoteRepository->save($this->_quote);
         }
     }
 }