/** * @magentoDataFixture Magento/Customer/_files/customer.php * @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php */ public function testFormPostAction() { $this->getRequest()->setParam('id', 2)->setMethod('POST')->setPostValue(['form_key' => $this->_objectManager->get('Magento\\Framework\\Data\\Form\\FormKey')->getFormKey(), 'firstname' => 'James', 'lastname' => 'Bond', 'company' => 'Magento Commerce Inc.', 'telephone' => '1112223333', 'fax' => '2223334444', 'street' => ['1234 Monterey Rd', 'Apt 13'], 'city' => 'Kyiv', 'region' => 'Kiev', 'postcode' => '55555', 'country_id' => 'UA', 'success_url' => '', 'error_url' => '', 'default_billing' => true, 'default_shipping' => true]); // we are overwriting the address coming from the fixture $this->dispatch('customer/address/formPost'); $this->assertRedirect($this->stringContains('customer/address/index')); $this->assertSessionMessages($this->equalTo(['You saved the address.']), \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS); $address = $this->accountManagement->getDefaultBillingAddress(1); $this->assertEquals('UA', $address->getCountryId()); $this->assertEquals('Kyiv', $address->getCity()); $this->assertEquals('Kiev', $address->getRegion()->getRegion()); $this->assertTrue($address->isDefaultBilling()); $this->assertTrue($address->isDefaultShipping()); }
/** * Retrieve billing address html * * @return \Magento\Framework\Phrase|string */ public function getBillingAddressHtml() { try { $address = $this->accountManagement->getDefaultBillingAddress($this->getCustomer()->getId()); } catch (NoSuchEntityException $e) { return __('The customer does not have default billing address.'); } if ($address === null) { return __('The customer does not have default billing address.'); } return $this->addressHelper->getFormatTypeRenderer('html')->renderArray($this->addressMapper->toFlatArray($address)); }
/** * Retrieve the customer's primary addresses (i.e. default billing and shipping). * * @return \Magento\Customer\Api\Data\AddressInterface[]|bool */ public function getPrimaryAddresses() { $addresses = []; $customerId = $this->getCustomer()->getId(); if ($defaultBilling = $this->customerAccountManagement->getDefaultBillingAddress($customerId)) { $addresses[] = $defaultBilling; } if ($defaultShipping = $this->customerAccountManagement->getDefaultShippingAddress($customerId)) { if ($defaultBilling) { if ($defaultBilling->getId() != $defaultShipping->getId()) { $addresses[] = $defaultShipping; } } else { $addresses[] = $defaultShipping; } } return empty($addresses) ? false : $addresses; }
/** * @magentoDbIsolation enabled */ public function testSaveActionWithValidCustomerDataAndValidAddressData() { /** @var $objectManager \Magento\TestFramework\ObjectManager */ $objectManager = Bootstrap::getObjectManager(); $post = ['customer' => ['middlename' => 'test middlename', 'group_id' => 1, 'website_id' => 0, 'firstname' => 'test firstname', 'lastname' => 'test lastname', 'email' => '*****@*****.**', 'default_billing' => '_item1', 'password' => 'password'], 'address' => ['_item1' => ['firstname' => 'test firstname', 'lastname' => 'test lastname', 'street' => ['test street'], 'city' => 'test city', 'country_id' => 'US', 'postcode' => '01001', 'telephone' => '+7000000001', 'default_billing' => 'true']]]; $this->getRequest()->setPostValue($post); $this->getRequest()->setParam('back', '1'); // Emulate setting customer data to session in editAction $objectManager->get('Magento\\Backend\\Model\\Session')->setCustomerData($post); $this->dispatch('backend/customer/index/save'); /** * Check that errors was generated and set to session */ $this->assertSessionMessages($this->isEmpty(), \Magento\Framework\Message\MessageInterface::TYPE_ERROR); /** * Check that customer data were cleaned after it was saved successfully */ $this->assertEmpty($objectManager->get('Magento\\Backend\\Model\\Session')->getCustomerData()); /** * Check that success message is set */ $this->assertSessionMessages($this->logicalNot($this->isEmpty()), \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS); /** * Check that customer id set and addresses saved */ $registry = $objectManager->get('Magento\\Framework\\Registry'); $customerId = $registry->registry(RegistryConstants::CURRENT_CUSTOMER_ID); $customer = $this->customerRepository->getById($customerId); $this->assertEquals('test firstname', $customer->getFirstname()); $addresses = $customer->getAddresses(); $this->assertEquals(1, count($addresses)); $this->assertNotEquals(0, $this->accountManagement->getDefaultBillingAddress($customerId)); $this->assertNull($this->accountManagement->getDefaultShippingAddress($customerId)); $this->assertRedirect($this->stringStartsWith($this->_baseControllerUrl . 'edit/id/' . $customerId . '/back/1')); /** @var \Magento\Newsletter\Model\Subscriber $subscriber */ $subscriber = $objectManager->get('Magento\\Newsletter\\Model\\SubscriberFactory')->create(); $this->assertEmpty($subscriber->getId()); $subscriber->loadByCustomerId($customerId); $this->assertEmpty($subscriber->getId()); }
/** * @param Product $product * @param null|false|\Magento\Quote\Model\Quote\Address $shipping * @param null|false|\Magento\Quote\Model\Quote\Address $billing * @param Website $website * @param bool $calculateTax * @param bool $round * @return \Magento\Framework\DataObject[] * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function getProductWeeeAttributes($product, $shipping = null, $billing = null, $website = null, $calculateTax = null, $round = true) { $result = []; $websiteId = $this->_storeManager->getWebsite($website)->getId(); /** @var \Magento\Store\Model\Store $store */ $store = $this->_storeManager->getWebsite($website)->getDefaultGroup()->getDefaultStore(); $allWeee = $this->getWeeeTaxAttributeCodes($store); if (!$allWeee) { return $result; } /** @var \Magento\Tax\Model\Calculation $calculator */ $calculator = $this->_calculationFactory->create(); $customerId = $this->_customerSession->getCustomerId(); if ($shipping && $shipping->getCountryId()) { $customerTaxClass = $shipping->getQuote()->getCustomerTaxClassId(); } else { // if customer logged use it default shipping and billing address if ($customerId) { $shipping = $this->accountManagement->getDefaultShippingAddress($customerId); $billing = $this->accountManagement->getDefaultBillingAddress($customerId); $customerTaxClass = null; } else { $shippingAddressArray = $this->_customerSession->getDefaultTaxShippingAddress(); $billingAddressArray = $this->_customerSession->getDefaultTaxBillingAddress(); if (!empty($billingAddressArray)) { $billing = new \Magento\Framework\DataObject($billingAddressArray); } if (!empty($shippingAddressArray)) { $shipping = new \Magento\Framework\DataObject($shippingAddressArray); } $customerTaxClass = $this->_customerSession->getCustomerTaxClassId(); } } $rateRequest = $calculator->getRateRequest($shipping, $billing, $customerTaxClass, $store, $customerId); $defaultRateRequest = $calculator->getDefaultRateRequest($store); $productAttributes = $this->getResource()->fetchWeeeTaxCalculationsByEntity($rateRequest->getCountryId(), $rateRequest->getRegionId(), $websiteId, $store->getId(), $product->getId()); foreach ($productAttributes as $attribute) { $value = $attribute['weee_value']; if ($value) { $taxAmount = $amount = 0; $amount = $value; $amountExclTax = $value; if ($calculateTax && $this->weeeConfig->isTaxable($store)) { /** @var \Magento\Tax\Model\Calculation $calculator */ $defaultPercent = $calculator->getRate($defaultRateRequest->setProductClassId($product->getTaxClassId())); $currentPercent = $calculator->getRate($rateRequest->setProductClassId($product->getTaxClassId())); if ($this->_taxData->priceIncludesTax($store)) { $amountInclTax = $value / (100 + $defaultPercent) * (100 + $currentPercent); if ($round) { $amountInclTax = $this->priceCurrency->round($amountInclTax); } $taxAmount = $amountInclTax - $amountInclTax / (100 + $currentPercent) * 100; if ($round) { $taxAmount = $this->priceCurrency->round($taxAmount); } $amountExclTax = $amountInclTax - $taxAmount; } else { $appliedRates = $this->_calculationFactory->create()->getAppliedRates($rateRequest); if (count($appliedRates) > 1) { $taxAmount = 0; foreach ($appliedRates as $appliedRate) { $taxRate = $appliedRate['percent']; if ($round) { $taxAmount += $this->priceCurrency->round($value * $taxRate / 100); } else { $taxAmount += $value * $taxRate / 100; } } } else { if ($round) { $taxAmount = $this->priceCurrency->round($value * $currentPercent / 100); } else { $taxAmount = $value * $currentPercent / 100; } } } } $one = new \Magento\Framework\DataObject(); $one->setName($attribute['label_value'] ? __($attribute['label_value']) : __($attribute['frontend_label']))->setAmount($amount)->setTaxAmount($taxAmount)->setAmountExclTax($amountExclTax)->setCode($attribute['attribute_code']); $result[] = $one; } } return $result; }
/** * 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); }
/** * @magentoDataFixture Magento/Customer/_files/customer.php */ public function testGetDefaultAddressesForNonExistentAddress() { $customerId = 1; $this->assertNull($this->accountManagement->getDefaultBillingAddress($customerId)); $this->assertNull($this->accountManagement->getDefaultShippingAddress($customerId)); }
/** * @param Product $product * @param null|false|\Magento\Quote\Model\Quote\Address $shipping * @param null|false|\Magento\Quote\Model\Quote\Address $billing * @param Website $website * @param bool $calculateTax * @return \Magento\Framework\Object[] * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function getProductWeeeAttributes($product, $shipping = null, $billing = null, $website = null, $calculateTax = null) { $result = []; $websiteId = $this->_storeManager->getWebsite($website)->getId(); /** @var \Magento\Store\Model\Store $store */ $store = $this->_storeManager->getWebsite($website)->getDefaultGroup()->getDefaultStore(); $allWeee = $this->getWeeeTaxAttributeCodes($store); if (!$allWeee) { return $result; } /** @var \Magento\Tax\Model\Calculation $calculator */ $calculator = $this->_calculationFactory->create(); if ($shipping && $shipping->getCountryId()) { $customerTaxClass = $shipping->getQuote()->getCustomerTaxClassId(); } else { // if customer logged use it default shipping and billing address if ($customerId = $this->_customerSession->getCustomerId()) { $shipping = $this->accountManagement->getDefaultShippingAddress($customerId); $billing = $this->accountManagement->getDefaultBillingAddress($customerId); $customerTaxClass = null; } else { $shippingAddressArray = $this->_customerSession->getDefaultTaxShippingAddress(); $billingAddressArray = $this->_customerSession->getDefaultTaxBillingAddress(); if (!empty($billingAddressArray)) { $billing = new \Magento\Framework\Object($billingAddressArray); } if (!empty($shippingAddressArray)) { $shipping = new \Magento\Framework\Object($shippingAddressArray); } $customerTaxClass = $this->_customerSession->getCustomerTaxClassId(); } } $rateRequest = $calculator->getRateRequest($shipping, $billing, $customerTaxClass, $store); $defaultRateRequest = $calculator->getDefaultRateRequest($store); $productAttributes = $product->getTypeInstance()->getSetAttributes($product); foreach ($productAttributes as $code => $attribute) { if (in_array($code, $allWeee)) { $attributeSelect = $this->getResource()->getReadConnection()->select(); $attributeSelect->from($this->getResource()->getTable('weee_tax'), 'value')->where('attribute_id = ?', (int) $attribute->getId())->where('website_id IN(?)', [$websiteId, 0])->where('country = ?', $rateRequest->getCountryId())->where('state IN(?)', [$rateRequest->getRegionId(), 0])->where('entity_id = ?', (int) $product->getId())->limit(1); $order = ['state ' . \Magento\Framework\DB\Select::SQL_DESC, 'website_id ' . \Magento\Framework\DB\Select::SQL_DESC]; $attributeSelect->order($order); $value = $this->getResource()->getReadConnection()->fetchOne($attributeSelect); if ($value) { $taxAmount = $amount = 0; $amount = $value; if ($calculateTax && $this->weeeConfig->isTaxable($store)) { /** @var \Magento\Tax\Model\Calculation $calculator */ $defaultPercent = $calculator->getRate($defaultRateRequest->setProductClassId($product->getTaxClassId())); $currentPercent = $calculator->getRate($rateRequest->setProductClassId($product->getTaxClassId())); if ($this->_taxData->priceIncludesTax($store)) { $amountInclTax = $value / (100 + $defaultPercent) * (100 + $currentPercent); //round the "golden price" $amountInclTax = $this->priceCurrency->round($amountInclTax); $taxAmount = $amountInclTax - $amountInclTax / (100 + $currentPercent) * 100; $taxAmount = $this->priceCurrency->round($taxAmount); } else { $appliedRates = $this->_calculationFactory->create()->getAppliedRates($rateRequest); if (count($appliedRates) > 1) { $taxAmount = 0; foreach ($appliedRates as $appliedRate) { $taxRate = $appliedRate['percent']; $taxAmount += $this->priceCurrency->round($value * $taxRate / 100); } } else { $taxAmount = $this->priceCurrency->round($value * $currentPercent / 100); } $taxAmount = $this->priceCurrency->round($value * $currentPercent / 100); } } $one = new \Magento\Framework\Object(); $one->setName(__($attribute->getFrontend()->getLabel()))->setAmount($amount)->setTaxAmount($taxAmount)->setCode($attribute->getAttributeCode()); $result[] = $one; } } } return $result; }
/** * Get request object with information necessary for getting tax rate * * Request object contain: * country_id (->getCountryId()) * region_id (->getRegionId()) * postcode (->getPostcode()) * customer_class_id (->getCustomerClassId()) * store (->getStore()) * * @param null|bool|\Magento\Framework\Object|CustomerAddress $shippingAddress * @param null|bool|\Magento\Framework\Object|CustomerAddress $billingAddress * @param null|int $customerTaxClass * @param null|int|\Magento\Store\Model\Store $store * @param int $customerId * @return \Magento\Framework\Object * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function getRateRequest($shippingAddress = null, $billingAddress = null, $customerTaxClass = null, $store = null, $customerId = null) { if ($shippingAddress === false && $billingAddress === false && $customerTaxClass === false) { return $this->getRateOriginRequest($store); } $address = new \Magento\Framework\Object(); $basedOn = $this->_scopeConfig->getValue(\Magento\Tax\Model\Config::CONFIG_XML_PATH_BASED_ON, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store); if ($shippingAddress === false && $basedOn == 'shipping' || $billingAddress === false && $basedOn == 'billing') { $basedOn = 'default'; } else { if (($billingAddress === null || !$billingAddress->getCountryId()) && $basedOn == 'billing' || ($shippingAddress === null || !$shippingAddress->getCountryId()) && $basedOn == 'shipping') { if ($customerId) { try { $defaultBilling = $this->customerAccountManagement->getDefaultBillingAddress($customerId); } catch (NoSuchEntityException $e) { } try { $defaultShipping = $this->customerAccountManagement->getDefaultShippingAddress($customerId); } catch (NoSuchEntityException $e) { } if ($basedOn == 'billing' && isset($defaultBilling) && $defaultBilling->getCountryId()) { $billingAddress = $defaultBilling; } elseif ($basedOn == 'shipping' && isset($defaultShipping) && $defaultShipping->getCountryId()) { $shippingAddress = $defaultShipping; } else { $basedOn = 'default'; } } else { $basedOn = 'default'; } } } switch ($basedOn) { case 'billing': $address = $billingAddress; break; case 'shipping': $address = $shippingAddress; break; case 'origin': $address = $this->getRateOriginRequest($store); break; case 'default': $address->setCountryId($this->_scopeConfig->getValue(\Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_COUNTRY, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store))->setRegionId($this->_scopeConfig->getValue(\Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_REGION, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store))->setPostcode($this->_scopeConfig->getValue(\Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_POSTCODE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store)); break; default: break; } if ($customerTaxClass === null || $customerTaxClass === false) { if ($customerId) { $customerData = $this->customerRepository->getById($customerId); $customerTaxClass = $this->customerGroupRepository->getById($customerData->getGroupId())->getTaxClassId(); } else { $customerTaxClass = $this->customerGroupManagement->getNotLoggedInGroup()->getTaxClassId(); } } $request = new \Magento\Framework\Object(); //TODO: Address is not completely refactored to use Data objects if ($address->getRegion() instanceof AddressRegion) { $regionId = $address->getRegion()->getRegionId(); } else { $regionId = $address->getRegionId(); } $request->setCountryId($address->getCountryId())->setRegionId($regionId)->setPostcode($address->getPostcode())->setStore($store)->setCustomerClassId($customerTaxClass); return $request; }
/** * Returns default billing address form current customer * * @return AddressInterface|null */ public function getDefaultBillingAddress() { return $this->accountManagement->getDefaultBillingAddress($this->currentCustomer->getCustomerId()); }