Skip to content

Instantly share code, notes, and snippets.

@Qetbn
Created May 13, 2014 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Qetbn/1c9e3db282ddc8e0af4d to your computer and use it in GitHub Desktop.
Save Qetbn/1c9e3db282ddc8e0af4d to your computer and use it in GitHub Desktop.
<?
/**
* Class SimpleCoupons
*
* Класс для генерации купонов для существующей скидки в 1С-Битрикс
* Необходимые модули: catalog
*/
class SimpleCoupons
{
protected $length = 4;
protected $fixed = "COUPON-";
protected $discountId = 0;
protected $couponId = "";
protected $fastMode = false;
/**
* конструктор класса
*/
public function __construct()
{
/* тест на наличие модуля */
if (!CModule::IncludeModule("catalog"))
return "";
}
/**
* @param bool $set включить или отключить проверку при создании
*/
public function setFastMode($set)
{
$this->fastMode = (bool)$set;
}
/**
* @param string $str блок с фиксированной частью в названии купона
*/
public function setFixedPart($str)
{
if (strlen($str) > 0) {
$this->fixed = $str;
}
}
/**
* @param int $length количество генерируемых символов
*/
public function setLength($length)
{
$length = (int)$length;
if ($length > 0) {
$this->length = $length;
}
}
/**
* @param int $id ID скидки
*/
public function setDiscountId($id)
{
$id = (int) $id;
if ($id > 0) {
$this->discountId = $id;
}
}
/**
* generateCouponName
*
* Генерация имени купона с проверкой на существование
*
* @return string coupon название купона
*/
protected function generateCouponName()
{
do {
/* генерация текста */
$chars = 'ABCDEFGHIJKLNMOPQRSTUVWXYZ0123456789';
$code = "";
for ($i = 0; $i < $this->length; $i++) {
$code .= substr($chars, round((rand(0, 10) * 0.1) * (strlen($chars) - 1)), 1);
}
$coupon = $this->fixed . $code;
/**
* если включен режим fastMode, не проверяем код купона на уникальность,
* в данном случае проверка будет возложена на результат создания записи
*/
if ($this->fastMode === true) {
$dbCouponCheck = CCatalogDiscountCoupon::GetList(array(), array("COUPON" => $coupon), false, false, array());
$rows = intval($dbCouponCheck->SelectedRowsCount());
} else {
$rows = 1;
}
} while ($rows === false);
return $coupon;
}
/**
* create
*
* Добавление купона к скидке
*
* @return string $couponId код купона
*/
public function create()
{
if (!$this->discountId > 0)
return false;
do {
/**
* запрашиваем код купона и генерируем массив данных
*/
$couponId = $this->generateCouponName();
$arCoupon = array(
"DISCOUNT_ID" => $this->discountId,
"ACTIVE" => "Y",
"ONE_TIME" => "O",
"COUPON" => $couponId,
"DATE_APPLY" => false
);
/**
* добавляем купон к скидке
*/
$res = CCatalogDiscountCoupon::Add($arCoupon);
} while ($res === false);
$this->couponId = $couponId;
return $this->couponId;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment