├── Model ├── Logger.php ├── Sync.php ├── OrderStatusHistory.php ├── ResourceModel │ ├── Richsnippet.php │ ├── Sync.php │ ├── Richsnippet │ │ └── Collection.php │ ├── OrderStatusHistory.php │ ├── Sync │ │ └── Collection.php │ └── OrderStatusHistory │ │ └── Collection.php ├── Logger │ └── YotpoHandler.php ├── Richsnippet.php ├── Jobs │ ├── ResetSyncFlags.php │ ├── UpdateMetadata.php │ └── OrdersSync.php ├── Api │ ├── AccountPlatform.php │ ├── Purchases.php │ ├── AccountUsages.php │ └── Products.php ├── AbstractApi.php ├── AbstractJobs.php └── Schema.php ├── view ├── adminhtml │ ├── web │ │ ├── images │ │ │ ├── consumer_insights.png │ │ │ ├── visual_marketing.jpg │ │ │ ├── reviews_and_ratings.jpg │ │ │ └── icons │ │ │ │ ├── upload-icon.svg │ │ │ │ ├── collect-icon.svg │ │ │ │ ├── photo-icon.svg │ │ │ │ ├── star-icon.svg │ │ │ │ ├── rate-icon.svg │ │ │ │ └── email-icon.svg │ │ └── css │ │ │ └── source │ │ │ └── _module.less │ ├── templates │ │ ├── system │ │ │ └── config │ │ │ │ ├── module_version.phtml │ │ │ │ ├── sync_status.phtml │ │ │ │ └── launch_yotpo_button.phtml │ │ ├── dashboard │ │ │ └── yotpo_reviews_tab.phtml │ │ └── report │ │ │ └── reviews.phtml │ └── layout │ │ └── yotpo_yotpo_report_reviews.xml └── frontend │ ├── layout │ ├── checkout_onepage_success.xml │ └── default.xml │ ├── templates │ ├── widget_script.phtml │ ├── widget_div.phtml │ ├── conversion.phtml │ └── bottomline.phtml │ └── web │ └── css │ └── source │ └── _module.less ├── registration.php ├── .gitignore ├── etc ├── events.xml ├── adminhtml │ ├── di.xml │ ├── routes.xml │ ├── events.xml │ ├── menu.xml │ └── system.xml ├── crontab.xml ├── cron_groups.xml ├── module.xml ├── config.xml ├── acl.xml ├── csp_whitelist.xml └── di.xml ├── Block ├── Adminhtml │ ├── Dashboard │ │ └── Tab │ │ │ └── YotpoReviews.php │ ├── System │ │ └── Config │ │ │ ├── Form │ │ │ └── Field │ │ │ │ ├── NoScopes.php │ │ │ │ ├── Date.php │ │ │ │ └── SyncStatus.php │ │ │ ├── ModuleVersion.php │ │ │ └── LaunchYotpoButton.php │ └── Report │ │ └── Reviews.php ├── Conversion.php └── Yotpo.php ├── composer.json ├── Controller └── Adminhtml │ ├── Dashboard │ └── YotpoReviews.php │ ├── External │ ├── Reviews.php │ └── Analytics.php │ └── Report │ └── Reviews.php ├── Plugin ├── Backend │ └── Block │ │ └── Dashboard │ │ └── Grids.php ├── Catalog │ └── Block │ │ └── Product │ │ ├── View.php │ │ └── ListProduct.php ├── AbstractYotpoReviewsSummary.php └── Review │ └── Block │ └── Product │ └── ReviewRenderer.php ├── Helper ├── Data.php └── RichSnippets.php ├── Console └── Command │ ├── UpdateMetadataCommand.php │ ├── SyncCommand.php │ └── ResetCommand.php ├── Observer ├── OrderSaveAfter.php └── Config │ ├── SingleStoreModeSwitch.php │ └── Save.php ├── README.md ├── Lib └── Http │ └── Client │ └── Curl.php ├── Setup └── UpgradeData.php ├── i18n └── en_US.csv ├── LICENSE.txt └── LICENSE_AFL.txt /Model/Logger.php: -------------------------------------------------------------------------------- 1 | 6 | 7 |
getModuleVersion() ?>
8 | 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #==== OS / Editors / etc... ===================# 2 | .DS_Store 3 | .project 4 | .idea 5 | .phpintel 6 | *.sublime-* 7 | .directory 8 | .ftpconfig 9 | .tags 10 | .tags1 11 | Thumbs.db 12 | *Thumbs.db 13 | *.girit-local* 14 | *~ 15 | 16 | nbproject/*.* 17 | nbproject/ 18 | *.iml 19 | -------------------------------------------------------------------------------- /Model/Sync.php: -------------------------------------------------------------------------------- 1 | _init(\Yotpo\Yotpo\Model\ResourceModel\Sync::class); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /etc/events.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Model/OrderStatusHistory.php: -------------------------------------------------------------------------------- 1 | _init(\Yotpo\Yotpo\Model\ResourceModel\OrderStatusHistory::class); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /view/adminhtml/web/images/icons/upload-icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /etc/adminhtml/di.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /etc/adminhtml/routes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Model/ResourceModel/Richsnippet.php: -------------------------------------------------------------------------------- 1 | _init('yotpo_rich_snippets', 'rich_snippet_id'); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Model/ResourceModel/Sync.php: -------------------------------------------------------------------------------- 1 | _setResource('sales'); 15 | $this->_init('yotpo_sync', 'sync_id'); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Model/Logger/YotpoHandler.php: -------------------------------------------------------------------------------- 1 | _init( 10 | \Yotpo\Yotpo\Model\Richsnippet::class, 11 | \Yotpo\Yotpo\Model\ResourceModel\Richsnippet::class 12 | ); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Model/ResourceModel/OrderStatusHistory.php: -------------------------------------------------------------------------------- 1 | _setResource('sales'); 15 | $this->_init('yotpo_order_status_history', 'id'); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Model/ResourceModel/Sync/Collection.php: -------------------------------------------------------------------------------- 1 | _init( 13 | \Yotpo\Yotpo\Model\Sync::class, 14 | \Yotpo\Yotpo\Model\ResourceModel\Sync::class 15 | ); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Block/Adminhtml/Dashboard/Tab/YotpoReviews.php: -------------------------------------------------------------------------------- 1 | unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue()->unsCanRestoreToDefault(); 12 | return parent::render($element); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Model/ResourceModel/OrderStatusHistory/Collection.php: -------------------------------------------------------------------------------- 1 | _init( 13 | \Yotpo\Yotpo\Model\OrderStatusHistory::class, 14 | \Yotpo\Yotpo\Model\ResourceModel\OrderStatusHistory::class 15 | ); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "yotpo/module-review", 3 | "description": "Yotpo Reviews extension for Magento2", 4 | "version": "3.1.4", 5 | "license": [ 6 | "OSL-3.0", 7 | "AFL-3.0" 8 | ], 9 | "require": { 10 | "php": "~5.6.0|^7.0", 11 | "magento/framework": ">=101.0.0" 12 | }, 13 | "type": "magento2-module", 14 | "autoload": { 15 | "files": [ 16 | "registration.php" 17 | ], 18 | "psr-4": { 19 | "Yotpo\\Yotpo\\": "" 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /etc/crontab.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | * * * * * 6 | 7 | 8 | 30 2 * * * 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /view/adminhtml/templates/system/config/sync_status.phtml: -------------------------------------------------------------------------------- 1 | getStatus(); 6 | ?> 7 | 8 |
escapeHtml(__('Sync progress: %1', $status['total_orders_synced'] . '/' . $status['total_orders'])) ?>
9 |
escapeHtml(__('Last sync date: %1', $status['last_sync_date'])) ?>
10 |
escapeHtml(__('Total orders synced with Yotpo: %1', $status['total_orders_synced_all'])) ?>
11 | 12 | -------------------------------------------------------------------------------- /view/frontend/layout/checkout_onepage_success.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /etc/adminhtml/events.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /etc/cron_groups.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 1 5 | 4 6 | 2 7 | 10 8 | 60 9 | 600 10 | 1 11 | 12 | 13 | -------------------------------------------------------------------------------- /view/adminhtml/web/images/icons/collect-icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /view/adminhtml/web/images/icons/photo-icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /view/adminhtml/web/images/icons/star-icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /view/frontend/templates/widget_script.phtml: -------------------------------------------------------------------------------- 1 | 6 | isEnabled()) { 7 | return; 8 | } 9 | ?> 10 | 11 | 14 | 15 | 16 | 19 | 20 | -------------------------------------------------------------------------------- /Controller/Adminhtml/Dashboard/YotpoReviews.php: -------------------------------------------------------------------------------- 1 | layoutFactory->create() 17 | ->createBlock(\Yotpo\Yotpo\Block\Adminhtml\Dashboard\Tab\YotpoReviews::class) 18 | ->setId('yotpoReviewsTab') 19 | ->toHtml(); 20 | $resultRaw = $this->resultRawFactory->create(); 21 | return $resultRaw->setContents($output); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Plugin/Backend/Block/Dashboard/Grids.php: -------------------------------------------------------------------------------- 1 | addTab( 19 | 'yotpo_reviews', 20 | [ 21 | 'label' => __('Yotpo Reviews'), 22 | 'url' => $subject->getUrl('yotpo_yotpo/*/YotpoReviews', ['_current' => true]), 23 | 'class' => 'ajax' 24 | ] 25 | ); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /etc/module.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Model/Richsnippet.php: -------------------------------------------------------------------------------- 1 | _init(\Yotpo\Yotpo\Model\ResourceModel\Richsnippet::class); 9 | } 10 | 11 | public function isValid() 12 | { 13 | return (strtotime($this->getExpirationTime()) > time()); 14 | } 15 | 16 | public function getSnippetByProductIdAndStoreId($product_id, $store_id) 17 | { 18 | $collection = $this->getCollection() 19 | ->addFieldToFilter('store_id', $store_id) 20 | ->addFieldToFilter('product_id', $product_id) 21 | ->setPageSize(1); 22 | if ($collection->count()) { 23 | return $collection->getFirstItem(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /view/frontend/templates/widget_div.phtml: -------------------------------------------------------------------------------- 1 | 6 | isEnabled() && $block->isRenderWidget() && $block->hasProduct())) { 7 | return; 8 | } 9 | ?> 10 | 11 | isRenderWidget()) : ?> 12 |
20 |
21 | 22 | 23 | -------------------------------------------------------------------------------- /view/frontend/templates/conversion.phtml: -------------------------------------------------------------------------------- 1 | 6 | isEnabled() && $block->hasOrder())) { 7 | return; 8 | } ?> 9 | 10 | getJsonData())) : ?> 11 | 14 | 17 | 18 | getNoscriptSrc())) : ?> 19 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /view/frontend/templates/bottomline.phtml: -------------------------------------------------------------------------------- 1 | 6 | isEnabled() && ($block->isRenderBottomline() || $block->isRenderBottomlineQna()))) { 7 | return; 8 | } ?> 9 | 10 |
11 | isRenderBottomline()) : ?> 12 |
15 |
16 | 17 | isRenderBottomlineQna()) : ?> 18 |
21 |
22 | 23 |
24 | 25 | -------------------------------------------------------------------------------- /view/adminhtml/templates/system/config/launch_yotpo_button.phtml: -------------------------------------------------------------------------------- 1 | 6 | isStoreScope()) : ?> 7 |

escapeHtml(__('Yotpo can only be connected, enabled, or disabled via the Store View menu.'))?>
8 | escapeHtml(__('To connect your App Key and API secret, first select the relevant Store View.')) ?> 9 |

10 |

11 | 12 | 13 |

14 | escapeHtml(__('Need help?')) ?> escapeHtml(__('Setup Guide')) ?> 15 |

16 | -------------------------------------------------------------------------------- /Model/Jobs/ResetSyncFlags.php: -------------------------------------------------------------------------------- 1 | _processOutput("ResetSyncFlags::execute() - (entity: {$entityType}) [STARTED]", "debug"); 13 | $this->_resourceConnection->getConnection('sales')->update( 14 | $this->_resourceConnection->getTableName('yotpo_sync', 'sales'), 15 | ['sync_flag' => 0], 16 | (($entityType) ? ['entity_type = ?' => "{$entityType}"] : []) 17 | ); 18 | $this->_processOutput("Yotpo - resetSyncFlags (entity: {$entityType}) [DONE]", "debug"); 19 | } catch (\Exception $e) { 20 | $this->_processOutput("ResetSyncFlags::execute() - Exception: " . $e->getMessage() . "\n" . $e->getTraceAsString(), "error"); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /view/frontend/layout/default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /view/adminhtml/layout/yotpo_yotpo_report_reviews.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Yotpo Reviews 5 | 6 | 7 | 8 | 9 | 10 | 0 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /etc/adminhtml/menu.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /view/adminhtml/web/images/icons/rate-icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Helper/Data.php: -------------------------------------------------------------------------------- 1 | getLayout()->createBlock(\Yotpo\Yotpo\Block\Yotpo::class) 14 | ->setTemplate('Yotpo_Yotpo::' . $blockName . '.phtml') 15 | ->setAttribute('product', $product) 16 | ->setAttribute('fromHelper', true) 17 | ->toHtml(); 18 | } 19 | 20 | public function showWidget(AbstractBlock $parentBlock, Product $product = null) 21 | { 22 | return $this->renderYotpoProductBlock('widget_div', $parentBlock, $product); 23 | } 24 | 25 | public function showBottomline(AbstractBlock $parentBlock, Product $product = null) 26 | { 27 | return $this->renderYotpoProductBlock('bottomline', $parentBlock, $product); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Plugin/Catalog/Block/Product/View.php: -------------------------------------------------------------------------------- 1 | yotpoConfig = $yotpoConfig; 21 | } 22 | 23 | /** 24 | * @method beforeToHtml 25 | * @param \Magento\Catalog\Block\Product\View $viewBlock 26 | * 27 | * @return array 28 | */ 29 | public function beforeToHtml( 30 | \Magento\Catalog\Block\Product\View $viewBlock 31 | ) { 32 | /** 33 | * @var \Magento\Framework\View\Layout $layout 34 | */ 35 | $layout = $viewBlock->getLayout(); 36 | 37 | if ($this->yotpoConfig->isEnabled() && $this->yotpoConfig->isMdrEnabled() && $layout->getBlock('reviews.tab')) { 38 | $layout->unsetElement('reviews.tab'); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Block/Adminhtml/System/Config/Form/Field/Date.php: -------------------------------------------------------------------------------- 1 | yotpoConfig = $yotpoConfig; 27 | parent::__construct($context, $data); 28 | } 29 | 30 | public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element) 31 | { 32 | $element->setDateFormat(DateTime::DATE_INTERNAL_FORMAT); 33 | $element->setTimeFormat(null); 34 | $element->setMinDate($this->yotpoConfig->getOrdersSyncAfterMinDate()); 35 | return parent::render($element); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /view/adminhtml/web/images/icons/email-icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /view/frontend/web/css/source/_module.less: -------------------------------------------------------------------------------- 1 | & when (@media-common = true) { 2 | .yotpo-yotpo-is-enabled { 3 | .yotpoBottomLine { 4 | width: 100%; 5 | } 6 | 7 | .yotpo-icon-double-bubble, 8 | .yotpo-stars { 9 | margin: 0 5px 0 0 !important; 10 | } 11 | 12 | .thumbnail .yotpo a { 13 | display: inline-block; 14 | } 15 | 16 | div.yotpo.bottomLine { 17 | display: inline-block; 18 | margin: 0 10px 1px 0; 19 | } 20 | 21 | div.yotpo.QABottomLine { 22 | display: inline-block; 23 | } 24 | 25 | div.yotpo.bottomLine.bottomline-position { 26 | display: inline-block; 27 | margin: 0 10px 1px 0; 28 | } 29 | 30 | .product-item .product-item-actions { 31 | margin-top: 5px !important; 32 | } 33 | 34 | &.catalog-category-view, 35 | &.catalog-product-view { 36 | &.page-products { 37 | .product-item .product-item-actions { 38 | margin-top: 0 !important; 39 | } 40 | } 41 | 42 | .product-info-main .product-reviews-summary { 43 | width: 100%; 44 | } 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /Plugin/AbstractYotpoReviewsSummary.php: -------------------------------------------------------------------------------- 1 | _context = $context; 39 | $this->_yotpoConfig = $yotpoConfig; 40 | $this->_coreRegistry = $coreRegistry; 41 | } 42 | 43 | protected function _getCategoryBottomLineHtml(Product $product) 44 | { 45 | return '
'; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /etc/config.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | https://api.yotpo.com/ 7 | //staticw2.yotpo.com/ 8 | 9 | 10 | 1 11 | 1 12 | 1 13 | 1 14 | 1 15 | complete 16 | 17 | 18 | 50 19 | 20 | 21 | 22 | 23 | 24 | 1 25 | 26 | 27 | 1 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Helper/RichSnippets.php: -------------------------------------------------------------------------------- 1 | yotpoApi = $yotpoApi; 38 | $this->coreRegistry = $coreRegistry; 39 | } 40 | 41 | /** 42 | * @method getRichSnippet 43 | * @return array 44 | */ 45 | public function getRichSnippet() 46 | { 47 | return $this->yotpoApi->getRichSnippet($this->coreRegistry->registry('current_product')->getId()); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Plugin/Catalog/Block/Product/ListProduct.php: -------------------------------------------------------------------------------- 1 | _yotpoConfig->isEnabled()) { 32 | return $proceed($product, $templateType, $displayIfNoReviews); 33 | } 34 | 35 | if ($this->_yotpoConfig->isCategoryBottomlineEnabled()) { 36 | return $this->_getCategoryBottomLineHtml($product); 37 | } elseif (!$this->_yotpoConfig->isMdrEnabled()) { 38 | return $proceed($product, $templateType, $displayIfNoReviews); 39 | } else { 40 | return ''; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /etc/acl.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Model/Api/AccountPlatform.php: -------------------------------------------------------------------------------- 1 | oauthAuthentication($storeId))) { 21 | throw new \Exception(__("Please make sure the APP KEY and SECRET you've entered are correct")); 22 | } 23 | 24 | $result = $this->sendApiRequest(self::PATH . "/update_metadata", [ 25 | 'utoken' => $token, 26 | 'app_key' => $this->_yotpoConfig->getAppKey($storeId), 27 | 'metadata' => [ 28 | 'platform' => 'magento2', 29 | 'version' => "{$this->_yotpoConfig->getMagentoPlatformVersion()} {$this->_yotpoConfig->getMagentoPlatformEdition()}", 30 | 'plugin_version' => $this->_yotpoConfig->getModuleVersion(), 31 | ], 32 | ]); 33 | if ($result['status'] !== 200) { 34 | throw new \Exception(__("Request to API failed! " . json_encode($result))); 35 | } 36 | } catch (\Exception $e) { 37 | $this->_yotpoConfig->log("AccountPlatform::updateMetadata() - exception: " . $e->getMessage() . "\n" . $e->getTraceAsString(), "error", ['$storeId' => $storeId]); 38 | } 39 | return $result; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Model/Api/Purchases.php: -------------------------------------------------------------------------------- 1 | prepareOrderData() 14 | * @param int $storeId 15 | * @return mixed 16 | */ 17 | public function createOne(array $orderData, $storeId = null) 18 | { 19 | if (!($orderData['utoken'] = $this->oauthAuthentication($storeId))) { 20 | throw new \Exception(__("Please make sure the APP KEY and SECRET you've entered are correct")); 21 | } 22 | return $this->sendApiRequest("apps/" . $this->_yotpoConfig->getAppKey($storeId) . "/" . self::PATH, $orderData); 23 | } 24 | 25 | /** 26 | * @method massCreate 27 | * @param array $orders Array of orders prepared by $this->prepareOrderData() 28 | * @param mixed $storeId 29 | * @return mixed 30 | */ 31 | public function massCreate(array $orders, $storeId = null) 32 | { 33 | if (!($token = $this->oauthAuthentication($storeId))) { 34 | throw new \Exception(__("Please make sure the APP KEY and SECRET you've entered are correct")); 35 | } 36 | return $this->sendApiRequest( 37 | "apps/" . $this->_yotpoConfig->getAppKey($storeId) . "/" . self::PATH . "/mass_create", 38 | [ 39 | 'utoken' => $token, 40 | 'platform' => 'magento2', 41 | 'extension_version' => $this->_yotpoConfig->getModuleVersion(), 42 | 'orders' => $orders, 43 | ] 44 | ); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /etc/csp_whitelist.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | *.yotpo.com 7 | 8 | 9 | 10 | 11 | *.yotpo.com 12 | 13 | 14 | 15 | 16 | *.yotpo.com 17 | 18 | 19 | 20 | 21 | *.yotpo.com 22 | 23 | 24 | 25 | 26 | *.yotpo.com 27 | 28 | 29 | 30 | 31 | *.yotpo.com 32 | *.googleapis.com 33 | 34 | 35 | 36 | 37 | *.yotpo.com 38 | *.googleapis.com 39 | *.gstatic.com 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Console/Command/UpdateMetadataCommand.php: -------------------------------------------------------------------------------- 1 | objectManager = $objectManager; 28 | parent::__construct(); 29 | } 30 | 31 | /** 32 | * {@inheritdoc} 33 | */ 34 | protected function configure() 35 | { 36 | $this->setName('yotpo:update-metadata') 37 | ->setDescription('Manually send platform metadata to Yotpo'); 38 | parent::configure(); 39 | } 40 | 41 | /** 42 | * {@inheritdoc} 43 | */ 44 | protected function execute(InputInterface $input, OutputInterface $output) 45 | { 46 | try { 47 | $output->writeln('' . 'Working on it ...' . ''); 48 | $this->objectManager->get(\Yotpo\Yotpo\Model\Jobs\UpdateMetadata::class) 49 | ->setCrontabAreaCode() 50 | ->initConfig([ 51 | "output" => $output, 52 | ])->execute(); 53 | $output->writeln('' . 'Done :)' . ''); 54 | } catch (\Exception $e) { 55 | $output->writeln('' . $e->getMessage() . ''); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Plugin/Review/Block/Product/ReviewRenderer.php: -------------------------------------------------------------------------------- 1 | _yotpoConfig->isEnabled()) { 32 | return $proceed($product, $templateType, $displayIfNoReviews); 33 | } 34 | 35 | $currentProduct = $this->_coreRegistry->registry('current_product'); 36 | if (!$currentProduct || $currentProduct->getId() !== $product->getId()) { 37 | if ($this->_yotpoConfig->isCategoryBottomlineEnabled()) { 38 | return $this->_getCategoryBottomLineHtml($product); 39 | } elseif (!$this->_yotpoConfig->isMdrEnabled()) { 40 | return $proceed($product, $templateType, $displayIfNoReviews); 41 | } 42 | } 43 | 44 | return ''; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Block/Adminhtml/System/Config/ModuleVersion.php: -------------------------------------------------------------------------------- 1 | yotpoConfig = $yotpoConfig; 35 | parent::__construct($context, $data); 36 | } 37 | 38 | /** 39 | * Remove scope label 40 | * 41 | * @param AbstractElement $element 42 | * @return string 43 | */ 44 | public function render(AbstractElement $element) 45 | { 46 | $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue(); 47 | return parent::render($element); 48 | } 49 | 50 | /** 51 | * Return element html 52 | * 53 | * @param AbstractElement $element 54 | * @return string 55 | */ 56 | protected function _getElementHtml(AbstractElement $element) 57 | { 58 | return $this->_toHtml(); 59 | } 60 | 61 | /** 62 | * Generate collect button html 63 | * 64 | * @return string 65 | */ 66 | public function getModuleVersion() 67 | { 68 | return $this->yotpoConfig->getModuleVersion(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /view/adminhtml/templates/dashboard/yotpo_reviews_tab.phtml: -------------------------------------------------------------------------------- 1 | 6 | isAppKeyAndSecretSet()) : ?> 7 |
8 | getTotals()) > 0) : ?> 9 | 17 | 18 |
19 | escapeHtml(__("No Data Found")) ?> 20 |
21 | 22 |
23 |
getLounchYotpoButtonHtml('MagentoAdmin_Dashboard') ?>
24 | 25 |
26 |
27 | escapeHtml(__("Collect and leverage customer reviews, ratings, and Q&A")) ?>
28 | escapeHtml(__("with Yotpo's AI-powered tools and on-site widgets.")) ?> 29 |
30 |
getLounchYotpoButtonHtml('MagentoAdmin_Dashboard') ?>
31 |
32 | escapeHtml(__("Already have an account?")) ?> ">escapeHtml(__("Connect Yotpo")) ?> 33 |
34 |
35 | 36 | -------------------------------------------------------------------------------- /Observer/OrderSaveAfter.php: -------------------------------------------------------------------------------- 1 | yotpoConfig = $yotpoConfig; 32 | $this->orderStatusHistoryFactory = $orderStatusHistoryFactory; 33 | } 34 | 35 | /** 36 | * @param Observer $observer 37 | */ 38 | public function execute(Observer $observer) 39 | { 40 | try { 41 | $order = $observer->getEvent()->getOrder(); 42 | if ($order->getOrigData('status') !== $order->getData('status')) { 43 | $this->orderStatusHistoryFactory->create() 44 | ->setOrderId($order->getId()) 45 | ->setStoreId($order->getStoreId()) 46 | ->setOldStatus($order->getOrigData('status')) 47 | ->setNewStatus($order->getData('status')) 48 | ->setCreatedAt($this->yotpoConfig->getCurrentDate()) 49 | ->save(); 50 | } 51 | } catch (\Exception $e) { 52 | $this->yotpoConfig->log("OrderSaveAfter::execute() - Exception: " . $e->getMessage() . "\n" . $e->getTraceAsString(), "error"); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /etc/di.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Yotpo\Yotpo\Console\Command\SyncCommand 7 | Yotpo\Yotpo\Console\Command\ResetCommand 8 | Yotpo\Yotpo\Console\Command\UpdateMetadataCommand 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | yotpo_sync 25 | 26 | 27 | 28 | 29 | 30 | 31 | Magento\Framework\Filesystem\Driver\File 32 | 33 | 34 | 35 | 36 | yotpoLogger 37 | 38 | Yotpo\Yotpo\Model\Logger\YotpoHandler 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /Model/Api/AccountUsages.php: -------------------------------------------------------------------------------- 1 | _yotpoConfig->getAppKey($storeId)) && ($secret = $this->_yotpoConfig->getSecret($storeId))) { 25 | if (!in_array($appKey, $appKeys)) { 26 | $appKeys[] = $appKey; 27 | } 28 | if (!$token) { 29 | if (!($token = $this->oauthAuthentication($storeId))) { 30 | throw new \Exception(__("Please make sure the APP KEY and SECRET you've entered are correct")); 31 | } 32 | } 33 | } 34 | } 35 | if (!$appKeys) { 36 | return; 37 | } 38 | $appKey = array_shift($appKeys); 39 | 40 | $params = [ 41 | 'utoken' => $token, 42 | 'platform' => 'magento2', 43 | 'extension_version' => $this->_yotpoConfig->getModuleVersion(), 44 | ]; 45 | if ($appKeys) { 46 | $params['app_key'] = $appKeys; 47 | } 48 | if ($fromDate) { 49 | $params['since'] = $fromDate; 50 | } 51 | if ($toDate) { 52 | $params['until'] = $toDate; 53 | } 54 | 55 | $result = $this->sendApiRequest("apps/" . $appKey . "/" . self::PATH . "/metrics", $params, 'get', 60, null); 56 | if ($result['status'] == 200 && $result['body']->response) { 57 | return (array)$result['body']->response; 58 | } 59 | } catch (\Exception $e) { 60 | $this->_yotpoConfig->log("AccountUsages::getMetrics() - exception: " . $e->getMessage() . "\n" . $e->getTraceAsString(), "error"); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Magento 2 [Yotpo](https://www.yotpo.com/) Extension 2 | 3 | --- 4 | 5 | This library includes the files of the Yotpo Reviews extension. 6 | The directories hierarchy is as positioned in a standard magento 2 project library 7 | 8 | This library will also include different version packages as magento 2 extensions 9 | 10 | --- 11 | 12 | ## Requirements 13 | Magento 2.0+ (Up to module verion 2.4.5) 14 | 15 | Magento 2.1+ (Module version 2.7.5 up to 2.7.7) 16 | 17 | Magento 2.2+ (Module version 2.8.0 and above) 18 | 19 | ## ✓ Install via [composer](https://getcomposer.org/download/) (recommended) 20 | Run the following command under your Magento 2 root dir: 21 | 22 | ``` 23 | composer require yotpo/module-review 24 | php bin/magento maintenance:enable 25 | php bin/magento setup:upgrade 26 | php bin/magento setup:di:compile 27 | php bin/magento setup:static-content:deploy 28 | php bin/magento maintenance:disable 29 | php bin/magento cache:clean 30 | ``` 31 | 32 | ## Install manually under app/code 33 | 1. Download & place the contents of [Yotpo's Core Module](https://github.com/YotpoLtd/magento2-module-yotpo-core) under {YOUR-MAGENTO2-ROOT-DIR}/app/code/Yotpo/Core. 34 | 2. Download & place the contents of this repository under {YOUR-MAGENTO2-ROOT-DIR}/app/code/Yotpo/Yotpo 35 | 3. Run the following commands under your Magento 2 root dir: 36 | ``` 37 | php bin/magento maintenance:enable 38 | php bin/magento setup:upgrade 39 | php bin/magento setup:di:compile 40 | php bin/magento setup:static-content:deploy 41 | php bin/magento maintenance:disable 42 | php bin/magento cache:clean 43 | ``` 44 | 45 | ## Usage 46 | 47 | After the installation, Go to The Magento 2 admin panel 48 | 49 | Go to Stores -> Settings -> Configuration, change store view (not to be default config) and click on Yotpo Product Reviews Software on the left sidebar 50 | 51 | Insert Your account app key and secret 52 | 53 | ## Advanced 54 | 55 | To insert the widget manually on your product page add the following code in one of your product .phtml files 56 | 57 | ``` 58 | helper('Yotpo\Yotpo\Helper\Data')->showWidget($block) ?> 59 | ``` 60 | 61 | To insert the bottomline manually on your catalog page add the following code in Magento\Catalog\view\frontend\templates\product\list.phtml 62 | 63 | ``` 64 | helper('Yotpo\Yotpo\Helper\Data')->showBottomline($block, $_product) ?> 65 | ``` 66 | 67 | --- 68 | 69 | https://www.yotpo.com/ 70 | 71 | Copyright © 2018 Yotpo. All rights reserved. 72 | 73 | ![Yotpo Logo](https://yap.yotpo.com/assets/images/logo_login.png) 74 | -------------------------------------------------------------------------------- /Controller/Adminhtml/External/Reviews.php: -------------------------------------------------------------------------------- 1 | yotpoConfig = $yotpoConfig; 33 | } 34 | private function initialize() 35 | { 36 | if (($this->scopeId = $this->getRequest()->getParam("store", null))) { 37 | $this->scope = ScopeInterface::SCOPE_STORE; 38 | } elseif (($this->scopeId = $this->getRequest()->getParam("website", null))) { 39 | $this->scope = ScopeInterface::SCOPE_WEBSITE; 40 | } 41 | if (!$this->yotpoConfig->isActivated($this->scopeId, $this->scope)) { 42 | $this->scope = ScopeInterface::SCOPE_STORE; 43 | foreach ($this->yotpoConfig->getAllStoreIds(true) as $scopeId) { 44 | $this->scopeId = $scopeId; 45 | if ($this->yotpoConfig->isActivated($this->scopeId, $this->scope)) { 46 | $this->appKey = $this->yotpoConfig->getAppKey($this->scopeId, $this->scope); 47 | break; 48 | } 49 | } 50 | } else { 51 | $this->appKey = $this->yotpoConfig->getAppKey($this->scopeId, $this->scope); 52 | } 53 | } 54 | public function execute() 55 | { 56 | $this->initialize(); 57 | if ($this->appKey) { 58 | return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT) 59 | ->setUrl('https://yap.yotpo.com/?utm_source=MagentoAdmin_ReportingReviews#/moderation/reviews'); 60 | } else { 61 | return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT) 62 | ->setUrl('https://www.yotpo.com/integrations/magento/?utm_source=MagentoAdmin_ReportingReviews'); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Controller/Adminhtml/External/Analytics.php: -------------------------------------------------------------------------------- 1 | yotpoConfig = $yotpoConfig; 33 | } 34 | private function initialize() 35 | { 36 | if (($this->scopeId = $this->getRequest()->getParam("store", null))) { 37 | $this->scope = ScopeInterface::SCOPE_STORE; 38 | } elseif (($this->scopeId = $this->getRequest()->getParam("website", null))) { 39 | $this->scope = ScopeInterface::SCOPE_WEBSITE; 40 | } 41 | if (!$this->yotpoConfig->isActivated($this->scopeId, $this->scope)) { 42 | $this->scope = ScopeInterface::SCOPE_STORE; 43 | foreach ($this->yotpoConfig->getAllStoreIds(true) as $scopeId) { 44 | $this->scopeId = $scopeId; 45 | if ($this->yotpoConfig->isActivated($this->scopeId, $this->scope)) { 46 | $this->appKey = $this->yotpoConfig->getAppKey($this->scopeId, $this->scope); 47 | break; 48 | } 49 | } 50 | } else { 51 | $this->appKey = $this->yotpoConfig->getAppKey($this->scopeId, $this->scope); 52 | } 53 | } 54 | public function execute() 55 | { 56 | $this->initialize(); 57 | if ($this->appKey) { 58 | return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT) 59 | ->setUrl('https://yap.yotpo.com/?utm_source=MagentoAdmin_ReportingAnalytics#/tools/conversions_dashboard/engagement'); 60 | } else { 61 | return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT) 62 | ->setUrl('https://www.yotpo.com/integrations/magento/?utm_source=MagentoAdmin_ReportingAnalytics'); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Model/Jobs/UpdateMetadata.php: -------------------------------------------------------------------------------- 1 | yotpoApi = $yotpoApi; 39 | } 40 | 41 | public function execute() 42 | { 43 | try { 44 | foreach ($this->_yotpoConfig->getAllStoreIds(false) as $storeId) { 45 | try { 46 | $this->emulateFrontendArea($storeId); 47 | if (!$this->_yotpoConfig->isEnabled()) { 48 | $this->_processOutput("UpdateMetadata::execute() - Skipping store ID: {$storeId} (disabled)", "debug"); 49 | continue; 50 | } 51 | $this->_processOutput("UpdateMetadata::execute() - Updating metadata for store ID: {$storeId} ...", "debug"); 52 | $result = $this->yotpoApi->updateMetadata($storeId); 53 | $this->_processOutput("UpdateMetadata::execute() - Updating metadata for store ID: {$storeId} [SUCCESS]", "debug"); 54 | } catch (\Exception $e) { 55 | $this->_processOutput("UpdateMetadata::execute() - Exception on store ID: {$storeId} - " . $e->getMessage() . "\n" . $e->getTraceAsString(), "error"); 56 | } 57 | $this->stopEnvironmentEmulation(); 58 | } 59 | } catch (\Exception $e) { 60 | $this->_processOutput("UpdateMetadata::execute() - Exception: " . $e->getMessage() . "\n" . $e->getTraceAsString(), "error"); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Controller/Adminhtml/Report/Reviews.php: -------------------------------------------------------------------------------- 1 | resultPageFactory = $resultPageFactory; 45 | $this->yotpoConfig = $yotpoConfig; 46 | } 47 | 48 | private function initialize() 49 | { 50 | if (($storeId = $this->getRequest()->getParam(ScopeInterface::SCOPE_STORE, 0))) { 51 | $this->allStoreIds = [$storeId]; 52 | } elseif (($websiteId = $this->getRequest()->getParam(ScopeInterface::SCOPE_WEBSITE, 0))) { 53 | $this->allStoreIds = $this->yotpoConfig->getStoreManager()->getWebsite($websiteId)->getStoreIds(); 54 | } else { 55 | $this->allStoreIds = $this->yotpoConfig->getAllStoreIds(false); 56 | } 57 | $this->allStoreIds = $this->yotpoConfig->filterDisabledStoreIds($this->allStoreIds); 58 | $this->scopeId = ($this->allStoreIds) ? $this->allStoreIds[0] : 0; 59 | 60 | $this->isEnabled = ($this->allStoreIds) ? true : false; 61 | $this->isAppKeyAndSecretSet = ($this->allStoreIds) ? true : false; 62 | $this->appKey = ($this->scopeId) ? $this->yotpoConfig->getAppKey($this->scopeId, $this->scope) : null; 63 | } 64 | 65 | /** 66 | * Load the page defined in view/adminhtml/layout/yotpo_yotpo_report_reviews.xml 67 | * 68 | * @return \Magento\Framework\View\Result\Page 69 | */ 70 | public function execute() 71 | { 72 | $this->initialize(); 73 | $resultPage = $this->resultPageFactory->create(); 74 | $resultPage->getConfig()->getTitle()->set(__('Yotpo Reviews')); 75 | if (!($this->isEnabled && $this->isAppKeyAndSecretSet)) { 76 | $resultPage->getLayout()->unsetElement('store_switcher'); 77 | } 78 | return $resultPage; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /Console/Command/SyncCommand.php: -------------------------------------------------------------------------------- 1 | \Yotpo\Yotpo\Model\Jobs\OrdersSync::class, 29 | ]; 30 | 31 | /** 32 | * @var ObjectManagerInterface 33 | */ 34 | private $objectManager; 35 | 36 | /** 37 | * @method __construct 38 | * @param ObjectManagerInterface $objectManager 39 | */ 40 | public function __construct( 41 | ObjectManagerInterface $objectManager 42 | ) { 43 | $this->objectManager = $objectManager; 44 | parent::__construct(); 45 | } 46 | 47 | /** 48 | * {@inheritdoc} 49 | */ 50 | protected function configure() 51 | { 52 | $this->setName('yotpo:sync') 53 | ->setDescription('Sync Yotpo manually (reviews module)') 54 | ->setDefinition([ 55 | new InputOption( 56 | self::ENTITY, 57 | '-e', 58 | InputOption::VALUE_REQUIRED, 59 | 'Entity type (allowed options: orders)', 60 | 'orders' 61 | ), 62 | new InputOption( 63 | self::LIMIT, 64 | '-l', 65 | InputOption::VALUE_OPTIONAL, 66 | 'Max entity items to sync. WARNING: Setting a high sync limit (or no limit) may result in a high server load (0=no limit).', 67 | null 68 | ), 69 | ]); 70 | parent::configure(); 71 | } 72 | 73 | /** 74 | * {@inheritdoc} 75 | */ 76 | protected function execute(InputInterface $input, OutputInterface $output) 77 | { 78 | try { 79 | $output->writeln('' . 'Working on it ...' . ''); 80 | $this->objectManager->get($this->jobModelsMap[$input->getOption(self::ENTITY)]) 81 | ->setCrontabAreaCode() 82 | ->initConfig([ 83 | "output" => $output, 84 | "limit" => $input->getOption(self::LIMIT), 85 | ])->execute(); 86 | $output->writeln('' . 'Done :)' . ''); 87 | } catch (\Exception $e) { 88 | $output->writeln('' . $e->getMessage() . ''); 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /Model/Api/Products.php: -------------------------------------------------------------------------------- 1 | richsnippet = $richsnippet; 36 | } 37 | 38 | /** 39 | * @method getRichSnippet 40 | * @return array 41 | */ 42 | public function getRichSnippet($productId = null) 43 | { 44 | $rich_snippet_data = [ 45 | "average_score" => 0.0, 46 | "reviews_count" => 0 47 | ]; 48 | 49 | try { 50 | $storeId = $this->_yotpoConfig->getCurrentStoreId(); 51 | $snippet = $this->richsnippet->getSnippetByProductIdAndStoreId($productId, $storeId); 52 | 53 | if ($snippet && $snippet->isValid()) { 54 | $rich_snippet_data["average_score"] = $snippet->getAverageScore(); 55 | $rich_snippet_data["reviews_count"] = $snippet->getReviewsCount(); 56 | } else { 57 | //no snippet for product or snippet isn't valid anymore. get valid snippet code from yotpo api 58 | $res = $this->sendApiRequest(self::PATH . "/" . $this->_yotpoConfig->getAppKey() . '/' . $productId . "/bottomline/", [], "get", 2); 59 | 60 | if ($res["status"] == 200) { 61 | $rich_snippet_data["average_score"] = round($res["body"]->response->bottomline->average_score, 2); 62 | $rich_snippet_data["reviews_count"] = $res["body"]->response->bottomline->total_reviews; 63 | } 64 | 65 | if ($snippet == null) { 66 | $snippet = $this->richsnippet; 67 | $snippet->setProductId($productId); 68 | $snippet->setStoreId($storeId); 69 | } 70 | 71 | $snippet->setAverageScore($rich_snippet_data["average_score"]); 72 | $snippet->setReviewsCount($rich_snippet_data["reviews_count"]); 73 | $snippet->setExpirationTime(date('Y-m-d H:i:s', time() + self::TTL)); 74 | $snippet->save(); 75 | } 76 | } catch (\Exception $e) { 77 | $this->_yotpoConfig->log("Products::getRichSnippet() - exception: " . $e->getMessage() . "\n" . $e->getTraceAsString(), "error"); 78 | } 79 | 80 | return $rich_snippet_data; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Observer/Config/SingleStoreModeSwitch.php: -------------------------------------------------------------------------------- 1 | storeManager = $storeManager; 37 | $this->yotpoConfig = $yotpoConfig; 38 | } 39 | 40 | /** 41 | * Modify config if single store mode switched. 42 | * 43 | * @param Observer $observer 44 | */ 45 | public function execute(Observer $observer) 46 | { 47 | $changedPaths = (array)$observer->getEvent()->getChangedPaths(); 48 | if (!in_array(StoreManager::XML_PATH_SINGLE_STORE_MODE_ENABLED, $changedPaths)) { 49 | return; 50 | } 51 | 52 | if ($this->storeManager->isSingleStoreMode()) { 53 | $this->migrateToSingleStoreMode(); 54 | } else { 55 | $this->migrateFromSingleStoreMode(); 56 | } 57 | } 58 | 59 | /** 60 | * Use default store view config as default config. 61 | */ 62 | private function migrateToSingleStoreMode() 63 | { 64 | $defaultStoreView = $this->storeManager->getDefaultStoreView(); 65 | $this->moveConfigValues( 66 | ['scope' => ScopeInterface::SCOPE_STORES, 'id' => $defaultStoreView->getId()], 67 | ['scope' => ScopeConfigInterface::SCOPE_TYPE_DEFAULT, 'id' => 0] 68 | ); 69 | } 70 | 71 | /** 72 | * Use default config as default store view config. 73 | */ 74 | private function migrateFromSingleStoreMode() 75 | { 76 | $defaultStoreView = $this->storeManager->getDefaultStoreView(); 77 | $this->moveConfigValues( 78 | ['scope' => ScopeConfigInterface::SCOPE_TYPE_DEFAULT, 'id' => 0], 79 | ['scope' => ScopeInterface::SCOPE_STORES, 'id' => $defaultStoreView->getId()] 80 | ); 81 | } 82 | 83 | /** 84 | * Move Yotpo setup configuration from one scope to another. 85 | * 86 | * @param array $from 87 | * @param array $to 88 | */ 89 | private function moveConfigValues($from, $to) 90 | { 91 | $appKey = $this->yotpoConfig->getAppKey($from['id'], $from['scope']); 92 | $apiSecret = $this->yotpoConfig->getSecret($from['id'], $from['scope']); 93 | $enabled = $this->yotpoConfig->isEnabled($from['id'], $from['scope']); 94 | if ($appKey && $apiSecret) { 95 | $this->yotpoConfig->setStoreCredentialsAndIsEnabled($appKey, $apiSecret, $enabled ? '1' : '0', $to['id'], $to['scope']); 96 | } else { 97 | $this->yotpoConfig->resetStoreCredentials($to['id'], $to['scope']); 98 | } 99 | 100 | $this->yotpoConfig->resetStoreCredentials($from['id'], $from['scope']); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /Block/Adminhtml/System/Config/LaunchYotpoButton.php: -------------------------------------------------------------------------------- 1 | yotpoConfig = $yotpoConfig; 49 | $this->_request = $request; 50 | $this->_websiteId = $request->getParam('website'); 51 | $this->_storeId = $this->getRequest()->getParam('store'); 52 | } 53 | 54 | /** 55 | * Remove scope label 56 | * 57 | * @param AbstractElement $element 58 | * @return string 59 | */ 60 | public function render(AbstractElement $element) 61 | { 62 | $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue(); 63 | return parent::render($element); 64 | } 65 | 66 | /** 67 | * Return element html 68 | * 69 | * @param AbstractElement $element 70 | * @return string 71 | */ 72 | protected function _getElementHtml(AbstractElement $element) 73 | { 74 | return $this->_toHtml(); 75 | } 76 | 77 | public function getAppKey() 78 | { 79 | if ($this->_storeId !== null) { 80 | return $this->yotpoConfig->getAppKey($this->_storeId, ScopeInterface::SCOPE_STORE); 81 | } elseif ($this->_websiteId !== null) { 82 | return $this->yotpoConfig->getAppKey($this->_websiteId, ScopeInterface::SCOPE_WEBSITE); 83 | } else { 84 | return $this->yotpoConfig->getAppKey(); 85 | } 86 | } 87 | 88 | /** 89 | * Generate yotpo button html 90 | * 91 | * @return string 92 | */ 93 | public function getButtonHtml() 94 | { 95 | $button = $this->getLayout()->createBlock( 96 | \Magento\Backend\Block\Widget\Button::class 97 | )->setData( 98 | [ 99 | 'id' => 'launch_yotpo_button', 100 | 'class' => 'launch-yotpo-button yotpo-cta-add-arrow', 101 | 'label' => __('Launch Yotpo'), 102 | ] 103 | ); 104 | if (!($appKey = $this->getAppKey())) { 105 | $button->setDisabled(true); 106 | } else { 107 | $button->setOnClick("window.open('https://yap.yotpo.com/#/preferredAppKey={$appKey}','_blank');"); 108 | } 109 | 110 | return $button->toHtml(); 111 | } 112 | 113 | public function isStoreScope() 114 | { 115 | return $this->getRequest()->getParam('store') || $this->yotpoConfig->isSingleStoreMode(); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /Block/Conversion.php: -------------------------------------------------------------------------------- 1 | yotpoConfig = $yotpoConfig; 42 | $this->checkoutSession = $checkoutSession; 43 | $this->orderRepository = $orderRepository; 44 | parent::__construct($context, $data); 45 | } 46 | 47 | /** 48 | * @method isEnabled 49 | * @return boolean 50 | */ 51 | public function isEnabled() 52 | { 53 | return $this->yotpoConfig->isEnabled() && $this->yotpoConfig->isAppKeyAndSecretSet(); 54 | } 55 | 56 | public function getOrderId() 57 | { 58 | return $this->checkoutSession->getLastOrderId(); 59 | } 60 | 61 | public function getOrder() 62 | { 63 | if (!$this->hasData('order') && $this->getOrderId()) { 64 | $this->setData('order', $this->orderRepository->get($this->getOrderId())); 65 | } 66 | return $this->getData('order'); 67 | } 68 | 69 | public function hasOrder() 70 | { 71 | return $this->getOrder() && $this->getOrder()->getId(); 72 | } 73 | 74 | public function getOrderAmount() 75 | { 76 | if (!$this->hasOrder()) { 77 | return null; 78 | } 79 | return $this->getOrder()->getSubtotal(); 80 | } 81 | 82 | public function getOrderCurrency() 83 | { 84 | if (!$this->hasOrder()) { 85 | return null; 86 | } 87 | return $this->getOrder()->getOrderCurrencyCode(); 88 | } 89 | 90 | /** 91 | * @method getJsonData 92 | * @return string|null 93 | */ 94 | public function getJsonData() 95 | { 96 | if (!($this->hasOrder() && $this->yotpoConfig->getAppKey())) { 97 | return null; 98 | } 99 | return json_encode( 100 | [ 101 | "orderId" => $this->getOrder()->getIncrementId(), 102 | "orderAmount" => $this->getOrderAmount(), 103 | "orderCurrency" => $this->getOrderCurrency(), 104 | ] 105 | ); 106 | } 107 | 108 | /** 109 | * @method getNoscriptSrc 110 | * @return string|null 111 | */ 112 | public function getNoscriptSrc() 113 | { 114 | if (!($this->hasOrder() && $this->yotpoConfig->getAppKey())) { 115 | return null; 116 | } 117 | return $this->yotpoConfig->getYotpoNoSchemaApiUrl( 118 | "conversion_tracking.gif?" . http_build_query( 119 | [ 120 | "app_key" => $this->yotpoConfig->getAppKey(), 121 | "order_id" => $this->getOrderId(), 122 | "order_amount" => $this->getOrderAmount(), 123 | "order_currency" => $this->getOrderCurrency(), 124 | ] 125 | ) 126 | ); 127 | } 128 | 129 | /** 130 | * @return string 131 | */ 132 | public function getYotpoWidgetUrl() { 133 | return $this->yotpoConfig->getYotpoWidgetUrl(); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /Console/Command/ResetCommand.php: -------------------------------------------------------------------------------- 1 | Reset Yotpo sync flags? (y/n)[n]\n"; 19 | const RESET_CONFIG_CONFIRM_MESSAGE = "Reset Yotpo configurations (reset to default)? (y/n)[n]\n"; 20 | 21 | /**#@+ 22 | * Keys and shortcuts for input arguments and options 23 | */ 24 | const ENTITY = 'entity'; 25 | /**#@- */ 26 | 27 | /** 28 | * @param ObjectManagerInterface 29 | */ 30 | private $objectManager; 31 | 32 | /** 33 | * @param ResourceConnection 34 | */ 35 | private $resourceConnection; 36 | 37 | /** 38 | * @method __construct 39 | * @param ObjectManagerInterface $objectManager 40 | * @param ResourceConnection $resourceConnection 41 | */ 42 | public function __construct( 43 | ObjectManagerInterface $objectManager, 44 | ResourceConnection $resourceConnection 45 | ) { 46 | $this->objectManager = $objectManager; 47 | $this->resourceConnection = $resourceConnection; 48 | parent::__construct(); 49 | } 50 | 51 | /** 52 | * {@inheritdoc} 53 | */ 54 | protected function configure() 55 | { 56 | $this->setName('yotpo:reset') 57 | ->setDescription('Reset Yotpo sync flags &/or configurations') 58 | ->setDefinition([ 59 | new InputOption( 60 | self::ENTITY, 61 | '-e', 62 | InputOption::VALUE_OPTIONAL, 63 | 'Entity type (orders)', 64 | 'orders' 65 | ) 66 | ]); 67 | parent::configure(); 68 | } 69 | 70 | /** 71 | * {@inheritdoc} 72 | */ 73 | protected function execute(InputInterface $input, OutputInterface $output) 74 | { 75 | try { 76 | if ($this->confirmQuestion(self::RESET_FLAGS_CONFIRM_MESSAGE, $input, $output)) { 77 | $output->writeln('' . 'Resetting Yotpo sync flags ...' . ''); 78 | $this->objectManager->get(\Yotpo\Yotpo\Model\Jobs\ResetSyncFlags::class) 79 | ->setCrontabAreaCode() 80 | ->initConfig([ 81 | "output" => $output 82 | ])->execute($input->getOption(self::ENTITY)); 83 | } 84 | if ($this->confirmQuestion(self::RESET_CONFIG_CONFIRM_MESSAGE, $input, $output)) { 85 | $output->writeln('' . 'Resetting Yotpo configurations ...' . ''); 86 | $this->resetConfig(); 87 | } 88 | $output->writeln('' . 'Done :)' . ''); 89 | } catch (\Exception $e) { 90 | $output->writeln('' . $e->getMessage() . ''); 91 | } 92 | } 93 | 94 | /** 95 | * @method confirmQuestion 96 | * @param string $message 97 | * @param InputInterface $input 98 | * @param OutputInterface $output 99 | * @return bool 100 | */ 101 | private function confirmQuestion(string $message, InputInterface $input, OutputInterface $output) 102 | { 103 | $confirmationQuestion = new ConfirmationQuestion($message, false); 104 | return (bool)$this->getHelper('question')->ask($input, $output, $confirmationQuestion); 105 | } 106 | 107 | private function resetConfig() 108 | { 109 | $this->resourceConnection->getConnection()->delete( 110 | $this->resourceConnection->getTableName('core_config_data'), 111 | "path LIKE '" . \Yotpo\Yotpo\Model\Config::XML_PATH_YOTPO_ALL . "/%'" 112 | ); 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /Lib/Http/Client/Curl.php: -------------------------------------------------------------------------------- 1 | _ch = curl_init(); 19 | 20 | $this->curlOption(CURLOPT_URL, $uri); 21 | if ($method === 'POST') { 22 | $this->curlOption(CURLOPT_POST, 1); 23 | $this->setPostParams($params); 24 | } elseif ($method === 'GET') { 25 | $this->curlOption(CURLOPT_HTTPGET, 1); 26 | } else { 27 | $this->curlOption(CURLOPT_CUSTOMREQUEST, $method); 28 | } 29 | 30 | if (count($this->_headers)) { 31 | $heads = []; 32 | foreach ($this->_headers as $k => $v) { 33 | $heads[] = $k . ': ' . $v; 34 | } 35 | $this->curlOption(CURLOPT_HTTPHEADER, $heads); 36 | } 37 | 38 | if (count($this->_cookies)) { 39 | $cookies = []; 40 | foreach ($this->_cookies as $k => $v) { 41 | $cookies[] = "{$k}={$v}"; 42 | } 43 | $this->curlOption(CURLOPT_COOKIE, implode(";", $cookies)); 44 | } 45 | 46 | if ($this->_timeout) { 47 | $this->curlOption(CURLOPT_TIMEOUT, $this->_timeout); 48 | } 49 | 50 | if ($this->_port != 80) { 51 | $this->curlOption(CURLOPT_PORT, $this->_port); 52 | } 53 | 54 | $this->curlOption(CURLOPT_RETURNTRANSFER, 1); 55 | $this->curlOption(CURLOPT_HEADERFUNCTION, [$this, 'parseHeaders']); 56 | 57 | if (count($this->_curlUserOptions)) { 58 | foreach ($this->_curlUserOptions as $k => $v) { 59 | $this->curlOption($k, $v); 60 | } 61 | } 62 | 63 | $this->_headerCount = 0; 64 | $this->_responseHeaders = []; 65 | $this->_responseBody = curl_exec($this->_ch); 66 | $err = curl_errno($this->_ch); 67 | if ($err) { 68 | $this->doError(curl_error($this->_ch)); 69 | } 70 | 71 | curl_close($this->_ch); 72 | } 73 | 74 | /** 75 | * Make GET request 76 | * 77 | * @param string $uri uri relative to host, ex. "/index.php" 78 | * @param array $params 79 | * @return void 80 | */ 81 | public function get($uri, array $params = []) 82 | { 83 | if ($params) { 84 | $uri .= ((parse_url($uri, PHP_URL_QUERY)) ? "&" : "?") . \preg_replace('/%5B([0-9]+)?%5D=/', '[]=', \http_build_query($params)); 85 | } 86 | $this->makeRequest("GET", $uri); 87 | } 88 | 89 | /** 90 | * Prepare and set post params. 91 | * 92 | * @param array $params 93 | * 94 | * @return void 95 | */ 96 | protected function setPostParams(array $params) 97 | { 98 | $contentType = null; 99 | if (!empty($this->_headers['Content-Type'])) { 100 | $contentType = $this->_headers['Content-Type']; 101 | } 102 | 103 | switch ($contentType) { 104 | case 'application/json': 105 | $params = json_encode($params); 106 | $this->curlOption(CURLOPT_POSTFIELDS, $params); 107 | $this->_headers['Content-Length'] = strlen($params); 108 | break; 109 | default: 110 | $this->curlOption(CURLOPT_POSTFIELDS, http_build_query($params)); 111 | } 112 | } 113 | 114 | /** 115 | * Reset class to initial values 116 | * @return $this 117 | */ 118 | public function reset() 119 | { 120 | $this->_host = 'localhost'; 121 | $this->_port = 80; 122 | $this->_sock = null; 123 | $this->_headers = []; 124 | $this->_postFields = []; 125 | $this->_cookies = []; 126 | $this->_responseHeaders = []; 127 | $this->_responseBody = ''; 128 | $this->_responseStatus = 0; 129 | $this->_timeout = 45; 130 | $this->_redirectCount = 0; 131 | $this->_ch = null; 132 | $this->_curlUserOptions = []; 133 | $this->_headerCount = 0; 134 | return $this; 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /Block/Yotpo.php: -------------------------------------------------------------------------------- 1 | yotpoConfig = $yotpoConfig; 42 | $this->coreRegistry = $coreRegistry; 43 | $this->catalogImageHelper = $catalogImageHelper; 44 | parent::__construct($context, $data); 45 | } 46 | 47 | /** 48 | * @method isEnabled 49 | * @return boolean 50 | */ 51 | public function isEnabled() 52 | { 53 | return $this->yotpoConfig->isEnabled() && $this->yotpoConfig->isAppKeyAndSecretSet(); 54 | } 55 | 56 | /** 57 | * @method getAppKey 58 | * @return string|null 59 | */ 60 | public function getAppKey() 61 | { 62 | return $this->yotpoConfig->getAppKey(); 63 | } 64 | 65 | public function getProduct() 66 | { 67 | if (is_null($this->getData('product'))) { 68 | $this->setData('product', $this->coreRegistry->registry('current_product')); 69 | } 70 | return $this->getData('product'); 71 | } 72 | 73 | public function hasProduct() 74 | { 75 | return $this->getProduct() && $this->getProduct()->getId(); 76 | } 77 | 78 | public function getProductId() 79 | { 80 | if (!$this->hasProduct()) { 81 | return null; 82 | } 83 | return $this->getProduct()->getId(); 84 | } 85 | 86 | public function getProductName() 87 | { 88 | if (!$this->hasProduct()) { 89 | return null; 90 | } 91 | return $this->escapeString($this->getProduct()->getName()); 92 | } 93 | 94 | public function getProductDescription() 95 | { 96 | if (!$this->hasProduct()) { 97 | return null; 98 | } 99 | return $this->escapeString($this->getProduct()->getShortDescription()); 100 | } 101 | 102 | public function getProductUrl() 103 | { 104 | if (!$this->hasProduct()) { 105 | return null; 106 | } 107 | return $this->getProduct()->getProductUrl(); 108 | } 109 | 110 | public function getProductFinalPrice() 111 | { 112 | if (!$this->hasProduct()) { 113 | return null; 114 | } 115 | return $this->getProduct()->getFinalPrice(); 116 | } 117 | 118 | /** 119 | * @method getProductImageUrl 120 | * @param string $imageId 121 | * @return string|null 122 | */ 123 | public function getProductImageUrl($imageId = 'product_page_image_large') 124 | { 125 | if (!$this->hasProduct()) { 126 | return null; 127 | } 128 | return $this->catalogImageHelper->init($this->getProduct(), $imageId)->getUrl(); 129 | } 130 | 131 | public function getCurrentCurrencyCode() 132 | { 133 | return $this->yotpoConfig->getStoreManager()->getStore()->getCurrentCurrency()->getCode(); 134 | } 135 | 136 | public function isRenderWidget() 137 | { 138 | return $this->hasProduct() && ($this->yotpoConfig->isWidgetEnabled() || $this->getData('fromHelper')); 139 | } 140 | 141 | public function isRenderBottomline() 142 | { 143 | return $this->hasProduct() && ($this->yotpoConfig->isBottomlineEnabled() || $this->getData('fromHelper')); 144 | } 145 | 146 | public function isRenderBottomlineQna() 147 | { 148 | return $this->hasProduct() && $this->yotpoConfig->isBottomlineQnaEnabled(); 149 | } 150 | 151 | public function escapeString($str) 152 | { 153 | return $this->_escaper->escapeHtml(strip_tags($str)); 154 | } 155 | 156 | public function getYotpoWidgetUrl() 157 | { 158 | return $this->yotpoConfig->getYotpoWidgetUrl(); 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /Observer/Config/Save.php: -------------------------------------------------------------------------------- 1 | cacheTypeList = $cacheTypeList; 53 | $this->appConfig = $config; 54 | $this->yotpoConfig = $yotpoConfig; 55 | $this->yotpoApi = $yotpoApi; 56 | } 57 | 58 | /** 59 | * @param Observer $observer 60 | */ 61 | public function execute(Observer $observer) 62 | { 63 | $changedPaths = (array)$observer->getEvent()->getChangedPaths(); 64 | if ($changedPaths) { 65 | $this->cacheTypeList->cleanType(Config::TYPE_IDENTIFIER); 66 | $this->appConfig->reinit(); 67 | 68 | $scope = $scopes = \Magento\Framework\App\Config\ScopeConfigInterface::SCOPE_TYPE_DEFAULT; 69 | if (($scopeId = $observer->getEvent()->getStore())) { 70 | $scope = ScopeInterface::SCOPE_STORE; 71 | $scopes = ScopeInterface::SCOPE_STORES; 72 | } elseif (($scopeId = $observer->getEvent()->getWebsite())) { 73 | $scope = ScopeInterface::SCOPE_WEBSITE; 74 | $scopes = ScopeInterface::SCOPE_WEBSITES; 75 | } else { 76 | $scopeId = 0; 77 | } 78 | 79 | $appKey = $this->yotpoConfig->getAppKey($scopeId, $scope); 80 | 81 | if (in_array(YotpoConfig::XML_PATH_YOTPO_DEBUG_MODE_ENABLED, $changedPaths)) { 82 | $this->yotpoConfig->log( 83 | "Yotpo Debug mode " . (($this->yotpoConfig->isDebugMode($scopeId, $scope)) ? 'started' : 'stopped'), 84 | "info", 85 | ['$app_key' => $appKey, '$scope' => ($scope ?: 'default'), '$scopeId' => $scopeId] 86 | ); 87 | } 88 | 89 | if ($scope !== ScopeInterface::SCOPE_STORE && !$this->yotpoConfig->isSingleStoreMode()) { 90 | $this->resetStoreCredentials($scopeId, $scopes); 91 | return true; 92 | } 93 | 94 | //Check if appKey is unique: 95 | if ($appKey) { 96 | foreach ($this->yotpoConfig->getAllStoreIds() as $key => $storeId) { 97 | if (($scopeId && $storeId !== $scopeId) && $this->yotpoConfig->getAppKey($storeId) === $appKey) { 98 | $this->resetStoreCredentials($scopeId, $scopes); 99 | throw new \Exception(__("The APP KEY you've entered is already in use by another store on this system. Note that Yotpo requires a unique set of APP KEY & SECRET for each store.")); 100 | } 101 | } 102 | } 103 | 104 | if ($this->yotpoConfig->isEnabled($scopeId, $scope) && !($this->yotpoApi->oauthAuthentication($scopeId, $scope))) { 105 | $this->resetStoreCredentials($scopeId, $scopes); 106 | throw new \Exception(__("Please make sure the APP KEY and SECRET you've entered are correct")); 107 | } 108 | } 109 | } 110 | 111 | /** 112 | * @method resetStoreCredentials 113 | * @param int|null $scopeId 114 | * @param string|null $scopes 115 | */ 116 | private function resetStoreCredentials($scopeId = null, $scopes = ScopeInterface::SCOPE_STORES) 117 | { 118 | $this->yotpoConfig->resetStoreCredentials($scopeId, $scopes); 119 | $this->cacheTypeList->cleanType(Config::TYPE_IDENTIFIER); 120 | $this->appConfig->reinit(); 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /Setup/UpgradeData.php: -------------------------------------------------------------------------------- 1 | yotpoConfig = $yotpoConfig; 49 | $this->notifierPool = $notifierPool; 50 | $this->output = $output; 51 | } 52 | 53 | /** 54 | * {@inheritdoc} 55 | */ 56 | public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) 57 | { 58 | $setup->startSetup(); 59 | 60 | if ($context->getVersion() && version_compare($context->getVersion(), '2.9.0', '<')) { 61 | $this->output->writeln("Reseting configurations for 'default' & 'website' scopes (only supports 'store' at the moment)"); 62 | 63 | $appKeysStores = []; 64 | 65 | //Move all configurations to the 'store' scope. 66 | foreach ($this->yotpoConfig->getAllStoreIds(false, false) as $key => $storeId) { 67 | $isEnabled = $this->yotpoConfig->isEnabled($storeId, ScopeInterface::SCOPE_STORE); 68 | $appKey = $this->yotpoConfig->getAppKey($storeId, ScopeInterface::SCOPE_STORE); 69 | $secret = $this->yotpoConfig->getSecret($storeId, ScopeInterface::SCOPE_STORE); 70 | 71 | if (!$appKey || !$secret) { 72 | $this->yotpoConfig->resetStoreCredentials($storeId); 73 | continue; 74 | } 75 | if (!isset($appKeysStores[$appKey])) { 76 | $appKeysStores[$appKey] = []; 77 | $this->yotpoConfig->setStoreCredentialsAndIsEnabled($appKey, $secret, $isEnabled, $storeId); 78 | } 79 | $appKeysStores[$appKey][] = $storeId; 80 | } 81 | 82 | // Clear config values for the 'default' & 'website' scopes 83 | $setup->getConnection()->delete( 84 | $setup->getTable('core_config_data'), 85 | "path IN ('" . implode("','", [YotpoConfig::XML_PATH_YOTPO_APP_KEY, YotpoConfig::XML_PATH_YOTPO_SECRET, YotpoConfig::XML_PATH_YOTPO_ENABLED]) . "') AND scope != '" . ScopeInterface::SCOPE_STORES . "'" 86 | ); 87 | 88 | //Remove appKey duplications 89 | $resetStores = []; 90 | foreach ($appKeysStores as $_appkey => $stores) { 91 | if (count($stores) > 1) { 92 | foreach ($stores as $storeId) { 93 | $this->yotpoConfig->resetStoreCredentials($storeId); 94 | $resetStores[] = $storeId; 95 | } 96 | } 97 | } 98 | $resetStoresMsg = ''; 99 | if ($resetStores) { 100 | $resetStoresMsg = ' *Note that Yotpo requires unique set of credentials for each store. As we have detected duplicate or invalid credentials, your Yotpo credentials have been reset for the following stores: ' . implode(",", $resetStores) . '. Copy and paste the Yotpo credentials of the aforementioned store(s) within the relevant Store View scope settings.'; 101 | $this->output->writeln("' . $resetStoresMsg . '"); 102 | } 103 | 104 | if ($context->getVersion()) { 105 | $this->addAdminNotification("Important message from Yotpo regarding the configuration scopes & multi-store support... (module: Yotpo_Yotpo)", "Note that Yotpo can only be connected and enabled/disabled via the Store View scope. As part of the latest module upgrade, your currently defined values were saved to your default store scope, and your default and website scope configurations were reset. \n Please verify that your Yotpo credentials are correct and connected to the right stores" . $resetStoresMsg); 106 | } 107 | } 108 | 109 | $setup->endSetup(); 110 | } 111 | 112 | private function addAdminNotification(string $title, $description = "", $type = 'critical') 113 | { 114 | $method = 'add' . ucfirst($type); 115 | $this->notifierPool->{$method}($title, $description); 116 | return $this; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /view/adminhtml/templates/report/reviews.phtml: -------------------------------------------------------------------------------- 1 | 6 | isEnabled() && $block->isAppKeyAndSecretSet()) : 7 | $periods = $block->getPeriods(); ?> 8 |
9 |
10 |
11 | 17 | 18 | getPeriod('30d')] ?> 19 | 20 | 21 |
    22 | $_label) : ?> 23 |
  • 24 | 27 | 28 | 29 |
  • 30 | 31 |
32 |
33 |
34 | escapeHtml(__("Yotpo at a glance")) ?> 35 |
36 |
37 | escapeHtml(__("User-generated content metrics gathered from your Yotpo dashboards.")) ?> 38 |
39 | getTotals()) > 0) : ?> 40 | 49 | 50 |
51 | escapeHtml(__("No Data Found")) ?> 52 |
53 | 54 |
55 |
getLounchYotpoButtonHtml() ?>
56 |
57 | ">escapeHtml(__("Yotpo Settings")) ?> 58 |
59 |
60 | 70 | 71 |
72 |
73 |

on happy customers") ?>

74 |

Connect your Yotpo account to your store to accelerate growth
with a full suite of solutions for customer reviews and visual marketing.") ?>

75 |
getLounchYotpoButtonHtml('MagentoAdmin_reviews') ?>
76 | 79 |
80 |
81 |
82 |

83 | ' alt=""> 84 |

85 |
86 |
87 |

88 | ' alt=""> 89 |

90 |
91 |
92 |

93 | ' alt=""> 94 |

95 |
96 |
97 |
98 | 103 | 104 | -------------------------------------------------------------------------------- /i18n/en_US.csv: -------------------------------------------------------------------------------- 1 | "Emails Sent","Emails Sent" 2 | "Avg. Star Rating","Avg. Star Rating" 3 | "Collected Reviews","Collected Reviews" 4 | "Collected Photos","Collected Photos" 5 | "Published Reviews","Published Reviews" 6 | "Engagement Rate","Engagement Rate" 7 | "Get Started","Get Started" 8 | "Launch Yotpo","Launch Yotpo" 9 | "Yotpo Reviews","Yotpo Reviews" 10 | "Please make sure the APP KEY and SECRET you've entered are correct","Please make sure the APP KEY and SECRET you've entered are correct" 11 | """Request to API failed! "" .","""Request to API failed! "" ." 12 | "The APP KEY you've entered is already in use by another store on this system. Note that Yotpo requires a unique set of APP KEY & SECRET for each store.","The APP KEY you've entered is already in use by another store on this system. Note that Yotpo requires a unique set of APP KEY & SECRET for each store." 13 | "No Data Found","No Data Found" 14 | "Collect and leverage customer reviews, ratings, and Q&A
with Yotpo's AI-powered tools and on-site widgets.","Collect and leverage customer reviews, ratings, and Q&A
with Yotpo's AI-powered tools and on-site widgets." 15 | "Already have an account?","Already have an account?" 16 | "Connect Yotpo","Connect Yotpo" 17 | "Time Period","Time Period" 18 | "Yotpo at a glance","Yotpo at a glance" 19 | "User-generated content metrics gathered from your Yotpo dashboards.","User-generated content metrics gathered from your Yotpo dashboards." 20 | "Yotpo Settings","Yotpo Settings" 21 | "Great brands are built
on happy customers","Great brands are built
on happy customers" 22 | "Yotpo is already installed in your Magento store!
Connect your Yotpo account to your store to accelerate growth
with a full suite of solutions for customer reviews and visual marketing.","Yotpo is already installed in your Magento store!
Connect your Yotpo account to your store to accelerate growth
with a full suite of solutions for customer reviews and visual marketing." 23 | "Reviews & Ratings","Reviews & Ratings" 24 | "Turn customer content into sales by collecting and leveraging reviews, ratings, and Q&A with Yotpo’s AI-powered solutions.","Turn customer content into sales by collecting and leveraging reviews, ratings, and Q&A with Yotpo’s AI-powered solutions." 25 | "Visual Marketing","Visual Marketing" 26 | "Collect, curate, and showcase customer photos and videos in fully customizable shoppable galleries across your site.","Collect, curate, and showcase customer photos and videos in fully customizable shoppable galleries across your site." 27 | "Consumer Insights","Consumer Insights" 28 | "Understand what customers are saying about your brand and products and make data-driven business decisions with actionable insights.","Understand what customers are saying about your brand and products and make data-driven business decisions with actionable insights." 29 | "Yotpo can only be connected, enabled, or disabled via the Store View menu.","Yotpo can only be connected, enabled, or disabled via the Store View menu." 30 | "To connect your App Key and API secret, first select the relevant Store View.","To connect your App Key and API secret, first select the relevant Store View." 31 | "Need help?","Need help?" 32 | "Setup Guide","Setup Guide" 33 | "Sync progress: %1","Sync progress: %1" 34 | "Last sync date: %1","Last sync date: %1" 35 | "Total orders synced with Yotpo: %1","Total orders synced with Yotpo: %1" 36 | Yotpo,Yotpo 37 | "Product Reviews Settings","Product Reviews Settings" 38 | "Yotpo Analytics","Yotpo Analytics" 39 | "Reviews and Visual Marketing","Reviews and Visual Marketing" 40 | Setup,Setup 41 | "Enable Yotpo","Enable Yotpo" 42 | "To connect Yotpo to your store, enter your App Key and API Secret in the fields below and save your configuration.","To connect Yotpo to your store, enter your App Key and API Secret in the fields below and save your configuration." 43 | "App Key","App Key" 44 | "Note: Additional stores must be connected to their own App Key via Store View settings.","Note: Additional stores must be connected to their own App Key via Store View settings." 45 | "API Secret","API Secret" 46 | "I can't find my API Secret","I can't find my API Secret" 47 | "Module Version","Module Version" 48 | "Widget Settings","Widget Settings" 49 | "Show Reviews Widget","Show Reviews Widget" 50 | "Show star rating on category pages","Show star rating on category pages" 51 | "Show star rating on product pages","Show star rating on product pages" 52 | "Show Q&A Bottom-line","Show Q&A Bottom-line" 53 | "Hide Magento Reviews","Hide Magento Reviews" 54 | "Enable Debug Mode","Enable Debug Mode" 55 | "Enable in order to log all Yotpo processes when Magento debug mode enabled.","Enable in order to log all Yotpo processes when Magento debug mode enabled." 56 | "Sync Settings","Sync Settings" 57 | "Sync Status","Sync Status" 58 | "Orders Sync From Date","Orders Sync From Date" 59 | "Orders Sync Limit","Orders Sync Limit" 60 | "Note: Setting a high sync limit (or no limit) may result in a high server load (0=no limit).","Note: Setting a high sync limit (or no limit) may result in a high server load (0=no limit)." 61 | "Orders Sync Statuses","Orders Sync Statuses" 62 | "Customize the order status that will trigger the order export after purchase. You can choose multiple statuses by holding ctrl button.","Customize the order status that will trigger the order export after purchase. You can choose multiple statuses by holding ctrl button." 63 | -------------------------------------------------------------------------------- /Model/AbstractApi.php: -------------------------------------------------------------------------------- 1 | curl = $curl; 55 | $this->productFactory = $productFactory; 56 | $this->_yotpoConfig = $yotpoConfig; 57 | } 58 | 59 | /** 60 | * @param bool $refresh 61 | * @return int 62 | */ 63 | protected function _getCurlStatus($refresh = false) 64 | { 65 | if ($this->status === null || $refresh) { 66 | $this->status = $this->curl->getStatus(); 67 | } 68 | 69 | return $this->status; 70 | } 71 | 72 | /** 73 | * @param bool $refresh 74 | * @return array 75 | */ 76 | protected function _getCurlHeaders($refresh = false) 77 | { 78 | if ($this->headers === null || $refresh) { 79 | $this->headers = $this->curl->getHeaders(); 80 | } 81 | 82 | return $this->headers; 83 | } 84 | 85 | /** 86 | * @param bool $refresh 87 | * @return array 88 | */ 89 | protected function _getCurlBody($refresh = false) 90 | { 91 | if ($this->body === null || $refresh) { 92 | $this->body = json_decode($this->curl->getBody()); 93 | } 94 | 95 | return $this->body; 96 | } 97 | 98 | /** 99 | * @return $this 100 | */ 101 | protected function _clearResponseData() 102 | { 103 | $this->body = $this->status = $this->headers = null; 104 | return $this; 105 | } 106 | 107 | /** 108 | * @return array 109 | */ 110 | protected function _prepareCurlResponseData() 111 | { 112 | $responseData = [ 113 | 'status' => $this->_getCurlStatus(), 114 | 'headers' => $this->_getCurlHeaders(), 115 | 'body' => $this->_getCurlBody(), 116 | ]; 117 | return $responseData; 118 | } 119 | 120 | /** 121 | * @method sendApiRequest 122 | * @param string $path 123 | * @param array $data 124 | * @param string $method 125 | * @param int $timeout 126 | * @param string $contentType 127 | * @return mixed 128 | */ 129 | public function sendApiRequest($path, array $data, $method = "post", $timeout = self::DEFAULT_TIMEOUT, $contentType = 'application/json') 130 | { 131 | try { 132 | $this->_yotpoConfig->log("AbstractApi::sendApiRequest() - request: ", "debug", [["path" => $path, "params" => $data, "method" => $method, "timeout" => $timeout, "contentType" => $contentType]]); 133 | 134 | $this->_clearResponseData(); 135 | $this->curl->reset(); 136 | 137 | if ($contentType) { 138 | $this->curl->setHeaders( 139 | [ 140 | 'Content-Type' => $contentType 141 | ] 142 | ); 143 | } 144 | 145 | $this->curl->setTimeout($timeout); 146 | 147 | $this->curl->{strtolower($method)}( 148 | $this->_yotpoConfig->getYotpoApiUrl($path), 149 | $data 150 | ); 151 | 152 | $this->_yotpoConfig->log("AbstractApi::sendApiRequest() - response: ", "debug", $this->_prepareCurlResponseData()); 153 | return $this->_prepareCurlResponseData(); 154 | } catch (\Exception $e) { 155 | $this->_yotpoConfig->log("AbstractApi::sendApiRequest() Exception: " . $e->getMessage() . "\n" . $e->getTraceAsString(), "error"); 156 | } 157 | } 158 | 159 | /** 160 | * @method oauthAuthentication 161 | * @param int|null $scopeId 162 | * @param string|null $scope 163 | * @return mixed 164 | */ 165 | public function oauthAuthentication($scopeId = null, $scope = null) 166 | { 167 | try { 168 | $app_key = $this->_yotpoConfig->getAppKey($scopeId, $scope); 169 | $secret = $this->_yotpoConfig->getSecret($scopeId, $scope); 170 | if (!($app_key && $secret)) { 171 | $this->_yotpoConfig->log("AbstractApi::oauthAuthentication({$scopeId}, {$scope}) - Missing app key or secret", "debug", ['$app_key' => $app_key]); 172 | return null; 173 | } 174 | $result = $this->sendApiRequest( 175 | 'oauth/token', 176 | [ 177 | 'client_id' => $app_key, 178 | 'client_secret' => $secret, 179 | 'grant_type' => 'client_credentials' 180 | ] 181 | ); 182 | if (!is_array($result)) { 183 | $this->_yotpoConfig->log("AbstractApi::oauthAuthentication({$scopeId}, {$scope}) - error: no response from api", "error", ['$app_key' => $app_key]); 184 | return null; 185 | } 186 | $token = (is_object($result['body']) && property_exists($result['body'], "access_token")) ? $result['body']->access_token : false; 187 | if (!$token) { 188 | $this->_yotpoConfig->log("AbstractApi::oauthAuthentication({$scopeId}, {$scope}) - error: no access token received", "error", ['$app_key' => $app_key]); 189 | return null; 190 | } 191 | return $token; 192 | } catch (\Exception $e) { 193 | $this->_yotpoConfig->log("AbstractApi::oauthAuthentication({$scopeId}, {$scope}) - exception: " . $e->getMessage() . "\n" . $e->getTraceAsString(), "error"); 194 | return null; 195 | } 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /Model/AbstractJobs.php: -------------------------------------------------------------------------------- 1 | notifierPool = $notifierPool; 66 | $this->appState = $appState; 67 | $this->_yotpoConfig = $yotpoConfig; 68 | $this->_resourceConnection = $resourceConnection; 69 | $this->_appEmulation = $appEmulation; 70 | } 71 | 72 | /** 73 | * @method strToCamelCase 74 | * @param string $str 75 | * @param string $prefix 76 | * @param string $suffix 77 | * @return string 78 | */ 79 | public function strToCamelCase($str, $prefix = '', $suffix = '') 80 | { 81 | return $prefix . str_replace('_', '', ucwords($str, '_')) . $suffix; 82 | } 83 | 84 | /** 85 | * @method initConfig 86 | * @param array $config 87 | * @return $this 88 | */ 89 | public function initConfig(array $config) 90 | { 91 | foreach ($config as $key => $val) { 92 | $method = $this->strToCamelCase(strtolower($key), 'set'); 93 | if (method_exists($this, $method)) { 94 | $this->{$method}($val); 95 | } 96 | } 97 | return $this; 98 | } 99 | 100 | /** 101 | * @method setOutput 102 | * @param OutputInterface $output 103 | */ 104 | public function setOutput(OutputInterface $output) 105 | { 106 | $this->output = $output; 107 | return $this; 108 | } 109 | 110 | /** 111 | * @method getOutput 112 | * @return OutputInterface 113 | */ 114 | public function getOutput() 115 | { 116 | return $this->output; 117 | } 118 | 119 | /** 120 | * Process output messages (log to system.log / output to terminal) 121 | * @method _processOutput 122 | * @return $this 123 | */ 124 | protected function _processOutput($message, $type = "info", $data = []) 125 | { 126 | if ($this->output instanceof OutputInterface) { 127 | //Output to terminal 128 | $outputType = ($type === "error") ? $type : "info"; 129 | $this->output->writeln('<' . $outputType . '>' . json_encode($message) . ''); 130 | if ($data) { 131 | $this->output->writeln('' . json_encode($data) . ''); 132 | } 133 | } else { 134 | //Add admin error notification 135 | if ($type === 'error' && !$this->adminNotificationError) { 136 | $this->addAdminNotification("Yopto - An error occurred during the automated sync process! (module: Yotpo_Yotpo)", "*If you enabled debug mode on Yotpo - Reviews & Visual Marketing, you should see more details in the log file (var/log/system.log)", 'critical'); 137 | $this->adminNotificationError = true; 138 | } 139 | } 140 | 141 | //Log to var/log/system.log or var/log/debug.log 142 | $this->_yotpoConfig->log($message, $type, $data); 143 | 144 | return $this; 145 | } 146 | 147 | private function addAdminNotification(string $title, $description = "", $type = 'critical') 148 | { 149 | $method = 'add' . ucfirst($type); 150 | $this->notifierPool->{$method}($title, $description); 151 | return $this; 152 | } 153 | 154 | public function setCrontabAreaCode() 155 | { 156 | try { 157 | $this->appState->setAreaCode(\Magento\Framework\App\Area::AREA_CRONTAB); 158 | } catch (\Exception $e) { 159 | $this->_processOutput("AbstractJobs::setCrontabAreaCode() - Exception: " . $e->getMessage() . "\n" . $e->getTraceAsString(), "debug"); 160 | } 161 | return $this; 162 | } 163 | 164 | /////////////////////////////// 165 | // App Environment Emulation // 166 | /////////////////////////////// 167 | 168 | /** 169 | * Start environment emulation of the specified store 170 | * 171 | * Function returns information about initial store environment and emulates environment of another store 172 | * 173 | * @param integer $storeId 174 | * @param string $area 175 | * @param bool $force A true value will ensure that environment is always emulated, regardless of current store 176 | * @return \Yotpo\Yotpo\Helper\Data 177 | */ 178 | public function startEnvironmentEmulation($storeId, $area = Area::AREA_FRONTEND, $force = false) 179 | { 180 | $this->stopEnvironmentEmulation(); 181 | $this->_appEmulation->startEnvironmentEmulation($storeId, $area, $force); 182 | return $this; 183 | } 184 | 185 | /** 186 | * Stop environment emulation 187 | * 188 | * Function restores initial store environment 189 | * 190 | * @return \Yotpo\Yotpo\Helper\Data 191 | */ 192 | public function stopEnvironmentEmulation() 193 | { 194 | $this->_appEmulation->stopEnvironmentEmulation(); 195 | return $this; 196 | } 197 | 198 | public function emulateFrontendArea($storeId, $force = true) 199 | { 200 | $this->startEnvironmentEmulation($storeId, Area::AREA_FRONTEND, $force); 201 | return $this; 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /Block/Adminhtml/System/Config/Form/Field/SyncStatus.php: -------------------------------------------------------------------------------- 1 | yotpoConfig = $yotpoConfig; 60 | $this->orderCollectionFactory = $orderCollectionFactory; 61 | $this->yotpoSyncFactory = $yotpoSyncFactory; 62 | $this->appEmulation = $appEmulation; 63 | parent::__construct($context, $data); 64 | } 65 | 66 | protected function _prepareLayout() 67 | { 68 | parent::_prepareLayout(); 69 | if (!$this->getTemplate()) { 70 | $this->setTemplate('Yotpo_Yotpo::system/config/sync_status.phtml'); 71 | } 72 | return $this; 73 | } 74 | 75 | /** 76 | * Remove scope label 77 | * 78 | * @param AbstractElement $element 79 | * @return string 80 | */ 81 | public function render(AbstractElement $element) 82 | { 83 | $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue(); 84 | return parent::render($element); 85 | } 86 | 87 | /** 88 | * Return element html 89 | * 90 | * @param AbstractElement $element 91 | * @return string 92 | */ 93 | protected function _getElementHtml(AbstractElement $element) 94 | { 95 | return $this->_toHtml(); 96 | } 97 | 98 | protected function getStoreId() 99 | { 100 | if ($this->getRequest()->getParam('store', 0)) { 101 | return $this->getRequest()->getParam('store', 0); 102 | } else { 103 | return $this->yotpoConfig->getCurrentStoreId(); 104 | } 105 | } 106 | 107 | protected function getStoreIds() 108 | { 109 | if (!$this->hasData('storeIds')) { 110 | if (($_storeId = $this->getRequest()->getParam("store", 0))) { 111 | $stores = [$_storeId]; 112 | } elseif (($websiteId = $this->getRequest()->getParam("website", 0))) { 113 | $stores = $this->yotpoConfig->getStoreManager()->getWebsite($websiteId)->getStoreIds(); 114 | } else { 115 | $stores = $this->yotpoConfig->getAllStoreIds(false); 116 | } 117 | $this->setData('storeIds', $this->yotpoConfig->filterDisabledStoreIds($stores)); 118 | } 119 | return $this->getData('storeIds'); 120 | } 121 | 122 | protected function getOrderCollection() 123 | { 124 | $collection = $this->orderCollectionFactory->create(); 125 | $collection->getSelect()->joinLeft( 126 | ['yotpo_sync'=>$collection->getTable('yotpo_sync')], 127 | "main_table.entity_id = yotpo_sync.entity_id AND main_table.store_id = yotpo_sync.store_id AND yotpo_sync.entity_type = 'orders'", 128 | [ 129 | 'yotpo_sync_flag'=>'yotpo_sync.sync_flag' 130 | ] 131 | ); 132 | return $collection; 133 | } 134 | 135 | public function getStatus() 136 | { 137 | $status = [ 138 | 'total_orders' => 0, 139 | 'total_orders_synced' => 0, 140 | 'total_orders_synced_all' => 0, 141 | 'last_sync_date' => "never", 142 | ]; 143 | 144 | foreach ($this->getStoreIds() as $key => $storeId) { 145 | $this->appEmulation->startEnvironmentEmulation($storeId, Area::AREA_FRONTEND, true); 146 | 147 | $orderStatuses = $this->yotpoConfig->getCustomOrderStatus($storeId); 148 | $afterDate = $this->yotpoConfig->getOrdersSyncAfterDate($storeId); 149 | 150 | $status['total_orders'] += $this->getOrderCollection() 151 | ->addAttributeToFilter('main_table.status', ['in' => $orderStatuses]) 152 | ->addAttributeToFilter('main_table.store_id', $storeId) 153 | ->addAttributeToFilter('main_table.created_at', ['gteq' => $afterDate]) 154 | ->getSize(); 155 | $status['total_orders_synced'] += $this->getOrderCollection() 156 | ->addAttributeToFilter('main_table.status', ['in' => $orderStatuses]) 157 | ->addAttributeToFilter('main_table.store_id', $storeId) 158 | ->addAttributeToFilter('main_table.created_at', ['gteq' => $afterDate]) 159 | ->addAttributeToFilter('yotpo_sync.sync_flag', 1) 160 | ->getSize(); 161 | $status['total_orders_synced_all'] += $this->getOrderCollection() 162 | ->addAttributeToFilter('main_table.store_id', $storeId) 163 | ->addAttributeToFilter('main_table.created_at', ['gteq' => $afterDate]) 164 | ->addAttributeToFilter('yotpo_sync.sync_flag', 1) 165 | ->getSize(); 166 | 167 | $this->appEmulation->stopEnvironmentEmulation(); 168 | } 169 | 170 | $lastSyncDate = $this->yotpoSyncFactory->create()->getCollection() 171 | ->addFieldToFilter('entity_type', 'orders') 172 | ->addFieldToFilter('store_id', ['in' => $this->getStoreIds()]) 173 | ->setOrder('sync_date', 'DESC') 174 | ->setPageSize(1) 175 | ->getFirstItem(); 176 | 177 | $status['last_sync_date'] = ($lastSyncDate && $lastSyncDate->getSyncDate()) ? $lastSyncDate->getSyncDate() : "never"; 178 | 179 | return $status; 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /etc/adminhtml/system.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | separator-top 9 | 10 | yotpo 11 | Yotpo_Yotpo::config 12 | 13 | 14 | 1 15 | 16 | 17 | yotpo/settings/active 18 | Yotpo\Yotpo\Block\Adminhtml\System\Config\Form\Field\NoScopes 19 | App Key and API Secret in the fields below and save your configuration.]]> 20 | Magento\Config\Model\Config\Source\Yesno 21 | 22 | 23 | 24 | yotpo/settings/app_key 25 | Yotpo\Yotpo\Block\Adminhtml\System\Config\Form\Field\NoScopes 26 | Note: Additional stores must be connected to their own App Key via Store View settings. 27 | 28 | 29 | 30 | yotpo/settings/secret 31 | Magento\Config\Model\Config\Backend\Encrypted 32 | Yotpo\Yotpo\Block\Adminhtml\System\Config\Form\Field\NoScopes 33 | I can't find my API Secret]]> 34 | 35 | 36 | 37 | Yotpo\Yotpo\Block\Adminhtml\System\Config\ModuleVersion 38 | ]]> 39 | 40 | 41 | Yotpo\Yotpo\Block\Adminhtml\System\Config\LaunchYotpoButton 42 | 43 | 44 | 45 | 46 | 0 47 | 48 | 49 | yotpo/settings/widget_enabled 50 | Magento\Config\Model\Config\Source\Yesno 51 | 52 | 53 | 54 | yotpo/settings/category_bottomline_enabled 55 | Magento\Config\Model\Config\Source\Yesno 56 | 57 | 58 | 59 | yotpo/settings/bottomline_enabled 60 | Magento\Config\Model\Config\Source\Yesno 61 | 62 | 63 | 64 | yotpo/settings/qna_enabled 65 | Magento\Config\Model\Config\Source\Yesno 66 | 67 | 68 | 69 | yotpo/settings/mdr_enabled 70 | Magento\Config\Model\Config\Source\Yesno 71 | 72 | 73 | 74 | yotpo/settings/debug_mode_active 75 | Magento\Config\Model\Config\Source\Yesno 76 | Enable in order to log all Yotpo processes when Magento debug mode enabled. 77 | 78 | 79 | 80 | 81 | 0 82 | 83 | 84 | Yotpo\Yotpo\Block\Adminhtml\System\Config\Form\Field\SyncStatus 85 | 86 | 87 | 88 | yotpo/sync_settings/orders_sync_start_date 89 | Yotpo\Yotpo\Block\Adminhtml\System\Config\Form\Field\Date 90 | 91 | 92 | 93 | yotpo/sync_settings/orders_sync_limit 94 | Note: Setting a high sync limit (or no limit) may result in a high server load (0=no limit). 95 | 96 | 97 | 98 | yotpo/settings/custom_order_status 99 | Magento\Sales\Model\ResourceModel\Order\Status\Collection 100 | validate-select 101 | 0 102 | Customize the order status that will trigger the order export after purchase. You can choose multiple statuses by holding ctrl button. 103 | 104 | 105 |
106 |
107 |
108 | -------------------------------------------------------------------------------- /Model/Jobs/OrdersSync.php: -------------------------------------------------------------------------------- 1 | orderCollectionFactory = $orderCollectionFactory; 61 | $this->yotpoApi = $yotpoApi; 62 | $this->yotpoSchema = $yotpoSchema; 63 | } 64 | 65 | private function flagItems($entityType, $storeId, array $entityIds) 66 | { 67 | foreach ($entityIds as &$entityId) { 68 | $entityId = [ 69 | "store_id" => $storeId, 70 | "entity_type" => $entityType, 71 | "entity_id" => $entityId, 72 | "sync_flag" => 1, 73 | "sync_date" => $this->_yotpoConfig->getCurrentDate(), 74 | ]; 75 | } 76 | return $this->_resourceConnection->getConnection('sales') 77 | ->insertOnDuplicate($this->_resourceConnection->getTableName('yotpo_sync', 'sales'), $entityIds, ['store_id', 'entity_type', 'entity_id', 'sync_flag', 'sync_date']); 78 | } 79 | 80 | /** 81 | * @method getOrderCollection 82 | * @return OrderCollection 83 | * @api 84 | */ 85 | public function getOrderCollection() 86 | { 87 | $collection = $this->orderCollectionFactory->create(); 88 | $collection->getSelect()->joinLeft( 89 | ['yotpo_sync'=>$collection->getTable('yotpo_sync')], 90 | "main_table.entity_id = yotpo_sync.entity_id AND main_table.store_id = yotpo_sync.store_id AND yotpo_sync.entity_type = 'orders'", 91 | [ 92 | 'yotpo_sync_flag'=>'yotpo_sync.sync_flag' 93 | ] 94 | ); 95 | return $collection; 96 | } 97 | 98 | /** 99 | * @method addOrderCollectionFilters 100 | * @param OrderCollection $collection 101 | * @param int|null $storeId 102 | * @return OrderCollection 103 | * @api 104 | */ 105 | public function addOrderCollectionFilters(OrderCollection $collection, $storeId = null) 106 | { 107 | $storeId = is_null($storeId) ? $this->_yotpoConfig->getCurrentStoreId() : $storeId; 108 | return $collection 109 | ->addAttributeToFilter('main_table.status', ['in' => $this->_yotpoConfig->getCustomOrderStatus()]) 110 | ->addAttributeToFilter('main_table.store_id', $storeId) 111 | ->addAttributeToFilter('main_table.created_at', ['gteq' => $this->_yotpoConfig->getOrdersSyncAfterDate()]) 112 | ->addAttributeToFilter('yotpo_sync.sync_flag', [['null' => true],['eq' => 0]]) 113 | ->addAttributeToSort('main_table.created_at', 'ASC'); 114 | } 115 | 116 | /** 117 | * @method setOrderCollectionLimit 118 | * @param OrderCollection $collection 119 | * @return OrderCollection 120 | * @api 121 | */ 122 | public function setOrderCollectionLimit(OrderCollection $collection, $limit = null) 123 | { 124 | if (!is_null($limit)) { 125 | $collection->setPageSize($limit); 126 | } elseif (($limit = ($this->limit === null) ? $this->_yotpoConfig->getOrdersSyncLimit() : $this->limit)) { 127 | $collection->setPageSize($limit); 128 | } 129 | return $collection; 130 | } 131 | 132 | /** 133 | * @method setLimit 134 | * @param null|int $limit 135 | * @return $this 136 | */ 137 | public function setLimit($limit) 138 | { 139 | $this->limit = $limit; 140 | return $this; 141 | } 142 | 143 | /** 144 | * @method getLimit 145 | * @return null|int 146 | */ 147 | public function getLimit() 148 | { 149 | return $this->limit; 150 | } 151 | 152 | /** 153 | * @method getCollectionIds 154 | * @param $collection 155 | * @return array 156 | */ 157 | private function getCollectionIds($collection) 158 | { 159 | $ids = []; 160 | foreach ($collection as $item) { 161 | $ids[] = $item->getId(); 162 | } 163 | return $ids; 164 | } 165 | 166 | public function execute() 167 | { 168 | try { 169 | foreach ($this->_yotpoConfig->getAllStoreIds(false) as $storeId) { 170 | try { 171 | $this->emulateFrontendArea($storeId); 172 | if (!$this->_yotpoConfig->isEnabled()) { 173 | $this->_processOutput("OrdersSync::execute() - Skipping store ID: {$storeId} (disabled)", "debug"); 174 | continue; 175 | } 176 | $this->_processOutput("OrdersSync::execute() - Processing orders for store ID: {$storeId} ...", "debug"); 177 | 178 | $ordersCollection = $this->getOrderCollection(); 179 | $ordersCollection = $this->addOrderCollectionFilters($ordersCollection, $storeId); 180 | $ordersCollection = $this->setOrderCollectionLimit($ordersCollection); 181 | 182 | $orders = $this->yotpoSchema->prepareOrdersData($ordersCollection); 183 | $ordersCollectionCount = $ordersCollection->count(); 184 | $ordersCount = count($orders); 185 | $this->_processOutput("OrdersSync::execute() - Found {$ordersCount} orders for sync (" . ($ordersCollectionCount - $ordersCount) . " skipped).", "debug"); 186 | if ($ordersCount > 0) { 187 | $resData = $this->yotpoApi->massCreate($orders, $storeId); 188 | $status = (int) ((is_object($resData['body']) && property_exists($resData['body'], "code")) ? $resData['body']->code : $resData['status']); 189 | if (!$status || 500 <= $status) { 190 | $this->_processOutput("OrdersSync::execute() - Orders sync for store ID: {$storeId} [FAILURE]", "error", $resData); 191 | } else { 192 | $this->flagItems('orders', $storeId, $this->getCollectionIds($ordersCollection)); 193 | if ($status !== 200) { 194 | $this->_processOutput("OrdersSync::execute() - Orders sync for store ID: {$storeId} [WARNING] Some of the orders failed to sync due to Yotpo API's internal validation.", "error", $resData); 195 | } else { 196 | $this->_processOutput("OrdersSync::execute() - Orders sync for store ID: {$storeId} [SUCCESS]", "debug"); 197 | } 198 | } 199 | } elseif ($ordersCollectionCount) { 200 | $this->flagItems('orders', $storeId, $this->getCollectionIds($ordersCollection)); 201 | } 202 | } catch (\Exception $e) { 203 | $this->_processOutput("OrdersSync::execute() - Exception: Failed sync orders for store ID: {$storeId} - " . $e->getMessage() . "\n" . $e->getTraceAsString(), "error"); 204 | } 205 | $this->stopEnvironmentEmulation(); 206 | } 207 | } catch (\Exception $e) { 208 | $this->_processOutput("OrdersSync::execute() - Exception: Failed to sync orders. " . $e->getMessage() . "\n" . $e->getTraceAsString(), "error"); 209 | } 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /Model/Schema.php: -------------------------------------------------------------------------------- 1 | yotpoConfig = $yotpoConfig; 49 | $this->productFactory = $productFactory; 50 | $this->escaper = $escaper; 51 | $this->orderStatusHistoryFactory = $orderStatusHistoryFactory; 52 | } 53 | 54 | /** 55 | * @method getProductMainImageUrl 56 | * @param Product $product 57 | * @return string 58 | */ 59 | private function getProductMainImageUrl(Product $product) 60 | { 61 | if (($filePath = $product->getData("image"))) { 62 | return (string) $this->yotpoConfig->getMediaUrl("catalog/product", $filePath); 63 | } 64 | return ""; 65 | } 66 | 67 | /** 68 | * @method prepareProductsData 69 | * @param Order $order 70 | * @return array 71 | */ 72 | private function prepareProductsData(Order $order) 73 | { 74 | $productsData = []; 75 | $groupProductsParents = []; 76 | 77 | try { 78 | foreach ($order->getAllVisibleItems() as $orderItem) { 79 | try { 80 | $product = null; 81 | if ($orderItem->getProductType() === ProductTypeGrouped::TYPE_CODE) { 82 | $productOptions = $orderItem->getProductOptions(); 83 | $productId = (isset($productOptions['super_product_config']) && isset($productOptions['super_product_config']['product_id'])) ? $productOptions['super_product_config']['product_id'] : null; 84 | if ($productId) { 85 | if (isset($groupProductsParents[$productId])) { 86 | $product = $groupProductsParents[$productId]; 87 | } else { 88 | $product = $groupProductsParents[$productId] = $this->productFactory->create()->load($productId); 89 | } 90 | } 91 | } else { 92 | $product = $orderItem->getProduct(); 93 | } 94 | 95 | if (!($product && $product->getId())) { 96 | continue; 97 | } 98 | if ( 99 | $orderItem->getData('amount_refunded') >= $orderItem->getData('row_total_incl_tax') || 100 | $orderItem->getData('qty_ordered') <= ($orderItem->getData('qty_refunded') + $orderItem->getData('qty_canceled')) 101 | ) { 102 | //Skip if item is fully canceled or refunded 103 | continue; 104 | } 105 | if ($orderItem->getProductType() === ProductTypeGrouped::TYPE_CODE && isset($productsData[$product->getId()])) { 106 | $productsData[$product->getId()]['price'] += $orderItem->getData('row_total_incl_tax') - $orderItem->getData('amount_refunded'); 107 | } else { 108 | $productsData[$product->getId()] = [ 109 | 'name' => $product->getName(), 110 | 'url' => $product->getProductUrl(), 111 | 'image' => $this->getProductMainImageUrl($product), 112 | 'description' => $this->escaper->escapeHtml(strip_tags($product->getDescription())), 113 | 'price' => $orderItem->getData('row_total_incl_tax') - $orderItem->getData('amount_refunded'), 114 | 'specs' => array_filter( 115 | [ 116 | 'external_sku' => $product->getSku(), 117 | 'upc' => $product->getUpc(), 118 | 'isbn' => $product->getIsbn(), 119 | 'mpn' => $product->getMpn(), 120 | 'brand' => $product->getBrand() ? $product->getAttributeText('brand') : null, 121 | ] 122 | ), 123 | ]; 124 | } 125 | } catch (\Exception $e) { 126 | $this->yotpoConfig->log("Schema::prepareProductsData() - exception: " . $e->getMessage() . "\n" . $e->getTraceAsString(), "error"); 127 | } 128 | } 129 | } catch (\Exception $e) { 130 | $this->yotpoConfig->log("Schema::prepareProductsData() - exception: " . $e->getMessage() . "\n" . $e->getTraceAsString(), "error"); 131 | } 132 | 133 | return $productsData; 134 | } 135 | 136 | /** 137 | * @method prepareOrdersData 138 | * @param OrderCollection $ordersCollection 139 | * @return array 140 | */ 141 | public function prepareOrdersData(OrderCollection $ordersCollection) 142 | { 143 | $ordersData = []; 144 | 145 | try { 146 | foreach ($ordersCollection as $order) { 147 | if (($_order = $this->prepareOrderData($order))) { 148 | $ordersData[] = $_order; 149 | } 150 | } 151 | } catch (\Exception $e) { 152 | $this->yotpoConfig->log("Schema::prepareOrdersData() - exception: " . $e->getMessage() . "\n" . $e->getTraceAsString(), "error"); 153 | return []; 154 | } 155 | 156 | return $ordersData; 157 | } 158 | 159 | /** 160 | * @method prepareOrderData 161 | * @param Order $order 162 | * @return array 163 | */ 164 | public function prepareOrderData(Order $order) 165 | { 166 | $orderData = []; 167 | 168 | try { 169 | $orderData['products'] = $this->prepareProductsData($order); 170 | if (!$orderData['products']) { 171 | return []; 172 | } 173 | $orderData['order_id'] = $order->getIncrementId(); 174 | $orderData['order_date'] = $order->getCreatedAt(); 175 | $orderData['fulfillment_date'] = $this->getOrderFulfillmentDate($order); 176 | $orderData['currency_iso'] = $order->getOrderCurrency()->getCode(); 177 | $orderData['email'] = $order->getCustomerEmail(); 178 | $orderData['customer_name'] = trim($order->getCustomerFirstName() . ' ' . $order->getCustomerLastName()); 179 | $orderData['platform'] = 'magento'; 180 | if (!$orderData['customer_name'] && ($billingAddress = $order->getBillingAddress())) { 181 | $orderData['customer_name'] = trim($billingAddress->getFirstname() . ' ' . $billingAddress->getLastname()); 182 | } 183 | if (!$order->getCustomerIsGuest()) { 184 | $orderData['user_reference'] = $order->getCustomerId(); 185 | } 186 | if (($fulfillmentDate = $this->getOrderFulfillmentDate($order))) { 187 | $orderData['fulfillment_status'] = 'fulfilled'; 188 | $orderData['fulfillment_status_date'] = $fulfillmentDate; 189 | } 190 | } catch (\Exception $e) { 191 | $this->yotpoConfig->log("Schema::prepareOrderData() - exception: " . $e->getMessage() . "\n" . $e->getTraceAsString(), "error"); 192 | return []; 193 | } 194 | 195 | return $orderData; 196 | } 197 | 198 | private function getOrderFulfillmentDate(Order $order) 199 | { 200 | $lastStatus = $this->orderStatusHistoryFactory->create()->getCollection() 201 | ->addFieldToSelect(["id","created_at"]) 202 | ->addFieldToFilter("order_id", $order->getId()) 203 | ->addFieldToFilter("store_id", $order->getStoreId()) 204 | ->setOrder('created_at', 'desc') 205 | ->setOrder('id', 'desc') 206 | ->setPageSize(1) 207 | ->getFirstItem(); 208 | if ($lastStatus && $lastStatus->getId()) { 209 | return $lastStatus->getCreatedAt(); 210 | } elseif (($lastStatus = $order->getStatusHistoryCollection()->getFirstItem())) { 211 | return $lastStatus->getCreatedAt(); 212 | } else { 213 | return null; 214 | } 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Open Software License ("OSL") v. 3.0 3 | 4 | This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: 5 | 6 | Licensed under the Open Software License version 3.0 7 | 8 | 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: 9 | 10 | 1. to reproduce the Original Work in copies, either alone or as part of a collective work; 11 | 12 | 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; 13 | 14 | 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License; 15 | 16 | 4. to perform the Original Work publicly; and 17 | 18 | 5. to display the Original Work publicly. 19 | 20 | 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. 21 | 22 | 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. 23 | 24 | 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. 25 | 26 | 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). 27 | 28 | 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. 29 | 30 | 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. 31 | 32 | 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. 33 | 34 | 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including 'fair use' or 'fair dealing'). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). 35 | 36 | 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. 37 | 38 | 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. 39 | 40 | 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. 41 | 42 | 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. 43 | 44 | 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 45 | 46 | 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. 47 | 48 | 16. Modification of This License. This License is Copyright (C) 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. -------------------------------------------------------------------------------- /LICENSE_AFL.txt: -------------------------------------------------------------------------------- 1 | 2 | Academic Free License ("AFL") v. 3.0 3 | 4 | This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: 5 | 6 | Licensed under the Academic Free License version 3.0 7 | 8 | 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: 9 | 10 | 1. to reproduce the Original Work in copies, either alone or as part of a collective work; 11 | 12 | 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; 13 | 14 | 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; 15 | 16 | 4. to perform the Original Work publicly; and 17 | 18 | 5. to display the Original Work publicly. 19 | 20 | 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. 21 | 22 | 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. 23 | 24 | 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. 25 | 26 | 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). 27 | 28 | 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. 29 | 30 | 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. 31 | 32 | 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. 33 | 34 | 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). 35 | 36 | 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. 37 | 38 | 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. 39 | 40 | 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. 41 | 42 | 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. 43 | 44 | 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 45 | 46 | 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. 47 | 48 | 16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. 49 | -------------------------------------------------------------------------------- /view/adminhtml/web/css/source/_module.less: -------------------------------------------------------------------------------- 1 | @import url('https://fonts.googleapis.com/css?family=Work+Sans:400,700'); 2 | 3 | .yotpo-reviews-totals { 4 | font-family: 'Open Sans', sans-serif; 5 | background: #ffffff; 6 | 7 | .yotpo-reviews-totals-list { 8 | display: block; 9 | max-width: 60rem; 10 | columns: 3; 11 | margin-bottom: 20px; 12 | 13 | .yotpo-reviews-totals-item { 14 | display: inline-block; 15 | padding: 1.2rem 1rem 1.2rem 0; 16 | max-width: 20rem; 17 | 18 | .yotpo-reviews-totals-label { 19 | display: block; 20 | font-size: 1.5rem; 21 | font-weight: normal; 22 | } 23 | 24 | .yotpo-reviews-totals-value { 25 | font-size: 2.4rem; 26 | font-weight: normal; 27 | } 28 | 29 | .yotpo-reviews-totals-icon { 30 | display: inline-block; 31 | width: 3.6rem; 32 | height: 3.2rem; 33 | vertical-align: sub; 34 | background-repeat: no-repeat; 35 | background-position: center center; 36 | background-size: contain; 37 | } 38 | 39 | &.yotpo-totals-emails-sent .yotpo-reviews-totals-icon { 40 | background-image: url("@{baseDir}Yotpo_Yotpo/images/icons/email-icon.svg"); 41 | } 42 | 43 | &.yotpo-totals-total-reviews .yotpo-reviews-totals-icon { 44 | background-image: url("@{baseDir}Yotpo_Yotpo/images/icons/collect-icon.svg"); 45 | } 46 | 47 | &.yotpo-totals-published-reviews .yotpo-reviews-totals-icon { 48 | background-image: url("@{baseDir}Yotpo_Yotpo/images/icons/upload-icon.svg"); 49 | } 50 | 51 | &.yotpo-totals-star-rating .yotpo-reviews-totals-icon { 52 | background-image: url("@{baseDir}Yotpo_Yotpo/images/icons/star-icon.svg"); 53 | } 54 | 55 | &.yotpo-totals-photos-generated .yotpo-reviews-totals-icon { 56 | background-image: url("@{baseDir}Yotpo_Yotpo/images/icons/photo-icon.svg"); 57 | } 58 | 59 | &.yotpo-totals-engagement-rate .yotpo-reviews-totals-icon { 60 | background-image: url("@{baseDir}Yotpo_Yotpo/images/icons/rate-icon.svg"); 61 | } 62 | } 63 | } 64 | 65 | .yotpo-reviews-totals-nodata { 66 | background: #ffffff; 67 | padding: 20px; 68 | } 69 | } 70 | 71 | .launch-yotpo-button { 72 | font-family: 'Open Sans', sans-serif; 73 | min-width: 161px; 74 | height: 38px; 75 | border-radius: 3px; 76 | font-size: 1.3rem; 77 | background-color: #2b7dbd; 78 | color: #ffffff; 79 | box-sizing: border-box; 80 | border: none; 81 | 82 | &:active, 83 | &:focus, 84 | &:hover { 85 | background-color: #0073ae; 86 | border-color: #007dbd; 87 | box-shadow: 0 0 0 1px #007bdb; 88 | color: #ffffff; 89 | text-decoration: none; 90 | } 91 | } 92 | 93 | .yotpo-reviews-totals-no-appkey { 94 | font-family: 'Open Sans', sans-serif; 95 | background: #ffffff; 96 | font-weight: normal; 97 | font-style: normal; 98 | font-stretch: normal; 99 | line-height: normal; 100 | letter-spacing: normal; 101 | text-align: center; 102 | 103 | .collect-and-leverage { 104 | max-width: 421px; 105 | font-size: 1.6rem; 106 | color: #676363; 107 | position: relative; 108 | margin: 20px auto; 109 | } 110 | 111 | .already-have-account { 112 | max-width: 250px; 113 | font-size: 1.3rem; 114 | position: relative; 115 | margin: 14px auto; 116 | 117 | a { 118 | color: #2b7dbd; 119 | } 120 | } 121 | } 122 | 123 | .yotpo_yotpo-report-reviews { 124 | #container.main-col { 125 | min-height: 500px; 126 | margin-bottom: 120px; 127 | } 128 | 129 | .yotpo-reports-period-select.admin__action-dropdown-wrap { 130 | float: right; 131 | 132 | .admin__action-dropdown-text { 133 | font-size: 1.5rem; 134 | } 135 | 136 | &._active .admin__action-dropdown, 137 | &.active .admin__action-dropdown { 138 | border: none; 139 | box-shadow: none; 140 | } 141 | 142 | .admin__action-dropdown { 143 | padding-left: 0 !important; 144 | } 145 | 146 | .admin__action-dropdown-menu { 147 | box-shadow: 0 2px 4px 0 rgba(46, 46, 46, 0.5); 148 | background-color: #ffffff; 149 | border: none; 150 | left: 0 !important; 151 | right: auto !important; 152 | z-index: 9; 153 | 154 | > li { 155 | > a { 156 | &:active, 157 | &:hover { 158 | background-color: #c7effd; 159 | } 160 | } 161 | } 162 | } 163 | } 164 | 165 | .yotpo-at-a-glance { 166 | line-height: 3rem; 167 | font-size: 1.8rem; 168 | font-weight: bold; 169 | color: #313030; 170 | } 171 | 172 | .user-generated-content { 173 | font-size: 1.4rem; 174 | font-weight: normal; 175 | color: #313030; 176 | } 177 | 178 | .launch-yotpo-button { 179 | margin-left: 16px; 180 | } 181 | 182 | a.yotpo-settings { 183 | font-size: 1.3rem; 184 | color: #2b7dbd; 185 | display: inline-block; 186 | margin-top: 16px; 187 | margin-left: 16px; 188 | font-weight: 600; 189 | } 190 | 191 | .yotpo-reviews-totals-container { 192 | box-sizing: border-box; 193 | max-width: 800px; 194 | padding: 25px 25px 55px; 195 | margin: 10px 0; 196 | background: #fff; 197 | } 198 | 199 | .yotpo-reviews-totals { 200 | max-width: 800px; 201 | 202 | .yotpo-reviews-totals-list { 203 | margin-top: 30px; 204 | margin-bottom: 30px; 205 | padding-left: 16px; 206 | 207 | .yotpo-reviews-totals-item { 208 | padding: 1.2rem 1rem 3.2rem 0; 209 | 210 | .yotpo-reviews-totals-icon { 211 | margin-right: 0.5rem; 212 | } 213 | 214 | .yotpo-reviews-totals-label { 215 | color: #545252; 216 | margin-top: 10px; 217 | } 218 | 219 | .yotpo-reviews-totals-value { 220 | display: inline-block; 221 | font-size: 3.6rem; 222 | line-height: 3.6rem; 223 | height: 3.6rem; 224 | } 225 | } 226 | } 227 | } 228 | 229 | .yotpo-reviews-totals-no-appkey { 230 | padding: 140px 0 30px 30px; 231 | display: inline-block; 232 | width: 100%; 233 | background: transparent; 234 | 235 | * { 236 | box-sizing: border-box; 237 | } 238 | 239 | .yotpo-title-content-container { 240 | float: left; 241 | text-align: left; 242 | padding: 0 40px 0 0; 243 | width: 40%; 244 | 245 | h2 { 246 | font-family: 'Work Sans', sans-serif; 247 | font-size: 4rem; 248 | font-weight: bold; 249 | line-height: 1.15; 250 | color: #051146; 251 | margin: 80px 0 10px; 252 | } 253 | 254 | p { 255 | font-size: 1.7rem; 256 | line-height: 1.6; 257 | color: #051146; 258 | } 259 | 260 | .launch-yotpo-button { 261 | font-size: 1.62rem; 262 | background-color: #1576ec; 263 | font-weight: bold; 264 | min-width: 19rem; 265 | height: 4.8rem; 266 | border-radius: 4.5px; 267 | margin: 30px 0 3px; 268 | } 269 | 270 | .already-have-account { 271 | font-size: 1.5rem; 272 | margin: 10px 0 0; 273 | max-width: none; 274 | } 275 | } 276 | 277 | .yotpo-shaddow-boxes-container { 278 | float: right; 279 | width: 60%; 280 | 281 | .yotpo-shaddow-box { 282 | width: 32%; 283 | max-width: 306px; 284 | height: 435px; 285 | overflow: hidden; 286 | float: left; 287 | box-shadow: 0 0 23px 0 rgba(0, 0, 0, 0.1); 288 | background-color: #ffffff; 289 | padding: 50px 22.5px; 290 | margin: 0 1%; 291 | 292 | &:first-of-type { 293 | margin-left: 0; 294 | } 295 | 296 | &:last-of-type { 297 | margin-right: 0; 298 | } 299 | 300 | h3 { 301 | font-size: 1.5rem; 302 | text-transform: uppercase; 303 | font-weight: 600; 304 | color: #051146; 305 | } 306 | 307 | img { 308 | width: 100%; 309 | display: block; 310 | } 311 | 312 | p { 313 | font-size: 1.3rem; 314 | color: #051146; 315 | margin: 35px 0 10px; 316 | min-height: 90px; 317 | } 318 | 319 | a { 320 | &.yotpo-cta-add-arrow:after { 321 | font-size: 1rem; 322 | } 323 | } 324 | } 325 | } 326 | @media all and (max-width: 1390px) { 327 | .yotpo-shaddow-boxes-container, 328 | .yotpo-title-content-container { 329 | float: none; 330 | clear: both; 331 | margin-bottom: 40px; 332 | width: 100%; 333 | } 334 | } 335 | } 336 | } 337 | 338 | .yotpo-cta-add-arrow { 339 | &:after { 340 | -webkit-font-smoothing: antialiased; 341 | -moz-osx-font-smoothing: grayscale; 342 | font-size: 1.3rem; 343 | color: inherit; 344 | font-style: normal; 345 | content: '\e629'; 346 | font-family: 'Admin Icons'; 347 | -webkit-transform: rotate(180deg); 348 | -moz-transform: rotate(180deg); 349 | -o-transform: rotate(180deg); 350 | -ms-transform: rotate(180deg); 351 | transform: rotate(180deg); 352 | display: inline-block; 353 | speak: none; 354 | text-align: center; 355 | vertical-align: middle; 356 | } 357 | } -------------------------------------------------------------------------------- /Block/Adminhtml/Report/Reviews.php: -------------------------------------------------------------------------------- 1 | collectionFactory = $collectionFactory; 71 | $this->yotpoConfig = $yotpoConfig; 72 | $this->yotpoApi = $yotpoApi; 73 | parent::__construct($context, $data); 74 | } 75 | 76 | private function initialize() 77 | { 78 | if ($this->initialized) { 79 | return; 80 | } 81 | $this->initialized = true; 82 | 83 | if (($storeId = $this->getRequest()->getParam(ScopeInterface::SCOPE_STORE, 0))) { 84 | $this->allStoreIds = [$storeId]; 85 | } elseif (($websiteId = $this->getRequest()->getParam(ScopeInterface::SCOPE_WEBSITE, 0))) { 86 | $this->allStoreIds = $this->yotpoConfig->getStoreManager()->getWebsite($websiteId)->getStoreIds(); 87 | } else { 88 | $this->allStoreIds = $this->yotpoConfig->getAllStoreIds(false); 89 | } 90 | $this->allStoreIds = $this->yotpoConfig->filterDisabledStoreIds($this->allStoreIds); 91 | $this->scopeId = ($this->allStoreIds) ? $this->allStoreIds[0] : null; 92 | 93 | $this->isEnabled = ($this->allStoreIds) ? true : false; 94 | $this->isAppKeyAndSecretSet = ($this->allStoreIds) ? true : false; 95 | $this->appKey = ($this->scopeId) ? $this->yotpoConfig->getAppKey($this->scopeId, $this->scope) : null; 96 | } 97 | 98 | public function isEnabledAndConfigured() 99 | { 100 | return ($this->isEnabled && $this->isAppKeyAndSecretSet) ? true : false; 101 | } 102 | 103 | public function getStoreIds() 104 | { 105 | return $this->allStoreIds; 106 | } 107 | 108 | public function getPeriod($default = null) 109 | { 110 | return $this->getRequest()->getParam('period', ($default ?: $this->_defaultPeriod)); 111 | } 112 | 113 | public function isEnabled() 114 | { 115 | return $this->isEnabled; 116 | } 117 | 118 | public function getAppKey() 119 | { 120 | return $this->appKey; 121 | } 122 | 123 | public function isAppKeyAndSecretSet() 124 | { 125 | return $this->isAppKeyAndSecretSet; 126 | } 127 | 128 | /** 129 | * @return array 130 | */ 131 | public function getTotals() 132 | { 133 | return $this->totals; 134 | } 135 | 136 | /** 137 | * @method addTotal 138 | * @param string $label 139 | * @param mixed $value 140 | * @param string $class 141 | */ 142 | private function addTotal($label, $value, $class = "") 143 | { 144 | $this->totals[] = ['label' => $label, 'value' => $value, 'class' => $class]; 145 | return $this; 146 | } 147 | 148 | /** 149 | * Calculate From and To dates (or times) by given period 150 | * 151 | * @param string $range 152 | * @param string $customStart 153 | * @param string $customEnd 154 | * @param bool $returnObjects 155 | * @return array 156 | */ 157 | private function getDateRange($range, $customStart, $customEnd, $returnObjects = false) 158 | { 159 | $dateEnd = new \DateTime(); 160 | $dateStart = new \DateTime(); 161 | 162 | // go to the end of a day 163 | //$dateEnd->setTime(23, 59, 59); 164 | //$dateStart->setTime(0, 0, 0); 165 | 166 | switch ($range) { 167 | case '24h': 168 | $dateEnd = new \DateTime(); 169 | $dateEnd->modify('+1 hour'); 170 | $dateStart = clone $dateEnd; 171 | $dateStart->modify('-1 day'); 172 | break; 173 | case '1d': 174 | $dateStart->modify('-1 days'); 175 | break; 176 | 177 | case '7d': 178 | $dateStart->modify('-6 days'); 179 | break; 180 | 181 | case '30d': 182 | $dateStart->modify('-30 days'); 183 | break; 184 | 185 | case '1m': 186 | $dateStart->setDate( 187 | $dateStart->format('Y'), 188 | $dateStart->format('m'), 189 | $this->yotpoConfig->getConfig('reports/dashboard/mtd_start') 190 | ); 191 | break; 192 | 193 | case 'custom': 194 | $dateStart = $customStart ? $customStart : $dateEnd; 195 | $dateEnd = $customEnd ? $customEnd : $dateEnd; 196 | break; 197 | 198 | case '1y': 199 | case '2y': 200 | $startMonthDay = explode( 201 | ',', 202 | $this->yotpoConfig->getConfig('reports/dashboard/ytd_start') 203 | ); 204 | $startMonth = isset($startMonthDay[0]) ? (int)$startMonthDay[0] : 1; 205 | $startDay = isset($startMonthDay[1]) ? (int)$startMonthDay[1] : 1; 206 | $dateStart->setDate($dateStart->format('Y'), $startMonth, $startDay); 207 | if ($range == '2y') { 208 | $dateStart->modify('-1 year'); 209 | } 210 | break; 211 | 212 | case 'all': 213 | $dateStart->modify('-1000 years'); 214 | break; 215 | } 216 | 217 | if ($returnObjects) { 218 | return [$dateStart, $dateEnd]; 219 | } else { 220 | return ['from' => $dateStart, 'to' => $dateEnd, 'datetime' => true]; 221 | } 222 | } 223 | 224 | /** 225 | * @return $this|void 226 | */ 227 | protected function _prepareLayout() 228 | { 229 | $this->initialize(); 230 | $storeIds = $this->getStoreIds(); 231 | $dateRange = $this->getDateRange($this->getPeriod(), 0, 0, true); 232 | 233 | $metrics = $this->yotpoApi->getMetrics( 234 | $this->getStoreIds(), 235 | $dateRange[0]->format(DateTime::DATETIME_PHP_FORMAT), 236 | $dateRange[1]->format(DateTime::DATETIME_PHP_FORMAT) 237 | ); 238 | 239 | if (!isset($metrics['emails_sent'])) { 240 | $emailsSent = "-"; 241 | } elseif ($metrics['emails_sent'] > 999999) { 242 | $emailsSent = number_format((float)($metrics['emails_sent']/1000000), 1, '.', "") . 'M'; 243 | } elseif ($metrics['emails_sent'] > 99999) { 244 | $emailsSent = number_format((float)($metrics['emails_sent']/1000), 0, '.', "") . 'K'; 245 | } elseif ($metrics['emails_sent'] > 999) { 246 | $emailsSent = number_format((float)($metrics['emails_sent']/1000), 1, '.', "") . 'K'; 247 | } else { 248 | $emailsSent = round((float)$metrics['emails_sent'], 2); 249 | } 250 | 251 | $this->addTotal(__('Emails Sent'), $emailsSent, 'yotpo-totals-emails-sent'); 252 | $this->addTotal(__('Avg. Star Rating'), (isset($metrics['star_rating'])) ? round((float)$metrics['star_rating'], 2) : '-', 'yotpo-totals-star-rating'); 253 | $this->addTotal(__('Collected Reviews'), (isset($metrics['total_reviews'])) ? round((float)$metrics['total_reviews'], 2) : '-', 'yotpo-totals-total-reviews'); 254 | $this->addTotal(__('Collected Photos'), (isset($metrics['photos_generated'])) ? round((float)$metrics['photos_generated'], 2) : '-', 'yotpo-totals-photos-generated'); 255 | $this->addTotal(__('Published Reviews'), (isset($metrics['published_reviews'])) ? round((float)$metrics['published_reviews'], 2) : '-', 'yotpo-totals-published-reviews'); 256 | $this->addTotal(__('Engagement Rate'), (isset($metrics['engagement_rate'])) ? round((float)$metrics['engagement_rate'], 2) . '%' : '-', 'yotpo-totals-engagement-rate'); 257 | } 258 | 259 | /** 260 | * Generate yotpo button html 261 | * 262 | * @param string $utm 263 | * @return string 264 | */ 265 | public function getLounchYotpoButtonHtml($utm = 'MagentoAdmin_Dashboard') 266 | { 267 | $this->initialize(); 268 | $button = $this->getLayout()->createBlock( 269 | \Magento\Backend\Block\Widget\Button::class 270 | )->setData( 271 | [ 272 | 'id' => 'launch_yotpo_button', 273 | 'class' => 'launch-yotpo-button yotpo-cta-add-arrow', 274 | ] 275 | ); 276 | if (!($appKey = $this->getAppKey())) { 277 | $button->setLabel(__('Get Started')); 278 | $button->setOnClick("window.open('https://www.yotpo.com/integrations/magento/?utm_source={$utm}','_blank');"); 279 | } else { 280 | $button->setLabel(__('Launch Yotpo')); 281 | $button->setOnClick("window.open('https://yap.yotpo.com/#/preferredAppKey={$appKey}','_blank');"); 282 | } 283 | 284 | return $button->toHtml(); 285 | } 286 | 287 | /** 288 | * Get url for Yotpo configuration 289 | * 290 | * @return string 291 | */ 292 | public function getYotpoConfigUrl() 293 | { 294 | $this->initialize(); 295 | $params = ['section' => 'yotpo']; 296 | if ($this->scope) { 297 | $params[$this->scope] = $this->scopeId; 298 | } 299 | return $this->_urlBuilder->getUrl('adminhtml/system_config/edit', $params); 300 | } 301 | 302 | public function getPeriods() 303 | { 304 | return [ 305 | '1d' => 'Last Day', 306 | '7d' => 'Last 7 Days', 307 | '30d' => 'Last 30 Days', 308 | 'all' => 'All Time', 309 | ]; 310 | } 311 | } 312 | --------------------------------------------------------------------------------