Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
discount.php
1<?php
9
10use Bitrix\Main,
18
19Loc::loadMessages(__FILE__);
20
79class DiscountTable extends Main\Entity\DataManager
80{
81 const VERSION_OLD = 0x0001;
82 const VERSION_NEW = 0x0002;
83 const VERSION_15 = 0x0003;
84
87
88 protected static $deleteCoupons = false;
89
95 public static function getTableName()
96 {
97 return 'b_sale_discount';
98 }
99
105 public static function getMap()
106 {
107 return array(
108 'ID' => new Main\Entity\IntegerField('ID', array(
109 'primary' => true,
110 'autocomplete' => true,
111 'title' => Loc::getMessage('DISCOUNT_ENTITY_ID_FIELD')
112 )),
113 'XML_ID' => new Main\Entity\StringField('XML_ID', array(
114 'validation' => array(__CLASS__, 'validateXmlId'),
115 'title' => Loc::getMessage('DISCOUNT_ENTITY_XML_ID_FIELD')
116 )),
117 'LID' => new Main\Entity\StringField('LID', array(
118 'required' => true,
119 'validation' => array(__CLASS__, 'validateLid'),
120 'title' => Loc::getMessage('DISCOUNT_ENTITY_LID_FIELD')
121 )),
122 'NAME' => new Main\Entity\StringField('NAME', array(
123 'validation' => array(__CLASS__, 'validateName'),
124 'title' => Loc::getMessage('DISCOUNT_ENTITY_NAME_FIELD')
125 )),
126 'PRICE_FROM' => new Main\Entity\FloatField('PRICE_FROM', array()),
127 'PRICE_TO' => new Main\Entity\FloatField('PRICE_TO', array()),
128 'CURRENCY' => new Main\Entity\StringField('CURRENCY', array(
129 'validation' => array(__CLASS__, 'validateCurrency'),
130 'title' => Loc::getMessage('DISCOUNT_ENTITY_CURRENCY_FIELD')
131 )),
132 'DISCOUNT_VALUE' => new Main\Entity\FloatField('DISCOUNT_VALUE', array()),
133 'DISCOUNT_TYPE' => new Main\Entity\StringField('DISCOUNT_TYPE', array(
134 'default_value' => 'P',
135 'validation' => array(__CLASS__, 'validateDiscountType')
136 )),
137 'ACTIVE' => new Main\Entity\BooleanField('ACTIVE', array(
138 'values' => array('N', 'Y'),
139 'default_value' => 'Y',
140 'title' => Loc::getMessage('DISCOUNT_ENTITY_ACTIVE_FIELD')
141 )),
142 'SORT' => new Main\Entity\IntegerField('SORT', array(
143 'title' => Loc::getMessage('DISCOUNT_ENTITY_SORT_FIELD')
144 )),
145 'ACTIVE_FROM' => new Main\Entity\DatetimeField('ACTIVE_FROM', array(
146 'default_value' => null,
147 'title' => Loc::getMessage('DISCOUNT_ENTITY_ACTIVE_FROM_FIELD')
148 )),
149 'ACTIVE_TO' => new Main\Entity\DatetimeField('ACTIVE_TO', array(
150 'default_value' => null,
151 'title' => Loc::getMessage('DISCOUNT_ENTITY_ACTIVE_TO_FIELD')
152 )),
153 'TIMESTAMP_X' => new Main\Entity\DatetimeField('TIMESTAMP_X', array(
154 'default_value' => function(){ return new Main\Type\DateTime(); },
155 'title' => Loc::getMessage('DISCOUNT_ENTITY_TIMESTAMP_X_FIELD')
156 )),
157 'MODIFIED_BY' => new Main\Entity\IntegerField('MODIFIED_BY', array(
158 'default_value' => null,
159 'title' => Loc::getMessage('DISCOUNT_ENTITY_MODIFIED_BY_FIELD')
160 )),
161 'DATE_CREATE' => new Main\Entity\DatetimeField('DATE_CREATE', array(
162 'default_value' => function(){ return new Main\Type\DateTime(); },
163 'title' => Loc::getMessage('DISCOUNT_ENTITY_DATE_CREATE_FIELD')
164 )),
165 'CREATED_BY' => new Main\Entity\IntegerField('CREATED_BY', array(
166 'default_value' => null,
167 'title' => Loc::getMessage('DISCOUNT_ENTITY_CREATED_BY_FIELD')
168 )),
169 'PRIORITY' => new Main\Entity\IntegerField('PRIORITY', array(
170 'default_value' => 1,
171 'title' => Loc::getMessage('DISCOUNT_ENTITY_PRIORITY_FIELD')
172 )),
173 'LAST_DISCOUNT' => new Main\Entity\BooleanField('LAST_DISCOUNT', array(
174 'values' => array('N', 'Y'),
175 'default_value' => 'Y',
176 'title' => Loc::getMessage('DISCOUNT_ENTITY_LAST_DISCOUNT_FIELD')
177 )),
178 'LAST_LEVEL_DISCOUNT' => new Main\Entity\BooleanField('LAST_LEVEL_DISCOUNT', array(
179 'values' => array('N', 'Y'),
180 'default_value' => 'N',
181 )),
182 'VERSION' => new Main\Entity\EnumField('VERSION', array(
183 'values' => array(self::VERSION_OLD, self::VERSION_NEW, self::VERSION_15),
184 'default_value' => self::VERSION_15,
185 'title' => Loc::getMessage('DISCOUNT_ENTITY_VERSION_FIELD')
186 )),
187 'CONDITIONS_LIST' => new Main\Entity\TextField('CONDITIONS_LIST', array(
188 'serialized' => true,
189 'column_name' => 'CONDITIONS',
190 'title' => Loc::getMessage('DISCOUNT_ENTITY_CONDITIONS_LIST_FIELD')
191 )),
192 'CONDITIONS' => new Main\Entity\ExpressionField('CONDITIONS', '%s', 'CONDITIONS_LIST'),
193 'UNPACK' => new Main\Entity\TextField('UNPACK', array()),
194 'ACTIONS_LIST' => new Main\Entity\TextField('ACTIONS_LIST', array(
195 'serialized' => true,
196 'column_name' => 'ACTIONS',
197 'title' => Loc::getMessage('DISCOUNT_ENTITY_ACTIONS_LIST_FIELD')
198 )),
199 'ACTIONS' => new Main\Entity\ExpressionField('ACTIONS', '%s', 'ACTIONS_LIST'),
200 'APPLICATION' => new Main\Entity\TextField('APPLICATION', array()),
201 'PREDICTION_TEXT' => new Main\Entity\TextField('PREDICTION_TEXT', array()),
202 'PREDICTIONS_APP' => new Main\Entity\TextField('PREDICTIONS_APP', array()),
203 'PREDICTIONS_LIST' => new Main\Entity\TextField('PREDICTIONS_LIST', array(
204 'serialized' => true,
205 'column_name' => 'PREDICTIONS',
206 )),
207 'PREDICTIONS' => new Main\Entity\ExpressionField('PREDICTIONS', '%s', 'PREDICTIONS_LIST'),
208 'USE_COUPONS' => new Main\Entity\BooleanField('USE_COUPONS', array(
209 'values' => array('N', 'Y'),
210 'default_value' => 'N',
211 'title' => Loc::getMessage('DISCOUNT_ENTITY_USE_COUPONS_FIELD')
212 )),
213 'EXECUTE_MODULE' => new Main\Entity\StringField('EXECUTE_MODULE', array(
214 'validation' => array(__CLASS__, 'validateExecuteModule'),
215 'title' => Loc::getMessage('DISCOUNT_ENTITY_EXECUTE_MODULE_FIELD')
216 )),
217 'EXECUTE_MODE' => new Main\Entity\IntegerField('EXECUTE_MODE', array(
218 'default_value' => self::EXECUTE_MODE_GENERAL,
219 )),
220 'HAS_INDEX' => new Main\Entity\BooleanField('HAS_INDEX', array(
221 'values' => array('N', 'Y'),
222 'default_value' => 'N',
223 )),
224 'PRESET_ID' => new Main\Entity\StringField('PRESET_ID', array(
225 'validation' => array(__CLASS__, 'validatePresetId'),
226 )),
227 'SHORT_DESCRIPTION_STRUCTURE' => new Main\Entity\TextField('SHORT_DESCRIPTION_STRUCTURE', array(
228 'serialized' => true,
229 'column_name' => 'SHORT_DESCRIPTION',
230 )),
231 'SHORT_DESCRIPTION' => new Main\Entity\ExpressionField('SHORT_DESCRIPTION', '%s', 'SHORT_DESCRIPTION_STRUCTURE'),
232 'CREATED_BY_USER' => new Main\Entity\ReferenceField(
233 'CREATED_BY_USER',
234 'Bitrix\Main\User',
235 array('=this.CREATED_BY' => 'ref.ID'),
236 array('join_type' => 'LEFT')
237 ),
238 'MODIFIED_BY_USER' => new Main\Entity\ReferenceField(
239 'MODIFIED_BY_USER',
240 'Bitrix\Main\User',
241 array('=this.MODIFIED_BY' => 'ref.ID'),
242 array('join_type' => 'LEFT')
243 ),
244 'COUPON' => new Main\Entity\ReferenceField(
245 'COUPON',
246 'Bitrix\Sale\Internals\DiscountCoupon',
247 array('=this.ID' => 'ref.DISCOUNT_ID'),
248 array('join_type' => 'LEFT')
249 ),
250 'DISCOUNT_ENTITY' => new Main\Entity\ReferenceField(
251 'DISCOUNT_ENTITY',
252 'Bitrix\Sale\Internals\DiscountEntities',
253 array('=this.ID' => 'ref.DISCOUNT_ID'),
254 array('join_type' => 'LEFT')
255 )
256 );
257 }
263 public static function validateXmlId()
264 {
265 return array(
266 new Main\Entity\Validator\Length(null, 255),
267 );
268 }
274 public static function validateLid()
275 {
276 return array(
277 new Main\Entity\Validator\Length(null, 2),
278 );
279 }
285 public static function validateName()
286 {
287 return array(
288 new Main\Entity\Validator\Length(null, 255),
289 );
290 }
296 public static function validateCurrency()
297 {
298 return array(
299 new Main\Entity\Validator\Length(null, 3),
300 );
301 }
307 public static function validateDiscountType()
308 {
309 return array(
310 new Main\Entity\Validator\Length(null, 1),
311 );
312 }
313
319 public static function validateExecuteModule()
320 {
321 return array(
322 new Main\Entity\Validator\Length(null, 50),
323 );
324 }
325
331 public static function validatePresetId()
332 {
333 return array(
334 new Main\Entity\Validator\Length(null, 255),
335 );
336 }
337
344 public static function onBeforeAdd(Main\Entity\Event $event)
345 {
346 $result = new Main\Entity\EventResult;
347 $fields = $event->getParameter('fields');
348
349 $modifyFieldList = array(
350 'DISCOUNT_VALUE' => 0,
351 'DISCOUNT_TYPE' => 'P',
352 );
353 if (isset($fields['LID']))
354 $modifyFieldList['CURRENCY'] = SiteCurrencyTable::getSiteCurrency($fields['LID']);
355 self::setUserID($modifyFieldList, $fields, array('CREATED_BY', 'MODIFIED_BY'));
356 self::setTimestamp($modifyFieldList, $fields, array('DATE_CREATE', 'TIMESTAMP_X'));
357 self::setShortDescription($modifyFieldList, $fields);
358
359 self::copyOldFields($modifyFieldList, $fields);
360 $result->unsetField('CONDITIONS');
361 $result->unsetField('ACTIONS');
362
363 if (!empty($modifyFieldList))
364 $result->modifyFields($modifyFieldList);
365 unset($modifyFieldList);
366
367 return $result;
368 }
369
376 public static function onAfterAdd(Main\Entity\Event $event)
377 {
378 $id = $event->getParameter('primary');
379 $fields = $event->getParameter('fields');
380 if (isset($fields['ACTIONS_LIST']))
381 {
382 if (!is_array($fields['ACTIONS_LIST']) && \CheckSerializedData($fields['ACTIONS_LIST']))
383 $fields['ACTIONS_LIST'] = unserialize($fields['ACTIONS_LIST'], ['allowed_classes' => false]);
384 if (is_array($fields['ACTIONS_LIST']))
385 {
386 $giftManager = Gift\Manager::getInstance();
387 if ($giftManager->isContainGiftAction($fields))
388 {
389 if (!$giftManager->existsDiscountsWithGift())
390 $giftManager->enableExistenceDiscountsWithGift();
391 Gift\RelatedDataTable::fillByDiscount($fields + $id);
392 }
393 unset($giftManager);
394 }
395 }
396
397 $specificFields = array(
398 'EXECUTE_MODE' => static::resolveExecuteModeByDiscountId($id),
399 );
400
401 if (isset($fields['CONDITIONS_LIST']))
402 {
403 $specificFields['HAS_INDEX'] = Index\Manager::getInstance()->indexDiscount($fields + $id) ? 'Y' : 'N';
404 }
405
406 static::updateSpecificFields($id['ID'], $specificFields);
407 static::updateConfigurationIfNeeded($fields, $specificFields);
408
409 self::dropIblockCache();
410 }
411
419 protected static function resolveExecuteModeByDiscountId($discountId)
420 {
421 $fields = static::getRowById($discountId);
422
423 if (empty($fields))
424 {
425 return self::EXECUTE_MODE_GENERAL;
426 }
427
428 return Analyzer::getInstance()->canCalculateSeparately($fields) ?
429 self::EXECUTE_MODE_SEPARATELY : self::EXECUTE_MODE_GENERAL;
430 }
431
439 protected static function updateConfigurationIfNeeded(array $fields, array $specificFields)
440 {
441 if (
442 isset($specificFields['EXECUTE_MODE']) &&
443 $specificFields['EXECUTE_MODE'] == self::EXECUTE_MODE_GENERAL &&
444 isset($fields['ACTIVE']) &&
445 $fields['ACTIVE'] === 'Y'
446 )
447 {
448 Config\Option::set('sale', 'discount_separately_calculation', 'N');
449 }
450 else
451 {
452 $canCalculateSeparately = Analyzer::getInstance()->canCalculateSeparatelyAllDiscount();
453 Config\Option::set('sale', 'discount_separately_calculation', $canCalculateSeparately? 'Y' : 'N');
454 }
455 }
456
462 protected static function updateSpecificFields($id, array $fields)
463 {
464 if (!$fields)
465 {
466 return;
467 }
468
469 $connection = Main\Application::getConnection();
470 $sqlHelper = $connection->getSqlHelper();
471
472 $tableName = static::getTableName();
473 $update = $sqlHelper->prepareUpdate($tableName, $fields);
474
475 $connection->queryExecute(
476 "UPDATE {$tableName} SET {$update[0]} WHERE ID={$id}"
477 );
478 }
479
486 public static function onBeforeUpdate(Main\Entity\Event $event)
487 {
488 $result = new Main\Entity\EventResult;
489 $fields = $event->getParameter('fields');
490
491 $modifyFieldList = array();
492 self::setUserID($modifyFieldList, $fields, array('MODIFIED_BY'));
493 self::setTimestamp($modifyFieldList, $fields, array('TIMESTAMP_X'));
494 self::setShortDescription($modifyFieldList, $fields);
495
496 self::copyOldFields($modifyFieldList, $fields);
497 $result->unsetField('CONDITIONS');
498 $result->unsetField('ACTIONS');
499
500 if (!empty($modifyFieldList))
501 $result->modifyFields($modifyFieldList);
502 unset($modifyFieldList);
503
504 return $result;
505 }
506
513 public static function onAfterUpdate(Main\Entity\Event $event)
514 {
515 $id = $event->getParameter('primary');
516 $fields = $event->getParameter('fields');
517 if (isset($fields['ACTIVE']))
518 DiscountGroupTable::changeActiveByDiscount($id['ID'], $fields['ACTIVE']);
519
520 if (isset($fields['ACTIONS_LIST']))
521 {
522 if (!is_array($fields['ACTIONS_LIST']) && \CheckSerializedData($fields['ACTIONS_LIST']))
523 $fields['ACTIONS_LIST'] = unserialize($fields['ACTIONS_LIST'], ['allowed_classes' => false]);
524 if (is_array($fields['ACTIONS_LIST']))
525 {
526 Gift\RelatedDataTable::deleteByDiscount($id['ID']);
527 $giftManager = Gift\Manager::getInstance();
528 if ($giftManager->isContainGiftAction($fields))
529 {
530 if (!$giftManager->existsDiscountsWithGift())
531 $giftManager->enableExistenceDiscountsWithGift();
532 Gift\RelatedDataTable::fillByDiscount($fields + $id);
533 }
534 }
535 }
536
537 $specificFields = array(
538 'EXECUTE_MODE' => static::resolveExecuteModeByDiscountId($id),
539 );
540
541 if (isset($fields['CONDITIONS_LIST']))
542 {
543 $specificFields['HAS_INDEX'] = Index\Manager::getInstance()->indexDiscount($fields + $id) ? 'Y' : 'N';
544 }
545
546 static::updateSpecificFields($id['ID'], $specificFields);
547 static::updateConfigurationIfNeeded($fields, $specificFields);
548
549 self::dropIblockCache();
550 }
551
558 public static function onDelete(Main\Entity\Event $event)
559 {
560 $id = $event->getParameter('primary');
561 $id = $id['ID'];
562 $discount = self::getList(array(
563 'select' => array('ID', 'USE_COUPONS'),
564 'filter' => array('=ID' => $id)
565 ))->fetch();
566 if (!empty($discount))
567 {
568 if ((string)$discount['USE_COUPONS'] === 'Y')
569 self::$deleteCoupons = $discount['ID'];
570 }
571 unset($discount, $id);
572 }
573
580 public static function onAfterDelete(Main\Entity\Event $event)
581 {
582 $id = $event->getParameter('primary');
583 $id = $id['ID'];
586 DiscountGroupTable::deleteByDiscount($id);
587 if (self::$deleteCoupons !== false)
588 {
589 DiscountCouponTable::deleteByDiscount(self::$deleteCoupons);
590 self::$deleteCoupons = false;
591 }
592 Gift\RelatedDataTable::deleteByDiscount($id);
593 Index\Manager::getInstance()->dropIndex($id);
594
595 self::dropIblockCache();
596
597 unset($id);
598 }
599
607 public static function setUseCoupons($discountList, $use)
608 {
609 if (!is_array($discountList))
610 $discountList = array($discountList);
611 $use = (string)$use;
612 if ($use !== 'Y' && $use !== 'N')
613 return;
614 Main\Type\Collection::normalizeArrayValuesByInt($discountList);
615 if (empty($discountList))
616 return;
618 $helper = $conn->getSqlHelper();
619 $conn->queryExecute(
620 'update '.$helper->quote(self::getTableName()).
621 ' set '.$helper->quote('USE_COUPONS').' = \''.$use.'\' where '.
622 $helper->quote('ID').' in ('.implode(',', $discountList).')'
623 );
624 unset($helper, $conn);
625
626 if($use === 'Y')
627 {
628 Gift\RelatedDataTable::deleteByDiscounts($discountList);
629 }
630 }
631
638 public static function setAllUseCoupons($use)
639 {
640 $use = (string)$use;
641 if ($use !== 'Y' && $use !== 'N')
642 return;
643 $conn = Application::getConnection();
644 $helper = $conn->getSqlHelper();
645 $conn->queryExecute(
646 'update '.$helper->quote(self::getTableName()).' set '.$helper->quote('USE_COUPONS').' = \''.$use.'\''
647 );
648 unset($helper, $conn);
649 }
650
659 protected static function setUserID(&$result, $data, $keys)
660 {
661 static $currentUserID = false;
662 if ($currentUserID === false)
663 {
664 global $USER;
665 $currentUserID = (isset($USER) && $USER instanceof \CUser ? (int)$USER->getID() : null);
666 }
667 foreach ($keys as $oneKey)
668 {
669 $setField = true;
670 if (array_key_exists($oneKey, $data))
671 $setField = ($data[$oneKey] !== null && (int)$data[$oneKey] <= 0);
672
673 if ($setField)
674 $result[$oneKey] = $currentUserID;
675 }
676 unset($oneKey);
677 }
678
679 protected static function setShortDescription(&$result, array $data)
680 {
681 if (!empty($data['SHORT_DESCRIPTION_STRUCTURE']))
682 return;
683 if (empty($data['ACTIONS']) && empty($data['ACTIONS_LIST']))
684 return;
685
686 $actionConfiguration = Actions::getActionConfiguration($data);
687 if (!$actionConfiguration)
688 return;
689
690 $result['SHORT_DESCRIPTION_STRUCTURE'] = $actionConfiguration;
691 }
692
701 protected static function setTimestamp(&$result, $data, $keys)
702 {
703 foreach ($keys as $oneKey)
704 {
705 $setField = true;
706 if (array_key_exists($oneKey, $data))
707 $setField = ($data[$oneKey] !== null && !is_object($data[$oneKey]));
708
709 if ($setField)
710 $result[$oneKey] = new Main\Type\DateTime();
711 }
712 unset($oneKey);
713 }
714
722 protected static function copyOldFields(&$result, $data)
723 {
724 if (!isset($data['CONDITIONS_LIST']) && isset($data['CONDITIONS']))
725 $result['CONDITIONS_LIST'] = (is_array($data['CONDITIONS']) ? $data['CONDITIONS'] : unserialize($data['CONDITIONS'], ['allowed_classes' => false]));
726
727 if (!isset($data['ACTIONS_LIST']) && isset($data['ACTIONS']))
728 $result['ACTIONS_LIST'] = (is_array($data['ACTIONS']) ? $data['ACTIONS'] : unserialize($data['ACTIONS'], ['allowed_classes' => false]));
729 }
730
737 private static function dropIblockCache()
738 {
739 if (
740 !Main\ModuleManager::isModuleInstalled('bitrix24')
741 || !Main\Loader::includeModule('crm')
742 || !Main\Loader::includeModule('iblock')
743 )
744 return;
745
746 $iblockId = \CCrmCatalog::GetDefaultID();
747 if ($iblockId > 0)
748 \CIBlock::clearIblockTagCache($iblockId);
749 unset($iblockId);
750 }
751}
static update($primary, array $data)
Definition discount.php:377
static getConnection($name="")
static loadMessages($file)
Definition loc.php:64
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
static getActionConfiguration(array $discount)
Definition actions.php:1239
static updateSpecificFields($id, array $fields)
Definition discount.php:462
static setUseCoupons($discountList, $use)
Definition discount.php:607
static setUserID(&$result, $data, $keys)
Definition discount.php:659
static onBeforeAdd(Main\Entity\Event $event)
Definition discount.php:344
static onAfterDelete(Main\Entity\Event $event)
Definition discount.php:580
static copyOldFields(&$result, $data)
Definition discount.php:722
static onDelete(Main\Entity\Event $event)
Definition discount.php:558
static setTimestamp(&$result, $data, $keys)
Definition discount.php:701
static onAfterUpdate(Main\Entity\Event $event)
Definition discount.php:513
static updateConfigurationIfNeeded(array $fields, array $specificFields)
Definition discount.php:439
static onBeforeUpdate(Main\Entity\Event $event)
Definition discount.php:486
static onAfterAdd(Main\Entity\Event $event)
Definition discount.php:376
static resolveExecuteModeByDiscountId($discountId)
Definition discount.php:419
static setShortDescription(&$result, array $data)
Definition discount.php:679