Example #1
0
 /**
  * @return void
  */
 public function execute()
 {
     /**
      * if we create first address we need reset emd init checkout
      */
     $customerId = $this->_getCheckout()->getCustomer()->getId();
     if (count($this->_customerAddressService->getAddresses($customerId)) == 1) {
         $this->_getCheckout()->reset();
     }
     $this->_redirect('*/checkout/addresses');
 }
Example #2
0
 public function testGetAddressCollectionJson()
 {
     $addressData = $this->_getAddresses();
     $this->_addressService->expects($this->any())->method('getAddresses')->will($this->returnValue($addressData));
     $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(array('    ', "\n", "\r"), '', $expectedOutput);
     $expectedOutput = str_replace(': ', ':', $expectedOutput);
     $this->assertEquals($expectedOutput, $this->_addressBlock->getAddressCollectionJson());
 }
Example #3
0
 /**
  * Get a list of current customer addresses.
  *
  * @return \Magento\Customer\Service\V1\Data\Address[]
  */
 public function getAddressCollection()
 {
     $addresses = $this->getData('address_collection');
     if (is_null($addresses)) {
         try {
             $addresses = $this->_customerAddressService->getAddresses($this->_multishipping->getCustomer()->getId());
         } catch (NoSuchEntityException $e) {
             return array();
         }
         $this->setData('address_collection', $addresses);
     }
     return $addresses;
 }
Example #4
0
 /**
  * Retrieve current customer address DATA collection.
  *
  * @return \Magento\Customer\Service\V1\Data\Address[]
  */
 public function getAddressCollection()
 {
     if ($this->getCustomerId()) {
         return $this->_addressService->getAddresses($this->getCustomerId());
     }
     return array();
 }
Example #5
0
 /**
  * @param int $addressId
  * @return \Magento\Customer\Service\V1\Data\Address|null
  */
 public function getAddressById($addressId)
 {
     try {
         return $this->_addressService->getAddress($addressId);
     } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
         return null;
     }
 }
Example #6
0
 /**
  * @return string|null
  */
 public function getBillingAddressHtml()
 {
     try {
         $address = $this->_addressService->getAddress($this->getCustomer()->getDefaultBilling());
     } catch (NoSuchEntityException $e) {
         return __('The customer does not have default billing address.');
     }
     return $this->_addressHelper->getFormatTypeRenderer('html')->renderArray(AddressConverter::toFlatArray($address));
 }
Example #7
0
 /**
  * Put existing customer data into the backend session
  */
 protected function setupExistingCustomerData()
 {
     /** @var Customer $customer */
     $customer = $this->_customerAccountService->getCustomer(1);
     $this->_customerData = array('customer_id' => $customer->getId(), 'account' => \Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($customer));
     $this->_customerData['account']['id'] = $customer->getId();
     /** @var Address[] $addresses */
     $addresses = $this->_addressService->getAddresses(1);
     foreach ($addresses as $addressData) {
         $this->_customerData['address'][$addressData->getId()] = AddressConverter::toFlatArray($addressData);
         $this->_customerData['address'][$addressData->getId()]['id'] = $addressData->getId();
     }
     $this->_backendSession->setCustomerData($this->_customerData);
 }
 public function testValidateAddressesOneInvalidNoKeys()
 {
     $invalidAddress = $this->_addressBuilder->setFirstname('Freddy')->setLastname('Mercury')->create();
     try {
         $this->_service->validateAddresses(array_merge($this->_expectedAddresses, array($invalidAddress)));
         $this->fail("InputException was expected but not thrown");
     } catch (InputException $actualException) {
         $expectedException = new InputException();
         $expectedException->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'street', 'index' => 2]);
         $expectedException->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'city', 'index' => 2]);
         $expectedException->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'telephone', 'index' => 2]);
         $expectedException->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'postcode', 'index' => 2]);
         $expectedException->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'countryId', 'index' => 2]);
         $this->assertEquals($expectedException, $actualException);
     }
 }
 /**
  * @dataProvider saveBillingDataProvider
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function testSaveBilling($data, $customerAddressId, $quoteCustomerId, $addressCustomerId, $isAddress, $validateDataResult, $validateResult, $checkoutMethod, $customerPassword, $confirmPassword, $validationResultMessages, $isEmailAvailable, $isVirtual, $getStepDataResult, $expected)
 {
     $passwordHash = 'password hash';
     $this->requestMock->expects($this->any())->method('isAjax')->will($this->returnValue(false));
     $customerValidationResultMock = $this->getMock('Magento\\Customer\\Service\\V1\\Data\\CustomerValidationResults', [], [], '', false);
     $customerValidationResultMock->expects($this->any())->method('isValid')->will($this->returnValue(empty($validationResultMessages)));
     $customerValidationResultMock->expects($this->any())->method('getMessages')->will($this->returnValue($validationResultMessages));
     $this->customerAccountServiceMock->expects($this->any())->method('getPasswordHash')->with($customerPassword)->will($this->returnValue($passwordHash));
     $this->customerAccountServiceMock->expects($this->any())->method('validateCustomerData')->will($this->returnValue($customerValidationResultMock));
     $this->customerAccountServiceMock->expects($this->any())->method('isEmailAvailable')->will($this->returnValue($isEmailAvailable));
     /** @var \Magento\Sales\Model\Quote|\PHPUnit_Framework_MockObject_MockObject $quoteMock */
     $quoteMock = $this->getMock('Magento\\Sales\\Model\\Quote', ['getCustomerId', '__wakeup', 'getBillingAddress', 'setPasswordHash', 'getCheckoutMethod', 'isVirtual', 'getShippingAddress', 'getCustomerData', 'collectTotals', 'save'], [], '', false);
     $shippingAddressMock = $this->getMock('Magento\\Sales\\Model\\Quote\\Address', ['setSameAsBilling', '__wakeup', 'unserialize'], [], '', false);
     $shippingAddressMock->expects($this->any())->method('setSameAsBilling')->with((int) $data['use_for_shipping']);
     $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));
     $quoteMock->expects($this->any())->method('getShippingAddress')->will($this->returnValue($shippingAddressMock));
     $addressMock = $this->getMock('Magento\\Sales\\Model\\Quote\\Address', ['setSaveInAddressBook', 'getData', 'setEmail', '__wakeup', 'importCustomerAddressData', 'validate'], [], '', 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));
     $formMock = $this->getMock('Magento\\Customer\\Model\\Metadata\\Form', [], [], '', false);
     $formMock->expects($this->atLeastOnce())->method('validateData')->will($this->returnValue($validateDataResult));
     $this->requestMock->expects($this->any())->method('getParam')->will($this->returnValueMap([['customer_password', $customerPassword], ['confirm_password', $confirmPassword]]));
     $formMock->expects($this->any())->method('prepareRequest')->will($this->returnValue($this->requestMock));
     $this->customerFormFactoryMock->expects($this->any())->method('create')->will($this->returnValue($formMock));
     $customerDataMock = $this->getMock('Magento\\Customer\\Service\\V1\\Data\\Customer', [], [], '', false);
     $customerDataMock->expects($this->any())->method('__toArray')->will($this->returnValue([]));
     $this->customerBuilderMock->expects($this->any())->method('create')->will($this->returnValue($customerDataMock));
     $quoteMock->expects($this->atLeastOnce())->method('getCustomerData')->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((int) $data['use_for_shipping'] === 1 ? true : $getStepDataResult));
     $this->checkoutSessionMock->expects($this->any())->method('setStepData')->will($this->returnSelf());
     $customerAddressMock = $this->getMock('Magento\\Customer\\Service\\V1\\Data\\Address', [], [], '', false);
     $customerAddressMock->expects($this->any())->method('getCustomerId')->will($this->returnValue($addressCustomerId));
     $this->customerAddressServiceMock->expects($this->any())->method('getAddress')->will($isAddress ? $this->returnValue($customerAddressMock) : $this->throwException(new \Exception()));
     $this->customerBuilderMock->expects($checkoutMethod === Onepage::METHOD_REGISTER ? $this->never() : $this->once())->method('populate');
     $this->customerBuilderMock->expects($checkoutMethod === Onepage::METHOD_REGISTER ? $this->never() : $this->once())->method('setGroupId');
     $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));
 }
Example #10
0
 /**
  * @magentoDataFixture Magento/Sales/_files/quote.php
  */
 public function testSubmitOrderExistingCustomer()
 {
     $this->_prepareQuote(false);
     $customerDetails = $this->_customerDetailsBuilder->setCustomer($this->getSampleCustomerEntity())->setAddresses($this->getSampleAddressEntity())->create();
     $customerData = $this->_customerAccountService->createCustomer($customerDetails, 'password');
     $existingCustomerId = $customerData->getId();
     $customerData = $this->_customerBuilder->mergeDataObjectWithArray($customerData, array(CustomerData::EMAIL => '*****@*****.**'));
     $addresses = $this->_customerAddressService->getAddresses($existingCustomerId);
     $this->_serviceQuote->getQuote()->setCustomerData($customerData);
     $this->_serviceQuote->getQuote()->setCustomerAddressData($addresses);
     $this->_serviceQuote->submitOrderWithDataObject();
     $customerId = $this->_serviceQuote->getQuote()->getCustomerData()->getId();
     $this->assertNotNull($customerId);
     //Make sure no new customer is created
     $this->assertEquals($existingCustomerId, $customerId);
     $customerData = $this->_customerAccountService->getCustomer($existingCustomerId);
     $this->assertEquals('*****@*****.**', $customerData->getEmail());
 }
Example #11
0
 /**
  * Retrieve the customer's primary addresses (i.e. default billing and shipping).
  *
  * @return \Magento\Customer\Service\V1\Data\Address[]|bool
  */
 public function getPrimaryAddresses()
 {
     $addresses = array();
     $customerId = $this->getCustomer()->getId();
     if ($defaultBilling = $this->_addressService->getDefaultBillingAddress($customerId)) {
         $addresses[] = $defaultBilling;
     }
     if ($defaultShipping = $this->_addressService->getDefaultShippingAddress($customerId)) {
         if ($defaultBilling) {
             if ($defaultBilling->getId() != $defaultShipping->getId()) {
                 $addresses[] = $defaultShipping;
             }
         } else {
             $addresses[] = $defaultShipping;
         }
     }
     return empty($addresses) ? false : $addresses;
 }
Example #12
0
 /**
  * Retrieve options for addresses dropdown
  *
  * @return array
  */
 public function getAddressOptions()
 {
     $options = $this->getData('address_options');
     if (is_null($options)) {
         $options = [];
         $addresses = [];
         try {
             $addresses = $this->_customerAddressService->getAddresses($this->getCustomerId());
         } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
             /** Customer does not exist */
         }
         /** @var \Magento\Customer\Service\V1\Data\Address $address */
         foreach ($addresses as $address) {
             $label = $this->_addressConfig->getFormatByCode(AddressConfig::DEFAULT_ADDRESS_FORMAT)->getRenderer()->renderArray(\Magento\Customer\Service\V1\Data\AddressConverter::toFlatArray($address));
             $options[] = ['value' => $address->getId(), 'label' => $label];
         }
         $this->setData('address_options', $options);
     }
     return $options;
 }
Example #13
0
 /**
  * @magentoDataFixture Magento/Customer/_files/customer_sample.php
  */
 public function testSaveActionExistingCustomerAndExistingAddressData()
 {
     $post = array('customer_id' => '1', 'account' => array('middlename' => 'test middlename', 'group_id' => 1, 'website_id' => 1, 'firstname' => 'test firstname', 'lastname' => 'test lastname', 'email' => '*****@*****.**', 'default_shipping' => '_item1', 'new_password' => 'auto', 'sendemail_store_id' => '1', 'sendemail' => '1'), 'address' => array('1' => array('firstname' => 'update firstname', 'lastname' => 'update lastname', 'street' => array('update street'), 'city' => 'update city', 'country_id' => 'US', 'postcode' => '01001', 'telephone' => '+7000000001'), '_item1' => array('firstname' => 'new firstname', 'lastname' => 'new lastname', 'street' => array('new street'), 'city' => 'new city', 'country_id' => 'US', 'postcode' => '01001', 'telephone' => '+7000000001'), '_template_' => array('firstname' => '', 'lastname' => '', 'street' => array(), 'city' => '', 'country_id' => 'US', 'postcode' => '', 'telephone' => '')), 'subscription' => '');
     $this->getRequest()->setPost($post);
     $this->getRequest()->setParam('customer_id', 1);
     $this->dispatch('backend/customer/index/save');
     /**
      * Check that success message is set
      */
     $this->assertSessionMessages($this->equalTo(array('You saved the customer.')), \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS);
     /** @var $objectManager \Magento\TestFramework\ObjectManager */
     $objectManager = Bootstrap::getObjectManager();
     /**
      * Check that customer id set and addresses saved
      */
     $registry = $objectManager->get('Magento\\Framework\\Registry');
     $customerId = $registry->registry(RegistryConstants::CURRENT_CUSTOMER_ID);
     $customer = $this->customerAccountService->getCustomer($customerId);
     $this->assertEquals('test firstname', $customer->getFirstname());
     /**
      * Addresses should be removed by \Magento\Customer\Model\Resource\Customer::_saveAddresses during _afterSave
      * addressOne - updated
      * addressTwo - removed
      * addressThree - removed
      * _item1 - new address
      */
     $addresses = $this->customerAddressService->getAddresses($customerId);
     $this->assertEquals(2, count($addresses));
     $updatedAddress = $this->customerAddressService->getAddress(1);
     $this->assertEquals('update firstname', $updatedAddress->getFirstname());
     $newAddress = $this->customerAddressService->getDefaultShippingAddress($customerId);
     $this->assertEquals('new firstname', $newAddress->getFirstname());
     /** @var \Magento\Newsletter\Model\Subscriber $subscriber */
     $subscriber = $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 #14
0
 /**
  * Get order data jason
  *
  * @return string
  */
 public function getOrderDataJson()
 {
     $data = array();
     if ($this->getCustomerId()) {
         $data['customer_id'] = $this->getCustomerId();
         $data['addresses'] = array();
         $addresses = $this->_addressService->getAddresses($this->getCustomerId());
         foreach ($addresses as $addressData) {
             $addressForm = $this->_customerFormFactory->create('customer_address', 'adminhtml_customer_address', AddressConverter::toFlatArray($addressData));
             $data['addresses'][$addressData->getId()] = $addressForm->outputData(\Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_JSON);
         }
     }
     if (!is_null($this->getStoreId())) {
         $data['store_id'] = $this->getStoreId();
         $currency = $this->_localeCurrency->getCurrency($this->getStore()->getCurrentCurrencyCode());
         $symbol = $currency->getSymbol() ? $currency->getSymbol() : $currency->getShortName();
         $data['currency_symbol'] = $symbol;
         $data['shipping_method_reseted'] = !(bool) $this->getQuote()->getShippingAddress()->getShippingMethod();
         $data['payment_method'] = $this->getQuote()->getPayment()->getMethod();
     }
     return $this->_jsonEncoder->encode($data);
 }
Example #15
0
 /**
  * @param string $type
  * @return string
  */
 public function getAddressesHtmlSelect($type)
 {
     if ($this->isCustomerLoggedIn()) {
         $customerId = $this->_getCustomerData()->getId();
         $options = array();
         try {
             $addresses = $this->_customerAddressService->getAddresses($customerId);
         } catch (NoSuchEntityException $e) {
             $addresses = array();
         }
         foreach ($addresses as $address) {
             /** @var \Magento\Customer\Service\V1\Data\Address $address */
             $label = $this->_addressConfig->getFormatByCode(AddressConfig::DEFAULT_ADDRESS_FORMAT)->getRenderer()->renderArray(\Magento\Customer\Service\V1\Data\AddressConverter::toFlatArray($address));
             $options[] = array('value' => $address->getId(), 'label' => $label);
         }
         $addressId = $this->getAddress()->getCustomerAddressId();
         if (empty($addressId)) {
             try {
                 if ($type == 'billing') {
                     $address = $this->_customerAddressService->getDefaultBillingAddress($customerId);
                 } else {
                     $address = $this->_customerAddressService->getDefaultShippingAddress($customerId);
                 }
                 if ($address) {
                     $addressId = $address->getId();
                 }
             } catch (NoSuchEntityException $e) {
                 // Do nothing
             }
         }
         $select = $this->getLayout()->createBlock('Magento\\Framework\\View\\Element\\Html\\Select')->setName($type . '_address_id')->setId($type . '-address-select')->setClass('address-select')->setValue($addressId)->setOptions($options);
         $select->addOption('', __('New Address'));
         return $select->getHtml();
     }
     return '';
 }
Example #16
0
 /**
  * Returns default shipping address for current customer
  *
  * @return Address|null
  */
 public function getDefaultShippingAddress()
 {
     return $this->customerAddressService->getDefaultShippingAddress($this->currentCustomer->getCustomerId());
 }
Example #17
0
 /**
  * Returns true if shipping address is same as billing or it is undefined
  *
  * @return bool
  */
 protected function _isDefaultShippingNullOrSameAsBillingAddress()
 {
     $customerData = $this->getQuote()->getCustomerData();
     $customerId = $customerData->getId();
     $defaultBillingAddress = null;
     $defaultShippingAddress = null;
     if ($customerId) {
         /* we should load data from the service once customer is saved */
         $defaultBillingAddress = $this->_customerAdressService->getDefaultBillingAddress($customerId);
         $defaultShippingAddress = $this->_customerAdressService->getDefaultShippingAddress($customerId);
     } else {
         /* we should load data from the quote if customer is not saved yet */
         $defaultBillingAddress = $customerData->getDefaultBilling();
         $defaultShippingAddress = $customerData->getDefaultShipping();
     }
     return !$defaultShippingAddress || $defaultBillingAddress && $defaultShippingAddress && $defaultBillingAddress->getId() == $defaultShippingAddress->getId();
 }
Example #18
0
 /**
  * Save checkout shipping address
  *
  * @param   array $data
  * @param   int $customerAddressId
  * @return  array
  */
 public function saveShipping($data, $customerAddressId)
 {
     if (empty($data)) {
         return array('error' => -1, 'message' => __('Invalid data'));
     }
     $address = $this->getQuote()->getShippingAddress();
     $addressForm = $this->_formFactory->create('customer_address', 'customer_address_edit', array(), $this->_request->isAjax(), Form::IGNORE_INVISIBLE, array());
     if (!empty($customerAddressId)) {
         $addressData = null;
         try {
             $addressData = $this->_customerAddressService->getAddress($customerAddressId);
         } catch (NoSuchEntityException $e) {
             // do nothing if customer is not found by id
         }
         if ($addressData->getCustomerId() != $this->getQuote()->getCustomerId()) {
             return array('error' => 1, 'message' => __('The customer address is not valid.'));
         }
         $address->importCustomerAddressData($addressData)->setSaveInAddressBook(0);
         $addressErrors = $addressForm->validateData($address->getData());
         if ($addressErrors !== true) {
             return array('error' => 1, 'message' => $addressErrors);
         }
     } else {
         // emulate request object
         $addressData = $addressForm->extractData($addressForm->prepareRequest($data));
         $addressErrors = $addressForm->validateData($addressData);
         if ($addressErrors !== true) {
             return array('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 array('error' => 1, 'message' => $validateRes);
     }
     $this->getQuote()->collectTotals()->save();
     $this->getCheckout()->setStepData('shipping', 'complete', true)->setStepData('shipping_method', 'allow', true);
     return array();
 }
Example #19
0
 /**
  * Create customerAddressDataObject and save it in the Model\Quote so that it can be used to persist later.
  *
  * @param CustomerDataObject $customerDataObject
  * @param \Magento\Sales\Model\Quote\Address $quoteCustomerAddress
  * @return void
  * @throws \InvalidArgumentException
  */
 protected function _prepareCustomerAddress($customerDataObject, $quoteCustomerAddress)
 {
     // Possible that customerId is null for new customers
     $customerId = $customerDataObject->getId();
     $quoteCustomerAddress->setCustomerId($customerId);
     $customerAddressDataObject = $quoteCustomerAddress->exportCustomerAddressData();
     $quoteAddressId = $quoteCustomerAddress->getCustomerAddressId();
     $addressType = $quoteCustomerAddress->getAddressType();
     if ($quoteAddressId) {
         /** Update existing address */
         $existingAddressDataObject = $this->_customerAddressService->getAddress($quoteAddressId);
         /** Update customer address data */
         $customerAddressDataObject = $this->_customerAddressBuilder->mergeDataObjects($existingAddressDataObject, $customerAddressDataObject);
     } elseif ($addressType == CustomerAddressDataObject::ADDRESS_TYPE_SHIPPING) {
         try {
             $billingAddressDataObject = $this->_customerAddressService->getDefaultBillingAddress($customerId);
         } catch (\Exception $e) {
             /** Billing address does not exist. */
         }
         $isShippingAsBilling = $quoteCustomerAddress->getSameAsBilling();
         if (isset($billingAddressDataObject) && $isShippingAsBilling) {
             /** Set existing billing address as default shipping */
             $customerAddressDataObject = $this->_customerAddressBuilder->populate($billingAddressDataObject)->setDefaultShipping(true)->create();
         }
     }
     switch ($addressType) {
         case CustomerAddressDataObject::ADDRESS_TYPE_BILLING:
             if (is_null($customerDataObject->getDefaultBilling())) {
                 $customerAddressDataObject = $this->_customerAddressBuilder->populate($customerAddressDataObject)->setDefaultBilling(true)->create();
             }
             break;
         case CustomerAddressDataObject::ADDRESS_TYPE_SHIPPING:
             if (is_null($customerDataObject->getDefaultShipping())) {
                 $customerAddressDataObject = $this->_customerAddressBuilder->populate($customerAddressDataObject)->setDefaultShipping(true)->create();
             }
             break;
         default:
             throw new \InvalidArgumentException('Customer address type is invalid.');
     }
     $this->getQuote()->addCustomerAddressData($customerAddressDataObject);
 }
Example #20
0
 /**
  * Retrieve customer default shipping address
  *
  * @return \Magento\Customer\Service\V1\Data\Address|null
  */
 public function getCustomerDefaultShippingAddress()
 {
     $address = $this->getData('customer_default_shipping_address');
     if (is_null($address)) {
         $customerId = $this->getCustomer()->getId();
         $address = $this->_customerAddressService->getDefaultShippingAddress($customerId);
         if (!$address) {
             /** Default shipping address is not available, try to find any customer address */
             $allAddresses = $this->_customerAddressService->getAddresses($customerId);
             $address = count($allAddresses) ? reset($allAddresses) : null;
         }
         $this->setData('customer_default_shipping_address', $address);
     }
     return $address;
 }
 /**
  * {inheritDoc}
  */
 public function getCustomerDetailsByEmail($customerEmail, $websiteId = null)
 {
     $customerData = $this->getCustomerByEmail($customerEmail, $websiteId);
     return $this->customerDetailsBuilder->setCustomer($customerData)->setAddresses($this->customerAddressService->getAddresses($customerData->getId()))->create();
 }
Example #22
0
 /**
  * Retrieve the number of addresses associated with the customer given a customer Id.
  *
  * @return int
  */
 public function getCustomerAddressCount()
 {
     return count($this->_addressService->getAddresses($this->_customerSession->getCustomerId()));
 }
Example #23
0
 /**
  * Submit the quote. Quote submit process will create the order based on quote data
  *
  * @return \Magento\Sales\Model\Order
  * @throws \Exception
  */
 public function submitOrderWithDataObject()
 {
     $this->_deleteNominalItems();
     $this->_validate();
     $quote = $this->_quote;
     $isVirtual = $quote->isVirtual();
     $transaction = $this->_transactionFactory->create();
     $customerData = null;
     if (!$quote->getCustomerIsGuest()) {
         $customerData = $quote->getCustomerData();
         $addresses = $quote->getCustomerAddressData();
         $customerDetails = $this->_customerDetailsBuilder->setCustomer($customerData)->setAddresses($addresses)->create();
         if ($customerData->getId()) {
             $this->_customerAccountService->updateCustomer($customerDetails);
         } else {
             //for new customers
             $customerData = $this->_customerAccountService->createCustomerWithPasswordHash($customerDetails, $quote->getPasswordHash());
             $addresses = $this->_customerAddressService->getAddresses($customerData->getId());
             //Update quote address information
             foreach ($addresses as $address) {
                 if ($address->isDefaultBilling()) {
                     $quote->getBillingAddress()->setCustomerAddressData($address);
                 } else {
                     if ($address->isDefaultShipping()) {
                         $quote->getShippingAddress()->setCustomerAddressData($address);
                     }
                 }
             }
             if ($quote->getShippingAddress() && $quote->getShippingAddress()->getSameAsBilling()) {
                 $quote->getShippingAddress()->setCustomerAddressData($quote->getBillingAddress()->getCustomerAddressData());
             }
         }
         $quote->setCustomerData($customerData)->setCustomerAddressData($addresses);
     }
     $transaction->addObject($quote);
     $quote->reserveOrderId();
     if ($isVirtual) {
         $order = $this->_convertor->addressToOrder($quote->getBillingAddress());
     } else {
         $order = $this->_convertor->addressToOrder($quote->getShippingAddress());
     }
     $order->setBillingAddress($this->_convertor->addressToOrderAddress($quote->getBillingAddress()));
     if ($quote->getBillingAddress()->getCustomerAddressData()) {
         $order->getBillingAddress()->setCustomerAddressData($quote->getBillingAddress()->getCustomerAddressData());
     }
     if (!$isVirtual) {
         $order->setShippingAddress($this->_convertor->addressToOrderAddress($quote->getShippingAddress()));
         if ($quote->getShippingAddress()->getCustomerAddressData()) {
             $order->getShippingAddress()->setCustomerAddressData($quote->getShippingAddress()->getCustomerAddressData());
         }
     }
     $order->setPayment($this->_convertor->paymentToOrderPayment($quote->getPayment()));
     foreach ($this->_orderData as $key => $value) {
         $order->setData($key, $value);
     }
     foreach ($quote->getAllItems() as $item) {
         $orderItem = $this->_convertor->itemToOrderItem($item);
         if ($item->getParentItem()) {
             $orderItem->setParentItem($order->getItemByQuoteItemId($item->getParentItem()->getId()));
         }
         $order->addItem($orderItem);
     }
     if ($customerData) {
         $order->setCustomerId($customerData->getId());
     }
     $order->setQuote($quote);
     $transaction->addObject($order);
     $transaction->addCommitCallback(array($order, 'place'));
     $transaction->addCommitCallback(array($order, 'save'));
     /**
      * We can use configuration data for declare new order status
      */
     $this->_eventManager->dispatch('checkout_type_onepage_save_order', array('order' => $order, 'quote' => $quote));
     $this->_eventManager->dispatch('sales_model_service_quote_submit_before', array('order' => $order, 'quote' => $quote));
     try {
         $transaction->save();
         $this->_inactivateQuote();
         $this->_eventManager->dispatch('sales_model_service_quote_submit_success', array('order' => $order, 'quote' => $quote));
     } catch (\Exception $e) {
         //reset order ID's on exception, because order not saved
         $order->setId(null);
         /** @var $item \Magento\Sales\Model\Order\Item */
         foreach ($order->getItemsCollection() as $item) {
             $item->setOrderId(null);
             $item->setItemId(null);
         }
         $this->_eventManager->dispatch('sales_model_service_quote_submit_failure', array('order' => $order, 'quote' => $quote));
         throw $e;
     }
     $this->_order = $order;
     return $order;
 }