/** * @param \Magento\Framework\App\Action\Action $subject * @param callable $proceed * @param \Magento\Framework\App\RequestInterface $request * @return mixed */ public function aroundDispatch(\Magento\Framework\App\Action\Action $subject, \Closure $proceed, \Magento\Framework\App\RequestInterface $request) { $defaultStore = $this->storeManager->getWebsite()->getDefaultStore(); $this->httpContext->setValue(\Magento\Core\Helper\Data::CONTEXT_CURRENCY, $this->session->getCurrencyCode(), $defaultStore->getDefaultCurrency()->getCode()); $this->httpContext->setValue(\Magento\Core\Helper\Data::CONTEXT_STORE, $this->httpRequest->getParam('___store', $defaultStore->getStoreCodeFromCookie()), $this->storeManager->getWebsite()->getDefaultStore()->getCode()); return $proceed($request); }
/** * Set new customer group to all his quotes * * @param \Magento\Framework\Event\Observer $observer * @return void */ public function dispatch(\Magento\Framework\Event\Observer $observer) { /** @var CustomerData $customerDataObject */ $customerDataObject = $observer->getEvent()->getCustomerDataObject(); /** @var CustomerData $origCustomerDataObject */ $origCustomerDataObject = $observer->getEvent()->getOrigCustomerDataObject(); if ($customerDataObject->getGroupId() !== $origCustomerDataObject->getGroupId()) { /** * It is needed to process customer's quotes for all websites * if customer accounts are shared between all of them */ /** @var $websites \Magento\Store\Model\Website[] */ $websites = $this->_config->isWebsiteScope() ? array($this->_storeManager->getWebsite($customerDataObject->getWebsiteId())) : $this->_storeManager->getWebsites(); foreach ($websites as $website) { $quote = $this->_quoteFactory->create(); $quote->setWebsite($website); $quote->loadByCustomer($customerDataObject->getId()); if ($quote->getId()) { $quote->setCustomerGroupId($customerDataObject->getGroupId()); $quote->collectTotals(); $quote->save(); } } } }
/** * Get url for config settings where base url option can be changed * * @return string */ protected function _getConfigUrl() { $output = ''; $defaultUnsecure = $this->_config->getValue(\Magento\Store\Model\Store::XML_PATH_UNSECURE_BASE_URL, 'default'); $defaultSecure = $this->_config->getValue(\Magento\Store\Model\Store::XML_PATH_SECURE_BASE_URL, 'default'); if ($defaultSecure == \Magento\Store\Model\Store::BASE_URL_PLACEHOLDER || $defaultUnsecure == \Magento\Store\Model\Store::BASE_URL_PLACEHOLDER) { $output = $this->_urlBuilder->getUrl('adminhtml/system_config/edit', array('section' => 'web')); } else { /** @var $dataCollection \Magento\Core\Model\Resource\Config\Data\Collection */ $dataCollection = $this->_configValueFactory->create()->getCollection(); $dataCollection->addValueFilter(\Magento\Store\Model\Store::BASE_URL_PLACEHOLDER); /** @var $data \Magento\Framework\App\Config\ValueInterface */ foreach ($dataCollection as $data) { if ($data->getScope() == 'stores') { $code = $this->_storeManager->getStore($data->getScopeId())->getCode(); $output = $this->_urlBuilder->getUrl('adminhtml/system_config/edit', array('section' => 'web', 'store' => $code)); break; } elseif ($data->getScope() == 'websites') { $code = $this->_storeManager->getWebsite($data->getScopeId())->getCode(); $output = $this->_urlBuilder->getUrl('adminhtml/system_config/edit', array('section' => 'web', 'website' => $code)); break; } } } return $output; }
/** * {@inheritdoc} * @throws \Magento\Framework\App\InitException */ public function getScope($scopeId = null) { $scope = $this->_storeManager->getWebsite($scopeId); if (!$scope instanceof \Magento\Framework\App\ScopeInterface) { throw new \Magento\Framework\App\InitException('Invalid scope object'); } return $scope; }
/** * Substitute empty value with Default country. * * @return void */ protected function _afterLoad() { $value = (string) $this->getValue(); if (empty($value)) { if ($this->getWebsite()) { $defaultCountry = $this->_storeManager->getWebsite($this->getWebsite())->getConfig(\Magento\Core\Helper\Data::XML_PATH_DEFAULT_COUNTRY); } else { $defaultCountry = $this->_coreData->getDefaultCountry($this->getStore()); } $this->setValue($defaultCountry); } }
/** * Export shipping table rates in csv format * * @return ResponseInterface */ public function execute() { $fileName = 'tablerates.csv'; /** @var $gridBlock \Magento\OfflineShipping\Block\Adminhtml\Carrier\Tablerate\Grid */ $gridBlock = $this->_view->getLayout()->createBlock('Magento\\OfflineShipping\\Block\\Adminhtml\\Carrier\\Tablerate\\Grid'); $website = $this->_storeManager->getWebsite($this->getRequest()->getParam('website')); if ($this->getRequest()->getParam('conditionName')) { $conditionName = $this->getRequest()->getParam('conditionName'); } else { $conditionName = $website->getConfig('carriers/tablerate/condition_name'); } $gridBlock->setWebsiteId($website->getId())->setConditionName($conditionName); $content = $gridBlock->getCsvFile(); return $this->_fileFactory->create($fileName, $content, \Magento\Framework\App\Filesystem::VAR_DIR); }
/** * Prepare website current dates table * * @return \Magento\Catalog\Model\Indexer\Product\Price\AbstractAction */ protected function _prepareWebsiteDateTable() { $write = $this->_getConnection(); $baseCurrency = $this->_config->getValue(\Magento\Directory\Model\Currency::XML_PATH_CURRENCY_BASE); $select = $write->select()->from(array('cw' => $this->_getTable('store_website')), array('website_id'))->join(array('csg' => $this->_getTable('store_group')), 'cw.default_group_id = csg.group_id', array('store_id' => 'default_store_id'))->where('cw.website_id != 0'); $data = array(); foreach ($write->fetchAll($select) as $item) { /** @var $website \Magento\Store\Model\Website */ $website = $this->_storeManager->getWebsite($item['website_id']); if ($website->getBaseCurrencyCode() != $baseCurrency) { $rate = $this->_currencyFactory->create()->load($baseCurrency)->getRate($website->getBaseCurrencyCode()); if (!$rate) { $rate = 1; } } else { $rate = 1; } /** @var $store \Magento\Store\Model\Store */ $store = $this->_storeManager->getStore($item['store_id']); if ($store) { $timestamp = $this->_localeDate->scopeTimeStamp($store); $data[] = array('website_id' => $website->getId(), 'website_date' => $this->_dateTime->formatDate($timestamp, false), 'rate' => $rate); } } $table = $this->_getTable('catalog_product_index_website'); $this->_emptyTable($table); if ($data) { $write->insertMultiple($table, $data); } return $this; }
/** * Get scope name and scopeId * @todo refactor to scope resolver * @return void */ private function initScope() { if (is_null($this->getSection())) { $this->setSection(''); } if (is_null($this->getWebsite())) { $this->setWebsite(''); } if (is_null($this->getStore())) { $this->setStore(''); } if ($this->getStore()) { $scope = 'stores'; $store = $this->_storeManager->getStore($this->getStore()); $scopeId = (int) $store->getId(); $scopeCode = $store->getCode(); } elseif ($this->getWebsite()) { $scope = 'websites'; $website = $this->_storeManager->getWebsite($this->getWebsite()); $scopeId = (int) $website->getId(); $scopeCode = $website->getCode(); } else { $scope = 'default'; $scopeId = 0; $scopeCode = ''; } $this->setScope($scope); $this->setScopeId($scopeId); $this->setScopeCode($scopeCode); }
/** * @param \Magento\Customer\Model\Config\Share $configShare * @param \Magento\Framework\StoreManagerInterface $storeManager * @param string $namespace * @param array $data */ public function __construct(\Magento\Customer\Model\Config\Share $configShare, \Magento\Framework\StoreManagerInterface $storeManager, $namespace = 'customer', array $data = array()) { if ($configShare->isWebsiteScope()) { $namespace .= '_' . $storeManager->getWebsite()->getCode(); } parent::__construct($namespace, $data); }
/** * Save title and price of link item * * @param \Magento\Downloadable\Model\Link $linkObject * @return $this */ public function saveItemTitleAndPrice($linkObject) { $writeAdapter = $this->_getWriteAdapter(); $linkTitleTable = $this->getTable('downloadable_link_title'); $linkPriceTable = $this->getTable('downloadable_link_price'); $select = $writeAdapter->select()->from($this->getTable('downloadable_link_title'))->where('link_id=:link_id AND store_id=:store_id'); $bind = array(':link_id' => $linkObject->getId(), ':store_id' => (int) $linkObject->getStoreId()); if ($writeAdapter->fetchOne($select, $bind)) { $where = array('link_id = ?' => $linkObject->getId(), 'store_id = ?' => (int) $linkObject->getStoreId()); if ($linkObject->getUseDefaultTitle()) { $writeAdapter->delete($linkTitleTable, $where); } else { $insertData = array('title' => $linkObject->getTitle()); $writeAdapter->update($linkTitleTable, $insertData, $where); } } else { if (!$linkObject->getUseDefaultTitle()) { $writeAdapter->insert($linkTitleTable, array('link_id' => $linkObject->getId(), 'store_id' => (int) $linkObject->getStoreId(), 'title' => $linkObject->getTitle())); } } $select = $writeAdapter->select()->from($linkPriceTable)->where('link_id=:link_id AND website_id=:website_id'); $bind = array(':link_id' => $linkObject->getId(), ':website_id' => (int) $linkObject->getWebsiteId()); if ($writeAdapter->fetchOne($select, $bind)) { $where = array('link_id = ?' => $linkObject->getId(), 'website_id = ?' => $linkObject->getWebsiteId()); if ($linkObject->getUseDefaultPrice()) { $writeAdapter->delete($linkPriceTable, $where); } else { $writeAdapter->update($linkPriceTable, array('price' => $linkObject->getPrice()), $where); } } else { if (!$linkObject->getUseDefaultPrice()) { $dataToInsert[] = array('link_id' => $linkObject->getId(), 'website_id' => (int) $linkObject->getWebsiteId(), 'price' => (double) $linkObject->getPrice()); if ($linkObject->getOrigData('link_id') != $linkObject->getLinkId()) { $_isNew = true; } else { $_isNew = false; } if ($linkObject->getWebsiteId() == 0 && $_isNew && !$this->_catalogData->isPriceGlobal()) { $websiteIds = $linkObject->getProductWebsiteIds(); foreach ($websiteIds as $websiteId) { $baseCurrency = $this->_configuration->getValue(\Magento\Directory\Model\Currency::XML_PATH_CURRENCY_BASE, 'default'); $websiteCurrency = $this->_storeManager->getWebsite($websiteId)->getBaseCurrencyCode(); if ($websiteCurrency == $baseCurrency) { continue; } $rate = $this->_createCurrency()->load($baseCurrency)->getRate($websiteCurrency); if (!$rate) { $rate = 1; } $newPrice = $linkObject->getPrice() * $rate; $dataToInsert[] = array('link_id' => $linkObject->getId(), 'website_id' => (int) $websiteId, 'price' => $newPrice); } } $writeAdapter->insertMultiple($linkPriceTable, $dataToInsert); } } return $this; }
/** * Get options for grid filter * * @return null|array */ public function getCondition() { $id = $this->getValue(); if (!$id) { return null; } $website = $this->_storeManager->getWebsite($id); return array('in' => $website->getStoresIds(true)); }
/** * Retrieve default currency for selected store, website or website group * @todo: Refactor to ScopeDefiner * @param \Magento\Framework\App\RequestInterface $request * @return string */ public function getDefaultCurrency(\Magento\Framework\App\RequestInterface $request) { if ($request->getParam('store')) { $store = $request->getParam('store'); $currencyCode = $this->_storeManager->getStore($store)->getBaseCurrencyCode(); } else { if ($request->getParam('website')) { $website = $request->getParam('website'); $currencyCode = $this->_storeManager->getWebsite($website)->getBaseCurrencyCode(); } else { if ($request->getParam('group')) { $group = $request->getParam('group'); $currencyCode = $this->_storeManager->getGroup($group)->getWebsite()->getBaseCurrencyCode(); } else { $currencyCode = $this->_configuration->getValue(\Magento\Directory\Model\Currency::XML_PATH_CURRENCY_BASE, 'default'); } } } return $currencyCode; }
/** * {@inheritdoc} */ public function delete($productSku, $customerGroupId, $qty) { $product = $this->productRepository->get($productSku, true); if ($this->config->getValue('catalog/price/scope', \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE) == 0) { $websiteId = 0; } else { $websiteId = $this->storeManager->getWebsite()->getId(); } $this->priceModifier->removeTierPrice($product, $customerGroupId, $qty, $websiteId); return true; }
/** * Get DB resource statement for processing query result * * @param int $fromDate * @param int $toDate * @param int|null $productId * @param int|null $websiteId * @return \Zend_Db_Statement_Interface */ protected function _getRuleProductsStmt($fromDate, $toDate, $productId = null, $websiteId = null) { $read = $this->_getReadAdapter(); /** * Sort order is important * It used for check stop price rule condition. * website_id customer_group_id product_id sort_order * 1 1 1 0 * 1 1 1 1 * 1 1 1 2 * if row with sort order 1 will have stop flag we should exclude * all next rows for same product id from price calculation */ $select = $read->select()->from(array('rp' => $this->getTable('catalogrule_product')))->where($read->quoteInto('rp.from_time = 0 or rp.from_time <= ?', $toDate) . ' OR ' . $read->quoteInto('rp.to_time = 0 or rp.to_time >= ?', $fromDate))->order(array('rp.website_id', 'rp.customer_group_id', 'rp.product_id', 'rp.sort_order', 'rp.rule_id')); if (!is_null($productId)) { $select->where('rp.product_id=?', $productId); } /** * Join default price and websites prices to result */ $priceAttr = $this->_eavConfig->getAttribute(Product::ENTITY, 'price'); $priceTable = $priceAttr->getBackend()->getTable(); $attributeId = $priceAttr->getId(); $joinCondition = '%1$s.entity_id=rp.product_id AND (%1$s.attribute_id=' . $attributeId . ') and %1$s.store_id=%2$s'; $select->join(array('pp_default' => $priceTable), sprintf($joinCondition, 'pp_default', \Magento\Store\Model\Store::DEFAULT_STORE_ID), array('default_price' => 'pp_default.value')); if ($websiteId !== null) { $website = $this->_storeManager->getWebsite($websiteId); $defaultGroup = $website->getDefaultGroup(); if ($defaultGroup instanceof \Magento\Store\Model\Group) { $storeId = $defaultGroup->getDefaultStoreId(); } else { $storeId = \Magento\Store\Model\Store::DEFAULT_STORE_ID; } $select->joinInner(array('product_website' => $this->getTable('catalog_product_website')), 'product_website.product_id=rp.product_id ' . 'AND rp.website_id=product_website.website_id ' . 'AND product_website.website_id=' . $websiteId, array()); $tableAlias = 'pp' . $websiteId; $fieldAlias = 'website_' . $websiteId . '_price'; $select->joinLeft(array($tableAlias => $priceTable), sprintf($joinCondition, $tableAlias, $storeId), array($fieldAlias => $tableAlias . '.value')); } else { foreach ($this->_storeManager->getWebsites() as $website) { $websiteId = $website->getId(); $defaultGroup = $website->getDefaultGroup(); if ($defaultGroup instanceof \Magento\Store\Model\Group) { $storeId = $defaultGroup->getDefaultStoreId(); } else { $storeId = \Magento\Store\Model\Store::DEFAULT_STORE_ID; } $tableAlias = 'pp' . $websiteId; $fieldAlias = 'website_' . $websiteId . '_price'; $select->joinLeft(array($tableAlias => $priceTable), sprintf($joinCondition, $tableAlias, $storeId), array($fieldAlias => $tableAlias . '.value')); } } return $read->query($select); }
/** * Processing object after delete data * * @return \Magento\Framework\Model\AbstractModel */ protected function _afterDelete() { $result = parent::_afterDelete(); if ($this->getScope() == \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITES) { $attribute = $this->_eavConfig->getAttribute('customer_address', 'street'); $website = $this->_storeManager->getWebsite($this->getScopeCode()); $attribute->setWebsite($website); $attribute->load($attribute->getId()); $attribute->setData('scope_multiline_count', null); $attribute->save(); } return $result; }
/** * @param \Magento\Framework\App\Helper\Context $context * @param \Magento\Framework\StoreManagerInterface $storeManager * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig * @param array $data * * @throws \InvalidArgumentException */ public function __construct(\Magento\Framework\App\Helper\Context $context, \Magento\Framework\StoreManagerInterface $storeManager, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, array $data = array()) { parent::__construct($context); $this->_scopeConfig = $scopeConfig; $this->_currentStore = isset($data['current_store']) ? $data['current_store'] : $storeManager->getStore(); if (!$this->_currentStore instanceof \Magento\Store\Model\Store) { throw new \InvalidArgumentException('Required store object is invalid'); } $this->_website = isset($data['website']) ? $data['website'] : $storeManager->getWebsite(); if (!$this->_website instanceof \Magento\Store\Model\Website) { throw new \InvalidArgumentException('Required website object is invalid'); } }
/** * Processing object after delete data * * @return \Magento\Framework\Model\AbstractModel */ protected function _afterDelete() { $result = parent::_afterDelete(); if ($this->getScope() == 'websites') { $website = $this->storeManager->getWebsite($this->getScopeCode()); foreach ($this->_getAttributeObjects() as $attributeObject) { $attributeObject->setWebsite($website); $attributeObject->load($attributeObject->getId()); $attributeObject->setData('scope_is_required', null); $attributeObject->setData('scope_is_visible', null); $attributeObject->save(); } } return $result; }
/** * Calculate product price based on special price data and price rules * * @param float $basePrice * @param float $specialPrice * @param string $specialPriceFrom * @param string $specialPriceTo * @param bool|float|null $rulePrice * @param mixed|null $wId * @param integer|null $gId * @param int|null $productId * @return float */ public function calculatePrice($basePrice, $specialPrice, $specialPriceFrom, $specialPriceTo, $rulePrice = false, $wId = null, $gId = null, $productId = null) { \Magento\Framework\Profiler::start('__PRODUCT_CALCULATE_PRICE__'); if ($wId instanceof Store) { $sId = $wId->getId(); $wId = $wId->getWebsiteId(); } else { $sId = $this->_storeManager->getWebsite($wId)->getDefaultGroup()->getDefaultStoreId(); } $finalPrice = $basePrice; $finalPrice = $this->calculateSpecialPrice($finalPrice, $specialPrice, $specialPriceFrom, $specialPriceTo, $sId); if ($rulePrice === false) { $storeTimestamp = $this->_localeDate->scopeTimeStamp($sId); $rulePrice = $this->_ruleFactory->create()->getRulePrice($storeTimestamp, $wId, $gId, $productId); } if ($rulePrice !== null && $rulePrice !== false) { $finalPrice = min($finalPrice, $rulePrice); } $finalPrice = max($finalPrice, 0); \Magento\Framework\Profiler::stop('__PRODUCT_CALCULATE_PRICE__'); return $finalPrice; }
/** * Save billing address information to quote * This method is called by One Page Checkout JS (AJAX) while saving the billing information. * * @param array $data * @param int $customerAddressId * @return array */ public function saveBilling($data, $customerAddressId) { if (empty($data)) { return array('error' => -1, 'message' => __('Invalid data')); } $address = $this->getQuote()->getBillingAddress(); $addressForm = $this->_formFactory->create(\Magento\Customer\Service\V1\AddressMetadataServiceInterface::ENTITY_TYPE_ADDRESS, 'customer_address_edit', array(), $this->_request->isAjax(), Form::IGNORE_INVISIBLE, array()); if (!empty($customerAddressId)) { try { $customerAddress = $this->_customerAddressService->getAddress($customerAddressId); } catch (\Exception $e) { /** Address does not exist */ } if (isset($customerAddress)) { if ($customerAddress->getCustomerId() != $this->getQuote()->getCustomerId()) { return array('error' => 1, 'message' => __('The customer address is not valid.')); } $address->importCustomerAddressData($customerAddress)->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' => array_values($addressErrors)); } $addressData = $addressForm->compactData($addressData); $address->addData($addressData); //unset billing address attributes which were not shown in form foreach ($addressForm->getAttributes() as $attribute) { if (!isset($data[$attribute->getAttributeCode()])) { $address->setData($attribute->getAttributeCode(), null); } } $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); $this->getQuote()->setBillingAddress($address); } // validate billing address if (($validateRes = $address->validate()) !== true) { return array('error' => 1, 'message' => $validateRes); } if (true !== ($result = $this->_validateCustomerData($data))) { return $result; } else { /** Even though _validateCustomerData should not modify data, it does */ $address = $this->getQuote()->getBillingAddress(); } if (!$this->getQuote()->getCustomerId() && self::METHOD_REGISTER == $this->getQuote()->getCheckoutMethod()) { if ($this->_customerEmailExists($address->getEmail(), $this->_storeManager->getWebsite()->getId())) { return array('error' => 1, 'message' => __('There is already a registered customer using this email address. Please log in using this email address or enter a different email address to register your account.')); } } if (!$this->getQuote()->isVirtual()) { /** * Billing address using options */ $usingCase = isset($data['use_for_shipping']) ? (int) $data['use_for_shipping'] : 0; switch ($usingCase) { case 0: $shipping = $this->getQuote()->getShippingAddress(); $shipping->setSameAsBilling(0); break; case 1: $billing = clone $address; $billing->unsAddressId()->unsAddressType(); $shipping = $this->getQuote()->getShippingAddress(); $shippingMethod = $shipping->getShippingMethod(); // Billing address properties that must be always copied to shipping address $requiredBillingAttributes = array('customer_address_id'); // don't reset original shipping data, if it was not changed by customer foreach ($shipping->getData() as $shippingKey => $shippingValue) { if (!is_null($shippingValue) && !is_null($billing->getData($shippingKey)) && !isset($data[$shippingKey]) && !in_array($shippingKey, $requiredBillingAttributes)) { $billing->unsetData($shippingKey); } } $shipping->addData($billing->getData())->setSameAsBilling(1)->setSaveInAddressBook(0)->setShippingMethod($shippingMethod)->setCollectShippingRates(true); $this->getCheckout()->setStepData('shipping', 'complete', true); break; } } $this->getQuote()->collectTotals(); $this->getQuote()->save(); if (!$this->getQuote()->isVirtual() && $this->getCheckout()->getStepData('shipping', 'complete') == true) { //Recollect Shipping rates for shipping methods $this->getQuote()->getShippingAddress()->setCollectShippingRates(true); } $this->getCheckout()->setStepData('billing', 'allow', true)->setStepData('billing', 'complete', true)->setStepData('shipping', 'allow', true); return array(); }
/** * Initialize currently ran store * * @param \Magento\Framework\StoreManagerInterface $storage * @param array $arguments * @return void * @throws \Magento\Framework\App\InitException */ protected function _reinitStores(\Magento\Framework\StoreManagerInterface $storage, $arguments) { Profiler::start('init_stores'); $storage->reinitStores(); Profiler::stop('init_stores'); $scopeCode = $arguments['scopeCode']; $scopeType = $arguments['scopeType'] ?: ScopeInterface::SCOPE_STORE; if (empty($scopeCode) && false == is_null($storage->getWebsite(true))) { $scopeCode = $storage->getWebsite(true)->getCode(); $scopeType = ScopeInterface::SCOPE_WEBSITE; } switch ($scopeType) { case ScopeInterface::SCOPE_STORE: $storage->setCurrentStore($scopeCode); break; case ScopeInterface::SCOPE_GROUP: $storage->setCurrentStore($this->_getStoreByGroup($storage, $scopeCode)); break; case ScopeInterface::SCOPE_WEBSITE: $storage->setCurrentStore($this->_getStoreByWebsite($storage, $scopeCode)); break; default: throw new \Magento\Framework\App\InitException('Store Manager has not been initialized properly'); } $currentStore = $storage->getStore()->getCode(); if (!empty($currentStore)) { $this->_checkCookieStore($storage, $scopeType); $this->_checkRequestStore($storage, $scopeType); } }
/** * Set website id * * @param int $websiteId * @return $this */ public function setWebsiteId($websiteId) { $this->_website = $this->_storeManager->getWebsite($websiteId); return $this; }
/** * Get website code * * @param mixed $website * @return string */ protected function _getWebsiteCode($website = null) { return $this->_storeManager->getWebsite($website)->getCode(); }
/** * Upload table rate file and import data from it * * @param \Magento\Framework\Object $object * @throws \Magento\Framework\Model\Exception * @return \Magento\OfflineShipping\Model\Resource\Carrier\Tablerate * @todo: this method should be refactored as soon as updated design will be provided * @see https://wiki.corp.x.com/display/MCOMS/Magento+Filesystem+Decisions */ public function uploadAndImport(\Magento\Framework\Object $object) { if (empty($_FILES['groups']['tmp_name']['tablerate']['fields']['import']['value'])) { return $this; } $csvFile = $_FILES['groups']['tmp_name']['tablerate']['fields']['import']['value']; $website = $this->_storeManager->getWebsite($object->getScopeId()); $this->_importWebsiteId = (int) $website->getId(); $this->_importUniqueHash = array(); $this->_importErrors = array(); $this->_importedRows = 0; $tmpDirectory = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem::SYS_TMP_DIR); $path = $tmpDirectory->getRelativePath($csvFile); $stream = $tmpDirectory->openFile($path); // check and skip headers $headers = $stream->readCsv(); if ($headers === false || count($headers) < 5) { $stream->close(); throw new \Magento\Framework\Model\Exception(__('Please correct Table Rates File Format.')); } if ($object->getData('groups/tablerate/fields/condition_name/inherit') == '1') { $conditionName = (string) $this->_coreConfig->getValue('carriers/tablerate/condition_name', 'default'); } else { $conditionName = $object->getData('groups/tablerate/fields/condition_name/value'); } $this->_importConditionName = $conditionName; $adapter = $this->_getWriteAdapter(); $adapter->beginTransaction(); try { $rowNumber = 1; $importData = array(); $this->_loadDirectoryCountries(); $this->_loadDirectoryRegions(); // delete old data by website and condition name $condition = array('website_id = ?' => $this->_importWebsiteId, 'condition_name = ?' => $this->_importConditionName); $adapter->delete($this->getMainTable(), $condition); while (false !== ($csvLine = $stream->readCsv())) { $rowNumber++; if (empty($csvLine)) { continue; } $row = $this->_getImportRow($csvLine, $rowNumber); if ($row !== false) { $importData[] = $row; } if (count($importData) == 5000) { $this->_saveImportData($importData); $importData = array(); } } $this->_saveImportData($importData); $stream->close(); } catch (\Magento\Framework\Model\Exception $e) { $adapter->rollback(); $stream->close(); throw new \Magento\Framework\Model\Exception($e->getMessage()); } catch (\Exception $e) { $adapter->rollback(); $stream->close(); $this->_logger->logException($e); throw new \Magento\Framework\Model\Exception(__('Something went wrong while importing table rates.')); } $adapter->commit(); if ($this->_importErrors) { $error = __('We couldn\'t import this file because of these errors: %1', implode(" \n", $this->_importErrors)); throw new \Magento\Framework\Model\Exception($error); } return $this; }
/** * @param Product $product * @param null|false|\Magento\Sales\Model\Quote\Address $shipping * @param null|false|\Magento\Sales\Model\Quote\Address $billing * @param Website $website * @param bool $calculateTax * @param bool $ignoreDiscount * @return \Magento\Framework\Object[] */ public function getProductWeeeAttributes($product, $shipping = null, $billing = null, $website = null, $calculateTax = null, $ignoreDiscount = false) { $result = array(); $allWeee = $this->getWeeeTaxAttributeCodes(); if (!$allWeee) { return $result; } $websiteId = $this->_storeManager->getWebsite($website)->getId(); /** @var \Magento\Store\Model\Store $store */ $store = $this->_storeManager->getWebsite($website)->getDefaultGroup()->getDefaultStore(); /** @var \Magento\Tax\Model\Calculation $calculator */ $calculator = $this->_calculationFactory->create(); if ($shipping) { $customerTaxClass = $shipping->getQuote()->getCustomerTaxClassId(); } else { $customerTaxClass = null; } $rateRequest = $calculator->getRateRequest($shipping, $billing, $customerTaxClass, $store); $defaultRateRequest = $calculator->getDefaultRateRequest($store); $discountPercent = 0; if (!$ignoreDiscount && $this->weeeConfig->isDiscounted($store)) { $discountPercent = $this->_getDiscountPercentForProduct($product); } $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(?)', array($websiteId, 0))->where('country = ?', $rateRequest->getCountryId())->where('state IN(?)', array($rateRequest->getRegionId(), '*'))->where('entity_id = ?', (int) $product->getId())->limit(1); $order = array('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) { if ($discountPercent) { $value = $this->_storeManager->getStore()->roundPrice($value - $value * $discountPercent / 100); } $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 = $store->roundPrice($amountInclTax); $taxAmount = $amountInclTax - $amountInclTax / (100 + $currentPercent) * 100; $taxAmount = $store->roundPrice($taxAmount); } else { $appliedRates = $this->_calculationFactory->create()->getAppliedRates($rateRequest); if (count($appliedRates) > 1) { $taxAmount = 0; foreach ($appliedRates as $appliedRate) { $taxRate = $appliedRate['percent']; $taxAmount += $this->_storeManager->getStore()->roundPrice($value * $taxRate / 100); } } else { $taxAmount = $this->_storeManager->getStore()->roundPrice($value * $currentPercent / 100); } $taxAmount = $store->roundPrice($value * $currentPercent / 100); } } $one = new \Magento\Framework\Object(); $one->setName(__($attribute->getFrontend()->getLabel()))->setAmount($amount)->setTaxAmount($taxAmount)->setCode($attribute->getAttributeCode()); $result[] = $one; } } } return $result; }
/** * Retrieve website model * * @return Website|bool */ public function getWebsite() { if (is_null($this->getWebsiteId())) { return false; } return $this->_storeManager->getWebsite($this->getWebsiteId()); }
/** * Saving customer subscription status * * @param int $customerId * @param bool $subscribe indicates whether the customer should be subscribed or unsubscribed * @return $this * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ protected function _updateCustomerSubscription($customerId, $subscribe) { try { $customerData = $this->_customerAccountService->getCustomer($customerId); } catch (NoSuchEntityException $e) { return $this; } $this->loadByCustomerId($customerId); if (!$subscribe && !$this->getId()) { return $this; } if (!$this->getId()) { $this->setSubscriberConfirmCode($this->randomSequence()); } $sendInformationEmail = false; $status = self::STATUS_SUBSCRIBED; if ($subscribe) { if (CustomerAccountServiceInterface::ACCOUNT_CONFIRMATION_REQUIRED == $this->_customerAccountService->getConfirmationStatus($customerId)) { $status = self::STATUS_UNCONFIRMED; } } else { $status = self::STATUS_UNSUBSCRIBED; } /** * If subscription status has been changed then send email to the customer */ if ($status != self::STATUS_UNCONFIRMED && $status != $this->getStatus()) { $sendInformationEmail = true; } if ($status != $this->getStatus()) { $this->setStatusChanged(true); } $this->setStatus($status); if (!$this->getId()) { $storeId = $customerData->getStoreId(); if ($customerData->getStoreId() == 0) { $storeId = $this->_storeManager->getWebsite($customerData->getWebsiteId())->getDefaultStore()->getId(); } $this->setStoreId($storeId)->setCustomerId($customerData->getId())->setEmail($customerData->getEmail()); } else { $this->setStoreId($customerData->getStoreId())->setEmail($customerData->getEmail()); } $this->save(); $sendSubscription = $sendInformationEmail; if (is_null($sendSubscription) xor $sendSubscription) { try { if ($this->isStatusChanged() && $status == self::STATUS_UNSUBSCRIBED) { $this->sendUnsubscriptionEmail(); } elseif ($this->isStatusChanged() && $status == self::STATUS_SUBSCRIBED) { $this->sendConfirmationSuccessEmail(); } } catch (MailException $e) { // If we are not able to send a new account email, this should be ignored $this->_logger->logException($e); } } return $this; }
/** * Set Website scope * * @param Website|int $website * @return $this */ public function setWebsite($website) { $this->_website = $this->_storeManager->getWebsite($website); $this->addBindParam('scope_website_id', $this->_website->getId()); return $this; }
/** * Generation Shipment Details Node according to origin region * * @param \Magento\Shipping\Model\Simplexml\Element $xml * @param RateRequest $rawRequest * @param string $originRegion * @return void */ protected function _shipmentDetails($xml, $rawRequest, $originRegion = '') { $nodeShipmentDetails = $xml->addChild('ShipmentDetails', '', ''); $nodeShipmentDetails->addChild('NumberOfPieces', count($rawRequest->getPackages())); if ($originRegion) { $nodeShipmentDetails->addChild('CurrencyCode', $this->_storeManager->getWebsite($this->_request->getWebsiteId())->getBaseCurrencyCode()); } $nodePieces = $nodeShipmentDetails->addChild('Pieces', '', ''); /* * Package type * EE (DHL Express Envelope), OD (Other DHL Packaging), CP (Custom Packaging) * DC (Document), DM (Domestic), ED (Express Document), FR (Freight) * BD (Jumbo Document), BP (Jumbo Parcel), JD (Jumbo Junior Document) * JP (Jumbo Junior Parcel), PA (Parcel), DF (DHL Flyer) */ $i = 0; foreach ($rawRequest->getPackages() as $package) { $nodePiece = $nodePieces->addChild('Piece', '', ''); $packageType = 'EE'; if ($package['params']['container'] == self::DHL_CONTENT_TYPE_NON_DOC) { $packageType = 'CP'; } $nodePiece->addChild('PieceID', ++$i); $nodePiece->addChild('PackageType', $packageType); $nodePiece->addChild('Weight', round($package['params']['weight'], 1)); $params = $package['params']; if ($params['width'] && $params['length'] && $params['height']) { if (!$originRegion) { $nodePiece->addChild('Width', round($params['width'])); $nodePiece->addChild('Height', round($params['height'])); $nodePiece->addChild('Depth', round($params['length'])); } else { $nodePiece->addChild('Depth', round($params['length'])); $nodePiece->addChild('Width', round($params['width'])); $nodePiece->addChild('Height', round($params['height'])); } } $content = array(); foreach ($package['items'] as $item) { $content[] = $item['name']; } $nodePiece->addChild('PieceContents', substr(implode(',', $content), 0, 34)); } if (!$originRegion) { $nodeShipmentDetails->addChild('Weight', round($rawRequest->getPackageWeight(), 1)); $nodeShipmentDetails->addChild('WeightUnit', substr($this->_getWeightUnit(), 0, 1)); $nodeShipmentDetails->addChild('GlobalProductCode', $rawRequest->getShippingMethod()); $nodeShipmentDetails->addChild('LocalProductCode', $rawRequest->getShippingMethod()); $nodeShipmentDetails->addChild('Date', $this->_coreDate->date('Y-m-d')); $nodeShipmentDetails->addChild('Contents', 'DHL Parcel'); /** * The DoorTo Element defines the type of delivery service that applies to the shipment. * The valid values are DD (Door to Door), DA (Door to Airport) , AA and DC (Door to * Door non-compliant) */ $nodeShipmentDetails->addChild('DoorTo', 'DD'); $nodeShipmentDetails->addChild('DimensionUnit', substr($this->_getDimensionUnit(), 0, 1)); if ($package['params']['container'] == self::DHL_CONTENT_TYPE_NON_DOC) { $packageType = 'CP'; } $nodeShipmentDetails->addChild('PackageType', $packageType); if ($this->getConfigData('content_type') == self::DHL_CONTENT_TYPE_NON_DOC) { $nodeShipmentDetails->addChild('IsDutiable', 'Y'); } $nodeShipmentDetails->addChild('CurrencyCode', $this->_storeManager->getWebsite($this->_request->getWebsiteId())->getBaseCurrencyCode()); } else { if ($package['params']['container'] == self::DHL_CONTENT_TYPE_NON_DOC) { $packageType = 'CP'; } $nodeShipmentDetails->addChild('PackageType', $packageType); $nodeShipmentDetails->addChild('Weight', $rawRequest->getPackageWeight()); $nodeShipmentDetails->addChild('DimensionUnit', substr($this->_getDimensionUnit(), 0, 1)); $nodeShipmentDetails->addChild('WeightUnit', substr($this->_getWeightUnit(), 0, 1)); $nodeShipmentDetails->addChild('GlobalProductCode', $rawRequest->getShippingMethod()); $nodeShipmentDetails->addChild('LocalProductCode', $rawRequest->getShippingMethod()); /** * The DoorTo Element defines the type of delivery service that applies to the shipment. * The valid values are DD (Door to Door), DA (Door to Airport) , AA and DC (Door to * Door non-compliant) */ $nodeShipmentDetails->addChild('DoorTo', 'DD'); $nodeShipmentDetails->addChild('Date', $this->_coreDate->date('Y-m-d')); $nodeShipmentDetails->addChild('Contents', 'DHL Parcel TEST'); } }
/** * Get relative watermark file path * or false if file not found * * @return string | bool */ protected function _getWatermarkFilePath() { $filePath = false; if (!($file = $this->getWatermarkFile())) { return $filePath; } $baseDir = $this->_catalogProductMediaConfig->getBaseMediaPath(); $candidates = array($baseDir . '/watermark/stores/' . $this->_storeManager->getStore()->getId() . $file, $baseDir . '/watermark/websites/' . $this->_storeManager->getWebsite()->getId() . $file, $baseDir . '/watermark/default/' . $file, $baseDir . '/watermark/' . $file); foreach ($candidates as $candidate) { if ($this->_mediaDirectory->isExist($candidate)) { $filePath = $this->_mediaDirectory->getAbsolutePath($candidate); break; } } if (!$filePath) { $filePath = $this->_viewFileSystem->getStaticFileName($file); } return $filePath; }
/** * {@inheritDoc} */ public function isCustomerInStore($customerWebsiteId, $storeId) { $ids = []; if ((bool) $this->configShare->isWebsiteScope()) { $ids = $this->storeManager->getWebsite($customerWebsiteId)->getStoreIds(); } else { foreach ($this->storeManager->getStores() as $store) { $ids[] = $store->getId(); } } return in_array($storeId, $ids); }