Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
discountcoupon.php
1<?php
3
8
9Loc::loadMessages(__FILE__);
10
53class DiscountCouponTable extends Main\Entity\DataManager
54{
55 const TYPE_UNKNOWN = 0x0000;
56 const TYPE_BASKET_ROW = 0x0001;
57 const TYPE_ONE_ORDER = 0x0002;
58 const TYPE_MULTI_ORDER = 0x0004;
59 const TYPE_ARCHIVED = 0x0008;
60
61 const EVENT_ON_GENERATE_COUPON = 'onGenerateCoupon';
62 const EVENT_ON_AFTER_DELETE_DISCOUNT = 'onAfterDeleteDiscountCoupons';
63
64 protected static $discountCheckList = array();
65 protected static $checkDiscountCouponsUse = 0;
66
72 public static function getTableName()
73 {
74 return 'b_sale_discount_coupon';
75 }
76
82 public static function getMap()
83 {
84 return array(
85 'ID' => new Main\Entity\IntegerField('ID', array(
86 'primary' => true,
87 'autocomplete' => true,
88 'title' => Loc::getMessage('DISCOUNT_COUPON_ENTITY_ID_FIELD')
89 )),
90 'DISCOUNT_ID' => new Main\Entity\IntegerField('DISCOUNT_ID', array(
91 'required' => true,
92 'validation' => array(__CLASS__, 'validateDiscountId'),
93 'title' => Loc::getMessage('DISCOUNT_COUPON_ENTITY_DISCOUNT_ID_FIELD')
94 )),
95 'ACTIVE' => new Main\Entity\BooleanField('ACTIVE', array(
96 'values' => array('N', 'Y'),
97 'default_value' => 'Y',
98 'title' => Loc::getMessage('DISCOUNT_COUPON_ENTITY_ACTIVE_FIELD')
99 )),
100 'ACTIVE_FROM' => new Main\Entity\DatetimeField('ACTIVE_FROM', array(
101 'default_value' => null,
102 'title' => Loc::getMessage('DISCOUNT_COUPON_ENTITY_ACTIVE_FROM_FIELD')
103 )),
104 'ACTIVE_TO' => new Main\Entity\DatetimeField('ACTIVE_TO', array(
105 'default_value' => null,
106 'title' => Loc::getMessage('DISCOUNT_COUPON_ENTITY_ACTIVE_TO_FIELD')
107 )),
108 'COUPON' => new Main\Entity\StringField('COUPON', array(
109 'required' => true,
110 'validation' => array(__CLASS__, 'validateCoupon'),
111 'title' => Loc::getMessage('DISCOUNT_COUPON_ENTITY_COUPON_FIELD')
112 )),
113 'TYPE' => new Main\Entity\IntegerField('TYPE', array(
114 'validation' => array(__CLASS__, 'validateType'),
115 'title' => Loc::getMessage('DISCOUNT_COUPON_ENTITY_TYPE_FIELD')
116 )),
117 'MAX_USE' => new Main\Entity\IntegerField('MAX_USE', array(
118 'default_value' => 0,
119 'title' => Loc::getMessage('DISCOUNT_COUPON_ENTITY_MAX_USE_FIELD')
120 )),
121 'USE_COUNT' => new Main\Entity\IntegerField('USE_COUNT', array(
122 'default_value' => 0,
123 'title' => Loc::getMessage('DISCOUNT_COUPON_ENTITY_USE_COUNT_FIELD')
124 )),
125 'USER_ID' => new Main\Entity\IntegerField('USER_ID', array(
126 'default_value' => 0,
127 'title' => Loc::getMessage('DISCOUNT_COUPON_ENTITY_USER_ID_FIELD')
128 )),
129 'DATE_APPLY' => new Main\Entity\DatetimeField('DATE_APPLY', array(
130 'default_value' => null,
131 'title' => Loc::getMessage('DISCOUNT_COUPON_ENTITY_DATE_APPLY_FIELD')
132 )),
133 'TIMESTAMP_X' => new Main\Entity\DatetimeField('TIMESTAMP_X', array(
134 'default_value' => function(){ return new Main\Type\DateTime(); },
135 'title' => Loc::getMessage('DISCOUNT_COUPON_ENTITY_TIMESTAMP_X_FIELD')
136 )),
137 'MODIFIED_BY' => new Main\Entity\IntegerField('MODIFIED_BY', array(
138 'default_value' => null,
139 'title' => Loc::getMessage('DISCOUNT_COUPON_ENTITY_MODIFIED_BY_FIELD')
140 )),
141 'DATE_CREATE' => new Main\Entity\DatetimeField('DATE_CREATE', array(
142 'default_value' => function(){ return new Main\Type\DateTime(); },
143 'title' => Loc::getMessage('DISCOUNT_COUPON_ENTITY_DATE_CREATE_FIELD')
144 )),
145 'CREATED_BY' => new Main\Entity\IntegerField('CREATED_BY', array(
146 'default_value' => null,
147 'title' => Loc::getMessage('DISCOUNT_COUPON_ENTITY_CREATED_BY_FIELD')
148 )),
149 'DESCRIPTION' => new Main\Entity\TextField('DESCRIPTION', array(
150 'default_value' => null,
151 'title' => Loc::getMessage('DISCOUNT_COUPON_ENTITY_DESCRIPTION_FIELD')
152 )),
153 'CREATED_BY_USER' => new Main\Entity\ReferenceField(
154 'CREATED_BY_USER',
155 'Bitrix\Main\User',
156 array('=this.CREATED_BY' => 'ref.ID'),
157 array('join_type' => 'LEFT')
158 ),
159 'MODIFIED_BY_USER' => new Main\Entity\ReferenceField(
160 'MODIFIED_BY_USER',
161 'Bitrix\Main\User',
162 array('=this.MODIFIED_BY' => 'ref.ID'),
163 array('join_type' => 'LEFT')
164 ),
165 'DISCOUNT' => new Main\Entity\ReferenceField(
166 'DISCOUNT',
167 'Bitrix\Sale\Internals\Discount',
168 array('=this.DISCOUNT_ID' => 'ref.ID'),
169 array('join_type' => 'LEFT')
170 )
171 );
172 }
173
179 public static function validateDiscountId()
180 {
181 return array(
182 array(__CLASS__, 'checkDiscountId')
183 );
184 }
185
191 public static function validateCoupon()
192 {
193 return array(
194 new Main\Entity\Validator\Length(null, 32),
195 array(__CLASS__, 'checkCoupon')
196 );
197 }
198
204 public static function validateType()
205 {
206 return array(
207 array(__CLASS__, 'checkType')
208 );
209 }
210
220 public static function checkDiscountId($value, $primary, array $row, Main\Entity\Field $field)
221 {
222 if ((int)$value <= 0)
223 return Loc::getMessage('DISCOUNT_COUPON_VALIDATOR_DISCOUNT_ID');
224
225 return true;
226 }
227
237 public static function checkType($value, $primary, array $row, Main\Entity\Field $field)
238 {
239 if (
240 $value == self::TYPE_BASKET_ROW
241 || $value == self::TYPE_ONE_ORDER
242 || $value == self::TYPE_MULTI_ORDER
243 )
244 return true;
245
246 return Loc::getMessage('DISCOUNT_COUPON_VALIDATOR_TYPE');
247 }
248
258 public static function checkCoupon($value, $primary, array $row, Main\Entity\Field $field)
259 {
260 $value = trim((string)$value);
261 if ($value == '')
262 return Loc::getMessage('DISCOUNT_COUPON_VALIDATOR_COUPON_EMPTY');
263
264 $existCoupon = Sale\DiscountCouponsManager::isExist($value);
265 if (!empty($existCoupon))
266 {
267 $currentId = (int)(is_array($primary) ? $primary['ID'] : $primary);
268 if ($existCoupon['MODULE'] != 'sale' || $currentId != $existCoupon['ID'])
269 return Loc::getMessage('DISCOUNT_COUPON_VALIDATOR_COUPON_EXIST');
270 }
271 return true;
272 }
273
280 public static function onBeforeAdd(Main\Entity\Event $event)
281 {
282 $result = new Main\Entity\EventResult;
283 $data = $event->getParameter('fields');
284
285 $modifyFieldList = array();
286 self::setUserID($modifyFieldList, $data, array('CREATED_BY', 'MODIFIED_BY'));
287 self::setTimestamp($modifyFieldList, $data, array('DATE_CREATE', 'TIMESTAMP_X'));
288
289 if (!empty($modifyFieldList))
290 $result->modifyFields($modifyFieldList);
291 unset($modifyFieldList, $data);
292
293 return $result;
294 }
295
302 public static function onAfterAdd(Main\Entity\Event $event)
303 {
304 if (!self::isCheckedCouponsUse())
305 return;
306 $data = $event->getParameter('fields');
307 $id = (int)$data['DISCOUNT_ID'];
308 self::$discountCheckList[$id] = $id;
309 unset($id, $data);
310 self::updateUseCoupons();
311 }
312
319 public static function onBeforeUpdate(Main\Entity\Event $event)
320 {
321 $result = new Main\Entity\EventResult;
322 $data = $event->getParameter('fields');
323
324 $modifyFieldList = array();
325 self::setUserID($modifyFieldList, $data, array('MODIFIED_BY'));
326 self::setTimestamp($modifyFieldList, $data, array('TIMESTAMP_X'));
327
328 if (!empty($modifyFieldList))
329 $result->modifyFields($modifyFieldList);
330 unset($modifyFieldList, $data);
331
332 return $result;
333 }
334
341 public static function onUpdate(Main\Entity\Event $event)
342 {
343 if (!self::isCheckedCouponsUse())
344 return;
345 $data = $event->getParameter('fields');
346 if (isset($data['DISCOUNT_ID']))
347 {
348 $data['DISCOUNT_ID'] = (int)$data['DISCOUNT_ID'];
349 $coupon = static::getList(array(
350 'select' => array('ID', 'DISCOUNT_ID'),
351 'filter' => array('=ID' => $event->getParameter('id'))
352 ))->fetch();
353 if (!empty($coupon))
354 {
355 $coupon['DISCOUNT_ID'] = (int)$coupon['DISCOUNT_ID'];
356 if ($coupon['DISCOUNT_ID'] !== $data['DISCOUNT_ID'])
357 {
358 self::$discountCheckList[$data['DISCOUNT_ID']] = $data['DISCOUNT_ID'];
359 self::$discountCheckList[$coupon['DISCOUNT_ID']] = $coupon['DISCOUNT_ID'];
360 }
361 }
362 unset($coupon);
363 }
364 unset($data);
365 }
366
373 public static function onAfterUpdate(Main\Entity\Event $event)
374 {
375 self::updateUseCoupons();
376 }
377
384 public static function onDelete(Main\Entity\Event $event)
385 {
386 if (!self::isCheckedCouponsUse())
387 return;
388 $coupon = self::getList(array(
389 'select' => array('ID', 'DISCOUNT_ID'),
390 'filter' => array('=ID' => $event->getParameter('id'))
391 ))->fetch();
392 if (!empty($coupon))
393 {
394 $coupon['DISCOUNT_ID'] = (int)$coupon['DISCOUNT_ID'];
395 self::$discountCheckList[$coupon['DISCOUNT_ID']] = $coupon['DISCOUNT_ID'];
396 }
397 unset($coupon);
398 }
399
406 public static function onAfterDelete(Main\Entity\Event $event)
407 {
408 self::updateUseCoupons();
409 }
410
417 public static function getCouponTypes($extendedMode = false)
418 {
419 $extendedMode = ($extendedMode === true);
420 if ($extendedMode)
421 {
422 return array(
423 self::TYPE_BASKET_ROW => Loc::getMessage('DISCOUNT_COUPON_TABLE_TYPE_BASKET_ROW'),
424 self::TYPE_ONE_ORDER => Loc::getMessage('DISCOUNT_COUPON_TABLE_TYPE_ONE_ORDER'),
425 self::TYPE_MULTI_ORDER => Loc::getMessage('DISCOUNT_COUPON_TABLE_TYPE_MULTI_ORDER')
426 );
427 }
428 return array(self::TYPE_BASKET_ROW, self::TYPE_ONE_ORDER, self::TYPE_MULTI_ORDER);
429 }
430
436 public static function disableCheckCouponsUse()
437 {
438 self::$checkDiscountCouponsUse--;
439 }
440
446 public static function enableCheckCouponsUse()
447 {
448 self::$checkDiscountCouponsUse++;
449 }
450
456 public static function isCheckedCouponsUse()
457 {
458 return (self::$checkDiscountCouponsUse >= 0);
459 }
460
466 public static function clearDiscountCheckList()
467 {
468 self::$discountCheckList = array();
469 }
470
477 public static function setDiscountCheckList($discountList)
478 {
479 if (!is_array($discountList))
480 $discountList = array($discountList => $discountList);
481 if (!empty($discountList))
482 self::$discountCheckList = (empty(self::$discountCheckList) ? $discountList : array_merge(self::$discountCheckList, $discountList));
483 }
484
490 public static function updateUseCoupons()
491 {
492 if (!self::isCheckedCouponsUse() || empty(self::$discountCheckList))
493 return;
494
495 Main\Type\Collection::normalizeArrayValuesByInt(self::$discountCheckList);
496 if (empty(self::$discountCheckList))
497 return;
498
499 $withoutCoupons = array_fill_keys(self::$discountCheckList, true);
500 $withCoupons = array();
501 $couponIterator = DiscountCouponTable::getList(array(
502 'select' => array('DISCOUNT_ID', new Main\Entity\ExpressionField('CNT', 'COUNT(*)')),
503 'filter' => array('@DISCOUNT_ID' => self::$discountCheckList),
504 'group' => array('DISCOUNT_ID')
505 ));
506 while ($coupon = $couponIterator->fetch())
507 {
508 $coupon['CNT'] = (int)$coupon['CNT'];
509 if ($coupon['CNT'] > 0)
510 {
511 $coupon['DISCOUNT_ID'] = (int)$coupon['DISCOUNT_ID'];
512 unset($withoutCoupons[$coupon['DISCOUNT_ID']]);
513 $withCoupons[$coupon['DISCOUNT_ID']] = true;
514 }
515 }
516 unset($coupon, $couponIterator);
517 if (!empty($withoutCoupons))
518 {
519 $withoutCoupons = array_keys($withoutCoupons);
520 DiscountTable::setUseCoupons($withoutCoupons, 'N');
521 }
522 if (!empty($withCoupons))
523 {
524 $withCoupons = array_keys($withCoupons);
525 DiscountTable::setUseCoupons($withCoupons, 'Y');
526 }
527 unset($withCoupons, $withoutCoupons);
528
529 static::clearDiscountCheckList();
530 }
531
538 public static function deleteByDiscount($discount)
539 {
540 $discount = (int)$discount;
541 if ($discount <= 0)
542 return;
543
544 $couponsList = array();
545 $couponIterator = self::getList(array(
546 'select' => array('ID'),
547 'filter' => array('=DISCOUNT_ID' => $discount)
548 ));
549 while ($coupon = $couponIterator->fetch())
550 $couponsList[] = $coupon['ID'];
551 unset($coupon, $couponIterator);
552 if (!empty($couponsList))
553 {
555 $helper = $conn->getSqlHelper();
556 $conn->queryExecute(
557 'delete from '.$helper->quote(self::getTableName()).' where '.$helper->quote('DISCOUNT_ID').' = '.$discount
558 );
559 $event = new Main\Event('sale', self::EVENT_ON_AFTER_DELETE_DISCOUNT, array($discount, $couponsList));
560 $event->send();
561 }
562 }
563
572 public static function saveApplied($coupons, $userId, Main\Type\DateTime $currentTime)
573 {
574 $currentTimestamp = $currentTime->getTimestamp();
575 if ($userId === null || (int)$userId == 0)
576 return false;
577 $userId = (int)$userId;
578 if (!is_array($coupons))
579 $coupons = array($coupons);
580 if (empty($coupons))
581 return false;
582 Main\Type\Collection::normalizeArrayValuesByInt($coupons);
583 if (empty($coupons))
584 return false;
585
586 $errorList = [];
587 $deactivateCoupons = array();
588 $incrementalCoupons = array();
589 $limitedCoupons = array();
590 $couponIterator = self::getList(array(
591 'select' => array(
592 'ID', 'COUPON', 'DISCOUNT_ID', 'TYPE', 'ACTIVE', 'MAX_USE', 'USE_COUNT', 'USER_ID', 'ACTIVE_TO', 'ACTIVE_FROM',
593 'DISCOUNT_ACTIVE' => 'DISCOUNT.ACTIVE',
594 'DISCOUNT_ACTIVE_FROM' => 'DISCOUNT.ACTIVE_FROM', 'DISCOUNT_ACTIVE_TO' => 'DISCOUNT.ACTIVE_TO'
595 ),
596 'filter' => array('@ID' => $coupons),
597 'order' => array('ID' => 'ASC')
598 ));
599 while ($existCoupon = $couponIterator->fetch())
600 {
601 $couponCode = $existCoupon['COUPON'];
602 if ($existCoupon['DISCOUNT_ACTIVE'] != 'Y')
603 {
604 $errorList[$couponCode] = Loc::getMessage('DISCOUNT_COUPON_SAVE_ERROR_DISCOUNT_INACTIVE');
605 continue;
606 }
607 if (
608 ($existCoupon['DISCOUNT_ACTIVE_FROM'] instanceof Main\Type\DateTime && $existCoupon['DISCOUNT_ACTIVE_FROM']->getTimestamp() > $currentTimestamp)
609 ||
610 ($existCoupon['DISCOUNT_ACTIVE_TO'] instanceof Main\Type\DateTime && $existCoupon['DISCOUNT_ACTIVE_TO']->getTimestamp() < $currentTimestamp)
611 )
612 {
613 $errorList[$couponCode] = Loc::getMessage('DISCOUNT_COUPON_SAVE_ERROR_DISCOUNT_WRONG_ACTIVE_PERIOD');
614 continue;
615 }
616
617 $existCoupon['USER_ID'] = (int)$existCoupon['USER_ID'];
618 if ($existCoupon['USER_ID'] > 0 && $existCoupon['USER_ID'] != $userId)
619 {
620 $errorList[$couponCode] = Loc::getMessage('DISCOUNT_COUPON_SAVE_ERROR_WRONG_USER_COUPON');
621 continue;
622 }
623 if (
624 ($existCoupon['ACTIVE_FROM'] instanceof Main\Type\DateTime && $existCoupon['ACTIVE_FROM']->getTimestamp() > $currentTimestamp)
625 ||
626 ($existCoupon['ACTIVE_TO'] instanceof Main\Type\DateTime && $existCoupon['ACTIVE_TO']->getTimestamp() < $currentTimestamp)
627 )
628 {
629 $errorList[$couponCode] = Loc::getMessage('DISCOUNT_COUPON_SAVE_ERROR_COUPON_WRONG_ACTIVE_PERIOD');
630 continue;
631 }
632 if ($existCoupon['ACTIVE'] != 'Y')
633 {
634 switch ($existCoupon['TYPE'])
635 {
636 case self::TYPE_BASKET_ROW:
637 $errorList[$couponCode] = Loc::getMessage('DISCOUNT_COUPON_SAVE_ERROR_COUPON_BASKET_ROW_INACTIVE');
638 break;
640 $errorList[$couponCode] = Loc::getMessage('DISCOUNT_COUPON_SAVE_ERROR_COUPON_ONE_ORDER_INACTIVE');
641 break;
642 default:
643 $errorList[$couponCode] = Loc::getMessage('DISCOUNT_COUPON_SAVE_ERROR_COUPON_INACTIVE');
644 break;
645 }
646 continue;
647 }
648
649 if (
650 $existCoupon['TYPE'] == self::TYPE_BASKET_ROW
651 || $existCoupon['TYPE'] == self::TYPE_ONE_ORDER
652 )
653 {
654 $deactivateCoupons[$couponCode] = $existCoupon['ID'];
655 }
656 elseif ($existCoupon['TYPE'] == self::TYPE_MULTI_ORDER)
657 {
658 $existCoupon['MAX_USE'] = (int)$existCoupon['MAX_USE'];
659 $existCoupon['USE_COUNT'] = (int)$existCoupon['USE_COUNT'];
660
661 if ($existCoupon['MAX_USE'] > 0 && $existCoupon['USE_COUNT'] >= $existCoupon['MAX_USE'])
662 {
663 $errorList[$couponCode] = Loc::getMessage('DISCOUNT_COUPON_SAVE_ERROR_COUPON_MAX_USE_LIMIT');
664 continue;
665 }
666 if ($existCoupon['MAX_USE'] > 0 && $existCoupon['USE_COUNT'] >= ($existCoupon['MAX_USE'] - 1))
667 {
668 $limitedCoupons[$existCoupon['COUPON']] = $existCoupon['ID'];
669 }
670 else
671 {
672 $incrementalCoupons[$existCoupon['COUPON']] = $existCoupon['ID'];
673 }
674 }
675
676 }
677 unset($existCoupon, $couponIterator);
678 if (!empty($errorList))
679 {
680 return [
681 'STATUS' => false,
682 'ERROR' => $errorList,
683 'DEACTIVATE' => 0,
684 'LIMITED' => 0,
685 'INCREMENT' => 0
686 ];
687 }
688 if (!empty($deactivateCoupons) || !empty($limitedCoupons) || !empty($incrementalCoupons))
689 {
691 $helper = $conn->getSqlHelper();
692 $tableName = $helper->quote(self::getTableName());
693 if (!empty($deactivateCoupons))
694 {
695 $conn->queryExecute(
696 'update '.$tableName.' set '.$helper->quote('ACTIVE').' = \'N\', '.$helper->quote('DATE_APPLY').' = '.$helper->getCurrentDateTimeFunction().
697 ' where '.$helper->quote('ID').' in ('.implode(',', $deactivateCoupons).')'
698 );
699 }
700 if (!empty($incrementalCoupons))
701 {
702 $conn->queryExecute(
703 'update '.$tableName.' set '.$helper->quote('DATE_APPLY').' = '.$helper->getCurrentDateTimeFunction().', '.
704 $helper->quote('USE_COUNT').' = '.$helper->quote('USE_COUNT').' + 1'.
705 ' where '.$helper->quote('ID').' in ('.implode(',', $incrementalCoupons).')'
706 );
707 }
708 if (!empty($limitedCoupons))
709 {
710 $conn->queryExecute(
711 'update '.$tableName.' set '.$helper->quote('DATE_APPLY').' = '.$helper->getCurrentDateTimeFunction().', '.
712 $helper->quote('ACTIVE').' = \'N\', '.$helper->quote('USE_COUNT').' = '.$helper->quote('USE_COUNT').' + 1'.
713 ' where '.$helper->quote('ID').' in ('.implode(',', $limitedCoupons).')'
714 );
715 }
716 unset($tableName, $helper);
717 }
718 return [
719 'STATUS' => true,
720 'ERROR_LIST' => [],
721 'DEACTIVATE' => $deactivateCoupons,
722 'LIMITED' => $limitedCoupons,
723 'INCREMENT' => $incrementalCoupons
724 ];
725 }
726
733 public static function generateCoupon($check = false)
734 {
735 static $eventExists = null;
736
737 $check = ($check === true);
738 if ($eventExists === true || $eventExists === null)
739 {
740 $event = new Main\Event('sale', self::EVENT_ON_GENERATE_COUPON, array('CHECK' => $check));
741 $event->send();
742 $resultList = $event->getResults();
743 if (!empty($resultList) && is_array($resultList))
744 {
746 foreach ($resultList as &$eventResult)
747 {
748 if ($eventResult->getType() != Main\EventResult::SUCCESS)
749 continue;
750 $eventExists = true;
751 $result = $eventResult->getParameters();
752 if (!empty($result) && is_string($result))
753 return $result;
754 }
755 unset($eventResult);
756 }
757 if ($eventExists === null)
758 $eventExists = false;
759 }
760
761 $allchars = 'ABCDEFGHIJKLNMOPQRSTUVWXYZ0123456789';
762 $charsLen = mb_strlen($allchars) - 1;
763
764 do
765 {
766 $resultCorrect = true;
767 $partOne = '';
768 $partTwo = '';
769 for ($i = 0; $i < 5; $i++)
770 $partOne .= mb_substr($allchars, rand(0, $charsLen), 1);
771
772 for ($i = 0; $i < 7; $i++)
773 $partTwo .= mb_substr($allchars, rand(0, $charsLen), 1);
774
775 $result = 'SL-'.$partOne.'-'.$partTwo;
776 if ($check)
777 {
778 $existCoupon = Sale\DiscountCouponsManager::isExist($result);
779 $resultCorrect = empty($existCoupon);
780 }
781 } while (!$resultCorrect);
782 return $result;
783 }
784
793 public static function addPacket(array $data, $count, $limit = 0)
794 {
795 $result = new Main\Entity\Result();
796 $result->setData(array(
797 'result' => 0,
798 'count' => $count,
799 'limit' => $limit,
800 'all' => 0
801 ));
802 $count = (int)$count;
803 if ($count <= 0)
804 {
805 $result->addError(new Main\Entity\EntityError(
806 Loc::getMessage('DISCOUNT_COUPON_PACKET_COUNT_ERR'),
807 'COUPON_PACKET'
808 ));
809 }
810 foreach (static::getEntity()->getFields() as $field)
811 {
812 if ($field instanceof Main\Entity\ScalarField && !array_key_exists($field->getName(), $data))
813 {
814 $defaultValue = $field->getDefaultValue();
815
816 if ($defaultValue !== null)
817 $data[$field->getName()] = $field->getDefaultValue();
818 }
819 }
820 $checkResult = static::checkPacket($data, false);
821 if (!$checkResult->isSuccess())
822 {
823 foreach ($checkResult->getErrors() as $checkError)
824 {
825 $result->addError($checkError);
826 }
827 unset($checkError);
828 }
829 unset($checkResult);
830 $useCoupons = false;
831 $discountIterator = DiscountTable::getList(array(
832 'select' => array('ID', 'USE_COUPONS'),
833 'filter' => array('=ID' => $data['DISCOUNT_ID'])
834 ));
835 if ($discount = $discountIterator->fetch())
836 {
837 $useCoupons = ($discount['USE_COUPONS'] == 'Y');
838 }
839 else
840 {
841 $result->addError(new Main\Entity\EntityError(
842 Loc::getMessage('DISCOUNT_COUPON_PACKET_DISCOUNT_ERR'),
843 'COUPON_PACKET'
844 ));
845 }
846 if (!$result->isSuccess(true))
847 return $result;
848
849 self::setDiscountCheckList($data['DISCOUNT_ID']);
850 self::disableCheckCouponsUse();
851 $limit = (int)$limit;
852 if ($limit < $count)
853 $limit = $count*2;
854 $resultCount = 0;
855 $all = 0;
856 do
857 {
858 $data['COUPON'] = self::generateCoupon(true);
859 $couponResult = self::add($data);
860 if ($couponResult->isSuccess())
861 $resultCount++;
862 $all++;
863 } while ($resultCount < $count && $all < $limit);
864 $result->setData(array(
865 'result' => $resultCount,
866 'count' => $count,
867 'limit' => $limit,
868 'all' => $all
869 ));
870 if ($resultCount == 0)
871 {
872 $result->addError(new Main\Entity\EntityError(
873 ($useCoupons
874 ? Loc::getMessage('DISCOUNT_COUPON_PACKET_GENERATE_COUPON_ZERO_ERR')
875 : Loc::getMessage('DISCOUNT_COUPON_PACKET_NEW_GENERATE_COUPON_ZERO_ERR')
876 ),
877 'COUPON_PACKET'
878 ));
879 self::clearDiscountCheckList();
880 }
881 elseif ($resultCount < $count)
882 {
883 $result->addError(new Main\Entity\EntityError(
885 'DISCOUNT_COUPON_PACKET_GENERATE_COUPON_COUNT_ERR',
886 array(
887 '#RESULT#' => $resultCount,
888 '#COUNT#' => $count,
889 '#ALL#' => $all
890 )
891 ),
892 'COUPON_PACKET'
893 ));
894 }
895 self::enableCheckCouponsUse();
896 self::updateUseCoupons();
897
898 return $result;
899 }
900
908 public static function checkPacket(array $data, $newDiscount = false)
909 {
910 $result = new Main\Entity\Result();
911
912 $newDiscount = ($newDiscount === true);
913 if (empty($data) || !is_array($data))
914 {
915 $result->addError(new Main\Entity\EntityError(
916 Loc::getMessage('DISCOUNT_COUPON_PACKET_EMPTY'),
917 'COUPON_PACKET'
918 ));
919 }
920 else
921 {
922 if (empty($data['TYPE']) || !in_array((int)$data['TYPE'], self::getCouponTypes(false)))
923 {
924 $result->addError(new Main\Entity\EntityError(
925 Loc::getMessage('DISCOUNT_COUPON_VALIDATOR_TYPE'),
926 'COUPON_PACKET'
927 ));
928 }
929 if (!$newDiscount && empty($data['DISCOUNT_ID']))
930 {
931 $result->addError(new Main\Entity\EntityError(
932 Loc::getMessage('DISCOUNT_COUPON_VALIDATOR_DISCOUNT_ID'),
933 'COUPON_PACKET'
934 ));
935 }
936 if (
937 (isset($data['ACTIVE_FROM']) && !($data['ACTIVE_FROM'] instanceof Main\Type\DateTime))
938 ||
939 (isset($data['ACTIVE_TO']) && !($data['ACTIVE_TO'] instanceof Main\Type\DateTime))
940 )
941 {
942 $result->addError(new Main\Entity\EntityError(
943 Loc::getMessage('DISCOUNT_COUPON_VALIDATOR_PERIOD'),
944 'COUPON_PACKET'
945 ));
946 }
947 }
948 return $result;
949 }
950
957 public static function prepareCouponData(&$fields)
958 {
959 $result = new Main\Entity\Result();
960 if (!empty($fields) && is_array($fields))
961 {
962 if (isset($fields['ACTIVE_FROM']) && is_string($fields['ACTIVE_FROM']))
963 {
964 $fields['ACTIVE_FROM'] = trim($fields['ACTIVE_FROM']);
965 $fields['ACTIVE_FROM'] = ($fields['ACTIVE_FROM'] !== '' ? Main\Type\DateTime::createFromUserTime($fields['ACTIVE_FROM']) : null);
966 }
967 if (isset($fields['ACTIVE_TO']) && is_string($fields['ACTIVE_TO']))
968 {
969 $fields['ACTIVE_TO'] = trim($fields['ACTIVE_TO']);
970 $fields['ACTIVE_TO'] = ($fields['ACTIVE_TO'] !== '' ? Main\Type\DateTime::createFromUserTime($fields['ACTIVE_TO']) : null);
971 }
972 }
973 return $result;
974 }
975
982 public static function isValidCouponType($couponType)
983 {
984 $couponType = (int)$couponType;
985 return (
986 $couponType == self::TYPE_BASKET_ROW
987 || $couponType == self::TYPE_ONE_ORDER
988 || $couponType == self::TYPE_MULTI_ORDER
989 );
990 }
991
1000 protected static function setUserID(array &$result, array $data, array $keys)
1001 {
1002 static $currentUserID = false;
1003 if ($currentUserID === false)
1004 {
1005 global $USER;
1007 $currentUserID = (isset($USER) && $USER instanceof \CUser ? (int)$USER->getID() : null);
1008 }
1009 foreach ($keys as $oneKey)
1010 {
1011 $setField = true;
1012 if (array_key_exists($oneKey, $data))
1013 $setField = ($data[$oneKey] !== null && (int)$data[$oneKey] <= 0);
1014
1015 if ($setField)
1016 $result[$oneKey] = $currentUserID;
1017 }
1018 unset($oneKey);
1019 }
1020
1029 protected static function setTimestamp(array &$result, array $data, array $keys)
1030 {
1031 foreach ($keys as $oneKey)
1032 {
1033 $setField = true;
1034 if (array_key_exists($oneKey, $data))
1035 $setField = ($data[$oneKey] !== null && !is_object($data[$oneKey]));
1036
1037 if ($setField)
1038 $result[$oneKey] = new Main\Type\DateTime();
1039 }
1040 unset($oneKey);
1041 }
1042}
static setUserID(&$result, $data, $keys)
static setTimestamp(&$result, $data, $keys)
static setUseCoupons($discountList, $use)
Definition discount.php:442
static getConnection($name="")
static loadMessages($file)
Definition loc.php:64
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
static checkCoupon($value, $primary, array $row, Main\Entity\Field $field)
static getCouponTypes($extendedMode=false)
static setUserID(array &$result, array $data, array $keys)
static onUpdate(Main\Entity\Event $event)
static onBeforeAdd(Main\Entity\Event $event)
static onAfterDelete(Main\Entity\Event $event)
static onDelete(Main\Entity\Event $event)
static checkPacket(array $data, $newDiscount=false)
static onAfterUpdate(Main\Entity\Event $event)
static onBeforeUpdate(Main\Entity\Event $event)
static checkType($value, $primary, array $row, Main\Entity\Field $field)
static onAfterAdd(Main\Entity\Event $event)
static saveApplied($coupons, $userId, Main\Type\DateTime $currentTime)
static setTimestamp(array &$result, array $data, array $keys)
static checkDiscountId($value, $primary, array $row, Main\Entity\Field $field)
static addPacket(array $data, $count, $limit=0)