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 Magento\Framework\Message\ManagerInterface;
use \Psr\Log\LoggerInterface;
use \Magento\Backend\App\Action\Context;
use \Magento\Framework\View\Result\PageFactory;
use \Magento\Backend\Model\Auth\Session;
use \Magento\Newsletter\Model\Subscriber;
use \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory as CustomerCollectionFactory;
use \Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory as SubscriberCollectionFactory;
use \Magento\Sales\Model\ResourceModel\Order\CollectionFactory as OrderCollectionFactory;
use \Magento\Framework\Controller\Result\JsonFactory;
use \Benhauer\Salesmanago\Exception\SalesManagoException;
use \Benhauer\Salesmanago\Exception\UserAccessException;
use \Benhauer\Salesmanago\Helper\Config as ConfigHelper;
use \Benhauer\Salesmanago\Model\User as UserModel;
use \Benhauer\Salesmanago\Model\Export as ExportModel;
use \SALESmanago\Factories\FactoryOrganizer;
use \SALESmanago\Provider\UserProvider;
class ExportData extends \Magento\Backend\App\Action
{
const
ADVANCED = 'advanced',
WITH_STATUS = 'exportWithStatus',
CALENDAR = 'calendar',
C_FROM = 'from',
C_TO = 'to',
EXP_PACKAGE_SIZE = 200;
protected $factoryOrganizer;
protected $model;
protected $context;
protected $storeId = 0;
protected $scope = 'default';
protected $messageManager;
protected static $exportedOrderTypes = [
'complete',
'closed',
'pending'
];
protected $requestParams;
public $advancedExport;
public $exportTags;
public $exportDateRange;
public $subscriberFactory;
public $exportModel;
public function __construct(
Context $context,
UserModel $model,
FactoryOrganizer $factoryOrganizer,
ConfigHelper $config,
JsonFactory $resultJsonFactory,
PageFactory $pageFactory,
Subscriber $subscriber,
CustomerCollectionFactory $customerFactory,
SubscriberCollectionFactory $subscriberFactory,
OrderCollectionFactory $orderFactory,
ExportModel $exportModel,
LoggerInterface $logger
) {
parent::__construct($context);
$this->model = $model;
$this->config = $config;
$this->factoryOrganizer = $factoryOrganizer;
$this->messageManager = $context->getMessageManager();
$this->pageFactory = $pageFactory;
$this->subscriber = $subscriber;
$this->customerFactory = $customerFactory;
$this->orderFactory = $orderFactory;
$this->factoryOrganizer = $factoryOrganizer;
$this->logger = $logger;
$this->exportModel = $exportModel;
$this->subscriberFactory = $subscriberFactory;
}
public function execute()
{
if ($loadByStoreCheck = $this->loadByStoreCheck()) {
return $loadByStoreCheck;
}
$this->requestParams = $this->getRequest()->getParam('exportConfig');
if ($this->requestParams) {
$this->exportData($this->requestParams);
}
$this->renderView();
}
public function exportData($export) {
if ($this->requestParams['contactsExport']) {
$this->setContacts();
}
if ($this->requestParams['eventsExport']) {
$this->setEvents();
}
}
protected 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->model->isPluginConfActive()) {
return $this->redirectTo();
}
return false;
}
protected function redirectTo($redirectTo = 'index')
{
$store = '';
if (!empty($this->storeId)) {
$store = '/store/'.$this->storeId ;
}
return $this->_redirect('*/*/'.$redirectTo.$store);
}
protected function renderView(){
$this->_view->loadLayout();
$this->_view->renderLayout();
}
protected function setContacts()
{
try {
$userAccount = $this->factoryOrganizer->getInst(
FactoryOrganizer::USER_ACCOUNT_C,
UserProvider::initSettingsUser(
$this->model
),
$this->model
);
/**@todo change this
* if(isset($this->requestParams[self::ADVANCED])) {
* $this->setAdvancedExport($this->requestParams[self::ADVANCED]);
* }
*/
if (isset($this->requestParams[self::WITH_STATUS])
&& !empty($this->requestParams[self::WITH_STATUS])
) {
$this->exportModel->setContactOptStatus($this->requestParams[self::WITH_STATUS]);
}
$cExportedCustomers = $this->exportCustomers($userAccount);
$cExportedSubscribersNoCustomers = $this->exportSubscribersNoCustomer($userAccount);
$this->messageManager->addSuccess(__("Success") . ' Exported Customers: '.$cExportedCustomers.' Exported Subscribers: '. $cExportedSubscribersNoCustomers);
} catch (UserAccessException $e) {
$this->logger->critical($e->getUserMessage());
} catch (SalesManagoException $e) {
$this->logger->critical($e->getSalesManagoMessage());
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
/**
* Prapare & export packages of contacts from customers to SM
* @param object $userAccount - form salesmanaga service
* @return integer subscriber collection size;
* @throw & @log UserAccessException, SalesManagoException, Exception
*/
protected function exportCustomers($userAccount)
{
try{
$CustomerCollection = $this->getCustomerCollection();
$customerCollectionSize = $CustomerCollection->getSize();
$loops = intval(ceil($customerCollectionSize / self::EXP_PACKAGE_SIZE));
$CustomerCollection->setPageSize(self::EXP_PACKAGE_SIZE);
for ($i = 1; $i <= $loops; $i++) {
$CustomerCollection->setCurPage($i);
$CustomerCollectionExportData = $this->exportModel
->prepareContactsToExport(
$CustomerCollection,
$this->subscriber
);
$userAccount->exportContacts($CustomerCollectionExportData);
}
return $customerCollectionSize;
} catch (UserAccessException $e) {
$this->logger->critical($e->getUserMessage());
} catch (SalesManagoException $e) {
$this->logger->critical($e->getSalesManagoMessage());
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
/**
* Prapare & export packages of contacts from subscribers to SM
* @param object $userAccount - form salesmanaga service
* @return integer subscriber collection size;
* @throw & @log UserAccessException, SalesManagoException, Exception
*/
protected function exportSubscribersNoCustomer($userAccount)
{
try{
$SubscribersCollection = $this->getSubscribersNoCustomerCollection();
$subscribersCollectionSize = $SubscribersCollection->getSize();
$loops = ceil($subscribersCollectionSize / self::EXP_PACKAGE_SIZE);
$SubscribersCollection->setPageSize(self::EXP_PACKAGE_SIZE);
for ($i = 0; $i < $loops; $i++) {
$SubscribersCollection->setCurPage($i);
$SubscribersCollectionExportData = $this->exportModel->prepareContactsToExport(
$SubscribersCollection,
$this->subscriber
);
$userAccount->exportContacts($SubscribersCollectionExportData);
}
return $subscribersCollectionSize;
} catch (UserAccessException $e) {
$this->logger->critical($e->getUserMessage());
} catch (SalesManagoException $e) {
$this->logger->critical($e->getSalesManagoMessage());
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
protected function setEvents()
{
try {
$userAccount = $this->factoryOrganizer->getInst(
FactoryOrganizer::USER_ACCOUNT_C,
UserProvider::initSettingsUser(
$this->model
),
$this->model
);
if (isset($this->requestParams[self::ADVANCED])) {
$this->setAdvancedExport($this->requestParams[self::ADVANCED]);
}
$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);
}
$this->messageManager->addSuccess(__("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
]
);
}
if ($this->storeId != 0) {
$orderFactory->addFieldToFilter('store_id', ['eq' => $this->storeId]);
}
$orderFactory
->addFieldToFilter('status', ['in' => self::$exportedOrderTypes])
->addFieldToSelect(['*']);
return $orderFactory;
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
$this->messageManager->addError($e->getMessage());
}
}
/**
* @return int - size of Customer collection
*/
protected function getCountOrders()
{
return $this->getOrdersCollection()->getSize();
}
protected function setAdvancedExport($param)
{
$this->advancedExport = $param['active'];
if ($this->advancedExport
&& !empty($param['tag'])
) {
$this->exportModel->setExportTags($param['tag']);
}
if ($this->advancedExport
&& !empty($param[self::CALENDAR][self::C_FROM])
&& !empty($param[self::CALENDAR][self::C_TO])
) {
$this->exportDateRange = [
'from' => $param[self::CALENDAR][self::C_FROM].' 00:00:01',
'to' => $param[self::CALENDAR][self::C_TO].' 23:59:59'
];
}
return $this;
}
/**
* Filter Customer collection depends on $this->exportDateRange, $this->storeId
* @return \Magento\Customer\Model\ResourceModel\Customer\Collection|\Magento\Framework\Data\Collection\AbstractDb $customerFactory
*/
protected function getCustomerCollection()
{
try {
$customerFactory = $this->customerFactory
->create()
->addFieldToSelect(array('*'));
if ($this->storeId !== 0) {
$customerFactory->addFieldToFilter('store_id', ['eq' => $this->storeId]);
}
if (isset($this->exportDateRange)) {
$customerFactory
->addFieldToFilter(
'created_at',
[
'from' => $this->exportDateRange[self::C_FROM],
'to' => $this->exportDateRange[self::C_TO]
]
);
}
return $customerFactory;
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
$this->messageManager->addError($e->getMessage());
}
}
/**
* Filter Subscriber collection depends on $this->exportDateRange, $this->storeId
* @return \Magento\Newsletter\Model\ResourceModel\Subscriber\Collection $subscriberFactory - subscribers which is not a customer
*/
protected function getSubscribersNoCustomerCollection()
{
try {
$subscriberFactory = $this->subscriberFactory->create();
$subscriberFactory
->addFieldToSelect(array('*'))
->addFieldToFilter('customer_id', array('eq' => '0'));/*get only subscribers which aren't customers*/
if ($this->storeId !== 0) {
$subscriberFactory->addFieldToFilter('store_id', ['eq' => $this->storeId]);
}
if (isset($this->exportDateRange)) {
$subscriberFactory
->addFieldToFilter(
'change_status_at',
[
'from' => $this->exportDateRange[self::C_FROM],
'to' => $this->exportDateRange[self::C_TO]
]
);
}
return $subscriberFactory;
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
}
<?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\Framework\App\Helper\AbstractHelper;
use \Magento\Framework\App\Helper\Context;
use \Magento\Store\Model\StoreManagerInterface;
use \Magento\Framework\Stdlib\CookieManagerInterface;
use \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory;
use \Magento\Framework\Session\SessionManagerInterface;
use \Benhauer\Salesmanago\Model\Hooks as HooksModel;
class Tagger extends AbstractHelper
{
const
T_PURCHASE = 'prc',
T_GUEST_PURCHASE = 'gprc',
T_REGISTER = 'rgs',
T_NEWSLETTER = 'nws',
T_STORE_VIEW = 'strvw',
T_COOKIE_NAME = 'smcntctgs',
T_SESSION_NAME = 'sessionTags';
private $model;
private $contact;
private $storeManager;
private $cookieManager;
private $cookieMetadataFactory;
private $sessionManager;
private $_checkOptInState = true;
private $_cookieExpiredTime = 30960000;
public function __construct(
Context $context,
StoreManagerInterface $storeManager,
CookieManagerInterface $cookieManager,
CookieMetadataFactory $cookieMetadataFactory,
SessionManagerInterface $sessionManager
) {
$this->storeManager = $storeManager;
$this->cookieManager = $cookieManager;
$this->sessionManager = $sessionManager;
$this->cookieMetadataFactory = $cookieMetadataFactory;
parent::__construct($context);
}
/**
* Set Model;
* @param object $model;
* @return $this;
*/
public function setModel($model)
{
$this->model = $model;
return $this;
}
/**
* @param bool $checkOptInState
* @return $this
*/
public function setCheckOptInState($checkOptInState = true)
{
$this->_checkOptInState = $checkOptInState;
return $this;
}
/**
* @param $tagsType = array()
* @param $contact = array() of strings OR STRING
* @param boolean $reqSubscriptionConfirmation;
*
* @return $contact
*/
public function setTags(&$contact = null, $tagsType, $reqSubscriptionConfirmation = false)
{
if(!isset($this->contact)
&& $contact === null
) {
return false;
}
if ($contact != null) {
$this->contact = $contact;
}
if ($reqSubscriptionConfirmation && is_string($tagsType)) {
$tagsType = '';
}
if ($reqSubscriptionConfirmation && is_array($tagsType)) {
$tagsType = array_diff($tagsType, [self::T_NEWSLETTER]);
}
if ($tagsType == self::T_STORE_VIEW) {
$this->_setSpacialTags();
} else {
if (is_array($tagsType)) {
foreach($tagsType as $type) {
$this->_switcher($type);
}
} else {
$this->_switcher($tagsType);
}
//Always tagged by Store View name
$this->_setStoreView();
}
return $this->contact;
}
/**
* Overwritte system methods which sets tags veriable to cookie;
*/
protected function _setCookie($stringTagsToSet)
{
$metadata = $this->cookieMetadataFactory
->createPublicCookieMetadata()
->setDuration($this->_cookieExpiredTime)
->setPath($this->sessionManager->getCookiePath())
->setDomain($this->sessionManager->getCookieDomain());
$this->cookieManager->setPublicCookie(self::T_COOKIE_NAME, $stringTagsToSet, $metadata);
}
/**
* Overwritte system methods which get tags veriable from cookie;
*/
protected function _getCookie()
{
return $this->cookieManager->getCookie(self::T_COOKIE_NAME);
}
/**
* Overwritte system methods which set tags veriable to session;
*/
protected function _setToSession($param)
{
return $this->sessionManager->setSessionTags($param);
}
/**
* Overwritte system methods which get tags veriable from session;
*/
protected function _getFromSession()
{
return $this->sessionManager->getSessionTags();
}
/**
* Assight tags to contact;
*/
protected function _assignToContact($param)
{
$this->contact['options']['tags'] = $param;
return true;
}
/**
* Get tags from contact
*/
protected function _getFromContact()
{
return (isset($this->contact['options']) && isset($this->contact['options']['tags']))
? $this->contact['options']['tags']
: false;
}
/**
* Get email from contact
*/
protected function _getContactEmail()
{
$email = $this->contact['data']['email'];
return hash("sha256", $email);
}
/**
* Get optin state from contact
*/
protected function _getContactOptInState()
{
$state = (isset($this->contact['options']['forceOptIn'])
&& $this->contact['options']['forceOptIn'] == true)
? true
: false;
return $state;
}
/**
* Get Store Name for tag
*/
protected function _getStoreName()
{
return $this->storeManager->getStore()->getName();
}
/**
* _switcher for tags type;
* @param string $type;
*/
private function _switcher($type)
{
switch ($type) {
case self::T_REGISTER:
$this->_setRegister();
break;
case self::T_PURCHASE:
$this->_setPurchase();
break;
case self::T_GUEST_PURCHASE:
$this->_setGuestPurchase();
break;
case self::T_NEWSLETTER:
$this->_setNewsletter();
break;
}
}
/**
* Sets & Check set purchase tag;
*/
private function _setPurchase()
{
$tag = strtolower($this->model->getTags(HooksModel::T_PURCHASE));
$this->_customCheck($tag, self::T_PURCHASE);
}
/**
* Sets & Check set guest purchase tag;
*/
private function _setGuestPurchase()
{
$tag = strtolower($this->model->getTags(HooksModel::T_GUEST_PURCHASE));
$this->_customCheck($tag, self::T_GUEST_PURCHASE);
}
/**
* Sets & Check register tag
*/
private function _setRegister()
{
$tag = strtolower($this->model->getTags(HooksModel::T_REGISTER));
$this->_customCheckWithCookie($tag, self::T_REGISTER);
}
/**
* Sets & Check Newsletter Tag
*/
private function _setNewsletter()
{
if ($this->_checkOptInState && $this->_getContactOptInState()) {
$tag = strtolower($this->model->getTags(HooksModel::T_NEWS));
$this->_customCheckWithCookie($tag, self::T_NEWSLETTER);
} elseif (!$this->_checkOptInState) {
$tag = strtolower($this->model->getTags(HooksModel::T_NEWS));
$this->_customCheckWithCookie($tag, self::T_NEWSLETTER);
}
}
/**
* Sets tag Store View Name
*/
private function _setStoreView()
{
$tag = str_replace(' ', '_', strtolower($this->_getStoreName()));
$this->_customCheckWithCookie($tag, self::T_STORE_VIEW);
}
/**
* Set tags as newsletter and store name;
*/
private function _setSpacialTags()
{
$this->_setStoreView();
$this->_setNewsletter();
}
/**
* Checks if tag already exist in customer tags, session variable, cookie;
* Checks type of tags (repeatable or non repeatable);
* @param string $tag - tag;
* @param string shortTag - tag;
* @return array $this->contact;
*/
private function _customCheckWithCookie($tag, $shortTag)
{
$tag = strtolower($tag);
$contactTags = $this->_getContactTagsFromWebStorage();
$tagsFromContact = $this->_getFromContact();
if ($contactTags) {
$contactTags = explode(',', $contactTags);
if (!in_array($shortTag, $contactTags)) {
$contactTags[] = $shortTag;
$contactTags = implode(',', $contactTags);
$this->_setContactTagsToSession($contactTags);
if ($tagsFromContact
&& !empty($tagsFromContact)
&& !empty($tag)
) {
$this->_assignToContact($tagsFromContact.','.$tag);
} elseif(!empty($tag)) {
$this->_assignToContact($tag);
}
}
} else {
$this->_setContactTagsToSession($shortTag);
if ($tagsFromContact
&& !empty($tagsFromContact)
&& !empty($tag)
) {
$this->_assignToContact($tagsFromContact.','.$tag);
} elseif(!empty($tag)) {
$this->_assignToContact($tag);
}
}
if ($this->_getFromSession()) {
$this->_setContactTagsToCookie($this->_getFromSession());
}
return $this->contact;
}
/**
* Checks if tag already exist in customer tags
* @param string $tag - tag
*/
private function _customCheck($tag)
{
$tag = strtolower($tag);
$contactTags = $this->_getFromContact();
if ($contactTags) {
if (!in_array($tag, explode(',', $contactTags))) {
$this->_assignToContact($contactTags.','.$tag);
}
} else {
$this->_assignToContact($tag);
}
}
/**
* @return mixed - array if cookie exist otherwise false.
*/
private function _getParseCookie()
{
$tagsCookie = $this->_getCookie();
return (empty($tagsCookie) || !isset($tagsCookie))
? ''
: json_decode(stripslashes($tagsCookie), true);
}
/**
* @return mixed - array if session variable exist otherwise false.
*/
private function _getParseFromSession()
{
$tagsSession = $this->_getFromSession();
return (empty($tagsSession) || !isset($tagsSession))
? ''
: json_decode(stripslashes($tagsSession), true);
}
/**
* Get tags form SESSION variable or Cookies depends which exist,
* for $this->Contact->email
*
* @return string $tags
*/
private function _getContactTagsFromWebStorage()
{
$contactTags = $this->_getContactTagsFromCookie();
$contactTags = !empty($contactTags)
? $contactTags
: $this->_getContactTagsFromSession();
return strtolower($contactTags);
}
/**
* Get tags from cookie by $this->Contact->email
* @return string $tagsFromCookie - string of tags for contact email;
*/
private function _getContactTagsFromCookie()
{
$contactEmail = $this->_getContactEmail();
$tagsFromCookie = $this->_getParseCookie();
if (!empty( $tagsFromCookie )) {
$tagsFromCookie = (array_key_exists($contactEmail, $tagsFromCookie))
? $tagsFromCookie[$contactEmail]
: '';
}
return strtolower($tagsFromCookie);
}
/**
* Set tags for $this->Contact->email to Cookie from SESSION variable;
* @param string $sessionVariableWithAllTags - json from session variable
* @return boolean _setCookie()
*/
private function _setContactTagsToCookie($sessionVariableWithAllTags)
{
$contactEmail = $this->_getContactEmail();
$tagsCookie = $this->_getParseCookie();
$tagsSession = json_decode($sessionVariableWithAllTags, true);
if ($tagsCookie == null) {
return $this->_setCookie($sessionVariableWithAllTags);
}
if ((array_key_exists($contactEmail, $tagsCookie)
&& array_key_exists($contactEmail, $tagsSession))
|| (!array_key_exists($contactEmail, $tagsCookie)
&& array_key_exists($contactEmail, $tagsSession)
)
) {
$tagsCookie[$contactEmail] = $tagsSession[$contactEmail];
}
return $this->_setCookie(json_encode($tagsCookie));
}
/**
* Get tags from SESSION variable by $this->Contact->email
* @return string $sessionTags - string of tags for $this->Contact->email;
*/
private function _getContactTagsFromSession()
{
$contactEmail = $this->_getContactEmail();
$sessionTags = $this->_getParseFromSession();
if (!empty( $sessionTags )) {
$sessionTags = (array_key_exists($contactEmail, $sessionTags))
? $sessionTags[$contactEmail]
: '';
}
return strtolower($sessionTags);
}
/**
* Set tags for $this->Contact->email to Session variable;
* @param string $string - tags for $this->Contact->email
* @return string/json
*/
private function _setContactTagsToSession($string)
{
$contactEmail = $this->_getContactEmail();
if (!$this->sessionManager->getSessionTags()) {
$this->sessionManager->setSessionTags(json_encode(array($contactEmail => $string)));
return $this->sessionManager->getSessionTags();
}
$sessionUnJsonVariable = json_decode($this->sessionManager->getSessionTags(), true);
if (!is_array($sessionUnJsonVariable)) {
$this->sessionManager->setSessionTags('');
$this->_setContactTagsToSession($string);
}
$sessionUnJsonVariable[$contactEmail] = $string;
$this->sessionManager->setSessionTags(json_encode($sessionUnJsonVariable));
return $this->sessionManager->getSessionTags();
}
}
<?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;
use \Magento\Framework\Model\AbstractModel as MagentoAbstractModel;
use \Magento\Framework\Model\Context;
use \Magento\Framework\Registry;
use \Magento\Framework\UrlInterface;
use \Magento\Framework\App\Config\Storage\WriterInterface;
use \Magento\Store\Model\StoreManagerInterface;
use \Magento\Config\Model\ResourceModel\Config\Data\CollectionFactory as ConfigCollection;
use \Magento\Framework\App\Config\ScopeConfigInterface;
use \Magento\Framework\App\Cache\Manager as CacheManager;
use \SALESmanago\Entity\Settings;
use \SALESmanago\Factories\FactoryOrganizer;
abstract class AbstractModel extends MagentoAbstractModel
{
const
SETTINGS_PATH = 'benhauer_salesmanago/general',
SETTINGS_PATH_SM_STORE_ID = 'benhauer_salesmanago/storeId',
P_CONFIG = 'config',
P_OPTIONS = 'options',
P_PROPERTIES = 'properties',
ACTIVE = 'active',
CLIENT_ID = 'clientId',
SHA = 'sha',
API_KEY = 'apiKey',
API_SECRET = 'apiSecret',
ENDPOINT = 'endpoint',
TOKEN = 'token',
EMAIL = 'email',
WEB_PUSH = 'webPush',
SYNC_RULE = 'synchronizeRule',
LANG = 'lang',
C_MAIN = 'colorMain',
C_MAIN_FONT = 'colorMainFont',
C_ADDITIONAL = 'colorAdditional',
C_ADDITIONAL_FONT = 'colorAdditionalFont',
O_TYPES = 'orderTypes',
STORE_ID = 'storeId',
OWNER = 'owner',
E_COOKIE_TIME = 'eventCookie',
C_EVENT_COOKIE_TIME = 'eventCookie',
C_CALLBACK_OPTIN = 'callbackOptIn',
C_CALLBACK_OPTOUT = 'callbackOptOut',
C_CLIENT_ID = 'clientId',
C_SHA = 'sha',
C_ENDPOINT = 'endpoint',
C_OWNER_EMAIL = 'ownerEmail',
C_SYNCHRONIZE = 'synchronize',
C_DOUBLE_OPT_IN = 'doubleOptIn',
C_LOCATION = 'location',
C_API_KEY = 'apiKey',
C_TOKEN = 'token',
C_EXPIRES_TOKEN_AT = 'expiresTokenAt',
C_UPDATED_AT = 'updatedAt',
C_CREATE_AT = 'createdAt',
C_LANG = 'lang',
C_COLOR = 'color',
C_COLOR_MAIN = 'main',
C_COLOR_ADDITIONAL = 'additional',
C_COLOR_ADDITIONAL_FONT = 'additional_font',
C_PATH_DEVIDER = '/',
C_SETTINGS_PATH = 'salesmanago/settings',
C_STORES_WITH_CONFIGURATION = 'storesWithConfiguration',
C_CHECK_STORE_SCOPE_ID = 'checkStoreScopeId',
C_PLATFORM_SETTING_PATH = 'salesmanago_platform_settings/',
C_ACCOUNT_SETTINGS_PATH = 'salesmanago_account_settings/',
C_PATH_TYPE_GENERAL = 'general/',
C_PATH_TYPE_COLORS = 'color/',
C_PATH_TYPE_EVENTS = 'events/',
C_PATH_TYPE_CALLBACKS = 'callbacks/',
C_PATH_TYPE_API_DOUBLE_OPT_IN = 'apiDoubleOptIn/',
TAGS = 'tags',
T_NEWS = 'subscription',
T_REGISTER = 'registration',
T_LOGIN = 'login',
T_PURCHASE = 'purchase',
T_GUEST_PURCHASE ='purchaseGuest',
DOUBLE_OPT_IN = 'useApiDoubleOptIn',
DOUBLE_OPT_IN_EMAIL_TEMPLATE_ID = 'apiDoubleOptInEmailTemplateId',
DOUBLE_OPT_IN_EMAIL_ACCOUNT_ID = 'apiDoubleOptInEmailAccountId',
DOUBLE_OPT_IN_EMAIL_SUBJECT_ID = 'apiDoubleOptInEmailSubject';
public $cacheManager;
public $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT;
public $scopeId = 0;
public $updateAtTime = 0;
public $scopeConfigInterface;
public $storeManager;
public $configWriter;
public $collectionFactory;
public $defaultValue = [];
public $userValue = [];
public $factoryOrganizer;
public $settingItem = [];
public function __construct(
Context $context,
Registry $registry,
StoreManagerInterface $storeManager,
WriterInterface $configWriter,
ConfigCollection $collectionFactory,
FactoryOrganizer $factoryOrganizer,
ScopeConfigInterface $scopeConfigInterface,
CacheManager $cacheManager
) {
parent::__construct($context, $registry);
$this->cacheManager = $cacheManager;
$this->scopeConfigInterface = $scopeConfigInterface;
$this->storeManager = $storeManager;
$this->configWriter = $configWriter;
$this->collectionFactory = $collectionFactory;
$this->factoryOrganizer = $factoryOrganizer;
$this->defaultValue = [
'domain' => $this->storeManager
->getStore($this->scopeId)
->getBaseUrl(UrlInterface::URL_TYPE_WEB),
self::TAGS => [
self::T_LOGIN => 'magento2_login',
self::T_NEWS => 'magento2_newsletter',
self::T_PURCHASE => 'magento2_purchase',
self::T_REGISTER => 'magento2_register',
self::T_GUEST_PURCHASE => 'magento2_guest_purchase'
],
self::E_COOKIE_TIME => '3',
self::ACTIVE => false,
self::C_CREATE_AT => time(),
self::C_UPDATED_AT => time()
];
}
/**
* @param string $path - settings path;
* @param mixed $value - settings value;
*/
protected function setConfigItem($path, $value)
{
$this->scope = ($this->scopeId != 0) ? 'stores' : $this->scope;
$this->configWriter->save(
$path,
$value,
$this->scope,
$this->scopeId
);
}
/**
* @param string $path - settings path;
* @return string $item - config item value;
*/
protected function getConfigItem($path)
{
$scopeCode = $this->storeManager->getStore($this->scopeId)->getCode();
$scope = $this->scope;
if ($scopeCode == ScopeConfigInterface::SCOPE_TYPE_DEFAULT) {
$scopeCode = 0;
}
$settingItem = $this->collectionFactory
->create()
->addFieldToFilter('scope_id', array('eq' => $this->scopeId))
->addFieldToFilter('path', array('eq' => $path))
->getFirstItem()
->getData();
$item = isset($settingItem['value']) ? $settingItem['value'] : null;
return $item;
}
private function getSettingItem($scopeId, $path) {
return $this->collectionFactory
->create()
->addFieldToFilter('scope_id', array('eq' => $scopeId))
->addFieldToFilter('path', array('eq' => $path))
->getFirstItem()
->getData();
}
/**
* Check for existing configuration for current store id
* @return boolean - true - config exist, false - no
*/
public function isPluginConfActive()
{
$checkScopeId = $this->checkScopeId();
$clientId = $this->getClientId();
return ($clientId && $checkScopeId);
}
/**
* Set scope id - this need for check which stores configuration set (for which store view),
* magento load next configuration if curret (by store id) is not exist;
*
* @return $this;
*/
public function setScopeCheckId($scopeId)
{
$path = self::C_SETTINGS_PATH . self::C_PATH_DEVIDER . self::C_CHECK_STORE_SCOPE_ID;
$this->setConfigItem($path, $scopeId);
return $this;
}
/**
* Check if curret scope (by scope id) is seted in configuration,
* in this way script could check if some configuration exist for specific store id;
*/
public function checkScopeId()
{
$path = self::C_SETTINGS_PATH . self::C_PATH_DEVIDER . self::C_CHECK_STORE_SCOPE_ID;
$checkScopeId = $this->getConfigItem($path);
return ($this->scopeId == $checkScopeId);
}
/**
* Clear all cache values;
*/
protected function clearCache()
{
/*$this->cacheManager->flush($this->cacheManager->getAvailableTypes());*/
$this->cacheManager->clean($this->cacheManager->getAvailableTypes());
}
/**
* @param string $id - sm client id;
* @return $this;
*/
public function setClientId($id)
{
$this->setConfigItem(
self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_CLIENT_ID,
$id
);
return $this;
}
/**
* @return string sm clientId;
*/
public function getClientId()
{
return $this->getConfigItem(self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_CLIENT_ID);
}
/**
* @return string sm clientId;
*/
public function getClientsIds()
{
$stores = $this->storeManager->getStores();
$scopeId = $this->scopeId;
$clientIds = [];
foreach ($stores as $store) {
$storeId = $store->getId();
$this->scopeId = $storeId;
$clientId = $this->getConfigItem(self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_CLIENT_ID);
if ($clientId) {
array_push($clientIds, $clientId);
}
}
$this->scopeId = $scopeId;
return $clientIds;
}
/**
* @param string $sha - sm sha;
* @return $this;
*/
public function setSHA($sha)
{
$this->setConfigItem(
self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_SHA,
$sha
);
return $this;
}
/**
* @return string sm SHA;
*/
public function getSHA()
{
return $this->getConfigItem(self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_SHA);
}
/**
* @param string $apiKey - sm api key;
* @return $this;
*/
public function setApiKey($apiKey)
{
$this->setConfigItem(
self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_API_KEY,
$apiKey
);
return $this;
}
/**
* @return string sm Api Key;
*/
public function getApiKey()
{
return $this->getConfigItem(self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_API_KEY);
}
/**
* @param string $ownerEmail - sm owner email;
* @return $this;
*/
public function setOwner($ownerEmail)
{
$this->setConfigItem(
self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_OWNER_EMAIL,
$ownerEmail
);
return $this;
}
/**
* @return string sm owner email;
*/
public function getOwnerEmail()
{
return $this->getConfigItem(self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_OWNER_EMAIL);
}
/**
* @param string $endpoint - sm app endpoint;
* @return $this;
*/
public function setEndpoint($endpoint)
{
$this->setConfigItem(
self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_ENDPOINT,
$endpoint
);
return $this;
}
/**
* @return string sm endpoint;
*/
public function getEndpoint()
{
return $this->getConfigItem(self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_ENDPOINT);
}
/**
* @param string $token - sm token;
* @return $this;
*/
public function setToken($token)
{
$this->setConfigItem(
self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_TOKEN,
$token
);
return $this;
}
/**
* @return string sm token;
*/
public function getToken()
{
return $this->getConfigItem(self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_TOKEN);
}
/**
* Set expires token time
*/
public function setExpiresTokenAt()
{
$timestamp = time();
$now = date("Y-m-d H:i:s", $timestamp);
$this->setConfigItem(
self::C_SETTINGS_PATH . self::C_PATH_DEVIDER . self::C_EXPIRES_TOKEN_AT,
strtotime("$now +29 Days + 20 Hours")
);
return $this;
}
/**
* Get expires token time
*/
public function getExpiresTokenAt()
{
return $this->getConfigItem(self::C_SETTINGS_PATH . self::C_EXPIRES_TOKEN_AT);
}
/**
* Set update at time
*/
public function setUpdatedAtTime()
{
$this->setConfigItem(
self::C_SETTINGS_PATH . self::C_PATH_DEVIDER . self::C_UPDATED_AT,
time()
);
return $this;
}
/**
* Get update at time
*/
public function getUpdatedAtTime()
{
return $this->getConfigItem(self::C_SETTINGS_PATH . self::C_PATH_DEVIDER . self::C_UPDATED_AT);
}
/**
* Set created at time
*/
public function setCreatedAtTime()
{
$this->setConfigItem(
self::C_SETTINGS_PATH . self::C_PATH_DEVIDER . self::C_CREATE_AT,
time()
);
return $this;
}
/**
* Get created at time
*/
public function getCreatedAtTime()
{
return $this->getConfigItem(self::C_SETTINGS_PATH . self::C_PATH_DEVIDER . self::C_CREATE_AT);
}
/**
* @param string - sm lang;
* @return $this
*/
public function setLang($lang)
{
$this->setConfigItem(
self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_LANG,
$lang
);
return $this;
}
/**
* @return string sm lang;
*/
public function getLang()
{
return $this->getConfigItem(self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_LANG);
}
/**
* @param array $arrayColors an associative array (main, mainFont, additional, additionalFont) with colors
* @return $this
*/
public function setColors($arrayOfColors)
{
if (empty($arrayOfColors)) {
return $this;
}
foreach ($arrayOfColors as $colorName => $color) {
$this->setConfigItem(
self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_COLORS . $colorName,
$color
);
}
return $this;
}
/**
* @param array $array - an associative array of tags, where key is self::CONST name of tag & value is a tag;
*/
public function setTags($array = [])
{
$array = empty($array) ? $this->defaultValue[self::TAGS] : $array;
foreach ($array as $tagName => $tag) {
$this->setConfigItem(
self::C_PLATFORM_SETTING_PATH . self::TAGS . self::C_PATH_DEVIDER . $tagName,
$tag
);
}
return $this;
}
/**
* @param string self::CONST tag name
* @return mixed array of tags || string tag
*/
public function getTags($tagName = '')
{
if (!empty($tagName)) {
return $this->getConfigItem(self::C_PLATFORM_SETTING_PATH . self::TAGS . self::C_PATH_DEVIDER . $tagName);
}
$tags = [
self::T_NEWS => self::getTags(self::T_NEWS),
self::T_REGISTER => self::getTags(self::T_REGISTER),
self::T_LOGIN => self::getTags(self::T_LOGIN),
self::T_PURCHASE => self::getTags(self::T_PURCHASE),
self::T_GUEST_PURCHASE => self::getTags(self::T_GUEST_PURCHASE)
];
return $tags;
}
/**
* @param integer $hours
*/
public function setExtEventCookieLifeTime($hours = 3)
{
$this->setConfigItem(
self::C_PLATFORM_SETTING_PATH . self::C_PATH_TYPE_EVENTS . self::C_EVENT_COOKIE_TIME,
$hours
);
return $this;
}
/**
* @return integer - external cookie life time in hours
*/
public function getExtEventCookieLifeTime()
{
return $this->getConfigItem(self::C_PLATFORM_SETTING_PATH . self::C_PATH_TYPE_EVENTS . self::C_EVENT_COOKIE_TIME);
}
/**
* Get opt in configuration;
* @return array
*/
public function getDoubleOptInData()
{
$answer = [
self::DOUBLE_OPT_IN => boolval($this->getConfigItem(self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_API_DOUBLE_OPT_IN . self::DOUBLE_OPT_IN)),
self::DOUBLE_OPT_IN_EMAIL_TEMPLATE_ID => $this->getConfigItem(self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_API_DOUBLE_OPT_IN . self::DOUBLE_OPT_IN_EMAIL_TEMPLATE_ID),
self::DOUBLE_OPT_IN_EMAIL_ACCOUNT_ID => $this->getConfigItem(self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_API_DOUBLE_OPT_IN . self::DOUBLE_OPT_IN_EMAIL_ACCOUNT_ID),
self::DOUBLE_OPT_IN_EMAIL_SUBJECT_ID => $this->getConfigItem(self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_API_DOUBLE_OPT_IN . self::DOUBLE_OPT_IN_EMAIL_SUBJECT_ID)
];
return $answer;
}
/**
* Get synchronize rule state
* @return boolean;
*/
public function getSynchronize()
{
return boolval($this->getConfigItem(self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_SYNCHRONIZE));
}
/**
* @return $this;
*/
public function setCallbacks()
{
$storeDomain = $this->storeManager
->getStore($this->scopeId)
->getBaseUrl(UrlInterface::URL_TYPE_WEB);
$url = [
self::C_CALLBACK_OPTIN => $storeDomain . "salesmanago/newsletter/in?email=\$email\$&key=sha1(\$email\${$this->getClientId()})",
self::C_CALLBACK_OPTOUT => $storeDomain . "salesmanago/newsletter/out?email=\$email\$&key=sha1(\$email\${$this->getClientId()})"
];
$this->setConfigItem(
self::C_PLATFORM_SETTING_PATH . self::C_PATH_TYPE_CALLBACKS . self::C_CALLBACK_OPTIN,
$url[self::C_CALLBACK_OPTIN]
);
$this->setConfigItem(
self::C_PLATFORM_SETTING_PATH . self::C_PATH_TYPE_CALLBACKS . self::C_CALLBACK_OPTOUT,
$url[self::C_CALLBACK_OPTOUT]
);
return $this;
}
/**
* Gets all data core config for SM Service
* @return array of config
*/
public function getDataCoreConfig()
{
$clientId = $this->getClientId();
if ($clientId == null && $this->scopeId != 0) {
$this->scopeId = 0;
$this->getDataCoreConfig();
}
$answer = [
'tags' => self::getTags(),
'active' => false,
'createdAt' => $this->getCreatedAtTime(),
'updatedAt' => $this->getUpdatedAtTime(),
'clientId' => $this->getClientId(),
'sha' => $this->getSHA(),
'apiKey' => $this->getApiKey(),
'owner' => $this->getOwnerEmail(),
'endpoint' => $this->getEndpoint(),
'token' => $this->getToken(),
'expiresTokenAt' => $this->getExpiresTokenAt(),
'properties' => [
'lang' => $this->getLang(),
'color' => [
'main' => '#A8E622',
'mainFont' => '#D82424',
'additional' => '#DA4646',
'additionalFont' => '#B57C7C'
]
]
];
$doubleOptIn = $this->getDoubleOptInData();
$answer = !empty($doubleOptIn) ? array_merge($answer, $doubleOptIn) : $answer;
return $answer;
}
public function removePluginConfiguration()
{
try {
$pathToRemove = [
self::C_CHECK_STORE_SCOPE_ID => self::C_SETTINGS_PATH . self::C_PATH_DEVIDER . self::C_CHECK_STORE_SCOPE_ID,
self::C_CLIENT_ID => self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_CLIENT_ID,
self::C_SHA => self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_SHA,
self::C_API_KEY => self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_API_KEY,
self::C_OWNER_EMAIL => self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_OWNER_EMAIL,
self::C_ENDPOINT => self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_ENDPOINT,
self::C_TOKEN => self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_TOKEN,
self::C_EXPIRES_TOKEN_AT => self::C_SETTINGS_PATH . self::C_PATH_DEVIDER . self::C_EXPIRES_TOKEN_AT,
self::C_UPDATED_AT => self::C_SETTINGS_PATH . self::C_PATH_DEVIDER . self::C_UPDATED_AT,
self::C_CREATE_AT => self::C_SETTINGS_PATH . self::C_PATH_DEVIDER . self::C_CREATE_AT,
self::C_LANG => self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_GENERAL . self::C_LANG,
self::C_PATH_TYPE_COLORS => self::C_ACCOUNT_SETTINGS_PATH . self::C_PATH_TYPE_COLORS,
self::C_PATH_TYPE_COLORS => self::C_PLATFORM_SETTING_PATH . self::TAGS,
self::C_PATH_TYPE_CALLBACKS => self::C_PLATFORM_SETTING_PATH . self::C_PATH_TYPE_CALLBACKS
];
foreach ($pathToRemove as $path) {
$this->configWriter->delete($path, $this->scope, $this->scopeId);
}
$this->clearCache();
return true;
} catch (\Exception $e) {
return false;
}
}
/**
* Sets default configuration afte
*/
public function setDefaultAdditionalDataAfterInit()
{
$this
->setTags()
->setExtEventCookieLifeTime()
->setCallbacks()
->_setSMStoreId(
$this->storeManager->getStore($this->scopeId)->getUrl()
);
}
/**
* Sets the ids of stores which is configured (logged in)
*/
public function setsStoreIdsWithInitClient($storeId)
{
$path = self::C_SETTINGS_PATH . self::C_PATH_DEVIDER . self::C_STORES_WITH_CONFIGURATION;
$ids = $this->scopeConfigInterface->getValue($path);
// if (!empty($ids)) {
// $ids = explode($ids, ',');
// $ids = in_array($ids, $storeId) ?
// }
$this->configWriter->save($path, $value);
return $this;
}
public function update($id, $settings)
{
$this->setExpiresTokenAt();
}
public function prepareValue($settings, $default = false)
{
$this->userValue = $settings;
if ($default) {
$this->userValue = $this->arrayMergeRecursiveDistinct(
$this->defaultValue,
$settings
);
}
return $this;
}
public function buildValue()
{
return json_encode($this->userValue);
}
public function arrayMergeRecursiveDistinct(array &$array1, array &$array2)
{
$merged = $array1;
foreach ($array2 as $key => &$value) {
if (is_array($value)
&& isset($merged[$key])
&& is_array($merged[$key])
) {
$merged[$key] = $this->arrayMergeRecursiveDistinct(
$merged[$key],
$value
);
} else {
$merged[$key] = $value;
}
}
return $merged;
}
public function getValue()
{
$this->userValue = $this->getDataCoreConfig();
return $this;
}
public function extendValue($extend)
{
$this->userValue = $this->arrayMergeRecursiveDistinct(
$this->userValue,
$extend
);
return $this;
}
public function setUserData($value, $path = null)
{
}
/**
* @param string $string - one of scopes names: stores, websites, default;
* @return $this;
*/
public function setScope($string)
{
$this->scope = $string;
return $this;
}
/**
* @param integer $id - one of ids;
* @return $this
*/
public function setScopeId($id)
{
$this->scopeId = $id;
return $this;
}
public function filterData($data)
{
$data = array_map(function ($var) {
return is_array($var) ? self::filterData($var) : $var;
}, $data);
$data = array_filter($data, function ($value) {
return !empty($value) || $value === false;
});
return $data;
}
public function isSetKey($array, $key)
{
return isset($array[$key]) ? $array[$key] : "";
}
/**
* @param string $storeDomain
* @param string $settingsPath - for sm store id
* @return mixed
*/
public function getSMStoreId($storeDomain = null)
{
$path = self::C_PLATFORM_SETTING_PATH . self::C_PATH_TYPE_EVENTS . self::C_LOCATION;
$id = $this->getConfigItem($path);
if (empty($id) && $storeDomain == null) {
return '';
} elseif ($id == null && $storeDomain != null) {
return $this->_setSMStoreId($storeDomain);
}
return !empty($id) ? $id : '';
}
/**
* Generate and set SALESmanago store identificator based on platform home url;
* @param string $storeDomain - base Home Url form platform
* @param string $settingsPath - custom setting path
* @return boolean
*/
protected function _setSMStoreId($storeDomain = null, $settingsPath = null)
{
if ($storeDomain == null) {
return false;
}
$path = self::C_PLATFORM_SETTING_PATH . self::C_PATH_TYPE_EVENTS . self::C_LOCATION;
$id = hash('haval128,5', $storeDomain . $this->scopeId . $this->scope);
$this->setConfigItem($path, $id);
return $id;
}
}
<?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 \Psr\Log\LoggerInterface;
use \Magento\Framework\Stdlib\DateTime\TimezoneInterface as MagentoDateTime;
use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface as MagentoObserverInterface;
use \Magento\Checkout\Model\Session;
use \Magento\Store\Api\Data\StoreInterface;
use \Magento\Framework\UrlInterface;
use \Magento\Newsletter\Model\Subscriber;
use \Magento\Customer\Api\CustomerRepositoryInterface;
use \Magento\Framework\Stdlib\CookieManagerInterface;
use \Magento\Store\Model\StoreManagerInterface;
use \SALESmanago\Provider\UserProvider;
use \SALESmanago\Factories\FactoryOrganizer;
use \Benhauer\Salesmanago\Model\Hooks as HooksModel;
use \Benhauer\Salesmanago\Model\Contact;
use \Benhauer\Salesmanago\Helper\Tagger;
abstract class AbstractObserver implements MagentoObserverInterface
{
const
UPSERT_FLAG_STATUS = 'statusUpsert',
UPSERT_FLAG_ALL_DATA = 'allDataUpser',
UPSERT_FLAG_EMAIL = 'emailUpsert',
UPSERT_FLAG_NO_CHECK = 'noCheck';
public $session;
public $store;
public $subscriber;
public $model;
public $customerRepositoryInterface;
public $objDate;
public $factoryOrganizer;
public $cookieManager;
public $tagger;
public $logger;
public $CustomerSession;
public function __construct(
Session $session,
StoreInterface $store,
Subscriber $subscriber,
HooksModel $model,
CustomerRepositoryInterface $customerRepositoryInterface,
CookieManagerInterface $cookieManager,
MagentoDateTime $objDate,
FactoryOrganizer $factoryOrganizer,
Tagger $tagger,
LoggerInterface $logger,
Contact $modelContact,
StoreManagerInterface $storeManager
) {
$this->session = $session;
$this->store = $store;
$this->subscriber = $subscriber;
$this->customerRepositoryInterface = $customerRepositoryInterface;
$this->model = $model;
$this->factoryOrganizer = $factoryOrganizer;
$this->objDate = $objDate;
$this->cookieManager = $cookieManager;
$this->tagger = $tagger;
$this->logger = $logger;
$this->modelContact = $modelContact;
$this->storeManager = $storeManager;
}
public function execute(Observer $observer)
{
$this->setStoreViewForModel();
if ($this->model->getUserSettings(null) == false) {
return true;
}
$this->hookAct($observer);
}
/**
* Main method
* @param Observer $observer
* @return mixed
*/
public function hookAct(Observer $observer)
{
return $observer;
}
/**
* @param int $customerId
* @return array
* @throws \Exception
*/
public function getCustomerById($customerId)
{
try {
$Contact = $this->modelContact->getContactByCustomerId($customerId);
$Contact->getOptions()
->setAdditional(
[HooksModel::SYNC_RULE => $this->model->getSynchronizeRule()]
);
$contactData = $Contact->getDataOptions();
return $contactData;
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
public function getCartModified($observer)
{
try {
$cart = $observer->getCart()->getQuote();
$cartItems = $cart->getAllItems();
$prods = [
'ids' => [],
'names' => [],
'qty' => [],
'sku' => []
];
$dateTime = $this->objDate->date();
foreach ($cartItems 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());
}
}
$contactEvent = [
'date' => $dateTime->format('c'),
'description' => '',
'products' => implode(",", $prods['ids']),
'location' => $this->model->getSMStoreId(UrlInterface::URL_TYPE_WEB),
'value' => $cart->getGrandTotal(),
'detail1' => implode(",", $prods['names']),
'detail2' => implode("/", $prods['qty']),
'detail3' => implode(",", $prods['sku']),
'detail4' => $this->store->getLocaleCode(),
'externalId' => $cart->getEntityId()
];
return $this->model->filterData($contactEvent);
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
public function getProductsFromOrder($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());
}
}
$products = [
'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 $products;
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
public function createContactCookie($response)
{
try {
if ($response['success']) {
$connectSalesManago = $this->factoryOrganizer->getInst(
FactoryOrganizer::CONNECT_SALESMANAGO_C,
UserProvider::initSettingsUser($this->model)
);
$connectSalesManago->createCookie(
FactoryOrganizer::COOKIES_CLIENT,
$response['contactId']
);
}
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
/**
* Creates smevent cookie for CART event;
* @param $response - Sm response with smevent id;
*/
public function createEventCookie($response)
{
try {
if ($response['success']) {
$connectSalesManago = $this->factoryOrganizer->getInst(
FactoryOrganizer::CONNECT_SALESMANAGO_C,
UserProvider::initSettingsUser($this->model)
);
$extEventCookieLiveTime = intval($this->model->getExtEventCookieLifeTime());
$time = $this->objDate->date();
$period = $time->getTimestamp() + (3600 * $extEventCookieLiveTime);
$connectSalesManago->createCookie(
FactoryOrganizer::COOKIES_EXT_EVENT,
$response['eventId'],
$period
);
}
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
public function deleteEventCookie($response)
{
try {
if ($response['success']) {
$connectSalesManago = $this->getConnectSalesManago();
$connectSalesManago->deleteCookie(
FactoryOrganizer::COOKIES_EXT_EVENT
);
}
} catch (\Exception $e) {
}
}
public 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;
}
/**
* Subscribe contact to magento newsletter if "syncRule" & optIn state constact in SALESmanago
*
* @param $email
* @param $responceAfterUpsert
* @return bool
*/
public function synchronizeContactFromSm($email, $responceAfterUpsert)
{
try {
if (!isset($responceAfterUpsert['synchronizeFromSales'])) {
return true;
}
if (!$responceAfterUpsert['synchronizeFromSales']) {
return true;
}
$checkSubscriber = $this->subscriber->loadByEmail($email);
if ($this->session->getLastSyncEmail()
&& ($this->session->getLastSyncEmail() == $email)
) {
return true;
}
if ($checkSubscriber->isSubscribed()) {
return true;
}
$this->session->setProgrammaticallyNewsletterStatus(true);
if ($checkSubscriber->getOrigData() == null) {
//next one subscribing customer which don't exist in subscribers:
$checkSubscriber->subscribe($email);
$checkSubscriber->setStatus(Subscriber::STATUS_SUBSCRIBED)->save();
} else {
//next one change status:
$checkSubscriber->setStatus(Subscriber::STATUS_SUBSCRIBED)->save();
}
$this->session->setLastSyncEmail($email);
return true;
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
public function getConnectSalesManago()
{
$connectSalesManago = $this->factoryOrganizer->getInst(
FactoryOrganizer::CONNECT_SALESMANAGO_C,
UserProvider::initSettingsUser($this->model)
);
return $connectSalesManago;
}
/**
* @param int $contact - with key data & options;
* @return boolean
*/
public function isOptIn($contact)
{
if(!isset($contact['options'])){
return false;
}
if(!isset($contact['options']['forceOptIn'])){
return false;
}
return $contact['options']['forceOptIn'];
}
/**
* Set store view id from $this->requestPrams to each model;
*/
public function setStoreViewForModel()
{
$storeId = $this->storeManager->getStore()->getId();
if ($storeId != null && $storeId != 0) {
$this->model->setScopeId($storeId);
$this->model->setScope('store');
}
}
/**
* @param array $contact
* @param object $controller
*/
protected function upsertContact($contact, $controller, $flag = self::UPSERT_FLAG_NO_CHECK)
{
$response = $controller->contactUpsert(
$contact['data'],
$contact['options'],
''
);
$this->createContactCookie($response);
$this->synchronizeContactFromSm(
$contact['data']['email'],
$response
);
return $response;
}
/**
* @param string $email
* @param string $flag $this CONST;
*/
protected function setCheckUpsertFlags($email, $flag)
{
if ($flag == self::UPSERT_FLAG_NO_CHECK) {
return true;
}
$arrFlag = json_decode($this->session->getUpsertFlags(), true);
if (boolval($arrFlag) && in_array($flag, $arrFlag[$email])) {
return false;
} else if (boolval($arrFlag) && !in_array($flag, $arrFlag[$email])) {
array_push($arrFlag[$email], $flag);
} else if (!boolval($arrFlag)) {
$arrFlag = [$email => [] ];
array_push($arrFlag[$email], $flag);
}
$this->session->setUpsertFlags(json_encode($arrFlag));
return true;
}
}
<?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());
}
}
}
<?php
namespace Benhauer\Salesmanago\Observer\Events\Purchase;
use \Psr\Log\LoggerInterface;
use \Magento\Framework\Stdlib\DateTime\TimezoneInterface as MagentoDateTime;
use \Magento\Framework\Event\ObserverInterface;
use \Magento\Checkout\Model\Session;
use \Magento\Store\Api\Data\StoreInterface;
use \Magento\Framework\UrlInterface;
use \Magento\Newsletter\Model\Subscriber;
use \Magento\Customer\Api\CustomerRepositoryInterface;
use \Magento\Framework\Stdlib\CookieManagerInterface;
use \Magento\Store\Model\StoreManagerInterface;
use \Magento\Sales\Api\OrderRepositoryInterface;
use \Magento\Quote\Model\QuoteFactory;
use \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory;
use \Magento\Framework\Session\SessionManagerInterface;
use \Magento\Framework\Event\Observer;
use \SALESmanago\Services\ConnectSalesManagoService;
use \SALESmanago\Provider\UserProvider;
use \SALESmanago\Factories\FactoryOrganizer;
use \Benhauer\Salesmanago\Model\Hooks as HooksModel;
use \Benhauer\Salesmanago\Model\Contact;
use \Benhauer\Salesmanago\Helper\Tagger;
use \Benhauer\Salesmanago\Model\Config\PurchasesConfig;
use \Benhauer\Salesmanago\Observer\AbstractObserver as SalesmanagoAbstractObserver;
abstract class AbstractPurchaseObserver extends SalesmanagoAbstractObserver
{
public $purchasesConfigModel;
public $orderRepository;
public $quoteFactory;
const ORDER_ID_COOKIE_NAME = 'smorid';
static $cookieExpiredTime = 30960000;
public function __construct(
Session $session,
StoreInterface $store,
Subscriber $subscriber,
HooksModel $model,
CustomerRepositoryInterface $customerRepositoryInterface,
CookieManagerInterface $cookieManager,
MagentoDateTime $objDate,
FactoryOrganizer $factoryOrganizer,
Tagger $tagger,
LoggerInterface $logger,
Contact $modelContact,
StoreManagerInterface $storeManager,
PurchasesConfig $purchasesConfigModel,
OrderRepositoryInterface $orderRepository,
QuoteFactory $quoteFactory,
CookieMetadataFactory $cookieMetadataFactory,
SessionManagerInterface $sessionManager
) {
parent::__construct(
$session,
$store,
$subscriber,
$model,
$customerRepositoryInterface,
$cookieManager,
$objDate,
$factoryOrganizer,
$tagger,
$logger,
$modelContact,
$storeManager
);
$this->purchasesConfigModel = $purchasesConfigModel;
$this->orderRepository = $orderRepository;
$this->quoteFactory = $quoteFactory;
$this->cookieMetadataFactory = $cookieMetadataFactory;
$this->sessionManager = $sessionManager;
}
public function execute(Observer $observer)
{
if ($this->purchasesConfigModel->getType() == PurchasesConfig::P_T_CRON) {
$this->deleteEventCookie(['success' => true]);
}
if (!$this->purchasesConfigModel->isHookActive($observer->getEvent()->getName())) {
return false;
}
$this->setStoreViewForModel();
if ($this->model->getUserSettings(null) == false) {
return true;
}
$this->hookAct($observer);
}
public function hookAct(Observer $observer){}
public function executePurchase($order = null) {
try {
if (empty($order)) {
return false;
}
$contact = '';
$billingAddress = $order->getBillingAddress();
$customerEmail = $billingAddress->getEmail();
$smClientCookie = $this->cookieManager->getCookie('smclient');
$connectSalesManago = $this->getConnectSalesManago();
if ($order->getCustomerId() == null
&& $order->getCustomerIsGuest()
) {
$Contact = $this->modelContact->getContactByCustomerBillingAddress($billingAddress, $customerEmail);
$Contact->getOptions()->setAdditional(
[HooksModel::SYNC_RULE => $this->model->getSynchronizeRule()]
);
$contact = $Contact->getDataOptions();
$contact = $this->tagger
->setModel($this->model)
->setTags($contact, [Tagger::T_PURCHASE, Tagger::T_GUEST_PURCHASE]);
$response = $this->upsertContact($contact, $connectSalesManago, SalesmanagoAbstractObserver::UPSERT_FLAG_ALL_DATA);
} elseif ($order->getCustomerId() != null) {
$customerId = $order->getCustomerId();
$contact = $this->getCustomerById($customerId);
$contact = $this->tagger
->setModel($this->model)
->setTags($contact, Tagger::T_PURCHASE);
$response = $this->upsertContact($contact, $connectSalesManago, SalesmanagoAbstractObserver::UPSERT_FLAG_ALL_DATA);
}
if (isset($contact['data'])) {
$contact = $contact['data'];
} elseif ($smClientCookie != null && !isset($contact['email'])) {
$contact = [
'contactId' => $smClientCookie
];
}
$products = $this->getProductsFromOrder($order, $this->quoteFactory);
if (isset($products['description']) && (strpos($products['description'], 'klarna') !== false)) {
return true;
}
$response = $connectSalesManago->contactExtEvent(
ConnectSalesManagoService::EVENT_TYPE_PURCHASE,
$products,
$contact,
''
);
$this->deleteEventCookie($response);
return true;
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
/**
* Set order Id to cookie;
*/
protected function setOrderIdToCookie($value)
{
$this->session->setSmOrderId($value);
$metadata = $this->cookieMetadataFactory
->createPublicCookieMetadata()
->setDuration(self::$cookieExpiredTime)
->setPath($this->sessionManager->getCookiePath())
->setDomain($this->sessionManager->getCookieDomain());
$this->cookieManager->setPublicCookie(self::ORDER_ID_COOKIE_NAME, $value, $metadata);
}
/**
* Gets order Id from cookie;
*/
protected function getOrderIdFromCookie()
{
$sessionOrderId = $this->session->getSmOrderId();
$cookieOrderId = $this->cookieManager->getCookie(self::ORDER_ID_COOKIE_NAME);
$orderId = empty($sessionOrderId) ? $cookieOrderId : $sessionOrderId;
return $orderId;
}
}
<?php
namespace Benhauer\Salesmanago\Observer\Events\Purchase;
use \Psr\Log\LoggerInterface;
use \Magento\Framework\Stdlib\DateTime\TimezoneInterface as MagentoDateTime;
use \Magento\Checkout\Model\Session;
use \Magento\Store\Api\Data\StoreInterface;
use \Magento\Newsletter\Model\Subscriber;
use \Magento\Sales\Api\OrderRepositoryInterface;
use \Magento\Quote\Model\QuoteFactory;
use \Magento\Framework\Stdlib\CookieManagerInterface;
use \Magento\Customer\Api\CustomerRepositoryInterface;
use \Magento\Framework\Event\Observer;
use \Magento\Store\Model\StoreManagerInterface;
use \SALESmanago\Factories\FactoryOrganizer;
use \SALESmanago\Provider\UserProvider;
use \SALESmanago\Services\ConnectSalesManagoService;
use \Benhauer\Salesmanago\Observer\AbstractObserver;
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 KlarnaCheckOutAction extends SalesmanagoAbstractObserver
{
public $orderRepository;
public $quoteFactory;
public $cookieManager;
const PAYMENT_METHOD = 'klarna';
public function hookAct(Observer $observer)
{
try {
$order = $observer->getEvent()->getOrder();
$paymentMethod = $order->getPayment()->getMethod();
if (strpos($paymentMethod, self::PAYMENT_METHOD) === false) {
return true;
}
$contact = '';
$billingAddress = $order->getBillingAddress();
$customerEmail = $billingAddress->getEmail();
$smClientCookie = $this->cookieManager->getCookie('smclient');
$connectSalesManago = $this->getConnectSalesManago();
if ($order->getCustomerId() == null
&& $order->getCustomerIsGuest()
) {
$Contact = $this->modelContact->getContactByCustomerBillingAddress($billingAddress, $customerEmail);
$Contact->getOptions()->setAdditional(
[HooksModel::SYNC_RULE => $this->model->getSynchronizeRule()]
);
$contact = $Contact->getDataOptions();
$contact = $this->tagger
->setModel($this->model)
->setTags($contact, [Tagger::T_PURCHASE, Tagger::T_GUEST_PURCHASE]);
$response = $this->upsertContact($contact, $connectSalesManago, SalesmanagoAbstractObserver::UPSERT_FLAG_ALL_DATA);
} elseif ($order->getCustomerId() != null) {
$customerId = $order->getCustomerId();
$contact = $this->getCustomerById($customerId);
$contact = $this->tagger
->setModel($this->model)
->setTags($contact, Tagger::T_PURCHASE);
$response = $this->upsertContact($contact, $connectSalesManago, SalesmanagoAbstractObserver::UPSERT_FLAG_ALL_DATA);
$contact = $contact['data'];
}
if (isset($contact['data'])) {
$contact = $contact['data'];
} elseif ($smClientCookie != null && !isset($contact['email'])) {
$contact = [
'contactId' => $smClientCookie
];
}
$products = $this->getProductsFromOrder($order, $this->quoteFactory);
$response = $connectSalesManago->contactExtEvent(
ConnectSalesManagoService::EVENT_TYPE_PURCHASE,
$products,
$contact,
''
);
$this->deleteEventCookie($response);
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
}
<?php
namespace Benhauer\Salesmanago\Observer\Events\Purchase;
use \Psr\Log\LoggerInterface;
use \Magento\Framework\Stdlib\DateTime\TimezoneInterface as MagentoDateTime;
use \Magento\Checkout\Model\Session;
use \Magento\Store\Api\Data\StoreInterface;
use \Magento\Newsletter\Model\Subscriber;
use \Magento\Sales\Api\OrderRepositoryInterface;
use \Magento\Quote\Model\QuoteFactory;
use \Magento\Framework\Stdlib\CookieManagerInterface;
use \Magento\Customer\Api\CustomerRepositoryInterface;
use \Magento\Framework\Event\Observer;
use \Magento\Store\Model\StoreManagerInterface;
use \SALESmanago\Factories\FactoryOrganizer;
use \SALESmanago\Provider\UserProvider;
use \SALESmanago\Services\ConnectSalesManagoService;
use \Benhauer\Salesmanago\Observer\AbstractObserver;
use \Benhauer\Salesmanago\Model\Hooks as HooksModel;
use \Benhauer\Salesmanago\Model\Contact;
use \Benhauer\Salesmanago\Helper\Tagger;
use \Benhauer\Salesmanago\Helper\Config as SmPluginConfig;
use Benhauer\Salesmanago\Observer\AbstractObserver as SalesmanagoAbstractObserver;
class OrderStatusChanged extends SalesmanagoAbstractObserver
{
public $orderRepository;
public $quoteFactory;
public $cookieManager;
public function __construct(
Session $session,
StoreInterface $store,
Subscriber $subscriber,
HooksModel $model,
CustomerRepositoryInterface $customerRepositoryInterface,
CookieManagerInterface $cookieManager,
MagentoDateTime $objDate,
FactoryOrganizer $factoryOrganizer,
Tagger $tagger,
LoggerInterface $logger,
Contact $modelContact,
StoreManagerInterface $storeManager,
QuoteFactory $quoteFactory
) {
parent::__construct(
$session,
$store,
$subscriber,
$model,
$customerRepositoryInterface,
$cookieManager,
$objDate,
$factoryOrganizer,
$tagger,
$logger,
$modelContact,
$storeManager
);
$this->quoteFactory = $quoteFactory;
}
public function hookAct(Observer $observer)
{
$order = $observer->getOrder();
$orderStatus = $order->getStatus();
//Runs for special order types
if ($type = $this->model->checkOrderStatusToProcess($orderStatus)) {
$this->sendExternalEventFromOrder($order, false, $type);
}
if (!SmPluginConfig::$enOrderTypes) {
return true;
}
$orderTypes = $this->model->getSubmittedOrderTypes();
// Only trigger when an order enters processing state.
if ($this->model->checkIfOrderStatusChoosed($orderStatus)) {
$this->sendExternalEventFromOrder($order);
return true;
}
return false;
}
public function sendExternalEventFromOrder($order, $withUpsert = true, $eventType = 'OTHER')
{
try {
$contact = '';
$billingAddress = $order->getBillingAddress();
$customerEmail = $billingAddress->getEmail();
$connectSalesManago = $this->getConnectSalesManago();
if ($order->getCustomerId() == null && $order->getCustomerIsGuest()) {
$Contact = $this->modelContact->getContactByCustomerBillingAddress($billingAddress, $customerEmail);
$Contact->getOptions()->setAdditional(
[HooksModel::SYNC_RULE => $this->model->getSynchronizeRule()]
);
$contact = $Contact->getDataOptions();
if ($withUpsert) {
$contact = $this->tagger
->setModel($this->model)
->setTags($contact, [Tagger::T_PURCHASE, Tagger::T_GUEST_PURCHASE]);
$response = $this->upsertContact($contact, $connectSalesManago, SalesmanagoAbstractObserver::UPSERT_FLAG_ALL_DATA);
}
} elseif ($order->getCustomerId() != null) {
$Contact = $this->modelContact->getContactByCustomerId($order->getCustomerId());
$contact = $Contact->getDataOptions();
if ($withUpsert) {
$contact = $this->tagger
->setModel($this->model)
->setTags($contact, Tagger::T_PURCHASE);
$response = $this->upsertContact($contact, $connectSalesManago, SalesmanagoAbstractObserver::UPSERT_FLAG_ALL_DATA);
}
$contact = $contact['data'];
}
if (isset($contact['data'])) {
$contact = $contact['data'];
}
if (!isset($contact['email']) || empty($contact['email'])) {
return true;
}
$products = $this->getProductsFromOrder($order, $this->quoteFactory);
$products['description'] = ($eventType == 'OTHER')
? $order->getState()
: $products['description'];
$response = $connectSalesManago->contactExtEvent(
$eventType,
$products,
$contact,
''
);
$this->deleteEventCookie($response);
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
}
<?php
namespace Benhauer\Salesmanago\Observer\Events\Purchase;
use \Benhauer\Salesmanago\Model\Config\PurchasesConfig;
use \Magento\Framework\Event\Observer;
use \Benhauer\Salesmanago\Observer\Events\Purchase\AbstractPurchaseObserver as SalesmanagoAbstractPurchaseObserver;
class PurchaseObserver extends SalesmanagoAbstractPurchaseObserver
{
public function hookAct(Observer $observer)
{
try {
$order = $observer->getData('order');
$orderIds = $observer->getData('order_ids');
/*this is for specific hooks*/
if (empty($order) && $orderIds) {
$orderId = reset($orderIds);
$order = $this->orderRepository->get($orderId);
}
$type = $this->purchasesConfigModel->getType();
if ($type == PurchasesConfig::P_T_ON_EVENT
&& $observer->getEvent()->getName() == PurchasesConfig::$defaultPurchaseEvent
) {
$this->setOrderIdToCookie($order->getId);
return true;
} else if (
$type == PurchasesConfig::P_T_ON_EVENT
&& $observer->getEvent()->getName() == $this->purchasesConfigModel->getConfig()
) {
$orderId = $this->getOrderIdFromCookie();
$order = $this->orderRepository->get($orderId);
} else if ($type != PurchasesConfig::P_T_ON_EVENT
&& $type != PurchasesConfig::P_T_ON_EVENT
&& $type != PurchasesConfig::P_T_ON_CHOOSEN_EVENT
&& $observer->getEvent()->getName() != PurchasesConfig::$defaultPurchaseEvent
) {
return false;
}
if (empty($order)) {
return false;
}
return $this->executePurchase($order);
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
}
<?php
namespace Benhauer\Salesmanago\Observer;
use \Psr\Log\LoggerInterface;
use \Magento\Framework\Stdlib\DateTime\TimezoneInterface as MagentoDateTime;
use \Magento\Checkout\Model\Session;
use \Magento\Store\Api\Data\StoreInterface;
use \Magento\Newsletter\Model\Subscriber;
use \Magento\Sales\Api\OrderRepositoryInterface;
use \Magento\Quote\Model\QuoteFactory;
use \Magento\Framework\Stdlib\CookieManagerInterface;
use \Magento\Customer\Api\CustomerRepositoryInterface;
use \Magento\Framework\Event\Observer;
use \Magento\Store\Model\StoreManagerInterface;
use \SALESmanago\Factories\FactoryOrganizer;
use \SALESmanago\Provider\UserProvider;
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 KlarnaCheckOutAction extends SalesmanagoAbstractObserver
{
public $orderRepository;
public $quoteFactory;
public $cookieManager;
const PAYMENT_METHOD = 'klarna';
public function __construct(
Session $session,
StoreInterface $store,
Subscriber $subscriber,
OrderRepositoryInterface $orderRepository,
QuoteFactory $quoteFactory,
HooksModel $model,
CookieManagerInterface $cookieManager,
MagentoDateTime $objDate,
FactoryOrganizer $factoryOrganizer,
CustomerRepositoryInterface $customerRepositoryInterface,
Tagger $tagger,
LoggerInterface $logger,
Contact $modelContact,
StoreManagerInterface $storeManager
) {
parent::__construct(
$session,
$store,
$subscriber,
$model,
$customerRepositoryInterface,
$cookieManager,
$objDate,
$factoryOrganizer,
$tagger,
$logger,
$modelContact,
$storeManager
);
$this->orderRepository = $orderRepository;
$this->quoteFactory = $quoteFactory;
}
public function hookAct(Observer $observer)
{
try {
$order = $observer->getEvent()->getOrder();
$paymentMethod = $order->getPayment()->getMethod();
if (strpos($paymentMethod, self::PAYMENT_METHOD) === false) {
return true;
}
$contact = '';
$billingAddress = $order->getBillingAddress();
$customerEmail = $billingAddress->getEmail();
$smClientCookie = $this->cookieManager->getCookie('smclient');
$connectSalesManago = $this->getConnectSalesManago();
if ($order->getCustomerId() == null
&& $order->getCustomerIsGuest()
) {
$Contact = $this->modelContact->getContactByCustomerBillingAddress($billingAddress, $customerEmail);
$Contact->getOptions()->setAdditional(
[HooksModel::SYNC_RULE => $this->model->getSynchronizeRule()]
);
$contact = $Contact->getDataOptions();
$contact = $this->tagger
->setModel($this->model)
->setTags($contact, [Tagger::T_PURCHASE, Tagger::T_GUEST_PURCHASE]);
$response = $this->upsertContact($contact, $connectSalesManago, SalesmanagoAbstractObserver::UPSERT_FLAG_ALL_DATA);
/*$response = $connectSalesManago->contactUpsert(
$contact['data'],
$contact['options'],
''
);
$this->createContactCookie($response);
$this->synchronizeContactFromSm(
$Contact->getEmail(),
$response
);*/
} elseif ($order->getCustomerId() != null) {
$customerId = $order->getCustomerId();
$contact = $this->getCustomerById($customerId);
$contact = $this->tagger
->setModel($this->model)
->setTags($contact, Tagger::T_PURCHASE);
$response = $this->upsertContact($contact, $connectSalesManago, SalesmanagoAbstractObserver::UPSERT_FLAG_ALL_DATA);
$contact = $contact['data'];
}
if (isset($contact['data'])) {
$contact = $contact['data'];
} elseif ($smClientCookie != null && !isset($contact['email'])) {
$contact = [
'contactId' => $smClientCookie
];
}
$products = $this->getProductsFromOrder($order, $this->quoteFactory);
$response = $connectSalesManago->contactExtEvent(
ConnectSalesManagoService::EVENT_TYPE_PURCHASE,
$products,
$contact,
''
);
$this->deleteEventCookie($response);
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
}
<?php
namespace Benhauer\Salesmanago\Observer;
use \Psr\Log\LoggerInterface;
use \Magento\Framework\Stdlib\DateTime\TimezoneInterface as MagentoDateTime;
use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;
use \Magento\Checkout\Model\Session;
use \Magento\Store\Api\Data\StoreInterface;
use \Magento\Framework\UrlInterface;
use \Magento\Newsletter\Model\Subscriber;
use \Magento\Customer\Api\CustomerRepositoryInterface;
use \Magento\Framework\Stdlib\CookieManagerInterface;
use \Magento\Store\Model\StoreManagerInterface;
use \SALESmanago\Provider\UserProvider;
use \SALESmanago\Factories\FactoryOrganizer;
use \Benhauer\Salesmanago\Model\Hooks as HooksModel;
use \Benhauer\Salesmanago\Model\Contact;
use \Benhauer\Salesmanago\Helper\Tagger;
use \Magento\Customer\Model\Session as CustomerSession;
use \Benhauer\Salesmanago\Observer\AbstractObserver as SalesmanagoAbstractObserver;
class NewsletterStatusModified extends SalesmanagoAbstractObserver
{
public $CustomerSession;
public function __construct(
Session $session,
StoreInterface $store,
Subscriber $subscriber,
HooksModel $model,
CustomerRepositoryInterface $customerRepositoryInterface,
CookieManagerInterface $cookieManager,
MagentoDateTime $objDate,
FactoryOrganizer $factoryOrganizer,
Tagger $tagger,
LoggerInterface $logger,
CustomerSession $CustomerSession,
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 {
/**Status 4 is setted while double optin is active, this if prevent from multiply upsert*/
if ($observer->getSubscriber()->getStatus() == 4
&& $this->model->getApiDoubleOptIn() != false
) {
return true;
}
if ($this->session->getProgrammaticallyNewsletterStatus()) {
$this->session->setProgrammaticallyNewsletterStatus(false);
return true;
}
if (($this->session->getLastSubscribedEmail() == $observer->getSubscriber()->getEmail())
&& !$this->isSubscriberStatusChanged($observer->getSubscriber())
) {
return true;
}
$customerId = $observer->getSubscriber()->getCustomerId();
$connectSalesManago = $this->getConnectSalesManago();
if ($customerId != 0) {
$contact = $this->getCustomerById($customerId);
} else {
$contact['data'] = [
'email' => $observer->getSubscriber()->getSubscriberEmail()
];
$contact['options'] = [
'forceOptIn' => $observer->getSubscriber()->isSubscribed(),
'forceOptOut' => !$observer->getSubscriber()->isSubscribed(),
'forcePhoneOptIn' => $observer->getSubscriber()->isSubscribed(),
'forcePhoneOptOut' => !$observer->getSubscriber()->isSubscribed(),
HooksModel::SYNC_RULE => $this->model->getSynchronizeRule(),
'createdOn' => method_exists($observer->getSubscriber(), 'getCreatedAt')
? date("F j, Y, g:i a", $observer->getSubscriber()->getCreatedAt())
: date("F j, Y, g:i a", time())
];
}
$contact = $this->setContactApiDoubleOptIn($contact, $observer->getSubscriber());
$reqSubscriptionConfirmation = false;
$contact = $this->tagger
->setModel($this->model)
->setCheckOptInState(false)
->setTags($contact, Tagger::T_NEWSLETTER, $reqSubscriptionConfirmation);
$this->upsertContact($contact, $connectSalesManago, self::UPSERT_FLAG_STATUS);
$this->session->setLastSubscribedEmail($observer->getSubscriber()->getEmail());
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
/**
* @param array $contact - with key data & options;
* @param object $subscriber
* @return array $contact
* @throws \Exception
*/
public function setContactApiDoubleOptIn($contact, $subscriber)
{
try {
$apiDoubleOptin = $this->CustomerSession->getApiDoubleOptInData();
$email = $contact['data']['email'];
if (is_array($apiDoubleOptin)
&& array_key_exists($email, $apiDoubleOptin)
&& $apiDoubleOptin[$email]) {
return $contact;
}
$apiDoubleOptinConf = $this->model->getApiDoubleOptIn();
if ($apiDoubleOptinConf['useApiDoubleOptIn']
&& $this->isOptIn($contact)
) {
if (!empty($apiDoubleOptin)) {
$apiDoubleOptin = array_merge($apiDoubleOptin, [$email => true]);
} else {
$apiDoubleOptin = [$email => true];
}
$this->session->setProgrammaticallyNewsletterStatus(true);
$subscriber->setStatus(Subscriber::STATUS_UNCONFIRMED)->save();
$this->CustomerSession->setApiDoubleOptInData($apiDoubleOptin);
$contact['options'] = array_merge($contact['options'], $this->model->getApiDoubleOptIn());
}
return $contact;
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
private function isSubscriberStatusChanged($subscriber)
{
try {
$previousStatus = (int) $subscriber->getOrigData('subscriber_status');
$currentStatus = (int) $subscriber->getStatus();
if ($previousStatus != $currentStatus) {
return true;
}
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
return false;
}
}
<?php
namespace Benhauer\Salesmanago\Observer;
use \Magento\Framework\Event\Observer;
use \Benhauer\Salesmanago\Observer\AbstractObserver as SalesmanagoAbstractObserver;
class WishlistModified extends SalesmanagoAbstractObserver
{
public function hookAct(Observer $observer)
{
try {
$eventItems = $observer->getEvent()->getItems();
$product = reset($eventItems)->getProduct();
$customerId = reset($eventItems)->getWishlist()->getCustomerId();
$customer = $this->customerRepositoryInterface->getById($customerId);
$customerEmail = $customer->getEmail();
$productId = $product->getEntityId();
$productName = $product->getName();
$productValue = round($product->getPrice(), 2);
$dateTime = $this->objDate->date();
$connectSalesManago = $this->getConnectSalesManago();
$eventData = [
'date' => $dateTime->format('c'),
'products' => $productId,
'value' => $productValue,
'detail1' => $productName,
'description' => 'WISHLIST',
];
$contact = ['email' => $customerEmail];
$connectSalesManago->contactExtEvent(
"OTHER",
$eventData,
$contact,
''
);
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
}
SALESmanago integration for Magento 2
=======================
Magento 2 package for SALESmanago integration
Just install the package, login to it from you Magento admin panel and it is ready!
More at https://support.salesmanago.com/integration-with-magento-1-2/
The scope of integration
========================
Basic scope of integration
Integrate external events like ‘cart’ or ‘purchase’ both for contacts who are logged in and those who are not – as long as they have a tracking cookie smclient
Export of contacts and historical transactions from e-commerce platform
Automatic addition of a monitoring code to a website
Possibility of assigning tags when a contact registers, signs up for a newsletter or makes a purchase, later these contacts with tags will be sent to the system
Automatic addition of such features as Live Chat, Pop-up Basic and Web Push
Contact form integration
Adding a monitoring parameter to contacts that filled in a contact form
Transfer of information given when contacts register and log in
Transfer of contact data (e.g. name and surname, email address, telephone number, address, company name, date of birth, date of creating a contact, tags assigned in the shop)
Transfer of contacts along with their opt-in/opt-out
status
Back synchronisation (This feature enables checking if contacts who register on e-commerce platform can already be found in SALESmanago database. When a contact exists in the database with opt-in status but while registration does not give a consent, in both SALESmanago system and e-commerce platform the contact has opt-in status.)
Transfer of contacts together with tags indicating name of the shop
Requirements
============
* PHP >= 5.5
* cURL Extension
Installation
============
composer require benhauer/salesmanago-integration
Run next Magento commands:
php bin/magento setup:upgrade;
php bin/magento setup:di:compile;
php bin/magento setup:static-content:deploy;
php bin/magento cache:flush;
<?php
namespace Benhauer\Salesmanago\UI\DataProvider;
use \Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface;
use \Magento\Ui\DataProvider\AbstractDataProvider;
class AccountSettingsDataProvider extends AbstractDataProvider implements DataProviderInterface
{
// public function getData()
// {
// return $this->searchResultToOutput($this->getSearchResult());
// }
public function prepareDataSource(array $dataSource) {
return [
'data' => [
'config' => [
'componentType'=>'container',
'location' => '123123'
],
'items' => [
'location' => '1231235'
]
]
];
// if (isset($dataSource['data']['items'])) {
// foreach ($dataSource['data']['items'] as &$item) {
// $item[$this->getData('name')]['edit'] = [
// 'href' => $this->urlBuilder->getUrl(
// 'contacts/test/edit',
// ['id' => $item['pfay_contacts_id']]
// ),
// 'label' => __('Edit'),
// 'hidden' => false,
// ];
// $item[$this->getData('name')]['delete'] = [
// 'href' => $this->urlBuilder->getUrl(
// 'contacts/test/delete',
// ['id' => $item['pfay_contacts_id']]
// ),
// 'label' => __('Delete'),
// 'hidden' => false,
// ];
// }
// }
// return $dataSource;
}
public function addFilter(\Magento\Framework\Api\Filter $filter)
{
return;
}
}
{
"name": "salesmanago/integration",
"description": "Magento2 marketing automation extension",
"type": "magento2-module",
"version": "3.1.0",
"license": [
"OSL-3.0",
"AFL-3.0"
],
"require": {
"php": "~7.2.0||~7.3.0",
"guzzlehttp/guzzle": "^6.3",
"salesmanago/api-sso-util": "2.5.4"
},
"autoload": {
"files": [
"registration.php"
],
"psr-4": {
"Benhauer\\Salesmanago\\": ""
}
},
"authors": [
{
"name": "SALESmanago",
"email": "dev@salesmanago.pl"
}
]
}
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
<acl>
<resources>
<resource id="Magento_Backend::admin">
<resource id="Magento_Backend::stores">
<resource id="Magento_Backend::stores_settings">
<resource id="Magento_Config::config">
<resource id="Benhauer_Salesmanago::benhauer_salesmanago" title="Salesmanago"/>
</resource>
</resource>
</resource>
</resource>
</resources>
</acl>
</config>
\ No newline at end of file
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
<menu>
<add id="Benhauers_Salesmanago::SalesmanagoIndex"
title="Salesmanago"
module="Benhauer_Salesmanago"
sortOrder="9999"
action="salesmanago/config/index"
resource="Magento_Backend::content" />
</menu>
</config>
<?xml version="1.0"?>
<!--
/**
* @author Salesmanago Team
* @copyright Copyright (c) 2019 Salesmanago (http://www.salesmanago.com)
* @package Benhauer_Salesmanago
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="salesmanago" frontName="salesmanago">
<module name="Benhauer_Salesmanago"/>
</route>
</router>
</config>
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<tab id="salesmanago" translate="label" sortOrder="10">
<label>SALESmanago</label>
</tab>
<section id="salesmanago_account_settings" translate="label" sortOrder="131" showInDefault="1" showInWebsite="1" showInStore="1">
<class>separator-top</class>
<label>Account Settings</label>
<tab>salesmanago</tab>
<resource>Benhauer_Salesmanago::benhauer_salesmanago</resource>
<group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Account Settings</label>
<field id="clientId" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Client ID</label>
<frontend_model>Benhauer\Salesmanago\Block\System\Config\Form\Field\Disable</frontend_model>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="endpoint" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Endpoint</label>
<frontend_model>Benhauer\Salesmanago\Block\System\Config\Form\Field\Disable</frontend_model>
</field>
<field id="ownerEmail" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Contact owner email</label>
<source_model>Benhauer\Salesmanago\Model\Config\Source\Select</source_model>
</field>
<field id="synchronize" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Synchronize contacts statuses</label>
<comment>During new user registration, download the consent status of the contact from SALESmanago</comment>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
</group>
<group id="apiDoubleOptIn" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Double Optin</label>
<field id="useApiDoubleOptIn" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Double Opt In</label>
<comment>During new user subscription, use Double Opt In</comment>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="apiDoubleOptInEmailTemplateId" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Template ID</label>
<comment>(optional)</comment>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<depends>
<field id="doubleOptIn">1</field>
</depends>
</field>
<field id="apiDoubleOptInEmailAccountId" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Email ID</label>
<comment>(optional)</comment>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<depends>
<field id="doubleOptIn">1</field>
</depends>
</field>
<field id="apiDoubleOptInEmailSubject" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Email Subject</label>
<comment>(optional)</comment>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<depends>
<field id="doubleOptIn">1</field>
</depends>
</field>
</group>
</section>
<section id="salesmanago_platform_settings" translate="label" sortOrder="133" showInDefault="1" showInWebsite="1" showInStore="1">
<class>separator-top</class>
<label>Magento 2 Settings</label>
<tab>salesmanago</tab>
<resource>Benhauer_Salesmanago::benhauer_salesmanago</resource>
<group id="callbacks" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Callbacks</label>
<field id="callbackOptIn" translate="label" type="text" sortOrder="1" showInDefault="1"
showInWebsite="1" showInStore="1">
<label>Opt-in callback URL:</label>
<frontend_model>Benhauer\Salesmanago\Block\System\Config\Form\Field\Disable</frontend_model>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="callbackOptOut" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Opt-out callback URL:</label>
<frontend_model>Benhauer\Salesmanago\Block\System\Config\Form\Field\Disable</frontend_model>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
</group>
<group id="tags" translate="label" type="text" sortOrder="11" showInDefault="1" showInWebsite="1"
showInStore="1">
<label>Tags</label>
<field id="registration" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Registration tag</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment>Tags assigned after registration (comma separated)</comment>
<validate>no-whitespace</validate>
</field>
<field id="subscription" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Subscription tag</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment>Tags assigned after subscription to the newsletter (comma separated)</comment>
<validate>no-whitespace</validate>
</field>
<field id="purchase" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Purchase tag</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment>Tags assigned after purchase (comma separated)</comment>
<validate>no-whitespace</validate>
</field>
<field id="purchaseGuest" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Guest purchase tag</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment>Tags assigned after guest purchase (comma separated)</comment>
<validate>no-whitespace</validate>
</field>
</group>
<group id="events" translate="label" type="text" sortOrder="12" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Events</label>
<field id="location" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Location/SALESmanago Store id</label>
<comment>Unique store id</comment>
<frontend_model>Benhauer\Salesmanago\Block\System\Config\Form\Field\Disable</frontend_model>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="eventCookie" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Event cookie lifetime</label>
<comment>The time the cookie SMEVENT expires (h)</comment>
<source_model>Benhauer\Salesmanago\Model\Config\Source\SelectCookieLifeTime</source_model>
</field>
</group>
<group id="purchases" translate="label" type="text" sortOrder="13" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Purchases</label>
<field id="purchaseProcessingType" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Purchase events processing type</label>
<comment>Here you can choose in which way PURCHASE events will be send to SALESmanago</comment>
<source_model>Benhauer\Salesmanago\Model\Config\Source\SelectPurchaseProcessingType</source_model>
</field>
<field id="purchaseProcessingTypeSystemEvents" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>System events list</label>
<comment>Choose on which system event will be send PURCHASE event</comment>
<source_model>Benhauer\Salesmanago\Model\Config\Source\SelectSystemEventsForPurchase</source_model>
<depends>
<field id="purchaseProcessingType">1</field>
</depends>
</field>
<field id="purchaseProcessingTypeCron" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>CRON job frequency (h)</label>
<comment>Choose frequency of CRON job run. Attention your CRON job must be cyclic.</comment>
<source_model>Benhauer\Salesmanago\Model\Config\Source\SelectCronJobFrequency</source_model>
<depends>
<field id="purchaseProcessingType">3</field>
</depends>
</field>
</group>
</section>
</system>
</config>
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
<group id="benhauer_salesmanago">
<job name="purchases" instance="Benhauer\Salesmanago\Cron\Purchase" method="execute">
<schedule>1 * * * *</schedule>
</job>
</group>
</config>
\ No newline at end of file
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="customer_login">
<observer name="customerLogin" instance="Benhauer\Salesmanago\Observer\CustomerLogin"/>
</event>
<event name="customer_register_success">
<observer name="customerRegister" instance="Benhauer\Salesmanago\Observer\CustomerRegister"/>
</event>
<event name="customer_account_edited">
<observer name="customerModified" instance="Benhauer\Salesmanago\Observer\CustomerModified"/>
</event>
<event name="newsletter_subscriber_save_after">
<observer name="newsletterModified" instance="Benhauer\Salesmanago\Observer\NewsletterStatusModified"/>
</event>
<event name="customer_address_save_commit_after">
<observer name="addressModified" instance="Benhauer\Salesmanago\Observer\AddressModified"/>
</event>
<event name="customer_address_save_after">
<observer name="addressSaveAfterModified" instance="Benhauer\Salesmanago\Observer\AddressModified"/>
</event>
<event name="checkout_cart_save_after">
<observer name="cartModified" instance="Benhauer\Salesmanago\Observer\CartModified"/>
</event>
<event name="wishlist_product_add_after">
<observer name="wishlistModified" instance="Benhauer\Salesmanago\Observer\WishlistModified"/>
</event>
<event name="adminhtml_customer_save_after">
<observer name="adminCustomerModified" instance="Benhauer\Salesmanago\Observer\AdminCustomerModified"/>
</event>
<event name="checkout_onepage_controller_success_action">
<!--['order_ids' => [$session->getLastOrderId()], 'order' => $session->getLastRealOrder()]-->
<observer name="PurchaseObserver" instance="Benhauer\Salesmanago\Observer\Events\Purchase\PurchaseObserver"/>
</event>
<event name="multishipping_checkout_controller_success_action">
<!--['order_ids' => $ids]-->
<observer name="PurchaseObserver" instance="Benhauer\Salesmanago\Observer\Events\Purchase\PurchaseObserver" />
</event>
<event name="checkout_submit_all_after"> <!--['order' => $order, 'quote' => $quote]-->
<observer name="PurchaseObserver" instance="Benhauer\Salesmanago\Observer\Events\Purchase\PurchaseObserver"/>
</event>
<event name="checkout_controller_onepage_saveOrder"> <!--['result' => $result, 'action' => $this]-->
<observer name="PurchaseObserver" instance="Benhauer\Salesmanago\Observer\Events\Purchase\PurchaseObserver" />
</event>
<event name="sales_order_save_after">
<observer name="orderStatusChanged" instance="Benhauer\Salesmanago\Observer\Events\Purchase\OrderStatusChanged"/>
</event>
<event name="restore_quote"> <!--['order' => $order, 'quote' => $quote]-->
<observer name="PurchaseObserver" instance="Benhauer\Salesmanago\Observer\Events\Purchase\PurchaseObserver" />
</event>
<event name="sales_convert_order_to_quote"> <!--['order' => $order, 'quote' => $quote]-->
<observer name="PurchaseObserver" instance="Benhauer\Salesmanago\Observer\Events\Purchase\PurchaseObserver" />
</event>
<event name="sales_order_invoice_register"> <!--[$this->_eventObject => $this, 'order' => $order]-->
<observer name="PurchaseObserver" instance="Benhauer\Salesmanago\Observer\Events\Purchase\PurchaseObserver" />
</event>
<event name="_set_sales_order"> <!--['collection' => $this, $this->_eventObject => $this, 'order' => $order]-->
<observer name="PurchaseObserver" instance="Benhauer\Salesmanago\Observer\Events\Purchase\PurchaseObserver" />
</event>
<event name="checkout_type_onepage_save_order_after"> <!--['order' => $order, 'quote' => $this->getQuote()]-->
<observer name="PurchaseObserver" instance="Benhauer\Salesmanago\Observer\Events\Purchase\PurchaseObserver" />
</event>
<event name="checkout_type_multishipping_create_orders_single"> <!--['order' => $order, 'address' => $address, 'quote' => $this->getQuote()]-->
<observer name="PurchaseObserver" instance="Benhauer\Salesmanago\Observer\Events\Purchase\PurchaseObserver" />
</event>
<event name="paypal_express_place_order_success"> <!--['order' => $order, 'quote' => $this->_getQuote()]-->
<observer name="PurchaseObserver" instance="Benhauer\Salesmanago\Observer\Events\Purchase\PurchaseObserver" />
</event>
<event name="sales_convert_quote_to_order"> <!--['order' => $order, 'quote' => $object->getQuote()]-->
<observer name="PurchaseObserver" instance="Benhauer\Salesmanago\Observer\Events\Purchase\PurchaseObserver" />
</event>
</config>
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route frontName="salesmanago" id="salesmanago">
<module name="Benhauer_Salesmanago"/>
</route>
</router>
</config>
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Benhauer_Salesmanago" schema_version="3.0.5" setup_version="3.0.5"></module>
</config>
<?php
/**
* @author Salesmanago Team
* @copyright Copyright (c) 2020 Salesmanago (http://www.salesmanago.com)
* @package Benhauer_Salesmanago
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Benhauer_Salesmanago',
__DIR__
);
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<css src="Benhauer_Salesmanago::css/app-magento-global.css"/>
</head>
</page>
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<css src="Benhauer_Salesmanago::css/app-magento-form.css" />
</head>
<body>
<referenceContainer name="content">
<block class="Magento\Framework\View\Element\Template" name="salesmanagologo" template="Benhauer_Salesmanago::logo.phtml" />
<uiComponent name="salesmanago_create_form"/>
</referenceContainer>
<referenceContainer name="content">
<block class="Magento\Framework\View\Element\Template" name="personal_consent_regulations" template="Benhauer_Salesmanago::personal_consent_regulations.phtml" after="-" />
</referenceContainer>
<referenceContainer name="page.main.actions">
<block class="Magento\Backend\Block\Store\Switcher" name="store_switcher"></block>
</referenceContainer>
</body>
</page>
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<uiComponent name="salesmanago_export_form"/>
</referenceContainer>
<referenceContainer name="left">
<block class="Benhauer\Salesmanago\Block\Adminhtml\Client\IndexMenu" name="adminhtml.plugin_menu" before="-"/>
</referenceContainer>
<referenceContainer name="page.main.actions">
<block class="Magento\Backend\Block\Store\Switcher" name="store_switcher"></block>
</referenceContainer>
</body>
</page>
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<css src="Benhauer_Salesmanago::css/app-magento.css"/>
<script src="Benhauer_Salesmanago::js/metrix.js"/>
</head>
<body>
<referenceContainer name="content">
<uiComponent name="salesmanago_index_content"/>
<block class="Benhauer\Salesmanago\Block\Adminhtml\Client\WelcomeForm"
name="welcome_form"
as="welcome_form"
template="Benhauer_Salesmanago::welcome_form.phtml"
before="-"/>
</referenceContainer>
<referenceContainer name="left">
<block class="Benhauer\Salesmanago\Block\Adminhtml\Client\IndexMenu"
name="plugin_menu"
as="plugin_menu"
template="Benhauer_Salesmanago::plugin_menu.phtml"
before="-"/>
</referenceContainer>
<referenceContainer name="page.main.actions">
<block class="Magento\Backend\Block\Store\Switcher" name="store_switcher"></block>
</referenceContainer>
</body>
</page>
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<css src="Benhauer_Salesmanago::css/app-magento-form.css" />
</head>
<body>
<referenceContainer name="content">
<block class="Magento\Framework\View\Element\Template" name="salesmanagologo" template="Benhauer_Salesmanago::logo.phtml" />
<uiComponent name="salesmanago_login_form"/>
</referenceContainer>
<referenceContainer name="page.main.actions">
<block class="Magento\Backend\Block\Store\Switcher" name="store_switcher"></block>
</referenceContainer>
</body>
</page>
<?xml version="1.0" encoding="UTF-8"?>
<page_layouts xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/PageLayout/etc/layouts.xsd">
<layout id="admin-2columns-left-custom">
<label translate="true">Admin 2columns Left Custom</label>
</layout>
</page_layouts>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">pfay_contacts_form.contacts_form_data_source</item>
<item name="deps" xsi:type="string">pfay_contacts_form.contacts_form_data_source</item>
</item>
<item name="label" xsi:type="string" translate="true">Sample Form</item>
<item name="layout" xsi:type="array">
<item name="type" xsi:type="string">tabs</item>
</item>
<item name="buttons" xsi:type="array">
<item name="back" xsi:type="string">Pfay\Contacts\Block\Adminhtml\Contact\Edit\BackButton</item>
<item name="delete" xsi:type="string">Pfay\Contacts\Block\Adminhtml\Contact\Edit\DeleteButton</item>
<item name="reset" xsi:type="string">Pfay\Contacts\Block\Adminhtml\Contact\Edit\ResetButton</item>
<item name="save" xsi:type="string">Pfay\Contacts\Block\Adminhtml\Contact\Edit\SaveButton</item>
</item>
</argument>
<dataSource name="contacts_form_data_source">
<argument name="dataProvider" xsi:type="configurableObject">
<argument name="class" xsi:type="string">Pfay\Contacts\Model\Contact\DataProvider</argument>
<argument name="name" xsi:type="string">contacts_form_data_source</argument>
<argument name="primaryFieldName" xsi:type="string">pfay_contacts_id</argument>
<argument name="requestFieldName" xsi:type="string">id</argument>
</argument>
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
</item>
</argument>
</dataSource>
<fieldset name="contact">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Sample Fieldset</item>
</item>
</argument>
<!-- This field represents form id and is hidden -->
<field name="pfay_contact_id">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="visible" xsi:type="boolean">false</item>
<item name="dataType" xsi:type="string">text</item>
<item name="formElement" xsi:type="string">input</item>
<item name="source" xsi:type="string">contact</item>
</item>
</argument>
</field>
<!-- This field has data type 'text' and standard 'input' form element and looks like input -->
<field name="name">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string">Name</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="dataType" xsi:type="string">text</item>
<item name="formElement" xsi:type="string">input</item>
<item name="source" xsi:type="string">contact</item>
</item>
</argument>
</field>
<!-- This field has data type 'text' and standard 'input' form element and looks like input -->
<field name="email">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string">Email</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="dataType" xsi:type="string">text</item>
<item name="formElement" xsi:type="string">input</item>
<item name="source" xsi:type="string">contact</item>
</item>
</argument>
</field>
</fieldset>
</form>
<?php
/*@escapeNotVerified*/
echo $block->generateTemplate();
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
/** @var $block \Magento\Config\Block\System\Config\Tabs */
?>
<?php if ($block->getTabs()): ?>
<div id="<?= /* @escapeNotVerified */ $block->getId() ?>" class="config-nav">
<?php
/** @var $_tab \Magento\Config\Model\Config\Structure\Element\Tab */
foreach ($block->getTabs() as $_tab):
?>
<?php
$activeCollapsible = false;
foreach ($_tab->getChildren() as $_section) {
if ($block->isSectionActive($_section)) {
$activeCollapsible = true;
}
}
?>
<div class="config-nav-block admin__page-nav _collapsed
<?php if ($_tab->getClass()): ?>
<?= /* @escapeNotVerified */ $_tab->getClass() ?>
<?php endif ?>"
data-mage-init='{"collapsible":{"active": "<?= /* @escapeNotVerified */ $activeCollapsible ?>",
"openedState": "_show",
"closedState": "_hide",
"collapsible": true,
"animate": 200}}'>
<!-- <div class="admin__page-nav-title title _collapsible" data-role="title">-->
<!-- <strong>--><?//= /* @escapeNotVerified */ /*$_tab->getLabel()*/ ?><!--</strong>-->
<!-- </div>-->
<ul class="admin__page-nav-items items" data-role="content">
<?php $_iterator = 1; ?>
<?php
/** @var $_section \Magento\Config\Model\Config\Structure\Element\Section */
foreach ($_tab->getChildren() as $_section): ?>
<li class="admin__page-nav-item item
<?= /* @escapeNotVerified */ $_section->getClass() ?>
<?php if ($block->isSectionActive($_section)): ?> _active<?php endif ?>
<?= $_tab->getChildren()->isLast($_section) ? ' _last' : '' ?>">
<a href="<?= /* @escapeNotVerified */ $block->getSectionUrl($_section) ?>"
class="admin__page-nav-link item-nav">
<span><?= /* @escapeNotVerified */ $_section->getLabel() ?></span>
</a>
</li>
<?php $_iterator++; ?>
<?php endforeach; ?>
</ul>
</div>
<?php
endforeach;
?>
</div>
<?php endif; ?>
<img class="sm-form-logo" src="<?php echo $block->getViewFileUrl('Benhauer_Salesmanago::img/salesmanago-logo.png'); ?>" />
<div class="admin__field-note sm-consent">
<span>
By clicking the create account button, you confirm that you have familiarised yourself with information about the
<a href="https://www.salesmanago.com/info/information_obligation.htm">processing of personal data</a> and accept the
<a href="https://www.salesmanago.com/marketing-automation/terms.htm">terms and conditions.</a>
</span>
</div>
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
/** @var $block \Magento\Config\Block\System\Config\Tabs */
?>
<?php if ($block->getTabs()): ?>
<div id="<?= /* @escapeNotVerified */ $block->getId() ?>" class="config-nav">
<?php
/** @var $_tab \Magento\Config\Model\Config\Structure\Element\Tab */
/*foreach ($block->getTabs() as $_tab):
?>
<?php
$activeCollapsible = false;
foreach ($_tab->getChildren() as $_section) {
if ($block->isSectionActive($_section)) {
$activeCollapsible = true;
}
}*/
?>
<div class="config-nav-block admin__page-nav _collapsed
<?php if (false/*$_tab->getClass()*/): ?>
<?= /* @escapeNotVerified */ /*$_tab->getClass()*/ false ?>
<?php endif ?>"
>
<ul class="admin__page-nav-items items" data-role="content">
<?php $_iterator = 1; $iteration = count($block->getMenuItems())?>
<?php
foreach ($block->getMenuItems() as $manuItem): ?>
<li class="admin__page-nav-item item
<?= /* @escapeNotVerified */ /*$_section->getClass()*/ false ?>
<?php if ($block->isItemActive($manuItem)): ?> _active<?php endif ?>
<?= ($iteration == $_iterator) ? ' _last' : '' ?>">
<a href="<?= /* @escapeNotVerified */ $block->getUrl($manuItem['url']) ?>"
class="admin__page-nav-link item-nav">
<span><?= /* @escapeNotVerified */ $manuItem['label'] ?></span>
</a>
</li>
<?php $_iterator++; ?>
<?php endforeach; ?>
</ul>
</div>
<?php
/*endforeach;*/
?>
</div>
<?php endif; ?>
<div class="fieldset-wrapper-title">
<strong>Welcome</strong>
</div>
<div class="bhr-container">
<div class="bhr-form__group bhr-row">
<h1 class="bhr-img bhr-img-settings">
</h1>
<div class="bhr-account">
<p class="bhr-account__plan-type">SALESmanago Marketing Automation&nbsp;<?php echo $this->planType; ?></p>
<p class="bhr-account__contacts"><?php echo $this->contactCount; ?></p>
<p class="bhr-account__info">Number of contacts</p>
<p class="bhr-account__contacts"><?php echo $this->pluginVersion; ?></p>
<p class="bhr-account__info">Plugin version</p>
</div>
</div>
</div>
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<item name="buttons" xsi:type="array">
<item name="logout" xsi:type="string">Benhauer\Salesmanago\Block\Adminhtml\Client\LogoutButton</item>
<item name="save" xsi:type="string">Benhauer\Salesmanago\Block\Adminhtml\Client\SaveButton</item>
</item>
</form>
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">salesmanago_config_usersettings.client_login_form_data_source</item>
<item name="deps" xsi:type="string">salesmanago_config_usersettings.client_login_form_data_source</item>
</item>
<item name="label" xsi:type="string" translate="true">User Settings</item>
<item name="layout" xsi:type="array">
<item name="type" xsi:type="string">tabs</item>
</item>
<item name="buttons" xsi:type="array">
<item name="logout" xsi:type="string">Benhauer\Salesmanago\Block\Adminhtml\Client\LogoutButton</item>
<item name="save" xsi:type="string">Benhauer\Salesmanago\Block\Adminhtml\Client\SaveButton</item>
</item>
</argument>
<dataSource name="contacts_form_data_source">
<argument name="dataProvider" xsi:type="configurableObject">
<argument name="class" xsi:type="string">Benhauer\Salesmanago\Model\DummyDataProvider</argument>
<argument name="name" xsi:type="string">client_login_form_data_source</argument>
<argument name="requestFieldName" xsi:type="string">id</argument>
</argument>
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
</item>
</argument>
</dataSource>
<fieldset name="client">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Login Form</item>
</item>
</argument>
<!-- This field has data type 'text' and standard 'input' form element and looks like input -->
<field name="username">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string">Login</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="dataType" xsi:type="string">text</item>
<item name="formElement" xsi:type="string">input</item>
</item>
</argument>
</field>
<!-- This field has data type 'text' and standard 'input' form element and looks like input -->
<field name="password">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string">Password</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="dataType" xsi:type="string">text</item>
<item name="formElement" xsi:type="string">input</item>
</item>
</argument>
</field>
</fieldset>
</form>
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">salesmanago_create_form.client_login_form_data_source</item>
<item name="deps" xsi:type="string">salesmanago_create_form.client_login_form_data_source</item>
</item>
<item name="label" xsi:type="string" translate="true">Login Form</item>
<item name="layout" xsi:type="array">
<item name="type" xsi:type="string">tabs</item>
</item>
<item name="buttons" xsi:type="array">
<item name="save" xsi:type="string">Benhauer\Salesmanago\Block\Adminhtml\Client\CreateCreateButton</item>
<item name="login" xsi:type="string">Benhauer\Salesmanago\Block\Adminhtml\Client\CreateLoginButton</item>
</item>
</argument>
<dataSource name="contacts_form_data_source">
<argument name="dataProvider" xsi:type="configurableObject">
<argument name="class" xsi:type="string">Benhauer\Salesmanago\Model\DummyDataProvider</argument>
<argument name="name" xsi:type="string">client_login_form_data_source</argument>
<argument name="requestFieldName" xsi:type="string">id</argument>
</argument>
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
</item>
</argument>
</dataSource>
<fieldset name="client">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Create Account</item>
</item>
</argument>
<field name="name">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string">Name</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="dataType" xsi:type="string">text</item>
<item name="formElement" xsi:type="string">input</item>
<item name="validation" xsi:type="array">
<item name="required-entry" xsi:type="boolean">true</item>
</item>
</item>
</argument>
</field>
<field name="username">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string">Email</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="dataType" xsi:type="string">text</item>
<item name="formElement" xsi:type="string">input</item>
<item name="validation" xsi:type="array">
<item name="required-entry" xsi:type="boolean">true</item>
<item name="validate-email" xsi:type="boolean">true</item>
</item>
</item>
</argument>
</field>
<field name="password">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="elementTmpl" xsi:type="string">Benhauer_Salesmanago/form/element/password</item>
<item name="label" xsi:type="string">Password</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="dataType" xsi:type="string">text</item>
<item name="formElement" xsi:type="string">input</item>
<item name="validation" xsi:type="array">
<item name="required-entry" xsi:type="boolean">true</item>
<item name="validate-password" xsi:type="boolean">true</item>
</item>
</item>
</argument>
</field>
<field name="phone">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string">Phone</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="dataType" xsi:type="string">text</item>
<item name="formElement" xsi:type="string">input</item>
<item name="validation" xsi:type="array">
<item name="required-entry" xsi:type="boolean">true</item>
<item name="validate-number" xsi:type="boolean">true</item>
</item>
</item>
</argument>
</field>
<field name="zgoda_eng_przetwarzanie">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="visible" xsi:type="boolean">true</item>
<item name="dataType" xsi:type="string">text</item>
<item name="formElement" xsi:type="string">checkbox</item>
<item name="valueMap" xsi:type="array">
<item name="true" xsi:type="number">1</item>
<item name="false" xsi:type="number">0</item>
</item>
<item name="notice" xsi:type="string" translate="true">
I agree to process my personal data in marketing purposes of Benhauer LTD (the owner of SALESmanago).
</item>
<item name="additionalClasses" xsi:type="string">sm-consent-checkbox-notice</item>
<!-- <item name="validation" xsi:type="array">-->
<!-- <item name="validate-one-checkbox-required-by-name" xsi:type="boolean">true</item>-->
<!-- </item>-->
</item>
</argument>
</field>
<field name="zgoda_eng_handlowa">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="visible" xsi:type="boolean">true</item>
<item name="dataType" xsi:type="string">text</item>
<item name="formElement" xsi:type="string">checkbox</item>
<item name="valueMap" xsi:type="array">
<item name="true" xsi:type="number">1</item>
<item name="false" xsi:type="number">0</item>
</item>
<item name="notice" xsi:type="string" translate="true">
I agree to receive commercial e-communication about products of Benhauer and its partners.
</item>
<item name="additionalClasses" xsi:type="string">sm-consent-checkbox-notice</item>
<!-- <item name="validation" xsi:type="array">-->
<!-- <item name="validate-one-checkbox-required-by-name" xsi:type="boolean">true</item>-->
<!-- </item>-->
</item>
</argument>
</field>
</fieldset>
</form>
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">salesmanago_export_form.client_export_form_data_source</item>
<item name="deps" xsi:type="string">salesmanago_export_form.client_export_form_data_source</item>
</item>
<item name="label" xsi:type="string" translate="true">Login Form</item>
<item name="layout" xsi:type="array">
<item name="type" xsi:type="string">tabs</item>
</item>
<item name="buttons" xsi:type="array">
<item name="logout" xsi:type="string">Benhauer\Salesmanago\Block\Adminhtml\Client\LogoutButton</item>
<item name="config" xsi:type="string">Benhauer\Salesmanago\Block\Adminhtml\Client\ConfigButton</item>
<item name="save" xsi:type="string">Benhauer\Salesmanago\Block\Adminhtml\Client\ExportButton</item>
</item>
</argument>
<dataSource name="contacts_form_data_source">
<argument name="dataProvider" xsi:type="configurableObject">
<argument name="class" xsi:type="string">Benhauer\Salesmanago\Model\DummyDataProvider</argument>
<argument name="name" xsi:type="string">client_export_form_data_source</argument>
<argument name="requestFieldName" xsi:type="string">id</argument>
</argument>
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
</item>
</argument>
</dataSource>
<fieldset name="exportConfig">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Export</item>
</item>
</argument>
<field name="eventsExport">
<argument name="data" xsi:type="array">
<item name="options" xsi:type="object">Magento\Config\Model\Config\Source\Yesno</item>
<item name="config" xsi:type="array">
<item name="sortOrder" xsi:type="number">60</item>
<item name="filter" xsi:type="string">select</item>
<item name="label" translate="true" xsi:type="string">Export historical transaction data</item>
<item name="formElement" xsi:type="string">select</item>
<item name="dataType" xsi:type="string">select</item>
<item name="editor" xsi:type="array">
<item name="editorType" xsi:type="string">select</item>
</item>
<item name="notice" xsi:type="string" translate="true">
We will automatically transfer all historical transaction data.
</item>
<item name="additionalClasses" xsi:type="string">sm-consent-checkbox-notice</item>
</item>
</argument>
</field>
<field name="contactsExport">
<argument name="data" xsi:type="array">
<item name="options" xsi:type="object">Magento\Config\Model\Config\Source\Yesno</item>
<item name="config" xsi:type="array">
<item name="sortOrder" xsi:type="number">60</item>
<item name="filter" xsi:type="string">select</item>
<item name="label" translate="true" xsi:type="string">Export contacts to SALESmanago</item>
<item name="formElement" xsi:type="string">select</item>
<item name="dataType" xsi:type="string">select</item>
<item name="editor" xsi:type="array">
<item name="editorType" xsi:type="string">select</item>
</item>
<item name="notice" xsi:type="string" translate="true">
We will automatically export all your customers to SALESmanago.
</item>
<item name="additionalClasses" xsi:type="string">sm-consent-checkbox-notice</item>
</item>
</argument>
</field>
</fieldset>
</form>
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">salesmanago_index_content.client_login_form_data_source</item>
<item name="deps" xsi:type="string">salesmanago_index_content.client_login_form_data_source</item>
</item>
<item name="label" xsi:type="string" translate="true">Login Form</item>
<item name="layout" xsi:type="array">
<item name="type" xsi:type="string">tabs</item>
</item>
<item name="buttons" xsi:type="array">
<item name="logout" xsi:type="string">Benhauer\Salesmanago\Block\Adminhtml\Client\LogoutButton</item>
<item name="config" xsi:type="string">Benhauer\Salesmanago\Block\Adminhtml\Client\ConfigButton</item>
</item>
</argument>
<dataSource name="client_login_form_data_source">
<argument name="dataProvider" xsi:type="configurableObject">
<argument name="class" xsi:type="string">Benhauer\Salesmanago\Model\DummyDataProvider</argument>
<argument name="name" xsi:type="string">client_login_form_data_source</argument>
<argument name="requestFieldName" xsi:type="string">id</argument>
</argument>
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
</item>
</argument>
</dataSource>
</form>
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">salesmanago_login_form.client_login_form_data_source</item>
<item name="deps" xsi:type="string">salesmanago_login_form.client_login_form_data_source</item>
</item>
<item name="label" xsi:type="string" translate="true">Log in to your SALESmanago account</item>
<item name="layout" xsi:type="array">
<item name="type" xsi:type="string">tabs</item>
</item>
<item name="buttons" xsi:type="array">
<item name="create" xsi:type="string">Benhauer\Salesmanago\Block\Adminhtml\Client\LoginCreateButton</item>
<item name="save" xsi:type="string">Benhauer\Salesmanago\Block\Adminhtml\Client\LoginLoginButton</item>
</item>
</argument>
<dataSource name="contacts_form_data_source">
<argument name="dataProvider" xsi:type="configurableObject">
<argument name="class" xsi:type="string">Benhauer\Salesmanago\Model\DummyDataProvider</argument>
<argument name="name" xsi:type="string">client_login_form_data_source</argument>
<argument name="requestFieldName" xsi:type="string">id</argument>
</argument>
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
</item>
</argument>
</dataSource>
<fieldset name="client">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Log in to your SALESmanago account</item>
</item>
</argument>
<field name="username">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string">Login</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="dataType" xsi:type="string">text</item>
<item name="formElement" xsi:type="string">input</item>
<item name="validation" xsi:type="array">
<item name="required-entry" xsi:type="boolean">true</item>
<item name="validate-email" xsi:type="boolean">true</item>
</item>
</item>
</argument>
</field>
<field name="password">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="elementTmpl" xsi:type="string">Benhauer_Salesmanago/form/element/password</item>
<item name="label" xsi:type="string">Password</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="dataType" xsi:type="string">text</item>
<item name="formElement" xsi:type="string">input</item>
<item name="validation" xsi:type="array">
<item name="required-entry" xsi:type="boolean">true</item>
<item name="validate-password" xsi:type="boolean">true</item>
</item>
</item>
</argument>
</field>
</fieldset>
</form>
.page-columns #container {
max-width: 800px !important;
margin: 0 auto !important;
}
.sm-form-logo {
max-width: 50%;
margin: 0 auto;
display: block;
}
.sm-consent {
max-width: 386px !important;
margin: 0 auto !important;
display: block;
}
.sm-consent-checkbox-notice .admin__field-note{
display: inline !important;
}
.fieldset-wrapper-title {
text-align: center;
}
.admin__menu .level-0.item-salesmanagoindex > a:before {
background-image: url('../images/logo_mini.png');
width: 50px;
display: inline-block;
content: "";
background-size: 49px;
height: 50px;
background-repeat: no-repeat;
}
.bhr-container {
margin: auto;
padding: 50px;
border-width: 0;
background-color: #fff;
min-width: 310px;
-webkit-box-sizing: border-box;
box-sizing: border-box;
max-width: 992px;
}
#bhr-app {
font-family: Open Sans,sans-serif;
text-align: center;
color: #2c3e50;
font-size: 100%;
font-weight: 400;
background-size: cover;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
background: url(../img/space-bg.c7a38d5c.png);
min-height: 100vh;
}
.bhr-row {
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
}
.bhr-form__group {
padding: 15px 0;
}
.bhr-row {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.bhr-account {
border-right: 2px solid #78a614;
padding: 8px 15px;
text-align: right;
color: #2c3e50;
max-width: 330px;
}
.bhr-account p {
margin: 0;
}
.bhr-account__plan-type {
font-size: 1.25em;
font-weight: 300;
}
.bhr-account__contacts {
font-size: 1.5em;
color: #78a614;
}
.bhr-account__info {
font-size: .78em;
color: #808386;
}
This source diff could not be displayed because it is too large. You can view the blob instead.
function docReady(fn) {
if (document.readyState === "complete" || document.readyState === "interactive") {
setTimeout(fn, 1);
} else {
document.addEventListener("DOMContentLoaded", fn);
}
};
\ No newline at end of file
<input class="admin__control-text" type="password" data-bind="
hasFocus: focused,
value: value,
attr: {
name: inputName,
placeholder: placeholder,
'aria-describedby': noticeId,
id: uid,
disabled: disabled
}"/>
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="footer-container">
<block
class="Benhauer\Salesmanago\Block\Tracking\Monitoring"
name="salesmanago-tracking-code"
after="-"
template="Benhauer_Salesmanago::salesmanago/integration/tracking.phtml"
cacheable="true"
>
</block>
</referenceBlock>
</body>
</page>
\ No newline at end of file
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<referenceContainer name="content">
<block class="Benhauer\Salesmanago\Block\Index" name="salesmanago_index_index" template="Benhauer_Salesmanago::index.phtml" cacheable="true"/>
</referenceContainer>
</page>
\ No newline at end of file
<h2>Welcome to salesmanago.pl</h2>
\ No newline at end of file
<?php
/*@escapeNotVerified*/
echo $block->trackingScript;
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