610 lines
31 KiB
PHP
Executable File
610 lines
31 KiB
PHP
Executable File
<?php
|
||
/*********************************************************************************
|
||
* Набор методов для отправки заказных писем на бумаге через сервис pochta-sud.ru
|
||
* All Rights Reserved.
|
||
* Contributor(s): Илья Руденко itsaturn@yandex.ru
|
||
********************************************************************************/
|
||
require_once 'include/utils/utils.php';
|
||
require_once 'include/Webservices/Revise.php';
|
||
require_once 'modules/Users/Users.php';
|
||
require_once 'includes/Loader.php';
|
||
include_once 'include/Webservices/Query.php';
|
||
require_once 'include/Webservices/Utils.php';
|
||
vimport ('includes.runtime.Globals');
|
||
vimport ('includes.runtime.BaseModel');
|
||
vimport ('includes.runtime.LanguageHandler');
|
||
|
||
function getDoc($projectid, $letter_id, $lettertype, $doctype) {
|
||
$lettertype = mb_strtolower($lettertype);
|
||
$type = mb_strtolower($doctype);
|
||
|
||
file_put_contents('logs/Letters.log', PHP_EOL.date('Y-m-d H:i:s').' - Запрос '.$doctype.' для отправления '.$letter_id.' - '.$lettertype.PHP_EOL, FILE_APPEND);
|
||
$allowed = array('справка', 'опись');
|
||
if (!in_array($doctype, $allowed)) {
|
||
file_put_contents('logs/Letters.log', PHP_EOL.date('Y-m-d H:i:s').' - Но это недопустимый тип документа - поэтому выходим'.PHP_EOL, FILE_APPEND);
|
||
return 'Неизвестный тип документа : '.$doctype;
|
||
}
|
||
if (!is_numeric($letter_id)) {
|
||
return 'Не указан № отправления letter_id';
|
||
}
|
||
|
||
// Инициализация cURL
|
||
$ch = curl_init();
|
||
|
||
// $token = 'ead6ccca0c820b63286cd0f2fca5821d'; // Тестовый
|
||
//$token = '9e9dce7a0cef9d90404169286762669f'; // Боевой
|
||
$token = '8da7669523a916b2862824dbf77a4198'; // Боевой
|
||
|
||
if ($doctype == 'справка') {
|
||
$url = 'https://api.pochta-sud.ru/letter/'.$letter_id.'/invoice';
|
||
} else {
|
||
$url = 'https://api.pochta-sud.ru/letter/'.$letter_id.'/listing';
|
||
}
|
||
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - сформировали url: '.$url.PHP_EOL, FILE_APPEND);
|
||
|
||
curl_setopt($ch, CURLOPT_URL, $url);
|
||
curl_setopt($ch, CURLOPT_POST, 0);
|
||
//curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
|
||
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
||
'Authorization: Bearer ' . $token,
|
||
'Content-Type: multipart/form-data',
|
||
]);
|
||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||
|
||
// Выполнение запроса
|
||
$output = curl_exec($ch);
|
||
|
||
// Проверка на ошибки
|
||
if (curl_errno($ch)) {
|
||
$output = 'Ошибка:' . curl_error($ch);
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - получили ошибку от сервера: '.curl_error($ch).PHP_EOL, FILE_APPEND);
|
||
} else {
|
||
if ($output == 'Not Found: Invoice not found') {
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - получили ответ от сервера - Not Found: Invoice not found'.PHP_EOL, FILE_APPEND);
|
||
} else {
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - получили корректный ответ от сервера, начинаем сохранять файл'.PHP_EOL, FILE_APPEND);
|
||
|
||
global $adb, $current_user;
|
||
|
||
// 0. Готовим имя файла
|
||
$noteid = $adb->getUniqueID("vtiger_crmentity");
|
||
$attachid = $adb->getUniqueID("vtiger_crmentity");
|
||
if ($lettertype == 'претензионное') {
|
||
if ($doctype == 'опись') {
|
||
$filename = 'Доказательство_направления_претензии_ответчику.pdf';
|
||
$description = 'Доказательство направления претензии ответчику';
|
||
} elseif ($doctype == 'справка') {
|
||
$filename = 'Доказательство_оплаты_направления_претензии_ответчику.pdf';
|
||
$description = 'Доказательство оплаты направления претензии ответчику';
|
||
} else {
|
||
$filename = 'Неизвесный_документ.pdf';
|
||
$description = 'Неизвесный документ при отправке претензионного';
|
||
}
|
||
} elseif ($lettertype == 'исковое') {
|
||
if ($doctype == 'опись') {
|
||
$filename = 'Доказательство_направления_иска_ответчику.pdf';
|
||
$description = 'Доказательство направления иска ответчику';
|
||
} elseif ($doctype == 'справка') {
|
||
$filename = 'Доказательство_оплаты_направления_иска_ответчику.pdf';
|
||
$description = 'Доказательство оплаты направления иска ответчику';
|
||
} else {
|
||
$filename = 'Неизвесный_документ.pdf';
|
||
$description = 'Неизвесный документ при отправке искового';
|
||
}
|
||
} else {
|
||
$filename = 'Неизвесный_документ.pdf';
|
||
$description = 'Запрос '.$doctype.' по отправлению неизвестного типа: '.$lettertype;
|
||
}
|
||
|
||
$upload_file_path = decideFilePath(); // Получили папку для сохранения
|
||
$file = $upload_file_path . $attachid . "_" . $filename; // Собрали имя новому файлу
|
||
file_put_contents($file, $output);
|
||
|
||
// 1. Создаем сущность Документ
|
||
$date_var = date('Y-m-d H:i:s');
|
||
$ownerid = getUserId($projectid); // Поднимем ответственного из проекта, куда добавляем файл
|
||
|
||
// 1.1 Запись в crmentity
|
||
$sql1 = "insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,createdtime,modifiedtime) values(?,?,?,?,?,?)";
|
||
$params1 = array($noteid, $ownerid, $ownerid, 'Documents', $adb->formatDate($date_var, true), $adb->formatDate($date_var, true));
|
||
$adb->pquery($sql1, $params1);
|
||
$logstring = date('Y-m-d H:i:s').' Добавили Документ в crmentity'.PHP_EOL;
|
||
file_put_contents('logs/Letters.log', $logstring, FILE_APPEND);
|
||
|
||
// 1.2 Запись в notes
|
||
/*
|
||
$logstring = date('Y-m-d H:i:s').' Готовимся добавлять: noteid: '.$noteid.';';
|
||
$logstring .= ' description: '.$description.';';
|
||
$logstring .= ' filename: '.$filename.';';
|
||
$logstring .= ' filesize: '.filesize($file).';'.PHP_EOL;
|
||
file_put_contents('logs/Letters.log', $logstring, FILE_APPEND);
|
||
*/
|
||
$sql2 = "insert into vtiger_notes(notesid, title, filename, folderid, filetype, filelocationtype, filedownloadcount, filestatus, filesize) values(?,?,?,?,?,?,?,?,?)";
|
||
$params2 = array($noteid, $description, $filename, 3, 'application/pdf', 'I', 0, 1, filesize($file));
|
||
$adb->pquery($sql2, $params2);
|
||
$logstring = date('Y-m-d H:i:s').' Добавили Документ в notes: https://crm.clientright.ru/index.php?module=Documents&view=Detail&record='.$noteid.PHP_EOL;
|
||
file_put_contents('logs/Letters.log', $logstring, FILE_APPEND);
|
||
|
||
// 2. Создаем сущность Аттачи Документов
|
||
// 2.1 Запись в crmentity
|
||
$sql1 = "insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,createdtime,modifiedtime) values(?,?,?,?,?,?)";
|
||
$params1 = array($attachid, $ownerid, $ownerid, 'Documents Attachment', $adb->formatDate($date_var, true), $adb->formatDate($date_var, true));
|
||
$adb->pquery($sql1, $params1);
|
||
$logstring = date('Y-m-d H:i:s').' Добавили файл в crmentity'.PHP_EOL;
|
||
file_put_contents('logs/Letters.log', $logstring, FILE_APPEND);
|
||
|
||
// 2.2 Запись в attachments
|
||
$sql2 = "insert into vtiger_attachments(attachmentsid, name, type, path, storedname) values(?,?,?,?,?)";
|
||
$params2 = array($attachid, $filename, 'application/pdf', $upload_file_path, $filename);
|
||
$adb->pquery($sql2, $params2);
|
||
$logstring = date('Y-m-d H:i:s').' Добавили файл в attachments: '.$attachid.PHP_EOL;
|
||
file_put_contents('logs/Letters.log', $logstring, FILE_APPEND);
|
||
|
||
// 3. Связываем Документ с Аттачем
|
||
$sql3 = "insert into vtiger_seattachmentsrel(crmid, attachmentsid) values(?,?)";
|
||
$adb->pquery($sql3, array($noteid, $attachid));
|
||
$logstring = date('Y-m-d H:i:s').' связали файл с Документом'.PHP_EOL;
|
||
file_put_contents('logs/Letters.log', $logstring, FILE_APPEND);
|
||
|
||
// 4. Привязываем Документ к Проекту (или другой сущности) по crmid
|
||
$sql4 = "insert into vtiger_senotesrel(crmid, notesid) values(?,?)";
|
||
$adb->pquery($sql4, array($projectid, $noteid));
|
||
$logstring = date('Y-m-d H:i:s').' связали Документ с Проектом'.PHP_EOL;
|
||
file_put_contents('logs/Letters.log', $logstring, FILE_APPEND);
|
||
|
||
$output = 'YES';
|
||
}
|
||
|
||
return $output;
|
||
}
|
||
|
||
// Закрытие cURL сессии
|
||
curl_close($ch);
|
||
}
|
||
|
||
function SendLetter($projectid, $type) {
|
||
$type = mb_strtolower($type);
|
||
file_put_contents('logs/Letters.log', PHP_EOL.date('Y-m-d H:i:s').' - Отправляем '.$type.' по Проекту '.$projectid.PHP_EOL, FILE_APPEND);
|
||
|
||
$allowed = array('претензионное', 'исковое');
|
||
if (!in_array($type, $allowed)) {
|
||
file_put_contents('logs/Letters.log', PHP_EOL.date('Y-m-d H:i:s').' - Но это недопустимый тип отправления - поэтому выходим '.$projectid.PHP_EOL, FILE_APPEND);
|
||
return 'Неизвестный тип отправления : '.$type;
|
||
}
|
||
|
||
$output = 'YES';
|
||
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_code as offindex, oa.bill_city as offcity, oa.bill_street as offstreet, p.linktoaccountscontacts as contactid, pcf.cf_1507 as casenumber, o.accountname as offname
|
||
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_account o on o.accountid = pcf.cf_2274
|
||
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);
|
||
// cf_2274 - злодей
|
||
// cf_1994 - заявитель
|
||
|
||
if ($adb->num_rows($result) == 0) {
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - Проект с id '.$projectid.' не найден'.PHP_EOL, FILE_APPEND);
|
||
return 'Проект не найден';
|
||
} 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');
|
||
$name = str_replace('"', '"', $adb->query_result($result, 0, 'accountname'));
|
||
$name = str_replace('«', '"', $name);
|
||
$name = str_replace('»', '"', $name);
|
||
//$name = str_replace('"', '', $name);
|
||
//$name = addslashes($name);
|
||
|
||
$offname = str_replace('"', '"', $adb->query_result($result, 0, 'offname'));
|
||
$offname = str_replace('«', '"', $offname);
|
||
$offname = str_replace('»', '"', $offname);
|
||
//$offname = str_replace('"', '', $offname);
|
||
//$offname = addslashes($offname);
|
||
|
||
// Данные отправителя
|
||
$source = [
|
||
'type' => 'organization',
|
||
'taxId' => $adb->query_result($result, 0, 'inn'),
|
||
'name' => $name,
|
||
'email' => $adb->query_result($result, 0, 'email1')
|
||
];
|
||
if (empty($adb->query_result($result, 0, 'ship_code'))) {
|
||
$source['address'] = $adb->query_result($result, 0, 'ship_street');
|
||
} else {
|
||
$source['address'] = $adb->query_result($result, 0, 'ship_code').', '.$adb->query_result($result, 0, 'ship_city').', '.$adb->query_result($result, 0, 'ship_street');
|
||
}
|
||
// Данные получателя
|
||
if (strlen(trim($adb->query_result($result, 0, 'inn'))) == 10) {
|
||
$destination = ['type' => 'organization', 'taxId' => $adb->query_result($result, 0, 'inn')];
|
||
} else {
|
||
$destination = ['type' => 'individual'];
|
||
}
|
||
$destination['name'] = $offname;
|
||
if (empty($adb->query_result($result, 0, 'offindex'))) {
|
||
$destination['address'] = $adb->query_result($result, 0, 'offstreet');
|
||
} else {
|
||
$destination['address'] = $adb->query_result($result, 0, 'offindex').', '.$adb->query_result($result, 0, 'offcity').', '.$adb->query_result($result, 0, 'offstreet');
|
||
}
|
||
|
||
// Файлы для отправки
|
||
$claim = getClaim($projectid, $type); // Ищем основной документ для отправки - исковое заявление или претензию
|
||
if ($claim['result'] == 'NO') {
|
||
// Не нашлось основного документа в Проекте
|
||
if ($type == 'исковое') {
|
||
return 'В Проекте '.$projectid. 'отсутствует Исковое заявление';
|
||
} elseif ($type == 'претензионное') {
|
||
return 'В Проекте '.$projectid. 'отсутствует претензионное письмо';
|
||
}
|
||
} else {
|
||
$document = new CURLFile($claim['filepath'], 'application/pdf'); // Есть основной документ - добавляем его в массив
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - добавили в массив файл "'.$claim['filename'].'"'.PHP_EOL, FILE_APPEND);
|
||
$authdoc = getAuthDoc($accountid, $userid); // Поднимаем доверку на представителя Заявителя (он же ответственный по Проекту)
|
||
|
||
if ($authdoc['result'] == 'NO') {
|
||
// Нет у представителя Заявителя доверки
|
||
return 'У Ответственного по Проекту '.$projectid. ' в Контрагенте '.$accountid.' нет доверенности от Заявителя';
|
||
} else {
|
||
$attachments = [];
|
||
// $attachments[0] = fopen($authdoc['filepath'], 'r'); // Есть доверка - добавляем ее в массив
|
||
$attachments[0] = new CURLFile($authdoc['filepath'], 'application/pdf'); // Есть доверка - добавляем ее в массив
|
||
$attachment_names[0] = 'Доверенность.pdf';
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - добавили в массив файл "'.$authdoc['filepath'].'" и дали ему имя: '.$attachment_names[0].PHP_EOL, FILE_APPEND);
|
||
// А дальше разница - если отправка искового, то надо добыть все документы для суда. А для отправки претензии - только добавить заявление терпилы
|
||
if ($type == 'исковое') {
|
||
$otherDocs = getOtherDocs($projectid, $accountid, $acc1, $acc2); // Получили массив всех прочих документов Проекта и связанных Контрагентов
|
||
if (count($otherDocs) > 0) {
|
||
for ($i=0; $i<count($otherDocs); $i++) {
|
||
// $attachments[$i + 1] = fopen($otherDocs[$i]['filepath'], 'r');
|
||
$attachments[$i + 1] = new CURLFile($otherDocs[$i]['filepath'], 'application/pdf');
|
||
$attachment_names[$i + 1] = $otherDocs[$i]['description'].'.pdf';
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - добавили в массив файл "'.$otherDocs[$i]['filepath'].'"; и дали ему имя: '.$attachment_names[$i + 1].PHP_EOL, FILE_APPEND);
|
||
}
|
||
}
|
||
} elseif ($type == 'претензионное') {
|
||
$plea = getPlea($projectid); // Поднимаем точечно заявление терпилы
|
||
if ($plea['result'] == 'NO') {
|
||
// В Проекте нет заявления потерпевшего
|
||
return 'В Проекте '.$projectid. ' нет заявления потерпевшего';
|
||
} else {
|
||
// $attachments[1] = fopen($plea['filepath'], 'r');
|
||
$attachments[1] = new CURLFile($plea['filepath'], 'application/pdf');
|
||
$attachment_names[1] = 'Заявление.pdf';
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - добавили в массив файл "'.$plea['filepath'].'" и дали ему имя: '.$attachment_names[1].PHP_EOL, FILE_APPEND);
|
||
}
|
||
}
|
||
|
||
// Создание массива данных для отправки
|
||
$data = [];
|
||
$data['source'] = json_encode($source);
|
||
$data['destination'] = json_encode($destination);
|
||
$data['document'] = $document;
|
||
for ($i=0; $i<count($attachments); $i++) {
|
||
$attstr = 'attachments['.$i.']';
|
||
$data[$attstr] = $attachments[$i];
|
||
$attstr = 'attachment_names['.$i.']';
|
||
$data[$attstr] = $attachment_names[$i];
|
||
// Вместо
|
||
// $data['attachments[0]'] = $attachments[0];
|
||
// $data['attachments[1]'] = $attachments[1];
|
||
// $data['attachments[2]'] = $attachments[2];
|
||
}
|
||
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - итоговый массив для отправки: '.json_encode($data).PHP_EOL, FILE_APPEND);
|
||
|
||
// Инициализация cURL
|
||
$ch = curl_init();
|
||
|
||
// $token = 'ead6ccca0c820b63286cd0f2fca5821d'; // Тестовый
|
||
// $token = '9e9dce7a0cef9d90404169286762669f'; // Боевой
|
||
$token = '8da7669523a916b2862824dbf77a4198'; // Боевой
|
||
|
||
curl_setopt($ch, CURLOPT_URL, 'https://api.pochta-sud.ru/letter');
|
||
curl_setopt($ch, CURLOPT_POST, 1);
|
||
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
|
||
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
||
'Authorization: Bearer ' . $token,
|
||
'Content-Type: multipart/form-data',
|
||
]);
|
||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||
|
||
// Выполнение запроса
|
||
$output = curl_exec($ch);
|
||
|
||
// Проверка на ошибки
|
||
if (curl_errno($ch)) {
|
||
$output = 'Ошибка:' . curl_error($ch);
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - получили ошибку от сервера: '.curl_error($ch).PHP_EOL, FILE_APPEND);
|
||
} else {
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - получили корректный ответ от сервера: '.$output.PHP_EOL, FILE_APPEND);
|
||
$arr = json_decode($output, true);
|
||
$output = $arr['letter_id'];
|
||
|
||
if (!is_numeric($output)) {
|
||
// Что-то пошло не так - получили корректный ответ об ошибке, без взрыва. Вытащим его
|
||
$output = $arr['message'];
|
||
}
|
||
}
|
||
|
||
// Закрытие cURL сессии
|
||
curl_close($ch);
|
||
}
|
||
}
|
||
}
|
||
|
||
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/Letters.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');
|
||
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - Нашли доверенность в Контрагенте '.$accountid.PHP_EOL, FILE_APPEND);
|
||
}
|
||
|
||
return $output;
|
||
}
|
||
|
||
function getClaim($projectid, $type) {
|
||
// Возвращает основной документ-требование по Проекту. Это может быть исковое заявление или претензионное письмо
|
||
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 ';
|
||
if ($type == 'исковое') {
|
||
$query .= 'n.filename like "%Исковое_заявление%"';
|
||
} elseif ($type == 'претензионное') {
|
||
$query .= 'n.notecontent = "претензия почта api"'; // Так у нас кодируется признак претензионного письма
|
||
} else {
|
||
return false;
|
||
}
|
||
|
||
$result = $adb->pquery($query, array($projectid));
|
||
|
||
if ($adb->num_rows($result) == 0) {
|
||
$output['result'] = 'NO';
|
||
if ($processType = 'исковое') {
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - Исковое заявление с подстрокой "Исковое_заявление" в Проекте '.$projectid.' не найдено'.PHP_EOL, FILE_APPEND);
|
||
} else {
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - Претензионное письмо со строкой "претензия почта api" в Проекте '.$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['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['filename'];
|
||
}
|
||
$output['filename'] = str_replace(' ', '_', $output['filename']);
|
||
$output['type'] = $adb->query_result($result, 0, 'type');
|
||
|
||
if ($processType = 'исковое') {
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - Нашли исковое заявление в Проекте '.$projectid.PHP_EOL, FILE_APPEND);
|
||
} else {
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - Нашли претензионное письмо в Проекте '.$projectid.PHP_EOL, FILE_APPEND);
|
||
}
|
||
}
|
||
|
||
return $output;
|
||
}
|
||
|
||
function getPlea($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.notecontent = "заявление почта api"';
|
||
|
||
$result = $adb->pquery($query, array($projectid));
|
||
|
||
if ($adb->num_rows($result) == 0) {
|
||
$output['result'] = 'NO';
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - Заявление потерпевшего со строкой "заявление почта api" в Проекте '.$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['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['filename'];
|
||
}
|
||
$output['filename'] = str_replace(' ', '_', $output['filename']);
|
||
$output['type'] = $adb->query_result($result, 0, 'type');
|
||
|
||
file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - Нашли заявление потерпевшего в Проекте '.$projectid.PHP_EOL, FILE_APPEND);
|
||
}
|
||
|
||
return $output;
|
||
}
|
||
|
||
function getOtherDocs($projectid, $accountid, $acc1, $acc2) {
|
||
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 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');
|
||
}
|
||
}
|
||
|
||
// А теперь из Контрагентов (трех), но только те, которые лежат в папке "Суд"
|
||
$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 getUserId($crmid) {
|
||
global $adb;
|
||
$query = 'select smownerid as userid
|
||
from vtiger_crmentity
|
||
where deleted = 0 and crmid = ?';
|
||
$result = $adb->pquery($query, array($crmid));
|
||
|
||
if ($adb->num_rows($result) == 1) {
|
||
// Что-то нашлось
|
||
$output = $adb->query_result($result, 0, 'userid');
|
||
} else {
|
||
// Активных Проектов нет, а может быть несколько - значит ответственным будет админ
|
||
$output = 1;
|
||
}
|
||
return $output;
|
||
}
|
||
|
||
?>
|