From 247b9b0e7662fe7843a09384da5997d3e4a89dc4 Mon Sep 17 00:00:00 2001 From: Marco Boatti Date: Sat, 25 Sep 2021 14:38:38 +0200 Subject: [PATCH 01/17] tmp Create Reviews --- Block/ProductSnippet.php | 5 - CHANGELOG.md | 11 +- Cron/Reviews.php | 239 +++++++++++++++++++++++++++++ Model/Config/Source/WebService.php | 35 ++++- Model/ProductReviews.php | 47 ++++++ Model/ResourceModel/Review.php | 72 +++++++++ Setup/UpgradeSchema.php | 115 ++++++++++++++ composer.json | 2 +- etc/adminhtml/system.xml | 8 + etc/crontab.xml | 8 + etc/di.xml | 4 + etc/module.xml | 2 +- 12 files changed, 532 insertions(+), 16 deletions(-) create mode 100644 Cron/Reviews.php create mode 100644 Model/ProductReviews.php create mode 100644 Model/ResourceModel/Review.php create mode 100644 Setup/UpgradeSchema.php create mode 100644 etc/crontab.xml create mode 100644 etc/di.xml diff --git a/Block/ProductSnippet.php b/Block/ProductSnippet.php index beda370..0308559 100755 --- a/Block/ProductSnippet.php +++ b/Block/ProductSnippet.php @@ -165,11 +165,6 @@ public function getMediaUrl() return $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); } - public function getAllReview() - { - return $this->_webservice->getAllReviews($params = ''); - } - /** * @return string */ diff --git a/CHANGELOG.md b/CHANGELOG.md index 5148b46..5970527 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,12 +2,19 @@ #### RELASE NOTES -### V2.6.0 14/04/2020 +### V2.7.0 + +- Add Feedaty Review Columns to review_detail table + +### 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/Reviews.php b/Cron/Reviews.php new file mode 100644 index 0000000..f0aa8e6 --- /dev/null +++ b/Cron/Reviews.php @@ -0,0 +1,239 @@ +logger = $logger; + $this->_webService = $webService; + $this->_reviewFactory = $reviewFactory; + $this->_ratingFactory = $ratingFactory; + $this->_storeManager = $storeManager; + $this->date = $date; + } + + /** + * @param $productId + * @param $feedatyId + * @return mixed + */ + public function getReviewCollection($productId, $feedatyId){ + $collection = $this->_reviewFactory->create()->getCollection() + ->addEntityFilter( + 'product', + $productId + ) + ->addFieldToFilter( + 'feedaty_source_id', + $feedatyId + ) + ->setDateOrder(); + + return $collection->getData(); + } + + /* + * Get last Review Created + */ + public function getAllFeedatyReviewCount(){ + $collection = $this->_reviewFactory->create()->getCollection() + ->addFieldToFilter( + 'feedaty_source', + 1 + ) + ->setOrder( + 'review_id', + 'desc' + ) + ->setDateOrder(); + + // $collection->getSelect()->group('feedaty_source_id'); + return count($collection->getData()); + } + + /* + * Get last Review Created + */ + public function getLastFeedatyReviewCreated(){ + $collection = $this->_reviewFactory->create()->getCollection() + ->addFieldToFilter( + 'feedaty_source', + 1 + ) + ->setOrder( + 'review_id', + 'desc' + ) + ->setPageSize(1) + ->setCurPage(1) + ->setDateOrder(); + + return $collection->getData(); + } + + public function getTotalProductReviews() + { + return $this->_webService->getTotalProductReviewsCount(); + } + /** + * Review Data + * + * @return Review + */ + public function getReviewData($reviewId) + { + try { + $review = $this->_reviewFactory->create()->load($reviewId); + } catch (LocalizedException $exception) { + throw new LocalizedException(__($exception->getMessage())); + } + return $review; + } + /** + * @throws \Magento\Framework\Exception\LocalizedException + */ + public function execute() + { + + $totalFeedatyReviews = $this->getTotalProductReviews(); + $totalReviewCreatedCount = $this->getAllFeedatyReviewCount(); + $this->logger->addInfo("START - Cronjob Feedaty | 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->getLastFeedatyReviewCreated(); + + $count = 100; // get x reviews + + $row = $totalFeedatyReviews - $totalReviewCreatedCount - $count; + + + //Get Feedaty Product Reviews + $feedatyProductReviews = $this->getProductReviewsPagination($row,$count); + + //Foreach Review + foreach ($feedatyProductReviews as $review){ + //feedaty_source_id + $feedatyId = $review['ID']; + + $replaceFromDate = ["/Date(", ")/"]; + $replaceToDate = ["", ""]; + //Review Date + $createdAt = date('Y-m-d h:i:s', floor((int)str_replace($replaceFromDate,$replaceToDate,$review['Released'])/ 1000)); + //$reviewReleased =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']; + //Get Feedaty Product Reviews + $magentoProductReviews = $this->getReviewCollection($productId, $feedatyId); + + //AP Rating node + $rating = $item['Rating']; + + //API Review Node + $detail = $item['Review']; + + //TODO VERIFICARE website view + + if (empty($magentoProductReviews)) { + // $this->createProductReview($productId, $feedatyId, $rating, $detail, $createdAt,$today,$row); + + // Product Review + $this->logger->addInfo("EXEC - Cronjob Feedaty create Product Review | date execution: ". date('Y-m-d H:i:s') ." | Product Id : ". $productId . " | Feedaty ID" .$feedatyId ); + + } + } + } + + // General Cron Report on system.log + $this->logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date execution: ". date('Y-m-d H:i:s') ." -- Last Review Created " . print_r($lastReviewCreated,true) ." -- Review Date CreatedAt " . print_r($createdAt,true) ." -- Pagination " . $row ); + // $this->logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date: ". date('Y-m-d H:i:s') ); + } + + public function getProductReviewsPagination($row, $count) + { + return $this->_webService->getProductReviewsPagination($row, $count); + } + + + protected function createProductReview($productId, $feedatyId, $rating, $detail, $createdAt,$today,$row){ + + $reviewFinalData['ratings'][1] = $rating; + $reviewFinalData['ratings'][2] = $rating; + $reviewFinalData['ratings'][3] = $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_create'] = $today; + $reviewFinalData['feedaty_update'] = $today; + $review = $this->_reviewFactory->create()->setData($reviewFinalData); + //$review->setFeedatySource(1); + // $review->setData('feedaty_source_id', 123123); + + $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($this->_storeManager->getStore()->getId()) + ->setStores([$this->_storeManager->getStore()->getId()]) + ->save(); + + //Since the created_at is set only when the $object does not have an id, i save the object again. + $review->setCreatedAt($createdAt)->save(); + //$review->setCreatedAt('2018-07-31 11:30:05')->save(); + + foreach ($reviewFinalData['ratings'] as $ratingId => $optionId) { + $this->_ratingFactory->create() + ->setRatingId($ratingId) + ->setReviewId($review->getId()) + ->addOptionVote($optionId, $productId); + } + + $review->aggregate(); + } +} + diff --git a/Model/Config/Source/WebService.php b/Model/Config/Source/WebService.php index a342a02..5fa76a4 100755 --- a/Model/Config/Source/WebService.php +++ b/Model/Config/Source/WebService.php @@ -159,7 +159,6 @@ private function getAccessToken($token,$merchant,$secret) { ]; $this->_curl->post($url,$fields); - $response = $this->_curl->getBody(); return $response; @@ -228,12 +227,30 @@ public function retriveInformationsProduct($feedaty_code, $id) { /** * @param $productId * @return mixed|string|null - * @todo : complete function and use to save data in db */ - public function getProductReviews($productId){ + /*public function getProductReviews($productId){ return $this->getAllReviews('?retrieve=onlyproductreviews&sku='.$productId); + }*/ + + /* public function getAllProductReviews(){ + return $this->getAllReviews('?retrieve=onlyproductreviews'); + }*/ + + public function getProductReviewsPagination($row = 0, $count = 50){ + $allReviews = $this->getAllReviews('?retrieve=onlyproductreviews&row='.$row.'&count='.$count); + return $allReviews['Reviews']; + } + + public function getTotalProductReviewsCount() + { + $allProductReviews = $this->getAllReviews('?retrieve=onlyproductreviews&row=0&count=1'); + + $totalResults = $allProductReviews['TotalProductReviews']; + + return $totalResults; } + /** * @param string $params * @return mixed|string|null @@ -241,8 +258,10 @@ public function getProductReviews($productId){ */ public function getAllReviews($params = '') { - $merchant = $this->_configRules->getFeedatyCode(); - $secret = $this->_configRules->getFeedatySecret(); + // $merchant = $this->_configRules->getFeedatyCode(); + $merchant = '10213422'; + // $secret = $this->_configRules->getFeedatySecret(); + $secret = '5b1e6e29ff4f45138f07fe2c0d0b6860'; $url = 'http://api.feedaty.com/Reviews/Get'.$params; $token = ''; @@ -271,7 +290,7 @@ public function getAllReviews($params = '') $data = $this->unserializeJson($result); - $reviews = $data['Data']['Reviews']; + $reviews = $data['Data']; return $reviews; } @@ -369,7 +388,6 @@ public function getFeedatyData($feedaty_code) { $string = "FeedatyData" . $feedaty_code . $resolver->getLocale(); $content = $cache->load( $string ); - if ( !$content || strlen($content) == 0 || $content === "null" ) { $ch = curl_init(); @@ -392,6 +410,9 @@ public function getFeedatyData($feedaty_code) { $data = json_decode($content, true); + if(!$data){ + $data = []; + } return $data; } 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/Review.php b/Model/ResourceModel/Review.php new file mode 100644 index 0000000..36191f3 --- /dev/null +++ b/Model/ResourceModel/Review.php @@ -0,0 +1,72 @@ +getConnection(); + /** + * save detail + */ + $detail = [ + 'title' => $object->getTitle(), + 'detail' => $object->getDetail(), + 'nickname' => $object->getNickname(), + 'feedaty_source' => $object->getFeedatySource(), + 'feedaty_source_id' => $object->getFeedatySourceId(), + 'feedaty_pagination' => $object->getFeedatyPagination(), + 'feedaty_create' => $object->getFeedatyCreate(), + 'feedaty_update' => $object->getFeedatyUpdate(), + ]; + $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/Setup/UpgradeSchema.php b/Setup/UpgradeSchema.php new file mode 100644 index 0000000..f2b123d --- /dev/null +++ b/Setup/UpgradeSchema.php @@ -0,0 +1,115 @@ +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', + ], + + ]; + + $connection = $setup->getConnection(); + + foreach ($columns as $name => $definition) { + $connection->addColumn($tableName, $name, $definition); + } + } + + } + + + + if(version_compare($context->getVersion(), '2.7.1') < 0) { + + $feedatyTable = $setup->getTable('feedaty_badge_settings'); + + if ($setup->getConnection()->isTableExists($feedatyTable) != true) { + $table = $setup->getConnection() + ->newTable($feedatyTable) + ->addColumn( + 'id', + Table::TYPE_INTEGER, + null, + [ + 'identity' => true, + 'unsigned' => true, + 'nullable' => false, + 'primary' => true + ], + 'ID' + ) + ->addColumn( + 'create_pagination', + Table::TYPE_INTEGER, + null, + [ + 'nullable' => true + ], + 'Create Review Cron Pagination ' + ) + ->addColumn( + 'auth_code', + Table::TYPE_TEXT, + 250, + 'Auth Code ' + ) + ->setComment('Feedaty Badge'); + $setup->getConnection()->createTable($table); + } + } + + + $installer->endSetup(); + } +} + diff --git a/composer.json b/composer.json index 002be7f..6c580c1 100755 --- a/composer.json +++ b/composer.json @@ -37,7 +37,7 @@ "version": "2.6.7-stable", - + "type": "magento2-module", "autoload": { diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 6b4b5e5..9f02348 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -79,6 +79,14 @@ + + + + + Magento\Config\Model\Config\Source\Yesno + + +
diff --git a/etc/crontab.xml b/etc/crontab.xml new file mode 100644 index 0000000..52b1e7d --- /dev/null +++ b/etc/crontab.xml @@ -0,0 +1,8 @@ + + + + + */2 * * * * + + + 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/module.xml b/etc/module.xml index 1347b38..d48f99c 100755 --- a/etc/module.xml +++ b/etc/module.xml @@ -1,6 +1,6 @@ - + From 3e7271f73d0d33c2f51c89fdd583364a3f9b21c9 Mon Sep 17 00:00:00 2001 From: Marco Boatti Date: Sun, 26 Sep 2021 14:42:36 +0200 Subject: [PATCH 02/17] Add Website from order --- Cron/Reviews.php | 127 ++++++++++++++++++++++------- Model/Config/Source/WebService.php | 16 ++-- 2 files changed, 106 insertions(+), 37 deletions(-) diff --git a/Cron/Reviews.php b/Cron/Reviews.php index f0aa8e6..3ffd736 100644 --- a/Cron/Reviews.php +++ b/Cron/Reviews.php @@ -2,6 +2,9 @@ namespace Feedaty\Badge\Cron; +use Magento\Store\Api\Data\StoreInterface; +use Magento\Store\Api\StoreRepositoryInterface; + class Reviews { @@ -26,8 +29,20 @@ class Reviews */ protected $_storeManager; + /** + * @var \Magento\Framework\Stdlib\DateTime\DateTime + */ protected $date; + + /** + * @var StoreRepositoryInterface + */ + private $_storeRepository; + + + protected $_orderRepository; + /** * @param \Psr\Log\LoggerInterface $logger * @param \Feedaty\Badge\Model\Config\Source\WebService $webService @@ -41,7 +56,9 @@ public function __construct( \Magento\Review\Model\ReviewFactory $reviewFactory, \Magento\Review\Model\RatingFactory $ratingFactory, \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Framework\Stdlib\DateTime\DateTime $date + \Magento\Framework\Stdlib\DateTime\DateTime $date, + StoreRepositoryInterface $storeRepository, + \Magento\Sales\Api\OrderRepositoryInterface $orderRepository ) { $this->logger = $logger; @@ -50,8 +67,50 @@ public function __construct( $this->_ratingFactory = $ratingFactory; $this->_storeManager = $storeManager; $this->date = $date; + $this->_storeRepository = $storeRepository; + $this->_orderRepository = $orderRepository; } + + public function getStoreViewIdByOrder($orderId) + { + $this->logger->addInfo("FEEDATY START GET STORE: ".$orderId ); + $order = null; + try { + $order = $this->_orderRepository->get($orderId); + + } catch (\Exception $e) { + $this->logger->critical("FEEDATY ERROR : ".$e->getMessage()); + $this->logger->critical("FEEDATY ERROR : order id does not exist ".$orderId); + + } + + + if(!is_null($order)){ + $websiteId = $order->getStore()->getWebsiteId(); + $this->logger->addInfo("FEEDATY ORDER websiteId: " .$websiteId); + return $websiteId; + } + + return null; + + } + + function getAllStoreList() + { + $storeList = $this->_storeRepository->getList(); + + $storeIds = array(); + foreach ($storeList as $store) { + $storeIds = $store->getStoreId(); // store id + } + + $this->logger->addInfo("STORES LIST: " .print_r($storeList,true) ); + + return $storeIds; + } + + /** * @param $productId * @param $feedatyId @@ -138,6 +197,7 @@ public function execute() $totalFeedatyReviews = $this->getTotalProductReviews(); $totalReviewCreatedCount = $this->getAllFeedatyReviewCount(); $this->logger->addInfo("START - Cronjob Feedaty | Get Feedaty Reviews | date: " . date('Y-m-d H:i:s') . ' ---- Total Feedaty Product Reviews ' . $totalFeedatyReviews . ' totalReviewCreatedCount group by feedaty_id ' . $totalReviewCreatedCount ); + // $this->logger->addInfo("START - Cronjob Feedaty | STORES | date: " . $this->getAllStoreList() ); //Get Last Review Created on Magento (on first run vill be null) $lastReviewCreated = $this->getLastFeedatyReviewCreated(); @@ -149,46 +209,53 @@ public function execute() //Get Feedaty Product Reviews $feedatyProductReviews = $this->getProductReviewsPagination($row,$count); + if(!empty($feedatyProductReviews)){ + //Foreach Review + foreach ($feedatyProductReviews as $review){ + //feedaty_source_id + $feedatyId = $review['ID']; + + $orderId = $review['OrderID']; - //Foreach Review - foreach ($feedatyProductReviews as $review){ - //feedaty_source_id - $feedatyId = $review['ID']; + $storeView = $this->getStoreViewIdByOrder($orderId); - $replaceFromDate = ["/Date(", ")/"]; - $replaceToDate = ["", ""]; - //Review Date - $createdAt = date('Y-m-d h:i:s', floor((int)str_replace($replaceFromDate,$replaceToDate,$review['Released'])/ 1000)); - //$reviewReleased =date('Y-m-d h:i:s', floor((int)str_replace($replaceFromDate,$replaceToDate,$review['Released'])/ 1000)); + $replaceFromDate = ["/Date(", ")/"]; + $replaceToDate = ["", ""]; + //Review Date + $createdAt = date('Y-m-d h:i:s', floor((int)str_replace($replaceFromDate,$replaceToDate,$review['Released'])/ 1000)); + //$reviewReleased =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){ + $today = $this->date->gmtDate(); + foreach ($review['ProductsReviews'] as $item){ - $productId = $item['SKU']; - //Get Feedaty Product Reviews - $magentoProductReviews = $this->getReviewCollection($productId, $feedatyId); + $productId = $item['SKU']; - //AP Rating node - $rating = $item['Rating']; + //Get Feedaty Product Reviews + $magentoProductReviews = $this->getReviewCollection($productId, $feedatyId); - //API Review Node - $detail = $item['Review']; + //AP Rating node + $rating = $item['Rating']; - //TODO VERIFICARE website view + //API Review Node + $detail = $item['Review']; - if (empty($magentoProductReviews)) { - // $this->createProductReview($productId, $feedatyId, $rating, $detail, $createdAt,$today,$row); + //TODO VERIFICARE website view - // Product Review - $this->logger->addInfo("EXEC - Cronjob Feedaty create Product Review | date execution: ". date('Y-m-d H:i:s') ." | Product Id : ". $productId . " | Feedaty ID" .$feedatyId ); + if (empty($magentoProductReviews)) { + $this->createProductReview($productId, $feedatyId, $rating, $detail, $createdAt,$today,$row,$storeView); + // Product Review + $this->logger->addInfo("EXEC - Cronjob Feedaty create Product Review | date execution: ". date('Y-m-d H:i:s') ." | Product Id : ". $productId . " | Feedaty ID" .$feedatyId ); + + } } } + // General Cron Report on system.log + $this->logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date execution: ". date('Y-m-d H:i:s') ." -- Last Review Created " . print_r($lastReviewCreated,true) ." -- Review Date CreatedAt " . print_r($createdAt,true) ." -- Pagination " . $row); } - // General Cron Report on system.log - $this->logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date execution: ". date('Y-m-d H:i:s') ." -- Last Review Created " . print_r($lastReviewCreated,true) ." -- Review Date CreatedAt " . print_r($createdAt,true) ." -- Pagination " . $row ); - // $this->logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date: ". date('Y-m-d H:i:s') ); + + // $this->logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date: ". date('Y-m-d H:i:s') ); } public function getProductReviewsPagination($row, $count) @@ -197,11 +264,12 @@ public function getProductReviewsPagination($row, $count) } - protected function createProductReview($productId, $feedatyId, $rating, $detail, $createdAt,$today,$row){ + protected function createProductReview($productId, $feedatyId, $rating, $detail, $createdAt,$today,$row,$storeView){ $reviewFinalData['ratings'][1] = $rating; $reviewFinalData['ratings'][2] = $rating; $reviewFinalData['ratings'][3] = $rating; + $reviewFinalData['nickname'] = "Feedaty"; $reviewFinalData['title'] = "Acquirente Verificato"; $reviewFinalData['detail'] = $detail; @@ -219,7 +287,8 @@ protected function createProductReview($productId, $feedatyId, $rating, $detail, ->setEntityPkValue($productId) ->setStatusId(\Magento\Review\Model\Review::STATUS_APPROVED) ->setStoreId($this->_storeManager->getStore()->getId()) - ->setStores([$this->_storeManager->getStore()->getId()]) + //->setStores(!is_null($storeView) ? [$storeView] : $this->_storeManager->getStore()->getId()) + ->setStores(!is_null($storeView) ? [$storeView] : [0,1,2]) ->save(); //Since the created_at is set only when the $object does not have an id, i save the object again. diff --git a/Model/Config/Source/WebService.php b/Model/Config/Source/WebService.php index 5fa76a4..b29cb5a 100755 --- a/Model/Config/Source/WebService.php +++ b/Model/Config/Source/WebService.php @@ -112,12 +112,13 @@ public function unserializeJson($result) */ private function getReqToken(){ + $url = "http://api.feedaty.com/OAuth/RequestToken"; $this->_curl->addHeader('Content-Type','application/x-www-form-urlencoded'); $this->_curl->get($url); $response = json_decode($this->_curl->getBody()); - + $this->_logger->critical('Feedaty response token //////////////////: '. print_r($response,true)); return $response; } @@ -258,14 +259,13 @@ public function getTotalProductReviewsCount() */ public function getAllReviews($params = '') { - // $merchant = $this->_configRules->getFeedatyCode(); - $merchant = '10213422'; - // $secret = $this->_configRules->getFeedatySecret(); - $secret = '5b1e6e29ff4f45138f07fe2c0d0b6860'; - $url = 'http://api.feedaty.com/Reviews/Get'.$params; + $merchant = $this->_configRules->getFeedatyCode(); + $secret = $this->_configRules->getFeedatySecret(); + $url = 'http://api.feedaty.com/Reviews/Get'.$params; $token = ''; + try { $token = $this->getReqToken(); if ($token != '') { @@ -282,7 +282,7 @@ public function getAllReviews($params = '') try { $this->_curl->get($url); } catch (\Exception $e) { - $this->_logger->critical('Feedaty log: '. $e->getMessage()); + $this->_logger->critical('Feedaty log CURL: '. $e->getMessage()); } // output of curl request @@ -295,7 +295,7 @@ public function getAllReviews($params = '') return $reviews; } } catch (\Exception $e) { - $this->_logger->critical('Feedaty log: '. $e->getMessage()); + $this->_logger->critical('Feedaty log TOKEN: '. $e->getMessage()); } return null; From 78271cf3a261cbd52ab84b23dedbcbcaffb9cf39 Mon Sep 17 00:00:00 2001 From: Marco Boatti Date: Sun, 3 Oct 2021 09:46:02 +0200 Subject: [PATCH 03/17] getRemoved Reviews --- Cron/Reviews.php | 99 +++++++++++++++++++++++++++--- Model/Config/Source/WebService.php | 46 ++++++++++++-- 2 files changed, 132 insertions(+), 13 deletions(-) diff --git a/Cron/Reviews.php b/Cron/Reviews.php index 3ffd736..d0ea0fb 100644 --- a/Cron/Reviews.php +++ b/Cron/Reviews.php @@ -72,6 +72,13 @@ public function __construct( } + public function disableReview($reviewData){ + + $review = $this->_reviewFactory->create()->load($reviewData[0]['review_id']); + $review->setStatusId(\Magento\Review\Model\Review::STATUS_NOT_APPROVED)->save();; + + } + public function getStoreViewIdByOrder($orderId) { $this->logger->addInfo("FEEDATY START GET STORE: ".$orderId ); @@ -80,8 +87,8 @@ public function getStoreViewIdByOrder($orderId) $order = $this->_orderRepository->get($orderId); } catch (\Exception $e) { - $this->logger->critical("FEEDATY ERROR : ".$e->getMessage()); - $this->logger->critical("FEEDATY ERROR : order id does not exist ".$orderId); + $this->logger->info("FEEDATY ERROR : ".$e->getMessage()); + $this->logger->info("FEEDATY ERROR : order id does not exist ".$orderId); } @@ -150,6 +157,24 @@ public function getAllFeedatyReviewCount(){ return count($collection->getData()); } + public function getAllFeedatyRemovedReviewCount(){ + $collection = $this->_reviewFactory->create()->getCollection() + ->addStatusFilter( + \Magento\Review\Model\Review::STATUS_NOT_APPROVED) + ->addFieldToFilter( + 'feedaty_source', + 1 + ) + ->setOrder( + 'review_id', + 'desc' + ) + ->setDateOrder(); + + // $collection->getSelect()->group('feedaty_source_id'); + return count($collection->getData()); + } + /* * Get last Review Created */ @@ -170,10 +195,25 @@ public function getLastFeedatyReviewCreated(){ return $collection->getData(); } - public function getTotalProductReviews() - { - return $this->_webService->getTotalProductReviewsCount(); + public function getReviewByFeedatyId($feedatyid){ + $collection = $this->_reviewFactory->create()->getCollection() + ->addFieldToFilter( + 'feedaty_source_id', + $feedatyid + ) + ->setOrder( + 'review_id', + 'desc' + ) + ->setPageSize(1) + ->setCurPage(1) + ->setDateOrder(); + + return $collection->getData(); } + + + /** * Review Data * @@ -194,8 +234,10 @@ public function getReviewData($reviewId) public function execute() { - $totalFeedatyReviews = $this->getTotalProductReviews(); + $totalFeedatyReviews = $this->_webService->getTotalProductReviewsCount(); + $totalFeedatyRemovedReviews = $this->_webService->getTotalProductRemovedReviewsCount(); $totalReviewCreatedCount = $this->getAllFeedatyReviewCount(); + $totalRemovedReviewCreatedCount = $this->getAllFeedatyRemovedReviewCount(); $this->logger->addInfo("START - Cronjob Feedaty | Get Feedaty Reviews | date: " . date('Y-m-d H:i:s') . ' ---- Total Feedaty Product Reviews ' . $totalFeedatyReviews . ' totalReviewCreatedCount group by feedaty_id ' . $totalReviewCreatedCount ); // $this->logger->addInfo("START - Cronjob Feedaty | STORES | date: " . $this->getAllStoreList() ); @@ -207,6 +249,7 @@ public function execute() $row = $totalFeedatyReviews - $totalReviewCreatedCount - $count; + ///// CREATE NEW REVIEWS //Get Feedaty Product Reviews $feedatyProductReviews = $this->getProductReviewsPagination($row,$count); if(!empty($feedatyProductReviews)){ @@ -254,6 +297,41 @@ public function execute() $this->logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date execution: ". date('Y-m-d H:i:s') ." -- Last Review Created " . print_r($lastReviewCreated,true) ." -- Review Date CreatedAt " . print_r($createdAt,true) ." -- Pagination " . $row); } + ///// DISABLE REMOVED REVIEWS + /// + $rowRemoved = $totalFeedatyRemovedReviews - $totalRemovedReviewCreatedCount - $count; + + $this->logger->addInfo("REMOVED ITEMS ROWS ".$rowRemoved); + $this->logger->addInfo("REMOVED ITEMS totalFeedatyRemovedReviews ".$totalFeedatyRemovedReviews); + $this->logger->addInfo("REMOVED ITEMS ROWS totalRemovedReviewCreatedCount ".$totalRemovedReviewCreatedCount); + + $feedatyProductReviewsRemoved = $this->getRemovedReviews($rowRemoved,$count); + if(!empty($feedatyProductReviewsRemoved)){ + + $this->logger->addInfo("START REMOVED - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: ". date('Y-m-d H:i:s') ); + + //Foreach Review + foreach ($feedatyProductReviewsRemoved as $removedReview){ + + $feedatyId = $removedReview['MerchantFeedbackReviewID']; + + $reviewToDisable = $this->getReviewByFeedatyId($feedatyId); + $this->logger->addInfo("REVIEW TO DISABLE OBJ - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: ". date('Y-m-d H:i:s') ." -- REVIEWS TO DISABLE " . print_r($reviewToDisable,true)); + + if(!empty($reviewToDisable)){ + //if it is not just disabled + if($reviewToDisable[0]['status_id'] != 3){ + $this->disableReview($reviewToDisable); + $this->logger->addInfo("REMOVED ITEM ID - : ". date('Y-m-d H:i:s') ." -- FeedatySourceID " . $feedatyId); + } + + + } + + } + // General Cron Report on system.log + } + // $this->logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date: ". date('Y-m-d H:i:s') ); } @@ -263,13 +341,18 @@ public function getProductReviewsPagination($row, $count) return $this->_webService->getProductReviewsPagination($row, $count); } + public function getRemovedReviews($row, $count) + { + return $this->_webService->getRemovedReviews($row, $count); + } + protected function createProductReview($productId, $feedatyId, $rating, $detail, $createdAt,$today,$row,$storeView){ $reviewFinalData['ratings'][1] = $rating; $reviewFinalData['ratings'][2] = $rating; $reviewFinalData['ratings'][3] = $rating; - + $reviewFinalData['nickname'] = "Feedaty"; $reviewFinalData['title'] = "Acquirente Verificato"; $reviewFinalData['detail'] = $detail; @@ -279,8 +362,6 @@ protected function createProductReview($productId, $feedatyId, $rating, $detail, $reviewFinalData['feedaty_create'] = $today; $reviewFinalData['feedaty_update'] = $today; $review = $this->_reviewFactory->create()->setData($reviewFinalData); - //$review->setFeedatySource(1); - // $review->setData('feedaty_source_id', 123123); $review->unsetData('review_id'); $review->setEntityId($review->getEntityIdByCode(\Magento\Review\Model\Review::ENTITY_PRODUCT_CODE)) diff --git a/Model/Config/Source/WebService.php b/Model/Config/Source/WebService.php index b29cb5a..aeb6f5a 100755 --- a/Model/Config/Source/WebService.php +++ b/Model/Config/Source/WebService.php @@ -118,7 +118,7 @@ private function getReqToken(){ $this->_curl->get($url); $response = json_decode($this->_curl->getBody()); - $this->_logger->critical('Feedaty response token //////////////////: '. print_r($response,true)); + $this->_logger->info('Feedaty response token //////////////////: '. print_r($response,true)); return $response; } @@ -242,6 +242,16 @@ public function getProductReviewsPagination($row = 0, $count = 50){ return $allReviews['Reviews']; } + + public function getRemovedReviews($row = 0, $count = 50){ + $allReviews = $this->getAllRemovedReviews('?row='.$row.'&count='.$count); + + $this->_logger->info('ALL REMOVED REVIEW FEEDATY REMOVED: '. print_r($allReviews['Reviews'],true)); + + return $allReviews['Reviews']; + + } + public function getTotalProductReviewsCount() { $allProductReviews = $this->getAllReviews('?retrieve=onlyproductreviews&row=0&count=1'); @@ -251,7 +261,28 @@ public function getTotalProductReviewsCount() return $totalResults; } + public function getTotalProductRemovedReviewsCount() + { + $allProductReviews = $this->getAllRemovedReviews('?row=0&count=1'); + $this->_logger->info('Feedaty REMOVED: '. print_r($allProductReviews,true)); + $totalResults = $allProductReviews['TotalResults']; + + return $totalResults; + } + + + public function getAllRemovedReviews($params = '') + { + $url = 'http://api.feedaty.com/Reviews/Removed'.$params; + return $this->getReviewsData($url); + } + public function getAllMediatedReviews($params = '') + { + $url = 'http://api.feedaty.com/Reviews/Mediated'.$params; + $mediated = $this->getReviewsData($url); + return $mediated; + } /** * @param string $params * @return mixed|string|null @@ -259,9 +290,16 @@ public function getTotalProductReviewsCount() */ public function getAllReviews($params = '') { - $merchant = $this->_configRules->getFeedatyCode(); - $secret = $this->_configRules->getFeedatySecret(); - $url = 'http://api.feedaty.com/Reviews/Get'.$params; + $url = 'http://api.feedaty.com/Reviews/Get'.$params; + return $this->getReviewsData($url); + } + + + + public function getReviewsData($url) + { + $merchant = $this->_configRules->getFeedatyCode(); + $secret = $this->_configRules->getFeedatySecret(); $token = ''; From 41494a468240a52fe1f5fc255d7b40cfb557d67c Mon Sep 17 00:00:00 2001 From: Marco Boatti Date: Sun, 3 Oct 2021 17:22:45 +0200 Subject: [PATCH 04/17] Disable removed Reviews --- Cron/Reviews.php | 140 ++++++++++++++++++++++++++++++----------------- 1 file changed, 90 insertions(+), 50 deletions(-) diff --git a/Cron/Reviews.php b/Cron/Reviews.php index d0ea0fb..f705b00 100644 --- a/Cron/Reviews.php +++ b/Cron/Reviews.php @@ -51,14 +51,14 @@ class Reviews * @param \Magento\Store\Model\StoreManagerInterface $storeManager */ public function __construct( - \Psr\Log\LoggerInterface $logger, + \Psr\Log\LoggerInterface $logger, \Feedaty\Badge\Model\Config\Source\WebService $webService, - \Magento\Review\Model\ReviewFactory $reviewFactory, - \Magento\Review\Model\RatingFactory $ratingFactory, - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Framework\Stdlib\DateTime\DateTime $date, - StoreRepositoryInterface $storeRepository, - \Magento\Sales\Api\OrderRepositoryInterface $orderRepository + \Magento\Review\Model\ReviewFactory $reviewFactory, + \Magento\Review\Model\RatingFactory $ratingFactory, + \Magento\Store\Model\StoreManagerInterface $storeManager, + \Magento\Framework\Stdlib\DateTime\DateTime $date, + StoreRepositoryInterface $storeRepository, + \Magento\Sales\Api\OrderRepositoryInterface $orderRepository ) { $this->logger = $logger; @@ -72,30 +72,41 @@ public function __construct( } - public function disableReview($reviewData){ + public function disableReview($reviewData) + { + + $this->logger->addInfo("FEEDATY DISABLE REVIEW REVIEW DATA: ID REW " . $reviewData['review_id']); + $review = null; + try { + $review = $this->_reviewFactory->create()->load($reviewData['review_id']); + } catch (\Exception $e) { + $this->logger->info("FEEDATY ERROR LINE 86 : " . $e->getMessage()); + } - $review = $this->_reviewFactory->create()->load($reviewData[0]['review_id']); - $review->setStatusId(\Magento\Review\Model\Review::STATUS_NOT_APPROVED)->save();; + if (!is_null($review)) { + $this->logger->addInfo("FEEDATY DISABLE REVIEW OBJECT: "); + $review->setStatusId(\Magento\Review\Model\Review::STATUS_NOT_APPROVED)->save(); + } } public function getStoreViewIdByOrder($orderId) { - $this->logger->addInfo("FEEDATY START GET STORE: ".$orderId ); + $this->logger->addInfo("FEEDATY START GET STORE: " . $orderId); $order = null; try { $order = $this->_orderRepository->get($orderId); } catch (\Exception $e) { - $this->logger->info("FEEDATY ERROR : ".$e->getMessage()); - $this->logger->info("FEEDATY ERROR : order id does not exist ".$orderId); + $this->logger->info("FEEDATY ERROR : " . $e->getMessage()); + $this->logger->info("FEEDATY ERROR : order id does not exist " . $orderId); } - if(!is_null($order)){ + if (!is_null($order)) { $websiteId = $order->getStore()->getWebsiteId(); - $this->logger->addInfo("FEEDATY ORDER websiteId: " .$websiteId); + $this->logger->addInfo("FEEDATY ORDER websiteId: " . $websiteId); return $websiteId; } @@ -112,7 +123,7 @@ function getAllStoreList() $storeIds = $store->getStoreId(); // store id } - $this->logger->addInfo("STORES LIST: " .print_r($storeList,true) ); + $this->logger->addInfo("STORES LIST: " . print_r($storeList, true)); return $storeIds; } @@ -123,7 +134,8 @@ function getAllStoreList() * @param $feedatyId * @return mixed */ - public function getReviewCollection($productId, $feedatyId){ + public function getReviewCollection($productId, $feedatyId) + { $collection = $this->_reviewFactory->create()->getCollection() ->addEntityFilter( 'product', @@ -141,7 +153,8 @@ public function getReviewCollection($productId, $feedatyId){ /* * Get last Review Created */ - public function getAllFeedatyReviewCount(){ + public function getAllFeedatyReviewCount() + { $collection = $this->_reviewFactory->create()->getCollection() ->addFieldToFilter( 'feedaty_source', @@ -153,11 +166,12 @@ public function getAllFeedatyReviewCount(){ ) ->setDateOrder(); - // $collection->getSelect()->group('feedaty_source_id'); + // $collection->getSelect()->group('feedaty_source_id'); return count($collection->getData()); } - public function getAllFeedatyRemovedReviewCount(){ + public function getAllFeedatyRemovedReviewCount() + { $collection = $this->_reviewFactory->create()->getCollection() ->addStatusFilter( \Magento\Review\Model\Review::STATUS_NOT_APPROVED) @@ -178,7 +192,8 @@ public function getAllFeedatyRemovedReviewCount(){ /* * Get last Review Created */ - public function getLastFeedatyReviewCreated(){ + public function getLastFeedatyReviewCreated() + { $collection = $this->_reviewFactory->create()->getCollection() ->addFieldToFilter( 'feedaty_source', @@ -195,7 +210,8 @@ public function getLastFeedatyReviewCreated(){ return $collection->getData(); } - public function getReviewByFeedatyId($feedatyid){ + public function getReviewByFeedatyId($feedatyid) + { $collection = $this->_reviewFactory->create()->getCollection() ->addFieldToFilter( 'feedaty_source_id', @@ -212,6 +228,21 @@ public function getReviewByFeedatyId($feedatyid){ return $collection->getData(); } + public function getAllReviewsByFeedatyId($feedatyid) + { + $collection = $this->_reviewFactory->create()->getCollection() + ->addFieldToFilter( + 'feedaty_source_id', + $feedatyid + ) + ->setOrder( + 'review_id', + 'desc' + ) + ->setDateOrder(); + + return $collection->getData(); + } /** @@ -228,6 +259,7 @@ public function getReviewData($reviewId) } return $review; } + /** * @throws \Magento\Framework\Exception\LocalizedException */ @@ -238,8 +270,8 @@ public function execute() $totalFeedatyRemovedReviews = $this->_webService->getTotalProductRemovedReviewsCount(); $totalReviewCreatedCount = $this->getAllFeedatyReviewCount(); $totalRemovedReviewCreatedCount = $this->getAllFeedatyRemovedReviewCount(); - $this->logger->addInfo("START - Cronjob Feedaty | Get Feedaty Reviews | date: " . date('Y-m-d H:i:s') . ' ---- Total Feedaty Product Reviews ' . $totalFeedatyReviews . ' totalReviewCreatedCount group by feedaty_id ' . $totalReviewCreatedCount ); - // $this->logger->addInfo("START - Cronjob Feedaty | STORES | date: " . $this->getAllStoreList() ); + $this->logger->addInfo("START - Cronjob Feedaty | Get Feedaty Reviews | date: " . date('Y-m-d H:i:s') . ' ---- Total Feedaty Product Reviews ' . $totalFeedatyReviews . ' totalReviewCreatedCount group by feedaty_id ' . $totalReviewCreatedCount); + // $this->logger->addInfo("START - Cronjob Feedaty | STORES | date: " . $this->getAllStoreList() ); //Get Last Review Created on Magento (on first run vill be null) $lastReviewCreated = $this->getLastFeedatyReviewCreated(); @@ -251,10 +283,10 @@ public function execute() ///// CREATE NEW REVIEWS //Get Feedaty Product Reviews - $feedatyProductReviews = $this->getProductReviewsPagination($row,$count); - if(!empty($feedatyProductReviews)){ + $feedatyProductReviews = $this->getProductReviewsPagination($row, $count); + if (!empty($feedatyProductReviews)) { //Foreach Review - foreach ($feedatyProductReviews as $review){ + foreach ($feedatyProductReviews as $review) { //feedaty_source_id $feedatyId = $review['ID']; @@ -265,11 +297,11 @@ public function execute() $replaceFromDate = ["/Date(", ")/"]; $replaceToDate = ["", ""]; //Review Date - $createdAt = date('Y-m-d h:i:s', floor((int)str_replace($replaceFromDate,$replaceToDate,$review['Released'])/ 1000)); + $createdAt = date('Y-m-d h:i:s', floor((int)str_replace($replaceFromDate, $replaceToDate, $review['Released']) / 1000)); //$reviewReleased =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){ + foreach ($review['ProductsReviews'] as $item) { $productId = $item['SKU']; @@ -285,46 +317,53 @@ public function execute() //TODO VERIFICARE website view if (empty($magentoProductReviews)) { - $this->createProductReview($productId, $feedatyId, $rating, $detail, $createdAt,$today,$row,$storeView); + $this->createProductReview($productId, $feedatyId, $rating, $detail, $createdAt, $today, $row, $storeView); // Product Review - $this->logger->addInfo("EXEC - Cronjob Feedaty create Product Review | date execution: ". date('Y-m-d H:i:s') ." | Product Id : ". $productId . " | Feedaty ID" .$feedatyId ); + $this->logger->addInfo("EXEC - Cronjob Feedaty create Product Review | date execution: " . date('Y-m-d H:i:s') . " | Product Id : " . $productId . " | Feedaty ID" . $feedatyId); } } } // General Cron Report on system.log - $this->logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date execution: ". date('Y-m-d H:i:s') ." -- Last Review Created " . print_r($lastReviewCreated,true) ." -- Review Date CreatedAt " . print_r($createdAt,true) ." -- Pagination " . $row); + $this->logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date execution: " . date('Y-m-d H:i:s') . " -- Last Review Created " . print_r($lastReviewCreated, true) . " -- Review Date CreatedAt " . print_r($createdAt, true) . " -- Pagination " . $row); } ///// DISABLE REMOVED REVIEWS /// $rowRemoved = $totalFeedatyRemovedReviews - $totalRemovedReviewCreatedCount - $count; - $this->logger->addInfo("REMOVED ITEMS ROWS ".$rowRemoved); - $this->logger->addInfo("REMOVED ITEMS totalFeedatyRemovedReviews ".$totalFeedatyRemovedReviews); - $this->logger->addInfo("REMOVED ITEMS ROWS totalRemovedReviewCreatedCount ".$totalRemovedReviewCreatedCount); + $this->logger->addInfo("REMOVED ITEMS ROWS " . $rowRemoved); + $this->logger->addInfo("REMOVED ITEMS totalFeedatyRemovedReviews " . $totalFeedatyRemovedReviews); + $this->logger->addInfo("REMOVED ITEMS ROWS totalRemovedReviewCreatedCount " . $totalRemovedReviewCreatedCount); - $feedatyProductReviewsRemoved = $this->getRemovedReviews($rowRemoved,$count); - if(!empty($feedatyProductReviewsRemoved)){ + $feedatyProductReviewsRemoved = $this->getRemovedReviews($rowRemoved, $count); + if (!empty($feedatyProductReviewsRemoved)) { - $this->logger->addInfo("START REMOVED - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: ". date('Y-m-d H:i:s') ); + $this->logger->addInfo("START REMOVED - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . print_r($feedatyProductReviewsRemoved,true)); //Foreach Review - foreach ($feedatyProductReviewsRemoved as $removedReview){ + foreach ($feedatyProductReviewsRemoved as $removedReview) { $feedatyId = $removedReview['MerchantFeedbackReviewID']; - $reviewToDisable = $this->getReviewByFeedatyId($feedatyId); - $this->logger->addInfo("REVIEW TO DISABLE OBJ - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: ". date('Y-m-d H:i:s') ." -- REVIEWS TO DISABLE " . print_r($reviewToDisable,true)); + $reviewToDisable = $this->getAllReviewsByFeedatyId($feedatyId); + $this->logger->addInfo("REVIEW TO DISABLE OBJ - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . date('Y-m-d H:i:s') . " -- REVIEWS TO DISABLE " . print_r($reviewToDisable, true)); - if(!empty($reviewToDisable)){ + if (!empty($reviewToDisable)) { //if it is not just disabled - if($reviewToDisable[0]['status_id'] != 3){ - $this->disableReview($reviewToDisable); - $this->logger->addInfo("REMOVED ITEM ID - : ". date('Y-m-d H:i:s') ." -- FeedatySourceID " . $feedatyId); - } + foreach ($reviewToDisable as $item){ + $this->logger->addInfo("REVIEW TO DISABLE ITEM LIN 341 - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . print_r($item, true)); + $this->logger->addInfo("ITEM ID TO DISABLE 357 : " . $item['review_id']); + $this->logger->addInfo("ITEM STATUS TO DISABLE 357 : " . $item['status_id']); + if ($item['status_id'] !== 3) { + $this->logger->addInfo("STATUS ENALBED"); + + $this->disableReview($item); + $this->logger->addInfo("REMOVED ITEM ID - : " . date('Y-m-d H:i:s') . " -- FeedatySourceID " . $feedatyId); + } + } } @@ -333,7 +372,7 @@ public function execute() } - // $this->logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date: ". date('Y-m-d H:i:s') ); + // $this->logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date: ". date('Y-m-d H:i:s') ); } public function getProductReviewsPagination($row, $count) @@ -343,11 +382,12 @@ public function getProductReviewsPagination($row, $count) public function getRemovedReviews($row, $count) { - return $this->_webService->getRemovedReviews($row, $count); + return $this->_webService->getRemovedReviews($row, $count); } - protected function createProductReview($productId, $feedatyId, $rating, $detail, $createdAt,$today,$row,$storeView){ + protected function createProductReview($productId, $feedatyId, $rating, $detail, $createdAt, $today, $row, $storeView) + { $reviewFinalData['ratings'][1] = $rating; $reviewFinalData['ratings'][2] = $rating; @@ -369,7 +409,7 @@ protected function createProductReview($productId, $feedatyId, $rating, $detail, ->setStatusId(\Magento\Review\Model\Review::STATUS_APPROVED) ->setStoreId($this->_storeManager->getStore()->getId()) //->setStores(!is_null($storeView) ? [$storeView] : $this->_storeManager->getStore()->getId()) - ->setStores(!is_null($storeView) ? [$storeView] : [0,1,2]) + ->setStores(!is_null($storeView) ? [$storeView] : [0, 1, 2]) ->save(); //Since the created_at is set only when the $object does not have an id, i save the object again. From 785fed20795c5825912a756841a1608ab10aae8f Mon Sep 17 00:00:00 2001 From: Marco Boatti Date: Sat, 16 Oct 2021 14:12:37 +0200 Subject: [PATCH 05/17] Update Mediate Reviews --- Cron/Reviews.php | 344 ++++++++++++------ Helper/ConfigRules.php | 6 + Model/Config/Source/WebService.php | 20 +- Model/ResourceModel/Review.php | 2 + Setup/UpgradeSchema.php | 48 ++- etc/adminhtml/system.xml | 13 +- etc/crontab.xml | 2 +- etc/module.xml | 2 +- view/frontend/layout/catalog_product_view.xml | 2 +- 9 files changed, 316 insertions(+), 123 deletions(-) diff --git a/Cron/Reviews.php b/Cron/Reviews.php index f705b00..84fab04 100644 --- a/Cron/Reviews.php +++ b/Cron/Reviews.php @@ -2,6 +2,7 @@ namespace Feedaty\Badge\Cron; +use Feedaty\Badge\Helper\ConfigRules; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Api\StoreRepositoryInterface; @@ -43,6 +44,11 @@ class Reviews protected $_orderRepository; + /** + * @var ConfigRules + */ + protected $_configRules; + /** * @param \Psr\Log\LoggerInterface $logger * @param \Feedaty\Badge\Model\Config\Source\WebService $webService @@ -58,7 +64,8 @@ public function __construct( \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\Stdlib\DateTime\DateTime $date, StoreRepositoryInterface $storeRepository, - \Magento\Sales\Api\OrderRepositoryInterface $orderRepository + \Magento\Sales\Api\OrderRepositoryInterface $orderRepository, + ConfigRules $configRules ) { $this->logger = $logger; @@ -69,13 +76,14 @@ public function __construct( $this->date = $date; $this->_storeRepository = $storeRepository; $this->_orderRepository = $orderRepository; + $this->_configRules = $configRules; } public function disableReview($reviewData) { - $this->logger->addInfo("FEEDATY DISABLE REVIEW REVIEW DATA: ID REW " . $reviewData['review_id']); + //$this->logger->addInfo("FEEDATY DISABLE REVIEW REVIEW DATA: ID REW " . $reviewData['review_id']); $review = null; try { $review = $this->_reviewFactory->create()->load($reviewData['review_id']); @@ -84,15 +92,35 @@ public function disableReview($reviewData) } if (!is_null($review)) { - $this->logger->addInfo("FEEDATY DISABLE REVIEW OBJECT: "); + // $this->logger->addInfo("FEEDATY DISABLE REVIEW OBJECT: "); $review->setStatusId(\Magento\Review\Model\Review::STATUS_NOT_APPROVED)->save(); } } + + public function mediateReview($reviewData, $reviewDetail) + { + + $this->logger->addInfo("FEEDATY MEDIATE REVIEW REVIEW DATA: ID REW " . $reviewData['review_id']); + $review = null; + try { + $review = $this->_reviewFactory->create()->load($reviewData['review_id']); + } catch (\Exception $e) { + $this->logger->info("FEEDATY ERROR LINE 86 : " . $e->getMessage()); + } + + if (!is_null($review)) { + $this->logger->addInfo("FEEDATY MEDIATE REVIEW OBJECT: "); + $review->setDetail($reviewDetail)->save(); + $review->setFeedatyProductMediated(1)->save(); + } + + } + public function getStoreViewIdByOrder($orderId) { - $this->logger->addInfo("FEEDATY START GET STORE: " . $orderId); + // $this->logger->addInfo("FEEDATY START GET STORE: " . $orderId); $order = null; try { $order = $this->_orderRepository->get($orderId); @@ -123,7 +151,7 @@ function getAllStoreList() $storeIds = $store->getStoreId(); // store id } - $this->logger->addInfo("STORES LIST: " . print_r($storeList, true)); + // $this->logger->addInfo("STORES LIST: " . print_r($storeList, true)); return $storeIds; } @@ -189,33 +217,32 @@ public function getAllFeedatyRemovedReviewCount() return count($collection->getData()); } - /* - * Get last Review Created - */ - public function getLastFeedatyReviewCreated() + public function getAllFeedatyMediatedReviewCount() { $collection = $this->_reviewFactory->create()->getCollection() ->addFieldToFilter( - 'feedaty_source', + 'feedaty_product_mediated', 1 ) ->setOrder( 'review_id', 'desc' ) - ->setPageSize(1) - ->setCurPage(1) ->setDateOrder(); - return $collection->getData(); + // $collection->getSelect()->group('feedaty_source_id'); + return count($collection->getData()); } - public function getReviewByFeedatyId($feedatyid) + /* + * Get last Review Created + */ + public function getLastFeedatyReviewCreated() { $collection = $this->_reviewFactory->create()->getCollection() ->addFieldToFilter( - 'feedaty_source_id', - $feedatyid + 'feedaty_source', + 1 ) ->setOrder( 'review_id', @@ -228,11 +255,12 @@ public function getReviewByFeedatyId($feedatyid) return $collection->getData(); } + public function getAllReviewsByFeedatyId($feedatyid) { $collection = $this->_reviewFactory->create()->getCollection() ->addFieldToFilter( - 'feedaty_source_id', + 'feedaty_product_review_id', $feedatyid ) ->setOrder( @@ -245,20 +273,6 @@ public function getAllReviewsByFeedatyId($feedatyid) } - /** - * Review Data - * - * @return Review - */ - public function getReviewData($reviewId) - { - try { - $review = $this->_reviewFactory->create()->load($reviewId); - } catch (LocalizedException $exception) { - throw new LocalizedException(__($exception->getMessage())); - } - return $review; - } /** * @throws \Magento\Framework\Exception\LocalizedException @@ -266,132 +280,240 @@ public function getReviewData($reviewId) public function execute() { - $totalFeedatyReviews = $this->_webService->getTotalProductReviewsCount(); - $totalFeedatyRemovedReviews = $this->_webService->getTotalProductRemovedReviewsCount(); - $totalReviewCreatedCount = $this->getAllFeedatyReviewCount(); - $totalRemovedReviewCreatedCount = $this->getAllFeedatyRemovedReviewCount(); - $this->logger->addInfo("START - Cronjob Feedaty | Get Feedaty Reviews | date: " . date('Y-m-d H:i:s') . ' ---- Total Feedaty Product Reviews ' . $totalFeedatyReviews . ' totalReviewCreatedCount group by feedaty_id ' . $totalReviewCreatedCount); - // $this->logger->addInfo("START - Cronjob Feedaty | STORES | date: " . $this->getAllStoreList() ); + /** + * IF IMPORT IS ENABLED + */ + $enableImportReviews = $this->_configRules->getCreateReviewEnabled(); + + if($enableImportReviews == 1){ - //Get Last Review Created on Magento (on first run vill be null) - $lastReviewCreated = $this->getLastFeedatyReviewCreated(); + /** + * Get Feedaty TotalProductReviews Count + */ + $totalFeedatyReviews = $this->_webService->getTotalProductReviewsCount(); - $count = 100; // get x reviews + /** + * Get Feedaty Removed Reviews TotalResults Count + */ + $totalFeedatyRemovedReviews = $this->_webService->getTotalProductRemovedReviewsCount(); - $row = $totalFeedatyReviews - $totalReviewCreatedCount - $count; + /** + * Get Feedaty Removed Reviews TotalResults Count + */ + $totalFeedatyMediatedReviews = $this->_webService->getTotalProductMediatedReviewsCount(); - ///// CREATE NEW REVIEWS - //Get Feedaty Product Reviews - $feedatyProductReviews = $this->getProductReviewsPagination($row, $count); - if (!empty($feedatyProductReviews)) { - //Foreach Review - foreach ($feedatyProductReviews as $review) { - //feedaty_source_id - $feedatyId = $review['ID']; + /** + * Get Feedaty Reviews Created on Magento Total Count + */ + $totalReviewCreatedCount = $this->getAllFeedatyReviewCount(); - $orderId = $review['OrderID']; + /** + * Get Feedaty Reviews Removed on Magento Total Count + */ + $totalRemovedReviewCreatedCount = $this->getAllFeedatyRemovedReviewCount(); - $storeView = $this->getStoreViewIdByOrder($orderId); - $replaceFromDate = ["/Date(", ")/"]; - $replaceToDate = ["", ""]; - //Review Date - $createdAt = date('Y-m-d h:i:s', floor((int)str_replace($replaceFromDate, $replaceToDate, $review['Released']) / 1000)); - //$reviewReleased =date('Y-m-d h:i:s', floor((int)str_replace($replaceFromDate,$replaceToDate,$review['Released'])/ 1000)); + /** + * Get Feedaty Reviews Removed on Magento Total Count + */ + $totalMediatedReviewCreatedCount = $this->getAllFeedatyMediatedReviewCount(); - $today = $this->date->gmtDate(); - foreach ($review['ProductsReviews'] as $item) { - $productId = $item['SKU']; + $this->logger->addInfo("START - Cronjob Feedaty | Get Feedaty Reviews | date: " . date('Y-m-d H:i:s') . ' ---- Total Feedaty Product Reviews ' . $totalFeedatyReviews . ' totalReviewCreatedCount group by feedaty_id ' . $totalReviewCreatedCount); - //Get Feedaty Product Reviews - $magentoProductReviews = $this->getReviewCollection($productId, $feedatyId); + /** + * Get Last Review Created on Magento (on first run vill be null) + */ + $lastReviewCreated = $this->getLastFeedatyReviewCreated(); - //AP Rating node - $rating = $item['Rating']; + /** + * Get n Reviews from Feedaty + */ + $count = 100; - //API Review Node - $detail = $item['Review']; + /** + * Set Row Param from Feedaty + */ + $row = $totalFeedatyReviews - $totalReviewCreatedCount - $count; - //TODO VERIFICARE website view + $this->logger->addInfo("MEDIATED LINE 339 " ); - if (empty($magentoProductReviews)) { - $this->createProductReview($productId, $feedatyId, $rating, $detail, $createdAt, $today, $row, $storeView); + /** + * CREATE NEW REVIEWS + */ + //Get Feedaty Product Reviews Data + $feedatyProductReviews = $this->_webService->getProductReviewsPagination($row, $count); - // Product Review - $this->logger->addInfo("EXEC - Cronjob Feedaty create Product Review | date execution: " . date('Y-m-d H:i:s') . " | Product Id : " . $productId . " | Feedaty ID" . $feedatyId); + $this->logger->addInfo("MEDIATED LINE 347 " ); + if (!empty($feedatyProductReviews)) { + //Foreach Review + foreach ($feedatyProductReviews as $review) { + //feedaty_source_id + $feedatyId = $review['ID']; + + $orderId = $review['OrderID']; + + $storeView = $this->getStoreViewIdByOrder($orderId); + + $replaceFromDate = ["/Date(", ")/"]; + $replaceToDate = ["", ""]; + //Review Date + $createdAt = date('Y-m-d h:i:s', floor((int)str_replace($replaceFromDate, $replaceToDate, $review['Released']) / 1000)); + //$reviewReleased =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->getReviewCollection($productId, $feedatyId); + + //AP Rating node + $rating = $item['Rating']; + + //API Review Node + $detail = $item['Review']; + + //TODO VERIFICARE website view + + if (empty($magentoProductReviews)) { + $this->createProductReview($productId, $feedatyId, $feedatyProductReviewId, $rating, $detail, $createdAt, $today, $row, $storeView); + + // Product Review + // $this->logger->addInfo("EXEC - Cronjob Feedaty create Product Review | date execution: " . date('Y-m-d H:i:s') . " | Product Id : " . $productId . " | Feedaty ID" . $feedatyId); + + } } } + // General Cron Report on system.log + $this->logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date execution: " . date('Y-m-d H:i:s') . " -- Last Review Created " . print_r($lastReviewCreated, true) . " -- Review Date CreatedAt " . print_r($createdAt, true) . " -- Pagination " . $row); } - // General Cron Report on system.log - $this->logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date execution: " . date('Y-m-d H:i:s') . " -- Last Review Created " . print_r($lastReviewCreated, true) . " -- Review Date CreatedAt " . print_r($createdAt, true) . " -- Pagination " . $row); - } - ///// DISABLE REMOVED REVIEWS - /// - $rowRemoved = $totalFeedatyRemovedReviews - $totalRemovedReviewCreatedCount - $count; + /** + * UPDATE MEDIATED REVIEWS + */ - $this->logger->addInfo("REMOVED ITEMS ROWS " . $rowRemoved); - $this->logger->addInfo("REMOVED ITEMS totalFeedatyRemovedReviews " . $totalFeedatyRemovedReviews); - $this->logger->addInfo("REMOVED ITEMS ROWS totalRemovedReviewCreatedCount " . $totalRemovedReviewCreatedCount); + $this->logger->addInfo("MEDIATED LINE 397 " ); + + $rowMediated = $totalFeedatyMediatedReviews - $totalMediatedReviewCreatedCount - $count; + + if($rowMediated < 0 ){ + $this->logger->addInfo("ROW MEDIATED IS ZERO " ); + $rowMediated = 0; + } + $this->logger->addInfo("MEDIATED ITEMS ROWS " .$rowMediated); + $this->logger->addInfo("MEDIATED ITEMS totalFeedatyMediatedReviews " . $totalFeedatyMediatedReviews); + $this->logger->addInfo("MEDIATED ITEMS totalMediatedReviewCreatedCount " . $totalMediatedReviewCreatedCount); - $feedatyProductReviewsRemoved = $this->getRemovedReviews($rowRemoved, $count); - if (!empty($feedatyProductReviewsRemoved)) { + /** + * Get Feedaty Mediated Reviews + */ + $feedatyProductReviewsMediated = $this->_webService->getMediatedReviews($rowMediated, $count); - $this->logger->addInfo("START REMOVED - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . print_r($feedatyProductReviewsRemoved,true)); + $this->logger->addInfo("MEDIATED ITEMS feedatyProductReviewsMediated " . print_r($feedatyProductReviewsMediated)); - //Foreach Review - foreach ($feedatyProductReviewsRemoved as $removedReview) { + if (!empty($feedatyProductReviewsMediated)) { - $feedatyId = $removedReview['MerchantFeedbackReviewID']; + $this->logger->addInfo("START MEDIATED - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . print_r($feedatyProductReviewsMediated,true)); - $reviewToDisable = $this->getAllReviewsByFeedatyId($feedatyId); - $this->logger->addInfo("REVIEW TO DISABLE OBJ - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . date('Y-m-d H:i:s') . " -- REVIEWS TO DISABLE " . print_r($reviewToDisable, true)); + //Foreach Review + foreach ($feedatyProductReviewsMediated as $mediatedReview) { - if (!empty($reviewToDisable)) { - //if it is not just disabled - foreach ($reviewToDisable as $item){ - $this->logger->addInfo("REVIEW TO DISABLE ITEM LIN 341 - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . print_r($item, true)); - $this->logger->addInfo("ITEM ID TO DISABLE 357 : " . $item['review_id']); - $this->logger->addInfo("ITEM STATUS TO DISABLE 357 : " . $item['status_id']); + $feedatyId = $mediatedReview['FeedbackReviewID']; + $reviewDetail = $mediatedReview['MerchantReview']; - if ($item['status_id'] !== 3) { - $this->logger->addInfo("STATUS ENALBED"); + $reviewToMediate = $this->getAllReviewsByFeedatyId($feedatyId); + // $this->logger->addInfo("REVIEW TO DISABLE OBJ - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . date('Y-m-d H:i:s') . " -- REVIEWS TO DISABLE " . print_r($reviewToDisable, true)); - $this->disableReview($item); - $this->logger->addInfo("REMOVED ITEM ID - : " . date('Y-m-d H:i:s') . " -- FeedatySourceID " . $feedatyId); + if (!empty($reviewToMediate)) { + //if it is not just disabled + foreach ($reviewToMediate as $item){ +// $this->logger->addInfo("REVIEW TO DISABLE ITEM LIN 341 - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . print_r($item, true)); +// $this->logger->addInfo("ITEM ID TO DISABLE 357 : " . $item['review_id']); +// $this->logger->addInfo("ITEM STATUS TO DISABLE 357 : " . $item['status_id']); + + if ($item['status_id'] !== 3) { + $this->logger->addInfo("STATUS ENALBED"); + + $this->mediateReview($item,$reviewDetail); + $this->logger->addInfo("MEDIATED ITEM ID - : " . date('Y-m-d H:i:s') . " -- FeedatySourceID " . $feedatyId); + } } + } } - + // General Cron Report on system.log } - // General Cron Report on system.log - } - // $this->logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date: ". date('Y-m-d H:i:s') ); - } + /** + * DISABLE REMOVED REVIEWS + */ - public function getProductReviewsPagination($row, $count) - { - return $this->_webService->getProductReviewsPagination($row, $count); - } + $rowRemoved = $totalFeedatyRemovedReviews - $totalRemovedReviewCreatedCount - $count; + +// $this->logger->addInfo("REMOVED ITEMS ROWS " . $rowRemoved); +// $this->logger->addInfo("REMOVED ITEMS totalFeedatyRemovedReviews " . $totalFeedatyRemovedReviews); +// $this->logger->addInfo("REMOVED ITEMS ROWS totalRemovedReviewCreatedCount " . $totalRemovedReviewCreatedCount); +// + /** + * Get Feedaty Removed Reviews + */ + $feedatyProductReviewsRemoved = $this->_webService->getRemovedReviews($rowRemoved, $count); + + + if (!empty($feedatyProductReviewsRemoved)) { + + // $this->logger->addInfo("START REMOVED - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . print_r($feedatyProductReviewsRemoved,true)); + + //Foreach Review + foreach ($feedatyProductReviewsRemoved as $removedReview) { + + $feedatyId = $removedReview['FeedbackReviewID']; + + $reviewToDisable = $this->getAllReviewsByFeedatyId($feedatyId); + // $this->logger->addInfo("REVIEW TO DISABLE OBJ - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . date('Y-m-d H:i:s') . " -- REVIEWS TO DISABLE " . print_r($reviewToDisable, true)); + + if (!empty($reviewToDisable)) { + //if it is not just disabled + foreach ($reviewToDisable as $item){ +// $this->logger->addInfo("REVIEW TO DISABLE ITEM LIN 341 - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . print_r($item, true)); +// $this->logger->addInfo("ITEM ID TO DISABLE 357 : " . $item['review_id']); +// $this->logger->addInfo("ITEM STATUS TO DISABLE 357 : " . $item['status_id']); + + if ($item['status_id'] !== 3) { + // $this->logger->addInfo("STATUS ENALBED"); + + $this->disableReview($item); + // $this->logger->addInfo("REMOVED ITEM ID - : " . date('Y-m-d H:i:s') . " -- FeedatySourceID " . $feedatyId); + } + } + + } + + } + // General Cron Report on system.log + } + } + else{ + $this->logger->addInfo("Feedaty Cronjob is not enabled | date: ". date('Y-m-d H:i:s') ); + } - public function getRemovedReviews($row, $count) - { - return $this->_webService->getRemovedReviews($row, $count); } - protected function createProductReview($productId, $feedatyId, $rating, $detail, $createdAt, $today, $row, $storeView) + protected function createProductReview($productId, $feedatyId, $feedatyProductReviewId, $rating, $detail, $createdAt, $today, $row, $storeView) { $reviewFinalData['ratings'][1] = $rating; $reviewFinalData['ratings'][2] = $rating; $reviewFinalData['ratings'][3] = $rating; + $reviewFinalData['ratings'][4] = $rating; $reviewFinalData['nickname'] = "Feedaty"; $reviewFinalData['title'] = "Acquirente Verificato"; @@ -399,8 +521,10 @@ protected function createProductReview($productId, $feedatyId, $rating, $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'); diff --git a/Helper/ConfigRules.php b/Helper/ConfigRules.php index 73d53f8..9952e6e 100644 --- a/Helper/ConfigRules.php +++ b/Helper/ConfigRules.php @@ -62,4 +62,10 @@ public function getFeedatySecret() { return $feedaty_code; } + public function getCreateReviewEnabled() { + $feedaty_code = $this->getPreferencesConfig('create_reviews_enabled'); + + return $feedaty_code; + } + } diff --git a/Model/Config/Source/WebService.php b/Model/Config/Source/WebService.php index aeb6f5a..c3f7f9d 100755 --- a/Model/Config/Source/WebService.php +++ b/Model/Config/Source/WebService.php @@ -252,6 +252,15 @@ public function getRemovedReviews($row = 0, $count = 50){ } + public function getMediatedReviews($row = 0, $count = 50){ + $allReviews = $this->getAllMediatedReviews('?row='.$row.'&count='.$count); + + $this->_logger->info('ALL REMOVED REVIEW FEEDATY REMOVED: '. print_r($allReviews['Reviews'],true)); + + return $allReviews['Reviews']; + + } + public function getTotalProductReviewsCount() { $allProductReviews = $this->getAllReviews('?retrieve=onlyproductreviews&row=0&count=1'); @@ -264,7 +273,16 @@ public function getTotalProductReviewsCount() public function getTotalProductRemovedReviewsCount() { $allProductReviews = $this->getAllRemovedReviews('?row=0&count=1'); - $this->_logger->info('Feedaty REMOVED: '. print_r($allProductReviews,true)); + // $this->_logger->info('Feedaty REMOVED: '. print_r($allProductReviews,true)); + $totalResults = $allProductReviews['TotalResults']; + + return $totalResults; + } + + public function getTotalProductMediatedReviewsCount() + { + $allProductReviews = $this->getAllMediatedReviews('?row=0&count=1'); + $this->_logger->info('Feedaty MEDIATED: '. print_r($allProductReviews,true)); $totalResults = $allProductReviews['TotalResults']; return $totalResults; diff --git a/Model/ResourceModel/Review.php b/Model/ResourceModel/Review.php index 36191f3..39544b2 100644 --- a/Model/ResourceModel/Review.php +++ b/Model/ResourceModel/Review.php @@ -27,9 +27,11 @@ protected function _afterSave(AbstractModel $object) '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()]); diff --git a/Setup/UpgradeSchema.php b/Setup/UpgradeSchema.php index f2b123d..c8cfa81 100644 --- a/Setup/UpgradeSchema.php +++ b/Setup/UpgradeSchema.php @@ -68,7 +68,6 @@ public function upgrade( SchemaSetupInterface $setup, ModuleContextInterface $co } - if(version_compare($context->getVersion(), '2.7.1') < 0) { $feedatyTable = $setup->getTable('feedaty_badge_settings'); @@ -109,6 +108,53 @@ public function upgrade( SchemaSetupInterface $setup, ModuleContextInterface $co } + if(version_compare($context->getVersion(), '2.7.2') < 0) { + + $tableName = $setup->getTable('review_detail'); + + if ($setup->getConnection()->isTableExists($tableName) == true) { + $columns = [ + 'feedaty_product_review_id' => [ + 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, + 'nullable' => false, + 'default' => 0, + 'comment' => 'Feedaty Product Review ID', + ] + ]; + + $connection = $setup->getConnection(); + + foreach ($columns as $name => $definition) { + $connection->addColumn($tableName, $name, $definition); + } + } + + } + + + if(version_compare($context->getVersion(), '2.7.3') < 0) { + + $tableName = $setup->getTable('review_detail'); + + if ($setup->getConnection()->isTableExists($tableName) == true) { + $columns = [ + '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); + } + } + + } + $installer->endSetup(); } } diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 9f02348..0b48cd0 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -20,6 +20,11 @@ validate-alphanum + + + + Magento\Config\Model\Config\Source\Yesno + @@ -79,14 +84,6 @@ - - - - - Magento\Config\Model\Config\Source\Yesno - - -
diff --git a/etc/crontab.xml b/etc/crontab.xml index 52b1e7d..92453cd 100644 --- a/etc/crontab.xml +++ b/etc/crontab.xml @@ -1,7 +1,7 @@ - + */2 * * * * diff --git a/etc/module.xml b/etc/module.xml index d48f99c..70a3b14 100755 --- a/etc/module.xml +++ b/etc/module.xml @@ -1,6 +1,6 @@ - + diff --git a/view/frontend/layout/catalog_product_view.xml b/view/frontend/layout/catalog_product_view.xml index 7e9943f..98ade5c 100644 --- a/view/frontend/layout/catalog_product_view.xml +++ b/view/frontend/layout/catalog_product_view.xml @@ -2,7 +2,7 @@ - Date: Fri, 22 Oct 2021 08:36:59 +0200 Subject: [PATCH 06/17] row Removed fix --- Cron/Reviews.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Cron/Reviews.php b/Cron/Reviews.php index 84fab04..0803ae8 100644 --- a/Cron/Reviews.php +++ b/Cron/Reviews.php @@ -457,6 +457,10 @@ public function execute() $rowRemoved = $totalFeedatyRemovedReviews - $totalRemovedReviewCreatedCount - $count; + if($rowRemoved < 0 ){ + $this->logger->addInfo("ROW REMOVED IS ZERO " ); + $rowRemoved = 0; + } // $this->logger->addInfo("REMOVED ITEMS ROWS " . $rowRemoved); // $this->logger->addInfo("REMOVED ITEMS totalFeedatyRemovedReviews " . $totalFeedatyRemovedReviews); // $this->logger->addInfo("REMOVED ITEMS ROWS totalRemovedReviewCreatedCount " . $totalRemovedReviewCreatedCount); @@ -533,7 +537,7 @@ protected function createProductReview($productId, $feedatyId, $feedatyProductRe ->setStatusId(\Magento\Review\Model\Review::STATUS_APPROVED) ->setStoreId($this->_storeManager->getStore()->getId()) //->setStores(!is_null($storeView) ? [$storeView] : $this->_storeManager->getStore()->getId()) - ->setStores(!is_null($storeView) ? [$storeView] : [0, 1, 2]) + ->setStores(!is_null($storeView) ? [$storeView] : [0,1]) ->save(); //Since the created_at is set only when the $object does not have an id, i save the object again. @@ -544,6 +548,7 @@ protected function createProductReview($productId, $feedatyId, $feedatyProductRe $this->_ratingFactory->create() ->setRatingId($ratingId) ->setReviewId($review->getId()) + ->setRatingSummary(4) ->addOptionVote($optionId, $productId); } From 7ed7637a8d4fa30fd9391aced84c657220750b2d Mon Sep 17 00:00:00 2001 From: Marco Boatti Date: Sat, 23 Oct 2021 14:57:31 +0200 Subject: [PATCH 07/17] getRatingCollection --- Cron/Reviews.php | 37 ++++++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/Cron/Reviews.php b/Cron/Reviews.php index 0803ae8..ee7df0a 100644 --- a/Cron/Reviews.php +++ b/Cron/Reviews.php @@ -55,6 +55,10 @@ class Reviews * @param \Magento\Review\Model\ReviewFactory $reviewFactory * @param \Magento\Review\Model\RatingFactory $ratingFactory * @param \Magento\Store\Model\StoreManagerInterface $storeManager + * @param \Magento\Framework\Stdlib\DateTime\DateTime $date + * @param StoreRepositoryInterface $storeRepository + * @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository + * @param ConfigRules $configRules */ public function __construct( \Psr\Log\LoggerInterface $logger, @@ -273,6 +277,15 @@ public function getAllReviewsByFeedatyId($feedatyid) } + public function getRatingCollection(){ + + $this->logger->addInfo("COLLECT RATING"); + + $ratingCollection = $this->_ratingFactory->create()->getResourceCollection()->addEntityFilter('product')->load(); + + return $ratingCollection->getData(); + + } /** * @throws \Magento\Framework\Exception\LocalizedException @@ -514,10 +527,15 @@ public function execute() protected function createProductReview($productId, $feedatyId, $feedatyProductReviewId, $rating, $detail, $createdAt, $today, $row, $storeView) { - $reviewFinalData['ratings'][1] = $rating; - $reviewFinalData['ratings'][2] = $rating; - $reviewFinalData['ratings'][3] = $rating; - $reviewFinalData['ratings'][4] = $rating; + $ratingCollection = $this->getRatingCollection(); + + foreach ($ratingCollection as $ratingItem){ + $this->logger->addInfo("RATING ID " . $ratingItem['rating_id']); + $reviewFinalData['ratings'][$ratingItem['rating_id']] = $rating; + } + + $this->logger->addInfo("RATING COLLECTION " . print_r($ratingCollection,true)); + $reviewFinalData['nickname'] = "Feedaty"; $reviewFinalData['title'] = "Acquirente Verificato"; @@ -536,23 +554,20 @@ protected function createProductReview($productId, $feedatyId, $feedatyProductRe ->setEntityPkValue($productId) ->setStatusId(\Magento\Review\Model\Review::STATUS_APPROVED) ->setStoreId($this->_storeManager->getStore()->getId()) - //->setStores(!is_null($storeView) ? [$storeView] : $this->_storeManager->getStore()->getId()) - ->setStores(!is_null($storeView) ? [$storeView] : [0,1]) + ->setStores(!is_null($storeView) ? [$storeView] : [$this->_storeManager->getStore()->getId()]) + // ->setStores([$this->_storeManager->getStore()->getId()]) ->save(); - //Since the created_at is set only when the $object does not have an id, i save the object again. - $review->setCreatedAt($createdAt)->save(); - //$review->setCreatedAt('2018-07-31 11:30:05')->save(); - foreach ($reviewFinalData['ratings'] as $ratingId => $optionId) { $this->_ratingFactory->create() ->setRatingId($ratingId) ->setReviewId($review->getId()) - ->setRatingSummary(4) ->addOptionVote($optionId, $productId); } $review->aggregate(); + + $review->setCreatedAt($createdAt)->save(); } } From f210c80f6b79ff9f2248818fa157beed482ccf52 Mon Sep 17 00:00:00 2001 From: Marco Boatti Date: Wed, 27 Oct 2021 09:00:05 +0200 Subject: [PATCH 08/17] Recoding --- Cron/Reviews.php | 331 ++++------------------------- Helper/Reviews.php | 269 +++++++++++++++++++++++ Model/Config/Source/WebService.php | 2 +- 3 files changed, 311 insertions(+), 291 deletions(-) create mode 100644 Helper/Reviews.php diff --git a/Cron/Reviews.php b/Cron/Reviews.php index ee7df0a..5ceab75 100644 --- a/Cron/Reviews.php +++ b/Cron/Reviews.php @@ -3,8 +3,10 @@ namespace Feedaty\Badge\Cron; use Feedaty\Badge\Helper\ConfigRules; +use Feedaty\Badge\Helper\Reviews as ReviewsHelper; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Api\StoreRepositoryInterface; +use Magento\Store\Model\Store; class Reviews @@ -12,7 +14,7 @@ class Reviews /** * @var \Psr\Log\LoggerInterface */ - protected $logger; + protected $_logger; /** * @var \Feedaty\Badge\Model\Config\Source\WebService */ @@ -33,21 +35,17 @@ class Reviews /** * @var \Magento\Framework\Stdlib\DateTime\DateTime */ - protected $date; - + protected $_date; /** - * @var StoreRepositoryInterface + * @var ConfigRules */ - private $_storeRepository; - - - protected $_orderRepository; + protected $_configRules; /** - * @var ConfigRules + * @var ReviewsHelper */ - protected $_configRules; + protected $_reviewsHelper; /** * @param \Psr\Log\LoggerInterface $logger @@ -56,9 +54,8 @@ class Reviews * @param \Magento\Review\Model\RatingFactory $ratingFactory * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Magento\Framework\Stdlib\DateTime\DateTime $date - * @param StoreRepositoryInterface $storeRepository - * @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository * @param ConfigRules $configRules + * @param ReviewsHelper $reviewsHelper */ public function __construct( \Psr\Log\LoggerInterface $logger, @@ -67,232 +64,26 @@ public function __construct( \Magento\Review\Model\RatingFactory $ratingFactory, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\Stdlib\DateTime\DateTime $date, - StoreRepositoryInterface $storeRepository, - \Magento\Sales\Api\OrderRepositoryInterface $orderRepository, - ConfigRules $configRules + ConfigRules $configRules, + ReviewsHelper $reviewsHelper ) { - $this->logger = $logger; + $this->_logger = $logger; $this->_webService = $webService; $this->_reviewFactory = $reviewFactory; $this->_ratingFactory = $ratingFactory; $this->_storeManager = $storeManager; - $this->date = $date; - $this->_storeRepository = $storeRepository; - $this->_orderRepository = $orderRepository; + $this->_date = $date; $this->_configRules = $configRules; - } - - - public function disableReview($reviewData) - { - - //$this->logger->addInfo("FEEDATY DISABLE REVIEW REVIEW DATA: ID REW " . $reviewData['review_id']); - $review = null; - try { - $review = $this->_reviewFactory->create()->load($reviewData['review_id']); - } catch (\Exception $e) { - $this->logger->info("FEEDATY ERROR LINE 86 : " . $e->getMessage()); - } - - if (!is_null($review)) { - // $this->logger->addInfo("FEEDATY DISABLE REVIEW OBJECT: "); - $review->setStatusId(\Magento\Review\Model\Review::STATUS_NOT_APPROVED)->save(); - } - - } - - - public function mediateReview($reviewData, $reviewDetail) - { - - $this->logger->addInfo("FEEDATY MEDIATE REVIEW REVIEW DATA: ID REW " . $reviewData['review_id']); - $review = null; - try { - $review = $this->_reviewFactory->create()->load($reviewData['review_id']); - } catch (\Exception $e) { - $this->logger->info("FEEDATY ERROR LINE 86 : " . $e->getMessage()); - } - - if (!is_null($review)) { - $this->logger->addInfo("FEEDATY MEDIATE REVIEW OBJECT: "); - $review->setDetail($reviewDetail)->save(); - $review->setFeedatyProductMediated(1)->save(); - } - - } - - public function getStoreViewIdByOrder($orderId) - { - // $this->logger->addInfo("FEEDATY START GET STORE: " . $orderId); - $order = null; - try { - $order = $this->_orderRepository->get($orderId); - - } catch (\Exception $e) { - $this->logger->info("FEEDATY ERROR : " . $e->getMessage()); - $this->logger->info("FEEDATY ERROR : order id does not exist " . $orderId); - - } - - - if (!is_null($order)) { - $websiteId = $order->getStore()->getWebsiteId(); - $this->logger->addInfo("FEEDATY ORDER websiteId: " . $websiteId); - return $websiteId; - } - - return null; - - } - - function getAllStoreList() - { - $storeList = $this->_storeRepository->getList(); - - $storeIds = array(); - foreach ($storeList as $store) { - $storeIds = $store->getStoreId(); // store id - } - - // $this->logger->addInfo("STORES LIST: " . print_r($storeList, true)); - - return $storeIds; + $this->_reviewsHelper = $reviewsHelper; } - /** - * @param $productId - * @param $feedatyId - * @return mixed - */ - public function getReviewCollection($productId, $feedatyId) - { - $collection = $this->_reviewFactory->create()->getCollection() - ->addEntityFilter( - 'product', - $productId - ) - ->addFieldToFilter( - 'feedaty_source_id', - $feedatyId - ) - ->setDateOrder(); - - return $collection->getData(); - } - - /* - * Get last Review Created - */ - public function getAllFeedatyReviewCount() - { - $collection = $this->_reviewFactory->create()->getCollection() - ->addFieldToFilter( - 'feedaty_source', - 1 - ) - ->setOrder( - 'review_id', - 'desc' - ) - ->setDateOrder(); - - // $collection->getSelect()->group('feedaty_source_id'); - return count($collection->getData()); - } - - public function getAllFeedatyRemovedReviewCount() - { - $collection = $this->_reviewFactory->create()->getCollection() - ->addStatusFilter( - \Magento\Review\Model\Review::STATUS_NOT_APPROVED) - ->addFieldToFilter( - 'feedaty_source', - 1 - ) - ->setOrder( - 'review_id', - 'desc' - ) - ->setDateOrder(); - - // $collection->getSelect()->group('feedaty_source_id'); - return count($collection->getData()); - } - - public function getAllFeedatyMediatedReviewCount() - { - $collection = $this->_reviewFactory->create()->getCollection() - ->addFieldToFilter( - 'feedaty_product_mediated', - 1 - ) - ->setOrder( - 'review_id', - 'desc' - ) - ->setDateOrder(); - - // $collection->getSelect()->group('feedaty_source_id'); - return count($collection->getData()); - } - - /* - * Get last Review Created - */ - public function getLastFeedatyReviewCreated() - { - $collection = $this->_reviewFactory->create()->getCollection() - ->addFieldToFilter( - 'feedaty_source', - 1 - ) - ->setOrder( - 'review_id', - 'desc' - ) - ->setPageSize(1) - ->setCurPage(1) - ->setDateOrder(); - - return $collection->getData(); - } - - - public function getAllReviewsByFeedatyId($feedatyid) - { - $collection = $this->_reviewFactory->create()->getCollection() - ->addFieldToFilter( - 'feedaty_product_review_id', - $feedatyid - ) - ->setOrder( - 'review_id', - 'desc' - ) - ->setDateOrder(); - - return $collection->getData(); - } - - - public function getRatingCollection(){ - - $this->logger->addInfo("COLLECT RATING"); - - $ratingCollection = $this->_ratingFactory->create()->getResourceCollection()->addEntityFilter('product')->load(); - - return $ratingCollection->getData(); - - } - /** * @throws \Magento\Framework\Exception\LocalizedException */ public function execute() { - /** * IF IMPORT IS ENABLED */ @@ -310,7 +101,6 @@ public function execute() */ $totalFeedatyRemovedReviews = $this->_webService->getTotalProductRemovedReviewsCount(); - /** * Get Feedaty Removed Reviews TotalResults Count */ @@ -319,26 +109,24 @@ public function execute() /** * Get Feedaty Reviews Created on Magento Total Count */ - $totalReviewCreatedCount = $this->getAllFeedatyReviewCount(); + $totalReviewCreatedCount = $this->_reviewsHelper->getAllFeedatyReviewCount(); /** * Get Feedaty Reviews Removed on Magento Total Count */ - $totalRemovedReviewCreatedCount = $this->getAllFeedatyRemovedReviewCount(); - + $totalRemovedReviewCreatedCount = $this->_reviewsHelper->getAllFeedatyRemovedReviewCount(); /** * Get Feedaty Reviews Removed on Magento Total Count */ - $totalMediatedReviewCreatedCount = $this->getAllFeedatyMediatedReviewCount(); + $totalMediatedReviewCreatedCount = $this->_reviewsHelper->getAllFeedatyMediatedReviewCount(); - - $this->logger->addInfo("START - Cronjob Feedaty | Get Feedaty Reviews | date: " . date('Y-m-d H:i:s') . ' ---- Total Feedaty Product Reviews ' . $totalFeedatyReviews . ' totalReviewCreatedCount group by feedaty_id ' . $totalReviewCreatedCount); + $this->_logger->addInfo("START - Cronjob Feedaty | 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->getLastFeedatyReviewCreated(); + $lastReviewCreated = $this->_reviewsHelper->getLastFeedatyReviewCreated(); /** * Get n Reviews from Feedaty @@ -350,7 +138,6 @@ public function execute() */ $row = $totalFeedatyReviews - $totalReviewCreatedCount - $count; - $this->logger->addInfo("MEDIATED LINE 339 " ); /** * CREATE NEW REVIEWS @@ -358,7 +145,6 @@ public function execute() //Get Feedaty Product Reviews Data $feedatyProductReviews = $this->_webService->getProductReviewsPagination($row, $count); - $this->logger->addInfo("MEDIATED LINE 347 " ); if (!empty($feedatyProductReviews)) { //Foreach Review @@ -368,22 +154,21 @@ public function execute() $orderId = $review['OrderID']; - $storeView = $this->getStoreViewIdByOrder($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)); - //$reviewReleased =date('Y-m-d h:i:s', floor((int)str_replace($replaceFromDate,$replaceToDate,$review['Released'])/ 1000)); - $today = $this->date->gmtDate(); + $today = $this->_date->gmtDate(); foreach ($review['ProductsReviews'] as $item) { $productId = $item['SKU']; $feedatyProductReviewId = $item['ID']; //Get Feedaty Product Reviews - $magentoProductReviews = $this->getReviewCollection($productId, $feedatyId); + $magentoProductReviews = $this->_reviewsHelper->getReviewCollection($productId, $feedatyId); //AP Rating node $rating = $item['Rating']; @@ -391,47 +176,35 @@ public function execute() //API Review Node $detail = $item['Review']; - //TODO VERIFICARE website view - if (empty($magentoProductReviews)) { $this->createProductReview($productId, $feedatyId, $feedatyProductReviewId, $rating, $detail, $createdAt, $today, $row, $storeView); - - // Product Review - // $this->logger->addInfo("EXEC - Cronjob Feedaty create Product Review | date execution: " . date('Y-m-d H:i:s') . " | Product Id : " . $productId . " | Feedaty ID" . $feedatyId); - } } } // General Cron Report on system.log - $this->logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date execution: " . date('Y-m-d H:i:s') . " -- Last Review Created " . print_r($lastReviewCreated, true) . " -- Review Date CreatedAt " . print_r($createdAt, true) . " -- Pagination " . $row); + $this->_logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date execution: " . date('Y-m-d H:i:s') . " -- Last Review Created " . print_r($lastReviewCreated, true) . " -- Review Date CreatedAt " . print_r($createdAt, true) . " -- Pagination " . $row); } /** * UPDATE MEDIATED REVIEWS */ - $this->logger->addInfo("MEDIATED LINE 397 " ); - $rowMediated = $totalFeedatyMediatedReviews - $totalMediatedReviewCreatedCount - $count; if($rowMediated < 0 ){ - $this->logger->addInfo("ROW MEDIATED IS ZERO " ); + $rowMediated = 0; } - $this->logger->addInfo("MEDIATED ITEMS ROWS " .$rowMediated); - $this->logger->addInfo("MEDIATED ITEMS totalFeedatyMediatedReviews " . $totalFeedatyMediatedReviews); - $this->logger->addInfo("MEDIATED ITEMS totalMediatedReviewCreatedCount " . $totalMediatedReviewCreatedCount); /** * Get Feedaty Mediated Reviews */ $feedatyProductReviewsMediated = $this->_webService->getMediatedReviews($rowMediated, $count); - $this->logger->addInfo("MEDIATED ITEMS feedatyProductReviewsMediated " . print_r($feedatyProductReviewsMediated)); if (!empty($feedatyProductReviewsMediated)) { - $this->logger->addInfo("START MEDIATED - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . print_r($feedatyProductReviewsMediated,true)); + $this->_logger->addInfo("START MEDIATED - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . print_r($feedatyProductReviewsMediated,true)); //Foreach Review foreach ($feedatyProductReviewsMediated as $mediatedReview) { @@ -439,75 +212,52 @@ public function execute() $feedatyId = $mediatedReview['FeedbackReviewID']; $reviewDetail = $mediatedReview['MerchantReview']; - $reviewToMediate = $this->getAllReviewsByFeedatyId($feedatyId); - // $this->logger->addInfo("REVIEW TO DISABLE OBJ - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . date('Y-m-d H:i:s') . " -- REVIEWS TO DISABLE " . print_r($reviewToDisable, true)); + $reviewToMediate = $this->_reviewsHelper->getAllReviewsByFeedatyId($feedatyId); if (!empty($reviewToMediate)) { //if it is not just disabled foreach ($reviewToMediate as $item){ -// $this->logger->addInfo("REVIEW TO DISABLE ITEM LIN 341 - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . print_r($item, true)); -// $this->logger->addInfo("ITEM ID TO DISABLE 357 : " . $item['review_id']); -// $this->logger->addInfo("ITEM STATUS TO DISABLE 357 : " . $item['status_id']); if ($item['status_id'] !== 3) { - $this->logger->addInfo("STATUS ENALBED"); - - $this->mediateReview($item,$reviewDetail); - $this->logger->addInfo("MEDIATED ITEM ID - : " . date('Y-m-d H:i:s') . " -- FeedatySourceID " . $feedatyId); + $this->_reviewsHelper->mediateReview($item,$reviewDetail); } } } } - // General Cron Report on system.log } /** * DISABLE REMOVED REVIEWS */ - $rowRemoved = $totalFeedatyRemovedReviews - $totalRemovedReviewCreatedCount - $count; if($rowRemoved < 0 ){ - $this->logger->addInfo("ROW REMOVED IS ZERO " ); $rowRemoved = 0; } -// $this->logger->addInfo("REMOVED ITEMS ROWS " . $rowRemoved); -// $this->logger->addInfo("REMOVED ITEMS totalFeedatyRemovedReviews " . $totalFeedatyRemovedReviews); -// $this->logger->addInfo("REMOVED ITEMS ROWS totalRemovedReviewCreatedCount " . $totalRemovedReviewCreatedCount); -// + /** * Get Feedaty Removed Reviews */ $feedatyProductReviewsRemoved = $this->_webService->getRemovedReviews($rowRemoved, $count); - if (!empty($feedatyProductReviewsRemoved)) { - // $this->logger->addInfo("START REMOVED - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . print_r($feedatyProductReviewsRemoved,true)); - //Foreach Review foreach ($feedatyProductReviewsRemoved as $removedReview) { $feedatyId = $removedReview['FeedbackReviewID']; - $reviewToDisable = $this->getAllReviewsByFeedatyId($feedatyId); - // $this->logger->addInfo("REVIEW TO DISABLE OBJ - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . date('Y-m-d H:i:s') . " -- REVIEWS TO DISABLE " . print_r($reviewToDisable, true)); + $reviewToDisable = $this->_reviewsHelper->getAllReviewsByFeedatyId($feedatyId); if (!empty($reviewToDisable)) { //if it is not just disabled foreach ($reviewToDisable as $item){ -// $this->logger->addInfo("REVIEW TO DISABLE ITEM LIN 341 - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . print_r($item, true)); -// $this->logger->addInfo("ITEM ID TO DISABLE 357 : " . $item['review_id']); -// $this->logger->addInfo("ITEM STATUS TO DISABLE 357 : " . $item['status_id']); if ($item['status_id'] !== 3) { - // $this->logger->addInfo("STATUS ENALBED"); - - $this->disableReview($item); - // $this->logger->addInfo("REMOVED ITEM ID - : " . date('Y-m-d H:i:s') . " -- FeedatySourceID " . $feedatyId); + $this->_reviewsHelper->disableReview($item); } } @@ -518,7 +268,7 @@ public function execute() } } else{ - $this->logger->addInfo("Feedaty Cronjob is not enabled | date: ". date('Y-m-d H:i:s') ); + $this->_logger->addInfo("Feedaty Cronjob is not enabled | date: ". date('Y-m-d H:i:s') ); } } @@ -527,16 +277,14 @@ public function execute() protected function createProductReview($productId, $feedatyId, $feedatyProductReviewId, $rating, $detail, $createdAt, $today, $row, $storeView) { - $ratingCollection = $this->getRatingCollection(); + $ratingCollection = $this->_reviewsHelper->getRatingCollection(); foreach ($ratingCollection as $ratingItem){ - $this->logger->addInfo("RATING ID " . $ratingItem['rating_id']); + $this->_logger->addInfo("RATING ITEM " . print_r($ratingItem,true)); + $reviewFinalData['ratings'][$ratingItem['rating_id']] = $rating; } - $this->logger->addInfo("RATING COLLECTION " . print_r($ratingCollection,true)); - - $reviewFinalData['nickname'] = "Feedaty"; $reviewFinalData['title'] = "Acquirente Verificato"; $reviewFinalData['detail'] = $detail; @@ -553,16 +301,19 @@ protected function createProductReview($productId, $feedatyId, $feedatyProductRe $review->setEntityId($review->getEntityIdByCode(\Magento\Review\Model\Review::ENTITY_PRODUCT_CODE)) ->setEntityPkValue($productId) ->setStatusId(\Magento\Review\Model\Review::STATUS_APPROVED) - ->setStoreId($this->_storeManager->getStore()->getId()) + ->setStoreId(Store::DEFAULT_STORE_ID) ->setStores(!is_null($storeView) ? [$storeView] : [$this->_storeManager->getStore()->getId()]) - // ->setStores([$this->_storeManager->getStore()->getId()]) + ->setCustomerId(null) ->save(); - foreach ($reviewFinalData['ratings'] as $ratingId => $optionId) { + foreach ($reviewFinalData['ratings'] as $ratingId => $ratingValue) { + $this->_logger->addInfo("RATING ID " . $ratingId); + $this->_logger->addInfo("RATING OPTION ID " . $ratingValue); + $this->_ratingFactory->create() ->setRatingId($ratingId) ->setReviewId($review->getId()) - ->addOptionVote($optionId, $productId); + ->addOptionVote($ratingValue, $productId); } $review->aggregate(); diff --git a/Helper/Reviews.php b/Helper/Reviews.php new file mode 100644 index 0000000..1e15a96 --- /dev/null +++ b/Helper/Reviews.php @@ -0,0 +1,269 @@ +_logger = $logger; + $this->_reviewFactory = $reviewFactory; + $this->_ratingFactory = $ratingFactory; + $this->_storeRepository = $storeRepository; + $this->_orderRepository = $orderRepository; + } + + /** + * @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 disableReview : " . $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 mediateReview : " . $e->getMessage()); + } + + if (!is_null($review)) { + $review->setDetail($reviewDetail)->save(); + $review->setFeedatyProductMediated(1)->save(); + } + + } + + /** + * @param $orderId + * @return int|string|null + */ + public function getStoreViewIdByOrder($orderId) + { + + $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->_reviewFactory->create()->getCollection() + ->addEntityFilter( + 'product', + $productId + ) + ->addFieldToFilter( + 'feedaty_source_id', + $feedatyId + ) + ->setDateOrder(); + + return $collection->getData(); + } + + /* + * Get last Review Created + */ + public function getAllFeedatyReviewCount() + { + $collection = $this->_reviewFactory->create()->getCollection() + ->addFieldToFilter( + 'feedaty_source', + 1 + ) + ->setOrder( + 'review_id', + 'desc' + ) + ->setDateOrder(); + + return count($collection->getData()); + } + + /** + * @return int|void + */ + public function getAllFeedatyRemovedReviewCount() + { + $collection = $this->_reviewFactory->create()->getCollection() + ->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->_reviewFactory->create()->getCollection() + ->addFieldToFilter( + 'feedaty_product_mediated', + 1 + ) + ->setOrder( + 'review_id', + 'desc' + ) + ->setDateOrder(); + + return count($collection->getData()); + } + + /* + * Get last Review Created + */ + public function getLastFeedatyReviewCreated() + { + $collection = $this->_reviewFactory->create()->getCollection() + ->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->_reviewFactory->create()->getCollection() + ->addFieldToFilter( + 'feedaty_product_review_id', + $feedatyid + ) + ->setOrder( + 'review_id', + 'desc' + ) + ->setDateOrder(); + + return $collection->getData(); + } + + /** + * @return mixed + * @throws \Magento\Framework\Exception\LocalizedException + */ + public function getRatingCollection(){ + $ratingCollection = $this->_ratingFactory->create()->getResourceCollection()->addEntityFilter('product')->load(); + return $ratingCollection->getData(); + } + + +} diff --git a/Model/Config/Source/WebService.php b/Model/Config/Source/WebService.php index c3f7f9d..3b17726 100755 --- a/Model/Config/Source/WebService.php +++ b/Model/Config/Source/WebService.php @@ -118,7 +118,7 @@ private function getReqToken(){ $this->_curl->get($url); $response = json_decode($this->_curl->getBody()); - $this->_logger->info('Feedaty response token //////////////////: '. print_r($response,true)); + return $response; } From 80fd5b6360df1e904b398ad818804356a7e9d1f0 Mon Sep 17 00:00:00 2001 From: Marco Boatti Date: Mon, 1 Nov 2021 14:07:03 +0100 Subject: [PATCH 09/17] fix setup --- Setup/UpgradeSchema.php | 41 ----------------------------------------- etc/crontab.xml | 2 +- 2 files changed, 1 insertion(+), 42 deletions(-) diff --git a/Setup/UpgradeSchema.php b/Setup/UpgradeSchema.php index c8cfa81..3f476ce 100644 --- a/Setup/UpgradeSchema.php +++ b/Setup/UpgradeSchema.php @@ -64,47 +64,6 @@ public function upgrade( SchemaSetupInterface $setup, ModuleContextInterface $co $connection->addColumn($tableName, $name, $definition); } } - - } - - - if(version_compare($context->getVersion(), '2.7.1') < 0) { - - $feedatyTable = $setup->getTable('feedaty_badge_settings'); - - if ($setup->getConnection()->isTableExists($feedatyTable) != true) { - $table = $setup->getConnection() - ->newTable($feedatyTable) - ->addColumn( - 'id', - Table::TYPE_INTEGER, - null, - [ - 'identity' => true, - 'unsigned' => true, - 'nullable' => false, - 'primary' => true - ], - 'ID' - ) - ->addColumn( - 'create_pagination', - Table::TYPE_INTEGER, - null, - [ - 'nullable' => true - ], - 'Create Review Cron Pagination ' - ) - ->addColumn( - 'auth_code', - Table::TYPE_TEXT, - 250, - 'Auth Code ' - ) - ->setComment('Feedaty Badge'); - $setup->getConnection()->createTable($table); - } } diff --git a/etc/crontab.xml b/etc/crontab.xml index 92453cd..6188ee4 100644 --- a/etc/crontab.xml +++ b/etc/crontab.xml @@ -2,7 +2,7 @@ - */2 * * * * + */5 * * * * From bc26222aa2d1faa4624ffc108efca397487ef839 Mon Sep 17 00:00:00 2001 From: Marco Boatti Date: Sat, 13 Nov 2021 14:24:32 +0100 Subject: [PATCH 10/17] New Store Badge Widget --- Model/Config/Source/StyleStore.php | 9 ++--- Model/Config/Source/WebService.php | 37 ++++++++++++------- etc/widget.xml | 18 --------- .../templates/widget/store-bagde.phtml | 33 ++++++++++------- 4 files changed, 47 insertions(+), 50 deletions(-) diff --git a/Model/Config/Source/StyleStore.php b/Model/Config/Source/StyleStore.php index 17fea85..2de1739 100755 --- a/Model/Config/Source/StyleStore.php +++ b/Model/Config/Source/StyleStore.php @@ -65,21 +65,20 @@ public function toOptionArray() { } - $data = $this->_fdservice->getFeedatyData($merchant_code); - + $dataObject = $this->_fdservice->getFeedatyData($merchant_code); + $data = $dataObject['merchant']['variants']; if($data) { - // get Badges foreach ($data as $k => $v) { // if ($v['type'] == "merchant" && $v['name'] != "dynamic" ) { - if ($v['type'] == "merchant" ) { + // if ($v['type'] == "merchant" ) { $return[] = ['value' => $k,'label' => $v['name_shown_it-IT']]; - } + // } } diff --git a/Model/Config/Source/WebService.php b/Model/Config/Source/WebService.php index 3b17726..f04975b 100755 --- a/Model/Config/Source/WebService.php +++ b/Model/Config/Source/WebService.php @@ -446,19 +446,30 @@ public function getFeedatyData($feedaty_code) { $content = $cache->load( $string ); 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); - - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - - curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); - - $content = trim(curl_exec($ch)); - - curl_close($ch); +// $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); +// +// curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); +// +// curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); +// +// $content = trim(curl_exec($ch)); +// +// curl_close($ch); + + $url = 'https://widget.feedaty.com/?action=widget_list&style_ver=2021&merchant='.$feedaty_code; + + $arrContextOptions=array( + "ssl"=>array( + "verify_peer"=>false, + "verify_peer_name"=>false, + ), + ); + + $content = file_get_contents( $url, false, stream_context_create($arrContextOptions)); $cache->save($content, $string, array("feedaty_cache"), 24*60*60); // 24 hours of cache diff --git a/etc/widget.xml b/etc/widget.xml index 6b944b1..f01d7ed 100755 --- a/etc/widget.xml +++ b/etc/widget.xml @@ -7,15 +7,6 @@ - - - - - - - - - @@ -25,15 +16,6 @@ - - - - - - - - - diff --git a/view/frontend/templates/widget/store-bagde.phtml b/view/frontend/templates/widget/store-bagde.phtml index 1db744b..59d8eaf 100644 --- a/view/frontend/templates/widget/store-bagde.phtml +++ b/view/frontend/templates/widget/store-bagde.phtml @@ -11,51 +11,56 @@ $zoorate_env = "widget.zoorate.com"; */ $merchant = $block->getFeedatyCode(); -$data = $block->getFeedatyData($merchant); +$dataObject = $block->getFeedatyData($merchant); $badge_style = $block->getData('style'); $variant = $block->getData('variant'); $rvlang = $block->getData('rvlang'); $guilang = $block->getData('guilang'); -$rvlang = $rvlang ? $rvlang : "all"; +//$rvlang = $rvlang ? $rvlang : "all"; +$rvlang = "all"; + +//$guilang = $guilang ? $guilang : "it-IT"; +$guilang = "all"; + + +$data = $dataObject['merchant']['variants']; + -$guilang = $guilang ? $guilang : "it-IT"; if (count($data) > 0) { $ver = $block->getExtensionVersion(); + + // echo '
'; if (array_key_exists($badge_style, $data)) { $widget = $data[$badge_style]; $name = $widget["name"]; - + //die(var_dump($data)); + // die(var_dump($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("ZOORATE_SERVER", $zoorate_env, $widget['html']); - $widget['html'] = str_replace("VARIANT", $variant, $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"]); - + // die(var_dump($element)); // $html = $observer->getTransport()->getOutput(); // $html.= "".$element; - echo "" . $element; + echo $element; // $observer->getTransport()->setOutput( $html ); - } + } } From 64af65594db2125768a1dbc93bee7518d1208079 Mon Sep 17 00:00:00 2001 From: Marco Boatti Date: Sun, 21 Nov 2021 15:22:42 +0100 Subject: [PATCH 11/17] New Store Badge Widget --- Model/Config/Source/ProductBadgeStyle.php | 18 ++++ Model/Config/Source/StoreBadgeStyle.php | 17 ++++ Model/Config/Source/StyleStoreCarousel.php | 83 +++++++++++++++++++ etc/widget.xml | 23 ++++- .../templates/widget/store-bagde.phtml | 19 +++-- 5 files changed, 150 insertions(+), 10 deletions(-) create mode 100644 Model/Config/Source/ProductBadgeStyle.php create mode 100644 Model/Config/Source/StoreBadgeStyle.php create mode 100755 Model/Config/Source/StyleStoreCarousel.php diff --git a/Model/Config/Source/ProductBadgeStyle.php b/Model/Config/Source/ProductBadgeStyle.php new file mode 100644 index 0000000..4c6c4a5 --- /dev/null +++ b/Model/Config/Source/ProductBadgeStyle.php @@ -0,0 +1,18 @@ + "product","label" => __("Product Bagde Style")], + ["value" => "carouselproduct","label" => __("Carousel Bagde Style")], + ["value" => "product_tab","label" => __("Tab Bagde Style")], + ]; + + return $return; + } +} diff --git a/Model/Config/Source/StoreBadgeStyle.php b/Model/Config/Source/StoreBadgeStyle.php new file mode 100644 index 0000000..741f266 --- /dev/null +++ b/Model/Config/Source/StoreBadgeStyle.php @@ -0,0 +1,17 @@ + "merchant","label" => __("Merchant Bagde Style")], + ["value" => "carousel","label" => __("Carousel Bagde Style")] + ]; + + return $return; + } +} diff --git a/Model/Config/Source/StyleStoreCarousel.php b/Model/Config/Source/StyleStoreCarousel.php new file mode 100755 index 0000000..277baba --- /dev/null +++ b/Model/Config/Source/StyleStoreCarousel.php @@ -0,0 +1,83 @@ +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 $return; + + } + + $dataObject = $this->_fdservice->getFeedatyData($merchant_code); + + $data = $dataObject['carousel']['variants']; + + if($data) { + + // get Badges + foreach ($data as $k => $v) { + $return[] = ['value' => $k,'label' => $v['name_shown_it-IT']]; + } + + } + + return $return; + } +} diff --git a/etc/widget.xml b/etc/widget.xml index f01d7ed..27ca46b 100755 --- a/etc/widget.xml +++ b/etc/widget.xml @@ -4,8 +4,20 @@ Show Feedaty Store Badge - - + + + + + + + + + + + + + + @@ -13,8 +25,11 @@ Show Feedaty Product Badge - - + + + + + diff --git a/view/frontend/templates/widget/store-bagde.phtml b/view/frontend/templates/widget/store-bagde.phtml index 59d8eaf..f18f83b 100644 --- a/view/frontend/templates/widget/store-bagde.phtml +++ b/view/frontend/templates/widget/store-bagde.phtml @@ -13,8 +13,15 @@ $merchant = $block->getFeedatyCode(); $dataObject = $block->getFeedatyData($merchant); +//$badge_style = 'vcarosello_1'; $badge_style = $block->getData('style'); -$variant = $block->getData('variant'); +if($badge_style == 'merchant'){ + $variant = $block->getData('variant_merchant'); +} +else{ + $variant = $block->getData('variant_carousel'); +} + $rvlang = $block->getData('rvlang'); $guilang = $block->getData('guilang'); @@ -25,20 +32,20 @@ $rvlang = "all"; $guilang = "all"; -$data = $dataObject['merchant']['variants']; - +$data = $dataObject[$badge_style]['variants']; +//die(var_dump($data)); if (count($data) > 0) { $ver = $block->getExtensionVersion(); // echo '
'; - if (array_key_exists($badge_style, $data)) { - $widget = $data[$badge_style]; + if (array_key_exists($variant, $data)) { + $widget = $data[$variant]; $name = $widget["name"]; - //die(var_dump($data)); + // die(var_dump($data)); // die(var_dump($name)); // Se non trova variante setta la blue white From 0c1ad3ef051f40e622d62b2a6994f72ef491cb75 Mon Sep 17 00:00:00 2001 From: Marco Boatti Date: Sat, 27 Nov 2021 10:43:35 +0100 Subject: [PATCH 12/17] Product badge --- Model/Config/Source/ProductBadgeStyle.php | 4 +- Model/Config/Source/StyleProduct.php | 174 +++++++++--------- Model/Config/Source/StyleProductCarousel.php | 86 +++++++++ Model/Config/Source/StyleProductTab.php | 86 +++++++++ etc/widget.xml | 19 +- .../templates/widget/product-bagde.phtml | 48 +++-- .../templates/widget/store-bagde.phtml | 44 +---- 7 files changed, 307 insertions(+), 154 deletions(-) create mode 100755 Model/Config/Source/StyleProductCarousel.php create mode 100755 Model/Config/Source/StyleProductTab.php diff --git a/Model/Config/Source/ProductBadgeStyle.php b/Model/Config/Source/ProductBadgeStyle.php index 4c6c4a5..619d88c 100644 --- a/Model/Config/Source/ProductBadgeStyle.php +++ b/Model/Config/Source/ProductBadgeStyle.php @@ -9,8 +9,8 @@ public function toOptionArray() { $return = [ ["value" => "product","label" => __("Product Bagde Style")], - ["value" => "carouselproduct","label" => __("Carousel Bagde Style")], - ["value" => "product_tab","label" => __("Tab Bagde Style")], + ["value" => "carouselproduct","label" => __("Product Carousel Bagde Style")], + ["value" => "product_tab","label" => __("Product Tab Bagde Style")], ]; return $return; diff --git a/Model/Config/Source/StyleProduct.php b/Model/Config/Source/StyleProduct.php index 84180ab..fdc8b5f 100755 --- a/Model/Config/Source/StyleProduct.php +++ b/Model/Config/Source/StyleProduct.php @@ -1,88 +1,86 @@ -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; - } -} +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(); + + } + + $dataObject = $this->_fdservice->getFeedatyData($merchant_code); + + $data = $dataObject['product']['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/StyleProductCarousel.php b/Model/Config/Source/StyleProductCarousel.php new file mode 100755 index 0000000..da4fc6c --- /dev/null +++ b/Model/Config/Source/StyleProductCarousel.php @@ -0,0 +1,86 @@ +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(); + + } + + $dataObject = $this->_fdservice->getFeedatyData($merchant_code); + + $data = $dataObject['carouselproduct']['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/StyleProductTab.php b/Model/Config/Source/StyleProductTab.php new file mode 100755 index 0000000..f902cd0 --- /dev/null +++ b/Model/Config/Source/StyleProductTab.php @@ -0,0 +1,86 @@ +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(); + + } + + $dataObject = $this->_fdservice->getFeedatyData($merchant_code); + + $data = $dataObject['product_tab']['variants']; + + if($data) { + + foreach ($data as $k => $v) { + + $return[] = ['value' => $k,'label' => $v['name_shown_it-IT']]; + + } + + } + + return $return; + } +} diff --git a/etc/widget.xml b/etc/widget.xml index 27ca46b..932c14a 100755 --- a/etc/widget.xml +++ b/etc/widget.xml @@ -28,8 +28,23 @@ - - + + + + + + + + + + + + + + + + + diff --git a/view/frontend/templates/widget/product-bagde.phtml b/view/frontend/templates/widget/product-bagde.phtml index 3969cc2..b56c3bb 100644 --- a/view/frontend/templates/widget/product-bagde.phtml +++ b/view/frontend/templates/widget/product-bagde.phtml @@ -9,18 +9,25 @@ $zoorate_env = "widget.zoorate.com"; /* * Merchant Code */ -$merchant = $block->getFeedatyCode(); +$merchant = $block->getFeedatyCode(); -$data = $block->getFeedatyData($merchant); +$dataObject = $block->getFeedatyData($merchant); $badge_style = $block->getData('style'); -$variant = $block->getData('variant'); -$rvlang = $block->getData('rvlang'); -$guilang = $block->getData('guilang'); -$rvlang = $rvlang ? $rvlang : "all"; +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 = $guilang ? $guilang : "it-IT"; +$guilang = "all"; + +$data = $dataObject[$badge_style]['variants']; $product = $block->getCurrentProduct(); @@ -31,29 +38,18 @@ if (!empty($product)) { 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"; + if (array_key_exists($variant, $data)) { + $widget = $data[$variant]; + $name = $widget["name"]; - $guilang = $guilang ? $guilang : "it-IT"; + $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']); - $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"]); - $element = htmlspecialchars_decode($widget["html"]); + echo $element; - echo "" . $element; - } } } } diff --git a/view/frontend/templates/widget/store-bagde.phtml b/view/frontend/templates/widget/store-bagde.phtml index f18f83b..602c2cc 100644 --- a/view/frontend/templates/widget/store-bagde.phtml +++ b/view/frontend/templates/widget/store-bagde.phtml @@ -1,6 +1,5 @@ getFeedatyCode(); +$merchant = $block->getFeedatyCode(); $dataObject = $block->getFeedatyData($merchant); -//$badge_style = 'vcarosello_1'; + $badge_style = $block->getData('style'); -if($badge_style == 'merchant'){ +if ($badge_style == 'merchant') { $variant = $block->getData('variant_merchant'); -} -else{ +} else { $variant = $block->getData('variant_carousel'); } -$rvlang = $block->getData('rvlang'); -$guilang = $block->getData('guilang'); - -//$rvlang = $rvlang ? $rvlang : "all"; $rvlang = "all"; - -//$guilang = $guilang ? $guilang : "it-IT"; $guilang = "all"; - $data = $dataObject[$badge_style]['variants']; -//die(var_dump($data)); - if (count($data) > 0) { $ver = $block->getExtensionVersion(); - - - // echo '
'; if (array_key_exists($variant, $data)) { $widget = $data[$variant]; $name = $widget["name"]; - // die(var_dump($data)); - // die(var_dump($name)); - // Se non trova variante setta la blue white - - - - // $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("GUI_LANG", $guilang, $widget['html']); - $element = htmlspecialchars_decode($widget["html"]); - // die(var_dump($element)); - // $html = $observer->getTransport()->getOutput(); + $widget['html'] = str_replace("REV_LANG", $rvlang, $widget['html']); - // $html.= "".$element; - echo $element; + $element = htmlspecialchars_decode($widget["html"]); - // $observer->getTransport()->setOutput( $html ); + echo $element; } } From 2195fcc46eb828d954b6dbdb1c52732283480660 Mon Sep 17 00:00:00 2001 From: Marco Boatti Date: Sat, 27 Nov 2021 11:07:54 +0100 Subject: [PATCH 13/17] Widget Recode --- Helper/WidgetHelper.php | 86 +++++++++++++++++++ Model/Config/Source/StyleProduct.php | 79 +++-------------- Model/Config/Source/StyleProductCarousel.php | 79 +++-------------- Model/Config/Source/StyleProductTab.php | 79 +++-------------- Model/Config/Source/StyleStore.php | 90 ++++---------------- Model/Config/Source/StyleStoreCarousel.php | 84 ++++-------------- 6 files changed, 154 insertions(+), 343 deletions(-) create mode 100755 Helper/WidgetHelper.php 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/StyleProduct.php b/Model/Config/Source/StyleProduct.php index fdc8b5f..d952cc6 100755 --- a/Model/Config/Source/StyleProduct.php +++ b/Model/Config/Source/StyleProduct.php @@ -3,84 +3,29 @@ namespace Feedaty\Badge\Model\Config\Source; use \Magento\Framework\Option\ArrayInterface; -use \Magento\Framework\App\Config\ScopeConfigInterface; -use Feedaty\Badge\Model\Config\Source\WebService; -use \Magento\Store\Model\StoreManagerInterface; -use Feedaty\Badge\Helper\Data as DataHelp; -use \Magento\Framework\App\Request\Http; +use Feedaty\Badge\Helper\WidgetHelper; class StyleProduct implements ArrayInterface { - /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface - */ - protected $scopeConfig; /** - * @var Feedaty\Badge\Helper\Data - */ - protected $dataHelper; + * @var WidgetHelper + */ + protected $_widgetHelper; - /* - * Constructor - * - */ - public function __construct( - ScopeConfigInterface $scopeConfig, - StoreManagerInterface $storeManager, - DataHelp $dataHelper, - Http $request, - WebService $fdservice - ) + /** + * @param WidgetHelper $widgetHelper + */ + public function __construct(WidgetHelper $widgetHelper) { - $this->scopeConfig = $scopeConfig; - $this->storeManager = $storeManager; - $this->_dataHelper = $dataHelper; - $this->_request = $request; - $this->_fdservice = $fdservice; + $this->_widgetHelper = $widgetHelper; } /** - * - * @return $return - */ + * @return array + */ 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(); - - } - - $dataObject = $this->_fdservice->getFeedatyData($merchant_code); - - $data = $dataObject['product']['variants']; - - if($data) { - - foreach ($data as $k => $v) { - - $return[] = ['value' => $k,'label' => $v['name_shown_it-IT']]; - - } - - } - - return $return; + return $this->_widgetHelper->badgeData('product'); } } diff --git a/Model/Config/Source/StyleProductCarousel.php b/Model/Config/Source/StyleProductCarousel.php index da4fc6c..17b0e07 100755 --- a/Model/Config/Source/StyleProductCarousel.php +++ b/Model/Config/Source/StyleProductCarousel.php @@ -3,84 +3,29 @@ namespace Feedaty\Badge\Model\Config\Source; use \Magento\Framework\Option\ArrayInterface; -use \Magento\Framework\App\Config\ScopeConfigInterface; -use Feedaty\Badge\Model\Config\Source\WebService; -use \Magento\Store\Model\StoreManagerInterface; -use Feedaty\Badge\Helper\Data as DataHelp; -use \Magento\Framework\App\Request\Http; +use Feedaty\Badge\Helper\WidgetHelper; class StyleProductCarousel implements ArrayInterface { - /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface - */ - protected $scopeConfig; /** - * @var Feedaty\Badge\Helper\Data - */ - protected $dataHelper; + * @var WidgetHelper + */ + protected $_widgetHelper; - /* - * Constructor - * - */ - public function __construct( - ScopeConfigInterface $scopeConfig, - StoreManagerInterface $storeManager, - DataHelp $dataHelper, - Http $request, - WebService $fdservice - ) + /** + * @param WidgetHelper $widgetHelper + */ + public function __construct(WidgetHelper $widgetHelper) { - $this->scopeConfig = $scopeConfig; - $this->storeManager = $storeManager; - $this->_dataHelper = $dataHelper; - $this->_request = $request; - $this->_fdservice = $fdservice; + $this->_widgetHelper = $widgetHelper; } /** - * - * @return $return - */ + * @return array + */ 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(); - - } - - $dataObject = $this->_fdservice->getFeedatyData($merchant_code); - - $data = $dataObject['carouselproduct']['variants']; - - if($data) { - - foreach ($data as $k => $v) { - - $return[] = ['value' => $k,'label' => $v['name_shown_it-IT']]; - - } - - } - - return $return; + return $this->_widgetHelper->badgeData('carouselproduct'); } } diff --git a/Model/Config/Source/StyleProductTab.php b/Model/Config/Source/StyleProductTab.php index f902cd0..0b0eeca 100755 --- a/Model/Config/Source/StyleProductTab.php +++ b/Model/Config/Source/StyleProductTab.php @@ -3,84 +3,29 @@ namespace Feedaty\Badge\Model\Config\Source; use \Magento\Framework\Option\ArrayInterface; -use \Magento\Framework\App\Config\ScopeConfigInterface; -use Feedaty\Badge\Model\Config\Source\WebService; -use \Magento\Store\Model\StoreManagerInterface; -use Feedaty\Badge\Helper\Data as DataHelp; -use \Magento\Framework\App\Request\Http; +use Feedaty\Badge\Helper\WidgetHelper; class StyleProductTab implements ArrayInterface { - /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface - */ - protected $scopeConfig; /** - * @var Feedaty\Badge\Helper\Data - */ - protected $dataHelper; + * @var WidgetHelper + */ + protected $_widgetHelper; - /* - * Constructor - * - */ - public function __construct( - ScopeConfigInterface $scopeConfig, - StoreManagerInterface $storeManager, - DataHelp $dataHelper, - Http $request, - WebService $fdservice - ) + /** + * @param WidgetHelper $widgetHelper + */ + public function __construct(WidgetHelper $widgetHelper) { - $this->scopeConfig = $scopeConfig; - $this->storeManager = $storeManager; - $this->_dataHelper = $dataHelper; - $this->_request = $request; - $this->_fdservice = $fdservice; + $this->_widgetHelper = $widgetHelper; } /** - * - * @return $return - */ + * @return array + */ 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(); - - } - - $dataObject = $this->_fdservice->getFeedatyData($merchant_code); - - $data = $dataObject['product_tab']['variants']; - - if($data) { - - foreach ($data as $k => $v) { - - $return[] = ['value' => $k,'label' => $v['name_shown_it-IT']]; - - } - - } - - return $return; + return $this->_widgetHelper->badgeData('product_tab'); } } diff --git a/Model/Config/Source/StyleStore.php b/Model/Config/Source/StyleStore.php index 2de1739..52c590d 100755 --- a/Model/Config/Source/StyleStore.php +++ b/Model/Config/Source/StyleStore.php @@ -1,89 +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; - - } - - $dataObject = $this->_fdservice->getFeedatyData($merchant_code); - - $data = $dataObject['merchant']['variants']; - - 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 index 277baba..1bcdb97 100755 --- a/Model/Config/Source/StyleStoreCarousel.php +++ b/Model/Config/Source/StyleStoreCarousel.php @@ -1,83 +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; - - } - - $dataObject = $this->_fdservice->getFeedatyData($merchant_code); - - $data = $dataObject['carousel']['variants']; - - if($data) { - - // get Badges - foreach ($data as $k => $v) { - $return[] = ['value' => $k,'label' => $v['name_shown_it-IT']]; - } - - } - - return $return; + * @return array + */ + public function toOptionArray() + { + return $this->_widgetHelper->badgeData('carousel'); } } From 66c62d550219cf0a121cdbe9ec46e75b11939b7b Mon Sep 17 00:00:00 2001 From: Marco Boatti Date: Tue, 7 Dec 2021 17:08:37 +0100 Subject: [PATCH 14/17] Force Create Reviews Default Store --- Helper/ConfigRules.php | 17 ++++++++++++++++- Helper/Reviews.php | 41 +++++++++++++++++++++++++++------------- etc/adminhtml/system.xml | 13 +++++++++++++ 3 files changed, 57 insertions(+), 14 deletions(-) diff --git a/Helper/ConfigRules.php b/Helper/ConfigRules.php index 9952e6e..162f820 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 { @@ -62,10 +62,25 @@ 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; + } + } diff --git a/Helper/Reviews.php b/Helper/Reviews.php index 1e15a96..19b70ae 100644 --- a/Helper/Reviews.php +++ b/Helper/Reviews.php @@ -2,10 +2,10 @@ namespace Feedaty\Badge\Helper; +use Feedaty\Badge\Helper\ConfigRules; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Store\Api\StoreRepositoryInterface; - class Reviews extends AbstractHelper { @@ -33,6 +33,10 @@ class Reviews extends AbstractHelper */ protected $_orderRepository; + /** + * @var \Feedaty\Badge\Helper\ConfigSetting + */ + protected $_helperConfigRules; /** * @param \Psr\Log\LoggerInterface $logger @@ -46,7 +50,9 @@ public function __construct( \Magento\Review\Model\ReviewFactory $reviewFactory, \Magento\Review\Model\RatingFactory $ratingFactory, StoreRepositoryInterface $storeRepository, - \Magento\Sales\Api\OrderRepositoryInterface $orderRepository + \Magento\Sales\Api\OrderRepositoryInterface $orderRepository, + ConfigRules $helperConfigRules + ) { $this->_logger = $logger; @@ -54,6 +60,7 @@ public function __construct( $this->_ratingFactory = $ratingFactory; $this->_storeRepository = $storeRepository; $this->_orderRepository = $orderRepository; + $this->_helperConfigRules = $helperConfigRules; } /** @@ -100,21 +107,29 @@ public function mediateReview($reviewData, $reviewDetail) */ public function getStoreViewIdByOrder($orderId) { + $forceDefaultStore = $this->_helperConfigRules->getReviewForceDefaultStore(); - $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($forceDefaultStore === "1"){ + $defaultStore = $this->_helperConfigRules->getReviewDefaultStore(); + return $defaultStore; } - - if (!is_null($order)) { - $websiteId = $order->getStore()->getWebsiteId(); - return $websiteId; + 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 null; } diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 0b48cd0..6e2b6f5 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -25,6 +25,19 @@ Magento\Config\Model\Config\Source\Yesno + + + + Magento\Config\Model\Config\Source\Yesno + + + + + Magento\Store\Ui\Component\Listing\Column\Store\Options + + 1 + + From 982ffb1640babdcb1135d09bf938eda0346f5b41 Mon Sep 17 00:00:00 2001 From: Marco Boatti Date: Sun, 12 Dec 2021 14:42:07 +0100 Subject: [PATCH 15/17] Recode module [step 1] --- Helper/ConfigRules.php | 7 + Model/Config/Source/FeedatyOrder.php | 17 -- Model/Config/Source/PositionProduct.php | 37 ---- Model/Config/Source/WebService.php | 172 +++++------------- Observer/ProductReviews.php | 113 ------------ etc/adminhtml/system.xml | 28 --- etc/frontend/events.xml | 6 - .../adminhtml_system_config_edit.xml | 12 -- view/adminhtml/requirejs-config.js | 8 - view/frontend/templates/product_reviews.phtml | 40 ---- 10 files changed, 50 insertions(+), 390 deletions(-) delete mode 100755 Model/Config/Source/FeedatyOrder.php delete mode 100755 Model/Config/Source/PositionProduct.php delete mode 100644 Observer/ProductReviews.php delete mode 100755 etc/frontend/events.xml delete mode 100644 view/adminhtml/adminhtml_system_config_edit.xml delete mode 100644 view/adminhtml/requirejs-config.js delete mode 100644 view/frontend/templates/product_reviews.phtml diff --git a/Helper/ConfigRules.php b/Helper/ConfigRules.php index 162f820..5e75248 100644 --- a/Helper/ConfigRules.php +++ b/Helper/ConfigRules.php @@ -83,4 +83,11 @@ public function getReviewDefaultStore() return $default_store; } + //TODO CHECK IF NEED + public function getTimeout() + { + $default_store = $this->getPreferencesConfig('create_reviews_default_store'); + return $default_store; + } + } diff --git a/Model/Config/Source/FeedatyOrder.php b/Model/Config/Source/FeedatyOrder.php deleted file mode 100755 index 542c589..0000000 --- a/Model/Config/Source/FeedatyOrder.php +++ /dev/null @@ -1,17 +0,0 @@ - "0","label" => __("Newest reviews first")], - ["value" => "1","label" => __("Old reviews first")], - ]; - - 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/WebService.php b/Model/Config/Source/WebService.php index f04975b..489dbfe 100755 --- a/Model/Config/Source/WebService.php +++ b/Model/Config/Source/WebService.php @@ -3,6 +3,7 @@ use \Magento\Framework\HTTP\Client\Curl; use \Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\HTTP\Client\CurlFactory; use \Magento\Store\Model\StoreManagerInterface; use Feedaty\Badge\Helper\Data as FeedatyHelper; use Feedaty\Badge\Helper\ConfigRules; @@ -10,6 +11,8 @@ use \Magento\Framework\Serialize\Serializer\Json; use \Psr\Log\LoggerInterface; + + class WebService { @@ -48,6 +51,12 @@ class WebService */ private $_logger; + + /** + * @var CurlFactory + */ + private $curlFactory; + /** * WebService constructor. * @param ScopeConfigInterface $scopeConfig @@ -67,7 +76,8 @@ public function __construct( ObjectManagerInterface $objectmanager, Json $json, ConfigRules $configRules, - LoggerInterface $logger + LoggerInterface $logger, + CurlFactory $curlFactory ) { $this->_scopeConfig = $scopeConfig; @@ -75,9 +85,6 @@ public function __construct( $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; @@ -89,8 +96,9 @@ public function __construct( $timeout = $timeout == null ? "1000" : $timeout; - $this->_curl->setOption(CURLOPT_CONNECTTIMEOUT_MS, $timeout); - $this->_curl->setOption(CURLOPT_TIMEOUT_MS, $timeout); + + + $this->curlFactory = $curlFactory; } @@ -104,38 +112,39 @@ public function unserializeJson($result) return $jsonDecode; } - /** - * Function getReqToken - get the request token - * - * @return $response - * - */ - private function getReqToken(){ - - - $url = "http://api.feedaty.com/OAuth/RequestToken"; - $this->_curl->addHeader('Content-Type','application/x-www-form-urlencoded'); - $this->_curl->get($url); - $response = json_decode($this->_curl->getBody()); - - return $response; + /** + * Get request headers + * + * @return array + */ + private function getHeaders() + { + return [ + 'Content-Type' => 'application/x-www-form-urlencoded' + ]; } /** - * Function serializeData - serialize data to send - * - * @param $fields - * - * @return $dati - */ - private function serializeData($fields){ - $data = ''; - foreach($fields as $k => $v){ - $data .= $k . '=' . urlencode($v) . '&'; + * @return array + */ + private function getReqToken() + { + $this->_logger->info('FEEDATY TOKEN LOG REQ: START'); + $url = "http://api.feedaty.com/OAuth/RequestToken"; + try { + $curl = $this->curlFactory->create(); + $curl->addHeader('Content-Type', 'application/x-www-form-urlencoded'); + $curl->setTimeout(3000); + $curl->get($url); + $response = json_decode($curl->getBody()); + + } catch (\Exception $exception) { + $response = []; + $this->_logger->critical('FEEDATY TOKEN LOG ERROR: '.$exception); } - $data = rtrim($data, '&'); - return $data; + + return $response; } /** @@ -301,10 +310,10 @@ public function getAllMediatedReviews($params = '') $mediated = $this->getReviewsData($url); return $mediated; } + /** * @param string $params * @return mixed|string|null - * @todo : complete function and use to save data in db */ public function getAllReviews($params = '') { @@ -446,20 +455,6 @@ public function getFeedatyData($feedaty_code) { $content = $cache->load( $string ); 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); -// -// curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); -// -// curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); -// -// $content = trim(curl_exec($ch)); -// -// curl_close($ch); - $url = 'https://widget.feedaty.com/?action=widget_list&style_ver=2021&merchant='.$feedaty_code; $arrContextOptions=array( @@ -483,85 +478,4 @@ public function getFeedatyData($feedaty_code) { 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); - - curl_setopt($ch, CURLOPT_HTTPHEADER, $header); - - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); - - curl_setopt($ch, CURLOPT_RETURNTRANSFER , true); - - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $timeout); - - curl_setopt($ch, CURLOPT_TIMEOUT_MS, $timeout); - - $content = json_decode( curl_exec($ch), true ); - - $http_resp = curl_getinfo($ch, CURLINFO_HTTP_CODE); - - curl_close($ch); - - if ($content != null && $http_resp == "200") - { - // 6 hours of cache - $cache_interface->save( - - json_encode($content ,true), - $cache_key, - array("feedaty_cache"), - 24*60*60 - - ); - } - //debug call - - if($fdDebugEnabled != 0) { - - $message = "Rating API response: ".$http_resp." http code"; - $this->_feedatyHelper->feedatyDebug($message, "API RATINGS RESPONSE INFO"); - - } - } - - 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/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/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 6e2b6f5..0a2281a 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -99,34 +99,6 @@
-
- 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 - - - -
-
separator-top 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/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/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 From 596b1f02da9edee0f6da03aadce352b8adbb7c60 Mon Sep 17 00:00:00 2001 From: Marco Boatti Date: Fri, 24 Dec 2021 15:21:14 +0100 Subject: [PATCH 16/17] New Set Order [in progress] --- Cron/Orders.php | 168 +++++++++++++++++++++++++++++ Helper/Orders.php | 167 ++++++++++++++++++++++++++++ Model/Config/Source/WebService.php | 75 +++++++++++++ Observer/InterceptOrder.php | 11 +- etc/crontab.xml | 3 + 5 files changed, 423 insertions(+), 1 deletion(-) create mode 100644 Cron/Orders.php create mode 100644 Helper/Orders.php diff --git a/Cron/Orders.php b/Cron/Orders.php new file mode 100644 index 0000000..ff92231 --- /dev/null +++ b/Cron/Orders.php @@ -0,0 +1,168 @@ +_logger = $logger; + $this->_webService = $webService; + $this->_reviewFactory = $reviewFactory; + $this->_ratingFactory = $ratingFactory; + $this->_storeManager = $storeManager; + $this->_date = $date; + $this->_configRules = $configRules; + $this->_orderRepository = $orderRepository; + $this->ordersHelper = $ordersHelper; + $this->productRepository = $productRepository; + } + + + /** + * @throws \Magento\Framework\Exception\LocalizedException + */ + public function execute() + { + + + //Starter Log + $this->_logger->addInfo("START - Cronjob Feedaty | Set Feedaty Orders | date: " . date('Y-m-d H:i:s') ); + //$orderStatus = explode(',', 'complete,processing'); + //$orderStatus = explode(',', $this->_dataHelper->getOrderStatusFilter()); + // $value = ; + + $orders = $this->ordersHelper->getOrders(); + + + $data = array(); + + /* pass data array to write in csv file */ + $i = 0; + foreach ($orders as $order){ + + $items = $order->getItems(); + + $storeId = $order->getStoreId(); + /** + * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, + */ + $localeCode = $this->ordersHelper->getCulture($storeId); + + $data[$i] = [ + + 'ID' => $order->getIncrementId(), + 'Date' => $order->getCreatedAt(), + 'CustomerEmail' => $order->getCustomerEmail(), + 'CustomerID' => $order->getCustomerEmail(), + 'Culture' => $localeCode, + 'Platform' => $this->ordersHelper->getPlatform(), + 'Products' => [] + + ]; + + foreach ($items as $item){ + $itemType = $item->getProductType(); + + $sku = $item->getSku(); + $productId = $item->getProductId(); + $productUrl = $item->getProduct()->getProductUrl(); + + array_push($data[$i]['Products'], + [ + 'SKU' => $productId, + 'URL' => $productUrl, + ] + ); + + + } + + $i++; + } + $this->_logger->addInfo("Order List - Cronjob Feedaty | Set Feedaty Orders | date 1.0.1: " . print_r($data,true) ); + + } + +} + diff --git a/Helper/Orders.php b/Helper/Orders.php new file mode 100644 index 0000000..e949994 --- /dev/null +++ b/Helper/Orders.php @@ -0,0 +1,167 @@ +logger = $logger; + $this->_reviewFactory = $reviewFactory; + $this->_ratingFactory = $ratingFactory; + $this->_storeRepository = $storeRepository; + $this->orderRepository = $orderRepository; + $this->_helperConfigRules = $helperConfigRules; + $this->scopeConfig = $scopeConfig; + $this->searchCriteriaBuilder = $searchCriteriaBuilder; + $this->productRepository = $productRepository; + $this->productMetadata = $productMetadata; + $this->productFactory = $productFactory; + } + + 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)) { + $culture = "en"; + } + + return $culture; + } + + + public function getOrders() + { + $criteria = $this->searchCriteriaBuilder + // ->addFilter('status','processing','eq') + // ->addFilter('updated_at', $this->_ordersHelper->getOrderFromDate(),'gteq') + // ->addFilter('updated_at',$to,'lteq') + ->setPageSize(500) + ->setCurrentPage(1) + ->create(); + $orderResult = $this->orderRepository->getList($criteria); + + $orders = $orderResult->getItems(); + + return $orders; + } + + + + public function getPlatform() + { + $platform = $this->productMetadata->getName() . ' ' . $this->productMetadata->getEdition() . ' ' . $this->productMetadata->getVersion(); + return $platform; + } + + + + + +} diff --git a/Model/Config/Source/WebService.php b/Model/Config/Source/WebService.php index 489dbfe..d49d71d 100755 --- a/Model/Config/Source/WebService.php +++ b/Model/Config/Source/WebService.php @@ -365,6 +365,81 @@ public function getReviewsData($url) return null; } + + + + + /** + * Function send_order + * + * @param object $data + * + */ + public function sendOrder($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'; + + $token = $this->getReqToken(); + + $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"); + + } + + curl_close($ch); + + return 1 ; + + } + + + + /** * Function send_order * diff --git a/Observer/InterceptOrder.php b/Observer/InterceptOrder.php index cf378bc..2b39f93 100644 --- a/Observer/InterceptOrder.php +++ b/Observer/InterceptOrder.php @@ -123,7 +123,7 @@ public function execute( \Magento\Framework\Event\Observer $observer ) { $orderopt = $store->getConfig('feedaty_global/feedaty_sendorder/sendorder'); - if( $order !== null && $order->getStatus() == $orderopt ) { + if( $order !== null ) { $order_id = $order->getId(); @@ -289,6 +289,15 @@ public function execute( \Magento\Framework\Event\Observer $observer ) { // send to feedaty + echo "
";
+                        var_dump($fd_data);
+                        echo "
"; + + + print_r($merchant); + print_r($secret); + die('FEEDATY ORDER DATA: DATA'); + $this->_fdservice->send_order( $merchant, $secret, $fd_data ); } diff --git a/etc/crontab.xml b/etc/crontab.xml index 6188ee4..2e422d1 100644 --- a/etc/crontab.xml +++ b/etc/crontab.xml @@ -4,5 +4,8 @@ */5 * * * * + + */1 * * * * + From 40d8b57f142467090e650df1e720b5ebf4fddeed Mon Sep 17 00:00:00 2001 From: Marco Boatti Date: Thu, 13 Jan 2022 17:27:22 +0100 Subject: [PATCH 17/17] * 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 --- Block/Adminhtml/BadgeSelect.php | 166 ----- Block/Adminhtml/Preview.php | 105 ---- Block/Adminhtml/ProdPreview.php | 109 ---- Block/Product.php | 13 - Block/ProductSnippet.php | 85 ++- Block/Widget/ProductBadge.php | 10 +- Block/Widget/StoreBadge.php | 2 +- CHANGELOG.md | 18 +- Cron/Orders.php | 167 ++--- Cron/Reviews.php | 12 +- Helper/ConfigRules.php | 12 +- Helper/ConfigSetting.php | 12 + Helper/Orders.php | 209 ++++--- Helper/Reviews.php | 54 +- Model/Config/Source/FeedatyTimeout.php | 23 - Model/Config/Source/ProdVariants.php | 82 --- Model/Config/Source/ProductBadgeStyle.php | 6 +- Model/Config/Source/StoreBadgeStyle.php | 4 +- Model/Config/Source/WebService.php | 575 +++++++----------- Model/Order.php | 24 + Model/ResourceModel/Order.php | 13 + Model/ResourceModel/Order/Collection.php | 19 + Observer/InterceptOrder.php | 326 ---------- Setup/UpgradeSchema.php | 96 +-- composer.json | 2 +- etc/adminhtml/menu.xml | 2 - etc/adminhtml/system.xml | 41 -- etc/crontab.xml | 4 +- etc/events.xml | 6 - etc/module.xml | 2 +- etc/widget.xml | 4 +- view/frontend/layout/catalog_product_view.xml | 2 +- view/frontend/layout/default.xml | 11 - view/frontend/templates/fdtbase.phtml | 5 - view/frontend/templates/product-snippet.phtml | 60 +- ...roduct-bagde.phtml => product-badge.phtml} | 0 .../{store-bagde.phtml => store-badge.phtml} | 0 37 files changed, 748 insertions(+), 1533 deletions(-) delete mode 100644 Block/Adminhtml/BadgeSelect.php delete mode 100644 Block/Adminhtml/Preview.php delete mode 100644 Block/Adminhtml/ProdPreview.php delete mode 100755 Block/Product.php delete mode 100644 Model/Config/Source/FeedatyTimeout.php delete mode 100644 Model/Config/Source/ProdVariants.php create mode 100644 Model/Order.php create mode 100644 Model/ResourceModel/Order.php create mode 100644 Model/ResourceModel/Order/Collection.php delete mode 100644 Observer/InterceptOrder.php delete mode 100755 etc/events.xml delete mode 100644 view/frontend/layout/default.xml delete mode 100644 view/frontend/templates/fdtbase.phtml rename view/frontend/templates/widget/{product-bagde.phtml => product-badge.phtml} (100%) rename view/frontend/templates/widget/{store-bagde.phtml => store-badge.phtml} (100%) 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 0308559..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 getProductReviews($productId) + { + $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 retriveInformationsProduct($feedaty_code, $id) + public function getStoreId() + { + return $this->_storeManager->getStore()->getId(); + } + + public function getRatingSummary($product) { - return $this->_webservice->retriveInformationsProduct($feedaty_code, $id); + + $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 */ @@ -171,8 +208,16 @@ public function getMediaUrl() 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 5970527..8c03566 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,9 +2,25 @@ #### RELASE NOTES + ### V2.7.0 -- Add Feedaty Review Columns to review_detail table +* 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 diff --git a/Cron/Orders.php b/Cron/Orders.php index ff92231..f18ef2f 100644 --- a/Cron/Orders.php +++ b/Cron/Orders.php @@ -2,165 +2,118 @@ namespace Feedaty\Badge\Cron; -use Feedaty\Badge\Helper\ConfigRules; -use Feedaty\Badge\Helper\Reviews as ReviewsHelper; -use Magento\Catalog\Api\ProductRepositoryInterface; -use Magento\Store\Api\Data\StoreInterface; -use Magento\Store\Api\StoreRepositoryInterface; -use Magento\Store\Model\Store; -use \Magento\Framework\App\Config\ScopeConfigInterface; +use Feedaty\Badge\Helper\Orders as OrdersHelper; +use Feedaty\Badge\Model\Config\Source\WebService; +use Psr\Log\LoggerInterface; class Orders { - - /** - * @var \Psr\Log\LoggerInterface - */ - protected $_logger; - /** - * @var \Feedaty\Badge\Model\Config\Source\WebService - */ - protected $_webService; - /** - * @var \Magento\Review\Model\ReviewFactory - */ - protected $_reviewFactory; - /** - * @var \Magento\Review\Model\RatingFactory - */ - protected $_ratingFactory; - /** - * @var \Magento\Store\Model\StoreManagerInterface - */ - protected $_storeManager; - /** - * @var \Magento\Framework\Stdlib\DateTime\DateTime + * @var LoggerInterface */ - protected $_date; + protected $logger; /** - * @var ConfigRules - */ - protected $_configRules; - - /** - * @var ReviewsHelper + * @var OrdersHelper */ protected $ordersHelper; - /** - * @var \Magento\Sales\Api\OrderRepositoryInterface + * @var WebService */ - protected $_orderRepository; - + private $webService; /** - * @var ProductRepositoryInterface - */ - protected $productRepository; - /** - * @param ScopeConfigInterface $scopeConfig - * @param \Psr\Log\LoggerInterface $logger - * @param \Feedaty\Badge\Model\Config\Source\WebService $webService - * @param \Magento\Review\Model\ReviewFactory $reviewFactory - * @param \Magento\Review\Model\RatingFactory $ratingFactory - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Magento\Framework\Stdlib\DateTime\DateTime $date - * @param ConfigRules $configRules - * @param \Feedaty\Badge\Helper\Orders $ordersHelper - * @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository - * @param \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder + * @param LoggerInterface $logger + * @param OrdersHelper $ordersHelper */ public function __construct( - \Psr\Log\LoggerInterface $logger, - \Feedaty\Badge\Model\Config\Source\WebService $webService, - \Magento\Review\Model\ReviewFactory $reviewFactory, - \Magento\Review\Model\RatingFactory $ratingFactory, - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Framework\Stdlib\DateTime\DateTime $date, - ConfigRules $configRules, - \Feedaty\Badge\Helper\Orders $ordersHelper, - \Magento\Sales\Api\OrderRepositoryInterface $orderRepository, - ProductRepositoryInterface $productRepository + LoggerInterface $logger, + OrdersHelper $ordersHelper, + WebService $webService ) { - $this->_logger = $logger; - $this->_webService = $webService; - $this->_reviewFactory = $reviewFactory; - $this->_ratingFactory = $ratingFactory; - $this->_storeManager = $storeManager; - $this->_date = $date; - $this->_configRules = $configRules; - $this->_orderRepository = $orderRepository; + $this->logger = $logger; $this->ordersHelper = $ordersHelper; - $this->productRepository = $productRepository; + $this->webService = $webService; } - /** - * @throws \Magento\Framework\Exception\LocalizedException + * Send Orders to Feedaty Orders API */ public function execute() { + /** + * Send Module Information Data + */ + $this->webService->fdSendInstallationInfo(); //Starter Log - $this->_logger->addInfo("START - Cronjob Feedaty | Set Feedaty Orders | date: " . date('Y-m-d H:i:s') ); - //$orderStatus = explode(',', 'complete,processing'); - //$orderStatus = explode(',', $this->_dataHelper->getOrderStatusFilter()); - // $value = ; + $this->logger->addInfo("Feedaty | START Cronjob | Set Feedaty Orders | date: " . date('Y-m-d H:i:s') ); $orders = $this->ordersHelper->getOrders(); $data = array(); - /* pass data array to write in csv file */ + /* Order Increment */ $i = 0; - foreach ($orders as $order){ - $items = $order->getItems(); + if(count($orders) > 0){ + foreach ($orders as $order){ + + /* Get all visible order products */ + $items = $order->getAllVisibleItems(); - $storeId = $order->getStoreId(); - /** - * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, - */ - $localeCode = $this->ordersHelper->getCulture($storeId); + $storeId = $order->getStoreId(); + /** + * Get Locale + */ + $localeCode = $this->ordersHelper->getCulture($storeId); - $data[$i] = [ + $data[$i] = [ + 'ID' => $order->getEntityId(), + 'Date' => $order->getCreatedAt(), + 'CustomerEmail' => $order->getCustomerEmail(), + 'CustomerID' => $order->getCustomerEmail(), + 'Culture' => $localeCode, + 'Platform' => $this->ordersHelper->getPlatform(), + 'Products' => [] - 'ID' => $order->getIncrementId(), - 'Date' => $order->getCreatedAt(), - 'CustomerEmail' => $order->getCustomerEmail(), - 'CustomerID' => $order->getCustomerEmail(), - 'Culture' => $localeCode, - 'Platform' => $this->ordersHelper->getPlatform(), - 'Products' => [] + ]; - ]; + foreach ($items as $item){ - foreach ($items as $item){ - $itemType = $item->getProductType(); + $productId = $item->getProductId(); - $sku = $item->getSku(); - $productId = $item->getProductId(); - $productUrl = $item->getProduct()->getProductUrl(); + $productThumbnailUrl = $this->ordersHelper->getProductThumbnailUrl($item); array_push($data[$i]['Products'], [ - 'SKU' => $productId, - 'URL' => $productUrl, + 'SKU' => $productId , + 'URL' => $item->getProduct()->getProductUrl(), + 'ThumbnailURL' => $productThumbnailUrl, + 'Name' => $item->getName() ] ); + } + $i++; } - $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']); + } + } + } } - $this->_logger->addInfo("Order List - Cronjob Feedaty | Set Feedaty Orders | date 1.0.1: " . print_r($data,true) ); } diff --git a/Cron/Reviews.php b/Cron/Reviews.php index 5ceab75..9e3aa98 100644 --- a/Cron/Reviews.php +++ b/Cron/Reviews.php @@ -84,6 +84,7 @@ public function __construct( */ public function execute() { + /** * IF IMPORT IS ENABLED */ @@ -121,7 +122,7 @@ public function execute() */ $totalMediatedReviewCreatedCount = $this->_reviewsHelper->getAllFeedatyMediatedReviewCount(); - $this->_logger->addInfo("START - Cronjob Feedaty | Get Feedaty Reviews | date: " . date('Y-m-d H:i:s') . ' ---- Total Feedaty Product Reviews ' . $totalFeedatyReviews . ' totalReviewCreatedCount group by feedaty_id ' . $totalReviewCreatedCount); + $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) @@ -182,7 +183,7 @@ public function execute() } } // General Cron Report on system.log - $this->_logger->addInfo("END - Cronjob Feedaty is executed | Get Feedaty Reviews | date execution: " . date('Y-m-d H:i:s') . " -- Last Review Created " . print_r($lastReviewCreated, true) . " -- Review Date CreatedAt " . print_r($createdAt, true) . " -- Pagination " . $row); + $this->_logger->addInfo("Feedaty | END Cronjob | Get Feedaty Reviews | date execution: " . date('Y-m-d H:i:s') ); } /** @@ -204,7 +205,7 @@ public function execute() if (!empty($feedatyProductReviewsMediated)) { - $this->_logger->addInfo("START MEDIATED - Cronjob Feedaty is executed | Disabled Feedaty Reviews ID | date execution: " . print_r($feedatyProductReviewsMediated,true)); + $this->_logger->addInfo("Feedaty | START Mediated Reviews"); //Foreach Review foreach ($feedatyProductReviewsMediated as $mediatedReview) { @@ -268,7 +269,7 @@ public function execute() } } else{ - $this->_logger->addInfo("Feedaty Cronjob is not enabled | date: ". date('Y-m-d H:i:s') ); + $this->_logger->addInfo("Feedaty | Cronjob is not enabled. Configure it from admin panel | date: ". date('Y-m-d H:i:s') ); } } @@ -280,7 +281,6 @@ protected function createProductReview($productId, $feedatyId, $feedatyProductRe $ratingCollection = $this->_reviewsHelper->getRatingCollection(); foreach ($ratingCollection as $ratingItem){ - $this->_logger->addInfo("RATING ITEM " . print_r($ratingItem,true)); $reviewFinalData['ratings'][$ratingItem['rating_id']] = $rating; } @@ -307,8 +307,6 @@ protected function createProductReview($productId, $feedatyId, $feedatyProductRe ->save(); foreach ($reviewFinalData['ratings'] as $ratingId => $ratingValue) { - $this->_logger->addInfo("RATING ID " . $ratingId); - $this->_logger->addInfo("RATING OPTION ID " . $ratingValue); $this->_ratingFactory->create() ->setRatingId($ratingId) diff --git a/Helper/ConfigRules.php b/Helper/ConfigRules.php index 5e75248..80abf64 100644 --- a/Helper/ConfigRules.php +++ b/Helper/ConfigRules.php @@ -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 * @@ -83,11 +87,11 @@ public function getReviewDefaultStore() return $default_store; } - //TODO CHECK IF NEED - public function getTimeout() + + public function getSendOrderStatus() { - $default_store = $this->getPreferencesConfig('create_reviews_default_store'); - return $default_store; + $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 index e949994..fe5ce31 100644 --- a/Helper/Orders.php +++ b/Helper/Orders.php @@ -4,109 +4,100 @@ namespace Feedaty\Badge\Helper; -use Feedaty\Badge\Helper\ConfigRules; -use Magento\Catalog\Api\Data\ProductInterface; -use Magento\Catalog\Api\ProductRepositoryInterface; -use Magento\Catalog\Model\ProductFactory; +use Feedaty\Badge\Model\Order; +use Feedaty\Badge\Model\OrderFactory; +use Feedaty\Badge\Model\ResourceModel\Order as FeedatyResourceOrder; +use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\ProductMetadataInterface; -use Magento\Store\Api\StoreRepositoryInterface; -use \Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Sales\Api\OrderRepositoryInterface; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Psr\Log\LoggerInterface; + class Orders extends AbstractHelper { - /** - * @var \Psr\Log\LoggerInterface + * @var LoggerInterface */ protected $logger; /** - * @var \Magento\Review\Model\ReviewFactory + * @var OrderRepositoryInterface */ - protected $_reviewFactory; + protected $orderRepository; + /** - * @var \Magento\Review\Model\RatingFactory + * @var ConfigRules */ - protected $_ratingFactory; + protected $helperConfigRules; /** - * @var StoreRepositoryInterface + * @var ScopeConfigInterface */ - protected $_storeRepository; + protected $scopeConfig; /** - * @var \Magento\Sales\Api\OrderRepositoryInterface + * @var SearchCriteriaBuilder */ - protected $orderRepository; + protected $searchCriteriaBuilder; /** - * @var \Feedaty\Badge\Helper\ConfigSetting + * @var ProductMetadataInterface */ - protected $_helperConfigRules; - + protected $productMetadata; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface + * @var Order */ - protected $scopeConfig; + private $feedatyOrderModel; /** - * @var \Magento\Framework\Api\SearchCriteriaBuilder + * @var FeedatyResourceOrder */ - protected $searchCriteriaBuilder; - + private $feedatyOrderResourceModel; /** - * @var ProductRepositoryInterface + * @var OrderFactory */ - protected $productRepository; - - - protected $productMetadata; - - protected $productFactory; + private $orderFactory; /** - * @param \Psr\Log\LoggerInterface $logger - * @param \Magento\Review\Model\ReviewFactory $reviewFactory - * @param \Magento\Review\Model\RatingFactory $ratingFactory - * @param StoreRepositoryInterface $storeRepository - * @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository - * @param \Feedaty\Badge\Helper\ConfigRules $helperConfigRules + * @param LoggerInterface $logger + * @param OrderRepositoryInterface $orderRepository + * @param ConfigRules $helperConfigRules * @param ScopeConfigInterface $scopeConfig - * @param \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder - * @param ProductRepositoryInterface $productRepository + * @param SearchCriteriaBuilder $searchCriteriaBuilder * @param ProductMetadataInterface $productMetadata - * @param ProductFactory $productFactory + * @param Order $feedatyOrderModel + * @param FeedatyResourceOrder $feedatyOrderResourceModel + * @param OrderFactory $orderFactory */ public function __construct( - \Psr\Log\LoggerInterface $logger, - \Magento\Review\Model\ReviewFactory $reviewFactory, - \Magento\Review\Model\RatingFactory $ratingFactory, - StoreRepositoryInterface $storeRepository, - \Magento\Sales\Api\OrderRepositoryInterface $orderRepository, - ConfigRules $helperConfigRules, - ScopeConfigInterface $scopeConfig, - \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder, - ProductRepositoryInterface $productRepository, - ProductMetadataInterface $productMetadata, - ProductFactory $productFactory - + LoggerInterface $logger, + OrderRepositoryInterface $orderRepository, + ConfigRules $helperConfigRules, + ScopeConfigInterface $scopeConfig, + SearchCriteriaBuilder $searchCriteriaBuilder, + ProductMetadataInterface $productMetadata, + Order $feedatyOrderModel, + FeedatyResourceOrder $feedatyOrderResourceModel, + OrderFactory $orderFactory ) { $this->logger = $logger; - $this->_reviewFactory = $reviewFactory; - $this->_ratingFactory = $ratingFactory; - $this->_storeRepository = $storeRepository; $this->orderRepository = $orderRepository; - $this->_helperConfigRules = $helperConfigRules; + $this->helperConfigRules = $helperConfigRules; $this->scopeConfig = $scopeConfig; $this->searchCriteriaBuilder = $searchCriteriaBuilder; - $this->productRepository = $productRepository; $this->productMetadata = $productMetadata; - $this->productFactory = $productFactory; + $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')); @@ -122,46 +113,120 @@ public function getOrderFromDate(){ public function getCulture($storeId) : string { $locale = $this->scopeConfig->getValue('general/locale/code', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId); - - $culture = strtok($locale, '/'); - + $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() { - $criteria = $this->searchCriteriaBuilder - // ->addFilter('status','processing','eq') - // ->addFilter('updated_at', $this->_ordersHelper->getOrderFromDate(),'gteq') - // ->addFilter('updated_at',$to,'lteq') - ->setPageSize(500) - ->setCurrentPage(1) - ->create(); - $orderResult = $this->orderRepository->getList($criteria); - - $orders = $orderResult->getItems(); + $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 index 19b70ae..0016bac 100644 --- a/Helper/Reviews.php +++ b/Helper/Reviews.php @@ -5,6 +5,9 @@ use Feedaty\Badge\Helper\ConfigRules; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Store\Api\StoreRepositoryInterface; +use Magento\Review\Model\ResourceModel\Review\CollectionFactory; +use Magento\Review\Model\ResourceModel\Rating\CollectionFactory as RatingCollectionFactory; + class Reviews extends AbstractHelper { @@ -37,6 +40,14 @@ class Reviews extends AbstractHelper * @var \Feedaty\Badge\Helper\ConfigSetting */ protected $_helperConfigRules; + /** + * @var CollectionFactory + */ + private $reviewCollection; + /** + * @var RatingCollectionFactory + */ + private $ratingCollectionFactory; /** * @param \Psr\Log\LoggerInterface $logger @@ -51,7 +62,9 @@ public function __construct( \Magento\Review\Model\RatingFactory $ratingFactory, StoreRepositoryInterface $storeRepository, \Magento\Sales\Api\OrderRepositoryInterface $orderRepository, - ConfigRules $helperConfigRules + ConfigRules $helperConfigRules, + CollectionFactory $reviewCollection, + RatingCollectionFactory $ratingCollectionFactory ) { @@ -61,6 +74,8 @@ public function __construct( $this->_storeRepository = $storeRepository; $this->_orderRepository = $orderRepository; $this->_helperConfigRules = $helperConfigRules; + $this->reviewCollection = $reviewCollection; + $this->ratingCollectionFactory = $ratingCollectionFactory; } /** @@ -73,7 +88,7 @@ public function disableReview($reviewData) try { $review = $this->_reviewFactory->create()->load($reviewData['review_id']); } catch (\Exception $e) { - $this->_logger->info("Feedaty error disableReview : " . $e->getMessage()); + $this->_logger->info("Feedaty | Error can not disable Review : " . $e->getMessage()); } if (!is_null($review)) { @@ -91,7 +106,7 @@ public function mediateReview($reviewData, $reviewDetail) try { $review = $this->_reviewFactory->create()->load($reviewData['review_id']); } catch (\Exception $e) { - $this->_logger->info("Feedaty Error mediateReview : " . $e->getMessage()); + $this->_logger->info("Feedaty | Error cannot mediate Review : " . $e->getMessage()); } if (!is_null($review)) { @@ -119,7 +134,7 @@ public function getStoreViewIdByOrder($orderId) $order = $this->_orderRepository->get($orderId); } catch (\Exception $e) { - $this->_logger->info("Feedaty Error : order id does not exist " . $orderId . " Error message". $e->getMessage()); + $this->_logger->info("Feedaty | Error : order id does not exist " . $orderId . " Error message". $e->getMessage()); } if (!is_null($order)) { @@ -156,7 +171,8 @@ function getAllStoreList() */ public function getReviewCollection($productId, $feedatyId) { - $collection = $this->_reviewFactory->create()->getCollection() + + $collection = $this->reviewCollection->create() ->addEntityFilter( 'product', $productId @@ -168,6 +184,7 @@ public function getReviewCollection($productId, $feedatyId) ->setDateOrder(); return $collection->getData(); + } /* @@ -175,7 +192,7 @@ public function getReviewCollection($productId, $feedatyId) */ public function getAllFeedatyReviewCount() { - $collection = $this->_reviewFactory->create()->getCollection() + $collection = $this->reviewCollection->create() ->addFieldToFilter( 'feedaty_source', 1 @@ -194,7 +211,7 @@ public function getAllFeedatyReviewCount() */ public function getAllFeedatyRemovedReviewCount() { - $collection = $this->_reviewFactory->create()->getCollection() + $collection = $this->reviewCollection->create() ->addStatusFilter( \Magento\Review\Model\Review::STATUS_NOT_APPROVED) ->addFieldToFilter( @@ -215,7 +232,7 @@ public function getAllFeedatyRemovedReviewCount() */ public function getAllFeedatyMediatedReviewCount() { - $collection = $this->_reviewFactory->create()->getCollection() + $collection = $this->reviewCollection->create() ->addFieldToFilter( 'feedaty_product_mediated', 1 @@ -234,7 +251,7 @@ public function getAllFeedatyMediatedReviewCount() */ public function getLastFeedatyReviewCreated() { - $collection = $this->_reviewFactory->create()->getCollection() + $collection = $this->reviewCollection->create() ->addFieldToFilter( 'feedaty_source', 1 @@ -252,15 +269,15 @@ public function getLastFeedatyReviewCreated() /** - * @param $feedatyid + * @param $feedatyId * @return mixed */ - public function getAllReviewsByFeedatyId($feedatyid) + public function getAllReviewsByFeedatyId($feedatyId) { - $collection = $this->_reviewFactory->create()->getCollection() + $collection = $this->reviewCollection->create() ->addFieldToFilter( 'feedaty_product_review_id', - $feedatyid + $feedatyId ) ->setOrder( 'review_id', @@ -272,11 +289,14 @@ public function getAllReviewsByFeedatyId($feedatyid) } /** - * @return mixed - * @throws \Magento\Framework\Exception\LocalizedException + * @return array|null */ - public function getRatingCollection(){ - $ratingCollection = $this->_ratingFactory->create()->getResourceCollection()->addEntityFilter('product')->load(); + public function getRatingCollection() + { + $ratingCollection = $this->ratingCollectionFactory->create() + ->addEntityFilter('product') + ->load(); + return $ratingCollection->getData(); } 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/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 index 619d88c..6648ab3 100644 --- a/Model/Config/Source/ProductBadgeStyle.php +++ b/Model/Config/Source/ProductBadgeStyle.php @@ -8,9 +8,9 @@ class ProductBadgeStyle implements ArrayInterface public function toOptionArray() { $return = [ - ["value" => "product","label" => __("Product Bagde Style")], - ["value" => "carouselproduct","label" => __("Product Carousel Bagde Style")], - ["value" => "product_tab","label" => __("Product Tab Bagde Style")], + ["value" => "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/StoreBadgeStyle.php b/Model/Config/Source/StoreBadgeStyle.php index 741f266..98cc9ac 100644 --- a/Model/Config/Source/StoreBadgeStyle.php +++ b/Model/Config/Source/StoreBadgeStyle.php @@ -8,8 +8,8 @@ class StoreBadgeStyle implements ArrayInterface public function toOptionArray() { $return = [ - ["value" => "merchant","label" => __("Merchant Bagde Style")], - ["value" => "carousel","label" => __("Carousel Bagde Style")] + ["value" => "merchant","label" => __("Merchant Badge Style")], + ["value" => "carousel","label" => __("Carousel Badge Style")] ]; return $return; diff --git a/Model/Config/Source/WebService.php b/Model/Config/Source/WebService.php index d49d71d..c9fed4e 100755 --- a/Model/Config/Source/WebService.php +++ b/Model/Config/Source/WebService.php @@ -1,128 +1,108 @@ _scopeConfig = $scopeConfig; - $this->_storeManager = $storeManager; - $this->_feedatyHelper = $feedatyHelper; - $this->_curl = $curl; - $this->_objectManager = $objectmanager; - $this->_json = $json; $this->_configRules = $configRules; $this->_logger = $logger; - - $timeout = $this->_scopeConfig->getValue( - 'feedaty_global/timeout_connection/timeout', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - ); - - $timeout = $timeout == null ? "1000" : $timeout; - - - $this->curlFactory = $curlFactory; + $this->cache = $cache; + $this->resolver = $resolver; + $this->serializer = $serializer; + $this->productMetadata = $productMetadata; + $this->moduleList = $moduleList; + $this->storeManager = $storeManager; } - /** - * @param $result - * @return array|bool|float|int|mixed|string|null + /* + * JSON encode */ - public function unserializeJson($result) + public function jsonEncode($data) { - $jsonDecode = $this->_json->unserialize($result); - - return $jsonDecode; + return $this->serializer->serialize($data); } - /** - * Get request headers - * - * @return array + /* + * JSON decode */ - private function getHeaders() + public function jsonDecode($string) { - return [ - 'Content-Type' => 'application/x-www-form-urlencoded' - ]; + return $this->serializer->unserialize($string); } /** @@ -130,23 +110,51 @@ private function getHeaders() */ private function getReqToken() { - $this->_logger->info('FEEDATY TOKEN LOG REQ: START'); $url = "http://api.feedaty.com/OAuth/RequestToken"; try { $curl = $this->curlFactory->create(); $curl->addHeader('Content-Type', 'application/x-www-form-urlencoded'); - $curl->setTimeout(3000); + $curl->setTimeout(1000); $curl->get($url); - $response = json_decode($curl->getBody()); + $response = $this->jsonDecode($curl->getBody()); + } catch (\Exception $exception) { + $response = []; + $this->_logger->critical('Feedaty | Error cannot get Request Token: '.$exception); + } + + return $response; + } + + /** + * Send Order + * @param $data + * @return array|bool|float|int|string|null + */ + public function sendOrder($data) { + + $url = 'http://api.feedaty.com/Orders/Insert'; + + $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 TOKEN LOG ERROR: '.$exception); + $this->_logger->critical('Feedaty | Error cannot send order to Feedaty API: '.$exception); } return $response; + } + /** * Function getAccessToken - get the access token * @@ -154,22 +162,33 @@ private function getReqToken() * * @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; } @@ -184,126 +203,95 @@ 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) { - - $cache = $this->_objectManager->get('Magento\Framework\App\CacheInterface'); - - $timeout = $this->_scopeConfig->getValue( - 'feedaty_global/timeout_widgets/timeout', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - ); - - $cache_key = "feedaty_product_tab_".$feedaty_code . "PID=" .$id; - - $content = $cache->load($cache_key); - - if (!$content || strlen($content) == 0 || $content === "null") - { - $ch = curl_init(); - - $resolver = $this->_objectManager->get('Magento\Framework\Locale\Resolver'); - - $url = 'http://widget.zoorate.com/go.php?function=feed&action=ws&task=product&merchant_code='.$feedaty_code.'&ProductID='.$id.'&language='.$resolver->getLocale(); - - 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); - - if (strlen($content) > 0) - { - // 24 hours of cache - $cache->save($content, $cache_key, array("feedaty_cache"), 24*60*60); - } - } - - $data = json_decode($content, true); - - return $data; - } /** - * @param $productId - * @return mixed|string|null + * @param int $row + * @param int $count + * @return mixed|string */ - /*public function getProductReviews($productId){ - return $this->getAllReviews('?retrieve=onlyproductreviews&sku='.$productId); - }*/ - - /* public function getAllProductReviews(){ - return $this->getAllReviews('?retrieve=onlyproductreviews'); - }*/ - public function getProductReviewsPagination($row = 0, $count = 50){ $allReviews = $this->getAllReviews('?retrieve=onlyproductreviews&row='.$row.'&count='.$count); return $allReviews['Reviews']; } + /** + * @param int $row + * @param int $count + * @return mixed + */ public function getRemovedReviews($row = 0, $count = 50){ $allReviews = $this->getAllRemovedReviews('?row='.$row.'&count='.$count); - - $this->_logger->info('ALL REMOVED REVIEW FEEDATY REMOVED: '. print_r($allReviews['Reviews'],true)); - return $allReviews['Reviews']; - } + /** + * @param int $row + * @param int $count + * @return mixed + */ public function getMediatedReviews($row = 0, $count = 50){ $allReviews = $this->getAllMediatedReviews('?row='.$row.'&count='.$count); - - $this->_logger->info('ALL REMOVED REVIEW FEEDATY REMOVED: '. print_r($allReviews['Reviews'],true)); - return $allReviews['Reviews']; } + /** + * @return mixed|string + */ public function getTotalProductReviewsCount() { $allProductReviews = $this->getAllReviews('?retrieve=onlyproductreviews&row=0&count=1'); - $totalResults = $allProductReviews['TotalProductReviews']; return $totalResults; } + /** + * Get Removed Reviews Count + * @return mixed + */ public function getTotalProductRemovedReviewsCount() { $allProductReviews = $this->getAllRemovedReviews('?row=0&count=1'); - // $this->_logger->info('Feedaty REMOVED: '. print_r($allProductReviews,true)); $totalResults = $allProductReviews['TotalResults']; return $totalResults; } + /** + * Get Mediated Reviews Count + * @return mixed + */ public function getTotalProductMediatedReviewsCount() { $allProductReviews = $this->getAllMediatedReviews('?row=0&count=1'); - $this->_logger->info('Feedaty MEDIATED: '. print_r($allProductReviews,true)); $totalResults = $allProductReviews['TotalResults']; return $totalResults; } - + /** + * 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); } + /** + * Get All Mediated Reviews + * @param string $params + * @return mixed|null + */ public function getAllMediatedReviews($params = '') { $url = 'http://api.feedaty.com/Reviews/Mediated'.$params; @@ -312,8 +300,9 @@ public function getAllMediatedReviews($params = '') } /** + * Get all reviews * @param string $params - * @return mixed|string|null + * @return mixed|null */ public function getAllReviews($params = '') { @@ -322,235 +311,141 @@ public function getAllReviews($params = '') } - + /** + * Get Reviews Data + * @param $url + * @return array|mixed|null + */ public function getReviewsData($url) { - $merchant = $this->_configRules->getFeedatyCode(); - $secret = $this->_configRules->getFeedatySecret(); - $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 CURL: '. $e->getMessage()); - } - - // output of curl request - $result = $this->_curl->getBody(); - - $data = $this->unserializeJson($result); - + $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']; - return $reviews; + + } catch (\Exception $e) { + $this->_logger->critical('Feedaty | Error getting Reviews Data: '. $e->getMessage()); } - } catch (\Exception $e) { - $this->_logger->critical('Feedaty log TOKEN: '. $e->getMessage()); + + return $reviews; } return null; } - - /** - * Function send_order - * - * @param object $data - * + * Get Feedaty data + * @param $feedaty_code + * @return array|bool|float|int|string|null */ - public function sendOrder($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'; - - $token = $this->getReqToken(); - - $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) ); + public function getFeedatyData($feedaty_code) + { - $fdDebugEnabled = $this->_scopeConfig->getValue( 'feedaty_global/debug/debug_enabled', $store_scope ); + $string = "FeedatyData" . $feedaty_code . $this->resolver->getLocale(); - if($fdDebugEnabled != 0) { + $content = $this->cache->load( $string ); - $message = $data; - $this->_feedatyHelper->feedatyDebug($message, "FEEDATY DATA"); + $data = []; - $message = $content; - $this->_feedatyHelper->feedatyDebug($message, "FEEDATY RESPONSE"); + if ( !$content || strlen($content) == 0 || $content === "null" ) + { + $url = 'https://widget.feedaty.com/?action=widget_list&style_ver=2021&merchant='.$feedaty_code; - $message = curl_getinfo($ch,CURLINFO_HEADER_OUT); - $this->_feedatyHelper->feedatyDebug($message, "CURL HEADER INFO"); + $arrContextOptions=array( + "ssl"=>array( + "verify_peer"=>false, + "verify_peer_name"=>false, + ), + ); - $message = curl_getinfo($ch,CURLINFO_HEADER_OUT); - $this->_feedatyHelper->feedatyDebug($message, "CURL INFO"); + $content = file_get_contents( $url, false, stream_context_create($arrContextOptions)); - if(curl_errno($ch)) - $this->_feedatyHelper->feedatyDebug(curl_error($ch), "CURL ERROR"); + $this->cache->save($content, $string, array("feedaty_cache"), 24*60*60); // 24 hours of cache } + $data = $this->jsonDecode($content); - curl_close($ch); - - return 1 ; + return $data; } - - /** - * 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'; - - $token = $this->getReqToken(); - - $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); + * @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_POST, 1); - curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($data)); + public function getModuleVersion() + { + return $this->moduleList->getOne('Feedaty_Badge')['setup_version']; + } - curl_setopt($ch, CURLOPT_HTTPHEADER,['Content-Type: application/json', 'Authorization: Oauth '.$accessToken->AccessToken]); - curl_setopt($ch, CURLOPT_HEADER, 1); + public function getBaseUrl() + { + return $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB); + } - curl_setopt($ch, CURLINFO_HEADER_OUT, true); + public function getStoreName() + { + return $this->storeManager->getStore()->getName(); + } - $content = trim( curl_exec($ch) ); + public function fdSendInstallationInfo() + { - $fdDebugEnabled = $this->_scopeConfig->getValue( 'feedaty_global/debug/debug_enabled', $store_scope ); + /* Platform (obviously Magento) and version */ + $fdata['keyValuePairs'][] = array('Key' => 'Platform', 'Value' => $this->getPlatform()); - if($fdDebugEnabled != 0) { + /* Plugin version */ + $fdata['keyValuePairs'][] = array('Key' => 'Version', 'Value' => $this->getModuleVersion()); - $message = $data; - $this->_feedatyHelper->feedatyDebug($message, "FEEDATY DATA"); + /* Base store url */ + $fdata['keyValuePairs'][] = array('Key' => 'Url', 'Value' => $this->getBaseUrl()); - $message = $content; - $this->_feedatyHelper->feedatyDebug($message, "FEEDATY RESPONSE"); + /* Php version */ + $fdata['keyValuePairs'][] = array('Key' => 'Php Version', 'Value' => phpversion()); - $message = curl_getinfo($ch,CURLINFO_HEADER_OUT); - $this->_feedatyHelper->feedatyDebug($message, "CURL HEADER INFO"); + /* Store name */ + $fdata['keyValuePairs'][] = array('Key' => 'Name', 'Value' => $this->getStoreName()); - $message = curl_getinfo($ch,CURLINFO_HEADER_OUT); - $this->_feedatyHelper->feedatyDebug($message, "CURL INFO"); + /* Current server date */ + $fdata['keyValuePairs'][] = array('Key' => 'Date', 'Value' => date('c')); - if(curl_errno($ch)) - $this->_feedatyHelper->feedatyDebug(curl_error($ch), "CURL ERROR"); + /* 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()); } - curl_close($ch); - - return 1 ; - } - /** - * 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'); - - $timeout = $this->_scopeConfig->getValue( - 'feedaty_global/timeout_widgets/timeout', - \Magento\Store\Model\ScopeInterface::SCOPE_STORE - ); - - $string = "FeedatyData" . $feedaty_code . $resolver->getLocale(); - - $content = $cache->load( $string ); - if ( !$content || strlen($content) == 0 || $content === "null" ) - { - $url = 'https://widget.feedaty.com/?action=widget_list&style_ver=2021&merchant='.$feedaty_code; - $arrContextOptions=array( - "ssl"=>array( - "verify_peer"=>false, - "verify_peer_name"=>false, - ), - ); - - $content = file_get_contents( $url, false, stream_context_create($arrContextOptions)); - - $cache->save($content, $string, array("feedaty_cache"), 24*60*60); // 24 hours of cache - - } - - $data = json_decode($content, true); - - if(!$data){ - $data = []; - } - return $data; - - } } 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/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/Observer/InterceptOrder.php b/Observer/InterceptOrder.php deleted file mode 100644 index 2b39f93..0000000 --- a/Observer/InterceptOrder.php +++ /dev/null @@ -1,326 +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_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 - - echo "
";
-                        var_dump($fd_data);
-                        echo "
"; - - - print_r($merchant); - print_r($secret); - die('FEEDATY ORDER DATA: DATA'); - - $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/Setup/UpgradeSchema.php b/Setup/UpgradeSchema.php index 3f476ce..f197d7c 100644 --- a/Setup/UpgradeSchema.php +++ b/Setup/UpgradeSchema.php @@ -55,54 +55,19 @@ public function upgrade( SchemaSetupInterface $setup, ModuleContextInterface $co 'size' => null, 'comment' => 'Feedaty Review Create At', ], - - ]; - - $connection = $setup->getConnection(); - - foreach ($columns as $name => $definition) { - $connection->addColumn($tableName, $name, $definition); - } - } - } - - - if(version_compare($context->getVersion(), '2.7.2') < 0) { - - $tableName = $setup->getTable('review_detail'); - - if ($setup->getConnection()->isTableExists($tableName) == true) { - $columns = [ 'feedaty_product_review_id' => [ 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, 'nullable' => false, 'default' => 0, 'comment' => 'Feedaty Product Review ID', - ] - ]; - - $connection = $setup->getConnection(); - - foreach ($columns as $name => $definition) { - $connection->addColumn($tableName, $name, $definition); - } - } - - } - - - if(version_compare($context->getVersion(), '2.7.3') < 0) { - - $tableName = $setup->getTable('review_detail'); - - if ($setup->getConnection()->isTableExists($tableName) == true) { - $columns = [ + ], 'feedaty_product_mediated' => [ 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN, 'nullable' => false, 'default' => 0, 'comment' => 'Feedaty Product Mediated', ] + ]; $connection = $setup->getConnection(); @@ -111,7 +76,64 @@ public function upgrade( SchemaSetupInterface $setup, ModuleContextInterface $co $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 6c580c1..1525170 100755 --- a/composer.json +++ b/composer.json @@ -35,7 +35,7 @@ "AFL-3.0" ], - "version": "2.6.7-stable", + "version": "2.7.0-stable", "type": "magento2-module", 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 0a2281a..d7f0993 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -48,7 +48,6 @@ - @@ -57,46 +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 - - -
diff --git a/etc/crontab.xml b/etc/crontab.xml index 2e422d1..6123071 100644 --- a/etc/crontab.xml +++ b/etc/crontab.xml @@ -4,8 +4,8 @@ */5 * * * * - - */1 * * * * + + */30 * * * * 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/module.xml b/etc/module.xml index 70a3b14..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 932c14a..f39632b 100755 --- a/etc/widget.xml +++ b/etc/widget.xml @@ -35,13 +35,13 @@ - + - + diff --git a/view/frontend/layout/catalog_product_view.xml b/view/frontend/layout/catalog_product_view.xml index 98ade5c..7e9943f 100644 --- a/view/frontend/layout/catalog_product_view.xml +++ b/view/frontend/layout/catalog_product_view.xml @@ -2,7 +2,7 @@ - - - - - - - - - - - \ 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/widget/product-bagde.phtml b/view/frontend/templates/widget/product-badge.phtml similarity index 100% rename from view/frontend/templates/widget/product-bagde.phtml rename to view/frontend/templates/widget/product-badge.phtml diff --git a/view/frontend/templates/widget/store-bagde.phtml b/view/frontend/templates/widget/store-badge.phtml similarity index 100% rename from view/frontend/templates/widget/store-bagde.phtml rename to view/frontend/templates/widget/store-badge.phtml