Skip to content

Commit

Permalink
Merge pull request #229 from EmicoEcommerce/feat-tw-analytics
Browse files Browse the repository at this point in the history
Feat: tw analytics
  • Loading branch information
ah-net authored Dec 17, 2024
2 parents baeeaa3 + b3dd05b commit 45a8646
Show file tree
Hide file tree
Showing 17 changed files with 626 additions and 20 deletions.
77 changes: 77 additions & 0 deletions Controller/Ajax/Analytics.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

namespace Tweakwise\Magento2Tweakwise\Controller\Ajax;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Tweakwise\Magento2Tweakwise\Model\Client;
use Tweakwise\Magento2Tweakwise\Model\PersonalMerchandisingConfig;
use Magento\Framework\Stdlib\Cookie\PublicCookieMetadata;
use Magento\Framework\Stdlib\CookieManagerInterface;
use Tweakwise\Magento2Tweakwise\Model\Client\RequestFactory;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\ResultInterface;

class Analytics extends Action
{
/**
* Constructor.
*
* @param Context $context
* @param JsonFactory $resultJsonFactory
* @param Client $client
* @param PersonalMerchandisingConfig $config
* @param RequestFactory $requestFactory
*/
public function __construct(
private Context $context,
private JsonFactory $resultJsonFactory,
private Client $client,
private PersonalMerchandisingConfig $config,
private RequestFactory $requestFactory
) {
parent::__construct($context);
}

/**
* @return ResponseInterface|Json|ResultInterface
*/
public function execute()
{
$result = $this->resultJsonFactory->create();
if ($this->config->isAnalyticsEnabled()) {
$type = $this->getRequest()->getParam('type');
$profileKey = $this->config->getProfileKey();

$tweakwiseRequest = $this->requestFactory->create();
$tweakwiseRequest->setProfileKey($profileKey);
$value = $this->getRequest()->getParam('value');

if ($type === 'product') {
$tweakwiseRequest->setParameter('productKey', $value);
$tweakwiseRequest->setPath('pageview');
} elseif ($type === 'search') {
$tweakwiseRequest->setParameter('searchTerm', $value);
$tweakwiseRequest->setPath('search');
}

if (!empty($tweakwiseRequest->getPath())) {
try {
$this->client->request($tweakwiseRequest);
$result->setData(['success' => true]);
} catch (\Exception $e) {
$result->setData(
[
'success' => false,
'message' => $e->getMessage()
]
);
}
}
}

return $result;
}
}
48 changes: 40 additions & 8 deletions Model/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Request as HttpRequest;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\RequestOptions;
use Magento\Framework\Profiler;
use Psr\Http\Message\ResponseInterface;
use SimpleXMLElement;
use GuzzleHttp\Client as HttpClient;
use Magento\Framework\UrlInterface;

class Client
{
Expand Down Expand Up @@ -71,16 +71,14 @@ class Client
* @param Logger $log
* @param ResponseFactory $responseFactory
* @param EndpointManager $endpointManager
* @param Timer $timer
* @param ModuleInformation $moduleInformation
*/
public function __construct(
Config $config,
Logger $log,
ResponseFactory $responseFactory,
EndpointManager $endpointManager,
Timer $timer,
private readonly ModuleInformation $moduleInformation
private UrlInterface $urlBuilder
) {
$this->config = $config;
$this->log = $log;
Expand All @@ -99,8 +97,7 @@ protected function getClient(): HttpClient
RequestOptions::TIMEOUT => self::REQUEST_TIMEOUT,
RequestOptions::HEADERS => [
'user-agent' => $this->config->getUserAgentString(),
'Accept-Encoding' => 'gzip, deflate',
'TWN-Source' => $this->moduleInformation->getModuleVersion(),
'Accept-Encoding' => 'gzip, deflate'
]
];
$this->client = new HttpClient($options);
Expand All @@ -114,10 +111,42 @@ protected function getClient(): HttpClient
* @return HttpRequest
*/
protected function createHttpRequest(Request $tweakwiseRequest): HttpRequest
{
if ($tweakwiseRequest->isPostRequest()) {
return $this->createPostRequest($tweakwiseRequest);
} else {
return $this->createGetRequest($tweakwiseRequest);
}
}

/**
* @param Request $tweakwiseRequest
* @return HttpRequest
*/
protected function createPostRequest(Request $tweakwiseRequest): HttpRequest
{
$path = $tweakwiseRequest->getPath();
$headers = [];

$headers['Content-Type'] = 'application/json';
$headers['Instance-Key'] = $this->config->getGeneralAuthenticationKey();
$body = json_encode($tweakwiseRequest->getParameters());
//post request are used for the analytics api
$uri = $this->urlBuilder->getUrl($tweakwiseRequest->getApiUrl() . '/' . $path);
return new HttpRequest('POST', $uri, $headers, $body);
}

/**
* @param Request $tweakwiseRequest
* @return HttpRequest
*/
protected function createGetRequest(Request $tweakwiseRequest): HttpRequest
{
$path = $tweakwiseRequest->getPath();
$pathSuffix = $tweakwiseRequest->getPathSuffix();

$headers = [];

if ($path === "recommendations/featured") {
if ($this->config->getRecommendationsFeaturedCategory()) {
$tweakwiseRequest->setCategory();
Expand All @@ -138,8 +167,7 @@ protected function createHttpRequest(Request $tweakwiseRequest): HttpRequest
}

$uri = new Uri($url);

return new HttpRequest('GET', $uri);
return new HttpRequest('GET', $uri, $headers);
}

/**
Expand Down Expand Up @@ -208,6 +236,10 @@ public function handleRequestSuccess(
)
);

if ($statusCode === 204) {
return $this->responseFactory->create($tweakwiseRequest, []);
}

if ($statusCode !== 200) {
throw new ApiException(
sprintf(
Expand Down
17 changes: 17 additions & 0 deletions Model/Client/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -326,4 +326,21 @@ public function setProfileKey(string $profileKey)
$this->setParameter('tn_profilekey', $profileKey);
return $this;
}

/**
* @return string|null
*/
public function setParameterArray(string $parameter, array $value)
{
$this->parameters[$parameter] = $value;
return $this;
}

/**
* @return string|null
*/
public function isPostRequest()
{
return false;
}
}
69 changes: 69 additions & 0 deletions Model/Client/Request/AnalyticsRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

/**
* Tweakwise (https://www.tweakwise.com/) - All Rights Reserved
*
* @copyright Copyright (c) 2017-2022 Tweakwise.com B.V. (https://www.tweakwise.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/

namespace Tweakwise\Magento2Tweakwise\Model\Client\Request;

use Tweakwise\Magento2Tweakwise\Model\Client\Request;
use Tweakwise\Magento2Tweakwise\Model\Client\Response\FacetResponse;

class AnalyticsRequest extends Request
{
/**
* @var string
*/
protected $path = '';

protected $apiUrl = 'https://navigator-analytics.tweakwise.com/api';

/**
* @return string
*/
public function isPostRequest()
{
return true;
}

/**
* @return string
*/
public function getApiurl()
{
return $this->apiUrl;
}

/**
* @return void
*/
public function setProfileKey(string $profileKey)
{
$this->setParameter('ProfileKey', $profileKey);
}

/**
* @return void
*/
public function setPath($path)
{
$this->path = $path;
}

/**
* @return string
*/
public function getProfileKey()
{
$profileKey = $this->getCookie($this->config->getPersonalMerchandisingCookieName());
if (!$profileKey) {
$profileKey = $this->generateProfileKey();
$this->setCookie('profileKey', $profileKey);
}

return $profileKey;
}
}
54 changes: 54 additions & 0 deletions Model/Client/Request/PurchaseRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

/**
* Tweakwise (https://www.tweakwise.com/) - All Rights Reserved
*
* @copyright Copyright (c) 2017-2022 Tweakwise.com B.V. (https://www.tweakwise.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/

namespace Tweakwise\Magento2Tweakwise\Model\Client\Request;

use Tweakwise\Magento2Tweakwise\Model\Client\Request;
use Tweakwise\Magento2Tweakwise\Model\Client\Response\FacetResponse;

class PurchaseRequest extends Request
{
/**
* @var string
*/
protected $path = 'purchase';

/**
* @var array
*/
protected $productKeys;

protected $apiUrl = 'https://navigator-analytics.tweakwise.com/api';

/**
* @return true
*/
public function isPostRequest()
{
return true;
}

/**
* @return mixed|string
*/
public function getApiurl()
{
return $this->apiUrl;
}

/**
* @param string $profileKey
*
* @return void
*/
public function setProfileKey(string $profileKey)
{
$this->setParameter('ProfileKey', $profileKey);
}
}
8 changes: 7 additions & 1 deletion Model/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,13 @@ public function isSearchBannersActive(Store $store = null)
*/
public function getPersonalMerchandisingCookieName(Store $store = null)
{
return (string) $this->getStoreConfig('tweakwise/personal_merchandising/cookie_name', $store);
$cookie = $this->getStoreConfig('tweakwise/personal_merchandising/cookie_name', $store);

if (empty($cookie)) {
$cookie = 'tw_analytics';
}

return $cookie;
}

/**
Expand Down
Loading

0 comments on commit 45a8646

Please sign in to comment.