Files
crm.clientright.ru/include/Webservices/CreateWebClaim.php

193 lines
8.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-интерфейс для создания Заявки (HelpDesk) из Web-формы
* Обязательные поля: title, contact_id, project_id, event_type
* Автор: Фёдор, 2025-11-01
********************************************************************************/
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-формы ERV Platform
*
* @param string $title - название заявки (обязательно)
* @param string $contact_id - ID контакта для привязки (обязательно)
* @param string $project_id - ID проекта для привязки (обязательно)
* @param string $event_type - тип страхового случая (обязательно)
* @param string $description - описание заявки (опционально)
* @param string $incident_date - дата инцидента (опционально)
* @param string $transport_number - номер рейса/поезда/парома (опционально)
* @return array - {"ticket_id": "123", "ticket_number": "TT12345"}
*/
function vtws_createwebclaim($title, $contact_id, $project_id, $event_type, $description = '', $incident_date = '', $transport_number = '', $user = false) {
// ✅ Очищаем буфер вывода и подавляем warnings
ob_start();
$logstring = date("Y-m-d H:i:s").' CreateWebClaim: '.json_encode($_REQUEST);
file_put_contents('logs/CreateWebClaim.log', $logstring.PHP_EOL, FILE_APPEND);
// Проверка обязательных полей
if(empty($title)){
ob_end_clean();
$logstring = date("Y-m-d H:i:s").' Не указано обязательное поле: title';
file_put_contents('logs/CreateWebClaim.log', $logstring.PHP_EOL, FILE_APPEND);
throw new WebServiceException(WebServiceErrorCode::$INVALIDID, "Не указано название заявки");
}
if(empty($contact_id)){
ob_end_clean();
$logstring = date("Y-m-d H:i:s").' Не указано обязательное поле: contact_id';
file_put_contents('logs/CreateWebClaim.log', $logstring.PHP_EOL, FILE_APPEND);
throw new WebServiceException(WebServiceErrorCode::$INVALIDID, "Не указан ID контакта");
}
if(empty($project_id)){
ob_end_clean();
$logstring = date("Y-m-d H:i:s").' Не указано обязательное поле: project_id';
file_put_contents('logs/CreateWebClaim.log', $logstring.PHP_EOL, FILE_APPEND);
throw new WebServiceException(WebServiceErrorCode::$INVALIDID, "Не указан ID проекта");
}
if(empty($event_type)){
ob_end_clean();
$logstring = date("Y-m-d H:i:s").' Не указано обязательное поле: event_type';
file_put_contents('logs/CreateWebClaim.log', $logstring.PHP_EOL, FILE_APPEND);
throw new WebServiceException(WebServiceErrorCode::$INVALIDID, "Не указан тип страхового случая");
}
global $adb, $current_user;
// Нормализуем ID контакта и проекта (можно передавать как "12x123" или "123")
$contactIdNumeric = preg_replace('/[^0-9]/', '', $contact_id);
$projectIdNumeric = preg_replace('/[^0-9]/', '', $project_id);
$contactWsId = '12x' . $contactIdNumeric;
$projectWsId = '33x' . $projectIdNumeric;
$logstring = date('Y-m-d H:i:s').' Нормализовали ID: contact='.$contactIdNumeric.' (raw='.$contact_id.'), project='.$projectIdNumeric.' (raw='.$project_id.')'.PHP_EOL;
file_put_contents('logs/CreateWebClaim.log', $logstring, FILE_APPEND);
// Маппинг типов событий на русские названия для категории
$eventTypeMap = array(
'delay_flight' => 'Задержка рейса',
'cancel_flight' => 'Отмена рейса',
'missed_connection' => 'Пропуск стыковки',
'delay_train' => 'Задержка поезда',
'cancel_train' => 'Отмена поезда',
'delay_ferry' => 'Задержка парома',
'cancel_ferry' => 'Отмена парома'
);
$ticketCategory = isset($eventTypeMap[$event_type]) ? $eventTypeMap[$event_type] : 'Цифровой адвокат ЕРВ';
// Формируем title если не указан
if (empty($title)) {
$title = $ticketCategory;
if (!empty($transport_number)) {
$title .= ' ' . $transport_number;
}
}
// Формируем описание
$fullDescription = '';
if (!empty($description)) {
$fullDescription .= $description . "\n\n";
}
if (!empty($event_type)) {
$fullDescription .= "Тип события: " . $ticketCategory . "\n";
}
if (!empty($incident_date)) {
$fullDescription .= "Дата инцидента: " . $incident_date . "\n";
}
if (!empty($transport_number)) {
$fullDescription .= "Номер транспорта: " . $transport_number . "\n";
}
$fullDescription .= "\nИсточник: ERV Platform Web Form";
try {
$params = array (
'ticket_title' => $title,
'parent_id' => '11x67458', // Заявитель - контрагент
'ticketcategories' => $ticketCategory,
'ticketstatus' => 'рассмотрение',
'contact_id' => $contactWsId,
'cf_2066' => $projectWsId, // Связь с проектом
'ticketpriorities' => 'High',
'assigned_user_id' => vtws_getWebserviceEntityId('Users', $current_user->id),
'description' => $fullDescription
);
$logstring = date('Y-m-d H:i:s').' Массив для создания Заявки: '.json_encode($params).PHP_EOL;
file_put_contents('logs/CreateWebClaim.log', $logstring, FILE_APPEND);
$result = vtws_create('HelpDesk', $params, $current_user);
$ticketId = substr($result['id'], 3); // Убираем префикс "17x"
$ticketNumber = isset($result['ticket_no']) ? $result['ticket_no'] : 'N/A';
$logstring = date('Y-m-d H:i:s').' ✅ Создана Заявка id='.$ticketId.' ticket_no='.$ticketNumber.PHP_EOL;
file_put_contents('logs/CreateWebClaim.log', $logstring, FILE_APPEND);
// 🚧 Создаём двустороннюю связь между Проектом и Заявкой
try {
$relationCheck = $adb->pquery(
"SELECT 1 FROM vtiger_crmentityrel
WHERE (crmid = ? AND relcrmid = ?)
OR (crmid = ? AND relcrmid = ?)
LIMIT 1",
array($projectIdNumeric, $ticketId, $ticketId, $projectIdNumeric)
);
if (!$relationCheck || $adb->num_rows($relationCheck) === 0) {
$adb->pquery(
"INSERT INTO vtiger_crmentityrel (crmid, module, relcrmid, relmodule) VALUES (?, ?, ?, ?)",
array($projectIdNumeric, 'Project', $ticketId, 'HelpDesk')
);
$logstring = date('Y-m-d H:i:s').' 🔗 Добавлена связь Project('.$projectIdNumeric.') ⇄ HelpDesk('.$ticketId.')'.PHP_EOL;
file_put_contents('logs/CreateWebClaim.log', $logstring, FILE_APPEND);
} else {
$logstring = date('Y-m-d H:i:s').' 🔗 Связь Project('.$projectIdNumeric.') ⇄ HelpDesk('.$ticketId.') уже существует'.PHP_EOL;
file_put_contents('logs/CreateWebClaim.log', $logstring, FILE_APPEND);
}
} catch (Exception $relEx) {
$logstring = date('Y-m-d H:i:s').' ⚠️ Ошибка связывания Project('.$projectIdNumeric.') ⇄ HelpDesk('.$ticketId.'): '.$relEx->getMessage().PHP_EOL;
file_put_contents('logs/CreateWebClaim.log', $logstring, FILE_APPEND);
}
// Возвращаем массив (vTiger сам сделает json_encode)
$output = array(
'ticket_id' => $ticketId,
'ticket_number' => $ticketNumber,
'title' => $title,
'category' => $ticketCategory,
'status' => 'рассмотрение'
);
} catch (WebServiceException $ex) {
ob_end_clean();
$logstring = date('Y-m-d H:i:s').' ❌ Ошибка создания: '.$ex->getMessage().PHP_EOL;
file_put_contents('logs/CreateWebClaim.log', $logstring, FILE_APPEND);
throw $ex;
}
$logstring = date('Y-m-d H:i:s').' Return: '.json_encode($output).PHP_EOL;
file_put_contents('logs/CreateWebClaim.log', $logstring, FILE_APPEND);
// ✅ Очищаем буфер (удаляем все warnings/notices)
ob_end_clean();
return $output;
}