Files
crm.clientright.ru/include/utils/Debexpert-guzzle.stable
Fedor ac7467f0b4 Major CRM updates: AI Assistant, Court Status API, S3 integration improvements, and extensive file storage system
- Added comprehensive AI Assistant system (aiassist/ directory):
  * Vector search and embedding capabilities
  * Typebot proxy integration
  * Elastic search functionality
  * Message classification and chat history
  * MCP proxy for external integrations

- Implemented Court Status API (GetCourtStatus.php):
  * Real-time court document status checking
  * Integration with external court systems
  * Comprehensive error handling and logging

- Enhanced S3 integration:
  * Improved file backup system with metadata
  * Batch processing capabilities
  * Enhanced error logging and recovery
  * Copy operations with URL fixing

- Added Telegram contact creation API
- Improved error logging across all modules
- Enhanced callback system for AI responses
- Extensive backup file storage with timestamps
- Updated documentation and README files

- File storage improvements:
  * Thousands of backup files with proper metadata
  * Fix operations for broken file references
  * Project-specific backup and recovery systems
  * Comprehensive file integrity checking

Total: 26,461+ files added/modified including AWS SDK, vendor dependencies, and extensive backup system.
2025-10-16 11:17:21 +03:00

697 lines
33 KiB
Plaintext
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
/*********************************************************************************
* Набор методов для работы с ej.sudrf.ru через сервис debex.ru
* All Rights Reserved.
* Contributor(s): Группа компаний АйТи Трейд.
********************************************************************************/
require_once 'include/utils/utils.php';
require_once 'include/Webservices/Revise.php';
require_once 'modules/Users/Users.php';
require_once 'includes/Loader.php';
require_once 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Exception\RequestException;
vimport ('includes.runtime.Globals');
vimport ('includes.runtime.BaseModel');
vimport ('includes.runtime.LanguageHandler');
function Send2Court($projectid, $version) {
file_put_contents('logs/send2court.log', PHP_EOL.date('Y-m-d H:i:s').' - Запущена процедура отправки искового по Проекту '.$projectid.' в режиме '.$version.PHP_EOL, FILE_APPEND);
global $adb;
$query = 'select u.index_notice, u.addr_notice, u.id as userid, a.accountid, a.accountname, a.inn, a.kpp, la.bill_code, la.bill_city, la.bill_street, ra.ship_code, ra.ship_city, ra.ship_street, a.phone, a.email1, pcf.cf_1511 as price, ca.mailingstreet, acf.cf_1951 as ogrn, u.email1 as usermail, pcf.cf_2274 as acc1, pcf.cf_2276 as acc2, pcf.cf_2292 as jurisdiction, pcf.cf_2294 as agrplace, oa.bill_street as offaddress, p.linktoaccountscontacts as contactid
from vtiger_project p
left join vtiger_projectcf pcf on pcf.projectid = p.projectid
left join vtiger_contactdetails cd on cd.contactid = p.linktoaccountscontacts
left join vtiger_contactaddress ca on ca.contactaddressid = p.linktoaccountscontacts
left join vtiger_account a on a.accountid = pcf.cf_1994
left join vtiger_accountscf acf on acf.accountid = pcf.cf_1994
left join vtiger_accountbillads la on la.accountaddressid = pcf.cf_1994
left join vtiger_accountshipads ra on ra.accountaddressid = pcf.cf_1994
left join vtiger_accountbillads oa on oa.accountaddressid = pcf.cf_2274
left join vtiger_crmentity e on e.crmid = p.projectid
left join vtiger_users u on u.id = e.smownerid
where e.deleted = 0 and p.projectid = '.$projectid;
$result = $adb->pquery($query);
if ($adb->num_rows($result) == 0) {
$output = 'Проект не найден';
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - Проект с id '.$projectid.' не найден'.PHP_EOL, FILE_APPEND);
} else {
$accountid = $adb->query_result($result, 0, 'accountid');
$acc1 = $adb->query_result($result, 0, 'acc1');
$acc2 = $adb->query_result($result, 0, 'acc2');
$userid = $adb->query_result($result, 0, 'userid');
$authdoc = getAuthDoc($accountid, $userid); // Поднимаем доверку на представителя Заявителя (он же ответственный по Проекту)
if ($authdoc['result'] == 'NO') {
$output = 'У Ответственного по Проекту '.$projectid. ' в Контрагенте '.$accountid.' нет доверенности от Заявителя';
} else {
$price = $adb->query_result($result, 0, 'price');
$contactid = $adb->query_result($result, 0, 'contactid');
$jurisdiction = $adb->query_result($result, 0, 'jurisdiction'); // Подсудность
if ($jurisdiction == 'По месту исполнения договора') {
$address = $adb->query_result($result, 0, 'agrplace');
} else {
if ($jurisdiction == 'По месту нахождения ответчика') {
$address = $adb->query_result($result, 0, 'offaddress');
} else {
$address = $adb->query_result($result, 0, 'mailingstreet');
}
}
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - Будем подаваться '.$jurisdiction.'. Эту здесь: '.$address.PHP_EOL, FILE_APPEND);
$court = getCourt($contactid, $address, $price); // Ищем суд по адресу и сумме цены иска
if ($court['result'] <> 'YES') {
$output = array('status' => 'ERROR', 'message' => $court['result']);
} else {
$claim = getClaim($projectid);
if ($claim['result'] == 'NO') {
$output = 'В Проекте '.$projectid. 'отсутствует Исковое заявление';
} else {
$multipart = []; // Этот массив будем отдавать в вызове
// Доверенность
$multipart[] = [
'name' => 'files',
'contents' => fopen($authdoc['filepath'], 'r'),
'path' => $authdoc['filepath'],
'filename' => $authdoc['filename']
];
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - добавили в массив файл "'.$authdoc['filename'].'"'.PHP_EOL, FILE_APPEND);
// Исковое
$multipart[] = [
'name' => 'files',
'contents' => fopen($claim['filepath'], 'r'),
'path' => $claim['filepath'],
'filename' => $claim['filename']
];
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - добавили в массив файл "'.$claim['filename'].'"'.PHP_EOL, FILE_APPEND);
$data = []; // А тут мы соберем огромный массив, который потом превратится в json для fillData
$data['appealType'] = 2; // Подает Представитель
$data['mySelfAdditionalData']['courtNoticesAddressIndex'] = $adb->query_result($result, 0, 'index_notice');
$data['mySelfAdditionalData']['courtNoticesAddress'] = $adb->query_result($result, 0, 'addr_notice');
$data['mySelfAdditionalData']['email'] = $adb->query_result($result, 0, 'usermail');
$data['mySelfAdditionalData']['authorizationDocument']['fileIndex'] = 0;
$data['mySelfAdditionalData']['authorizationDocument']['description'] = $authdoc['description'];
$data['mySelfAdditionalData']['authorizationDocument']['pagesCount'] = $authdoc['pages'];
$data['additionalForRepresentativeApplicants'][0]['dataType'] = 'entity';
$data['additionalForRepresentativeApplicants'][0]['entity']['name'] = htmlspecialchars_decode($adb->query_result($result, 0, 'accountname'));
$data['additionalForRepresentativeApplicants'][0]['entity']['international'] = false;
$data['additionalForRepresentativeApplicants'][0]['entity']['inn'] = $adb->query_result($result, 0, 'inn');
$data['additionalForRepresentativeApplicants'][0]['entity']['kpp'] = $adb->query_result($result, 0, 'kpp');
$data['additionalForRepresentativeApplicants'][0]['entity']['ogrnip'] = $adb->query_result($result, 0, 'ogrn');
$data['additionalForRepresentativeApplicants'][0]['entity']['proceduralStatus'] = '50710010';
$data['additionalForRepresentativeApplicants'][0]['entity']['legalIndex'] = $adb->query_result($result, 0, 'bill_code');
$data['additionalForRepresentativeApplicants'][0]['entity']['legalAddress'] = $adb->query_result($result, 0, 'bill_city').', '.$adb->query_result($result, 0, 'bill_street');
$data['additionalForRepresentativeApplicants'][0]['entity']['isLegalAdressEqualToActualResidenceAddress'] = false;
$data['additionalForRepresentativeApplicants'][0]['entity']['actualResidenceIndex'] = $adb->query_result($result, 0, 'ship_code');
$data['additionalForRepresentativeApplicants'][0]['entity']['actualResidenceAddress'] = $adb->query_result($result, 0, 'ship_city').', '.$adb->query_result($result, 0, 'ship_street');
$data['additionalForRepresentativeApplicants'][0]['entity']['email'] = $adb->query_result($result, 0, 'email1');
$data['additionalForRepresentativeApplicants'][0]['entity']['phoneNumber'] = $adb->query_result($result, 0, 'phone');
$data['court']['region'] = $court['region'];
$data['court']['judicialAuthority'] = $court['code'];
$data['appealDocument']['fileIndex'] = 1;
$data['appealDocument']['description'] = $claim['description'];
$data['appealDocument']['pagesCount'] = $claim['pages'];
$otherDocs = getOtherDocs($projectid, $accountid, $acc1, $acc2);
if (count($otherDocs) > 0) {
for ($i=0; $i<count($otherDocs); $i++) {
$newdoc = array();
$newdoc['fileIndex'] = $i + 2;
$newdoc['description'] = $otherDocs[$i]['description'];
$newdoc['pagesCount'] = $otherDocs[$i]['pages'];
$data['additionalAppealDocuments'][] = $newdoc;
$multipart[] = [
'name' => 'files',
'contents' => fopen($otherDocs[$i]['filepath'], 'r'),
'filename' => $otherDocs[$i]['filename']
];
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - добавили в массив файл "'.$otherDocs[$i]['filename'].'"'.PHP_EOL, FILE_APPEND);
}
}
$data['tax']['type'] = '1';
$data['processType'] = '201.01';
$multipart[] = [
'name' => 'certificate',
'contents' => fopen('storage/cert.pfx', 'r'),
'filename' => 'cert.pfx'
];
$multipart[] = [
'name' => 'fillData',
'contents' => json_encode($data)
];
$cookies = GetCookies($version);
if ($cookies != 'Не удалось получить куки') {
// Формируем заголовок запроса
// yft,fkjdj1 - это старый пин-код
$headers = [
'x-api-key' => GetKey($version),
'hidden-authorization-cookies' => htmlspecialchars_decode($cookies),
'hidden-certificate-pin' => '3365',
'custom' => 'Zx123456'
];
$url = GetUrl($version);
//$url = 'https://webhook.nodul.ru/765/dev/eea1b30c-14db-4499-9fc2-4d13e394bae6';
//$url = 'https://eoj0ndhyykckfh.m.pipedream.net';
//$url = 'https://webhook.nodul.ru/13/dev/test-some-error';
// Отправляем запрос с повторами
$output = SendRequest($url, $multipart, $headers, 1);
//file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - вернулись в основной скрипт после отправки запроса'.PHP_EOL, FILE_APPEND);
if ($version == 'Prod' and $output['status'] == 'OK') {
// Сохраним в Проекте входящий номер, если он есть
$number = $output['message'];
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - еще раз взяли номер в основном скрипте: '.$number.PHP_EOL, FILE_APPEND);
if (!empty($number) and !is_null($number)) {
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - убедились, что он не пустой'.PHP_EOL, FILE_APPEND);
$url = 'https://crm.clientright.ru//shorturl.php?id=65eeaa0f425672.54413377&workflow_id=31&record_id='.$projectid.'&reg='.$number;
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
$out = curl_exec($ch);
curl_close($ch);
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - получили ответ от WD: '.$out.PHP_EOL, FILE_APPEND);
//$query = 'update vtiger_projectcf set cf_2204 = "'.$number.'" where projectid = '.$projectid;
//$result = $adb->pquery($query);
//file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - сохранили в Проект рег.номер входящего: '.$number.PHP_EOL, FILE_APPEND);
}
}
//$output = json_encode($multipart);
}
}
}
}
}
if (is_array($output)) {
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - отдаем ответ в первичный вызывающий скрипт : '.json_encode($output).PHP_EOL, FILE_APPEND);
} else {
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - отдаем ответ в первичный вызывающий скрипт : '.$output.PHP_EOL, FILE_APPEND);
}
return $output;
}
function getAuthDoc($accountid, $userid) {
global $adb;
$output = [];
$query = 'select
n.title, ncf.cf_1953 as pages,
case when a.storedname is not null
then concat(a.`path`, a.attachmentsid, "_", a.storedname)
else concat(a.`path`, a.attachmentsid, "_", a.name)
end as filepath,
case when a.storedname is not null
then concat(a.attachmentsid, "_", a.storedname)
else concat(a.attachmentsid, "_", a.name)
end as filename,
a.`type`
from vtiger_senotesrel r
left join vtiger_notes n on n.notesid = r.notesid
left join vtiger_crmentity e on e.crmid = r.notesid
left join vtiger_notescf ncf on ncf.notesid = r.notesid
left join vtiger_seattachmentsrel r2 on r2.crmid = r.notesid
left join vtiger_attachments a on a.attachmentsid = r2.attachmentsid
where e.smownerid = ? and r.crmid = ? and e.deleted = 0 and n.filename like "%подтверждающий_полномочия%"';
$result = $adb->pquery($query, array($userid, $accountid));
if ($adb->num_rows($result) == 0) {
$output['result'] = 'NO';
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - доверенность с подстрокой "подтверждающий_полномочия" в Контрагенте '.$accountid.' не найдена'.PHP_EOL, FILE_APPEND);
} else {
$output['result'] = 'YES';
$output['description'] = $adb->query_result($result, 0, 'title');
if (!is_numeric(substr($output['description'], 0, 1))) {
$output['description'] = '0_'.$output[$i]['description'];
}
$output['description'] = str_replace(' ', '_', $output['description']);
$output['filepath'] = $adb->query_result($result, 0, 'filepath');
$output['filename'] = $adb->query_result($result, 0, 'title').'.pdf';
if (!is_numeric(substr($output['filename'], 0, 1))) {
$output['filename'] = '0_'.$output[$i]['filename'];
}
$output['filename'] = str_replace(' ', '_', $output['filename']);
$output['type'] = $adb->query_result($result, 0, 'type');
$output['pages'] = $adb->query_result($result, 0, 'pages');
if (empty($output['pages']) or $output['pages'] == 0) {
$output['pages'] = getPDFPageCount($output['filepath']);
}
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - Нашли доверенность в Контрагенте '.$accountid.PHP_EOL, FILE_APPEND);
}
return $output;
}
function getClaim($projectid) {
global $adb;
$output = [];
$query = 'select
n.title, ncf.cf_1953 as pages,
case when a.storedname is not null
then concat(a.`path`, a.attachmentsid, "_", a.storedname)
else concat(a.`path`, a.attachmentsid, "_", a.name)
end as filepath,
case when a.storedname is not null
then concat(a.attachmentsid, "_", a.storedname)
else concat(a.attachmentsid, "_", a.name)
end as filename,
a.`type`
from vtiger_senotesrel r
left join vtiger_notes n on n.notesid = r.notesid
left join vtiger_crmentity e on e.crmid = r.notesid
left join vtiger_notescf ncf on ncf.notesid = r.notesid
left join vtiger_seattachmentsrel r2 on r2.crmid = r.notesid
left join vtiger_attachments a on a.attachmentsid = r2.attachmentsid
where r.crmid = ? and e.deleted = 0 and n.filename like "%Исковоеаявление%"';
$result = $adb->pquery($query, array($projectid));
if ($adb->num_rows($result) == 0) {
$output['result'] = 'NO';
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - Исковое заявление с подстрокое "Исковоеаявление" в Проекте '.$projectid.' не найдено'.PHP_EOL, FILE_APPEND);
} else {
$output['result'] = 'YES';
$output['description'] = $adb->query_result($result, 0, 'title');
if (!is_numeric(substr($output['description'], 0, 1))) {
$output['description'] = '0_'.$output[$i]['description'];
}
$output['description'] = str_replace(' ', '_', $output['description']);
$output['filepath'] = $adb->query_result($result, 0, 'filepath');
$output['filename'] = $adb->query_result($result, 0, 'title').'.pdf';
if (!is_numeric(substr($output['filename'], 0, 1))) {
$output['filename'] = '0_'.$output[$i]['filename'];
}
$output['filename'] = str_replace(' ', '_', $output['filename']);
$output['type'] = $adb->query_result($result, 0, 'type');
$output['pages'] = $adb->query_result($result, 0, 'pages');
if (empty($output['pages']) or $output['pages'] == 0) {
$output['pages'] = getPDFPageCount($output['filepath']);
}
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - Нашли исковое заявление в Проекте '.$projectid.PHP_EOL, FILE_APPEND);
}
return $output;
}
function getOtherDocs($projectid, $accountid, $acc1, $acc2) {
global $adb;
$output = [];
//$i = 0;
// Сначала вытащим доки из Проекта, но только те, которые лежат в папке "Суд"
$query = 'select
n.title, ncf.cf_1953 as pages,
case when a.storedname is not null
then concat(a.`path`, a.attachmentsid, "_", a.storedname)
else concat(a.`path`, a.attachmentsid, "_", a.name)
end as filepath,
case when a.storedname is not null
then concat(a.attachmentsid, "_", a.storedname)
else concat(a.attachmentsid, "_", a.name)
end as filename,
a.`type`
from vtiger_senotesrel r
left join vtiger_notes n on n.notesid = r.notesid
left join vtiger_crmentity e on e.crmid = r.notesid
left join vtiger_notescf ncf on ncf.notesid = r.notesid
left join vtiger_seattachmentsrel r2 on r2.crmid = r.notesid
left join vtiger_attachments a on a.attachmentsid = r2.attachmentsid
where r.crmid = ? and e.deleted = 0 and n.filename not like "%Исковоеаявление%" and (a.`type` = "application/pdf" or a.`type` = "application/octet-stream") and n.folderid = 3';
$result = $adb->pquery($query, array($projectid));
if ($adb->num_rows($result) > 0) {
for ($i=0; $i<$adb->num_rows($result); $i++) {
$output[$i]['description'] = $adb->query_result($result, $i, 'title');
if (!is_numeric(substr($output[$i]['description'], 0, 1))) {
$output[$i]['description'] = $i.'_'.$output[$i]['description'];
}
$output[$i]['description'] = str_replace(' ', '_', $output[$i]['description']);
$output[$i]['filepath'] = $adb->query_result($result, $i, 'filepath');
$output[$i]['filename'] = $adb->query_result($result, $i, 'title').'.pdf';
if (!is_numeric(substr($output[$i]['filename'], 0, 1))) {
$output[$i]['filename'] = $i.'_'.$output[$i]['filename'];
}
$output[$i]['filename'] = str_replace(' ', '_', $output[$i]['filename']);
$output[$i]['type'] = $adb->query_result($result, $i, 'type');
$output[$i]['pages'] = $adb->query_result($result, $i, 'pages');
if (empty($output[$i]['pages']) or $output[$i]['pages'] == 0) {
$output[$i]['pages'] = getPDFPageCount($output[$i]['filepath']);
}
//echo $i.' - '.$output[$i]['filename'].'<br>';
}
}
// А теперь из Контрагентов (трех), но только те, которые лежат в папке "Суд"
$query = 'select n.title, ncf.cf_1953 as pages, concat(a.`path`, a.attachmentsid, "_", a.storedname) as filepath, concat(a.attachmentsid, "_", a.storedname) as filename, a.`type`
from vtiger_senotesrel r
left join vtiger_notes n on n.notesid = r.notesid
left join vtiger_crmentity e on e.crmid = r.notesid
left join vtiger_notescf ncf on ncf.notesid = r.notesid
left join vtiger_seattachmentsrel r2 on r2.crmid = r.notesid
left join vtiger_attachments a on a.attachmentsid = r2.attachmentsid
where r.crmid in (?, ?, ?) and e.deleted = 0 and (a.`type` = "application/pdf" or a.`type` = "application/octet-stream") and n.folderid = 3';
$result = $adb->pquery($query, array($accountid, $acc1, $acc2));
if ($adb->num_rows($result) > 0) {
for ($j=0; $j<$adb->num_rows($result); $j++) {
$output[$i]['description'] = $adb->query_result($result, $j, 'title');
if (!is_numeric(substr($output[$i]['description'], 0, 1))) {
$output[$i]['description'] = $i.'_'.$output[$i]['description'];
}
$output[$i]['description'] = str_replace(' ', '_', $output[$i]['description']);
$output[$i]['filepath'] = $adb->query_result($result, $j, 'filepath');
$output[$i]['filename'] = $adb->query_result($result, $j, 'title').'.pdf';
if (!is_numeric(substr($output[$i]['filename'], 0, 1))) {
$output[$i]['filename'] = $i.'_'.$output[$i]['filename'];
}
$output[$i]['filename'] = str_replace(' ', '_', $output[$i]['filename']);
$output[$i]['type'] = $adb->query_result($result, $j, 'type');
$output[$i]['pages'] = $adb->query_result($result, $j, 'pages');
if (empty($output[$i]['pages']) or $output[$i]['pages'] == 0) {
$output[$i]['pages'] = getPDFPageCount($output[$i]['filepath']);
}
$i++;
}
}
return $output;
}
function getCourt($contactid, $address, $price) {
$output = [];
$output['result'] = 'YES';
if (empty($address) and (empty($contactid) or $contactid < 1)) {
$output['result'] = 'Не указаны исходные данные';
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - не указан адрес для поиска суда'.PHP_EOL, FILE_APPEND);
} else {
if (empty($address) and $contactid > 0) {
$query = 'select a.mailingstreet
from vtiger_contactaddress a
left join vtiger_crmentity e on e.crmid = a.contactaddressid
where e.deleted = 0 and a.contactaddressid = '.$contactid;
$result = $adb->pquery($query);
if ($adb->num_rows($result) == 0) {
$output['result'] = 'Контакт не найден';
} else {
$address = $adb->query_result($result, 0, 'mailingstreet');
}
}
}
if ($output['result'] == 'YES') {
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - начинаем поиск суда для адреса '.$address.PHP_EOL, FILE_APPEND);
$host = "https://api.xn----7sbarabva2auedgdkhac2adbeqt1tna3e.xn--p1ai/api"; // адрес сервера api
$token = "y4kNd3Li2NDxyOgaG37ZDuGTWg5CfF2A2dERwbFUjas"; // указать полученный токен
// запрос по адресу
$url = $host."?token=".$token."&address=".urlencode($address);
// запрос по координатам
//$coords = "49.099524 55.794340"; // координаты точки, разделитель - пробел
//$url = $host . "?token=" . $token . "&coords=" . urlencode($coords);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$court = json_decode($response, true);
if ($price > 100000) {
// Если цена иска - от 100 тысяч, то нам будем нужен федеральный суд
$need = 'court_fs';
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - сумма иска более 100к - нужен федеральный суд'.PHP_EOL, FILE_APPEND);
} else {
// А если меньше, то мировой
$need = 'court_ms';
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - сумма иска менее 100к - нужен мировой суд'.PHP_EOL, FILE_APPEND);
}
if (isset($court['request'][$need])) {
$output['code'] = $court['request'][$need]['code'];
$output['region'] = substr($output['code'], 0, 2); // Первые две цифры кода суда - это регион
$output['name'] = $court['request'][$need]['title'];
$output['site'] = $court['request'][$need]['site'];
$output['phone'] = $court['request'][$need]['tel'];
$output['email'] = $court['request'][$need]['email'];
$output['address'] = $court['request'][$need]['address'];
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - и он найден в бесплатной версии API. Код суда: '.$output['code'].PHP_EOL, FILE_APPEND);
} else {
// В бесплатной версии поиска подсудности нужного суда не нашлось - придется лезть в платный сервис
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - но в бесплатной версии API его нет - полезем в платную'.PHP_EOL, FILE_APPEND);
$apikey = GetKey('Prod');
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api-yc.explorer.debex.ru/production/jurisdiction',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"address": "'.addslashes($address).'",
"get_fssp_geo": 1
}',
CURLOPT_HTTPHEADER => array(
'x-api-key: '.$apikey,
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$court = json_decode($response, true);
if ($price > 100000) {
// Если цена иска - от 100 тысяч, то нам будем нужен федеральный суд
$need = 'higher_court';
} else {
// А если меньше, то мировой
$need = 'court';
}
if (isset($court['result'][$need])) {
$output['code'] = $court['result'][$need]['code'];
$output['region'] = substr($output['code'], 0, 2); // Первые две цифры кода суда - это регион
$output['name'] = $court['result'][$need]['court_name'];
$output['site'] = $court['result'][$need]['website'];
$output['phone'] = $court['result'][$need]['phone_normalized'][0]['phone'];
$output['email'] = $court['result'][$need]['email'];
$output['address'] = $court['result'][$need]['address'];
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - а тут мы его и нашли: '.$output['code'].PHP_EOL, FILE_APPEND);
} else {
// Нужный суд не нашелся ни в платном, ни в бесплатном сервисе - не можем продолжать
$output['result'] = 'Суд для адреса '.$address.' не найден';
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - но его и в платном API тоже нет'.PHP_EOL, FILE_APPEND);
}
}
}
return $output;
}
function GetCookies($version) {
//$version = 'Dev';
if ($version == 'Dev') {
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - поднимаем тестовые куки для версии Dev'.PHP_EOL, FILE_APPEND);
$curl = curl_init();
$apiKey = GetKey('Dev');
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api-yc.explorer.debex.ru/dev/sudrf-auth',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
'x-api-key: '.$apiKey
),
));
$response = curl_exec($curl);
curl_close($curl);
} else {
$response = 'No';
if (file_exists('cookies.txt')) {
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - Найден файл со старыми куками'.PHP_EOL, FILE_APPEND);
$created = filemtime('cookies.txt'); // Дата создания файла (получения и сохранения cookies)
$now = time();
$diff = $now - $created;
if ($diff < 10800) {
// Если старый файл создан более 3 часов назад
$response = file_get_contents('cookies.txt');
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - создан менее 3 часов назад - берем куки из него'.PHP_EOL, FILE_APPEND);
} else {
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - создан более 3 часов назад - будем получать новые'.PHP_EOL, FILE_APPEND);
}
}
if ($response == 'No') {
// Будем получать новые
$url = "https://api-yc.explorer.debex.ru/production/sudrf-auth-chatbot";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'x-api-key: ' . GetKey('Prod'),
'hidden-bot-phone-number: +79262306381'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, []);
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - отправляем запрос с СМС-подтверждением'.PHP_EOL, FILE_APPEND);
$response = curl_exec($ch);
curl_close($ch);
// И сохраним их на будущее
if (strpos($response, "error") !== false) {
$response = 'Не удалось получить куки';
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - в ответ получили ошибку. Куков нет.'.PHP_EOL, FILE_APPEND);
} else {
file_put_contents('cookies.txt', $response);
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - ответ получен, новые куки сохранены в файле cookies.txt'.PHP_EOL, FILE_APPEND);
}
}
}
return $response;
}
function GetUrl($version) {
/*
if ($version == 'Dev') {
$url = 'https://explorer-proxy.debex.ru/api/dev/sudrf';
} elseif ($version == 'Stage') {
$url = 'https://explorer-proxy.debex.ru/api/stage/sudrf';
} elseif ($version == 'Prod') {
$url = 'https://explorer-proxy.debex.ru/api/production/sudrf';
}
*/
if ($version == 'Dev') {
$url = 'https://explorer-proxy.debex.ru/api/v3/dev/sudrf';
} elseif ($version == 'Stage') {
$url = 'https://explorer-proxy.debex.ru/api/v3/stage/sudrf';
} elseif ($version == 'Prod') {
$url = 'https://explorer-proxy.debex.ru/api/v3/production/sudrf';
}
return $url;
}
function GetKey($version) {
if ($version == 'Dev') {
$key = 'sandboxklientpravdjknkjsdndsd8y789!';
} else {
$key = 'productionklientpravkjnkjnhkhj87y!';
}
return $key;
}
function SendRequest ($url, $multipart, $headers, $count) {
if ($count < 6) {
$client = new Client();
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - непосредственно отправляем запрос. Попытка №'.$count.PHP_EOL, FILE_APPEND);
try {
$response = $client->request('POST', $url, [
'headers' => $headers,
'multipart' => $multipart
]);
$statusCode = $response->getStatusCode();
if ($statusCode >= 200 && $statusCode < 300) {
// Успешный ответ
//$output = $response->getBody()->getContents();
$output = $response->getBody();
} else {
// Ошибка
$output = "Ошибка HTTP: " . $statusCode . " - " . $response->getReasonPhrase();
}
// Выводим ответ
//$output = $response->getBody();
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - получили ответ на запрос: '.$output.PHP_EOL, FILE_APPEND);
// Вытаскиваем номер входящего
$arrResponse = json_decode($output, true);
$number = $arrResponse['data']['appealNumber'];
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - вытащили рег.номер: '.$number.PHP_EOL, FILE_APPEND);
$output = array('status' => 'OK', 'message' => $number);
} catch (Exception $ex) {
// Обрабатываем исключение, например, выводим сообщение об ошибке
$output = $ex->getMessage();
file_put_contents('logs/send2court.log', date('Y-m-d H:i:s').' - получили ошибку при выполнении запроса: '.$output.PHP_EOL, FILE_APPEND);
$RetryFlag = false; // Флаг перезапуска
$retry = array("500", "403", "417"); // Массив ошибок, при которых будем пробовать еще раз
foreach ($retry as $errorcode) {
if (strpos($output, $errorcode) !== false) {
// В строке с ответом с ошибкой есть код, при котором будем пробовать еще раз
$RetryFlag = true;
break;
}
}
if ($RetryFlag) {
sleep(10);
$count++;
$output = SendRequest($url, $multipart, $headers, $count);
} else {
$output = array('status' => 'ERROR', 'message' => 'Похоже на ошибку в составе данных - перезапускать не будем');
}
}
} else {
$output = array('status' => 'ERROR', 'message' => 'Пять попыток отправки не привели к успеху');
}
return $output;
}
?>