/** * {@inheritdoc} */ public function build($productId) { $timestamp = $this->localeDate->scopeTimeStamp($this->storeManager->getStore()); $currentDate = $this->dateTime->formatDate($timestamp, false); $linkField = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField(); $productTable = $this->resource->getTableName('catalog_product_entity'); return [$this->resource->getConnection()->select()->from(['parent' => $productTable], '')->joinInner(['link' => $this->resource->getTableName('catalog_product_relation')], "link.parent_id = parent.{$linkField}", [])->joinInner(['child' => $productTable], "child.entity_id = link.child_id", ['entity_id'])->joinInner(['t' => $this->resource->getTableName('catalogrule_product_price')], 't.product_id = child.entity_id', [])->where('parent.entity_id = ? ', $productId)->where('t.website_id = ?', $this->storeManager->getStore()->getWebsiteId())->where('t.customer_group_id = ?', $this->customerSession->getCustomerGroupId())->where('t.rule_date = ?', $currentDate)->order('t.rule_price ' . Select::SQL_ASC)->limit(1)]; }
/** * Returns catalog rule value * * @return float|boolean */ public function getValue() { if (null === $this->value) { $this->value = $this->resourceRuleFactory->create()->getRulePrice($this->dateTime->scopeTimeStamp($this->storeManager->getStore()->getId()), $this->storeManager->getStore()->getWebsiteId(), $this->customerSession->getCustomerGroupId(), $this->product->getId()); $this->value = $this->value ? floatval($this->value) : false; } return $this->value; }
/** * 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; }
/** * Add products to changes list with price which depends on date * * @return void */ public function execute() { $connection = $this->_getConnection(); foreach ($this->_storeManager->getStores(true) as $store) { $timestamp = $this->_localeDate->scopeTimeStamp($store); $currDate = $this->_dateTime->formatDate($timestamp, false); $currDateExpr = $connection->quote($currDate); // timestamp is locale based if (date('H', $timestamp) == '00') { $format = '%Y-%m-%d %H:%i:%s'; $this->_refreshSpecialPriceByStore($store->getId(), 'special_from_date', $connection->getDateFormatSql($currDateExpr, $format)); $dateTo = $connection->getDateAddSql($currDateExpr, -1, \Magento\Framework\DB\Adapter\AdapterInterface::INTERVAL_DAY); $this->_refreshSpecialPriceByStore($store->getId(), 'special_to_date', $connection->getDateFormatSql($dateTo, $format)); } } }
/** * {@inheritdoc} */ public function build($productId) { $linkField = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField(); $connection = $this->resource->getConnection(); $specialPriceAttribute = $this->eavConfig->getAttribute(Product::ENTITY, 'special_price'); $specialPriceFromDate = $this->eavConfig->getAttribute(Product::ENTITY, 'special_from_date'); $specialPriceToDate = $this->eavConfig->getAttribute(Product::ENTITY, 'special_to_date'); $timestamp = $this->localeDate->scopeTimeStamp($this->storeManager->getStore()); $currentDate = $this->dateTime->formatDate($timestamp, false); $productTable = $this->resource->getTableName('catalog_product_entity'); $specialPrice = $this->resource->getConnection()->select()->from(['parent' => $productTable], '')->joinInner(['link' => $this->resource->getTableName('catalog_product_relation')], "link.parent_id = parent.{$linkField}", [])->joinInner(['child' => $productTable], "child.entity_id = link.child_id", ['entity_id'])->joinInner(['t' => $specialPriceAttribute->getBackendTable()], "t.{$linkField} = child.{$linkField}", [])->joinLeft(['special_from' => $specialPriceFromDate->getBackendTable()], $connection->quoteInto("t.{$linkField} = special_from.{$linkField} AND special_from.attribute_id = ?", $specialPriceFromDate->getAttributeId()), '')->joinLeft(['special_to' => $specialPriceToDate->getBackendTable()], $connection->quoteInto("t.{$linkField} = special_to.{$linkField} AND special_to.attribute_id = ?", $specialPriceToDate->getAttributeId()), '')->where('parent.entity_id = ? ', $productId)->where('t.attribute_id = ?', $specialPriceAttribute->getAttributeId())->where('t.value IS NOT NULL')->where('special_from.value IS NULL OR ' . $connection->getDatePartSql('special_from.value') . ' <= ?', $currentDate)->where('special_to.value IS NULL OR ' . $connection->getDatePartSql('special_to.value') . ' >= ?', $currentDate)->order('t.value ' . Select::SQL_ASC)->limit(1); $specialPriceDefault = clone $specialPrice; $specialPriceDefault->where('t.store_id = ?', Store::DEFAULT_STORE_ID); $select[] = $specialPriceDefault; if (!$this->catalogHelper->isPriceGlobal()) { $specialPrice->where('t.store_id = ?', $this->storeManager->getStore()->getId()); $select[] = $specialPrice; } return $select; }
public function execute() { if (!$this->_isAllowed()) { echo $this->__('Access Denied'); return; } $SCHEDULE_EVERY_MINUTES = 30; //Flooring the minutes $startTimeSeconds = (int) ($this->_timezone->scopeTimeStamp() / 60) * 60; //Ceiling to the next 5 minutes $startTimeMinutes = $startTimeSeconds / 60; $startTimeMinutes = (int) ($startTimeMinutes / 5) * 5 + 5; $startTimeSeconds = $startTimeMinutes * 60; $jobs = $this->_cronConfig->getJobs(); if (isset($jobs[self::CRON_GROUP])) { $i = 0; foreach ($jobs[self::CRON_GROUP] as $jobCode => $jobConfig) { if (strpos($jobCode, self::CRON_JOB) === false) { continue; } $timecreated = strftime('%Y-%m-%d %H:%M:%S', $this->_timezone->scopeTimeStamp()); $timescheduled = strftime('%Y-%m-%d %H:%M:%S', $startTimeSeconds + $i * 60 * $SCHEDULE_EVERY_MINUTES); try { $lastItem = $this->_cronSchedule->getCollection()->addFieldToFilter('job_code', 'celebros_export')->addFieldToFilter('scheduled_at', $timescheduled)->getLastItem(); if (!$lastItem->getScheduleId()) { $this->_cronSchedule->setJobCode($jobCode)->setCreatedAt($timecreated)->setScheduledAt($timescheduled)->setStatus('pending')->save(); echo "{$jobCode} cron job is scheduled at {$timescheduled} <br/>"; } else { echo "{$jobCode} cron job are already exist at {$timescheduled} <br/>"; } } catch (\Exception $e) { throw new \Exception(__('Unable to schedule Cron')); } $i++; } } }
/** * Check if cron job is exists db table and executed less 6 hours ago * * @param string $jobCode * @return bool */ public function isCronRunning($jobCode) { $collection = $this->scheduleCollectionFactory->create(); if ($jobCode) { $collection->addFieldToFilter('job_code', $jobCode); } $collection->addFieldToFilter('status', 'success')->setOrder('scheduled_at', 'desc')->setPageSize(1); /** @var \Magento\Cron\Model\Schedule $job */ $job = $collection->getFirstItem(); if (!$job->getId()) { return false; } $jobTimestamp = strtotime($job->getExecutedAt()); //in store timezone $timestamp = $this->timezone->scopeTimeStamp(); //in store timezone if (abs($timestamp - $jobTimestamp) > 6 * 60 * 60) { return false; } return true; }
/** * Load custom design settings for specified store and date * * @param string $storeId * @param string|null $date * @return $this */ public function loadChange($storeId, $date = null) { if ($date === null) { $date = $this->_dateTime->formatDate($this->_localeDate->scopeTimeStamp($storeId), false); } $changeCacheId = 'design_change_' . md5($storeId . $date); $result = $this->_cacheManager->load($changeCacheId); if ($result === false) { $result = $this->getResource()->loadChange($storeId, $date); if (!$result) { $result = []; } $this->_cacheManager->save(serialize($result), $changeCacheId, [self::CACHE_TAG], 86400); } else { $result = unserialize($result); } if ($result) { $this->setData($result); } return $this; }
/** * 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; }
/** * Apply catalog price rules to product on frontend * * @param \Magento\Framework\Event\Observer $observer * @return $this */ public function execute(\Magento\Framework\Event\Observer $observer) { /* @var $collection ProductCollection */ $collection = $observer->getEvent()->getCollection(); $store = $this->storeManager->getStore($observer->getEvent()->getStoreId()); $websiteId = $store->getWebsiteId(); if ($observer->getEvent()->hasCustomerGroupId()) { $groupId = $observer->getEvent()->getCustomerGroupId(); } else { if ($this->customerSession->isLoggedIn()) { $groupId = $this->customerSession->getCustomerGroupId(); } else { $groupId = $this->groupManagement->getNotLoggedInGroup()->getId(); } } if ($observer->getEvent()->hasDate()) { $date = new \DateTime($observer->getEvent()->getDate()); } else { $date = (new \DateTime())->setTimestamp($this->localeDate->scopeTimeStamp($store)); } $productIds = []; /* @var $product Product */ foreach ($collection as $product) { $key = implode('|', [$date->format('Y-m-d H:i:s'), $websiteId, $groupId, $product->getId()]); if (!$this->rulePricesStorage->hasRulePrice($key)) { $productIds[] = $product->getId(); } } if ($productIds) { $rulePrices = $this->resourceRuleFactory->create()->getRulePrices($date, $websiteId, $groupId, $productIds); foreach ($productIds as $productId) { $key = implode('|', [$date->format('Y-m-d H:i:s'), $websiteId, $groupId, $productId]); $this->rulePricesStorage->setRulePrice($key, isset($rulePrices[$productId]) ? $rulePrices[$productId] : false); } } return $this; }
/** * @param string $jobCode * @param string $cronExpression * @param int $time * @return Schedule */ protected function generateSchedule($jobCode, $cronExpression, $time) { $schedule = $this->_scheduleFactory->create()->setCronExpr($cronExpression)->setJobCode($jobCode)->setStatus(Schedule::STATUS_PENDING)->setCreatedAt(strftime('%Y-%m-%d %H:%M:%S', $this->timezone->scopeTimeStamp()))->setScheduledAt(strftime('%Y-%m-%d %H:%M', $time)); return $schedule; }
/** * Join prices from price rules to products collection * * @return $this */ protected function _joinPriceRules() { if ($this->isEnabledFlat()) { $customerGroup = $this->_customerSession->getCustomerGroupId(); $priceColumn = 'e.display_price_group_' . $customerGroup; $this->getSelect()->columns(array('_rule_price' => $priceColumn)); return $this; } if (!$this->moduleManager->isEnabled('Magento_CatalogRule')) { return $this; } $wId = $this->_storeManager->getWebsite()->getId(); $gId = $this->_customerSession->getCustomerGroupId(); $storeDate = $this->_localeDate->scopeTimeStamp($this->getStoreId()); $conditions = 'price_rule.product_id = e.entity_id AND '; $conditions .= "price_rule.rule_date = '" . $this->dateTime->formatDate($storeDate, false) . "' AND "; $conditions .= $this->getConnection()->quoteInto('price_rule.website_id = ? AND', $wId); $conditions .= $this->getConnection()->quoteInto('price_rule.customer_group_id = ?', $gId); $this->getSelect()->joinLeft(array('price_rule' => $this->getTable('catalogrule_product_price')), $conditions, array('rule_price' => 'rule_price')); return $this; }
/** * @param EventObserver $observer * @return $this */ public function prepareCatalogProductCollectionPrices(EventObserver $observer) { /* @var $collection ProductCollection */ $collection = $observer->getEvent()->getCollection(); $store = $this->_storeManager->getStore($observer->getEvent()->getStoreId()); $websiteId = $store->getWebsiteId(); if ($observer->getEvent()->hasCustomerGroupId()) { $groupId = $observer->getEvent()->getCustomerGroupId(); } else { if ($this->_customerSession->isLoggedIn()) { $groupId = $this->_customerSession->getCustomerGroupId(); } else { $groupId = Group::NOT_LOGGED_IN_ID; } } if ($observer->getEvent()->hasDate()) { $date = $observer->getEvent()->getDate(); } else { $date = $this->_localeDate->scopeTimeStamp($store); } $productIds = array(); /* @var $product Product */ foreach ($collection as $product) { $key = implode('|', array($date, $websiteId, $groupId, $product->getId())); if (!isset($this->_rulePrices[$key])) { $productIds[] = $product->getId(); } } if ($productIds) { $rulePrices = $this->_resourceRuleFactory->create()->getRulePrices($date, $websiteId, $groupId, $productIds); foreach ($productIds as $productId) { $key = implode('|', array($date, $websiteId, $groupId, $productId)); $this->_rulePrices[$key] = isset($rulePrices[$productId]) ? $rulePrices[$productId] : false; } } return $this; }