getMessage().PHP_EOL, FILE_APPEND); return false; } } 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 с правильным boundary ]); 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); // Устанавливаем правильное имя для основного документа $document_name = 'Исковое заявление.pdf'; if ($type == 'претензионное') { $document_name = 'Претензионное письмо.pdf'; } $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) { $attachmentIndex = 1; // Начинаем с индекса 1 (0 занят доверенностью) for ($i=0; $ipquery($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['description']; } $output['description'] = str_replace(' ', '_', $output['description']); // Проверяем тип размещения файла $filelocationtype = $adb->query_result($result, 0, 'filelocationtype'); $s3_filename = $adb->query_result($result, 0, 's3_filename'); $s3_bucket = $adb->query_result($result, 0, 's3_bucket'); $s3_key = $adb->query_result($result, 0, 's3_key'); if ($filelocationtype == 'E' && !empty($s3_bucket) && !empty($s3_key)) { // Файл в S3 - скачиваем во временную папку file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - доверенность найдена в S3, bucket: '.$s3_bucket.', key: '.$s3_key.PHP_EOL, FILE_APPEND); $tempFilename = 'auth_doc_' . time() . '.pdf'; $tempPath = getTempFileFromS3($s3_bucket, $s3_key, $tempFilename); if ($tempPath) { $output['filepath'] = $tempPath; $output['is_temp_file'] = true; // Флаг для последующей очистки file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - S3 файл доверенности успешно скачан во временную папку'.PHP_EOL, FILE_APPEND); } else { $output['result'] = 'NO'; file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - не удалось скачать доверенность из S3'.PHP_EOL, FILE_APPEND); return $output; } } else { // Локальный файл (оригинальная логика) $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').' - Нашли доверенность в Контрагенте '.$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`, n.filename as s3_filename, n.s3_bucket, n.s3_key, n.filelocationtype 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 "%Исковое_заявление%" OR n.title like "%Исковое_заявление%" OR n.title like "%исковое%" OR 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 ($type == 'исковое') { 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']); // Проверяем тип размещения файла $filelocationtype = $adb->query_result($result, 0, 'filelocationtype'); $s3_filename = $adb->query_result($result, 0, 's3_filename'); $s3_bucket = $adb->query_result($result, 0, 's3_bucket'); $s3_key = $adb->query_result($result, 0, 's3_key'); if ($filelocationtype == 'E' && !empty($s3_bucket) && !empty($s3_key)) { // Файл в S3 - скачиваем во временную папку file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - основной документ найден в S3, bucket: '.$s3_bucket.', key: '.$s3_key.PHP_EOL, FILE_APPEND); $tempFilename = 'claim_doc_' . time() . '.pdf'; $tempPath = getTempFileFromS3($s3_bucket, $s3_key, $tempFilename); if ($tempPath) { $output['filepath'] = $tempPath; $output['is_temp_file'] = true; // Флаг для последующей очистки file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - S3 файл основного документа успешно скачан во временную папку'.PHP_EOL, FILE_APPEND); } else { $output['result'] = 'NO'; file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - не удалось скачать основной документ из S3'.PHP_EOL, FILE_APPEND); return $output; } } else { // Локальный файл (оригинальная логика) $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`, n.filename as s3_filename, n.s3_bucket, n.s3_key, n.filelocationtype 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']); // Проверяем тип размещения файла $filelocationtype = $adb->query_result($result, 0, 'filelocationtype'); $s3_filename = $adb->query_result($result, 0, 's3_filename'); $s3_bucket = $adb->query_result($result, 0, 's3_bucket'); $s3_key = $adb->query_result($result, 0, 's3_key'); if ($filelocationtype == 'E' && !empty($s3_bucket) && !empty($s3_key)) { // Файл в S3 - скачиваем во временную папку file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - заявление потерпевшего найдено в S3, bucket: '.$s3_bucket.', key: '.$s3_key.PHP_EOL, FILE_APPEND); $tempFilename = 'plea_doc_' . time() . '.pdf'; $tempPath = getTempFileFromS3($s3_bucket, $s3_key, $tempFilename); if ($tempPath) { $output['filepath'] = $tempPath; $output['is_temp_file'] = true; // Флаг для последующей очистки file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - S3 файл заявления потерпевшего успешно скачан во временную папку'.PHP_EOL, FILE_APPEND); } else { $output['result'] = 'NO'; file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - не удалось скачать заявление потерпевшего из S3'.PHP_EOL, FILE_APPEND); return $output; } } else { // Локальный файл (оригинальная логика) $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`, n.filename as s3_filename, n.s3_bucket, n.s3_key, n.filelocationtype 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.folderid = 3 and ( a.`type` = "application/pdf" or a.`type` = "application/octet-stream" or n.filename like "%.pdf" or a.name like "%.pdf" or a.storedname like "%.pdf" ) and ( n.title not like "%Исковое_заявление%" and n.title not like "%исковое%" and n.filename not like "%Исковое_заявление%" and n.filename not like "%исковое%" )'; $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']); // Проверяем тип размещения файла $filelocationtype = $adb->query_result($result, $i, 'filelocationtype'); $s3_filename = $adb->query_result($result, $i, 's3_filename'); $s3_bucket = $adb->query_result($result, $i, 's3_bucket'); $s3_key = $adb->query_result($result, $i, 's3_key'); if ($filelocationtype == 'E' && !empty($s3_bucket) && !empty($s3_key)) { // Файл в S3 - скачиваем во временную папку file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - дополнительный документ из проекта найден в S3, bucket: '.$s3_bucket.', key: '.$s3_key.PHP_EOL, FILE_APPEND); $tempFilename = 'other_doc_' . $i . '_' . time() . '.pdf'; $tempPath = getTempFileFromS3($s3_bucket, $s3_key, $tempFilename); if ($tempPath) { $output[$i]['filepath'] = $tempPath; $output[$i]['is_temp_file'] = true; // Флаг для последующей очистки file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - S3 файл дополнительного документа успешно скачан во временную папку: '.$tempPath.PHP_EOL, FILE_APPEND); } else { file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - ошибка скачивания S3 файла дополнительного документа из проекта, bucket: '.$s3_bucket.', key: '.$s3_key.PHP_EOL, FILE_APPEND); // Устанавливаем пустой filepath, чтобы избежать ошибки $output[$i]['filepath'] = ''; $output[$i]['is_temp_file'] = false; } } else { // Локальный файл (оригинальная логика) $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`, n.filename as s3_filename, n.s3_bucket, n.s3_key, n.filelocationtype 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 n.folderid = 3 and ( a.`type` = "application/pdf" or a.`type` = "application/octet-stream" or n.filename like "%.pdf" or a.name like "%.pdf" or a.storedname like "%.pdf" ) and ( n.title not like "%Исковое_заявление%" and n.title not like "%исковое%" and n.filename not like "%Исковое_заявление%" and n.filename not like "%исковое%" )'; $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']); // Проверяем тип размещения файла $filelocationtype = $adb->query_result($result, $j, 'filelocationtype'); $s3_filename = $adb->query_result($result, $j, 's3_filename'); $s3_bucket = $adb->query_result($result, $j, 's3_bucket'); $s3_key = $adb->query_result($result, $j, 's3_key'); if ($filelocationtype == 'E' && !empty($s3_bucket) && !empty($s3_key)) { // Файл в S3 - скачиваем во временную папку file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - дополнительный документ из контрагента найден в S3, bucket: '.$s3_bucket.', key: '.$s3_key.PHP_EOL, FILE_APPEND); $tempFilename = 'contractor_doc_' . $i . '_' . time() . '.pdf'; $tempPath = getTempFileFromS3($s3_bucket, $s3_key, $tempFilename); if ($tempPath) { $output[$i]['filepath'] = $tempPath; $output[$i]['is_temp_file'] = true; // Флаг для последующей очистки file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - S3 файл дополнительного документа из контрагента успешно скачан во временную папку: '.$tempPath.PHP_EOL, FILE_APPEND); } else { file_put_contents('logs/Letters.log', date('Y-m-d H:i:s').' - ошибка скачивания S3 файла дополнительного документа из контрагента, bucket: '.$s3_bucket.', key: '.$s3_key.PHP_EOL, FILE_APPEND); // Устанавливаем пустой filepath, чтобы избежать ошибки $output[$i]['filepath'] = ''; $output[$i]['is_temp_file'] = false; } } else { // Локальный файл (оригинальная логика) $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; } ?>