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

1338 lines
60 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
class WebHookIn {
private $db = null;
private $agency_id = 0;
private $user_id = 0;
private $users = array();
private $limit = 20;
private $page = 1;
private $allPages = 0;
public function __construct($db = null, $agency_id = null){
if($db){
$this->db = $db;
} else {
$pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
$this->db = $pdo;
}
if($agency_id > 0){
$this->set_agency_id($agency_id);
}
}
public function set_users($users){
$this->users = $users;
}
public function set_agency_id($agency_id){
$this->agency_id = $agency_id;
}
public function set_user_id($user_id){
$this->user_id = $user_id;
}
public function set_page($page){
$this->page = $page;
}
public function check_is_req($who_work, $source_id, $client_id){
$id_req = null;
$sql = "SELECT * FROM requisitions WHERE client_id={$client_id} AND who_work = {$who_work} AND source = {$source_id} AND deleted=0 AND cancel = 0";
$q = $this->db->query($sql, true);
if($this->db->num_rows($q) > 0){
$r = $this->db->fetch_assoc($q);
$id_req = (int)$r['id'];
}
return $id_req;
}
public function getAllUserAgency($agency_id){
$usersIds = array();
$sql_u = "SELECT * 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_u = $this->db->query($sql_u);
while($r_u = $this->db->fetch_assoc($q_u)){
$usersIds[] = (int)$r_u['id'];
}
$sql_u = "SELECT * FROM users_delete WHERE user_id in (select user_id from users_delete where user_id=$agency_id or id_manager=$agency_id or id_manager in
(select user_id from users_delete where id_manager=$agency_id or id_manager in
(select user_id from users_delete where id_manager=$agency_id)))";
$q_u = $this->db->query($sql_u);
while($r_u = $this->db->fetch_assoc($q_u)){
$usersIds[] = (int)$r_u['user_id'];
}
return $usersIds;
}
public function set_enable_webhook($enable_webhook){
if($this->agency_id > 0){
$sql = "UPDATE users SET enable_webhooks = {$enable_webhook} WHERE id = {$this->agency_id}";
$q = $this->db->query($sql);
}
return 1;
}
public function get_enable_webhook(){
$result = 0;
if($this->agency_id > 0){
$sql = "SELECT * FROM users WHERE id = {$this->agency_id}";
$q = $this->db->query($sql);
$r = $this->db->fetch_assoc($q);
if($r['enable_webhooks']){
$result = (int)$r['enable_webhooks'];
}
}
return $result;
}
/**
* Получение списка настроек вебхуков
*/
public function get_webhooks_list(){
$result = array();
$result['total'] = 0;
if($this->agency_id > 0){
$limitSql = "";
$where = '';
$sql_total = "SELECT COUNT(*) as total FROM webhook_configs
WHERE agency_id = {$this->agency_id} {$where}";
$q_total = $this->db->query($sql_total);
$r_total = $this->db->fetch_row($q_total);
if($r_total[0] > 0) $result['total'] = (int)$r_total[0];
if($this->page > 0){
$limitSql = ' limit '.($this->page-1)*$this->limit.', '.$this->limit;
}
$sql = "SELECT * FROM webhook_configs
WHERE agency_id = {$this->agency_id} {$where} {$limitSql}";
$q = $this->db->query($sql);
$arrAction = array('close_step'=>'Закрытие этапа',
'transition_step'=>'Переход на этапа',
'object_create'=>'Добавление нового объекта',
'object_update'=>'Редактирование объекта',
'object_advertise'=>'Выставление объекта в рекламу',
'object_unadvertise'=>'Снятие с рекламы',
'object_archive'=>'Отправка в архив',
'object_restore'=>'Возврат из архива',
'employee_create'=>'Добавление нового сотрудника',
'employee_update' => 'Изменение сотрудника',
'employee_block'=>'Блокировка сотрудника',
'employee_unblock'=>'Снятие блокировки с сотрудника',
'employee_delete'=>'Удаление сотрудника'
);
$arrSection = array('req'=>'Заявки', 'client'=>'Клиенты', 'object'=>'Объекты', 'employee'=>'Сотрудники');
while($r = $this->db->fetch_assoc($q)){
$r['action_name'] = $arrAction[$r['action']];
$r['section_name'] = $arrSection[$r['section']];
$list[] = $r;
}
}
$result['allPages'] = ceil($result['total']/$this->limit);
$result['list'] = isset($list) ? $list : [];
return $result;
}
/**
* Сохранение настроек вебхука
*/
public function save_webhook($item){
$errors = array();
$result = array();
$event = "add";
if($this->agency_id > 0 && $this->user_id > 0){
//Проверка url
if(!empty($item->url)){
$sql = "SELECT * FROM webhook_configs WHERE url = '{$item->url}' AND agency_id != {$this->agency_id}";
$q = $this->db->query($sql);
if($this->db->num_rows($q) > 0){
$errors['url'] = "Этот url использует другой пользователь";
}
}
if(empty($errors)){
$steps = null;
if(!empty($item->steps)){
$steps = json_encode($item->steps);
}
if($item->id > 0){
$sql_up = "UPDATE webhook_configs SET
url='{$item->url}',
user_id={$this->user_id},
name='{$item->name}',
section='{$item->section}',
action='{$item->action}',
funnel_id='{$item->funnel_id}',
is_active='{$item->is_active}'";
if(!empty($steps)){
$sql_up .= ", steps='{$steps}'";
}
$sql_up .= "WHERE id = {$item->id}";
$this->db->query($sql_up);
} else {
$sql_in = "INSERT INTO webhook_configs (`agency_id`, `user_id`, `url`, `name`, `section`, `action`, `funnel_id`, `is_active`";
if(!empty($steps)){
$sql_in .= ", `steps`";
}
$sql_in .= ")";
$sql_in .= " VALUES ({$this->agency_id}, {$this->user_id}, '{$item->url}', '{$item->name}', '{$item->section}', '{$item->action}', '{$item->funnel_id}', '{$item->is_active}'";
if(!empty($steps)){
$sql_in .= ", '{$steps}'";
}
$sql_in .= ")";
$this->db->query($sql_in);
}
}
}
if(!empty($errors)){
return array('result'=>'error', 'errors'=>$errors);
}
return array('result'=>'success');
}
/**
* Удаление вебхука
*/
public function delete_webhook($delete_id){
$errors = array();
if($this->agency_id > 0){
$sql_del = "DELETE FROM webhook_configs WHERE id = {$delete_id}";
if(!$this->db->query($sql_del)){
$errors[] = $this->db->error();
}
}
if(!empty($errors)){
return array('result'=>'error', 'errors'=>$errors);
}
return array('result'=>'success');
}
/**
* Проверка отправки
*/
public function check_send($data){
/*echo json_encode($data, JSON_UNESCAPED_UNICODE);
var_dump($this->agency_id);*/
//file_put_contents(__DIR__.'/log_hook_test.txt', date('d.m.Y H:i:s')." ".json_encode($data, JSON_UNESCAPED_UNICODE). "\n", FILE_APPEND);
if($this->agency_id > 0){
$sql = "SELECT enable_webhooks FROM users WHERE id = {$this->agency_id}";
$q = $this->db->query($sql);
$r = $this->db->fetch_assoc($q);
if($r['enable_webhooks'] > 0){
if($data['action'] == 'close_step'){
$sql = "SELECT * FROM webhook_configs WHERE agency_id = {$this->agency_id} AND is_active = 1 AND funnel_id='{$data['funnel_id']}' AND action in ('close_step', 'transition_step') AND section='{$data['section']}'";
// file_put_contents(__DIR__.'/log_hook_test.txt', date('d.m.Y H:i:s')." ".$sql. "\n", FILE_APPEND);
$q = $this->db->query($sql);
while($r = $this->db->fetch_assoc($q)){
if($r['action'] == 'close_step'){
$steps = json_decode($r['steps'], true);
if(!empty($steps) && in_array($data['step_id'], $steps)){
// file_put_contents(__DIR__.'/log_hook_test.txt', date('d.m.Y H:i:s')." ".$data['req_id']. "\n", FILE_APPEND);
$w = new WebHookSend($this->agency_id, 4, $data['req_id'], $r['section'], null, 'step_changed', $r['url'], $data);
}
}
if($r['action'] == 'transition_step'){
$steps = json_decode($r['steps'], true);
if(!empty($steps) && in_array($data['new_step_id'], $steps)){
// file_put_contents(__DIR__.'/log_hook_test.txt', date('d.m.Y H:i:s')." ".$data['req_id']. "\n", FILE_APPEND);
$w = new WebHookSend($this->agency_id, 4, $data['req_id'], $r['section'], null, 'step_changed', $r['url'], $data);
}
}
}
} else if (in_array($data['action'], ['object_create', 'object_update', 'object_archive', 'object_restore', 'object_advertise', 'object_unadvertise'])){
$sql = "SELECT * FROM webhook_configs WHERE agency_id = {$this->agency_id} AND is_active = 1
AND action='{$data['action']}' AND section='{$data['section']}'";
$q = $this->db->query($sql);
while($r = $this->db->fetch_assoc($q)){
$w = new WebHookSend($this->agency_id, 4, $data['object_id'], $r['section'], null, $data['action'], $r['url'], $data);
}
} else if (in_array($data['action'], ['employee_create', 'employee_update', 'employee_block', 'employee_unblock', 'employee_delete'])){
$sql = "SELECT * FROM webhook_configs WHERE agency_id = {$this->agency_id} AND is_active = 1
AND action='{$data['action']}' AND section='{$data['section']}'";
//echo $sql;
$q = $this->db->query($sql);
while($r = $this->db->fetch_assoc($q)){
$w = new WebHookSend($this->agency_id, 4, $data['employee_id'], $r['section'], null, $data['action'], $r['url'], $data);
}
}
}
}
}
/**
* Проверка отправляется ли хук агентством при определенном дейсвии
*/
public function check_hook($action, $section){
$result = false;
$sql = "SELECT enable_webhooks FROM users WHERE id = {$this->agency_id}";
$q = $this->db->query($sql);
$r = $this->db->fetch_assoc($q);
if($r['enable_webhooks'] > 0){
$sql = "SELECT * FROM webhook_configs WHERE agency_id = {$this->agency_id} AND is_active = 1
AND action = '{$action}' AND section='{$section}'";
$q = $this->db->query($sql);
if($this->db->num_rows($q) > 0){
$result = true;
}
}
return $result;
}
/**
* Получение объекта
*/
public function get_object($object_id){
$object = array();
if($object_id > 0){
$sql = "SELECT * FROM objects WHERE id = {$object_id}";
$q = $this->db->query($sql);
$object = $this->db->fetch_assoc($q);
$sqlAddInfo = "SELECT apartments, video_url, balcony, loggias, separate_wcs, combined_wcs, passenger_lifts, cargo_lifts, house_category, flat_number, garage_type_id, boks_vid_id,
commerc_site, building_area, ceiling_height, window_view, free_plan, renovation, commer_condition, commerc_building_class_id, commerc_building_type_id, highway_id FROM objects_additional_information WHERE object_id=$object[id]";
$rezAddInfo = $this->db->query($sqlAddInfo);
if ($this->db->num_rows($rezAddInfo) > 0) {
$objAddInfo =$this->db->fetch_assoc($rezAddInfo);
//дополнительные поля
$object['apartments'] = $objAddInfo['apartments'];
$object['video_url'] = $objAddInfo['video_url'];
$object['balcony'] = $objAddInfo['balcony'];
$object['loggias'] = $objAddInfo['loggias'];
$object['separate_wcs'] = $objAddInfo['separate_wcs'];
$object['combined_wcs'] = $objAddInfo['combined_wcs'];
$object['passenger_lifts'] = $objAddInfo['passenger_lifts'];
$object['cargo_lifts'] = $objAddInfo['cargo_lifts'];
$object['house_category'] = $objAddInfo['house_category'];
$object['flat_number'] = $objAddInfo['flat_number'];
$object['commerc_site'] = $objAddInfo['commerc_site'];
$object['building_area'] = $objAddInfo['building_area'];
$object['garage_type_id'] = $objAddInfo['garage_type_id'];
$object['boks_vid_id'] = $objAddInfo['boks_vid_id'];
$object['free_plan'] = $objAddInfo['free_plan'];
$object['renovation'] = $objAddInfo['renovation'];
$object['commer_condition'] = $objAddInfo['commer_condition'];
$object['commerc_building_class_id'] = $objAddInfo['commerc_building_class_id'];
$object['commerc_building_type_id'] = $objAddInfo['commerc_building_type_id'];
$object['highway_id'] = $objAddInfo['highway_id'];
$object['ceiling_height'] = $objAddInfo['ceiling_height'];
$object['window_view'] = $objAddInfo['window_view'];
} else {
$object['apartments'] = 0;
$object['video_url'] = null;
$object['balcony'] = null;
$object['loggias'] = null;
$object['separate_wcs'] = null;
$object['combined_wcs'] = null;
$object['passenger_lifts'] = null;
$object['cargo_lifts'] = null;
$object['house_category'] = null;
$object['flat_number'] = null;
$object['commerc_site'] = null;
$object['building_area'] = null;
$object['garage_type_id'] = null;
$object['boks_vid_id'] = null;
$object['free_plan'] = null;
$object['renovation'] = null;
$object['commer_condition'] = null;
$object['commerc_building_class_id'] = null;
$object['commerc_building_type_id'] = null;
$object['highway_id'] = 0;
$object['ceiling_height'] = 0;
$object['window_view'] = null;
}
$sqlPhotoInfo = "SELECT oop.sort_order, p.photo FROM objects_object_photo oop, object_photo p WHERE p.id = oop.object_photo_id AND oop.object_id = $object[id] ORDER BY oop.sort_order";
$rezPhotoInfo = $this->db->query($sqlPhotoInfo);
if ($this->db->num_rows($rezPhotoInfo) > 0) {
while ($photoInfo = $this->db->fetch_assoc($rezPhotoInfo)) {
$object['photo' . $photoInfo['sort_order']] = $photoInfo['photo'];
}
}
$plan = '';
$sqlP = "SELECT * FROM objects_plan WHERE object_id = $object[id]";
$rez_plan = $this->db->query($sqlP);
if($this->db->num_rows($rez_plan) > 0){
$obj_plan =$this->db->fetch_assoc($rez_plan);
if($obj_plan['img_plan'] != ''){
if (stripos($obj_plan['img_plan'], "http://") === false && stripos($obj_plan['img_plan'], "https://") === false) {
$obj_plan['img_plan'] = "https://joywork.ru/photos/" . $obj_plan['img_plan'];
}
$obj_plan['img_plan'] = str_replace("http://c01.joywork.ru", "https://c01.joywork.ru", $obj_plan['img_plan']);
$plan = $obj_plan['img_plan'];
}
}
$forPlan = true;
$images = array();
for ($k = 1; $k <= 40; $k++) {
if (isset($object['photo' . $k]) && $object['photo' . $k]) {
$srcFile = null;
if (stripos($object['photo' . $k], "http://") === false && stripos($object['photo'.$k],"https://") === false) {
$srcFile = $ph_url = "https://joywork.ru/photos/" . $object['photo' . $k];
} else {
$srcFile = str_replace("http://c01.joywork.ru", "https://c01.joywork.ru", $object['photo' . $k]);
}
if ($srcFile != null) {
$images[] = $srcFile;
if ($forPlan && $plan != '') {
$forPlan = false;
$images[] = $plan;
}
}
}
}
if ($forPlan && $plan != '') {
$images[] = $plan;
}
$sqlSaleInfo = "SELECT * FROM sale_objects WHERE object_id=$object[id]";
$rezSaleInfo = $this->db->query($sqlSaleInfo);
if ($this->db->num_rows($rezSaleInfo) > 0) {
$objSaleInfo = $this->db->fetch_assoc($rezSaleInfo);
$object['house_type'] = $objSaleInfo['house_type'];
$object['house_material'] = $objSaleInfo['house_material'];
$object['deal_type'] = $objSaleInfo['deal_type'];
$object['build_year'] = $objSaleInfo['build_year'];
$object['is_nb'] = $objSaleInfo['is_nb'];
$sqlHmInfo = "SELECT name FROM house_material WHERE id=$object[house_material]";
$rezHmInfo = $this->db->query($sqlHmInfo);
if ($this->db->num_rows($rezHmInfo) > 0) {
$objHmInfo = $this->db->fetch_assoc($rezHmInfo);
$object['house_material_name'] = $objHmInfo['name'];
} else {
$object['house_material_name'] = null;
}
$sqlHtInfo = "SELECT name FROM house_type WHERE id=$object[house_type]";
$rezHtInfo = $this->db->query($sqlHtInfo);
if ($this->db->num_rows($rezHtInfo) > 0) {
$objHtInfo = $this->db->fetch_assoc($rezHtInfo);
$object['house_type_name'] = $objHtInfo['name'];
} else {
$object['house_type_name'] = null;
}
$sqlDtInfo = "SELECT name FROM deal_type WHERE id=$object[deal_type]";
$rezDtInfo = $this->db->query($sqlDtInfo);
if ($this->db->num_rows($rezDtInfo) > 0) {
$objDtInfo = $this->db->fetch_assoc($rezDtInfo);
$object['deal_type_name'] = $objDtInfo['name'];
} else {
$object['deal_type_name'] = null;
}
} else {
$object['house_material'] = null;
$object['house_type'] = null;
$object['deal_type'] = null;
$object['build_year'] = null;
$object['deal_type_name'] = null;
$object['house_type_name'] = null;
$object['house_material_name'] = null;
$object['is_nb'] = null;
}
// Данные новостройки
$sqlNbInfo = "SELECT newbuilding_id, zipal_new_flat_type_id, nb_end_date FROM object_nb_info WHERE object_id=$object[id]";
$rezNbInfo = $this->db->query($sqlNbInfo);
if ($this->db->num_rows($rezNbInfo) > 0) {
$objNbInfo = $this->db->fetch_assoc($rezNbInfo);
$object['newbuilding_id'] = $objNbInfo['newbuilding_id'];
$object['zipal_new_flat_type_id'] = $objNbInfo['zipal_new_flat_type_id'];
$object['nb_end_date'] = $objNbInfo['nb_end_date'];
}
$operationType = 'аренда';
$mortgage = '';
$buildingType = '';
if ($object['operation_type'] == 1) {
$operationType = 'продажа';
$buildingType = $object['house_material_name'];
$mortgage = (strpos($object['stoim_prim'], "ипотека") === false) ? 'нет' : 'да';
}
$propertyType = 'жилая';
if ($object['type'] == 6 || $object['type'] == 4) {
$propertyType = '';
}
$category = 'квартира';
switch ($object['type']) {
case 1:
$category = 'квартира';
break;
case 2:
$category = 'комната';
break;
case 3:
$category = 'дом с участком';
break;
case 4:
$category = 'коммерческая';
if ($object['type_category'] && $object['type_category'] == 7) {
$category = 'гараж';
$garage_type = 'гараж';
$commercial_type = '';
if ($object['garage_type_id'] && $object['garage_type_id'] == 1) {
$garage_type = 'машиноместо';
}
if ($object['garage_type_id'] && $object['garage_type_id'] == 3) {
$garage_type = 'машиноместо';
}
if($object['parking_type_id'] > 0 && $object['parking_type_id'] == 2){
$parking_type = 'подземная';
} else if($object['parking_type_id'] > 0 && $object['parking_type_id'] == 3){
$parking_type = 'многоуровневая';
} else if($object['parking_type_id'] > 0 && $object['parking_type_id'] >= 5){
$parking_type = 'наземная';
}
if($object['boks_vid_id'] > 0 && $object['boks_vid_id'] == 1){
$building_type = 'кирпичный';
} else if($object['boks_vid_id'] > 0 && $object['boks_vid_id'] == 2){
$building_type = 'металлический';
} else if($object['boks_vid_id'] > 0 && $object['boks_vid_id'] == 3){
$building_type = 'железобетонный';
}
}
break;
case 5:
$category = 'часть дома';
break;
case 6:
$category = 'коммерческая';
break;
case 7:
$category = 'участок';
$propertyType = 'жилая';
break;
}
if($object['type'] == 3){
if($object['house_category']){
if($object['house_category'] == 1){
$category = 'дача';
}
if($object['house_category'] == 2){
$category = 'коттедж';
}
if($object['house_category'] == 3){
$category = 'таунхаус';
}
if($object['house_category'] == 4){
$category = 'дом с участком';
}
}
}
$sql = "SELECT metro.metro FROM metro, sp_metro WHERE sp_metro.id_metro = metro.id AND sp_metro.id_obj = $object[id]";
$result = $this->db->query($sql);
$m = $this->db->fetch_row($result);
$mtr = $m[0];
$location = [];
$sql = "SELECT * FROM object_location WHERE object_id = $object[id]";
$result = $this->db->query($sql);
if ($result) {
$location = $this->db->fetch_assoc($result);
}
$city = null;
if (!empty($location['city'])) {
$city = $location['city'];
}
$regionRayon = null;
$rayon = null;
if (!empty($location['rf_region_rayon'])) {
$regionRayon = $location['rf_region_rayon'];
}
if (!empty($object['rayon'])) {
$rayon = $object['rayon'];
}
$address = '';
if (!empty($location['street'])) {
$address = $location['street'];
if ($object['dom']) {
$address = $address . ", " . $object['dom'];
}
if ($object['korpus']) {
$address = $address . ", корпус " . $object['korpus'];
}
if ($object['litera']) {
$address = $address . ", литера" . $object['litera'];
}
}
if (isset($objRayonInfo) && $objRayonInfo['is_lo'] == 1) {
$location = array(
'country' => 'Россия',
'region' => 'Ленинградская область',
'sub-locality-name' => $object['rayon']
);
if (!empty($address))
$location['address'] = $address;
if (!empty($object['flat_number']))
$location['apartment'] = $object['flat_number'];
} else if($object['id_rf_region']){
$sql_rf = "SELECT `id`, `name` FROM `rf_regions` where id=$object[id_rf_region]";
$q_rf = $this->db->query($sql_rf);
$r_rf = $this->db->fetch_assoc($q_rf);
if ($object['id_rf_region'] == 1) {
$r_rf['name'] = 'Москва';
}
if (isset($location) && $location['address'] && strpos($location['address'], "Московская") !== false && strpos($location['address'], "ул Московская") === false) {
$r_rf['name'] = 'Московская область';
}
if ($object['id_rf_region'] == 2) {
$r_rf['name'] = 'Санкт-Петербург';
}
if (isset($location) && $location['address'] && strpos($location['address'], "Ленинградская") !== false) {
$r_rf['name'] = 'Ленинградская область';
}
if ($object['id_rf_region'] == 3) {
if (isset($location) && $location['address'] && strpos($location['address'], "Севастополь") !== false) {
$r_rf['name'] = 'Севастополь';
} else {
$r_rf['name'] = 'Крым';
}
}
$location = array(
'country' => 'Россия',
'region' => $r_rf['name'],
'district' => $regionRayon,
);
if ($city)
$location['locality-name'] = $city;
if (!empty($address))
$location['address'] = $address;
if (!empty($object['flat_number']))
$location['apartment'] = $object['flat_number'];
} else {
$location = array(
'country' => 'Россия',
'locality-name' => 'Санкт-Петербург',
);
if (!empty($address))
$location['address'] = $address;
if (!empty($object['flat_number']))
$location['apartment'] = $object['flat_number'];
}
$sql = "SELECT * FROM object_location WHERE object_id = $object[id]";
if ($result = $this->db->query($sql)) {
$locationInfo = $this->db->fetch_assoc($result);
if ($locationInfo['latitude'] && $locationInfo['longitude']) {
$location['latitude'] = $locationInfo['latitude'];
$location['longitude'] = $locationInfo['longitude'];
}
}
$location['metro'] = array();
if ($mtr) {
$location['metro'] = array(
'name' => $mtr,
'time-on-foot' => $object['peshkom'],
'time-on-transport' => $object['transport']
);
}
$object['currency'] = 'RUB';
$sqlObjPricese = "SELECT * FROM object_prices WHERE object_id = {$object['id']}";
$rezObjectPrise = $this->db->query($sqlObjPricese);
if ($this->db->num_rows($rezObjectPrise) > 0) {
$objPricese = $this->db->fetch_assoc($rezObjectPrise);
if($objPricese['currency'] == 1){
$object['currency'] = 'USD';
} else if ($objPricese['currency'] == 2){
$object['currency'] = 'EUR';
}
}
if ($object['operation_type'] == 0) {
$period = 'месяц';
if ($object['srok'] == 1) {
$period = 'день';
}
$price = array(
'value' => $object['stoim'],
'currency' => $object['currency'],
'period' => $period
);
} else {
$price = array(
'value' => $object['stoim'],
'currency' => $object['currency']
);
}
$userOwner = new User;
$userOwner->get($object['id_add_user']);
$sales = array(
'agent_id' => $object['id_add_user'],
'name' => htmlspecialchars_decode(trim($userOwner->last_name . ' ' . $userOwner->first_name . ' ' . $userOwner->middle_name)),
'email' => $userOwner->email
);
if (stripos($object['phone'], ",") === false) {
$sales['phone'] = $object['phone'];
} else {
$res = explode(",", $object['phone']);
$sales['phone'] = $res[0];
$secondPhone = $res[1];
}
$balcony = null;
$bathroomUnit = null;
$newFlat = false;
$renovation = null;
$advert = 0;
$commercialBuildingType = null;
$area = array();
$dealStatus = null;
$roomSpace = array();
$livingSpace = array();
$kitchenSpace = array();
$lotArea = array();
if ($object['type'] == 1 || $object['type'] == 2) {
if ($object['balcony'] && $object['balcony'] > 0) {
if ($object['balcony'] == 1) {
$balcony = 'балкон';
}
if ($object['balcony'] > 1 && $object['balcony'] < 5) {
$balcony = $object['balcony'] . ' балкона';
}
if ($object['balcony'] >= 5) {
$balcony = $object['balcony'] . ' балконов';
}
} else {
if ($object['loggias'] && $object['loggias'] > 0) {
if ($object['loggias'] == 1) {
$balcony = 'лоджия';
}
if ($object['loggias'] > 1 && $object['loggias'] < 5) {
$balcony = $object['loggias'];
}
if ($object['loggias'] >= 5) {
$balcony = $object['loggias'];
}
}
}
if ($object['separate_wcs'] && $object['separate_wcs'] > 0) {
$bathroomUnit='раздельный';
} else {
if ($object['combined_wcs'] && $object['combined_wcs'] > 0) {
$bathroomUnit='совмещенный';
}
}
if (isset($object['deal_type']) && ($object['deal_type'] == 5 || $object['deal_type'] == 6)) {
$newFlat = true;
}
}
if (($object['type'] == 1 || $object['type'] == 2 || ($object['type'] == 3 || $object['type'] == 5)) && $object['renovation']) {
if ($object['renovation'] == 1) {
$renovation = 'евроремонт';
}
if ($object['renovation'] == 2) {
$renovation ='косметический';
}
if ($object['renovation'] == 3) {
$renovation = 'дизайнерский';
}
if ($object['renovation'] == 4) {
$renovation = 'требует ремонта';
}
if ($object['renovation'] == 5) {
$renovation = 'дизайнерский';
}
if ($object['renovation'] == 6) {
$renovation = 'требует ремонта';
}
}
if($object['add_to_yandex_feed']){
$advert = 1;
}
if($object['type'] == 4){
if ($object['type_category'] != 7) {
if ($object['commer_condition'] == 1 || $object['commer_condition'] == 6) {
$renovation = 'с отделкой';
} else if ($object['commer_condition'] == 2 || $object['commer_condition'] == 3 || $object['commer_condition'] == 3) {
$renovation = 'требует ремонта';
} else if ($object['commer_condition'] == 5) {
$renovation = 'дизайнерский';
}
}
if ($object['commerc_building_type_id']) {
if ($object['commerc_building_type_id'] == 1 || $object['commerc_building_type_id'] == 8
|| $object['commerc_building_type_id'] == 9 || $object['commerc_building_type_id'] == 10
|| $object['commerc_building_type_id'] == 11 || $object['commerc_building_type_id'] == 12
|| $object['commerc_building_type_id'] == 16 || $object['commerc_building_type_id'] == 17
|| $object['commerc_building_type_id'] == 18 || $object['commerc_building_type_id'] == 19
|| $object['commerc_building_type_id'] == 20 || $object['commerc_building_type_id'] == 21
|| $object['commerc_building_type_id'] == 22 || $object['commerc_building_type_id'] == 30
|| $object['commerc_building_type_id'] == 31 || $object['commerc_building_type_id'] == 32
|| $object['commerc_building_type_id'] == 33 || $object['commerc_building_type_id'] == 43) {
$commercialBuildingType = 'detached building';
}
if ($object['commerc_building_type_id'] == 2 || $object['commerc_building_type_id'] == 3
|| $object['commerc_building_type_id'] == 4 || $object['commerc_building_type_id'] == 5
|| $object['commerc_building_type_id'] == 6 || $object['commerc_building_type_id'] == 7
|| $object['commerc_building_type_id'] == 25 || $object['commerc_building_type_id'] == 26
|| $object['commerc_building_type_id'] == 27 || $object['commerc_building_type_id'] == 28
|| $object['commerc_building_type_id'] == 29 || $object['commerc_building_type_id'] == 44) {
$commercialBuildingType = 'business center';
}
if ($object['commerc_building_type_id'] == 13 || $object['commerc_building_type_id'] == 14
|| $object['commerc_building_type_id'] == 15 || $object['commerc_building_type_id'] == 23
|| $object['commerc_building_type_id'] == 24 || $object['commerc_building_type_id'] == 48
|| $object['commerc_building_type_id'] == 49) {
$commercialBuildingType = 'warehouse';
}
if ($object['commerc_building_type_id'] == 34 || $object['commerc_building_type_id'] == 35) {
$commercialBuildingType = 'residential building';
}
if ($object['commerc_building_type_id'] == 36 || $object['commerc_building_type_id'] == 37
|| $object['commerc_building_type_id'] == 38 || $object['commerc_building_type_id'] == 39
|| $object['commerc_building_type_id'] == 40 || $object['commerc_building_type_id'] == 41
|| $object['commerc_building_type_id'] == 42 || $object['commerc_building_type_id'] == 45
|| $object['commerc_building_type_id'] == 46 || $object['commerc_building_type_id'] == 47) {
$commercialBuildingType = 'shopping center';
}
}
}
if ($object['type'] != 7) {
if (!empty($object['ploshad']) && $object['ploshad'] > 0) {
$area = array('value'=>$object['ploshad'], 'unit'=>'кв.м');
} else {
if (!empty($object['commerc_site']) && $object['commerc_site'] > 0) {
$area = array('value'=>$object['commerc_site'], 'unit'=>'гектар');
}
}
if ($object['type_category'] && $object['type_category'] == 6) {
if (!empty($object['building_area']) && $object['building_area'] > 0) {
$area = array('value'=>$object['building_area'], 'unit'=>'кв.м');
}
}
if (!empty($object['ploshad_komn']) && $object['ploshad_komn'] > 0) {
$sq = $object['ploshad_komn'];
if (strpos($object['ploshad_komn'], "+")) {
$sqTemp = 0;
$res = explode("+", $object['ploshad_komn']);
foreach ($res as $str) {
$sqTemp = $sqTemp + doubleval(trim(str_replace(",", ".", $str)));
//для комнат передаем для каждой отдельно, если указана сумма
if ($object['type'] == 2 || $object['type'] == 1) {
$roomSpace[] = array('value' => $str, 'unit' => 'кв.м');
}
$sq = $sqTemp;
}
}
$livingSpace = array('value'=>$sq, 'unit'=>'кв.м');
if (!empty($object['ploshad_k']) && $object['ploshad_k'] > 0) {
$kitchenSpace = array('value' => $object['ploshad_k'], 'unit' => 'кв.м');
}
}
} else {
$lotArea = array('value'=>$object['land_area'], 'unit'=>'сотка');
}
if ($object['type'] == 3) {
$lotArea = array('value'=>$object['land_area'], 'unit'=>'сотка');
}
if ($object['operation_type'] == 1) {
if ($object['deal_type'] == 1) {
$dealStatus = 'прямая продажа';
}
if ($object['deal_type'] == 2) {
$dealStatus = 'встречная продажа';
}
if ($object['deal_type'] == 4) {
$dealStatus = 'первичная продажа вторички';
}
if ($object['deal_type'] == 5) {
$dealStatus = 'переуступка';
}
}
$object['creation-date'] = (strtotime($object['date_really_add']) != 0) ? strtotime($object['date_really_add']) : strtotime($object['date_add']);
$object['last-update-date'] = strtotime($object['date_add']);
$result = array(
'type'=>$operationType,
'property-type'=>$propertyType,
'category'=>$category,
'mortgage'=>$mortgage,
'building-type'=>$buildingType,
'creation-date'=>date('Y-m-d\TH:i:s\+03:00', $object['creation-date']),
'last-update-date'=>date('Y-m-d\TH:i:s\+03:00', $object['last-update-date']),
'location'=>$location,
'price' => $price,
'video-review' => array('youtube-video-review-url'=>$object['video_url']),
'images' => $images,
'sales'=>$sales,
'description'=>trim(htmlspecialchars(br2nl($object['opis']), ENT_QUOTES)),
'balcony'=>$balcony,
'bathroom-unit'=>$bathroomUnit,
'apartments'=>($object['apartments'] && $object['apartments'] == 1 ? "true" : "false"),
'new-flat'=>$newFlat,
'renovation'=>$renovation,
'commercial-building-type'=> $commercialBuildingType,
'area'=>$area,
'floor' => $object['etazh'],
'floors-total' => $object['etazh_iz'],
);
if(!empty($dealStatus))
$result['deal-status'] = $dealStatus;
if(!empty($roomSpace))
$result['room-space'] = $roomSpace;
if(!empty($livingSpace))
$result['living-space'] = $livingSpace;
if(!empty($kitchenSpace))
$result['kitchen-space'] = $kitchenSpace;
if(!empty($lotArea))
$result['lot-area'] = $lotArea;
// Кадастровый номер (все типы объектов)
if (!empty($object['cadastral_number'])) {
$result['cadastral-number'] = htmlspecialchars(strip_tags($object['cadastral_number']));
}
// Количество комнат (квартиры, комнаты, дома)
if (!empty($object['komnat']) && $object['komnat'] > 0) {
$result['rooms'] = $object['komnat'];
}
if ($object['type'] == 2) {
if (!empty($object['vsego_komn']) && $object['vsego_komn'] > 0) {
$result['rooms-offered'] = $object['vsego_komn'];
}
}
// Коммуникации: дома, части домов, участки (types 3, 5, 7)
if (in_array($object['type'], [3, 5, 7])) {
// Газоснабжение
if (isset($object['gas_type_id']) && $object['gas_type_id'] > 0) {
if (in_array($object['gas_type_id'], [1, 4])) {
$result['gas-supply'] = 'нет';
} elseif (in_array($object['gas_type_id'], [2, 3, 5])) {
$result['gas-supply'] = 'да';
}
}
// Электроснабжение
if (isset($object['electricity_type_id']) && $object['electricity_type_id'] > 0) {
if (in_array($object['electricity_type_id'], [1, 3])) {
$result['electricity-supply'] = 'нет';
} elseif (in_array($object['electricity_type_id'], [2, 4])) {
$result['electricity-supply'] = 'да';
}
}
// Водоснабжение
if (isset($object['plumbing_type_id']) && $object['plumbing_type_id'] > 0) {
if (in_array($object['plumbing_type_id'], [2, 3, 4, 5])) {
$result['water-supply'] = 'да';
} elseif ($object['plumbing_type_id'] == 1) {
$result['water-supply'] = 'нет';
}
}
// Канализация
if (isset($object['sewerage_type']) && $object['sewerage_type'] > 0) {
if (in_array($object['sewerage_type'], [2, 3, 4, 5])) {
$result['sewerage-supply'] = 'да';
} elseif ($object['sewerage_type'] == 1) {
$result['sewerage-supply'] = 'нет';
}
}
}
// Вид разрешённого использования участка (types 7, 3)
if (in_array($object['type'], [7, 3]) && !empty($object['land_usage_type_id'])) {
$sqlUsageType = "SELECT code FROM land_usage_type WHERE id = {$object['land_usage_type_id']}";
$qUsageType = $this->db->query($sqlUsageType);
if($this->db->num_rows($qUsageType) > 0){
$usageType = $this->db->fetch_row($qUsageType);
if (!empty($usageType[0])) {
if ($usageType[0] == 'IGS') {
$result['lot-type'] = 'ИЖС';
} elseif ($usageType[0] == 'SNT' || $usageType[0] == 'GARDEN') {
$result['lot-type'] = 'садоводство';
}
}
}
}
// Год постройки
if (!empty($object['build_year']) && $object['build_year'] > 0) {
$result['built-year'] = $object['build_year'];
}
// Высота потолков (квартиры, комнаты, коммерция)
if (in_array((int)$object['type'], [1, 2]) || ((int)$object['type'] == 4 && in_array((int)$object['type_category'], [1, 2, 3, 4, 5, 6]))) {
if (!empty($object['ceiling_height']) && $object['ceiling_height'] > 0) {
$result['ceiling-height'] = (double)$object['ceiling_height'];
}
}
// Студия
if (!empty($object['studio_flag']) && $object['studio_flag'] == 1) {
$result['studio'] = 1;
}
// Вид из окон
if (!empty($object['window_view']) && $object['window_view'] > 0) {
if (in_array((int)$object['window_view'], [1, 6, 7])) {
$result['window-view'] = 'во двор';
} elseif (in_array((int)$object['window_view'], [2, 3, 4, 5, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30, 31, 34, 35, 36])) {
$result['window-view'] = 'на улицу';
}
}
// Лифт (квартиры, комнаты)
if ($object['type'] == 1 || $object['type'] == 2) {
if ((!empty($object['passenger_lifts']) && $object['passenger_lifts'] > 0) || (!empty($object['cargo_lifts']) && $object['cargo_lifts'] > 0)) {
$result['lift'] = 'true';
}
}
// Тип гаража и тип парковки
if ($object['type'] == 4 && $object['type_category'] == 7) {
$garageType = 'гараж';
if ($object['garage_type_id'] && ($object['garage_type_id'] == 1 || $object['garage_type_id'] == 3)) {
$garageType = 'машиноместо';
}
$result['garage-type'] = $garageType;
if ($object['parking_type_id'] > 0) {
if ($object['parking_type_id'] == 2) {
$result['parking-type'] = 'подземная';
} elseif ($object['parking_type_id'] == 3) {
$result['parking-type'] = 'многоуровневая';
} elseif ($object['parking_type_id'] >= 5) {
$result['parking-type'] = 'наземная';
}
}
}
// Класс бизнес-центра (коммерция, кроме гаражей)
if ($object['type'] == 4 && $object['type_category'] != 7) {
if (!empty($object['commerc_building_class_id'])) {
$classMap = array(1 => 'A', 2 => 'A+', 3 => 'B', 4 => 'B+', 5 => 'C+', 6 => 'C');
if (isset($classMap[$object['commerc_building_class_id']])) {
$result['office-class'] = $classMap[$object['commerc_building_class_id']];
}
}
}
// Тип коммерческого объекта
if ($object['type'] == 6 || $object['type'] == 4) {
if (!empty($object['type_category'])) {
$commercialTypeMap = array(
1 => 'office', 2 => 'warehouse', 3 => 'retail',
4 => 'manufacturing', 5 => 'free purpose', 6 => 'free purpose',
8 => 'business', 9 => 'land'
);
if (isset($commercialTypeMap[$object['type_category']]) && $object['type_category'] != 7) {
$result['commercial-type'] = $commercialTypeMap[$object['type_category']];
}
}
}
// Комиссия (аренда)
if ($object['operation_type'] == 0 && !empty($object['commission'])) {
if ($object['type'] == 4) {
$result['commission'] = $object['commission'];
} else {
$result['agent-fee'] = $object['commission'];
}
}
// Залог (аренда)
if ($object['operation_type'] == 0) {
if (!empty($object['lease_deposit_id']) || !empty($object['lease'])) {
$result['rent-pledge'] = 'да';
} else {
$result['rent-pledge'] = 'нет';
}
}
// Новостройки
if (isset($object['deal_type']) && ($object['deal_type'] == 5 || $object['deal_type'] == 6)) {
if (isset($object['newbuilding_id']) && $object['newbuilding_id']) {
$sqlNb = "SELECT * FROM newbuildings WHERE id = {$object['newbuilding_id']}";
$rezNb = $this->db->query($sqlNb);
if ($this->db->num_rows($rezNb) > 0) {
$nb = $this->db->fetch_assoc($rezNb);
$sqlObjName = "SELECT value FROM newbuilding_object WHERE id = {$nb['newbuilding_object_id']}";
$rezObjName = $this->db->query($sqlObjName);
$objName = $this->db->fetch_assoc($rezObjName);
if (!empty($objName['value'])) {
$result['building-name'] = htmlspecialchars(strip_tags($objName['value']), ENT_QUOTES);
}
if (!empty($nb['yandex_id'])) {
$result['yandex-building-id'] = $nb['yandex_id'];
}
if (!empty($nb['yandex_housing_id'])) {
$result['yandex-house-id'] = $nb['yandex_housing_id'];
}
}
}
if (isset($object['zipal_new_flat_type_id']) && $object['zipal_new_flat_type_id']) {
$sqlNbState = "SELECT code FROM zipal_new_flat_type WHERE id = '{$object['zipal_new_flat_type_id']}'";
$rezNbState = $this->db->query($sqlNbState);
if ($this->db->num_rows($rezNbState) > 0) {
$nbState = $this->db->fetch_assoc($rezNbState);
if ($nbState['code'] == 'NOT_READY') {
$result['building-state'] = 'unfinished';
} elseif ($nbState['code'] == 'READY') {
$result['building-state'] = 'built';
} else {
$result['building-state'] = 'hand-over';
}
}
}
}
if (isset($object['is_nb']) && $object['is_nb'] && isset($object['deal_type']) && ($object['deal_type'] == 1 || $object['deal_type'] == 2)) {
if (isset($object['newbuilding_id']) && $object['newbuilding_id']) {
$sqlNb = "SELECT * FROM newbuildings WHERE id = {$object['newbuilding_id']}";
$rezNb = $this->db->query($sqlNb);
if ($this->db->num_rows($rezNb) > 0) {
$nb = $this->db->fetch_assoc($rezNb);
$sqlObjName = "SELECT value FROM newbuilding_object WHERE id = {$nb['newbuilding_object_id']}";
$rezObjName = $this->db->query($sqlObjName);
$objName = $this->db->fetch_assoc($rezObjName);
if (!empty($objName['value']) && empty($result['building-name'])) {
$result['building-name'] = htmlspecialchars(strip_tags($objName['value']), ENT_QUOTES);
}
if (!empty($nb['yandex_id']) && empty($result['yandex-building-id'])) {
$result['yandex-building-id'] = $nb['yandex_id'];
}
if (!empty($nb['yandex_housing_id']) && empty($result['yandex-house-id'])) {
$result['yandex-house-id'] = $nb['yandex_housing_id'];
}
}
}
if (isset($object['zipal_new_flat_type_id']) && $object['zipal_new_flat_type_id'] && empty($result['building-state'])) {
$sqlNbState = "SELECT code FROM zipal_new_flat_type WHERE id = '{$object['zipal_new_flat_type_id']}'";
$rezNbState = $this->db->query($sqlNbState);
if ($this->db->num_rows($rezNbState) > 0) {
$nbState = $this->db->fetch_assoc($rezNbState);
if ($nbState['code'] == 'NOT_READY') {
$result['building-state'] = 'unfinished';
} elseif ($nbState['code'] == 'READY') {
$result['building-state'] = 'built';
} else {
$result['building-state'] = 'hand-over';
}
}
}
}
}
return $result;
}
/**
* Получение только ответственного по объекту
*/
public function get_object_sales($user_id){
$result = array();
if($user_id > 0){
$userOwner = new User;
$userOwner->get($user_id);
$sales = array(
'agent_id' => $user_id,
'name' => htmlspecialchars_decode(trim($userOwner->last_name . ' ' . $userOwner->first_name . ' ' . $userOwner->middle_name)),
'email' => $userOwner->email
);
$result['sales'] = $sales;
}
return $result;
}
/**
* Получение данных сотрудника
*/
public function get_employee($id){
$result = array();
if($id > 0){
$sql = "SELECT * FROM users WHERE id = {$id}";
$q = $this->db->query($sql);
$employee = $this->db->fetch_assoc($q);
$result['full_name'] = trim($employee['last_name'] . ' ' . $employee['first_name'] . ' ' . $employee['middle_name']);
$result['phone'] = $employee['phone'];
$result['email'] = $employee['email'];
$result['manager_id'] = $employee['id_manager'];
}
return $result;
}
/**
* Сохранение временных данных по объекту
*/
public function save_temp_object($object_id){
if($object_id > 0 && $this->agency_id > 0){
$object = $this->get_object($object_id);
$description = $object['description'];
unset($object['description']);
$info = json_encode($object, JSON_UNESCAPED_UNICODE);
$sql = "INSERT INTO `webhook_temp_object`(`object_id`, `info`, `description`) VALUES ({$object_id}, '{$info}', '{$description}')";
$this->db->query($sql);
}
}
/**
* Сохранение временных данных по сотруднику
*/
public function save_temp_employee($employee_id){
if($employee_id > 0 && $this->agency_id > 0){
$employee = json_encode($this->get_employee($employee_id), JSON_UNESCAPED_UNICODE);
$sql = "INSERT INTO `webhook_temp_employee`(`employee_id`, `info`) VALUES ({$employee_id}, '{$employee}')";
$this->db->query($sql);
}
}
/**
* Сохранение данных для последующей отправки по крону
*/
public function save_webhook_cron($user_id, $section, $action, $entity_id, $advert_platform = ''){
if($entity_id > 0 && $this->agency_id > 0){
$sql = "INSERT INTO `webhook_cron`(`event_type`, `entity_type`, `entity_id`, `initiator_user_id`, `initiator_agency_id`, `advert_platform`) VALUES
('{$action}', '{$section}', '{$entity_id}', {$user_id}, {$this->agency_id}, '$advert_platform')";
$this->db->query($sql);
}
}
/**
* Сохранение данных по нескльким объекта при смене ответственного
*/
public function save_webhook_cron_many($user_id, $old_user_id, $new_user_id){
if($old_user_id > 0 && $new_user_id > 0 && $this->agency_id > 0){
$object_ids = array();
$sql = "SELECT id FROM objects WHERE id_add_user = {$old_user_id}";
$q = $this->db->query($sql);
if($this->db->num_rows($q) > 0){
$sql_w = "INSERT INTO `webhook_cron`(`event_type`, `entity_type`, `entity_id`, `initiator_user_id`, `initiator_agency_id`, new_user_id) VALUES ";
$part_sql = '';
while($r=$this->db->fetch_assoc($q)){
if($part_sql != '') $part_sql .= ',';
$part_sql .= "('object_update', 'object', {$r['id']}, {$user_id}, {$this->agency_id}, {$new_user_id})";
}
if(!empty($part_sql)){
$sql_w .= $part_sql;
//file_put_contents(__DIR__.'/log_hook_test.txt', date('d.m.Y H:i:s')." ".$sql_w. "\n", FILE_APPEND);
$this->db->query($sql_w);
}
}
}
}
}