1
|
|
|
<?php |
|
|
|
|
2
|
|
|
/** |
3
|
|
|
* @author Alexey Tatarinov <[email protected]> |
4
|
|
|
* @link https://github.com/shogodev/argilla/ |
5
|
|
|
* @copyright Copyright © 2003-2015 Shogo |
6
|
|
|
* @license http://argilla.ru/LICENSE |
7
|
|
|
* |
8
|
|
|
* Пример подключения в frontend.php: |
9
|
|
|
* 'components' => array( |
10
|
|
|
* ... |
11
|
|
|
* 'retailCrm' => array( |
12
|
|
|
* 'class' => 'ext.retailcrm.RetailCrm', |
13
|
|
|
* ), |
14
|
|
|
* ... |
15
|
|
|
* ) |
16
|
|
|
*/ |
17
|
|
|
Yii::import('frontend.components.cli.*'); |
18
|
|
|
Yii::import('ext.retailcrm.components.RetailCrmDataManager'); |
19
|
|
|
|
20
|
|
|
Yii::import('ext.retailcrm.components.lib.ApiClient', true); |
21
|
|
|
Yii::import('ext.retailcrm.components.lib.Http.Client', true); |
22
|
|
|
Yii::import('ext.retailcrm.components.lib.Exception.CurlException', true); |
23
|
|
|
Yii::import('ext.retailcrm.components.lib.Exception.InvalidJsonException', true); |
24
|
|
|
Yii::import('ext.retailcrm.components.lib.Response.ApiResponse', true); |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Class RetailCrm |
28
|
|
|
*/ |
29
|
|
|
class RetailCrm extends CApplicationComponent |
30
|
|
|
{ |
31
|
|
|
public $debug = false; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @var string $url |
35
|
|
|
*/ |
36
|
|
|
protected $url; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @var string $apiKey |
40
|
|
|
*/ |
41
|
|
|
protected $apiKey; |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @var boolean $enabled |
45
|
|
|
*/ |
46
|
|
|
protected $enabled; |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @var boolean $log |
50
|
|
|
*/ |
51
|
|
|
protected $log; |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @var ConsoleFileLogger $logger |
55
|
|
|
*/ |
56
|
|
|
public $logger; |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @var RetailCrmDataManager $retailCrmDataManager |
60
|
|
|
*/ |
61
|
|
|
protected $retailCrmDataManager; |
62
|
|
|
|
63
|
|
|
protected $exportProductCounter; |
64
|
|
|
|
65
|
|
|
protected $beginExportTime; |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @var RetailCrm\ApiClient $apiClient |
69
|
|
|
*/ |
70
|
|
|
private $apiClient; |
71
|
|
|
|
72
|
|
|
public function init() |
73
|
|
|
{ |
74
|
|
|
parent::init(); |
75
|
|
|
|
76
|
|
|
$this->retailCrmDataManager = new RetailCrmDataManager(); |
77
|
|
|
|
78
|
|
|
$this->configure(); |
79
|
|
|
|
80
|
|
|
$this->logger = new ConsoleFileLogger('retail_crm.log'); |
81
|
|
|
$this->logger->showLog = false; |
82
|
|
|
|
83
|
|
|
$this->apiClient = new RetailCrm\ApiClient( |
84
|
|
|
$this->url, |
85
|
|
|
$this->apiKey |
86
|
|
|
); |
87
|
|
|
} |
88
|
|
|
|
89
|
|
View Code Duplication |
public function createCallback(Callback $model) |
|
|
|
|
90
|
|
|
{ |
91
|
|
|
if( !$this->enabled ) |
92
|
|
|
return; |
93
|
|
|
|
94
|
|
|
$this->flushContent(); |
95
|
|
|
|
96
|
|
|
try |
97
|
|
|
{ |
98
|
|
|
$data = $this->retailCrmDataManager->getCallbackData($model); |
99
|
|
|
} |
100
|
|
|
catch(CException $e) |
|
|
|
|
101
|
|
|
{ |
102
|
|
|
$this->logger->error('Ошибка в формировании данных для RetailCrm. '.$e->getMessage()); |
103
|
|
|
return; |
104
|
|
|
} |
105
|
|
|
$this->setCustomerData($data); |
106
|
|
|
|
107
|
|
|
if( $retailCrmOrderId = $this->sendOrder($data, $model) ) |
|
|
|
|
108
|
|
|
{ |
109
|
|
|
$this->retailCrmDataManager->setRetailCrmUrl($model, $data['number'], $this->url); |
110
|
|
|
} |
111
|
|
|
} |
112
|
|
|
|
113
|
|
View Code Duplication |
public function createOrder(Order $model) |
|
|
|
|
114
|
|
|
{ |
115
|
|
|
if( !$this->enabled ) |
116
|
|
|
return; |
117
|
|
|
|
118
|
|
|
$this->flushContent(); |
119
|
|
|
|
120
|
|
|
try |
121
|
|
|
{ |
122
|
|
|
$data = $this->retailCrmDataManager->getOrderData($model); |
123
|
|
|
} |
124
|
|
|
catch(CException $e) |
|
|
|
|
125
|
|
|
{ |
126
|
|
|
$this->logger->error('Ошибка в формировании данных для RetailCrm. '.$e->getMessage()); |
127
|
|
|
return; |
128
|
|
|
} |
129
|
|
|
|
130
|
|
|
$this->setCustomerData($data); |
131
|
|
|
if( $retailCrmOrderId = $this->sendOrder($data, $model) ) |
132
|
|
|
{ |
133
|
|
|
$this->retailCrmDataManager->updateOrderStatus($model); |
134
|
|
|
$this->retailCrmDataManager->setRetailCrmUrl($model, $retailCrmOrderId, $this->url); |
135
|
|
|
} |
136
|
|
|
} |
137
|
|
|
|
138
|
|
|
public function registerEventEndExportIcml() |
139
|
|
|
{ |
140
|
|
|
if( Yii::app()->request->getParam('force') != 'force' ) |
141
|
|
|
return; |
142
|
|
|
|
143
|
|
|
$this->beginExportTime = microtime(true); |
144
|
|
|
$this->logger->log('Начало экспорта icml'); |
145
|
|
|
$this->logger->flush(); |
146
|
|
|
Yii::app()->attachEventHandler('onEndRequest', array($this, 'onEndExport')); |
147
|
|
|
Yii::app()->attachEventHandler('onException', array($this, 'onError')); |
148
|
|
|
Yii::app()->attachEventHandler('onError', array($this, 'onError')); |
149
|
|
|
register_shutdown_function(array($this, 'exceptionShutdown')); |
150
|
|
|
} |
151
|
|
|
|
152
|
|
|
public function onEndExport($event) |
153
|
|
|
{ |
154
|
|
|
$time = microtime(true) - $this->beginExportTime; |
155
|
|
|
$logMessage = 'Экспорт icml завершен за '.sprintf("%.1f", $time).' с.'.PHP_EOL; |
156
|
|
|
$logMessage .= 'Обработано '.$this->exportProductCounter.' продуктов.'.PHP_EOL; |
157
|
|
|
$logMessage .= 'Максимальное использовано памяти '.Yii::app()->format->formatSize(memory_get_peak_usage()); |
158
|
|
|
|
159
|
|
|
$this->logger->log($logMessage); |
160
|
|
|
$this->logger->flush(); |
161
|
|
|
} |
162
|
|
|
|
163
|
|
|
public function onError($event) |
164
|
|
|
{ |
165
|
|
|
if( isset($event->exception) ) |
166
|
|
|
$this->logger->error($event->exception->getMessage()); |
167
|
|
|
else if( isset($event->message) ) |
168
|
|
|
$this->logger->error($event->message); |
169
|
|
|
else |
170
|
|
|
$this->logger->error("Не известная ошибка"); |
171
|
|
|
} |
172
|
|
|
|
173
|
|
|
public function exceptionShutdown() |
174
|
|
|
{ |
175
|
|
|
$error = error_get_last(); |
176
|
|
|
|
177
|
|
|
if (is_array($error) != FALSE) |
|
|
|
|
178
|
|
|
{ |
179
|
|
|
if (isset($error['type']) != FALSE) |
|
|
|
|
180
|
|
|
{ |
181
|
|
|
if ($error['type'] == 1) |
182
|
|
|
{ |
183
|
|
|
$this->logger->error("Фатальная ошибка: ".$error['message']); |
184
|
|
|
} |
185
|
|
|
} |
186
|
|
|
} |
187
|
|
|
} |
188
|
|
|
|
189
|
|
|
public function increaseExportProductCounter() |
190
|
|
|
{ |
191
|
|
|
$this->exportProductCounter++; |
192
|
|
|
} |
193
|
|
|
|
194
|
|
|
/** |
195
|
|
|
* @return ConsoleFileLogger |
196
|
|
|
*/ |
197
|
|
|
public function getLogger() |
198
|
|
|
{ |
199
|
|
|
return $this->logger; |
200
|
|
|
} |
201
|
|
|
|
202
|
|
|
public function createDebugReport($attributes, $offerCounter) |
203
|
|
|
{ |
204
|
|
|
if( $this->debug ) |
205
|
|
|
{ |
206
|
|
|
$log = 'Product id = '.$attributes['id'].' process'.PHP_EOL; |
207
|
|
|
$log .= 'Processed items '.$offerCounter.' Date '.date('d.m.Y H:i:s').PHP_EOL; |
208
|
|
|
$log .= 'Usage memory is '.round(memory_get_usage() / 1024).' KBt'.PHP_EOL; |
209
|
|
|
$log .= 'Peak usage memory is '.round(memory_get_peak_usage() / 1024).' KBt'.PHP_EOL; |
210
|
|
|
file_put_contents(Yii::getPathOfAlias('frontend.runtime').'/retail_crm_debug.log', array($log)); |
211
|
|
|
} |
212
|
|
|
} |
213
|
|
|
|
214
|
|
|
/** |
215
|
|
|
* @param array $data |
216
|
|
|
* |
217
|
|
|
* @return null |
218
|
|
|
*/ |
219
|
|
|
private function setCustomerData(&$data = array()) |
220
|
|
|
{ |
221
|
|
|
$filter = array(); |
222
|
|
|
|
223
|
|
|
if( !empty($data['phone']) ) |
224
|
|
|
$filter['name'] = $data['phone']; |
225
|
|
|
else if( !empty($data['email']) ) |
226
|
|
|
$filter['email'] = $data['email']; |
227
|
|
View Code Duplication |
else |
|
|
|
|
228
|
|
|
{ |
229
|
|
|
$nameArray = array(); |
230
|
|
|
if( !empty($data['lastName']) ) |
231
|
|
|
$nameArray[] = $data['lastName']; |
232
|
|
|
if( !empty($data['firstName']) ) |
233
|
|
|
$nameArray[] = $data['firstName']; |
234
|
|
|
if( !empty($data['patronymic']) ) |
235
|
|
|
$nameArray[] = $data['patronymic']; |
236
|
|
|
|
237
|
|
|
if( !empty($nameArray) ) |
238
|
|
|
$filter['name'] = implode(' ', $nameArray); |
239
|
|
|
} |
240
|
|
|
|
241
|
|
|
if( empty($filter) ) |
242
|
|
|
return; |
243
|
|
|
|
244
|
|
|
try |
245
|
|
|
{ |
246
|
|
|
$response = $this->apiClient->customersList($filter); |
247
|
|
|
} |
248
|
|
|
catch(\RetailCrm\Exception\CurlException $e) |
249
|
|
|
{ |
250
|
|
|
if( $this->log ) |
251
|
|
|
$this->logger->error("Сетевые проблемы. Ошибка подключения к retailCRM: ".$e->getMessage()); |
252
|
|
|
|
253
|
|
|
return; |
254
|
|
|
} |
255
|
|
|
|
256
|
|
|
if( $response->isSuccessful() ) |
257
|
|
|
{ |
258
|
|
|
if( !($user = Arr::reset($response->customers)) ) |
|
|
|
|
259
|
|
|
return; |
260
|
|
|
|
261
|
|
|
if( isset($user['customerId']) ) |
262
|
|
|
{ |
263
|
|
|
$data['customerId'] = $user['customerId']; |
264
|
|
|
} |
265
|
|
|
} |
266
|
|
|
else |
267
|
|
|
{ |
268
|
|
|
if( $this->log ) |
269
|
|
|
{ |
270
|
|
|
$errorMessage = "Ошибка при запросе пользователей: [Статус HTTP-ответа ".$response->getStatusCode()."] ".$response->getErrorMsg().'.'; |
|
|
|
|
271
|
|
|
if( $response->offsetExists('errors') ) |
272
|
|
|
$errorMessage .= ' '.$response->offsetGet('errors'); |
273
|
|
|
|
274
|
|
|
$this->logger->error($errorMessage); |
275
|
|
|
} |
276
|
|
|
} |
277
|
|
|
} |
278
|
|
|
|
279
|
|
|
private function configure() |
280
|
|
|
{ |
281
|
|
|
$configPath = Yii::getPathOfAlias('frontend.config.retail_crm').'.php'; |
282
|
|
|
if( file_exists($configPath) ) |
283
|
|
|
{ |
284
|
|
|
$config = require($configPath); |
285
|
|
|
$this->url = $config['url']; |
286
|
|
|
$this->apiKey = $config['apiKey']; |
287
|
|
|
|
288
|
|
|
if( isset($config['idPrefix']) ) |
289
|
|
|
$this->retailCrmDataManager->idPrefix = $config['idPrefix']; |
290
|
|
|
|
291
|
|
|
if( isset($config['log']) ) |
292
|
|
|
$this->log = $config['log']; |
293
|
|
|
|
294
|
|
|
if( isset($config['debug']) ) |
295
|
|
|
$this->debug = $config['debug']; |
296
|
|
|
|
297
|
|
|
$this->enabled = $config['enabled']; |
298
|
|
|
} |
299
|
|
|
else |
300
|
|
|
{ |
301
|
|
|
throw new CHttpException('500', 'Не найден кофигурационный файл retail_crm.php в папке config'); |
302
|
|
|
} |
303
|
|
|
} |
304
|
|
|
|
305
|
|
|
/** |
306
|
|
|
* @param array $data |
307
|
|
|
* @param CActiveRecord $model |
308
|
|
|
* |
309
|
|
|
* @return null|string $retailCrmId |
310
|
|
|
*/ |
311
|
|
|
private function sendOrder(array $data, CActiveRecord $model) |
312
|
|
|
{ |
313
|
|
|
try |
314
|
|
|
{ |
315
|
|
|
$response = $this->apiClient->ordersCreate($data); |
316
|
|
|
} |
317
|
|
|
catch(\RetailCrm\Exception\CurlException $e) |
318
|
|
|
{ |
319
|
|
|
if( $this->log ) |
320
|
|
|
$this->logger->error("Сетевые проблемы. Ошибка подключения к retailCRM: ".$e->getMessage()); |
321
|
|
|
|
322
|
|
|
return null; |
323
|
|
|
} |
324
|
|
|
|
325
|
|
|
if( $response->isSuccessful() && 201 === $response->getStatusCode() ) |
326
|
|
|
{ |
327
|
|
|
if( $this->log ) |
328
|
|
|
$this->logger->log('Заказ ('.get_class($model).') успешно создан id = '.$model->id.' retail_crm_id = '.$response->id); |
|
|
|
|
329
|
|
|
|
330
|
|
|
return $response->id; |
|
|
|
|
331
|
|
|
} |
332
|
|
|
else |
333
|
|
|
{ |
334
|
|
|
if( $this->log ) |
335
|
|
|
{ |
336
|
|
|
$errorMessage = "Ошибка создания заказа(".get_class($model).") id = {$model->id}: [Статус HTTP-ответа ".$response->getStatusCode()."] ".$response->getErrorMsg().'.'; |
|
|
|
|
337
|
|
|
if( $response->offsetExists('errors') ) |
338
|
|
|
$errorMessage .= ' '.print_r($response->offsetGet('errors'), true); |
339
|
|
|
|
340
|
|
|
$this->logger->error($errorMessage); |
341
|
|
|
} |
342
|
|
|
} |
343
|
|
|
|
344
|
|
|
return null; |
345
|
|
|
} |
346
|
|
|
|
347
|
|
|
private function flushContent() |
348
|
|
|
{ |
349
|
|
|
if( function_exists('fastcgi_finish_request') ) |
350
|
|
|
{ |
351
|
|
|
session_write_close(); |
352
|
|
|
fastcgi_finish_request(); |
353
|
|
|
} |
354
|
|
|
} |
355
|
|
|
} |
The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.
The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.
To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.