Files
crm.clientright.ru/include/Webservices/CreateWebClaim.php
Fedor c60d00f563 feat: Создана операция CreateWebClaim для заявок через webservice
-  CreateWebClaim.php: создание заявок (HelpDesk) в vTiger
-  Обязательные поля: title, contact_id, project_id, event_type
-  Опциональные: description, incident_date, transport_number
-  Маппинг event_type на русские категории
-  Возврат: {ticket_id, ticket_number, title, category, status}
-  Зарегистрирована в БД: operationid=52
-  webservice.php: ob_get_clean + ob_start для очистки BOM
-  Логирование в logs/CreateWebClaim.log
2025-11-02 00:09:22 +03:00

153 lines
6.5 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;
// Маппинг типов событий на русские названия для категории
$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' => '12x'.$contact_id,
'cf_2066' => '33x'.$project_id, // Связь с проектом
'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);
// Возвращаем массив (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;
}