1
0
mirror of synced 2024-11-25 06:26:07 +03:00

Configuration interface, Observer, ICML generator

This commit is contained in:
Alex Lushpai 2015-02-11 16:02:59 +03:00
parent a461967b35
commit 26dcf45071
19 changed files with 2269 additions and 1 deletions

View File

@ -1,6 +1,6 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2015 Alex Lushpai Copyright (c) 2015 RetailDriver LLC
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -0,0 +1,35 @@
<?php
class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Base extends Mage_Adminhtml_Block_System_Config_Form_Fieldset
{
protected $_fieldRenderer;
protected $_values;
protected $_apiKey;
protected $_apiUrl;
protected $_isCredentialCorrect;
public function __construct()
{
parent::__construct();
$this->_apiUrl = Mage::getStoreConfig('retailcrm/general/api_url');
$this->_apiKey = Mage::getStoreConfig('retailcrm/general/api_key');
$this->_isCredentialCorrect = false;
if (!empty($this->_apiUrl) && !empty($this->_apiKey)) {
$client = Mage::getModel(
'retailcrm/ApiClient',
array('url' => $this->_apiUrl, 'key' => $this->_apiKey, 'site' => null)
);
try {
$response = $client->sitesList();
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
if ($response->isSuccessful()) {
$this->_isCredentialCorrect = true;
}
}
}
}

View File

@ -0,0 +1,87 @@
<?php
class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Payment extends Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Base
{
public function render(Varien_Data_Form_Element_Abstract $element)
{
$html = $this->_getHeaderHtml($element);
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$groups = Mage::getSingleton('payment/config')->getActiveMethods();
foreach ($groups as $group) {
$html .= $this->_getFieldHtml($element, $group);
}
} else {
$html .= '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
}
$html .= $this->_getFooterHtml($element);
return $html;
}
protected function _getFieldRenderer()
{
if (empty($this->_fieldRenderer)) {
$this->_fieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field');
}
return $this->_fieldRenderer;
}
/**
* @return array
*/
protected function _getValues()
{
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$client = Mage::getModel(
'retailcrm/ApiClient',
array('url' => $this->_apiUrl, 'key' => $this->_apiKey, 'site' => null)
);
try {
$paymentTypes = $client->paymentTypesList();
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
if ($paymentTypes->isSuccessful()) {
if (empty($this->_values)) {
foreach ($paymentTypes['paymentTypes'] as $type) {
$this->_values[] = array('label' => Mage::helper('adminhtml')->__($type['name']), 'value' => $type['code']);
}
}
}
}
return $this->_values;
}
protected function _getFieldHtml($fieldset, $group)
{
$configData = $this->getConfigData();
$path = 'retailcrm/payment/'.$group->getId();
if (isset($configData[$path])) {
$data = $configData[$path];
$inherit = false;
} else {
$data = (int)(string)$this->getForm()->getConfigRoot()->descend($path);
$inherit = true;
}
$field = $fieldset->addField($group->getId(), 'select',
array(
'name' => 'groups[payment][fields]['.$group->getId().'][value]',
'label' => Mage::getStoreConfig('payment/'.$group->getId().'/title'),
'value' => $data,
'values' => $this->_getValues(),
'inherit' => $inherit,
'can_use_default_value' => 1,
'can_use_website_value' => 1
))->setRenderer($this->_getFieldRenderer());
return $field->toHtml();
}
}

View File

@ -0,0 +1,87 @@
<?php
class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Paymentstatus extends Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Base
{
public function render(Varien_Data_Form_Element_Abstract $element)
{
$html = $this->_getHeaderHtml($element);
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$client = Mage::getModel(
'retailcrm/ApiClient',
array('url' => $this->_apiUrl, 'key' => $this->_apiKey, 'site' => null)
);
try {
$paymentStatuses = $client->paymentStatusesList();
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
if ($paymentStatuses->isSuccessful() && !empty($paymentStatuses)) {
foreach ($paymentStatuses['paymentStatuses'] as $group) {
$html.= $this->_getFieldHtml($element, $group);
}
}
} else {
$html .= '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
}
$html .= $this->_getFooterHtml($element);
return $html;
}
protected function _getFieldRenderer()
{
if (empty($this->_fieldRenderer)) {
$this->_fieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field');
}
return $this->_fieldRenderer;
}
/**
* @return array
*/
protected function _getValues()
{
$values = Mage::getModel('sales/order_status')->getResourceCollection()->getData();
if (empty($this->_values)) {
$this->_values[] = array('label'=>Mage::helper('adminhtml')->__('===Select status==='), 'value'=>'');
foreach ($values as $value) {
$this->_values[] = array('label'=>Mage::helper('adminhtml')->__($value['label']), 'value'=>$value['status']);
}
}
return $this->_values;
}
protected function _getFieldHtml($fieldset, $group)
{
$configData = $this->getConfigData();
$path = 'retailcrm/paymentstatus/'.$group['code'];
if (isset($configData[$path])) {
$data = $configData[$path];
$inherit = false;
} else {
$data = (int)(string)$this->getForm()->getConfigRoot()->descend($path);
$inherit = true;
}
$field = $fieldset->addField($group['code'], 'select',
array(
'name' => 'groups[paymentstatus][fields]['.$group['code'].'][value]',
'label' => $group['name'],
'value' => $data,
'values' => $this->_getValues(),
'inherit' => $inherit,
'can_use_default_value' => 1,
'can_use_website_value' => 1
))->setRenderer($this->_getFieldRenderer());
return $field->toHtml();
}
}

View File

@ -0,0 +1,88 @@
<?php
class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Shipping extends Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Base
{
public function render(Varien_Data_Form_Element_Abstract $element)
{
$html = $this->_getHeaderHtml($element);
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$groups = Mage::getSingleton('shipping/config')->getActiveCarriers();
foreach ($groups as $group) {
$html .= $this->_getFieldHtml($element, $group);
}
} else {
$html .= '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
}
$html .= $this->_getFooterHtml($element);
return $html;
}
protected function _getFieldRenderer()
{
if (empty($this->_fieldRenderer)) {
$this->_fieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field');
}
return $this->_fieldRenderer;
}
/**
* @return array
*/
protected function _getValues()
{
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$client = Mage::getModel(
'retailcrm/ApiClient',
array('url' => $this->_apiUrl, 'key' => $this->_apiKey, 'site' => null)
);
try {
$deliveryTypes = $client->deliveryTypesList();
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
if ($deliveryTypes->isSuccessful()) {
if (empty($this->_values)) {
foreach ($deliveryTypes['deliveryTypes'] as $type) {
$this->_values[] = array('label'=>Mage::helper('adminhtml')->__($type['name']), 'value'=>$type['code']);
}
}
}
}
return $this->_values;
}
protected function _getFieldHtml($fieldset, $group)
{
$configData = $this->getConfigData();
$path = 'retailcrm/shipping/'.$group->getId();
if (isset($configData[$path])) {
$data = $configData[$path];
$inherit = false;
} else {
$data = (int)(string)$this->getForm()->getConfigRoot()->descend($path);
$inherit = true;
}
$field = $fieldset->addField($group->getId(), 'select',
array(
'name' => 'groups[shipping][fields]['.$group->getId().'][value]',
'label' => Mage::getStoreConfig('carriers/'.$group->getId().'/title'),
'value' => $data,
'values' => $this->_getValues(),
'inherit' => $inherit,
'can_use_default_value' => 1,
'can_use_website_value' => 1
))->setRenderer($this->_getFieldRenderer());
return $field->toHtml();
}
}

View File

@ -0,0 +1,86 @@
<?php
class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Status extends Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Base
{
public function render(Varien_Data_Form_Element_Abstract $element)
{
$html = $this->_getHeaderHtml($element);
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$client = Mage::getModel(
'retailcrm/ApiClient',
array('url' => $this->_apiUrl, 'key' => $this->_apiKey, 'site' => null)
);
try {
$statuses = $client->statusesList();
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
if ($statuses->isSuccessful() && !empty($statuses)) {
foreach ($statuses['statuses'] as $group) {
$html.= $this->_getFieldHtml($element, $group);
}
}
} else {
$html .= '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
}
$html .= $this->_getFooterHtml($element);
return $html;
}
protected function _getFieldRenderer()
{
if (empty($this->_fieldRenderer)) {
$this->_fieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field');
}
return $this->_fieldRenderer;
}
/**
* @return array
*/
protected function _getValues()
{
$values = Mage::getModel('sales/order_status')->getResourceCollection()->getData();
if (empty($this->_values)) {
$this->_values[] = array('label'=>Mage::helper('adminhtml')->__('===Select status==='), 'value'=>'');
foreach ($values as $value) {
$this->_values[] = array('label'=>Mage::helper('adminhtml')->__($value['label']), 'value'=>$value['status']);
}
}
return $this->_values;
}
protected function _getFieldHtml($fieldset, $group)
{
$configData = $this->getConfigData();
$path = 'retailcrm/status/'.$group['code'];
if (isset($configData[$path])) {
$data = $configData[$path];
$inherit = false;
} else {
$data = (int)(string)$this->getForm()->getConfigRoot()->descend($path);
$inherit = true;
}
$field = $fieldset->addField($group['code'], 'select',
array(
'name' => 'groups[status][fields]['.$group['code'].'][value]',
'label' => $group['name'],
'value' => $data,
'values' => $this->_getValues(),
'inherit' => $inherit,
'can_use_default_value' => 1,
'can_use_website_value' => 1
))->setRenderer($this->_getFieldRenderer());
return $field->toHtml();
}
}

View File

@ -0,0 +1,58 @@
<?php
/**
* Data helper
*
* @author RetailCRM
*/
class Retailcrm_Retailcrm_Helper_Data extends Mage_Core_Helper_Abstract
{
/**
* Path to store config if front-end output is enabled
*
* @var string
*/
const XML_API_URL = 'retailcrm/general/api_url';
/**
* Path to store config where count of news posts per page is stored
*
* @var string
*/
const XML_API_KEY = 'retailcrm/general/api_key';
/**
* Return api url
*
* @param integer|string|Mage_Core_Model_Store $store
* @return int
*/
public function getApiUrl($store = null)
{
return abs((int)Mage::getStoreConfig(self::XML_API_URL, $store));
}
/**
* Return api key
*
* @param integer|string|Mage_Core_Model_Store $store
* @return int
*/
public function getApiKey($store = null)
{
return abs((int)Mage::getStoreConfig(self::XML_API_KEY, $store));
}
public function rewrittenProductUrl($productId, $categoryId, $storeId)
{
$coreUrl = Mage::getModel('core/url_rewrite');
$idPath = sprintf('product/%d', $productId);
if ($categoryId) {
$idPath = sprintf('%s/%d', $idPath, $categoryId);
}
$coreUrl->setStoreId($storeId);
$coreUrl->loadByIdPath($idPath);
return Mage::getBaseUrl( Mage_Core_Model_Store::URL_TYPE_WEB, true ) . $coreUrl->getRequestPath();
}
}

View File

@ -0,0 +1,705 @@
<?php
/**
* retailCRM API client class
*/
class Retailcrm_Retailcrm_Model_ApiClient
{
const VERSION = 'v3';
protected $client;
/**
* Site code
*/
protected $siteCode;
/**
* Client creating
*
* @param array $parameters
* @internal param string $siteCode
*/
public function __construct($parameters)
{
$url = $parameters['url'];
$apiKey = $parameters['key'];
$site = $parameters['site'];
if ('/' != substr($url, strlen($url) - 1, 1)) {
$url .= '/';
}
$url = $url . 'api/' . self::VERSION;
$this->client = new Retailcrm_Retailcrm_Model_Http_Client($url, array('apiKey' => $apiKey));
$this->siteCode = $site;
}
/**
* Create a order
*
* @param array $order
* @param string $site (default: null)
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function ordersCreate(array $order, $site = null)
{
if (!sizeof($order)) {
throw new InvalidArgumentException('Parameter `order` must contains a data');
}
return $this->client->makeRequest("/orders/create", Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, $this->fillSite($site, array(
'order' => json_encode($order)
)));
}
/**
* Edit a order
*
* @param array $order
* @param string $by
* @param string $site (default: null)
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function ordersEdit(array $order, $by = 'externalId', $site = null)
{
if (!sizeof($order)) {
throw new InvalidArgumentException('Parameter `order` must contains a data');
}
$this->checkIdParameter($by);
if (!isset($order[$by])) {
throw new InvalidArgumentException(sprintf('Order array must contain the "%s" parameter.', $by));
}
return $this->client->makeRequest(
"/orders/" . $order[$by] . "/edit",
Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST,
$this->fillSite($site, array(
'order' => json_encode($order),
'by' => $by,
))
);
}
/**
* Upload array of the orders
*
* @param array $orders
* @param string $site (default: null)
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function ordersUpload(array $orders, $site = null)
{
if (!sizeof($orders)) {
throw new InvalidArgumentException('Parameter `orders` must contains array of the orders');
}
return $this->client->makeRequest("/orders/upload", Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, $this->fillSite($site, array(
'orders' => json_encode($orders),
)));
}
/**
* Get order by id or externalId
*
* @param string $id
* @param string $by (default: 'externalId')
* @param string $site (default: null)
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function ordersGet($id, $by = 'externalId', $site = null)
{
$this->checkIdParameter($by);
return $this->client->makeRequest("/orders/$id", Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, $this->fillSite($site, array(
'by' => $by
)));
}
/**
* Returns a orders history
*
* @param DateTime $startDate (default: null)
* @param DateTime $endDate (default: null)
* @param int $limit (default: 100)
* @param int $offset (default: 0)
* @param bool $skipMyChanges (default: true)
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function ordersHistory(
DateTime $startDate = null,
DateTime $endDate = null,
$limit = 100,
$offset = 0,
$skipMyChanges = true
) {
$parameters = array();
if ($startDate) {
$parameters['startDate'] = $startDate->format('Y-m-d H:i:s');
}
if ($endDate) {
$parameters['endDate'] = $endDate->format('Y-m-d H:i:s');
}
if ($limit) {
$parameters['limit'] = (int) $limit;
}
if ($offset) {
$parameters['offset'] = (int) $offset;
}
if ($skipMyChanges) {
$parameters['skipMyChanges'] = (bool) $skipMyChanges;
}
return $this->client->makeRequest('/orders/history', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, $parameters);
}
/**
* Returns filtered orders list
*
* @param array $filter (default: array())
* @param int $page (default: null)
* @param int $limit (default: null)
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function ordersList(array $filter = array(), $page = null, $limit = null)
{
$parameters = array();
if (sizeof($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
return $this->client->makeRequest('/orders', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, $parameters);
}
/**
* Returns statuses of the orders
*
* @param array $ids (default: array())
* @param array $externalIds (default: array())
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function ordersStatuses(array $ids = array(), array $externalIds = array())
{
$parameters = array();
if (sizeof($ids)) {
$parameters['ids'] = $ids;
}
if (sizeof($externalIds)) {
$parameters['externalIds'] = $externalIds;
}
return $this->client->makeRequest('/orders/statuses', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, $parameters);
}
/**
* Save order IDs' (id and externalId) association in the CRM
*
* @param array $ids
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function ordersFixExternalIds(array $ids)
{
if (!sizeof($ids)) {
throw new InvalidArgumentException('Method parameter must contains at least one IDs pair');
}
return $this->client->makeRequest("/orders/fix-external-ids", Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, array(
'orders' => json_encode($ids),
));
}
/**
* Create a customer
*
* @param array $customer
* @param string $site (default: null)
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function customersCreate(array $customer, $site = null)
{
if (!sizeof($customer)) {
throw new InvalidArgumentException('Parameter `customer` must contains a data');
}
return $this->client->makeRequest("/customers/create", Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, $this->fillSite($site, array(
'customer' => json_encode($customer)
)));
}
/**
* Edit a customer
*
* @param array $customer
* @param string $by (default: 'externalId')
* @param string $site (default: null)
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function customersEdit(array $customer, $by = 'externalId', $site = null)
{
if (!sizeof($customer)) {
throw new InvalidArgumentException('Parameter `customer` must contains a data');
}
$this->checkIdParameter($by);
if (!isset($customer[$by])) {
throw new InvalidArgumentException(sprintf('Customer array must contain the "%s" parameter.', $by));
}
return $this->client->makeRequest(
"/customers/" . $customer[$by] . "/edit",
Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST,
$this->fillSite($site, array(
'customer' => json_encode($customer),
'by' => $by,
)
));
}
/**
* Upload array of the customers
*
* @param array $customers
* @param string $site (default: null)
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function customersUpload(array $customers, $site = null)
{
if (!sizeof($customers)) {
throw new InvalidArgumentException('Parameter `customers` must contains array of the customers');
}
return $this->client->makeRequest("/customers/upload", Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, $this->fillSite($site, array(
'customers' => json_encode($customers),
)));
}
/**
* Get customer by id or externalId
*
* @param string $id
* @param string $by (default: 'externalId')
* @param string $site (default: null)
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function customersGet($id, $by = 'externalId', $site = null)
{
$this->checkIdParameter($by);
return $this->client->makeRequest("/customers/$id", Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, $this->fillSite($site, array(
'by' => $by
)));
}
/**
* Returns filtered customers list
*
* @param array $filter (default: array())
* @param int $page (default: null)
* @param int $limit (default: null)
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function customersList(array $filter = array(), $page = null, $limit = null)
{
$parameters = array();
if (sizeof($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
return $this->client->makeRequest('/customers', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, $parameters);
}
/**
* Save customer IDs' (id and externalId) association in the CRM
*
* @param array $ids
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function customersFixExternalIds(array $ids)
{
if (!sizeof($ids)) {
throw new InvalidArgumentException('Method parameter must contains at least one IDs pair');
}
return $this->client->makeRequest("/customers/fix-external-ids", Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, array(
'customers' => json_encode($ids),
));
}
/**
* Returns deliveryServices list
*
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function deliveryServicesList()
{
return $this->client->makeRequest('/reference/delivery-services', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET);
}
/**
* Returns deliveryTypes list
*
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function deliveryTypesList()
{
return $this->client->makeRequest('/reference/delivery-types', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET);
}
/**
* Returns orderMethods list
*
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function orderMethodsList()
{
return $this->client->makeRequest('/reference/order-methods', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET);
}
/**
* Returns orderTypes list
*
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function orderTypesList()
{
return $this->client->makeRequest('/reference/order-types', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET);
}
/**
* Returns paymentStatuses list
*
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function paymentStatusesList()
{
return $this->client->makeRequest('/reference/payment-statuses', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET);
}
/**
* Returns paymentTypes list
*
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function paymentTypesList()
{
return $this->client->makeRequest('/reference/payment-types', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET);
}
/**
* Returns productStatuses list
*
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function productStatusesList()
{
return $this->client->makeRequest('/reference/product-statuses', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET);
}
/**
* Returns statusGroups list
*
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function statusGroupsList()
{
return $this->client->makeRequest('/reference/status-groups', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET);
}
/**
* Returns statuses list
*
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function statusesList()
{
return $this->client->makeRequest('/reference/statuses', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET);
}
/**
* Returns sites list
*
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function sitesList()
{
return $this->client->makeRequest('/reference/sites', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET);
}
/**
* Edit deliveryService
*
* @param array $data delivery service data
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function deliveryServicesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/delivery-services/' . $data['code'] . '/edit',
Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST,
array(
'deliveryService' => json_encode($data)
)
);
}
/**
* Edit deliveryType
*
* @param array $data delivery type data
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function deliveryTypesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/delivery-types/' . $data['code'] . '/edit',
Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST,
array(
'deliveryType' => json_encode($data)
)
);
}
/**
* Edit orderMethod
*
* @param array $data order method data
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function orderMethodsEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/order-methods/' . $data['code'] . '/edit',
Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST,
array(
'orderMethod' => json_encode($data)
)
);
}
/**
* Edit orderType
*
* @param array $data order type data
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function orderTypesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/order-types/' . $data['code'] . '/edit',
Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST,
array(
'orderType' => json_encode($data)
)
);
}
/**
* Edit paymentStatus
*
* @param array $data payment status data
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function paymentStatusesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/payment-statuses/' . $data['code'] . '/edit',
Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST,
array(
'paymentStatus' => json_encode($data)
)
);
}
/**
* Edit paymentType
*
* @param array $data payment type data
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function paymentTypesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/payment-types/' . $data['code'] . '/edit',
Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST,
array(
'paymentType' => json_encode($data)
)
);
}
/**
* Edit productStatus
*
* @param array $data product status data
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function productStatusesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/product-statuses/' . $data['code'] . '/edit',
Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST,
array(
'productStatus' => json_encode($data)
)
);
}
/**
* Edit order status
*
* @param array $data status data
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function statusesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/statuses/' . $data['code'] . '/edit',
Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST,
array(
'status' => json_encode($data)
)
);
}
/**
* Edit site
*
* @param array $data site data
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function sitesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/sites/' . $data['code'] . '/edit',
Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST,
array(
'site' => json_encode($data)
)
);
}
/**
* Update CRM basic statistic
*
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function statisticUpdate()
{
return $this->client->makeRequest('/statistic/update', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET);
}
/**
* Return current site
*
* @return string
*/
public function getSite()
{
return $this->siteCode;
}
/**
* Set site
*
* @param string $site
* @return void
*/
public function setSite($site)
{
$this->siteCode = $site;
}
/**
* Check ID parameter
*
* @param string $by
* @return bool
*/
protected function checkIdParameter($by)
{
$allowedForBy = array('externalId', 'id');
if (!in_array($by, $allowedForBy)) {
throw new InvalidArgumentException(sprintf(
'Value "%s" for parameter "by" is not valid. Allowed values are %s.',
$by,
implode(', ', $allowedForBy)
));
}
return true;
}
/**
* Fill params by site value
*
* @param string $site
* @param array $params
* @return array
*/
protected function fillSite($site, array $params)
{
if ($site) {
$params['site'] = $site;
} elseif ($this->siteCode) {
$params['site'] = $this->siteCode;
}
return $params;
}
}

View File

@ -0,0 +1,5 @@
<?php
class Retailcrm_Retailcrm_Model_Exception_CurlException extends RuntimeException
{
}

View File

@ -0,0 +1,5 @@
<?php
class Retailcrm_Retailcrm_Model_Exception_InvalidJsonException extends DomainException
{
}

View File

@ -0,0 +1,427 @@
<?php
class Retailcrm_Retailcrm_Model_Exchange
{
protected $_apiKey;
protected $_apiUrl;
protected $_config;
protected $_api;
public function __construct()
{
$this->_apiUrl = Mage::getStoreConfig('retailcrm/general/api_url');
$this->_apiKey = Mage::getStoreConfig('retailcrm/general/api_key');
if(!empty($this->_apiUrl) && !empty($this->_apiKey)) {
$this->_api = Mage::getModel(
'retailcrm/ApiClient',
array('url' => $this->_apiUrl, 'key' => $this->_apiKey, 'site' => null)
);
}
}
/**
* @param mixed $order
*
* @return bool
*/
public function orderCreate($order)
{
$this->_config = Mage::getStoreConfig('retailcrm', $order->getStoreId());
$statuses = array_flip(array_filter($this->_config['status']));
$paymentsStatuses = array_flip(array_filter($this->_config['paymentstatuses']));
$payments = array_filter($this->_config['payment']);
$shippings = array_filter($this->_config['shipping']);
$address = $order->getShippingAddress()->getData();
$orderItems = $order->getItemsCollection();
$items = array();
foreach ($orderItems as $item){
$items[] = array(
'productId' => $item->product_id,
'initialPrice' => $item->getPrice(),
'taxPrice' => $item->getPriceInclTax(),
'productName' => $item->getName(),
'quantity' => (int) $item->getData('qty_ordered')
);
}
$customer = array(
'externalId' => ($order->getCustomerIsGuest() == 0) ? $order->getCustomerId() : 'g' . $order->getRealOrderId(),
'email' => $order->getCustomerEmail(),
'phone' => $address['telephone'],
'name' => $order->getCustomerName(),
'lastName' => $order->getCustomerLastname(),
'firstName' => $order->getCustomerFirstname(),
'patronymic' => $order->getCustomerMiddlename(),
);
$customerId = $this->setCustomerId($customer);
unset($customer);
$preparedOrder = array(
'site' => $order->getStore()->getCode(),
'externalId' => $order->getId(),
'number' => $order->getRealOrderId(),
'createdAt' => $order->getCreatedAt(),
'customerId' => $customerId,
'lastName' => $order->getCustomerLastname(),
'firstName' => $order->getCustomerFirstname(),
'patronymic' => $order->getCustomerMiddlename(),
'email' => $order->getCustomerEmail(),
'phone' => $address['telephone'],
'paymentType' => $payments[$order->getPayment()->getMethodInstance()->getCode()],
'paymentStatus' => $paymentsStatuses[$order->getStatus()],
'status' => $statuses[$order->getStatus()],
'discount' => abs($order->getDiscountAmount()),
'items' => $items,
'delivery' => array(
'code' => $shippings[$order->getShippingMethod()],
'cost' => $order->getShippingAmount(),
'address' => array(
'index' => $address['postcode'],
'city' => $address['city'],
'country' => $address['country_id'],
'street' => $address['street'],
'region' => $address['region'],
),
)
);
try {
$this->_api->ordersCreate($preparedOrder);
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
}
/**
* @param mixed $order
*
* @return bool
*/
public function orderEdit($order)
{
$this->_config = Mage::getStoreConfig('retailcrm', $order->getStoreId());
$statuses = array_flip(array_filter($this->_config['status']));
$paymentsStatuses = array_flip(array_filter($this->_config['paymentstatuses']));
$payments = array_filter($this->_config['payment']);
$shippings = array_filter($this->_config['shipping']);
$address = $order->getShippingAddress()->getData();
$orderItems = $order->getItemsCollection();
$items = array();
foreach ($orderItems as $item){
$items[] = array(
'productId' => $item->product_id,
'initialPrice' => $item->getPrice(),
'taxPrice' => $item->getPriceInclTax(),
'productName' => $item->getName(),
'quantity' => (int) $item->getData('qty_ordered')
);
}
$preparedOrder = array(
'site' => $order->getStore()->getCode(),
'externalId' => $order->getId(),
'number' => $order->getRealOrderId(),
'createdAt' => $order->getCreatedAt(),
'customerId' => ($order->getCustomerIsGuest() == 0) ? $order->getCustomerId() : 'g' . $order->getRealOrderId(),
'lastName' => $order->getCustomerLastname(),
'firstName' => $order->getCustomerFirstname(),
'patronymic' => $order->getCustomerMiddlename(),
'email' => $order->getCustomerEmail(),
'phone' => $address['telephone'],
'paymentType' => $payments[$order->getPayment()->getMethodInstance()->getCode()],
'paymentStatus' => $paymentsStatuses[$order->getStatus()],
'status' => $statuses[$order->getStatus()],
'discount' => abs($order->getDiscountAmount()),
'items' => $items,
'delivery' => array(
'code' => $shippings[$order->getShippingMethod()],
'cost' => $order->getShippingAmount(),
'address' => array(
'index' => $address['postcode'],
'city' => $address['city'],
'country' => $address['country_id'],
'street' => $address['street'],
'region' => $address['region'],
),
)
);
try {
$this->_api->ordersEdit($preparedOrder);
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
}
public function processOrders($orders, $nocheck = false)
{
if (!$nocheck) {
foreach ($orders as $idx => $order) {
$customer = array();
$customer['phones'][]['number'] = $order['phone'];
$customer['externalId'] = $order['customerId'];
$customer['firstName'] = $order['firstName'];
$customer['lastName'] = $order['lastName'];
$customer['patronymic'] = $order['patronymic'];
$customer['address'] = $order['delivery']['address'];
if (isset($order['email'])) {
$customer['email'] = $order['email'];
}
$checkResult = $this->checkCustomers($customer);
if ($checkResult === false) {
unset($orders[$idx]["customerId"]);
} else {
$orders[$idx]["customerId"] = $checkResult;
}
}
}
$splitOrders = array_chunk($orders, 50);
foreach($splitOrders as $orders) {
try {
$response = $this->_api->ordersUpload($orders);
time_nanosleep(0, 250000000);
if (!$response->isSuccessful()) {
Mage::log('RestApi::ordersUpload::API: ' . $response->getErrorMsg());
if (isset($response['errors'])) {
foreach ($response['errors'] as $error) {
Mage::log('RestApi::ordersUpload::API: ' . $error);
}
}
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log('RestApi::ordersUpload::Curl: ' . $e->getMessage());
return false;
}
}
}
public function orderHistory()
{
try {
$orders = $this->_api->ordersHistory(new DateTime($this->getDate($this->historyLog)));
Mage::log($orders->getGeneratedAt(), null, 'history.log');
return $orders['orders'];
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log('RestApi::orderHistory::Curl: ' . $e->getMessage());
return false;
}
}
public function orderFixExternalIds($data)
{
try {
$this->_api->ordersFixExternalIds($data);
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log('RestApi::orderFixExternalIds::Curl: ' . $e->getMessage());
return false;
}
return true;
}
public function customerFixExternalIds($data)
{
try {
$this->_api->customersFixExternalIds($data);
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log('RestApi::customerFixExternalIds::Curl: ' . $e->getMessage());
return false;
}
return true;
}
/**
* Export References to CRM
*
* @param array $deliveries deliveries data
* @param array $payments payments data
* @param array $statuses statuses data
*
*/
public function processReference($deliveries = null, $payments = null, $statuses = null)
{
if ($deliveries != null) {
$this->processDeliveries($deliveries);
}
if ($payments != null) {
$this->processPayments($payments);
}
if ($statuses != null) {
$this->processStatuses($statuses);
}
}
/**
* Export deliveries
*
* @param array $deliveries
*
* @return bool
*/
protected function processDeliveries($deliveries)
{
foreach ($deliveries as $delivery) {
try {
$this->_api->deliveryTypesEdit($delivery);
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log('RestApi::deliveryEdit::Curl: ' . $e->getMessage());
return false;
}
}
return true;
}
/**
* Export payments
*
* @param array $payments
*
* @return bool
*/
protected function processPayments($payments)
{
foreach ($payments as $payment) {
try {
$this->_api->paymentTypesEdit($payment);
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log('RestApi::paymentEdit::Curl: ' . $e->getMessage());
return false;
}
}
return true;
}
/**
* Export statuses
*
* @param array $statuses
*
* @return bool
*/
protected function processStatuses($statuses)
{
foreach ($statuses as $status) {
try {
$this->_api->statusesEdit($status);
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log('RestApi::statusEdit::Curl: ' . $e->getMessage());
return false;
}
}
return true;
}
private function setCustomerId($customer)
{
$customerId = $this->searchCustomer($customer);
if (is_array($customerId) && !empty($customerId)) {
if ($customerId['success']) {
return $customerId['result'];
} else {
$this->fixCustomer($customerId['result'], $customer['externalId']);
return $customer['externalId'];
}
} else {
$this->createCustomer(
array(
'externalId' => $customer['externalId'],
'firstName' => $customer['firstName'],
'lastName' => isset($customer['lastName']) ? $customer['lastName'] : '',
'patronymic' => isset($customer['patronymic']) ? $customer['patronymic'] : '',
'phones' => isset($customer['phone']) ? array($customer['phone']) : array(),
)
);
return $customer['externalId'];
}
}
private function searchCustomer($data)
{
try {
$customers = $this->api->customersList(
array(
'name' => isset($data['phone']) ? $data['phone'] : $data['name'],
'email' => $data['email']
),
1,
100
);
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
if ($customers->isSuccessful()) {
return (count($customers['customers']) > 0)
? $this->defineCustomer($customers['customers'])
: false
;
}
}
private function createCustomer($customer)
{
try {
$this->api->customersCreate($customer);
} catch (CurlException $e) {
$this->curlErrorHandler($e->getMessage(), 'CustomersCreate::Curl: ');
}
}
private function fixCustomer($id, $extId)
{
try {
$this->api->customersFixExternalIds(
array(
array(
'id' => $id,
'externalId' => $extId
)
)
);
} catch (CurlException $e) {
$this->curlErrorHandler($e->getMessage(), 'CustomersFixExternalIds::Curl: ');
}
}
private function defineCustomer($searchResult)
{
$result = '';
foreach ($searchResult as $customer) {
if (isset($customer['externalId']) && $customer['externalId'] != '') {
$result = $customer['externalId'];
break;
}
}
return ($result != '')
? array('success' => true, 'result' => $result)
: array('success' => false, 'result' => $searchResult[0]['id'])
;
}
}

View File

@ -0,0 +1,77 @@
<?php
/**
* HTTP client
*/
class Retailcrm_Retailcrm_Model_Http_Client
{
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
protected $url;
protected $defaultParameters;
public function __construct($url, array $defaultParameters = array())
{
if (false === stripos($url, 'https://')) {
throw new InvalidArgumentException('API schema requires HTTPS protocol');
}
$this->url = $url;
$this->defaultParameters = $defaultParameters;
}
/**
* Make HTTP request
*
* @param string $path
* @param string $method (default: 'GET')
* @param array $parameters (default: array())
* @param int $timeout
* @return Retailcrm_Retailcrm_Model_Response_ApiResponse
*/
public function makeRequest($path, $method, array $parameters = array(), $timeout = 60)
{
$allowedMethods = array(self::METHOD_GET, self::METHOD_POST);
if (!in_array($method, $allowedMethods)) {
throw new InvalidArgumentException(sprintf(
'Method "%s" is not valid. Allowed methods are %s',
$method,
implode(', ', $allowedMethods)
));
}
$parameters = array_merge($this->defaultParameters, $parameters);
$path = $this->url . $path;
if (self::METHOD_GET === $method && sizeof($parameters)) {
$path .= '?' . http_build_query($parameters);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $path);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, (int) $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if (self::METHOD_POST === $method) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
}
$responseBody = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);
if ($errno) {
throw new Retailcrm_Retailcrm_Model_Exception_CurlException($error, $errno);
}
return new Retailcrm_Retailcrm_Model_Response_ApiResponse($statusCode, $responseBody);
}
}

View File

@ -0,0 +1,178 @@
<?php
class Retailcrm_Retailcrm_Model_Icml
{
protected $_dd;
protected $_eCategories;
protected $_eOffers;
protected $_shop;
public function generate($shop)
{
$this->_shop = $shop;
$string = '<?xml version="1.0" encoding="UTF-8"?>
<yml_catalog date="'.date('Y-m-d H:i:s').'">
<shop>
<name>'.Mage::app()->getStore($shop)->getName().'</name>
<categories/>
<offers/>
</shop>
</yml_catalog>
';
$xml = new SimpleXMLElement($string, LIBXML_NOENT |LIBXML_NOCDATA | LIBXML_COMPACT | LIBXML_PARSEHUGE);
$this->_dd = new DOMDocument();
$this->_dd->preserveWhiteSpace = false;
$this->_dd->formatOutput = true;
$this->_dd->loadXML($xml->asXML());
$this->_eCategories = $this->_dd->getElementsByTagName('categories')->item(0);
$this->_eOffers = $this->_dd->getElementsByTagName('offers')->item(0);
$this->addCategories();
$this->addOffers();
$this->_dd->saveXML();
$baseDir = Mage::getBaseDir();
$this->_dd->save($baseDir . DS . 'retailcrm_' . Mage::app()->getStore($shop)->getCode() . '.xml');
}
private function addCategories()
{
$category = Mage::getModel('catalog/category');
$treeModel = $category->getTreeModel();
$treeModel->load();
$ids = $treeModel->getCollection()->getAllIds();
$categories = array();
if (!empty($ids))
{
foreach ($ids as $id)
{
$category = Mage::getModel('catalog/category');
$category->load($id);
$categoryData = array(
'id' => $category->getId(),
'name'=> $category->getName(),
'parentId' => $category->getParentId()
);
array_push($categories, $categoryData);
}
}
foreach($categories as $category) {
$e = $this->_eCategories->appendChild($this->_dd->createElement('category'));
$e->appendChild($this->_dd->createTextNode($category['name']));
$e->setAttribute('id', $category['id']);
if ($category['parentId'] > 0) {
$e->setAttribute('parentId', $category['parentId']);
}
}
}
private function addOffers()
{
$offers = array();
$helper = Mage::helper('retailcrm');
$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->addUrlRewrite();
foreach ($collection as $product) {
$offer = array();
$offer['id'] = $product->getId();
$offer['productId'] = $product->getId();
$offer['name'] = $product->getName();
$offer['productName'] = $product->getName();
$offer['initialPrice'] = (float) $product->getPrice();
$offer['url'] = $helper->rewrittenProductUrl($product->getId(), $product->getCategoryId(), $this->_shop);
$offer['picture'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'catalog/product'.$product->getImage();
$offer['quantity'] = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty();
foreach ($product->getCategoryIds() as $category_id) {
$offer['categoryId'][] = $category_id;
}
$offer['article'] = $product->getSku();
$offer['weight'] = $product->getWeight();
$offers[] = $offer;
}
foreach ($offers as $offer) {
$e = $this->_eOffers->appendChild($this->_dd->createElement('offer'));
$e->setAttribute('id', $offer['id']);
$e->setAttribute('productId', $offer['productId']);
if (isset($offer['quantity'] ) && $offer['quantity'] != '') {
$e->setAttribute('quantity', (int)$offer['quantity']);
}
foreach ($offer['categoryId'] as $categoryId) {
$e->appendChild($this->_dd->createElement('categoryId', $categoryId));
}
$e->appendChild($this->_dd->createElement('name'))->appendChild($this->_dd->createTextNode($offer['name']));
$e->appendChild($this->_dd->createElement('productName'))->appendChild($this->_dd->createTextNode($offer['name']));
$e->appendChild($this->_dd->createElement('price', $offer['initialPrice']));
if (isset($offer['purchasePrice'] ) && $offer['purchasePrice'] != '') {
$e->appendChild($this->_dd->createElement('purchasePrice'))->appendChild($this->_dd->createTextNode($offer['purchasePrice']));
}
if (isset($offer['vendor'] ) && $offer['vendor'] != '') {
$e->appendChild($this->_dd->createElement('vendor'))->appendChild($this->_dd->createTextNode($offer['vendor']));
}
if (isset($offer['picture'] ) && $offer['picture'] != '') {
$e->appendChild($this->_dd->createElement('picture', $offer['picture']));
}
if (isset($offer['url'] ) && $offer['url'] != '') {
$e->appendChild($this->_dd->createElement('url'))->appendChild($this->_dd->createTextNode($offer['url']));
}
if (isset($offer['xmlId'] ) && $offer['xmlId'] != '') {
$e->appendChild($this->_dd->createElement('xmlId'))->appendChild($this->_dd->createTextNode($offer['xmlId']));
}
if (isset($offer['article'] ) && $offer['article'] != '') {
$sku = $this->_dd->createElement('param');
$sku->setAttribute('name', 'article');
$sku->appendChild($this->_dd->createTextNode($offer['article']));
$e->appendChild($sku);
}
if (isset($offer['size'] ) && $offer['size'] != '') {
$size = $this->_dd->createElement('param');
$size->setAttribute('name', 'size');
$size->appendChild($this->_dd->createTextNode($offer['size']));
$e->appendChild($size);
}
if (isset($offer['color'] ) && $offer['color'] != '') {
$color = $this->_dd->createElement('param');
$color->setAttribute('name', 'color');
$color->appendChild($this->_dd->createTextNode($offer['color']));
$e->appendChild($color);
}
if (isset($offer['weight'] ) && $offer['weight'] != '') {
$weight = $this->_dd->createElement('param');
$weight->setAttribute('name', 'weight');
$weight->appendChild($this->_dd->createTextNode($offer['weight']));
$e->appendChild($weight);
}
}
}
}

View File

@ -0,0 +1,52 @@
<?php
/**
* Observer
*
* @author RetailDriver LLC
*/
class Retailcrm_Retailcrm_Model_Observer
{
/**
* Event after order created
*
* @param Varien_Event_Observer $observer
* @return bool
*/
public function orderCreate(Varien_Event_Observer $observer)
{
$order = $observer->getEvent()->getOrder();
Mage::getModel('retailcrm/exchange')->orderCreate($order);
return true;
}
/**
* Event after order updated
*
* @param Varien_Event_Observer $observer
* @return bool
*/
public function orderUpdate(Varien_Event_Observer $observer)
{
$order = $observer->getEvent()->getOrder();
if($order->getExportProcessed()){ //check if flag is already set for prevent triggering twice.
return;
}
Mage::getModel('retailcrm/exchange')->orderEdit($order);
$order->setExportProcessed(true);
return true;
}
public function exportCatalog()
{
foreach (Mage::app()->getWebsites() as $website) {
foreach ($website->getGroups() as $group) {
Mage::getModel('retailcrm/icml')->generate((int)$group->getId());
}
}
}
}

View File

@ -0,0 +1,123 @@
<?php
/**
* Response from retailCRM API
*/
class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess
{
// HTTP response status code
protected $statusCode;
// response assoc array
protected $response;
public function __construct($statusCode, $responseBody = null)
{
$this->statusCode = (int) $statusCode;
if (!empty($responseBody)) {
$response = json_decode($responseBody, true);
if (!$response && JSON_ERROR_NONE !== ($error = json_last_error())) {
throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException(
"Invalid JSON in the API response body. Error code #$error",
$error
);
}
$this->response = $response;
}
}
/**
* Return HTTP response status code
*
* @return int
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* HTTP request was successful
*
* @return bool
*/
public function isSuccessful()
{
return $this->statusCode < 400;
}
/**
* Allow to access for the property throw class method
*
* @param string $name
* @return mixed
*/
public function __call($name, $arguments)
{
// convert getSomeProperty to someProperty
$propertyName = strtolower(substr($name, 3, 1)) . substr($name, 4);
if (!isset($this->response[$propertyName])) {
throw new InvalidArgumentException("Method \"$name\" not found");
}
return $this->response[$propertyName];
}
/**
* Allow to access for the property throw object property
*
* @param string $name
* @return mixed
*/
public function __get($name)
{
if (!isset($this->response[$name])) {
throw new InvalidArgumentException("Property \"$name\" not found");
}
return $this->response[$name];
}
/**
* @param mixed $offset
* @param mixed $value
*/
public function offsetSet($offset, $value)
{
throw new BadMethodCallException('This activity not allowed');
}
/**
* @param mixed $offset
*/
public function offsetUnset($offset)
{
throw new BadMethodCallException('This call not allowed');
}
/**
* @param mixed $offset
* @return bool
*/
public function offsetExists($offset)
{
return isset($this->response[$offset]);
}
/**
* @param mixed $offset
* @return mixed
*/
public function offsetGet($offset)
{
if (!isset($this->response[$offset])) {
throw new InvalidArgumentException("Property \"$offset\" not found");
}
return $this->response[$offset];
}
}

View File

@ -0,0 +1,91 @@
<?xml version="1.0"?>
<!--
/**
* Copyright 2015 RetailCRM.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-->
<config>
<modules>
<Retailcrm_Retailcrm>
<version>1.0.0</version>
</Retailcrm_Retailcrm>
</modules>
<global>
<helpers>
<retailcrm>
<class>Retailcrm_Retailcrm_Helper</class>
</retailcrm>
</helpers>
<models>
<retailcrm>
<class>Retailcrm_Retailcrm_Model</class>
</retailcrm>
</models>
<blocks>
<retailcrm>
<class>Retailcrm_Retailcrm_Block</class>
</retailcrm>
</blocks>
<events>
<sales_order_place_after>
<observers>
<retailcrm_retailcrm_model_observer>
<type>singleton</type>
<class>Retailcrm_Retailcrm_Model_Observer</class>
<method>orderSave</method>
</retailcrm_retailcrm_model_observer>
</observers>
</sales_order_place_after>
<sales_order_save_after>
<observers>
<retailcrm_retailcrm_model_observer>
<type>singleton</type>
<class>Retailcrm_Retailcrm_Model_Observer</class>
<method>orderUpdate</method>
</retailcrm_retailcrm_model_observer>
</observers>
</sales_order_save_after>
</events>
</global>
<crontab>
<jobs>
<icml>
<schedule><cron_expr>* */6 * * *</cron_expr></schedule>
<run><model>retailcrm/observer::exportCatalog</model></run>
</icml>
</jobs>
</crontab>
<adminhtml>
<acl>
<resources>
<admin>
<children>
<system>
<children>
<config>
<children>
<retailcrm>
<title>Store RetailCRM Module Section</title>
</retailcrm>
</children>
</config>
</children>
</system>
</children>
</admin>
</resources>
</acl>
</adminhtml>
</config>

View File

@ -0,0 +1,114 @@
<?xml version="1.0"?>
<!--
/**
* Copyright 2012 RetailCRM.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-->
<config>
<tabs>
<retailcrm_extension>
<label>RetailCRM</label>
<sort_order>1000</sort_order>
</retailcrm_extension>
</tabs>
<sections>
<retailcrm translate="label" module="retailcrm">
<label>Settings</label>
<class>retailcrm-section</class>
<tab>retailcrm_extension</tab>
<frontend_type>text</frontend_type>
<sort_order>10</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<groups>
<general translate="label comment" module="retailcrm">
<expanded>1</expanded>
<label>General</label>
<comment>General settings that are required to connect retailcrm and Magento.</comment>
<frontend_type>text</frontend_type>
<sort_order>10</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<fields>
<api_url translate="label comment">
<label>API URL</label>
<frontend_type>text</frontend_type>
<sort_order>1</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<tooltip><![CDATA[https://<i><b>YourCrmName</b></i>.retailcrm.ru]]></tooltip>
</api_url>
<api_key translate="label comment">
<label>API Key</label>
<frontend_type>text</frontend_type>
<sort_order>3</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<tooltip><![CDATA[To generate an API Key, log in to RetailCRM then select Admin > Integration > API Keys]]></tooltip>
</api_key>
</fields>
</general>
<shipping translate="label comment" module="retailcrm">
<expanded>1</expanded>
<label>Shipping methods</label>
<comment>Comparison of shipping methods</comment>
<frontend_type>text</frontend_type>
<sort_order>11</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<frontend_model>retailcrm/adminhtml_system_config_form_fieldset_shipping</frontend_model>
</shipping>
<payment translate="label comment" module="retailcrm">
<expanded>1</expanded>
<label>Payment methods</label>
<comment>Comparison of payment methods</comment>
<frontend_type>text</frontend_type>
<sort_order>12</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<frontend_model>retailcrm/adminhtml_system_config_form_fieldset_payment</frontend_model>
</payment>
<payment_status translate="label comment" module="retailcrm">
<expanded>1</expanded>
<label>Payment statuses</label>
<comment>Comparison of payment statuses</comment>
<frontend_type>text</frontend_type>
<sort_order>13</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<frontend_model>retailcrm/adminhtml_system_config_form_fieldset_paymentstatus</frontend_model>
</payment_status>
<status translate="label comment" module="retailcrm">
<expanded>1</expanded>
<label>Order statuses</label>
<comment>Comparison of order statuses</comment>
<frontend_type>text</frontend_type>
<sort_order>14</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<frontend_model>retailcrm/adminhtml_system_config_form_fieldset_status</frontend_model>
</status>
</groups>
</retailcrm>
</sections>
</config>

View File

@ -0,0 +1,26 @@
<?xml version="1.0"?>
<!--
/**
* Copyright 2012 RetailCRM.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-->
<config>
<modules>
<Retailcrm_Retailcrm>
<active>true</active>
<codePool>community</codePool>
</Retailcrm_Retailcrm>
</modules>
</config>

24
retailcrm-1.0.0.xml Normal file
View File

@ -0,0 +1,24 @@
<?xml version="1.0"?>
<package>
<name>retailcrm</name>
<version>1.1.0</version>
<stability>stable</stability>
<license uri="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</license>
<channel>community</channel>
<extends/>
<summary>RetailCRM.</summary>
<description>Description</description>
<notes>Notes</notes>
<authors><author><name>Alex Lushpai</name><user>gwinn</user><email>lushpai@gmail.com</email></author></authors>
<date>2015-01-28</date>
<time>16:22:48</time>
<contents>
<target name="magecommunity">
<dir name="Retailcrm">
<dir name="Retailcrm"></dir>
</dir>
</target>
</contents>
<compatible/>
<dependencies><required><php><min>5.3.0</min><max>7.0.0</max></php></required></dependencies>
</package>