Commit 2a0ccc3d by Krystian Kowalczuk

Initial module

parents
<?php
namespace Benhauer\Salesmanago\Block\Adminhtml\Client;
use \Magento\Backend\Block\Template\Context;
use \Magento\Framework\Registry;
use \Magento\Framework\Data\FormFactory;
use \Magento\Store\Model\System\Store;
use \Magento\Backend\Block\Widget\Form\Generic;
class AccountSettings extends Generic
{
protected $_systemStore;
public function __construct(
Context $context,
Registry $registry,
FormFactory $formFactory,
Store $systemStore,
array $data = []
) {
$this->_systemStore = $systemStore;
parent::__construct($context, $registry, $formFactory, $data);
}
/**
* Init form
*
* @return void
*/
protected function _construct()
{
parent::_construct();
$this->setId('account_settings_form');
$this->setTitle(__('Account Settings'));
}
/**
* Prepare form
*
* @return $this
*/
protected function _prepareForm()
{
// $model = $this->_coreRegistry->registry('mystore_slider');
//
// if ($model->getId()) {
// $model->setData('test', 'female');
// }
$form = $this->_formFactory->create(
['data' =>
[
'id' => 'edit_form',
'action' => $this->getData('action'),
'method' => 'post', 'enctype' => 'multipart/form-data'
]
]
);
$form->setHtmlIdPrefix('mystore_slider_');
$fieldset = $form->addFieldset(
'base_fieldset',
[
'legend' => __('Account Settings'),
'class' => 'fieldset-wide'
]
);
$fieldset->addField(
'slider_title',
'text',
[
'name' => 'slider_title',
'label' => __('Slider Title'),
'title' => __('Slider Title'),
'value' => 'test value',
'required' => true
]
);
if (/*$model->getSliderId()*/ true) {
$fieldset->addField(
'slider_id',
'hidden',
[
'name' => 'slider_id'
]
);
}
$fieldset->addField(
'slider_title_button',
'button',
[
'name' => 'slider_title_save',
'label' => __('Save'),
'class' => 'save primary',
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'save']],
'form-role' => 'save',
],
'sort_order' => 90,
]
);
$fieldset->addField(
'url',
'text',
[
'name' => 'url',
'label' => __('Slider URL'),
'title' => __('Slider URL'),
'required' => true,
'class' => 'validate-xml-identifier'
]
);
$fieldset->addField(
'image',
'image',
[
'name' => 'image',
'label' => __('Slider Image'),
'title' => __('Slider Image'),
'required' => true
]
);
$fieldset->addField(
'test',
'radios',
[
'label' => __('test'),
'title' => __('test'),
'name' => 'test',
'required' => true,
'values' => array(
array('value'=>'male','label'=>'Male'),
array('value'=>'female','label'=>'Female'),
)
]
);
/**
* Check is single store mode
*/
if (!$this->_storeManager->isSingleStoreMode()) {
$field = $fieldset->addField(
'store_id',
'multiselect',
[
'name' => 'stores[]',
'label' => __('Store View'),
'title' => __('Store View'),
'required' => true,
'values' => $this->_systemStore->getStoreValuesForForm(false, true)
]
);
$renderer = $this->getLayout()->createBlock(
'Magento\Backend\Block\Store\Switcher\Form\Renderer\Fieldset\Element'
);
$field->setRenderer($renderer);
} else {
$fieldset->addField(
'store_id',
'hidden',
['name' => 'stores[]', 'value' => $this->_storeManager->getStore(true)->getId()]
);
$model->setStoreId($this->_storeManager->getStore(true)->getId());
}
$fieldset->addField(
'is_active',
'select',
[
'label' => __('Status'),
'title' => __('Status'),
'name' => 'is_active',
'required' => true,
'options' => ['1' => __('Enabled'), '0' => __('Disabled')]
]
);
// $form->setValues($model->getData());
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
<?php
namespace Benhauer\Salesmanago\Block\Adminhtml\Client;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
/**
* Class ResetButton
*/
class ConfigButton extends GenericButton implements ButtonProviderInterface
{
/**
* @return array
*/
public function getButtonData()
{
return [
'label' => __('Plugin Configuration'),
'class' => 'reset',
'on_click' => sprintf("location.href = '%s';", $this->getBackUrl()),
'sort_order' => 30
];
}
public function getBackUrl()
{
return $this->getUrl('*/*/index/smconfiguration/true');
}
}
<?php
namespace Benhauer\Salesmanago\Block\Adminhtml\Client;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
/**
* Class ResetButton
*/
class CreateCreateButton extends GenericButton implements ButtonProviderInterface
{
/**
* @return array
*/
public function getButtonData()
{
return [
'label' => __('Create'),
'class' => 'save primary',
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'save']],
'form-role' => 'save',
],
'sort_order' => 90,
];
}
}
<?php
namespace Benhauer\Salesmanago\Block\Adminhtml\Client;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class CreateLoginButton extends GenericButton implements ButtonProviderInterface
{
public function getButtonData()
{
return [
'label' => __('Go to Login'),
'class' => 'reset',
'on_click' => sprintf("location.href = '%s';", $this->getBackUrl()),
'sort_order' => 30
];
}
public function getBackUrl()
{
return $this->getUrl('*/*/login');
}
}
<?php
namespace Benhauer\Salesmanago\Block\Adminhtml\Client;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class ExportButton extends GenericButton implements ButtonProviderInterface
{
/**
* @return array
*/
public function getButtonData()
{
return [
'label' => __('Export'),
'class' => 'save primary',
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'save']],
'form-role' => 'save',
],
'sort_order' => 90,
];
}
}
<?php
namespace Benhauer\Salesmanago\Block\Adminhtml\Client;
use Magento\Search\Controller\RegistryConstants;
/**
* Class GenericButton
*/
class GenericButton
{
/**
* Url Builder
*
* @var \Magento\Framework\UrlInterface
*/
protected $urlBuilder;
/**
* Registry
*
* @var \Magento\Framework\Registry
*/
protected $registry;
protected $request;
/**
* Constructor
*
* @param \Magento\Backend\Block\Widget\Context $context
* @param \Magento\Framework\Registry $registry
*/
public function __construct(
\Magento\Backend\Block\Widget\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\App\Request\Http $request
) {
$this->urlBuilder = $context->getUrlBuilder();
$this->registry = $registry;
$this->request = $request;
}
/**
* Return the synonyms group Id.
*
* @return int|null
*/
public function getId()
{
$contact = $this->registry->registry('contact');
return $contact ? $contact->getId() : null;
}
/**
* Generate url by route and parameters
*
* @param string $route
* @param array $params
* @return string
*/
public function getUrl($route = '', $params = [])
{
return $this->urlBuilder->getUrl($route, $params);
}
}
<?php
namespace Benhauer\Salesmanago\Block\Adminhtml\Client;
use Magento\Config\Block\System\Config\Tabs;
class IndexMenu extends Tabs
{
protected $_template = 'Benhauer_Salesmanago::plugin_menu.phtml';
protected $tabs;
protected $store = 0;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Config\Model\Config\Structure $configStructure,
\Magento\Backend\Helper\Data $backendHelper,
array $data = []
) {
$this->_backendHelper = $backendHelper;
parent::__construct($context, $configStructure, $backendHelper, $data);
$this->setId('salesmanago_config_tabs');
$this->setTitle(__('Configuration '));
}
public function getMenuItems()
{
return [
['item' => 'index', 'class' => '', 'url' => '*/*/index', 'label' => 'Welcome', 'active' => false],
['item' => 'export', 'class' => '', 'url' => '*/*/exportdata', 'label' => 'Export Data', 'active' => false]
];
}
public function addFilter(\Magento\Framework\Api\Filter $filter)
{
return null;
}
public function isItemActive($item)
{
if (strpos($this->getCurrentUrl(), str_replace('*/*', '', $item['url'])) !== false) {
return true;
} else {
return false;
}
}
public function getUrl($route = '', $params = [])
{
if ($store = $this->_request->getParam('store')) {
$params = array_merge($params, ['store' => $store]);
}
return $this->_urlBuilder->getUrl($route, $params);
}
}
<?php
namespace Benhauer\Salesmanago\Block\Adminhtml\Client;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
/**
* Class ResetButton
*/
class LoginCreateButton extends GenericButton implements ButtonProviderInterface
{
/**
* @return array
*/
public function getButtonData()
{
return [
'label' => __('Go to Create Account'),
'class' => 'reset',
'on_click' => sprintf("location.href = '%s';", $this->getBackUrl()),
'sort_order' => 30
];
}
public function getBackUrl()
{
return $this->getUrl('*/*/create');
}
}
<?php
namespace Benhauer\Salesmanago\Block\Adminhtml\Client;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class LoginLoginButton extends GenericButton implements ButtonProviderInterface
{
/**
* @return array
*/
public function getButtonData()
{
return [
'label' => __('Login'),
'class' => 'save primary',
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'save']],
'form-role' => 'save',
],
'sort_order' => 90,
];
}
}
<?php
namespace Benhauer\Salesmanago\Block\Adminhtml\Client;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class LogoutButton extends GenericButton implements ButtonProviderInterface
{
/**
* @return array
*/
public function getButtonData()
{
return [
'label' => __('Logout'),
'class' => 'action-secondary',
'on_click' => sprintf("location.href = '%s';", $this->getLogoutUrl()),
'sort_order' => 30
];
}
public function getLogoutUrl()
{
$storeId = $this->request->getParam('store');
if ($storeId) {
return $this->getUrl('*/*/logout/store/'.$storeId);
}
return $this->getUrl('*/*/logout');
}
}
<?php
namespace Benhauer\Salesmanago\Block\Adminhtml\Client;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class SaveButton extends GenericButton implements ButtonProviderInterface
{
/**
* @return array
*/
public function getButtonData()
{
return [
'label' => __('Save'),
'class' => 'save primary',
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'save']],
'form-role' => 'save',
],
'sort_order' => 90,
];
}
}
<?php
namespace Benhauer\Salesmanago\Block\Adminhtml\Client;
use \Benhauer\Salesmanago\Helper\Metrix;
use \Magento\Backend\Block\Template\Context;
use \Magento\Backend\Block\Widget\Form\Generic;
use \Magento\Framework\Data\FormFactory;
use \Magento\Framework\Registry;
use \Magento\Store\Model\System\Store;
use \Benhauer\Salesmanago\Model\SM\Rest as SmModel;
use \Benhauer\Salesmanago\Helper\Config as PluginConfig;
class WelcomeForm extends Generic
{
protected $_systemStore;
protected $_metrix;
public $PluginConfig;
public $model;
public $contactCount = 0;
public $planType = '';
public $versionType = '';
public $pluginVersion = '1.0.0';
public function __construct(
Context $context,
Registry $registry,
FormFactory $formFactory,
Store $systemStore,
SmModel $model,
Metrix $metrix,
array $data = []
) {
$this->_systemStore = $systemStore;
$this->model = $model;
$this->_metrix = $metrix;
parent::__construct($context, $registry, $formFactory, $data);
}
/**
* Init form
*
* @return void
*/
protected function _construct() {
parent::_construct();
$this->setId('welcome_form');
$this->setTitle(__('Welcome'));
$this->getAccountTypeData();
}
public function getAccountTypeData()
{
$data = $this->model->getAccountType();
$this->versionType = isset($data['versionType']) ? $data['versionType'] : '';
$this->planType = isset($data['planType']) ? $data['planType'] : '';
$this->contactCount = isset($data['contactCount']) ? $data['contactCount'] : '';
$this->pluginVersion = PluginConfig::getPluginVersion();
}
public function addFilter(\Magento\Framework\Api\Filter $filter)
{
return null;
}
}
<?php
namespace Benhauer\Salesmanago\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;
class Disable extends \Magento\Config\Block\System\Config\Form\Field
{
protected function _getElementHtml(AbstractElement $element)
{
$element->setData('readonly', 1);
return $element->getElementHtml();
}
}
<?php
namespace Benhauer\Salesmanago\Block\Tracking;
use \Magento\Framework\View\Element\Template;
use \Magento\Framework\View\Element\Template\Context;
use \Magento\Store\Model\StoreManagerInterface;
use \SALESmanago\Provider\UserProvider;
use \SALESmanago\Factories\FactoryOrganizer;
use \Benhauer\Salesmanago\Model\Hooks as HooksModel;
class Monitoring extends Template
{
public $hooksModel;
public $trackingScript;
public $factoryOrganizer;
public $storeManager;
public function __construct(
Context $context,
HooksModel $hooksModel,
FactoryOrganizer $factoryOrganizer
) {
$data = [];
parent::__construct($context, $data);
$this->hooksModel = $hooksModel;
$this->factoryOrganizer = $factoryOrganizer;
$this->storeManager = $context->getStoreManager();
$this->setStoreViewForModel();
$this->getMonitoringCode();
}
/**
* Sets $this->trackingScript prepare monitorig script;
* @return string - monitoring scrip
*/
public function getMonitoringCode()
{
$userData = $this->hooksModel->getUserSettings(null);
if (isset($userData[HooksModel::CLIENT_ID])
&& !empty($userData[HooksModel::CLIENT_ID])
) {
$userAccount = $this->factoryOrganizer->getInst(
FactoryOrganizer::USER_ACCOUNT_C,
UserProvider::initSettingsUser(
$this->hooksModel
),
$this->hooksModel
);
$webPush = (isset($userData[HooksModel::WEB_PUSH]['code'])
&& !empty($userData[HooksModel::WEB_PUSH]['code']))
? $userData[HooksModel::WEB_PUSH]['code']
: '';
$trackingScript = $userAccount->createMonitorVisitorsCode(
$webPush
);
return $this->trackingScript = $trackingScript;
} else {
return $this->trackingScript = '';
}
}
/**
* Set store view id from $this->requestPrams to each model;
*/
public function setStoreViewForModel()
{
$storeId = $this->storeManager->getStore()->getId();
if ($storeId != null && $storeId != 0) {
$this->hooksModel->setScopeId($storeId);
$this->hooksModel->setScope('stores');
}
}
}
SALESmanago plugin for Magento2
-------------------------------
Version 3.1.0 02.09.2020
- fix syncRule;
- fix newsletter subscribers statuses;
- fix Go to configuration button
Version 3.0.9-p2 19.08.2020
- fix newsletter subscription;
Version 3.0.9 06.08.2020
- fix callback optin/optout - when main config is logout callback not working
- fix sending emails to contact after export
- fix miss province after export
--
Version 3.0.9-RC1 26.07.2020
- fix callback optin/optout - when main config is
logout callback not working
--
Version 3.0.8 16.07.2020
- fix optin/optout when confirm subscribe from url
--
Version 3.0.7-p1 18.06.2020
- add etc/acl.xml
- change TEST_MAIL value - the error concerns changes on the salesmanago side
- remove pageFactory from In and Out
- add guest purchase tag
- do not send the newsletter tag when the newsletter is not confirmed
- endpoint salesmanago.es
--
Version 3.0.6 21.02.2020
- adjust to magento 2.1.x;
- fix optout contact with guest purchase upsert;
- fix order cancelling;
--
Version 3.0.6-RC1 29.01.2020
- rename namespaces for Observers class;
- adjust to magento 2.1.x;
- fix optout contact with guest purchase upsert;
--
Version 3.0.5-p1 22.01.2020
- remove sales_order_save_after duplicate hook for OrderStatusChanged;
- remove checkout_submit_all_after duplicate hook for KlarnaCheckout;
--
Version 3.0.5 23.12.2019
- change namespaces for AbstractModel;
- change logo;
--
Version 3.0.4 07.11.2019
- add new purchase events configuration;
- add metrix;
- minor bug fixes;
--
Version 3.0.3 07.10.2019
- UI fixes
- minor bug fixes
--
Version 3.0.2 Refreshed 12.09.2019
- fix welcome ui component error;
--
Version 3.0.1 Refreshed 08.09.2019
- fix exports;
--
Version 3.0.0 Refreshed 14.08.2019
- views upgrade to magento views;
--
Version 2.1.7 Refreshed 14.08.2019
- add new api method;
--
Version 2.1.6 Refreshed 30.07.2019
- add cancel event;
- views update;
--
Version 2.1.5 Refreshed 25.07.2019
- fix CART for new API;
--
Version 2.1.4 Refreshed 24.07.2019
- new API;
--
Version 2.1.3 Refreshed 05.07.2019
- refactoring tags manager;
--
Version 2.1.2 Refreshed 07.06.2019
- refactoring for magento 2.1.6;
--
Version 2.1.1 Refreshed 07.06.2019
- fix contact create;
--
Version 2.1.0 Refreshed 27.04.2019
- add store views;
- add order statuses/types;
- add Klarna-payment catch purchase;
- add storeId to each store views;
--
Version 2.0.7 Refreshed 19.04.2019
- fix newsletter callback;
--
Version 2.0.6 Refreshed 10.04.2019
- update service fix synchronize rule;
--
Version 2.0.5 Refreshed 18.03.2019
- add double opt in;
--
Version 2.0.4 Refreshed 24.01.2019
- add error handling;
- add advanced exports;
- security fixes;
--
Version 2.0.3 Refreshed 08.12.2018
- add error handling for observer;
--
Version 2.0.2 Refreshed 03.12.2018
- added Tagger;
- fix tags repeat;
--
Version 2.0.1 Refreshed 09.10.2018
- updated admin views;
- added synchronize rule to sychronize contact;
--
Version 2.0.0 Refreshed 06.09.2018
- new sso core;
--
Version 1.0.4 Refreshed 12.03.2018
- Remove underscore from variables;
- Clear spaces;
- Use short array syntactics;
- Add comments;
- Remove clear SQL questions;
- Methods refactor;
- Remove logic from views files;
--
Version 1.0.3 Refreshed 30.03.2018
- Added StoreView tag when client upsert;
- Added CallBacks for optin and optout client;
--
Version 1.0.2 Refreshed 20.03.2018
- newsletter subscription fix
--
Version 1.0.1 Refreshed 09.01.2018
- Fixed package's name in composer ad registration.php + xml's
--
Version 1.0.0 Refreshed 06.10.2017
- New structure for marketplace and composer
--
Version 1.0.0 Released 15.02.2017
Integration Scope:
- Synchronize contact after:
- Registration,
- Login,
- Purchase without register (as a guest),
- Address modification,
- Newsletter subscription modification,
- Synchronized external events:
- Cart ( For signed up members and not - but with cookie )
- Purchase ( For signed up members and guests )
- WishList ( For signed up members)
- Adding "smclient" cookie:
- For every client synchronization,
- Automatic Sm script adding,
- Standard integration fields, js working timeout and tags fields:
- Newsletter tags,
- Registration tags,
- Purchase tags,
- Plugin translation for:
- English,
- German,
- Spanish,
- Polish,
- Russian,
Tested on:
- Magento CE: 2.1.2,
- Magento CE: 2.1.4,
- Magento CE: 2.3.0
<?php
namespace Benhauer\Salesmanago\Controller\Adminhtml\Config;
use Magento\Backend\App\Action;
use Magento\Framework\Message\ManagerInterface;
use SALESmanago\Factories\FactoryOrganizer;
use SALESmanago\Provider\UserProvider;
use Benhauer\Salesmanago\Model\Create as CreateModel;
use Benhauer\Salesmanago\Helper\Config as ConfigHelper;
class Create extends \Magento\Backend\App\Action
{
protected $model;
protected $config;
protected $context;
protected $storeId = 0;
protected $scope = 'default';
protected $messageManager;
protected $storeManager;
public function __construct(
Action\Context $context,
CreateModel $model,
FactoryOrganizer $factoryOrganizer,
ConfigHelper $config,
\Magento\Store\Model\StoreManagerInterface $storeManager
) {
parent::__construct($context);
$this->model = $model;
$this->factoryOrganizer = $factoryOrganizer;
$this->config = $config;
$this->messageManager = $context->getMessageManager();
$this->storeManager = $storeManager;
}
public function execute()
{
if ($loadByStoreCheck = $this->loadByStoreCheck()) {
return $loadByStoreCheck;
}
$clientCreateData = $this->getRequest()->getParam('client');
if ($clientCreateData['username']) {
$this->createClient($clientCreateData);
}
$this->_view->loadLayout();
$this->_view->renderLayout();
}
public function createClient($clientCreateData)
{
$bhrSso = $this->config->getBhrSso();
$connectSm = $this->factoryOrganizer->getInst(
FactoryOrganizer::CREATE_ACCOUNT_C,
UserProvider::settingsAccount(),
$this->model
);
$consentDetails = $this->consentDetailsCheck($clientCreateData);
if ($consentDetails) {
$response = $connectSm->createAccount(
[
'email' => htmlspecialchars($clientCreateData['username']),
'password' => htmlspecialchars($clientCreateData['password']),
'lang' => htmlspecialchars($bhrSso['lang']),
'name' => htmlspecialchars($clientCreateData['name']),
'phone' => htmlspecialchars($clientCreateData['phone']),
'website' => $this->storeManager->getStore($this->storeId)->getBaseUrl(),
'consentDetails' => $consentDetails,
'platform' => $bhrSso['platform'],
],
['0', '1', '2', '3']
);
if (!$response['success']) {
$this->messageManager->addError(__("{$response['message']}"));
return $this->_redirect('*/*/create');
} elseif ($response['success']) {
$this->model->setScopeCheckId($this->storeId);
$this->messageManager->addSuccess(__("Success"));
return $this->_redirect('*/*/index');
} else {
$this->messageManager->addError(__("Error 0"));
return $this->_redirect('*/*/create');
}
} else {
$this
->messageManager
->addErrorMessage(__("To create SALESmanago account you must accept our terms and conditions and marketing consent"));
}
}
public function loadByStoreCheck()
{
$this->storeId = $this->getRequest()->getParam('store');
if ($this->storeId == null) {
$this->storeId = 0;
$this->scope = 'default';
}
if ($this->storeId != null) {
$this->model
->setScopeId($this->storeId)
->setScope($this->scope);
}
if (($this->storeId || $this->storeId === 0)
&& $this->model->isPluginConfActive()
) {
return $this->redirectTo();
}
return false;
}
public function consentDetailsCheck($clientCreateData)
{
$consentDetails = [];
if (isset($clientCreateData['zgoda_eng_przetwarzanie'])
&& $clientCreateData['zgoda_eng_przetwarzanie'] != 0) {
$consentDetails[] = [
'consentName' => 'ZGODA_ENG_PRZETWARZANIE',
'consentAccept' => true,
];
}
if (isset($clientCreateData['zgoda_eng_handlowa'])
&& $clientCreateData['zgoda_eng_handlowa'] != 0) {
$consentDetails[] = [
'consentName' => 'ZGODA_ENG_HANDLOWA',
'consentAccept' => true,
];
}
if (!empty($consentDetails) && count($consentDetails)) {
$consentDetails[] = [
'consentName' => 'ZGODA_ENG_OSOBOWE_REGULAMIN',
'consentAccept' => true,
];
return $consentDetails;
}
return false;
}
public function redirectTo($redirectTo = 'login')
{
$store = '';
if (!empty($this->storeId)) {
$store = '/store/'.$this->storeId;
}
return $this->_redirect('*/*/'.$redirectTo.$store);
}
}
<?php
namespace Benhauer\Salesmanago\Controller\Adminhtml\Config;
use \Benhauer\Salesmanago\Exception\SalesManagoException;
use \Benhauer\Salesmanago\Exception\UserAccessException;
use \SALESmanago\Factories\FactoryOrganizer;
use \SALESmanago\Provider\UserProvider;
class CronExportData extends \Benhauer\Salesmanago\Controller\Adminhtml\Config\ExportData
{
/**
* from: 2019-10-01 00:00:01
* to: 2019-10-16 23:59:59
*/
public function setAdvancedExport($from = null, $to = null, $advancedExport = true)
{
$this->advancedExport = $advancedExport;
if ($this->advancedExport
&& !empty($from)
&& !empty($to)
) {
$this->exportDateRange = [
'from' => $from,
'to' => $to
];
}
return $this;
}
public function setEvents()
{
try {
$userAccount = $this->factoryOrganizer->getInst(
FactoryOrganizer::USER_ACCOUNT_C,
UserProvider::initSettingsUser(
$this->model
),
$this->model
);
$collectSize = $this->getCountOrders();
$collection = $this->getOrdersCollection();
$loops = intval(ceil($collectSize / self::EXP_PACKAGE_SIZE));
$collection->setPageSize(self::EXP_PACKAGE_SIZE);
for ($i = 0; $i < $loops; $i++) {
$collection->setCurPage($i);
$orders = $collection->setOrder('entity_id', 'DESC');
$package = $this->exportModel->prepareOrdersToExport($orders);
$userAccount->exportContactExtEvents($package);
}
return __("Success").' '.$collectSize. ' events was exported';
} catch (UserAccessException $e) {
$this->logger->critical($e->getUserMessage());
$this->messageManager->addError($e->getUserMessage());
} catch (SalesManagoException $e) {
$this->logger->critical($e->getSalesManagoMessage());
$this->messageManager->addError($e->getUserMessage());
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
$this->messageManager->addError($e->getMessage());
}
}
/**
* Filter Order collection depends on $this->exportDateRange, $this->storeId
* @return \Magento\Sales\Model\ResourceModel\Order\Collection $orderFactory
*/
protected function getOrdersCollection()
{
try {
$orderFactory = $this->orderFactory->create();
if (isset($this->exportDateRange)) {
$orderFactory->addFieldToFilter(
'created_at',
[
'from' => $this->exportDateRange['from'],
'to' => $this->exportDateRange['to'],
'date' => true
]
);
}
$orderFactory->addFieldToSelect(['*']);
return $orderFactory;
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
$this->messageManager->addError($e->getMessage());
}
}
}
\ No newline at end of file
<?php
namespace Benhauer\Salesmanago\Controller\Adminhtml\Config;
use Benhauer\Salesmanago\Helper\Config as ConfigHelper;
use Magento\Backend\App\Action;
use Magento\Framework\Message\ManagerInterface;
use SALESmanago\Factories\FactoryOrganizer;
use SALESmanago\Provider\UserProvider;
use Benhauer\Salesmanago\Model\User as UserModel;
class Index extends \Magento\Backend\App\Action
{
public $storeManager;
protected $storeId;
protected $scope = 'default';
public function __construct(
Action\Context $context,
UserModel $model,
FactoryOrganizer $factoryOrganizer,
ConfigHelper $config
) {
parent::__construct($context);
$this->model = $model;
$this->factoryOrganizer = $factoryOrganizer;
}
public function execute()
{
$smGoToConfigutation = $this->getRequest()->getParam('smconfiguration');
if ($this->getRequest()->getParam('smconfiguration') == "true") {
return $this->_redirect('adminhtml/system_config/edit/section/salesmanago_account_settings');
}
if ($loadByStoreCheck = $this->loadByStoreCheck()) {
return $loadByStoreCheck;
}
if ($this->model->isPluginConfActive()) {
$this->_view->loadLayout();
$this->_view->renderLayout();
} else {
return $this->_redirect('*/*/login');
}
}
public function loadByStoreCheck()
{
$this->storeId = $this->getRequest()->getParam('store');
if ($this->storeId == null) {
$this->storeId = 0;
$this->scope = 'default';
}
if ($this->storeId) {
$this->model
->setScopeId($this->storeId);
}
if (($this->storeId || $this->storeId === 0)
&& !$this->model->isPluginConfActive()
) {
return $this->redirectTo();
}
return false;
}
public function redirectTo($redirectTo = 'login')
{
$store = '';
if (!empty($this->storeId)) {
$store = '/store/'.$this->storeId;
}
return $this->_redirect('*/*/'.$redirectTo.$store);
}
}
<?php
namespace Benhauer\Salesmanago\Controller\Adminhtml\Config;
use Magento\Backend\App\Action;
use Magento\Framework\Message\ManagerInterface;
use SALESmanago\Factories\FactoryOrganizer;
use SALESmanago\Provider\UserProvider;
use \Benhauer\Salesmanago\Model\User as UserModel;
use \Benhauer\Salesmanago\Model\Login as LoginModel;
class Login extends \Magento\Backend\App\Action
{
protected $factoryOrganizer;
protected $model;
protected $context;
protected $storeId = 0;
protected $scope = 'default';
protected $messageManager;
public function __construct(
Action\Context $context,
FactoryOrganizer $factoryOrganizer,
LoginModel $model
) {
parent::__construct($context);
$this->model = $model;
$this->factoryOrganizer = $factoryOrganizer;
$this->messageManager = $context->getMessageManager();
}
public function execute()
{
if ($loadByStoreCheck = $this->loadByStoreCheck()) {
return $loadByStoreCheck;
}
$clientLoginData = $this->getRequest()->getParam('client');
if($clientLoginData['username']) {
return $this->loginClient($clientLoginData);
}
$this->_view->loadLayout();
$this->_view->renderLayout();
}
public function loginClient($clientLoginData)
{
$loginAccount = $this->factoryOrganizer->getInst(
FactoryOrganizer::LOGIN_ACCOUNT_C,
UserProvider::settingsUser(),
$this->model
);
$response = $loginAccount->loginUser($clientLoginData);
if (!$response['success']) {
$this->messageManager->addError(__("{$response['message']}"));
return $this->_redirect('*/*/login');
} elseif($response['success']) {
$this->model->setScopeCheckId($this->storeId);
$this->messageManager->addSuccess(__("Success"));
$this->redirectTo();
} else {
$this->messageManager->addError(__("Error 0"));
return $this->_redirect('*/*/login');
}
}
public function loadByStoreCheck()
{
$this->storeId = $this->getRequest()->getParam('store');
if ($this->storeId == null || $this->storeId == 0) {
$this->storeId = 0;
$this->scope = 'default';
}
if ($this->storeId != null) {
$this->model
->setScopeId($this->storeId)
->setScope($this->scope);
}
if (($this->storeId || $this->storeId === 0)
&& $this->model->isPluginConfActive()
) {
return $this->redirectTo();
}
return false;
}
public function redirectTo($redirectTo = 'index')
{
$store = '';
if (!empty($this->storeId)) {
$store = '/store/'.$this->storeId ;
}
return $this->_redirect('*/*/'.$redirectTo.$store);
}
}
<?php
namespace Benhauer\Salesmanago\Controller\Adminhtml\Config;
use Benhauer\Salesmanago\Helper\Config as ConfigHelper;
use Magento\Backend\App\Action;
use Magento\Framework\Message\ManagerInterface;
use SALESmanago\Factories\FactoryOrganizer;
use SALESmanago\Provider\UserProvider;
use Benhauer\Salesmanago\Model\User as UserModel;
class Logout extends \Magento\Backend\App\Action
{
protected $storeId = 0;
protected $scope = 'default';
protected $messageManager;
public function __construct(
Action\Context $context,
UserModel $model,
FactoryOrganizer $factoryOrganizer,
ConfigHelper $config
) {
parent::__construct($context);
$this->model = $model;
$this->config = $config;
$this->factoryOrganizer = $factoryOrganizer;
$this->messageManager = $context->getMessageManager();
}
public function execute()
{
$this->storeResolver();
if ($this->model->removePluginConfiguration()) {
$this->messageManager->addSuccess(__("Success"));
return $this->redirectTo('login');
}
$this->messageManager->addError(__("Something went wrong"));
return $this->redirectTo('index');
}
public function redirectTo($redirectTo = 'index')
{
$store = '';
if (!empty($this->storeId) && $this->storeId != 0) {
$store = '/store/'.$this->storeId ;
}
return $this->_redirect('*/*/'.$redirectTo.$store);
}
public function storeResolver()
{
$this->storeId = $this->getRequest()->getParam('store');
if ($this->storeId) {
$this->model->setScopeId($this->storeId);
$this->model->setScope('stores');
}
return $this;
}
}
<?php
namespace Benhauer\Salesmanago\Controller\Newsletter;
use \Magento\Checkout\Model\Session;
use \Magento\Newsletter\Model\Subscriber;
use \Magento\Framework\Controller\Result\JsonFactory;
use \Benhauer\Salesmanago\Model\Hooks;
use \Benhauer\Salesmanago\Model\AbstractModel;
abstract class Callback extends \Magento\Framework\App\Action\Action
{
public $pageFactory;
public $helper;
public $subscriber;
public $model;
public $rJsonFactory;
const TEST_MAIL = 'callback.test@salesmanago.com';
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $pageFactory,
JsonFactory $resultJsonFactory,
Subscriber $subscriber,
Hooks $model,
Session $session
) {
parent::__construct($context);
$this->pageFactory = $pageFactory;
$this->subscriber = $subscriber;
$this->model = $model;
$this->rJsonFactory = $resultJsonFactory->create();
$this->session = $session;
}
abstract public function execute();
/**
* Set contact status to subscribed;
*/
public function optIn()
{
$params = $this->getRequest()->getParams();
if ($this->isItTestCallback($params)) {
return $this->response('optIn', true);
}
if (!$this->parametersChecker($params)) {
return $this->response('', false, 'Does email exist?');
}
$checkSubscriber = $this->subscriber->loadByEmail($params['email']);
if (in_array($checkSubscriber->getStatus(),
[
Subscriber::STATUS_NOT_ACTIVE,
Subscriber::STATUS_UNCONFIRMED,
Subscriber::STATUS_UNSUBSCRIBED
])
) {
$this->session->setProgrammaticallyNewsletterStatus(true);
$checkSubscriber->setStatus(Subscriber::STATUS_SUBSCRIBED)->save();
return $this->response('optIn', true);
}
$this->_redirect('/');
}
/**
* Set contact status to unsubscribed
*/
public function optOut()
{
$params = $this->getRequest()->getParams();
if ($this->isItTestCallback($params)) {
return $this->response('optOut', true);
}
if (!$this->parametersChecker($params)) {
return $this->response('', false, 'Does email exist?');
}
$checkSubscriber = $this->subscriber->loadByEmail($params['email']);
if ($checkSubscriber->isSubscribed() || $checkSubscriber->getStatus() == 4 ) {
$this->session->setProgrammaticallyNewsletterStatus(true);
$checkSubscriber->unsubscribe();
return $this->response('optOut', true);
}
$this->_redirect('/');
}
/**
* Check if request is valid
* @param array - request
* @return boolean
*/
public function parametersChecker($params)
{
$clientsIds = $this->model->getClientsIds();
if (!isset($params['email']) && empty($params['email'])) {
return false;
}
if (!isset($params['key']) || empty($params['email'])) {
return false;
}
$clientId = $this->model->getClientId();
if (empty($clientId) && empty($clientsIds)) {
return false;
}
if (count($clientsIds) != 1 || !empty($clientsIds)) {
foreach ($clientsIds as $mClientId) {
$localSha = sha1($params['email'] . $mClientId);
if ($localSha == $params['key']) {
return true;
}
}
}
$localSha = sha1($params['email'] . $clientId);
if ($localSha != $params['key']) {
return false;
}
return true;
}
/**
* Check if client send test callback
* @param array - request
* @return boolean
*/
public function isItTestCallback($params)
{
if ($params['email'] == self::TEST_MAIL
&& $this->parametersChecker($params)
) {
return true;
}
return false;
}
/**
* Return $this->rJsonFactory->data
* @param string $inOut = 'optIn' || 'optOut'
* @param success boolean
* @param mixed $info - (string || null)
*/
public function response($inOut, $success = false, $info = null)
{
return $this->rJsonFactory->setData(
[
'success' => $success,
'message' => ($success) ? __("Contact is {$inOut}") : $info
]
);
}
}
<?php
namespace Benhauer\Salesmanago\Controller\Newsletter;
use Benhauer\Salesmanago\Controller\Newsletter\Callback;
class In extends Callback
{
public function execute()
{
return $this->optIn();
}
}
<?php
namespace Benhauer\Salesmanago\Controller\Newsletter;
class Out extends Callback
{
public function execute()
{
return $this->optOut();
}
}
<?php
namespace Benhauer\Salesmanago\Cron;
use \Magento\Framework\App\Console;
use \Magento\Framework\App\Cron;
use \Magento\Framework\App\State;
use \Magento\Framework\ObjectManagerInterface;
use \Psr\Log\LoggerInterface;
use \Benhauer\Salesmanago\Model\Config\PurchasesConfig;
use \Benhauer\Salesmanago\Controller\Adminhtml\Config\CronExportData;
class Purchase extends Cron
{
protected $logger;
protected $purchasesConfig;
protected $cronExportData;
protected $date;
public function __construct(
State $state,
Console\Request $request,
Console\Response $response,
ObjectManagerInterface $objectManager,
PurchasesConfig $purchasesConfig,
LoggerInterface $logger,
CronExportData $cronExportData,
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $date,
array $parameters = []
) {
parent::__construct($state, $request, $response, $objectManager, $parameters);
$this->logger = $logger;
$this->purchasesConfig = $purchasesConfig;
$this->cronExportData = $cronExportData;
$this->date = $date;
}
public function execute()
{
if (!$this->purchasesConfig->isCronActive()) {
return false;
}
$confTimeHours = $this->purchasesConfig->getConfig();
$intervalUnixTime = $confTimeHours*60*60;
$fromTime = time()-$intervalUnixTime;
$fromTime = date('Y-m-d H:i:s', $fromTime);
$toTime = time();
$toTime = date('Y-m-d H:i:s', $toTime);
$response = $this->cronExportData
->setAdvancedExport($fromTime, $toTime)
->setEvents();
$this->logger->info($response);
}
}
<?php
namespace Benhauer\Salesmanago\Exception;
use Throwable;
class AccountActiveException extends \Exception
{
protected $redirect;
public function __construct($message = "", $code = 0, $redirect = "", Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
$this->redirect = $redirect;
}
/**
* @return string
*/
public function getRedirect()
{
return $this->redirect;
}
public function getExceptionMessage()
{
$error = array(
'success' => false,
'code' => $this->getCode(),
'redirect' => $this->getRedirect(),
'message' => htmlspecialchars($this->getMessage())
);
return $error;
}
}
<?php
namespace Benhauer\Salesmanago\Exception;
class Exception extends \Exception
{
}
<?php
namespace Benhauer\Salesmanago\Exception;
class SalesManagoError
{
protected static function resolveErrorCode($message)
{
$errorMessage = array(
'User not authenticated',
'Api key not specified',
'Token not specified',
'Not authorized',
'Integration failed',
'Not authenticated',
'Not authenticated, not owner specified',
'Not authenticated, invalid owner',
'Authorization failed. Wrong Token',
'Authorization failed. Wrong clientId',
'Already registered',
'Unable to create account: Already registered',
'Cannot register appstore user',
'Invalid account',
'Token refreshed failed',
'Items retrieving failed',
'Cannot add appstore products',
'Cannot save integration properties',
'Integration properties retrieving failed',
'Cannot retrieve properties',
'No integration properties found',
'Cannot create live chat. Permission denied to Live Chat Module',
'Cannot create basic popup. Permission denied to Popup Module',
'Cannot create consent form. Permission denied to Web Push Module',
'Cannot create live chat',
'Cannot create basic popup',
'Cannot create web push consent form',
'Invalid confirmation email account'
);
$errorCode = array(
10,
11,
11,
11,
11,
12,
12,
12,
12,
12,
13,
13,
14,
15,
16,
17,
18,
19,
20,
20,
21,
22,
22,
22,
23,
23,
23,
24
);
$code = (int)str_replace($errorMessage, $errorCode, trim($message));
if (!is_int($code)) {
$code = 9;
}
return $code;
}
protected static function resolveErrorCurl($error)
{
$errorCodeCurl = array(
6,
28
);
$errorCode = array(
9,
9
);
if (in_array($error, $errorCodeCurl)) {
$code = (int)str_replace($errorCodeCurl, $errorCode, $error);
} else {
$code = 9;
}
return $code;
}
public static function handleError($message, $status = 0, $curl = false, $error = null)
{
if ($curl == true) {
$code = self::resolveErrorCurl($error);
} elseif ($status >= 400 && $status <= 500) {
$code = 8;
} elseif ($status >= 500) {
$code = 9;
} else {
$code = self::resolveErrorCode($message[0]);
$message = trim(implode(' | ', $message));
}
return new SalesManagoException($message, $code, $status);
}
}
<?php
namespace Benhauer\Salesmanago\Exception;
use Throwable;
class SalesManagoException extends \Exception
{
protected $status;
public function __construct($message = "", $code = 0, $status = 0, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
$this->status = $status;
}
/**
* @return int
*/
public function getStatus()
{
return $this->status;
}
public function getSalesManagoMessage()
{
$error = array(
'success' => false,
'code' => $this->getCode(),
'status' => $this->getStatus(),
'message' => htmlspecialchars($this->getMessage())
);
return $error;
}
}
<?php
namespace Benhauer\Salesmanago\Exception;
class UserAccessException extends \Exception
{
public function getUserMessage()
{
$error = array(
'success' => false,
'message' => htmlspecialchars($this->getMessage())
);
return $error;
}
}
<?php
namespace Benhauer\Salesmanago\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
class Config extends AbstractHelper
{
const
ASSETS_FILE_JS_MAIN = 'magento.js',
ASSETS_FILE_JS_VENDOR = 'chunk-vendors.86091822.js',
ASSETS_FILE_CSS_MAIN = 'main.9e692682.css',
ASSETS_FILE_CSS_OVERWRITE = 'app-magento.css',
/* app-global-css is declarated in view/adminhtml/layout/default */
BASE_URL = 'baseURL',
PLATFORM = 'platform',
CLIENT_ID = 'clientID',
SHOP_ORIGIN = 'shopOrigin',
LANG = 'lang',
VERSION = 'version',
PARAMS = 'params',
IS_AJAX = 'isAjax',
AUTH_TOKEN ='auth_token',
M_TYPE = 'mType',
M_ID = 'mId',
M_CODE = 'mCode',
ENABLE = 'enable', /*EN_*/
EN_SYNC_RULE = 'synchronizeRule',
EN_API_DOUBLE_OPT_IN = 'apiDoubleOptIn',
EN_CALLBACKS = 'callbacks',
EN_ORDER_TYPES = 'orderTypes',
EN_PLATFORM_REDIRECT = 'platformRedirect',/*EN_PL_RED_*/
EN_PL_RED_ACTIVE = 'active',
EN_PL_RED_NAME = 'name',
EN_PL_RED_URL = 'url';
/**
* Url to controllers for admin views
*/
private $_baseUrl = '/';
/**
* Platform name (with version)
*/
private static $_platform = 'Magento 2';
/**
* Platform version
*/
private $_platformVersion = '1.0.0';
/**
* Sm clientId
*/
private $_clientId = '';
/**
* Shop Url
*/
private $_shopOrigin = '';
/**
* PL or EN
*/
private $_lang = 'EN';
/**
* plugin version
*/
private static $_version = '3.1.0';
/**
* Flag for parameters enabled option
* @type boolean
*/
private $_params = true;
/**
* Magento view request check flag
* @type boolean
*/
private $_paramIsAjax = true;
private $_paramAuthToken = '';
/**
* One of Magento scope types: Website, Store, StoreView
* @type string
*/
private $_paramScopeType = null;
/**
* Id of Magento scope type
* @type integer
*/
private $_paramScopeId = null;
/**
* Magento scope code
* @type string
*/
private $_paramScopeCode = null;
/**
* Custom params which could be add through setCustomParameters
*/
private $_customParams = array();
/**
* Enabled functions:
*/
public static $enSynchronizeRule = true;
public static $enApiDoubleOptIn = true;
public static $enCallbacks = true;
public static $enOrderTypes = false;
/**
* This will add new menu item for sm views, which will redirect user back to admin
* For magento is true;
* @type boolean
*/
public static $enPlatformRedirectActive = true;
private $_enPlatformRedirectName;
private $_enPlatformRedirectUrl;
/**
* Enabled functions for admin/plugin/platform
*/
private $_enable = true;
/**
* @param string $baseUrl - base url for views
* @param string $platform - platform name (Magento)
* @param string $clientId - SM client id
* @param string $shopOrigin - base shop url
* @param string $lang - PL - for poland || EN - for others
* @param string $version - plugin version
* @param string $viewAuthToken - token
* @param string $magentoScopeType - Website, Store, StoreView
* @param mixed $magentoScopeId - Magento scope id
* @param string $magentoScopeCode - Magento scope short code
* @return $this
*/
public function set(
$baseUrl = '',
$platform = '',
$clientId = '',
$shopOrigin = '',
$lang = '',
$version = '',
$viewAuthToken = '',
$magentoScopeType = '',
$magentoScopeId = '',
$magentoScopeCode = ''
) {
$this->_baseUrl = (!empty($baseUrl)) ? $baseUrl : $this->_baseUrl;
self::$_platform = (!empty($platform)) ? $platform : self::$_platform;
$this->_clientId = (!empty($clientId)) ? $clientId : $this->_clientId;
$this->_shopOrigin = !empty($shopOrigin) ? $shopOrigin : $this->_shopOrigin;
$this->_lang = (!empty($lang)) ? $lang : $this->_lang;
self::$_version = (!empty($version)) ? $version : self::$_version;
$this->_paramAuthToken = (!empty($viewAuthToken)) ? $viewAuthToken : $this->_paramAuthToken;
$this->_paramScopeType = (!empty($magentoScopeType)) ? $magentoScopeType : $this->_paramScopeType;
$this->_paramScopeId = (!empty($magentoScopeId)) ? $magentoScopeId : $this->_paramScopeId;
$this->_paramScopeCode = (!empty($magentoScopeCode)) ? $magentoScopeCode : $this->_paramScopeCode;
return $this;
}
/**
* @return string self::$_version plugin version
*/
public static function getPluginVersion()
{
return self::$_version;
}
/**
* @return string self::$_platform plugin version
*/
public static function getPluginPlatform()
{
return self::$_platform;
}
/**
* @return array - admin views configuration
*/
public function getBhrSso()
{
$bhrSso = array(
self::BASE_URL => $this->_baseUrl,
self::PLATFORM => self::$_platform,
self::CLIENT_ID => $this->_clientId,
self::SHOP_ORIGIN => $this->_shopOrigin,
self::LANG => ($this->_lang != 'PL' && $this->_lang != 'EN') ? 'EN' : $this->_lang,
self::VERSION => self::$_version,
);
$bhrSso = array_merge($bhrSso, $this->_getParameters());
$bhrSso = array_merge($bhrSso, $this->_getEnabledFunctions());
return $bhrSso;
}
public function getConfigForViews()
{
return json_encode($this->getBhrSso());
}
/**
* Set auth token
* @param $param - authToken;
* @return $this
* */
public function setAuthToken($param)
{
$this->_paramAuthToken = $param;
return $this;
}
/**
* Sets custom parameters to parameters
* @param array $parameters associative array;
* @return $this
*/
public function setCustomParameters($parameters = array())
{
$this->_customParams = array_merge($this->_customParams, $parameters);
return $this;
}
/**
* @param string $name - menu item name
* @param string $url - platform admin url
* @return $this
*/
public function setPlatformRedirect($name = 'to platform', $url = '/') {
$this->_enPlatformRedirectName = $name;
$this->_enPlatformRedirectUrl = $url;
return $this;
}
/**
* Build array of default params which will be send in each request from view to platform
* @return array of params
*/
private function _getDefaultParams()
{
$params = ($this->_params)
? array(
self::PARAMS =>
array(
self::IS_AJAX => $this->_paramIsAjax,
self::AUTH_TOKEN => $this->_paramAuthToken,
self::M_TYPE => $this->_paramScopeType,
self::M_ID => $this->_paramScopeId,
self::M_CODE => $this->_paramScopeCode
)
)
: array();
return $params;
}
/**
* Build array of all parameters which will be send in each request from view to platform
* @return array of params
*/
private function _getParameters()
{
$params = $this->_getDefaultParams();
if (!isset($params[self::PARAMS])) {
return array(self::PARAMS => $this->_customParams);
}
if (empty($this->_customParams)) {
return $params;
}
$params[self::PARAMS] = array_merge($params[self::PARAMS], $this->_customParams);
return $params;
}
/**
* Build array of default enabled functions for platform
* @return array of params
*/
private function _getEnabledFunctions()
{
$enabled = ($this->_enable)
? array(self::ENABLE => array(
self::EN_SYNC_RULE => self::$enSynchronizeRule,
self::EN_API_DOUBLE_OPT_IN => self::$enApiDoubleOptIn,
self::EN_CALLBACKS => self::$enCallbacks,
self::EN_ORDER_TYPES => self::$enOrderTypes,
self::EN_PLATFORM_REDIRECT => array(
self::EN_PL_RED_ACTIVE => self::$enPlatformRedirectActive,
self::EN_PL_RED_NAME => $this->_enPlatformRedirectName,
self::EN_PL_RED_URL => $this->_enPlatformRedirectUrl
)
))
: array();
return $enabled;
}
}
<?php
namespace Benhauer\Salesmanago\Helper\Contact;
use \Magento\Framework\App\Helper\AbstractHelper;
class Address extends AbstractHelper
{
const
ADDRESS = 'address',
STREET_AD = 'streetAddress',
ZIP_CODE = 'zipCode',
CITY = 'city',
COUNTRY = 'country';
public $streetAddress;
public $zipCode;
public $city;
public $country;
/**
* @param $streetAddress;
* @param string $zipCode;
* @param string $city;
* @param string $country;
* @return self
*/
public function set(
$streetAddress = '',
$zipCode = '',
$city = '',
$country = ''
) {
$this->streetAddress = $streetAddress;
$this->zipCode = $zipCode;
$this->city = $city;
$this->country = $country;
return $this;
}
public function setStreetAddress($param)
{
$this->streetAddress = $param;
return $this;
}
public function setZipCode($param)
{
$this->zipCode = $param;
return $this;
}
public function setCity($param)
{
$this->city = $param;
return $this;
}
public function setCountry($param)
{
$this->country = $param;
return $this;
}
public function get()
{
return $this->filterData(array(
self::ADDRESS => array(
self::STREET_AD => $this->setStrFromArr($this->streetAddress),
self::ZIP_CODE => $this->zipCode,
self::CITY => $this->city,
self::COUNTRY => $this->country
)
));
}
protected function setStrFromArr($param, $glue = ' ')
{
if (!is_array($param)) {
return $param;
}
$param = $this->filterArr($param);
if (!empty($param)) {
return implode($glue, $param);
}
return '';
}
protected function filterArr($array)
{
return array_filter(
$array,
function ($value) {
return !empty($value);
}
);
}
protected function filterData($data)
{
$data = array_map(function ($var) {
return is_array($var) ? $this->filterData($var) : $var;
}, $data);
$data = array_filter($data, function ($value) {
return !empty($value) || $value === false;
});
return $data;
}
}
<?php
namespace Benhauer\Salesmanago\Helper\Contact;
use \Magento\Framework\App\Helper\AbstractHelper;
use \Benhauer\Salesmanago\Exception\Exception;
class Contact extends AbstractHelper
{
const
ASYNC = 'async',
CONTACT = 'contact',
EMAIL = 'email',
C_ID = 'contactId',
FAX = 'fax',
NAME = 'name',
PHONE = 'phone',
COMPANY = 'company',
STATE = 'state',
ADDRESS = 'address',
EXT_ID = 'externalId';
public $async = true;
public $email;
public $contactId;
public $fax;
public $name;
public $phone;
public $company;
public $state;
public $externalId;
public $Address;
public $Options;
public $isSubscribing = false;
public $contact = array();
/**
* @param string $email;
* @param string $contactId;
* @param array $name;
* @param string $phone;
* @param string $fax;
* @param string $company;
* @param string $state;
* @param string $externalId;
*/
public function set(
$email = '',
$contactId = '',
$name = array(),
$phone = '',
$fax = '',
$company = '',
$state = '',
$externalId = ''
) {
$this->email = $email;
$this->contactId = $contactId;
$this->name = $name;
$this->phone = $phone;
$this->fax = $fax;
$this->company = $company;
$this->state = $state;
$this->externalId = $externalId;
return $this;
}
/**
* Sets boolean $this->isSubscribing state of contact subscribing at that moment
*
* @param boolean
* @return $this
* */
public function setIsSubscribingState($bool)
{
$this->isSubscribing = boolval($bool);
return $this;
}
/**
* Sets subscriber actual subscribing flag,
* $this->isSubscribing - if contact subscribing at that moment;
*
* @return bool $this->isSubscribing
*/
public function getIsSubscribingState()
{
return $this->isSubscribing;
}
public function setEmail($param)
{
$this->email = $param;
return $this;
}
public function getEmail()
{
if (isset($this->email) && !empty($this->email)) {
return $this->email;
} else {
throw new \Exception('Can\'t remove empty Contact email');
}
}
public function setContactId($param)
{
$this->contactId = $param;
return $this;
}
public function getContactId()
{
return $this->contactId;
}
public function setName($param)
{
$this->name = $param;
return $this;
}
public function setFax($param)
{
$this->fax = $param;
return $this;
}
public function setPhone($param)
{
$this->phone = $param;
return $this;
}
public function setCompany($param)
{
$this->company = $param;
return $this;
}
public function setState($param)
{
$this->state = $param;
return $this;
}
public function setExtId($param)
{
$this->externalId = $param;
return $this;
}
public function setAddress(Address $ContactAddress)
{
$this->Address = $ContactAddress;
return $this;
}
public function getAddress()
{
return isset($this->Address)
? $this->Address
: $this->Address = new Address();
}
public function setOptions(Options $Options)
{
$this->Options = $Options;
return $this;
}
public function getOptions()
{
return isset($this->Options)
? $this->Options
: $this->Options = new Options();
}
public function setAsync($bool)
{
$this->async = filter_var($bool, FILTER_VALIDATE_BOOLEAN);
}
public function get()
{
if (empty($this->email) && empty($this->contactId)) {
throw new \Exception('Contact identificators wasn\'t specified');
}
$contact = array(
self::ASYNC => $this->async,
self::CONTACT =>
array(
self::FAX => $this->fax,
self::NAME => $this->setStrFromArr($this->name),
self::PHONE => $this->phone,
self::COMPANY => $this->company,
self::STATE => $this->state,
self::EXT_ID => $this->externalId
)
);
if (!empty($this->email)) {
$contact[self::CONTACT] = array_merge(
$contact[self::CONTACT],
array(self::EMAIL => $this->email)
);
} else {
$contact[self::CONTACT] = array_merge(
$contact[self::CONTACT],
array(self::C_ID => $this->contactId)
);
}
if (!empty($this->Address)) {
$contact[self::CONTACT] = array_merge(
$contact[self::CONTACT],
$this->Address->get()
);
}
if (isset($this->Options)) {
$contact = array_merge(
$contact,
$this->Options->get()
);
}
return $this->filterData($contact);
}
/**
* @throws \Exception;
* @return array $contact without async parameter;
*/
public function getForExport()
{
$contact = $this->get();
unset($contact[self::ASYNC]);
/*fix SM service problem in batchUpsert in v2.4.12*/
if (isset($contact[Options::TAGS])
&& !is_array($contact[Options::TAGS])
) {
$contact[Options::TAGS] = explode(',', $contact[Options::TAGS]);
}
return $contact;
}
public function getDataOptions()
{
$data = array(
'data' => array(),
'options' => array()
);
$contact = $this->get();
$data['data'] = $contact[self::CONTACT];
unset($contact[self::CONTACT]);
$data['options'] = $contact;
return $data;
}
public function getForInstantUpsert()
{
if (empty($this->email)) {
throw new \Exception('Contact identificators wasn\'t specified');
}
$contact = array(
self::EMAIL => $this->email,
self::NAME => $this->setNameFromArray(),
);
if (isset($this->Options)) {
$options = $this->Options->get();
$contact = array_merge($contact, $options);
}
return $contact;
}
protected function setStrFromArr($param, $glue = ' ')
{
if (!is_array($param)) {
return $param;
}
$param = $this->filterArr($param);
if (!empty($param)) {
return implode($glue, $param);
}
return '';
}
protected function filterArr($array)
{
return array_filter(
$array,
function ($value) {
return !empty($value);
}
);
}
protected function filterData($data)
{
$data = array_map(function ($var) {
return is_array($var) ? $this->filterData($var) : $var;
}, $data);
$data = array_filter($data, function ($value) {
return !empty($value) || $value === false;
});
return $data;
}
}
<?php
namespace Benhauer\Salesmanago\Helper\Contact;
use \Magento\Framework\App\Helper\AbstractHelper;
class Options extends AbstractHelper
{
const
BIRTHDAY = 'birthday',
TAGS = 'tags',
PROPERTIES = 'properties',
R_TAGS = 'removeTags',
F_OPT_IN = 'forceOptIn',
F_OPT_OUT = 'forceOptOut',
F_P_OPT_INT = 'forcePhoneOptIn',
F_P_OPT_OUT = 'forcePhoneOptOut',
N_EMAIL = 'newEmail',
CREATED_ON = 'createdOn',
U_API_D_OPT_IN = 'useApiDoubleOptIn',
D_OPT_IN_TEMPLATE_ID = 'apiDoubleOptInEmailTemplateId',
D_OPT_IN_EMAIL_ACC_ID = 'apiDoubleOptInEmailAccountId',
D_OPT_IN_EMAIL_SUBJ = 'apiDoubleOptInEmailSubject';
public $birthday;
public $forceOptIn;
public $forceOptOut;
public $forcePhoneOptIn;
public $forcePhoneOptOut;
public $properties;
public $tags;
public $removeTags;
public $newEmail;
public $additional = array();
public $useApiDoubleOptIn = array(
self::U_API_D_OPT_IN => false,
self::D_OPT_IN_TEMPLATE_ID => '',
self::D_OPT_IN_EMAIL_ACC_ID => '',
self::D_OPT_IN_EMAIL_SUBJ => ''
);
/**
* @param array $tags;
* @param array $removeTags;
* @param array $birthday;
* @param boolean $forceOptIn;
* @param boolean $forceOptOut;
* @param boolean $forcePhoneOptIn;
* @param boolean $forcePhoneOptOut;
* @param array $properties;
* @param string $newEmail;
*/
public function set(
$tags = array(),
$removeTags = array(),
$birthday = '',
$forceOptIn = '',
$forceOptOut = '',
$forcePhoneOptIn = '',
$forcePhoneOptOut = '',
$properties = array(),
$newEmail = ''
) {
$this->tags = $tags;
$this->removeTags = $removeTags;
$this->birthday = $birthday;
$this->forceOptIn = $forceOptIn;
$this->forceOptOut = $forceOptOut;
$this->forcePhoneOptIn = $forcePhoneOptIn;
$this->forcePhoneOptOut = $forcePhoneOptOut;
$this->properties = $properties;
$this->newEmail = $newEmail;
return $this;
}
public function setTags($param)
{
$this->tags = $param;
return $this;
}
public function getTags()
{
return $this->tags;
}
public function setBirthday($param)
{
$this->birthday = $param;
return $this;
}
public function setForceOptIn($param)
{
$this->forceOptIn = $param;
return $this;
}
public function getForceOptIn()
{
return $this->forceOptIn;
}
public function setForceOptOut($param)
{
$this->forceOptOut = $param;
return $this;
}
public function setForcePhoneOptIn($param)
{
$this->forcePhoneOptIn = $param;
return $this;
}
public function setForcePhoneOptOut($param)
{
$this->forcePhoneOptOut = $param;
return $this;
}
public function setProperties($param)
{
$this->properties = $param;
return $this;
}
public function setNewEmail($param)
{
$this->newEmail = $param;
return $this;
}
/**
* Sets additional options such syncrule createOn etc.
* @param array $params;
*/
public function setAdditional($params)
{
$this->additional = array_merge($this->additional, $params);
return $this;
}
/**
* @param array - array(
* 'useApiDoubleOptIn' => true/false,
* 'apiDoubleOptInEmailTemplateId' => '',
* 'apiDoubleOptInEmailAccountId' => '',
* 'apiDoubleOptInEmailSubject' => ''
* )
* @return $this;
*/
public function setUseApiDoubleOptIn($params)
{
if(empty($params)
|| !isset($params[self::U_API_D_OPT_IN])
|| !$params['useApiDoubleOptIn']
) {
return $this;
}
$this->useApiDoubleOptIn[self::U_API_D_OPT_IN] = $params[self::U_API_D_OPT_IN];
if (isset($params[self::D_OPT_IN_TEMPLATE_ID])) {
$this->useApiDoubleOptIn[self::D_OPT_IN_TEMPLATE_ID] = $params[self::D_OPT_IN_TEMPLATE_ID];
}
if (isset($params[self::D_OPT_IN_EMAIL_ACC_ID])) {
$this->useApiDoubleOptIn[self::D_OPT_IN_EMAIL_ACC_ID] = $params[self::D_OPT_IN_EMAIL_ACC_ID];
}
if (isset($params[self::D_OPT_IN_EMAIL_SUBJ])) {
$this->useApiDoubleOptIn[self::D_OPT_IN_EMAIL_SUBJ] = $params[self::D_OPT_IN_EMAIL_SUBJ];
}
return $this;
}
/**
* @return array
*/
public function getUseApiDoubleOptIn() {
return $this->useApiDoubleOptIn;
}
/**
* @return array - firltered array of sm contact options;
*/
public function get()
{
$this->setOptStatusesBaseOnForceOptIn();
$options = array(
self::TAGS => isset($this->tags) ? $this->setStrFromArr($this->tags, ',') : '',
self::R_TAGS => isset($this->tags) ? $this->setStrFromArr($this->removeTags, ',') : '',
self::N_EMAIL => isset($this->newEmail) ? $this->newEmail : '',
self::PROPERTIES => isset($this->properties) ? $this->properties : '',
self::F_OPT_IN => isset($this->forceOptIn) ? $this->forceOptIn : false,
self::F_OPT_OUT => isset($this->forceOptOut) ? $this->forceOptOut : false,
self::F_P_OPT_INT => isset($this->forcePhoneOptIn) ? $this->forcePhoneOptIn : false,
self::F_P_OPT_OUT => isset($this->forcePhoneOptOut) ? $this->forcePhoneOptOut : false,
self::BIRTHDAY => isset($this->birthday) ? $this->birthday : '',
self::CREATED_ON => isset($this->createdOn) ? $this->createdOn : ''
);
if ($this->useApiDoubleOptIn[self::U_API_D_OPT_IN]) {
$options = array_merge($this->useApiDoubleOptIn, $options);
}
if (isset($this->additional) && !empty($this->additional)) {
$options = array_merge($options, $this->additional);
}
return $this->filterData($options);
}
protected function filterArr($array)
{
return array_filter(
$array,
function ($value) {
return !empty($value);
}
);
}
protected function setStrFromArr($param, $glue = ' ')
{
if (!is_array($param)) {
return $param;
}
$param = $this->filterArr($param);
if (!empty($param)) {
return implode($glue, $param);
}
return '';
}
protected function setOptStatusesBaseOnForceOptIn()
{
if (is_bool($this->forceOptIn)
&& $this->forceOptOut != ''
) {
$this->forceOptOut = !$this->forceOptIn;
$this->forcePhoneOptIn = $this->forceOptIn;
$this->forcePhoneOptOut = !$this->forceOptIn;
}
}
protected function filterData($data)
{
$data = array_map(function ($var) {
return is_array($var) ? $this->filterData($var) : $var;
}, $data);
$data = array_filter($data, function ($value) {
return !empty($value) || $value === false;
});
return $data;
}
}
<?php
namespace Benhauer\Salesmanago\Helper;
use \Magento\Framework\App\Helper\AbstractHelper;
use \Magento\Framework\App\Helper\Context;
use \Magento\Framework\App\ProductMetadataInterface;
use \Benhauer\Salesmanago\Model\User;
use \Benhauer\Salesmanago\Helper\Config;
class Metrix extends AbstractHelper
{
protected $productMetadata;
protected $UserModel;
public function __construct(
Context $context,
User $UserModel,
ProductMetadataInterface $productMetadata
) {
parent::__construct($context);
$this->productMetadata = $productMetadata;
$this->UserModel = $UserModel;
}
/**
* return app metrix data
*/
public function getJsonConfig()
{
$params = [
'clientId' => $this->UserModel->getClientId(),
'owner' => $this->UserModel->getOwnerEmail(),
'platformName' => Config::getPluginPlatform().' '.$this->productMetadata->getEdition(),
'platformVersion' => $this->productMetadata->getVersion(),
'pluginVersion' => Config::getPluginVersion()
];
return json_encode($params);
}
}
\ No newline at end of file
<?php
namespace Benhauer\Salesmanago\Helper;
use \Magento\Directory\Api\CountryInformationAcquirerInterface;
use \Magento\Framework\App\ProductMetadata;
use \Magento\Newsletter\Model\Subscriber;
use \Magento\Framework\App\Helper\Context;
class Tools
{
public $metaData;
public $subscriber;
public $countryInformation;
public $logger;
public $scopeConfig;
public $assetRepository;
public $storeManager;
public function __construct(
ProductMetadata $metaData,
Subscriber $subscriber,
CountryInformationAcquirerInterface $countryInformation,
Context $context
) {
$this->metaData = $metaData;
$this->subscriber = $subscriber;
$this->countryInformation = $countryInformation;
$this->logger = $context->getLogger();
$this->scopeConfig = $context->getScopeConfig();
}
public function getScopeConfig()
{
return $this->scopeConfig;
}
public function checkSubscription($customerId)
{
$subscriber = $this->subscriber->loadByCustomerId($customerId);
return $subscriber->isSubscribed();
}
}
<?php
namespace Benhauer\Salesmanago\Model\Config;
use \Benhauer\Salesmanago\Model\AbstractModel as SalesmanagoAbstractModel;
class PurchasesConfig extends SalesmanagoAbstractModel
{
/**
* P_T - Processing Type;
* C_L - Config Label;
*/
const
P_T_DEFAULT = 0,
P_T_ON_CHOOSEN_EVENT = 1,
P_T_ON_EVENT = 2,
P_T_CRON = 3,
C_L_TYPE = 'purchaseProcessingType',
C_L_ON_CHOOSEN_EVENT = 'purchaseProcessingTypeSystemEvents',
C_L_ON_CRON = 'purchaseProcessingTypeCron';
public static $defaultPurchaseEvent = 'checkout_onepage_controller_success_action';
public static $lastEventToSendPurchase = 'checkout_submit_all_after';
/**
* @var array processing types labels;
*/
public static $processingTypes = [
['value' => self::P_T_DEFAULT, 'label' => 'Default'],
['value' => self::P_T_ON_CHOOSEN_EVENT, 'label' => 'System event'],
['value' => self::P_T_ON_EVENT, 'label' => 'After all purchase system events'],
['value' => self::P_T_CRON, 'label' => 'With CRON']
];
/**
* @var string
*/
public static $configPath = SalesmanagoAbstractModel::C_PLATFORM_SETTING_PATH.'purchases/';
/**
* @var array list of events for purchase;
*/
public static $processingSystemEvents = [
0 => 'checkout_onepage_controller_success_action',
1 => 'multishipping_checkout_controller_success_action',
2 => 'checkout_submit_all_after',
3 => 'checkout_controller_onepage_saveOrder',
4 => 'restore_quote',
5 => 'sales_convert_order_to_quote',
6 => 'sales_order_invoice_register',
7 => '_set_sales_order',
8 => 'checkout_type_onepage_save_order_after',
9 => 'checkout_type_multishipping_create_orders_single',
10 => 'paypal_express_place_order_success'
];
protected $config;
protected $type = self::P_T_DEFAULT;
/**
* Default CRON cycle in hrs;
*/
protected $defaultCroneCycle = 3;
/**
* @return bool|string
*/
public function getConfig()
{
$type = $this->getConfigItem(self::$configPath.self::C_L_TYPE);
switch ($type) {
case self::P_T_ON_CHOOSEN_EVENT:
$this->type = self::P_T_ON_CHOOSEN_EVENT;
$this->config = $this->getConfigItem(self::$configPath.self::C_L_ON_CHOOSEN_EVENT);
return $this->config;
break;
case self::P_T_ON_EVENT:
$this->type = self::P_T_ON_EVENT;
$this->config = self::$lastEventToSendPurchase;
return $this->config;
break;
case self::P_T_DEFAULT:
$this->type = self::P_T_DEFAULT;
$this->config = self::$defaultPurchaseEvent;
return $this->config;
break;
case self::P_T_CRON:
$this->type = self::P_T_CRON;
$this->config = $this->getConfigItem(self::$configPath.self::C_L_ON_CRON);
return empty($this->config) ? $this->defaultCroneCycle : $this->config;
break;
default:
return false;
break;
}
}
/**
* @return int configuration type
*/
public function getType()
{
$this->getConfig();
return $this->type;
}
/**
* @param string $hookName
* @return boolean
*/
public function isHookActive($hookName)
{
$config = $this->getConfig();
if ($this->type == self::P_T_CRON) {
return false;
}
if (isset(self::$processingSystemEvents[intval($this->config)])
&& (self::$processingSystemEvents[intval($this->config)] == $hookName)
) {
return true;
}
return false;
}
/**
* @return boolean
*/
public function isCronActive()
{
$this->getConfig();
if ($this->type == self::P_T_CRON) {
return true;
}
return false;
}
}
\ No newline at end of file
<?php
namespace Benhauer\Salesmanago\Model\Config\Source;
use \Magento\Framework\Message\ManagerInterface;
use \Benhauer\Salesmanago\Exception\Exception;
use \Benhauer\Salesmanago\Exception\SalesManagoException;
use \Benhauer\Salesmanago\Exception\UserAccessException;
use \Benhauer\Salesmanago\Model\User as UserModel;
use \SALESmanago\Factories\FactoryOrganizer;
use \SALESmanago\Provider\UserProvider;
class Select implements \Magento\Framework\Option\ArrayInterface
{
public $factoryOrganizer;
public $model;
public $request;
public function __construct(
FactoryOrganizer $factoryOrganizer,
UserModel $model,
\Magento\Framework\App\Request\Http $request
) {
$this->factoryOrganizer = $factoryOrganizer;
$this->model = $model;
$this->request = $request;
}
/**
* @return array
*/
public function toOptionArray()
{
return $this->getOwnersEmailsList();
}
/**
* @return array - owners emails list for config select;
*/
public function getOwnersEmailsList()
{
$answer = [];
try {
$this->storeResolver();
$integration = $this->factoryOrganizer->getInst(
FactoryOrganizer::USER_ACCOUNT_C,
UserProvider::initSettingsUser($this->model),
$this->model
);
$response = $integration->listUsersByClient();
if ($response['success'] && isset($response['users'])) {
foreach ($response['users'] as $user) {
$answer[] = ['value' => $user, 'label' => $user];
}
return $answer;
}
return $answer;
} catch (\Exception $e) {
return $answer;
}
}
public function storeResolver()
{
$storeId = $this->request->getParam('store');
if ($storeId) {
$this->model->setScopeId($storeId);
}
return $this;
}
}
<?php
namespace Benhauer\Salesmanago\Model\Config\Source;
use \Benhauer\Salesmanago\Exception\SalesManagoException;
use \Benhauer\Salesmanago\Exception\UserAccessException;
use \Benhauer\Salesmanago\Model\User as UserModel;
use \SALESmanago\Factories\FactoryOrganizer;
use \SALESmanago\Provider\UserProvider;
class SelectCookieLifeTime implements \Magento\Framework\Option\ArrayInterface
{
public $factoryOrganizer;
public $model;
public function __construct(
FactoryOrganizer $factoryOrganizer,
UserModel $model
) {
$this->factoryOrganizer = $factoryOrganizer;
$this->model = $model;
}
/**
* @return array
*/
public function toOptionArray()
{
$answer = [
['value' => 3, 'label' => '3'],
['value' => 12, 'label' => '12'],
['value' => 24, 'label' => '24'],
['value' => 48, 'label' => '48'],
['value' => 72, 'label' => '72'],
['value' => 100, 'label' => '100'],
['value' => 200, 'label' => '200'],
['value' => 300, 'label' => '300'],
['value' => 400, 'label' => '400'],
['value' => 500, 'label' => '500']
];
return $answer;
}
/**
* @return array - owners emails list for config select;
*/
public function getOwnersEmailsList()
{
$answer = [];
$integration = $this->factoryOrganizer->getInst(
FactoryOrganizer::USER_ACCOUNT_C,
UserProvider::initSettingsUser($this->model),
$this->model
);
$response = $integration->listUsersByClient();
if ($response['success'] && isset($response['users']))
{
foreach ($response['users'] as $user) {
$answer[] = ['value' => $user, 'label' => $user];
}
return $answer;
}
return $answer;
}
}
<?php
namespace Benhauer\Salesmanago\Model\Config\Source;
use \Benhauer\Salesmanago\Exception\SalesManagoException;
use \Benhauer\Salesmanago\Exception\UserAccessException;
use \Benhauer\Salesmanago\Model\User as UserModel;
use \SALESmanago\Factories\FactoryOrganizer;
use \SALESmanago\Provider\UserProvider;
class SelectCronJobFrequency implements \Magento\Framework\Option\ArrayInterface
{
public $factoryOrganizer;
public $model;
public function __construct(
FactoryOrganizer $factoryOrganizer,
UserModel $model
) {
$this->factoryOrganizer = $factoryOrganizer;
$this->model = $model;
}
/**
* @return array
*/
public function toOptionArray()
{
$answer = [
['value' => 1, 'label' => '1'],
['value' => 2, 'label' => '2'],
['value' => 3, 'label' => '3'],
['value' => 4, 'label' => '4'],
['value' => 6, 'label' => '6'],
['value' => 10, 'label' => '10'],
['value' => 15, 'label' => '15'],
['value' => 24, 'label' => '24'],
['value' => 32, 'label' => '32'],
['value' => 48, 'label' => '48']
];
return $answer;
}
}
<?php
namespace Benhauer\Salesmanago\Model\Config\Source;
use \Benhauer\Salesmanago\Exception\SalesManagoException;
use \Benhauer\Salesmanago\Exception\UserAccessException;
use \Benhauer\Salesmanago\Model\User as UserModel;
use \Benhauer\Salesmanago\Model\Config\PurchasesConfig;
use \SALESmanago\Factories\FactoryOrganizer;
use \SALESmanago\Provider\UserProvider;
class SelectPurchaseProcessingType implements \Magento\Framework\Option\ArrayInterface
{
public $factoryOrganizer;
public $model;
public function __construct(
FactoryOrganizer $factoryOrganizer,
UserModel $model
) {
$this->factoryOrganizer = $factoryOrganizer;
$this->model = $model;
}
/**
* @return array
*/
public function toOptionArray()
{
$answer = PurchasesConfig::$processingTypes;
return $answer;
}
}
<?php
namespace Benhauer\Salesmanago\Model\Config\Source;
use \Benhauer\Salesmanago\Exception\SalesManagoException;
use \Benhauer\Salesmanago\Exception\UserAccessException;
use \Benhauer\Salesmanago\Model\User as UserModel;
use \Benhauer\Salesmanago\Model\Config\PurchasesConfig;
use \SALESmanago\Factories\FactoryOrganizer;
use \SALESmanago\Provider\UserProvider;
class SelectSystemEventsForPurchase implements \Magento\Framework\Option\ArrayInterface
{
public $factoryOrganizer;
public $model;
public function __construct(
FactoryOrganizer $factoryOrganizer,
UserModel $model
) {
$this->factoryOrganizer = $factoryOrganizer;
$this->model = $model;
}
/**
* @return array
*/
public function toOptionArray()
{
$answer = PurchasesConfig::$processingSystemEvents;
return $answer;
}
}
<?php
namespace Benhauer\Salesmanago\Model;
use \Magento\Framework\Model\AbstractModel as MagentoAbstractModel;
use \Magento\Framework\Model\Context;
use \Magento\Framework\Registry;
use \Magento\Customer\Api\CustomerRepositoryInterface;
use \Magento\Newsletter\Model\Subscriber;
use \Magento\Directory\Api\CountryInformationAcquirerInterface;
use \Benhauer\Salesmanago\Model\Hooks as HooksModel;
use \Benhauer\Salesmanago\Helper\Contact\Contact as SmContact;
use \Benhauer\Salesmanago\Helper\Contact\Address as SmContactAddress;
use \Benhauer\Salesmanago\Helper\Contact\Options as SmContactOptions;
class Contact extends MagentoAbstractModel
{
public $Contact;
public $Address;
public $Options;
public $logger;
public $subscriber;
public function __construct(
Context $context,
Registry $registry,
SmContact $Contact,
SmContactAddress $Address,
SmContactOptions $Options,
CustomerRepositoryInterface $customerRepositoryInterface,
Subscriber $subscriber,
CountryInformationAcquirerInterface $countryInformation
) {
parent::__construct(
$context,
$registry
);
$this->customerRepositoryInterface = $customerRepositoryInterface;
$this->Contact = $Contact;
$this->Address = $Address;
$this->Options = $Options;
$this->logger = $context->getLogger();
$this->subscriber = $subscriber;
$this->countryInformation = $countryInformation;
}
/**
* @param int $customerId
* @return SmContact
* @throws \Exception
*/
public function getContactByCustomerId($customerId)
{
try {
$customer = $this->customerRepositoryInterface->getById($customerId);
if (method_exists($customer, 'getDefaultBillingAddress')) {
$customerAddress = $customer->getDefaultBillingAddress();
} else {
$customerAddresses = $customer->getAddresses();
//get only last address in array
foreach ($customerAddresses as $address) {
$customerAddress = $address;
}
}
$email = $customer->getEmail();
$name = [
$customer->getFirstname(),
$customer->getMiddlename(),
$customer->getLastname()
];
$phone = method_exists($customer, 'getTelephone') ? $customer->getTelephone() : '';
$fax = method_exists($customer, 'getFax') ? $customer->getFax() : '';
$company = method_exists($customer, 'getCompany') ? $customer->getCompany() : '';
$externalId = method_exists($customer, 'getId') ? $customer->getId() : '';
$street = '';
$postcode = '';
$city = '';
$country = '';
if (!empty($customerAddress)) {
$street = method_exists($customerAddress, 'getStreet')
? $customerAddress->getStreet()
: $street;
$postcode = method_exists($customerAddress, 'getPostcode')
? $customerAddress->getPostcode()
: $postcode;
$city = method_exists($customerAddress, 'getCity')
? $customerAddress->getCity()
: $city;
$country = method_exists($customerAddress, 'getCountry')
? $customerAddress->getCountry()
: (
method_exists($customerAddress, 'getCountryId')
? $customerAddress->getCountryId()
: $country
);
$phone = (empty($phone) && method_exists($customerAddress, 'getTelephone'))
? $customerAddress->getTelephone()
: $phone;
$fax = (empty($fax) && method_exists($customerAddress, 'getFax'))
? $customerAddress->getFax()
: $fax;
$company = (empty($company) && method_exists($customerAddress, 'getCompany'))
? $customerAddress->getCompany()
: $company;
}
$dob = ($customer->getDob()) ? date('Ymd', strtotime($customer->getDob())) : '';
$createdOn = method_exists($customer, 'getCreatedAt')
? $customer->getCreatedAt()
: date("F j, Y, g:i a", time());
$this->Contact->set(
$email,
'',
$name,
$phone,
$fax,
$company,
'',
$externalId
);
$Address = $this->Address->set(
$street,
$postcode,
$city,
$country
);
$Options = $this->Options->set(
'',
'',
$dob,
false,
true,
'',
'',
'',
''
)->setAdditional(
['createdOn' => $createdOn]
);
$this->Contact->setAddress($Address);
$this->Contact->setOptions($Options);
$this->_setContactOptStatus();
return $this->Contact;
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
/**
* @param object $billingAddress magento billing addess
* @param string $customerEmail - contact email
* @return SmContact
* @throws \Exception
*/
public function getContactByCustomerBillingAddress($billingAddress, $customerEmail)
{
$this->Options->setAdditional(
[
'province' => $billingAddress->getRegion(),
'createdOn' => date('c')
]
);
$this->Address->set(
$billingAddress->getStreet(),
$billingAddress->getPostCode(),
$billingAddress->getCity(),
$this->_getCountryNameByCode($billingAddress->getCountryId())
);
$this->Contact->set(
$customerEmail,
'',
[
$billingAddress->getFirstname(),
$billingAddress->getLastname()
],
$billingAddress->getTelephone(),
$billingAddress->getFax(),
$billingAddress->getCompany(),
'',
''
);
$this->Contact
->setAddress($this->Address)
->setOptions($this->Options);
$this->_setContactOptStatus();
return $this->Contact;
}
/**
* Sets Opt States for Contact object base on magento subscriber status
*
* @param string $email - contact email;
* @param string $customerId - external contact id;
* @return object $this->Contact;
*/
private function _setContactOptStatus($email = '', $customerId = '')
{
try {
$subscriber = false;
if (!empty($email)) {
$subscriber = $this->subscriber->loadByEmail($email);
}
if (!$subscriber && $this->Contact->getEmail()) {
$subscriber = $this->subscriber->loadByEmail($this->Contact->getEmail());
}
if (!empty($customerId) && !$subscriber) {
$subscriber = $this->subscriber->loadByCustomerId($customerId);
}
if ($subscriber && $subscriber->isSubscribed()) {
$this->Contact
->getOptions()
->setForceOptIn(true)
->setForcePhoneOptIn(true)
->setForcePhoneOptOut(false);
} else {
$this->Contact
->getOptions()
->setForceOptIn(false)
->setForceOptOut(true)
->setForcePhoneOptIn(false)
->setForcePhoneOptOut(true);
}
return $this->Contact;
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
/**
* @param string $countryId coutry short code such EN, PL, DE, etc.;
* @return string full country name;
* @log Exception to magento log file;
*/
private function _getCountryNameByCode($countryId)
{
try {
if ($countryId == null) {
return '';
}
return $this->countryInformation
->getCountryInfo($countryId)
->getFullNameLocale();
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
}
<?php
namespace Benhauer\Salesmanago\Model;
use \SALESmanago\Model\CreateInterface;
use \Benhauer\Salesmanago\Model\AbstractModel as SalesmanagoAbstractModel;
class Create extends SalesmanagoAbstractModel implements CreateInterface
{
public function insert($settings)
{
$this
->setClientId($settings[self::C_CLIENT_ID])
->setSHA($settings[self::C_SHA])
->setApiKey($settings[self::C_API_KEY])
->setOwner($settings[self::OWNER])
->setEndpoint($settings[self::C_ENDPOINT])
->setToken($settings[self::C_TOKEN])
->setExpiresTokenAt();
$this->setDefaultAdditionalDataAfterInit();
$this->clearCache();
}
}
<?php
namespace Benhauer\Salesmanago\Model;
class DummyDataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider
{
public function __construct(
$name = '',
$primaryFieldName = '',
$requestFieldName = ''
) {
$this->name = $name;
$this->primaryFieldName = $primaryFieldName;
$this->requestFieldName = $requestFieldName;
}
/**
* @return array
*/
public function getData()
{
return;
}
public function addFilter(\Magento\Framework\Api\Filter $filter)
{
return;
}
}
<?php
namespace Benhauer\Salesmanago\Model\Events;
use \Magento\Framework\UrlInterface;
use \Benhauer\Salesmanago\Model\AbstractModel as SalesmanagoAbstractModel;
class Purchase extends SalesmanagoAbstractModel
{
/**
* @param $order
* @param $quoteFactory
* @return array
*/
public function getPurchseByOrder($order, $quoteFactory)
{
try {
$dateTime = $this->objDate->date();
$prods = [
'ids' => [],
'names' => [],
'qty' => [],
'sku' => []
];
$quote = $quoteFactory
->create()
->load($order->getQuoteId());
$quoteItems = $quote->getAllVisibleItems();
foreach ($quoteItems as $item) {
if ($item->getPrice() > 0
&& $item->getPrice() != null
) {
array_push($prods['ids'], $item->getProductId());
array_push($prods['names'], $item->getName());
array_push($prods['qty'], $item->getQty());
array_push($prods['sku'], $item->getSku());
}
}
$purchaseContent = [
'date' => $dateTime->format('c'),
'description' => $order->getPayment()->getMethod(),
'products' => implode(",", $prods['ids']),
'location' => $this->model->getSMStoreId(UrlInterface::URL_TYPE_WEB),
'value' => $order->getGrandTotal(),
'detail1' => implode(",", $prods['names']),
'detail2' => implode("/", $prods['qty']),
'detail3' => implode(",", $prods['sku']),
'detail4' => $order->getBaseCurrencyCode(),
'externalId' => $order->getEntityId(),
'shopDomain' => $this->store->getBaseUrl(UrlInterface::URL_TYPE_WEB)
];
return $purchaseContent;
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
}
\ No newline at end of file
<?php
namespace Benhauer\Salesmanago\Model;
use \Magento\Backend\Model\UrlInterface;
use \Benhauer\Salesmanago\Model\AbstractModel as SalesmanagoAbstractModel;
class Export extends SalesmanagoAbstractModel
{
const
CUSTOMER_COLLECTION_TABLE = 'customer_entity',
SUBSCRIBER_COLLECTION_TABLE = 'newsletter_subscriber';
private $contactOptStatus;
private $exportTags;
/**
* @param object $collection Customerse or Subscribers
* @param object $subscriber to check if customer is subscribed
* @return array $tags
*/
public function prepareContactsToExport($collection, $subscriber)
{
$contacts = [];
$isCustomer = ($collection->getMainTable() == self::CUSTOMER_COLLECTION_TABLE) ? true : false;
foreach ($collection as $customer) {
$customerEmail = $customer->getEmail();
$cSubscribed = $subscriber->loadByEmail($customerEmail);
/* "if" below - fix magento load subscriber bug - in magento version 2.3.2:
* when try to load subscriber by customer email or customer id - was returned different email of suscriber*/
if($customerEmail != $cSubscribed->getEmail()){
$isSubscribed = false;
} else {
$isSubscribed = boolval($cSubscribed->isSubscribed());
}
if (!empty($customerEmail)) {
$tags = $this->prepareTags($isSubscribed, $isCustomer);
$smContact = [
'contact' => [
'email' => $customer->getEmail(),
'name' => $customer->getName(),
'externalId' => $customer->getId(),
],
'birthday' => (!empty($customer->getDob()))
? date('Ymd', strtotime($customer->getDob()))
: '',
'tags' => $tags,
'removeTags' => '',
];
if (isset($this->contactOptStatus)) {
$smContact = array_merge($smContact, $this->contactOptStatus);
} else {
$smContact = array_merge($smContact,
[
'forceOptIn' => $isSubscribed,
'forceOptOut' => !$isSubscribed,
'forcePhoneOptIn' => $isSubscribed,
'forcePhoneOptOut' => !$isSubscribed
]
);
}
if ($addr = $customer->getDefaultBillingAddress()) {
$smContact['contact'] = array_merge(
$smContact['contact'],
[
'phone' => $addr->getTelephone(),
'fax' => $addr->getFax(),
'company' => $addr->getCompany(),
'address' => [
'streetAddress' => implode(',', $addr->getStreet()),
'zipCode' => $addr->getPostcode(),
'city' => $addr->getCity(),
'country' => $addr->getCountry()
],
]
);
if ($addr->getRegion()) {
$smContact = array_merge($smContact,
[
'province' => $addr->getRegion()
]
);
}
}
$contacts[] = $this->filterData($smContact);
}
}
return $contacts;
}
public function prepareOrdersToExport($orders)
{
$extEvents = [];
foreach ($orders as $order) {
$products = $order->getAllVisibleItems();
$prodData = [
'ids' => [],
'names' => [],
'skus' => [],
'qtys' => []
];
foreach ($products as $product) {
$prodData['ids'][] = $product->getProductId();
$prodData['names'][] = $product->getName();
$prodData['skus'][] = $product->getSku();
$prodData['qtys'][] = round($product->getQtyOrdered());
}
$status = (
$order->getData('status') == 'complete'
|| $order->getData('status') == 'closed'
|| $order->getData('status') == 'pending'
) ? "PURCHASE" : "CART";
$store = $this->storeManager->getStore();
$storeUrl = $store->getBaseUrl(UrlInterface::URL_TYPE_WEB);
if ($status != "CART") {
$extEvents[] = [
'email' => $order->getCustomerEmail(),
'contactEvent' => [
'date' => strtotime($order->getData('created_at')) * 1000,
'description' => $order->getPayment()->getMethod(),
'products' => (isset($prodData['ids'])) ? implode(",", $prodData['ids']) : '',
'location' => $this->getSMStoreId(),
'value' => $order->getGrandTotal(),
'contactExtEventType' => $status,
'detail1' => (isset($prodData['names'])) ? implode(",", $prodData['names']) : '',
'detail2' => (isset($prodData['qtys'])) ? implode("/", $prodData['qtys']) : '',
'detail3' => (isset($prodData['skus'])) ? implode("/", $prodData['skus']) : '',
'detail4' => $order->getBaseCurrencyCode(),
'externalId' => $order->getRealOrderId(),
'shopDomain' => $storeUrl
]
];
}
}
return $extEvents;
}
public function setContactOptStatus($param)
{
switch ($param) {
case "optIn":
$this->contactOptStatus = [
'forceOptIn' => true,
'forceOptOut' => false,
'forcePhoneOptIn' => true,
'forcePhoneOptOut' => false
];
break;
case "optOut":
$this->contactOptStatus = [
'forceOptIn' => false,
'forceOptOut' => true,
'forcePhoneOptIn' => false,
'forcePhoneOptOut' => true
];
break;
}
}
public function setExportTags($param)
{
$this->exportTags = strpos($param, ',')
? explode(',', $param)
: [$param];
}
/**
* @param boolean $isSubscribed
* @param boolean $isCustomer
* @return array $tags
*/
public function prepareTags($isSubscribed = false, $isCustomer = false)
{
$tags = $isSubscribed
? explode(",", $this->getTags(self::T_NEWS))
: [];
$tags = $isCustomer
? array_merge($tags, explode(",", $this->getTags(self::T_REGISTER)))
: $tags;
$tags = isset($this->exportTags)
? array_merge($tags, $this->exportTags)
: $tags;
return $tags;
}
}
<?php
namespace Benhauer\Salesmanago\Model;
use \Magento\Framework\App\Config\ScopeConfigInterface;
use \Benhauer\Salesmanago\Exception\UserAccessException;
use \SALESmanago\Entity\Settings;
use \SALESmanago\Model\SettingsInterface;
use \SALESmanago\Model\UserInterface as SmUserInterface;
use \SALESmanago\Services\ConnectSalesManagoService;
use \Benhauer\Salesmanago\Model\AbstractModel as SalesmanagoAbstractModel;
class Hooks extends SalesmanagoAbstractModel implements SettingsInterface, SmUserInterface
{
private $processigOrdersStatus = [
'canceled' => ConnectSalesManagoService::EVENT_TYPE_CANCELLATION
];
public function getUserSettings($userProperties)
{
$data = $this->getDataCoreConfig();
if (isset($data[Settings::CLIENT_ID])
|| !empty($data[Settings::CLIENT_ID])
) {
return $data;
}
return false;
}
/**
* @return array
* @throws UserAccessException
*/
public function monitorVisitorsData()
{
$userData = $this->getUserSettings(null);
return [
Settings::CLIENT_ID => $userData[Settings::CLIENT_ID],
Settings::ENDPOINT => $userData[Settings::ENDPOINT],
'webPush' => $userData['webPush']
];
}
public function getSynchronizeRule()
{
return $this->getSynchronize();
}
/**
* @return mixed - configuration of double optin (array) or false if double optin does not exis or not set up
*/
public function getApiDoubleOptIn()
{
$apiDoubleOptInData = $this->getDoubleOptInData();
return $apiDoubleOptInData
? array(
AbstractModel::DOUBLE_OPT_IN => $apiDoubleOptInData[AbstractModel::DOUBLE_OPT_IN],
AbstractModel::DOUBLE_OPT_IN_EMAIL_TEMPLATE_ID => isset($apiDoubleOptInData[AbstractModel::DOUBLE_OPT_IN_EMAIL_TEMPLATE_ID])
? $apiDoubleOptInData[AbstractModel::DOUBLE_OPT_IN_EMAIL_TEMPLATE_ID]
: '',
AbstractModel::DOUBLE_OPT_IN_EMAIL_ACCOUNT_ID => isset($apiDoubleOptInData[AbstractModel::DOUBLE_OPT_IN_EMAIL_ACCOUNT_ID])
? $apiDoubleOptInData[AbstractModel::DOUBLE_OPT_IN_EMAIL_ACCOUNT_ID]
: '',
AbstractModel::DOUBLE_OPT_IN_EMAIL_SUBJECT_ID => isset($apiDoubleOptInData[AbstractModel::DOUBLE_OPT_IN_EMAIL_SUBJECT_ID])
? $apiDoubleOptInData[AbstractModel::DOUBLE_OPT_IN_EMAIL_SUBJECT_ID]
: '',
)
: $apiDoubleOptInData[AbstractModel::DOUBLE_OPT_IN];
}
/**
* Return array of order types/states which was chosen in Sm plugin
* @return array
*/
public function getSubmittedOrderTypes()
{
$data = $this->getDataCoreConfig();
if (!isset($data[self::O_TYPES])) {
return array();
}
return $data[self::O_TYPES];
}
/**
* Get order statuses chosen by admin for sm plugin configuration & check if $param exist in there
* @param string one of order status
* @return boolean
*/
public function checkIfOrderStatusChoosed($param)
{
$oTypes = $this->getSubmittedOrderTypes();
if (empty($oTypes)) {
return false;
}
return array_key_exists($param, array_flip($oTypes));
}
public function checkOrderStatusToProcess($orderStatus)
{
return (array_key_exists($orderStatus, $this->processigOrdersStatus))
? $this->processigOrdersStatus[$orderStatus]
: false;
}
public function getUserToken($userProperties)
{
return true;
}
public function setCustomProperties($userProperties)
{
return true;
}
public function refreshUserToken($userProperties)
{
return true;
}
public function getDataForAccountType($userProperties)
{
return true;
}
}
<?php
namespace Benhauer\Salesmanago\Model;
use \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory as StatusCollectionFactory;
use \SALESmanago\Model\IntegrationInterface;
use \SALESmanago\Entity\Settings;
use \SALESmanago\Model\SettingsInterface;
use \Benhauer\Salesmanago\Model\AbstractModel as SalesmanagoAbstractModel;
class Integration extends SalesmanagoAbstractModel implements IntegrationInterface, SettingsInterface
{
public function delete($userProperties = null)
{
return $this->removePluginConfiguration();
}
public function getAccountUserData($userProperties)
{
$userData = $this->getDataCoreConfig();
return [
Settings::CLIENT_ID => $userData[Settings::CLIENT_ID],
Settings::ENDPOINT => $userData[Settings::ENDPOINT],
Settings::OWNER => $userData[Settings::OWNER],
self::WEB_PUSH => $userData[self::WEB_PUSH],
self::SYNC_RULE => isset($userData[self::SYNC_RULE])
? filter_var($userData[self::SYNC_RULE], FILTER_VALIDATE_BOOLEAN)
: false,
self::API_DOUBLE_OPT_IN => isset($userData[self::API_DOUBLE_OPT_IN])
? filter_var($userData[self::API_DOUBLE_OPT_IN], FILTER_VALIDATE_BOOLEAN)
: false,
self::DOUBLE_OPT_IN => (isset($userData[self::DOUBLE_OPT_IN]) && !empty($userData[self::DOUBLE_OPT_IN]))
? $userData[self::DOUBLE_OPT_IN]
: false,
self::STORE_ID => $this->getSMStoreId($this->storeManager->getStore()->getUrl())
];
}
public function setAccountUserData($userProperties)
{
$value = $this
->getValue()
->addUpdatedAtTime()
->extendValue(
[
Settings::OWNER => $userProperties[Settings::OWNER],
self::WEB_PUSH => isset($userProperties[self::WEB_PUSH])
? $userProperties[self::WEB_PUSH]
: '',
self::SYNC_RULE => $userProperties[self::SYNC_RULE],
self::API_DOUBLE_OPT_IN => isset($userProperties[self::API_DOUBLE_OPT_IN])
? filter_var($userProperties[self::API_DOUBLE_OPT_IN], FILTER_VALIDATE_BOOLEAN)
: false,
self::DOUBLE_OPT_IN => isset($userProperties[self::DOUBLE_OPT_IN])
? $userProperties[self::DOUBLE_OPT_IN]
: false
]
)
->buildValue();
return $this->setUserData($value);
}
public function getPlatformUserData($userProperties)
{
return $userProperties;
}
public function setPlatformUserData($userProperties)
{
return $userProperties;
}
public function getUserSettings($userProperties)
{
$data = empty($userProperties)
? $this->getDataCoreConfig()
: $this->getDataCoreConfig();
return $data;
}
/**
* Get Magento order statuses list and compare it with selected by client
* @return array - Statuses lists
*/
public function getMatchedOrderStatuses(StatusCollectionFactory $statusCollectionFactory)
{
$statuses = $statusCollectionFactory
->create()
->toOptionArray();
foreach ($statuses as $key => $status) {
$status['status'] = $status['value'];
unset($status['value']);
$status['selected'] = $this->checkIfOrderStatusChoosed($status['status']);
$statuses[$key] = $status;
}
return array('statuses' => $statuses);
}
/**
* Set Order statuses to settings
* @param array $params order statuses
* @return boolean
*/
public function setOrderStatuses($params = null)
{
if (empty($params) && $params != '') {
return false;
}
$data = $this->getDataCoreConfig();
$data[self::O_TYPES] = $params;
$this->update('', $data);
return true;
}
/**
* Get order statuses chosen by admin for sm plugin configuration & check if $param exist in there
* @param string one of order status
* @return boolean
*/
public function checkIfOrderStatusChoosed($param)
{
$data = $this->getDataCoreConfig();
if (!isset($data[self::O_TYPES])
|| empty($data[self::O_TYPES])
) {
return false;
}
return in_array($param, array_values($data[self::O_TYPES]));
}
}
<?php
namespace Benhauer\Salesmanago\Model;
use \SALESmanago\Model\LoginInterface;
use \Benhauer\Salesmanago\Model\AbstractModel as SalesmanagoAbstractModel;
class Login extends SalesmanagoAbstractModel implements LoginInterface
{
public function insert($settings)
{
$this
->setClientId($settings[self::C_CLIENT_ID])
->setSHA($settings[self::C_SHA])
->setApiKey($settings[self::C_API_KEY])
->setOwner($settings[self::OWNER])
->setEndpoint($settings[self::C_ENDPOINT])
->setToken($settings[self::C_TOKEN]);
$this->setDefaultAdditionalDataAfterInit();
$this->clearCache();
}
public function updateProperties($settings, $properties)
{
$this
->setClientId($settings[self::C_CLIENT_ID])
->setSHA($settings[self::C_SHA])
->setApiKey($settings[self::C_API_KEY])
->setOwner($settings[self::OWNER])
->setEndpoint($settings[self::C_ENDPOINT])
->setToken($settings[self::C_TOKEN])
->setLang($properties[self::C_LANG])
->setColors($properties[self::C_COLOR]);
$this->setDefaultAdditionalDataAfterInit();
$this->clearCache();
}
public function checkUser($settings)
{
$clientId = $this->getClientId();
return !empty($clientId) ? $clientId : false;
}
}
<?php
namespace Benhauer\Salesmanago\Model\SM;
use \Psr\Log\LoggerInterface;
use \Benhauer\Salesmanago\Exception\Exception;
use \Benhauer\Salesmanago\Exception\SalesManagoException;
use \Benhauer\Salesmanago\Exception\UserAccessException;
use \Benhauer\Salesmanago\Model\User as UserModel;
use \Magento\Framework\Model\AbstractModel as MagentoAbstractModel;
use \Magento\Framework\Registry;
use \Magento\Store\Model\StoreManagerInterface;
use \Magento\Framework\Model\Context;
use \Magento\Framework\Message\ManagerInterface;
use \Magento\Framework\App\Request\Http as HttpRequest;
use \SALESmanago\Factories\FactoryOrganizer;
use \SALESmanago\Provider\UserProvider;
use \Benhauer\Salesmanago\Helper\Config as ConfigHelper;
class Rest extends MagentoAbstractModel
{
public $factoryOrganizer;
public $model;
public $request;
public $logger;
public static $planTypes = [
'B2B_BASIC' => 'Basic',
'B2C_BASIC' => 'Basic',
'B2B_COMPLETE' => 'Professional',
'B2C_PRO' => 'Professional',
'B2B_ADVANCED' => 'Enterprise',
'B2C_ELITE' => 'Enterprise',
'STORE' => 'SALESmanago AppStore',
'STORE_FREE' => 'SALESmanago AppStore',
];
public function __construct(
Context $context,
Registry $registry,
UserModel $model,
FactoryOrganizer $factoryOrganizer,
ConfigHelper $config,
ManagerInterface $messageManager,
StoreManagerInterface $storeManager,
HttpRequest $request
) {
parent::__construct($context, $registry);
$this->model = $model;
$this->factoryOrganizer = $factoryOrganizer;
$this->config = $config;
$this->storeManager = $storeManager;
$this->messageManager = $messageManager;
$this->request = $request;
$this->logger = $context->getLogger();
}
public function getAccountType()
{
try {
$this->storeResolver();
$userAccount = $this->factoryOrganizer->getInst(
FactoryOrganizer::USER_ACCOUNT_C,
UserProvider::initSettingsUser(
$this->model
),
$this->model
);
$response = $userAccount->getAccountTypeWithContacts();
if (!$response['success']) {
$this
->messageManager
->addErrorMessage(__("Your SALESmanago token has expired, please logout and login again to refresh it."));
$response = [];
}
$result = $this->parseResponseData($response);
return $result;
} catch (UserAccessException $e) {
$this->logger->critical($e->getMessage());
return [];
} catch (SalesManagoException $e) {
$this->logger->critical($e->getMessage());
return [];
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
return [];
}
}
/**
* Parse Salesmanago response data for account type requst
* @param array $response
* @return array
*/
protected function parseResponseData($response)
{
$result = [
"contactCount" => $response['contactCount'],
"planType" => self::$planTypes[$response['planType']],
"versionType" => $response['versionType']
];
return $result;
}
public function storeResolver()
{
$storeId = $this->request->getParam('store');
if ($storeId) {
$this->model->setScopeId($storeId);
}
return $this;
}
}
<?php
namespace Benhauer\Salesmanago\Model;
use \SALESmanago\Entity\Settings;
use \Benhauer\Salesmanago\Exception\UserAccessException;
use \SALESmanago\Model\SettingsInterface;
use \SALESmanago\Model\UserInterface as SmUserInterface;
use \SALESmanago\Factories\FactoryOrganizer;
class User extends Export implements SettingsInterface, SmUserInterface
{
/**
* @param $userProperties
* @throws UserAccessException
* @return mixed
*/
public function getUserSettings($userProperties)
{
return $this->getDataCoreConfig();
}
public function getUserToken($userProperties)
{
$userData = $this->getDataCoreConfig();
$status = (strlen($this->getToken()) == 64) ? true : false;
$refresh = (time() > $this->getExpiresTokenAt()) ? true : false;
if (isset($userData['properties'])) {
$userData['properties'] = array_merge($userData['properties'], ['success' => true]);
}
$data = [
'success' => $status,
Settings::TOKEN => $this->getToken(),
'refresh' => $refresh,
'properties' => isset($userData['properties']) ? $userData['properties'] : ''
];
return $data;
}
public function refreshUserToken($userProperties)
{
if (isset($userProperties['token']) && !empty($userProperties['token'])) {
$this
->setExpiresTokenAt()
->setUpdatedAtTime()
->setToken($userProperties['token']);
} else {
$this
->setExpiresTokenAt()
->setUpdatedAtTime();
}
}
public function setCustomProperties($userProperties)
{
$this
->addUpdatedAtTime()
->extendValue(
['properties' => $userProperties]
);
}
public function getDataForAccountType($userProperties)
{
$uData = $this->getUserSettings(null);
return [
'token' => $uData['token'],
'email' => $uData['owner']
];
}
}
<?php
namespace Benhauer\Salesmanago\Observer;
use \Benhauer\Salesmanago\Model\Hooks as HooksModel;
use \Magento\Framework\Event\Observer;
use \Benhauer\Salesmanago\Helper\Tagger;
use \Benhauer\Salesmanago\Observer\AbstractObserver as SalesmanagoAbstractObserver;
class AddressModified extends SalesmanagoAbstractObserver
{
public function hookAct(Observer $observer)
{
try {
$connectSalesManago = $this->getConnectSalesManago();
$Contact = $this->modelContact->getContactByCustomerBillingAddress(
$observer->getCustomerAddress(),
$observer->getCustomerAddress()
->getCustomer()
->getEmail()
);
$Contact->getOptions()->setAdditional(
[HooksModel::SYNC_RULE => $this->model->getSynchronizeRule()]
);
$contact = $Contact->getDataOptions();
$this->upsertContact($contact, $connectSalesManago, SalesmanagoAbstractObserver::UPSERT_FLAG_NO_CHECK);
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
}
<?php
namespace Benhauer\Salesmanago\Observer;
use \Magento\Framework\Event\Observer;
use \Benhauer\Salesmanago\Helper\Tagger;
use \Benhauer\Salesmanago\Observer\CustomerModified as SalesmanagoCustomerModified;
class AdminCustomerModified extends SalesmanagoCustomerModified
{
protected $customer;
/**
* @return object Customer;
*/
public function getCustomer($observer)
{
$this->customer = $observer->getCustomer();
$this->setStoreViewForModel();
return $this->customer;
}
/**
* Set store view depends from which store view is customer;
*
* Set store view id from $this->requestPrams to each model;
*/
public function setStoreViewForModel()
{
$storeId = null;
if (isset($this->customer)) {
$storeId = $this->customer->getStoreId();
}
if ($storeId != null && $storeId != 0) {
$this->model->setScopeId($storeId);
$this->model->setScope('store');
}
}
}
<?php
namespace Benhauer\Salesmanago\Observer;
use \Psr\Log\LoggerInterface;
use \Magento\Framework\Stdlib\DateTime\TimezoneInterface as MagentoDateTime;
use \Magento\Framework\Event\Observer;
use \Magento\Newsletter\Model\Subscriber;
use \Magento\Checkout\Model\Session;
use \Magento\Customer\Model\Session as CustomerModelSession;
use \Magento\Store\Api\Data\StoreInterface;
use \Magento\Customer\Api\CustomerRepositoryInterface;
use \Magento\Framework\Stdlib\CookieManagerInterface;
use \Magento\Store\Model\StoreManagerInterface;
use \SALESmanago\Provider\UserProvider;
use \SALESmanago\Factories\FactoryOrganizer;
use \SALESmanago\Services\ConnectSalesManagoService;
use \Benhauer\Salesmanago\Model\Hooks as HooksModel;
use \Benhauer\Salesmanago\Model\Contact;
use \Benhauer\Salesmanago\Helper\Tagger;
use \Benhauer\Salesmanago\Observer\AbstractObserver as SalesmanagoAbstractObserver;
class CartModified extends SalesmanagoAbstractObserver
{
public $customerSession;
public $cookieManager;
public function __construct(
Session $session,
StoreInterface $store,
Subscriber $subscriber,
HooksModel $model,
CustomerRepositoryInterface $customerRepositoryInterface,
CustomerModelSession $customerSession,
CookieManagerInterface $cookieManager,
MagentoDateTime $objDate,
FactoryOrganizer $factoryOrganizer,
Tagger $tagger,
LoggerInterface $logger,
Contact $modelContact,
StoreManagerInterface $storeManager
) {
parent::__construct(
$session,
$store,
$subscriber,
$model,
$customerRepositoryInterface,
$cookieManager,
$objDate,
$factoryOrganizer,
$tagger,
$logger,
$modelContact,
$storeManager
);
$this->customerSession = $customerSession;
}
public function hookAct(Observer $observer)
{
try {
$dataEvent = $this->getCartModified($observer);
$eventId = $this->cookieManager->getCookie('smevent');
$contactId = ($this->cookieManager->getCookie('smclient'))
? ['contactId' => $this->cookieManager->getCookie('smclient')]
: '';
$connectSalesManago = $this->getConnectSalesManago();
if (!$eventId) {
$eventId = $this->session->getSmEventId();
}
if (isset($eventId)
&& !empty($eventId)
) {
$response = $connectSalesManago->contactExtEvent(
ConnectSalesManagoService::EVENT_TYPE_CART,
$dataEvent,
$contactId,
$eventId
);
return $response['success'];
} else {
$customerSession = $this->customerSession;
if ($customerSession->isLoggedIn()) {
$smContactData['email'] = $customerSession->getCustomer()->getEmail();
} else {
if (!empty($contactId)
) {
$smContactData['contactId'] = is_array($contactId) ? $contactId['contactId'] : $contactId;
}
}
if (isset($smContactData)
&& !empty($smContactData)
) {
$response = $connectSalesManago->contactExtEvent(
ConnectSalesManagoService::EVENT_TYPE_CART,
$dataEvent,
$smContactData,
$eventId
);
$this->createEventCookie($response);
}
}
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
}
<?php
namespace Benhauer\Salesmanago\Observer;
use \Magento\Framework\Event\Observer;
use \Benhauer\Salesmanago\Helper\Tagger;
use \Benhauer\Salesmanago\Observer\AbstractObserver as SalesmanagoAbstractObserver;
class CustomerLogin extends SalesmanagoAbstractObserver
{
public function hookAct(Observer $observer) {
try {
$connectSalesManago = $this->getConnectSalesManago();
$customerId = $observer->getCustomer()->getEntityId();
$customer = $this->getCustomerById($customerId);
$customer['options'] = isset($customer['options'])
? $customer['options']
: '';
$this->upsertContact($customer, $connectSalesManago, SalesmanagoAbstractObserver::UPSERT_FLAG_ALL_DATA);
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
}
<?php
namespace Benhauer\Salesmanago\Observer;
use \Magento\Framework\Event\Observer;
use \Benhauer\Salesmanago\Helper\Tagger;
use \Benhauer\Salesmanago\Observer\AbstractObserver as SalesmanagoAbstractObserver;
class CustomerModified extends SalesmanagoAbstractObserver
{
public function hookAct(Observer $observer)
{
try {
$customer = $this->getCustomerById($this->getCustomer($observer)->getId());
$connectSalesManago = $this->getConnectSalesManago();
$customer['options'] = isset($customer['options'])
? $customer['options']
: '';
$this->upsertContact($customer, $connectSalesManago, SalesmanagoAbstractObserver::UPSERT_FLAG_NO_CHECK);
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
/**
* @param object $observer;
* @return object Customer;
*/
public function getCustomer($observer)
{
$customer = $this->customerRepositoryInterface->get($observer->getData('email'));
return $customer;
}
}
<?php
namespace Benhauer\Salesmanago\Observer;
use \Psr\Log\LoggerInterface;
use \Magento\Framework\Event\Observer;
use \Benhauer\Salesmanago\Helper\Tagger;
use \Benhauer\Salesmanago\Observer\AbstractObserver as SalesmanagoAbstractObserver;
class CustomerRegister extends SalesmanagoAbstractObserver
{
public function hookAct(Observer $observer)
{
try {
$customerId = $observer->getCustomer()->getId();
$contact = $this->getCustomerById($customerId);
$connectSalesManago = $this->getConnectSalesManago();
$contact = $this->tagger
->setModel($this->model)
->setTags($contact, Tagger::T_REGISTER);
$this->upsertContact($contact, $connectSalesManago, SalesmanagoAbstractObserver::UPSERT_FLAG_ALL_DATA);
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment