1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
automatic.php
См. документацию.
1<?php
2
4
5use Bitrix\Sale\Order;
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();
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
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
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 {
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 {
631 }
632
633 return $result;
634 }
635
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 (!isset($item['DIMENSIONS']))
733 {
734 continue;
735 }
736 if (is_string($item['DIMENSIONS']) && $item['DIMENSIONS'] !== '')
737 {
738 $item['DIMENSIONS'] = unserialize($item['DIMENSIONS'], ['allowed_classes' => false]);
739 }
740
741 if(!is_array($item["DIMENSIONS"]) || empty($item["DIMENSIONS"]))
742 continue;
743
745 array(
746 $item["DIMENSIONS"]["WIDTH"],
747 $item["DIMENSIONS"]["HEIGHT"],
748 $item["DIMENSIONS"]["LENGTH"]
749 ),
750 $maxDimensions
751 );
752 }
753
754 if(!empty($maxDimensions))
755 $oldOrder["MAX_DIMENSIONS"] = $maxDimensions;
756 }
757
758 $hitCacheId = $sid.'_'.md5(serialize($oldOrder)).'_'.md5(serialize($config["CONFIG"]));
759
760 if(!isset($result[$hitCacheId]))
761 {
762 $result[$hitCacheId] = call_user_func($compatibilityFunc, $oldOrder, $config["CONFIG"]);
763 }
764
765 return $result[$hitCacheId];
766 }
767
768 public function isProfileCompatible($profileId, $config, Shipment $shipment)
769 {
770 $compatibilityFunc = $this->getCompability();
771
772 if($compatibilityFunc === false)
773 return true;
774
775 $res = $this->getCompatibleProfiles($this->sid.':'.$profileId, $compatibilityFunc, $config, $shipment);
776 return is_array($res) && in_array($profileId, $res);
777 }
778
779 public function getOldConfig()
780 {
781 return $this->oldConfig;
782 }
783
784 public function getSid()
785 {
786 return $this->sid;
787 }
788
797 public function calculateProfile($profileId, array $profileConfig, \Bitrix\Sale\Shipment $shipment)
798 {
799 static $result = array();
800 $oldOrder = self::convertNewOrderToOld($shipment);
801 $hitCacheId = $this->id.'_'.$profileId.'_'.md5(serialize($profileConfig)).'_'.md5(serialize($oldOrder));
802
803 if(isset($result[$hitCacheId]))
804 return clone $result[$hitCacheId];
805
806 global $APPLICATION;
807 $calcRes = new CalculationResult();
808 $step = 0;
809 $tmp = false;
811 $shipmentCollection = $shipment->getCollection();
813 $order = $shipmentCollection->getOrder();
814 $shipmentCurrency = $order->getCurrency();
815
816 if(!Loader::includeModule('currency'))
817 throw new SystemException("Can't include module \"Currency\"");
818
819 $calculator = $this->getCalcultor();
820
821 if ($calculator!== false)
822 {
823 if ($res = call_user_func(
824 $calculator,
825 $profileId,
826 $profileConfig["CONFIG"],
827 $oldOrder,
828 ++$step,
829 $tmp))
830 {
831 if (is_array($res))
832 {
833 if($res["RESULT"] == "OK" )
834 {
835 if(isset($res["TEXT"]))
836 $calcRes->setDescription($res["TEXT"]);
837
838 if(isset($res["VALUE"]))
839 $calcRes->setDeliveryPrice(floatval($res["VALUE"]));
840
841 if(isset($res["TRANSIT"]))
842 $calcRes->setPeriodDescription($res["TRANSIT"]);
843
844 if(isset($res["PERIOD_FROM"]))
845 $calcRes->setPeriodFrom($res["PERIOD_FROM"]);
846
847 if(isset($res["PERIOD_TO"]))
848 $calcRes->setPeriodTo($res["PERIOD_TO"]);
849
850 if(isset($res["PERIOD_TYPE"]))
851 $calcRes->setPeriodType($res["PERIOD_TYPE"]);
852 }
853 else
854 {
855 if(isset($res["TEXT"]) && $res["TEXT"] <> '')
856 {
857 $calcRes->addError(new EntityError(
858 $res["TEXT"],
859 'DELIVERY_CALCULATION'
860 ));
861 }
862 else
863 {
864 $calcRes->addError(new EntityError(
865 Loc::getMessage('SALE_DLVR_HANDL_AUT_ERROR_CALCULATION'),
866 'DELIVERY_CALCULATION'
867 ));
868 }
869 }
870 }
871 elseif (is_numeric($res))
872 {
873 $calcRes->setDeliveryPrice(floatval($res));
874 }
875 }
876 else
877 {
878 if ($ex = $APPLICATION->getException())
879 {
880 $calcRes->addError(new EntityError(
881 $ex->getString(),
882 'DELIVERY_CALCULATION'
883 ));
884 }
885 else
886 {
887 $calcRes->setDeliveryPrice(0);
888 }
889 }
890
891 if ($calcRes->isSuccess() && $this->currency != $shipmentCurrency)
892 {
893 $calcRes->setDeliveryPrice(
894 \CCurrencyRates::convertCurrency(
895 $calcRes->getPrice(),
896 $this->currency,
897 $shipmentCurrency
898 ));
899 }
900 }
901
902 $price = $calcRes->getPrice();
903
904 $calcRes->setDeliveryPrice(
905 $price + $this->getMarginPrice($price, $shipmentCurrency)
906 );
907
908 $result[$hitCacheId] = $calcRes;
909 return clone $result[$hitCacheId];
910 }
911
912 public static function getChildrenClassNames()
913 {
914 return array(
915 '\Bitrix\Sale\Delivery\Services\AutomaticProfile'
916 );
917 }
918
919 public function getConfigValues()
920 {
921 return $this->config;
922 }
923
924 protected function getMarginPrice($price, $shipmentCurrency = '')
925 {
926 if($this->config["MAIN"]["MARGIN_TYPE"] == "%")
927 {
928 $marginPrice = $price * floatval($this->config["MAIN"]["MARGIN_VALUE"]) / 100;
929 }
930 else
931 {
932 $marginPrice = floatval($this->config["MAIN"]["MARGIN_VALUE"]);
933
934 if($marginPrice && $shipmentCurrency != '' && $this->currency != $shipmentCurrency)
935 {
936 if(Loader::includeModule('currency'))
937 {
938 $marginPrice = \CCurrencyRates::convertCurrency(
939 $marginPrice,
940 $this->currency,
941 $shipmentCurrency
942 );
943 }
944 }
945 }
946
947 return $marginPrice;
948 }
949
951 {
952 if(empty($this->handlerInitParams["PROFILES"]) || !is_array($this->handlerInitParams["PROFILES"]))
953 return array();
954
955 $result = array();
956
957 foreach($this->handlerInitParams["PROFILES"] as $profId => $params)
958 {
959 if(empty($params["TITLE"]))
960 continue;
961
962 $result[] = array(
963 "CODE" => $this->handlerInitParams["SID"].":".$profId,
964 "PARENT_ID" => $this->id,
965 "NAME" => $params["TITLE"],
966 "ACTIVE" => $this->active ? "Y" : "N",
967 "SORT" => $this->sort,
968 "DESCRIPTION" => isset($params["DESCRIPTION"]) ? $params["DESCRIPTION"] : "",
969 "CLASS_NAME" => '\Bitrix\Sale\Delivery\Services\AutomaticProfile',
970 "CURRENCY" => $this->currency,
971 "XML_ID" => Manager::generateXmlId(),
972 "CONFIG" => array(
973 "MAIN" => array(
974 "PROFILE_ID" => $profId,
975 "MARGIN_VALUE" => 0,
976 "MARGIN_TYPE" => "%"
977 )
978 )
979 );
980 }
981
982 return $result;
983 }
984
985 public static function onAfterAdd($serviceId, array $fields = array())
986 {
987 if($serviceId <= 0)
988 return false;
989
990 $fields["ID"] = $serviceId;
991 $srv = new self($fields);
992 $profiles = $srv->getProfilesDefaultParams($fields);
993
994 if(!is_array($profiles))
995 return false;
996
997 $result = true;
998
999 foreach($profiles as $profile)
1000 {
1001 $res = Manager::add($profile);
1002 $result = $result && $res->isSuccess();
1003 }
1004
1005 return $result;
1006 }
1007
1008 public function getProfilesList()
1009 {
1010 static $result = null;
1011
1012 if($result === null)
1013 {
1014 $result = array();
1015
1016 foreach($this->handlerInitParams["PROFILES"] as $profId => $params)
1017 if(!empty($params["TITLE"]))
1018 $result[$profId] = $params["TITLE"];
1019 }
1020
1021 return $result;
1022 }
1023
1024 public static function canHasProfiles()
1025 {
1026 return self::$canHasProfiles;
1027 }
1028
1029 public function getAdminMessage()
1030 {
1031 $result = array();
1032
1033 if(isset($this->handlerInitParams["GET_ADMIN_MESSAGE"]) && is_callable($this->handlerInitParams["GET_ADMIN_MESSAGE"]))
1034 $result = call_user_func($this->handlerInitParams["GET_ADMIN_MESSAGE"]);
1035
1036 return $result;
1037 }
1038
1039 public function execAdminAction()
1040 {
1041 $result = new Result();
1042
1043 if(isset($this->handlerInitParams["EXEC_ADMIN_ACTION"]) && is_callable($this->handlerInitParams["EXEC_ADMIN_ACTION"]))
1044 $result = call_user_func($this->handlerInitParams["EXEC_ADMIN_ACTION"]);
1045
1046 return $result;
1047 }
1048
1049 public function getAdditionalInfoShipmentEdit(Shipment $shipment)
1050 {
1051 $result = '';
1052
1053 if(isset($this->handlerInitParams["GET_ADD_INFO_SHIPMENT_EDIT"]) && is_callable($this->handlerInitParams["GET_ADD_INFO_SHIPMENT_EDIT"]))
1054 {
1055 $result = call_user_func(
1056 $this->handlerInitParams["GET_ADD_INFO_SHIPMENT_EDIT"],
1057 $shipment
1058 );
1059
1060 if(!is_array($result))
1061 throw new SystemException('GET_ADD_INFO_SHIPMENT_EDIT return value must be array!');
1062 }
1063
1064 return $result;
1065 }
1066
1067 public function processAdditionalInfoShipmentEdit(Shipment $shipment, array $requestData)
1068 {
1069 $result = '';
1070
1071 if(isset($this->handlerInitParams["PROCESS_ADD_INFO_SHIPMENT_EDIT"]) && is_callable($this->handlerInitParams["PROCESS_ADD_INFO_SHIPMENT_EDIT"]))
1072 {
1073 $result = call_user_func(
1074 $this->handlerInitParams["PROCESS_ADD_INFO_SHIPMENT_EDIT"],
1075 $shipment,
1076 $requestData
1077 );
1078
1079 if($result && get_class($result) != 'Bitrix\Sale\Shipment')
1080 throw new SystemException('PROCESS_ADD_INFO_SHIPMENT_EDIT return value myst be of type "Bitrix\Sale\Result" !');
1081 }
1082
1083 return $result;
1084 }
1085
1086 public function getAdditionalInfoShipmentView(Shipment $shipment)
1087 {
1088 $result = '';
1089
1090 if(isset($this->handlerInitParams["GET_ADD_INFO_SHIPMENT_VIEW"]) && is_callable($this->handlerInitParams["GET_ADD_INFO_SHIPMENT_VIEW"]))
1091 {
1092 $result = call_user_func(
1093 $this->handlerInitParams["GET_ADD_INFO_SHIPMENT_VIEW"],
1094 $shipment
1095 );
1096
1097 if(!is_array($result))
1098 throw new SystemException('GET_ADD_INFO_SHIPMENT_VIEW return value must be array!');
1099 }
1100
1101 return $result;
1102 }
1103
1110 protected static function isAutomaticHandlerCompatible($handler): bool
1111 {
1112 $result = true;
1113
1114 if (isset($handler["IS_HANDLER_COMPATIBLE"])
1115 && is_callable($handler["IS_HANDLER_COMPATIBLE"]))
1116 {
1117 $result = call_user_func($handler["IS_HANDLER_COMPATIBLE"]);
1118 }
1119
1120 return $result;
1121 }
1122}
$basePath
Определения include.php:41
global $APPLICATION
Определения include.php:80
Определения loader.php:13
isProfileCompatible($profileId, $config, Shipment $shipment)
Определения automatic.php:768
static convertNewSettingsToOld(array $newSettings=array())
Определения automatic.php:280
static convertOldConfigToNew($oldConfig)
Определения automatic.php:295
static convertNewOrderToOld(\Bitrix\Sale\Shipment $shipment)
Определения automatic.php:425
static getHandlerInitParams($sid)
Определения automatic.php:430
static createConfig($initHandlerParams, $settings, $siteId=false)
Определения automatic.php:647
static getRegisteredHandlers($indexBy="")
Определения automatic.php:481
static convertOldConfigParamToNew(array $oldParam)
Определения automatic.php:366
static getClassDescription()
Определения automatic.php:84
__construct(array $initParams)
Определения automatic.php:39
static getCompatibleProfiles($sid, $compatibilityFunc, array $config, Shipment $shipment)
Определения automatic.php:718
static getChildrenClassNames()
Определения automatic.php:912
prepareFieldsForSaving(array $fields)
Определения automatic.php:235
getOldDbSettings($settings)
Определения automatic.php:636
getProfilesDefaultParams(array $fields=array())
Определения automatic.php:950
getMarginPrice($price, $shipmentCurrency='')
Определения automatic.php:924
static onAfterAdd($serviceId, array $fields=array())
Определения automatic.php:985
getAdditionalInfoShipmentEdit(Shipment $shipment)
Определения automatic.php:1049
processAdditionalInfoShipmentEdit(Shipment $shipment, array $requestData)
Определения automatic.php:1067
static isAutomaticHandlerCompatible($handler)
Определения automatic.php:1110
static convertNewServiceToOld($service, $sid=false)
Определения automatic.php:506
getAdditionalInfoShipmentView(Shipment $shipment)
Определения automatic.php:1086
static getByParentId($parentId)
Определения manager.php:741
static generateXmlId()
Определения manager.php:804
static getTypes()
Определения input.php:266
static getRestrictionsList($serviceId)
Определения restrictionmanager.php:158
static getMaxDimensions($arDim1, $arDim2)
Определения delivery_helper.php:160
if(!is_array($prop["VALUES"])) $tmp
Определения component_props.php:203
$filename
Определения file_edit.php:47
</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
$handle
Определения include.php:55
$result
Определения get_property_values.php:14
$_SERVER["DOCUMENT_ROOT"]
Определения cron_frame.php:9
$siteId
Определения ajax.php:8
ExecuteModuleEventEx($arEvent, $arParams=[])
Определения tools.php:5214
htmlspecialcharsbx($string, $flags=ENT_COMPAT, $doubleEncode=true)
Определения tools.php:2701
GetModuleEvents($MODULE_ID, $MESSAGE_ID, $bReturnArray=false)
Определения tools.php:5177
sortByColumn(array &$array, $columns, $callbacks='', $defaultValueIfNotSetValue=null, $preserveKeys=false)
Определения tools.php:5087
Определения directory.php:3
$order
Определения payment.php:8
$service
Определения payment.php:18
$settings
Определения product_settings.php:43
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
$config
Определения quickway.php:69
if(empty($signedUserToken)) $key
Определения quickway.php:257
$currency
Определения template.php:266
if($inWords) echo htmlspecialcharsbx(Number2Word_Rus(roundEx($totalVatSum $params['CURRENCY']
Определения template.php:799
$fields
Определения yandex_run.php:501