/**
  * 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();
 }
 /**
  * Fetch coupon info
  *
  * Controller Action
  */
 public function execute()
 {
     $total = $this->getRequest()->getParam('cost');
     $quote = $this->_checkoutSession->getQuote();
     //save value to DiscountCoupon collect
     $this->_registry->register('mercadopago_total_amount', $total);
     $this->quoteRepository->save($quote->collectTotals());
     return;
 }
Example #3
0
 /**
  * Update quote data
  *
  * @param Quote $quote
  * @param array $details
  * @return void
  */
 private function updateQuote(Quote $quote, array $details)
 {
     $quote->setMayEditShippingAddress(false);
     $quote->setMayEditShippingMethod(true);
     $this->updateQuoteAddress($quote, $details);
     $this->disabledQuoteAddressValidation($quote);
     $quote->collectTotals();
     $this->quoteRepository->save($quote);
 }
 /**
  * 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();
 }
 /**
  * {@inheritDoc}
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function assign($cartId, \Magento\Quote\Api\Data\AddressInterface $address, $useForShipping = false)
 {
     /** @var \Magento\Quote\Model\Quote $quote */
     $quote = $this->quoteRepository->getActive($cartId);
     $quote->removeAddress($quote->getBillingAddress()->getId());
     $quote->setBillingAddress($address);
     try {
         $quote->setDataChanges(true);
         $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();
 }
Example #6
0
 /**
  * @param \Magento\Checkout\Controller\Cart $subject
  * @param \Magento\Framework\App\RequestInterface $request
  * @return void
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function beforeDispatch(\Magento\Checkout\Controller\Cart $subject, \Magento\Framework\App\RequestInterface $request)
 {
     /** @var \Magento\Quote\Model\Quote $quote */
     $quote = $this->checkoutSession->getQuote();
     // Clear shipping addresses and item assignments after Multishipping flow
     if ($quote->isMultipleShippingAddresses()) {
         foreach ($quote->getAllShippingAddresses() as $address) {
             $quote->removeAddress($address->getId());
         }
         $quote->getShippingAddress();
         $quote->setIsMultiShipping(false);
         $quote->collectTotals();
         $this->cartRepository->save($quote);
     }
 }
 /**
  * {@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;
 }
 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);
 }
 /**
  * {@inheritDoc}
  *
  * @param int $cartId The shopping cart ID.
  * @param string $carrierCode The carrier code.
  * @param string $methodCode The shipping method code.
  * @return bool
  * @throws InputException The shipping method is not valid for an empty cart.
  * @throws CouldNotSaveException The shipping method could not be saved.
  * @throws NoSuchEntityException Cart contains only virtual products. Shipping method is not applicable.
  * @throws 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;
 }
Example #10
0
 /**
  * Retrieve quote model object
  *
  * @return \Magento\Quote\Model\Quote
  */
 public function getQuote()
 {
     if ($this->_quote === null) {
         $this->_quote = $this->quoteFactory->create();
         if ($this->getStoreId()) {
             if (!$this->getQuoteId()) {
                 $this->_quote->setCustomerGroupId($this->groupManagement->getDefaultGroup()->getId());
                 $this->_quote->setIsActive(false);
                 $this->_quote->setStoreId($this->getStoreId());
                 $this->quoteRepository->save($this->_quote);
                 $this->setQuoteId($this->_quote->getId());
                 $this->_quote = $this->quoteRepository->get($this->getQuoteId(), [$this->getStoreId()]);
             } else {
                 $this->_quote = $this->quoteRepository->get($this->getQuoteId(), [$this->getStoreId()]);
                 $this->_quote->setStoreId($this->getStoreId());
             }
             if ($this->getCustomerId() && $this->getCustomerId() != $this->_quote->getCustomerId()) {
                 $customer = $this->customerRepository->getById($this->getCustomerId());
                 $this->_quote->assignCustomer($customer);
                 $this->quoteRepository->save($this->_quote);
             }
         }
         $this->_quote->setIgnoreOldQty(true);
         $this->_quote->setIsSuperMode(true);
     }
     return $this->_quote;
 }
 /**
  * Execute operation
  *
  * @param string $shippingMethod
  * @param Quote $quote
  * @return void
  * @throws \InvalidArgumentException
  */
 public function execute($shippingMethod, Quote $quote)
 {
     if (empty($shippingMethod)) {
         throw new \InvalidArgumentException('The "shippingMethod" field does not exists.');
     }
     if (!$quote->getIsVirtual()) {
         $shippingAddress = $quote->getShippingAddress();
         if ($shippingMethod !== $shippingAddress->getShippingMethod()) {
             $this->disabledQuoteAddressValidation($quote);
             $shippingAddress->setShippingMethod($shippingMethod);
             $shippingAddress->setCollectShippingRates(true);
             $quote->collectTotals();
             $this->quoteRepository->save($quote);
         }
     }
 }
Example #12
0
 /**
  * @param $quoteId
  *
  * @return Quote
  */
 public function reOrder($quoteId)
 {
     $quote = $this->_quoteRepository->get($quoteId);
     $quote->setIsActive(1)->setReservedOrderId(null);
     $this->_quoteRepository->save($quote);
     return $quote;
 }
 /**
  * {@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;
 }
Example #15
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);
             }
         }
     }
 }
Example #16
0
 /**
  * Fetch coupon info
  *
  * Controller Action
  */
 public function execute()
 {
     $coupon_id = $this->getRequest()->getParam('id');
     if (!empty($coupon_id)) {
         $response = $this->coreModel->validCoupon($coupon_id);
     } else {
         $response = $this->getArrayErrorResponse();
     }
     if ($response['status'] != 200 && $response['status'] != 201) {
         $response = $this->getArrayErrorResponse();
     }
     //save value to DiscountCoupon collect
     $this->_registry->register('mercadopago_discount_amount', (double) $response['response']['coupon_amount']);
     $quote = $this->_checkoutSession->getQuote();
     $this->quoteRepository->save($quote->collectTotals());
     $jsonData = json_encode($response);
     $this->getResponse()->setHeader('Content-type', 'application/json');
     $this->getResponse()->setBody($jsonData);
 }
 /**
  * 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();
 }
Example #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);
         $order->setShippingMethod($quote->getShippingAddress()->getShippingMethod());
     }
     $billingAddress = $this->quoteAddressToOrderAddress->convert($quote->getBillingAddress(), ['address_type' => 'billing', 'email' => $quote->getCustomerEmail()]);
     $addresses[] = $billingAddress;
     $order->setBillingAddress($billingAddress);
     $order->setAddresses($addresses);
     $order->setPayment($this->quotePaymentToOrderPayment->convert($quote->getPayment()));
     $order->setItems($this->resolveItems($quote));
     if ($quote->getCustomer()) {
         $order->setCustomerId($quote->getCustomer()->getId());
     }
     $order->setQuoteId($quote->getId());
     //To Set Vat Exempt Quote values to Order
     $order->setVatpername($quote->getVatpername());
     $order->setVatcomment($quote->getVatcomment());
     $order->setVatdeclare($quote->getVatdeclare());
     $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, 'exception' => $e]);
         throw $e;
     }
     return $order;
 }
 /**
  * Set new customer group to all his quotes
  *
  * @param Observer $observer
  * @return void
  */
 public function execute(Observer $observer)
 {
     /** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
     $customer = $observer->getEvent()->getCustomerDataObject();
     try {
         $quote = $this->quoteRepository->getForCustomer($customer->getId());
         if ($customer->getGroupId() !== $quote->getCustomerGroupId()) {
             /**
              * 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) {
                 $quote->setWebsite($website);
                 $quote->setCustomerGroupId($customer->getGroupId());
                 $quote->collectTotals();
                 $this->quoteRepository->save($quote);
             }
         }
     } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
     }
 }
Example #20
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;
 }
 /**
  * {@inheritDoc}
  */
 public function set($cartId, $carrierCode, $methodCode)
 {
     /** @var \Magento\Quote\Model\Quote $quote */
     $quote = $this->quoteRepository->getActive($cartId);
     try {
         $this->apply($cartId, $carrierCode, $methodCode);
     } catch (\Exception $e) {
         throw $e;
     }
     try {
         $this->quoteRepository->save($quote->collectTotals());
     } catch (\Exception $e) {
         throw new CouldNotSaveException(__('Cannot set shipping method. %1', $e->getMessage()));
     }
     return true;
 }
 /**
  * {@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;
 }
Example #23
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;
 }
Example #24
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();
 }
 /**
  * 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
     }
 }
Example #27
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);
             $cartExtension = $this->_quote->getExtensionAttributes();
             if ($cartExtension && $cartExtension->getShippingAssignments()) {
                 $cartExtension->getShippingAssignments()[0]->getShipping()->setMethod($methodCode);
             }
             $this->_quote->collectTotals();
             $this->quoteRepository->save($this->_quote);
         }
     }
 }
Example #28
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;
 }
Example #29
0
 /**
  * Handle data sent from sidebar
  *
  * @param array $data
  * @return $this
  * @throws \Magento\Framework\Exception\LocalizedException
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  */
 public function applySidebarData($data)
 {
     if (isset($data['add_order_item'])) {
         foreach ($data['add_order_item'] as $orderItemId => $value) {
             /* @var $orderItem \Magento\Sales\Model\Order\Item */
             $orderItem = $this->_objectManager->create('Magento\\Sales\\Model\\Order\\Item')->load($orderItemId);
             $item = $this->initFromOrderItem($orderItem);
             if (is_string($item)) {
                 throw new \Magento\Framework\Exception\LocalizedException(__($item));
             }
         }
     }
     if (isset($data['add_cart_item'])) {
         foreach ($data['add_cart_item'] as $itemId => $qty) {
             $item = $this->getCustomerCart()->getItemById($itemId);
             if ($item) {
                 $this->moveQuoteItem($item, 'order', $qty);
                 $this->removeItem($itemId, 'cart');
             }
         }
     }
     if (isset($data['add_wishlist_item'])) {
         foreach ($data['add_wishlist_item'] as $itemId => $qty) {
             $item = $this->_objectManager->create('Magento\\Wishlist\\Model\\Item')->loadWithOptions($itemId, 'info_buyRequest');
             if ($item->getId()) {
                 $this->addProduct($item->getProduct(), $item->getBuyRequest()->toArray());
             }
         }
     }
     if (isset($data['add'])) {
         foreach ($data['add'] as $productId => $qty) {
             $this->addProduct($productId, ['qty' => $qty]);
         }
     }
     if (isset($data['remove'])) {
         foreach ($data['remove'] as $itemId => $from) {
             $this->removeItem($itemId, $from);
         }
     }
     if (isset($data['empty_customer_cart']) && (int) $data['empty_customer_cart'] == 1) {
         $this->getCustomerCart()->removeAllItems()->collectTotals();
         $this->quoteRepository->save($this->getCustomerCart());
     }
     $this->recollectCart();
     return $this;
 }
Example #30
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);
         }
     }
 }