Joywork/engine/classes/WebHookSend.php
2026-05-22 21:21:54 +03:00

685 lines
27 KiB
PHP
Raw 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
use Slim\Http\Request;
class WebHookSend {
private $db = null;
private $agency_id = 0;
private $user_id = 0;
private $client_id = 0;
private $req_id = 0;
private $object_id = 0;
private $employee_id = 0;
private $url = null;
private $metots = [1=>'get_ipoteka',
2=>'get_req',
3=>'update_status',
4=>'webhook_user'
];
private $metod = '';
private $status = '';
private $data = [];
private $section = '';
public function __construct($agency_id, $metod, $id, $section, $db = null, $status = '', $url = null, $data = []){
if($db){
$this->db = $db;
} else {
$pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
$this->db = $pdo;
}
$this->set_agency($agency_id);
$this->section = $section;
if($section == 'client'){
$this->set_client_id($id);
}
if($section == 'req'){
$this->set_req_id($id);
}
if($section == 'object'){
$this->set_object_id($id);
}
if($section == 'employee'){
$this->set_employee_id($id);
}
$this->set_status($status);
$this->set_metod($metod);
if($metod == 4 && !empty($url)){
$this->set_url($url);
} else
$this->get_url();
if(!empty($data)){
$this->data = $data;
if(isset($data['user_id'])){
$this->set_user_id($data['user_id']);
}
}
$this->web_hook_send();
//echo $agency_id;
}
/**
* Устоновка client_id
*/
public function set_client_id($client_id){
if((int)$client_id > 0){
$this->client_id = (int)$client_id;
} else {
// die("Установлен неверный клиент");
}
}
/**
* Установка req_id
*/
public function set_req_id($req_id){
$this->req_id = (int)$req_id;
}
/**
* Установка object_id
*/
public function set_object_id($object_id){
$this->object_id = (int)$object_id;
}
/**
* Установка employee_id
*/
public function set_employee_id($employee_id){
$this->employee_id = (int)$employee_id;
}
/**
* Установка agency_id
*/
public function set_agency($agency_id){
if((int)$agency_id > 0){
$this->agency_id = (int)$agency_id;
} else {
//die("Неврное агентство");
}
}
/**
* Установка user_id
*/
public function set_user_id($user_id){
$this->user_id = (int)$user_id;
}
/**
* Установка статуса
*/
public function set_status($status){
$this->status = $status;
}
/**
* Установка метода
*/
public function set_metod($number_metod){
if((int)$number_metod > 0 && isset($this->metots[(int)$number_metod])){
$this->metod = $this->metots[(int)$number_metod];
} else {
die("Установлен неверный метод!");
}
}
/**
* Установка url
*
*/
private function set_url($url){
$this->url = $url;
}
/**
* Получение url
*/
private function get_url(){
$sql = "SELECT * FROM web_hook_send WHERE agency_id = {$this->agency_id} AND metod = '{$this->metod}'";
$q = $this->db->query($sql, true);
if($this->db->num_rows($q) > 0){
$r = $this->db->fetch_assoc($q);
$this->url = $r['url'];
} else {
die("URL не найден!");
}
}
/**
* Сбор ипотеки
*/
private function get_ipoteka(){
$result = array();
if($this->client_id > 0){
$sql = "SELECT * FROM `ipoteka` WHERE client_id={$this->client_id}";
$q = $this->db->query($sql, true);
$r = $this->db->fetch_assoc($q);
$date = date('Y-m-d H:i:s');
$this->db->query("UPDATE ipoteka SET send_web_hook = 1, date_sent_web_hook = '{$date}' WHERE id={$r['id']}");
$r['metod'] = 'get_ipoteka';
$result = $r;
$sql_cl = "SELECT phone, fio, email, birthday FROM clients WHERE id = {$this->client_id}";
$q_cl = $this->db->query($sql_cl);
$cl = $this->db->fetch_assoc($q_cl);
$result['phone_clint'] = $cl['phone'];
$result['fio_clint'] = $cl['fio'];
$result['email_client'] = $cl['email'];
$result['birthday_client'] = $cl['birthday'];
$result['who_send'] = '';
if(isset($_SESSION['id']) && $_SESSION['id'] > 0){
$sql_user = "SELECT * FROM users WHERE id=".$_SESSION['id'];
$q_user = $this->db->query($sql_user);
$r_user = $this->db->fetch_assoc($q_user);
$who_send = trim($r_user['last_name'] . ' ' . $r_user['first_name'] . ' ' . $r_user['middle_name']);
$result['who_send'] = $who_send;
}
$content = json_encode($result, JSON_UNESCAPED_UNICODE);
// echo $content;
$this->send($content, 'MREAD6ECCXZ71D!A1OPEN');
} else {
// die("ClientId = 0");
}
}
/**
* Сбор заявки
*/
private function get_req(){
$result = array();
if($this->req_id > 0){
$is_send = true;
if($this->agency_id == 13154){
$is_send = false;
$sql_f = "SELECT * FROM requisition_data WHERE req_id = {$this->req_id}";
$q_f = $this->db->query($sql_f, true);
while($r_f = $this->db->fetch_assoc($q_f)){
if(($r_f['field_id'] == 142 || $r_f['field_id'] == 139) && $r_f['value'] == 1){
$is_send = true;
}
}
$sqlReq = "SELECT * FROM requisitions WHERE id = {$this->req_id}";
$qReq = $this->db->query($sqlReq);
$rReq = $this->db->fetch_assoc($qReq);
if($rReq['friend_client_id'] > 0 && ($rReq['confirm_recommendation'] == 1 || $rReq['confirm_recommendation'] == 2)){
$is_send = true;
$this->url = "https://kvsagency.ru/api/breadChangeLead";
}
}
if($is_send){
$req = new Requisitions(null, true) ;
if($this->agency_id == 13154 || $this->agency_id == 5238){
$rez = $req->get_req_id($this->req_id, false)['req'.$this->req_id];
$sql_cl = "SELECT phone, fio FROM clients WHERE id = {$rez['client_id']}";
$q_cl = $this->db->query($sql_cl);
$cl = $this->db->fetch_assoc($q_cl);
$result['id'] = $rez['id'];
$result['phone_client'] = $cl['phone'];
$result['description'] = $rez['description'];
$result['master_work'] = $rez['master_work_fio'];
$result['source_name'] = $rez['source_name'];
if($rReq['friend_client_id'] > 0 && ($rReq['confirm_recommendation'] == 1 || $rReq['confirm_recommendation'] == 2)){
if($rReq['confirm_recommendation'] == 1){
$result['status'] = 'confirmed';
} else if($rReq['confirm_recommendation'] == 2) {
$result['status'] = 'not confirmed';
}
$sqlFriend = "SELECT * FROM clients_friend WHERE id = {$rReq['friend_client_id']}";
$qFriend = $this->db->query($sqlFriend);
$rFriend = $this->db->fetch_assoc($qFriend);
$result['friendPhone'] = $rFriend['phone'];
}
} else {
$result = $req->get_req_id($this->req_id, false);
}
$result['who_send'] = '';
if(isset($_SESSION['id']) && $_SESSION['id'] > 0){
$sql_user = "SELECT * FROM users WHERE id=".$_SESSION['id'];
$q_user = $this->db->query($sql_user);
$r_user = $this->db->fetch_assoc($q_user);
$who_send = trim($r_user['last_name'] . ' ' . $r_user['first_name'] . ' ' . $r_user['middle_name']);
$result['who_send'] = $who_send;
}
$result['metod'] = 'get_req';
$content = json_encode($result, JSON_UNESCAPED_UNICODE);
//file_put_contents(__DIR__.'/log_hook.txt', date('d.m.Y H:i:s')." ".$content. "\n", FILE_APPEND);
$this->send($content, 'MREAD6ECCXZ71D!A1OPEN');
}
}
}
/**
* Извлеч временные старые данные для объекта
*/
private function get_object_old($object_id){
$object = array();
$sql = "SELECT * FROM webhook_temp_object WHERE object_id = {$object_id} order by id desc limit 1";
$q = $this->db->query($sql);
$r = $this->db->fetch_assoc($q);
$object['info'] = json_decode($r['info'], true);
$object['description'] = $r['description'];
$this->db->query("UPDATE webhook_temp_object SET is_check = 1 WHERE object_id = {$object_id}");
return $object;
}
/**
* Извлеч временные старые данные для сотрудника
*/
private function get_employee_old($employee_id){
$object = array();
$sql = "SELECT * FROM webhook_temp_employee WHERE employee_id = {$employee_id} order by id desc limit 1";
$q = $this->db->query($sql);
$r = $this->db->fetch_assoc($q);
$object = json_decode($r['info'], true);
$this->db->query("UPDATE webhook_temp_employee SET is_check = 1 WHERE employee_id = {$employee_id}");
return $object;
}
/**
* смена статуса
*/
private function update_status(){
$result = array();
$is_send = false;
if($this->req_id > 0){
$is_send = true;
$req = new Requisitions(null, true) ;
$rez = $req->get_req_id($this->req_id, false)['req'.$this->req_id];
$sql_cl = "SELECT phone, fio, email, birthday FROM clients WHERE id = {$rez['client_id']}";
$q_cl = $this->db->query($sql_cl);
$cl = $this->db->fetch_assoc($q_cl);
$result['id'] = $rez['id'];
$result['phone_client'] = $cl['phone'];
$result['fio_client'] = $cl['fio'];
$result['email_client'] = $cl['email'];
$result['description'] = $rez['description'];
$result['master_work'] = $rez['master_work_fio'];
$result['source_name'] = $rez['source_name'];
$result['status'] = 'create';
$result['who_send'] = '';
if($rez['deleted'] == 1){
$is_send = false;
}
if(!empty($this->status) && $this->status == 'close'){
if($rez['deleted'] == 1){
if($rez['friend_client_id'] > 0){
if($rez['confirm_recommendation'] == 1){
if($rez['confirm'] != 10){
$result['status'] = 'cancel';
$is_send = true;
} else {
$result['status'] = 'success';
$is_send = true;
}
} else if($rez['confirm_recommendation'] == 2) {
if($rez['confirm'] == 10){
$result['status'] = 'loyalty';
$is_send = true;
};
}
$sqlFriend = "SELECT * FROM clients_friend WHERE id = {$rez['friend_client_id']}";
$qFriend = $this->db->query($sqlFriend);
$rFriend = $this->db->fetch_assoc($qFriend);
$result['friendPhone'] = $rFriend['phone'];
} else {
$is_send = false;
}
} else {
$is_send = false;
}
}
if(isset($_SESSION['id']) && $_SESSION['id'] > 0){
$sql_user = "SELECT * FROM users WHERE id=".$_SESSION['id'];
$q_user = $this->db->query($sql_user);
$r_user = $this->db->fetch_assoc($q_user);
$who_send = trim($r_user['last_name'] . ' ' . $r_user['first_name'] . ' ' . $r_user['middle_name']);
$result['who_send'] = $who_send;
}
if($is_send){
$result['metod'] = 'update_status';
$content = json_encode($result, JSON_UNESCAPED_UNICODE);
//file_put_contents(__DIR__.'/log_hook.txt', date('d.m.Y H:i:s')." ".$content. " ".$this->url . "\n", FILE_APPEND);
$this->send($content, 'MREAD6ECCXZ71D!A1OPEN');
}
}
}
/**
* Отправка пользовательского хука
*/
private function webhook_user(){
$data = $this->data;
$result = array();
$is_send = true;
switch($this->section){
case 'req' : {
if($this->agency_id > 0 && $this->req_id > 0){
$result['event'] = 'step_changed';
$result['entity_type'] = ($this->section == 'req') ? 'requisition' : $this->section;
$result['funnel_id'] = $this->data['funnel_id'];
$sql_f = "SELECT * FROM funnel WHERE id = {$data['funnel_id']}";
$q_f = $this->db->query($sql_f);
$r_f = $this->db->fetch_assoc($q_f);
$result['funnel_name'] = $r_f['name'];
$sql_req = "SELECT * FROM requisitions WHERE id = {$this->req_id}";
$q_req = $this->db->query($sql_req);
$r_req = $this->db->fetch_assoc($q_req);
$result['req'] = array('id'=>$r_req['id'], 'name'=>$r_req['name']);
if($r_req['client_id'] > 0){
$sql_cl = "SELECT * FROM clients WHERE id = {$r_req['client_id']}";
$q_cl = $this->db->query($sql_cl);
$r_cl = $this->db->fetch_assoc($q_cl);
$result['client'] = array('id'=>$r_cl['id'], 'fio'=>$r_cl['fio'], 'phone'=>$r_cl['phone'], 'email'=>$r_cl['email']);
}
if($data['step_id'] > 0){
$result['old_step_id'] = $data['step_id'];
$sql_step = "SELECT id, name FROM funnel_steps WHERE id = {$data['step_id']}";
$q_step = $this->db->query($sql_step);
$r_step = $this->db->fetch_assoc($q_step);
$result['old_step_name'] = $r_step['name'];
}
if($data['new_step_id'] > 0){
$result['new_step_id'] = $data['new_step_id'];
$sql_step = "SELECT id, name FROM funnel_steps WHERE id = {$data['new_step_id']}";
$q_step = $this->db->query($sql_step);
$r_step = $this->db->fetch_assoc($q_step);
$result['new_step_name'] = $r_step['name'];
}
$result['timestamp'] = date('Y-m-d').'T'.date('H:i:s').'Z';
}
break;
}
case 'object': {
if($this->agency_id > 0 && $this->object_id > 0){
$result['event'] = $data['action'];
$result['timestamp'] = date('Y-m-d\TH:i:s\+03:00');
$result['object_id'] = $this->object_id;
$webHookIn = new WebHookIn(null, $this->agency_id);
$advert_buttons = array('add_to_yandex_feed'=>'free', 'add_to_avito_feed'=>'avito', 'add_to_cian_feed'=>'cian', 'add_to_domclick_feed'=>'domclick', 'add_to_emls_feed'=>'jcat', 'add_to_bn_feed'=>'yandex', 'all'=>'all');
$data = $this->data;
switch ($data['action']){
case 'object_create': {
$object = $webHookIn->get_object($this->object_id);
break;
}
case 'object_update': {
if(isset($data['new_who_work'])){
if($data['new_who_work'] > 0){
$object = $webHookIn->get_object_sales($data['new_who_work']);
}
} else {
$object_new = $webHookIn->get_object($this->object_id);
$temp_info = $this->get_object_old($this->object_id);
$object_old = $temp_info['info'];
$count_update = 0;
if(!empty($object_old) && !empty($object_new)){
foreach($object_new as $key => $value){
if(!isset($object_old[$key]) && !empty($object_new[$key]) && $key != 'description'){
$object[$key] = $object_new[$key];
if($key != 'last-update-date') $count_update++;
} else {
if(is_array($value)){
$temp_value = array_diff($object_new[$key], $object_old[$key]);
if(!empty($temp_value)){
$object[$key] = $temp_value;
if($key != 'last-update-date') $count_update++;
}
} else {
if($key == 'description'){
if(strcmp(trim($object_new[$key]), trim($temp_info['description'])) != 0){
$object[$key] = $object_new[$key];
if($key != 'last-update-date') $count_update++;
}
} else
if($object_new[$key] !== $object_old[$key]){
$object[$key] = $object_new[$key];
if($key != 'last-update-date') $count_update++;
}
}
}
}
}
if($count_update == 0) $is_send = false;
}
break;
}
case 'object_archive': {
$result['status'] = 'archived';
$result['archiver_user_id'] = $this->user_id;
$result['reason'] = $data['reason'];
break;
}
case 'object_restore': {
$result['restorer_user_id'] = $this->user_id;
$object = $webHookIn->get_object($this->object_id);
break;
}
case 'object_advertise': {
$result['status'] = 'advertised';
$result['advertiser_user_id'] = $this->user_id;
$result['advert_platform'] = $advert_buttons[$data['button']];
break;
}
case 'object_unadvertise': {
$result['status'] = 'hidden';
$result['unadvertiser_user_id'] = $this->user_id;
$result['reason'] = ($this->user_id > 0) ? 'manual_remove' : 'auto_remove';
$result['advert_platform'] = $advert_buttons[$data['button']];
break;
}
}
if(isset($object) && !empty($object))
$result['object'] = $object;
}
break;
}
case 'employee' : {
$webHookIn = new WebHookIn(null, $this->agency_id);
$result['event'] = $data['action'];
$result['timestamp'] = date('Y-m-d\TH:i:s\+03:00');
$result['employee_id'] = $this->employee_id;
switch($data['action']){
case 'employee_create' : {
$employee = $webHookIn->get_employee($this->employee_id);
$result['full_name'] = $employee['full_name'];
$result['phone'] = $employee['phone'];
$result['email'] = $employee['email'];
$result['manager_id'] = $employee['manager_id'];
break;
}
case 'employee_update' : {
$employee = $webHookIn->get_employee($this->employee_id);
$employee_old = $this->get_employee_old($this->employee_id);
$temp_arr = array_diff($employee, $employee_old);
if(empty($temp_arr)){
$is_send = false;
}
$result = array_merge($result, $temp_arr);
break;
}
case 'employee_block' : {
$result['status'] = "blocked";
break;
}
case 'employee_unblock' : {
$result['status'] = "active";
break;
}
case 'employee_delete' : {
$result['status'] = "deleted";
break;
}
}
break;
}
}
if(!empty($result) && $is_send){
//var_dump($result);
$content = json_encode($result, JSON_UNESCAPED_UNICODE);
// file_put_contents(__DIR__.'/log_hook.txt', date('d.m.Y H:i:s')." ".$content. "\n", FILE_APPEND);
$this->send($content);
}
}
/**
* Отправка вебхука
*/
private function web_hook_send(){
switch($this->metod){
case 'get_ipoteka':{
$this->get_ipoteka();
break;
}
case 'get_req':{
$this->get_req();
break;
}
case 'update_status':{
$this->update_status();
break;
}
case 'webhook_user':{
$this->webhook_user();
}
}
}
/**
* Логирование отправки
*/
private function logs($content, $result_curl, $result_info){
$user_id = null;
if(isset($this->user_id))
$user_id = (int)$this->user_id;
$data = $this->data;
$retry = 0;
if(isset($data['retry_id'])){
$retry_id = (int)$data['retry_id'];
}
$keys = array('event_type', 'entity_type', 'entity_id', 'url', 'payload_summary', 'response_status', 'retry_count', 'agency_id');
$values = array();
$content_arr = json_decode($content, true);
$values[] = $content_arr['event'];
$values[] = $this->section;
$values[] = ($this->section == 'object') ? $this->object_id : (($this->section == 'employee') ? $this->employee_id : 0);
$values[] = $this->url;
$values[] = $content;
$values[] = $result_info['http_code'];
$values[] = $retry;
$values[] = $this->agency_id;
if($result_info['http_code'] != '200'){
$keys[] = 'response_body';
$values[] = $result_curl;
}
if($user_id > 0){
$keys[] = 'initiator_user_id';
$values[] = $user_id;
}
if(isset($retry_id)){
$sql = "UPDATE webhook_logs SET retry_count = retry_count + 1, response_status = {$result_info['http_code']} WHERE id = $retry_id";
} else
$sql = "INSERT INTO webhook_logs (".implode(',', $keys).") VALUES ('".implode('\', \'', $values)."')";
//echo $sql."\n";
$this->db->query($sql);
}
/**
* Отправка кроном
*/
private function send($content, $api = null){
$ch = curl_init($this->url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
if(!empty($api))
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Bread-Api-Key: MREAD6ECCXZ71D!A1OPEN'));
else
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if($this->section == 'object' || $this->section == 'employee'){
$result_info = curl_getinfo($ch);
$this->logs($content, $result, $result_info);
}
//$content = json_encode($result, JSON_UNESCAPED_UNICODE);
//file_put_contents(__DIR__.'/log_hook.txt', date('d.m.Y H:i:s')." ".$content. " ".$this->url . "\n", FILE_APPEND);
curl_close($ch);
//echo $result;
}
}