diff --git a/Block/Adminhtml/BadgeSelect.php b/Block/Adminhtml/BadgeSelect.php deleted file mode 100644 index c192764..0000000 --- a/Block/Adminhtml/BadgeSelect.php +++ /dev/null @@ -1,166 +0,0 @@ -_scopeConfig->getValue('feedaty_global/feedaty_preferences/feedaty_code', $store_scope); - - $element_id = $element->getId(); - - $script = ""; - - return parent::_getElementHtml($element) . $script; - - } -} \ No newline at end of file diff --git a/Block/Adminhtml/Preview.php b/Block/Adminhtml/Preview.php deleted file mode 100644 index 87df7bf..0000000 --- a/Block/Adminhtml/Preview.php +++ /dev/null @@ -1,105 +0,0 @@ -_scopeConfig = $scopeConfig; - $this->_storeManager = $storeManager; - $this->_fdservice = $fdservice; - $this->_objectManager = $objectManager; - parent::__construct($context, $data); - } - - /** - * @return $html - */ - protected function _getElementHtml(AbstractElement $element) - { - - $store_scope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; - $merchant = $this->_scopeConfig->getValue('feedaty_global/feedaty_preferences/feedaty_code', $store_scope); - - $style = $this->_scopeConfig->getValue('feedaty_badge_options/widget_store/style', $store_scope); - $variant = $this->_scopeConfig->getValue('feedaty_badge_options/widget_store/variant', $store_scope); - - $data = $merchant != null ? $this->_fdservice->getFeedatyData($merchant) : null; - - if ($style != null && $data != null) { - - $widget = $data[$style]; - $name = $widget["name"]; - $variant = $widget["variants"][$variant]; - - $images = ""; - - if(strlen($variant) > 0 && strlen($name) > 0&& $data != null) { - - if( $name == 'dynamic' || $name == 'dynvertical' ) { - - $sizes = array_keys($widget['thumbs']); - - foreach ($sizes as $size) { - - $images .= ""; - } - - } - - else { - - $images .= ""; - } - - $html = $images ; - - } - - else { - - $html = "

Anteprima del widget non disponibile

"; - } - } - - else { - - $html = "

Anteprima del widget non disponibile

"; - } - - return $html; - - } -} \ No newline at end of file diff --git a/Block/Adminhtml/ProdPreview.php b/Block/Adminhtml/ProdPreview.php deleted file mode 100644 index 9ca7152..0000000 --- a/Block/Adminhtml/ProdPreview.php +++ /dev/null @@ -1,109 +0,0 @@ -_scopeConfig = $scopeConfig; - $this->_storeManager = $storeManager; - $this->_fdservice = $fdservice; - $this->_objectManager = $objectManager; - parent::__construct($context, $data); - } - - /** - * @return $html - */ - protected function _getElementHtml(AbstractElement $element) - { - - - $store_scope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; - $merchant = $this->_scopeConfig->getValue('feedaty_global/feedaty_preferences/feedaty_code', $store_scope); - - $style = $this->_scopeConfig->getValue('feedaty_badge_options/widget_products/product_style', $store_scope); - $variant = $this->_scopeConfig->getValue('feedaty_badge_options/widget_products/prod_variant', $store_scope); - - $data = $merchant != null ? $this->_fdservice->getFeedatyData($merchant) : null; - - if($style == null || $data == null) return $this->noPreview(); - - $widget = $data[$style]; - $name = $widget["name"]; - - if (! array_key_exists($variant, $widget["variants"])) return $this->noPreview(); - - $variant = $widget["variants"][$variant]; - - $images = ""; - - if(strlen($variant) > 0 && strlen($name) > 0 ) { - - if( $name == 'productdynamic' ) { - - $sizes = array_keys($widget['thumbs']); - - foreach ($sizes as $size) { - - $images .= ""; - } - - } - - else { - - $images .= ""; - } - - $html = $images; - - return $html; - } - - else { - - $html = "

Anteprima non disponibile

"; - } - - return $html; - - } - - private function noPreview() { - - return "

Anteprima non disponibile

"; - } -} \ No newline at end of file diff --git a/Block/Product.php b/Block/Product.php deleted file mode 100755 index 7381ea4..0000000 --- a/Block/Product.php +++ /dev/null @@ -1,13 +0,0 @@ -setTemplate('Feedaty_Badge::fdtbase.phtml'); - } -} diff --git a/Block/ProductSnippet.php b/Block/ProductSnippet.php index beda370..363d64a 100755 --- a/Block/ProductSnippet.php +++ b/Block/ProductSnippet.php @@ -7,7 +7,8 @@ use Magento\Framework\View\Element\Template; use Magento\Framework\View\Element\Template\Context; use Magento\Store\Model\StoreManagerInterface; -use Magento\Directory\Model\CurrencyFactory; +use Magento\Review\Model\ResourceModel\Review\CollectionFactory; +use Magento\Review\Model\ReviewFactory; class ProductSnippet extends Template { @@ -32,14 +33,13 @@ class ProductSnippet extends Template private $storeConfig; /** - * @var CurrencyFactory + * @var ReviewFactory */ - private $currencyCode; - + private $_reviewCollection; /** - * @var \Magento\Framework\Controller\Result\JsonFactory + * @var ReviewFactory */ - private $jsonResultFactory; + private $reviewFactory; /** * ProductSnippet constructor. @@ -49,29 +49,64 @@ class ProductSnippet extends Template * @param Data $catalogData */ public function __construct( - Context $context, - WebService $webservice, - ConfigRules $configRules, - Data $catalogData, - StoreManagerInterface $storeConfig, - CurrencyFactory $currencyFactory + Context $context, + WebService $webservice, + ConfigRules $configRules, + Data $catalogData, + StoreManagerInterface $storeConfig, + CollectionFactory $reviewCollection, + ReviewFactory $reviewFactory + ) { $this->_configRules = $configRules; $this->_webservice = $webservice; $this->_catalogData = $catalogData; $this->storeConfig = $storeConfig; - $this->currencyCode = $currencyFactory->create(); parent::__construct($context); + $this->_reviewCollection = $reviewCollection; + $this->reviewFactory = $reviewFactory; } /** - * @param $feedaty_code - * @param $id - * @return mixed + * @param $productId + * @return \Magento\Review\Model\ResourceModel\Review\Collection */ - public function retriveInformationsProduct($feedaty_code, $id) + public function getProductReviews($productId) { - return $this->_webservice->retriveInformationsProduct($feedaty_code, $id); + $collection = $this->_reviewCollection->create() + ->addStoreFilter($this->getStoreId()) + ->addFieldToSelect('*') + ->addStatusFilter( + \Magento\Review\Model\Review::STATUS_APPROVED + )->addEntityFilter( + 'product', + $productId + )->setDateOrder() + ->addRateVotes(); + + return $collection; + } + + + + /** + * Get store identifier + * + * @return int + */ + public function getStoreId() + { + return $this->_storeManager->getStore()->getId(); + } + + public function getRatingSummary($product) + { + + $this->reviewFactory->create()->getEntitySummary($product, $this->getStoreId()); + + $ratingSummary = $product->getRatingSummary()->getRatingSummary(); + + return $ratingSummary; } /** @@ -139,6 +174,8 @@ public function getProductSku() return $this->getProduct()->getSku(); } + + /** * @return string */ @@ -165,19 +202,22 @@ public function getMediaUrl() return $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); } - public function getAllReview() - { - return $this->_webservice->getAllReviews($params = ''); - } - /** * @return string */ public function getCurrencyCode() { $currencyCode = $this->storeConfig->getStore()->getCurrentCurrencyCode(); - // $currency = $this->currencyCode->load($currencyCode); - //return $currency->getCurrencySymbol(); return $currencyCode; } + + /** + * Get Store name + * + * @return string + */ + public function getStoreName() + { + return $this->_storeManager->getStore()->getName(); + } } diff --git a/Block/Widget/ProductBadge.php b/Block/Widget/ProductBadge.php index 84ba1e5..8bbeeb4 100755 --- a/Block/Widget/ProductBadge.php +++ b/Block/Widget/ProductBadge.php @@ -11,7 +11,7 @@ class ProductBadge extends Template implements BlockInterface { - protected $_template = "widget/product-bagde.phtml"; + protected $_template = "widget/product-badge.phtml"; /** * @var WebService @@ -48,18 +48,24 @@ public function __construct( } /** - * @return void + * @return array */ public function getFeedatyCode() { return $this->_configRules->getFeedatyCode(); } + /* + * Get Feedaty Data + */ public function getFeedatyData($merchantCode) { return $this->_webservice->getFeedatyData($merchantCode); } + /* + * Get Module Version + */ public function getExtensionVersion() { return json_decode(json_encode($this->_dataHelper->getExtensionVersion()), true); diff --git a/Block/Widget/StoreBadge.php b/Block/Widget/StoreBadge.php index 306087f..623f729 100755 --- a/Block/Widget/StoreBadge.php +++ b/Block/Widget/StoreBadge.php @@ -11,7 +11,7 @@ class StoreBadge extends Template implements BlockInterface { - protected $_template = "widget/store-bagde.phtml"; + protected $_template = "widget/store-badge.phtml"; /** * @var WebService diff --git a/CHANGELOG.md b/CHANGELOG.md index 5148b46..8c03566 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,12 +2,35 @@ #### RELASE NOTES -### V2.6.0 14/04/2020 + +### V2.7.0 + +* Features: + * New Feedaty Badges integrated + * New Rich snippets for all reviews integrated + * New export orders function. Orders are now exported to Feedaty with cronjob + * Old Product Snippet has been removed + * New Product Badge Widget + * New Store Badge Widget + * Curl Factory Pattern + * Removed custom timeout + * Platform Information API + * Ability to import reviews into Magento native reviews + +* Fixed Bugs + * Fixed json serialize vulnerability + * Minor bug fix + + +### V2.6.7 05/09/2021 +- Fix Culture Code - Reviews are now requested in the correct store view language + +### V2.6.0 14/04/2021 - New Product Badge Widget - New Store Badge Widget -### V2.5.7-dev- 14/04/2020 +### V2.5.7-dev- 14/04/2021 - Snippet prodotto diff --git a/Cron/Orders.php b/Cron/Orders.php new file mode 100644 index 0000000..f18ef2f --- /dev/null +++ b/Cron/Orders.php @@ -0,0 +1,121 @@ +logger = $logger; + $this->ordersHelper = $ordersHelper; + $this->webService = $webService; + } + + /** + * Send Orders to Feedaty Orders API + */ + public function execute() + { + /** + * Send Module Information Data + */ + $this->webService->fdSendInstallationInfo(); + + + //Starter Log + $this->logger->addInfo("Feedaty | START Cronjob | Set Feedaty Orders | date: " . date('Y-m-d H:i:s') ); + + $orders = $this->ordersHelper->getOrders(); + + + $data = array(); + + /* Order Increment */ + $i = 0; + + if(count($orders) > 0){ + foreach ($orders as $order){ + + /* Get all visible order products */ + $items = $order->getAllVisibleItems(); + + $storeId = $order->getStoreId(); + /** + * Get Locale + */ + $localeCode = $this->ordersHelper->getCulture($storeId); + + $data[$i] = [ + 'ID' => $order->getEntityId(), + 'Date' => $order->getCreatedAt(), + 'CustomerEmail' => $order->getCustomerEmail(), + 'CustomerID' => $order->getCustomerEmail(), + 'Culture' => $localeCode, + 'Platform' => $this->ordersHelper->getPlatform(), + 'Products' => [] + + ]; + + foreach ($items as $item){ + + $productId = $item->getProductId(); + + $productThumbnailUrl = $this->ordersHelper->getProductThumbnailUrl($item); + + array_push($data[$i]['Products'], + [ + 'SKU' => $productId , + 'URL' => $item->getProduct()->getProductUrl(), + 'ThumbnailURL' => $productThumbnailUrl, + 'Name' => $item->getName() + ] + ); + + } + + $i++; + } + + $response = (array) $this->webService->sendOrder($data); + + if(!empty($response)){ + foreach ($response['Data'] as $data){ + //if order Success or Duplicated set Feedaty Customer Notification true + if($data['Status'] == '1' || $data['Status'] == '201'){ + $this->ordersHelper->setFeedatyCustomerNotified((int)$data['OrderID']); + } + } + } + } + + } + +} + diff --git a/Cron/Reviews.php b/Cron/Reviews.php new file mode 100644 index 0000000..9e3aa98 --- /dev/null +++ b/Cron/Reviews.php @@ -0,0 +1,322 @@ +_logger = $logger; + $this->_webService = $webService; + $this->_reviewFactory = $reviewFactory; + $this->_ratingFactory = $ratingFactory; + $this->_storeManager = $storeManager; + $this->_date = $date; + $this->_configRules = $configRules; + $this->_reviewsHelper = $reviewsHelper; + } + + + /** + * @throws \Magento\Framework\Exception\LocalizedException + */ + public function execute() + { + + /** + * IF IMPORT IS ENABLED + */ + $enableImportReviews = $this->_configRules->getCreateReviewEnabled(); + + if($enableImportReviews == 1){ + + /** + * Get Feedaty TotalProductReviews Count + */ + $totalFeedatyReviews = $this->_webService->getTotalProductReviewsCount(); + + /** + * Get Feedaty Removed Reviews TotalResults Count + */ + $totalFeedatyRemovedReviews = $this->_webService->getTotalProductRemovedReviewsCount(); + + /** + * Get Feedaty Removed Reviews TotalResults Count + */ + $totalFeedatyMediatedReviews = $this->_webService->getTotalProductMediatedReviewsCount(); + + /** + * Get Feedaty Reviews Created on Magento Total Count + */ + $totalReviewCreatedCount = $this->_reviewsHelper->getAllFeedatyReviewCount(); + + /** + * Get Feedaty Reviews Removed on Magento Total Count + */ + $totalRemovedReviewCreatedCount = $this->_reviewsHelper->getAllFeedatyRemovedReviewCount(); + + /** + * Get Feedaty Reviews Removed on Magento Total Count + */ + $totalMediatedReviewCreatedCount = $this->_reviewsHelper->getAllFeedatyMediatedReviewCount(); + + $this->_logger->addInfo("Feedaty | Cronjob Run | Get Feedaty Reviews | date: " . date('Y-m-d H:i:s') . ' ---- Total Feedaty Product Reviews ' . $totalFeedatyReviews . ' totalReviewCreatedCount group by feedaty_id ' . $totalReviewCreatedCount); + + /** + * Get Last Review Created on Magento (on first run vill be null) + */ + $lastReviewCreated = $this->_reviewsHelper->getLastFeedatyReviewCreated(); + + /** + * Get n Reviews from Feedaty + */ + $count = 100; + + /** + * Set Row Param from Feedaty + */ + $row = $totalFeedatyReviews - $totalReviewCreatedCount - $count; + + + /** + * CREATE NEW REVIEWS + */ + //Get Feedaty Product Reviews Data + $feedatyProductReviews = $this->_webService->getProductReviewsPagination($row, $count); + + + if (!empty($feedatyProductReviews)) { + //Foreach Review + foreach ($feedatyProductReviews as $review) { + //feedaty_source_id + $feedatyId = $review['ID']; + + $orderId = $review['OrderID']; + + $storeView = $this->_reviewsHelper->getStoreViewIdByOrder($orderId); + + $replaceFromDate = ["/Date(", ")/"]; + $replaceToDate = ["", ""]; + //Review Date + $createdAt = date('Y-m-d h:i:s', floor((int)str_replace($replaceFromDate, $replaceToDate, $review['Released']) / 1000)); + + $today = $this->_date->gmtDate(); + foreach ($review['ProductsReviews'] as $item) { + + $productId = $item['SKU']; + $feedatyProductReviewId = $item['ID']; + + //Get Feedaty Product Reviews + $magentoProductReviews = $this->_reviewsHelper->getReviewCollection($productId, $feedatyId); + + //AP Rating node + $rating = $item['Rating']; + + //API Review Node + $detail = $item['Review']; + + if (empty($magentoProductReviews)) { + $this->createProductReview($productId, $feedatyId, $feedatyProductReviewId, $rating, $detail, $createdAt, $today, $row, $storeView); + } + } + } + // General Cron Report on system.log + $this->_logger->addInfo("Feedaty | END Cronjob | Get Feedaty Reviews | date execution: " . date('Y-m-d H:i:s') ); + } + + /** + * UPDATE MEDIATED REVIEWS + */ + + $rowMediated = $totalFeedatyMediatedReviews - $totalMediatedReviewCreatedCount - $count; + + if($rowMediated < 0 ){ + + $rowMediated = 0; + } + + /** + * Get Feedaty Mediated Reviews + */ + $feedatyProductReviewsMediated = $this->_webService->getMediatedReviews($rowMediated, $count); + + + if (!empty($feedatyProductReviewsMediated)) { + + $this->_logger->addInfo("Feedaty | START Mediated Reviews"); + + //Foreach Review + foreach ($feedatyProductReviewsMediated as $mediatedReview) { + + $feedatyId = $mediatedReview['FeedbackReviewID']; + $reviewDetail = $mediatedReview['MerchantReview']; + + $reviewToMediate = $this->_reviewsHelper->getAllReviewsByFeedatyId($feedatyId); + + if (!empty($reviewToMediate)) { + //if it is not just disabled + foreach ($reviewToMediate as $item){ + + if ($item['status_id'] !== 3) { + $this->_reviewsHelper->mediateReview($item,$reviewDetail); + } + } + + } + + } + } + + + /** + * DISABLE REMOVED REVIEWS + */ + $rowRemoved = $totalFeedatyRemovedReviews - $totalRemovedReviewCreatedCount - $count; + + if($rowRemoved < 0 ){ + $rowRemoved = 0; + } + + /** + * Get Feedaty Removed Reviews + */ + $feedatyProductReviewsRemoved = $this->_webService->getRemovedReviews($rowRemoved, $count); + + if (!empty($feedatyProductReviewsRemoved)) { + + //Foreach Review + foreach ($feedatyProductReviewsRemoved as $removedReview) { + + $feedatyId = $removedReview['FeedbackReviewID']; + + $reviewToDisable = $this->_reviewsHelper->getAllReviewsByFeedatyId($feedatyId); + + if (!empty($reviewToDisable)) { + //if it is not just disabled + foreach ($reviewToDisable as $item){ + + if ($item['status_id'] !== 3) { + $this->_reviewsHelper->disableReview($item); + } + } + + } + + } + // General Cron Report on system.log + } + } + else{ + $this->_logger->addInfo("Feedaty | Cronjob is not enabled. Configure it from admin panel | date: ". date('Y-m-d H:i:s') ); + } + + } + + + protected function createProductReview($productId, $feedatyId, $feedatyProductReviewId, $rating, $detail, $createdAt, $today, $row, $storeView) + { + + $ratingCollection = $this->_reviewsHelper->getRatingCollection(); + + foreach ($ratingCollection as $ratingItem){ + + $reviewFinalData['ratings'][$ratingItem['rating_id']] = $rating; + } + + $reviewFinalData['nickname'] = "Feedaty"; + $reviewFinalData['title'] = "Acquirente Verificato"; + $reviewFinalData['detail'] = $detail; + $reviewFinalData['feedaty_source'] = 1; + $reviewFinalData['feedaty_pagination'] = $row; + $reviewFinalData['feedaty_source_id'] = $feedatyId; + $reviewFinalData['feedaty_product_review_id'] = $feedatyProductReviewId; + $reviewFinalData['feedaty_create'] = $today; + $reviewFinalData['feedaty_update'] = $today; + $reviewFinalData['feedaty_product_mediated'] = 0; + $review = $this->_reviewFactory->create()->setData($reviewFinalData); + + $review->unsetData('review_id'); + $review->setEntityId($review->getEntityIdByCode(\Magento\Review\Model\Review::ENTITY_PRODUCT_CODE)) + ->setEntityPkValue($productId) + ->setStatusId(\Magento\Review\Model\Review::STATUS_APPROVED) + ->setStoreId(Store::DEFAULT_STORE_ID) + ->setStores(!is_null($storeView) ? [$storeView] : [$this->_storeManager->getStore()->getId()]) + ->setCustomerId(null) + ->save(); + + foreach ($reviewFinalData['ratings'] as $ratingId => $ratingValue) { + + $this->_ratingFactory->create() + ->setRatingId($ratingId) + ->setReviewId($review->getId()) + ->addOptionVote($ratingValue, $productId); + } + + $review->aggregate(); + + $review->setCreatedAt($createdAt)->save(); + } +} + diff --git a/Helper/ConfigRules.php b/Helper/ConfigRules.php index 73d53f8..80abf64 100644 --- a/Helper/ConfigRules.php +++ b/Helper/ConfigRules.php @@ -4,7 +4,7 @@ use Magento\Framework\App\Helper\AbstractHelper; use Magento\Store\Model\ScopeInterface; -use \Feedaty\Badge\Helper\ConfigSetting; +use Feedaty\Badge\Helper\ConfigSetting; class ConfigRules extends AbstractHelper { @@ -40,6 +40,10 @@ public function getPreferencesConfig($data){ return $this->helperConfigSetting->getPreferencesConfig($data); } + public function getSendOrderConfig($data){ + return $this->helperConfigSetting->getSendOrderConfig($data); + } + /** * Get Feedaty Merch Code * @@ -62,4 +66,32 @@ public function getFeedatySecret() { return $feedaty_code; } + /** + * @return array + */ + public function getCreateReviewEnabled() { + $feedaty_code = $this->getPreferencesConfig('create_reviews_enabled'); + + return $feedaty_code; + } + + public function getReviewForceDefaultStore() + { + $force_store = $this->getPreferencesConfig('create_reviews_force_default_store'); + return $force_store; + } + + public function getReviewDefaultStore() + { + $default_store = $this->getPreferencesConfig('create_reviews_default_store'); + return $default_store; + } + + + public function getSendOrderStatus() + { + $orderStatus = $this->getSendOrderConfig('sendorder'); + return $orderStatus; + } + } diff --git a/Helper/ConfigSetting.php b/Helper/ConfigSetting.php index 706634a..4ef0358 100644 --- a/Helper/ConfigSetting.php +++ b/Helper/ConfigSetting.php @@ -26,10 +26,22 @@ public function getConfigValue($field, $storeId = null) * @param $code * @param null $storeId * @return mixed + * Get Admin Preferences Configurations */ public function getPreferencesConfig($code, $storeId = null) { return $this->getConfigValue(self::XML_PATH_FEEDATY .'feedaty_preferences/'. $code, $storeId); } + /** + * @param $code + * @param null $storeId + * @return mixed + * Get Admin Send Order Configurations + */ + public function getSendOrderConfig($code, $storeId = null) + { + return $this->getConfigValue(self::XML_PATH_FEEDATY .'feedaty_sendorder/'. $code, $storeId); + } + } diff --git a/Helper/Orders.php b/Helper/Orders.php new file mode 100644 index 0000000..fe5ce31 --- /dev/null +++ b/Helper/Orders.php @@ -0,0 +1,232 @@ +logger = $logger; + $this->orderRepository = $orderRepository; + $this->helperConfigRules = $helperConfigRules; + $this->scopeConfig = $scopeConfig; + $this->searchCriteriaBuilder = $searchCriteriaBuilder; + $this->productMetadata = $productMetadata; + $this->feedatyOrderModel = $feedatyOrderModel; + $this->feedatyOrderResourceModel = $feedatyOrderResourceModel; + $this->orderFactory = $orderFactory; + } + + /** + * @return false|string + */ + public function getOrderFromDate(){ + + // $fromDate = date('Y-m-d H:i:s', strtotime('-3 hour')); + $fromDate = date('Y-m-d H:i:s', strtotime('-30 week')); + + return $fromDate; + } + + /** + * @param $storeId + * @return string + */ + public function getCulture($storeId) : string + { + $locale = $this->scopeConfig->getValue('general/locale/code', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId); + $culture = strtok($locale, '_'); + $allowedLanguages = array("it", "en", "es", "fr", "de"); + + //Set default language fallback + if (!in_array($culture, $allowedLanguages)) { + $this->logger->warning('Feedaty | Culture not found | Set default language fallback for '. $culture); + $culture = "en"; + } + + return $culture; + } + + /** + * @return array|\Magento\Sales\Api\Data\OrderInterface[] + */ + public function getOrders() + { + $orders = []; + $status = $this->getOrderstatus(); + $ordersNotified = $this->getFeedatyOrdersNotified(); + if(empty($ordersNotified)){ + $ordersNotified[] = 0; + } + try { + $criteria = $this->searchCriteriaBuilder + ->addFilter('status',$status,'eq') + ->addFilter('entity_id', $ordersNotified, 'nin') + ->setPageSize(500) + ->setCurrentPage(1) + ->create(); + $orderResult = $this->orderRepository->getList($criteria); + + $orders = $orderResult->getItems(); + + } catch (\Exception $e) { + $this->logger->critical('Feedaty | Error - Cannot get orders - '. $e->getMessage()); + } + + return $orders; + } + + /** + * @return string + * Get Order Status from Feedaty Configurations or set a default value + */ + public function getOrderstatus() : string + { + $status = 'processing'; + try { + $status = $this->helperConfigRules->getSendOrderStatus(); + } catch (\Exception $e) { + $this->logger->critical('Feedaty | Error - Cannot find send order status configuration. Set order status complete as default value - '. $e->getMessage()); + } + + return $status; + } + + public function getFeedatyOrdersNotified() + { + $ordersNotified = []; + $orders = $this->orderFactory->create()->getCollection(); + + foreach($orders as $order){ + $ordersNotified[] = $order->getOrderId(); + } + return $ordersNotified; + } + + /** + * @return string + * Get Magento Edition and Version + */ + public function getPlatform() + { + $platform = $this->productMetadata->getName() . ' ' . $this->productMetadata->getEdition() . ' ' . $this->productMetadata->getVersion(); + return $platform; + } + + /** + * @param $item + * @return string + * Get Product Image URL + */ + public function getProductThumbnailUrl($item) : string + { + $productThumbnailUrl = ''; + try { + $productThumbnail = $item->getProduct()->getImage(); + $productThumbnailUrl = $item->getProduct()->getMediaConfig()->getMediaUrl($productThumbnail); + } catch (\Exception $e) { + $this->logger->critical('Feedaty | Error - Cannot get product thumbnail URL - '. $e->getMessage()); + } + + return $productThumbnailUrl; + } + + /* + * Get Feedaty Customer Notified Orders + */ + + /** + * Set Feedaty Customer Notified Orders + * @param $order + * @throws \Magento\Framework\Exception\AlreadyExistsException + */ + public function setFeedatyCustomerNotified($orderId) + { + $feedatyOrder = $this->orderFactory->create(); + + $feedatyOrder->setOrderId($orderId); + $feedatyOrder->setFeedatyCustomerNotified(1); + + $this->feedatyOrderResourceModel->save($feedatyOrder); + + } + +} diff --git a/Helper/Reviews.php b/Helper/Reviews.php new file mode 100644 index 0000000..0016bac --- /dev/null +++ b/Helper/Reviews.php @@ -0,0 +1,304 @@ +_logger = $logger; + $this->_reviewFactory = $reviewFactory; + $this->_ratingFactory = $ratingFactory; + $this->_storeRepository = $storeRepository; + $this->_orderRepository = $orderRepository; + $this->_helperConfigRules = $helperConfigRules; + $this->reviewCollection = $reviewCollection; + $this->ratingCollectionFactory = $ratingCollectionFactory; + } + + /** + * @param $reviewData + * @throws \Exception + */ + public function disableReview($reviewData) + { + $review = null; + try { + $review = $this->_reviewFactory->create()->load($reviewData['review_id']); + } catch (\Exception $e) { + $this->_logger->info("Feedaty | Error can not disable Review : " . $e->getMessage()); + } + + if (!is_null($review)) { + $review->setStatusId(\Magento\Review\Model\Review::STATUS_NOT_APPROVED)->save(); + } + } + + /** + * @param $reviewData + * @param $reviewDetail + */ + public function mediateReview($reviewData, $reviewDetail) + { + $review = null; + try { + $review = $this->_reviewFactory->create()->load($reviewData['review_id']); + } catch (\Exception $e) { + $this->_logger->info("Feedaty | Error cannot mediate Review : " . $e->getMessage()); + } + + if (!is_null($review)) { + $review->setDetail($reviewDetail)->save(); + $review->setFeedatyProductMediated(1)->save(); + } + + } + + /** + * @param $orderId + * @return int|string|null + */ + public function getStoreViewIdByOrder($orderId) + { + $forceDefaultStore = $this->_helperConfigRules->getReviewForceDefaultStore(); + + if($forceDefaultStore === "1"){ + $defaultStore = $this->_helperConfigRules->getReviewDefaultStore(); + return $defaultStore; + } + else{ + $order = null; + try { + $order = $this->_orderRepository->get($orderId); + } + catch (\Exception $e) { + $this->_logger->info("Feedaty | Error : order id does not exist " . $orderId . " Error message". $e->getMessage()); + } + + if (!is_null($order)) { + $websiteId = $order->getStore()->getWebsiteId(); + return $websiteId; + } + + return null; + } + + + } + + /** + * @return array|int + */ + function getAllStoreList() + { + $storeList = $this->_storeRepository->getList(); + + $storeIds = array(); + foreach ($storeList as $store) { + $storeIds = $store->getStoreId(); // store id + } + + return $storeIds; + } + + + /** + * @param $productId + * @param $feedatyId + * @return mixed + */ + public function getReviewCollection($productId, $feedatyId) + { + + $collection = $this->reviewCollection->create() + ->addEntityFilter( + 'product', + $productId + ) + ->addFieldToFilter( + 'feedaty_source_id', + $feedatyId + ) + ->setDateOrder(); + + return $collection->getData(); + + } + + /* + * Get last Review Created + */ + public function getAllFeedatyReviewCount() + { + $collection = $this->reviewCollection->create() + ->addFieldToFilter( + 'feedaty_source', + 1 + ) + ->setOrder( + 'review_id', + 'desc' + ) + ->setDateOrder(); + + return count($collection->getData()); + } + + /** + * @return int|void + */ + public function getAllFeedatyRemovedReviewCount() + { + $collection = $this->reviewCollection->create() + ->addStatusFilter( + \Magento\Review\Model\Review::STATUS_NOT_APPROVED) + ->addFieldToFilter( + 'feedaty_source', + 1 + ) + ->setOrder( + 'review_id', + 'desc' + ) + ->setDateOrder(); + + return count($collection->getData()); + } + + /** + * @return int|void + */ + public function getAllFeedatyMediatedReviewCount() + { + $collection = $this->reviewCollection->create() + ->addFieldToFilter( + 'feedaty_product_mediated', + 1 + ) + ->setOrder( + 'review_id', + 'desc' + ) + ->setDateOrder(); + + return count($collection->getData()); + } + + /* + * Get last Review Created + */ + public function getLastFeedatyReviewCreated() + { + $collection = $this->reviewCollection->create() + ->addFieldToFilter( + 'feedaty_source', + 1 + ) + ->setOrder( + 'review_id', + 'desc' + ) + ->setPageSize(1) + ->setCurPage(1) + ->setDateOrder(); + + return $collection->getData(); + } + + + /** + * @param $feedatyId + * @return mixed + */ + public function getAllReviewsByFeedatyId($feedatyId) + { + $collection = $this->reviewCollection->create() + ->addFieldToFilter( + 'feedaty_product_review_id', + $feedatyId + ) + ->setOrder( + 'review_id', + 'desc' + ) + ->setDateOrder(); + + return $collection->getData(); + } + + /** + * @return array|null + */ + public function getRatingCollection() + { + $ratingCollection = $this->ratingCollectionFactory->create() + ->addEntityFilter('product') + ->load(); + + return $ratingCollection->getData(); + } + + +} diff --git a/Helper/WidgetHelper.php b/Helper/WidgetHelper.php new file mode 100755 index 0000000..ad1b258 --- /dev/null +++ b/Helper/WidgetHelper.php @@ -0,0 +1,86 @@ +scopeConfig = $scopeConfig; + $this->storeManager = $storeManager; + $this->_dataHelper = $dataHelper; + $this->_request = $request; + $this->_fdservice = $fdservice; + } + + /** + * + * @return $return + */ + public function badgeData($type) + { + + $return = array(); + + $store_scope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; + + $store = $this->storeManager->getStore($this->_request->getParam('store',0)); + + $merchant_code = $store->getConfig('feedaty_global/feedaty_preferences/feedaty_code'); + + if ($this->_request->getParam('store', 0) == 0) { + + $merchant_code = $this->scopeConfig->getValue('feedaty_global/feedaty_preferences/feedaty_code', $store_scope); + + } + + if (strlen($merchant_code) == 0) { + + return array(); + + } + + $dataObject = $this->_fdservice->getFeedatyData($merchant_code); + + $data = $dataObject[$type]['variants']; + + if($data) { + + foreach ($data as $k => $v) { + + $return[] = ['value' => $k,'label' => $v['name_shown_it-IT']]; + + } + + } + + return $return; + } +} diff --git a/Model/Config/Source/FeedatyTimeout.php b/Model/Config/Source/FeedatyTimeout.php deleted file mode 100644 index 729df41..0000000 --- a/Model/Config/Source/FeedatyTimeout.php +++ /dev/null @@ -1,23 +0,0 @@ - "250","label" => __("250 ms")], - ["value" => "500","label" => __("500 ms")], - ["value" => "1000","label" => __("1000 ms")], - ["value" => "2000","label" => __("2 s")], - ["value" => "3000","label" => __("3 s")], - ["value" => "20000","label" => __("20 s")], - ["value" => "50000","label" => __("50 s")], - ["value" => "100000","label" => __("100 s")] - ]; - - return $return; - } -} diff --git a/Model/Config/Source/PositionProduct.php b/Model/Config/Source/PositionProduct.php deleted file mode 100755 index e4c2883..0000000 --- a/Model/Config/Source/PositionProduct.php +++ /dev/null @@ -1,37 +0,0 @@ -"content","label"=>__("After Content")], - ["value"=>"catalog.product.related","label"=>__("Product Related")], - ["value"=>"productalert.price","label"=>__("After Price")], - ["value"=>"productalert.stock","label"=>__("After Stock Informations")], - ["value"=>"product.info.simple","label"=>__("Simple")], - ["value"=>"product.info.simple.extra.child0","label"=>__("Extra child")], - ["value"=>"product.info.addtocart","label"=>__("Add to cart")], - ["value"=>"product.description","label"=>__("Product description")], - ["value"=>"product.attributes","label"=>__("Product attributes")], - ["value"=>"product.info.upsell","label"=>__("Product upsell")], - ["value"=>"product.info.product_additional_data","label"=>__("Product additional")], - ["value"=>"product_tag_list","label"=>__("Product tag list")], - ["value"=>"product.info.review","label"=>__("Product Info - Review")], - ["value"=>"product.review.form","label"=>__("Product Review - Form")], - ["value"=>"product.reviews","label"=>__("Product Reviews")] - - ]; - return $return; - } -} diff --git a/Model/Config/Source/ProdVariants.php b/Model/Config/Source/ProdVariants.php deleted file mode 100644 index 7d225a3..0000000 --- a/Model/Config/Source/ProdVariants.php +++ /dev/null @@ -1,82 +0,0 @@ -scopeConfig = $scopeConfig; - $this->storeManager = $storeManager; - $this->_dataHelper = $dataHelper; - $this->_request = $request; - $this->_fdservice = $fdservice; - } - - public function toOptionArray() - { - $store_scope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; - $store = $this->storeManager->getStore($this->_request->getParam('store', 0)); - $merchant_code = $store->getConfig('feedaty_global/feedaty_preferences/feedaty_code'); - $plugin_enabled = $this->scopeConfig->getValue('feedaty_badge_options/widget_products/prod_enabled', $store_scope); - $badge_style = $this->scopeConfig->getValue('feedaty_badge_options/widget_products/prod_style', $store_scope); - $return = array(); - - if($this->_request->getParam('store', 0) == 0) - { - $merchant_code = $this->scopeConfig->getValue('feedaty_global/feedaty_preferences/feedaty_code', $store_scope); - } - - if (strlen($merchant_code > 0)) { - - - $data = $this->_fdservice->getFeedatyData($merchant_code); - - if($data) { - - foreach ($data as $k => $v) { - - if ($k == $badge_style) { - - foreach ($v['variants'] as $key => $value) { - - $return[] = ['value' => $key,'label' => $value]; - - } - - } - } - } - - } - - return $return; - - } -} diff --git a/Model/Config/Source/ProductBadgeStyle.php b/Model/Config/Source/ProductBadgeStyle.php new file mode 100644 index 0000000..6648ab3 --- /dev/null +++ b/Model/Config/Source/ProductBadgeStyle.php @@ -0,0 +1,18 @@ + "product","label" => __("Product Badge Style")], + ["value" => "carouselproduct","label" => __("Product Carousel Badge Style")], + ["value" => "product_tab","label" => __("Product Tab Badge Style")], + ]; + + return $return; + } +} diff --git a/Model/Config/Source/FeedatyOrder.php b/Model/Config/Source/StoreBadgeStyle.php old mode 100755 new mode 100644 similarity index 50% rename from Model/Config/Source/FeedatyOrder.php rename to Model/Config/Source/StoreBadgeStyle.php index 542c589..98cc9ac --- a/Model/Config/Source/FeedatyOrder.php +++ b/Model/Config/Source/StoreBadgeStyle.php @@ -1,17 +1,17 @@ - "0","label" => __("Newest reviews first")], - ["value" => "1","label" => __("Old reviews first")], - ]; - - return $return; - } -} + "merchant","label" => __("Merchant Badge Style")], + ["value" => "carousel","label" => __("Carousel Badge Style")] + ]; + + return $return; + } +} diff --git a/Model/Config/Source/StyleProduct.php b/Model/Config/Source/StyleProduct.php index 84180ab..d952cc6 100755 --- a/Model/Config/Source/StyleProduct.php +++ b/Model/Config/Source/StyleProduct.php @@ -1,88 +1,31 @@ -scopeConfig = $scopeConfig; - $this->storeManager = $storeManager; - $this->_dataHelper = $dataHelper; - $this->_request = $request; - $this->_fdservice = $fdservice; - } - - /** - * - * @return $return - */ - public function toOptionArray() - { - - $return = array(); - - $store_scope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; - - $store = $this->storeManager->getStore($this->_request->getParam('store',0)); - - $merchant_code = $store->getConfig('feedaty_global/feedaty_preferences/feedaty_code'); - - if ($this->_request->getParam('store', 0) == 0) { - - $merchant_code = $this->scopeConfig->getValue('feedaty_global/feedaty_preferences/feedaty_code', $store_scope); - - } - - if (strlen($merchant_code) == 0) { - - return array(); - - } - - $data = $this->_fdservice->getFeedatyData($merchant_code); - - if($data) { - - foreach ($data as $k => $v) { - - if ( $v['type'] == "product" && $v['name'] != "dynamicprod" ) { - - $return[] = ['value' => $k,'label' => $v['name']]; - - } - - } - - } - - return $return; - } -} +_widgetHelper = $widgetHelper; + } + + /** + * @return array + */ + public function toOptionArray() + { + return $this->_widgetHelper->badgeData('product'); + } +} diff --git a/Model/Config/Source/StyleProductCarousel.php b/Model/Config/Source/StyleProductCarousel.php new file mode 100755 index 0000000..17b0e07 --- /dev/null +++ b/Model/Config/Source/StyleProductCarousel.php @@ -0,0 +1,31 @@ +_widgetHelper = $widgetHelper; + } + + /** + * @return array + */ + public function toOptionArray() + { + return $this->_widgetHelper->badgeData('carouselproduct'); + } +} diff --git a/Model/Config/Source/StyleProductTab.php b/Model/Config/Source/StyleProductTab.php new file mode 100755 index 0000000..0b0eeca --- /dev/null +++ b/Model/Config/Source/StyleProductTab.php @@ -0,0 +1,31 @@ +_widgetHelper = $widgetHelper; + } + + /** + * @return array + */ + public function toOptionArray() + { + return $this->_widgetHelper->badgeData('product_tab'); + } +} diff --git a/Model/Config/Source/StyleStore.php b/Model/Config/Source/StyleStore.php index 17fea85..52c590d 100755 --- a/Model/Config/Source/StyleStore.php +++ b/Model/Config/Source/StyleStore.php @@ -1,90 +1,31 @@ scopeConfig = $scopeConfig; - $this->storeManager = $storeManager; - $this->_dataHelper = $dataHelper; - $this->_request = $request; - $this->_fdservice = $fdservice; + $this->_widgetHelper = $widgetHelper; } /** - * - * @return $return - */ - public function toOptionArray() { - - $return = array(); - - $store_scope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; - - $store = $this->storeManager->getStore($this->_request->getParam('store', 0)); - - $merchant_code = $store->getConfig('feedaty_global/feedaty_preferences/feedaty_code'); - - if($this->_request->getParam('store', 0) == 0) { - - $merchant_code = $this->scopeConfig->getValue('feedaty_global/feedaty_preferences/feedaty_code', $store_scope); - - } - - if (strlen($merchant_code == 0)) { - - return $return; - - } - - $data = $this->_fdservice->getFeedatyData($merchant_code); - - - - if($data) { - - - // get Badges - foreach ($data as $k => $v) { - - // if ($v['type'] == "merchant" && $v['name'] != "dynamic" ) { - if ($v['type'] == "merchant" ) { - $return[] = ['value' => $k,'label' => $v['name_shown_it-IT']]; - - } - - } - - } - - return $return; + * @return array + */ + public function toOptionArray() + { + return $this->_widgetHelper->badgeData('merchant'); } } diff --git a/Model/Config/Source/StyleStoreCarousel.php b/Model/Config/Source/StyleStoreCarousel.php new file mode 100755 index 0000000..1bcdb97 --- /dev/null +++ b/Model/Config/Source/StyleStoreCarousel.php @@ -0,0 +1,31 @@ +_widgetHelper = $widgetHelper; + } + + /** + * @return array + */ + public function toOptionArray() + { + return $this->_widgetHelper->badgeData('carousel'); + } +} diff --git a/Model/Config/Source/WebService.php b/Model/Config/Source/WebService.php index a342a02..c9fed4e 100755 --- a/Model/Config/Source/WebService.php +++ b/Model/Config/Source/WebService.php @@ -1,142 +1,160 @@ _scopeConfig = $scopeConfig; - $this->_storeManager = $storeManager; - $this->_feedatyHelper = $feedatyHelper; - $this->_curl = $curl; - $this->_objectManager = $objectmanager; - $this->_curl->setOption(CURLOPT_FOLLOWLOCATION, 1); - $this->_curl->setOption(CURLOPT_RETURNTRANSFER, 1); - $this->_curl->setOption(CURLOPT_VERBOSE, false); - $this->_json = $json; $this->_configRules = $configRules; $this->_logger = $logger; + $this->curlFactory = $curlFactory; + $this->cache = $cache; + $this->resolver = $resolver; + $this->serializer = $serializer; + $this->productMetadata = $productMetadata; + $this->moduleList = $moduleList; + $this->storeManager = $storeManager; + } - $timeout = $this->_scopeConfig->getValue( - 'feedaty_global/timeout_connection/timeout', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - ); - - $timeout = $timeout == null ? "1000" : $timeout; - $this->_curl->setOption(CURLOPT_CONNECTTIMEOUT_MS, $timeout); - $this->_curl->setOption(CURLOPT_TIMEOUT_MS, $timeout); + /* + * JSON encode + */ + public function jsonEncode($data) + { + return $this->serializer->serialize($data); } + /* + * JSON decode + */ + public function jsonDecode($string) + { + return $this->serializer->unserialize($string); + } /** - * @param $result - * @return array|bool|float|int|mixed|string|null + * @return array */ - public function unserializeJson($result) + private function getReqToken() { - $jsonDecode = $this->_json->unserialize($result); + $url = "http://api.feedaty.com/OAuth/RequestToken"; + try { + $curl = $this->curlFactory->create(); + $curl->addHeader('Content-Type', 'application/x-www-form-urlencoded'); + $curl->setTimeout(1000); + $curl->get($url); + $response = $this->jsonDecode($curl->getBody()); + } catch (\Exception $exception) { + $response = []; + $this->_logger->critical('Feedaty | Error cannot get Request Token: '.$exception); + } - return $jsonDecode; + return $response; } + + /** - * Function getReqToken - get the request token - * - * @return $response - * - */ - private function getReqToken(){ + * Send Order + * @param $data + * @return array|bool|float|int|string|null + */ + public function sendOrder($data) { - $url = "http://api.feedaty.com/OAuth/RequestToken"; - $this->_curl->addHeader('Content-Type','application/x-www-form-urlencoded'); - $this->_curl->get($url); + $url = 'http://api.feedaty.com/Orders/Insert'; - $response = json_decode($this->_curl->getBody()); + $token = $this->getReqToken(); + $accessToken = $this->getAccessToken($token); + $this->_logger->info('Feedaty | START Cronjob SendOrder'); + try { + $curl = $this->curlFactory->create(); + $curl->addHeader('Content-Type', 'application/json'); + $curl->addHeader( 'Authorization', 'Oauth '. $accessToken['AccessToken']); + $curl->setTimeout(1000); + $curl->post($url,$this->jsonEncode($data)); + $response = $this->jsonDecode($curl->getBody()); + } catch (\Exception $exception) { + $response = []; + $this->_logger->critical('Feedaty | Error cannot send order to Feedaty API: '.$exception); + } return $response; - } - /** - * Function serializeData - serialize data to send - * - * @param $fields - * - * @return $dati - */ - private function serializeData($fields){ - $data = ''; - foreach($fields as $k => $v){ - $data .= $k . '=' . urlencode($v) . '&'; - } - $data = rtrim($data, '&'); - return $data; } + /** * Function getAccessToken - get the access token * @@ -144,23 +162,33 @@ private function serializeData($fields){ * * @return $response - the access token */ - private function getAccessToken($token,$merchant,$secret) { + private function getAccessToken($token) { + + $merchant = $this->_configRules->getFeedatyCode(); + $secret = $this->_configRules->getFeedatySecret(); $encripted_code = $this->encryptToken($token,$merchant,$secret); $url = "http://api.feedaty.com/OAuth/AccessToken"; - $this->_curl->addHeader("Content-Type","application/x-www-form-urlencoded"); - $this->_curl->addHeader("Authorization", "Basic " . $encripted_code); - $this->_curl->addHeader("User-Agent","Mage2"); + try { + $curl = $this->curlFactory->create(); + $curl->addHeader('Content-Type', 'application/x-www-form-urlencoded'); + $curl->addHeader( 'Authorization', 'Basic ' . $encripted_code); + $curl->addHeader( 'User-Agent', 'Mage2'); - $fields = [ - 'oauth_token' => $token->RequestToken, - 'grant_type'=>'authorization' - ]; + $data = [ + 'oauth_token' => $token['RequestToken'], + 'grant_type'=>'authorization' + ]; + $curl->post($url,$data); - $this->_curl->post($url,$fields); - $response = $this->_curl->getBody(); + $response = $this->jsonDecode($curl->getBody()); + + } catch (\Exception $exception) { + $response = []; + $this->_logger->critical('Feedaty | Error cannot get Access Token: '.$exception); + } return $response; } @@ -175,305 +203,249 @@ private function getAccessToken($token,$merchant,$secret) { * @return $base64_sha_token - the encrypted token */ private function encryptToken($token, $merchant, $secret){ - $sha_token = sha1($token->RequestToken.$secret); + $sha_token = sha1($token['RequestToken'].$secret); $base64_sha_token = base64_encode($merchant.":".$sha_token); return $base64_sha_token; } + /** - * Function retriveInformationsProduct - * - * @param int $id - * - */ - public function retriveInformationsProduct($feedaty_code, $id) { + * @param int $row + * @param int $count + * @return mixed|string + */ + public function getProductReviewsPagination($row = 0, $count = 50){ + $allReviews = $this->getAllReviews('?retrieve=onlyproductreviews&row='.$row.'&count='.$count); + return $allReviews['Reviews']; + } - $cache = $this->_objectManager->get('Magento\Framework\App\CacheInterface'); - $timeout = $this->_scopeConfig->getValue( - 'feedaty_global/timeout_widgets/timeout', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - ); + /** + * @param int $row + * @param int $count + * @return mixed + */ + public function getRemovedReviews($row = 0, $count = 50){ + $allReviews = $this->getAllRemovedReviews('?row='.$row.'&count='.$count); + return $allReviews['Reviews']; + } - $cache_key = "feedaty_product_tab_".$feedaty_code . "PID=" .$id; + /** + * @param int $row + * @param int $count + * @return mixed + */ + public function getMediatedReviews($row = 0, $count = 50){ + $allReviews = $this->getAllMediatedReviews('?row='.$row.'&count='.$count); + return $allReviews['Reviews']; - $content = $cache->load($cache_key); + } - if (!$content || strlen($content) == 0 || $content === "null") - { - $ch = curl_init(); + /** + * @return mixed|string + */ + public function getTotalProductReviewsCount() + { + $allProductReviews = $this->getAllReviews('?retrieve=onlyproductreviews&row=0&count=1'); + $totalResults = $allProductReviews['TotalProductReviews']; - $resolver = $this->_objectManager->get('Magento\Framework\Locale\Resolver'); + return $totalResults; + } - $url = 'http://widget.zoorate.com/go.php?function=feed&action=ws&task=product&merchant_code='.$feedaty_code.'&ProductID='.$id.'&language='.$resolver->getLocale(); + /** + * Get Removed Reviews Count + * @return mixed + */ + public function getTotalProductRemovedReviewsCount() + { + $allProductReviews = $this->getAllRemovedReviews('?row=0&count=1'); + $totalResults = $allProductReviews['TotalResults']; - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); - $content = trim(curl_exec($ch)); - curl_close($ch); + return $totalResults; + } - if (strlen($content) > 0) - { - // 24 hours of cache - $cache->save($content, $cache_key, array("feedaty_cache"), 24*60*60); - } - } + /** + * Get Mediated Reviews Count + * @return mixed + */ + public function getTotalProductMediatedReviewsCount() + { + $allProductReviews = $this->getAllMediatedReviews('?row=0&count=1'); + $totalResults = $allProductReviews['TotalResults']; - $data = json_decode($content, true); + return $totalResults; + } - return $data; + /** + * Get All Removed Reviews + * @param string $params + * @return mixed|null + */ + public function getAllRemovedReviews($params = '') + { + $url = 'http://api.feedaty.com/Reviews/Removed'.$params; + return $this->getReviewsData($url); } /** - * @param $productId - * @return mixed|string|null - * @todo : complete function and use to save data in db + * Get All Mediated Reviews + * @param string $params + * @return mixed|null */ - public function getProductReviews($productId){ - return $this->getAllReviews('?retrieve=onlyproductreviews&sku='.$productId); + public function getAllMediatedReviews($params = '') + { + $url = 'http://api.feedaty.com/Reviews/Mediated'.$params; + $mediated = $this->getReviewsData($url); + return $mediated; } /** + * Get all reviews * @param string $params - * @return mixed|string|null - * @todo : complete function and use to save data in db + * @return mixed|null */ public function getAllReviews($params = '') { - $merchant = $this->_configRules->getFeedatyCode(); - $secret = $this->_configRules->getFeedatySecret(); $url = 'http://api.feedaty.com/Reviews/Get'.$params; - - $token = ''; - - try { - $token = $this->getReqToken(); - if ($token != '') { - $accessToken =json_decode($this->getAccessToken($token, $merchant, $secret)); - - $timeout = $this->_scopeConfig->getValue( - 'feedaty_global/timeout_connection/timeout', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - ); - - $this->_curl->addHeader("Content-Type", "application/x-www-form-urlencoded"); - $this->_curl->addHeader("Authorization", 'Oauth '.$accessToken->AccessToken); - $this->_curl->setTimeout($timeout); - try { - $this->_curl->get($url); - } catch (\Exception $e) { - $this->_logger->critical('Feedaty log: '. $e->getMessage()); - } - - // output of curl request - $result = $this->_curl->getBody(); - - $data = $this->unserializeJson($result); - - $reviews = $data['Data']['Reviews']; - - return $reviews; - } - } catch (\Exception $e) { - $this->_logger->critical('Feedaty log: '. $e->getMessage()); - } - - return null; + return $this->getReviewsData($url); } - /** - * Function send_order - * - * @param object $data - * - */ - public function send_order($merchant, $secret, $data) { - - $store_scope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; - - $timeout = $this->_scopeConfig->getValue( - 'feedaty_global/timeout_orders/timeout', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - ); - $ch = curl_init(); - - $url = 'http://api.feedaty.com/Orders/Insert'; + /** + * Get Reviews Data + * @param $url + * @return array|mixed|null + */ + public function getReviewsData($url) + { + $token = ''; $token = $this->getReqToken(); + if ($token != '') { + $accessToken = $this->getAccessToken($token); + $reviews = []; + try { + $curl = $this->curlFactory->create(); + $curl->addHeader('Content-Type', 'application/x-www-form-urlencoded'); + $curl->addHeader( 'Authorization', 'Oauth '. $accessToken['AccessToken']); + $curl->setTimeout(1000); + $curl->get($url); + $result = $curl->getBody(); + + $data = $this->jsonDecode($result); + $reviews = $data['Data']; + + + } catch (\Exception $e) { + $this->_logger->critical('Feedaty | Error getting Reviews Data: '. $e->getMessage()); + } - $accessToken =json_decode($this->getAccessToken($token, $merchant, $secret)); - - curl_setopt($ch, CURLOPT_URL, $url); - - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - - curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); - - curl_setopt($ch, CURLOPT_POST, 1); - - curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($data)); - - curl_setopt($ch, CURLOPT_HTTPHEADER,['Content-Type: application/json', 'Authorization: Oauth '.$accessToken->AccessToken]); - - curl_setopt($ch, CURLOPT_HEADER, 1); - - curl_setopt($ch, CURLINFO_HEADER_OUT, true); - - $content = trim( curl_exec($ch) ); - - $fdDebugEnabled = $this->_scopeConfig->getValue( 'feedaty_global/debug/debug_enabled', $store_scope ); - - if($fdDebugEnabled != 0) { - - $message = $data; - $this->_feedatyHelper->feedatyDebug($message, "FEEDATY DATA"); - - $message = $content; - $this->_feedatyHelper->feedatyDebug($message, "FEEDATY RESPONSE"); - - $message = curl_getinfo($ch,CURLINFO_HEADER_OUT); - $this->_feedatyHelper->feedatyDebug($message, "CURL HEADER INFO"); - - $message = curl_getinfo($ch,CURLINFO_HEADER_OUT); - $this->_feedatyHelper->feedatyDebug($message, "CURL INFO"); - - if(curl_errno($ch)) - $this->_feedatyHelper->feedatyDebug(curl_error($ch), "CURL ERROR"); - + return $reviews; } - curl_close($ch); - - return 1 ; - + return null; } /** - * Function _get_FeedatyData - * - * @return $data - */ - public function getFeedatyData($feedaty_code) { - - $cache = $this->_objectManager->get('Magento\Framework\App\CacheInterface'); - - $resolver = $this->_objectManager->get('Magento\Framework\Locale\Resolver'); + * Get Feedaty data + * @param $feedaty_code + * @return array|bool|float|int|string|null + */ + public function getFeedatyData($feedaty_code) + { - $timeout = $this->_scopeConfig->getValue( - 'feedaty_global/timeout_widgets/timeout', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - ); + $string = "FeedatyData" . $feedaty_code . $this->resolver->getLocale(); - $string = "FeedatyData" . $feedaty_code . $resolver->getLocale(); + $content = $this->cache->load( $string ); - $content = $cache->load( $string ); + $data = []; if ( !$content || strlen($content) == 0 || $content === "null" ) { - $ch = curl_init(); - - $url = 'http://widget.zoorate.com/go.php?function=feed_v6&action=widget_list&merchant_code='.$feedaty_code; - - curl_setopt($ch, CURLOPT_URL, $url); + $url = 'https://widget.feedaty.com/?action=widget_list&style_ver=2021&merchant='.$feedaty_code; - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + $arrContextOptions=array( + "ssl"=>array( + "verify_peer"=>false, + "verify_peer_name"=>false, + ), + ); - curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); + $content = file_get_contents( $url, false, stream_context_create($arrContextOptions)); - $content = trim(curl_exec($ch)); - - curl_close($ch); - - $cache->save($content, $string, array("feedaty_cache"), 24*60*60); // 24 hours of cache + $this->cache->save($content, $string, array("feedaty_cache"), 24*60*60); // 24 hours of cache } - - $data = json_decode($content, true); + $data = $this->jsonDecode($content); return $data; } - public function getRatings( $merchant, $sku = "null" , $scope = "product" ) { - - $store_scope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; - - $fdDebugEnabled = $this->_scopeConfig->getValue('feedaty_global/debug/debug_enabled', $store_scope); - - $timeout = $this->_scopeConfig->getValue('feedaty_global/timeout_microdata/timeout', $store_scope ); - - $cache_interface = $this->_objectManager->get('Magento\Framework\App\CacheInterface'); - - $cache_key = "feedaty_ratings_". $merchant . "_" . $sku; - - $content = json_decode( $cache_interface->load( $cache_key ), true); - - if ( !$content['data'] || $content['data'] == null ) - { - - $url = 'https://widget.zoorate.com/go.php?function=feed_v6&action=ratings'. - '&scope=' . $scope . - '&sku=' . $sku . - '&merchant=' . $merchant . - '&lang=null' ; - - $header = [ 'Content-Type: text/html','User-Agent: Mage2' ]; - - $ch = curl_init(); - - curl_setopt($ch, CURLOPT_URL, $url); + /** + * @return string + * Get Magento Edition and Version + */ + public function getPlatform() + { + $platform = $this->productMetadata->getName() . ' ' . $this->productMetadata->getEdition() . ' ' . $this->productMetadata->getVersion(); + return $platform; + } - curl_setopt($ch, CURLOPT_HTTPHEADER, $header); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); + public function getModuleVersion() + { + return $this->moduleList->getOne('Feedaty_Badge')['setup_version']; + } - curl_setopt($ch, CURLOPT_RETURNTRANSFER , true); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $timeout); + public function getBaseUrl() + { + return $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB); + } - curl_setopt($ch, CURLOPT_TIMEOUT_MS, $timeout); + public function getStoreName() + { + return $this->storeManager->getStore()->getName(); + } - $content = json_decode( curl_exec($ch), true ); + public function fdSendInstallationInfo() + { - $http_resp = curl_getinfo($ch, CURLINFO_HTTP_CODE); + /* Platform (obviously Magento) and version */ + $fdata['keyValuePairs'][] = array('Key' => 'Platform', 'Value' => $this->getPlatform()); - curl_close($ch); + /* Plugin version */ + $fdata['keyValuePairs'][] = array('Key' => 'Version', 'Value' => $this->getModuleVersion()); - if ($content != null && $http_resp == "200") - { - // 6 hours of cache - $cache_interface->save( + /* Base store url */ + $fdata['keyValuePairs'][] = array('Key' => 'Url', 'Value' => $this->getBaseUrl()); - json_encode($content ,true), - $cache_key, - array("feedaty_cache"), - 24*60*60 + /* Php version */ + $fdata['keyValuePairs'][] = array('Key' => 'Php Version', 'Value' => phpversion()); - ); - } - //debug call + /* Store name */ + $fdata['keyValuePairs'][] = array('Key' => 'Name', 'Value' => $this->getStoreName()); - if($fdDebugEnabled != 0) { + /* Current server date */ + $fdata['keyValuePairs'][] = array('Key' => 'Date', 'Value' => date('c')); - $message = "Rating API response: ".$http_resp." http code"; - $this->_feedatyHelper->feedatyDebug($message, "API RATINGS RESPONSE INFO"); + /* Feedaty Merchant code */ + $fdata['merchantCode'] = $this->_configRules->getFeedatyCode(); - } + try { + $url = 'http://www.zoorate.com/ws/feedatyapi.svc/SetPluginKeyValue'; + $curl = $this->curlFactory->create(); + $curl->addHeader('Content-Type', 'application/json'); + $curl->setTimeout(1000); + $curl->post($url, $this->jsonEncode($fdata)); + } catch (\Exception $e) { + $this->_logger->critical('Feedaty | Error sending Module Information Data: '. $e->getMessage()); } - return $content['data']; - } -} -/* TODO: --Implement magento curl client --Implement new API for product page reviews list --Implement Carousel Section --Implement Popup Section -*/ +} diff --git a/Model/Order.php b/Model/Order.php new file mode 100644 index 0000000..3bc56b5 --- /dev/null +++ b/Model/Order.php @@ -0,0 +1,24 @@ +_init('Feedaty\Badge\Model\ResourceModel\Order'); + } + + public function getIdentities() + { + return [self::CACHE_TAG . '_' . $this->getId()]; + } +} diff --git a/Model/ProductReviews.php b/Model/ProductReviews.php new file mode 100644 index 0000000..f789150 --- /dev/null +++ b/Model/ProductReviews.php @@ -0,0 +1,47 @@ +_storeManager = $storeManager; + $this->_productFactory = $productFactory; + $this->_ratingFactory = $ratingFactory; + $this->_reviewFactory = $reviewFactory; + } + + public function getReviewCollection($productId){ + $collection = $this->_reviewFactory->create() + ->addEntityFilter( + 'product', + $productId + )->setDateOrder(); + } + + public function getRatingCollection(){ + $ratingCollection = $this->_ratingFactory->create() + ->getResourceCollection() + ->addEntityFilter( + 'product' + )->setPositionOrder()->setStoreFilter( + $this->_storeManager->getStore()->getId() + )->addRatingPerStoreName( + $this->_storeManager->getStore()->getId() + )->load(); + + return $ratingCollection->getData(); + } + +} diff --git a/Model/ResourceModel/Order.php b/Model/ResourceModel/Order.php new file mode 100644 index 0000000..0fc822a --- /dev/null +++ b/Model/ResourceModel/Order.php @@ -0,0 +1,13 @@ +_init('feedaty_orders', 'feedaty_orders_id'); + } + +} diff --git a/Model/ResourceModel/Order/Collection.php b/Model/ResourceModel/Order/Collection.php new file mode 100644 index 0000000..0718588 --- /dev/null +++ b/Model/ResourceModel/Order/Collection.php @@ -0,0 +1,19 @@ +_init('Feedaty\Badge\Model\Order', 'Feedaty\Badge\Model\ResourceModel\Order'); + } + +} diff --git a/Model/ResourceModel/Review.php b/Model/ResourceModel/Review.php new file mode 100644 index 0000000..39544b2 --- /dev/null +++ b/Model/ResourceModel/Review.php @@ -0,0 +1,74 @@ +getConnection(); + /** + * save detail + */ + $detail = [ + 'title' => $object->getTitle(), + 'detail' => $object->getDetail(), + 'nickname' => $object->getNickname(), + 'feedaty_source' => $object->getFeedatySource(), + 'feedaty_source_id' => $object->getFeedatySourceId(), + 'feedaty_product_review_id' => $object->getFeedatyProductReviewId(), + 'feedaty_pagination' => $object->getFeedatyPagination(), + 'feedaty_create' => $object->getFeedatyCreate(), + 'feedaty_update' => $object->getFeedatyUpdate(), + 'feedaty_product_mediated' => $object->getFeedatyProductMediated(), + ]; + $select = $connection->select()->from($this->_reviewDetailTable, 'detail_id')->where('review_id = :review_id'); + $detailId = $connection->fetchOne($select, [':review_id' => $object->getId()]); + + if ($detailId) { + $condition = ["detail_id = ?" => $detailId]; + $connection->update($this->_reviewDetailTable, $detail, $condition); + } else { + $detail['store_id'] = $object->getStoreId(); + $detail['customer_id'] = $object->getCustomerId(); + $detail['review_id'] = $object->getId(); + $connection->insert($this->_reviewDetailTable, $detail); + } + + /** + * save stores + */ + $stores = $object->getStores(); + if (!empty($stores)) { + $condition = ['review_id = ?' => $object->getId()]; + $connection->delete($this->_reviewStoreTable, $condition); + + $insertedStoreIds = []; + foreach ($stores as $storeId) { + if (in_array($storeId, $insertedStoreIds)) { + continue; + } + + $insertedStoreIds[] = $storeId; + $storeInsert = ['store_id' => $storeId, 'review_id' => $object->getId()]; + $connection->insert($this->_reviewStoreTable, $storeInsert); + } + } + + // reaggregate ratings, that depend on this review + $this->_aggregateRatings($this->_loadVotedRatingIds($object->getId()), $object->getEntityPkValue()); + + return $this; + } +} diff --git a/Observer/InterceptOrder.php b/Observer/InterceptOrder.php deleted file mode 100644 index cf378bc..0000000 --- a/Observer/InterceptOrder.php +++ /dev/null @@ -1,317 +0,0 @@ -_scopeConfig = $scopeConfig; - $this->_storeManager = $storeManager; - $this->_storeConfigInterface = $storeConfigInterface; - $this->_imageHelper = $imageHelper; - $this->_fdservice = $fdservice; - $this->_objectManager = $objectmanager; - $this->_state = $state; - $this->_orderInterface = $orderInterface; - $this->_feedatyHelper = $feedatyHelper; - } - - /** - * Function execute - * - * @param $observer - */ - public function execute( \Magento\Framework\Event\Observer $observer ) { - - $increment_id = $observer->getEvent()->getOrder()->getIncrementId(); - - try { - - $order = $this->_orderInterface->loadByIncrementId( $increment_id ); - - $store_id = $order->getStoreId(); - - $store = $store_id == null ? $this->_storeManager->getStore() : $this->_storeManager->getStore($store_id); - - - $culture_code = $store->getConfig('general/locale/code'); - - - - $orderopt = $store->getConfig('feedaty_global/feedaty_sendorder/sendorder'); - - if( $order !== null && $order->getStatus() == $orderopt ) { - - $order_id = $order->getId(); - - $merchant = $store->getConfig('feedaty_global/feedaty_preferences/feedaty_code'); - - $secret = $store->getConfig('feedaty_global/feedaty_preferences/feedaty_secret'); - - $fdDebugEnabled = $store->getConfig('feedaty_global/debug/debug_enabled'); - - - - $verify = 0; - - if($fdDebugEnabled != 0) { - - $message = "MerchantCode: ".$merchant." MerchantSecret: ".$secret. "OrderID: " . $order_id; - - $this->_feedatyHelper->feedatyDebug( - $message, - "FEEDATY OBSERVER DATA" - ); - - } - - foreach ( ($order->getAllStatusHistory() ) as $orderComment ) { - - if ( $orderComment->getStatus() === $orderopt ) - - $verify++; - - } - - if ( $verify <= 1 ) { - - $baseurl_store = $store->getBaseUrl( UrlInterface::URL_TYPE_LINK ); - - // errore - $objproducts = $order->getAllItems() ; - - $objproducts = empty($objproducts) ? $order->getItems() : $objproducts ; - - if( !empty($objproducts) ) { - - unset($fd_products); - - foreach ( $objproducts as $itemId => $item ) { - - unset($tmp); - - if ( !$item->getParentItem() ) { - - //TODO ASSESMENT: Use factories - //https://magento.stackexchange.com/questions/91997/magento-2-how-to-retrieve-product-informations/113038#113038 - - $orderProduct = $this->_objectManager->create('Magento\Catalog\Model\Product')->load((int) $item->getProductId()); - - $tmp['SKU'] = $item->getProductId(); - - $tmp['URL'] = $orderProduct->getUrlModel()->getUrl($orderProduct); - - //$tmp['EAN'] = $item->getCustomAttribute('ean'); - - //get the image url - if ( $orderProduct->getImage() != "no_selection" ) { - - $tmp['ThumbnailURL'] = $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product' . $orderProduct->getImage(); - } - - else { - - $tmp['ThumbnailURL'] = ""; - - } - - $tmp['Name'] = $item->getName(); - - $tmp['Brand'] = $item->getBrand(); - - if ($tmp['Brand'] === null) $tmp['Brand'] = ""; - - $fd_products[] = $tmp; - - } - - //configurable and bundle products - else { - - $parentProductID = $item->getParentItem()->getProductId(); - - $childProductID = $item->getProductId(); - - $parentProduct = $this->_objectManager->create('Magento\Catalog\Model\Product') - ->load( (int) $parentProductID ); - - $childProduct = $this->_objectManager->create('Magento\Catalog\Model\Product') - ->load( (int) $childProductID ); - - - $tmp['SKU'] = $parentProductID; - - $tmp['URL'] = $parentProduct->getUrlModel()->getUrl($parentProduct); - - //$tmp['EAN'] = $childProduct->getCustomAttribute('ean'); - - //get the image url - if ($childProduct->getImage() != "no_selection") { - - $tmp['ThumbnailURL'] = $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product' . $childProduct->getImage(); - } - - else { - - $tmp['ThumbnailURL'] = ""; - - } - - $tmp['Name'] = $parentProduct->getName(); - - $tmp['Brand'] = $parentProduct->getBrand(); - - if ($tmp['Brand'] === null) $tmp['Brand'] = ""; - - $this->_feedatyHelper->feedatyDebug( - - json_encode($tmp), - "FEEDATY configurable Product: " - - ); - - $fd_products[] = $tmp; - - } - - } - - $cultures = explode( "_", $culture_code ); - - $culture = $cultures[0]; - - $allowedLanguages = array("it", "en", "es", "fr","de"); - if (!in_array($culture, $allowedLanguages)) { - $culture = 'en'; - } - - $mageMetadata = $this->_objectManager->get('Magento\Framework\App\ProductMetadataInterface'); - - // Formatting the array to be sent - $tmp_order['ID'] = $order->getId(); - - $tmp_order['Date'] = date("Y-m-d H:i:s"); - - $tmp_order['CustomerEmail'] = $order->getCustomerEmail(); - - $tmp_order['CustomerID'] = $order->getCustomerEmail(); - - $tmp_order['Culture'] = $culture; - - $tmp_order['Platform'] = "Magento ".$mageMetadata->getVersion(); - - $tmp_order['Products'] = $fd_products; - - $fd_data[] = $tmp_order; - - // send to feedaty - - $this->_fdservice->send_order( $merchant, $secret, $fd_data ); - - } - - else { - - $this->_feedatyHelper->feedatyDebug( "Can't find order products", "FEEDATY: " ); - - } - - } - - } - - } - - catch (Exception $exception) { - - $this->_feedatyHelper->feedatyDebug( $exception->getMessage, "FEEDATY: " ); - - } - - - } - -} diff --git a/Observer/ProductReviews.php b/Observer/ProductReviews.php deleted file mode 100644 index f373ca1..0000000 --- a/Observer/ProductReviews.php +++ /dev/null @@ -1,113 +0,0 @@ -_blockFactory = $blockFactory; - $this->_scopeConfig = $scopeConfig; - $this->storeManager = $storeManager; - $this->_registry = $registry; - $this->_backendUrl = $backendUrl; - $this->_objectManager = $objectmanager; - $this->_dataHelper = $dataHelper; - $this->_fdservice = $fdservice; - } - - public function execute(Observer $observer) { - - $store_scope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; - $block = $observer->getBlock(); - $transport = $observer->getTransport(); - $html = $transport->getHtml(); - $merchant = $this->_scopeConfig->getValue('feedaty_global/feedaty_preferences/feedaty_code', $store_scope); - $prod_pos = $this->_scopeConfig->getValue('feedaty_badge_options/review_products/product_position', $store_scope); - $plugin_enabled = $this->_scopeConfig->getValue('feedaty_badge_options/review_products/product_enabled', $store_scope); - $show_reviews = $this->_scopeConfig->getValue('feedaty_badge_options/review_products/count_review', $store_scope); - - if ($observer->getElementName() == $prod_pos) - { - $product = $this->_registry->registry('current_product'); - - if ($plugin_enabled != 0 && $product !== null) - { - $product_id = $product->getId(); - - $toview['data_review'] = $this->_fdservice->retriveInformationsProduct($merchant, $product_id); - - if ($this->_scopeConfig->getValue('feedaty_badge_options/review_products/order_review', $store_scope) == 1) - { - $toview['data_review']['Feedbacks'] = array_reverse($toview['data_review']['Feedbacks']); - } - - $toview['count_review'] = $show_reviews; - $toview['link'] = ''; - if(isset($toview['data_review']['Product'])){ - $toview['link'] = ''.__('Read all reviews').''; - } - - if (!empty($toview['data_review']['Feedbacks'])) - { - $html = $observer->getTransport()->getOutput(); - $buttons = $this->_objectManager->create('Feedaty\Badge\Block\Product', array('template'=>'Feedaty_Badge::product_reviews.phtml'))->setData('view', $toview)->setTemplate('Feedaty_Badge::product_reviews.phtml'); - - $html .= $buttons->toHtml(); - $observer->getTransport()->setOutput($html); - } - } - } - } -} diff --git a/Setup/UpgradeSchema.php b/Setup/UpgradeSchema.php new file mode 100644 index 0000000..f197d7c --- /dev/null +++ b/Setup/UpgradeSchema.php @@ -0,0 +1,142 @@ +startSetup(); + + if(version_compare($context->getVersion(), '2.7.0') < 0) { + + $tableName = $setup->getTable('review_detail'); + if ($setup->getConnection()->isTableExists($tableName) == true) { + $columns = [ + 'feedaty_source' => [ + 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN, + 'nullable' => false, + 'default' => false, + 'comment' => 'Feedaty Review', + ], + 'feedaty_pagination' => [ + 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, + 'nullable' => false, + 'default' => 0, + 'comment' => 'Feedaty Review Pagination', + ], + 'feedaty_source_id' => [ + 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, + 'nullable' => false, + 'default' => 0, + 'comment' => 'Feedaty Review ID', + ], + 'feedaty_update' => [ + 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + 'nullable' => false, + 'size' => null, + 'comment' => 'Feedaty Review Update At', + ], + 'feedaty_create' => [ + 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + 'nullable' => false, + 'size' => null, + 'comment' => 'Feedaty Review Create At', + ], + 'feedaty_product_review_id' => [ + 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, + 'nullable' => false, + 'default' => 0, + 'comment' => 'Feedaty Product Review ID', + ], + 'feedaty_product_mediated' => [ + 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN, + 'nullable' => false, + 'default' => 0, + 'comment' => 'Feedaty Product Mediated', + ] + + ]; + + $connection = $setup->getConnection(); + + foreach ($columns as $name => $definition) { + $connection->addColumn($tableName, $name, $definition); + } + } + } + + + + $tableName = $setup->getTable('feedaty_orders'); + if(version_compare($context->getVersion(), '2.7.0') < 0) { + if ($setup->getConnection()->isTableExists($tableName) != true) { + $table = $setup->getConnection() + ->newTable($tableName) + ->addColumn( + 'feedaty_orders_id', + Table::TYPE_INTEGER, + null, + [ + 'identity' => true, + 'unsigned' => true, + 'nullable' => false, + 'primary' => true + ], + 'ID' + ) + ->addColumn( + 'order_id', + Table::TYPE_TEXT, + null, + ['nullable' => false], + 'Title' + ) + ->addColumn( + 'feedaty_customer_notified', + Table::TYPE_INTEGER, + null, + [ + 'identity' => false, + 'unsigned' => true, + 'nullable' => true, + 'primary' => false + ], + 'Feedaty Order Notification Sent' + ) + ->addColumn( + 'created_at', + Table::TYPE_TIMESTAMP, + null, + ['nullable' => false, 'default' => Table::TIMESTAMP_INIT], + 'Created At' + ) + ->addColumn( + 'updated_at', + Table::TYPE_TIMESTAMP, + null, + ['nullable' => false, 'default' => Table::TIMESTAMP_INIT], + 'Created At' + ) + ->setComment('Feedaty Orders Data'); + + $setup->getConnection()->createTable($table); + } + } + + $installer->endSetup(); + } +} + diff --git a/composer.json b/composer.json index 002be7f..1525170 100755 --- a/composer.json +++ b/composer.json @@ -35,9 +35,9 @@ "AFL-3.0" ], - "version": "2.6.7-stable", + "version": "2.7.0-stable", + - "type": "magento2-module", "autoload": { diff --git a/etc/adminhtml/menu.xml b/etc/adminhtml/menu.xml index 07f816e..a0fae03 100644 --- a/etc/adminhtml/menu.xml +++ b/etc/adminhtml/menu.xml @@ -5,8 +5,6 @@ - - diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 6b4b5e5..d7f0993 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -20,6 +20,24 @@ validate-alphanum + + + + Magento\Config\Model\Config\Source\Yesno + + + + + Magento\Config\Model\Config\Source\Yesno + + + + + Magento\Store\Ui\Component\Listing\Column\Store\Options + + 1 + + @@ -30,7 +48,6 @@ - @@ -39,74 +56,6 @@ - - - - - Magento\Config\Model\Config\Source\Yesno - - - - - - - - Feedaty\Badge\Model\Config\Source\FeedatyTimeout - - - - - - - - Feedaty\Badge\Model\Config\Source\FeedatyTimeout - - - - - - - - Feedaty\Badge\Model\Config\Source\FeedatyTimeout - - - - - - - - Feedaty\Badge\Model\Config\Source\FeedatyTimeout - - - - - -
- separator-top - - feedaty - Feedaty_Badge::widget_preferences - - - - - - Magento\Config\Model\Config\Source\Yesno - - - - validate-number - - - - Feedaty\Badge\Model\Config\Source\FeedatyOrder - - - - Feedaty\Badge\Model\Config\Source\PositionProduct - - -
diff --git a/etc/crontab.xml b/etc/crontab.xml new file mode 100644 index 0000000..6123071 --- /dev/null +++ b/etc/crontab.xml @@ -0,0 +1,11 @@ + + + + + */5 * * * * + + + */30 * * * * + + + diff --git a/etc/di.xml b/etc/di.xml new file mode 100644 index 0000000..ac2ea07 --- /dev/null +++ b/etc/di.xml @@ -0,0 +1,4 @@ + + + + diff --git a/etc/events.xml b/etc/events.xml deleted file mode 100755 index 4294601..0000000 --- a/etc/events.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/etc/frontend/events.xml b/etc/frontend/events.xml deleted file mode 100755 index 2d7226e..0000000 --- a/etc/frontend/events.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/etc/module.xml b/etc/module.xml index 1347b38..aeeb050 100755 --- a/etc/module.xml +++ b/etc/module.xml @@ -1,6 +1,6 @@ - + diff --git a/etc/widget.xml b/etc/widget.xml index 6b944b1..f39632b 100755 --- a/etc/widget.xml +++ b/etc/widget.xml @@ -4,17 +4,20 @@ Show Feedaty Store Badge - - + + - - + + + + + - - - - - + + + + + @@ -22,17 +25,26 @@ Show Feedaty Product Badge - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + diff --git a/view/adminhtml/adminhtml_system_config_edit.xml b/view/adminhtml/adminhtml_system_config_edit.xml deleted file mode 100644 index 5cb0f62..0000000 --- a/view/adminhtml/adminhtml_system_config_edit.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/view/adminhtml/requirejs-config.js b/view/adminhtml/requirejs-config.js deleted file mode 100644 index acf8f70..0000000 --- a/view/adminhtml/requirejs-config.js +++ /dev/null @@ -1,8 +0,0 @@ -var config = { - map: { - '*': { - // Qui mappo eventuale js - //chosen: 'Feedaty_Badge/js/chosen/chosen.jquery' - } - } -}; \ No newline at end of file diff --git a/view/frontend/layout/default.xml b/view/frontend/layout/default.xml deleted file mode 100644 index 3a14f47..0000000 --- a/view/frontend/layout/default.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/view/frontend/templates/fdtbase.phtml b/view/frontend/templates/fdtbase.phtml deleted file mode 100644 index 86b244f..0000000 --- a/view/frontend/templates/fdtbase.phtml +++ /dev/null @@ -1,5 +0,0 @@ -getView(); -$view['generated'] = str_replace("{rate}", $view['rate'], $view['generated']); -//echo $generated; diff --git a/view/frontend/templates/product-snippet.phtml b/view/frontend/templates/product-snippet.phtml index 3feb9ef..a1ac8d6 100644 --- a/view/frontend/templates/product-snippet.phtml +++ b/view/frontend/templates/product-snippet.phtml @@ -28,26 +28,21 @@ $mediaUrl = $this->getMediaUrl(); */ if ($product !== null) { - $product_id = $product->getId(); + $productId = $product->getId(); /** - * Retrive Product Infomation + * Product Reviews data */ - $toview['data_review'] = $block->retriveInformationsProduct($merchant, $product_id); + $reviews = $block->getProductReviews($productId); } ?> - +getData())) : ?> getProductUrl(); /** - * Product URL + * Product Stock */ $productIsSalable = $block->getProductIsSalable() === true ? "https://schema.org/InStock" : "https://schema.org/OutOfStock"; - /** * Product Currency Code */ @@ -79,53 +73,68 @@ if ($product !== null) { */ $productSku = $block->getProductSku(); + /** * Product Desc */ - $productDescription = $block->getProductDescription(); + $productDescription = strip_tags($block->getProductDescription()); /** * Merchant Code */ - $merchantName = $toview['data_review']['MerchantName']; + $merchantName = $block->getStoreName(); + $reviewsJson = array(); /** - * Get all product reviews + * Get all reviews */ foreach ($reviews as $item) { /** * Product rating */ - $ratingValue = $item['ProductRating']; + $countRatings = count($item->getRatingVotes()) > 0 ? count($item->getRatingVotes()) : 1; + $allRatings = 0; + foreach ($item->getRatingVotes() as $vote) { + $allRatings = $allRatings + $vote->getPercent(); + } + $allRatingsAvg = $allRatings / $countRatings; + + + $itemRatingValue = $allRatingsAvg.'%'; + /** * Review Desc Details */ - $productReview = $item['ProductReview']; + $itemReview = $item->getDetail(); /** * Review Date */ - $productReviewDate = $item['Recorded']; + $itemReviewDate = date("Y-m-d", strtotime($item->getCreatedAt())); + /** + * Review Customer Name + */ + $itemNickname = $item->getNickname(); $reviewsJson[] = array( "@type" => "Review", "reviewRating" => [ "@type" => "Rating", - "ratingValue" => "$ratingValue" + "ratingValue" => "$itemRatingValue" ], "name" => "$productName", - "datePublished" => "$productReviewDate", + "datePublished" => "$itemReviewDate", "author" => [ "@type" => "Organization", - "name" => "Feedaty" + "name" => "$itemNickname" ], - "reviewBody" => "$productReview", + "reviewBody" => "$itemReview", "publisher" => [ "@type" => "Organization", "name" => "$merchantName" @@ -136,13 +145,16 @@ if ($product !== null) { /** * Rating Value */ - $ratingValue = $toview['data_review']['Product']['AvgRating']; + $ratingValue = $block->getRatingSummary($product).'%'; /** * Total product feedback */ - $ratingsCount = $toview['data_review']['Product']['RatingsCount']; + $ratingsCount = $reviews->count(); + + $reviewCount = $reviews->count(); + /** * Get Aggregate Rating and Product info @@ -166,7 +178,7 @@ if ($product !== null) { "ratingValue" => $ratingValue, "ratingCount" => $ratingsCount ], - "reviewCount" => $toview['data_review']['TotalFeedbacks'], + "reviewCount" => $reviewCount, "review" => $reviewsJson ); diff --git a/view/frontend/templates/product_reviews.phtml b/view/frontend/templates/product_reviews.phtml deleted file mode 100644 index 12aef4a..0000000 --- a/view/frontend/templates/product_reviews.phtml +++ /dev/null @@ -1,40 +0,0 @@ -getView(); - $reviews = $view['data_review']['Feedbacks']; -?> - -
- -

- -
- - $r) { ?> - - -
- -
- - - -
- -
-
- -
-
- -
- -
- -
- - - -
- - -
\ No newline at end of file diff --git a/view/frontend/templates/widget/product-badge.phtml b/view/frontend/templates/widget/product-badge.phtml new file mode 100644 index 0000000..b56c3bb --- /dev/null +++ b/view/frontend/templates/widget/product-badge.phtml @@ -0,0 +1,58 @@ + + +getFeedatyCode(); + +$dataObject = $block->getFeedatyData($merchant); + +$badge_style = $block->getData('style'); + +if ($badge_style == 'product') { + $variant = $block->getData('variant_product'); +} elseif ($badge_style == 'carouselproduct') { + $variant = $block->getData('variant_carouselproduct'); +} else { + $variant = $block->getData('variant_product_tab'); +} + +$rvlang = "all"; + +$guilang = "all"; + +$data = $dataObject[$badge_style]['variants']; + +$product = $block->getCurrentProduct(); + +if (!empty($product)) { + + $productId = $product->getId(); + + if (count($data) > 0) { + $ver = $block->getExtensionVersion(); + + if (array_key_exists($variant, $data)) { + $widget = $data[$variant]; + $name = $widget["name"]; + + $widget['html'] = str_replace("GUI_LANG", $guilang, $widget['html']); + $widget['html'] = str_replace("REV_LANG", $rvlang, $widget['html']); + $widget['html'] = str_replace("INSERT_SKU", $productId, $widget['html']); + + $element = htmlspecialchars_decode($widget["html"]); + + echo $element; + + } + } +} + + +?> diff --git a/view/frontend/templates/widget/product-bagde.phtml b/view/frontend/templates/widget/product-bagde.phtml deleted file mode 100644 index 3969cc2..0000000 --- a/view/frontend/templates/widget/product-bagde.phtml +++ /dev/null @@ -1,62 +0,0 @@ - - -getFeedatyCode(); - -$data = $block->getFeedatyData($merchant); - -$badge_style = $block->getData('style'); -$variant = $block->getData('variant'); -$rvlang = $block->getData('rvlang'); -$guilang = $block->getData('guilang'); - -$rvlang = $rvlang ? $rvlang : "all"; - -$guilang = $guilang ? $guilang : "it-IT"; - -$product = $block->getCurrentProduct(); - -if (!empty($product)) { - - $productId = $product->getId(); - - if (count($data) > 0) { - $ver = $block->getExtensionVersion(); - - if (array_key_exists($badge_style, $data)) { - $widget = $data[$badge_style]; - - if (array_key_exists($variant, $widget["variants"])) { - - $name = $widget["name"]; - - $variant = $widget["variants"][$variant]; - - $rvlang = $rvlang ? $rvlang : "all"; - - $guilang = $guilang ? $guilang : "it-IT"; - - $widget['html'] = str_replace("ZOORATE_SERVER", $zoorate_env, $widget['html']); - $widget['html'] = str_replace("VARIANT", $variant, $widget['html']); - $widget['html'] = str_replace("GUI_LANG", $guilang, $widget['html']); - $widget['html'] = str_replace("REV_LANG", $rvlang, $widget['html']); - $widget['html'] = str_replace("SKU", $productId, $widget['html']); - - $element = htmlspecialchars_decode($widget["html"]); - - echo "" . $element; - } - } - } -} - - -?> diff --git a/view/frontend/templates/widget/store-badge.phtml b/view/frontend/templates/widget/store-badge.phtml new file mode 100644 index 0000000..602c2cc --- /dev/null +++ b/view/frontend/templates/widget/store-badge.phtml @@ -0,0 +1,46 @@ + + +getFeedatyCode(); + +$dataObject = $block->getFeedatyData($merchant); + + +$badge_style = $block->getData('style'); +if ($badge_style == 'merchant') { + $variant = $block->getData('variant_merchant'); +} else { + $variant = $block->getData('variant_carousel'); +} + +$rvlang = "all"; +$guilang = "all"; + +$data = $dataObject[$badge_style]['variants']; + +if (count($data) > 0) { + $ver = $block->getExtensionVersion(); + if (array_key_exists($variant, $data)) { + $widget = $data[$variant]; + + $name = $widget["name"]; + + $widget['html'] = str_replace("GUI_LANG", $guilang, $widget['html']); + + $widget['html'] = str_replace("REV_LANG", $rvlang, $widget['html']); + + $element = htmlspecialchars_decode($widget["html"]); + + echo $element; + + } +} + +?> diff --git a/view/frontend/templates/widget/store-bagde.phtml b/view/frontend/templates/widget/store-bagde.phtml deleted file mode 100644 index 1db744b..0000000 --- a/view/frontend/templates/widget/store-bagde.phtml +++ /dev/null @@ -1,62 +0,0 @@ - - -getFeedatyCode(); - -$data = $block->getFeedatyData($merchant); - -$badge_style = $block->getData('style'); -$variant = $block->getData('variant'); -$rvlang = $block->getData('rvlang'); -$guilang = $block->getData('guilang'); - -$rvlang = $rvlang ? $rvlang : "all"; - -$guilang = $guilang ? $guilang : "it-IT"; - -if (count($data) > 0) { - $ver = $block->getExtensionVersion(); - - if (array_key_exists($badge_style, $data)) { - $widget = $data[$badge_style]; - - $name = $widget["name"]; - - // Se non trova variante setta la blue white - - if (array_key_exists($variant, $widget["variants"])) { - $variant = $widget["variants"][$variant]; - - $rvlang = $rvlang ? $rvlang : "all"; - - $guilang = $guilang ? $guilang : "it-IT"; - - $widget['html'] = str_replace("ZOORATE_SERVER", $zoorate_env, $widget['html']); - - $widget['html'] = str_replace("VARIANT", $variant, $widget['html']); - - $widget['html'] = str_replace("GUI_LANG", $guilang, $widget['html']); - - $widget['html'] = str_replace("REV_LANG", $rvlang, $widget['html']); - - $element = htmlspecialchars_decode($widget["html"]); - - // $html = $observer->getTransport()->getOutput(); - - // $html.= "".$element; - echo "" . $element; - - // $observer->getTransport()->setOutput( $html ); - } - } -} - -?>