From b35190b7e36cfd6b79525a7550d3984dc825d093 Mon Sep 17 00:00:00 2001 From: Alex Lushpai Date: Mon, 20 Jul 2015 17:59:27 +0300 Subject: [PATCH] rebranding, api url|key emptiness error fix, icml fixes --- composer.json | 35 - composer.lock | 67 -- intarocrm/config.xml | 13 - intarocrm/export.tpl | 40 - intarocrm/logo.gif | Bin 1124 -> 0 bytes intarocrm/logo.png | Bin 1963 -> 0 bytes retailcrm/classes/Icml.php | 136 +++ retailcrm/classes/Retailcrm.php | 1055 +++++++++++++++++ retailcrm/classes/Service.php | 43 + retailcrm/config.xml | 13 + retailcrm/export.tpl | 31 + {intarocrm => retailcrm}/index.php | 6 +- retailcrm/logo.gif | Bin 0 -> 306 bytes retailcrm/logo.png | Bin 0 -> 957 bytes .../intarocrm.php => retailcrm/retailcrm.php | 373 +++--- {intarocrm => retailcrm}/sync.php | 4 +- {intarocrm => retailcrm}/translations/ru.php | 0 17 files changed, 1479 insertions(+), 337 deletions(-) delete mode 100644 composer.json delete mode 100644 composer.lock delete mode 100644 intarocrm/config.xml delete mode 100644 intarocrm/export.tpl delete mode 100644 intarocrm/logo.gif delete mode 100644 intarocrm/logo.png create mode 100644 retailcrm/classes/Icml.php create mode 100644 retailcrm/classes/Retailcrm.php create mode 100644 retailcrm/classes/Service.php create mode 100644 retailcrm/config.xml create mode 100644 retailcrm/export.tpl rename {intarocrm => retailcrm}/index.php (58%) create mode 100644 retailcrm/logo.gif create mode 100644 retailcrm/logo.png rename intarocrm/intarocrm.php => retailcrm/retailcrm.php (83%) rename {intarocrm => retailcrm}/sync.php (71%) rename {intarocrm => retailcrm}/translations/ru.php (100%) diff --git a/composer.json b/composer.json deleted file mode 100644 index 5b855e4..0000000 --- a/composer.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "intarocrm/prestashop-module", - "description": "Prestashop integration for IntaroCRM", - "type": "library", - "keywords": ["api", "Intaro CRM", "rest"], - "homepage": "http://www.intarocrm.ru/", - "config": { - "vendor-dir": "intarocrm/classes" - }, - "authors": [ - { - "name": "Alex Lushpai", - "email": "lushpai@intaro.ru", - "role": "Developer" - } - ], - "support": { - "email": "support@intarocrm.ru" - }, - "require": { - "php": ">=5.3", - "intarocrm/rest-api-client": "1.2.*" - }, - "autoload": { - "psr-0": { - "": "src/" - } - }, - "repositories": [ - { - "type": "git", - "url": "https://github.com/intarocrm/rest-api-client" - } - ] -} diff --git a/composer.lock b/composer.lock deleted file mode 100644 index 239a739..0000000 --- a/composer.lock +++ /dev/null @@ -1,67 +0,0 @@ -{ - "_readme": [ - "This file locks the dependencies of your project to a known state", - "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file" - ], - "hash": "e4583dae732a6e5ebafff8cca46b1984", - "packages": [ - { - "name": "intarocrm/rest-api-client", - "version": "v1.2.5", - "source": { - "type": "git", - "url": "https://github.com/intarocrm/rest-api-client", - "reference": "b54350ff2f09d8202cf2931895bba8dced4dcf21" - }, - "require": { - "ext-curl": "*", - "php": ">=5.2.0" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.0.x-dev" - } - }, - "autoload": { - "psr-0": { - "IntaroCrm\\": "lib/" - } - }, - "authors": [ - { - "name": "Kruglov Kirill", - "email": "kruglov@intaro.ru", - "role": "Developer" - } - ], - "description": "PHP Client for IntaroCRM REST API", - "homepage": "http://www.intarocrm.ru/", - "keywords": [ - "Intaro CRM", - "api", - "rest" - ], - "support": { - "email": "support@intarocrm.ru" - }, - "time": "2014-04-13 09:58:37" - } - ], - "packages-dev": [ - - ], - "aliases": [ - - ], - "minimum-stability": "stable", - "stability-flags": [ - - ], - "platform": { - "php": ">=5.3" - }, - "platform-dev": [ - - ] -} diff --git a/intarocrm/config.xml b/intarocrm/config.xml deleted file mode 100644 index dcb2d94..0000000 --- a/intarocrm/config.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - intarocrm - - - - - - Вы уверены, что хотите удалить модуль? - 1 - 1 - - \ No newline at end of file diff --git a/intarocrm/export.tpl b/intarocrm/export.tpl deleted file mode 100644 index ed065b6..0000000 --- a/intarocrm/export.tpl +++ /dev/null @@ -1,40 +0,0 @@ - - - - {$shop_name} - {$yamarket_company_name} - {$shop_url} - PrestaShop - - {foreach from=$currencies item=cur name=currencies} - {if $cur.iso_code != 'GBP'} - - {/if} - {/foreach} - - - {foreach from=$categories item=cat name=categories} - {if $cat.id_category!=2} - {$cat.name} - {/if} - {/foreach} - - {if $yamarket_delivery_price}{$yamarket_delivery_price}{/if} - - {foreach from=$products item=offer name=products} - - {$offer.url} - {$offer.price} - {$offer.purchase_price} - {$currency} - {$offer.id_category_default} - {$offer.picture} - {$offer.name} - {if $offer.article} - {$offer.article} - {/if} - - {/foreach} - - - \ No newline at end of file diff --git a/intarocrm/logo.gif b/intarocrm/logo.gif deleted file mode 100644 index c9abff4af5b30e99274d8d056c86e98e156c5b7b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1124 zcmW-gTTGf~7{@WyxCJfWCoX1b)8gt!65n zlB8v6^13W-GgIl&Xm<5_FZ81qf_8K|w^qBEmFbenV8NLrUQsHRQd68F;c~KMLnia6 zRIvQ+%9TT-@vyLPKR@5A*Sq0o9oiLD05Z4UbkO5{FRWlqN5VMRxwhWl54-F5gwFkMijs9Iy;Zr+YkEscAA>@9zNWC`gFCVN-mRXNMb=7fSNPRuO# z`&Ws)Mfg|KQeA1O+Zh?#TJ4tE?9yFc)@q%ZN(Y}mFO|-U#nZ8z3Fi4p27R7R|C7aX za5yV*aT{E&D78XV8Z!nD8zvwju;91AuY>xB&uHAz&RE z-4Kdy3=OSCqbox~Zh+v=000XWAovIqejkG|0{|2h1R;?HNaVHP;0hF~5(KM2@D~8M zcKWn2IM_E03NoWm?Pt&8|MBE==DDSQO;Zz_BCun6=T?{~mvGVM_Rs28{HqipGs|8=9$?`6F zU$qb!#?()@vTH=aXJSje_P!c13d^hX2cs-WAVJ(pOn+{Xpvkhwf;&;Q$=}ejd-EL6 zYo%dK-Gl{VA|NE@mK@Kw0;G(A zTj>OG3r=`9raprt?PTRU2kI4M*`vhT5Ke=Vs`ypjoiW&uNz3lh&)nrSW-&Cj(mm&3 zV>VMaUKxPCa9hQO=2}ULq1!pphQ-IiwhK*aj%l?w|IJX7Cbq;qL8?W^Hf!U4IPx#AY({UO#lFTCIA3{ga82g0001h=l}q9FaQARU;qF* zm;eA5aGbhPJOBUy24YJ`L;(K){{a7>y{D4^000SaNLh0L002k;002k;M#*bF000J{ zNkldG@?FbI)Nhcjn#aYbriPL94M0Jb^;@m>Ad(u53EdLBs169lnQ#~aHrr_MnudMuYbm_al zzwoPH-<2nS`s3|qpMU<>+1}m_jHIkn=$uEqd+u7CLlDR?Jf}1&YKq0!U8`c2fC!Xl z&+e>lZ~wyo?8c41)sG*)rSk?c12e?v1W2lIlGgs(3`chk12IF?kfzST`Gwg#JC8|v?nokshE_TS?BM>U~#8dY>nWD=R$P+@u|i2-7LPZK*>5@6onp-nPtVGi+~fnHI|2~_qzs{Lkw`gWF&fd9$R29cxd@&doEJjon%94#ccc3g0 zGs>+k4nF>v(JQY|?C%rLp6%Qb0(|lbqtOUkS>fn|574q?b#0CD)vFwT`6c@G*R0;W zN&My;aI+alO~ceV!fUUw{?0q>fA$%NZOdGQ$$RgyfA1dq z@4ibsf1dWuH<>wywz1Cw<#;l|9z7!N?(%Fj!f$TkFJ5GRc*x;&itO$(FH4GR*EqU& z4+ZM^oYC8F<0cdI?p@^meGWeTlvaf5+&S3YWxlb2e)Sb6@4ruV?HYBAG#`G5OeQcY zk$>EJ%X~Cq2vC-Uwnaj~6$Mfh_@W@FGKvui0UeKdsjiuAY*1gigs!eqj7E$fK4iMK zhPExt=hWjdqsfGJX9u0naa&u|RfUx$?$IOSfA_Gm=qjP8A;-tKlanscMDX6@og<`G zyvKP@QP-&V6i=UG`};Iig#c|`cXdO%-tSdu+7?&W5F^J=o-nT}Ocj4{fFCMhKf&}> zN_BbK5$PI@8D14lO-2CUH2CRsXuU;@cvYe*P8Btyjggp?RxzT0nxRGL0H|s=MD*E^ z^4zkTV5tOa)(0d5*q3rm)@!mZnxQdvYro&O{Zx>W3sUKYp^I4>B>Ji~C{7LO`H7I> zuTe4WwFgmp5Y`T%8oZfA{(o=59_qy)c z?SEEPpFxXDpZ8|1V%DnsL-LtQI9Vzq1m`YYMbxL^E15+H~KV5&JnaxzjnvdI)S)6)Pe9J2Ym0D7?SC=Ka+=ghievYl9g< zgu*!rktHxb0gXv{qe_ziG#QxF8MGDxrT717%zo#7bm79?!x(=a;Ug~+g9wEPJ}K+h zA_Gx4w=CIS>HPw%a~)vk25};)@UNp7e|cs+{`>y{Aiojwk<7&20000bbVXQnWMOn= zI%9HWVRU5xGB7bTEig1KGC5Q+H99afIx#paFf=+aFh3h~g#Z8mC3HntbYx+4Wjbwd xWNBu305UK!G%YYREiyS&F*Q0cGdeXgD=;)VFffduhV%dc002ovPDHLkV1hcyn&$uj diff --git a/retailcrm/classes/Icml.php b/retailcrm/classes/Icml.php new file mode 100644 index 0000000..94009cd --- /dev/null +++ b/retailcrm/classes/Icml.php @@ -0,0 +1,136 @@ +shop = $shop; + $this->file = $file; + + $this->properties = array( + 'name', + 'productName', + 'initialPrice', + 'purchasePrice', + 'vendor', + 'picture', + 'url', + 'xmlId', + 'productActivity' + ); + + $this->params = array( + 'article' => 'Артикул', + 'color' => 'Цвет', + 'weight' => 'Вес', + 'size' => 'Размер', + ); + } + + public function generate($categories, $offers) + { + $string = ' + + + '.$this->shop.' + + + + + '; + + $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($categories); + $this->addOffers($offers); + + $this->dd->saveXML(); + $this->dd->save($this->file); + } + + private function addCategories($categories) + { + foreach($categories as $category) { + $e = $this->eCategories->appendChild( + $this->dd->createElement( + 'category', $category['name'] + ) + ); + + $e->setAttribute('id', $category['id']); + + if ($category['parentId'] > 0) { + $e->setAttribute('parentId', $category['parentId']); + } + } + } + + private function addOffers($offers) + { + foreach ($offers as $offer) { + + $e = $this->eOffers->appendChild( + $this->dd->createElement('offer') + ); + + $e->setAttribute('id', $offer['id']); + $e->setAttribute('productId', $offer['productId']); + + if (!empty($offer['quantity'])) { + $e->setAttribute('quantity', (int) $offer['quantity']); + } else { + $e->setAttribute('quantity', 0); + } + + foreach ($offer['categoryId'] as $categoryId) { + $e->appendChild( + $this->dd->createElement('categoryId', $categoryId) + ); + } + + $offerKeys = array_keys($offer); + + foreach ($offerKeys as $key) { + if (in_array($key, $this->properties)) { + $e->appendChild( + $this->dd->createElement($key) + )->appendChild( + $this->dd->createTextNode($offer[$key]) + ); + } + + if (in_array($key, array_keys($this->params))) { + $param = $this->dd->createElement('param'); + $param->setAttribute('code', $key); + $param->setAttribute('name', $this->params[$key]); + $param->appendChild( + $this->dd->createTextNode($offer[$key]) + ); + $e->appendChild($param); + } + } + } + } +} + diff --git a/retailcrm/classes/Retailcrm.php b/retailcrm/classes/Retailcrm.php new file mode 100644 index 0000000..4276019 --- /dev/null +++ b/retailcrm/classes/Retailcrm.php @@ -0,0 +1,1055 @@ +url = $url; + $this->defaultParameters = $defaultParameters; + $this->retry = 0; + } + + /** + * Make HTTP request + * + * @param string $path + * @param string $method (default: 'GET') + * @param array $parameters (default: array()) + * @param int $timeout + * @param bool $verify + * @param bool $debug + * @return ApiResponse + */ + public function makeRequest( + $path, + $method, + array $parameters = array(), + $timeout = 30, + $verify = false, + $debug = false + ) { + $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); + + $url = $this->url . $path; + + if (self::METHOD_GET === $method && sizeof($parameters)) { + $url .= '?' . http_build_query($parameters); + } + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt($ch, CURLOPT_FAILONERROR, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $verify); + + if (!$debug) { + curl_setopt($ch, CURLOPT_TIMEOUT, (int) $timeout); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, (int) $timeout); + } else { + curl_setopt($ch, CURLOPT_TIMEOUT_MS, (int) $timeout + ($this->retry * 2000)); + } + + 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 && in_array($errno, array(6, 7, 28, 34, 35)) && $this->retry < 3) { + $errno = null; + $error = null; + $this->retry += 1; + $this->makeRequest( + $path, + $method, + $parameters, + $timeout, + $verify, + $debug + ); + } + + if ($errno) { + throw new CurlException($error, $errno); + } + + return new ApiResponse($statusCode, $responseBody); + } + + public function getRetry() + { + return $this->retry; + } +} + +/** + * Response from retailCRM API + */ +class 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 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]; + } +} + + +/** + * retailCRM API client class + */ +class ApiClient +{ + const VERSION = 'v3'; + + protected $client; + + /** + * Site code + */ + protected $siteCode; + + /** + * Client creating + * + * @param string $url + * @param string $apiKey + * @param string $siteCode + * @return mixed + */ + public function __construct($url, $apiKey, $site = null) + { + if ('/' != substr($url, strlen($url) - 1, 1)) { + $url .= '/'; + } + + $url = $url . 'api/' . self::VERSION; + + $this->client = new Client($url, array('apiKey' => $apiKey)); + $this->siteCode = $site; + } + + /** + * Create a order + * + * @param array $order + * @param string $site (default: null) + * @return 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", Client::METHOD_POST, $this->fillSite($site, array( + 'order' => json_encode($order) + ))); + } + + /** + * Edit a order + * + * @param array $order + * @param string $site (default: null) + * @return 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", + 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 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", 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 ApiResponse + */ + public function ordersGet($id, $by = 'externalId', $site = null) + { + $this->checkIdParameter($by); + + return $this->client->makeRequest("/orders/$id", 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 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', Client::METHOD_GET, $parameters); + } + + /** + * Returns filtered orders list + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * @return 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', Client::METHOD_GET, $parameters); + } + + /** + * Returns statuses of the orders + * + * @param array $ids (default: array()) + * @param array $externalIds (default: array()) + * @return 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', Client::METHOD_GET, $parameters); + } + + /** + * Save order IDs' (id and externalId) association in the CRM + * + * @param array $ids + * @return 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", Client::METHOD_POST, array( + 'orders' => json_encode($ids), + )); + } + + /** + * Get orders assembly history + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * @return ApiResponse + */ + public function ordersPacksHistory(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/packs/history', Client::METHOD_GET, $parameters); + } + + /** + * Create a customer + * + * @param array $customer + * @param string $site (default: null) + * @return 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", 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 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", + 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 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", 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 ApiResponse + */ + public function customersGet($id, $by = 'externalId', $site = null) + { + $this->checkIdParameter($by); + + return $this->client->makeRequest("/customers/$id", 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 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', Client::METHOD_GET, $parameters); + } + + /** + * Save customer IDs' (id and externalId) association in the CRM + * + * @param array $ids + * @return 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", Client::METHOD_POST, array( + 'customers' => json_encode($ids), + )); + } + + /** + * Get purchace prices & stock balance + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * @param string $site (default: null) + * @return ApiResponse + */ + public function storeInventories(array $filter = array(), $page = null, $limit = null, $site = 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('/store/inventories', Client::METHOD_GET, $this->fillSite($site, $parameters)); + } + + /** + * Upload store inventories + * + * @param array $offers + * @param string $site (default: null) + * @return ApiResponse + */ + public function storeInventoriesUpload(array $offers, $site = null) + { + if (!sizeof($offers)) { + throw new InvalidArgumentException('Parameter `offers` must contains array of the customers'); + } + + return $this->client->makeRequest( + "/store/inventories/upload", + Client::METHOD_POST, + $this->fillSite($site, array('offers' => json_encode($offers))) + ); + } + + /** + * Returns deliveryServices list + * + * @return ApiResponse + */ + public function deliveryServicesList() + { + return $this->client->makeRequest('/reference/delivery-services', Client::METHOD_GET); + } + + /** + * Returns deliveryTypes list + * + * @return ApiResponse + */ + public function deliveryTypesList() + { + return $this->client->makeRequest('/reference/delivery-types', Client::METHOD_GET); + } + + /** + * Returns orderMethods list + * + * @return ApiResponse + */ + public function orderMethodsList() + { + return $this->client->makeRequest('/reference/order-methods', Client::METHOD_GET); + } + + /** + * Returns orderTypes list + * + * @return ApiResponse + */ + public function orderTypesList() + { + return $this->client->makeRequest('/reference/order-types', Client::METHOD_GET); + } + + /** + * Returns paymentStatuses list + * + * @return ApiResponse + */ + public function paymentStatusesList() + { + return $this->client->makeRequest('/reference/payment-statuses', Client::METHOD_GET); + } + + /** + * Returns paymentTypes list + * + * @return ApiResponse + */ + public function paymentTypesList() + { + return $this->client->makeRequest('/reference/payment-types', Client::METHOD_GET); + } + + /** + * Returns productStatuses list + * + * @return ApiResponse + */ + public function productStatusesList() + { + return $this->client->makeRequest('/reference/product-statuses', Client::METHOD_GET); + } + + /** + * Returns statusGroups list + * + * @return ApiResponse + */ + public function statusGroupsList() + { + return $this->client->makeRequest('/reference/status-groups', Client::METHOD_GET); + } + + /** + * Returns statuses list + * + * @return ApiResponse + */ + public function statusesList() + { + return $this->client->makeRequest('/reference/statuses', Client::METHOD_GET); + } + + /** + * Returns sites list + * + * @return ApiResponse + */ + public function sitesList() + { + return $this->client->makeRequest('/reference/sites', Client::METHOD_GET); + } + + /** + * Returns stores list + * + * @return ApiResponse + */ + public function storesList() + { + return $this->client->makeRequest('/reference/stores', Client::METHOD_GET); + } + + /** + * Edit deliveryService + * + * @param array $data delivery service data + * @return 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', + Client::METHOD_POST, + array( + 'deliveryService' => json_encode($data) + ) + ); + } + + /** + * Edit deliveryType + * + * @param array $data delivery type data + * @return 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', + Client::METHOD_POST, + array( + 'deliveryType' => json_encode($data) + ) + ); + } + + /** + * Edit orderMethod + * + * @param array $data order method data + * @return 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', + Client::METHOD_POST, + array( + 'orderMethod' => json_encode($data) + ) + ); + } + + /** + * Edit orderType + * + * @param array $data order type data + * @return 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', + Client::METHOD_POST, + array( + 'orderType' => json_encode($data) + ) + ); + } + + /** + * Edit paymentStatus + * + * @param array $data payment status data + * @return 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', + Client::METHOD_POST, + array( + 'paymentStatus' => json_encode($data) + ) + ); + } + + /** + * Edit paymentType + * + * @param array $data payment type data + * @return 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', + Client::METHOD_POST, + array( + 'paymentType' => json_encode($data) + ) + ); + } + + /** + * Edit productStatus + * + * @param array $data product status data + * @return 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', + Client::METHOD_POST, + array( + 'productStatus' => json_encode($data) + ) + ); + } + + /** + * Edit order status + * + * @param array $data status data + * @return 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', + Client::METHOD_POST, + array( + 'status' => json_encode($data) + ) + ); + } + + /** + * Edit site + * + * @param array $data site data + * @return 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', + Client::METHOD_POST, + array( + 'site' => json_encode($data) + ) + ); + } + + /** + * Edit store + * + * @param array $data site data + * @return ApiResponse + */ + public function storesEdit(array $data) + { + if (!isset($data['code'])) { + throw new InvalidArgumentException('Data must contain "code" parameter.'); + } + + if (!isset($data['name'])) { + throw new InvalidArgumentException('Data must contain "name" parameter.'); + } + + return $this->client->makeRequest( + '/reference/stores/' . $data['code'] . '/edit', + Client::METHOD_POST, + array( + 'store' => json_encode($data) + ) + ); + } + + /** + * Update CRM basic statistic + * + * @return ApiResponse + */ + public function statisticUpdate() + { + return $this->client->makeRequest('/statistic/update', 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; + } +} + +class InvalidJsonException extends DomainException +{ +} + +class CurlException extends RuntimeException +{ +} diff --git a/retailcrm/classes/Service.php b/retailcrm/classes/Service.php new file mode 100644 index 0000000..98d13a0 --- /dev/null +++ b/retailcrm/classes/Service.php @@ -0,0 +1,43 @@ + + + retailcrm + + + + + + + 1 + 1 + + \ No newline at end of file diff --git a/retailcrm/export.tpl b/retailcrm/export.tpl new file mode 100644 index 0000000..ead0361 --- /dev/null +++ b/retailcrm/export.tpl @@ -0,0 +1,31 @@ + + + + {$shop_name|escape} + {$company|escape} + {$shop_url|escape} + + {foreach from=$categories item=cat name=categories} + {if $cat.id_category > 2} + {$cat.name} + {/if} + {/foreach} + + + {foreach from=$products item=offer name=products} + + {if $offer.available_for_order}Y{else}N{/if} + {$offer.url|escape} + {$offer.price} + {$offer.purchase_price} + {$offer.id_category_default} + {$offer.picture|escape} + {$offer.name|escape} + {if $offer.article} + {$offer.article|escape} + {/if} + + {/foreach} + + + diff --git a/intarocrm/index.php b/retailcrm/index.php similarity index 58% rename from intarocrm/index.php rename to retailcrm/index.php index 5f95ef6..5f8745d 100644 --- a/intarocrm/index.php +++ b/retailcrm/index.php @@ -1,9 +1,9 @@ exportCatalog(); \ No newline at end of file +$export = new RetailCRM(); +echo $export->exportCatalog(); diff --git a/retailcrm/logo.gif b/retailcrm/logo.gif new file mode 100644 index 0000000000000000000000000000000000000000..ef6236111871375750f1465b1fc52dce815a8f62 GIT binary patch literal 306 zcmZ?wbhEHb6krfwSZc)ZQBv}gl+-7A`OgLhpG{0Y+u41MjQkoE^({XBM}7UTRjYoj zTlZ_@#$VgF|K73V*Up{4cklkaXV33_`+o1=|L5Sr--i$XK6>=e(WAeQ9s2`B$B+Lx zdGgQMvwyE$`+MWY-Le;+;i`}py{SFirPdGqh{=l|cn z{r~af|IeTQfBpLZ`}hApfBygd`~Tm+|3m{F1|R_W#epr{VP=7cj*#)DMt3pCKp(e< z9m>{$i(RItF-2-@c#v^?ss)GlgBwp{u+@-wy!5K6(1W1uzy^S~?gNAeNUEzn^JZxp@?Wr@)?+){7T%eVv^-q9L7%V00{5+1u0SB?R z2Egd;O*SiM6BuQ(z5QBxB2Xu%;mtj5f00E++BJ9jpB11(jSlLpCj;;uuCa)UA%u! z)z#iBSCraXr(WZ6I~rvT4QeP<{u|^TKCHNRPdRnU;rjH+jz+Pw!%mz~J34;OopK1| zmoIX4)pPYK5!th|=7R@FB*^Dut*xxC4ylw_SU@77wzXA0d7=aYE*kyrK($`Jl%@%Q zzkZ$6v{Wc`{Es~bo}%->=OZF(bd-ds7#w70&+d-+OmD9@9A=G;1SlSlH8DY)S3Z91 z@{xsb6g+p1bX`WHbp1LJDfRW$Z{Fk|^m)DN<;yN50_=D1L@WkCZfzM|U8#!~)7P%q zD=Wz5V45&Z`R!Zg&K*88Q>H}frAvHr5}AzJ)>ifEmHhC*92&}Wb&-^$Cbo!`?Mname = 'intarocrm'; + $this->name = 'retailcrm'; $this->tab = 'market_place'; - $this->version = '0.1'; - $this->author = 'Intaro Ltd.'; + $this->version = '0.2'; + $this->author = 'Retail Driver LCC'; - $this->displayName = $this->l('IntaroCRM'); - $this->description = $this->l('Integration module for IntaroCRM'); + $this->displayName = $this->l('RetailCRM'); + $this->description = $this->l('Integration module for RetailCRM'); $this->confirmUninstall = $this->l('Are you sure you want to uninstall?'); - $this->intaroCRM = new \IntaroCrm\RestApi( - Configuration::get('INTAROCRM_ADDRESS'), - Configuration::get('INTAROCRM_API_TOKEN') - ); + $this->apiUrl = Configuration::get('RETAILCRM_ADDRESS'); + $this->apiKey = Configuration::get('RETAILCRM_API_TOKEN'); + + if (!empty($this->apiUrl) && !empty($this->apiKey)) { + $this->api = new ApiClient( + $this->apiUrl, + $this->apiKey + ); + } $this->default_lang = (int)Configuration::get('PS_LANG_DEFAULT'); $this->default_currency = (int)Configuration::get('PS_CURRENCY_DEFAULT'); @@ -54,12 +61,12 @@ class IntaroCRM extends Module function uninstall() { return parent::uninstall() && - Configuration::deleteByName('INTAROCRM_ADDRESS') && - Configuration::deleteByName('INTAROCRM_API_TOKEN') && - Configuration::deleteByName('INTAROCRM_API_STATUS') && - Configuration::deleteByName('INTAROCRM_API_DELIVERY') && - Configuration::deleteByName('INTAROCRM_LAST_SYNC') && - Configuration::deleteByName('INTAROCRM_API_ADDR') + Configuration::deleteByName('RETAILCRM_ADDRESS') && + Configuration::deleteByName('RETAILCRM_API_TOKEN') && + Configuration::deleteByName('RETAILCRM_API_STATUS') && + Configuration::deleteByName('RETAILCRM_API_DELIVERY') && + Configuration::deleteByName('RETAILCRM_LAST_SYNC') && + Configuration::deleteByName('RETAILCRM_API_ADDR') ; } @@ -67,8 +74,8 @@ class IntaroCRM extends Module { $output = null; - $address = Configuration::get('INTAROCRM_ADDRESS'); - $token = Configuration::get('INTAROCRM_API_TOKEN'); + $address = Configuration::get('RETAILCRM_ADDRESS'); + $token = Configuration::get('RETAILCRM_API_TOKEN'); if (!$address || $address == '') { $output .= $this->displayError( $this->l('Invalid crm address') ); @@ -83,24 +90,24 @@ class IntaroCRM extends Module if (Tools::isSubmit('submit'.$this->name)) { - $address = strval(Tools::getValue('INTAROCRM_ADDRESS')); - $token = strval(Tools::getValue('INTAROCRM_API_TOKEN')); - $delivery = json_encode(Tools::getValue('INTAROCRM_API_DELIVERY')); - $status = json_encode(Tools::getValue('INTAROCRM_API_STATUS')); - $payment = json_encode(Tools::getValue('INTAROCRM_API_PAYMENT')); - $order_address = json_encode(Tools::getValue('INTAROCRM_API_ADDR')); + $address = strval(Tools::getValue('RETAILCRM_ADDRESS')); + $token = strval(Tools::getValue('RETAILCRM_API_TOKEN')); + $delivery = json_encode(Tools::getValue('RETAILCRM_API_DELIVERY')); + $status = json_encode(Tools::getValue('RETAILCRM_API_STATUS')); + $payment = json_encode(Tools::getValue('RETAILCRM_API_PAYMENT')); + $order_address = json_encode(Tools::getValue('RETAILCRM_API_ADDR')); if (!$address || empty($address) || !Validate::isGenericName($address)) { $output .= $this->displayError( $this->l('Invalid crm address') ); } elseif (!$token || empty($token) || !Validate::isGenericName($token)) { $output .= $this->displayError( $this->l('Invalid crm api token') ); } else { - Configuration::updateValue('INTAROCRM_ADDRESS', $address); - Configuration::updateValue('INTAROCRM_API_TOKEN', $token); - Configuration::updateValue('INTAROCRM_API_DELIVERY', $delivery); - Configuration::updateValue('INTAROCRM_API_STATUS', $status); - Configuration::updateValue('INTAROCRM_API_PAYMENT', $payment); - Configuration::updateValue('INTAROCRM_API_ADDR', $order_address); + Configuration::updateValue('RETAILCRM_ADDRESS', $address); + Configuration::updateValue('RETAILCRM_API_TOKEN', $token); + Configuration::updateValue('RETAILCRM_API_DELIVERY', $delivery); + Configuration::updateValue('RETAILCRM_API_STATUS', $status); + Configuration::updateValue('RETAILCRM_API_PAYMENT', $payment); + Configuration::updateValue('RETAILCRM_API_ADDR', $order_address); $output .= $this->displayConfirmation($this->l('Settings updated')); } } @@ -115,7 +122,7 @@ class IntaroCRM extends Module $this->displayConfirmation($this->l('Settings updated')); $default_lang = $this->default_lang; - $intaroCrm = $this->intaroCRM; + $intaroCrm = $this->api; /* * Network connection form @@ -128,14 +135,14 @@ class IntaroCRM extends Module array( 'type' => 'text', 'label' => $this->l('CRM address'), - 'name' => 'INTAROCRM_ADDRESS', + 'name' => 'RETAILCRM_ADDRESS', 'size' => 20, 'required' => true ), array( 'type' => 'text', 'label' => $this->l('CRM token'), - 'name' => 'INTAROCRM_API_TOKEN', + 'name' => 'RETAILCRM_API_TOKEN', 'size' => 20, 'required' => true ) @@ -146,35 +153,38 @@ class IntaroCRM extends Module ) ); - /* - * Delivery - */ - $fields_form[1]['form'] = array( - 'legend' => array( - 'title' => $this->l('Delivery'), - ), - 'input' => $this->getDeliveryTypes($default_lang, $intaroCrm), - ); - /* - * Order status - */ - $fields_form[2]['form'] = array( - 'legend' => array( - 'title' => $this->l('Order statuses'), - ), - 'input' => $this->getStatusTypes($default_lang, $intaroCrm), - ); + if (!empty($this->apiUrl) && !empty($this->apiKey)) { + /* + * Delivery + */ + $fields_form[1]['form'] = array( + 'legend' => array( + 'title' => $this->l('Delivery'), + ), + 'input' => $this->getDeliveryTypes(), + ); - /* - * Payment - */ - $fields_form[3]['form'] = array( - 'legend' => array( - 'title' => $this->l('Payment types'), - ), - 'input' => $this->getPaymentTypes($intaroCrm), - ); + /* + * Order status + */ + $fields_form[2]['form'] = array( + 'legend' => array( + 'title' => $this->l('Order statuses'), + ), + 'input' => $this->getStatusTypes(), + ); + + /* + * Payment + */ + $fields_form[3]['form'] = array( + 'legend' => array( + 'title' => $this->l('Payment types'), + ), + 'input' => $this->getPaymentTypes(), + ); + } /* * Address fields @@ -218,45 +228,45 @@ class IntaroCRM extends Module ) ); - $helper->fields_value['INTAROCRM_ADDRESS'] = Configuration::get('INTAROCRM_ADDRESS'); - $helper->fields_value['INTAROCRM_API_TOKEN'] = Configuration::get('INTAROCRM_API_TOKEN'); + $helper->fields_value['RETAILCRM_ADDRESS'] = Configuration::get('RETAILCRM_ADDRESS'); + $helper->fields_value['RETAILCRM_API_TOKEN'] = Configuration::get('RETAILCRM_API_TOKEN'); - $deliverySettings = Configuration::get('INTAROCRM_API_DELIVERY'); + $deliverySettings = Configuration::get('RETAILCRM_API_DELIVERY'); if (isset($deliverySettings) && $deliverySettings != '') { $deliveryTypes = json_decode($deliverySettings); foreach ($deliveryTypes as $idx => $delivery) { - $name = 'INTAROCRM_API_DELIVERY[' . $idx . ']'; + $name = 'RETAILCRM_API_DELIVERY[' . $idx . ']'; $helper->fields_value[$name] = $delivery; } } - $statusSettings = Configuration::get('INTAROCRM_API_STATUS'); + $statusSettings = Configuration::get('RETAILCRM_API_STATUS'); if (isset($statusSettings) && $statusSettings != '') { $statusTypes = json_decode($statusSettings); foreach ($statusTypes as $idx => $status) { - $name = 'INTAROCRM_API_STATUS[' . $idx . ']'; + $name = 'RETAILCRM_API_STATUS[' . $idx . ']'; $helper->fields_value[$name] = $status; } } - $paymentSettings = Configuration::get('INTAROCRM_API_PAYMENT'); + $paymentSettings = Configuration::get('RETAILCRM_API_PAYMENT'); if (isset($paymentSettings) && $paymentSettings != '') { $paymentTypes = json_decode($paymentSettings); foreach ($paymentTypes as $idx => $payment) { - $name = 'INTAROCRM_API_PAYMENT[' . $idx . ']'; + $name = 'RETAILCRM_API_PAYMENT[' . $idx . ']'; $helper->fields_value[$name] = $payment; } } - $addressSettings = Configuration::get('INTAROCRM_API_ADDR'); + $addressSettings = Configuration::get('RETAILCRM_API_ADDR'); if (isset($addressSettings) && $addressSettings != '') { $addressTypes = json_decode($addressSettings); foreach ($addressTypes as $idx => $address) { - $name = 'INTAROCRM_API_ADDR[' . $idx . ']'; + $name = 'RETAILCRM_API_ADDR[' . $idx . ']'; $helper->fields_value[$name] = $address; } } @@ -271,13 +281,14 @@ class IntaroCRM extends Module public function hookActionPaymentConfirmation($params) { - $this->intaroCRM->orderEdit( + $this->api->ordersEdit( array( 'externalId' => $params['id_order'], 'paymentStatus' => 'paid', 'createdAt' => $params['cart']->date_upd ) ); + return $this->hookActionOrderStatusPostUpdate($params); } @@ -287,13 +298,13 @@ class IntaroCRM extends Module $sql = 'SELECT * FROM '._DB_PREFIX_.'address WHERE id_address='.(int)$address_id; $address = Db::getInstance()->ExecuteS($sql); $address = $address[0]; - $delivery = json_decode(Configuration::get('INTAROCRM_API_DELIVERY')); - $payment = json_decode(Configuration::get('INTAROCRM_API_PAYMENT')); + $delivery = json_decode(Configuration::get('RETAILCRM_API_DELIVERY')); + $payment = json_decode(Configuration::get('RETAILCRM_API_PAYMENT')); $inCart = $params['cart']->getProducts(); if (isset($params['orderStatus'])) { try { - $crmCustomerId = $this->intaroCRM->customerCreate( + $this->api->customersCreate( array( 'externalId' => $params['cart']->id_customer, 'lastName' => $params['customer']->lastname, @@ -313,11 +324,11 @@ class IntaroCRM extends Module ) ); } - catch (\IntaroCrm\Exception\CurlException $e) { - error_log("customerCreate: connection error", 3, "intarocrm.log"); + catch (CurlException $e) { + error_log("customerCreate: connection error", 3, _PS_ROOT_DIR . "log/retailcrm.log"); } - catch (\IntaroCrm\Exception\ApiException $e) { - error_log('customerCreate: ' . $e->getMessage(), 3, "intarocrm.log"); + catch (InvalidJsonException $e) { + error_log('customerCreate: ' . $e->getMessage(), 3, _PS_ROOT_DIR . "log/retailcrm.log"); } try { @@ -338,7 +349,7 @@ class IntaroCRM extends Module } else { $pTypeKey = $params['order']->payment; } - $this->intaroCRM->orderCreate( + $this->api->ordersCreate( array( 'externalId' => $params['order']->id, 'orderType' => 'eshop-individual', @@ -364,23 +375,23 @@ class IntaroCRM extends Module ) ); } - catch (\IntaroCrm\Exception\CurlException $e) { - error_log('orderCreate: connection error', 3, "intarocrm.log"); + catch (CurlException $e) { + error_log('orderCreate: connection error', 3, _PS_ROOT_DIR . "log/retailcrm.log"); } - catch (\IntaroCrm\Exception\ApiException $e) { - error_log('orderCreate: ' . $e->getMessage(), 3, "intarocrm.log"); + catch (InvalidJsonException $e) { + error_log('orderCreate: ' . $e->getMessage(), 3, _PS_ROOT_DIR . "log/retailcrm.log"); } } if (isset($params['newOrderStatus']) && !empty($params['newOrderStatus'])) { $statuses = OrderState::getOrderStates($this->default_lang); - $aStatuses = json_decode(Configuration::get('INTAROCRM_API_STATUS')); + $aStatuses = json_decode(Configuration::get('RETAILCRM_API_STATUS')); foreach ($statuses as $status) { if ($status['name'] == $params['newOrderStatus']->name) { $currStatus = $status['id_order_state']; try { - $this->intaroCRM->orderEdit( + $this->api->ordersEdit( array( 'externalId' => $params['id_order'], 'status' => $aStatuses->$currStatus, @@ -388,38 +399,40 @@ class IntaroCRM extends Module ) ); } - catch (\IntaroCrm\Exception\CurlException $e) { - error_log('orderStatusUpdate: connection error', 3, "intarocrm.log"); + catch (CurlException $e) { + error_log('orderStatusUpdate: connection error', 3, _PS_ROOT_DIR . "log/retailcrm.log"); } - catch (\IntaroCrm\Exception\ApiException $e) { - error_log('orderStatusUpdate: ' . $e->getMessage(), 3, "intarocrm.log"); + catch (InvalidJsonException $e) { + error_log('orderStatusUpdate: ' . $e->getMessage(), 3, _PS_ROOT_DIR . "log/retailcrm.log"); } } } } } - protected function getApiDeliveryTypes($intaroCrm) + protected function getApiDeliveryTypes() { $crmDeliveryTypes = array(); - try { - $deliveryTypes = $intaroCrm->deliveryTypesList(); - } - catch (\IntaroCrm\Exception\CurlException $e) { - error_log('deliveryTypesList: connection error', 3, "intarocrm.log"); - } - catch (\IntaroCrm\Exception\ApiException $e) { - error_log('deliveryTypesList: ' . $e->getMessage(), 3, "intarocrm.log"); - } + if (!empty($this->apiUrl) && !empty($this->apiKey)) { + try { + $deliveryTypes = $this->api->deliveryTypesList(); + } + catch (CurlException $e) { + error_log('deliveryTypesList: connection error', 3, _PS_ROOT_DIR . "log/retailcrm.log"); + } + catch (InvalidJsonException $e) { + error_log('deliveryTypesList: ' . $e->getMessage(), 3, _PS_ROOT_DIR . "log/retailcrm.log"); + } - if (!empty($deliveryTypes)) { - $crmDeliveryTypes[] = array(); - foreach ($deliveryTypes as $dType) { - $crmDeliveryTypes[] = array( - 'id_option' => $dType['code'], - 'name' => $dType['name'], - ); + if (!empty($deliveryTypes)) { + $crmDeliveryTypes[] = array(); + foreach ($deliveryTypes as $dType) { + $crmDeliveryTypes[] = array( + 'id_option' => $dType['code'], + 'name' => $dType['name'], + ); + } } } @@ -427,12 +440,12 @@ class IntaroCRM extends Module } - protected function getDeliveryTypes($default_lang, $intaroCrm) + protected function getDeliveryTypes() { $deliveryTypes = array(); $carriers = Carrier::getCarriers( - $default_lang, true, false, false, + $this->default_lang, true, false, false, null, PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE ); @@ -441,10 +454,10 @@ class IntaroCRM extends Module $deliveryTypes[] = array( 'type' => 'select', 'label' => $carrier['name'], - 'name' => 'INTAROCRM_API_DELIVERY[' . $carrier['id_carrier'] . ']', + 'name' => 'RETAILCRM_API_DELIVERY[' . $carrier['id_carrier'] . ']', 'required' => false, 'options' => array( - 'query' => $this->getApiDeliveryTypes($intaroCrm), + 'query' => $this->getApiDeliveryTypes(), 'id' => 'id_option', 'name' => 'name' ) @@ -455,37 +468,39 @@ class IntaroCRM extends Module return $deliveryTypes; } - protected function getApiStatuses($intaroCrm) + protected function getApiStatuses() { $crmStatusTypes = array(); - try { - $statusTypes = $intaroCrm->orderStatusesList(); - } - catch (\IntaroCrm\Exception\CurlException $e) { - error_log('statusTypesList: connection error', 3, "intarocrm.log"); - } - catch (\IntaroCrm\Exception\ApiException $e) { - error_log('statusTypesList: ' . $e->getMessage(), 3, "intarocrm.log"); - } + if (!empty($this->apiUrl) && !empty($this->apiKey)) { + try { + $statusTypes = $this->api->statusesList(); + } + catch (CurlException $e) { + error_log('statusTypesList: connection error', 3, _PS_ROOT_DIR . "log/retailcrm.log"); + } + catch (InvalidJsonException $e) { + error_log('statusTypesList: ' . $e->getMessage(), 3, _PS_ROOT_DIR . "log/retailcrm.log"); + } - if (!empty($statusTypes)) { - $crmStatusTypes[] = array(); - foreach ($statusTypes as $sType) { - $crmStatusTypes[] = array( - 'id_option' => $sType['code'], - 'name' => $sType['name'] - ); + if (!empty($statusTypes)) { + $crmStatusTypes[] = array(); + foreach ($statusTypes as $sType) { + $crmStatusTypes[] = array( + 'id_option' => $sType['code'], + 'name' => $sType['name'] + ); + } } } return $crmStatusTypes; } - protected function getStatusTypes($default_lang, $intaroCrm) + protected function getStatusTypes() { $statusTypes = array(); - $states = OrderState::getOrderStates($default_lang, true); + $states = OrderState::getOrderStates($this->default_lang, true); if (!empty($states)) { foreach ($states as $state) { @@ -493,10 +508,10 @@ class IntaroCRM extends Module $statusTypes[] = array( 'type' => 'select', 'label' => $state['name'], - 'name' => 'INTAROCRM_API_STATUS[' . $state['id_order_state'] . ']', + 'name' => 'RETAILCRM_API_STATUS[' . $state['id_order_state'] . ']', 'required' => false, 'options' => array( - 'query' => $this->getApiStatuses($intaroCrm), + 'query' => $this->getApiStatuses(), 'id' => 'id_option', 'name' => 'name' ) @@ -508,34 +523,36 @@ class IntaroCRM extends Module return $statusTypes; } - protected function getApiPaymentTypes($intaroCrm) + protected function getApiPaymentTypes() { $crmPaymentTypes = array(); - try { - $paymentTypes = $intaroCrm->paymentTypesList(); - } - catch (\IntaroCrm\Exception\CurlException $e) { - error_log('paymentTypesList: connection error', 3, "intarocrm.log"); - } - catch (\IntaroCrm\Exception\ApiException $e) { - error_log('paymentTypesList: ' . $e->getMessage(), 3, "intarocrm.log"); - } + if (!empty($this->apiUrl) && !empty($this->apiKey)) { + try { + $paymentTypes = $this->api->paymentTypesList(); + } + catch (CurlException $e) { + error_log('paymentTypesList: connection error', 3, _PS_ROOT_DIR . "log/retailcrm.log"); + } + catch (InvalidJsonException $e) { + error_log('paymentTypesList: ' . $e->getMessage(), 3, _PS_ROOT_DIR . "log/retailcrm.log"); + } - if (!empty($paymentTypes)) { - $crmPaymentTypes[] = array(); - foreach ($paymentTypes as $pType) { - $crmPaymentTypes[] = array( - 'id_option' => $pType['code'], - 'name' => $pType['name'] - ); + if (!empty($paymentTypes)) { + $crmPaymentTypes[] = array(); + foreach ($paymentTypes as $pType) { + $crmPaymentTypes[] = array( + 'id_option' => $pType['code'], + 'name' => $pType['name'] + ); + } } } return $crmPaymentTypes; } - protected function getPaymentTypes($intaroCrm) + protected function getPaymentTypes() { $payments = $this->getSystemPaymentModules(); $paymentTypes = array(); @@ -545,10 +562,10 @@ class IntaroCRM extends Module $paymentTypes[] = array( 'type' => 'select', 'label' => $payment['name'], - 'name' => 'INTAROCRM_API_PAYMENT[' . $payment['code'] . ']', + 'name' => 'RETAILCRM_API_PAYMENT[' . $payment['code'] . ']', 'required' => false, 'options' => array( - 'query' => $this->getApiPaymentTypes($intaroCrm), + 'query' => $this->getApiPaymentTypes(), 'id' => 'id_option', 'name' => 'name' ) @@ -647,7 +664,7 @@ class IntaroCRM extends Module $addressFields[] = array( 'type' => 'select', 'label' => $this->l((string)$a), - 'name' => 'INTAROCRM_API_ADDR[' . $idx . ']', + 'name' => 'RETAILCRM_API_ADDR[' . $idx . ']', 'required' => false, 'options' => array( 'query' => array( @@ -775,16 +792,18 @@ class IntaroCRM extends Module $crewrite = Category::getLinkRewrite($product['id_category_default'], $id_lang); $url = $link->getProductLink($product['id_product'], $product['link_rewrite'], $crewrite); $version = substr(_PS_VERSION_, 0, 3); + if ($version == "1.3") - $available_for_order = $product['active'] && $product['quantity']; + $available_for_order = $product['active'] && $product['quantity']; else { $prod = new Product($product['id_product']); $available_for_order = $product['active'] && $product['available_for_order'] && $prod->checkQty(1); } + $items[] = array('id_product' => $product['id_product'], 'available_for_order' => $available_for_order, - 'price' => $product['price'], - 'purchase_price' => $product['wholesale_price'], + 'price' => round($product['price'],2), + 'purchase_price' => round($product['wholesale_price'], 2), 'name' => htmlspecialchars(strip_tags($product['name'])), 'article' => htmlspecialchars($product['reference']), 'id_category_default' => $category, @@ -813,7 +832,7 @@ class IntaroCRM extends Module /* * get last sync date */ - $lastSync = Configuration::get('INTAROCRM_LAST_SYNC'); + $lastSync = Configuration::get('RETAILCRM_LAST_SYNC'); $startFrom = ($lastSync === false) ? null : $lastSync; $endTime = date('Y-m-d H:i:s'); @@ -826,18 +845,18 @@ class IntaroCRM extends Module */ do { try { - $this->response = $this->intaroCRM->orderHistory( + $this->response = $this->api->ordersHistory( $startDate = $startFrom, $endDate = $endTime, $limit = 250, $offset = $counter ); $data = array_merge($data, $this->response); $counter += 250; } - catch (\IntaroCrm\Exception\CurlException $e) { - error_log('orderHistory: connection error', 3, "intarocrm.log"); + catch (CurlException $e) { + error_log('orderHistory: connection error', 3, _PS_ROOT_DIR . "log/retailcrm.log"); } - catch (\IntaroCrm\Exception\ApiException $e) { - error_log('orderHistory: ' . $e->getMessage(), 3, "intarocrm.log"); + catch (InvalidJsonException $e) { + error_log('orderHistory: ' . $e->getMessage(), 3, _PS_ROOT_DIR . "log/retailcrm.log"); } } while (!empty($response)); @@ -852,9 +871,9 @@ class IntaroCRM extends Module */ $this->customer = new Customer(); - $statuses = array_flip((array)json_decode(Configuration::get('INTAROCRM_API_STATUS'))); - $deliveries = array_flip((array)json_decode(Configuration::get('INTAROCRM_API_DELIVERY'))); - $payments = array_flip((array)json_decode(Configuration::get('INTAROCRM_API_PAYMENT'))); + $statuses = array_flip((array)json_decode(Configuration::get('RETAILCRM_API_STATUS'))); + $deliveries = array_flip((array)json_decode(Configuration::get('RETAILCRM_API_DELIVERY'))); + $payments = array_flip((array)json_decode(Configuration::get('RETAILCRM_API_PAYMENT'))); foreach ($data as $order) { if (!array_key_exists('externalId', $order)) { @@ -1048,15 +1067,15 @@ class IntaroCRM extends Module Db::getInstance()->execute(rtrim($query, ',')); try { - $this->intaroCRM->customerFixExternalIds($this->customerFix); - $this->intaroCRM->orderFixExternalIds($this->orderFix); + $this->api->customersFixExternalIds($this->customerFix); + $this->api->ordesrFixExternalIds($this->orderFix); } - catch (\IntaroCrm\Exception\CurlException $e) { - error_log('fixExternalId: connection error', 3, "intarocrm.log"); + catch (CurlException $e) { + error_log('fixExternalId: connection error', 3, _PS_ROOT_DIR . "log/retailcrm.log"); continue; } - catch (\IntaroCrm\Exception\ApiException $e) { - error_log('fixExternalId: ' . $e->getMessage(), 3, "intarocrm.log"); + catch (InvalidJsonException $e) { + error_log('fixExternalId: ' . $e->getMessage(), 3, _PS_ROOT_DIR . "log/retailcrm.log"); continue; } @@ -1244,15 +1263,15 @@ class IntaroCRM extends Module */ try { Configuration::updateValue( - 'INTAROCRM_LAST_SYNC', - date_format($this->intaroCRM->getGeneratedAt(), 'Y-m-d H:i:s') + 'RETAILCRM_LAST_SYNC', + date_format($this->api->getGeneratedAt(), 'Y-m-d H:i:s') ); } - catch (\IntaroCrm\Exception\CurlException $e) { - error_log('getLastSync: connection error', 3, "intarocrm.log"); + catch (CurlException $e) { + error_log('getLastSync: connection error', 3, _PS_ROOT_DIR . "log/retailcrm.log"); } - catch (\IntaroCrm\Exception\ApiException $e) { - error_log('getLastSync: ' . $e->getMessage(), 3, "intarocrm.log"); + catch (InvalidJsonException $e) { + error_log('getLastSync: ' . $e->getMessage(), 3, _PS_ROOT_DIR . "log/retailcrm.log"); } return count($data) . " records was synced"; diff --git a/intarocrm/sync.php b/retailcrm/sync.php similarity index 71% rename from intarocrm/sync.php rename to retailcrm/sync.php index bab4cc3..11e32a4 100644 --- a/intarocrm/sync.php +++ b/retailcrm/sync.php @@ -1,9 +1,9 @@ orderHistory(); diff --git a/intarocrm/translations/ru.php b/retailcrm/translations/ru.php similarity index 100% rename from intarocrm/translations/ru.php rename to retailcrm/translations/ru.php