/**
  * Validates the fields in a specified address data object.
  *
  * @param \Magento\Quote\Api\Data\AddressInterface $addressData The address data object.
  * @return bool
  * @throws \Magento\Framework\Exception\InputException The specified address belongs to another customer.
  * @throws \Magento\Framework\Exception\NoSuchEntityException The specified customer ID or address ID is not valid.
  */
 public function validate(\Magento\Quote\Api\Data\AddressInterface $addressData)
 {
     //validate customer id
     if ($addressData->getCustomerId()) {
         $customer = $this->customerRepository->getById($addressData->getCustomerId());
         if (!$customer->getId()) {
             throw new \Magento\Framework\Exception\NoSuchEntityException(__('Invalid customer id %1', $addressData->getCustomerId()));
         }
     }
     if ($addressData->getCustomerAddressId()) {
         try {
             $this->addressRepository->getById($addressData->getCustomerAddressId());
         } catch (NoSuchEntityException $e) {
             throw new \Magento\Framework\Exception\NoSuchEntityException(__('Invalid address id %1', $addressData->getId()));
         }
         $applicableAddressIds = array_map(function ($address) {
             /** @var \Magento\Customer\Api\Data\AddressInterface $address */
             return $address->getId();
         }, $this->customerRepository->getById($addressData->getCustomerId())->getAddresses());
         if (!in_array($addressData->getCustomerAddressId(), $applicableAddressIds)) {
             throw new \Magento\Framework\Exception\NoSuchEntityException(__('Invalid address id %1', $addressData->getCustomerAddressId()));
         }
     }
     return true;
 }
 /**
  * Set persistent data to customer session
  *
  * @param \Magento\Framework\Event\Observer $observer
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  *
  * @return $this
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     if (!$this->_persistentData->canProcess($observer) || !$this->_persistentData->isShoppingCartPersist()) {
         return $this;
     }
     if ($this->_persistentSession->isPersistent() && !$this->_customerSession->isLoggedIn()) {
         /** @var  \Magento\Customer\Api\Data\CustomerInterface $customer */
         $customer = $this->customerRepository->getById($this->_persistentSession->getSession()->getCustomerId());
         if ($defaultShipping = $customer->getDefaultShipping()) {
             /** @var  \Magento\Customer\Model\Data\Address $address */
             $address = $this->addressRepository->getById($defaultShipping);
             if ($address) {
                 $this->_customerSession->setDefaultTaxShippingAddress(['country_id' => $address->getCountryId(), 'region_id' => $address->getRegion() ? $address->getRegionId() : null, 'postcode' => $address->getPostcode()]);
             }
         }
         if ($defaultBilling = $customer->getDefaultBilling()) {
             $address = $this->addressRepository->getById($defaultBilling);
             if ($address) {
                 $this->_customerSession->setDefaultTaxBillingAddress(['country_id' => $address->getCountryId(), 'region_id' => $address->getRegion() ? $address->getRegionId() : null, 'postcode' => $address->getPostcode()]);
             }
         }
         $this->_customerSession->setCustomerId($customer->getId())->setCustomerGroupId($customer->getGroupId());
     }
     return $this;
 }
Example #3
0
 /**
  * Prepare the layout of the address edit block.
  *
  * @return $this
  */
 protected function _prepareLayout()
 {
     parent::_prepareLayout();
     // Init address object
     if ($addressId = $this->getRequest()->getParam('id')) {
         try {
             $this->_address = $this->_addressRepository->getById($addressId);
             if ($this->_address->getCustomerId() != $this->_customerSession->getCustomerId()) {
                 $this->_address = null;
             }
         } catch (NoSuchEntityException $e) {
             $this->_address = null;
         }
     }
     if ($this->_address === null || !$this->_address->getId()) {
         $this->_address = $this->addressDataFactory->create();
         $customer = $this->getCustomer();
         $this->_address->setPrefix($customer->getPrefix());
         $this->_address->setFirstname($customer->getFirstname());
         $this->_address->setMiddlename($customer->getMiddlename());
         $this->_address->setLastname($customer->getLastname());
         $this->_address->setSuffix($customer->getSuffix());
     }
     $this->pageConfig->getTitle()->set($this->getTitle());
     if ($postedData = $this->_customerSession->getAddressFormData(true)) {
         if (!empty($postedData['region_id']) || !empty($postedData['region'])) {
             $postedData['region'] = ['region_id' => $postedData['region_id'], 'region' => $postedData['region']];
         }
         $this->dataObjectHelper->populateWithArray($this->_address, $postedData, '\\Magento\\Customer\\Api\\Data\\AddressInterface');
     }
     return $this;
 }
 /**
  * {@inheritDoc}
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 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.'));
     }
     $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);
     } elseif ($quote->getCustomerId()) {
         $address->setEmail($quote->getCustomerEmail());
     }
     $address->setSameAsBilling($sameAsBilling);
     $address->setSaveInAddressBook($saveInAddressBook);
     $address->setCollectShippingRates(true);
     try {
         $this->totalsCollector->collectAddressTotals($quote, $address);
         $address->save();
     } catch (\Exception $e) {
         $this->logger->critical($e);
         throw new InputException(__('Unable to save address. Please, check input data.'));
     }
     if (!$quote->validateMinimumAmount($quote->getIsMultiShipping())) {
         throw new InputException($this->scopeConfig->getValue('sales/minimum_order/error_message', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $quote->getStoreId()));
     }
     return $quote->getShippingAddress()->getId();
 }
 /**
  * @param CartInterface $quote
  * @param AddressInterface $address
  * @param bool $useForShipping
  * @return void
  * @throws NoSuchEntityException
  * @throws InputException
  */
 public function save(CartInterface $quote, AddressInterface $address, $useForShipping = false)
 {
     /** @var \Magento\Quote\Model\Quote $quote */
     $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);
     }
 }
 /**
  * @magentoDataFixture Magento/Customer/_files/customer.php
  * @magentoDataFixture Magento/Customer/_files/customer_address.php
  * @magentoDataFixture Magento/Checkout/_files/quote_with_product_and_payment.php
  */
 public function testGetAddress()
 {
     $addressFromFixture = $this->_addressRepository->getById(self::FIXTURE_ADDRESS_ID);
     $address = $this->_block->getAddress();
     $this->assertEquals($addressFromFixture->getFirstname(), $address->getFirstname());
     $this->assertEquals($addressFromFixture->getLastname(), $address->getLastname());
     $this->assertEquals($addressFromFixture->getCustomerId(), $address->getCustomerId());
 }
 /**
  * @magentoApiDataFixture Magento/Customer/_files/customer.php
  * @magentoApiDataFixture Magento/Customer/_files/customer_address.php
  */
 public function testDeleteAddress()
 {
     $fixtureAddressId = 1;
     $serviceInfo = ['rest' => ['resourcePath' => "/V1/addresses/{$fixtureAddressId}", 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE], 'soap' => ['service' => self::SOAP_SERVICE_NAME, 'serviceVersion' => self::SOAP_SERVICE_VERSION, 'operation' => self::SOAP_SERVICE_NAME . 'DeleteById']];
     $requestData = ['addressId' => $fixtureAddressId];
     $response = $this->_webApiCall($serviceInfo, $requestData);
     $this->assertTrue($response, 'Expected response should be true.');
     $this->setExpectedException('Magento\\Framework\\Exception\\NoSuchEntityException', 'No such entity with addressId = 1');
     $this->addressRepository->getById($fixtureAddressId);
 }
 public function testGetDefaultRateRequest()
 {
     $customerDataSet = $this->customerRepository->getById(self::FIXTURE_CUSTOMER_ID);
     $address = $this->addressRepository->getById(self::FIXTURE_ADDRESS_ID);
     $rateRequest = $this->_model->getRateRequest(null, null, null, null, $customerDataSet->getId());
     $this->assertNotNull($rateRequest);
     $this->assertEquals($address->getCountryId(), $rateRequest->getCountryId());
     $this->assertEquals($address->getRegion()->getRegionId(), $rateRequest->getRegionId());
     $this->assertEquals($address->getPostcode(), $rateRequest->getPostcode());
     $customerTaxClassId = $this->groupRepository->getById($customerDataSet->getGroupId())->getTaxClassId();
     $this->assertEquals($customerTaxClassId, $rateRequest->getCustomerClassId());
 }
 /**
  * Test case when customer has addresses, but default {$addressType} address is not set.
  *
  * @param string $addressType
  * @magentoDataFixture Magento/Customer/_files/customer.php
  * @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php
  * @magentoAppIsolation enabled
  * @dataProvider getCustomerDefaultAddressDataProvider
  */
 public function testGetCustomerDefaultAddressDefaultAddressNotSet($addressType)
 {
     /**
      * Preconditions:
      * - customer has addresses, but default address of {$addressType} is not set
      * - current customer is set to customer session
      */
     $fixtureCustomerId = 1;
     $firstFixtureAddressId = 1;
     $firstFixtureAddressStreet = ['Green str, 67'];
     /** @var \Magento\Customer\Model\Customer $customer */
     $customer = Bootstrap::getObjectManager()->create('Magento\\Customer\\Model\\Customer')->load($fixtureCustomerId);
     if ($addressType == self::ADDRESS_TYPE_SHIPPING) {
         $customer->setDefaultShipping(null)->save();
     } else {
         // billing
         $customer->setDefaultBilling(null)->save();
     }
     /** @var \Magento\Customer\Model\Session $customerSession */
     $customerSession = Bootstrap::getObjectManager()->get('Magento\\Customer\\Model\\Session');
     $customerSession->setCustomer($customer);
     /** Execute SUT */
     if ($addressType == self::ADDRESS_TYPE_SHIPPING) {
         $addressId = $this->_multishippingCheckout->getCustomerDefaultShippingAddress();
     } else {
         // billing
         $addressId = $this->_multishippingCheckout->getCustomerDefaultBillingAddress();
     }
     $address = $this->addressRepository->getById($addressId);
     $this->assertInstanceOf('\\Magento\\Customer\\Api\\Data\\AddressInterface', $address, "Address was not loaded.");
     $this->assertEquals($firstFixtureAddressId, $address->getId(), "Invalid address loaded.");
     $this->assertEquals($firstFixtureAddressStreet, $address->getStreet(), "Street in default {$addressType} address is invalid.");
 }
Example #10
0
 /**
  * @magentoDataFixture Magento/Customer/_files/customer_sample.php
  */
 public function testSaveActionExistingCustomerAndExistingAddressData()
 {
     $post = ['customer' => ['entity_id' => '1', 'middlename' => 'test middlename', 'group_id' => 1, 'website_id' => 1, 'firstname' => 'test firstname', 'lastname' => 'test lastname', 'email' => '*****@*****.**', 'new_password' => 'auto', 'sendemail_store_id' => '1', 'sendemail' => '1', 'created_at' => '2000-01-01 00:00:00', 'default_shipping' => '_item1', 'default_billing' => 1], 'address' => ['1' => ['firstname' => 'update firstname', 'lastname' => 'update lastname', 'street' => ['update street'], 'city' => 'update city', 'region_id' => 10, 'country_id' => 'US', 'postcode' => '01001', 'telephone' => '+7000000001', 'default_billing' => 'true'], '_item1' => ['firstname' => 'new firstname', 'lastname' => 'new lastname', 'street' => ['new street'], 'city' => 'new city', 'region_id' => 10, 'country_id' => 'US', 'postcode' => '01001', 'telephone' => '+7000000001', 'default_shipping' => 'true'], '_template_' => ['firstname' => '', 'lastname' => '', 'street' => [], 'city' => '', 'region_id' => 10, 'country_id' => 'US', 'postcode' => '', 'telephone' => '']], 'subscription' => ''];
     $this->getRequest()->setPostValue($post);
     $this->getRequest()->setParam('id', 1);
     $this->dispatch('backend/customer/index/save');
     /** Check that success message is set */
     $this->assertSessionMessages($this->equalTo(['You saved the customer.']), \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS);
     /** Check that customer id set and addresses saved */
     $registry = $this->objectManager->get('Magento\\Framework\\Registry');
     $customerId = $registry->registry(RegistryConstants::CURRENT_CUSTOMER_ID);
     $customer = $this->customerRepository->getById($customerId);
     $this->assertEquals('test firstname', $customer->getFirstname());
     /**
      * Addresses should be removed by
      * \Magento\Customer\Model\ResourceModel\Customer::_saveAddresses during _afterSave
      * addressOne - updated
      * addressTwo - removed
      * addressThree - removed
      * _item1 - new address
      */
     $addresses = $customer->getAddresses();
     $this->assertEquals(2, count($addresses));
     $updatedAddress = $this->addressRepository->getById(1);
     $this->assertEquals('update firstname', $updatedAddress->getFirstname());
     $newAddress = $this->accountManagement->getDefaultShippingAddress($customerId);
     $this->assertEquals('new firstname', $newAddress->getFirstname());
     /** @var \Magento\Newsletter\Model\Subscriber $subscriber */
     $subscriber = $this->objectManager->get('Magento\\Newsletter\\Model\\SubscriberFactory')->create();
     $this->assertEmpty($subscriber->getId());
     $subscriber->loadByCustomerId($customerId);
     $this->assertNotEmpty($subscriber->getId());
     $this->assertEquals(1, $subscriber->getStatus());
     $this->assertRedirect($this->stringStartsWith($this->_baseControllerUrl . 'index/key/'));
 }
Example #11
0
 /**
  * @param int $addressId
  * @return \Magento\Customer\Api\Data\AddressInterface|null
  */
 public function getAddressById($addressId)
 {
     try {
         return $this->addressRepository->getById($addressId);
     } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
         return null;
     }
 }
 /**
  * Populate customer model
  *
  * @param Quote $quote
  * @return void
  */
 public function populateCustomerInfo(QuoteEntity $quote)
 {
     $customer = $quote->getCustomer();
     if (!$customer->getId()) {
         $customer = $this->accountManagement->createAccountWithPasswordHash($customer, $quote->getPasswordHash());
         $quote->setCustomer($customer);
     } else {
         $this->customerRepository->save($customer);
     }
     if (!$quote->getBillingAddress()->getId() && $customer->getDefaultBilling()) {
         $quote->getBillingAddress()->importCustomerAddressData($this->customerAddressRepository->getById($customer->getDefaultBilling()));
         $quote->getBillingAddress()->setCustomerAddressId($customer->getDefaultBilling());
     }
     if (!$quote->getShippingAddress()->getSameAsBilling() && !$quote->getBillingAddress()->getId() && $customer->getDefaultShipping()) {
         $quote->getShippingAddress()->importCustomerAddressData($this->customerAddressRepository->getById($customer->getDefaultShipping()));
         $quote->getShippingAddress()->setCustomerAddressId($customer->getDefaultShipping());
     }
 }
 /**
  * {@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;
 }
Example #14
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);
             }
         }
     }
 }
 /**
  * {@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();
 }
 /**
  * {@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());
 }
Example #17
0
 /**
  * Reimport customer billing address to quote
  *
  * @param int $addressId customer address id
  * @return \Magento\Multishipping\Model\Checkout\Type\Multishipping
  */
 public function setQuoteCustomerBillingAddress($addressId)
 {
     try {
         $address = $this->addressRepository->getById($addressId);
     } catch (\Exception $e) {
         //
     }
     if (isset($address)) {
         $this->getQuote()->getBillingAddress($addressId)->importCustomerAddressData($address)->collectTotals();
         $this->getQuote()->collectTotals();
         $this->quoteRepository->save($this->getQuote());
     }
     return $this;
 }
 /**
  * @magentoDataFixture Magento/Customer/_files/customer.php
  * @magentoDataFixture Magento/Customer/_files/customer_address.php
  */
 public function testDeleteAddressById()
 {
     $addressId = 1;
     // See that customer already has an address with expected addressId
     $addressDataObject = $this->repository->getById($addressId);
     $this->assertEquals($addressDataObject->getId(), $addressId);
     // Delete the address from the customer
     $this->repository->deleteById($addressId);
     // See that address is deleted
     try {
         $addressDataObject = $this->repository->getById($addressId);
         $this->fail("Expected NoSuchEntityException not caught");
     } catch (NoSuchEntityException $exception) {
         $this->assertEquals('No such entity with addressId = 1', $exception->getMessage());
     }
 }
Example #19
0
 /**
  * Reimport customer billing address to quote
  *
  * @param int $addressId customer address id
  * @throws \Magento\Framework\Exception\LocalizedException
  * @return \Magento\Multishipping\Model\Checkout\Type\Multishipping
  */
 public function setQuoteCustomerBillingAddress($addressId)
 {
     if (!$this->isAddressIdApplicable($addressId)) {
         throw new LocalizedException(__('Please check billing address information.'));
     }
     try {
         $address = $this->addressRepository->getById($addressId);
     } catch (\Exception $e) {
         //
     }
     if (isset($address)) {
         $this->getQuote()->getBillingAddress($addressId)->importCustomerAddressData($address)->collectTotals();
         $this->getQuote()->collectTotals();
         $this->quoteRepository->save($this->getQuote());
     }
     return $this;
 }
Example #20
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();
 }
 public function aroundSaveAddressInformation(\Magento\Checkout\Model\ShippingInformationManagement $subject, \Closure $proceed, $cartId, ShippingInformationInterface $addressInformation)
 {
     // Only validate address if module is enabled
     $quote = $this->quoteRepository->getActive($cartId);
     $storeId = $quote->getStoreId();
     if (!$this->config->isModuleEnabled($storeId)) {
         $paymentDetails = $proceed($cartId, $addressInformation);
         $this->ensureTaxCalculationSuccess($storeId);
         return $paymentDetails;
     }
     // Only validate address if address validation is enabled
     if (!$this->config->isAddressValidationEnabled($storeId)) {
         $paymentDetails = $proceed($cartId, $addressInformation);
         $this->ensureTaxCalculationSuccess($storeId);
         return $paymentDetails;
     }
     // If quote is virtual, getShippingAddress will return billing address, so no need to check if quote is virtual
     $shippingAddress = $addressInformation->getShippingAddress();
     $shippingInformationExtension = $addressInformation->getExtensionAttributes();
     $errorMessage = null;
     $validAddress = null;
     $customerAddress = null;
     $quoteAddress = null;
     $shouldValidateAddress = true;
     if (!is_null($shippingInformationExtension)) {
         $shouldValidateAddress = $shippingInformationExtension->getShouldValidateAddress();
     }
     $customerAddressId = $shippingAddress->getCustomerAddressId();
     $enabledAddressValidationCountries = explode(',', $this->config->getAddressValidationCountriesEnabled($storeId));
     if (!in_array($shippingAddress->getCountryId(), $enabledAddressValidationCountries)) {
         $shouldValidateAddress = false;
     }
     if ($shouldValidateAddress) {
         try {
             $validAddress = $this->validationInteraction->validateAddress($shippingAddress, $storeId);
         } catch (AddressValidateException $e) {
             $errorMessage = $e->getMessage();
         } catch (\SoapFault $e) {
             // If there is a SoapFault, it will have already been logged, so just disable address validation, as we
             // don't want to display SoapFault error message to user
             $shouldValidateAddress = false;
         } catch (\Exception $e) {
             $this->avaTaxLogger->error('Error in validating address in aroundSaveAddressInformation: ' . $e->getMessage());
             // Continue without address validation
             $shouldValidateAddress = false;
         }
     }
     // Determine which address to save to the customer or shipping addresses
     if (!is_null($validAddress)) {
         $quoteAddress = $validAddress;
     } else {
         $quoteAddress = $shippingAddress;
     }
     try {
         /*
          * Regardless of whether address was validated by AvaTax, if the address is a customer address then we need
          * to save that address on the customer record. The reason for this is that when a user is on the "Review
          * & Payments" step and they are selecting between "Valid" and "Original" address options, the selected
          * address information is submitted to this API so that the customer address is updated and tax
          * calculation is affected accordingly.
          */
         if ($customerAddressId) {
             // Update the customer address
             $customerAddress = $this->customerAddressRepository->getById($customerAddressId);
             $mergedCustomerAddress = $this->addressInteraction->copyQuoteAddressToCustomerAddress($quoteAddress, $customerAddress);
             $this->customerAddressRepository->save($mergedCustomerAddress);
         } else {
             // Update the shipping address
             $addressInformation->setShippingAddress($quoteAddress);
         }
     } catch (\Exception $e) {
         // There may be scenarios in which the above address updating may fail, in which case we should just do
         // nothing
         $this->avaTaxLogger->error('Error in saving address: ' . $e->getMessage());
         // Continue without address validation
         $shouldValidateAddress = false;
     }
     $returnValue = $proceed($cartId, $addressInformation);
     $this->ensureTaxCalculationSuccess($storeId);
     if (!$shouldValidateAddress) {
         return $returnValue;
     }
     $paymentDetailsExtension = $returnValue->getExtensionAttributes();
     if (is_null($paymentDetailsExtension)) {
         $paymentDetailsExtension = $this->paymentDetailsExtensionFactory->create();
     }
     if (!is_null($validAddress)) {
         $paymentDetailsExtension->setValidAddress($validAddress);
     } else {
         $paymentDetailsExtension->setErrorMessage($errorMessage);
     }
     $paymentDetailsExtension->setOriginalAddress($shippingAddress);
     $returnValue->setExtensionAttributes($paymentDetailsExtension);
     return $returnValue;
 }
Example #22
0
 /**
  * Save checkout shipping address
  *
  * @param   array $data
  * @param   int $customerAddressId
  * @return  array
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function saveShipping($data, $customerAddressId)
 {
     if (empty($data)) {
         return ['error' => -1, 'message' => __('Invalid data')];
     }
     $address = $this->getQuote()->getShippingAddress();
     $addressForm = $this->_formFactory->create('customer_address', 'customer_address_edit', [], $this->_request->isAjax(), Form::IGNORE_INVISIBLE, []);
     if (!empty($customerAddressId)) {
         $addressData = null;
         try {
             $addressData = $this->addressRepository->getById($customerAddressId);
         } catch (NoSuchEntityException $e) {
             // do nothing if customer is not found by id
         }
         if ($addressData->getCustomerId() != $this->getQuote()->getCustomerId()) {
             return ['error' => 1, 'message' => __('The customer address is not valid.')];
         }
         $address->importCustomerAddressData($addressData)->setSaveInAddressBook(0);
         $addressErrors = $addressForm->validateData($address->getData());
         if ($addressErrors !== true) {
             return ['error' => 1, 'message' => $addressErrors];
         }
     } else {
         // emulate request object
         $addressData = $addressForm->extractData($addressForm->prepareRequest($data));
         $addressErrors = $addressForm->validateData($addressData);
         if ($addressErrors !== true) {
             return ['error' => 1, 'message' => $addressErrors];
         }
         $compactedData = $addressForm->compactData($addressData);
         // unset shipping address attributes which were not shown in form
         foreach ($addressForm->getAttributes() as $attribute) {
             $attributeCode = $attribute->getAttributeCode();
             if (!isset($data[$attributeCode])) {
                 $address->setData($attributeCode, null);
             } else {
                 $address->setDataUsingMethod($attributeCode, $compactedData[$attributeCode]);
             }
         }
         $address->setCustomerAddressId(null);
         // Additional form data, not fetched by extractData (as it fetches only attributes)
         $address->setSaveInAddressBook(empty($data['save_in_address_book']) ? 0 : 1);
         $address->setSameAsBilling(empty($data['same_as_billing']) ? 0 : 1);
     }
     $address->setCollectShippingRates(true);
     if (($validateRes = $address->validate()) !== true) {
         return ['error' => 1, 'message' => $validateRes];
     }
     $address->collectTotals()->save();
     $this->getCheckout()->setStepData('shipping', 'complete', true)->setStepData('shipping_method', 'allow', true);
     return [];
 }
Example #23
0
 /**
  * Create customer address and save it in the quote so that it can be used to persist later.
  *
  * @param \Magento\Customer\Api\Data\CustomerInterface $customer
  * @param \Magento\Quote\Model\Quote\Address $quoteCustomerAddress
  * @return void
  * @throws \InvalidArgumentException
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 protected function _prepareCustomerAddress($customer, $quoteCustomerAddress)
 {
     // Possible that customerId is null for new customers
     $quoteCustomerAddress->setCustomerId($customer->getId());
     $customerAddress = $quoteCustomerAddress->exportCustomerAddress();
     $quoteAddressId = $quoteCustomerAddress->getCustomerAddressId();
     $addressType = $quoteCustomerAddress->getAddressType();
     if ($quoteAddressId) {
         /** Update existing address */
         $existingAddressDataObject = $this->addressRepository->getById($quoteAddressId);
         /** Update customer address data */
         $this->dataObjectHelper->mergeDataObjects(get_class($existingAddressDataObject), $existingAddressDataObject, $customerAddress);
         $customerAddress = $existingAddressDataObject;
     } elseif ($addressType == \Magento\Quote\Model\Quote\Address::ADDRESS_TYPE_SHIPPING) {
         try {
             $billingAddressDataObject = $this->accountManagement->getDefaultBillingAddress($customer->getId());
         } catch (\Exception $e) {
             /** Billing address does not exist. */
         }
         $isShippingAsBilling = $quoteCustomerAddress->getSameAsBilling();
         if (isset($billingAddressDataObject) && $isShippingAsBilling) {
             /** Set existing billing address as default shipping */
             $customerAddress = $billingAddressDataObject;
             $customerAddress->setIsDefaultShipping(true);
         }
     }
     switch ($addressType) {
         case \Magento\Quote\Model\Quote\Address::ADDRESS_TYPE_BILLING:
             if (is_null($customer->getDefaultBilling())) {
                 $customerAddress->setIsDefaultBilling(true);
             }
             break;
         case \Magento\Quote\Model\Quote\Address::ADDRESS_TYPE_SHIPPING:
             if (is_null($customer->getDefaultShipping())) {
                 $customerAddress->setIsDefaultShipping(true);
             }
             break;
         default:
             throw new \InvalidArgumentException('Customer address type is invalid.');
     }
     $this->getQuote()->setCustomer($customer);
     $this->getQuote()->addCustomerAddress($customerAddress);
 }
Example #24
0
 /**
  * Assign customer model to quote with billing and shipping address change
  *
  * @param \Magento\Customer\Api\Data\CustomerInterface $customer
  * @param Address $billingAddress Quote billing address
  * @param Address $shippingAddress Quote shipping address
  * @return $this
  */
 public function assignCustomerWithAddressChange(\Magento\Customer\Api\Data\CustomerInterface $customer, Address $billingAddress = null, Address $shippingAddress = null)
 {
     if ($customer->getId()) {
         $this->setCustomer($customer);
         if (null !== $billingAddress) {
             $this->setBillingAddress($billingAddress);
         } else {
             try {
                 $defaultBillingAddress = $this->addressRepository->getById($customer->getDefaultBilling());
             } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
                 //
             }
             if (isset($defaultBillingAddress)) {
                 /** @var \Magento\Quote\Model\Quote\Address $billingAddress */
                 $billingAddress = $this->_quoteAddressFactory->create();
                 $billingAddress->importCustomerAddressData($defaultBillingAddress);
                 $this->setBillingAddress($billingAddress);
             }
         }
         if (null === $shippingAddress) {
             try {
                 $defaultShippingAddress = $this->addressRepository->getById($customer->getDefaultShipping());
             } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
                 //
             }
             if (isset($defaultShippingAddress)) {
                 /** @var \Magento\Quote\Model\Quote\Address $shippingAddress */
                 $shippingAddress = $this->_quoteAddressFactory->create();
                 $shippingAddress->importCustomerAddressData($defaultShippingAddress);
             } else {
                 $shippingAddress = $this->_quoteAddressFactory->create();
             }
         }
         $this->setShippingAddress($shippingAddress);
     }
     return $this;
 }