Files
crm.clientright.ru/include/Webservices/CreateWebContact.php
Fedor 01c4fe80b5 chore: snapshot current working tree changes
Save all currently accumulated repository changes as a backup snapshot for Gitea so no local work is lost.
2026-03-26 14:19:01 +03:00

159 lines
7.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/*********************************************************************************
* API-интерфейс для создания Контакта из Web-формы (упрощённый)
* Обязательное поле: только mobile
* Логика: если контакт существует - возвращаем ID БЕЗ обновления
* Автор: Фёдор, 2025-10-30
********************************************************************************/
include_once 'include/Webservices/Query.php';
include_once 'modules/Users/Users.php';
require_once('include/Webservices/Utils.php');
require_once 'include/Webservices/Create.php';
require_once 'includes/Loader.php';
vimport ('includes.runtime.Globals');
vimport ('includes.runtime.BaseModel');
vimport ('includes.runtime.LanguageHandler');
/**
* Создание контакта из web-формы
* Если контакт с таким mobile уже существует - просто возвращаем его ID
* @param string $mobile - номер телефона (обязательное поле)
* @param string $firstname - имя (опционально)
* @param string $lastname - фамилия (опционально)
* @param string $email - email (опционально)
* @return array - Массив с contact_id, is_new, cf_2624 (Данные подтверждены) и unified_id (cf_2616)
*/
function vtws_createwebcontact($mobile, $firstname = '', $lastname = '', $email = '', $user = false) {
// ✅ Очищаем буфер вывода и подавляем warnings
ob_start();
$logstring = date("Y-m-d H:i:s").' '.json_encode($_REQUEST);
file_put_contents('logs/CreateWebContact.log', $logstring.PHP_EOL, FILE_APPEND);
// Проверка обязательного поля
if(empty($mobile)){
ob_end_clean();
$logstring = date("Y-m-d H:i:s").' Не указано обязательное поле: mobile';
file_put_contents('logs/CreateWebContact.log', $logstring.PHP_EOL, FILE_APPEND);
throw new WebServiceException(WebServiceErrorCode::$INVALIDID, "Не указан номер телефона (mobile)");
}
// Форматирование телефона: убираем всё кроме цифр
$mobile = preg_replace('/[^0-9]/', '', $mobile);
if (strlen($mobile) == 11 && $mobile[0] == '8') {
$mobile = "7".substr($mobile, 1);
} else if (strlen($mobile) == 10) {
$mobile = "7".$mobile;
} else if (strlen($mobile) != 11 || $mobile[0] != '7') {
ob_end_clean();
$logstring = date("Y-m-d H:i:s").' Некорректный номер телефона: '.$mobile;
file_put_contents('logs/CreateWebContact.log', $logstring.PHP_EOL, FILE_APPEND);
throw new WebServiceException(WebServiceErrorCode::$INVALIDID, "Некорректный номер телефона");
}
$logstring = date('Y-m-d H:i:s').' Ищем контакт по mobile='.$mobile.PHP_EOL;
file_put_contents('logs/CreateWebContact.log', $logstring, FILE_APPEND);
global $adb, $current_user;
$isNew = false; // Флаг: создан ли контакт сейчас
// Проверяем существование контакта по номеру телефона
// ✅ Добавляем выборку полей cf_2624 (Данные подтверждены) и cf_2616 (unified_id)
$query = "select c.contactid, cf.cf_2624, cf.cf_2616
from vtiger_contactdetails c
left join vtiger_crmentity e on e.crmid = c.contactid
left join vtiger_contactscf cf on cf.contactid = c.contactid
where e.deleted = 0 and c.mobile = ?
limit 1";
$result = $adb->pquery($query, array($mobile));
$cf_2624_value = "0"; // По умолчанию "Нет" (данные не подтверждены)
$unified_id = null; // По умолчанию null
if ($adb->num_rows($result) > 0) {
// Контакт существует - ПРОСТО ВОЗВРАЩАЕМ ID (НЕ обновляем!)
$output = $adb->query_result($result, 0, 'contactid');
$isNew = false;
// ✅ Получаем значение поля cf_2624 (Данные подтверждены)
$cf_2624_value = $adb->query_result($result, 0, 'cf_2624');
if (empty($cf_2624_value)) {
$cf_2624_value = "0"; // По умолчанию "Нет"
}
// ✅ Получаем значение поля cf_2616 (unified_id)
$unified_id = $adb->query_result($result, 0, 'cf_2616');
if (empty($unified_id)) {
$unified_id = null; // Если пустое - возвращаем null
}
$logstring = date('Y-m-d H:i:s').' ✅ Контакт найден с id '.$output.', cf_2624='.$cf_2624_value.', unified_id='.($unified_id ?? 'null').' (БЕЗ обновления)'.PHP_EOL;
file_put_contents('logs/CreateWebContact.log', $logstring, FILE_APPEND);
} else {
// Контакт НЕ существует - создаём новый
// Дефолтные значения если не указаны
if (empty($firstname)) {
$firstname = 'Клиент';
}
if (empty($lastname)) {
$lastname = 'ERV_' . substr($mobile, -4); // ERV_4567
}
$params = array (
'firstname' => $firstname,
'lastname' => $lastname,
'mobile' => $mobile,
'email' => $email,
'birthday' => '01-01-1990', // Дефолтная дата
'cf_1257' => '', // ИНН пустой
'cf_1157' => '', // Отчество пустое
'cf_1263' => '', // Место рождения пустое
'mailingstreet' => '', // Адрес пустой
'cf_1849' => '', // Реквизиты пустые
'cf_1580' => '', // Код пустой
'cf_2624' => '0', // ✅ Данные подтверждены = "Нет" (по умолчанию для новых контактов)
'assigned_user_id' => vtws_getWebserviceEntityId('Users', $current_user->id)
);
$logstring = date('Y-m-d H:i:s').' Массив для создания Web Контакта: '.json_encode($params).PHP_EOL;
file_put_contents('logs/CreateWebContact.log', $logstring, FILE_APPEND);
try {
$contact = vtws_create('Contacts', $params, $current_user);
$output = substr($contact['id'], 3);
$isNew = true; // Контакт только что создан!
$cf_2624_value = "0"; // Новый контакт - данные не подтверждены
$unified_id = null; // Новый контакт - unified_id ещё не установлен
$logstring = date('Y-m-d H:i:s').' ✅ Создан новый Web Контакт с id '.$output.', cf_2624=0, unified_id=null'.PHP_EOL;
file_put_contents('logs/CreateWebContact.log', $logstring, FILE_APPEND);
} catch (WebServiceException $ex) {
ob_end_clean();
$logstring = date('Y-m-d H:i:s').' ❌ Ошибка создания: '.$ex->getMessage().PHP_EOL;
file_put_contents('logs/CreateWebContact.log', $logstring, FILE_APPEND);
throw $ex;
}
}
// Возвращаем массив (vTiger сам сделает json_encode)
$result = array(
'contact_id' => $output,
'is_new' => $isNew,
'cf_2624' => $cf_2624_value, // ✅ "1" = данные подтверждены, "0" = не подтверждены
'unified_id' => $unified_id // ✅ unified_id из поля cf_2616 или null
);
$logstring = date('Y-m-d H:i:s').' Return: '.json_encode($result).PHP_EOL;
file_put_contents('logs/CreateWebContact.log', $logstring, FILE_APPEND);
// ✅ Очищаем буфер (удаляем все warnings/notices)
ob_end_clean();
return $result;
}
?>