1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
handler.php
См. документацию.
1<?php
2
3namespace Sale\Handlers\Delivery;
4
5use Bitrix\Main\Error,
6 Bitrix\Main\Loader,
7 Bitrix\Main\IO\File,
8 Bitrix\Sale\Shipment,
9 Bitrix\Main\Page\Asset,
10 Bitrix\Main\Config\Option,
11 Bitrix\Main\SystemException,
12 Bitrix\Main\Localization\Loc,
13 Bitrix\Main\ArgumentNullException,
14 Bitrix\Sale\Delivery\Services\Base,
15 Bitrix\Sale\Delivery\ExtraServices,
16 Bitrix\Sale\Location\ExternalTable,
17 Bitrix\Sale\Location\LocationTable,
18 Bitrix\Sale\Delivery\Services\Manager,
19 Bitrix\Sale\Delivery\ExtraServices\Table,
20 Bitrix\Sale\Location\Admin\LocationHelper,
21 Sale\Handlers\Delivery\Additional\Location,
22 Sale\Handlers\Delivery\Additional\RestClient,
23 Bitrix\Sale\Internals\ServiceRestrictionTable,
24 Sale\Handlers\Delivery\Additional\DeliveryRequests\RusPost,
25 Sale\Handlers\Delivery\Additional\RusPost\Reliability;
26
27Loc::loadMessages(__FILE__);
28
29Loader::registerAutoLoadClasses(
30 'sale',
31 array(
32 __NAMESPACE__.'\Additional\Action' => 'handlers/delivery/additional/action.php',
33 __NAMESPACE__.'\AdditionalProfile' => 'handlers/delivery/additional/profile.php',
34 __NAMESPACE__.'\Additional\Location' => 'handlers/delivery/additional/location.php',
35 __NAMESPACE__.'\Additional\CacheManager' => 'handlers/delivery/additional/cache.php',
36 __NAMESPACE__.'\Additional\RestClient' => 'handlers/delivery/additional/restclient.php',
37 __NAMESPACE__.'\Additional\RusPost\Helper' => 'handlers/delivery/additional/ruspost/helper.php',
38 __NAMESPACE__.'\Additional\DeliveryRequests\RusPost\Handler' => 'handlers/delivery/additional/deliveryrequests/ruspost/handler.php',
39 )
40);
41
47class AdditionalHandler extends Base
48{
50 protected $serviceType = "";
51 protected static $canHasProfiles = true;
52 protected static $whetherAdminExtraServicesShow = true;
53 protected $trackingClass = '\Sale\Handlers\Delivery\AdditionalTracking';
54 protected $trackingTitle = '';
55 protected $trackingDescription = '';
56 protected $profilesListFull = null;
57 protected $extraServicesList = null;
58
59 const LOGO_FILE_ID_OPTION = 'handlers_dlv_add_lgotip';
60
66
67 public function __construct(array $initParams)
68 {
69 parent::__construct($initParams);
70
71 if(isset($initParams['SERVICE_TYPE']) && $initParams['SERVICE_TYPE'] <> '')
72 $this->serviceType = $initParams['SERVICE_TYPE'];
73 elseif(isset($this->config["MAIN"]["SERVICE_TYPE"]))
74 $this->serviceType = $this->config["MAIN"]["SERVICE_TYPE"];
75
76 if($this->serviceType == '')
77 throw new ArgumentNullException('initParams[SERVICE_TYPE]');
78
79 if (
80 isset($initParams['CONFIG']['MAIN']['SERVICE_TYPE'])
81 && $initParams['CONFIG']['MAIN']['SERVICE_TYPE'] === "RUSPOST"
82 )
83 {
84 $this->setTrackingClass('\Bitrix\Sale\Delivery\Tracking\RusPost');
85 }
86 elseif(empty($this->config['MAIN']['TRACKING_TITLE']))
87 {
88 $this->trackingClass = '';
89 }
90
91 if(intval($this->id) <= 0)
92 {
93 $srvParams = $this->getServiceParams();
94
95 if(!empty($srvParams['NAME']))
96 $this->name = $srvParams['NAME'];
97
98 if(!empty($srvParams['DESCRIPTION']))
99 $this->description = $srvParams['DESCRIPTION'];
100
101 if(!empty($srvParams['LOGOTIP']))
102 $this->logotip = $srvParams['LOGOTIP'];
103 }
104
105 $this->deliveryRequestHandler = $this->getDeliveryRequestHandler();
106 }
107
111 public function getHandlerCode(): string
112 {
113 return 'BITRIX_ADDITIONAL_' . (string)$this->serviceType;
114 }
115
116 public function getDeliveryRequestHandler()
117 {
118 $result = null;
119
120 if($this->serviceType == "RUSPOST")
121 if(!empty($this->config["MAIN"]["OTPRAVKA_AUTH_TOKEN"]) && !empty($this->config["MAIN"]["OTPRAVKA_AUTH_KEY"]))
122 $result = new RusPost\Handler($this);
123
124 return $result;
125 }
126
130 public static function getClassTitle()
131 {
132 return Loc::getMessage("SALE_DLVRS_ADD_NAME");
133 }
134
138 public static function getClassDescription()
139 {
140 return Loc::getMessage("SALE_DLVRS_ADD_DESCRIPTION");
141 }
142
148 protected function getConfigStructure()
149 {
150 $fields = $this->getServiceParams();
151
152 if(empty($fields))
153 throw new SystemException(Loc::getMessage('SALE_DLVRS_ADD_CONFIG_RECEIVE_ERROR'));
154
155 $result = array(
156 "MAIN" => array(
157 "TITLE" => Loc::getMessage("SALE_DLVRS_ADD_MAIN_TITLE"),
158 "DESCRIPTION" => Loc::getMessage("SALE_DLVRS_ADD_MAIN_DESCRIPTION"),
159 "ITEMS" => array(
160 "SERVICE_TYPE_NAME" => array(
161 "TYPE" => "STRING",
162 "NAME" => Loc::getMessage("SALE_DLVRS_ADD_SERVICE_TYPE"),
163 "READONLY" => true,
164 "DEFAULT" => $fields['NAME']
165 ),
166 "SERVICE_TYPE" => array(
167 "TYPE" => "STRING",
168 "NAME" =>"SERVICE_TYPE",
169 "HIDDEN" => true,
170 "DEFAULT" => $this->serviceType
171 )
172 )
173 )
174 );
175
176 if(!empty($fields['CONFIG']) && is_array($fields['CONFIG']))
177 {
178 foreach($fields['CONFIG'] as $key => $params)
179 {
180 if($this->serviceType == "RUSPOST" && $this->id <= 0 && $key == 'SHIPPING_POINT')
181 {
182 continue;
183 }
184
185 $result['MAIN']['ITEMS'][$key] = $params;
186 }
187 }
188
189 $result['MAIN']['ITEMS']["DEFAULT_VALUES"] = array(
190 "TYPE" => "DELIVERY_SECTION",
191 "NAME" =>Loc::getMessage('SALE_DLVRS_ADD_MAIN_DEFAULT_VALUES'),
192 );
193 $result['MAIN']['ITEMS']["LENGTH_DEFAULT"] = array(
194 "TYPE" => "STRING",
195 "NAME" =>Loc::getMessage('SALE_DLVRS_ADD_MAIN_LENGTH_DEFAULT'),
196 "DEFAULT" => 200
197 );
198 $result['MAIN']['ITEMS']["WIDTH_DEFAULT"] = array(
199 "TYPE" => "STRING",
200 "NAME" =>Loc::getMessage('SALE_DLVRS_ADD_MAIN_WIDTH_DEFAULT'),
201 "DEFAULT" => 300
202 );
203 $result['MAIN']['ITEMS']["HEIGHT_DEFAULT"] = array(
204 "TYPE" => "STRING",
205 "NAME" =>Loc::getMessage('SALE_DLVRS_ADD_MAIN_HEIGHT_DEFAULT'),
206 "DEFAULT" => 200
207 );
208 $result['MAIN']['ITEMS']["WEIGHT_DEFAULT"] = array(
209 "TYPE" => "STRING",
210 "NAME" =>Loc::getMessage('SALE_DLVRS_ADD_MAIN_WEIGHT_DEFAULT'),
211 "DEFAULT" => 500
212 );
213
214 return $result;
215 }
216
220 public static function getSupportedServicesList()
221 {
222 static $result = null;
223
224 if($result === null)
225 {
226 $client = new RestClient();
227 $res = $client->getDeliveryList();
228
229 if($res->isSuccess())
230 {
231 $result = $res->getData();
232 }
233 else
234 {
235 $errors = array();
236 $notes = array();
237 $nothingFound = false;
238
240 foreach($res->getErrorCollection() as $error)
241 {
242 if($error->getCode() === \Bitrix\Sale\Services\Base\RestClient::ERROR_NOTHING_FOUND)
243 {
244 $nothingFound = true;
245 continue;
246 }
247
248 $message = $error->getMessage();
249
250 if($message == 'verification_needed. License check failed.')
251 $notes[$error->getCode()] = Loc::getMessage('SALE_DLVRS_ADD_LIST_LICENSE_WRONG');
252 else
253 $errors[$error->getCode()] = $message;
254 }
255
256 if(!empty($errors))
257 $result = array("ERRORS" => $errors);
258
259 if(!empty($notes))
260 $result['NOTES'] = $notes;
261
262 if(empty($errors) && empty($notes))
263 {
264 if($nothingFound === false || $res->getErrorCollection()->count() !== 1)
265 {
266 $errors[] = Loc::getMessage('SALE_DLVRS_ADD_LIST_RECEIVE_ERROR');
267 }
268 }
269 }
270 }
271
272 return $result;
273 }
274
278 protected function getServiceParams()
279 {
280 $result = array();
281 $client = new RestClient();
282 $res = $client->getDeliveryFields($this->serviceType);
283
284 if($res->isSuccess())
285 {
286 $logo = false;
287 $logoId = intval($this->getLogoFileId());
288
289 if($logoId > 0)
290 {
291 $logo = \CFile::GetByID($logoId)->Fetch();
292 }
293
294 $result = $res->getData();
295
296 if(($logoId <= 0 || !$logo) && !empty($result['LOGOTIP']['CONTENT']) && !empty($result['LOGOTIP']['NAME']))
297 {
298 $tmpDir = \CTempFile::GetDirectoryName();
299 CheckDirPath($tmpDir);
300 $filePath = $tmpDir."/".$result['LOGOTIP']['NAME'];
301
302 $res = File::putFileContents(
303 $filePath,
304 base64_decode($result['LOGOTIP']['CONTENT'])
305 );
306
307 if($res)
308 {
309 $file = \CFile::MakeFileArray($tmpDir."/".$result['LOGOTIP']['NAME']);
310 $file['MODULE_ID'] = "sale";
311 $logoId = intval(\CFile::SaveFile($file, "sale/delivery/logotip"));
312 $this->setLogoFileId($logoId);
313 }
314 }
315
316 $result['LOGOTIP'] = $logoId > 0 ? $logoId : 0;
317 }
318
319 return $result;
320 }
321
322 protected function getLogoFileId()
323 {
324 return intval(Option::get('sale', self::LOGO_FILE_ID_OPTION.'_'.$this->serviceType, ''));
325 }
326
327 protected function setLogoFileId($logoId)
328 {
329 if(intval($logoId) > 0)
330 Option::set('sale', self::LOGO_FILE_ID_OPTION.'_'.$this->serviceType, $logoId);
331 }
332
336 public static function getChildrenClassNames()
337 {
338 return array(
339 '\Sale\Handlers\Delivery\AdditionalProfile'
340 );
341 }
342
346 public function getProfilesList()
347 {
348 $result =array();
349
350 $profiles = $this->getProfilesListFull();
351
352 foreach($profiles as $profileType => $profile)
353 $result[$profileType] = $profile['NAME'];
354
355 return $result;
356 }
357
358 public function getTrackingStatuses(array $trackingNumbers = array())
359 {
360 $result = array();
361 $client = new RestClient();
362 $res = $client->getTrackingStatuses(
363 $this->serviceType,
364 AdditionalProfile::extractConfigValues($this->getConfig()),
365 $trackingNumbers
366 );
367
368 if($res->isSuccess())
369 {
370 $data = $res->getData();
371
372 if(!empty($data['STATUSES']) && is_array($data['STATUSES']))
373 $result = $data['STATUSES'];
374 }
375
376 return $result;
377 }
378
379 public function getTrackingClassTitle()
380 {
381 return !empty($this->config['MAIN']['TRACKING_TITLE']) ? $this->config['MAIN']['TRACKING_TITLE'] : '';
382 }
383
384 public function getTrackingClassDescription()
385 {
386 return !empty($this->config['MAIN']['TRACKING_DESCRIPTION']) ? $this->config['MAIN']['TRACKING_DESCRIPTION'] : '';
387 }
388
392 public function getProfilesListFull()
393 {
394 if($this->profilesListFull === null)
395 {
396 $this->profilesListFull = array();
397 $client = new RestClient();
398 $res = $client->getDeliveryProfilesList($this->serviceType);
399
400 if($res->isSuccess())
401 $this->profilesListFull = $res->getData();
402 }
403
404 return $this->profilesListFull;
405 }
406
410 public static function whetherAdminExtraServicesShow()
411 {
412 return self::$whetherAdminExtraServicesShow;
413 }
414
418 public function getServiceType()
419 {
420 return $this->serviceType;
421 }
422
427 public function getCompatibleProfiles($shipment)
428 {
429 return $this->getProfilesList();
430 }
431
435 public static function canHasProfiles()
436 {
437 return self::$canHasProfiles;
438 }
439
440 public static function onAfterUpdate($serviceId, array $fields = array())
441 {
443 $service = new self($fields);
444
445 if ($service->getServiceType() == 'RUSPOST')
446 {
447 $config = $service->getConfigValues();
448 $doInstall = isset($config['MAIN']['RELIABILITY']) && $config['MAIN']['RELIABILITY'] == 'Y';
449 self::installReliability($serviceId, $doInstall);
450 }
451 }
452
458 public static function onAfterAdd($serviceId, array $fields = array())
459 {
460 if($serviceId <= 0)
461 return false;
462
463 $result = true;
464
465 //Add profiles
466 $fields["ID"] = $serviceId;
467 $srv = new self($fields);
468 $profiles = $srv->getProfilesListFull();
469
470 if(is_array($profiles) && !empty($profiles))
471 {
472 foreach($profiles as $profileType => $pFields)
473 {
474 if(isset($pFields['DEFAULT_INSTALL_SKIP']) && $pFields['DEFAULT_INSTALL_SKIP'] == 'Y')
475 continue;
476
477 $profile = $srv->getProfileDefaultParams($profileType, $pFields);
478 $res = Manager::add($profile);
479
480 if($res->isSuccess() && !empty($pFields["RESTRICTIONS"]) && is_array($pFields["RESTRICTIONS"]))
481 {
482 $profileId = $res->getId();
483
484 foreach($pFields["RESTRICTIONS"] as $restrictionType => $params)
485 {
486 $srv->addRestriction($restrictionType, $profileId, $params);
487 }
488 }
489
490 $result = $result && $res->isSuccess();
491 }
492 }
493
494 $extraservices = $srv->getEmbeddedExtraServicesList();
495
496 if(!empty($extraservices))
497 {
498 //Add extra services
499 foreach($extraservices as $code => $esFields)
500 {
501 $esFields['DELIVERY_ID'] = $serviceId;
502 $esFields['CODE'] = $code;
503 $res = Table::add($esFields);
504 $result = $result && $res->isSuccess();
505 }
506 }
507
508 if ($srv->getServiceType() == 'RUSPOST')
509 {
510 $config = $srv->getConfigValues();
511 $doInstall = isset($config['MAIN']['RELIABILITY']) && $config['MAIN']['RELIABILITY'] == 'Y';
512 self::installReliability($serviceId, $doInstall);
513 }
514
515 return $result;
516 }
517
518 protected static function installReliability(int $serviceId, bool $doInstall)
519 {
520 if($doInstall)
521 {
522 Reliability\Service::install($serviceId);
523 }
524 else
525 {
526 Reliability\Service::unInstall($serviceId);
527 }
528 }
529
536 protected function addRestriction($type, $profileId, array $params)
537 {
538 $fields = array();
539 $className = null;
540
541 switch($type)
542 {
543 case "WEIGHT":
544 $className = \Bitrix\Sale\Delivery\Restrictions\ByWeight::class;
545
546 $p = array();
547 if(isset($params['MIN'])) $p['MIN_WEIGHT'] = $params['MIN'];
548 if(isset($params['MAX'])) $p['MAX_WEIGHT'] = $params['MAX'];
549
550 if(!empty($p))
551 {
552 $fields = array(
553 "SERVICE_ID" => $profileId,
554 "SERVICE_TYPE" => \Bitrix\Sale\Services\Base\RestrictionManager::SERVICE_TYPE_SHIPMENT,
555 "PARAMS" => $p
556 );
557 }
558
559 break;
560
561 case "DIMENSIONS":
562 $className = \Bitrix\Sale\Delivery\Restrictions\ByDimensions::class;
563
564 $p = array();
565 if(isset($params['LENGTH'])) $p['LENGTH'] = $params['LENGTH'];
566 if(isset($params['WIDTH'])) $p['WIDTH'] = $params['WIDTH'];
567 if(isset($params['HEIGHT'])) $p['HEIGHT'] = $params['HEIGHT'];
568
569 if(!empty($p))
570 {
571 $fields = array(
572 "SERVICE_ID" => $profileId,
573 "SERVICE_TYPE" => \Bitrix\Sale\Services\Base\RestrictionManager::SERVICE_TYPE_SHIPMENT,
574 "PARAMS" => $p
575 );
576 }
577
578 break;
579
580 case "MAX_SIZE":
581
582 $className = \Bitrix\Sale\Delivery\Restrictions\ByMaxSize::class;
583
584 $p = array();
585 if(isset($params['MAX_SIZE']) && intval($params['MAX_SIZE']) > 0) $p['MAX_SIZE'] = $params['MAX_SIZE'];
586
587 if(!empty($p))
588 {
589 $fields = array(
590 "SERVICE_ID" => $profileId,
591 "SERVICE_TYPE" => \Bitrix\Sale\Services\Base\RestrictionManager::SERVICE_TYPE_SHIPMENT,
592 "PARAMS" => $p
593 );
594 }
595
596 break;
597
598 case 'BY_LOCATION':
599 case 'EXCLUDE_LOCATION':
600
601 $className = ($type === 'BY_LOCATION')
602 ? \Bitrix\Sale\Delivery\Restrictions\ByLocation::class
603 : \Bitrix\Sale\Delivery\Restrictions\ExcludeLocation::class;
604
605 if (isset($params['LOCATION']))
606 {
607 $p['LOCATION'] = $params['LOCATION'];
608 }
609
610 if(!empty($p))
611 {
612 $fields = array(
613 'SERVICE_ID' => $profileId,
614 'SERVICE_TYPE' => \Bitrix\Sale\Services\Base\RestrictionManager::SERVICE_TYPE_SHIPMENT,
615 'PARAMS' => $p,
616 );
617 }
618
619 break;
620 }
621
622 if($className && !empty($fields))
623 {
624 $className::save($fields);
625 }
626 }
627
633 protected function getProfileDefaultParams($type, array $fields)
634 {
635 if(isset($fields["ACTIVE"]))
636 $active = $fields["ACTIVE"];
637 else
638 $active = $this->active ? "Y" : "N";
639
640 if(isset($fields["SORT"]))
641 $sort = $fields["SORT"];
642 else
643 $sort = $this->sort;
644
645 $result = array(
646 "CODE" => "",
647 "PARENT_ID" => $this->id,
648 "NAME" => $fields["NAME"],
649 "ACTIVE" => $active,
650 "SORT" => $sort,
651 "DESCRIPTION" => $fields["DESCRIPTION"],
652 "CLASS_NAME" => '\Sale\Handlers\Delivery\AdditionalProfile',
653 "CURRENCY" => $this->currency,
654 "CONFIG" => array(
655 "MAIN" => array(
656 "PROFILE_TYPE" => $type,
657 "NAME" => $fields["NAME"],
658 "DESCRIPTION" => $fields["DESCRIPTION"]
659 )
660 )
661 );
662
663 if(!empty($fields["MODE"]))
664 $result['CONFIG']['MAIN']["MODE"] = $fields["MODE"];
665
666 if(!empty($fields['DEFAULT']['MAIN']))
667 $result['CONFIG']['MAIN'] = array_merge($result['CONFIG']['MAIN'], $fields['DEFAULT']['MAIN']);
668
669 return $result;
670 }
671
672 public function getAdminMessage()
673 {
674 $result = array();
675 $message = '';
676
677 if($this->isLicenseWrong())
678 $message = Loc::getMessage('SALE_DLVRS_ADD_LICENSE_WRONG');
679 elseif(!Location::isInstalled() && !empty($_REQUEST['ID']))
680 $message = Loc::getMessage('SALE_DLVRS_ADD_LOC_INSTALL');
681
682 if($message <> '')
683 {
684 $result = array(
685 "DETAILS" => $message,
686 "TYPE" => "ERROR",
687 "HTML" => true
688 );
689 }
690
691 return $result;
692 }
693
694 protected function isLicenseWrong()
695 {
696 return Option::get('sale', RestClient::WRONG_LICENSE_OPTION, 'N') == 'Y';
697 }
698
699 public function execAdminAction()
700 {
701 $result = new \Bitrix\Sale\Result();
702 \Bitrix\Main\UI\Extension::load("main.core");
703 Asset::getInstance()->addJs("/bitrix/js/sale/additional_delivery.js");
704 Asset::getInstance()->addString('<link rel="stylesheet" type="text/css" href="/bitrix/css/sale/additional_delivery.css">');
705 Asset::getInstance()->addString('<script>
706 if(top.BX)
707 {
708 BX.addCustomEvent(
709 \'onSaleDeliveryRusPostShippingPointSelect\',
710 BX.Sale.Handler.Delivery.Additional.onRusPostShippingPointsSelect
711 );
712 }
713 </script>');
714 return $result;
715 }
716
717 public function getAdminAdditionalTabs()
718 {
719 self::install();
720
721 ob_start();
722 require_once(__DIR__.'/location/admin_tab.php');
723 $content = ob_get_contents();
724 ob_end_clean();
725
726 return array(
727 array(
728 "TAB" => Loc::getMessage('SALE_DLVRS_ADD_LOC_TAB'),
729 "TITLE" => Loc::getMessage('SALE_DLVRS_ADD_LOC_TAB_TITLE'),
730 "CONTENT" => $content
731 )
732 );
733 }
734
735 public static function install()
736 {
737 global $DB;
738
739 if(!file_exists($_SERVER["DOCUMENT_ROOT"].'/bitrix/css/sale/additional_delivery.css'))
740 {
742 $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/sale/handlers/delivery/additional/install/css",
743 $_SERVER["DOCUMENT_ROOT"]."/bitrix/css/sale", true, true
744 );
746 $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/sale/handlers/delivery/additional/install/js",
747 $_SERVER["DOCUMENT_ROOT"]."/bitrix/js/sale", true, true
748 );
750 $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/sale/handlers/delivery/additional/install/tools",
751 $_SERVER["DOCUMENT_ROOT"]."/bitrix/tools/sale", true, true
752 );
753 }
754
755 $con = \Bitrix\Main\Application::getConnection();
756
757 if(!$con->isTableExists('b_sale_hdale'))
758 {
759 $DB->RunSQLBatch($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/sale/handlers/delivery/additional/install/db/".$con->getType()."/install.sql");
760 }
761
762 $eventManager = \Bitrix\Main\EventManager::getInstance();
763 $eventManager->registerEventHandler('sale', 'onSaleDeliveryExtraServicesClassNamesBuildList' , 'sale', '\Sale\Handlers\Delivery\AdditionalHandler', 'onSaleDeliveryExtraServicesClassNamesBuildList');
764 $eventManager->registerEventHandler('sale', 'onSaleDeliveryTrackingClassNamesBuildList', 'sale', '\Sale\Handlers\Delivery\AdditionalHandler', 'onSaleDeliveryTrackingClassNamesBuildList');
765
766 return parent::install();
767 }
768
769 public static function unInstall()
770 {
771 global $DB;
772
773 if(file_exists($_SERVER["DOCUMENT_ROOT"].'/bitrix/css/sale/additional_delivery.css'))
774 {
776 $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/sale/handlers/delivery/additional/install/css",
777 $_SERVER["DOCUMENT_ROOT"]."/bitrix/css/sale"
778 );
780 $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/sale/handlers/delivery/additional/install/js",
781 $_SERVER["DOCUMENT_ROOT"]."/bitrix/js/sale"
782 );
784 $_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/sale/handlers/delivery/additional/install/tools",
785 $_SERVER["DOCUMENT_ROOT"]."/bitrix/tools/sale"
786 );
787 }
788
789 $con = \Bitrix\Main\Application::getConnection();
790
791 if(!$con->isTableExists('b_sale_hdale'))
792 {
793 $DB->RunSQLBatch($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/sale/handlers/delivery/additional/install/db/".$con->getType()."/uninstall.sql");
794 }
795
796 $eventManager = \Bitrix\Main\EventManager::getInstance();
797 $eventManager->unRegisterEventHandler('sale', 'onSaleDeliveryExtraServicesClassNamesBuildList' , 'sale', '\Sale\Handlers\Delivery\AdditionalHandler', 'onSaleDeliveryExtraServicesClassNamesBuildList');
798 $eventManager->unRegisterEventHandler('sale', 'onSaleDeliveryTrackingClassNamesBuildList' , 'sale', '\Sale\Handlers\Delivery\AdditionalHandler', 'onSaleDeliveryTrackingClassNamesBuildList');
799
800 return parent::install();
801 }
802
803 public static function onSaleDeliveryTrackingClassNamesBuildList()
804 {
805 return new \Bitrix\Main\EventResult(
806 \Bitrix\Main\EventResult::SUCCESS,
807 array(
808 '\Sale\Handlers\Delivery\AdditionalTracking' => '/bitrix/modules/sale/handlers/delivery/additional/tracking.php'
809 ),
810 'sale'
811 );
812 }
813
814 public function getEmbeddedExtraServicesList()
815 {
816 if($this->extraServicesList === null)
817 {
818 $this->extraServicesList = array();
819 $client = new RestClient();
820 $res = $client->getDeliveryExtraServices($this->serviceType);
821
822 if($res->isSuccess())
823 $this->extraServicesList = $res->getData();
824 }
825
826 return $this->extraServicesList;
827 }
828
829 public static function onSaleDeliveryExtraServicesClassNamesBuildList()
830 {
831 return new \Bitrix\Main\EventResult(
832 \Bitrix\Main\EventResult::SUCCESS,
833 array(
834 '\Sale\Handlers\Delivery\Additional\ExtraServices\Insurance' => '/bitrix/modules/sale/handlers/delivery/additional/extra_services/insurance.php',
835 '\Sale\Handlers\Delivery\Additional\ExtraServices\Lift' => '/bitrix/modules/sale/handlers/delivery/additional/extra_services/lift.php'
836 ),
837 'sale'
838 );
839 }
840
841 public function isCompatible(Shipment $shipment)
842 {
843 $client = new RestClient();
844 return $client->isServerAlive();
845 }
846
847 public function getTrackingUrlTempl()
848 {
849 $config = \Sale\Handlers\Delivery\AdditionalProfile::extractConfigValues($this->getConfig());
850 return !empty($config["MAIN"]["TRACKING_URL_TEMPL"]) ? $config["MAIN"]["TRACKING_URL_TEMPL"] : '';
851 }
852
858 public static function getShipmentParams(Shipment $shipment, $serviceType)
859 {
861 $shipmentCollection = $shipment->getCollection();
863 $order = $shipmentCollection->getOrder();
864 $props = $order->getPropertyCollection();
865 $loc = $props->getDeliveryLocation();
866 $locToInternalCode = !!$loc ? $loc->getValue() : "";
867 $locFromRequest = array();
868 $locToRequest = array();
869
870 if(!empty($locToInternalCode))
871 $locToRequest = self::getLocationForRequest($locToInternalCode);
872
873 $shopLocation = \CSaleHelper::getShopLocation();
874
875 if(!empty($shopLocation['CODE']))
876 $locFromRequest = self::getLocationForRequest($shopLocation['CODE']);
877
878 $result = array(
879 "ITEMS" => array(),
880 "LOCATION_FROM" => $locFromRequest['EXTERNAL_ID'] ?? null,
881 "LOCATION_FROM_NAME" => $locFromRequest['NAME'] ?? null,
882 "LOCATION_FROM_CODE" => (!empty($shopLocation['CODE'])) ? $shopLocation['CODE'] : '',
883 "LOCATION_TO" => $locToRequest['EXTERNAL_ID'] ?? null,
884 "LOCATION_TO_NAME" => $locToRequest['NAME'] ?? null,
885 "LOCATION_TO_CODE" => $locToInternalCode,
886 "LOCATION_TO_TYPES" => self::getLocationChainByTypes($locToInternalCode, LANGUAGE_ID)
887 );
888
889 if($address = $props->getAddress())
890 $result["ADDRESS"] = $address->getValue();
891
892 if($phone = $props->getPhone())
893 $result["PHONE"] = $phone->getValue();
894
895 if($payerName = $props->getPayerName())
896 $result["PAYER_NAME"] = $payerName->getValue();
897
898 if($serviceType == "RUSPOST" )
899 {
900 $zipFrom = \CSaleHelper::getShopLocationZIP();
901
902 if($zipFrom <> '')
903 {
904 $result["ZIP_FROM"] = $zipFrom;
905 }
906 elseif(!empty($shopLocation['CODE']))
907 {
908 $extLoc = LocationHelper::getZipByLocation($shopLocation['CODE'], array('limit' => 1))->fetch();
909
910 if(!empty($extLoc['XML_ID']))
911 $result["ZIP_FROM"] = $extLoc['XML_ID'];
912 }
913
914 $zipTo = $props->getDeliveryLocationZip();
915 $zipTo = !!$zipTo ? $zipTo->getValue() : "";
916
917 if($zipTo <> '')
918 {
919 $result["ZIP_TO"] = $zipTo;
920 }
921 elseif(!empty($locToInternalCode))
922 {
923 $extLoc = LocationHelper::getZipByLocation($locToInternalCode, array('limit' => 1))->fetch();
924
925 if(!empty($extLoc['XML_ID']))
926 $result["ZIP_TO"] = $extLoc['XML_ID'];
927 }
928 }
929
930 $price = 0;
931 $weight = 0;
932
934 foreach($shipment->getShipmentItemCollection()->getShippableItems() as $shipmentItem)
935 {
936 $basketItem = $shipmentItem->getBasketItem();
937
938 if(!$basketItem)
939 continue;
940
941 //$itemFieldValues = $basketItem->getFieldValues();
942 $itemFieldValues = array(
943 "PRICE" => $basketItem->getPrice(),
944 "WEIGHT" => $basketItem->getWeight(),
945 "CURRENCY" => $basketItem->getCurrency(),
946 "QUANTITY" => $shipmentItem->getQuantity(),
947 "DIMENSIONS" => $basketItem->getField("DIMENSIONS")
948 );
949
950 $price += $itemFieldValues["PRICE"] * $itemFieldValues["QUANTITY"];
951
952 if(!empty($itemFieldValues["DIMENSIONS"]) && is_string($itemFieldValues["DIMENSIONS"]))
953 $itemFieldValues["DIMENSIONS"] = unserialize($itemFieldValues["DIMENSIONS"], ['allowed_classes' => false]);
954
955 $result["ITEMS"][] = $itemFieldValues;
956 }
957
958 //Extra services
959 $esList = \Bitrix\Sale\Delivery\ExtraServices\Manager::getExtraServicesList($shipment->getDeliveryId(), false);
960
961 if(!empty($esList))
962 {
963 $result['EXTRA_SERVICES'] = array();
964
965 foreach($shipment->getExtraServices() as $esId => $esVal)
966 {
967 if(empty($esList[$esId]['CODE']))
968 continue;
969
970 if($esList[$esId]['CLASS_NAME'] == '\Bitrix\Sale\Delivery\ExtraServices\Checkbox' && $esVal != 'Y')
971 continue;
972
973 $result['EXTRA_SERVICES'][$esList[$esId]['CODE']] = $esVal;
974 }
975 }
976
977 $delivery= Manager::getObjectById($shipment->getDeliveryId());
978 $result['DELIVERY_SERVICE_CONFIG'] = $delivery ? $delivery->getConfigValues() : [];
979 $result['WEIGHT'] = $shipment->getWeight();
980 $result['PRICE'] = $price;
981 $result['SHIPMENT_ID'] = $shipment->getId();
982 $result['PRICE_DELIVERY'] = $shipment->getField('PRICE_DELIVERY');
983
984 return $result;
985 }
986
992 protected static function getLocationForRequest($locationCode)
993 {
994 if($locationCode == '')
995 return array();
996
997 static $result = array();
998
999 if(!isset($result[$locationCode]))
1000 {
1001 $externalId = Location::getExternalId($locationCode);
1002 $name = '';
1003
1004 if($externalId <> '')
1005 {
1006 $dbRes = ExternalTable::getList(array(
1007 'filter' => array(
1008 'XML_ID' => $externalId,
1009 'SERVICE_ID' => Location::getExternalServiceId(),
1010 'LOCATION.NAME.LANGUAGE_ID' => 'ru'
1011 ),
1012 'select' => array('NAME' => 'LOCATION.NAME.NAME')
1013 ));
1014
1015 if($rec = $dbRes->fetch())
1016 $name = $rec['NAME'];
1017 }
1018
1019 $result[$locationCode] = array(
1020 'EXTERNAL_ID' => $externalId,
1021 'NAME' => $name
1022 );
1023 }
1024
1025 return $result[$locationCode];
1026 }
1027
1033 protected static function getLocationChainByTypes($locationCode, $lang = LANGUAGE_ID)
1034 {
1035 if ($locationCode == '')
1036 {
1037 return [];
1038 }
1039
1040 $res = LocationTable::getList([
1041 'filter' => [
1042 '=CODE' => $locationCode,
1043 ],
1044 'select' => [
1045 'ID',
1046 'CODE',
1047 'LEFT_MARGIN',
1048 'RIGHT_MARGIN',
1049 ]
1050 ]);
1051
1052 if (!$loc = $res->fetch())
1053 {
1054 return [];
1055 }
1056
1057 $result = [];
1058
1059 $res = LocationTable::getList(array(
1060 'filter' => [
1061 '<=LEFT_MARGIN' => $loc['LEFT_MARGIN'],
1062 '>=RIGHT_MARGIN' => $loc['RIGHT_MARGIN'],
1063 'NAME.LANGUAGE_ID' => $lang,
1064 'TYPE.NAME.LANGUAGE_ID' => $lang,
1065 ],
1066 'select' => [
1067 'ID',
1068 'CODE',
1069 'LOCATION_NAME' => 'NAME.NAME',
1070 'TYPE_NAME' => 'TYPE.NAME.NAME',
1071 'TYPE_CODE' => 'TYPE.CODE',
1072 ]
1073 ));
1074
1075 while ($locParent = $res->fetch())
1076 {
1077 if (!isset($result[$locParent['TYPE_CODE']]))
1078 {
1079 $result[$locParent['TYPE_CODE']] = [];
1080 }
1081
1082 $result[$locParent['TYPE_CODE']][] = $locParent['LOCATION_NAME'];
1083 }
1084
1085 return $result;
1086 }
1087
1088 public function prepareFieldsForSaving(array $fields)
1089 {
1090 if(isset($fields['CONFIG']['MAIN']['SHIPPING_POINT']['NAME']))
1091 $fields['CONFIG']['MAIN']['SHIPPING_POINT']['NAME'] = htmlspecialcharsback($fields['CONFIG']['MAIN']['SHIPPING_POINT']['NAME']);
1092
1093 if(isset($fields['CONFIG']['MAIN']['SHIPPING_POINT']['VALUE']))
1094 $fields['CONFIG']['MAIN']['SHIPPING_POINT']['VALUE'] = htmlspecialcharsback($fields['CONFIG']['MAIN']['SHIPPING_POINT']['VALUE']);
1095
1096 if(isset($fields['CONFIG']['MAIN']['SHIPPING_POINT']['ADDITIONAL']))
1097 $fields['CONFIG']['MAIN']['SHIPPING_POINT']['ADDITIONAL'] = htmlspecialcharsback($fields['CONFIG']['MAIN']['SHIPPING_POINT']['ADDITIONAL']);
1098
1099 return parent::prepareFieldsForSaving($fields);
1100 }
1101
1103 public static function isHandlerCompatible()
1104 {
1105 if(!parent::isHandlerCompatible())
1106 {
1107 return false;
1108 }
1109
1110 return in_array(
1111 \Bitrix\Sale\Delivery\Helper::getPortalZone(),
1112 ['', 'ru', 'kz', 'by'],
1113 true
1114 );
1115 }
1116}
$con
Определения admin_tab.php:7
$type
Определения options.php:106
$content
Определения commerceml.php:144
$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
$res
Определения filter_act.php:7
$_REQUEST["admin_mnu_menu_id"]
Определения get_menu.php:8
$result
Определения get_property_values.php:14
$p
Определения group_list_element_edit.php:23
$errors
Определения iblock_catalog_edit.php:74
$_SERVER["DOCUMENT_ROOT"]
Определения cron_frame.php:9
global $DB
Определения cron_frame.php:29
if(!is_null($config))($config as $configItem)(! $configItem->isVisible()) $code
Определения options.php:195
if(!defined('SITE_ID')) $lang
Определения include.php:91
CheckDirPath($path)
Определения tools.php:2707
htmlspecialcharsback($str)
Определения tools.php:2693
DeleteDirFiles($frDir, $toDir, $arExept=[])
Определения tools.php:2874
CopyDirFiles($path_from, $path_to, $ReWrite=true, $Recursive=false, $bDeleteAfterCopy=false, $strExclude="")
Определения tools.php:2732
$name
Определения menu_edit.php:35
$order
Определения payment.php:8
$service
Определения payment.php:18
$message
Определения payment.php:8
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
$config
Определения quickway.php:69
if(empty($signedUserToken)) $key
Определения quickway.php:257
$props
Определения template.php:269
if($inWords) echo htmlspecialcharsbx(Number2Word_Rus(roundEx($totalVatSum $params['CURRENCY']
Определения template.php:799
$eventManager
Определения include.php:412
$error
Определения subscription_card_product.php:20
$dbRes
Определения yandex_detail.php:168
$fields
Определения yandex_run.php:501