Files
erv-clientright/test/server_webservice2.php
2026-03-13 10:42:01 +03:00

606 lines
24 KiB
PHP
Raw Permalink 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
header('Access-Control-Allow-Origin: *'); // Разрешаем доступ с любого источника
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: origin, Content-Type, X-Requested-With, XMLHttpRequest');
// ПРОСТАЯ ОТЛАДКА
file_put_contents('debug.txt', "SERVER_WEBSERVICE2_FIXED.PHP ВЫПОЛНЯЕТСЯ!\n", FILE_APPEND);
file_put_contents('debug.txt', "POST: " . json_encode($_POST) . "\n", FILE_APPEND);
// Настройка логирования
$log_dir = 'formlog';
if (!is_dir($log_dir)) {
mkdir($log_dir);
}
function log_message($message) {
global $log_dir;
$date = date('Y-m-d H:i:s');
file_put_contents("$log_dir/form_log.log", "[$date] $message" . PHP_EOL, FILE_APPEND);
}
// Получаем данные из POST
$upload_urls_real = $_POST['upload_urls_real'] ?? [];
$appends = $_POST['appends'] ?? [];
$docs_names = $_POST['docs_names'] ?? [];
$docs_ticket_files_ids = $_POST['docs_ticket_files_ids'] ?? [];
$sub_dir = $_POST['sub_dir'] ?? '';
$lastname = str_replace(' ', '', $_POST['lastname'] ?? '');
// ОТЛАДКА: Проверяем что получили
log_message("DEBUG: \$_POST = " . json_encode($_POST));
log_message("DEBUG: appends count = " . count($appends));
log_message("DEBUG: appends = " . json_encode($appends));
$cf_2566 = $_POST['cf_2566'] ?? null; // Дата страхового случая
$cf_2568 = $_POST['cf_2568'] ?? null; // Номер рейса
$event_types = [
'delay_flight' => ['code' => '001', 'text' => 'Задержка авиарейса (более 3 часов)'],
'cancel_flight' => ['code' => '002', 'text' => 'Отмена авиарейса'],
'miss_connection' => ['code' => '003', 'text' => 'Пропуск (задержка прибытия) стыковочного рейса'],
'emergency_landing' => ['code' => '004', 'text' => 'Посадка воздушного судна на запасной аэродром'],
'delay_train' => ['code' => '005', 'text' => 'Задержка отправки поезда'],
'cancel_train' => ['code' => '006', 'text' => 'Отмена поезда'],
'delay_ferry' => ['code' => '007', 'text' => 'Задержка/отмена отправки парома/круизного судна'],
];
// Логируем полученные данные
log_message("Полученные данные: " . json_encode($_POST));
log_message("Дата страхового случая: $cf_2566");
log_message("Номер рейса: $cf_2568");
// Логируем переданные данные с названиями полей
log_message("Переданные данные:");
foreach ($appends as $key => $itemjson) {
$item = json_decode($itemjson);
$field_name = $item->ws_name ?? $key; // Используем ws_name, если он есть
$field_value = $item->field_val ?? ''; // Если нет значения, то выводим пустую строку
// Логируем данные в виде "Название поля: Значение"
log_message("$field_name : $field_value");
}
// Подготовка тела письма
$mail_body = 'Пользователь заполнил форму! <br><br>';
foreach ($appends as $key => $itemjson) {
$item = json_decode($itemjson);
$mail_body .= $key . ' : ' . $item->field_val . '<br>';
}
// Логируем тело письма
log_message("Тело письма: $mail_body");
// Формируем данные для отправки почты
$email_data = array(
'to' => 'kfv.advokat@gmail.com',
'subject' => 'Новая заявка из системы Клиентправ/ЛексПриорити',
'body' => 'Данные заявки: ' . $mail_body,
'attachments' => $upload_urls_real
);
// Сохраняем данные для скрипта отправки почты
$email_file = 'formlog/email_data.json';
file_put_contents($email_file, json_encode($email_data, JSON_UNESCAPED_UNICODE));
// Запускаем отправку почты в фоновом режиме
exec('php send_email_2.php > /dev/null 2>/dev/null &');
// Логирование отправленных данных
log_message("Отправленные данные на CRM: " . json_encode($upload_urls_real));
// Прочая логика (например, работа с API и т.д.)
$endpointUrl = "https://crm.clientright.ru/webservice.php";
// 1) Вынимаем временный токен из ответа
$ch = curl_init();
$url = $endpointUrl . "?operation=getchallenge&username=api";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // Увеличенный таймаут
$response = curl_exec($ch);
$jsonResponse = json_decode($response, true);
$challengeToken = $jsonResponse['result']['token'];
$result['challengeToken'] = $challengeToken;
$userAccessKey = '4r9ANex8PT2IuRV';
$generatedKey = md5($challengeToken.$userAccessKey);
// 2) Логинимся
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => array(
'operation' => 'login',
'username' => 'api',
'accessKey' => $generatedKey
)
));
$response = curl_exec($ch);
$jsonResponse = json_decode($response, true);
$sessionId = $jsonResponse['result']['sessionName'];
log_message("Получен sessionId: " . $sessionId);
// 2) Создание клиента-физлица
$client_array = array(
'operation' => 'CreateContact',
'sessionName' => $sessionId,
);
log_message("=== ОБРАБОТКА КЛИЕНТА ===");
log_message("Начальный client_array: " . json_encode($client_array, JSON_UNESCAPED_UNICODE));
foreach ($appends as $key => $itemjson) {
$item = json_decode($itemjson);
log_message("Обрабатываем элемент [$key]: ws_type='{$item->ws_type}', ws_name='{$item->ws_name}', field_val='{$item->field_val}'");
if ($item->ws_type == "client") {
$client_array[$item->ws_name] = $item->field_val;
log_message("✅ Добавлено в client_array: {$item->ws_name} = '{$item->field_val}'");
if ($item->ws_name == "code") $sms = $item->field_val;
} else {
log_message("⏭️ Пропущено (ws_type != 'client')");
}
}
log_message("Итоговый client_array: " . json_encode($client_array, JSON_UNESCAPED_UNICODE));
log_message("=== КОНЕЦ ОБРАБОТКИ КЛИЕНТА ===");
$maxAttempts = 3; // Максимальное количество попыток
$attempts = 0;
$client_id = null;
do {
// Логируем данные, которые отправляем на сервер
log_message("Отправляемые данные на сервер (client_array): " . json_encode($client_array, JSON_UNESCAPED_UNICODE));
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $client_array
));
$response = curl_exec($ch);
// Логируем ответ от сервера
log_message("Ответ от сервера: " . $response);
// Удаляем лишние символы
$response = trim($response);
$response = preg_replace('/^\xEF\xBB\xBF/', '', $response); // Удаляем BOM
// Декодируем JSON и проверяем на ошибки
$output = json_decode($response, TRUE);
if (json_last_error() !== JSON_ERROR_NONE) {
log_message("Ошибка декодирования JSON: " . json_last_error_msg());
log_message("Неправильный JSON: " . $response); // Логируем неверный JSON
break; // Выход из цикла в случае ошибки
}
// Проверяем успешность запроса
log_message("DEBUG: output = " . json_encode($output));
log_message("DEBUG: output['success'] = " . (isset($output['success']) ? ($output['success'] ? 'true' : 'false') : 'not set'));
log_message("DEBUG: output['result'] = " . (isset($output['result']) ? $output['result'] : 'not set'));
if (isset($output['success']) && $output['success'] === true) {
$client_id = $output['result'] ?? null;
log_message("Создан клиент с ID: " . ($client_id ? $client_id : 'Ошибка получения ID'));
} else {
log_message("Ошибка при создании клиента, ответ сервера: " . json_encode($output));
}
$attempts++;
} while (!$client_id && $attempts < $maxAttempts);
// Логируем ответ сервера при создании клиента
log_message("Ответ сервера при создании клиента: " . json_encode($output));
// 3) Создание контрагента-обидчика
$contractor_array = array(
'operation' => 'CreateAccount',
'sessionName' => $sessionId,
);
log_message("=== ОБРАБОТКА КОНТРАГЕНТА ===");
log_message("Начальный contractor_array: " . json_encode($contractor_array, JSON_UNESCAPED_UNICODE));
foreach ($appends as $key => $itemjson) {
$item = json_decode($itemjson);
log_message("Обрабатываем элемент [$key]: ws_type='{$item->ws_type}', ws_name='{$item->ws_name}', field_val='{$item->field_val}'");
if ($item->ws_type == "contractor" && $item->field_val != "") {
$contractor_array[$item->ws_name] = $item->field_val;
log_message("✅ Добавлено в contractor_array: {$item->ws_name} = '{$item->field_val}'");
} else {
log_message("⏭️ Пропущено (ws_type != 'contractor' или пустое значение)");
}
}
log_message("Итоговый contractor_array: " . json_encode($contractor_array, JSON_UNESCAPED_UNICODE));
log_message("=== КОНЕЦ ОБРАБОТКИ КОНТРАГЕНТА ===");
// Проверяем наличие ИНН и ОГРН, если их нет, генерируем
if (empty($contractor_array['inn'])) {
// Генерация случайного ИНН, начинающегося с "00"
$contractor_array['inn'] = '00' . str_pad(mt_rand(0, 999999999), 9, '0', STR_PAD_LEFT); // Генерируем 9 цифр
log_message("Сгенерирован случайный ИНН для контрагента: " . $contractor_array['inn']);
}
if (empty($contractor_array['ogrn'])) {
// Генерация случайного ОГРН, начинающегося с "00"
$contractor_array['ogrn'] = '00' . str_pad(mt_rand(0, 999999999), 11, '0', STR_PAD_LEFT); // Генерируем 11 цифр
log_message("Сгенерирован случайный ОГРН для контрагента: " . $contractor_array['ogrn']);
}
$attempts = 0;
$contractor_id = null;
do {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $contractor_array
));
$response = curl_exec($ch);
// Удаляем лишние символы и проверяем ответ
$response = trim($response);
$response = preg_replace('/^\xEF\xBB\xBF/', '', $response); // Удаляем BOM
// Логируем ответ от сервера
log_message("Ответ от сервера при создании контрагента: " . $response);
// Декодируем JSON и проверяем на ошибки
$output = json_decode($response, TRUE);
if (json_last_error() !== JSON_ERROR_NONE) {
log_message("Ошибка декодирования JSON: " . json_last_error_msg());
log_message("Неправильный JSON: " . $response); // Логируем неверный JSON
break; // Выход из цикла в случае ошибки
}
// Проверяем успешность запроса
log_message("DEBUG CONTRACTOR: output = " . json_encode($output));
log_message("DEBUG CONTRACTOR: output['success'] = " . (isset($output['success']) ? ($output['success'] ? 'true' : 'false') : 'not set'));
log_message("DEBUG CONTRACTOR: output['result'] = " . (isset($output['result']) ? $output['result'] : 'not set'));
$contractor_id = $output['result'] ?? null;
log_message("Попытка создания контрагента, попытка: " . ($attempts + 1));
if ($contractor_id) {
log_message("Создан контрагент с ID: " . $contractor_id);
} else {
log_message("Ошибка получения ID контрагента, ответ сервера: " . json_encode($output));
}
$attempts++;
} while (!$contractor_id && $attempts < $maxAttempts);
// 3.1) Агент
if ($_POST['getservice'] == "agent") {
$agent_array = array(
'operation' => 'CreateAccount',
'sessionName' => $sessionId,
);
foreach ($appends as $key => $itemjson) {
$item = json_decode($itemjson);
if ($item->ws_type == "agent" && $item->field_val != "") {
$agent_array[$item->ws_name] = $item->field_val;
}
}
$attempts = 0;
$agent_id = null;
do {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $agent_array
));
$response = curl_exec($ch);
// Удаляем лишние символы и проверяем ответ
$response = trim($response);
$response = preg_replace('/^\xEF\xBB\xBF/', '', $response); // Удаляем BOM
// Логируем ответ от сервера
log_message("Ответ от сервера при создании агента: " . $response);
// Декодируем JSON и проверяем на ошибки
$output = json_decode($response, TRUE);
if (json_last_error() !== JSON_ERROR_NONE) {
log_message("Ошибка декодирования JSON: " . json_last_error_msg());
log_message("Неправильный JSON: " . $response); // Логируем неверный JSON
break; // Выход из цикла в случае ошибки
}
// Проверяем успешность запроса
$agent_id = $output['result'] ?? null;
log_message("Попытка создания агента, попытка: " . ($attempts + 1));
if ($agent_id) {
log_message("Создан Агент с ID: " . $agent_id);
} else {
log_message("Ошибка получения ID агента, ответ сервера: " . json_encode($output));
}
$attempts++;
} while (!$agent_id && $attempts < $maxAttempts);
} else {
$agent_id = '';
}
// 4) Проект
log_message("=== СОЗДАНИЕ ПРОЕКТА ===");
log_message("client_id = " . ($client_id ? $client_id : 'NULL'));
log_message("contractor_id = " . ($contractor_id ? $contractor_id : 'NULL'));
log_message("agent_id = " . ($agent_id ? $agent_id : 'NULL'));
log_message("sms = " . ($sms ?? 'NULL'));
$project_array = array(
'operation' => 'CreateProject',
'sessionName' => $sessionId,
'contactid' => $client_id,
'offenderid' => $contractor_id,
'agentid' => $agent_id,
'sms' => $sms
);
log_message("project_array: " . json_encode($project_array, JSON_UNESCAPED_UNICODE));
// Пушим в массив остальные поля
foreach ($appends as $key => $itemjson) {
$item = json_decode($itemjson);
if ($item->ws_type != "contractor" && $item->ws_type != "client" && $item->ws_type != "agent" && $item->ws_type != "other" && $item->ws_type != "project") {
$project_array[$item->ws_name] = $item->field_val;
}
}
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $project_array
));
// Выполняем запрос и получаем ответ
$response = curl_exec($ch);
// Логируем ответ от сервера
log_message("Ответ от сервера при создании проекта: " . $response);
$project_id = preg_replace('/[^0-9]/', '', $response);
log_message("Создан проект с ID: " . $project_id);
// 5) Прикрепление файлов к проекту
if ($upload_urls_real) {
foreach ($upload_urls_real as $key => $url) {
$params = array(
'operation' => 'AddPDF',
'sessionName' => $sessionId,
'crmid' => $project_id,
'url' => $url
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $params
));
$response = curl_exec($ch);
$output = json_decode($response, TRUE);
log_message("Прикреплен файл к проекту: " . $response);
}
}
// 6) Остальные поля
$other_array = array();
foreach ($appends as $key => $itemjson) {
$item = json_decode($itemjson);
if ($item->ws_type == "other" || $item->ws_type == "project") {
$other_array[$item->ws_name] = $item->field_val;
}
}
$params = array(
'operation' => 'UpdateEntity',
'sessionName' => $sessionId,
//'crmid' => $project_id,
'element' => json_encode($other_array)
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $params
));
$response = curl_exec($ch);
$output = json_decode($response, TRUE);
// Логирование обновленных полей и ответа сервера
log_message("Обновлены остальные поля: " . json_encode($other_array));
log_message("Ответ сервера при обновлении полей: " . json_encode($output));
// 6.1) Остальные поля проект
$other_array = array();
foreach ($appends as $key => $itemjson) {
$item = json_decode($itemjson);
if ($item->ws_type == "other" || $item->ws_type == "project") {
$other_array[$item->ws_name] = $item->field_val;
}
}
$params = array(
'operation' => 'UpdateEntity',
'sessionName' => $sessionId,
'crmid' => $project_id,
'element' => json_encode($other_array)
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $params
));
$response = curl_exec($ch);
$output = json_decode($response, TRUE);
// Логирование обновленных полей и ответа сервера
log_message("Обновлены остальные поля: " . json_encode($other_array));
log_message("Ответ сервера при обновлении полей: " . json_encode($output));
// 7 Создание заявок
$ticket_id_array = array();
foreach ($appends as $key => $itemjson) {
$item = json_decode($itemjson);
if ($item->ws_type == "ticket") {
if (isset($event_types[$item->field_val])) {
$event_code = $event_types[$item->field_val]['code']; // например "003"
$event_text = $event_types[$item->field_val]['text']; // например "Пропуск (задержка прибытия) стыковочного рейса"
} else {
$event_code = $item->field_val;
$event_text = $item->field_val;
}
$params = array(
'operation' => 'CreateERVTicket',
'sessionName' => $sessionId,
'title' => $event_text, //заголовок
'contactid' => $client_id,
'projectid' => $project_id
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $params
));
$response = curl_exec($ch);
if (curl_errno($ch)) {
log_message("Ошибка cURL при создании заявки: " . curl_error($ch));
continue; // Переходим к следующей заявке в случае ошибки
}
$output = json_decode($response, TRUE);
if (isset($output['success']) && $output['success'] === true) {
$ticket_id = $output['result'];
$ticket_id_array[] = $ticket_id;
log_message("Создана заявка с ID: " . $ticket_id);
// Обновляем поля cf_2508 и cf_2505 для заявки
$update_params = array(
'operation' => 'UpdateEntity',
'sessionName' => $sessionId,
'crmid' => $ticket_id,
'element' => json_encode(array(
'cf_2508' => $event_code, // Код события
'cf_2505' => $cf_2566 // Дата страхового случая
))
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $update_params
));
$update_response = curl_exec($ch);
log_message("Обновление cf_2508 и cf_2505 для заявки $ticket_id: " . $update_response);
} else {
log_message("Ошибка создания заявки: " . json_encode($output));
}
}
}
// 8) Остальные поля
$other_array = array();
foreach ($appends as $key => $itemjson) {
$item = json_decode($itemjson);
if ($item->ws_type == "other" || $item->ws_type == "ticket") {
$other_array[$item->ws_name] = $item->field_val;
}
}
$params = array(
'operation' => 'UpdateEntity',
'sessionName' => $sessionId,
'crmid' => $ticket_id,
'element' => json_encode($other_array)
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $params
));
$response = curl_exec($ch);
$output = json_decode($response, TRUE);
// Логирование обновленных полей и ответа сервера
log_message("Обновлены остальные поля: " . json_encode($other_array));
log_message("Ответ сервера при обновлении полей: " . json_encode($output));
// 9) Прикрепление файлов к заявкам
if ($docs_ticket_files_ids) {
foreach ($docs_ticket_files_ids as $ticket_id => $file_ids) {
foreach ($file_ids as $item) {
$params = array(
'operation' => 'AddPDF',
'sessionName' => $sessionId,
'crmid' => $ticket_id,
'url' => $item
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $params
));
$response = curl_exec($ch);
if (curl_errno($ch)) {
log_message("Ошибка cURL при прикреплении файла: " . curl_error($ch));
} else {
log_message("Ответ от сервера при прикреплении файла к заявке $item: " . $response);
}
}
}
}
// Возвращаем успешный ответ
echo json_encode(array(
'status' => 'success',
'message' => 'Данные успешно обработаны.'
), JSON_UNESCAPED_UNICODE);
?>