Joywork/cron/telegramm_notice.php
2026-05-22 21:21:54 +03:00

1982 lines
95 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
set_time_limit(0);
$start = microtime(true);
require_once $_SERVER['DOCUMENT_ROOT'] . "/config.php";
header('Content-Type: application/json');
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
$pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
$tel = new Telegram(false, $pdo);
$users_req_exception = array(); //Исключение телефонов для этих юзеров
$agency_id = 19895;
$sql_users = "SELECT id FROM users WHERE id in (select id from users where id=$agency_id or id_manager=$agency_id or id_manager in
(select id from users where id_manager=$agency_id or id_manager in
(select id from users where id_manager=$agency_id)))";
$q_users = $pdo->query($sql_users);
while($r_users = $pdo->fetch_assoc($q_users)){
$users_req_exception[] = (int)$r_users['id'];
}
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error.txt", date('d.m.y H:i:s').' start '."\n", FILE_APPEND);
//Пользоваватели получающие уведомления.
$sql = "SELECT id, id_manager, telegramm_chat_id, telegramm_date, gmtmsk, CONCAT(last_name, ' ', first_name, ' ', middle_name) as ufio FROM users WHERE telegramm_notice = 1";
$user_ids = array();
$users = array();
$users_time = array();
$users_ids_10 = array();
$users_ids_11 = array();
$users_ids_12 = array();
$q = $pdo->query($sql);
// echo mysql_num_rows($q);
while ($r = $pdo->fetch_assoc($q)) {
if($r['id'] > 0){
$user_ids[] = (int)$r['id'];
$users[$r['id']] = $r;
$users_time[(int)$r['gmtmsk']][] = (int)$r['id'];
if(empty($r['telegramm_date']) || ($r['telegramm_date'] != date('Y-m-d 10:00:00'))){
$users_ids_10[] = $r['id'];
}
if(empty($r['telegramm_date']) || ($r['telegramm_date'] != date('Y-m-d 11:00:00'))){
$users_ids_11[] = $r;
}
if(empty($r['telegramm_date']) || ($r['telegramm_date'] != date('Y-m-d 12:00:00'))){
$users_ids_12[] = $r;
}
}
}
// var_dump($users_time);
echo 'Время выполнения скрипта 1: '.round(microtime(true) - $start, 4).' сек.'."\n";
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error.txt", date('d.m.y H:i:s').' end 1'."\n", FILE_APPEND);
$start1 = microtime(true);
$update_ids = array();
$types_phone = array(1 => 'Telphin', 2 => 'Билайн');
$telephony_call = "SELECT t.id, t.user_id, t.who_work, t.from_mes, t.to_mes, CONCAT(w.last_name, ' ', w.first_name, ' ', w.middle_name) as wfio, t.client_id, t.type_phone, t.tel, c.fio as cfio, c.phone, t.created_at FROM telephony_notifications as t " .
"LEFT JOIN users as w ON t.who_work = w.id " .
"LEFT JOIN clients as c ON c.id = t.client_id " .
"WHERE t.tel != 1 and t.user_id in (".implode(',', $user_ids).") and t.user_id != 9904";
//echo $telephony_call."\n";
if ($q_call = $pdo->query($telephony_call)) {
if ($pdo->num_rows($q_call) > 0) {
while ($r_call = $pdo->fetch_assoc($q_call)) {
$sql_update_call = "";
$text = '';
// hide_client_contacts: маска для получателя уведомления
$_hideCall = should_hide_contacts_for_user_id($r_call['user_id']);
if ($_hideCall) {
$phone = mask_client_phone($r_call['phone']);
$cfio = mask_fio_for_user_id($r_call['cfio'], $r_call['user_id']);
} else {
$phone = $r_call['phone'];
if (strpos($phone, '+7') !== false) {
$phone = substr($phone, 0, 2) . "(" . substr($phone, 2, 3) . ")" . substr($phone, 5, 3) . "-" . substr($phone, 8, 2) . "-" . substr($phone, 10, 2);
}
$cfio = $r_call['cfio'];
}
$type_phone = $types_phone[$r_call['type_phone']];
if ($r_call['to_mes'] == 1) {
$text = "<b>О клиенте " . $type_phone . "</b>\n";
if(!in_array($r_call['user_id'], $users_req_exception))
$text .= "Клиент " . $cfio . " тел. " . $phone . "\n";
$text .= "уже закреплен за сотрудником " . $r_call['wfio'] . "\n";
$text .= "<i> (время создания " . date("d.m.Y H:i", strtotime($r_call['created_at'])) . ")</i>\n";
} else if ($r_call['from_mes'] == 1) {
$text = "<b>О клиенте " . $type_phone . "</b>\n";
if(!in_array($r_call['user_id'], $users_req_exception))
$text .= "Клиент " . $cfio . " тел. " . $phone . "\n";
$text .= "звонил повторно\n Звонок принял сотрудник " . $r_call['wfio'] . "\n";
$text .= "<i> (время создания " . date("d.m.Y H:i", strtotime($r_call['created_at'])) . ")</i>\n";
}
$chatId = $users[$r_call['user_id']]['telegramm_chat_id'];
if($chatId > 0 && !empty($text)){
$tel->send($text, $chatId);
}
// if($sql_update_call != '') $sql_update_call .= "; ";
$update_ids[] = $r_call['id'];
}
}
if(!empty($update_ids)){
$sql_update_call = "UPDATE telephony_notifications SET tel = 1 WHERE id in (".implode(',', $update_ids).")";
echo $sql_update_call."\n";
$pdo->query($sql_update_call);
}
}
echo 'Время выполнения скрипта 2: '.round(microtime(true) - $start1, 4)." сек.\n";
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error.txt", date('d.m.y H:i:s').' end 4'."\n", FILE_APPEND);
$start2 = microtime(true);
/* $pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
$tel = new Telegram(false, $pdo);*/
//Уведомление о задачах
$currentTime = time();
//var_dump($users_time);
foreach($users_time as $gmtmsk=>$user_arr){
$update_ids = array();
$hoursToAdd = (int)$gmtmsk;
$time_zone = '';
if($hoursToAdd >= 0){
$time_zone = '+'.$hoursToAdd.' hour';
} else {
$time_zone = '-'.$hoursToAdd.' hour';
}
$secondsToAdd = $hoursToAdd * (60 * 60);
$newTime = $currentTime + $secondsToAdd;
$events_query = "SELECT e.id, e.type, e.comment, e.sum, e.address, e.create_date, e.schedule_date, e.name, e.client_id, e.req_id, e.tracking, e.user_id FROM user_client_events as e WHERE e.tel != 1 and e.calendar_view = 0
and e.schedule_date is not null and e.schedule_date != '0000-00-00 00:00:00' and cancel=0 and e.tracking = 0 and e.old_req_id = 0 and e.user_id in (".implode(',', $user_arr).") and e.schedule_date <= '" . date("Y-m-d H:i:s", $newTime) . "'";
/* if($hoursToAdd == 4){
echo $events_query."\n";
}*/
//echo $events."\n";
$q_events = $pdo->query($events_query);
$events = array();
$client_ids = array();
$clients = array();
$req_ids = array();
$clients_req = array();
$reqs = array();
$client_req_ids = array();
while ($ev = $pdo->fetch_assoc($q_events)) {
if($ev['client_id'] > 0){
$client_ids[] = $ev['client_id'];
}
if($ev['req_id'] > 0){
$req_ids[] = $ev['req_id'];
}
$events[$ev['id']] = $ev;
}
//Выборка клиентов
if(!empty($client_ids)){
$clients = $tel->get_clients_array($client_ids);
}
//Выборка заявок
if(!empty($req_ids)){
$res_req = $tel->get_reqs_array($req_ids);
$reqs = $res_req['reqs'];
$client_req_ids = $res_req['client_ids'];
}
//Выборка клиентов в заявках
if(!empty($client_req_ids)){
$clients_req = $tel->get_clients_array($client_req_ids);
}
foreach($events as $id=>$ev){
// hide_client_contacts: получатель уведомления = $ev['user_id']
$_hideEv = should_hide_contacts_for_user_id($ev['user_id']);
$phoneClient = '';
if ($ev['client_id'] > 0) {
$r_cl = $clients[$ev['client_id']];
} else if ($ev['req_id'] > 0) {
$r_cl = $reqs[$ev['req_id']];
if($r_cl['client_id'] > 0){
$r_clr = $clients_req[$r_cl['client_id']];
if ($_hideEv) {
$phoneClient .= "<i>Клиент: </i>" . mask_fio_for_user_id($r_clr['fio'], $ev['user_id']) . " тел. " . mask_client_phone($r_clr['phone']) . "\n";
} else {
$phoneClient .= "<i>Клиент: </i>" . $r_clr['fio'] . " тел. " . substr($r_clr['phone'], 0, 2) . "(" . substr($r_clr['phone'], 2, 3) . ")" . substr($r_clr['phone'], 5, 3) . "-" . substr($r_clr['phone'], 8, 2) . "-" . substr($r_clr['phone'], 10, 2)."\n";
}
}
}
$title = '';
$text = '';
$schedule_date = date("d.m.Y", strtotime($ev['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
// hide_client_contacts: вычисляем отображаемые fio/phone единожды
$_cl_fio = isset($r_cl['fio']) ? ($_hideEv ? mask_fio_for_user_id($r_cl['fio'], $ev['user_id']) : $r_cl['fio']) : '';
if ($ev['client_id'] > 0) {
if ($_hideEv) {
$phone = mask_client_phone($r_cl['phone']);
} else {
$phone = $r_cl['phone'];
if (strpos($phone, '+7') !== false) {
$phone = substr($phone, 0, 2) . "(" . substr($phone, 2, 3) . ")" . substr($phone, 5, 3) . "-" . substr($phone, 8, 2) . "-" . substr($phone, 10, 2);
}
}
}
switch ($ev['type']) {
case 'call':
{
if ($ev['client_id'] > 0) {
$title = "<b>Звонок</b> клиенту " . $_cl_fio . " тел. " . $phone;
} else if ($ev['req_id'] > 0) {
$title = "<b>Звонок</b> по заявке " . $_cl_fio . " ID: ".$r_cl['id'];
if(!in_array($ev['user_id'], $users_req_exception))
$text .=$phoneClient;
}
$text .= $d . " " . getRusMonth($m) . " " . $y . " в " . date("H:i", strtotime($ev['schedule_date']));
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . $ev['comment'];
}
// $text .= "\n<i>". date("H:i", strtotime($ev['create_date']))."</i>";
break;
}
case 'meet':
{
if ($ev['client_id'] > 0) {
$title = "<b>Встреча</b> клиенту " . $_cl_fio . " тел. " . $phone;
} else if ($ev['req_id'] > 0) {
$title = "<b>Встреча</b> по заявке " . $_cl_fio . " ID: ".$r_cl['id'];
if(!in_array($ev['user_id'], $users_req_exception))
$text .=$phoneClient;
}
$text .= 'Встреча будет ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date']));
if ($ev['address']) {
$text .= "\n<i>Адрес:</i> " . $ev['address'];
}
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . $ev['comment'];
}
// $text .= "\n<i>". date("H:i", strtotime($ev['create_date']))."</i>";
break;
}
case 'show':
{
if ($ev['client_id'] > 0) {
$title = "<b>Показ</b> клиенту " . $_cl_fio . " тел. " . $phone;
} else if ($ev['req_id'] > 0) {
$title = "<b>Показ</b> по заявке " . $_cl_fio . " ID: ".$r_cl['id'];
if(!in_array($ev['user_id'], $users_req_exception))
$text .=$phoneClient;
}
$text .= 'Показ будет ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date']));
if ($ev['address']) {
$text .= "\n<i>Адрес:</i> " . $ev['address'];
}
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . $ev['comment'];
}
// $text .= "\n<i>". date("H:i", strtotime($ev['create_date']))."</i>";
break;
}
case 'deal':
{
if ($ev['client_id'] > 0) {
$title = "<b>Сделка</b> с клиентом " . $_cl_fio . " тел. " . $phone;
} else if ($ev['req_id'] > 0) {
$title = "<b>Сделка</b> по заявке " . $_cl_fio . " ID: ".$r_cl['id'];
if(!in_array($ev['user_id'], $users_req_exception))
$text .=$phoneClient;
}
$text .= 'Сделка будет ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date']));
if ($ev['sum']) {
$text .= "\n<i>Сумма сделки:</i> " . $ev['sum'] . " р.";
}
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . $ev['comment'];
}
// $text .= "\n<i>". date("H:i", strtotime($ev['create_date']))."</i>";
break;
}
case 'even':
{
$title = '<b>' . $ev['name'] . '</b>';
$text .= 'Мероприятие состоится ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date']));
if ($ev['client_id'] > 0) {
if (!empty($r_cl['fio'])) {
$text .= "\nКлиент <b>" . $_cl_fio . "</b> тел. " . $phone;
}
} else if ($ev['req_id'] > 0) {
if (!empty($r_cl['fio'])) {
$text .= "\nЗаявка <b>" . $_cl_fio . " ID: ".$r_cl['id'] . "</b> ";
}
if(!in_array($ev['user_id'], $users_req_exception))
$text .=$phoneClient;
}
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . str_replace('&quot;', '',$ev['comment']);
}
// $text .= "\n<i>". date("H:i", strtotime($ev['create_date']))."</i>";
break;
}
}
// echo $text;
$text_o = "Напоминание <i> (время создания " . date("d.m.Y H:i", strtotime($time_zone, strtotime($ev['create_date']))) . ")</i>\n"
. $title . " \n" . str_replace(['&lt;i&gt;', '&lt;/i&gt;', '&lt;br&gt;', '&lt;b&gt;', '&lt;/b&gt;'], ['<i>', '</i>', "\n", '<b>', '</b>'], htmlentities($text));
//echo $text_o."\n";
$chatId = $users[$ev['user_id']]['telegramm_chat_id'];
if($chatId>0){
// if($chatId == '689521489' || $chatId == '255183898' || $chatId == '105877066'){
$keyboardArr = [];
$keyboardArr = [
[
[
'text' => 'Отметить выполненной',
'callback_data' => serialize(array('action'=>10,'id'=>$ev['id']))
]
]
];
if($ev['req_id'] > 0 || $ev['client_id'] > 0){
$keyboardArr[] = [
[
'text' => 'Отметить выполненной и написать комментарий',
'callback_data' => serialize(array('action'=>11,'id'=>$ev['id']))
],
];
}
$tel->send($text_o, $chatId, null, $keyboardArr);
/* } else {
$tel->send($text_o, $chatId);
}*/
}
$update_ids[] = $ev['id'];
if(count($update_ids) == 100){
$sql_up = "UPDATE user_client_events SET tel = 1 WHERE id in (".implode(',',$update_ids).")";
if(!$pdo->query($sql_up)){
file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error_sql.txt", date('d.m.y H:i:s').' '.$sql_up.' '.json_encode($pdo->error(), JSON_UNESCAPED_UNICODE)."\n", FILE_APPEND);
}
$update_ids = array();
}
}
if(!empty($update_ids)){
$sql_up = "UPDATE user_client_events SET tel = 1 WHERE id in (".implode(',',$update_ids).")";
if(!$pdo->query($sql_up)){
file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error_sql.txt", date('d.m.y H:i:s').' '.$sql_up.' '.json_encode($pdo->error(), JSON_UNESCAPED_UNICODE)."\n", FILE_APPEND);
}
}
echo 'Время выполнения скрипта 3: '.round(microtime(true) - $start2, 4)." сек.\n";
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error.txt", date('d.m.y H:i:s').' end 3'."\n", FILE_APPEND);
$start3 = microtime(true);
/* $pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
$tel = new Telegram(false, $pdo);*/
$events_query = "SELECT e.id, e.type, e.comment, e.sum, e.address, e.create_date, e.schedule_date, e.schedule_date_to, e.name, e.client_id, e.req_id, e.user_id FROM user_client_events as e WHERE
e.tracking = 1 and e.tel = 0 and e.calendar_view = 0 and e.schedule_date is not null and cancel=0 and e.user_id in (".implode(',', $user_arr).") and e.schedule_date_to <= '" . date("Y-m-d H:i:s", $newTime) . "'";
//echo $events_query."\n";
$q_events = $pdo->query($events_query);
$events = array();
$client_ids = array();
$clients = array();
$req_ids = array();
$clients_req = array();
$reqs = array();
$client_req_ids = array();
$update_ids = array();
while ($ev = $pdo->fetch_assoc($q_events)) {
if($ev['client_id'] > 0){
$client_ids[] = $ev['client_id'];
}
if($ev['req_id'] > 0){
$req_ids[] = $ev['req_id'];
}
$events[$ev['id']] = $ev;
}
//Выборка клиентов
if(!empty($client_ids)){
$clients = $tel->get_clients_array($client_ids);
}
//Выборка заявок
if(!empty($req_ids)){
$res_req = $tel->get_reqs_array($req_ids);
$reqs = $res_req['reqs'];
$client_req_ids = $res_req['client_ids'];
}
//Выборка клиентов в заявках
if(!empty($client_req_ids)){
$clients_req = $tel->get_clients_array($client_req_ids);
}
foreach($events as $id=>$ev){
// hide_client_contacts: получатель = $ev['user_id']
$_hideEv = should_hide_contacts_for_user_id($ev['user_id']);
$title = '';
$text = '';
$phoneClient = '';
$schedule_date = date("d.m.Y", strtotime($ev['schedule_date']));
$schedule_date_to = date("d.m.Y", strtotime($ev['schedule_date_to']));
list($d, $m, $y) = explode(".", $schedule_date);
if ($ev['client_id'] > 0) {
$r_cl = $clients[$ev['client_id']];
} else if ($ev['req_id'] > 0) {
$r_cl = $reqs[$ev['req_id']];
if($r_cl['client_id'] > 0){
$r_clr = $clients_req[$r_cl['client_id']];
if ($_hideEv) {
$formatPhone = mask_client_phone($r_clr['phone']);
$phoneClient .= "<i>Клиент: </i>" . mask_fio_for_user_id($r_clr['fio'], $ev['user_id']) . " тел. " . $formatPhone ."\n";
} else {
if (strpos($phone, '+7') !== false) {
$formatPhone = substr($r_clr['phone'], 0, 2) . "(" . substr($r_clr['phone'], 2, 3) . ")" . substr($r_clr['phone'], 5, 3) . "-" . substr($r_clr['phone'], 8, 2) . "-" . substr($r_clr['phone'], 10, 2);
} else {
$formatPhone = $r_clr['phone'];
}
$phoneClient .= "<i>Клиент: </i>" . $r_clr['fio'] . " тел. " . $formatPhone ."\n";
}
}
}
$_cl_fio = isset($r_cl['fio']) ? ($_hideEv ? mask_fio_for_user_id($r_cl['fio'], $ev['user_id']) : $r_cl['fio']) : '';
switch ($ev['type']) {
case 'call':
{
if($ev['client_id'] > 0){
if ($_hideEv) {
$phone = mask_client_phone($r_cl['phone']);
} else {
$phone = $r_cl['phone'];
if (strpos($phone, '+7') !== false) {
$phone = substr($phone, 0, 2) . "(" . substr($phone, 2, 3) . ")" . substr($phone, 5, 3) . "-" . substr($phone, 8, 2) . "-" . substr($phone, 10, 2);
}
}
$title = "<b>Звонок</b> клиенту " . $_cl_fio . " тел. " . $phone;
$text .= "Позвонить с " . date("d.m.Y H:i", strtotime($ev['schedule_date_to']));
$text .= "\nпо " . date("d.m.Y H:i", strtotime($ev['schedule_date']));
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . $ev['comment'];
}
} else if($ev['req_id'] > 0){
$title = "<b>Звонок</b> по заявке " . $_cl_fio . " ID: ".$r_cl['id'];
$text .= "Позвонить с " . date("d.m.Y H:i", strtotime($ev['schedule_date_to']));
$text .= "\nпо " . date("d.m.Y H:i", strtotime($ev['schedule_date']));
if(!in_array($ev['user_id'], $users_req_exception))
$text .= "\n".$phoneClient;
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . $ev['comment'];
}
}
break;
}
}
// echo $text;
$text_o = "Напоминание <i> (время создания " . date("d.m.Y H:i", strtotime($time_zone, strtotime($ev['create_date']))) . ")</i>\n"
. $title . " \n" . str_replace(['&lt;i&gt;', '&lt;/i&gt;', '&lt;br&gt;', '&lt;b&gt;', '&lt;/b&gt;'], ['<i>', '</i>', "\n", '<b>', '</b>'], htmlentities($text));
//echo $text_o."\n";
$chatId = $users[$ev['user_id']]['telegramm_chat_id'];
if($chatId>0){
$tel->send($text_o, $chatId);
}
$update_ids[] = $ev['id'];
if(count($update_ids) == 100){
$pdo->query("UPDATE user_client_events SET tel = 2 WHERE id in (".implode(',',$update_ids).")");
$update_ids = array();
}
}
if(!empty($update_ids)){
$pdo->query("UPDATE user_client_events SET tel = 2 WHERE id in (".implode(',',$update_ids).")");
}
echo 'Время выполнения скрипта 4: '.round(microtime(true) - $start3, 4)." сек.\n";
$start4 = microtime(true);
/* $pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
$tel = new Telegram(false, $pdo);*/
$events = "SELECT e.id, e.type, e.comment, c.phone, e.sum, e.address, e.create_date, e.schedule_date, c.fio, e.user_id FROM user_client_jw_events as e LEFT JOIN clients_jw as c on e.client_id = c.id WHERE e.tel = 0 and e.calendar_view = 0
and e.schedule_date is not null and e.user_id in (".implode(',',$user_arr).") and e.schedule_date <= '" . date("Y-m-d H:i:s", $newTime) . "'";
$q_events =$pdo->query($events);
$update_ids = array();
while ($ev = $pdo->fetch_assoc($q_events)) {
// hide_client_contacts: получатель = $ev['user_id']
$_hideEv = should_hide_contacts_for_user_id($ev['user_id']);
$title = '';
$text = '';
$schedule_date = date("d.m.Y", strtotime($ev['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
if ($_hideEv) {
$phone = mask_client_phone($ev['phone']);
$_fio = mask_fio_for_user_id($ev['fio'], $ev['user_id']);
} else {
$phone = $ev['phone'];
if (strpos($phone, '+7') !== false) {
$phone = substr($phone, 0, 2) . "(" . substr($phone, 2, 3) . ")" . substr($phone, 5, 3) . "-" . substr($phone, 8, 2) . "-" . substr($phone, 10, 2);
}
$_fio = $ev['fio'];
}
switch ($ev['type']) {
case 'call':
{
$title = "<b>Звонок</b> клиенту " . $_fio . " тел. " . $phone;
$text .= $d . " " . getRusMonth($m) . " " . $y . " в " . date("H:i", strtotime($ev['schedule_date']));
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . $ev['comment'];
}
// $text .= "\n<i>". date("H:i", strtotime($ev['create_date']))."</i>";
break;
}
case 'meet':
{
$title = '<b>Встреча</b> с клиентом ' . $_fio . ' тел. ' . $phone;
$text .= 'Встреча будет ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date']));
if ($ev['address']) {
$text .= "\n<i>Адрес:</i> " . $ev['address'];
}
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . $ev['comment'];
}
// $text .= "\n<i>". date("H:i", strtotime($ev['create_date']))."</i>";
break;
}
case 'show':
{
$title = '<b>Показ</b> для клиента ' . $_fio . ' тел. ' . $phone;
$text .= 'Показ будет ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date']));
if ($ev['address']) {
$text .= "\n<i>Адрес:</i> " . $ev['address'];
}
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . $ev['comment'];
}
// $text .= "\n<i>". date("H:i", strtotime($ev['create_date']))."</i>";
break;
}
case 'deal':
{
$title = '<b>Сделка</b> с клиентом ' . $_fio . ' тел. ' . $phone;
$text .= 'Сделка будет ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date']));
if ($ev['sum']) {
$text .= "\n<i>Сумма сделки:</i> " . $ev['sum'] . " р.";
}
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . $ev['comment'];
}
// $text .= "\n<i>". date("H:i", strtotime($ev['create_date']))."</i>";
break;
}
}
// // echo $text;
//$text = htmlentities($text);
$text_o = "Напоминание <i> (время создания " . date("d.m.Y H:i", strtotime($time_zone, strtotime($ev['create_date']))) . ")</i>\n"
. $title . " \n" . str_replace(['&lt;i&gt;', '&lt;/i&gt;', '&lt;br&gt;'], ['<i>', '</i>', "\n"], htmlentities($text));
$chatId = $users[$ev['user_id']]['telegramm_chat_id'];
if($chatId>0){
$tel->send($text_o, $chatId);
}
$update_ids[] = $ev['id'];
}
if(!empty($update_ids)){
$pdo->query("UPDATE user_client_jw_events SET tel = 1 WHERE id in (".implode(',', $update_ids).")");
}
echo 'Время выполнения скрипта 5: '.round(microtime(true) - $start4, 4)." сек.\n";
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error.txt", date('d.m.y H:i:s').' end 5'."\n", FILE_APPEND);
$start5 = microtime(true);
/* $pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
$tel = new Telegram(false, $pdo);*/
//sub_comment
$update_ids = array();
$events = array();
$obj_coordinates = array();
$object_ids = array();
$events_query = "SELECT e.id,
e.type,
e.comment,
e.sum,
e.address,
e.create_date,
e.schedule_date,
e.object_id,
e.user_id,
IF(IFNULL(s.sub_comment, '') = '', NULL, s.sub_comment) AS sub_comment,
IF(s.created_by <> 0, (
SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name)
FROM users as u WHERE u.id = s.created_by
), NULL
) as sub_comment_author,
c.phone,
c.sobstv,
c.initial_object_phone,
c.initial_object_sobstv,
c.phone_search,
c.nazv,
c.adres
FROM user_object_events AS e
LEFT JOIN objects AS c ON e.object_id = c.id
LEFT JOIN user_sub_comments AS s ON s.event_id = e.id AND s.section_id = 1
WHERE e.tel = 0 AND
e.calendar_view = 0 AND
e.schedule_date IS NOT NULL AND
e.user_id in (".implode(',',$user_arr).") AND
e.schedule_date <= '" . date("Y-m-d H:i:s", $newTime) . "'";
$q_events = $pdo->query($events_query);
while ($ev = $pdo->fetch_assoc($q_events)) {
if ($ev['type'] == 'comment') continue;
$object_ids[] = $ev['object_id'];
$events[] = $ev;
}
if(!empty($object_ids)){
$sql_coordinates = "SELECT address, object_id FROM object_location WHERE object_id in (".implode(',', $object_ids).")";
$res_coordinate = $pdo->query($sql_coordinates);
while($r_coordinate = $pdo->fetch_assoc($res_coordinate)){
$obj_coordinates[$r_coordinate['object_id']] = $r_coordinate['address'];
}
}
foreach($events as $ev){
// hide_client_contacts: получатель = $ev['user_id']
$_hideEv = should_hide_contacts_for_user_id($ev['user_id']);
$title = '';
$text = '';
if (isset($obj_coordinates[$ev['object_id']]) && !empty($obj_coordinates[$ev['object_id']]['address'])) {
$ev['adres'] = $obj_coordinates[$ev['object_id']]['address'];
}
$schedule_date = date("d.m.Y", strtotime($ev['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$sobstv = $ev['sobstv'];
if (!empty($ev['initial_object_sobstv'])) {
$sobstv = $ev['initial_object_sobstv'];
}
$phone = $ev['phone'];
if (!empty($ev['initial_object_phone'])) {
$phone = $ev['initial_object_phone'];
} else if (!empty($ev['phone_search'])) {
$phone = '+7' . $ev['phone_search'];
}
// Маска телефона собственника объекта (фактически контакт клиента-собственника)
if ($_hideEv) {
$phone = mask_client_phone($phone);
$sobstv = mask_fio_for_user_id($sobstv, $ev['user_id']);
}
switch ($ev['type']) {
case 'call':
{
$title = '<b>Звонок</b> по объекту ' . $ev['nazv'];
$text .= $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date']));
$text .= "\n тел. " . $phone . ", ответственный: " . $sobstv;
if ($ev['adres']) {
$text .= "\n<i>Адрес объекта:</i> " . $ev['adres'];
}
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . $ev['comment'];
}
if ($ev['sub_comment']) {
$text .= "\n<i>Комментарий к задаче: </i>" . $ev['sub_comment'] . " (" .$ev['sub_comment_author'] . ")";
}
// $text .= "\n<i>". date("H:i", strtotime($ev['create_date']))."</i>";
break;
}
case 'meet':
{
$title = '<b>Встреча</b> по объекту ' . $ev['nazv'];
$text .= 'Встреча будет ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date']));
$text .= "\n тел. " . $phone . ", ответственный: " . $sobstv;
if ($ev['address']) {
$text .= "\n<i>Адрес:</i> " . $ev['address'];
}
if ($ev['adres']) {
$text .= "\n<i>Адрес объекта:</i> " . $ev['adres'];
}
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . $ev['comment'];
}
if ($ev['sub_comment']) {
$text .= "\n<i>Комментарий к задаче: </i>" . $ev['sub_comment'] . " (" .$ev['sub_comment_author'] . ")";
}
// $text .= "\n<i>". date("H:i", strtotime($ev['create_date']))."</i>";
break;
}
case 'show':
{
$title = '<b>Показ</b> по объекту ' . $ev['nazv'];
$text .= 'Показ будет ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date']));
$text .= "\n тел. " . $phone . ", ответственный: " . $sobstv;
if ($ev['address']) {
$text .= "\n<i>Адрес:</i> " . $ev['address'];
}
if ($ev['adres']) {
$text .= "\n<i>Адрес объекта:</i> " . $ev['adres'];
}
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . $ev['comment'];
}
if ($ev['sub_comment']) {
$text .= "\n<i>Комментарий к задаче: </i>" . $ev['sub_comment'] . " (" .$ev['sub_comment_author'] . ")";
}
// $text .= "\n<i>". date("H:i", strtotime($ev['create_date']))."</i>";
break;
}
case 'deal':
{
$title = '<b>Сделка</b> по объекту ' . $ev['nazv'];
$text .= 'Сделка будет ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date']));
$text .= "\n тел. " . $phone . ", ответственный: " . $sobstv;
if ($ev['sum']) {
$text .= "\n<i>Сумма сделки:</i> " . $ev['sum'] . " р.";
}
if ($ev['adres']) {
$text .= "\n<i>Адрес объекта:</i> " . $ev['adres'];
}
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . $ev['comment'];
}
if ($ev['sub_comment']) {
$text .= "\n<i>Комментарий к задаче: </i>" . $ev['sub_comment'] . " (" .$ev['sub_comment_author'] . ")";
}
//$text .= "\n<i>". date("H:i", strtotime($ev['create_date']))."</i>";
break;
}
case 'moderation':
{
$title = '<b>На модерацию</b> отправлен объект ' . $ev['nazv'];
$text .= 'ID '.$ev['object_id'].".";
if ($ev['adres']) {
$text .= "\n<i>Адрес объекта:</i> " . $ev['adres'];
}
$text .= "\n тел. " . $phone . ", ответственный: " . $sobstv;
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . $ev['comment'];
}
if ($ev['sub_comment']) {
$text .= "\n<i>Комментарий к задаче: </i>" . $ev['sub_comment'] . " (" .$ev['sub_comment_author'] . ")";
}
//$text .= "\n<i>". date("H:i", strtotime($ev['create_date']))."</i>";
break;
}
case 'even':
{
$title = '<b>Задача</b> по объекту ' . $ev['nazv'];
$text .= 'ID '.$ev['object_id'].".";
if ($ev['adres']) {
$text .= "\n<i>Адрес объекта:</i> " . $ev['adres'];
}
$text .= "\n тел. " . $phone . ", ответственный: " . $sobstv;
if ($ev['comment']) {
$text .= "\n<i>Комментарий: </i>" . $ev['comment'];
}
if ($ev['sub_comment']) {
$text .= "\n<i>Комментарий к задаче: </i>" . $ev['sub_comment'] . " (" .$ev['sub_comment_author'] . ")";
}
//$text .= "\n<i>". date("H:i", strtotime($ev['create_date']))."</i>";
break;
}
/*case 'comment':
{
if ($ev['comment'])
$text .= $ev['comment'];
break;
}*/
}
$text_o = "Напоминание <i> (время создания " . date("d.m.Y H:i", strtotime($time_zone, strtotime($ev['create_date']))) . ")</i>\n"
. $title . " \n" . str_replace(['&lt;i&gt;', '&lt;/i&gt;', '&lt;br&gt;'], ['<i>', '</i>', "\n"], htmlentities($text));
// echo $text_o."\n";
$chatId = $users[$ev['user_id']]['telegramm_chat_id'];
if($chatId>0){
// if($chatId == '689521489' || $chatId == '255183898' || $chatId == '105877066'){
$keyboardArr = [];
$keyboardArr = [
[
[
'text' => 'Отметить выполненной',
'callback_data' => serialize(array('action'=>13,'id'=>$ev['id']))
]
],
[
[
'text' => 'Отметить выполненной и написать комментарий',
'callback_data' => serialize(array('action'=>14,'id'=>$ev['id']))
]
]
];
$tel->send($text_o, $chatId, null, $keyboardArr);
/* } else {
$tel->send($text_o, $chatId);
}*/
}
$update_ids[] = $ev['id'];
if(count($update_ids) == 100){
$pdo->query("UPDATE user_object_events SET tel = 1 WHERE id in (".implode(',',$update_ids).")");
$update_ids = array();
}
}
if(!empty($update_ids)){
$sql_up = "UPDATE user_object_events SET tel = 1 WHERE id in (".implode(',',$update_ids).")";
if(!$pdo->query($sql_up)){
file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error_sql.txt", date('d.m.y H:i:s').' '.$sql_up.' '.$pdo->error()."\n", FILE_APPEND);
}
}
echo 'Время выполнения скрипта 6: '.round(microtime(true) - $start5, 4)." сек.\n";
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error.txt", date('d.m.y H:i:s').' end 6'."\n", FILE_APPEND);
$start6 = microtime(true);
}
//Переданные клиенты
$update_ids = array();
$events_client = array();
$client_ids = array();
$req_ids = array();
$client_req_ids = array();
$object_ids = array();
$users_ec_ids = array();
$users_ec = array();
$clients = array();
$reqs = array();
$clients_req = array();
$objects = array();
$sql_ec = "SELECT * FROM events_clients WHERE from_id in (".implode(',', $user_ids).") AND `read` IN (0,1,2) AND (event = 'add' or event = 'transmitted_parallel' or event = 'transmitted' or event = 'transmitted_adjacent' or event = 'union') AND `send_telegramm` = 0 AND (req_id>0 or client_id>0) AND date > '2025-12-24 00:00:00' limit 500";
// echo $sql_ec."\n";
// die();
/* $pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
$tel = new Telegram(false, $pdo);*/
//$sql_up = "UPDATE events_clients SET send_telegramm = 2 WHERE from_id in (".implode(',', $user_ids).") AND `read` IN (0,1,2) AND (event = 'add' or event = 'transmitted_parallel' or event = 'transmitted' or event = 'transmitted_adjacent' or event = 'union') AND `send_telegramm` = 0 AND (req_id>0 or client_id>0) AND date > '2025-12-24 00:00:00' limit 500";
$q_ec = $pdo->query($sql_ec);
//$pdo->query($sql_up);
// echo mysql_num_rows($q_ec).'<br>';
while ($r_ec = $pdo->fetch_assoc($q_ec)) {
$events_client[] = $r_ec;
if($r_ec['user_id'] > 0){
$users_ec_ids[] = $r_ec['user_id'];
}
if($r_ec['client_id'] > 0){
$client_ids[] = $r_ec['client_id'];
}
if($r_ec['req_id'] > 0){
$req_ids[] = $r_ec['req_id'];
}
$update_ids[] = $r_ec['id'];
// var_dump($update_ids);
if(count($update_ids) == 50){
$sql_up = "UPDATE events_clients SET send_telegramm = 1 WHERE id in (".implode(',', $update_ids).")";
if(!mysql_query($sql_up)){
file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error_sql.txt", date('d.m.y H:i:s').' '.$sql_up.' '.mysql_error()."\n", FILE_APPEND);
}
$update_ids = array();
}
}
if(!empty($update_ids)){
$sql_up = "UPDATE events_clients SET send_telegramm = 1 WHERE id in (".implode(',', $update_ids).")";
if(!mysql_query($sql_up)){
file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error_sql.txt", date('d.m.y H:i:s').' '.$sql_up.' '.mysql_error()."\n", FILE_APPEND);
}
//mysql_query("UPDATE events_clients SET send_telegramm = 1 WHERE id in (".implode(',', $update_ids).")");
}
if(!empty($users_ec_ids)){
$sql_in = "SELECT `id`, `first_name`, `last_name`, `middle_name`, `agency`, `manager` FROM `users` WHERE `id` in (".implode(',', $users_ec_ids).")";
$q_in = $pdo->query($sql_in);
while($r_in = $pdo->fetch_assoc($q_in)){
$users_ec[$r_in['id']] = $r_in;
}
}
//Выборка клиентов
// var_dump($client_ids);
if(!empty($client_ids)){
$clients = $tel->get_clients_array($client_ids);
}
//Выборка заявок
if(!empty($req_ids)){
$res_req = $tel->get_reqs_array($req_ids);
$reqs = $res_req['reqs'];
$client_req_ids = $res_req['client_ids'];
}
//Выборка объектов
foreach($clients as $c){
if((int)$c['of_objects'] > 0){
$object_ids[] = (int)$c['of_objects'];
}
}
foreach($reqs as $req){
if((int)$req['of_objects'] > 0){
$object_ids[] = (int)$req['of_objects'];
}
}
if(!empty($object_ids)){
$sql_obj = "SELECT nazv, adres, id FROM objects WHERE id in (".implode(',', $object_ids).")";
$q_obj = $pdo->query($sql_obj);
while($r_obj = $pdo->fetch_assoc($q_obj)){
$objects[$r_obj['id']] = $r_obj;
}
}
//Выборка клиентов в заявках
if(!empty($client_req_ids)){
$clients_req = $tel->get_clients_array($client_req_ids);
}
foreach($events_client as $r_ec){
//var_dump($r_ec);
// hide_client_contacts: получатель уведомления = $r_ec['from_id']
$_hideEc = should_hide_contacts_for_user_id($r_ec['from_id']);
$r_in = $users_ec[$r_ec['user_id']];
$post = "Сотрудник";
if ($r_in['agency'] == 1) {
$post = "Агенство";
} else if ($r_in['manager'] == 1) {
$post = "Менеджер";
}
/* $sql_cl = "SELECT `fio`, `phone`, `of_objects`, `opis` FROM `clients` WHERE `id` = " . $r_ec['client_id'];
if ($r_ec['req_id'] > 0) {
$sql_cl = "SELECT `name` as `fio`, '' as `phone`, `object_id` as `of_objects`, client_id, description as opis FROM `requisitions` WHERE `id` = " . $r_ec['req_id'];
}*/
//$q_cl = mysql_query($sql_cl);
$r_cl = null;
if($r_ec['client_id'] > 0){
$r_cl = $clients[$r_ec['client_id']];
} else if($r_ec['req_id'] > 0){
$r_cl = $reqs[$r_ec['req_id']];
}
$text_o = "<b>Вам передают клиента</b> <i> (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")</i>\n";
$text_o .= $post . " " . trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']) . " передал вам клиента ID: ".$r_ec['client_id']."\n";
if ($r_ec['req_id'] > 0) {
$text_o = "<b>Вам передают заявку</b> <i> (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")</i>\n";
$text_o .= $post . " " . trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']) . " передал вам заявку ID: ".$r_ec['req_id']."\n";
}
$dop_tex_o = '';
$dop_tex_o2 = '';
//Взятие в работу в смежных воронках
if($r_ec['event'] == 'transmitted_adjacent'){
$dop_tex_o = '';
$dop_tex_o2 = '';
$text_funnel = "";
$sql_f = "SELECT * FROM funnel WHERE id = {$r_ec['funnelid']}";
$q_f = mysql_query($sql_f);
$name_funel = '';
if($r_f = mysql_fetch_assoc($q_f)){
$name_funel = $r_f['name'];
}
if(!empty($name_funel)){
$text_funnel .= " <b>«".$name_funel."»</b>\n";
}
$text_o = "<b>Клиент взят в работу в смежной воронке \n";
$text_o .= $text_funnel;
$text_o .= "</b> ID: ".$r_ec['client_id']." <i> (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")</i>\n";
if($r_ec['client_id'] == 0 && $r_ec['req_id'] > 0){
$text_o = "<b>Заявка </b> ID: ".$r_ec['req_id']." <i> (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")</i>\n";
$text_o .= "взята в работу в смежной воронке";
$text_o .= $text_funnel;
$text_o .= "Принял: ". $post . " " . trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']) . "\n";
if ($r_cl['client_id'] > 0) {
$r_cln = $clients_req[$r_cl['client_id']];
if (!empty($r_cln['phone'])) {
$r_cl['phone'] = $r_cln['phone'];
}
$_clnFio = $_hideEc ? mask_fio_for_user_id($r_cln['fio'], $r_ec['from_id']) : $r_cln['fio'];
$text_o .= "Kлиент: <b> ID ".$r_cl['client_id']." ".$_clnFio."</b>";
if(!empty($r_cln['phone'])){
$phone = $_hideEc ? mask_client_phone($r_cln['phone']) : $r_cln['phone'];
if(!in_array($r_ec['from_id'], $users_req_exception))
$text_o .= " тел. " . $phone;
}
}
}
// if ($r_ec['req_id'] > 0) {
// $text_o = "<b>Вам передают заявку</b> <i> (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")</i>\n";
// $text_o .= $post . " " . trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']) . " Принял заявку ID: ".$r_ec['req_id']."\n";
// }
/* if(!empty($r_ec['dop_text'])){
$dop_tex_o2 = "\n".$r_ec['dop_text']."\n";
}*/
}
// Добавлен клиент
// Событие add
if ($r_ec['event'] == 'add') {
$text_o = "<b>Добавлен клиент </b> ID: ".$r_ec['client_id']." <i> (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")</i>\n";
if($r_ec['client_id'] == 0 && $r_ec['req_id'] > 0){
$text_o = "<b>Добавлена заявка </b> ID: ".$r_ec['req_id']." <i> (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")</i>\n";
if ($r_cl['client_id'] > 0) {
$r_cln = $clients_req[$r_cl['client_id']];
if (!empty($r_cln['phone'])) {
$r_cl['phone'] = $r_cln['phone'];
}
$_clnFio = $_hideEc ? mask_fio_for_user_id($r_cln['fio'], $r_ec['from_id']) : $r_cln['fio'];
$dop_tex_o .= " по клиенту: <b> ID ".$r_cl['client_id']." ".$_clnFio."</b>";
if(!empty($r_cln['phone'])){
$phone = $_hideEc ? mask_client_phone($r_cln['phone']) : $r_cln['phone'];
if(!in_array($r_ec['from_id'], $users_req_exception))
$dop_tex_o .= " тел. " . $phone;
}
}
}
if(!empty($r_ec['dop_text'])){
$dop_tex_o2 = "\n".$r_ec['dop_text']."\n";
}
}
if ($r_ec['event'] == 'union') {
//$text_o = "<b>Добавлен клиент </b> ID: ".$r_ec['client_id']." <i> (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")</i>\n";
if($r_ec['client_id'] == 0 && $r_ec['req_id'] > 0){
$text_o = "<b>Заявки объединены: </b>";
}
if(!empty($r_ec['dop_text'])){
$dop_tex_o2 = "\n".str_replace("<br>", "\n", $r_ec['dop_text'])."\n";
$text_o .= $dop_tex_o2;
}
}
if ($r_ec['event'] == 'transmitted_parallel' && $r_ec['read'] == 0) {
$text_o = "<b>Вас приглашают к совместной работе</b> <i> (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")</i>\n";
//var_dump($text_o);
if ($r_ec['req_id'] > 0) {
$text_o .= $post . " " . trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']) . " приглашает вас к совместной работе по заявке\n";
if ($r_cl['client_id'] > 0) {
$r_cln = $clients_req[$r_cl['client_id']];
if (!empty($r_cln['phone'])) {
$r_cl['phone'] = $r_cln['phone'];
}
}
//var_dump($text_o);
} else {
$text_o .= $post . " " . trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']) . " приглашает вас к совместной работе по клиенту\n";
}
} else if ($r_ec['event'] == 'transmitted_parallel' && $r_ec['read'] == 2) {
if ($r_ec['req_id'] > 0) {
$text_o = "<b>Поступила заявка по которой вы назначены партнером </b> <i> (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")</i>\n";
$text_o .= $post . " " . trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']) . " - ответственный по заявке\n";
if ($r_cl['client_id'] > 0) {
$r_cln = $clients_req[$r_cl['client_id']];
if (!empty($r_cln['phone'])) {
$r_cl['phone'] = $r_cln['phone'];
}
}
//var_dump($text_o);
} else {
$text_o = "<b>Поступил клиент по которому вы назначены партнером </b> <i> (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")</i>\n";
$text_o .= $post . " " . trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']) . " - ответственный по клиенту\n";
//var_dump($text_o);
}
} else if ($r_ec['req_id'] > 0) {
if($r_ec['event'] != 'transmitted_adjacent'){
if ($r_cl['client_id'] > 0) {
$r_cln = $clients_req[$r_cl['client_id']];
$_clnFio = $_hideEc ? mask_fio_for_user_id($r_cln['fio'], $r_ec['from_id']) : $r_cln['fio'];
$dop_tex_o .= " по клиенту: <b> ID ".$r_cl['client_id']." ".$_clnFio."</b>";
if(!empty($r_cln['phone'])){
$phone = $_hideEc ? mask_client_phone($r_cln['phone']) : $r_cln['phone'];
if(!in_array($r_ec['user_id'], $users_req_exception)){
$dop_tex_o .= " тел. " . $phone;
} else {
if($r_cl['type_id'] != 4 && $r_cl['heir'] != 4){
if(!in_array($r_ec['from_id'], $users_req_exception))
$dop_tex_o .= " тел. " . $phone;
}
}
}
}
}
}
//var_dump($text_o);
// echo $text_o.'<br>';
if($r_ec['event'] != 'transmitted_adjacent' && $r_ec['event'] != 'union' && $r_ec['event'] != 'add'){
$_clFio = $_hideEc ? mask_fio_for_user_id($r_cl['fio'], $r_ec['from_id']) : $r_cl['fio'];
$text_o .= "<b>" . $_clFio . "</b>";
if(isset($dop_tex_o2)){
$text_o .= $dop_tex_o2;
}
if(isset($dop_tex_o) && $r_ec['req_id'] > 0){
$text_o .= $dop_tex_o;
} else if (!empty($r_cl['phone'])) {
$phone = $_hideEc ? mask_client_phone($r_cl['phone']) : $r_cl['phone'];
// $phone = substr($phone, 0, 2) . "(" . substr($phone, 2, 3) . ")" . substr($phone, 5, 3) . "-" . substr($phone, 8, 2) . "-" . substr($phone, 10, 2);
if(!in_array($r_ec['from_id'], $users_req_exception))
$text_o .= " тел. " . $phone;
}
}
if(!empty($r_cl['opis']) && $r_ec['event'] != 'union'){
$text_o .= "\nОписание: ".$r_cl['opis'];
}
if (!empty($r_cl['of_objects']) && $r_ec['event'] != 'union') {
$r_obj =$objects[$r_cl['of_objects']];
$name = '';
if (!empty($r_obj['nazv'])) {
$name .= $r_obj['nazv'];
}
if (!empty($r_obj['adres'])) {
if ($name != '') {
$name .= ',';
}
$name .= ' адрес: ' . $r_obj['adres'];
}
if (!empty($name)) {
$text_o .= "\nЗаявка по объекту ID ".$r_obj['id']." " . $name;
}
}
// echo $text_o."\n";
$text_o = str_replace(['&lt;i&gt;', '&lt;/i&gt;', '&lt;br&gt;', '&lt;b&gt;', '&lt;/b&gt;', '&laquo;', '&raquo;'], ['<i>', '</i>', "\n", '<b>', '</b>', '', ''], htmlentities($text_o));
//echo $text_o."\n\n";
$chatId = $users[$r_ec['from_id']]['telegramm_chat_id'];
if($chatId>0){
$keyboardArr = [];
if($r_ec['event'] == 'transmitted' || $r_ec['event'] == 'transmitted_parallel'){
$keyboardArr = [
[
[
'text' => 'Принять в работу',
'callback_data' => serialize(array('action'=>16,'id'=>$r_ec['id']))
]
]
];
}
$tel->send($text_o, $chatId, null, $keyboardArr);
}
// mysql_query("UPDATE events_clients SET send_telegramm = 1 WHERE id = " . $r_ec['id']);
}
echo 'Время выполнения скрипта 7: '.round(microtime(true) - $start6, 4)." сек.\n";
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error.txt", date('d.m.y H:i:s').' end 7'."\n", FILE_APPEND);
$start7 = microtime(true);
/*$pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);*/
// $tel = new Telegram(false, $pdo);
$update_ids = array();
$events_object = array();
$client_ids = array();
$req_ids = array();
$client_req_ids = array();
$object_ids = array();
$users_ec_ids = array();
$users_ec = array();
$clients = array();
$reqs = array();
$clients_req = array();
$objects = array();
$objClientsLike = [];
//Переданные объекты
$sql_object_send = "SELECT * FROM objects_to_send WHERE new_user_id in (".implode(',',$user_ids).") AND send_telegramm=0";
//echo $sql_object_send."\n";
//die();
$q_object_send = $pdo->query($sql_object_send);
while($r_object_send = $pdo->fetch_assoc($q_object_send)){
$events_object[] = $r_object_send;
$users_ec_ids[] = $r_object_send['sended_user_id'];
$object_ids[] = $r_object_send['object_id'];
$update_ids[] = $r_object_send['id'];
if(count($update_ids) == 50){
$sql_up = "update objects_to_send set send_telegramm = 1 WHERE id in (".implode(',',$update_ids).")";
if(!mysql_query($sql_up)){
file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error_sql.txt", date('d.m.y H:i:s').' '.$sql_up.' '.mysql_error()."\n", FILE_APPEND);
}
$update_ids = array();
}
}
if(!empty($update_ids)){
$sql_up = "update objects_to_send set send_telegramm = 1 WHERE id in (".implode(',',$update_ids).")";
//echo $sql_up."\n";
if(!mysql_query($sql_up)){
file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error_sql.txt", date('d.m.y H:i:s').' '.$sql_up.' '.mysql_error()."\n", FILE_APPEND);
}
//$pdo->query("update objects_to_send set send_telegramm = 1 WHERE id in (".implode(',',$update_ids).")");
}
if(!empty($users_ec_ids)){
$sql_in = "SELECT `id`, `agency_name`, `first_name`, `last_name`, `middle_name`, `agency`, `manager` FROM `users` WHERE `id` in (".implode(',', $users_ec_ids).")";
$q_in = $pdo->query($sql_in);
while($r_u = $pdo->fetch_assoc($q_in)){
$users_ec[$r_u['id']] = $r_u;
}
}
if(!empty($object_ids)){
/* $sqlClients = "SELECT `id`, `fio`, `email`, `phone` FROM `clients` WHERE " . implode(" or ", $objClientsLike);
$q_client = $pdo->query($sqlClients);
while($r_client = $pdo->fetch_assoc($q_client)){
$clients[$r_client['id']] = $r_client;
}*/
$sql_obj = "SELECT nazv, id FROM `objects` WHERE id in (".implode(',',$object_ids).")";
$q_obj = $pdo->query($sql_obj);
while($r_obj = $pdo->fetch_assoc($q_obj)){
$objects[$r_obj['id']] = $r_obj;
}
}
foreach($events_object as $r_object_send){
$r_in = $users_ec[$r_object_send['sended_user_id']];
$post = "Сотрудник " . trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']);
if ($r_in['agency'] == 1) {
$post = "Агентство " . $r_in['agency_name'];
} else {
if ($r_in['manager'] == 1) {
$post = "Менеджер " . trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']);
}
}
$clientsNum = 0;
$clientsString = '';
$clientObjIds = [];
/*$sql_cl_obj = "SELECT client_id FROM client_objects WHERE object_id = {$r_object_send['object_id']}";
$q_cl_obj = $pdo->query($sql_cl_obj);
while($r_cl_obj = $pdo->fetch_assoc($q_cl_obj)){
$clientObjIds[] = $r_cl_obj['client_id'];
}
if(!empty($clientObjIds)){
$sql_clients = "SELECT `id`, `fio`, `email` FROM `clients` WHERE id in (".implode(',', $clientObjIds).")";
$q_client = $pdo->query($sql_clients);
if($pdo->num_rows($q_client) > 0){
while($client = $pdo->fetch_assoc($q_client)) {
$clientsNum++;
$clientsString = $clientsString . ($clientsNum > 1 ? ", " : "") . $client['fio'];
if(!empty($client['phone'])){
$clientsString .= ' ('.$client['phone'].')';
}
$clientsString .= "\n";
}
}
}*/
// $sql_obj = "SELECT nazv, id FROM `objects` WHERE id= $r_object_send[object_id]";
// $q_obj = mysql_query($sql_obj);
$r_obj = $objects[$r_object_send['object_id']];
$first_line = $post . "\nпередал вам объект ID ".$r_obj['id']." «<b>" . $r_obj['nazv'] . "</b>»";
if ($clientsNum > 0) {
if ($clientsNum > 1) {
$first_line = $first_line . "\n и клиентов <b>" . $clientsString."</b>";
} else {
$first_line = $first_line . "\n и клиента <b>" . $clientsString."</b>";
}
}
$first_line .="\n <i> (время создания " . date("d.m.Y H:i", strtotime($r_object_send['create_date'])) . ")</i>";
//echo $first_line."\n";
$chatId = $users[$r_object_send['new_user_id']]['telegramm_chat_id'];
if($chatId>0){
$keyboardArr = [];
$keyboardArr = [
[
[
'text' => 'Принять в работу',
'callback_data' => serialize(array('action'=>17,'id'=>$r_object_send['id']))
]
]
];
$tel->send($first_line, $chatId, null, $keyboardArr);
}
}
echo 'Время выполнения скрипта 8: '.round(microtime(true) - $start7, 4)." сек.\n";
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error.txt", date('d.m.y H:i:s').' end 8'."\n", FILE_APPEND);
$start8 = microtime(true);
/*$pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
$tel = new Telegram(false, $pdo);*/
//уведомления по выпискам
$update_ids = array();
$sql_req_notice = "SELECT * FROM discharge_user_notice WHERE user_id in (".implode(',', $user_ids).") AND sended = 0";
$q_req_notice = $pdo->query($sql_req_notice);
while ($notice = $pdo->fetch_assoc($q_req_notice)) {
$chatId = $users[$notice['user_id']]['telegramm_chat_id'];
if($chatId>0){
$tel->send($notice['text'], $chatId);
}
$update_ids[] = $notice['id'];
}
if(!empty($update_ids)){
$sql_req_notice_u = "UPDATE discharge_user_notice SET sended = 1 WHERE id in (".implode(',',$update_ids).")";
$pdo->query($sql_req_notice_u);
}
echo 'Время выполнения скрипта 9: '.round(microtime(true) - $start8, 4)." сек.\n";
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error.txt", date('d.m.y H:i:s').' end 9'."\n", FILE_APPEND);
$start9 = microtime(true);
/* $pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
$tel = new Telegram(false, $pdo);*/
//Уведомления о рекламе
$areas = array('yandex' => 'Яндекс', 'avito' => 'Авито', 'cian' => 'Циан', 'domclick' => 'Домклик', 'jcad' => 'JCAD');
$update_ids = array();
$sql_ad = "SELECT * FROM object_ad WHERE manager_id in (".implode(',', $user_ids).") AND send = 0";
$q_ad = $pdo->query($sql_ad);
while($r_ad = $pdo->fetch_assoc($q_ad)){
$sql_in = "SELECT `first_name`, `last_name`, `middle_name`, `agency`, `manager` FROM `users` WHERE `id` = {$r_ad['user_id']}";
$q_in = $pdo->query($sql_in);
$r_in = $pdo->fetch_assoc($q_in);
$post = "Сотрудник";
if ($r_in['agency'] == 1) {
$post = "Агенство";
} else if ($r_in['manager'] == 1) {
$post = "Менеджер";
}
$em = $post." ".trim($r_in['last_name']." ".$r_in['first_name']." ".$r_in['middle_name']);
$sql_o = "SELECT id, adres, stoim FROM objects WHERE id = {$r_ad['object_id']}";
$q_o = $pdo->query($sql_o);
$obj = $pdo->fetch_assoc($q_o);
if($obj){
$text_o = "<b>".$em."</b>\n";
if($r_ad['on_off'] == 0){
$text_o .= "убрал объект из рекламы";
if(!empty($r_ad['area']) && isset($areas[$r_ad['area']])){
$text_o .= " ".$areas[$r_ad['area']];
}
$text_o .= "\n";
} else {
$text_o .= "добавил объект в рекламу\n";
}
$text_o .= "ID: ".$obj['id']."\n";
$text_o .= "Адрес: ".$obj['adres']."\n";
$text_o .= "Цена: ".$obj['stoim']."\n";
if($r_ad['on_off'] == 0){
$text_o .= "";
} else {
$text_o .= "Необходимо проверить и выставить данный объект в рекламу";
}
$chatId = $users[$r_ad['manager_id']]['telegramm_chat_id'];
if($chatId>0){
$tel->send($text_o, $chatId);
}
$update_ids[] = $r_ad['id'];
} else {
$update_ids[] = $r_ad['id'];
}
}
if(!empty($update_ids)){
$sql_req_notice_u = "UPDATE object_ad SET send = 1 WHERE id in (".implode(',',$update_ids).")";
$pdo->query($sql_req_notice_u);
}
echo 'Время выполнения скрипта 10: '.round(microtime(true) - $start9, 4)." сек.\n";
$start10 = microtime(true);
/*$pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
$tel = new Telegram(false, $pdo);*/
//Уведомления о закрытии этапа
$update_ids = array();
$sql_st = "SELECT * FROM `step_notify_closure` WHERE send = 0 AND user_id in (".implode(',', $user_ids).")";
$q_st = $pdo->query($sql_st);
while($r_st = $pdo->fetch_assoc($q_st)){
$text = htmlspecialchars_decode(str_replace(['&lt;i&gt;', '&lt;/i&gt;', '&lt;br&gt;', '&lt;b&gt;', '&lt;/b&gt;', '&laquo;', '&raquo;'], ['<i>', '</i>', "\n", '<b>', '</b>', '', ''],$r_st['text']));
$chatId = $users[$r_st['user_id']]['telegramm_chat_id'];
if($chatId>0){
$tel->send($text, $chatId);
}
$update_ids[] = $r_st['id'];
}
if(!empty($update_ids)){
$sql_req_notice_u = "UPDATE step_notify_closure SET send = 1 WHERE id in (".implode(',',$update_ids).")";
$pdo->query($sql_req_notice_u);
}
echo 'Время выполнения скрипта 11: '.round(microtime(true) - $start10, 4)." сек.\n";
$start11 = microtime(true);
/* $pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
$tel = new Telegram(false, $pdo);*/
if (date("H") == 10 && ! empty($users_ids_10)) {
$startDateWhereBirthday = "DATE_FORMAT(birthday, '%m-%d') ='" . date('m-d') . "'";
$sql_b = "SELECT id, fio, birthday, phone, who_work FROM clients WHERE cancel=0 AND who_work in (".implode(',', $users_ids_10).") AND " . $startDateWhereBirthday;
$q_b = $pdo->query($sql_b);
while ($r_b = $pdo->fetch_assoc($q_b)) {
// hide_client_contacts: получатель = $r_b['who_work']
$_hideB = should_hide_contacts_for_user_id($r_b['who_work']);
$text_o = "<b>Сегодня День рождения</b>\n";
$_bFio = $_hideB ? mask_fio_for_user_id($r_b['fio'], $r_b['who_work']) : $r_b['fio'];
$text_o .= "у клиента «<b>" . $_bFio . "</b>»\n";
if (!empty($r_b['phone'])) {
if ($_hideB) {
$phone = mask_client_phone($r_b['phone']);
} else {
$phone = $r_b['phone'];
if (strpos($phone, '+7') !== false) {
$phone = substr($phone, 0, 2) . "(" . substr($phone, 2, 3) . ")" . substr($phone, 5, 3) . "-" . substr($phone, 8, 2) . "-" . substr($phone, 10, 2);
}
}
if(!in_array($r_b['who_work'], $users_req_exception))
$text_o .= "телефон: " . $phone;
}
// $text_o = str_replace(['&lt;i&gt;', '&lt;/i&gt;','&lt;br&gt;'],['<i>','</i>',"\n"], htmlentities($text_o));
$chatId = $users[$r_b['who_work']]['telegramm_chat_id'];
if($chatId>0 && $chatId != 8244379328){
$tel->send($text_o, $chatId);
}
}
$sql_t_u = "UPDATE users SET telegramm_date = '" . date('Y-m-d 10:00:00') . "' WHERE id in (".implode(',', $users_ids_10).")";
$pdo->query($sql_t_u);
}
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error.txt", date('d.m.y H:i:s').' end 87'."\n", FILE_APPEND);
$start88 = microtime(true);
// Уведомления о днях рождения у сотрудников агенств
if (date("H") == 11 && !empty($users_ids_11)) {
/* $pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
$tel = new Telegram(false, $pdo);*/
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error.txt", date('d.m.y H:i:s').' start 88'."\n", FILE_APPEND);
foreach($users_ids_11 as $user){
//if($user['id'] == 15163){
//$agencyId = $user['id'];
$agencyId = User::getUserAgencyID($user['id']);
if((int)$agencyId == 0){
$agencyId = $user['id'];
}
/* if (isset($user['id_manager'])) {
if (boolval($user['id_manager'])) {
$agencyId = $user['id_manager'];
}
}*/
$usersIds = [];
//echo "/***** ".$agencyId."******/\n";
$sql_users = "SELECT id FROM users WHERE id in (select id from users where id=$agencyId or id_manager=$agencyId or id_manager in
(select id from users where id_manager=$agencyId or id_manager in
(select id from users where id_manager=$agencyId)))";
$q_users = $pdo->query($sql_users);
while($r_users = $pdo->fetch_assoc($q_users)){
$usersIds[] = (int)$r_users['id'];
}
if (!empty($usersIds)) {
$startDateWhereBirthday = "DATE_FORMAT(birthday, '%m-%d') = '" . date('m-d', strtotime("+1 day")) . "'";
$sql_b = "SELECT id, fio, last_name, first_name, middle_name, birthday, phone FROM users WHERE (id IN (" . implode(',', $usersIds) . ") AND id != $user[id]) AND " . $startDateWhereBirthday;
// echo $sql_b."\n";
$q_b = $pdo->query($sql_b);
while ($r_b = $pdo->fetch_assoc($q_b)) {
$fio = trim($r_b['last_name'] . ' ' . $r_b['first_name'] . ' ' . $r_b['middle_name']);
$text_o = "Завтра <b>День рождения</b>\n";
$text_o .= "у <b>" . $fio . "</b>, сотрудника Вашего агентства.\n";
if (!empty($r_b['phone'])) {
$phone = $r_b['phone'];
if (strpos($phone, '+7') !== false) {
$phone = substr($phone, 0, 2) . "(" . substr($phone, 2, 3) . ")" . substr($phone, 5, 3) . "-" . substr($phone, 8, 2) . "-" . substr($phone, 10, 2);
}
if(!in_array($user['id'], $users_req_exception))
$text_o .= " Телефон: " . $phone . ".\n";
}
$chatId = $users[$user['id']]['telegramm_chat_id'];
if($chatId>0 && $chatId != 8244379328){
// echo $text_o."\n";
$tel->send($text_o, $chatId);
////file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error.log", date('d.m.y H:i:s').' '.$user['id'].' '.$chatId.' '.$text_o."\n", FILE_APPEND);
}
}
}
//}
}
$sql_t_u = "UPDATE users SET telegramm_date = '" . date('Y-m-d 11:00:00') . "' WHERE id in (".implode(',', $user_ids).")";
// echo $sql_t_u;
$pdo->query($sql_t_u);
}
echo 'Время выполнения скрипта 88: '.round(microtime(true) - $start88, 4)." сек.\n";
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error.txt", date('d.m.y H:i:s').' end 88'."\n", FILE_APPEND);
// Уведомления о днях рождения у сотрудников партнёров
if (date("H") == 12 && !empty($users_ids_12)) {
/* $pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
$tel = new Telegram(false, $pdo);*/
$startDateWhereBirthday = "DATE_FORMAT(employee.birthday, '%m-%d') = '" . date('m-d') . "'";
foreach($users_ids_12 as $user){
$sql_b = "SELECT employee.id,
employee.partner_id,
employee.name,
employee.phone,
employee.birthday,
partner.name AS partner_name,
partner.resident AS partner_resident
FROM `partners_employees` AS employee
LEFT JOIN `partners` AS partner ON partner.id = employee.partner_id
LEFT JOIN `users` AS users ON employee.created_by = users.id OR employee.updated_by
WHERE (users.id = " . $user['id'] . " OR users.id_manager = " . $user['id'] . " OR users.id_manager IN (
SELECT id FROM `users` WHERE id_manager = " . $user['id'] . "
))
AND (
employee.created_by = " . $user['id'] . " OR
employee.updated_by = " . $user['id'] . " OR
employee.id IN (
SELECT clients.employee_id
FROM `clients` AS clients
WHERE clients.who_work = " . $user['id'] . "
)
)
AND employee.birthday_notify > 0 AND employee.status > 0
AND $startDateWhereBirthday
GROUP BY employee.id";
$q_b = $pdo->query($sql_b);
while ($r_b = $pdo->fetch_assoc($q_b)) {
if (!empty($r_b['name']) && !empty($r_b['partner_name'])) {
$text_o = "<b>Сегодня День рождения</b>\n";
$text_o .= "у сотрудника «<b>" . $r_b['name'] . "</b>» партнёра «<b>" . $r_b['partner_name'] . (!empty($r_b['partner_resident']) ? ", " . $r_b['partner_resident'] : "") . "</b>»\n";
if (!empty($r_b['phone'])) {
$phone = $r_b['phone'];
if (strpos($phone, '+7') !== false) {
$phone = substr($phone, 0, 2) . "(" . substr($phone, 2, 3) . ")" . substr($phone, 5, 3) . "-" . substr($phone, 8, 2) . "-" . substr($phone, 10, 2);
}
if(!in_array($user['id'], $users_req_exception))
$text_o .= "телефон: " . $phone;
}
$chatId = $users[$user['id']]['telegramm_chat_id'];
if($chatId>0 && $chatId != 8244379328){
$tel->send($text_o, $chatId);
}
}
}
}
$sql_t_u = "UPDATE users SET telegramm_date = '" . date('Y-m-d 12:00:00') . "' WHERE id in (".implode(',', $user_ids).")";
$pdo->query($sql_t_u);
}
echo 'Время выполнения скрипта: '.round(microtime(true) - $start, 4).' сек.';
/*-----------------------------------------------------------------------------------------------------------------*/
const TOKEN = '793676666:AAGFo66CjsmO2KxZVRwQbH8pLTvenpsHiHI';
const BASE_URL = 'https://api.telegram.org/bot' . TOKEN . '/';
require_once $_SERVER['DOCUMENT_ROOT'] . "/telegramm/vendor/autoload.php";
$bot = new \TelegramBot\Api\Client(TOKEN);
//Получение уведомлений с ПроНовостройки
$sqlpro = "SELECT block_message.*, blocks.name as block_name FROM block_message left join blocks on blocks.id = block_message.block_id WHERE block_message.tel = 0";
$qpro = $pdo->query($sqlpro);
$names = array('phone' => 'Телефон', 'fio' => 'Имя', 'block_name' => 'ЖК', 'income' => 'Месячный доход семьи', 'work' => 'Общий трудовой стаж', 'payment' => 'Первоначальный взнос', 'flatId' => 'ID квартиры', 'date' => 'Дата', 'time' => 'Время');
// echo mysql_num_rows($qpro);
while ($rpro = $pdo->fetch_assoc($qpro)) {
$chatId = 255183898;
$title = 'Клиент с ПроНовостройки';
$text = '';
$schedule_date = date("d.m.Y", strtotime($rpro['date_created']));
switch ($rpro['subject']) {
case 'consultation':{
$text .= "<b>Получить консультацию юриста</b>\n";
break;
}
case 'mortgage':{
$text .= "<b>Подать заявки во все банки</b>\n";
break;
}
case 'tobook':{
$text .= "<b>Забронироваать и получить дополнительную скидку</b>\n";
break;
}
case 'excursion':{
$text .= "<b>Записаться на экскурсию</b>\n";
break;
}
case 'tocall':{
$text .= "<b>Заявка на звонок</b>\n";
break;
}
case 'report':{
$text .= "<b>Заявка на отчет</b>\n";
break;
}
}
foreach ($rpro as $key => $value) {
// echo $key.'---';
if ($key != 'date_created' && $key != 'id' && $key != 'block_id' && $key != 'subject' && !empty($value)) {
$text .= $names[$key] . ": " . $value . "\n";
}
}
$text .= "<i> (время создания " . date("d.m.Y H:i", strtotime($rpro['date_created'])) . ")</i>\n";
// echo $text.'<br>';
try {
$bot->sendMessage($chatId, $text, 'html');
} catch (Exception $e) {
echo 'Выброшено исключение: ', $e->getMessage(), "\n";
// file_put_content($_SERVER['DOCUMENT_ROOT']."/".telegramm_error.log.$e->getMessage(), )
}
$pdo->query("UPDATE block_message SET tel = 1 WHERE id = " . $rpro['id']);
}
$bot->run();
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_error.txt", date('d.m.y H:i:s').' end ', FILE_APPEND);
// Уведомления о днях рождения у клиентов
/* if (date("H") == 10) {
if (empty($r['telegramm_date']) || ($r['telegramm_date'] != date('Y-m-d 10:00:00'))) {
$startDateWhereBirthday = "DATE_FORMAT(birthday, '%m-%d') ='" . date('m-d') . "'";
$sql_b = "SELECT id, fio, birthday, phone FROM clients WHERE who_work = " . $r['id'] . " AND " . $startDateWhereBirthday;
// echo $sql_b;
$q_b = mysql_query($sql_b);
while ($r_b = mysql_fetch_assoc($q_b)) {
$text_o = "<b>Сегодня День рождения</b>\n";
$text_o .= "у клиента «<b>" . $r_b['fio'] . "</b>»\n";
if (!empty($r_b['phone'])) {
$phone = $r_b['phone'];
$phone = substr($phone, 0, 2) . "(" . substr($phone, 2, 3) . ")" . substr($phone, 5, 3) . "-" . substr($phone, 8, 2) . "-" . substr($phone, 10, 2);
$text_o .= "телефон: " . $phone;
}
// $text_o = str_replace(['&lt;i&gt;', '&lt;/i&gt;','&lt;br&gt;'],['<i>','</i>',"\n"], htmlentities($text_o));
// // echo $text_o;
try {
$bot->sendMessage($chatId, $text_o, 'html');
} catch (Exception $e) {
echo 'Выброшено исключение: ', $e->getMessage(), "\n";
// file_put_content($_SERVER['DOCUMENT_ROOT']."/".telegramm_error.log.$e->getMessage(), )
}
}
}
$sql_t_u = "UPDATE users SET telegramm_date = '" . date('Y-m-d 10:00:00') . "' WHERE id = " . $r['id'];
// echo $sql_t_u;
mysql_query($sql_t_u);
}
// Уведомления о днях рождения у сотрудников агенств
/* if (date("H") == 11) {
if (empty($r['telegramm_date']) || ($r['telegramm_date'] != date('Y-m-d 11:00:00'))) {
$agencyId = $r['id'];
if (isset($r['id_manager'])) {
if (boolval($r['id_manager'])) {
$agencyId = $r['id_manager'];
}
}
$usersIds = User::getAllAgencyUsers($agencyId);
if (!empty($usersIds)) {
$startDateWhereBirthday = "DATE_FORMAT(birthday, '%m-%d') = '" . date('m-d', strtotime("+1 day")) . "'";
$sql_b = "SELECT id, fio, last_name, first_name, middle_name, birthday, phone FROM users WHERE (id IN (" . implode(',', $usersIds) . ") AND id != $r[id]) AND " . $startDateWhereBirthday;
// echo $sql_b;
$q_b = mysql_query($sql_b);
while ($r_b = mysql_fetch_assoc($q_b)) {
$fio = trim($r_b['last_name'] . ' ' . $r_b['first_name'] . ' ' . $r_b['middle_name']);
$text_o = "Завтра <b>День рождения</b>\n";
$text_o .= "у <b>" . $fio . "</b>, сотрудника Вашего агентства.\n";
if (!empty($r_b['phone'])) {
$phone = $r_b['phone'];
$phone = substr($phone, 0, 2) . "(" . substr($phone, 2, 3) . ")" . substr($phone, 5, 3) . "-" . substr($phone, 8, 2) . "-" . substr($phone, 10, 2);
$text_o .= " Телефон: " . $phone . ".\n";
}
try {
$bot->sendMessage($chatId, $text_o, 'html');
//var_export([$r['id'], $chatId, $text_o, $sql_b]);
} catch (Exception $e) {
echo 'Выброшено исключение: ', $e->getMessage(), "\n";
// file_put_content($_SERVER['DOCUMENT_ROOT']."/".telegramm_error.log.$e->getMessage(), )
}
}
}
}
$sql_t_u = "UPDATE users SET telegramm_date = '" . date('Y-m-d 11:00:00') . "' WHERE id = " . $r['id'];
// echo $sql_t_u;
mysql_query($sql_t_u);
}
// Уведомления о днях рождения у сотрудников партнёров
/* if (date("H") == 12) {
if (empty($r['telegramm_date']) || ($r['telegramm_date'] != date('Y-m-d 12:00:00'))) {
$startDateWhereBirthday = "DATE_FORMAT(employees.birthday, '%m-%d') = '" . date('m-d') . "'";
$sql_b = "SELECT employee.id,
employee.partner_id,
employee.name,
employee.phone,
employee.birthday,
partner.name AS partner_name,
partner.resident AS partner_resident
FROM `partners_employees` AS employee
LEFT JOIN `partners` AS partner ON partner.id = employee.partner_id
LEFT JOIN `users` AS users ON employee.created_by = users.id OR employee.updated_by
WHERE (users.id = " . $r['id'] . " OR users.id_manager = " . $r['id'] . " OR users.id_manager IN (
SELECT id FROM `users` WHERE id_manager = " . $r['id'] . "
))
AND (
employee.created_by = " . $r['id'] . " OR
employee.updated_by = " . $r['id'] . " OR
employee.id IN (
SELECT clients.employee_id
FROM `clients` AS clients
WHERE clients.who_work = " . $r['id'] . "
)
)
AND employee.birthday_notify > 0 AND employee.status > 0
AND $startDateWhereBirthday
GROUP BY employee.id";
$q_b = mysql_query($sql_b);
while ($r_b = mysql_fetch_assoc($q_b)) {
if (!empty($r_b['name']) && !empty($r_b['partner_name'])) {
$text_o = "<b>Сегодня День рождения</b>\n";
$text_o .= "у сотрудника «<b>" . $r_b['name'] . "</b>» партнёра «<b>" . $r_b['partner_name'] . (!empty($r_b['partner_resident']) ? ", " . $r_b['partner_resident'] : "") . "</b>»\n";
if (!empty($r_b['phone'])) {
$phone = $r_b['phone'];
$phone = substr($phone, 0, 2) . "(" . substr($phone, 2, 3) . ")" . substr($phone, 5, 3) . "-" . substr($phone, 8, 2) . "-" . substr($phone, 10, 2);
$text_o .= "телефон: " . $phone;
}
try {
$bot->sendMessage($chatId, $text_o, 'html');
//var_export([$r['id'], $chatId, $text_o, $sql_b]);
} catch (Exception $e) {
echo 'Выброшено исключение: ', $e->getMessage(), "\n";
// file_put_content($_SERVER['DOCUMENT_ROOT']."/".telegramm_error.log.$e->getMessage(), )
}
}
}
}
$sql_t_u = "UPDATE users SET telegramm_date = '" . date('Y-m-d 12:00:00') . "' WHERE id = " . $r['id'];
// echo $sql_t_u;
mysql_query($sql_t_u);
}*/
// Уведомления о новых объектах по заявкам из автопоиска
/*if (date("H") == 14) {
if (empty($r['telegramm_date']) || ($r['telegramm_date'] != date('Y-m-d 14:00:00'))) {
$autosearch = new AutoSearch();
if ($results = $autosearch->getSummaryInfo(intval($r['id']), true, true)) {
$message = $autosearch->buildTelegramMessage($results, $r['id']);
if (!empty($message)) {
$message = "<b>Автопоиск (подбор) объектов</b>".$message;
try {
if (mb_strlen($message) > 4096) {
$i = 0;
$messages = [];
foreach (preg_split("/(\r\n|\n|\r)/", $message) AS $string) {
if ((mb_strlen($string) + mb_strlen($messages[$i])) <= 4020) {
$messages[$i] .= $string."\n";
} else {
$i++;
$messages[$i] .= $string."\n";
}
}
foreach ($messages AS $message) {
$bot->sendMessage($chatId, $message, 'html');
//var_export([$user['id'], $chatId, $message]);
}
} else {
$bot->sendMessage($chatId, $message, 'html');
//var_export([$user['id'], $chatId, $message]);
}
} catch (Exception $e) {
echo 'Выброшено исключение: ', $e->getMessage(), "\n";
// file_put_content($_SERVER['DOCUMENT_ROOT']."/".telegramm_error.log.$e->getMessage(), )
}
}
}
}
$sql_t_u = "UPDATE users SET telegramm_date = '" . date('Y-m-d 14:00:00') . "' WHERE id = " . $r['id'];
mysql_query($sql_t_u);
}*/