- Модуль: crm
- Путь к файлу: ~/bitrix/modules/crm/classes/general/crm_quote.php
- Класс: \CAllCrmQuote
- Вызов: CAllCrmQuote::SetQuoteNumber
static function SetQuoteNumber($ID)
{
global $DB;
$ID = intval($ID);
if ($ID <= 0)
return false;
$type = COption::GetOptionString("crm", "quote_number_template", "");
$numeratorSettings = \Bitrix\Main\Numerator\Numerator::getOneByType(REGISTRY_TYPE_CRM_QUOTE);
$bCustomAlgorithm = false;
$value = $ID;
foreach(GetModuleEvents("crm", "OnBeforeCrmQuoteNumberSet", true) as $arEvent)
{
$tmpRes = ExecuteModuleEventEx($arEvent, Array($ID, $type));
if ($tmpRes !== false)
{
$bCustomAlgorithm = true;
$value = $tmpRes;
}
}
if ($bCustomAlgorithm)
{
$arFields = array("QUOTE_NUMBER" => $value);
$sUpdate = $DB->PrepareUpdate('b_crm_quote', $arFields);
$sql = "UPDATE b_crm_quote SET $sUpdate WHERE ID = $ID";
$res = $DB->Query($sql, true);
}
else
{
$res = false;
if ($numeratorSettings) // if special template (numerator) is selected
{
for ($i = 0; $i < 10; $i++)
{
$value = false;
$numerator = \Bitrix\Main\Numerator\Numerator::load($numeratorSettings['id'], ['QUOTE_ID' => $ID]);
if ($numerator)
{
$value = $numerator->getNext();
}
if ($value !== false)
{
$arFields = array("QUOTE_NUMBER" => $value);
$sUpdate = $DB->PrepareUpdate('b_crm_quote', $arFields);
$sql = "UPDATE b_crm_quote SET $sUpdate WHERE ID = $ID";
$res = $DB->Query($sql, true);
if ($res)
{
break;
}
}
}
}
}
if (!$numeratorSettings || !$res) // if no special template is used or error occured
{
if ($type !== 'NUMBER')
{
$arFields = array('QUOTE_NUMBER' => $ID);
$sUpdate = $DB->PrepareUpdate('b_crm_quote', $arFields);
$sql = "UPDATE b_crm_quote SET $sUpdate WHERE ID = $ID";
$res = $DB->Query($sql, true);
}
if (!$res && (!$numeratorSettings || $type === 'NUMBER')) // try set max number + 1
{
$maxLastId = $ID;
$maxLastIdIsSet = false;
for ($i = 0; $i < 10; $i++)
{
$sql = 'SELECT MAX(CAST(QUOTE_NUMBER AS UNSIGNED)) AS LAST_NUMBER FROM b_crm_quote';
$resLastId = $DB->Query($sql, true);
if ($row = $resLastId->fetch())
{
if (strval($row['LAST_NUMBER']) <> '')
{
$maxLastId = $row['LAST_NUMBER'];
$maxLastIdIsSet = true;
}
}
if ($maxLastIdIsSet)
{
$arFields = array('~QUOTE_NUMBER' => "($maxLastId + 1)");
$sUpdate = $DB->PrepareUpdate('b_crm_quote', $arFields);
$sql = "UPDATE b_crm_quote SET $sUpdate WHERE ID = $ID";
$res = $DB->Query($sql, true);
if ($res)
{
COption::SetOptionString("crm", "quote_number_template", "NUMBER");
COption::SetOptionString("crm", "quote_number_data", $maxLastId);
if (!$numeratorSettings)
{
$numeratorForQuotes = \Bitrix\Main\Numerator\Numerator::create();
$numeratorForQuotes->setConfig([
\Bitrix\Main\Numerator\Numerator::getType() =>
[
'name' => 'numerator for quote',
'template' => '{NUMBER}',
'type' => 'QUOTE',
],
\Bitrix\Main\Numerator\Generator\SequentNumberGenerator::getType() =>
[
'start' => $maxLastId,
'isDirectNumeration' => true,
],
]);
$numeratorForQuotes->save();
}
break;
}
}
}
}
}
return $res;
}