public function testGetSetCustomerGroupId() { $this->assertEquals($this->groupManagement->getNotLoggedInGroup()->getId(), $this->_model->getCustomerGroupId()); $customerGroupId = 123; $this->_model->setCustomerGroupId($customerGroupId); $this->assertEquals($customerGroupId, $this->_model->getCustomerGroupId()); }
/** * Handle customer VAT number if needed on collect_totals_before event of quote address * * @param \Magento\Framework\Event\Observer $observer * @return void */ public function dispatch(\Magento\Framework\Event\Observer $observer) { /** @var \Magento\Quote\Model\Quote\Address $quoteAddress */ $quoteAddress = $observer->getQuoteAddress(); /** @var \Magento\Quote\Model\Quote $quote */ $quote = $quoteAddress->getQuote(); $customer = $quote->getCustomer(); $storeId = $customer->getStoreId(); if ($customer->getCustomAttribute('disable_auto_group_change') && $customer->getCustomAttribute('disable_auto_group_change')->getValue() || false == $this->vatValidator->isEnabled($quoteAddress, $storeId)) { return; } $customerCountryCode = $quoteAddress->getCountryId(); $customerVatNumber = $quoteAddress->getVatId(); $groupId = null; if (empty($customerVatNumber) || false == $this->customerVat->isCountryInEU($customerCountryCode)) { $groupId = $customer->getId() ? $this->groupManagement->getDefaultGroup($storeId)->getId() : $this->groupManagement->getNotLoggedInGroup()->getId(); } else { // Magento always has to emulate group even if customer uses default billing/shipping address $groupId = $this->customerVat->getCustomerGroupIdBasedOnVatNumber($customerCountryCode, $this->vatValidator->validate($quoteAddress, $storeId), $storeId); } if ($groupId) { $quoteAddress->setPrevQuoteCustomerGroupId($quote->getCustomerGroupId()); $quote->setCustomerGroupId($groupId); $customer->setGroupId($groupId); $quote->setCustomer($customer); } }
/** * Handle customer VAT number if needed on collect_totals_before event of quote address * * @param \Magento\Framework\Event\Observer $observer * @return void */ public function execute(\Magento\Framework\Event\Observer $observer) { /** @var \Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment */ $shippingAssignment = $observer->getShippingAssignment(); /** @var \Magento\Quote\Model\Quote $quote */ $quote = $observer->getQuote(); /** @var \Magento\Quote\Model\Quote\Address $address */ $address = $shippingAssignment->getShipping()->getAddress(); $customer = $quote->getCustomer(); $storeId = $customer->getStoreId(); if ($customer->getDisableAutoGroupChange() || false == $this->vatValidator->isEnabled($address, $storeId)) { return; } $customerCountryCode = $address->getCountryId(); $customerVatNumber = $address->getVatId(); $groupId = null; if (empty($customerVatNumber) || false == $this->customerVat->isCountryInEU($customerCountryCode)) { $groupId = $customer->getId() ? $this->groupManagement->getDefaultGroup($storeId)->getId() : $this->groupManagement->getNotLoggedInGroup()->getId(); } else { // Magento always has to emulate group even if customer uses default billing/shipping address $groupId = $this->customerVat->getCustomerGroupIdBasedOnVatNumber($customerCountryCode, $this->vatValidator->validate($address, $storeId), $storeId); } if ($groupId) { $address->setPrevQuoteCustomerGroupId($quote->getCustomerGroupId()); $quote->setCustomerGroupId($groupId); $customer->setGroupId($groupId); $quote->setCustomer($customer); } }
/** * Getter for customer group id, return default group if not set * * @return int */ public function getCustomerGroupId() { if ($this->customerGroupId === null) { return $this->groupManagement->getAllCustomersGroup()->getId(); } return parent::getCustomerGroupId(); }
/** * Retrieve customer groups as array * * @return array */ public function toOptionArray() { if (!$this->_options) { $groups = $this->_groupManagement->getLoggedInGroups(); $this->_options = $this->_converter->toOptionArray($groups, 'id', 'code'); } return $this->_options; }
/** * @return array */ public function toOptionArray() { if (!$this->_options) { $groups = $this->_groupManagement->getLoggedInGroups(); $this->_options = $this->_converter->toOptionArray($groups, 'id', 'code'); array_unshift($this->_options, ['value' => '', 'label' => __('-- Please Select --')]); } return $this->_options; }
/** * @magentoDataFixture Magento/Catalog/Model/Resource/_files/product_simple.php */ public function testAddTierPriceData() { $this->_collection->setFlag('tier_price_added', false); $this->_collection->addIdFilter(2); $this->assertInstanceOf('\\Magento\\Catalog\\Model\\Resource\\Product\\Collection', $this->_collection->addTierPriceData()); $tierPrice = $this->_collection->getFirstItem()->getDataByKey('tier_price'); $this->assertEquals($this->_groupManagement->getNotLoggedInGroup()->getId(), current($tierPrice)['cust_group']); $this->assertEquals($this->_groupManagement->getAllCustomersGroup()->getId(), next($tierPrice)['cust_group']); $this->assertTrue($this->_collection->getFlag('tier_price_added')); }
/** * Verify that the Delete button does not exist for the default group. * @magentoAppIsolation enabled */ public function testDeleteButtonNotExistInDefaultGroup() { $groupId = $this->groupManagement->getDefaultGroup(0)->getId(); $this->registry->register(RegistryConstants::CURRENT_GROUP_ID, $groupId); $this->getRequest()->setParam('id', $groupId); /** @var $block Edit */ $block = $this->layout->createBlock('Magento\\Customer\\Block\\Adminhtml\\Group\\Edit', 'block'); $buttonsHtml = $block->getButtonsHtml(); $this->assertNotContains('delete', $buttonsHtml); }
/** * Method set default group id to the customers collection * * @param \Magento\Framework\Model\AbstractModel $group * @return $this */ protected function _afterDelete(\Magento\Framework\Model\AbstractModel $group) { $customerCollection = $this->_createCustomersCollection()->addAttributeToFilter('group_id', $group->getId())->load(); foreach ($customerCollection as $customer) { /** @var $customer \Magento\Customer\Model\Customer */ $customer->load($customer->getId()); $defaultGroupId = $this->_groupManagement->getDefaultGroup($customer->getStoreId())->getId(); $customer->setGroupId($defaultGroupId); $customer->save(); } return parent::_afterDelete($group); }
/** * Update Save and Delete buttons. Remove Delete button if group can't be deleted. * * @return void */ protected function _construct() { parent::_construct(); $this->_objectId = 'id'; $this->_controller = 'adminhtml_group'; $this->_blockGroup = 'Magento_Customer'; $this->buttonList->update('save', 'label', __('Save Customer Group')); $this->buttonList->update('delete', 'label', __('Delete Customer Group')); $groupId = $this->coreRegistry->registry(RegistryConstants::CURRENT_GROUP_ID); if (!$groupId || $this->groupManagement->isReadonly($groupId)) { $this->buttonList->remove('delete'); } }
protected function setUp() { parent::setUp(); $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class)->getMockForAbstractClass(); $this->groupRepositoryMock = $this->getMockBuilder(GroupRepositoryInterface::class)->getMockForAbstractClass(); $this->groupManagementMock = $this->getMockBuilder(GroupManagementInterface::class)->getMockForAbstractClass(); $this->searchCriteriaBuilderMock = $this->getMockBuilder(SearchCriteriaBuilder::class)->disableOriginalConstructor()->getMock(); $this->moduleManagerMock = $this->getMockBuilder(ModuleManager::class)->disableOriginalConstructor()->getMock(); $this->directoryHelperMock = $this->getMockBuilder(DirectoryHelper::class)->disableOriginalConstructor()->getMock(); $this->productResourceMock = $this->getMockBuilder(ProductResource::class)->disableOriginalConstructor()->getMock(); $this->attributeMock = $this->getMockBuilder(Attribute::class)->disableOriginalConstructor()->getMock(); $this->customerGroupMock = $this->getMockBuilder(CustomerGroupInterface::class)->getMockForAbstractClass(); $this->groupManagementMock->expects($this->any())->method('getAllCustomersGroup')->willReturn($this->customerGroupMock); }
protected function setUp() { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->product = $this->objectManagerHelper->getObject('Magento\\Catalog\\Model\\Product'); $this->tpFactory = $this->getMockForAbstractClass('Magento\\Catalog\\Api\\Data\\ProductTierPriceInterfaceFactory', [], '', false, true, true, ['create']); $this->websiteMock = $this->getMock('Magento\\Store\\Model\\Website', ['getId'], [], '', false); $storeMangerMock = $this->getMockForAbstractClass('Magento\\Store\\Model\\StoreManagerInterface', [], '', false, true, true, ['getWebsite']); $storeMangerMock->expects($this->any())->method('getWebsite')->will($this->returnValue($this->websiteMock)); $this->scopeConfigMock = $this->getMockForAbstractClass('Magento\\Framework\\App\\Config\\ScopeConfigInterface', [], '', false, true, true, ['getValue']); $group = $this->getMock('\\Magento\\Customer\\Model\\Data\\Group', [], [], '', false); $group->expects($this->any())->method('getId')->willReturn(GroupManagement::CUST_GROUP_ALL); $this->groupManagementMock = $this->getMock('Magento\\Customer\\Api\\GroupManagementInterface', [], [], '', false); $this->groupManagementMock->expects($this->any())->method('getAllCustomersGroup')->will($this->returnValue($group)); $this->model = $this->objectManagerHelper->getObject('Magento\\Catalog\\Model\\Product\\Type\\Price', ['tierPriceFactory' => $this->tpFactory, 'config' => $this->scopeConfigMock, 'storeManager' => $storeMangerMock, 'groupManagement' => $this->groupManagementMock]); }
/** * Run test getQuote method * * @return void */ public function testGetQuoteWithoutQuoteId() { $quoteId = 22; $storeId = 10; $customerId = 66; $customerGroupId = 77; $this->quote->expects($this->any())->method('getQuoteId')->will($this->returnValue(null)); $this->quote->expects($this->any())->method('setQuoteId')->with($quoteId); $cartInterfaceMock = $this->getMock('\\Magento\\Quote\\Api\\Data\\CartInterface', ['getId', 'setId', 'getCreatedAt', 'setCreatedAt', 'getUpdatedAt', 'setUpdatedAt', 'getConvertedAt', 'setConvertedAt', 'getIsActive', 'setIsActive', 'getIsVirtual', 'getItems', 'setItems', 'getItemsCount', 'setItemsCount', 'getItemsQty', 'setItemsQty', 'getCustomer', 'setCustomer', 'getBillingAddress', 'setBillingAddress', 'getReservedOrderId', 'setReservedOrderId', 'getOrigOrderId', 'setOrigOrderId', 'getCurrency', 'setCurrency', 'getCustomerIsGuest', 'setCustomerIsGuest', 'getCustomerNote', 'setCustomerNote', 'getCustomerNoteNotify', 'setCustomerNoteNotify', 'getCustomerTaxClassId', 'setCustomerTaxClassId', 'getStoreId', 'setStoreId', 'getExtensionAttributes', 'setExtensionAttributes', 'setIgnoreOldQty', 'setIsSuperMode', 'setCustomerGroupId']); $this->quoteFactoryMock->expects($this->once())->method('create')->willReturn($cartInterfaceMock); $this->quote->expects($this->any())->method('getStoreId')->will($this->returnValue($storeId)); $this->quote->expects($this->any())->method('getCustomerId')->will($this->returnValue($customerId)); $cartInterfaceMock->expects($this->atLeastOnce())->method('getId')->willReturn($quoteId); $defaultGroup = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\GroupInterface')->getMock(); $defaultGroup->expects($this->any())->method('getId')->will($this->returnValue($customerGroupId)); $this->groupManagementMock->expects($this->any())->method('getDefaultGroup')->will($this->returnValue($defaultGroup)); $dataCustomerMock = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\CustomerInterface')->disableOriginalConstructor()->getMock(); $this->customerRepositoryMock->expects($this->once())->method('getById')->with($customerId)->willReturn($dataCustomerMock); $quoteMock = $this->getMock('Magento\\Quote\\Model\\Quote', ['setStoreId', 'setCustomerGroupId', 'setIsActive', 'assignCustomer', 'setIgnoreOldQty', 'setIsSuperMode', '__wakeup'], [], '', false); $this->quoteRepositoryMock->expects($this->once())->method('get')->willReturn($quoteMock); $cartInterfaceMock->expects($this->once())->method('setCustomerGroupId')->with($customerGroupId)->will($this->returnSelf()); $quoteMock->expects($this->once())->method('assignCustomer')->with($dataCustomerMock); $quoteMock->expects($this->once())->method('setIgnoreOldQty')->with(true); $quoteMock->expects($this->once())->method('setIsSuperMode')->with(true); $this->assertEquals($quoteMock, $this->quote->getQuote()); }
/** * Set current attribute to entry (for specified product) * * @param Product $product * @param Entry $entry * @return Entry */ public function convertAttribute($product, $entry) { $product->setWebsiteId($this->_storeManager->getStore($product->getStoreId())->getWebsiteId()); $defaultCustomerGroup = $this->groupManagement->getDefaultGroup($product->getStoreId()); $product->setCustomerGroupId($defaultCustomerGroup->getId()); /** @var \Magento\Store\Model\Store $store */ $store = $this->_storeManager->getStore($product->getStoreId()); $isSalePriceAllowed = $this->_config->getTargetCountry($product->getStoreId()) == 'US'; // get tax settings $priceDisplayType = $this->_taxData->getPriceDisplayType($product->getStoreId()); $inclTax = $priceDisplayType == Config::DISPLAY_TYPE_INCLUDING_TAX; $finalPrice = $this->_getFinalPrice($product, $store, $inclTax, $isSalePriceAllowed); // calculate price attribute value $price = $this->_getPrice($product, $store, $priceDisplayType, $inclTax, $isSalePriceAllowed); if ($isSalePriceAllowed) { // set sale_price and effective dates for it if ($price && $price - $finalPrice > 0.0001) { $this->_setAttributePrice($entry, $product, $price); $this->_setAttributePrice($entry, $product, $finalPrice, 'sale_price'); $this->_setEffectiveDate($product, $entry); } else { $this->_setAttributePrice($entry, $product, $finalPrice); $entry->removeContentAttribute('sale_price_effective_date'); $entry->removeContentAttribute('sale_price'); } // calculate taxes $tax = $this->getGroupAttributeTax(); if (!$inclTax && !is_null($tax)) { $tax->convertAttribute($product, $entry); } } else { $this->_setAttributePrice($entry, $product, $price); } return $entry; }
/** * @param string $formCode * @param RequestInterface $request * @return \Magento\Customer\Api\Data\CustomerInterface */ public function extract($formCode, RequestInterface $request) { $customerForm = $this->formFactory->create('customer', $formCode); $customerData = $customerForm->extractData($request); $allowedAttributes = $customerForm->getAllowedAttributes(); $isGroupIdEmpty = isset($allowedAttributes['group_id']); $customerDataObject = $this->customerFactory->create(); $this->dataObjectHelper->populateWithArray($customerDataObject, $customerData, '\\Magento\\Customer\\Api\\Data\\CustomerInterface'); $store = $this->storeManager->getStore(); if ($isGroupIdEmpty) { $customerDataObject->setGroupId($this->customerGroupManagement->getDefaultGroup($store->getId())->getId()); } $customerDataObject->setWebsiteId($store->getWebsiteId()); $customerDataObject->setStoreId($store->getId()); return $customerDataObject; }
/** * Retrieve quote model object * * @return \Magento\Quote\Model\Quote */ public function getQuote() { if ($this->_quote === null) { $this->_quote = $this->quoteFactory->create(); if ($this->getStoreId()) { if (!$this->getQuoteId()) { $this->_quote->setCustomerGroupId($this->groupManagement->getDefaultGroup()->getId()); $this->_quote->setIsActive(false); $this->_quote->setStoreId($this->getStoreId()); $this->quoteRepository->save($this->_quote); $this->setQuoteId($this->_quote->getId()); $this->_quote = $this->quoteRepository->get($this->getQuoteId(), [$this->getStoreId()]); } else { $this->_quote = $this->quoteRepository->get($this->getQuoteId(), [$this->getStoreId()]); $this->_quote->setStoreId($this->getStoreId()); } if ($this->getCustomerId() && $this->getCustomerId() != $this->_quote->getCustomerId()) { $customer = $this->customerRepository->getById($this->getCustomerId()); $this->_quote->assignCustomer($customer); $this->quoteRepository->save($this->_quote); } } $this->_quote->setIgnoreOldQty(true); $this->_quote->setIsSuperMode(true); } return $this->_quote; }
/** * Address after save event handler * * @param \Magento\Framework\Event\Observer $observer * @return void * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function afterAddressSave($observer) { /** @var $customerAddress Address */ $customerAddress = $observer->getCustomerAddress(); $customer = $customerAddress->getCustomer(); if (!$this->_customerAddress->isVatValidationEnabled($customer->getStore()) || $this->_coreRegistry->registry(self::VIV_PROCESSED_FLAG) || !$this->_canProcessAddress($customerAddress)) { return; } try { $this->_coreRegistry->register(self::VIV_PROCESSED_FLAG, true); if ($customerAddress->getVatId() == '' || !$this->_customerVat->isCountryInEU($customerAddress->getCountry())) { $defaultGroupId = $this->_groupManagement->getDefaultGroup($customer->getStore())->getId(); if (!$customer->getDisableAutoGroupChange() && $customer->getGroupId() != $defaultGroupId) { $customer->setGroupId($defaultGroupId); $customer->save(); } } else { $result = $this->_customerVat->checkVatNumber($customerAddress->getCountryId(), $customerAddress->getVatId()); $newGroupId = $this->_customerVat->getCustomerGroupIdBasedOnVatNumber($customerAddress->getCountryId(), $result, $customer->getStore()); if (!$customer->getDisableAutoGroupChange() && $customer->getGroupId() != $newGroupId) { $customer->setGroupId($newGroupId); $customer->save(); } $customerAddress->setVatValidationResult($result); } } catch (\Exception $e) { $this->_coreRegistry->register(self::VIV_PROCESSED_FLAG, false, true); } }
/** * Run test getQuote method * * @return void */ public function testGetQuote() { $storeId = 10; $quoteId = 22; $customerGroupId = 77; $customerId = 66; $quoteMock = $this->getMock('Magento\\Quote\\Model\\Quote', ['setStoreId', 'setCustomerGroupId', 'setIsActive', 'getId', 'assignCustomer', 'setIgnoreOldQty', 'setIsSuperMode', '__wakeup'], [], '', false); $defaultGroup = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\GroupInterface')->getMock(); $defaultGroup->expects($this->any())->method('getId')->will($this->returnValue($customerGroupId)); $this->groupManagementMock->expects($this->any())->method('getDefaultGroup')->will($this->returnValue($defaultGroup)); $this->quoteRepositoryMock->expects($this->once())->method('create')->will($this->returnValue($quoteMock)); $this->quote->expects($this->any())->method('getStoreId')->will($this->returnValue($storeId)); $quoteMock->expects($this->once())->method('setStoreId')->with($storeId); $this->quote->expects($this->any())->method('getQuoteId')->will($this->returnValue(null)); $quoteMock->expects($this->once())->method('setCustomerGroupId')->with($customerGroupId)->will($this->returnSelf()); $quoteMock->expects($this->once())->method('setIsActive')->with(false)->will($this->returnSelf()); $this->quoteRepositoryMock->expects($this->once())->method('save')->with($quoteMock); $quoteMock->expects($this->once())->method('getId')->will($this->returnValue($quoteId)); $this->quote->expects($this->any())->method('setQuoteId')->with($quoteId); $this->quote->expects($this->any())->method('getCustomerId')->will($this->returnValue($customerId)); $dataCustomerMock = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\CustomerInterface')->disableOriginalConstructor()->getMock(); $this->customerRepositoryMock->expects($this->once())->method('getById')->with($customerId)->willReturn($dataCustomerMock); $quoteMock->expects($this->once())->method('assignCustomer')->with($dataCustomerMock); $quoteMock->expects($this->once())->method('setIgnoreOldQty')->with(true); $quoteMock->expects($this->once())->method('setIsSuperMode')->with(true); $this->assertEquals($quoteMock, $this->quote->getQuote()); }
/** * @param $testGroup * @param $storeId */ private function assertDefaultGroupMatches($testGroup, $storeId) { $group = $this->groupManagement->getDefaultGroup($storeId); $this->assertEquals($testGroup['id'], $group->getId()); $this->assertEquals($testGroup['code'], $group->getCode()); $this->assertEquals($testGroup['tax_class_id'], $group->getTaxClassId()); $this->assertEquals($testGroup['tax_class_name'], $group->getTaxClassName()); }
/** * Logout without dispatching event * * @return $this */ protected function _logout() { $this->_customer = null; $this->_customerModel = null; $this->setCustomerId(null); $this->setCustomerGroupId($this->groupManagement->getNotLoggedInGroup()->getId()); $this->destroy(['clear_storage' => false]); return $this; }
public function testExtract() { $customerData = ['firstname' => 'firstname', 'lastname' => 'firstname', 'email' => 'email.example.com']; $this->formFactory->expects($this->once())->method('create')->with('customer', 'form-code')->willReturn($this->customerForm); $this->customerForm->expects($this->once())->method('extractData')->with($this->request)->willReturn($customerData); $this->customerForm->expects($this->once())->method('getAllowedAttributes')->willReturn(['group_id' => 'attribute object']); $this->customerFactory->expects($this->once())->method('create')->willReturn($this->customerData); $this->dataObjectHelper->expects($this->once())->method('populateWithArray')->with($this->customerData, $customerData, '\\Magento\\Customer\\Api\\Data\\CustomerInterface')->willReturn($this->customerData); $this->storeManager->expects($this->once())->method('getStore')->willReturn($this->store); $this->store->expects($this->exactly(2))->method('getId')->willReturn(1); $this->customerGroupManagement->expects($this->once())->method('getDefaultGroup')->with(1)->willReturn($this->customerGroup); $this->customerGroup->expects($this->once())->method('getId')->willReturn(1); $this->customerData->expects($this->once())->method('setGroupId')->with(1); $this->store->expects($this->once())->method('getWebsiteId')->willReturn(1); $this->customerData->expects($this->once())->method('setWebsiteId')->with(1); $this->customerData->expects($this->once())->method('setStoreId')->with(1); $this->assertSame($this->customerData, $this->customerExtractor->extract('form-code', $this->request)); }
/** * Render block HTML * * @return string */ public function _toHtml() { if (!$this->getOptions()) { if ($this->_addGroupAllOption) { $this->addOption($this->groupManagement->getAllCustomersGroup()->getId(), __('ALL GROUPS')); } foreach ($this->_getCustomerGroups() as $groupId => $groupLabel) { $this->addOption($groupId, addslashes($groupLabel)); } } return parent::_toHtml(); }
/** * Test retrieving a valid group form. */ public function testGetForm() { $this->registry->register(RegistryConstants::CURRENT_GROUP_ID, $this->groupManagement->getDefaultGroup(0)->getId()); /** @var $block Form */ $block = $this->layout->createBlock('Magento\\Customer\\Block\\Adminhtml\\Group\\Edit\\Form', 'block'); $form = $block->getForm(); $this->assertEquals('edit_form', $form->getId()); $this->assertEquals('post', $form->getMethod()); $baseFieldSet = $form->getElement('base_fieldset'); $this->assertNotNull($baseFieldSet); $groupCodeElement = $form->getElement('customer_group_code'); $this->assertNotNull($groupCodeElement); $taxClassIdElement = $form->getElement('tax_class_id'); $this->assertNotNull($taxClassIdElement); $idElement = $form->getElement('id'); $this->assertNotNull($idElement); $this->assertEquals('1', $idElement->getValue()); $this->assertEquals('3', $taxClassIdElement->getValue()); /** @var \Magento\Tax\Model\TaxClass\Source\Customer $taxClassCustomer */ $taxClassCustomer = Bootstrap::getObjectManager()->get('Magento\\Tax\\Model\\TaxClass\\Source\\Customer'); $this->assertEquals($taxClassCustomer->toOptionArray(false), $taxClassIdElement->getData('values')); $this->assertEquals('General', $groupCodeElement->getValue()); }
/** * Apply catalog price rules to product on frontend * * @param \Magento\Framework\Event\Observer $observer * @return $this */ public function execute(\Magento\Framework\Event\Observer $observer) { /* @var $collection ProductCollection */ $collection = $observer->getEvent()->getCollection(); $store = $this->storeManager->getStore($observer->getEvent()->getStoreId()); $websiteId = $store->getWebsiteId(); if ($observer->getEvent()->hasCustomerGroupId()) { $groupId = $observer->getEvent()->getCustomerGroupId(); } else { if ($this->customerSession->isLoggedIn()) { $groupId = $this->customerSession->getCustomerGroupId(); } else { $groupId = $this->groupManagement->getNotLoggedInGroup()->getId(); } } if ($observer->getEvent()->hasDate()) { $date = new \DateTime($observer->getEvent()->getDate()); } else { $date = (new \DateTime())->setTimestamp($this->localeDate->scopeTimeStamp($store)); } $productIds = []; /* @var $product Product */ foreach ($collection as $product) { $key = implode('|', [$date->format('Y-m-d H:i:s'), $websiteId, $groupId, $product->getId()]); if (!$this->rulePricesStorage->hasRulePrice($key)) { $productIds[] = $product->getId(); } } if ($productIds) { $rulePrices = $this->resourceRuleFactory->create()->getRulePrices($date, $websiteId, $groupId, $productIds); foreach ($productIds as $productId) { $key = implode('|', [$date->format('Y-m-d H:i:s'), $websiteId, $groupId, $productId]); $this->rulePricesStorage->setRulePrice($key, isset($rulePrices[$productId]) ? $rulePrices[$productId] : false); } } return $this; }
/** * {@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 getList($sku, $customerGroupId) { $product = $this->productRepository->get($sku, ['edit_mode' => true]); $priceKey = 'website_price'; $value = $this->config->getValue('catalog/price/scope', \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE); if ($value == 0) { $priceKey = 'price'; } $cgi = $customerGroupId === 'all' ? $this->groupManagement->getAllCustomersGroup()->getId() : $customerGroupId; $prices = []; foreach ($product->getData('tier_price') as $price) { if (is_numeric($customerGroupId) && intval($price['cust_group']) === intval($customerGroupId) || $customerGroupId === 'all' && $price['all_groups']) { /** @var \Magento\Catalog\Api\Data\ProductTierPriceInterface $tierPrice */ $tierPrice = $this->priceFactory->create(); $tierPrice->setValue($price[$priceKey])->setQty($price['price_qty'])->setCustomerGroupId($cgi); $prices[] = $tierPrice; } } return $prices; }
/** * Address after save event handler * * @param \Magento\Framework\Event\Observer $observer * @return void * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function execute(\Magento\Framework\Event\Observer $observer) { /** @var $customerAddress Address */ $customerAddress = $observer->getCustomerAddress(); $customer = $customerAddress->getCustomer(); if (!$this->_customerAddress->isVatValidationEnabled($customer->getStore()) || $this->_coreRegistry->registry(self::VIV_PROCESSED_FLAG) || !$this->_canProcessAddress($customerAddress)) { return; } try { $this->_coreRegistry->register(self::VIV_PROCESSED_FLAG, true); if ($customerAddress->getVatId() == '' || !$this->_customerVat->isCountryInEU($customerAddress->getCountry())) { $defaultGroupId = $this->_groupManagement->getDefaultGroup($customer->getStore())->getId(); if (!$customer->getDisableAutoGroupChange() && $customer->getGroupId() != $defaultGroupId) { $customer->setGroupId($defaultGroupId); $customer->save(); $this->customerSession->setCustomerGroupId($defaultGroupId); } } else { $result = $this->_customerVat->checkVatNumber($customerAddress->getCountryId(), $customerAddress->getVatId()); $newGroupId = $this->_customerVat->getCustomerGroupIdBasedOnVatNumber($customerAddress->getCountryId(), $result, $customer->getStore()); if (!$customer->getDisableAutoGroupChange() && $customer->getGroupId() != $newGroupId) { $customer->setGroupId($newGroupId); $customer->save(); $this->customerSession->setCustomerGroupId($newGroupId); } $customerAddress->setVatValidationResult($result); if ($this->appState->getAreaCode() == Area::AREA_FRONTEND) { if ($result->getIsValid()) { $this->addValidMessage($customerAddress, $result); } elseif ($result->getRequestSuccess()) { $this->addInvalidMessage($customerAddress); } else { $this->addErrorMessage($customerAddress); } } } } catch (\Exception $e) { $this->_coreRegistry->register(self::VIV_PROCESSED_FLAG, false, true); } }
/** * Can apply tier price * * @param array $currentTierPrice * @param int $prevPriceGroup * @param float|string $prevQty * @return bool */ protected function canApplyTierPrice(array $currentTierPrice, $prevPriceGroup, $prevQty) { $custGroupAllId = (int) $this->groupManagement->getAllCustomersGroup()->getId(); // Tier price can be applied, if: // tier price is for current customer group or is for all groups if ((int) $currentTierPrice['cust_group'] !== $this->customerGroup && (int) $currentTierPrice['cust_group'] !== $custGroupAllId) { return false; } // and tier qty is lower than product qty if ($this->quantity < $currentTierPrice['price_qty']) { return false; } // and tier qty is bigger than previous qty if ($currentTierPrice['price_qty'] < $prevQty) { return false; } // and found tier qty is same as previous tier qty, but current tier group isn't ALL_GROUPS if ($currentTierPrice['price_qty'] == $prevQty && $prevPriceGroup !== $custGroupAllId && $currentTierPrice['cust_group'] === $custGroupAllId) { return false; } return true; }
/** * Add tier price data to loaded items * * @return $this * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function addTierPriceData() { if ($this->getFlag('tier_price_added')) { return $this; } $tierPrices = []; $productIds = []; foreach ($this->getItems() as $item) { $productIds[] = $item->getId(); $tierPrices[$item->getId()] = []; } if (!$productIds) { return $this; } /** @var $attribute \Magento\Catalog\Model\ResourceModel\Eav\Attribute */ $attribute = $this->getAttribute('tier_price'); $websiteId = 0; if (!$attribute->isScopeGlobal() && null !== $this->getStoreId()) { $websiteId = $this->_storeManager->getStore($this->getStoreId())->getWebsiteId(); } $linkField = $this->getConnection()->getAutoIncrementField($this->getTable('catalog_product_entity')); $connection = $this->getConnection(); $columns = ['price_id' => 'value_id', 'website_id' => 'website_id', 'all_groups' => 'all_groups', 'cust_group' => 'customer_group_id', 'price_qty' => 'qty', 'price' => 'value', 'product_id' => $linkField]; $select = $connection->select()->from($this->getTable('catalog_product_entity_tier_price'), $columns)->where($linkField . ' IN(?)', $productIds)->order([$linkField, 'qty']); if ($websiteId == 0) { $select->where('website_id = ?', $websiteId); } else { $select->where('website_id IN(?)', [0, $websiteId]); } foreach ($connection->fetchAll($select) as $row) { $tierPrices[$row['product_id']][] = ['website_id' => $row['website_id'], 'cust_group' => $row['all_groups'] ? $this->_groupManagement->getAllCustomersGroup()->getId() : $row['cust_group'], 'price_qty' => $row['price_qty'], 'price' => $row['price'], 'website_price' => $row['price']]; } /* @var $backend \Magento\Catalog\Model\Product\Attribute\Backend\Tierprice */ $backend = $attribute->getBackend(); foreach ($this->getItems() as $item) { $data = $tierPrices[$item->getId()]; if (!empty($data) && $websiteId) { $data = $backend->preparePriceData($data, $item->getTypeId(), $websiteId); } $item->setData('tier_price', $data); } $this->setFlag('tier_price_added', true); return $this; }
/** * Get product tier price by qty * * @param float $qty * @param Product $product * @return float|array * @deprecated (MAGETWO-31465) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function getTierPrice($qty, $product) { $allGroups = $this->_groupManagement->getAllCustomersGroup()->getId(); $prices = $product->getData('tier_price'); if ($prices === null) { $attribute = $product->getResource()->getAttribute('tier_price'); if ($attribute) { $attribute->getBackend()->afterLoad($product); $prices = $product->getData('tier_price'); } } if ($prices === null || !is_array($prices)) { if ($qty !== null) { return $product->getPrice(); } return [['price' => $product->getPrice(), 'website_price' => $product->getPrice(), 'price_qty' => 1, 'cust_group' => $allGroups]]; } $custGroup = $this->_getCustomerGroupId($product); if ($qty) { $prevQty = 1; $prevPrice = $product->getPrice(); $prevGroup = $allGroups; foreach ($prices as $price) { if ($price['cust_group'] != $custGroup && $price['cust_group'] != $allGroups) { // tier not for current customer group nor is for all groups continue; } if ($qty < $price['price_qty']) { // tier is higher than product qty continue; } if ($price['price_qty'] < $prevQty) { // higher tier qty already found continue; } if ($price['price_qty'] == $prevQty && $prevGroup != $allGroups && $price['cust_group'] == $allGroups) { // found tier qty is same as current tier qty but current tier group is ALL_GROUPS continue; } if ($price['website_price'] < $prevPrice) { $prevPrice = $price['website_price']; $prevQty = $price['price_qty']; $prevGroup = $price['cust_group']; } } return $prevPrice; } else { $qtyCache = []; foreach ($prices as $priceKey => $price) { if ($price['cust_group'] != $custGroup && $price['cust_group'] != $allGroups) { unset($prices[$priceKey]); } elseif (isset($qtyCache[$price['price_qty']])) { $priceQty = $qtyCache[$price['price_qty']]; if ($prices[$priceQty]['website_price'] > $price['website_price']) { unset($prices[$priceQty]); $qtyCache[$price['price_qty']] = $priceKey; } else { unset($prices[$priceKey]); } } else { $qtyCache[$price['price_qty']] = $priceKey; } } } return $prices ? $prices : []; }