Добрый день!
Помогите разобраться, необходимо записывать параметр LINE который приходит от АТС в поле дополнительно о лиде в CRM
Редактирую в модуле телефонииbitrix/ modules/ vedisoft.prostiezvonki/ lib/Main.php
Помогите разобраться, необходимо записывать параметр LINE который приходит от АТС в поле дополнительно о лиде в CRM
Редактирую в модуле телефонии
Код |
---|
<?php namespace Prostiezvonki; use Bitrix\Main\Config\Option; use Bitrix\Main\Localization\Loc; use crm\CCrmCallToUrl; use CJSCore; Loc::loadMessages(__FILE__); class Main { static $MODULE_ID = 'vedisoft.prostiezvonki'; static $ADMIN_MODULE_NAME = 'vedisoft_prostiezvonki'; static $settings = array(); static public function OnPageStartHandler($arFields) { global $APPLICATION; CJSCore::Init(array("jquery")); $path = '/bitrix/js/prostiezvonki/'; $APPLICATION->AddHeadScript($path . 'prostiezvonki.js'); $APPLICATION->AddHeadScript($path . 'pz.js'); $APPLICATION->AddHeadScript($path . 'noty/jquery.noty.js'); $APPLICATION->AddHeadScript($path . 'noty/layouts/bottomRight.js'); $APPLICATION->AddHeadScript($path . 'noty/themes/default.js'); $APPLICATION->SetAdditionalCSS($path . 'css/pz.css'); } static public function getUserPhoneNumber($userId = null) { global $USER; if (!$userId) { $userId = $USER->GetID(); } $rsUser = \CUser::GetByID($userId); $arUser = $rsUser->Fetch(); return $arUser['UF_PHONE_INNER']; } static public function getOption($name, $default = null) { return Option::get(self::$ADMIN_MODULE_NAME, $name, $default); } static public function setOption($name, $value) { Option::set(self::$ADMIN_MODULE_NAME, $name, $value); } static public function storeEvent($event) { $result = PhoneCallsTable::add(array( 'PHONE_MASTER' => $event['fr om'], 'PHONE_SLAVE' => $event['to'], 'DIRECTION' => $event['direction'], 'TALK_START' => \Bitrix\Main\Type\DateTime::createFromTimestamp($event['start']), 'TALK_END' => \Bitrix\Main\Type\DateTime::createFromTimestamp($event['end']), 'TALK_DURATION' => $event['duration'], )); if (!$result->isSuccess()) { throw new ErrorException(implode("\n", $result->getErrorMessages())); } global $curUser; $siteID = SITE_ID; $clientPhone = !empty($event['direction']) ? $event['to'] : $event['from']; $userPhone = empty($event['direction']) ? $event['to'] : $event['from']; $owner = self::getOwner($clientPhone); $data['communication'] = array( 'type' => 'PHONE', 'entityType' => $owner['type'], 'entityId' => $owner['id'], 'value' => $clientPhone, ); $ownerTypeName = $owner['type']; if (empty($ownerTypeName)) { throw new ErrorException('OWNER TYPE IS NOT DEFINED!'); } $ownerTypeID = \CCrmOwnerType::ResolveID($ownerTypeName); if (!\CCrmOwnerType::IsDefined($ownerTypeID)) { throw new ErrorException('OWNER TYPE IS NOT SUPPORTED!'); } $ownerID = $owner['id']; if ($ownerID <= 0) { throw new ErrorException('OWNER ID IS NOT DEFINED!'); } if (!\CCrmActivity::CheckUpdatePermission($ownerTypeID, $ownerID)) { throw new ErrorException('CRM_PERMISSION_DENIED'); } $responsibleID = 0; $userID = \CCrmSecurityHelper::GetCurrentUser()->GetID(); if ($userID <= 0) { $userID = \CCrmOwnerType::GetResponsibleID($ownerTypeID, $ownerID, false); if ($userID <= 0) { throw new ErrorException('CRM_ACTIVITY_RESPONSIBLE_NOT_FOUND'); } } $start = \ConvertTimeStamp($event['start'], 'FULL'); $end = \ConvertTimeStamp($event['end'], 'FULL'); $direction = $event['direction'] + 1; // Communications $commData = isset($data['communication']) ? $data['communication'] : array(); $commID = isset($commData['id']) ? intval($commData['id']) : 0; $commEntityType = isset($commData['entityType']) ? strtoupper(strval($commData['entityType'])) : ''; $commEntityID = isset($commData['entityId']) ? intval($commData['entityId']) : 0; $commType = isset($commData['type']) ? strtoupper(strval($commData['type'])) : ''; $commValue = isset($commData['value']) ? strval($commData['value']) : ''; list($date, $time) = explode(' ', $start); $subject = GetMessage('SUBJECT_FOR_PHONECALL', array( '#FROM#' => $event['from'], '#TO#' => $event['to'], '#LINE#' => $event['line'], '#DURATION#' => Duration::format($event['duration']), '#DATE#' => $date, '#TIME#' => $time, )); $description = GetMessage('DESCRIPTION_FOR_PHONECALL', array( '#FROM#' => $event['from'], '#TO#' => $event['to'], )); if ($event['record']) { $description .= ', ' . GetMessage('LINK_FOR_PHONECALL', array( '#RECORD#' => $event['record'], )); } $fields = array( 'TYPE_ID' => \CCrmActivityType::Call, 'SUBJECT' => $subject, 'COMPLETED' => 'Y', 'PRIORITY' => \CCrmActivityPriority::Medium, 'DESCRIPTION' => $description, 'DESCRIPTION_TYPE' => \CCrmContentType::Html, 'LOCATION' => '', 'DIRECTION' => $direction, 'NOTIFY_TYPE' => \CCrmActivityNotifyType::None, 'SETTINGS' => array() ); $bindings = array( "{$ownerTypeName}_{$ownerID}" => array( 'OWNER_TYPE_ID' => $ownerTypeID, 'OWNER_ID' => $ownerID ) ); $isNew = true; $fields['START_TIME'] = $start; $fields['END_TIME'] = $end; $fields['OWNER_ID'] = $ownerID; $fields['OWNER_TYPE_ID'] = $ownerTypeID; $fields['RESPONSIBLE_ID'] = $responsibleID > 0 ? $responsibleID : $userID; $fields['BINDINGS'] = array_values($bindings); $ID = \CCrmActivity::Add($fields, false, true, array( 'REGISTER_SONET_EVENT' => true )); if (!$ID) { throw new ErrorException(\CCrmActivity::GetLastErrorMessage()); } $comms[] = array( 'ID' => $commID, 'TYPE' => $commType, 'VALUE' => $commValue, 'ENTITY_ID' => $commEntityID, 'ENTITY_TYPE_ID' => \CCrmOwnerType::ResolveID($commEntityType) ); \CCrmActivity::SaveCommunications($ID, $comms, $fields, !$isNew, false); \CCrmActivity::SaveRecentlyUsedCommunication(current($comms)); return $fields; } public static function getOwner($phone) { $owners = self::getOwners($phone); $types = array( 'CONTACT', 'COMPANY', 'LEAD', ); foreach ($types as $type) { if (!empty($owners[$type])) { $entity = current($owners[$type]); if ($type == 'COMPANY') { $entity['FULL_NAME'] = $entity['TITLE']; } if ($type == 'LEAD') { if ($entity['FULL_NAME']) { $entity['FULL_NAME'] = $entity['TITLE'] . ' (' . $entity['FULL_NAME'] . ')'; } else { $entity['FULL_NAME'] = $entity['TITLE']; } } return array( 'type' => $type, 'id' => $entity['ID'], 'body' => $entity['FULL_NAME'], 'entity' => $entity, 'header' => Loc::getMessage('NOTY_HEADER'), 'footer' => Loc::getMessage('NOTY_FOOTER'), ); } } if (self::getOption('lead_autocreation', false)) { $last_autolead = trim(file_get_contents('prostiezvonki.txt')); if ($last_autolead == $phone) { sleep(1); return self::getOwner($phone); } $entity = self::createNewLead($phone); } else { $entity = null; } if (!$entity) { return array( 'type' => 0, 'id' => 0, 'body' => Loc::getMessage('UNKNOWN_PHONENUMBER'), 'entity' => null, 'header' => Loc::getMessage('NOTY_HEADER'), 'footer' => Loc::getMessage('NOTY_FOOTER'), ); } if ($entity['FULL_NAME']) { $entity['FULL_NAME'] = $entity['TITLE'] . ' (' . $entity['FULL_NAME'] . ')'; } else { $entity['FULL_NAME'] = $entity['TITLE']; } return array( 'type' => 'LEAD', 'id' => $entity['ID'], 'body' => $entity['FULL_NAME'], 'entity' => $entity, 'header' => Loc::getMessage('NOTY_HEADER'), 'footer' => Loc::getMessage('NOTY_FOOTER'), ); } public static function getOwners($phone) { if (!\CModule::IncludeModule('crm')) { return array(); } /* @var $DB \CDatabase */ global $DB; $sql = " SEL ECT CFM.ID, CFM.ENTITY_ID, CFM.ELEMENT_ID, CFM.TYPE_ID, CFM.VALUE_TYPE, CFM.COMPLEX_ID, CFM.VALUE FR OM b_crm_field_multi CFM WH ERE CFM.ENTITY_ID IN ('LEAD', 'CONTACT', 'COMPANY') AND CFM.TYPE_ID = 'PHONE' AND <field> LIKE '<value>' ORDER BY CFM.ID asc "; $strSql = strtr($sql, array( '<field>' => self::prepareDatabasePhone('CFM.VALUE'), '<value>' => $DB->forSql('%' . self::correctPhone($phone)), )); $dbResult = $DB->Query($strSql, false, $err_mess . __LINE__); $owners = array(); if ($dbResult->errorno) { return $owners; } while ($row = $dbResult->GetNext()) { $entity = self::getCrmEntity($row['ENTITY_ID'], $row['ELEMENT_ID']); $owners[$row['ENTITY_ID']][] = $entity; } return $owners; } public static function createNewLead($phone) { file_put_contents('prostiezvonki.txt', $phone); $multifields = array( 'PHONE' => $phone, ); $params = array( 'TITLE' => Loc::getMessage('NEW_AUTO_LEAD') . $phone, 'PHONE' => $phone, ); $fields = self::getLeadRequiredFields(); foreach ($fields as $field => $attrs) { $field_name = 'lead_' . strtolower($field); if ($attrs['TYPE'] == 'crm_multifield') { $multifields[$field] = self::getOption($field_name, null); continue; } $params[$field] = self::getOption($field_name, null); } $lead = new \CCrmLead; $lead_id = $lead->Add($params); if (!$lead_id) { file_put_contents('prostiezvonki.txt', ''); return false; } $multi_fields = \CCrmFieldMulti::GetEntityTypes(); if (empty($multi_fields['PHONE'])) { file_put_contents('prostiezvonki.txt', ''); return false; } foreach ($multifields as $field => $value) { $params = array( 'ENTITY_ID' => 'LEAD', 'ELEMENT_ID' => $lead_id, 'TYPE_ID' => $field, 'VALUE_TYPE' => array_shift($multi_fields[$field]), 'VALUE' => $value, ); $multi_field = new \CCrmFieldMulti; $multi_field->Add($params); if (!$multi_field) { file_put_contents('prostiezvonki.txt', ''); return false; } } return array( 'ID' => $lead_id, 'TITLE' => Loc::getMessage('NEW_AUTO_LEAD') . $phone, ); } public static function getLeadRequiredFields() { if (!\CModule::IncludeModule("crm")) { return false; } $fields = \CCrmLead::GetFieldsInfo(); $multis = \CCrmFieldMulti::GetEntityTypeInfos(); foreach($multis as $id => $multi) { $fields[$id] = array( 'TYPE' => 'crm_multifield', 'ATTRIBUTES' => array(\CCrmFieldInfoAttr::Multiple), 'LABELS' => array( 'FORM' => $multi['NAME'], ), ); } $userType = new \CCrmUserType($GLOBALS['USER_FIELD_MANAGER'], \CCrmLead::$sUFEntityID); $userType->PrepareFieldsInfo($fields); foreach ($fields as $field => $attrs) { if ($field == 'TITLE' || $field == 'PHONE') { unset($fields[$field]); } if (array_search('REQ', $attrs['ATTRIBUTES']) === false || is_null(array_search('REQ', $attrs['ATTRIBUTES']))) { unset($fields[$field]); } } return $fields; } public static function prepareDatabasePhone($phone_field) { $phone_field = "REPLACE($phone_field, '+', '')"; $phone_field = "REPLACE($phone_field, ' ', '')"; $phone_field = "REPLACE($phone_field, '-', '')"; $phone_field = "REPLACE($phone_field, ')', '')"; $phone_field = "REPLACE($phone_field, '(', '')"; return $phone_field; } public static function getCrmEntity($type, $id) { switch ($type) { case 'CONTACT': $object = \CCrmContact::GetByID($id, false); break; case 'LEAD': $object = \CCrmLead::GetByID($id, false); break; case 'COMPANY': $object = \CCrmCompany::GetByID($id, false); break; } return $object; } protected static function correctPhone($phone) { $number = preg_replace('/[^0-9]/u', '', $phone); return substr($number, - (int) self::getOption('phone_length', 7)); } } |