/** * @param Observer $observer * @return void * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function execute(Observer $observer) { if ($this->moduleManager->isEnabled('Magento_PageCache') && $this->cacheConfig->isEnabled() && $this->taxHelper->isCatalogPriceDisplayAffectedByTax()) { /** @var \Magento\Customer\Model\Data\Customer $customer */ $customer = $observer->getData('customer'); $customerGroupId = $customer->getGroupId(); $customerGroup = $this->groupRepository->getById($customerGroupId); $customerTaxClassId = $customerGroup->getTaxClassId(); $this->customerSession->setCustomerTaxClassId($customerTaxClassId); /** @var \Magento\Customer\Api\Data\AddressInterface[] $addresses */ $addresses = $customer->getAddresses(); if (isset($addresses)) { $defaultShippingFound = false; $defaultBillingFound = false; foreach ($addresses as $address) { if ($address->isDefaultBilling()) { $defaultBillingFound = true; $this->customerSession->setDefaultTaxBillingAddress(['country_id' => $address->getCountryId(), 'region_id' => $address->getRegion() ? $address->getRegion()->getRegionId() : null, 'postcode' => $address->getPostcode()]); } if ($address->isDefaultShipping()) { $defaultShippingFound = true; $this->customerSession->setDefaultTaxShippingAddress(['country_id' => $address->getCountryId(), 'region_id' => $address->getRegion() ? $address->getRegion()->getRegionId() : null, 'postcode' => $address->getPostcode()]); } if ($defaultShippingFound && $defaultBillingFound) { break; } } } } }
/** * Prepare Data Source * * @param array $dataSource * @return void */ public function prepareDataSource(array &$dataSource) { if (isset($dataSource['data']['items'])) { foreach ($dataSource['data']['items'] as &$item) { $item[$this->getData('name')] = $this->groupRepository->getById($item[$this->getData('name')])->getCode(); } } }
/** * @return \Magento\Customer\Api\Data\GroupInterface */ protected function loadSource() { if ($this->isBackendOrder()) { // For backend orders $customerGroupId = $this->objectManager->get('Magento\\Backend\\Model\\Session\\Quote')->getQuote()->getCustomerGroupId(); } else { $customerGroupId = $this->objectManager->get('Magento\\Customer\\Model\\Session')->getCustomerGroupId(); } return $this->groupRepository->getById($customerGroupId); }
/** * Update customer group value * Method set group code instead id value * @return void */ private function setCustomerGroupValue() { $value = $this->getData(self::$customerGroupAttributeCode); try { $group = $this->groupRepository->getById($value); $this->setCustomAttribute(self::$customerGroupAttributeCode, $group->getCode()); } catch (NoSuchEntityException $e) { $this->setCustomAttribute(self::$customerGroupAttributeCode, 'N/A'); } }
/** * Retrieve the header text, either editing an existing group or creating a new one. * * @return \Magento\Framework\Phrase */ public function getHeaderText() { $groupId = $this->coreRegistry->registry(RegistryConstants::CURRENT_GROUP_ID); if ($groupId === null) { return __('New Customer Group'); } else { $group = $this->groupRepository->getById($groupId); return __('Edit Customer Group "%1"', $this->escapeHtml($group->getCode())); } }
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()); }
/** * Prepare Data Source * * @param array $dataSource * @return array */ public function prepareDataSource(array $dataSource) { if (isset($dataSource['data']['items'])) { foreach ($dataSource['data']['items'] as &$item) { try { $item[$this->getData('name')] = $this->groupRepository->getById($item[$this->getData('name')])->getCode(); } catch (NoSuchEntityException $exception) { $item[$this->getData('name')] = __('Group was removed'); } catch (\Exception $exception) { $item[$this->getData('name')] = ''; } } } return $dataSource; }
/** * @magentoDbIsolation enabled */ public function testDelete() { $group = $this->groupFactory->create()->setId(null)->setCode('New Group')->setTaxClassId(3); $groupId = $this->groupRepository->save($group)->getId(); $newGroup = $this->groupRepository->getById($groupId); $this->assertTrue($this->groupRepository->delete($newGroup)); }
/** * Get Customer Group By Id * * @param int $customerGroupId * @param null $allGroups * @return string */ protected function _getCustomerGroupById($customerGroupId, $allGroups = null) { if ($allGroups) { return ImportAdvancedPricing::VALUE_ALL_GROUPS; } else { return $this->_groupRepository->getById($customerGroupId)->getCode(); } }
/** * Retrieve customer group by id * * @param int $groupId * @return \Magento\Customer\Api\Data\GroupInterface|null */ private function getGroup($groupId) { try { $group = $this->groupRepository->getById($groupId); } catch (NoSuchEntityException $e) { $group = null; } return $group; }
/** * @magentoDataFixture Magento/Customer/_files/customer_group.php */ public function testSaveActionNewGroupWithoutGroupCode() { $groupId = $this->findGroupIdWithCode(self::CUSTOMER_GROUP_CODE); $originalCode = $this->groupRepository->getById($groupId)->getCode(); $this->getRequest()->setParam('tax_class', self::TAX_CLASS_ID); $this->dispatch('backend/customer/group/save'); $this->assertSessionMessages($this->equalTo(['code is a required field.']), MessageInterface::TYPE_ERROR); $this->assertSessionMessages($this->isEmpty(), MessageInterface::TYPE_SUCCESS); $this->assertEquals($originalCode, $this->groupRepository->getById($groupId)->getCode()); $this->assertRedirect($this->stringStartsWith(self::BASE_CONTROLLER_URL . 'edit/')); $this->assertEquals('', $this->session->getCustomerGroupData()['customer_group_code']); $this->assertEquals(self::TAX_CLASS_ID, $this->session->getCustomerGroupData()['tax_class_id']); }
/** * Prepare form for render * * @return void */ protected function _prepareLayout() { parent::_prepareLayout(); /** @var \Magento\Framework\Data\Form $form */ $form = $this->_formFactory->create(); $groupId = $this->_coreRegistry->registry(RegistryConstants::CURRENT_GROUP_ID); /** @var \Magento\Customer\Api\Data\GroupInterface $customerGroup */ if ($groupId === null) { $customerGroup = $this->groupDataFactory->create(); $defaultCustomerTaxClass = $this->_taxHelper->getDefaultCustomerTaxClass(); } else { $customerGroup = $this->_groupRepository->getById($groupId); $defaultCustomerTaxClass = $customerGroup->getTaxClassId(); } $fieldset = $form->addFieldset('base_fieldset', ['legend' => __('Group Information')]); $validateClass = sprintf('required-entry validate-length maximum-length-%d', \Magento\Customer\Model\GroupManagement::GROUP_CODE_MAX_LENGTH); $name = $fieldset->addField('customer_group_code', 'text', ['name' => 'code', 'label' => __('Group Name'), 'title' => __('Group Name'), 'note' => __('Maximum length must be less then %1 symbols', \Magento\Customer\Model\GroupManagement::GROUP_CODE_MAX_LENGTH), 'class' => $validateClass, 'required' => true]); if ($customerGroup->getId() == 0 && $customerGroup->getCode()) { $name->setDisabled(true); } $fieldset->addField('tax_class_id', 'select', ['name' => 'tax_class', 'label' => __('Tax Class'), 'title' => __('Tax Class'), 'class' => 'required-entry', 'required' => true, 'values' => $this->_taxCustomer->toOptionArray()]); if ($customerGroup->getId() !== null) { // If edit add id $form->addField('id', 'hidden', ['name' => 'id', 'value' => $customerGroup->getId()]); } if ($this->_backendSession->getCustomerGroupData()) { $form->addValues($this->_backendSession->getCustomerGroupData()); $this->_backendSession->setCustomerGroupData(null); } else { // TODO: need to figure out how the DATA can work with forms $form->addValues(['id' => $customerGroup->getId(), 'customer_group_code' => $customerGroup->getCode(), 'tax_class_id' => $defaultCustomerTaxClass]); } $form->setUseContainer(true); $form->setId('edit_form'); $form->setAction($this->getUrl('customer/*/save')); $form->setMethod('post'); $this->setForm($form); }
/** * Get AvaTax Customer Usage Type for customer * * @param \Magento\Customer\Api\Data\CustomerInterface $customer * @return null|string */ public function getAvataxTaxCodeForCustomer(\Magento\Customer\Api\Data\CustomerInterface $customer) { $customerGroupId = $customer->getGroupId(); if (!$customerGroupId) { return null; } try { $customerGroup = $this->customerGroupRepository->getById($customerGroupId); $taxClassId = $customerGroup->getTaxClassId(); } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { return null; } return $this->getAvaTaxTaxCode($taxClassId); }
/** * Return name of the customer group. * * @return string */ public function getCustomerGroupName() { if ($this->getOrder()) { $customerGroupId = $this->getOrder()->getCustomerGroupId(); try { if ($customerGroupId !== null) { return $this->groupRepository->getById($customerGroupId)->getCode(); } } catch (NoSuchEntityException $e) { return ''; } } return ''; }
/** * {@inheritdoc} * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function add($sku, $customerGroupId, $price) { if (!\Zend_Validate::is($price, 'Float') || $price <= 0 || !\Zend_Validate::is($price, 'Float')) { throw new InputException(__('Please provide valid data')); } $customerGroup = $this->groupRepository->getById($customerGroupId); $product = $this->productRepository->get($sku, true); $groupPrices = $product->getData('group_price'); $websiteIdentifier = 0; $value = $this->config->getValue('catalog/price/scope', \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE); if ($value != 0) { $websiteIdentifier = $this->storeManager->getWebsite()->getId(); } $found = false; foreach ($groupPrices as &$currentPrice) { if (intval($currentPrice['cust_group']) === $customerGroupId && intval($currentPrice['website_id']) === intval($websiteIdentifier)) { $currentPrice['price'] = $price; $found = true; break; } } if (!$found) { $groupPrices[] = ['cust_group' => $customerGroup->getId(), 'website_id' => $websiteIdentifier, 'price' => $price]; } $product->setData('group_price', $groupPrices); $errors = $product->validate(); if (is_array($errors) && count($errors)) { $errorAttributeCodes = implode(', ', array_keys($errors)); throw new InputException(__('Values of following attributes are invalid: %1', $errorAttributeCodes)); } try { $this->productRepository->save($product); } catch (\Exception $e) { throw new CouldNotSaveException(__('Could not save group price')); } return true; }
/** * {@inheritdoc} * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function add($sku, $customerGroupId, $price, $qty) { if (!\Zend_Validate::is($price, 'Float') || $price <= 0 || !\Zend_Validate::is($qty, 'Float') || $qty <= 0) { throw new InputException(__('Please provide valid data')); } $product = $this->productRepository->get($sku, ['edit_mode' => true]); $tierPrices = $product->getData('tier_price'); $websiteIdentifier = 0; $value = $this->config->getValue('catalog/price/scope', \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE); if ($value != 0) { $websiteIdentifier = $this->storeManager->getWebsite()->getId(); } $found = false; foreach ($tierPrices as &$item) { if ('all' == $customerGroupId) { $isGroupValid = $item['all_groups'] == 1; } else { $isGroupValid = $item['cust_group'] == $customerGroupId; } if ($isGroupValid && $item['website_id'] == $websiteIdentifier && $item['price_qty'] == $qty) { $item['price'] = $price; $found = true; break; } } if (!$found) { $mappedCustomerGroupId = 'all' == $customerGroupId ? $this->groupManagement->getAllCustomersGroup()->getId() : $this->groupRepository->getById($customerGroupId)->getId(); $tierPrices[] = ['cust_group' => $mappedCustomerGroupId, 'price' => $price, 'website_price' => $price, 'website_id' => $websiteIdentifier, 'price_qty' => $qty]; } $product->setData('tier_price', $tierPrices); $errors = $product->validate(); if (is_array($errors) && count($errors)) { $errorAttributeCodes = implode(', ', array_keys($errors)); throw new InputException(__('Values of following attributes are invalid: %1', $errorAttributeCodes)); } try { $this->productRepository->save($product); } catch (\Exception $e) { throw new CouldNotSaveException(__('Could not save group price')); } return true; }
/** * {@inheritdoc} */ public function getNotLoggedInGroup() { return $this->groupRepository->getById(self::NOT_LOGGED_IN_ID); }
/** * Get product price with all tax settings processing * * @param \Magento\Catalog\Model\Product $product * @param float $price inputted product price * @param bool $includingTax return price include tax flag * @param null|\Magento\Customer\Model\Address\AbstractAddress $shippingAddress * @param null|\Magento\Customer\Model\Address\AbstractAddress $billingAddress * @param null|int $ctc customer tax class * @param null|string|bool|int|\Magento\Store\Model\Store $store * @param bool $priceIncludesTax flag what price parameter contain tax * @param bool $roundPrice * @return float * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function getTaxPrice($product, $price, $includingTax = null, $shippingAddress = null, $billingAddress = null, $ctc = null, $store = null, $priceIncludesTax = null, $roundPrice = true) { if (!$price) { return $price; } $store = $this->_storeManager->getStore($store); if ($this->_taxConfig->needPriceConversion($store)) { if ($priceIncludesTax === null) { $priceIncludesTax = $this->_taxConfig->priceIncludesTax($store); } $shippingAddressDataObject = null; if ($shippingAddress === null) { $shippingAddressDataObject = $this->convertDefaultTaxAddress($this->_customerSession->getDefaultTaxShippingAddress()); } elseif ($shippingAddress instanceof \Magento\Customer\Model\Address\AbstractAddress) { $shippingAddressDataObject = $shippingAddress->getDataModel(); } $billingAddressDataObject = null; if ($billingAddress === null) { $billingAddressDataObject = $this->convertDefaultTaxAddress($this->_customerSession->getDefaultTaxBillingAddress()); } elseif ($billingAddress instanceof \Magento\Customer\Model\Address\AbstractAddress) { $billingAddressDataObject = $billingAddress->getDataModel(); } $taxClassKey = $this->_taxClassKeyFactory->create(); $taxClassKey->setType(TaxClassKeyInterface::TYPE_ID)->setValue($product->getTaxClassId()); if ($ctc === null && $this->_customerSession->getCustomerGroupId() != null) { $ctc = $this->customerGroupRepository->getById($this->_customerSession->getCustomerGroupId())->getTaxClassId(); } $customerTaxClassKey = $this->_taxClassKeyFactory->create(); $customerTaxClassKey->setType(TaxClassKeyInterface::TYPE_ID)->setValue($ctc); $item = $this->_quoteDetailsItemFactory->create(); $item->setQuantity(1)->setCode($product->getSku())->setShortDescription($product->getShortDescription())->setTaxClassKey($taxClassKey)->setIsTaxIncluded($priceIncludesTax)->setType('product')->setUnitPrice($price); $quoteDetails = $this->_quoteDetailsFactory->create(); $quoteDetails->setShippingAddress($shippingAddressDataObject)->setBillingAddress($billingAddressDataObject)->setCustomerTaxClassKey($customerTaxClassKey)->setItems([$item])->setCustomerId($this->_customerSession->getCustomerId()); $storeId = null; if ($store) { $storeId = $store->getId(); } $taxDetails = $this->_taxCalculationService->calculateTax($quoteDetails, $storeId, $roundPrice); $items = $taxDetails->getItems(); $taxDetailsItem = array_shift($items); if ($includingTax !== null) { if ($includingTax) { $price = $taxDetailsItem->getPriceInclTax(); } else { $price = $taxDetailsItem->getPrice(); } } else { switch ($this->_taxConfig->getPriceDisplayType($store)) { case Config::DISPLAY_TYPE_EXCLUDING_TAX: case Config::DISPLAY_TYPE_BOTH: $price = $taxDetailsItem->getPrice(); break; case Config::DISPLAY_TYPE_INCLUDING_TAX: $price = $taxDetailsItem->getPriceInclTax(); break; default: break; } } } if ($roundPrice) { return $this->priceCurrency->round($price); } else { return $price; } }
/** * @magentoDataFixture Magento/Customer/_files/customer.php */ public function testGetGroupName() { $groupName = $this->_groupRepository->getById($this->_loadCustomer()->getGroupId())->getCode(); $this->assertEquals($groupName, $this->_block->getGroupName()); }
/** * {@inheritdoc} */ public function getCustomerTaxClassId() { /** * tax class can vary at any time. so instead of using the value from session, * we need to retrieve from db every time to get the correct tax class */ //if (!$this->getData('customer_group_id') && !$this->getData('customer_tax_class_id')) { $groupId = $this->getCustomerGroupId(); if (!is_null($groupId)) { $taxClassId = $this->groupRepository->getById($this->getCustomerGroupId())->getTaxClassId(); $this->setCustomerTaxClassId($taxClassId); } return $this->getData(self::KEY_CUSTOMER_TAX_CLASS_ID); }
/** * Retrieve customer tax class identifier * * @return int */ public function getTaxClassId() { if (!$this->getData('tax_class_id')) { $groupTaxClassId = $this->_groupRepository->getById($this->getGroupId())->getTaxClassId(); $this->setData('tax_class_id', $groupTaxClassId); } return $this->getData('tax_class_id'); }
/** * Add account data to quote * * @param array $accountData * @return $this */ public function setAccountData($accountData) { $customer = $this->getQuote()->getCustomer(); $form = $this->_createCustomerForm($customer); // emulate request $request = $form->prepareRequest($accountData); $data = $form->extractData($request); $data = $form->restoreData($data); $customer = $this->customerFactory->create(); $this->dataObjectHelper->populateWithArray($customer, $data, '\\Magento\\Customer\\Api\\Data\\CustomerInterface'); $this->getQuote()->updateCustomerData($customer); $data = []; $customerData = $this->customerMapper->toFlatArray($customer); foreach ($form->getAttributes() as $attribute) { $code = sprintf('customer_%s', $attribute->getAttributeCode()); $data[$code] = isset($customerData[$attribute->getAttributeCode()]) ? $customerData[$attribute->getAttributeCode()] : null; } if (isset($data['customer_group_id'])) { $customerGroup = $this->groupRepository->getById($data['customer_group_id']); $data['customer_tax_class_id'] = $customerGroup->getTaxClassId(); $this->setRecollect(true); } $this->getQuote()->addData($data); return $this; }
/** * 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; }