Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
manager.php
1<?php
3
5
17use Bitrix\Main\Entity\EventResult;
25
26Loc::loadMessages(__FILE__);
27
34{
37
38 protected static $handlers = null;
39 protected static $restHandlers = [];
40 protected static $cachedFields = array();
41
42 /* Directories where we can found handlers */
43 protected static $handlersDirectories = array();
45 protected static $objectsPool = null;
46
53 public static function getById($deliveryId)
54 {
55 $id = intval($deliveryId);
56
57 if($id <= 0)
58 throw new SystemException("deliveryId");
59
60 if(!isset(self::$cachedFields[$deliveryId]) || !is_array(self::$cachedFields[$deliveryId]))
61 {
62 self::$cachedFields[$deliveryId] = array();
63
64 $resSrvParams = Table::getList(array(
65 'filter' => array("=ID" => $deliveryId)
66 ));
67
68 if($srvParams = $resSrvParams->fetch())
69 self::$cachedFields[$srvParams["ID"]] = $srvParams;
70 }
71
72 return self::$cachedFields[$deliveryId];
73 }
74
82 public static function getList(array $params = array()): \Bitrix\Main\ORM\Query\Result
83 {
84 return Table::getList($params);
85 }
86
92 public static function getRestrictedObjectsList(Shipment $shipment, $restrictionMode = Restrictions\Manager::MODE_CLIENT)
93 {
94 $result = array();
95 $services = self::getRestrictedList($shipment, $restrictionMode);
96
97 foreach($services as $srvParams)
98 {
99 if($srvParams["CLASS_NAME"]::canHasProfiles())
100 continue;
101
102 if(is_callable($srvParams["CLASS_NAME"]."::canHasChildren") && $srvParams["CLASS_NAME"]::canHasChildren())
103 continue;
104
105 $service = self::getPooledObject($srvParams);
106
107 if(!$service)
108 continue;
109
110 if(!$service->isCompatible($shipment))
111 continue;
112
113 if($shipment->getCurrency() != $service->getCurrency())
114 {
115 $service->getExtraServices()->setOperationCurrency(
116 $shipment->getCurrency()
117 );
118 }
119
120 $result[$srvParams["ID"]] = $service;
121 }
122
123 return $result;
124 }
125
131 public static function isServiceExist($deliveryId)
132 {
133 if(intval($deliveryId) <= 0)
134 return false;
135
136 $srv = self::getById($deliveryId);
137 return !empty($srv);
138 }
139
147 public static function getActiveList($calculatingOnly = false, $restrictedIds = null)
148 {
149 //If we alredy got all active services
150 static $isDataPrepared = false;
151 static $activeIds = array();
152 static $canHasProfiles = array();
153 static $canHasChildren = array();
154 static $DontHaveRestrictionsIds = array();
155
156 if(is_array($restrictedIds))
157 {
158 $unPreparedRestrictedIds = array_diff_key(
159 array_flip(
160 $restrictedIds
161 ),
162 self::$cachedFields
163 );
164
165 $unPreparedRestrictedIds = array_keys($unPreparedRestrictedIds);
166 }
167 else
168 {
169 $unPreparedRestrictedIds = array();
170 }
171
172 if(!$isDataPrepared || !empty($unPreparedRestrictedIds))
173 {
174 $result = array();
175 self::initHandlers();
176
177 $filter = array(
178 '=ACTIVE' => 'Y'
179 );
180
181 $params = array(
182 'order' => array('SORT' =>'ASC', 'NAME' => 'ASC'),
183 'filter' => $filter
184 );
185
186 $params['runtime'] = array(
187 new \Bitrix\Main\Entity\ExpressionField(
188 'RESTRICTIONS_EXIST',
189 'CASE WHEN EXISTS('.
190 'SELECT 1 FROM b_sale_service_rstr SSR WHERE SSR.SERVICE_ID = %s AND SSR.SERVICE_TYPE = '.Restrictions\Manager::SERVICE_TYPE_SHIPMENT.') THEN 1 ELSE 0 END',
191 'ID'
192 )
193 );
194
195 $params['select'] = array('*', 'RESTRICTIONS_EXIST');
196
197 if(!empty($unPreparedRestrictedIds))
198 {
199 if($isDataPrepared)
200 {
201 $params['filter']['ID'] = $unPreparedRestrictedIds;
202 }
203 else
204 {
205 $params['filter'][] = array(
206 "LOGIC" => "OR",
207 "ID" => $unPreparedRestrictedIds,
208 'RESTRICTIONS_EXIST' => 0
209 );
210 }
211 }
212
213 $dbRes = Table::getList($params);
214 $profilesParentsIds = array();
215
216 while($service = $dbRes->fetch())
217 {
218 if(!is_subclass_of($service["CLASS_NAME"], 'Bitrix\Sale\Delivery\Services\Base'))
219 continue;
220
221 if(!$service['RESTRICTIONS_EXIST'])
222 $DontHaveRestrictionsIds[] = $service['ID'];
223
224 if($service["CLASS_NAME"]::canHasChildren())
225 $canHasChildren[$service["ID"]] = true;
226
227 if ($service['CLASS_NAME']::canHasProfiles())
228 $canHasProfiles[$service["ID"]] = true;
229
230 if($service["PARENT_ID"] != 0)
231 $profilesParentsIds[$service["PARENT_ID"]] = $service['ID'];
232
233 $result[$service["ID"]] = $service;
234
235 if($service['ACTIVE'] == 'Y')
236 $activeIds[$service["ID"]] = $service["ID"];
237 }
238
239 foreach(array_diff_key($canHasProfiles, $profilesParentsIds) as $id => $tmp)
240 unset($result[$id]);
241
242 self::$cachedFields = self::$cachedFields + $result;
243 Restrictions\Manager::prepareData(array_keys($result));
244 ExtraServices\Manager::prepareData(array_keys($result));
245
246 //selected all active
247 if(!$isDataPrepared && empty($unPreparedRestrictedIds))
248 $isDataPrepared = true;
249 }
250
251 if(is_array($restrictedIds) && !empty($restrictedIds))
252 $storedIds = array_diff($restrictedIds, $unPreparedRestrictedIds);
253 else
254 $storedIds = array();
255
256 if(!empty($storedIds) && is_array($storedIds))
257 {
258 foreach($storedIds as $storedId)
259 {
260 if(empty(self::$cachedFields[$storedId]))
261 continue;
262
263 $service = self::$cachedFields[$storedId];
264
265 if(!class_exists($service["CLASS_NAME"]))
266 continue;
267
268 if($service["CLASS_NAME"]::canHasChildren())
269 $canHasChildren[$storedId] = true;
270
271 if ($service['CLASS_NAME']::canHasProfiles())
272 $canHasProfiles[$storedId] = true;
273
274 if($service['ACTIVE'] == 'Y')
275 $activeIds[$storedId] = $storedId;
276 }
277 }
278
279 $active = array_intersect_key(self::$cachedFields, array_flip($activeIds));
280
281 if(is_array($restrictedIds))
282 {
283 $result = array_intersect_key($active, array_flip($DontHaveRestrictionsIds));
284
285 if(!empty($restrictedIds))
286 $result = $result + array_intersect_key($active, array_flip($restrictedIds));
287 }
288 else
289 {
290 $result = $active;
291 }
292
293 /*
294 * Clean children if parent is not present in result.
295 * We mean that it doesn't pass restrictions checks.
296 * Or it is not active.
297 */
298
299 foreach($result as $id => $fields)
300 {
301 if(intval($fields['PARENT_ID']) <= 0)
302 continue;
303
304 if(empty($result[$fields['PARENT_ID']]))
305 unset($result[$id]);
306 }
307
308 if($calculatingOnly)
309 $result = array_diff_key($result, $canHasChildren, $canHasProfiles);
310
311 if(!empty($result))
312 sortByColumn($result, array("SORT" => SORT_ASC, "NAME" => SORT_ASC), '', null, true);
313
314 return $result;
315 }
316
323 public static function getRestrictedList(Shipment $shipment = null, $restrictionMode, array $skipChecks = array())
324 {
325 $result = array();
326
327 if(empty($skipChecks))
328 {
329 $skipChecks = array(
330 self::SKIP_CHILDREN_PARENT_CHECK,
331 self::SKIP_PROFILE_PARENT_CHECK
332 );
333 }
334
335 //Have restrictions and this restrictions successfully checked
336 $restrictedSrvIds = Restrictions\Manager::getRestrictedIds($shipment, $restrictionMode);
337 //Don't have any restrictions + successfully checked
338 $services = self::getActiveList(false, array_keys($restrictedSrvIds));
339
340 foreach($services as $srvParams)
341 {
342 $srvParams["RESTRICTED"] = false;
343
344 if(!in_array(self::SKIP_PROFILE_PARENT_CHECK, $skipChecks))
345 if($srvParams["CLASS_NAME"]::canHasProfiles())
346 continue;
347
348 if(!in_array(self::SKIP_CHILDREN_PARENT_CHECK, $skipChecks))
349 if(is_callable($srvParams["CLASS_NAME"]."::canHasChildren") && $srvParams["CLASS_NAME"]::canHasChildren())
350 continue;
351
352 if(isset($restrictedSrvIds[$srvParams["ID"]]) && $restrictedSrvIds[$srvParams["ID"]] == Restrictions\Manager::SEVERITY_SOFT)
353 $srvParams["RESTRICTED"] = true;
354
355 $result[$srvParams["ID"]] = $srvParams;
356 }
357
358 return $result;
359 }
360
367 public static function createObject(array $srvParams)
368 {
369 self::initHandlers();
370 $errorMsg = '';
371 $service = null;
372
373 if(!isset($srvParams['PARENT_ID']))
374 {
375 $srvParams['PARENT_ID'] = 0;
376 }
377
378 if(class_exists($srvParams['CLASS_NAME']))
379 {
380 if(is_subclass_of($srvParams['CLASS_NAME'], Base::class))
381 {
382 try
383 {
384 $service = new $srvParams['CLASS_NAME']($srvParams);
385 }
386 catch (SystemException $err)
387 {
388 $errorMsg = $err->getMessage();
389 }
390 }
391 else
392 {
393 $errorMsg = 'Class "' . $srvParams['CLASS_NAME'] . '" is not subclass of of Bitrix\Sale\Delivery\Services\Base';
394 }
395 }
396 else
397 {
398 $errorMsg = 'Can\'t create delivery object. Class "'.$srvParams['CLASS_NAME']. '" does not exist.';
399 }
400
401 if($errorMsg !== '')
402 {
403 static::log(
404 [
405 'SEVERITY' => \CEventLog::SEVERITY_ERROR,
406 'AUDIT_TYPE_ID' => 'SALE_DELIVERY_CREATE_OBJECT_ERROR',
407 'MODULE_ID' => 'sale',
408 'ITEM_ID' => 'createObject()',
409 'DESCRIPTION' => $errorMsg.' Fields: '.serialize($srvParams),
410 ]
411 );
412
413 return null;
414 }
415
416 return $service;
417 }
418
419 protected static function log(array $params): void
420 {
421 \CEventLog::Add($params);
422 }
423
424 public static function getPooledObject(array $fields)
425 {
426 if(self::$objectsPool === null)
427 self::$objectsPool = new ObjectPool();
428
429 return self::$objectsPool->getObject($fields);
430 }
431
438 public static function getObjectById($deliveryId)
439 {
440 if(intval($deliveryId) <= 0 )
441 throw new ArgumentNullException("deliveryId");
442
443 $srvParams = self::getById($deliveryId);
444
445 if(empty($srvParams))
446 return null;
447
448 return self::getPooledObject($srvParams);
449 }
450
458 public static function getObjectByCode($serviceCode)
459 {
460 if($serviceCode == '' )
461 throw new ArgumentNullException("serviceCode");
462
463 $srvParams = array();
464
465 foreach(self::$cachedFields as $id => $srv)
466 {
467 if($srv['CODE'] == $serviceCode)
468 {
469 $srvParams = $srv;
470 }
471 }
472
473 if(empty($srvParams))
474 {
475 $resSrvParams = Table::getList(array(
476 'filter' => array('=CODE' => $serviceCode)
477 ));
478
479 if(!($srvParams = $resSrvParams->fetch()))
480 throw new SystemException("Can't get delivery service data with code: \"".$serviceCode."\"");
481
482 self::$cachedFields[$srvParams['ID']] = $srvParams;
483 }
484
485 return self::getPooledObject($srvParams);
486 }
487
495 protected static function initHandlers()
496 {
497 if(self::$handlers !== null)
498 return true;
499
500 self::$handlersDirectories = array(
501 'LOCAL' => '/local/php_interface/include/sale_delivery/',
502 'CUSTOM' => Option::get('sale', 'delivery_handles_custom_path', BX_PERSONAL_ROOT.'/php_interface/include/sale_delivery/'),
503 'SYSTEM' => '/bitrix/modules/sale/handlers/delivery/'
504 );
505
506 $result = array(
507 '\Bitrix\Sale\Delivery\Services\Group' => 'lib/delivery/services/group.php',
508 '\Bitrix\Sale\Delivery\Services\Automatic' => 'lib/delivery/services/automatic.php',
509 '\Bitrix\Sale\Delivery\Services\Configurable' => 'lib/delivery/services/configurable.php',
510 '\Bitrix\Sale\Delivery\Services\AutomaticProfile' => 'lib/delivery/services/automatic_profile.php',
511 '\Bitrix\Sale\Delivery\Services\EmptyDeliveryService' => 'lib/delivery/services/emptydeliveryservice.php',
512 );
513
514 \Bitrix\Main\Loader::registerAutoLoadClasses('sale', $result);
515
516 /*
517 * To add you own handler you must wrote smth. like this in for example init.php:
518 *
519 * function addCustomDeliveryServices()
520 * {
521 * return new \Bitrix\Main\EventResult(
522 * \Bitrix\Main\EventResult::SUCCESS,
523 * array(
524 * '\Sale\Handlers\Delivery\SimpleHandler' => '/bitrix/modules/sale/handlers/delivery/simple/handler.php'
525 * ),
526 * 'sale'
527 * );
528 * }
529 *
530 * $eventManager->addEventHandler('sale', 'onSaleDeliveryHandlersClassNamesBuildList', 'addCustomDeliveryServices');
531 */
532
533 $event = new Event('sale', 'onSaleDeliveryHandlersClassNamesBuildList');
534 $event->send();
535 $resultList = $event->getResults();
536
537 if (is_array($resultList) && !empty($resultList))
538 {
539 $customClasses = array();
540
541 foreach ($resultList as $eventResult)
542 {
544 if ($eventResult->getType() != EventResult::SUCCESS)
545 continue;
546
547 $params = $eventResult->getParameters();
548
549 if(!empty($params) && is_array($params))
550 $customClasses = array_merge($customClasses, $params);
551 }
552
553 if(!empty($customClasses))
554 {
555 \Bitrix\Main\Loader::registerAutoLoadClasses(null, $customClasses);
556 $result = array_merge($result, $customClasses);
557 }
558 }
559
560 $handlers = self::getHandlersClasses();
561
562 if(!empty($handlers))
563 {
564 \Bitrix\Main\Loader::registerAutoLoadClasses(null, $handlers);
565 $result = array_merge($result, self::getHandlersClasses());
566 }
567
568 self::$handlers = array_keys($result);
569
570 for($idx = count(self::$handlers) - 1; $idx >= 0; $idx--)
571 {
573 $handler = self::$handlers[$idx];
574
575 if(!$handler::isHandlerCompatible())
576 {
577 unset(self::$handlers[$idx]);
578 continue;
579 }
580
581 $profiles = $handler::getChildrenClassNames();
582
583 if(!empty($profiles))
584 {
585 self::$handlers = array_merge(self::$handlers, $profiles);
586 }
587 }
588
589 return true;
590 }
591
596 protected static function getHandlersClasses()
597 {
598 $result = array();
599
600 foreach(self::$handlersDirectories as $handlersDirectory)
601 {
602 $dirPath = $_SERVER['DOCUMENT_ROOT'].$handlersDirectory;
603
604 if(!Directory::isDirectoryExists($dirPath))
605 continue;
606
607 $dir = new Directory($_SERVER['DOCUMENT_ROOT'].$handlersDirectory);
608
609 foreach ($dir->getChildren() as $handler)
610 {
611 if (!$handler->isDirectory())
612 continue;
613
616 $handlerDir = $handler->getPath();
617 $handlerPath = $handlerDir.'/handler.php';
618
619 if(!File::isFileExists($handlerPath))
620 continue;
621
622 $handlerClassName = ucfirst($handler->getName().'Handler');
623 $fullClassName = '\Sale\Handlers\Delivery\\'.$handlerClassName;
624 $result[$fullClassName] = $handlersDirectory.$handler->getName().'/handler.php';
625 require_once($handlerPath);
626 }
627 }
628
629 return $result;
630 }
631
636 public static function getHandlersList()
637 {
638 if(self::$handlers === null)
639 self::initHandlers();
640
641 return self::$handlers;
642 }
643
650 public static function getRestHandlerList(): ?array
651 {
652 static $init = false;
653 if (!$init)
654 {
655 $init = true;
656 $restHandlerList = \Bitrix\Sale\Delivery\Rest\Internals\DeliveryRestHandlerTable::getList([
657 'select' => ['ID', 'NAME', 'CODE', 'SORT', 'DESCRIPTION', 'SETTINGS', 'PROFILES'],
658 ])->fetchAll();
659 foreach ($restHandlerList as $restHandler)
660 {
661 self::$restHandlers[$restHandler['CODE']] = $restHandler;
662 }
663 }
664
665 return self::$restHandlers;
666 }
667
676 public static function calculateDeliveryPrice(Shipment $shipment, $deliveryId = 0, $extraServices = array())
677 {
678 if($deliveryId <=0)
679 $deliveryId = $shipment->getDeliveryId();
680
681 $delivery = self::getObjectById($deliveryId);
682
683 if($delivery)
684 {
685 $result = $delivery->calculate($shipment, $extraServices);
686 }
687 else
688 {
689 $result = new CalculationResult();
690 $result->addError(new Error("Can't create delivery service object with id: \"".$deliveryId."\""));
691 }
692
693 return $result;
694 }
695
704 public static function getGroupId(string $name): int
705 {
706 $group = Table::getRow([
707 'select' => ['ID'],
708 'filter' => [
709 '=NAME' => $name,
710 '=CLASS_NAME' => '\Bitrix\Sale\Delivery\Services\Group',
711 ]
712 ]);
713
714 if ($group)
715 {
716 $result = $group["ID"];
717 }
718 else
719 {
720 $res = self::add([
721 'NAME' => $name,
722 'CLASS_NAME' => '\Bitrix\Sale\Delivery\Services\Group',
723 'ACTIVE' => 'Y',
724 'CURRENCY' => Option::get('sale', 'default_currency'),
725 ]);
726
727 if($res->isSuccess())
728 $result = (int)$res->getId();
729 else
730 throw new SystemException(implode("<br>\n",$res->getErrorMessages()));
731 }
732
733 return $result;
734 }
735
741 public static function getByParentId($parentId)
742 {
743 $result = array();
744 $srvList = self::getActiveList();
745
746 foreach($srvList as $id => $srv)
747 {
748 if($srv['PARENT_ID'] == $parentId)
749 {
750 $result[$srv['ID']] = $srv;
751 }
752 }
753
754 return $result;
755 }
756
761 public static function getLocationConnectorEntityName()
762 {
763 return 'Bitrix\Sale\Delivery\DeliveryLocation';
764 }
765
773 public static function add(array $fields)
774 {
775 self::initHandlers();
776
777 if(!empty($fields["CLASS_NAME"]))
778 {
780 $onBeforeAddResult = $fields["CLASS_NAME"]::onBeforeAdd($fields);
781 if (!$onBeforeAddResult->isSuccess())
782 {
783 return (new AddResult())->addErrors($onBeforeAddResult->getErrors());
784 }
785 }
786
787 $res = \Bitrix\Sale\Delivery\Services\Table::add($fields);
788
789 if($res->isSuccess())
790 {
791 if(!empty($fields["CLASS_NAME"]))
792 $fields["CLASS_NAME"]::onAfterAdd($res->getId(), $fields);
793
794 if(!empty($fields['CODE']))
795 self::setIdCodeCached($res->getId(), $fields['CODE']);
796 }
797
798 return $res;
799 }
800
804 public static function generateXmlId()
805 {
806 return uniqid('bx_');
807 }
808
817 public static function update($id, array $fields)
818 {
819 self::initHandlers();
820
821 if (!empty($fields["CLASS_NAME"]) && class_exists($fields["CLASS_NAME"]))
822 {
823 $fields["CLASS_NAME"]::onBeforeUpdate($id, $fields);
824 }
825
826 $res = \Bitrix\Sale\Delivery\Services\Table::update($id, $fields);
827
828 if ($res->isSuccess())
829 {
830 if (!empty($fields["CLASS_NAME"]) && class_exists($fields["CLASS_NAME"]))
831 {
832 $fields["CLASS_NAME"]::onAfterUpdate($res->getId(), $fields);
833 }
834
835 if (isset($fields['CODE']))
836 {
837 self::cleanIdCodeCached($id);
838 }
839
840 if (Loader::includeModule('pull'))
841 {
842 \CPullWatch::AddToStack(
843 'SALE_DELIVERY_SERVICE',
844 [
845 'module_id' => 'sale',
846 'command' => 'onDeliveryServiceSave',
847 'params' => [
848 'ID' => $id,
849 ]
850 ]
851 );
852 }
853 }
854
855 return $res;
856 }
857
868 public static function delete($id, bool $checkServiceUsage = true)
869 {
870 if ((int)$id <= 0)
871 {
872 throw new ArgumentNullException('id');
873 }
874
875 if ($checkServiceUsage)
876 {
877 $res = self::checkServiceUsage($id);
878 if (!$res->isSuccess())
879 {
880 return $res;
881 }
882 }
883
884 self::initHandlers();
885
886 $res = Table::getList(array(
887 'filter' => array(
888 'ID' => $id
889 ),
890 'select' => array('ID', 'CLASS_NAME', 'LOGOTIP')
891 ));
892
893 $className = '';
894 $logotip = 0;
895
896 if ($service = $res->fetch())
897 {
898 $className = $service['CLASS_NAME'];
899 $logotip = intval($service['LOGOTIP']);
900 }
901
902 $res = \Bitrix\Sale\Delivery\Services\Table::delete($id);
903
904 if ($res->isSuccess())
905 {
906 if (!empty($className) && class_exists($className))
907 {
908 $className::onAfterDelete($id);
909 }
910
911 self::deleteRelatedEntities($id, $checkServiceUsage);
912
913 if ($logotip > 0)
914 {
915 \CFile::Delete($logotip);
916 }
917 }
918
919 return $res;
920 }
921
929 public static function onGetBusinessValueConsumers()
930 {
931 static $result = null;
932
933 if($result !== null)
934 return $result;
935
936 $result = array();
937 $handlers = self::getHandlersList();
938 $consumers = array();
939
941 foreach($handlers as $handlerClassName)
942 {
943 $tmpCons = $handlerClassName::onGetBusinessValueConsumers();
944
946 if(!empty($tmpCons))
947 $consumers[$handlerClassName] = $tmpCons;
948 }
949
950 $res = Table::getList(array(
951 'filter' => array(
952 '=CLASS_NAME' => array_keys($consumers),
953 '=ACTIVE' => 'Y'
954 ),
955 'select' => array('ID', 'CLASS_NAME', 'NAME')
956 ));
957
958 while($dlv = $res->fetch())
959 {
960 $result['DELIVERY_'.$dlv['ID']] = $consumers[$dlv['CLASS_NAME']];
961 $result['DELIVERY_'.$dlv['ID']]['NAME'] = $dlv['NAME'];
962 }
963
964 return $result;
965 }
966
967 public static function onGetBusinessValueGroups()
968 {
969 $result = array(
970 'DELIVERY' => array('NAME' => Loc::getMessage('SALE_DLVR_MNGR_DLV_SRVS'), 'SORT' => 100),
971 );
972
973 $handlers = self::getHandlersList();
974
976 foreach($handlers as $handlerClassName)
977 $result = array_merge($result, $handlerClassName::onGetBusinessValueGroups());
978
979 return $result;
980 }
981
989 public static function setChildrenFieldsValues($id, array $fields)
990 {
991 if(empty($fields))
992 return 0;
993
994 $counter = 0;
995
996 $res = Table::getList(array(
997 'filter' => array('PARENT_ID' => $id),
998 'select' => array('ID')
999 ));
1000
1001 while($child = $res->fetch())
1002 {
1003 $ures = self::update($child['ID'], $fields);
1004
1005 if($ures->isSuccess())
1006 $counter++;
1007
1008 $counter += self::setChildrenFieldsValues($child['ID'], $fields);
1009 }
1010
1011 return $counter;
1012 }
1013
1018 public static function getIdByCode($code)
1019 {
1020 $result = self::getIdCodeCached($code, "code");
1021
1022 if($result !== false)
1023 return $result;
1024
1025 foreach(self::$cachedFields as $id => $srv)
1026 {
1027 if($srv['CODE'] == $code)
1028 {
1029 $result = $id;
1030 }
1031 }
1032
1033 if(intval($result) <= 0)
1034 {
1035 $res = Table::getList(array(
1036 'filter' => array(
1037 '=CODE' => $code
1038 )
1039 ));
1040
1041 if($handler = $res->fetch())
1042 {
1043 $result = $handler["ID"];
1044 self::$cachedFields[$handler["ID"]] = $handler;
1045 }
1046 }
1047
1048 $result = intval($result);
1049 self::setIdCodeCached($result, $code);
1050 return $result;
1051 }
1052
1058 public static function getCodeById($id)
1059 {
1060 $result = self::getIdCodeCached($id, "id");
1061
1062 if($result !== false)
1063 return $result;
1064
1065 $srv = self::getById($id);
1066
1067 $result = $srv['CODE'];
1068 self::setIdCodeCached($id, $result);
1069 return $result;
1070 }
1071
1078 protected static function getIdCodeCached($value, $type)
1079 {
1080 $result = false;
1081 $ttl = 315360000;
1082 $cacheId = "SALE_DELIVERY_ID_CODE_MAP_".($type == "id" ? "I" : "C")."_".$value;
1083 $cacheManager = \Bitrix\Main\Application::getInstance()->getManagedCache();
1084
1085 if($cacheManager->read($ttl, $cacheId))
1086 $result = $cacheManager->get($cacheId);
1087
1088 return $result;
1089 }
1090
1096 protected static function setIdCodeCached($id, $code)
1097 {
1098 $cacheManager = \Bitrix\Main\Application::getInstance()->getManagedCache();
1099 $cacheManager->set("SALE_DELIVERY_ID_CODE_MAP_I_".$id, $code);
1100 $cacheManager->set("SALE_DELIVERY_ID_CODE_MAP_C_".$code, $id);
1101 }
1102
1107 protected static function cleanIdCodeCached($id)
1108 {
1109 $cacheManager = \Bitrix\Main\Application::getInstance()->getManagedCache();
1110 $code = self::getIdCodeCached($id, "id");
1111 $cacheManager->clean("SALE_DELIVERY_ID_CODE_MAP_I_".$id);
1112
1113 if($code <> '')
1114 $cacheManager->clean("SALE_DELIVERY_ID_CODE_MAP_C_".$code);
1115 }
1116
1122 protected static function isDeliveryInShipments($deliveryId)
1123 {
1124 $res = ShipmentTable::getList(array(
1125 'filter' => array(
1126 "=DELIVERY_ID" => $deliveryId,
1127 "=SYSTEM" => "N"
1128 ),
1129 'select' => array("ID")
1130 ));
1131
1132 if($res->fetch())
1133 $result = true;
1134 else
1135 $result = false;
1136
1137 return $result;
1138 }
1139
1146 public static function checkServiceUsage($deliveryId)
1147 {
1148 $result = new Result();
1149
1150 if(self::isDeliveryInShipments($deliveryId))
1151 {
1152 $result->addError(new Error(Loc::getMessage('SALE_DLVR_MNGR_ERR_DEL_IN_SHPMNTS_EXIST')));
1153 }
1154 else
1155 {
1156 $dbRes = Table::getList(array(
1157 'filter' => array(
1158 "PARENT_ID" => $deliveryId
1159 ),
1160 'select' => array("ID")
1161 ));
1162
1163 while($child = $dbRes->fetch())
1164 {
1165 if(self::isDeliveryInShipments($child["ID"]))
1166 {
1167 $result->addError(new Error(Loc::getMessage('SALE_DLVR_MNGR_ERR_DEL_IN_SHPMNTS_EXIST_CHLD')));
1168 break;
1169 }
1170 }
1171 }
1172
1173 return $result;
1174 }
1175
1185 protected static function deleteRelatedEntities($deliveryId, bool $checkServiceUsage = true)
1186 {
1187 $con = \Bitrix\Main\Application::getConnection();
1188 $deliveryId = (int)$deliveryId;
1189
1190 $con->queryExecute("
1191 DELETE FROM b_sale_service_rstr
1192 WHERE
1193 SERVICE_ID = " . $deliveryId . "
1194 AND SERVICE_TYPE = " . (int)Restrictions\Manager::SERVICE_TYPE_SHIPMENT . "
1195 ");
1196 $con->queryExecute("DELETE FROM b_sale_delivery2location WHERE DELIVERY_ID=".$deliveryId);
1197 $con->queryExecute("DELETE FROM b_sale_delivery2paysystem WHERE DELIVERY_ID=".$deliveryId);
1198 $con->queryExecute("DELETE FROM b_sale_delivery_es WHERE DELIVERY_ID=".$deliveryId);
1199
1200 $dbRes = Table::getList(array(
1201 'filter' => array(
1202 "PARENT_ID" => $deliveryId
1203 ),
1204 'select' => array("ID")
1205 ));
1206
1207 while ($child = $dbRes->fetch())
1208 {
1209 self::delete($child["ID"], $checkServiceUsage);
1210 }
1211
1212 self::cleanIdCodeCached($deliveryId);
1213 return true;
1214 }
1215
1220 public static function getEmptyDeliveryServiceId()
1221 {
1222 self::initHandlers();
1223 return \Bitrix\Sale\Delivery\Services\EmptyDeliveryService::getEmptyDeliveryServiceId();
1224 }
1225
1237 public static function checkServiceRestriction($deliveryId, $checkParams, $restrictionClassName)
1238 {
1239 if(empty($deliveryId))
1240 throw new ArgumentNullException("deliveryId");
1241
1242 if(!is_array($deliveryId))
1243 $deliveryId = array($deliveryId);
1244
1245 $dbRstrRes = ServiceRestrictionTable::getList(array(
1246 'filter' => array(
1247 '=SERVICE_ID' => $deliveryId,
1248 '=SERVICE_TYPE' => Restrictions\Manager::SERVICE_TYPE_SHIPMENT,
1249 '=CLASS_NAME' => $restrictionClassName
1250 )
1251 ));
1252
1253 $tmp = array();
1255 $restriction = static::getRestrictionObject($restrictionClassName);
1256
1257 while($rstFields = $dbRstrRes->fetch())
1258 {
1259 $rstParams = is_array($rstFields["PARAMS"]) ? $rstFields["PARAMS"] : array();
1260 $tmp[$rstFields['SERVICE_ID']] = $restriction->check($checkParams, $rstParams, $rstFields['SERVICE_ID']);
1261 }
1262
1263 if(count($deliveryId) == 1)
1264 return current($tmp);
1265
1266 $result = array();
1267
1268 foreach($deliveryId as $id)
1269 if(!isset($tmp[$id]) || (isset($tmp[$id]) && $tmp[$id] == true))
1270 $result[] = $id;
1271
1272 return $result;
1273 }
1274
1281 public static function isDeliveryServiceClassValid($class)
1282 {
1283 if($class == '')
1284 return false;
1285
1286 self::initHandlers();
1287
1288 if(!class_exists($class))
1289 return false;
1290
1291 if(!is_subclass_of($class, 'Bitrix\Sale\Delivery\Services\Base'))
1292 return false;
1293
1294 return true;
1295 }
1296
1297 /*
1298 * Deprecated methods. Will be removed in future versions.
1299 */
1300
1304 public static function calculate(Shipment $shipment)
1305 {
1306 $delivery = self::getObjectById($shipment->getDeliveryId());
1307 return $delivery->calculate($shipment);
1308 }
1309
1313 public static function getRestrictionObject($className)
1314 {
1315 if(!class_exists($className))
1316 throw new SystemException("Can't find class: ".$className);
1317
1318 static $cache = array();
1319
1320 if(isset($cache[$className]))
1321 return $cache[$className];
1322
1323 $restriction = new $className;
1324
1325 if(!is_subclass_of($className, 'Bitrix\Sale\Services\Base\Restriction'))
1326 throw new SystemException('Object must be the instance of Bitrix\Sale\Services\Base\Restriction');
1327
1328 $cache[$className] = $restriction;
1329 return $restriction;
1330 }
1331
1335 public static function checkServiceRestrictions($deliveryId, Shipment $shipment, $restrictionsClassesToSkip = array())
1336 {
1337 return Restrictions\Manager::checkService($deliveryId, $shipment) == Restrictions\Manager::SEVERITY_NONE;
1338 }
1339
1343 public static function getServicesForShipment(Shipment $shipment)
1344 {
1345 return self::getRestrictedObjectsList($shipment);
1346 }
1347
1351 public static function isExistService($deliveryId)
1352 {
1353 return self::isServiceExist($deliveryId);
1354 }
1355
1359 public static function getActive()
1360 {
1361 return self::getActiveList();
1362 }
1363
1367 public static function getServicesBriefsForShipment(Shipment $shipment = null, array $skipChecks = array(), $getAll = false)
1368 {
1369 return self::getRestrictedList($shipment, Restrictions\Manager::MODE_CLIENT, $skipChecks);
1370 }
1371
1375 public static function createServiceObject(array $srvParams)
1376 {
1377 return self::createObject($srvParams);
1378 }
1379
1383 public static function getService($deliveryId)
1384 {
1385 return self::getObjectById($deliveryId);
1386 }
1387
1391 public static function getServiceByCode($serviceCode)
1392 {
1393 return self::getObjectByCode($serviceCode);
1394 }
1395
1399 public static function getHandlersClassNames()
1400 {
1401 return self::getHandlersList();
1402 }
1403
1407 public static function getRestrictionClassNames()
1408 {
1409 return Restrictions\Manager::getClassesList();
1410 }
1411
1415 public static function getRestrictionsByDeliveryId($deliveryId)
1416 {
1417 return Restrictions\Manager::getRestrictionsList($deliveryId);
1418 }
1419}
static isDirectoryExists($path)
static loadMessages($file)
Definition loc.php:64
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
static add(array $data)
Definition manager.php:333
static getObjectById($deliveryId)
Definition manager.php:438
static setChildrenFieldsValues($id, array $fields)
Definition manager.php:989
static getRestrictedObjectsList(Shipment $shipment, $restrictionMode=Restrictions\Manager::MODE_CLIENT)
Definition manager.php:92
static getRestrictionObject($className)
Definition manager.php:1313
static getList(array $params=array())
Definition manager.php:82
static calculate(Shipment $shipment)
Definition manager.php:1304
static deleteRelatedEntities($deliveryId, bool $checkServiceUsage=true)
Definition manager.php:1185
static createServiceObject(array $srvParams)
Definition manager.php:1375
static getIdCodeCached($value, $type)
Definition manager.php:1078
static getRestrictedList(Shipment $shipment=null, $restrictionMode, array $skipChecks=array())
Definition manager.php:323
static calculateDeliveryPrice(Shipment $shipment, $deliveryId=0, $extraServices=array())
Definition manager.php:676
static getServicesBriefsForShipment(Shipment $shipment=null, array $skipChecks=array(), $getAll=false)
Definition manager.php:1367
static getGroupId(string $name)
Definition manager.php:704
static createObject(array $srvParams)
Definition manager.php:367
static checkServiceUsage($deliveryId)
Definition manager.php:1146
static getObjectByCode($serviceCode)
Definition manager.php:458
static getServiceByCode($serviceCode)
Definition manager.php:1391
static isServiceExist($deliveryId)
Definition manager.php:131
static getActiveList($calculatingOnly=false, $restrictedIds=null)
Definition manager.php:147
static checkServiceRestrictions($deliveryId, Shipment $shipment, $restrictionsClassesToSkip=array())
Definition manager.php:1335
static isDeliveryInShipments($deliveryId)
Definition manager.php:1122
static getServicesForShipment(Shipment $shipment)
Definition manager.php:1343
static update($id, array $fields)
Definition manager.php:817
static getRestrictionsByDeliveryId($deliveryId)
Definition manager.php:1415
static getPooledObject(array $fields)
Definition manager.php:424