Skip to content

Commit

Permalink
Merge pull request #5 from trustpilot/Order_From_Backend
Browse files Browse the repository at this point in the history
Order_from_backend
  • Loading branch information
vilgro committed Jun 6, 2018
2 parents 79370f4 + 00d243d commit 2fbae65
Show file tree
Hide file tree
Showing 11 changed files with 332 additions and 22 deletions.
2 changes: 1 addition & 1 deletion Block/Success.php
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function __construct(
$this->_helper = $helper;
$this->_notifications = $notifications;
$this->_customer = $customer;
$this->_version = '1.0.82';
$this->_version = '1.0.128';
parent::__construct($context, $data);
}

Expand Down
5 changes: 2 additions & 3 deletions Helper/Data.php
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,11 @@ class Data extends AbstractHelper

public function getGeneralConfigValue($value)
{
return $this->scopeConfig->getValue(self::XML_PATH_TRUSTPILOT_GENERAL
. $value, \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE);
return $this->scopeConfig->getValue(self::XML_PATH_TRUSTPILOT_GENERAL . $value, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
}

public function getTrustBoxConfigValue($value)
{
return $this->scopeConfig->getValue(self::XML_PATH_TRUSTPILOT_TRUSTBOX . $value, \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE);
return $this->scopeConfig->getValue(self::XML_PATH_TRUSTPILOT_TRUSTBOX . $value, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
}
}
72 changes: 72 additions & 0 deletions Helper/HttpClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

namespace Trustpilot\Reviews\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use \Psr\Log\LoggerInterface;

class HttpClient extends AbstractHelper
{
const HTTP_REQUEST_TIMEOUT = 3;
protected $_logger;

public function __construct(LoggerInterface $logger)
{
$this->_logger = $logger;
}

public function request($url, $httpRequest, $origin = null, $data = null, $params = array(), $timeout = self::HTTP_REQUEST_TIMEOUT)
{
try{
$ch = curl_init();
$this->setCurlOptions($ch, $httpRequest, $data, $origin, $timeout);
$url = $this->buildParams($url, $params);
curl_setopt($ch, CURLOPT_URL, $url);
$content = curl_exec($ch);
$responseData = json_decode($content);
$responseInfo = curl_getinfo($ch);
$responseCode = $responseInfo['http_code'];
curl_close($ch);
$response = array();
$response['code'] = $responseCode;
if ($responseData) {
$response['data'] = $responseData;
}
return $response;
} catch (Exception $e){
//intentionally empty
}
}

private function jsonEncoder($data)
{
if (function_exists('json_encode'))
return json_encode($data);
elseif (method_exists('Tools', 'jsonEncode'))
return Tools::jsonEncode($data);
}

private function setCurlOptions($ch, $httpRequest, $data, $origin, $timeout)
{
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
if ($httpRequest == 'POST') {
$encoded_data = $this->jsonEncoder($data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('content-type: application/json', 'Content-Length: ' . strlen($encoded_data), 'Origin: ' . $origin));
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded_data);
return;
} elseif ($httpRequest == 'GET') {
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
return;
}
return;
}

private function buildParams($url, $params = array()){
if (!empty($params) && is_array($params)) {
$url .= '?'.http_build_query($params);
}
return $url;
}
}
79 changes: 79 additions & 0 deletions Helper/OrderData.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

namespace Trustpilot\Reviews\Helper;

use Magento\Catalog\Model\Product;
use Magento\Framework\App\Helper\AbstractHelper;
use \Magento\Store\Model\StoreManagerInterface;

class OrderData extends AbstractHelper
{
protected $_product;

public function __construct(
Product $product,
StoreManagerInterface $storeManager
) {
$this->_storeManager = $storeManager;
$this->_product = $product;
}

public function getEmail($order)
{
if ($this->is_empty($order))
return '';

if (!($this->is_empty($order->getCustomerEmail())))
return $order->getCustomerEmail();

else if (!($this->is_empty($order->getShippingAddress()->getEmail())))
return $order->getShippingAddress()->getEmail();

else if (!($this->is_empty($order->getBillingAddress()->getEmail())))
return $order->getBillingAddress()->getEmail();

else if (!($this->is_empty($order->getCustomerId())))
return $this->_customer->load($order->getCustomerId())->getEmail();

return '';
}

public function getSkus($products)
{
$skus = [];
foreach ($products as $product) {
array_push($skus, $product['sku']);
}
return $skus;
}

public function is_empty($var)
{
return empty($var);
}

public function getProducts($order){
$products = [];
try {
$items = $order->getAllItems();
foreach ($items as $i) {
$product = $this->_product->load($i->getProductId());
$brand = $product->getAttributeText('manufacturer');
array_push(
$products,
[
'productUrl' => $product->getProductUrl(),
'name' => $product->getName(),
'brand' => $brand ? $brand : '',
'sku' => $product->getSku(),
'imageUrl' => $this->_storeManager->getStore($order->getStoreId())->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA)
. 'catalog/product' . $product->getImage()
]
);
}
} catch (Exception $e) {
// Just skipping products data if we are not able to collect it
}
return $products;
}
}
46 changes: 46 additions & 0 deletions Helper/TrustpilotHttpClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace Trustpilot\Reviews\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Trustpilot\Reviews\Helper\HttpClient;
use Trustpilot\Reviews\Helper\Data;
use \Psr\Log\LoggerInterface;
use \Magento\Store\Model\StoreManagerInterface;

class TrustpilotHttpClient extends AbstractHelper
{
protected $_logger;
protected $_httpClient;
protected $_dataHelper;
protected $_apiUrl;
protected $_storeManager;

public function __construct(
LoggerInterface $logger,
HttpClient $httpClient,
StoreManagerInterface $storeManager,
Data $dataHelper)
{
$this->_logger = $logger;
$this->_httpClient = $httpClient;
$this->_dataHelper = $dataHelper;
$this->_storeManager=$storeManager;

}

public function postInvitation($integrationKey, $storeId, $data = array())
{
$this->_apiUrl = $this->_dataHelper->getGeneralConfigValue('ApiUrl');
$url = $this->_apiUrl . $integrationKey . '/invitation';
$httpRequest = "POST";
$origin = $this->_storeManager->getStore($storeId)->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);
$response = $this->_httpClient->request(
$url,
$httpRequest,
$origin,
$data
);
return $response;
}
}
61 changes: 45 additions & 16 deletions Observer/ConfigObserver.php
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public function __construct(LoggerInterface $logger, Data $helper)
public function execute(EventObserver $observer)
{
$settings = self::getSettings();
$service_url = $this->_helper->getGeneralConfigValue('ApiUrl') . $settings->general->key . '/settings' ;
$service_url = $this->_helper->getGeneralConfigValue('ApiUrl') . $this->_helper->getGeneralConfigValue('key') . '/settings' ;
$curl = curl_init($service_url);
$headers = [
'Content-Type: application/json; charset=utf-8'
Expand All @@ -43,22 +43,51 @@ public function execute(EventObserver $observer)

public function getSettings()
{
$general = new \stdClass();
$general->key = trim($this->_helper->getGeneralConfigValue('key'));;
$globalSettings = new \stdClass();
$globalSettings->source = 'Magento2';
$globalSettings->pluginVersion = $this->_helper->getGeneralConfigValue('ReleaseNumber');
$globalSettings->magentoVersion = 'Magento-'.$this->getVersion();
$id = 0;

$stores = $this->getStores();
foreach ($stores as $store) {
$general = new \stdClass();
$general->key = trim($this->_helper->getGeneralConfigValue('key'));
$general->storeId = $store->getId();
$general->storeCode = $store->getCode();
$general->storeName = $store->getName();
$general->storeTitle = $store->getTitle();
$general->storeActive = $store->isActive();
$general->storeHomeUrl = $store->getCurrentUrl();
$general->websiteId = $store["website_id"];

$trustbox = new \stdClass();
$trustbox->enabled = trim($this->_helper->getTrustBoxConfigValue('trustbox_enable'));
$trustbox->locale = trim($this->_helper->getTrustBoxConfigValue('trustbox_locale'));
$trustbox->template = trim($this->_helper->getTrustBoxConfigValue('trustbox_template'));
$trustbox->position = trim($this->_helper->getTrustBoxConfigValue('trustbox_position'));
$trustbox->paddingx = trim($this->_helper->getTrustBoxConfigValue('trustbox_paddingx'));
$trustbox->paddingy = trim($this->_helper->getTrustBoxConfigValue('trustbox_paddingy'));

$settings = new \stdClass();
$settings->general = $general;
$settings->trustbox = $trustbox;

$globalSettings->$id = $settings;
$id = $id + 1;
}
return $globalSettings;
}

$trustbox = new \stdClass();
$trustbox->enabled = trim($this->_helper->getTrustBoxConfigValue('trustbox_enable'));
$trustbox->locale = trim($this->_helper->getTrustBoxConfigValue('trustbox_locale'));
$trustbox->template = trim($this->_helper->getTrustBoxConfigValue('trustbox_template'));
$trustbox->position = trim($this->_helper->getTrustBoxConfigValue('trustbox_position'));
$trustbox->paddingx = trim($this->_helper->getTrustBoxConfigValue('trustbox_paddingx'));
$trustbox->paddingy = trim($this->_helper->getTrustBoxConfigValue('trustbox_paddingy'));
private function getVersion() {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productMetadata = $objectManager->get('Magento\Framework\App\ProductMetadataInterface');
return $productMetadata->getVersion();
}

$settings = new \stdClass();
$settings->source = 'Magento2';
$settings->general = $general;
$settings->trustbox = $trustbox;

return $settings;
private function getStores() {
$om = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $om->get('Magento\Store\Model\StoreManagerInterface');
return $storeManager->getStores($withDefault = false);
}
}
76 changes: 76 additions & 0 deletions Observer/OrderSaveObserver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php
namespace Trustpilot\Reviews\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer as EventObserver;
use \Psr\Log\LoggerInterface;
use Trustpilot\Reviews\Helper\OrderData;
use Trustpilot\Reviews\Helper\Data;
use Magento\Framework\App\ProductMetadataInterface;
use Trustpilot\Reviews\Helper\TrustpilotHttpClient;

define('__ACCEPTED__', 202);

class OrderSaveObserver implements ObserverInterface
{

protected $_trustpilotHttpClient;
protected $_logger;
protected $_productMetadata;
protected $_orderDataHelper;
protected $_dataHelper;
protected $_storeManager;

public function __construct(
LoggerInterface $logger,
TrustpilotHttpClient $trustpilotHttpClient,
OrderData $orderDataHelper,
ProductMetadataInterface $productMetadata,
Data $dataHelper)
{
$this->_dataHelper = $dataHelper;
$this->_trustpilotHttpClient = $trustpilotHttpClient;
$this->_logger = $logger;
$this->_orderDataHelper = $orderDataHelper;
$this->_productMetadata = $productMetadata;
$this->_version = $this->_dataHelper->getGeneralConfigValue('ReleaseNumber');
}

public function execute(EventObserver $observer)
{
$order = $observer->getEvent()->getOrder();
$storeId = $order->getStoreId();
$orderStatusId = $order->getState();
try {
$key = trim($this->_dataHelper->getGeneralConfigValue('key'));
$data = [
'referenceId' => $order->getRealOrderId(),
'source' => 'Magento-' . $this->_productMetadata->getVersion(),
'pluginVersion' => $this->_version,
'orderStatusId' => $orderStatusId ,
'orderStatusName' => $order->getStatusLabel(),
'hook' => 'sales_order_save_after'
];
if ($orderStatusId == \Magento\Sales\Model\Order::STATE_NEW) {
$data['recipientEmail'] = trim($this->_orderDataHelper->getEmail($order));
$data['recipientName'] = $order->getCustomerName();
$response = $this->_trustpilotHttpClient->postInvitation($key, $storeId, $data);
if ($response['code'] == __ACCEPTED__) {
$products = $this->_orderDataHelper->getProducts($order);
$data['products'] = $products;
$data['productSkus'] = $this->_orderDataHelper->getSkus($products);
$this->_trustpilotHttpClient->postInvitation($key, $storeId, $data);
}
} else {
$data['payloadType'] = 'OrderStatusUpdate';
$this->_trustpilotHttpClient->postInvitation($key, $storeId, $data);
}
return;
} catch (Exception $e) {
$error = ['message' => $e->getMessage()];
$data = ['error' => $error];
$this->_trustpilotHttpClient->postInvitation($key, $storeId, $data);
return;
}
}
}
2 changes: 1 addition & 1 deletion composer.json
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "trustpilot/module-reviews",
"description": "The Trustpilot Review extension makes it simple and easy for merchants to collect reviews from their customers to power their marketing efforts, increase sales conversion, build their online reputation and draw business insights.",
"type": "magento2-module",
"version": "1.0.82",
"version": "1.0.128",
"license": [
"OSL-3.0"
],
Expand Down
3 changes: 3 additions & 0 deletions etc/adminhtml/events.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,7 @@
<event name="admin_system_config_changed_section_trustpilotTrustbox">
<observer name="custom_admin_system_config_changed_section_trustpilotTrustbox" instance="Trustpilot\Reviews\Observer\ConfigObserver"/>
</event>
<event name="admin_system_config_changed_section_trustpilotGeneral">
<observer name="custom_admin_system_config_changed_section_trustpilotTrustbox" instance="Trustpilot\Reviews\Observer\ConfigObserver"/>
</event>
</config>
Loading

0 comments on commit 2fbae65

Please sign in to comment.