/**
  * @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);
     }
 }
Example #2
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;
 }
 /**
  * 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;
 }
 /**
  * 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;
 }
 /**
  * {@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();
 }
 /**
  * @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);
 }
Example #8
0
 public function testGetAddressCollectionJson()
 {
     $addressData = $this->_getAddresses();
     $searchResult = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\AddressSearchResultsInterface', [], '', false, true, true, ['getItems']);
     $searchResult->expects($this->any())->method('getItems')->will($this->returnValue($addressData));
     $this->addressRepository->expects($this->any())->method('getList')->will($this->returnValue($searchResult));
     $expectedOutput = '[
         {
             "firstname": false,
             "lastname": false,
             "company": false,
             "street": "",
             "city": false,
             "country_id": "US",
             "region": false,
             "region_id": false,
             "postcode": false,
             "telephone": false,
             "fax": false,
             "vat_id": false
         },
         {
             "firstname": "FirstName1",
             "lastname": "LastName1",
             "company": false,
             "street": "Street1",
             "city": false,
             "country_id": false,
             "region": false,
             "region_id": false,
             "postcode": false,
             "telephone": false,
             "fax": false,
             "vat_id": false
         },
         {
             "firstname": "FirstName2",
             "lastname": "LastName2",
             "company": false,
             "street": "Street2",
             "city": false,
             "country_id": false,
             "region": false,
             "region_id": false,
             "postcode": false,
             "telephone": false,
             "fax": false,
             "vat_id": false
         }
     ]';
     $expectedOutput = str_replace(['    ', "\n", "\r"], '', $expectedOutput);
     $expectedOutput = str_replace(': ', ':', $expectedOutput);
     $this->assertEquals($expectedOutput, $this->_addressBlock->getAddressCollectionJson());
 }
 /**
  * @return void
  */
 public function execute()
 {
     $filter = $this->filterBuilder->setField('parent_id')->setValue($this->_getCheckout()->getCustomer()->getId())->setConditionType('eq')->create();
     $addresses = (array) $this->addressRepository->getList($this->searchCriteriaBuilder->addFilters([$filter])->create())->getItems();
     /**
      * if we create first address we need reset emd init checkout
      */
     if (count($addresses) === 1) {
         $this->_getCheckout()->reset();
     }
     $this->_redirect('*/checkout/addresses');
 }
 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());
 }
Example #11
0
 /**
  * Get a list of current customer addresses.
  *
  * @return \Magento\Customer\Api\Data\AddressInterface[]
  */
 public function getAddress()
 {
     $addresses = $this->getData('address_collection');
     if ($addresses === null) {
         try {
             $filter = $this->filterBuilder->setField('parent_id')->setValue($this->_multishipping->getCustomer()->getId())->setConditionType('eq')->create();
             $addresses = (array) $this->addressRepository->getList($this->searchCriteriaBuilder->addFilters([$filter])->create())->getItems();
         } catch (NoSuchEntityException $e) {
             return [];
         }
         $this->setData('address_collection', $addresses);
     }
     return $addresses;
 }
 public function testPopulateCustomerInfo()
 {
     $this->quoteMock->expects($this->once())->method('getCustomer')->willReturn($this->customerMock);
     $this->customerMock->expects($this->atLeastOnce())->method('getId')->willReturn(null);
     $this->customerMock->expects($this->atLeastOnce())->method('getDefaultBilling')->willReturn(100500);
     $this->quoteMock->expects($this->atLeastOnce())->method('getBillingAddress')->willReturn($this->quoteAddressMock);
     $this->quoteMock->expects($this->atLeastOnce())->method('getShippingAddress')->willReturn($this->quoteAddressMock);
     $this->quoteMock->expects($this->atLeastOnce())->method('setCustomer')->with($this->customerMock)->willReturnSelf();
     $this->quoteMock->expects($this->once())->method('getPasswordHash')->willReturn('password hash');
     $this->quoteAddressMock->expects($this->atLeastOnce())->method('getId')->willReturn(null);
     $this->customerAddressRepositoryMock->expects($this->atLeastOnce())->method('getById')->with(100500)->willReturn($this->customerAddressMock);
     $this->quoteAddressMock->expects($this->atLeastOnce())->method('importCustomerAddressData')->willReturnSelf();
     $this->accountManagementMock->expects($this->once())->method('createAccountWithPasswordHash')->with($this->customerMock, 'password hash')->willReturn($this->customerMock);
     $this->customerManagement->populateCustomerInfo($this->quoteMock);
 }
Example #13
0
 public function testSetLayoutWithoutAddress()
 {
     $addressId = 1;
     $customerPrefix = 'prefix';
     $customerFirstName = 'firstname';
     $customerMiddlename = 'middlename';
     $customerLastname = 'lastname';
     $customerSuffix = 'suffix';
     $title = 'title';
     $layoutMock = $this->getMockBuilder('Magento\\Framework\\View\\LayoutInterface')->getMock();
     $this->requestMock->expects($this->once())->method('getParam')->with('id', null)->willReturn($addressId);
     $this->addressRepositoryMock->expects($this->once())->method('getById')->with($addressId)->willThrowException(\Magento\Framework\Exception\NoSuchEntityException::singleField('addressId', $addressId));
     $newAddressMock = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\AddressInterface')->getMock();
     $this->addressDataFactoryMock->expects($this->once())->method('create')->willReturn($newAddressMock);
     $customerMock = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\CustomerInterface')->getMock();
     $this->currentCustomerMock->expects($this->once())->method('getCustomer')->willReturn($customerMock);
     $customerMock->expects($this->once())->method('getPrefix')->willReturn($customerPrefix);
     $customerMock->expects($this->once())->method('getFirstname')->willReturn($customerFirstName);
     $customerMock->expects($this->once())->method('getMiddlename')->willReturn($customerMiddlename);
     $customerMock->expects($this->once())->method('getLastname')->willReturn($customerLastname);
     $customerMock->expects($this->once())->method('getSuffix')->willReturn($customerSuffix);
     $newAddressMock->expects($this->once())->method('setPrefix')->with($customerPrefix)->willReturnSelf();
     $newAddressMock->expects($this->once())->method('setFirstname')->with($customerFirstName)->willReturnSelf();
     $newAddressMock->expects($this->once())->method('setMiddlename')->with($customerMiddlename)->willReturnSelf();
     $newAddressMock->expects($this->once())->method('setLastname')->with($customerLastname)->willReturnSelf();
     $newAddressMock->expects($this->once())->method('setSuffix')->with($customerSuffix)->willReturnSelf();
     $pageTitleMock = $this->getMockBuilder('Magento\\Framework\\View\\Page\\Title')->disableOriginalConstructor()->getMock();
     $this->pageConfigMock->expects($this->once())->method('getTitle')->willReturn($pageTitleMock);
     $this->model->setData('title', $title);
     $pageTitleMock->expects($this->once())->method('set')->with($title)->willReturnSelf();
     $this->assertEquals($this->model, $this->model->setLayout($layoutMock));
     $this->assertEquals($layoutMock, $this->model->getLayout());
 }
 /**
  * @param \Magento\Framework\Api\Filter[] $filters
  * @param \Magento\Framework\Api\Filter[] $filterGroup
  * @param \Magento\Framework\Api\SortOrder[] $filterOrders
  * @param array $expectedResult array of expected results indexed by ID
  *
  * @dataProvider searchAddressDataProvider
  *
  * @magentoDataFixture  Magento/Customer/_files/customer.php
  * @magentoDataFixture  Magento/Customer/_files/customer_two_addresses.php
  * @magentoAppIsolation enabled
  */
 public function testSearchAddresses($filters, $filterGroup, $filterOrders, $expectedResult)
 {
     /** @var \Magento\Framework\Api\SearchCriteriaBuilder $searchBuilder */
     $searchBuilder = $this->_objectManager->create('Magento\\Framework\\Api\\SearchCriteriaBuilder');
     foreach ($filters as $filter) {
         $searchBuilder->addFilters([$filter]);
     }
     if ($filterGroup !== null) {
         $searchBuilder->addFilters($filterGroup);
     }
     if ($filterOrders !== null) {
         foreach ($filterOrders as $order) {
             $searchBuilder->addSortOrder($order);
         }
     }
     $searchResults = $this->repository->getList($searchBuilder->create());
     $this->assertEquals(count($expectedResult), $searchResults->getTotalCount());
     $i = 0;
     /** @var \Magento\Customer\Api\Data\AddressInterface $item*/
     foreach ($searchResults->getItems() as $item) {
         $this->assertEquals($expectedResult[$i]['id'], $item->getId());
         $this->assertEquals($expectedResult[$i]['city'], $item->getCity());
         $this->assertEquals($expectedResult[$i]['postcode'], $item->getPostcode());
         $this->assertEquals($expectedResult[$i]['firstname'], $item->getFirstname());
         $i++;
     }
 }
Example #15
0
 public function testExecuteWithException()
 {
     $addressId = 1;
     $customerId = 2;
     $this->resultRedirectFactory->expects($this->once())->method('create')->willReturn($this->resultRedirect);
     $this->request->expects($this->once())->method('getParam')->with('id', false)->willReturn($addressId);
     $this->validatorMock->expects($this->once())->method('validate')->with($this->request)->willReturn(true);
     $this->addressRepositoryMock->expects($this->once())->method('getById')->with($addressId)->willReturn($this->address);
     $this->sessionMock->expects($this->once())->method('getCustomerId')->willReturn($customerId);
     $this->address->expects($this->once())->method('getCustomerId')->willReturn(34);
     $exception = new \Exception('Exception');
     $this->messageManager->expects($this->once())->method('addError')->with(__('We can\'t delete the address right now.'))->willThrowException($exception);
     $this->messageManager->expects($this->once())->method('addException')->with($exception, __('We can\'t delete the address right now.'));
     $this->resultRedirect->expects($this->once())->method('setPath')->with('*/*/index')->willReturnSelf();
     $this->assertSame($this->resultRedirect, $this->model->execute());
 }
Example #16
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/'));
 }
 public function testCreateAccountWithPasswordHashWithCustomerAddresses()
 {
     $websiteId = 1;
     $addressId = 2;
     $customerId = null;
     $storeId = 1;
     $hash = '4nj54lkj5jfi03j49f8bgujfgsd';
     //Handle store
     $store = $this->getMockBuilder('Magento\\Store\\Model\\Store')->disableOriginalConstructor()->getMock();
     $store->expects($this->any())->method('getWebsiteId')->willReturn($websiteId);
     //Handle address - existing and non-existing. Non-Existing should return null when call getId method
     $existingAddress = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\AddressInterface')->disableOriginalConstructor()->getMock();
     $nonExistingAddress = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\AddressInterface')->disableOriginalConstructor()->getMock();
     //Ensure that existing address is not in use
     $this->addressRepository->expects($this->atLeastOnce())->method("save")->withConsecutive(array($this->logicalNot($this->identicalTo($existingAddress))), array($this->identicalTo($nonExistingAddress)));
     $existingAddress->expects($this->any())->method("getId")->willReturn($addressId);
     //Expects that id for existing address should be unset
     $existingAddress->expects($this->once())->method("setId")->with(null);
     //Handle Customer calls
     $customer = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\CustomerInterface')->getMock();
     $customer->expects($this->atLeastOnce())->method('getWebsiteId')->willReturn($websiteId);
     $customer->expects($this->atLeastOnce())->method('getStoreId')->willReturn($storeId);
     $customer->expects($this->any())->method("getId")->willReturn($customerId);
     //Return Customer from customer repositoryå
     $this->customerRepository->expects($this->atLeastOnce())->method('save')->willReturn($customer);
     $this->customerRepository->expects($this->once())->method('getById')->with($customerId)->willReturn($customer);
     $customerSecure = $this->getMockBuilder('Magento\\Customer\\Model\\Data\\CustomerSecure')->setMethods(['setRpToken', 'setRpTokenCreatedAt', 'getPasswordHash'])->disableOriginalConstructor()->getMock();
     $customerSecure->expects($this->once())->method('setRpToken')->with($hash);
     $customerSecure->expects($this->any())->method('getPasswordHash')->willReturn($hash);
     $this->customerRegistry->expects($this->any())->method('retrieveSecureData')->with($customerId)->willReturn($customerSecure);
     $this->random->expects($this->once())->method('getUniqueHash')->willReturn($hash);
     $customer->expects($this->atLeastOnce())->method('getAddresses')->willReturn([$existingAddress, $nonExistingAddress]);
     $this->storeManager->expects($this->atLeastOnce())->method('getStore')->willReturn($store);
     $this->assertSame($customer, $this->accountManagement->createAccountWithPasswordHash($customer, $hash));
 }
 /**
  * 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 #19
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;
     }
 }
Example #20
0
 /**
  * @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));
 }
 /**
  * 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;
 }
 /**
  * @When I add the address to my address book
  */
 public function iAddTheAddressToMyAddressBook()
 {
     try {
         $this->customerAddress = $this->addressRepository->save($this->customerAddress);
         $this->saveAddressException = null;
     } catch (LocalizedException $e) {
         $this->saveAddressException = $e;
     }
 }
 /**
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function testCreateAccountWithPassword()
 {
     $websiteId = 1;
     $storeId = null;
     $defaultStoreId = 1;
     $customerId = 1;
     $customerEmail = '*****@*****.**';
     $password = '******';
     $hash = '4nj54lkj5jfi03j49f8bgujfgsd';
     $newLinkToken = '2jh43j5h2345jh23lh452h345hfuzasd96ofu';
     $templateIdentifier = 'Template Identifier';
     $sender = 'Sender';
     $this->string->expects($this->any())->method('strlen')->willReturnCallback(function ($string) {
         return strlen($string);
     });
     $this->encryptor->expects($this->once())->method('getHash')->with($password, true)->willReturn($hash);
     $address = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\AddressInterface')->disableOriginalConstructor()->getMock();
     $address->expects($this->once())->method('setCustomerId')->with($customerId);
     $store = $this->getMockBuilder('Magento\\Store\\Model\\Store')->disableOriginalConstructor()->getMock();
     $store->expects($this->once())->method('getId')->willReturn($defaultStoreId);
     $website = $this->getMockBuilder('Magento\\Store\\Model\\Website')->disableOriginalConstructor()->getMock();
     $website->expects($this->atLeastOnce())->method('getStoreIds')->willReturn([1, 2, 3]);
     $website->expects($this->once())->method('getDefaultStore')->willReturn($store);
     $customer = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\CustomerInterface')->getMock();
     $customer->expects($this->atLeastOnce())->method('getId')->willReturn($customerId);
     $customer->expects($this->atLeastOnce())->method('getEmail')->willReturn($customerEmail);
     $customer->expects($this->atLeastOnce())->method('getWebsiteId')->willReturn($websiteId);
     $customer->expects($this->atLeastOnce())->method('getStoreId')->willReturn($storeId);
     $customer->expects($this->once())->method('setStoreId')->with($defaultStoreId);
     $customer->expects($this->once())->method('getAddresses')->willReturn([$address]);
     $customer->expects($this->once())->method('setAddresses')->with(null);
     $this->customerRepository->expects($this->once())->method('get')->with($customerEmail)->willReturn($customer);
     $this->share->expects($this->once())->method('isWebsiteScope')->willReturn(true);
     $this->storeManager->expects($this->atLeastOnce())->method('getWebsite')->with($websiteId)->willReturn($website);
     $this->customerRepository->expects($this->atLeastOnce())->method('save')->willReturn($customer);
     $this->addressRepository->expects($this->atLeastOnce())->method('save')->with($address);
     $this->customerRepository->expects($this->once())->method('getById')->with($customerId)->willReturn($customer);
     $this->random->expects($this->once())->method('getUniqueHash')->willReturn($newLinkToken);
     $customerSecure = $this->getMockBuilder('Magento\\Customer\\Model\\Data\\CustomerSecure')->setMethods(['setRpToken', 'setRpTokenCreatedAt', 'getPasswordHash'])->disableOriginalConstructor()->getMock();
     $customerSecure->expects($this->any())->method('setRpToken')->with($newLinkToken);
     $customerSecure->expects($this->any())->method('setRpTokenCreatedAt');
     $customerSecure->expects($this->any())->method('getPasswordHash')->willReturn($hash);
     $this->customerRegistry->expects($this->atLeastOnce())->method('retrieveSecureData')->willReturn($customerSecure);
     $this->dataObjectProcessor->expects($this->once())->method('buildOutputDataArray')->willReturn([]);
     $this->scopeConfig->expects($this->at(1))->method('getValue')->with(AccountManagement::XML_PATH_REGISTER_EMAIL_TEMPLATE, ScopeInterface::SCOPE_STORE, $defaultStoreId)->willReturn($templateIdentifier);
     $this->scopeConfig->expects($this->at(2))->method('getValue')->willReturn($sender);
     $transport = $this->getMockBuilder('Magento\\Framework\\Mail\\TransportInterface')->getMock();
     $this->transportBuilder->expects($this->once())->method('setTemplateIdentifier')->with($templateIdentifier)->willReturnSelf();
     $this->transportBuilder->expects($this->once())->method('setTemplateOptions')->willReturnSelf();
     $this->transportBuilder->expects($this->once())->method('setTemplateVars')->willReturnSelf();
     $this->transportBuilder->expects($this->once())->method('setFrom')->with($sender)->willReturnSelf();
     $this->transportBuilder->expects($this->once())->method('addTo')->willReturnSelf();
     $this->transportBuilder->expects($this->once())->method('getTransport')->willReturn($transport);
     $transport->expects($this->once())->method('sendMessage');
     $this->accountManagement->createAccount($customer, $password);
 }
Example #25
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();
 }
Example #27
0
 /**
  * Retrieve current customer address DATA collection.
  *
  * @return \Magento\Customer\Api\Data\AddressInterface[]
  */
 public function getAddressCollection()
 {
     if ($this->getCustomerId()) {
         $filter = $this->filterBuilder->setField('parent_id')->setValue($this->getCustomerId())->setConditionType('eq')->create();
         $this->searchCriteriaBuilder->addFilters([$filter]);
         $searchCriteria = $this->searchCriteriaBuilder->create();
         $result = $this->addressService->getList($searchCriteria);
         return $result->getItems();
     }
     return [];
 }
 /**
  * {@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());
 }
 /**
  *Set additional information for shipping address
  *
  * @param \Magento\Checkout\Model\ShippingInformationManagement $subject
  * @param callable $proceed
  *
  * @return \Magento\Checkout\Api\Data\PaymentDetailsInterface $paymentDetails
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 public function aroundSaveAddressInformation(\Magento\Checkout\Model\ShippingInformationManagement $subject, $proceed, $cartId, \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation)
 {
     try {
         $carrierCode = $addressInformation->getShippingCarrierCode();
         $methodCode = $addressInformation->getShippingMethodCode();
         $shippingMethod = $carrierCode . '_' . $methodCode;
         $quote = $this->quoteRepository->getActive($cartId);
         $address = $quote->getShippingAddress();
         $validation = $this->checkoutSession->getShipAddressValidation();
         if (is_array($validation) && isset($validation['key'])) {
             if (isset($validation['validation_status'])) {
                 $additionalDetail['address_valid'] = $validation['validation_status'];
                 $address->setValidationStatus($validation['validation_status']);
             }
             if (isset($validation['destination_type'])) {
                 $additionalDetail['destination_type'] = $validation['destination_type'];
                 $address->setDestinationType($validation['destination_type']);
             }
             $this->checkoutSession->setShipAddressValidation(null);
         }
         $address->save();
         $additionalDetail = new \Magento\Framework\DataObject();
         $extAttributes = $addressInformation->getShippingAddress()->getExtensionAttributes();
         //push out event so other modules can save their data TODO add carrier_group_id
         $this->eventManager->dispatch('shipperhq_additional_detail_checkout', ['address_extn_attributes' => $extAttributes, 'additional_detail' => $additionalDetail, 'carrier_code' => $carrierCode]);
         $additionalDetailArray = $additionalDetail->convertToArray();
         $this->shipperLogger->postDebug('ShipperHQ Shipper', 'processing additional detail ', $additionalDetail);
         $this->carrierGroupHelper->saveCarrierGroupInformation($address, $shippingMethod, $additionalDetailArray);
     } catch (\Exception $e) {
         $this->shipperLogger->postCritical('Shipperhq_Shipper', 'Shipping Information Plugin', 'Exception raised ' . $e->getMessage());
     }
     $result = $proceed($cartId, $addressInformation);
     if ($address->getCustomerId()) {
         $customerAddresses = $quote->getCustomer()->getAddresses();
         foreach ($customerAddresses as $oneAddress) {
             if ($oneAddress->getId() == $address->getCustomerAddressId()) {
                 if ($address->getValidationStatus()) {
                     $oneAddress->setCustomAttribute('validation_status', $address->getValidationStatus());
                 }
                 if ($address->getDestinationType()) {
                     $oneAddress->setCustomAttribute('destination_type', $address->getDestinationType());
                 }
                 $this->addressRepository->save($oneAddress);
             }
         }
     }
     return $result;
 }
 /**
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function testCreateAccountWithPassword()
 {
     $websiteId = 1;
     $storeId = null;
     $defaultStoreId = 1;
     $customerId = 1;
     $customerEmail = '*****@*****.**';
     $hash = '4nj54lkj5jfi03j49f8bgujfgsd';
     $newLinkToken = '2jh43j5h2345jh23lh452h345hfuzasd96ofu';
     $templateIdentifier = 'Template Identifier';
     $sender = 'Sender';
     $password = '******';
     $minPasswordLength = 5;
     $minCharacterSetsNum = 2;
     $this->scopeConfig->expects($this->any())->method('getValue')->willReturnMap([[AccountManagement::XML_PATH_MINIMUM_PASSWORD_LENGTH, 'default', null, $minPasswordLength], [AccountManagement::XML_PATH_REQUIRED_CHARACTER_CLASSES_NUMBER, 'default', null, $minCharacterSetsNum], [AccountManagement::XML_PATH_REGISTER_EMAIL_TEMPLATE, ScopeInterface::SCOPE_STORE, $defaultStoreId, $templateIdentifier], [AccountManagement::XML_PATH_REGISTER_EMAIL_IDENTITY, ScopeInterface::SCOPE_STORE, 1, $sender]]);
     $this->string->expects($this->any())->method('strlen')->with($password)->willReturn(iconv_strlen($password, 'UTF-8'));
     $this->encryptor->expects($this->once())->method('getHash')->with($password, true)->willReturn($hash);
     $address = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\AddressInterface')->disableOriginalConstructor()->getMock();
     $address->expects($this->once())->method('setCustomerId')->with($customerId);
     $store = $this->getMockBuilder('Magento\\Store\\Model\\Store')->disableOriginalConstructor()->getMock();
     $store->expects($this->once())->method('getId')->willReturn($defaultStoreId);
     $website = $this->getMockBuilder('Magento\\Store\\Model\\Website')->disableOriginalConstructor()->getMock();
     $website->expects($this->atLeastOnce())->method('getStoreIds')->willReturn([1, 2, 3]);
     $website->expects($this->once())->method('getDefaultStore')->willReturn($store);
     $customer = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\CustomerInterface')->getMock();
     $customer->expects($this->atLeastOnce())->method('getId')->willReturn($customerId);
     $customer->expects($this->atLeastOnce())->method('getEmail')->willReturn($customerEmail);
     $customer->expects($this->atLeastOnce())->method('getWebsiteId')->willReturn($websiteId);
     $customer->expects($this->atLeastOnce())->method('getStoreId')->willReturn($storeId);
     $customer->expects($this->once())->method('setStoreId')->with($defaultStoreId);
     $customer->expects($this->once())->method('getAddresses')->willReturn([$address]);
     $customer->expects($this->once())->method('setAddresses')->with(null);
     $this->customerRepository->expects($this->once())->method('get')->with($customerEmail)->willReturn($customer);
     $this->share->expects($this->once())->method('isWebsiteScope')->willReturn(true);
     $this->storeManager->expects($this->atLeastOnce())->method('getWebsite')->with($websiteId)->willReturn($website);
     $this->customerRepository->expects($this->atLeastOnce())->method('save')->willReturn($customer);
     $this->addressRepository->expects($this->atLeastOnce())->method('save')->with($address);
     $this->customerRepository->expects($this->once())->method('getById')->with($customerId)->willReturn($customer);
     $this->random->expects($this->once())->method('getUniqueHash')->willReturn($newLinkToken);
     $customerSecure = $this->getMockBuilder('Magento\\Customer\\Model\\Data\\CustomerSecure')->setMethods(['setRpToken', 'setRpTokenCreatedAt', 'getPasswordHash'])->disableOriginalConstructor()->getMock();
     $customerSecure->expects($this->any())->method('setRpToken')->with($newLinkToken);
     $customerSecure->expects($this->any())->method('setRpTokenCreatedAt');
     $customerSecure->expects($this->any())->method('getPasswordHash')->willReturn($hash);
     $this->customerRegistry->expects($this->atLeastOnce())->method('retrieveSecureData')->willReturn($customerSecure);
     $this->emailNotificationMock->expects($this->once())->method('newAccount')->willReturnSelf();
     $this->accountManagement->createAccount($customer, $password);
 }