/** * Execute before toHtml() code. * * @return $this */ public function _beforeToHtml() { $this->_currency = $this->_currencyFactory->create()->load($this->_scopeConfig->getValue(Currency::XML_PATH_CURRENCY_BASE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE)); $this->_collection = $this->_collectionFactory->create()->setCustomerIdFilter((int) $this->_coreRegistry->registry(RegistryConstants::CURRENT_CUSTOMER_ID))->setOrderStateFilter(Order::STATE_CANCELED, true)->load(); $this->_groupedCollection = []; foreach ($this->_collection as $sale) { if ($sale->getStoreId() !== null) { $store = $this->_storeManager->getStore($sale->getStoreId()); $websiteId = $store->getWebsiteId(); $groupId = $store->getGroupId(); $storeId = $store->getId(); $sale->setWebsiteId($store->getWebsiteId()); $sale->setWebsiteName($store->getWebsite()->getName()); $sale->setGroupId($store->getGroupId()); $sale->setGroupName($store->getGroup()->getName()); } else { $websiteId = 0; $groupId = 0; $storeId = 0; $sale->setStoreName(__('Deleted Stores')); } $this->_groupedCollection[$websiteId][$groupId][$storeId] = $sale; $this->_websiteCounts[$websiteId] = isset($this->_websiteCounts[$websiteId]) ? $this->_websiteCounts[$websiteId] + 1 : 1; } return parent::_beforeToHtml(); }
/** * Saving currency rates * * @param array $rates * @return \Magento\Directory\Model\Currency\Import\AbstractImport */ protected function _saveRates($rates) { foreach ($rates as $currencyCode => $currencyRates) { $this->_currencyFactory->create()->setId($currencyCode)->setRates($currencyRates)->save(); } return $this; }
public function testFetchRates() { $currencyFromList = ['USD']; $currencyToList = ['EUR', 'UAH']; $responseBody = '{"query":{"count":7,"created":"2016-04-05T16:46:55Z","lang":"en-US","results":{"rate":' . '[{"id":"USDEUR","Name":"USD/EUR","Rate":"0.9022","Date":"4/5/2016"}]}}}'; $expectedCurrencyRateList = ['USD' => ['EUR' => 0.9022, 'UAH' => null]]; $message = "We can't retrieve a rate from http://query.yahooapis.com/v1/public/yql?format=json" . "&q=select+*+from+yahoo.finance.xchange+where+pair+in+%28%22USDEUR%22%2C%22USDUAH%22)" . "&env=store://datatables.org/alltableswithkeys for UAH."; /** @var \Magento\Directory\Model\Currency|\PHPUnit_Framework_MockObject_MockObject $currencyMock */ $currencyMock = $this->getMockBuilder('Magento\\Directory\\Model\\Currency')->disableOriginalConstructor()->setMethods([])->getMock(); /** @var \Magento\Framework\HTTP\ZendClient|\PHPUnit_Framework_MockObject_MockObject $currencyMock */ $httpClientMock = $this->getMockBuilder('Magento\\Framework\\HTTP\\ZendClient')->disableOriginalConstructor()->setMethods([])->getMock(); /** @var \Zend_Http_Response|\PHPUnit_Framework_MockObject_MockObject $currencyMock */ $httpResponseMock = $this->getMockBuilder('Zend_Http_Response')->disableOriginalConstructor()->setMethods([])->getMock(); $this->currencyFactoryMock->expects($this->any())->method('create')->willReturn($currencyMock); $currencyMock->expects($this->once())->method('getConfigBaseCurrencies')->willReturn($currencyFromList); $currencyMock->expects($this->once())->method('getConfigAllowCurrencies')->willReturn($currencyToList); $this->httpClientFactoryMock->expects($this->any())->method('create')->willReturn($httpClientMock); $httpClientMock->expects($this->atLeastOnce())->method('setUri')->willReturnSelf(); $httpClientMock->expects($this->atLeastOnce())->method('setConfig')->willReturnSelf(); $httpClientMock->expects($this->atLeastOnce())->method('request')->willReturn($httpResponseMock); $httpResponseMock->expects($this->any())->method('getBody')->willReturn($responseBody); $this->assertEquals($expectedCurrencyRateList, $this->model->fetchRates()); $messages = $this->model->getMessages(); $this->assertNotEmpty($messages); $this->assertTrue(is_array($messages)); $this->assertEquals($message, (string) $messages[0]); }
public function testFetchRates() { $currencyFromList = ['USD']; $currencyToList = ['EUR', 'UAH']; $responseBody = '{"base":"USD","date":"2015-10-07","rates":{"EUR":0.9022}}'; $expectedCurrencyRateList = ['USD' => ['EUR' => 0.9022, 'UAH' => null]]; $message = "We can't retrieve a rate from http://api.fixer.io/latest?base=USD&symbols=EUR,UAH for UAH."; /** @var \Magento\Directory\Model\Currency|\PHPUnit_Framework_MockObject_MockObject $currencyMock */ $currencyMock = $this->getMockBuilder('Magento\\Directory\\Model\\Currency')->disableOriginalConstructor()->setMethods([])->getMock(); /** @var \Magento\Framework\HTTP\ZendClient|\PHPUnit_Framework_MockObject_MockObject $currencyMock */ $httpClientMock = $this->getMockBuilder('Magento\\Framework\\HTTP\\ZendClient')->disableOriginalConstructor()->setMethods([])->getMock(); /** @var \Zend_Http_Response|\PHPUnit_Framework_MockObject_MockObject $currencyMock */ $httpResponseMock = $this->getMockBuilder('Zend_Http_Response')->disableOriginalConstructor()->setMethods([])->getMock(); $this->currencyFactoryMock->expects($this->any())->method('create')->willReturn($currencyMock); $currencyMock->expects($this->once())->method('getConfigBaseCurrencies')->willReturn($currencyFromList); $currencyMock->expects($this->once())->method('getConfigAllowCurrencies')->willReturn($currencyToList); $this->httpClientFactoryMock->expects($this->any())->method('create')->willReturn($httpClientMock); $httpClientMock->expects($this->atLeastOnce())->method('setUri')->willReturnSelf(); $httpClientMock->expects($this->atLeastOnce())->method('setConfig')->willReturnSelf(); $httpClientMock->expects($this->atLeastOnce())->method('request')->willReturn($httpResponseMock); $httpResponseMock->expects($this->any())->method('getBody')->willReturn($responseBody); $this->assertEquals($expectedCurrencyRateList, $this->model->fetchRates()); $messages = $this->model->getMessages(); $this->assertNotEmpty($messages); $this->assertTrue(is_array($messages)); $this->assertEquals($message, (string) $messages[0]); }
/** * Check base currency is available in installed currencies * * @return $this * @throws \Magento\Framework\Exception\LocalizedException */ public function afterSave() { $value = $this->getValue(); if (!in_array($value, $this->_getInstalledCurrencies())) { throw new \Magento\Framework\Exception\LocalizedException(__('Sorry, we haven\'t installed the base currency you selected.')); } $this->currencyFactory->create()->saveRates([$value => [$value => 1]]); return $this; }
/** * @param \Magento\Backend\Block\Context $context * @param \Magento\Framework\StoreManagerInterface $storeManager * @param \Magento\Directory\Model\Currency\DefaultLocator $currencyLocator * @param \Magento\Directory\Model\CurrencyFactory $currencyFactory * @param \Magento\Framework\Locale\CurrencyInterface $localeCurrency * @param array $data */ public function __construct(\Magento\Backend\Block\Context $context, \Magento\Framework\StoreManagerInterface $storeManager, \Magento\Directory\Model\Currency\DefaultLocator $currencyLocator, \Magento\Directory\Model\CurrencyFactory $currencyFactory, \Magento\Framework\Locale\CurrencyInterface $localeCurrency, array $data = array()) { parent::__construct($context, $data); $this->_storeManager = $storeManager; $this->_currencyLocator = $currencyLocator; $this->_localeCurrency = $localeCurrency; $defaultBaseCurrencyCode = $this->_scopeConfig->getValue(\Magento\Directory\Model\Currency::XML_PATH_CURRENCY_BASE, 'default'); $this->_defaultBaseCurrency = $currencyFactory->create()->load($defaultBaseCurrencyCode); }
/** * {@inheritdoc} */ public function getCurrency($scope = null, $currency = null) { if ($currency instanceof Currency) { $currentCurrency = $currency; } elseif (is_string($currency)) { $currency = $this->currencyFactory->create()->load($currency); $baseCurrency = $this->getStore($scope)->getBaseCurrency(); $currentCurrency = $baseCurrency->getRate($currency) ? $currency : $baseCurrency; } else { $currentCurrency = $this->getStore($scope)->getCurrentCurrency(); } return $currentCurrency; }
public function testConvertWithCurrencyString() { $amount = 5.6; $currency = 'ru'; $convertedAmount = 9.300000000000001; $currentCurrency = $this->getCurrentCurrencyMock(); $currentCurrency->expects($this->once())->method('load')->with($currency)->will($this->returnSelf()); $this->currencyFactory->expects($this->once())->method('create')->will($this->returnValue($currentCurrency)); $baseCurrency = $this->getBaseCurrencyMock($amount, $convertedAmount, $currentCurrency); $baseCurrency->expects($this->once())->method('getRate')->with($currentCurrency)->will($this->returnValue(1.2)); $store = $this->getStoreMock($baseCurrency); $this->assertEquals($convertedAmount, $this->priceCurrency->convert($amount, $store, $currency)); }
/** * Modify precision for JPY * * @param \Magento\Framework\Locale\Format $subject Currency Format Obj * @param \Closure $proceed Closure * @param null|string $localeCode Locale Code * @param null|string $currencyCode Currency Code * * @return mixed */ public function aroundGetPriceFormat(Format $subject, \Closure $proceed, $localeCode = null, $currencyCode = null) { if ($currencyCode) { $currency = $this->_currencyFactory->create()->load($currencyCode); } else { $currency = $this->_scopeResolver->getScope()->getCurrentCurrency(); } $result = $proceed($localeCode, $currencyCode); if ($currency->getCode() == 'JPY') { $result['precision'] = '0'; $result['requiredPrecision'] = '0'; } return $result; }
/** * Retrieve avilable currency codes * * @return string[] */ public function getAvailableCurrencies() { $dirtyCodes = $this->getStore()->getAvailableCurrencyCodes(); $codes = []; if (is_array($dirtyCodes) && count($dirtyCodes)) { $rates = $this->_currencyFactory->create()->getCurrencyRates($this->_storeManager->getStore()->getBaseCurrency(), $dirtyCodes); foreach ($dirtyCodes as $code) { if (isset($rates[$code]) || $code == $this->_storeManager->getStore()->getBaseCurrencyCode()) { $codes[] = $code; } } } return $codes; }
public function testScheduledUpdateCurrencyRates() { $this->scopeConfig->expects($this->at(0))->method('getValue')->with(Observer::IMPORT_ENABLE, ScopeInterface::SCOPE_STORE)->will($this->returnValue(1)); $this->scopeConfig->expects($this->at(1))->method('getValue')->with(Observer::CRON_STRING_PATH, ScopeInterface::SCOPE_STORE)->will($this->returnValue('cron-path')); $this->scopeConfig->expects($this->at(2))->method('getValue')->with(Observer::IMPORT_SERVICE, ScopeInterface::SCOPE_STORE)->will($this->returnValue('import-service')); $importInterfaceMock = $this->getMockBuilder('Magento\\Directory\\Model\\Currency\\Import\\Webservicex')->disableOriginalConstructor()->setMethods(['fetchRates', 'getMessages'])->getMock(); $importInterfaceMock->expects($this->once())->method('fetchRates')->will($this->returnValue([])); $importInterfaceMock->expects($this->once())->method('getMessages')->will($this->returnValue([])); $this->importFactory->expects($this->once())->method('create')->with('import-service')->will($this->returnValue($importInterfaceMock)); $currencyMock = $this->getMockBuilder('Magento\\Directory\\Model\\Currency')->disableOriginalConstructor()->setMethods(['saveRates', '__wakeup', '__sleep'])->getMock(); $currencyMock->expects($this->once())->method('saveRates')->will($this->returnValue(null)); $this->currencyFactory->expects($this->once())->method('create')->will($this->returnValue($currencyMock)); $this->observer->scheduledUpdateCurrencyRates(null); }
/** * @param mixed $schedule * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function scheduledUpdateCurrencyRates($schedule) { $importWarnings = []; if (!$this->_scopeConfig->getValue(self::IMPORT_ENABLE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE) || !$this->_scopeConfig->getValue(self::CRON_STRING_PATH, \Magento\Store\Model\ScopeInterface::SCOPE_STORE)) { return; } $errors = []; $rates = []; $service = $this->_scopeConfig->getValue(self::IMPORT_SERVICE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE); if ($service) { try { $importModel = $this->_importFactory->create($service); $rates = $importModel->fetchRates(); $errors = $importModel->getMessages(); } catch (\Exception $e) { $importWarnings[] = __('FATAL ERROR:') . ' ' . __('We can\'t initialize the import model.'); } } else { $importWarnings[] = __('FATAL ERROR:') . ' ' . __('Please specify the correct Import Service.'); } if (sizeof($errors) > 0) { foreach ($errors as $error) { $importWarnings[] = __('WARNING:') . ' ' . $error; } } if (sizeof($importWarnings) == 0) { $this->_currencyFactory->create()->saveRates($rates); } else { $this->inlineTranslation->suspend(); $this->_transportBuilder->setTemplateIdentifier($this->_scopeConfig->getValue(self::XML_PATH_ERROR_TEMPLATE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE))->setTemplateOptions(['area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE, 'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID])->setTemplateVars(['warnings' => join("\n", $importWarnings)])->setFrom($this->_scopeConfig->getValue(self::XML_PATH_ERROR_IDENTITY, \Magento\Store\Model\ScopeInterface::SCOPE_STORE))->addTo($this->_scopeConfig->getValue(self::XML_PATH_ERROR_RECIPIENT, \Magento\Store\Model\ScopeInterface::SCOPE_STORE)); $transport = $this->_transportBuilder->getTransport(); $transport->sendMessage(); $this->inlineTranslation->resume(); } }
/** * Prepare website current dates table * * @return \Magento\Catalog\Model\Indexer\Product\Price\AbstractAction */ protected function _prepareWebsiteDateTable() { $baseCurrency = $this->_config->getValue(\Magento\Directory\Model\Currency::XML_PATH_CURRENCY_BASE); $select = $this->_connection->select()->from(['cw' => $this->_defaultIndexerResource->getTable('store_website')], ['website_id'])->join(['csg' => $this->_defaultIndexerResource->getTable('store_group')], 'cw.default_group_id = csg.group_id', ['store_id' => 'default_store_id'])->where('cw.website_id != 0'); $data = []; foreach ($this->_connection->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[] = ['website_id' => $website->getId(), 'website_date' => $this->_dateTime->formatDate($timestamp, false), 'rate' => $rate]; } } $table = $this->_defaultIndexerResource->getTable('catalog_product_index_website'); $this->_emptyTable($table); if ($data) { foreach ($data as $row) { $this->_connection->insertOnDuplicate($table, $row, array_keys($row)); } } return $this; }
/** * After Save Attribute manipulation * * @param \Magento\Catalog\Model\Product $object * @return $this */ public function afterSave($object) { $value = $object->getData($this->getAttribute()->getAttributeCode()); /** * Orig value is only for existing objects */ $oridData = $object->getOrigData(); $origValueExist = $oridData && array_key_exists($this->getAttribute()->getAttributeCode(), $oridData); if ($object->getStoreId() != 0 || !$value || $origValueExist) { return $this; } if ($this->getAttribute()->getIsGlobal() == \Magento\Catalog\Model\Resource\Eav\Attribute::SCOPE_WEBSITE) { $baseCurrency = $this->_config->getValue(\Magento\Directory\Model\Currency::XML_PATH_CURRENCY_BASE, 'default'); $storeIds = $object->getStoreIds(); if (is_array($storeIds)) { foreach ($storeIds as $storeId) { $storeCurrency = $this->_storeManager->getStore($storeId)->getBaseCurrencyCode(); if ($storeCurrency == $baseCurrency) { continue; } $rate = $this->_currencyFactory->create()->load($baseCurrency)->getRate($storeCurrency); if (!$rate) { $rate = 1; } $newValue = $value * $rate; $object->addAttributeUpdate($this->getAttribute()->getAttributeCode(), $newValue, $storeId); } } } return $this; }
/** * Save option value price data * * @param \Magento\Framework\Model\AbstractModel $object * @return void */ protected function _saveValuePrices(\Magento\Framework\Model\AbstractModel $object) { $priceTable = $this->getTable('catalog_product_option_type_price'); $price = (double) sprintf('%F', $object->getPrice()); $priceType = $object->getPriceType(); if (!$object->getData('scope', 'price')) { //save for store_id = 0 $select = $this->_getReadAdapter()->select()->from($priceTable, 'option_type_id')->where('option_type_id = ?', (int) $object->getId())->where('store_id = ?', \Magento\Store\Model\Store::DEFAULT_STORE_ID); $optionTypeId = $this->_getReadAdapter()->fetchOne($select); if ($optionTypeId) { if ($object->getStoreId() == '0') { $bind = array('price' => $price, 'price_type' => $priceType); $where = array('option_type_id = ?' => $optionTypeId, 'store_id = ?' => \Magento\Store\Model\Store::DEFAULT_STORE_ID); $this->_getWriteAdapter()->update($priceTable, $bind, $where); } } else { $bind = array('option_type_id' => (int) $object->getId(), 'store_id' => \Magento\Store\Model\Store::DEFAULT_STORE_ID, 'price' => $price, 'price_type' => $priceType); $this->_getWriteAdapter()->insert($priceTable, $bind); } } $scope = (int) $this->_config->getValue(\Magento\Store\Model\Store::XML_PATH_PRICE_SCOPE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE); if ($object->getStoreId() != '0' && $scope == \Magento\Store\Model\Store::PRICE_SCOPE_WEBSITE) { $baseCurrency = $this->_config->getValue(\Magento\Directory\Model\Currency::XML_PATH_CURRENCY_BASE, 'default'); $storeIds = $this->_storeManager->getStore($object->getStoreId())->getWebsite()->getStoreIds(); if (is_array($storeIds)) { foreach ($storeIds as $storeId) { if ($priceType == 'fixed') { $storeCurrency = $this->_storeManager->getStore($storeId)->getBaseCurrencyCode(); /** @var $currencyModel \Magento\Directory\Model\Currency */ $currencyModel = $this->_currencyFactory->create(); $currencyModel->load($baseCurrency); $rate = $currencyModel->getRate($storeCurrency); if (!$rate) { $rate = 1; } $newPrice = $price * $rate; } else { $newPrice = $price; } $select = $this->_getReadAdapter()->select()->from($priceTable, 'option_type_id')->where('option_type_id = ?', (int) $object->getId())->where('store_id = ?', (int) $storeId); $optionTypeId = $this->_getReadAdapter()->fetchOne($select); if ($optionTypeId) { $bind = array('price' => $newPrice, 'price_type' => $priceType); $where = array('option_type_id = ?' => (int) $optionTypeId, 'store_id = ?' => (int) $storeId); $this->_getWriteAdapter()->update($priceTable, $bind, $where); } else { $bind = array('option_type_id' => (int) $object->getId(), 'store_id' => (int) $storeId, 'price' => $newPrice, 'price_type' => $priceType); $this->_getWriteAdapter()->insert($priceTable, $bind); } } } } else { if ($scope == \Magento\Store\Model\Store::PRICE_SCOPE_WEBSITE && $object->getData('scope', 'price')) { $where = array('option_type_id = ?' => (int) $object->getId(), 'store_id = ?' => (int) $object->getStoreId()); $this->_getWriteAdapter()->delete($priceTable, $where); } } }
/** * Retrieve currencies array * Return array: code => currency name * Return empty array if only one currency * * @return array */ public function getCurrencies() { $currencies = $this->getData('currencies'); if (is_null($currencies)) { $currencies = []; $codes = $this->_storeManager->getStore()->getAvailableCurrencyCodes(true); if (is_array($codes) && count($codes) > 1) { $rates = $this->_currencyFactory->create()->getCurrencyRates($this->_storeManager->getStore()->getBaseCurrency(), $codes); foreach ($codes as $code) { if (isset($rates[$code])) { $currencies[$code] = $this->_locale->getTranslation($code, 'nametocurrency'); } } } $this->setData('currencies', $currencies); } return $currencies; }
/** * Save value prices * * @param \Magento\Framework\Model\AbstractModel $object * @return $this */ protected function _saveValuePrices(\Magento\Framework\Model\AbstractModel $object) { $priceTable = $this->getTable('catalog_product_option_price'); $readAdapter = $this->_getReadAdapter(); $writeAdapter = $this->_getWriteAdapter(); /* * Better to check param 'price' and 'price_type' for saving. * If there is not price skip saving price */ if ($object->getType() == \Magento\Catalog\Model\Product\Option::OPTION_TYPE_FIELD || $object->getType() == \Magento\Catalog\Model\Product\Option::OPTION_TYPE_AREA || $object->getType() == \Magento\Catalog\Model\Product\Option::OPTION_TYPE_FILE || $object->getType() == \Magento\Catalog\Model\Product\Option::OPTION_TYPE_DATE || $object->getType() == \Magento\Catalog\Model\Product\Option::OPTION_TYPE_DATE_TIME || $object->getType() == \Magento\Catalog\Model\Product\Option::OPTION_TYPE_TIME) { //save for store_id = 0 if (!$object->getData('scope', 'price')) { $statement = $readAdapter->select()->from($priceTable, 'option_id')->where('option_id = ?', $object->getId())->where('store_id = ?', \Magento\Store\Model\Store::DEFAULT_STORE_ID); $optionId = $readAdapter->fetchOne($statement); if ($optionId) { if ($object->getStoreId() == '0') { $data = $this->_prepareDataForTable(new \Magento\Framework\Object(array('price' => $object->getPrice(), 'price_type' => $object->getPriceType())), $priceTable); $writeAdapter->update($priceTable, $data, array('option_id = ?' => $object->getId(), 'store_id = ?' => \Magento\Store\Model\Store::DEFAULT_STORE_ID)); } } else { $data = $this->_prepareDataForTable(new \Magento\Framework\Object(array('option_id' => $object->getId(), 'store_id' => \Magento\Store\Model\Store::DEFAULT_STORE_ID, 'price' => $object->getPrice(), 'price_type' => $object->getPriceType())), $priceTable); $writeAdapter->insert($priceTable, $data); } } $scope = (int) $this->_config->getValue(\Magento\Store\Model\Store::XML_PATH_PRICE_SCOPE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE); if ($object->getStoreId() != '0' && $scope == \Magento\Store\Model\Store::PRICE_SCOPE_WEBSITE) { $baseCurrency = $this->_config->getValue(\Magento\Directory\Model\Currency::XML_PATH_CURRENCY_BASE, 'default'); $storeIds = $this->_storeManager->getStore($object->getStoreId())->getWebsite()->getStoreIds(); if (is_array($storeIds)) { foreach ($storeIds as $storeId) { if ($object->getPriceType() == 'fixed') { $storeCurrency = $this->_storeManager->getStore($storeId)->getBaseCurrencyCode(); $rate = $this->_currencyFactory->create()->load($baseCurrency)->getRate($storeCurrency); if (!$rate) { $rate = 1; } $newPrice = $object->getPrice() * $rate; } else { $newPrice = $object->getPrice(); } $statement = $readAdapter->select()->from($priceTable)->where('option_id = ?', $object->getId())->where('store_id = ?', $storeId); if ($readAdapter->fetchOne($statement)) { $data = $this->_prepareDataForTable(new \Magento\Framework\Object(array('price' => $newPrice, 'price_type' => $object->getPriceType())), $priceTable); $writeAdapter->update($priceTable, $data, array('option_id = ?' => $object->getId(), 'store_id = ?' => $storeId)); } else { $data = $this->_prepareDataForTable(new \Magento\Framework\Object(array('option_id' => $object->getId(), 'store_id' => $storeId, 'price' => $newPrice, 'price_type' => $object->getPriceType())), $priceTable); $writeAdapter->insert($priceTable, $data); } } } } elseif ($scope == \Magento\Store\Model\Store::PRICE_SCOPE_WEBSITE && $object->getData('scope', 'price')) { $writeAdapter->delete($priceTable, array('option_id = ?' => $object->getId(), 'store_id = ?' => $object->getStoreId())); } } return $this; }
/** * Retrieve currencies array * Return array: code => currency name * Return empty array if only one currency * * @return array */ public function getCurrencies() { $currencies = $this->getData('currencies'); if ($currencies === null) { $currencies = []; $codes = $this->_storeManager->getStore()->getAvailableCurrencyCodes(true); if (is_array($codes) && count($codes) > 1) { $rates = $this->_currencyFactory->create()->getCurrencyRates($this->_storeManager->getStore()->getBaseCurrency(), $codes); foreach ($codes as $code) { if (isset($rates[$code])) { $allCurrencies = (new CurrencyBundle())->get($this->localeResolver->getLocale())['Currencies']; $currencies[$code] = $allCurrencies[$code][1] ?: $code; } } } $this->setData('currencies', $currencies); } return $currencies; }
/** * Convert currency * * @param float $amount * @param string $from * @param string $to * @return float * @SuppressWarnings(PHPMD.ShortVariable) */ public function currencyConvert($amount, $from, $to = null) { if (empty($this->_currencyCache[$from])) { $this->_currencyCache[$from] = $this->_currencyFactory->create()->load($from); } if ($to === null) { $to = $this->_storeManager->getStore()->getCurrentCurrencyCode(); } $converted = $this->_currencyCache[$from]->convert($amount, $to); return $converted; }
/** * Prepare layout * * @return \Magento\Framework\View\Element\AbstractBlock */ protected function _prepareLayout() { $newRates = $this->_backendSession->getRates(); $this->_backendSession->unsetData('rates'); $currencyModel = $this->_dirCurrencyFactory->create(); $currencies = $currencyModel->getConfigAllowCurrencies(); $defaultCurrencies = $currencyModel->getConfigBaseCurrencies(); $oldCurrencies = $this->_prepareRates($currencyModel->getCurrencyRates($defaultCurrencies, $currencies)); foreach ($currencies as $currency) { foreach ($oldCurrencies as $key => $value) { if (!array_key_exists($currency, $oldCurrencies[$key])) { $oldCurrencies[$key][$currency] = ''; } } } foreach ($oldCurrencies as $key => $value) { ksort($oldCurrencies[$key]); } sort($currencies); $this->setAllowedCurrencies($currencies)->setDefaultCurrencies($defaultCurrencies)->setOldRates($oldCurrencies)->setNewRates($this->_prepareRates($newRates)); return parent::_prepareLayout(); }
/** * Functions returns array with price formatting info * * @param string $localeCode Locale code. * @param string $currencyCode Currency code. * @return array * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function getPriceFormat($localeCode = null, $currencyCode = null) { $localeCode = $localeCode ?: $this->_localeResolver->getLocale(); if ($currencyCode) { $currency = $this->currencyFactory->create()->load($currencyCode); } else { $currency = $this->_scopeResolver->getScope()->getCurrentCurrency(); } $localeData = (new DataBundle())->get($localeCode); $defaultSet = $localeData['NumberElements']['default'] ?: self::$defaultNumberSet; $format = $localeData['NumberElements'][$defaultSet]['patterns']['currencyFormat'] ?: ($localeData['NumberElements'][self::$defaultNumberSet]['patterns']['currencyFormat'] ?: explode(';', $localeData['NumberPatterns'][1])[0]); $decimalSymbol = $localeData['NumberElements'][$defaultSet]['symbols']['decimal'] ?: ($localeData['NumberElements'][self::$defaultNumberSet]['symbols']['decimal'] ?: $localeData['NumberElements'][0]); $groupSymbol = $localeData['NumberElements'][$defaultSet]['symbols']['group'] ?: ($localeData['NumberElements'][self::$defaultNumberSet]['symbols']['group'] ?: $localeData['NumberElements'][1]); $pos = strpos($format, ';'); if ($pos !== false) { $format = substr($format, 0, $pos); } $format = preg_replace("/[^0\\#\\.,]/", "", $format); $totalPrecision = 0; $decimalPoint = strpos($format, '.'); if ($decimalPoint !== false) { $totalPrecision = strlen($format) - (strrpos($format, '.') + 1); } else { $decimalPoint = strlen($format); } $requiredPrecision = $totalPrecision; $t = substr($format, $decimalPoint); $pos = strpos($t, '#'); if ($pos !== false) { $requiredPrecision = strlen($t) - $pos - $totalPrecision; } if (strrpos($format, ',') !== false) { $group = $decimalPoint - strrpos($format, ',') - 1; } else { $group = strrpos($format, '.'); } $integerRequired = strpos($format, '.') - strpos($format, '0'); $result = ['pattern' => $currency->getOutputFormat(), 'precision' => $totalPrecision, 'requiredPrecision' => $requiredPrecision, 'decimalSymbol' => $decimalSymbol, 'groupSymbol' => $groupSymbol, 'groupLength' => $group, 'integerRequired' => $integerRequired]; return $result; }
public function getBaseCurrencies() { $currency = $this->_currencyFactory->create(); return $currency->getConfigBaseCurrencies(); }
/** * Retrieve order website currency for working with base prices * * @return Currency */ public function getBaseCurrency() { if ($this->_baseCurrency === null) { $this->_baseCurrency = $this->_currencyFactory->create()->load($this->getBaseCurrencyCode()); } return $this->_baseCurrency; }
/** * Retrieve website base currency * * @return \Magento\Directory\Model\Currency */ public function getBaseCurrency() { $currency = $this->getData('base_currency'); if ($currency === null) { $currency = $this->_currencyFactory->create()->load($this->getBaseCurrencyCode()); $this->setData('base_currency', $currency); } return $currency; }
public function getBaseCurrencyRate($code) { $currencyModel = $this->dirCurrencyFactory->create(); $allowedCurrencies = $currencyModel->getConfigAllowCurrencies(); if (!in_array($code, $allowedCurrencies)) { return false; } $baseCurrencyCode = $this->storeManager->getStore()->getBaseCurrencyCode(); if (!$this->baseCurrencyRate) { $this->baseCurrencyRate = $currencyModel->load($code)->getAnyRate($baseCurrencyCode); } return $this->baseCurrencyRate > 0 ? $this->baseCurrencyRate : false; }
/** * Add data about search criteria to object state * * @param EntityAttribute $attribute * @param mixed $value * @return $this */ protected function _addSearchCriteria($attribute, $value) { $name = $attribute->getStoreLabel(); if (is_array($value)) { if (isset($value['from']) && isset($value['to'])) { if (!empty($value['from']) || !empty($value['to'])) { if (isset($value['currency'])) { /** @var $currencyModel Currency */ $currencyModel = $this->_currencyFactory->create()->load($value['currency']); $from = $currencyModel->format($value['from'], array(), false); $to = $currencyModel->format($value['to'], array(), false); } else { $currencyModel = null; } if (strlen($value['from']) > 0 && strlen($value['to']) > 0) { // - $value = sprintf('%s - %s', $currencyModel ? $from : $value['from'], $currencyModel ? $to : $value['to']); } elseif (strlen($value['from']) > 0) { // and more $value = __('%1 and greater', $currencyModel ? $from : $value['from']); } elseif (strlen($value['to']) > 0) { // to $value = __('up to %1', $currencyModel ? $to : $value['to']); } } else { return $this; } } } if (($attribute->getFrontendInput() == 'select' || $attribute->getFrontendInput() == 'multiselect') && is_array($value)) { foreach ($value as $key => $val) { $value[$key] = $attribute->getSource()->getOptionText($val); if (is_array($value[$key])) { $value[$key] = $value[$key]['label']; } } $value = implode(', ', $value); } elseif ($attribute->getFrontendInput() == 'select' || $attribute->getFrontendInput() == 'multiselect') { $value = $attribute->getSource()->getOptionText($value); if (is_array($value)) { $value = $value['label']; } } elseif ($attribute->getFrontendInput() == 'boolean') { $value = $value == 1 ? __('Yes') : __('No'); } $this->_searchCriterias[] = array('name' => $name, 'value' => $value); return $this; }
/** * @return \Magento\Directory\Model\Currency */ protected function _createCurrency() { return $this->_currencyFactory->create(); }
/** * Retrieve store current currency * * @return Currency */ public function getCurrentCurrency() { $currency = $this->getData('current_currency'); if ($currency === null) { $currency = $this->currencyFactory->create()->load($this->getCurrentCurrencyCode()); $baseCurrency = $this->getBaseCurrency(); if (!$baseCurrency->getRate($currency)) { $currency = $baseCurrency; $this->setCurrentCurrencyCode($baseCurrency->getCode()); } $this->setData('current_currency', $currency); } return $currency; }