/** * 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) { } } } }
/** * {@inheritDoc} * * @param int $cartId The cart ID. * @return Totals Quote totals data. */ public function get($cartId) { /** * Quote. * * @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); $shippingAddress = $quote->getShippingAddress(); if ($quote->isVirtual()) { $totalsData = array_merge($quote->getBillingAddress()->getData(), $quote->getData()); } else { $totalsData = array_merge($shippingAddress->getData(), $quote->getData()); } $totals = $this->totalsFactory->create(); $this->dataObjectHelper->populateWithArray($totals, $totalsData, '\\Magento\\Quote\\Api\\Data\\TotalsInterface'); $items = []; $weeeTaxAppliedAmount = 0; foreach ($quote->getAllVisibleItems() as $index => $item) { $items[$index] = $this->itemConverter->modelToDataObject($item); $weeeTaxAppliedAmount += $item->getWeeeTaxAppliedAmount(); } $totals->setCouponCode($this->couponService->get($cartId)); $calculatedTotals = $this->totalsConverter->process($quote->getTotals()); $amount = $totals->getGrandTotal() - $totals->getTaxAmount(); $amount = $amount > 0 ? $amount : 0; $totals->setGrandTotal($amount); $totals->setTotalSegments($calculatedTotals); $totals->setItems($items); $totals->setWeeeTaxAppliedAmount($weeeTaxAppliedAmount); return $totals; }
/** * @param CartTotalRepository $subject * @param \Closure $proceed * @param int $cartId * @return \Magento\Quote\Model\Cart\Totals * @throws \Magento\Framework\Exception\NoSuchEntityException * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundGet(CartTotalRepository $subject, \Closure $proceed, $cartId) { $result = $proceed($cartId); $quote = $this->quoteRepository->getActive($cartId); $totals = $quote->getTotals(); if (!array_key_exists('tax', $totals)) { return $result; } $taxes = $totals['tax']->getData(); if (!array_key_exists('full_info', $taxes)) { return $result; } $detailsId = 1; $finalData = []; foreach ($taxes['full_info'] as $info) { if (array_key_exists('hidden', $info) && $info['hidden'] || $info['amount'] == 0 && $this->taxConfig->displayCartZeroTax()) { continue; } $taxDetails = $this->detailsFactory->create([]); $taxDetails->setAmount($info['amount']); $taxRates = $this->getRatesData($info['rates']); $taxDetails->setRates($taxRates); $taxDetails->setGroupId($detailsId); $finalData[] = $taxDetails; $detailsId++; } $attributes = $result->getExtensionAttributes(); if ($attributes === null) { $attributes = $this->extensionFactory->create(); } $attributes->setTaxGrandtotalDetails($finalData); /** @var $result \Magento\Quote\Model\Cart\Totals */ $result->setExtensionAttributes($attributes); return $result; }
/** * 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(); }
public function testSaveAddresses() { $cartId = 100; $additionalData = $this->getMock('\\Magento\\Quote\\Api\\Data\\AddressAdditionalDataInterface'); $billingAddressMock = $this->getMock('\\Magento\\Quote\\Model\\Quote\\Address', [], [], '', false); $shippingAddressMock = $this->getMock('\\Magento\\Quote\\Model\\Quote\\Address', [], [], '', false); $this->billingAddressManagement->expects($this->once())->method('assign')->with($cartId, $billingAddressMock)->willReturn(1); $billingAddressMock->expects($this->once())->method('format')->with('html'); $this->billingAddressManagement->expects($this->once())->method('get')->with($cartId)->willReturn($billingAddressMock); $this->shippingAddressManagement->expects($this->once())->method('assign')->with($cartId, $shippingAddressMock)->willReturn(1); $shippingAddressMock->expects($this->once())->method('format')->with('html'); $this->shippingAddressManagement->expects($this->once())->method('get')->with($cartId)->willReturn($shippingAddressMock); $shippingMethodMock = $this->getMock('\\Magento\\Quote\\Api\\Data\\ShippingMethodInterface'); $this->shippingMethodManagement->expects($this->once())->method('getList')->with($cartId)->willReturn([$shippingMethodMock]); $paymentMethodMock = $this->getMock('\\Magento\\Quote\\Api\\Data\\PaymentMethodInterface'); $this->paymentMethodManagement->expects($this->once())->method('getList')->with($cartId)->willReturn([$paymentMethodMock]); $addressDetailsMock = $this->getMock('\\Magento\\Quote\\Model\\AddressDetails', [], [], '', false); $this->addressDetailsFactory->expects($this->once())->method('create')->willReturn($addressDetailsMock); $addressDetailsMock->expects($this->once())->method('setShippingMethods')->with([$shippingMethodMock])->willReturnSelf(); $addressDetailsMock->expects($this->once())->method('setPaymentMethods')->with([$paymentMethodMock])->willReturnSelf(); $this->dataProcessor->expects($this->once())->method('process')->with($additionalData); $quote = $this->getMock('Magento\\Quote\\Model\\Quote', [], [], '', false); $quote->expects($this->once())->method('setCheckoutMethod')->willReturnSelf(); $this->quoteRepository->expects($this->once())->method('getActive')->willReturn($quote); $this->model->saveAddresses($cartId, $billingAddressMock, $shippingAddressMock, $additionalData, 'register'); }
/** * Saves payment information in quote * * @param Object $response * @return void */ public function savePaymentInQuote($response) { $quote = $this->quoteRepository->get($this->sessionTransparent->getQuoteId()); /** @var InfoInterface $payment */ $payment = $this->paymentManagement->get($quote->getId()); $payment->setAdditionalInformation('pnref', $response->getPnref()); $this->errorHandler->handle($payment, $response); $this->paymentManagement->set($quote->getId(), $payment); }
/** * @param \Magento\Checkout\Model\ShippingInformationManagement $subject * @param $cartId * @param \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation */ public function beforeSaveAddressInformation(\Magento\Checkout\Model\ShippingInformationManagement $subject, $cartId, \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation) { $customFee = $addressInformation->getExtensionAttributes()->getFee(); $quote = $this->quoteRepository->getActive($cartId); if ($customFee) { $fee = $this->dataHelper->getCustomFee(); $quote->setFee($fee); } else { $quote->setFee(NULL); } }
/** * Return shipping options items for shipping address from request * * @return void */ public function execute() { try { $quoteId = $this->getRequest()->getParam('quote_id'); $this->_quote = $this->quoteRepository->get($quoteId); $this->_initCheckout(); $response = $this->_checkout->getShippingOptionsCallbackResponse($this->getRequest()->getParams()); $this->getResponse()->setBody($response); } catch (\Exception $e) { $this->_objectManager->get('Psr\\Log\\LoggerInterface')->critical($e); } }
/** * 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(); }
/** * 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} * * @param int $cartId The cart ID. * @return Totals Quote totals data. */ public function get($cartId) { /** * Quote. * * @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); $shippingAddress = $quote->getShippingAddress(); $totalsData = array_merge($shippingAddress->getData(), $quote->getData()); $totals = $this->totalsFactory->create(); $this->dataObjectHelper->populateWithArray($totals, $totalsData, '\\Magento\\Quote\\Api\\Data\\TotalsInterface'); $totals->setItems($quote->getAllItems()); return $totals; }
public function testSavePaymentInQuote() { $quoteId = 1; $response = new DataObject(); $payment = $this->getMockBuilder('Magento\\Quote\\Model\\Quote\\Payment')->disableOriginalConstructor()->getMock(); $payment->expects($this->once())->method('setAdditionalInformation')->with('pnref'); $this->errorHandlerMock->expects($this->once())->method('handle')->with($payment, $response); $quote = $this->getMock('Magento\\Quote\\Api\\Data\\CartInterface', [], [], '', false); $quote->expects($this->exactly(2))->method('getId')->willReturn($quoteId); $this->sessionTransparent->expects($this->once())->method('getQuoteId')->willReturn($quoteId); $this->quoteRepository->expects($this->once())->method('get')->willReturn($quote); $this->paymentMethodManagementInterface->expects($this->once())->method('get')->willReturn($payment); $this->paymentMethodManagementInterface->expects($this->once())->method('set'); $this->model->savePaymentInQuote($response); }
/** * {@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')); } $billingAddress = $quote->getBillingAddress(); if (!$billingAddress->getCountryId()) { throw new StateException(__('Billing 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; }
public function testGetCartForCustomer() { $customerId = 100; $cartMock = $this->getMock('\\Magento\\Quote\\Model\\Quote', [], [], '', false); $this->quoteRepositoryMock->expects($this->once())->method('getActiveForCustomer')->with($customerId)->willReturn($cartMock); $this->assertEquals($cartMock, $this->model->getCartForCustomer($customerId)); }
/** * @param int $direction * @param string $expectedDirection * @dataProvider getListSuccessDataProvider */ public function testGetListSuccess($direction, $expectedDirection) { $searchResult = $this->getMock('\\Magento\\Quote\\Api\\Data\\CartSearchResultsInterface', [], [], '', false); $searchCriteriaMock = $this->getMock('\\Magento\\Framework\\Api\\SearchCriteria', [], [], '', false); $cartMock = $this->getMock('Magento\\Payment\\Model\\Cart', [], [], '', false); $filterMock = $this->getMock('\\Magento\\Framework\\Api\\Filter', [], [], '', false); $pageSize = 10; $this->searchResultsBuilderMock->expects($this->once())->method('setSearchCriteria'); $filterGroupMock = $this->getMock('\\Magento\\Framework\\Api\\Search\\FilterGroup', [], [], '', false); $searchCriteriaMock->expects($this->any())->method('getFilterGroups')->will($this->returnValue([$filterGroupMock])); //addFilterGroupToCollection() checks $filterGroupMock->expects($this->any())->method('getFilters')->will($this->returnValue([$filterMock])); $filterMock->expects($this->once())->method('getField')->will($this->returnValue('store_id')); $filterMock->expects($this->any())->method('getConditionType')->will($this->returnValue('eq')); $filterMock->expects($this->once())->method('getValue')->will($this->returnValue('filter_value')); //back in getList() $this->quoteCollectionMock->expects($this->once())->method('getSize')->willReturn($pageSize); $this->searchResultsBuilderMock->expects($this->once())->method('setTotalCount')->with($pageSize); $sortOrderMock = $this->getMockBuilder('Magento\\Framework\\Api\\SortOrder')->setMethods(['getField', 'getDirection'])->disableOriginalConstructor()->getMock(); //foreach cycle $searchCriteriaMock->expects($this->once())->method('getSortOrders')->will($this->returnValue([$sortOrderMock])); $sortOrderMock->expects($this->once())->method('getField')->will($this->returnValue('id')); $sortOrderMock->expects($this->once())->method('getDirection')->will($this->returnValue($direction)); $this->quoteCollectionMock->expects($this->once())->method('addOrder')->with('id', $expectedDirection); $searchCriteriaMock->expects($this->once())->method('getCurrentPage')->will($this->returnValue(1)); $searchCriteriaMock->expects($this->once())->method('getPageSize')->will($this->returnValue(10)); $this->quoteCollectionMock->expects($this->once())->method('setCurPage')->with(1); $this->quoteCollectionMock->expects($this->once())->method('setPageSize')->with(10); $this->quoteCollectionMock->expects($this->once())->method('getItems')->willReturn([$cartMock]); $this->searchResultsBuilderMock->expects($this->once())->method('setItems')->with([$cartMock]); $this->searchResultsBuilderMock->expects($this->once())->method('create')->will($this->returnValue($searchResult)); $this->assertEquals($searchResult, $this->model->getList($searchCriteriaMock)); }
/** * Get active quote by id * * @param int $cartId * @param int[] $sharedStoreIds * @throws NoSuchEntityException * @return CartInterface */ public function get($cartId, array $sharedStoreIds = []) { $quote = parent::get($cartId, $sharedStoreIds); if (!$quote->getIsActive()) { throw NoSuchEntityException::singleField('cartId', $cartId); } return $quote; }
/** * {@inheritDoc} */ public function get($cartId) { /** * Quote. * * @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.')); } /** * Address. * * @var \Magento\Quote\Model\Quote\Address $address */ return $quote->getShippingAddress(); }
/** * {@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; }
/** * @dataProvider saveBillingDataProvider * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.ExcessiveParameterList) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function testSaveBilling($data, $customerAddressId, $quoteCustomerId, $addressCustomerId, $isAddress, $validateDataResult, $validateResult, $checkoutMethod, $customerPassword, $confirmPassword, $validationResultMessages, $isEmailAvailable, $isVirtual, $getStepDataResult, $expected) { $useForShipping = (int) $data['use_for_shipping']; $passwordHash = 'password hash'; $this->requestMock->expects($this->any())->method('isAjax')->will($this->returnValue(false)); $customerValidationResultMock = $this->getMock('Magento\\Customer\\Api\\Data\\ValidationResultsInterface', [], [], '', false); $customerValidationResultMock->expects($this->any())->method('isValid')->will($this->returnValue(empty($validationResultMessages))); $customerValidationResultMock->expects($this->any())->method('getMessages')->will($this->returnValue($validationResultMessages)); $this->accountManagementMock->expects($this->any())->method('getPasswordHash')->with($customerPassword)->will($this->returnValue($passwordHash)); $this->accountManagementMock->expects($this->any())->method('validate')->will($this->returnValue($customerValidationResultMock)); $this->accountManagementMock->expects($this->any())->method('isEmailAvailable')->will($this->returnValue($isEmailAvailable)); /** @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject $quoteMock */ $quoteMock = $this->getMock('Magento\\Quote\\Model\\Quote', ['getData', 'getCustomerId', '__wakeup', 'getBillingAddress', 'setPasswordHash', 'getCheckoutMethod', 'isVirtual', 'getShippingAddress', 'getCustomerData', 'collectTotals', 'save', 'getCustomer'], [], '', false); $customerMock = $this->getMockForAbstractClass('Magento\\Framework\\Api\\AbstractExtensibleObject', [], '', false, true, true, ['__toArray']); $shippingAddressMock = $this->getMock('Magento\\Quote\\Model\\Quote\\Address', ['setSameAsBilling', 'save', 'collectTotals', 'addData', 'setShippingMethod', 'setCollectShippingRates', '__wakeup'], [], '', false); $quoteMock->expects($this->any())->method('getShippingAddress')->will($this->returnValue($shippingAddressMock)); $shippingAddressMock->expects($useForShipping ? $this->any() : $this->once())->method('setSameAsBilling')->with($useForShipping)->will($this->returnSelf()); $expects = !$useForShipping || $checkoutMethod != Onepage::METHOD_REGISTER ? $this->once() : $this->never(); $shippingAddressMock->expects($expects)->method('save'); $shippingAddressMock->expects($useForShipping ? $this->once() : $this->never())->method('addData')->will($this->returnSelf()); $shippingAddressMock->expects($this->any())->method('setSaveInAddressBook')->will($this->returnSelf()); $shippingAddressMock->expects($useForShipping ? $this->once() : $this->never())->method('setShippingMethod')->will($this->returnSelf()); $shippingAddressMock->expects($useForShipping ? $this->once() : $this->never())->method('setCollectShippingRates')->will($this->returnSelf()); $shippingAddressMock->expects($useForShipping ? $this->once() : $this->never())->method('collectTotals'); $quoteMock->expects($this->any())->method('setPasswordHash')->with($passwordHash); $quoteMock->expects($this->any())->method('getCheckoutMethod')->will($this->returnValue($checkoutMethod)); $quoteMock->expects($this->any())->method('isVirtual')->will($this->returnValue($isVirtual)); $addressMock = $this->getMock('Magento\\Quote\\Model\\Quote\\Address', ['setSaveInAddressBook', 'getData', 'setEmail', '__wakeup', 'importCustomerAddressData', 'validate', 'save'], [], '', false); $addressMock->expects($this->any())->method('importCustomerAddressData')->will($this->returnSelf()); $addressMock->expects($this->atLeastOnce())->method('validate')->will($this->returnValue($validateResult)); $addressMock->expects($this->any())->method('getData')->will($this->returnValue([])); $quoteMock->expects($this->any())->method('getBillingAddress')->will($this->returnValue($addressMock)); $quoteMock->expects($this->any())->method('getCustomerId')->will($this->returnValue($quoteCustomerId)); $this->quoteRepositoryMock->expects($checkoutMethod === Onepage::METHOD_REGISTER ? $this->once() : $this->never())->method('save')->with($quoteMock); $addressMock->expects($checkoutMethod === Onepage::METHOD_REGISTER ? $this->never() : $this->once())->method('save'); $quoteMock->expects($this->any())->method('getCustomer')->will($this->returnValue($customerMock)); $data1 = []; $extensibleDataObjectConverterMock = $this->getMock('Magento\\Framework\\Api\\ExtensibleDataObjectConverter', ['toFlatArray'], [], '', false); $extensibleDataObjectConverterMock->expects($this->any())->method('toFlatArray')->with($customerMock)->will($this->returnValue($data1)); $formMock = $this->getMock('Magento\\Customer\\Model\\Metadata\\Form', [], [], '', false); $formMock->expects($this->atLeastOnce())->method('validateData')->will($this->returnValue($validateDataResult)); $this->formFactoryMock->expects($this->any())->method('create')->will($this->returnValue($formMock)); $formMock->expects($this->any())->method('prepareRequest')->will($this->returnValue($this->requestMock)); $formMock->expects($this->any())->method('extractData')->with($this->requestMock)->will($this->returnValue([])); $formMock->expects($this->any())->method('validateData')->with([])->will($this->returnValue(false)); $customerDataMock = $this->getMock('Magento\\Customer\\Api\\Data\\CustomerInterface', [], [], '', false); $this->customerDataFactoryMock->expects($this->any())->method('create')->will($this->returnValue($customerDataMock)); $this->checkoutSessionMock->expects($this->any())->method('getQuote')->will($this->returnValue($quoteMock)); $this->checkoutSessionMock->expects($this->any())->method('getStepData')->will($this->returnValue($useForShipping ? true : $getStepDataResult)); $this->checkoutSessionMock->expects($this->any())->method('setStepData')->will($this->returnSelf()); $customerAddressMock = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\AddressInterface', [], '', false); $customerAddressMock->expects($this->any())->method('getCustomerId')->will($this->returnValue($addressCustomerId)); $this->addressRepositoryMock->expects($this->any())->method('getById')->will($isAddress ? $this->returnValue($customerAddressMock) : $this->throwException(new \Exception())); $websiteMock = $this->getMock('Magento\\Store\\Model\\Website', [], [], '', false); $this->storeManagerMock->expects($this->any())->method('getWebsite')->will($this->returnValue($websiteMock)); $this->assertEquals($expected, $this->onepage->saveBilling($data, $customerAddressId)); }
/** * {@inheritdoc} */ public function getActiveForCustomer($customerId, array $sharedStoreIds = array()) { $pluginInfo = $this->pluginList->getNext($this->subjectType, 'getActiveForCustomer'); if (!$pluginInfo) { return parent::getActiveForCustomer($customerId, $sharedStoreIds); } else { return $this->___callPlugins('getActiveForCustomer', func_get_args(), $pluginInfo); } }
/** * {@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; }
/** * @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); } } } }
/** * {@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()); }
/** * Loads customer, quote and quote item by request params * * @return $this * @throws \Magento\Framework\Exception\LocalizedException */ protected function _initData() { $this->_customerId = (int) $this->getRequest()->getParam('customer_id'); if (!$this->_customerId) { throw new \Magento\Framework\Exception\LocalizedException(__('No customer ID defined.')); } $quoteItemId = (int) $this->getRequest()->getParam('id'); $websiteId = (int) $this->getRequest()->getParam('website_id'); try { $this->_quote = $this->quoteRepository->getForCustomer($this->_customerId); } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { $this->_quote = $this->quoteRepository->create(); } $this->_quote->setWebsite($this->_objectManager->get('Magento\\Store\\Model\\StoreManagerInterface')->getWebsite($websiteId)); $this->_quoteItem = $this->_quote->getItemById($quoteItemId); if (!$this->_quoteItem) { throw new LocalizedException(__('Please correct the quote items and try again.')); } return $this; }
/** * {@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')); } if (!$this->helper->isMessagesAllowed('quote', $quote, $this->storeManager->getStore())) { throw new CouldNotSaveException(__('Gift Message is not available')); } $this->giftMessageManager->setMessage($quote, 'quote', $giftMessage); return true; }
/** * 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(); }
/** * @{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; }
/** * Get the quote of the cart * * @return \Magento\Quote\Model\Quote */ protected function getQuote() { if (null === $this->quote) { $customerId = $this->getCustomerId(); $storeIds = $this->_storeManager->getWebsite($this->getWebsiteId())->getStoreIds(); try { $this->quote = $this->quoteRepository->getForCustomer($customerId, $storeIds); } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { $this->quote = $this->quoteRepository->create()->setSharedStoreIds($storeIds); } } return $this->quote; }
/** * {@inheritDoc} * * @param int $cartId The cart ID. * @return Totals Quote totals data. */ public function get($cartId) { /** * Quote. * * @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); $shippingAddress = $quote->getShippingAddress(); if ($quote->isVirtual()) { $totalsData = array_merge($quote->getBillingAddress()->getData(), $quote->getData()); } else { $totalsData = array_merge($shippingAddress->getData(), $quote->getData()); } $totals = $this->totalsFactory->create(); $this->dataObjectHelper->populateWithArray($totals, $totalsData, '\\Magento\\Quote\\Api\\Data\\TotalsInterface'); $items = []; foreach ($quote->getAllVisibleItems() as $index => $item) { $items[$index] = $this->converter->modelToDataObject($item); } $totals->setItems($items); return $totals; }
/** * 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; }