query($sql); $max = new MaxClass(); $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, max_chat_id, max_user_id, max_date, gmtmsk, CONCAT(last_name, ' ', first_name, ' ', middle_name) as ufio FROM users WHERE max_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['max_date']) || ($r['max_date'] != date('Y-m-d 10:00:00'))){ $users_ids_10[] = $r['id']; } if(empty($r['max_date']) || ($r['max_date'] != date('Y-m-d 11:00:00'))){ $users_ids_11[] = $r; } if(empty($r['max_date']) || ($r['max_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.max != 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 = "О клиенте " . $type_phone . "\n"; if(!in_array($r_call['user_id'], $users_req_exception)) $text .= "Клиент " . $cfio . " тел. " . $phone . "\n"; $text .= "уже закреплен за сотрудником " . $r_call['wfio'] . "\n"; $text .= " (время создания " . date("d.m.Y H:i", strtotime($r_call['created_at'])) . ")\n"; } else if ($r_call['from_mes'] == 1) { $text = "О клиенте " . $type_phone . "\n"; if(!in_array($r_call['user_id'], $users_req_exception)) $text .= "Клиент " . $cfio . " тел. " . $phone . "\n"; $text .= "звонил повторно\n Звонок принял сотрудник " . $r_call['wfio'] . "\n"; $text .= " (время создания " . date("d.m.Y H:i", strtotime($r_call['created_at'])) . ")\n"; } $userId = $users[$r_call['user_id']]['max_user_id']; if($userId > 0 && !empty($text)){ $max->send_messages_to_user($userId, $text); } // if($sql_update_call != '') $sql_update_call .= "; "; $update_ids[] = $r_call['id']; } } if(!empty($update_ids)){ $sql_update_call = "UPDATE telephony_notifications SET max = 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.max != 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 = $max->get_clients_array($client_ids); } //Выборка заявок if(!empty($req_ids)){ $res_req = $max->get_reqs_array($req_ids); $reqs = $res_req['reqs']; $client_req_ids = $res_req['client_ids']; } //Выборка клиентов в заявках if(!empty($client_req_ids)){ $clients_req = $max->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 .= "Клиент: " . mask_fio_for_user_id($r_clr['fio'], $ev['user_id']) . " тел. " . mask_client_phone($r_clr['phone']) . "\n"; } else { $phoneClient .= "Клиент: " . $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); $_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 = "Звонок клиенту " . $_cl_fio . " тел. " . $phone; } else if ($ev['req_id'] > 0) { $title = "Звонок по заявке " . $_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Комментарий: " . $ev['comment']; } // $text .= "\n". date("H:i", strtotime($ev['create_date'])).""; break; } case 'meet': { if ($ev['client_id'] > 0) { $title = "Встреча клиенту " . $_cl_fio . " тел. " . $phone; } else if ($ev['req_id'] > 0) { $title = "Встреча по заявке " . $_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Адрес: " . $ev['address']; } if ($ev['comment']) { $text .= "\nКомментарий: " . $ev['comment']; } // $text .= "\n". date("H:i", strtotime($ev['create_date'])).""; break; } case 'show': { if ($ev['client_id'] > 0) { $title = "Показ клиенту " . $_cl_fio . " тел. " . $phone; } else if ($ev['req_id'] > 0) { $title = "Показ по заявке " . $_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Адрес: " . $ev['address']; } if ($ev['comment']) { $text .= "\nКомментарий: " . $ev['comment']; } // $text .= "\n". date("H:i", strtotime($ev['create_date'])).""; break; } case 'deal': { if ($ev['client_id'] > 0) { $title = "Сделка с клиентом " . $_cl_fio . " тел. " . $phone; } else if ($ev['req_id'] > 0) { $title = "Сделка по заявке " . $_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Сумма сделки: " . $ev['sum'] . " р."; } if ($ev['comment']) { $text .= "\nКомментарий: " . $ev['comment']; } // $text .= "\n". date("H:i", strtotime($ev['create_date'])).""; break; } case 'even': { $title = '' . $ev['name'] . ''; $text .= 'Мероприятие состоится ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date'])); if ($ev['client_id'] > 0) { if (!empty($r_cl['fio'])) { $text .= "\nКлиент " . $_cl_fio . " тел. " . $phone; } } else if ($ev['req_id'] > 0) { if (!empty($r_cl['fio'])) { $text .= "\nЗаявка " . $_cl_fio . " ID: ".$r_cl['id'] . " "; } if(!in_array($ev['user_id'], $users_req_exception)) $text .=$phoneClient; } if ($ev['comment']) { $text .= "\nКомментарий: " . str_replace('"', '',$ev['comment']); } // $text .= "\n". date("H:i", strtotime($ev['create_date'])).""; break; } } // echo $text; $text_o = "Напоминание (время создания " . date("d.m.Y H:i", strtotime($time_zone, strtotime($ev['create_date']))) . ")\n" . $title . " \n" . str_replace(['<i>', '</i>', '<br>', '<b>', '</b>'], ['', '', "\n", '', ''], htmlentities($text)); //echo $text_o."\n"; $userId = $users[$ev['user_id']]['max_user_id']; if($userId>0){ $keyboardArr = []; $attachments = []; $keyboardArr = [ [ [ "type" => "callback", 'text' => 'Отметить выполненной', 'payload' => serialize(array('action'=>10,'id'=>$ev['id'])) ] ] ]; if($ev['req_id'] > 0 || $ev['client_id'] > 0){ $keyboardArr[] = [ [ "type" => "callback", 'text' => 'Отметить выполненной и написать комментарий', 'payload' => serialize(array('action'=>11,'id'=>$ev['id'])) ], ]; } if(!empty($keyboardArr)){ $attachments = [ array( 'type'=>'inline_keyboard', 'payload' => array( 'buttons' => $keyboardArr ) ) ]; } $max->send_messages_to_user($userId, $text_o, $attachments); } $update_ids[] = $ev['id']; if(count($update_ids) == 100){ $sql_up = "UPDATE user_client_events SET max = 1 WHERE id in (".implode(',',$update_ids).")"; if(!$pdo->query($sql_up)){ file_put_contents($_SERVER['DOCUMENT_ROOT']."/max_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 max = 1 WHERE id in (".implode(',',$update_ids).")"; if(!$pdo->query($sql_up)){ file_put_contents($_SERVER['DOCUMENT_ROOT']."/max_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.max = 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 = $max->get_clients_array($client_ids); } //Выборка заявок if(!empty($req_ids)){ $res_req = $max->get_reqs_array($req_ids); $reqs = $res_req['reqs']; $client_req_ids = $res_req['client_ids']; } //Выборка клиентов в заявках if(!empty($client_req_ids)){ $clients_req = $max->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 .= "Клиент: " . 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 .= "Клиент: " . $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 = "Звонок клиенту " . $_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Комментарий: " . $ev['comment']; } } else if($ev['req_id'] > 0){ $title = "Звонок по заявке " . $_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Комментарий: " . $ev['comment']; } } break; } } // echo $text; $text_o = "Напоминание (время создания " . date("d.m.Y H:i", strtotime($time_zone, strtotime($ev['create_date']))) . ")\n" . $title . " \n" . str_replace(['<i>', '</i>', '<br>', '<b>', '</b>'], ['', '', "\n", '', ''], htmlentities($text)); //echo $text_o."\n"; $userId = $users[$ev['user_id']]['max_user_id']; if($userId>0){ $max->send_messages_to_user($userId, $text_o); } $update_ids[] = $ev['id']; if(count($update_ids) == 100){ $pdo->query("UPDATE user_client_events SET max = 2 WHERE id in (".implode(',',$update_ids).")"); $update_ids = array(); } } if(!empty($update_ids)){ $pdo->query("UPDATE user_client_events SET max = 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.max = 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)) { $title = ''; $text = ''; $schedule_date = date("d.m.Y", strtotime($ev['schedule_date'])); list($d, $m, $y) = explode(".", $schedule_date); $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); } switch ($ev['type']) { case 'call': { $title = "Звонок клиенту " . $ev['fio'] . " тел. " . $phone; $text .= $d . " " . getRusMonth($m) . " " . $y . " в " . date("H:i", strtotime($ev['schedule_date'])); if ($ev['comment']) { $text .= "\nКомментарий: " . $ev['comment']; } // $text .= "\n". date("H:i", strtotime($ev['create_date'])).""; break; } case 'meet': { $title = 'Встреча с клиентом ' . $ev['fio'] . ' тел. ' . $phone; $text .= 'Встреча будет ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date'])); if ($ev['address']) { $text .= "\nАдрес: " . $ev['address']; } if ($ev['comment']) { $text .= "\nКомментарий: " . $ev['comment']; } // $text .= "\n". date("H:i", strtotime($ev['create_date'])).""; break; } case 'show': { $title = 'Показ для клиента ' . $ev['fio'] . ' тел. ' . $phone; $text .= 'Показ будет ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date'])); if ($ev['address']) { $text .= "\nАдрес: " . $ev['address']; } if ($ev['comment']) { $text .= "\nКомментарий: " . $ev['comment']; } // $text .= "\n". date("H:i", strtotime($ev['create_date'])).""; break; } case 'deal': { $title = 'Сделка с клиентом ' . $ev['fio'] . ' тел. ' . $phone; $text .= 'Сделка будет ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date'])); if ($ev['sum']) { $text .= "\nСумма сделки: " . $ev['sum'] . " р."; } if ($ev['comment']) { $text .= "\nКомментарий: " . $ev['comment']; } // $text .= "\n". date("H:i", strtotime($ev['create_date'])).""; break; } } // // echo $text; //$text = htmlentities($text); $text_o = "Напоминание (время создания " . date("d.m.Y H:i", strtotime($time_zone, strtotime($ev['create_date']))) . ")\n" . $title . " \n" . str_replace(['<i>', '</i>', '<br>'], ['', '', "\n"], htmlentities($text)); $userId = $users[$ev['user_id']]['max_user_id']; if($userId>0){ $max->send_messages_to_user($userId,$text_o); } $update_ids[] = $ev['id']; } if(!empty($update_ids)){ $pdo->query("UPDATE user_client_jw_events SET max = 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.max = 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']; } // Маска телефона/ФИО собственника объекта для hide-юзера if ($_hideEv) { $phone = mask_client_phone($phone); $sobstv = mask_fio_for_user_id($sobstv, $ev['user_id']); } switch ($ev['type']) { case 'call': { $title = 'Звонок по объекту ' . $ev['nazv']; $text .= $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date'])); $text .= "\n тел. " . $phone . ", ответственный: " . $sobstv; if ($ev['adres']) { $text .= "\nАдрес объекта: " . $ev['adres']; } if ($ev['comment']) { $text .= "\nКомментарий: " . $ev['comment']; } if ($ev['sub_comment']) { $text .= "\nКомментарий к задаче: " . $ev['sub_comment'] . " (" .$ev['sub_comment_author'] . ")"; } // $text .= "\n". date("H:i", strtotime($ev['create_date'])).""; break; } case 'meet': { $title = 'Встреча по объекту ' . $ev['nazv']; $text .= 'Встреча будет ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date'])); $text .= "\n тел. " . $phone . ", ответственный: " . $sobstv; if ($ev['address']) { $text .= "\nАдрес: " . $ev['address']; } if ($ev['adres']) { $text .= "\nАдрес объекта: " . $ev['adres']; } if ($ev['comment']) { $text .= "\nКомментарий: " . $ev['comment']; } if ($ev['sub_comment']) { $text .= "\nКомментарий к задаче: " . $ev['sub_comment'] . " (" .$ev['sub_comment_author'] . ")"; } // $text .= "\n". date("H:i", strtotime($ev['create_date'])).""; break; } case 'show': { $title = 'Показ по объекту ' . $ev['nazv']; $text .= 'Показ будет ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date'])); $text .= "\n тел. " . $phone . ", ответственный: " . $sobstv; if ($ev['address']) { $text .= "\nАдрес: " . $ev['address']; } if ($ev['adres']) { $text .= "\nАдрес объекта: " . $ev['adres']; } if ($ev['comment']) { $text .= "\nКомментарий: " . $ev['comment']; } if ($ev['sub_comment']) { $text .= "\nКомментарий к задаче: " . $ev['sub_comment'] . " (" .$ev['sub_comment_author'] . ")"; } // $text .= "\n". date("H:i", strtotime($ev['create_date'])).""; break; } case 'deal': { $title = 'Сделка по объекту ' . $ev['nazv']; $text .= 'Сделка будет ' . $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($ev['schedule_date'])); $text .= "\n тел. " . $phone . ", ответственный: " . $sobstv; if ($ev['sum']) { $text .= "\nСумма сделки: " . $ev['sum'] . " р."; } if ($ev['adres']) { $text .= "\nАдрес объекта: " . $ev['adres']; } if ($ev['comment']) { $text .= "\nКомментарий: " . $ev['comment']; } if ($ev['sub_comment']) { $text .= "\nКомментарий к задаче: " . $ev['sub_comment'] . " (" .$ev['sub_comment_author'] . ")"; } //$text .= "\n". date("H:i", strtotime($ev['create_date'])).""; break; } case 'moderation': { $title = 'На модерацию отправлен объект ' . $ev['nazv']; $text .= 'ID '.$ev['object_id']."."; if ($ev['adres']) { $text .= "\nАдрес объекта: " . $ev['adres']; } $text .= "\n тел. " . $phone . ", ответственный: " . $sobstv; if ($ev['comment']) { $text .= "\nКомментарий: " . $ev['comment']; } if ($ev['sub_comment']) { $text .= "\nКомментарий к задаче: " . $ev['sub_comment'] . " (" .$ev['sub_comment_author'] . ")"; } //$text .= "\n". date("H:i", strtotime($ev['create_date'])).""; break; } case 'even': { $title = 'Задача по объекту ' . $ev['nazv']; $text .= 'ID '.$ev['object_id']."."; if ($ev['adres']) { $text .= "\nАдрес объекта: " . $ev['adres']; } $text .= "\n тел. " . $phone . ", ответственный: " . $sobstv; if ($ev['comment']) { $text .= "\nКомментарий: " . $ev['comment']; } if ($ev['sub_comment']) { $text .= "\nКомментарий к задаче: " . $ev['sub_comment'] . " (" .$ev['sub_comment_author'] . ")"; } //$text .= "\n". date("H:i", strtotime($ev['create_date'])).""; break; } /*case 'comment': { if ($ev['comment']) $text .= $ev['comment']; break; }*/ } $text_o = "Напоминание (время создания " . date("d.m.Y H:i", strtotime($time_zone, strtotime($ev['create_date']))) . ")\n" . $title . " \n" . str_replace(['<i>', '</i>', '<br>'], ['', '', "\n"], htmlentities($text)); // echo $text_o."\n"; $userId = $users[$ev['user_id']]['max_user_id']; if($userId>0){ $keyboardArr = []; $attachments = []; $keyboardArr = [ [ [ "type" => "callback", 'text' => 'Отметить выполненной', 'payload' => serialize(array('action'=>13,'id'=>$ev['id'])) ] ], [ [ "type" => "callback", 'text' => 'Отметить выполненной и написать комментарий', 'payload' => serialize(array('action'=>14,'id'=>$ev['id'])) ], ] ]; if(!empty($keyboardArr)){ $attachments = [ array( 'type'=>'inline_keyboard', 'payload' => array( 'buttons' => $keyboardArr ) ) ]; } $max->send_messages_to_user($userId, $text_o, $attachments); } $update_ids[] = $ev['id']; if(count($update_ids) == 100){ $pdo->query("UPDATE user_object_events SET max = 1 WHERE id in (".implode(',',$update_ids).")"); $update_ids = array(); } } if(!empty($update_ids)){ $sql_up = "UPDATE user_object_events SET max = 1 WHERE id in (".implode(',',$update_ids).")"; if(!$pdo->query($sql_up)){ file_put_contents($_SERVER['DOCUMENT_ROOT']."/max_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_max` = 0 AND (req_id>0 or client_id>0) AND date > '2026-03-25 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).'
'; 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_max = 1 WHERE id in (".implode(',', $update_ids).")"; if(!mysql_query($sql_up)){ file_put_contents($_SERVER['DOCUMENT_ROOT']."/max_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_max = 1 WHERE id in (".implode(',', $update_ids).")"; if(!mysql_query($sql_up)){ file_put_contents($_SERVER['DOCUMENT_ROOT']."/max_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 = $max->get_clients_array($client_ids); } //Выборка заявок if(!empty($req_ids)){ $res_req = $max->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 = $max->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 = "Вам передают клиента (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")\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 = "Вам передают заявку (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")\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 .= " «".$name_funel."»\n"; } $text_o = "Клиент взят в работу в смежной воронке \n"; $text_o .= $text_funnel; $text_o .= " ID: ".$r_ec['client_id']." (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")\n"; if($r_ec['client_id'] == 0 && $r_ec['req_id'] > 0){ $text_o = "Заявка ID: ".$r_ec['req_id']." (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")\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лиент: ID ".$r_cl['client_id']." ".$_clnFio.""; 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 = "Вам передают заявку (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")\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 = "Добавлен клиент ID: ".$r_ec['client_id']." (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")\n"; if($r_ec['client_id'] == 0 && $r_ec['req_id'] > 0){ $text_o = "Добавлена заявка ID: ".$r_ec['req_id']." (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")\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 .= " по клиенту: ID ".$r_cl['client_id']." ".$_clnFio.""; 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 = "Добавлен клиент ID: ".$r_ec['client_id']." (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")\n"; if($r_ec['client_id'] == 0 && $r_ec['req_id'] > 0){ $text_o = "Заявки объединены: "; } if(!empty($r_ec['dop_text'])){ $dop_tex_o2 = "\n".str_replace("
", "\n", $r_ec['dop_text'])."\n"; $text_o .= $dop_tex_o2; } } if ($r_ec['event'] == 'transmitted_parallel' && $r_ec['read'] == 0) { $text_o = "Вас приглашают к совместной работе (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")\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 = "Поступила заявка по которой вы назначены партнером (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")\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 = "Поступил клиент по которому вы назначены партнером (время создания " . date("d.m.Y H:i", strtotime($r_ec['date'])) . ")\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 .= " по клиенту: ID ".$r_cl['client_id']." ".$_clnFio.""; 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.'
'; 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 .= "" . $_clFio . ""; 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(['<i>', '</i>', '<br>', '<b>', '</b>', '«', '»'], ['', '', "\n", '', '', '', ''], htmlentities($text_o)); //echo $text_o."\n\n"; $userId = $users[$r_ec['from_id']]['max_user_id']; $attachments = []; if($userId>0){ if($r_ec['event'] == 'transmitted' || $r_ec['event'] == 'transmitted_parallel'){ $attachments = [ array( 'type'=>'inline_keyboard', 'payload' => array( 'buttons' => [ [ [ "type" => "callback", 'text' => 'Принять в работу', 'payload' => serialize(array('action'=>16,'id'=>$r_ec['id'])) ] ] ] ) ) ]; } $res = $max->send_messages_to_user($userId, $text_o, $attachments); } // 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_max=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_max = 1 WHERE id in (".implode(',',$update_ids).")"; if(!mysql_query($sql_up)){ file_put_contents($_SERVER['DOCUMENT_ROOT']."/max_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_max = 1 WHERE id in (".implode(',',$update_ids).")"; //echo $sql_up."\n"; if(!mysql_query($sql_up)){ file_put_contents($_SERVER['DOCUMENT_ROOT']."/max_error_sql.txt", date('d.m.y H:i:s').' '.$sql_up.' '.mysql_error()."\n", FILE_APPEND); } } 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 = []; $r_obj = $objects[$r_object_send['object_id']]; $first_line = $post . "\nпередал вам объект ID ".$r_obj['id']." «" . $r_obj['nazv'] . "»"; if ($clientsNum > 0) { if ($clientsNum > 1) { $first_line = $first_line . "\n и клиентов " . $clientsString.""; } else { $first_line = $first_line . "\n и клиента " . $clientsString.""; } } $first_line .="\n (время создания " . date("d.m.Y H:i", strtotime($r_object_send['create_date'])) . ")"; //echo $first_line."\n"; $userId = $users[$r_object_send['new_user_id']]['max_user_id']; if($userId>0){ $attachments = [ array( 'type'=>'inline_keyboard', 'payload' => array( 'buttons' => [ [ [ "type" => "callback", 'text' => 'Принять в работу', 'payload' => serialize(array('action'=>17,'id'=>$r_object_send['id'])) ] ] ] ) ) ]; $max->send_messages_to_user($userId, $first_line, $attachments); } } 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 send_max = 0"; $q_req_notice = $pdo->query($sql_req_notice); while ($notice = $pdo->fetch_assoc($q_req_notice)) { $userId = $users[$notice['user_id']]['max_user_id']; if($userId>0){ $max->send_messages_to_user($userId, $notice['text']); } $update_ids[] = $notice['id']; } if(!empty($update_ids)){ $sql_req_notice_u = "UPDATE discharge_user_notice SET send_max = 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_max = 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 = "".$em."\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 .= "Необходимо проверить и выставить данный объект в рекламу"; } $userId = $users[$r_ad['manager_id']]['max_user_id']; if($userId>0){ $max->send_messages_to_user($userId, $text_o); } $update_ids[] = $r_ad['id']; } else { $update_ids[] = $r_ad['id']; } } if(!empty($update_ids)){ $sql_req_notice_u = "UPDATE object_ad SET send_max = 1 WHERE id in (".implode(',',$update_ids).")"; $pdo->query($sql_req_notice_u); } echo 'Время выполнения скрипта 10: '.round(microtime(true) - $start9, 4)." сек.\n"; $start10 = microtime(true); //Уведомления о закрытии этапа $update_ids = array(); $sql_st = "SELECT * FROM `step_notify_closure` WHERE send_max = 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(['<i>', '</i>', '<br>', '<b>', '</b>', '«', '»'], ['', '', "\n", '', '', '', ''],$r_st['text'])); $userId = $users[$r_st['user_id']]['max_user_id']; if($userId>0){ $max->send_messages_to_user($userId, $text); } $update_ids[] = $r_st['id']; } if(!empty($update_ids)){ $sql_req_notice_u = "UPDATE step_notify_closure SET send_max = 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 = "Сегодня День рождения\n"; $_bFio = $_hideB ? mask_fio_for_user_id($r_b['fio'], $r_b['who_work']) : $r_b['fio']; $text_o .= "у клиента «" . $_bFio . "»\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(['<i>', '</i>','<br>'],['','',"\n"], htmlentities($text_o)); $userId = $users[$r_b['who_work']]['max_user_id']; if($userId>0){ $max->send_messages_to_user($userId, $text_o); } } $sql_t_u = "UPDATE users SET max_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 = "Завтра День рождения\n"; $text_o .= "у " . $fio . ", сотрудника Вашего агентства.\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"; } $userId = $users[$user['id']]['max_user_id']; if($userId>0){ // echo $text_o."\n"; $max->send_messages_to_user($userId, $text_o); ////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 max_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 = "Сегодня День рождения\n"; $text_o .= "у сотрудника «" . $r_b['name'] . "» партнёра «" . $r_b['partner_name'] . (!empty($r_b['partner_resident']) ? ", " . $r_b['partner_resident'] : "") . "»\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; } $userId = $users[$user['id']]['max_user_id']; if($userId>0){ $max->send_messages_to_user($userId, $text_o); } } } } $sql_t_u = "UPDATE users SET max_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).' сек.'; /*-----------------------------------------------------------------------------------------------------------------*/