示例#1
0
 /**
  * Filter value
  *
  * @param float $value
  * @return string
  */
 public function filter($value)
 {
     $value = $this->_localeFormat->getNumber($value);
     $value = $this->priceCurrency->round($this->_rate * $value);
     $value = sprintf("%f", $value);
     return $this->_currency->toCurrency($value);
 }
示例#2
0
 /**
  * Js configuration array for autocomplete
  *
  * @return array
  */
 public function getJsConfig()
 {
     $config = ["*" => ['Magento_Ui/js/core/app' => ['components' => ['autocompleteInjection' => ['component' => 'Mirasvit_SearchAutocomplete/js/injection', 'config' => []], 'autocomplete' => ['component' => 'Mirasvit_SearchAutocomplete/js/autocomplete', 'provider' => 'autocompleteProvider', 'config' => ['query' => $this->searchHelper->getEscapedQueryText(), 'priceFormat' => $this->localeFormat->getPriceFormat()]], 'autocompleteProvider' => ['component' => 'Mirasvit_SearchAutocomplete/js/provider', 'config' => ['url' => $this->getUrl('searchautocomplete/ajax/suggest', ['_secure' => $this->getRequest()->isSecure()]), 'delay' => $this->config->getDelay(), 'minSearchLength' => $this->config->getMinChars()]], 'autocompleteNavigation' => ['component' => 'Mirasvit_SearchAutocomplete/js/navigation', 'autocomplete' => 'autocomplete']]]]];
     if ($this->config->isShowPopularSearches()) {
         $config['*']['Magento_Ui/js/core/app']['components']['autocompletePopular'] = ['component' => 'Mirasvit_SearchAutocomplete/js/popular', 'autocomplete' => 'autocomplete', 'provider' => 'autocompleteProvider', 'config' => ['enabled' => $this->config->isShowPopularSearches(), 'queries' => $this->config->getPopularSearches()]];
     } else {
         $config['*']['Magento_Ui/js/core/app']['components']['autocompleteRecent'] = ['component' => 'Mirasvit_SearchAutocomplete/js/recent', 'autocomplete' => 'autocomplete', 'provider' => 'autocompleteProvider', 'config' => ['limit' => 5]];
     }
     return $config;
 }
 /**
  * Append virtual rule and sorting product data.
  *
  * @param CategoryDataProvider $dataProvider Data provider.
  * @param \Closure             $proceed      Original method.
  *
  * @return array
  */
 public function aroundGetData(CategoryDataProvider $dataProvider, \Closure $proceed)
 {
     $data = $proceed();
     $currentCategory = $dataProvider->getCurrentCategory();
     if ($currentCategory->getId() === null || $currentCategory->getLevel() < 2) {
         $data[$currentCategory->getId()]['use_default']['is_virtual_category'] = true;
     }
     $data[$currentCategory->getId()]['sorted_products'] = $this->getProductSavedPositions($currentCategory);
     $data[$currentCategory->getId()]['product_sorter_load_url'] = $this->getProductSorterLoadUrl($currentCategory);
     $data[$currentCategory->getId()]['price_format'] = $this->localeFormat->getPriceFormat();
     return $data;
 }
 protected function setUp()
 {
     $this->objectManagerHelper = new ObjectManagerHelper($this);
     $this->mathDivision = $this->getMock('\\Magento\\Framework\\Math\\Division', ['getExactDivision'], [], '', false);
     $this->localeFormat = $this->getMockForAbstractClass('\\Magento\\Framework\\Locale\\FormatInterface', ['getNumber']);
     $this->localeFormat->expects($this->any())->method('getNumber')->willReturn($this->qty);
     $this->object = $this->objectManagerHelper->getObject('Magento\\Framework\\DataObject');
     $this->objectFactory = $this->getMock('\\Magento\\Framework\\DataObject\\Factory', ['create'], [], '', false);
     $this->objectFactory->expects($this->any())->method('create')->willReturn($this->object);
     $this->product = $this->getMock('Magento\\Catalog\\Model\\Product', ['load', 'isComposite', '__wakeup', 'isSaleable'], [], '', false);
     $this->productFactory = $this->getMock('Magento\\Catalog\\Model\\ProductFactory', ['create'], [], '', false);
     $this->productFactory->expects($this->any())->method('create')->willReturn($this->product);
     $this->stockStateProvider = $this->objectManagerHelper->getObject('Magento\\CatalogInventory\\Model\\StockStateProvider', ['mathDivision' => $this->mathDivision, 'localeFormat' => $this->localeFormat, 'objectFactory' => $this->objectFactory, 'productFactory' => $this->productFactory, 'qtyCheckApplicable' => $this->qtyCheckApplicable]);
 }
示例#5
0
 /**
  * Filter value
  *
  * @param float $value
  * @return string
  */
 public function filter($value)
 {
     $value = $this->_localeFormat->getNumber($value);
     $value = $this->_storeManager->getStore()->roundPrice($this->_rate * $value);
     $value = sprintf("%f", $value);
     return $this->_currency->toCurrency($value);
 }
 /**
  * {@inheritdoc}
  */
 public function getConfig()
 {
     $quoteId = $this->checkoutSession->getQuote()->getId();
     $output['formKey'] = $this->formKey->getFormKey();
     $output['customerData'] = $this->getCustomerData();
     $output['quoteData'] = $this->getQuoteData();
     $output['quoteItemData'] = $this->getQuoteItemData();
     $output['isCustomerLoggedIn'] = $this->isCustomerLoggedIn();
     $output['selectedShippingMethod'] = $this->getSelectedShippingMethod();
     $output['storeCode'] = $this->getStoreCode();
     $output['isGuestCheckoutAllowed'] = $this->isGuestCheckoutAllowed();
     $output['isCustomerLoginRequired'] = $this->isCustomerLoginRequired();
     $output['registerUrl'] = $this->getRegisterUrl();
     $output['checkoutUrl'] = $this->getCheckoutUrl();
     $output['pageNotFoundUrl'] = $this->pageNotFoundUrl();
     $output['forgotPasswordUrl'] = $this->getForgotPasswordUrl();
     $output['staticBaseUrl'] = $this->getStaticBaseUrl();
     $output['priceFormat'] = $this->localeFormat->getPriceFormat(null, $this->checkoutSession->getQuote()->getQuoteCurrencyCode());
     $output['basePriceFormat'] = $this->localeFormat->getPriceFormat(null, $this->checkoutSession->getQuote()->getBaseCurrencyCode());
     $output['postCodes'] = $this->postCodesConfig->getPostCodes();
     $output['imageData'] = $this->imageProvider->getImages($quoteId);
     $output['defaultCountryId'] = $this->directoryHelper->getDefaultCountry();
     $output['totalsData'] = $this->getTotalsData();
     $output['shippingPolicy'] = ['isEnabled' => $this->scopeConfig->isSetFlag('shipping/shipping_policy/enable_shipping_policy', ScopeInterface::SCOPE_STORE), 'shippingPolicyContent' => nl2br($this->scopeConfig->getValue('shipping/shipping_policy/shipping_policy_content', ScopeInterface::SCOPE_STORE))];
     $output['activeCarriers'] = $this->getActiveCarriers();
     $output['originCountryCode'] = $this->getOriginCountryCode();
     $output['paymentMethods'] = $this->getPaymentMethods();
     $output['autocomplete'] = $this->isAutocompleteEnabled();
     return $output;
 }
示例#7
0
 /**
  * Get JSON encoded configuration array which can be used for JS dynamic
  * price calculation depending on product options
  *
  * @return string
  */
 public function getJsonConfig()
 {
     $config = array();
     if (!$this->hasOptions()) {
         return $this->_jsonEncoder->encode($config);
     }
     $customerId = $this->getCustomerId();
     /* @var $product \Magento\Catalog\Model\Product */
     $product = $this->getProduct();
     $defaultTax = $this->taxCalculationService->getDefaultCalculatedRate($product->getTaxClassId(), $customerId);
     $currentTax = $this->taxCalculationService->getCalculatedRate($product->getTaxClassId(), $customerId);
     $tierPrices = array();
     $tierPricesList = $product->getPriceInfo()->getPrice('tier_price')->getTierPriceList();
     foreach ($tierPricesList as $tierPrice) {
         $tierPrices[] = $this->_coreData->currency($tierPrice['price']->getValue(), false, false);
     }
     $config = array('productId' => $product->getId(), 'priceFormat' => $this->_localeFormat->getPriceFormat(), 'includeTax' => $this->_taxData->priceIncludesTax() ? 'true' : 'false', 'showIncludeTax' => $this->_taxData->displayPriceIncludingTax(), 'showBothPrices' => $this->_taxData->displayBothPrices(), 'productPrice' => $this->_coreData->currency($product->getPriceInfo()->getPrice('final_price')->getValue(), false, false), 'productOldPrice' => $this->_coreData->currency($product->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue(), false, false), 'inclTaxPrice' => $this->_coreData->currency($product->getPriceInfo()->getPrice('final_price')->getAmount()->getValue(), false, false), 'exclTaxPrice' => $this->_coreData->currency($product->getPriceInfo()->getPrice('final_price')->getAmount()->getBaseAmount(), false, false), 'defaultTax' => $defaultTax, 'currentTax' => $currentTax, 'idSuffix' => '_clone', 'oldPlusDisposition' => 0, 'plusDisposition' => 0, 'plusDispositionTax' => 0, 'oldMinusDisposition' => 0, 'minusDisposition' => 0, 'tierPrices' => $tierPrices);
     $responseObject = new \Magento\Framework\Object();
     $this->_eventManager->dispatch('catalog_product_view_config', array('response_object' => $responseObject));
     if (is_array($responseObject->getAdditionalOptions())) {
         foreach ($responseObject->getAdditionalOptions() as $option => $value) {
             $config[$option] = $value;
         }
     }
     return $this->_jsonEncoder->encode($config);
 }
 /**
  * @param string|float|int|null $qty
  * @return float|null
  */
 protected function getNumber($qty)
 {
     if (!is_numeric($qty)) {
         $qty = $this->localeFormat->getNumber($qty);
         return $qty;
     }
     return $qty;
 }
示例#9
0
 /**
  * Get formed config data from calculated options data
  *
  * @param Product $product
  * @param array $options
  * @return array
  */
 private function getConfigData(Product $product, array $options)
 {
     $isFixedPrice = $this->getProduct()->getPriceType() == \Magento\Bundle\Model\Product\Price::PRICE_TYPE_FIXED;
     $productAmount = $product->getPriceInfo()->getPrice(\Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE)->getPriceWithoutOption();
     $baseProductAmount = $product->getPriceInfo()->getPrice(\Magento\Catalog\Pricing\Price\RegularPrice::PRICE_CODE)->getAmount();
     $config = ['options' => $options, 'selected' => $this->selectedOptions, 'bundleId' => $product->getId(), 'priceFormat' => $this->localeFormat->getPriceFormat(), 'prices' => ['oldPrice' => ['amount' => $isFixedPrice ? $baseProductAmount->getValue() : 0], 'basePrice' => ['amount' => $isFixedPrice ? $productAmount->getBaseAmount() : 0], 'finalPrice' => ['amount' => $isFixedPrice ? $productAmount->getValue() : 0]], 'priceType' => $product->getPriceType(), 'isFixedPrice' => $isFixedPrice];
     return $config;
 }
示例#10
0
 /**
  * Get prices javascript format json
  *
  * @param  null|int|string|Store $store
  * @return string
  */
 public function getPriceFormat($store = null)
 {
     $this->_localeResolver->emulate($store);
     $priceFormat = $this->_localeFormat->getPriceFormat();
     $this->_localeResolver->revert();
     if ($store) {
         $priceFormat['pattern'] = $this->_storeManager->getStore($store)->getCurrentCurrency()->getOutputFormat();
     }
     return $this->jsonHelper->jsonEncode($priceFormat);
 }
示例#11
0
 /**
  * Retrieve Field Format for slider display
  *
  * @return array
  */
 protected function getFieldFormat()
 {
     $format = $this->localeFormat->getPriceFormat();
     $attribute = $this->getFilter()->getAttributeModel();
     $format['pattern'] = (string) $attribute->getDisplayPattern();
     $format['precision'] = (int) $attribute->getDisplayPrecision();
     $format['requiredPrecision'] = (int) $attribute->getDisplayPrecision();
     $format['integerRequired'] = (int) $attribute->getDisplayPrecision() > 0;
     return $format;
 }
示例#12
0
 /**
  * @param string $entityType
  * @param string $value
  * @param AbstractAttribute $attribute
  * @return string
  * @throws \Exception
  */
 protected function prepareValue($entityType, $value, AbstractAttribute $attribute)
 {
     $metadata = $this->metadataPool->getMetadata($entityType);
     $type = $attribute->getBackendType();
     if (($type == 'int' || $type == 'decimal' || $type == 'datetime') && $value === '') {
         $value = null;
     } elseif ($type == 'decimal') {
         $value = $this->localeFormat->getNumber($value);
     }
     $describe = $metadata->getEntityConnection()->describeTable($attribute->getBackendTable());
     return $metadata->getEntityConnection()->prepareColumnValue($describe['value'], $value);
 }
示例#13
0
 /**
  * @param float $price
  * @param array $options
  * @return string
  */
 public function formatTxt($price, $options = [])
 {
     if (!is_numeric($price)) {
         $price = $this->_localeFormat->getNumber($price);
     }
     /**
      * Fix problem with 12 000 000, 1 200 000
      *
      * %f - the argument is treated as a float, and presented as a floating-point number (locale aware).
      * %F - the argument is treated as a float, and presented as a floating-point number (non-locale aware).
      */
     $price = sprintf("%F", $price);
     return $this->_localeCurrency->getCurrency($this->getCode())->toCurrency($price, $options);
 }
示例#14
0
 public function testGetBuyRequestOptionByCode()
 {
     $optionCode = "info_buyRequest";
     $buyRequestQuantity = 23;
     $optionMock = $this->getMockBuilder('Magento\\Quote\\Model\\Quote\\Item\\Option')->setMethods(['setItem', 'getCode', '__wakeup', 'getValue'])->disableOriginalConstructor()->getMock();
     $optionMock->expects($this->once())->method('setItem')->with($this->model)->will($this->returnValue($optionMock));
     $optionMock->expects($this->exactly(3))->method('getCode')->will($this->returnValue($optionCode));
     $optionMock->expects($this->once())->method('getValue')->will($this->returnValue(serialize(['qty' => $buyRequestQuantity])));
     $this->model->addOption($optionMock);
     $quantity = 12;
     $this->localeFormat->expects($this->at(0))->method('getNumber')->with($quantity)->will($this->returnValue($quantity));
     $this->model->setQty($quantity);
     $this->assertEquals($quantity, $this->model->getQty());
     $buyRequest = $this->model->getBuyRequest();
     $this->assertEquals($buyRequestQuantity, $buyRequest->getOriginalQty());
     $this->assertEquals($quantity, $buyRequest->getQty());
 }
 /**
  * {@inheritdoc}
  */
 public function getConfig()
 {
     $configuration = [];
     $configuration['giftMessage'] = [];
     $orderLevelGiftMessageConfiguration = (bool) $this->scopeConfiguration->getValue(GiftMessageHelper::XPATH_CONFIG_GIFT_MESSAGE_ALLOW_ORDER, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
     $itemLevelGiftMessageConfiguration = (bool) $this->scopeConfiguration->getValue(GiftMessageHelper::XPATH_CONFIG_GIFT_MESSAGE_ALLOW_ITEMS, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
     if ($orderLevelGiftMessageConfiguration) {
         $orderMessages = $this->getOrderLevelGiftMessages();
         $configuration['isOrderLevelGiftOptionsEnabled'] = (bool) $this->isQuoteVirtual() ? false : true;
         $configuration['giftMessage']['orderLevel'] = $orderMessages === null ? true : $orderMessages->getData();
     }
     $itemMessages = $this->getItemLevelGiftMessages();
     $configuration['isItemLevelGiftOptionsEnabled'] = $itemLevelGiftMessageConfiguration;
     $configuration['giftMessage']['itemLevel'] = $itemMessages === null ? true : $itemMessages;
     $configuration['priceFormat'] = $this->localeFormat->getPriceFormat(null, $this->checkoutSession->getQuote()->getQuoteCurrencyCode());
     $configuration['storeCode'] = $this->getStoreCode();
     $configuration['isCustomerLoggedIn'] = $this->isCustomerLoggedIn();
     $configuration['formKey'] = $this->formKey->getFormKey();
     $store = $this->storeManager->getStore();
     $configuration['baseUrl'] = $store->isFrontUrlSecure() ? $store->getBaseUrl(UrlInterface::URL_TYPE_LINK, true) : $store->getBaseUrl(UrlInterface::URL_TYPE_LINK, false);
     return $configuration;
 }
示例#16
0
 /**
  * Load array
  *
  * @param array $arr
  * @return $this
  */
 public function loadArray($arr)
 {
     $this->setAttribute(isset($arr['attribute']) ? $arr['attribute'] : false);
     $attribute = $this->getAttributeObject();
     $isContainsOperator = !empty($arr['operator']) && in_array($arr['operator'], array('{}', '!{}'));
     if ($attribute && $attribute->getBackendType() == 'decimal' && !$isContainsOperator) {
         if (isset($arr['value'])) {
             if (!empty($arr['operator']) && in_array($arr['operator'], array('!()', '()')) && false !== strpos($arr['value'], ',')) {
                 $tmp = array();
                 foreach (explode(',', $arr['value']) as $value) {
                     $tmp[] = $this->_localeFormat->getNumber($value);
                 }
                 $arr['value'] = implode(',', $tmp);
             } else {
                 $arr['value'] = $this->_localeFormat->getNumber($arr['value']);
             }
         } else {
             $arr['value'] = false;
         }
         $arr['is_value_parsed'] = isset($arr['is_value_parsed']) ? $this->_localeFormat->getNumber($arr['is_value_parsed']) : false;
     }
     return parent::loadArray($arr);
 }
示例#17
0
 /**
  * Get JSON encoded configuration array which can be used for JS dynamic
  * price calculation depending on product options
  *
  * @return string
  */
 public function getJsonConfig()
 {
     /* @var $product \Magento\Catalog\Model\Product */
     $product = $this->getProduct();
     if (!$this->hasOptions()) {
         $config = ['productId' => $product->getId(), 'priceFormat' => $this->_localeFormat->getPriceFormat()];
         return $this->_jsonEncoder->encode($config);
     }
     $tierPrices = [];
     $tierPricesList = $product->getPriceInfo()->getPrice('tier_price')->getTierPriceList();
     foreach ($tierPricesList as $tierPrice) {
         $tierPrices[] = $this->priceCurrency->convert($tierPrice['price']->getValue());
     }
     $config = ['productId' => $product->getId(), 'priceFormat' => $this->_localeFormat->getPriceFormat(), 'prices' => ['oldPrice' => ['amount' => $this->priceCurrency->convert($product->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue()), 'adjustments' => []], 'basePrice' => ['amount' => $this->priceCurrency->convert($product->getPriceInfo()->getPrice('final_price')->getAmount()->getBaseAmount()), 'adjustments' => []], 'finalPrice' => ['amount' => $this->priceCurrency->convert($product->getPriceInfo()->getPrice('final_price')->getAmount()->getValue()), 'adjustments' => []]], 'idSuffix' => '_clone', 'tierPrices' => $tierPrices];
     $responseObject = new \Magento\Framework\DataObject();
     $this->_eventManager->dispatch('catalog_product_view_config', ['response_object' => $responseObject]);
     if (is_array($responseObject->getAdditionalOptions())) {
         foreach ($responseObject->getAdditionalOptions() as $option => $value) {
             $config[$option] = $value;
         }
     }
     return $this->_jsonEncoder->encode($config);
 }
示例#18
0
 /**
  * {@inheritdoc}
  */
 public function getConfig()
 {
     $quoteId = $this->checkoutSession->getQuote()->getId();
     return ['formKey' => $this->formKey->getFormKey(), 'customerData' => $this->getCustomerData(), 'quoteData' => $this->getQuoteData(), 'quoteItemData' => $this->getQuoteItemData(), 'isCustomerLoggedIn' => $this->isCustomerLoggedIn(), 'selectedShippingMethod' => $this->getSelectedShippingMethod(), 'storeCode' => $this->getStoreCode(), 'isGuestCheckoutAllowed' => $this->isGuestCheckoutAllowed(), 'isCustomerLoginRequired' => $this->isCustomerLoginRequired(), 'registerUrl' => $this->getRegisterUrl(), 'customerAddressCount' => $this->getCustomerAddressCount(), 'forgotPasswordUrl' => $this->getForgotPasswordUrl(), 'staticBaseUrl' => $this->getStaticBaseUrl(), 'priceFormat' => $this->localeFormat->getPriceFormat(null, $this->checkoutSession->getQuote()->getQuoteCurrencyCode()), 'basePriceFormat' => $this->localeFormat->getPriceFormat(null, $this->currencyManager->getDefaultCurrency()), 'postCodes' => $this->postCodesConfig->getPostCodes(), 'imageData' => $this->imageProvider->getImages($quoteId), 'countryData' => $this->getCountryData(), 'totalsData' => $this->getTotalsData(), 'shippingRates' => $this->getDefaultShippingRates(), 'shippingPolicy' => ['isEnabled' => $this->scopeConfig->isSetFlag('shipping/shipping_policy/enable_shipping_policy', ScopeInterface::SCOPE_STORE), 'shippingPolicyContent' => nl2br($this->scopeConfig->getValue('shipping/shipping_policy/shipping_policy_content', ScopeInterface::SCOPE_STORE))], 'activeCarriers' => $this->getActiveCarriers(), 'originCountryCode' => $this->getOriginCountryCode(), 'paymentMethods' => $this->getPaymentMethods()];
 }
示例#19
0
文件: Item.php 项目: uibar/lavinia2
 /**
  * Prepare quantity
  *
  * @param float|int $qty
  * @return int|float
  */
 protected function _prepareQty($qty)
 {
     $qty = $this->_localeFormat->getNumber($qty);
     $qty = $qty > 0 ? $qty : 1;
     return $qty;
 }
示例#20
0
 /**
  * Prepare value for save
  *
  * @param mixed $value
  * @param AbstractAttribute $attribute
  * @return mixed
  */
 protected function _prepareValueForSave($value, AbstractAttribute $attribute)
 {
     $type = $attribute->getBackendType();
     if (($type == 'int' || $type == 'decimal' || $type == 'datetime') && $value === '') {
         $value = null;
     } elseif ($type == 'decimal') {
         $value = $this->_localeFormat->getNumber($value);
     }
     $backendTable = $attribute->getBackendTable();
     if (!isset(self::$_attributeBackendTables[$backendTable])) {
         self::$_attributeBackendTables[$backendTable] = $this->_getReadAdapter()->describeTable($backendTable);
     }
     $describe = self::$_attributeBackendTables[$backendTable];
     return $this->_getReadAdapter()->prepareColumnValue($describe['value'], $value);
 }
示例#21
0
 /**
  * {@inheritdoc}
  */
 public function getConfig()
 {
     return ['formKey' => $this->formKey->getFormKey(), 'customerData' => $this->getCustomerData(), 'quoteData' => $this->getQuoteData(), 'quoteItemData' => $this->getQuoteItemData(), 'isCustomerLoggedIn' => $this->isCustomerLoggedIn(), 'selectedShippingMethod' => $this->getSelectedShippingMethod(), 'storeCode' => $this->getStoreCode(), 'isGuestCheckoutAllowed' => $this->isGuestCheckoutAllowed(), 'isCustomerLoginRequired' => $this->isCustomerLoginRequired(), 'registerUrl' => $this->getRegisterUrl(), 'customerAddressCount' => $this->getCustomerAddressCount(), 'forgotPasswordUrl' => $this->getForgotPasswordUrl(), 'staticBaseUrl' => $this->getStaticBaseUrl(), 'priceFormat' => $this->localeFormat->getPriceFormat(null, $this->checkoutSession->getQuote()->getQuoteCurrencyCode()), 'basePriceFormat' => $this->localeFormat->getPriceFormat(null, $this->currencyManager->getDefaultCurrency())];
 }
示例#22
0
 /**
  * Return formatted price
  *
  * @param float|int $price
  * @return float|int
  */
 protected function parseCustomPrice($price)
 {
     $price = $this->localeFormat->getNumber($price);
     return $price > 0 ? $price : 0;
 }
示例#23
0
 /**
  * Retrieve price format configuration.
  *
  * @return array
  */
 protected function getPriceFormat()
 {
     return $this->localeFormat->getPriceFormat();
 }
示例#24
0
 /**
  * Returns whether the value is greater than, or equal to, zero
  *
  * @param mixed $value
  * @return bool
  */
 protected function isPositiveOrZero($value)
 {
     $value = $this->localeFormat->getNumber($value);
     $isNegative = $value < 0;
     return !$isNegative;
 }
示例#25
0
文件: Bundle.php 项目: aiesh/magento2
 /**
  * Returns JSON encoded config to be used in JS scripts
  *
  * @return string
  * 
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function getJsonConfig()
 {
     /** @var \Magento\Bundle\Model\Option[] $optionsArray */
     $optionsArray = $this->getOptions();
     $options = array();
     $selected = array();
     $currentProduct = $this->getProduct();
     if ($preConfiguredFlag = $currentProduct->hasPreconfiguredValues()) {
         $preConfiguredValues = $currentProduct->getPreconfiguredValues();
         $defaultValues = array();
     }
     $position = 0;
     foreach ($optionsArray as $optionItem) {
         /* @var $optionItem \Magento\Bundle\Model\Option */
         if (!$optionItem->getSelections()) {
             continue;
         }
         $optionId = $optionItem->getId();
         $option = array('selections' => array(), 'title' => $optionItem->getTitle(), 'isMulti' => in_array($optionItem->getType(), array('multi', 'checkbox')), 'position' => $position++);
         $selectionCount = count($optionItem->getSelections());
         foreach ($optionItem->getSelections() as $selectionItem) {
             /* @var $selectionItem \Magento\Catalog\Model\Product */
             $selectionId = $selectionItem->getSelectionId();
             $qty = !($selectionItem->getSelectionQty() * 1) ? '1' : $selectionItem->getSelectionQty() * 1;
             // recalculate currency
             $tierPrices = $selectionItem->getPriceInfo()->getPrice(\Magento\Catalog\Pricing\Price\TierPrice::PRICE_CODE)->getTierPriceList();
             foreach ($tierPrices as &$tierPriceInfo) {
                 /** @var \Magento\Framework\Pricing\Amount\Base $price */
                 $price = $tierPriceInfo['price'];
                 $priceBaseAmount = $price->getBaseAmount();
                 $priceValue = $price->getValue();
                 $bundleProductPrice = $this->_productPrice->create();
                 $priceBaseAmount = $bundleProductPrice->getLowestPrice($currentProduct, $priceBaseAmount);
                 $priceValue = $bundleProductPrice->getLowestPrice($currentProduct, $priceValue);
                 $tierPriceInfo['price'] = $this->priceCurrency->convert($this->_taxData->displayPriceIncludingTax() ? $priceValue : $priceBaseAmount);
                 $tierPriceInfo['exclTaxPrice'] = $this->priceCurrency->convert($priceBaseAmount);
                 $tierPriceInfo['inclTaxPrice'] = $this->priceCurrency->convert($priceValue);
             }
             // break the reference with the last element
             $canApplyMAP = false;
             $bundleOptionPriceAmount = $currentProduct->getPriceInfo()->getPrice('bundle_option')->getOptionSelectionAmount($selectionItem);
             $priceInclTax = $bundleOptionPriceAmount->getValue();
             $priceExclTax = $bundleOptionPriceAmount->getBaseAmount();
             $selection = array('qty' => $qty, 'customQty' => $selectionItem->getSelectionCanChangeQty(), 'inclTaxPrice' => $this->priceCurrency->convert($priceInclTax), 'exclTaxPrice' => $this->priceCurrency->convert($priceExclTax), 'priceType' => $selectionItem->getSelectionPriceType(), 'tierPrice' => $tierPrices, 'name' => $selectionItem->getName(), 'plusDisposition' => 0, 'minusDisposition' => 0, 'canApplyMAP' => $canApplyMAP);
             $selection['price'] = $this->_taxData->displayPriceIncludingTax() ? $selection['inclTaxPrice'] : $selection['exclTaxPrice'];
             $responseObject = new \Magento\Framework\Object();
             $args = array('response_object' => $responseObject, 'selection' => $selectionItem);
             $this->_eventManager->dispatch('bundle_product_view_config', $args);
             if (is_array($responseObject->getAdditionalOptions())) {
                 foreach ($responseObject->getAdditionalOptions() as $index => $value) {
                     $selection[$index] = $value;
                 }
             }
             $option['selections'][$selectionId] = $selection;
             if (($selectionItem->getIsDefault() || $selectionCount == 1 && $optionItem->getRequired()) && $selectionItem->isSalable()) {
                 $selected[$optionId][] = $selectionId;
             }
         }
         $options[$optionId] = $option;
         // Add attribute default value (if set)
         if ($preConfiguredFlag) {
             $configValue = $preConfiguredValues->getData('bundle_option/' . $optionId);
             if ($configValue) {
                 $defaultValues[$optionId] = $configValue;
             }
         }
     }
     $isFixedPrice = $this->getProduct()->getPriceType() == \Magento\Bundle\Model\Product\Price::PRICE_TYPE_FIXED;
     $productAmount = $currentProduct->getPriceInfo()->getPrice(\Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE)->getAmount();
     $baseProductAmount = $currentProduct->getPriceInfo()->getPrice(\Magento\Catalog\Pricing\Price\RegularPrice::PRICE_CODE)->getAmount();
     $config = array('options' => $options, 'selected' => $selected, 'bundleId' => $currentProduct->getId(), 'priceFormat' => $this->_localeFormat->getPriceFormat(), 'basePrice' => $this->priceCurrency->convert($baseProductAmount->getValue()), 'finalBasePriceInclTax' => $isFixedPrice ? $this->priceCurrency->convert($productAmount->getValue()) : 0, 'finalBasePriceExclTax' => $isFixedPrice ? $this->priceCurrency->convert($productAmount->getBaseAmount()) : 0, 'priceType' => $currentProduct->getPriceType(), 'specialPrice' => $currentProduct->getPriceInfo()->getPrice(\Magento\Catalog\Pricing\Price\SpecialPrice::PRICE_CODE)->getValue(), 'includeTax' => $this->_taxData->priceIncludesTax() ? 'true' : 'false', 'isFixedPrice' => $isFixedPrice);
     $config['finalPrice'] = $this->_taxData->displayPriceIncludingTax() ? $config['finalBasePriceInclTax'] : $config['finalBasePriceExclTax'];
     if ($preConfiguredFlag && !empty($defaultValues)) {
         $config['defaultValues'] = $defaultValues;
     }
     return $this->jsonEncoder->encode($config);
 }
示例#26
0
文件: Item.php 项目: aiesh/magento2
 /**
  * Checking quote item quantity
  *
  * Second parameter of this method specifies quantity of this product in whole shopping cart
  * which should be checked for stock availability
  *
  * @param int|float $qty quantity of this item (item qty x parent item qty)
  * @param int|float $summaryQty quantity of this product
  * @param int|float $origQty original qty of item (not multiplied on parent item qty)
  * @return \Magento\Framework\Object
  */
 public function checkQuoteItemQty($qty, $summaryQty, $origQty = 0)
 {
     $result = new \Magento\Framework\Object();
     $result->setHasError(false);
     if (!is_numeric($qty)) {
         $qty = $this->_localeFormat->getNumber($qty);
     }
     /**
      * Check quantity type
      */
     $result->setItemIsQtyDecimal($this->getIsQtyDecimal());
     if (!$this->getIsQtyDecimal()) {
         $result->setHasQtyOptionUpdate(true);
         $qty = intval($qty);
         /**
          * Adding stock data to quote item
          */
         $result->setItemQty($qty);
         if (!is_numeric($qty)) {
             $qty = $this->_localeFormat->getNumber($qty);
         }
         $origQty = intval($origQty);
         $result->setOrigQty($origQty);
     }
     if ($this->getMinSaleQty() && $qty < $this->getMinSaleQty()) {
         $result->setHasError(true)->setMessage(__('The fewest you may purchase is %1.', $this->getMinSaleQty() * 1))->setErrorCode('qty_min')->setQuoteMessage(__('Please correct the quantity for some products.'))->setQuoteMessageIndex('qty');
         return $result;
     }
     if ($this->getMaxSaleQty() && $qty > $this->getMaxSaleQty()) {
         $result->setHasError(true)->setMessage(__('The most you may purchase is %1.', $this->getMaxSaleQty() * 1))->setErrorCode('qty_max')->setQuoteMessage(__('Please correct the quantity for some products.'))->setQuoteMessageIndex('qty');
         return $result;
     }
     $result->addData($this->checkQtyIncrements($qty)->getData());
     if ($result->getHasError()) {
         return $result;
     }
     if (!$this->getManageStock()) {
         return $result;
     }
     if (!$this->getIsInStock()) {
         $result->setHasError(true)->setMessage(__('This product is out of stock.'))->setQuoteMessage(__('Some of the products are currently out of stock.'))->setQuoteMessageIndex('stock');
         $result->setItemUseOldQty(true);
         return $result;
     }
     if (!$this->checkQty($summaryQty) || !$this->checkQty($qty)) {
         $message = __('We don\'t have as many "%1" as you requested.', $this->getProductName());
         $result->setHasError(true)->setMessage($message)->setQuoteMessage($message)->setQuoteMessageIndex('qty');
         return $result;
     } else {
         if ($this->getQty() - $summaryQty < 0) {
             if ($this->getProductName()) {
                 if ($this->getIsChildItem()) {
                     $backOrderQty = $this->getQty() > 0 ? ($summaryQty - $this->getQty()) * 1 : $qty * 1;
                     if ($backOrderQty > $qty) {
                         $backOrderQty = $qty;
                     }
                     $result->setItemBackorders($backOrderQty);
                 } else {
                     $orderedItems = (int) $this->getOrderedItems();
                     // Available item qty in stock excluding item qty in other quotes
                     $qtyAvailable = ($this->getQty() - ($summaryQty - $qty)) * 1;
                     if ($qtyAvailable > 0) {
                         $backOrderQty = $qty * 1 - $qtyAvailable;
                     } else {
                         $backOrderQty = $qty * 1;
                     }
                     if ($backOrderQty > 0) {
                         $result->setItemBackorders($backOrderQty);
                     }
                     $this->setOrderedItems($orderedItems + $qty);
                 }
                 if ($this->getBackorders() == \Magento\CatalogInventory\Model\Stock::BACKORDERS_YES_NOTIFY) {
                     if (!$this->getIsChildItem()) {
                         $result->setMessage(__('We don\'t have as many "%1" as you requested, but we\'ll back order the remaining %2.', $this->getProductName(), $backOrderQty * 1));
                     } else {
                         $result->setMessage(__('We don\'t have "%1" in the requested quantity, so we\'ll back order the remaining %2.', $this->getProductName(), $backOrderQty * 1));
                     }
                 } elseif ($this->_hasDefaultNotificationMessage()) {
                     $result->setMessage(__('We don\'t have as many "%1" as you requested.', $this->getProductName()));
                 }
             }
         } else {
             if (!$this->getIsChildItem()) {
                 $this->setOrderedItems($qty + (int) $this->getOrderedItems());
             }
         }
     }
     return $result;
 }
示例#27
0
 /**
  * Prepare shipping rate result based on response
  *
  * @param string $response
  * @return Result
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 protected function _parseCgiResponse($response)
 {
     $costArr = [];
     $priceArr = [];
     if (strlen(trim($response)) > 0) {
         $rRows = explode("\n", $response);
         $allowedMethods = explode(",", $this->getConfigData('allowed_methods'));
         foreach ($rRows as $rRow) {
             $row = explode('%', $rRow);
             switch (substr($row[0], -1)) {
                 case 3:
                 case 4:
                     if (in_array($row[1], $allowedMethods)) {
                         $responsePrice = $this->_localeFormat->getNumber($row[8]);
                         $costArr[$row[1]] = $responsePrice;
                         $priceArr[$row[1]] = $this->getMethodPrice($responsePrice, $row[1]);
                     }
                     break;
                 case 5:
                     $errorTitle = $row[1];
                     $message = __('Sorry, something went wrong. Please try again or contact us and we\'ll try to help.');
                     $this->_logger->debug($message . ': ' . $errorTitle);
                     break;
                 case 6:
                     if (in_array($row[3], $allowedMethods)) {
                         $responsePrice = $this->_localeFormat->getNumber($row[10]);
                         $costArr[$row[3]] = $responsePrice;
                         $priceArr[$row[3]] = $this->getMethodPrice($responsePrice, $row[3]);
                     }
                     break;
                 default:
                     break;
             }
         }
         asort($priceArr);
     }
     $result = $this->_rateFactory->create();
     if (empty($priceArr)) {
         $error = $this->_rateErrorFactory->create();
         $error->setCarrier('ups');
         $error->setCarrierTitle($this->getConfigData('title'));
         $error->setErrorMessage($this->getConfigData('specificerrmsg'));
         $result->append($error);
     } else {
         foreach ($priceArr as $method => $price) {
             $rate = $this->_rateMethodFactory->create();
             $rate->setCarrier('ups');
             $rate->setCarrierTitle($this->getConfigData('title'));
             $rate->setMethod($method);
             $methodArray = $this->configHelper->getCode('method', $method);
             $rate->setMethodTitle($methodArray);
             $rate->setCost($costArr[$method]);
             $rate->setPrice($price);
             $result->append($rate);
         }
     }
     return $result;
 }