Частный битрикс-разработчик Вероника Малышева

Битрикс-шпаргалки - Сообщения с тегом "битрикс24"

  • Архив

    «   Апрель 2020   »
    Пн Вт Ср Чт Пт Сб Вс
        1 2 3 4 5
    6 7 8 9 10 11 12
    13 14 15 16 17 18 19
    20 21 22 23 24 25 26
    27 28 29 30      

методы работы с api bitrix24 коробка

добавить сделку
$arFields = array(
      "TITLE" => $_POST["name_deal"], 
        "TYPE_ID" => "SALE", 
        "STAGE_ID" => "NEW",                
        "COMPANY_ID" => $companyId,                        
        "OPENED" => "Y", 
        "ASSIGNED_BY_ID" => $managerId, 
        //"CREATED_BY_ID" =>$managerId,                         
        //UF_CRM_CONF_NAME => $_POST["configs_deal"],
        UF_CRM_CONF_NAME1 => $_POST["configsnew_deal"], //пользовательское свойство сделки   


);
$options = array('CURRENT_USER'=>1); //из под админа
$deal = new CCrmDeal(false);
$dealId = $deal->Add($arFields,true,$options);
if($dealId > 0){                    
   CModule::IncludeModule('bizproc');
   $arErrors = Array();                  
   CBPDocument::StartWorkflow(
         $bpId,
         array("crm","CCrmDocumentDeal","DEAL_".$dealId),
         array("TargetUser" => "user_1"),
         $arErrorsTmp
   );                  
}
   

проапдейтить сделку
//вариант 1
$deal = new CCrmDeal(false); //false - не учитывать права
global $DB; 
$DB->StartTransaction();              
$arUpdateData = array("STAGE_ID" => $stage);  //поля которые обновляем
$arOptions = array( 
  "CURRENT_USER"=> $arTaskCopy["CREATED_BY"] //из под кого обновляем
);              
if($deal->Update(
    $dealId,
    $arUpdateData,
    true,
    true,
    $arOptions                   
)){               
   $DB->Commit(); 
   CModule::IncludeModule('bizproc'); //запускаем бизнес-процесс или робота
   $arErrors = Array();                  
   CBPDocument::StartWorkflow(
     $bpId,
       array("crm","CCrmDocumentDeal","DEAL_". $dealId),
       array(),
       $arErrorsTmp
    );                    
}
else{                  
 $DB->Rollback();
}

//вариант 2
$deal  =  new  \CCrmDeal( false );   
$arUpdateData = array(); //поля которые обновляем
$arOptions = array("CURRENT_USER"=> $arTaskCopy["CREATED_BY"]); //из под кого обновляем
 
//сначала заполняем поля
$upRes = $deal->Update($dealId, $arUpdateData, true, true, $arOptions);                                       
//потом переходим на этап 
$arUpdateData = array("STAGE_ID" => 4);   
$upRes = $deal->Update($dealId, $arUpdateData, true, true, $arOptions);
//запускаем бизнес процесс                             
CModule::IncludeModule('bizproc');            
CBPDocument::StartWorkflow(
   $bpId,
   array("crm","CCrmDocumentDeal","DEAL_".$dealId),
   array("TargetUser" => "user_".$userId),
   $arErrorsTmp
); 
   

получить компанию
$companyId = intval($arFields["COMPANY_ID"]);
$arFilter = array("ID"=>$companyId,"CHECK_PERMISSIONS"=>"N");
$arSelect = array("TITLE","", UF_CRM_TARIFF,UF_CRM_COMPANY_TIME);
$rsCompany = CCrmCompany::GetList(Array(),$arFilter,$arSelect);
if($arComp = $rsCompany->Fetch()){
  
}       
проапдейтить компанию
$cCompany  =  new  \CCrmCompany( false );
$arUpdateData = array(UF_CRM_COMPANY_TIME => $newTime); 
$arOptions = array(
       //'DISABLE_USER_FIELD_CHECK' => true,
    "CURRENT_USER"=> 1,
    "ENABLE_SYSTEM_EVENTS" =>true
); 
$upRes = $cCompany->Update($arComp["ID"], $arUpdateData, true, true, $arOptions);

создать счет
$arInvoiceProps = array();
$entityRequisite = new \Bitrix\Crm\EntityRequisite;
$rsRequisite = $entityRequisite->getList([
   "select"=>array("*"),
   "filter"=>array("ENTITY_ID"=>$companyId,"ENTITY_TYPE_ID"=>CCrmOwnerType::Company),
   "order"=>array("SORT"=>"desc","ID"=>"desc")

]);
$arRequisite = $rsRequisite->fetchAll();

if(count($arRequisite)>0){
   $arRequisite = $arRequisite[0];
   $arInvoiceProps = array(                            
   9 => $arRequisite["RQ_INN"],                            
   10 => $arRequisite["RQ_KPP"],                           
   11 => $arRequisite["RQ_COMPANY_NAME"],                           
    14 => $arComp["CLIENT_EMAIL"],

   );
   $address = new \Bitrix\Crm\EntityAddress();
   $dbRes   = $address->getList(array(
    'filter' => array(
        'ENTITY_ID' => $arRequisite['ID'],
        'ANCHOR_ID' => $companyId
    )
));
$arAddresses = array();
while ($arAddr =  $dbRes->Fetch()) {
   if($arAddr["TYPE_ID"]==6){
      $arInvoiceProps[12] = $addr["ADDRESS_1"]." ".$addr["ADDRESS_2"];//юр адрес
      $arInvoiceProps[17] = $addr["POSTAL_CODE"];//индекс
      $arInvoiceProps[18] = $addr["CITY"];//город
      
   }
                     
}                            
}
else{
   $arInvoiceProps = array(                                                      
   11 => $arComp["TITLE"],                           
    14 => $arComp["CLIENT_EMAIL"]                        
   );
}
$arInvoiceProps[15] = ""; //телефон
$arInvoiceProps[13] = ""; //контактное лицо
   
   
   

$arFieldsInvoice = Array(
   "ORDER_TOPIC" => $arFields["TITLE"],
   "STATUS_ID" => "N",
   "DATE_INSERT" => date("d.m.Y H:i:s", strtotime("+0 hours")),
   "DATE_BILL" => date("d.m.Y", strtotime("+0 hours")),
   "PAY_VOUCHER_DATE" => "",
   "DATE_PAY_BEFORE" => "",
   "RESPONSIBLE_ID" => 1,
   "COMMENTS" => "",
   "USER_DESCRIPTION" => "",
   "UF_QUOTE_ID" => 0,
   "UF_DEAL_ID" => $arFields["ID"],
   "UF_COMPANY_ID" => $companyId,
   "UF_CONTACT_ID" => 0,
   "UF_MYCOMPANY_ID" => 9,
   "PRODUCT_ROWS" => Array(
      Array(
         "ID" => 0,
         "PRODUCT_ID" => 0,
         "PRODUCT_NAME" => "Оказание услуг бла-бла",
         "QUANTITY" =>$quantity,
         "PRICE" => $price,
         "VAT_RATE" => 0,
         "DISCOUNT_PRICE" => 0,
         "MEASURE_CODE" => 356,
         "MEASURE_NAME" => "ч",
         "CUSTOMIZED" => "Y"
      )
   ),
   "PERSON_TYPE_ID" => 1,
   "PAY_SYSTEM_ID" => 1,
   "INVOICE_PROPERTIES" => $arInvoiceProps,
   UF_CRM_1567860613 => 1 //доп свойства счета                  
);
$oCrmInvoice = new CCrmInvoice(false);
$result = $oCrmInvoice->Add($arFieldsInvoice);
получить счета
$oCrmInvoice = new CCrmInvoice(false);
$arFilter = array(   
  "CHECK_PERMISSIONS"=>"N",
  "UF_DEAL_ID" => $arDealIds,      
   "CANCELED"=>"N"            
 );            
 $arSelect = array("ID","UF_DEAL_ID");   
 $res = CCrmInvoice::GetList($arOrder = Array("ID"=>"DESC"), $arFilter ,false, false, $arSelect);   
 while($row = $res->Fetch()){            
    $oCrmInvoice->Update($row["ID"],array("CANCELED"=>"Y","STATUS_ID"=>"D")); //деактивируем счета                  
}
публичная ссылка на счет
$link = CCrmInvoice::getPublicLink($invoiceId); 


получить реквизиты по инн
if (\Bitrix\Main\Loader::includeModule('socialservices')) {
   $client = new \Bitrix\socialservices\properties\Client;
   $arRequisite = $client->getByInn($inn);
}



напоминание о задаче
//добавляем напоминание 
CModule::IncludeModule("tasks");
$arFields = Array(
    "TASK_ID" => $idTask,
    "USER_ID" => $arTask["CREATED_BY"],
    "REMIND_DATE" => date("d.m.Y H:i:s", strtotime("+5 hours")), 
    "TYPE" => CTaskReminders::REMINDER_TYPE_DEADLINE,
    "TRANSPORT" => CTaskReminders::REMINDER_TRANSPORT_JABBER
);
$obTaskReminders = new CTaskReminders;
$ID = $obTaskReminders->Add($arFields);
задачи для дела получить и обновить
$arFilter = array(                       
   'TAG' => $tag,
   "UF_CRM_TASK" => $arTask["UF_CRM_TASK"][0],   
);
$res = CTasks::GetList(
    Array("DEADLINE" => "ASC"), 
    $arFilter,
    array("ID"),
    array("USER_ID"=>1)                    
);
$obTask = new CTasks;
while($arTask1 = $res->GetNext()){   
   $obTask->Update(
      $arTask1["ID"],  
      array(
         "STATUS" => CTasks::STATE_COMPLETED               
      ), 
      array('USER_ID' => 1)
   );
}


создаем новую задачу
$newTask = array(
   "TITLE" => "заголовок",
   "DESCRIPTION" => "описание",
   "TAGS" => array("CRM","tag1"),
   "DEADLINE" => date("d.m.Y H:i:s", strtotime(("+".($time+4)." hours"))),
   "CREATED_BY" => $arTaskCopy["RESPONSIBLE_ID"],
   "RESPONSIBLE_ID" => $arTaskCopy["RESPONSIBLE_ID"],
   "AUDITORS" => $arTaskCopy["AUDITORS"],
   //"TASK_CONTROL" => "Y",
   "ADD_IN_REPORT" => "Y",
   "DEPENDS_ON"=> $arFields["ID"],
   "UF_CRM_TASK" => $arTaskCopy["UF_CRM_TASK"]
);   

$taskItem = \CTaskItem::add($newTask, 1); 
создать подзадачу для задачи из бизнес-процесса
$arFields = Array(
        "TITLE" => "Название задачи",
        "DESCRIPTION" => "Описание",
        "RESPONSIBLE_ID" => $userId, //ответственный
        "GROUP_ID" => $this->GetVariable('WORKGROUPID'),
        "PARENT_ID"=>'{=A2629_10558_53461_99205:TaskId}',
    );
 
    $obTask = new CTasks;
    $ID = $obTask->Add($arFields);


Добавим компанию, привяжем к пользователю, создадим контакт
$cCompany  =  new  \CCrmCompany( false );
$arFieldsComp = array(
    'TITLE' => (strlen($arNewUser["INN"])==10)?$arRequisite["NAME_SHORT"]:"ИП ".$arRequisite["LAST_NAME"]." ".substr($arRequisite["NAME"], 0,1).". ".substr($arRequisite["SECOND_NAME"],0,1).".",      
    "ASSIGNED_BY_ID" => $manager,                                
    //'CONTACT_ID' => array($iContactID),//здесь привязываем к компании контакт (обязательно с array())
    UF_CRM_TARIFF => 154 //почасовое обслуживание
);
$companyId = $cCompany->Add($arFieldsComp);

if($companyId >0){
   //обновим пользователя, добавим компанию
   $user = new CUser;
   if(!$user->Update($arNewUser["ID"], array("UF_CONTACT"=>$companyId))){
      //не смогли обновить пользователя
   }
   //добавим реквизиты 
   if(strlen($arNewUser["INN"])==10){ //юр лицо
      $arFields = array(
         'ENTITY_ID' => $companyId,
         'ENTITY_TYPE_ID' => CCrmOwnerType::Company,
         'PRESET_ID' => 1,//организация                              
         'NAME' => $arRequisite['NAME_SHORT'],
         'SORT' => 500,
         'ACTIVE' => 'Y',
         'RQ_COMPANY_NAME' => $arRequisite['NAME_SHORT'],
         'RQ_COMPANY_FULL_NAME' => $arRequisite['NAME'],                              
         'RQ_INN' => $arRequisite["INN"], //инн
         'RQ_KPP' => $arRequisite["KPP"],  //кпп
         'RQ_OGRN' => $arRequisite["OGRN"], //огрн
         'RQ_COMPANY_REG_DATE' => $arRequisite["CREATION_REGISTRATION_DATE"],
         'RQ_OKVED' => $arRequisite["OKVED_CODE"],                              
      );

      if(isset($arRequisite["OFFICIALS"][0]["LAST_NAME"])){
         $arFields["RQ_DIRECTOR"] = $arRequisite["OFFICIALS"][0]["LAST_NAME"]." ".$arRequisite["OFFICIALS"][0]["NAME"]." ".$arRequisite["OFFICIALS"][0]["SECOND_NAME"];
      }
   }
   else{//ИП
      $arFields = array(
         'ENTITY_ID' => $companyId,
         'ENTITY_TYPE_ID' => CCrmOwnerType::Company,
         'PRESET_ID' => 2,//ИП                              
         'NAME' => "ИП ".$arRequisite["LAST_NAME"]." ".$arRequisite["NAME"]." ".$arRequisite["SECOND_NAME"],
         'SORT' => 500,
         'ACTIVE' => 'Y',
         'RQ_LAST_NAME' => $arRequisite['LAST_NAME'],
         'RQ_FIRST_NAME' => $arRequisite["NAME"],
         'RQ_SECOND_NAME' => $arRequisite["SECOND_NAME"],                              
         'RQ_COMPANY_FULL_NAME' => $arRequisite['NAME'],                              
         'RQ_INN' => $arRequisite["INN"], //инн                              
         'RQ_OGRNIP' => $arRequisite["OGRNIP"], //огрн
         'RQ_OKVED' => $arRequisite["OKVED_CODE"],                           
      );

   }
   
   $res = $entityRequisite->add($arFields);
   
   if($res->getId() > 0){
      //адрес добавляем
      $address = new \Bitrix\Crm\EntityAddress();
      $address->register(8, $res->getId(), 6, array(                                                            
         "ADDRESS_1" =>$arRequisite["ADDRESS_STREET_NAME"]." ".$arRequisite["ADDRESS_STREET_TYPE"]." ".$arRequisite["ADDRESS_HOUSE"]." ".$arRequisite["ADDRESS_BUILDING"],
         "ADDRESS_2" => $arRequisite["ADDRESS_FLAT"],
         "CITY" => $arRequisite["ADDRESS_REGION_NAME"],
         "POSTAL_CODE" => $arRequisite["ADDRESS_INDEX"],
         "COUNTRY" => "РФ"
      ));
   }                                          
   //создаем контакт 
   $arFields = array(
       "NAME" => $arNewUser["NAME"],
       "LAST_NAME" => $arNewUser["LAST_NAME"],                                     
       "POST" => "не указано",//должность               
       "OPENED" => "N", //открыто для других пользователей                
       "EXPORT" => "Y",//участвует в экспорте                
       'FM' => array(//почта, телефон
           'EMAIL' => array(
                   'n0' => array('VALUE' => $arNewUser["EMAIL"], 'VALUE_TYPE' => 'WORK')
                 ),
                 'PHONE' => array(
                    'n0' => array('VALUE' => $arNewUser["PERSONAL_MOBILE"], 'VALUE_TYPE' => 'WORK')
                 ) 
             ),
             "COMPANY_ID" => $companyId,                
        "ASSIGNED_BY_ID" => $manager,//id ответственного менеджера 
   );
   //создаем контакт   
   $oContact = new \CCrmContact(false);
   $oContact->add($arFields);
   if($oContact->LAST_ERROR != ""){                           
      //не создался контакт
   }
   
}

получить реквизиты компании
$entityRequisite = new \Bitrix\Crm\EntityRequisite;
$rsRequisite = $entityRequisite->getList([
   "select"=>array("*"),
   "filter"=>array("ENTITY_ID"=>$companyId,"ENTITY_TYPE_ID"=>CCrmOwnerType::Company),
   "order"=>array("SORT"=>"desc","ID"=>"desc")

]);
$arRequisite = $rsRequisite->fetchAll();
$arResult["REQUISITE"] = $arRequisite[0];
if(isset($arResult["REQUISITE"]['ID']) && $arResult["REQUISITE"]['ID']>0){
      $bank   = new \Bitrix\Crm\EntityBankDetail();
      $dbRes  = $bank->getList(array(
       'filter' => array('ENTITY_ID' => $arResult["REQUISITE"]['ID'])
   ));
   $arResult["BANK"] =  $dbRes->Fetch();
   $address = new \Bitrix\Crm\EntityAddress();
   $dbRes   = $address->getList(array(
       'filter' => array(
           'ENTITY_ID' => $arResult["REQUISITE"]['ID'],
           //'ANCHOR_ID' => $companyId
       )
   ));
   $arResult["ADDRESS"] = array();
   while ($arAddr =  $dbRes->Fetch()) {
      if($arAddr["TYPE_ID"]==6){
         $arResult["ADDRESS"]["OFFICIAL"] = $arAddr;
      }
      elseif($arAddr["TYPE_ID"]==2){
         $arResult["ADDRESS"]["FACT"] =  $arAddr;   
      }                     
   }

}   

по ID пользователя получим компанию, к которой он относится, получим реквизиты компании  и их проапдейтим
global $USER;
if(is_object($USER) && $USER->IsAuthorized()){
   $rsUser = CUser::GetList($by, $order,
       array("ID" => $USER->GetID()),
       array(
           "SELECT" => array("ID","UF_CONTACT"),
       )
   );
   if($arUser = $rsUser->Fetch()){         
      $companyId = intval($arUser["UF_CONTACT"]);
       if($companyId>0 && CModule::IncludeModule('crm')){                 
          $arFilter = array("ID"=>$companyId,"CHECK_PERMISSIONS"=>"N");
          $arSelect = array("ID","TITLE");
          $rsCompany = CCrmCompany::GetList(Array(),$arFilter,$arSelect);
          if($arCompany = $rsCompany->Fetch()){   
             $entityRequisite = new \Bitrix\Crm\EntityRequisite;
             $rsRequisite = $entityRequisite->getList([
                "select"=>array("*"),
                "filter"=>array(
                   "ENTITY_ID"=>$companyId,
                   "ID"=> intval($_REQUEST["req_id"]),
                   "ENTITY_TYPE_ID"=>CCrmOwnerType::Company
                ),
                "order"=>array("SORT"=>"desc","ID"=>"desc")

             ]);
             $arRequisiteOld = $rsRequisite->fetchAll();
             $arRequisiteTemp = $arRequisiteOld[0];
             if(isset($arRequisiteTemp['ID']) && (intval($arRequisiteTemp['ID'])>0)){
                $arRequisite = $_REQUEST['fields'];
                if($_REQUEST["type_company"] == "ip"){
                   //ИП
                   $arFields = array(                                                      
                     'NAME' => $arRequisite['RQ_COMPANY_NAME'],                           
                     'ACTIVE' => 'Y',
                     'RQ_LAST_NAME' => $arRequisite['RQ_LAST_NAME'],
                     'RQ_FIRST_NAME' => $arRequisite["RQ_FIRST_NAME"],
                     'RQ_SECOND_NAME' => $arRequisite["RQ_SECOND_NAME"],                              
                     'RQ_COMPANY_FULL_NAME' => $arRequisite['RQ_COMPANY_FULL_NAME'],                              
                     'RQ_INN' => $arRequisite["RQ_INN"], //инн                              
                     'RQ_OGRNIP' => $arRequisite["RQ_OGRNIP"], //огрн
                     'RQ_OKVED' => "",                           
                  );
                }
                else{
                   //юр лицо
                   $arFields = array(                                                   
                     'NAME' => $arRequisite['RQ_COMPANY_NAME'],
                     'SORT' => 500,
                     'ACTIVE' => 'Y',
                     'RQ_COMPANY_NAME' => $arRequisite['RQ_COMPANY_NAME'],
                     'RQ_COMPANY_FULL_NAME' => $arRequisite['RQ_COMPANY_FULL_NAME'],                              
                     'RQ_INN' => $arRequisite["RQ_INN"], //инн
                     'RQ_KPP' => $arRequisite["RQ_KPP"],  //кпп
                     'RQ_OGRN' => $arRequisite["RQ_OGRN"], //огрн
                     'RQ_COMPANY_REG_DATE' => "",
                     'RQ_OKVED' => "",   
                     'RQ_DIRECTOR' => $arRequisite["RQ_DIRECTOR"],
                     'RQ_ACCOUNTANT' => $arRequisite["RQ_ACCOUNTANT"]                           
                  );
                }
                $entityRequisite->Update(intval($arRequisiteTemp['ID']),$arFields);                   

                $bank   = new \Bitrix\Crm\EntityBankDetail();
               $dbRes  = $bank->getList(array(
                   'filter' => array('ENTITY_ID' => $arRequisiteTemp['ID'])
               ));
               $arBankOld =  $dbRes->Fetch();
               
               $arFields = array(
                  "RQ_BANK_NAME" => $arRequisite["RQ_BANK_NAME"],
                  "RQ_BIK" => $arRequisite["RQ_BIK"],
                  "RQ_ACC_NUM" => $arRequisite["RQ_ACC_NUM"],
                  "RQ_COR_ACC_NUM" => $arRequisite["RQ_COR_ACC_NUM"],
                  "RQ_BANK_ADDR" => $arRequisite["RQ_BANK_ADDR"],
               );
               if($arBankOld["ID"] >0){
                  $bank->Update(intval($arBankOld["ID"]),$arFields);
               }

               $address = new \Bitrix\Crm\EntityAddress();
               $address->deleteByEntity(2, $arRequisiteTemp['ID']);
               $address->deleteByEntity(6, $arRequisiteTemp['ID']);

               //юр адрес
               $arFields = array(
                  "ADDRESS_1" => $arRequisite["company_addr_address_1"],
                  "ADDRESS_2" => $arRequisite["company_addr_address_2"],
                  "CITY" => $arRequisite["company_addr_city"],
                  "POSTAL_CODE" => $arRequisite["company_addr_postal_code"],
                  "COUNTRY" => $arRequisite["company_addr_country"],
                  "REGION" => $arRequisite["company_addr_region"],
                  "PROVINCE" => $arRequisite["company_addr_province"],
               );
               $res = $address->register(8, $arRequisiteTemp['ID'], 6, $arFields);
               
               //факт адрес
               $arFields = array(
                  "ADDRESS_1" => $arRequisite["company_realaddr_address_1"],
                  "ADDRESS_2" => $arRequisite["company_realaddr_address_2"],
                  "CITY" => $arRequisite["company_realaddr_city"],
                  "POSTAL_CODE" => $arRequisite["company_realaddr_postal_code"],
                  "COUNTRY" => $arRequisite["company_realaddr_country"],
                  "REGION" => $arRequisite["company_realaddr_region"],
                  "PROVINCE" => $arRequisite["company_realaddr_province"],
               );
               $res = $address->register(8, $arRequisiteTemp['ID'], 2, $arFields);
               
               echo Cutil::PhpToJSObject(true);
               die();

             }   
             
          }
       }
   }   
}
получить контакта по компании
 $arDelete = array();
$res = CCrmContact::GetContactByCompanyId($arFields['ID']);
while ($ar = $res->Fetch()) {
     $arDelete[] = $ar['ID'];
}
$CCrmContact = new CCrmContact();
$CCrmContact->UpdateCompanyId($arDelete, 0);

отправим уведомление в мессенджер
$arFields = array(
   "MESSAGE_TYPE" => "S", # P - private chat, G - group chat, S - notification
   "TO_USER_ID" => $manager,
   "FROM_USER_ID" => $arNewUser["ID"],
   "MESSAGE" => "Новый клиент",
   "AUTHOR_ID" => $arNewUser["ID"],
   "EMAIL_TEMPLATE" => "some",

   "NOTIFY_TYPE" => 2,  # 1 - confirm, 2 - notify single from, 4 - notify single
   "NOTIFY_MODULE" => "main", # module id sender (ex: xmpp, main, etc)
   "NOTIFY_EVENT" => "IM_GROUP_INVITE", # module event id for search (ex, IM_GROUP_INVITE)
   "NOTIFY_TITLE" => "Новый клиент", # notify title to send email
);
if(CModule::IncludeModule('im')){
   CIMMessenger::Add($arFields);
}


перезвоните мне от клиента
$rsUser = CUser::GetList($by, $order,
    array("ID" => $USER->GetID()),
    array(
        "SELECT" => array("ID","NAME","UF_CONTACT","PERSONAL_MOBILE"),
    )
);
if($arUser = $rsUser->Fetch()){                
    $companyId = $arUser["UF_CONTACT"];        
    if(intval($companyId)>0 && CModule::IncludeModule('crm') && CModule::IncludeModule('im')){                                 
       $arComp = CCrmCompany::GetByID(intval($companyId),false);
       $managerId = $arComp["ASSIGNED_BY_ID"];
       if($managerId >0 && ($USER->GetID() != $managerId)){                        
          $result = CIMMessage::Add(array(  
              'FROM_USER_ID' => $USER->GetID(),  
              'TO_USER_ID' => $managerId, 
              'MESSAGE' => 'Перезвоните мне, пожалуйста! Тел: '.$arUser["PERSONAL_MOBILE"], 
          ));                      
       }
    }
}

создать рабочую группу и ее диск из бизнес-процесса
CModule::IncludeModule('socialnetwork');
CModule::IncludeModule('disk');
CModule::IncludeModule('webdav');
 
$SocGroup=new CSocNetGroup;
global $USER;
 
$arFieldsSG=array(
   "NAME"=>"{=Document:TITLE}",
   "SITE_ID" => "s1",
   "DESCRIPTION"=>"{=Document:TITLE} Workgroup",
   "ACTIVE"=>"Y",
   "VISIBLE"=>"Y",
   "OPENED"=>"Y",
   "CLOSED"=>"N",
   "SUBJECT_ID"=>4,
   "OWNER_ID"=>1,
   "INITIATE_PERMS"=>A,
   "SPAM_PERMS"=>"N",
   "SUBJECT_NAME"=>"Management Board"
 
);
 
$GroupID=CSocNetGroup::CreateGroup($USER->GetID(),$arFieldsSG);
 
if (CModule::IncludeModule("disk")){
   BitrixDiskDriver::getInstance()->addGroupStorage($GroupID);
}
 
$this->SetVariable('WORKGROUPID',$GroupID);



добавить событие в календарь пользователя
$fromTs = MakeTimeStamp($_POST['from'], "MM/DD/YYYYS");
$toTs = MakeTimeStamp($_POST['to'], "MM/DD/YYYYS");
$arFields = array(
    "OWNER_ID" => 1,
     "CAL_TYPE" =>'user',
   "NAME" => $_POST['eventName'],
   "DESCRIPTION" => $_POST['description'],
   "SKIP_TIME" => date('H:i', $fromTs) == '00:00' && date('H:i', $toTs) == '00:00',
   "IS_MEETING" => false,
   "RRULE" => false,
   "DT_FROM_TS" => $fromTs,
   "DT_TO_TS" => $toTs
);

$CalEventId = CCalendar::SaveEvent(
   array(
      'arFields' => $arFields,
      'autoDetectSection' => true
   )
);
запустить бизнес-процесс, не привязанный к CRM
$documentId = CBPVirtualDocument::CreateDocument(
    0,
    array(
     "IBLOCK_ID" => 27,
     "NAME" => "Create Notification",
     "CREATED_BY" => "user_".$GLOBALS["USER"]->GetID(),
    )
);
$arErrorsTmp = array();
$wfId = CBPDocument::StartWorkflow(
   $bpId,
    array("bizproc", "CBPVirtualDocument", $documentId),
    array_merge(array(), array("TargetUser" => "user_".intval($GLOBALS["USER"]->GetID()))),
    $arErrorsTmp
);
добавить лид
CModule::IncludeModule('crm');
 
$lead = new CCrmLead;
 
$arFields = Array(
    "TITLE" => "Заголовок",
    "COMPANY_TITLE" => "Название компании",
   "NAME" => "Имя",
   "LAST_NAME" => "Фамилия",
   SECOND_NAME" => "Отчество",
   "POST" => "Должность",
   "ADDRESS" => "Адрес",
   "COMMENTS" => "Комментарий",
    "SOURCE_DESCRIPTION" => "",
   "STATUS_DESCRIPTION" => "",
   //"OPPORTUNITY" => 123456,
   "CURRENCY_ID" => "RUB",
   //"PRODUCT_ID" => "PRODUCT_1",
   "SOURCE_ID" => "SELF",
       "STATUS_ID" => "NEW",
       "ASSIGNED_BY_ID" => $userId,  
       "UF_CRM_143192342342" => "",   
   );
 
$lidId = $lead->Add($arFields);