Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
automatic.php
1<?php
2
4
14use Bitrix\Main\Entity\EntityError;
20
21Loc::loadMessages(__FILE__);
22
28class Automatic extends Base
29{
31 protected $handlerCode = 'BITRIX_AUTOMATIC';
32
33 protected $sid = "";
34 protected $oldConfig = array();
35 protected $handlerInitParams = array();
36
37 protected static $canHasProfiles = true;
38
39 public function __construct(array $initParams)
40 {
41 parent::__construct($initParams);
42
43 if(isset($this->config["MAIN"]["SID"]) && $this->config["MAIN"]["SID"] <> '')
44 {
45 $initedHandlers = self::getRegisteredHandlers("SID");
46
47 if(!isset($initedHandlers[$this->config["MAIN"]["SID"]]))
48 {
49 throw new SystemException("Can't initialize service with code\"".$this->config["MAIN"]["SID"]."\"");
50 }
51
52 $this->sid = $this->code = $this->config["MAIN"]["SID"];
53 $this->handlerInitParams = $this->getHandlerInitParams($this->sid);
54
55 if(!empty($this->handlerInitParams["TRACKING_CLASS_NAME"]))
56 $this->setTrackingClass($this->handlerInitParams["TRACKING_CLASS_NAME"]);
57
58 if($this->handlerInitParams == false)
59 throw new SystemException("Can't get delivery services init params. Delivery id: ".$this->id.", sid: ".$this->sid);
60
61 if($this->currency == '' && !empty($this->handlerInitParams["BASE_CURRENCY"]))
62 $this->currency = $this->handlerInitParams["BASE_CURRENCY"];
63 }
64
65 $initParams = self::convertNewServiceToOld($initParams, $this->sid);
66
67 if(isset($initParams["CONFIG"]))
68 $this->oldConfig = $initParams["CONFIG"];
69 }
70
74 public function getHandlerCode(): string
75 {
76 return 'BITRIX_' . (string)$this->sid;
77 }
78
79 public static function getClassTitle()
80 {
81 return Loc::getMessage("SALE_DLVR_HANDL_AUT_NAME");
82 }
83
84 public static function getClassDescription()
85 {
86 return Loc::getMessage("SALE_DLVR_HANDL_AUT_DESCRIPTION");
87 }
88
89 protected function getConfigStructure()
90 {
91 static $handlers = null;
92 static $jsData = array();
93
94 $initedHandlers = self::getRegisteredHandlers("SID");
95
96 sortByColumn($initedHandlers, array(mb_strtoupper("NAME") => SORT_ASC));
97
98 if($handlers === null)
99 {
100 $handlers = array("" => "");
101
102 foreach($initedHandlers as $handler)
103 {
104 if (isset($handler["DEPRECATED"]) && $handler["DEPRECATED"] = "Y")
105 {
106 continue;
107 }
108
109 if (!self::isAutomaticHandlerCompatible($handler))
110 {
111 continue;
112 }
113
114 $handlers[$handler["SID"]] = $handler["NAME"]." [".$handler["SID"]."]";
115 $jsData[$handler["SID"]] = array(
116 htmlspecialcharsbx($handler["NAME"]),
117 htmlspecialcharsbx($handler["DESCRIPTION"]),
118 htmlspecialcharsbx($handler["DESCRIPTION_INNER"])
119 );
120 }
121 }
122
123 if (($this->handlerInitParams["SID"] ?? '') == '' || $this->id <=0)
124 {
125 $result = array(
126 "MAIN" => array(
127 "TITLE" => Loc::getMessage("SALE_DLVR_HANDL_AUT_HANDLER_SETTINGS"),
128 "DESCRIPTION" => Loc::getMessage("SALE_DLVR_HANDL_AUT_HANDLER_SETTINGS_DSCR"),
129 "ITEMS" => array (
130 "SID" => array(
131 "TYPE" => "ENUM",
132 "NAME" => Loc::getMessage("SALE_DLVR_HANDL_AUT_HANDLER_CHOOSE"),
133 "OPTIONS" => $handlers,
134 "ONCHANGE" => "var data=".\CUtil::PhpToJSObject($jsData)."; BX.onCustomEvent('onDeliveryServiceNameChange',[{name: data[this.value][0], description: data[this.value][1]}]); BX('adm-sale-delivery-auto-description_inner_view').innerHTML=data[this.value][2]; //this.form.submit();"
135 ),
136 "DESCRIPTION_INNER" => array(
137 "TYPE" => "DELIVERY_READ_ONLY",
138 "NAME" => Loc::getMessage("SALE_DLVR_HANDL_AUT_DESCRIPTION_INNER"),
139 "ID" => "adm-sale-delivery-auto-description_inner",
140 "DEFAULT" => ""
141 ),
142 )
143 )
144 );
145 }
146 else
147 {
148 $handler = $this->handlerInitParams["SID"];
149
150 $result = array(
151 "MAIN" => array(
152 "TITLE" => Loc::getMessage("SALE_DLVR_HANDL_AUT_HANDLER_SETTINGS"),
153 "DESCRIPTION" => Loc::getMessage("SALE_DLVR_HANDL_AUT_HANDLER_SETTINGS_DSCR"),
154 "ITEMS" => array (
155 "SID" => array(
156 "TYPE" => "DELIVERY_READ_ONLY",
157 "NAME" => Loc::getMessage("SALE_DLVR_HANDL_AUT_HANDLER_CHOOSE"),
158 "VALUE" => $handler,
159 "VALUE_VIEW" => $handlers[$handler]
160 ),
161 "DESCRIPTION_INNER" => array(
162 "TYPE" => "DELIVERY_READ_ONLY",
163 "NAME" => Loc::getMessage("SALE_DLVR_HANDL_AUT_DESCRIPTION_INNER"),
164 "VALUE" => $this->handlerInitParams["DESCRIPTION_INNER"]
165 )
166 )
167 )
168 );
169 }
170
171 $serviceCurrency = $this->currency;
172
173 if(\Bitrix\Main\Loader::includeModule('currency'))
174 {
175 $currencyList = CurrencyManager::getCurrencyList();
176
177 if (isset($currencyList[$this->currency]))
178 $serviceCurrency = $currencyList[$this->currency];
179
180 unset($currencyList);
181 }
182
183 $marginTypes = array(
184 "%" => "%",
185 "CURRENCY" => $serviceCurrency
186 );
187
188 $result["MAIN"]["ITEMS"]["MARGIN_VALUE"] = array(
189 "TYPE" => "STRING",
190 "NAME" => Loc::getMessage("SALE_DLVR_HANDL_AUT_MARGIN_VALUE"),
191 "DEFAULT" => 0
192 );
193
194 $result["MAIN"]["ITEMS"]["MARGIN_TYPE"] = array(
195 "TYPE" => "ENUM",
196 "NAME" => Loc::getMessage("SALE_DLVR_HANDL_AUT_MARGIN_TYPE"),
197 "DEFAULT" => "%",
198 "OPTIONS" => $marginTypes
199 );
200
201 if($this->sid <> '')
202 {
203 $configProfileIds = array_keys($this->handlerInitParams["PROFILES"]);
204 }
205 else
206 {
207 $configProfileIds = array();
208 }
209
210 if(isset($this->oldConfig["CONFIG_GROUPS"]))
211 {
212 $groupProfileIds = array_keys($this->oldConfig["CONFIG_GROUPS"]);
213 $intersect = array_intersect($groupProfileIds, $configProfileIds);
214
215 foreach($intersect as $pid)
216 unset($this->oldConfig["CONFIG_GROUPS"][$pid]);
217 }
218
219 $oldConfig = $this->convertOldConfigToNew($this->oldConfig);
220
221 if(!empty($oldConfig))
222 {
223 if(isset($oldConfig["CONFIG_GROUPS"]["MAIN"]))
224 {
225 $oldConfig["CONFIG_GROUPS"]["MAIN_OLD"] = $oldConfig["CONFIG_GROUPS"]["MAIN"];
226 unset($oldConfig["CONFIG_GROUPS"]["MAIN"]);
227 }
228
229 $result = array_merge($result, $oldConfig);
230 }
231
232 return $result;
233 }
234
235 public function prepareFieldsForSaving(array $fields)
236 {
237 $fields = parent::prepareFieldsForSaving($fields);
238
239 if(!isset($fields["CONFIG"]))
240 return $fields;
241
242 if(!isset($fields["CONFIG"]["MAIN"]["SID"]) || $fields["CONFIG"]["MAIN"]["SID"] == '')
243 throw new SystemException(Loc::getMessage("SALE_DLVR_HANDL_AUT_ERROR_HANDLER"));
244
245 if($this->sid == '')
246 return $fields;
247
248 $fields["CODE"] = $this->sid;
249
250 $configMain = $fields["CONFIG"]["MAIN"];
251
252 if (isset($this->handlerInitParams["DBSETSETTINGS"]) && is_callable($this->handlerInitParams["DBSETSETTINGS"]))
253 {
254 $oldSettings = $fields["CONFIG"];
255 unset($oldSettings["MAIN"]);
256
257 $oldSettings = self::convertNewSettingsToOld($oldSettings);
258
259 if (!$strOldSettings = call_user_func($this->handlerInitParams["DBSETSETTINGS"], $oldSettings))
260 throw new SystemException("Can't save delivery services's old settings");
261 }
262 else
263 {
264 $strOldSettings = "";
265 }
266
267 $strOldSettings = serialize($strOldSettings);
268 $fields["CONFIG"] = array(
269 "MAIN" => $configMain
270 );
271
272 $fields["CONFIG"]["MAIN"]["OLD_SETTINGS"] = $strOldSettings;
273
274 if(isset($this->handlerInitParams["CURRENCY"]) && $this->handlerInitParams["CURRENCY"] <> '')
275 $fields["CURRENCY"] = $this->handlerInitParams["CURRENCY"];
276
277 return $fields;
278 }
279
280 public static function convertNewSettingsToOld(array $newSettings = array())
281 {
282 $result = array();
283
284 foreach($newSettings as $key => $value)
285 {
286 if(is_array($value))
287 $result = array_merge($result, self::convertNewSettingsToOld($value));
288 else
289 $result[$key] = $value;
290 }
291
292 return $result;
293 }
294
295 public static function convertOldConfigToNew($oldConfig)
296 {
297 if(!isset($oldConfig["CONFIG_GROUPS"]) || !is_array($oldConfig["CONFIG_GROUPS"]) || !isset($oldConfig["CONFIG"]) || !is_array($oldConfig["CONFIG"]))
298 return array();
299
300 $result = array();
301
302
303 Input\Manager::getTypes();
304 $mc = new MultiControlString();
305
306 foreach($oldConfig["CONFIG_GROUPS"] as $groupId => $groupName)
307 {
308 $handlerConfig = array(
309 "TITLE" => $groupName,
310 "DESCRIPTION" => $groupName,
311 "ITEMS" => array()
312 );
313
314 foreach($oldConfig["CONFIG"] as $key => $param)
315 {
316 if($param["GROUP"] == $groupId)
317 {
318 $newParam = self::convertOldConfigParamToNew($param);
319
320 if(isset($param["MCS_ID"]))
321 {
322 if($newParam["TYPE"] == 'DELIVERY_MULTI_CONTROL_STRING')
323 {
324 if(!$mc->isClean())
325 {
326 $handlerConfig["ITEMS"][$mc->getKey()] = $mc->getParams();
327 $mc->clean();
328 }
329
330 $mc->setParams($key, $newParam);
331 }
332 elseif(!$mc->isClean())
333 {
334 $mc->addItem($key, $newParam);
335 }
336 else
337 {
338 $handlerConfig["ITEMS"][$key] = $newParam;
339 }
340 }
341 elseif(!$mc->isClean())
342 {
343 $handlerConfig["ITEMS"][$mc->getKey()] = $mc->getParams();
344 $mc->clean();
345 $handlerConfig["ITEMS"][$key] = $newParam;
346 }
347 else
348 {
349 $handlerConfig["ITEMS"][$key] = $newParam;
350 }
351 }
352 }
353
354 if(!$mc->isClean())
355 {
356 $handlerConfig["ITEMS"][$mc->getKey()] = $mc->getParams();
357 $mc->clean();
358 }
359
360 $result[$groupId] = $handlerConfig;
361 }
362
363 return $result;
364 }
365
366 protected static function convertOldConfigParamToNew(array $oldParam)
367 {
368 $result = array();
369
370 if(isset($oldParam["TYPE"]))
371 {
372 switch($oldParam["TYPE"])
373 {
374 case 'STRING':
375 case 'TEXT':
376 $result["TYPE"] = 'STRING';
377 break;
378
379 case 'DROPDOWN':
380 $result["TYPE"] = 'ENUM';
381 break;
382
383 case 'RADIO':
384 $result["TYPE"] = 'ENUM';
385 $result["MULTIELEMENT"] = 'Y';
386 break;
387
388 case 'CHECKBOX':
389 $result["TYPE"] = 'Y/N';
390 break;
391
392 case 'SECTION':
393 $result["TYPE"] = 'DELIVERY_SECTION';
394 break;
395
396 case 'MULTI_CONTROL_STRING':
397 $result["TYPE"] = 'DELIVERY_MULTI_CONTROL_STRING';
398 break;
399
400 default:
401 $result["TYPE"] = 'DELIVERY_READ_ONLY';
402 break;
403 }
404 }
405 else
406 {
407 $result["TYPE"] = 'STRING';
408 }
409
410 if(isset($oldParam["TITLE"]))
411 $result["NAME"] = $oldParam["TITLE"];
412
413 if(isset($oldParam["DEFAULT"]))
414 $result["DEFAULT"] = $oldParam["DEFAULT"];
415
416 if(isset($oldParam["VALUE"]))
417 $result["VALUE"] = $oldParam["VALUE"];
418
419 if(isset($oldParam["VALUES"]))
420 $result["OPTIONS"] = $oldParam["VALUES"];
421
422 return $result;
423 }
424
425 protected static function convertNewOrderToOld(\Bitrix\Sale\Shipment $shipment)
426 {
427 return \CSaleDelivery::convertOrderNewToOld($shipment);
428 }
429
430 public static function getHandlerInitParams($sid)
431 {
432 if($sid == '')
433 return false;
434
435 $handlers = self::getRegisteredHandlers("SID");
436
437 return isset($handlers[$sid]) ? $handlers[$sid] : false;
438 }
439
440 public static function initHandlers()
441 {
442 static $isHandlerInited = false;
443
444 if($isHandlerInited)
445 return true;
446
447 $arPathList = array( // list of valid services include files paths (security)
448 \Bitrix\Main\Config\Option::get('sale', 'delivery_handles_custom_path', BX_PERSONAL_ROOT.'/php_interface/include/sale_delivery/'),
449 "/bitrix/modules/sale/delivery/",
450 );
451
452 $arLoadedHandlers = array();
453
454 foreach ($arPathList as $basePath)
455 {
456 if (file_exists($_SERVER["DOCUMENT_ROOT"].$basePath) && is_dir($_SERVER["DOCUMENT_ROOT"].$basePath))
457 {
458 $handle = @opendir($_SERVER["DOCUMENT_ROOT"].$basePath);
459 while(($filename = readdir($handle)) !== false)
460 {
461 if($filename == "." || $filename == ".." || in_array($filename, $arLoadedHandlers))
462 continue;
463
464 if (!is_dir($_SERVER["DOCUMENT_ROOT"].$basePath."/".$filename) && mb_substr($filename, 0, 9) == "delivery_")
465 {
466 if(\Bitrix\Main\IO\Path::getExtension($filename) == 'php')
467 {
468 $arLoadedHandlers[] = $filename;
469 require_once($_SERVER["DOCUMENT_ROOT"].$basePath."/".$filename);
470 }
471 }
472 }
473 @closedir($handle);
474 }
475 }
476
477 $isHandlerInited = true;
478 return true;
479 }
480
481 public static function getRegisteredHandlers($indexBy = "")
482 {
483 static $arHandlersList = array();
484
485 if(isset($arHandlersList[$indexBy]) && is_array($arHandlersList[$indexBy]))
486 return $arHandlersList[$indexBy];
487
489
490 $arHandlersList[$indexBy] = array();
491
492 foreach(GetModuleEvents("sale", "onSaleDeliveryHandlersBuildList", true) as $arHandler)
493 {
494 $initParams = ExecuteModuleEventEx($arHandler);
495
496
497 if($indexBy <> '' && isset($initParams[$indexBy]))
498 $arHandlersList[$indexBy][$initParams[$indexBy]] = $initParams;
499 else
500 $arHandlersList[$indexBy][] = $initParams;
501 }
502
503 return $arHandlersList[$indexBy];
504 }
505
506 public static function convertNewServiceToOld($service, $sid = false)
507 {
508 if(!$sid && !isset($service["CONFIG"]["MAIN"]["SID"]))
509 return array();
510
512 $handlers = self::getRegisteredHandlers("SID");
513
514 if($sid !== false)
515 $service["SID"] = $sid;
516 else
517 $service["SID"] = $service["CONFIG"]["MAIN"]["SID"];
518
519 $handlerExists = isset($handlers[$service["SID"]]) && is_array($handlers[$service["SID"]]);
520
521 $service["TAX_RATE"] = $service["CONFIG"]["MAIN"]["MARGIN_VALUE"]; //todo: %, CURRENCY
522 $service["INSTALLED"] = 'Y';
523
524 $service["BASE_CURRENCY"] = $service["CURRENCY"];
525 $service["SETTINGS"] = $service["CONFIG"]["MAIN"]["OLD_SETTINGS"] ?? '';
526 $service["HANDLER"] = '';
527 if ($handlerExists)
528 {
529 $service["HANDLER"] = $handlers[$service["SID"]]["HANDLER"] ?? '';
530 }
531
532 $service['LOGOTIP'] = (int)($service['LOGOTIP'] ?? 0);
533 if ($service["LOGOTIP"] > 0)
534 {
535 $service["LOGOTIP"] = \CFile::getFileArray($service["LOGOTIP"]);
536 }
537
538 $siteId = false;
539
540 $serviceId = (int)($service['ID'] ?? 0);
541 if ($serviceId)
542 {
543 $restrictions = \Bitrix\Sale\Delivery\Restrictions\Manager::getRestrictionsList($serviceId);
544
545 foreach($restrictions as $restriction)
546 {
547 if($restriction["CLASS_NAME"] == '\Bitrix\Sale\Delivery\Restrictions\BySite' && !empty($restriction["PARAMS"]["SITE_ID"]))
548 {
549 if(is_array($restriction["PARAMS"]["SITE_ID"]))
550 {
551 reset($restriction["PARAMS"]["SITE_ID"]);
552 $siteId = current($restriction["PARAMS"]["SITE_ID"]);
553 }
554 else
555 {
556 $siteId = $restriction["PARAMS"]["SITE_ID"];
557 }
558
559 break;
560 }
561 }
562 }
563
564 if(!$siteId)
565 $siteId = Helper::getDefaultSiteId();
566
567 $service['CONFIG'] = [];
568 if ($handlerExists)
569 {
570 $service["CONFIG"] = self::createConfig($handlers[$service["SID"]], $service["SETTINGS"], $siteId);
571 }
572 $service["SETTINGS"] = unserialize($service["SETTINGS"], ['allowed_classes' => false]);
573 $service["PROFILES"] = array();
574
575 if ($serviceId > 0)
576 {
577 foreach(Manager::getByParentId($serviceId) as $profile)
578 {
579 $profileId = $profile["CONFIG"]["MAIN"]["PROFILE_ID"];
580 $profileParams = array(
581 "TITLE" => $profile["NAME"],
582 "DESCRIPTION" => $profile["DESCRIPTION"],
583 "TAX_RATE" => $service["CONFIG"]["MAIN"]["MARGIN_VALUE"] ?? '',
584 "ACTIVE" => $profile["ACTIVE"]
585 );
586
587 $restrictions = Restrictions\Manager::getRestrictionsList($profile["ID"]);
588
589 foreach($restrictions as $restriction)
590 {
591 switch($restriction["CLASS_NAME"])
592 {
593 case '\Bitrix\Sale\Delivery\Restrictions\ByWeight':
594 $profileParams["RESTRICTIONS_WEIGHT"] = array($restriction["PARAMS"]["MIN_WEIGHT"], $restriction["PARAMS"]["MAX_WEIGHT"]);
595 break;
596
597 case '\Bitrix\Sale\Delivery\Restrictions\ByPrice':
598 $profileParams["RESTRICTIONS_SUM"] = array($restriction["PARAMS"]["MIN_PRICE"], $restriction["PARAMS"]["MAX_PRICE"]);
599 break;
600
601 case '\Bitrix\Sale\Delivery\Restrictions\ByDimensions':
602 $profileParams["RESTRICTIONS_DIMENSIONS"] = array(
603 $restriction["PARAMS"]["LENGTH"],
604 $restriction["PARAMS"]["WIDTH"],
605 $restriction["PARAMS"]["HEIGHT"]
606 );
607
608 $profileParams["RESTRICTIONS_MAX_SIZE"] = $restriction["PARAMS"]["MAX_DIMENSION"];
609 $profileParams["RESTRICTIONS_DIMENSIONS_SUM"] = $restriction["PARAMS"]["MAX_DIMENSIONS_SUM"];
610 break;
611
612 default:
613 break;
614 }
615
616 }
617
618 $service["PROFILES"][$profileId] = $profileParams;
619 }
620 }
621
622 unset($service["CODE"]);
623
624 if ($handlerExists)
625 {
626 $result = array_merge($handlers[$service["SID"]], $service);
627 }
628 else
629 {
630 $result = $service;
631 }
632
633 return $result;
634 }
635
636 public function getOldDbSettings($settings)
637 {
638 if($settings == '')
639 return array();
640
641 if(!is_callable($this->handlerInitParams["DBGETSETTINGS"]))
642 return $settings;
643
644 return call_user_func($this->handlerInitParams["DBGETSETTINGS"], $settings);
645 }
646
647 public static function createConfig($initHandlerParams, $settings, $siteId = false)
648 {
649 static $result = array();
650 $hitCacheId = md5(serialize($initHandlerParams))."_".md5(serialize($settings))."_".strval($siteId);
651
652 if(!isset($result[$hitCacheId]))
653 {
654 $config = array(
655 "CONFIG_GROUPS" => array(),
656 "CONFIG" => array(),
657 );
658
659 if (is_callable($initHandlerParams["GETCONFIG"]))
660 {
661 $conf = call_user_func($initHandlerParams["GETCONFIG"], $siteId);
662
663 if(isset($conf["CONFIG_GROUPS"]))
664 $config["CONFIG_GROUPS"] = $conf["CONFIG_GROUPS"];
665
666 if ($settings <> '' && is_callable($initHandlerParams["DBGETSETTINGS"]))
667 {
668 $settings = unserialize($settings, ['allowed_classes' => false]);
669 $arConfigValues = call_user_func($initHandlerParams["DBGETSETTINGS"], $settings);
670 }
671 else
672 {
673 $arConfigValues = array();
674 }
675
676 foreach ($conf["CONFIG"] as $key => $arConfig)
677 {
678 if (is_array($conf["CONFIG"][$key]))
679 {
680 $config["CONFIG"][$key] = $conf["CONFIG"][$key];
681
682 if(isset($arConfigValues[$key]))
683 $config["CONFIG"][$key]["VALUE"] = $arConfigValues[$key];
684 elseif(isset($conf["CONFIG"][$key]["DEFAULT"]))
685 $config["CONFIG"][$key]["VALUE"] = $conf["CONFIG"][$key]["DEFAULT"];
686 else
687 $config["CONFIG"][$key]["VALUE"] = "";
688 }
689 }
690 }
691
692 $result[$hitCacheId] = $config;
693 }
694
695 return $result[$hitCacheId];
696 }
697
698 protected function getCalcultor()
699 {
700 $result = false;
701
702 if(isset($this->handlerInitParams["CALCULATOR"]) && is_callable($this->handlerInitParams["CALCULATOR"]))
703 $result = $this->handlerInitParams["CALCULATOR"];
704
705 return $result;
706 }
707
708 protected function getCompability()
709 {
710 $result = false;
711
712 if(isset($this->handlerInitParams["COMPABILITY"]) && is_callable($this->handlerInitParams["COMPABILITY"]))
713 $result = $this->handlerInitParams["COMPABILITY"];
714
715 return $result;
716 }
717
718 protected static function getCompatibleProfiles($sid, $compatibilityFunc, array $config, Shipment $shipment)
719 {
720 if($sid == '')
721 throw new ArgumentNullException("sid");
722
723 static $result = array();
724 $oldOrder = self::convertNewOrderToOld($shipment);
725
726 if(!empty($oldOrder["ITEMS"]) && is_array($oldOrder["ITEMS"]))
727 {
728 $maxDimensions = array();
729
730 foreach($oldOrder["ITEMS"] as $item)
731 {
732 if(is_string($item["DIMENSIONS"]))
733 $item["DIMENSIONS"] = unserialize($item["DIMENSIONS"], ['allowed_classes' => false]);
734
735 if(!is_array($item["DIMENSIONS"]) || empty($item["DIMENSIONS"]))
736 continue;
737
738 $maxDimensions = \CSaleDeliveryHelper::getMaxDimensions(
739 array(
740 $item["DIMENSIONS"]["WIDTH"],
741 $item["DIMENSIONS"]["HEIGHT"],
742 $item["DIMENSIONS"]["LENGTH"]
743 ),
744 $maxDimensions
745 );
746 }
747
748 if(!empty($maxDimensions))
749 $oldOrder["MAX_DIMENSIONS"] = $maxDimensions;
750 }
751
752 $hitCacheId = $sid.'_'.md5(serialize($oldOrder)).'_'.md5(serialize($config["CONFIG"]));
753
754 if(!isset($result[$hitCacheId]))
755 {
756 $result[$hitCacheId] = call_user_func($compatibilityFunc, $oldOrder, $config["CONFIG"]);
757 }
758
759 return $result[$hitCacheId];
760 }
761
762 public function isProfileCompatible($profileId, $config, Shipment $shipment)
763 {
764 $compatibilityFunc = $this->getCompability();
765
766 if($compatibilityFunc === false)
767 return true;
768
769 $res = $this->getCompatibleProfiles($this->sid.':'.$profileId, $compatibilityFunc, $config, $shipment);
770 return is_array($res) && in_array($profileId, $res);
771 }
772
773 public function getOldConfig()
774 {
775 return $this->oldConfig;
776 }
777
778 public function getSid()
779 {
780 return $this->sid;
781 }
782
791 public function calculateProfile($profileId, array $profileConfig, \Bitrix\Sale\Shipment $shipment)
792 {
793 static $result = array();
794 $oldOrder = self::convertNewOrderToOld($shipment);
795 $hitCacheId = $this->id.'_'.$profileId.'_'.md5(serialize($profileConfig)).'_'.md5(serialize($oldOrder));
796
797 if(isset($result[$hitCacheId]))
798 return clone $result[$hitCacheId];
799
800 global $APPLICATION;
801 $calcRes = new CalculationResult();
802 $step = 0;
803 $tmp = false;
805 $shipmentCollection = $shipment->getCollection();
807 $order = $shipmentCollection->getOrder();
808 $shipmentCurrency = $order->getCurrency();
809
810 if(!Loader::includeModule('currency'))
811 throw new SystemException("Can't include module \"Currency\"");
812
813 $calculator = $this->getCalcultor();
814
815 if ($calculator!== false)
816 {
817 if ($res = call_user_func(
818 $calculator,
819 $profileId,
820 $profileConfig["CONFIG"],
821 $oldOrder,
822 ++$step,
823 $tmp))
824 {
825 if (is_array($res))
826 {
827 if($res["RESULT"] == "OK" )
828 {
829 if(isset($res["TEXT"]))
830 $calcRes->setDescription($res["TEXT"]);
831
832 if(isset($res["VALUE"]))
833 $calcRes->setDeliveryPrice(floatval($res["VALUE"]));
834
835 if(isset($res["TRANSIT"]))
836 $calcRes->setPeriodDescription($res["TRANSIT"]);
837
838 if(isset($res["PERIOD_FROM"]))
839 $calcRes->setPeriodFrom($res["PERIOD_FROM"]);
840
841 if(isset($res["PERIOD_TO"]))
842 $calcRes->setPeriodTo($res["PERIOD_TO"]);
843
844 if(isset($res["PERIOD_TYPE"]))
845 $calcRes->setPeriodType($res["PERIOD_TYPE"]);
846 }
847 else
848 {
849 if(isset($res["TEXT"]) && $res["TEXT"] <> '')
850 {
851 $calcRes->addError(new EntityError(
852 $res["TEXT"],
853 'DELIVERY_CALCULATION'
854 ));
855 }
856 else
857 {
858 $calcRes->addError(new EntityError(
859 Loc::getMessage('SALE_DLVR_HANDL_AUT_ERROR_CALCULATION'),
860 'DELIVERY_CALCULATION'
861 ));
862 }
863 }
864 }
865 elseif (is_numeric($res))
866 {
867 $calcRes->setDeliveryPrice(floatval($res));
868 }
869 }
870 else
871 {
872 if ($ex = $APPLICATION->getException())
873 {
874 $calcRes->addError(new EntityError(
875 $ex->getString(),
876 'DELIVERY_CALCULATION'
877 ));
878 }
879 else
880 {
881 $calcRes->setDeliveryPrice(0);
882 }
883 }
884
885 if ($calcRes->isSuccess() && $this->currency != $shipmentCurrency)
886 {
887 $calcRes->setDeliveryPrice(
888 \CCurrencyRates::convertCurrency(
889 $calcRes->getPrice(),
890 $this->currency,
891 $shipmentCurrency
892 ));
893 }
894 }
895
896 $price = $calcRes->getPrice();
897
898 $calcRes->setDeliveryPrice(
899 $price + $this->getMarginPrice($price, $shipmentCurrency)
900 );
901
902 $result[$hitCacheId] = $calcRes;
903 return clone $result[$hitCacheId];
904 }
905
906 public static function getChildrenClassNames()
907 {
908 return array(
909 '\Bitrix\Sale\Delivery\Services\AutomaticProfile'
910 );
911 }
912
913 public function getConfigValues()
914 {
915 return $this->config;
916 }
917
918 protected function getMarginPrice($price, $shipmentCurrency = '')
919 {
920 if($this->config["MAIN"]["MARGIN_TYPE"] == "%")
921 {
922 $marginPrice = $price * floatval($this->config["MAIN"]["MARGIN_VALUE"]) / 100;
923 }
924 else
925 {
926 $marginPrice = floatval($this->config["MAIN"]["MARGIN_VALUE"]);
927
928 if($marginPrice && $shipmentCurrency != '' && $this->currency != $shipmentCurrency)
929 {
930 if(Loader::includeModule('currency'))
931 {
932 $marginPrice = \CCurrencyRates::convertCurrency(
933 $marginPrice,
934 $this->currency,
935 $shipmentCurrency
936 );
937 }
938 }
939 }
940
941 return $marginPrice;
942 }
943
944 public function getProfilesDefaultParams(array $fields = array())
945 {
946 if(empty($this->handlerInitParams["PROFILES"]) || !is_array($this->handlerInitParams["PROFILES"]))
947 return array();
948
949 $result = array();
950
951 foreach($this->handlerInitParams["PROFILES"] as $profId => $params)
952 {
953 if(empty($params["TITLE"]))
954 continue;
955
956 $result[] = array(
957 "CODE" => $this->handlerInitParams["SID"].":".$profId,
958 "PARENT_ID" => $this->id,
959 "NAME" => $params["TITLE"],
960 "ACTIVE" => $this->active ? "Y" : "N",
961 "SORT" => $this->sort,
962 "DESCRIPTION" => isset($params["DESCRIPTION"]) ? $params["DESCRIPTION"] : "",
963 "CLASS_NAME" => '\Bitrix\Sale\Delivery\Services\AutomaticProfile',
964 "CURRENCY" => $this->currency,
965 "XML_ID" => Manager::generateXmlId(),
966 "CONFIG" => array(
967 "MAIN" => array(
968 "PROFILE_ID" => $profId,
969 "MARGIN_VALUE" => 0,
970 "MARGIN_TYPE" => "%"
971 )
972 )
973 );
974 }
975
976 return $result;
977 }
978
979 public static function onAfterAdd($serviceId, array $fields = array())
980 {
981 if($serviceId <= 0)
982 return false;
983
984 $fields["ID"] = $serviceId;
985 $srv = new self($fields);
986 $profiles = $srv->getProfilesDefaultParams($fields);
987
988 if(!is_array($profiles))
989 return false;
990
991 $result = true;
992
993 foreach($profiles as $profile)
994 {
995 $res = Manager::add($profile);
996 $result = $result && $res->isSuccess();
997 }
998
999 return $result;
1000 }
1001
1002 public function getProfilesList()
1003 {
1004 static $result = null;
1005
1006 if($result === null)
1007 {
1008 $result = array();
1009
1010 foreach($this->handlerInitParams["PROFILES"] as $profId => $params)
1011 if(!empty($params["TITLE"]))
1012 $result[$profId] = $params["TITLE"];
1013 }
1014
1015 return $result;
1016 }
1017
1018 public static function canHasProfiles()
1019 {
1020 return self::$canHasProfiles;
1021 }
1022
1023 public function getAdminMessage()
1024 {
1025 $result = array();
1026
1027 if(isset($this->handlerInitParams["GET_ADMIN_MESSAGE"]) && is_callable($this->handlerInitParams["GET_ADMIN_MESSAGE"]))
1028 $result = call_user_func($this->handlerInitParams["GET_ADMIN_MESSAGE"]);
1029
1030 return $result;
1031 }
1032
1033 public function execAdminAction()
1034 {
1035 $result = new Result();
1036
1037 if(isset($this->handlerInitParams["EXEC_ADMIN_ACTION"]) && is_callable($this->handlerInitParams["EXEC_ADMIN_ACTION"]))
1038 $result = call_user_func($this->handlerInitParams["EXEC_ADMIN_ACTION"]);
1039
1040 return $result;
1041 }
1042
1043 public function getAdditionalInfoShipmentEdit(Shipment $shipment)
1044 {
1045 $result = '';
1046
1047 if(isset($this->handlerInitParams["GET_ADD_INFO_SHIPMENT_EDIT"]) && is_callable($this->handlerInitParams["GET_ADD_INFO_SHIPMENT_EDIT"]))
1048 {
1049 $result = call_user_func(
1050 $this->handlerInitParams["GET_ADD_INFO_SHIPMENT_EDIT"],
1051 $shipment
1052 );
1053
1054 if(!is_array($result))
1055 throw new SystemException('GET_ADD_INFO_SHIPMENT_EDIT return value must be array!');
1056 }
1057
1058 return $result;
1059 }
1060
1061 public function processAdditionalInfoShipmentEdit(Shipment $shipment, array $requestData)
1062 {
1063 $result = '';
1064
1065 if(isset($this->handlerInitParams["PROCESS_ADD_INFO_SHIPMENT_EDIT"]) && is_callable($this->handlerInitParams["PROCESS_ADD_INFO_SHIPMENT_EDIT"]))
1066 {
1067 $result = call_user_func(
1068 $this->handlerInitParams["PROCESS_ADD_INFO_SHIPMENT_EDIT"],
1069 $shipment,
1070 $requestData
1071 );
1072
1073 if($result && get_class($result) != 'Bitrix\Sale\Shipment')
1074 throw new SystemException('PROCESS_ADD_INFO_SHIPMENT_EDIT return value myst be of type "Bitrix\Sale\Result" !');
1075 }
1076
1077 return $result;
1078 }
1079
1080 public function getAdditionalInfoShipmentView(Shipment $shipment)
1081 {
1082 $result = '';
1083
1084 if(isset($this->handlerInitParams["GET_ADD_INFO_SHIPMENT_VIEW"]) && is_callable($this->handlerInitParams["GET_ADD_INFO_SHIPMENT_VIEW"]))
1085 {
1086 $result = call_user_func(
1087 $this->handlerInitParams["GET_ADD_INFO_SHIPMENT_VIEW"],
1088 $shipment
1089 );
1090
1091 if(!is_array($result))
1092 throw new SystemException('GET_ADD_INFO_SHIPMENT_VIEW return value must be array!');
1093 }
1094
1095 return $result;
1096 }
1097
1104 protected static function isAutomaticHandlerCompatible($handler): bool
1105 {
1106 $result = true;
1107
1108 if (isset($handler["IS_HANDLER_COMPATIBLE"])
1109 && is_callable($handler["IS_HANDLER_COMPATIBLE"]))
1110 {
1111 $result = call_user_func($handler["IS_HANDLER_COMPATIBLE"]);
1112 }
1113
1114 return $result;
1115 }
1116}
static loadMessages($file)
Definition loc.php:64
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
isProfileCompatible($profileId, $config, Shipment $shipment)
static convertNewSettingsToOld(array $newSettings=array())
static convertNewOrderToOld(\Bitrix\Sale\Shipment $shipment)
static createConfig($initHandlerParams, $settings, $siteId=false)
static getRegisteredHandlers($indexBy="")
static convertOldConfigParamToNew(array $oldParam)
static getCompatibleProfiles($sid, $compatibilityFunc, array $config, Shipment $shipment)
getProfilesDefaultParams(array $fields=array())
getMarginPrice($price, $shipmentCurrency='')
static onAfterAdd($serviceId, array $fields=array())
getAdditionalInfoShipmentEdit(Shipment $shipment)
processAdditionalInfoShipmentEdit(Shipment $shipment, array $requestData)
static convertNewServiceToOld($service, $sid=false)
getAdditionalInfoShipmentView(Shipment $shipment)