1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
service.php
См. документацию.
1<?php
2
3namespace Sale\Handlers\Delivery\Additional\RusPost\Reliability;
4
5use Bitrix\Main\ArgumentNullException;
6use Bitrix\Main\Event;
7use Bitrix\Main\Loader;
8use Bitrix\Main\Localization\Loc;
9use Bitrix\Main\Web\HttpClient;
10use Bitrix\Sale\Delivery;
11use Bitrix\Sale\Internals\ReliabilityTable;
12use Bitrix\Sale\Order;
13use Bitrix\Sale\PropertyValueCollectionBase;
14use Bitrix\Sale\Shipment;
15
16Loader::registerAutoLoadClasses(
17 'sale',
18 array(
19 __NAMESPACE__.'\Reliability' => 'handlers/delivery/additional/ruspost/reliability/reliability.php',
20 __NAMESPACE__.'\ReliabilityCollection' => 'handlers/delivery/additional/ruspost/reliability/reliabilitycollection.php',
21 __NAMESPACE__.'\Requester' => 'handlers/delivery/additional/ruspost/reliability/requester.php'
22 )
23);
24
29class Service
30{
31 const UNKNOWN = 0;
32 const RELIABLE = 10;
33 const FRAUD = 20;
34
43 public static function getReliabilityCollection(int $deliveryId, ReliabilityCollection $collection)
44 {
45 if($deliveryId <= 0)
46 {
47 throw new ArgumentNullException('deliveryId');
48 }
49
50 if($collection->count() <= 0)
51 {
52 return $collection;
53 }
54
55 $notFoundInDb = $collection->getHashList();
56
58 $stored = self::getTableClass()::query()
59 ->addFilter('HASH', $collection->getHashList())
60 ->whereNotNull("RELIABILITY")
61 ->addSelect('*')
62 ->fetchCollection();
63
64 if($stored)
65 {
66 $notFoundInDb = array_diff($collection->getHashList(), $stored->getHashList());
67
68 if (empty($notFoundInDb))
69 {
70 return $stored;
71 }
72 }
73
74 $requested = self::requestReliability(
75 $deliveryId,
76 $collection->filterByHashes($notFoundInDb)
77 );
78
79 $result = new ReliabilityCollection();
80 $result->setItems($collection->getAll());
81
82 if($stored)
83 {
84 $result->setItems($stored->getAll());
85 }
86
87 if($requested)
88 {
89 $result->setItems($requested->getAll());
90 }
91
92 $result->saveItems();
93 return $result;
94 }
95
106 public static function getReliabilityValue(int $deliveryId, string $fullName, string $address, string $phone)
107 {
108 $collection = new ReliabilityCollection();
109 $collection->add(Reliability::create($fullName, $address, $phone));
110 $hash = self::createHash($fullName, $address, $phone);
111
112 $resultCollection = self::getReliabilityCollection(
113 $deliveryId,
114 $collection
115 );
116
117 if($reliability = $resultCollection->getByPrimary($hash))
118 {
119 return $reliability->getReliability();
120 }
121
122 return self::UNKNOWN;
123 }
124
131 public static function prepareData(int $deliveryId, int $attempt = 0)
132 {
133 if($deliveryId <= 0)
134 {
135 return '';
136 }
137
139 $collection = self::getTableClass()::query()
140 ->whereNull('RELIABILITY')
141 ->addSelect('*')
142 ->fetchCollection();
143
144 if($collection->count() <= 0)
145 {
146 return '';
147 }
148
150 if($requestedCollection = self::requestReliability($deliveryId, $collection))
151 {
152 $requestedCollection->saveItems();
153 return '';
154 }
155
156 if($attempt > 0)
157 {
158 return self::createAgentName($deliveryId, --$attempt);
159 }
160
161 return '';
162 }
163
170 private static function extractProperties(Shipment $shipment)
171 {
172 if (!($order = $shipment->getOrder()))
173 {
174 return null;
175 }
176
177 if (!($userId = (int)$order->getUserId()) || $userId === (int)\CSaleUser::GetAnonymousUserID())
178 {
179 return null;
180 }
181
182 if(!$props = $order->getPropertyCollection())
183 {
184 return null;
185 }
186
187 return $props;
188 }
189
195 private static function extractDataFromProps(PropertyValueCollectionBase $props)
196 {
197 $addressValue = '';
198 $fullNameValue = '';
199 $phoneValue = '';
200
201 if($address = $props->getAddress())
202 {
203 if($address->getValue() <> '')
204 {
205 $addressValue = (string)$address->getValue();
206 }
207 }
208
209 if($payerName = $props->getPayerName())
210 {
211 if($payerName->getValue() <> '' )
212 {
213 $fullNameValue = (string)$payerName->getValue();
214 }
215 }
216
217 if($phone = $props->getPhone())
218 {
219 if($phone->getValue() <> '' )
220 {
221 $phoneValue = (string)$phone->getValue();
222 }
223 }
224
225 if($addressValue == '' && $fullNameValue == '' && $phoneValue == '')
226 {
227 return null;
228 }
229
230 return[$fullNameValue, $addressValue, $phoneValue];
231 }
232
243 public static function onShipmentSave($expectedDeliveryId, Event $event)
244 {
246 if (!($shipment = $event->getParameter('ENTITY')))
247 {
248 return;
249 }
250
252 if (!($delivery = $shipment->getDelivery()))
253 {
254 return;
255 }
256
257 if(!self::isDeliverySuitable($delivery, $expectedDeliveryId))
258 {
259 return;
260 }
261
262 if(!$props = self::extractProperties($shipment))
263 {
264 return;
265 }
266
267 if(!($data = self::extractDataFromProps($props)))
268 {
269 return;
270 }
271
272 list($fullName, $address, $phone) = $data;
273 $hash = self::createHash($fullName, $address, $phone);
274
275 if(!($reliability = self::getTableClass()::getByPrimary($hash)->fetchObject()))
276 {
277 $reliability = Reliability::create($fullName, $address, $phone);
278 $reliability->save();
279 }
280
281 self::addAgent($delivery->getId(), 3);
282 }
283
294 public static function onSaleAdminOrderInfoBlockShow($expectedDeliveryId, Event $event)
295 {
297 $order = $event->getParameter("ORDER");
298
299 $findSuitable = false;
300
302 foreach ($order->getShipmentCollection() as $shipment)
303 {
304 if($shipment->isSystem())
305 {
306 continue;
307 }
308
309 if(!($delivery = $shipment->getDelivery()))
310 {
311 continue;
312 }
313
314 if (self::isDeliverySuitable($delivery, $expectedDeliveryId))
315 {
316 $findSuitable = true;
317 break;
318 }
319 }
320
321 $result = new \Bitrix\Main\EventResult(\Bitrix\Main\EventResult::SUCCESS);
322
323 if(!$findSuitable)
324 {
325 return $result;
326 }
327
328 if(!($props = $order->getPropertyCollection()))
329 {
330 return $result;
331 }
332
333 if(!($data = self::extractDataFromProps($props)))
334 {
335 return $result;
336 }
337
338 list($fullName, $address, $phone) = $data;
339 $reliability = self::getReliabilityValue($delivery->getId(), $fullName, $address, $phone);
340
341 global $APPLICATION;
342
343 ob_start();
344
345 $APPLICATION->IncludeComponent(
346 'bitrix:sale.delivery.ruspost.reliability',
347 '.default',
348 ['RELIABILITY' => $reliability]
349 );
350
351 $value = ob_get_contents();
352 ob_end_clean();
353
354 return new \Bitrix\Main\EventResult(
355 \Bitrix\Main\EventResult::SUCCESS,
356 [
357 [
358 'TITLE' => Loc::getMessage('SALE_DLVRS_RELIABILITY_TITLE'),
359 'VALUE' => $value
360 ]
361 ],
362 'sale'
363 );
364 }
365
366
374 private static function requestReliability(int $deliveryId, ReliabilityCollection $collection)
375 {
376 if($deliveryId <= 0)
377 {
378 return $collection;
379 }
380
381 if($collection->count() <= 0)
382 {
383 return $collection;
384 }
385
386 $delivery = Delivery\Services\Manager::getObjectById($deliveryId);
387
388 if(!$delivery || !self::isDeliverySuitable($delivery))
389 {
390 return $collection;
391 }
392
394 if(!($deliveryRequest = $delivery->getDeliveryRequestHandler()))
395 {
396 return $collection;
397 }
398
399 $deliveryRequest->setHttpClient(self::createHttpClient());
400
401 return (new Requester($deliveryRequest))
402 ->request($collection);
403 }
404
409 private static function isDeliverySuitable(Delivery\Services\Base $delivery, $expectedDeliveryId = 0)
410 {
411 if (get_class($delivery) !== 'Sale\Handlers\Delivery\AdditionalProfile' || $delivery->getId() <= 0)
412 {
413 return false;
414 }
415
417
418 if ($delivery->getParentService()->getServiceType() !== 'RUSPOST')
419 {
420 return false;
421 }
422
423 if($expectedDeliveryId > 0)
424 {
425 if(!($deliveryRequest = $delivery->getDeliveryRequestHandler()))
426 {
427 return false;
428 }
429
430 if($deliveryRequest->getHandlingDeliveryServiceId() != $expectedDeliveryId)
431 {
432 return false;
433 }
434 }
435
436 return true;
437 }
438
445 public static function createHash(string $fullName, string $address, string $phone)
446 {
447 return md5(trim($fullName).trim($address).trim($phone));
448 }
449
453 public static function install(int $deliveryId)
454 {
455 $eventManager = \Bitrix\Main\EventManager::getInstance();
456 $eventManager->registerEventHandler('sale', 'OnSaleShipmentEntitySaved' , 'sale', '\Sale\Handlers\Delivery\Additional\RusPost\Reliability\Service', 'onShipmentSave', 100, "", [$deliveryId]);
457 $eventManager->registerEventHandler('sale', 'onSaleAdminOrderInfoBlockShow' , 'sale', '\Sale\Handlers\Delivery\Additional\RusPost\Reliability\Service', 'onSaleAdminOrderInfoBlockShow', 100, "", [$deliveryId]);
458 }
459
463 public static function unInstall(int $deliveryId)
464 {
465 $eventManager = \Bitrix\Main\EventManager::getInstance();
466 $eventManager->unRegisterEventHandler('sale', 'OnSaleShipmentEntitySaved' , 'sale', '\Sale\Handlers\Delivery\Additional\RusPost\Reliability\Service', 'onShipmentSave', "", [$deliveryId]);
467 $eventManager->unRegisterEventHandler('sale', 'onSaleAdminOrderInfoBlockShow' , 'sale', '\Sale\Handlers\Delivery\Additional\RusPost\Reliability\Service', 'onSaleAdminOrderInfoBlockShow', "", [$deliveryId]);
468 }
469
473 private static function createHttpClient()
474 {
475 return new HttpClient(array(
476 "version" => "1.1",
477 "socketTimeout" => 5,
478 "streamTimeout" => 5,
479 "redirect" => true,
480 "redirectMax" => 3,
481 ));
482 }
483
487 private static function addAgent(int $deliveryId, int $attempts)
488 {
489 if($attempts <= 0)
490 {
491 return;
492 }
493
494 \CAgent::AddAgent(self::createAgentName($deliveryId, $attempts), "sale", "N", 60, "", "Y");
495 }
496
502 private static function createAgentName(int $deliveryId, int $attempts)
503 {
504 return '\Sale\Handlers\Delivery\Additional\RusPost\Reliability\Service::prepareData('.$deliveryId.', '.$attempts.');';
505 }
506
510 private static function getTableClass()
511 {
512 return ReliabilityTable::class;
513 }
514}
$hash
Определения ajax_redirector.php:8
global $APPLICATION
Определения include.php:80
if(!is_object($USER)||! $USER->IsAuthorized()) $userId
Определения check_mail.php:18
static GetAnonymousUserID()
Определения basket.php:3562
$data['IS_AVAILABLE']
Определения .description.php:13
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$result
Определения get_property_values.php:14
$value
Определения Param.php:39
$order
Определения payment.php:8
$event
Определения prolog_after.php:141
$props
Определения template.php:269
$eventManager
Определения include.php:412