2314 lines
84 KiB
PHP
2314 lines
84 KiB
PHP
<?php
|
||
require_once($_SERVER['DOCUMENT_ROOT']."/ajax/vue_php_function.php");
|
||
if(!$_SESSION['id']) { header("location:/index.php"); die("Доступ запрещён!");}
|
||
|
||
/*error_reporting(E_ALL | E_STRICT);
|
||
ini_set('display_errors', 1);*/
|
||
|
||
$data = json_decode(file_get_contents("php://input"));
|
||
|
||
//var_dump($data);
|
||
|
||
$pdo = new MysqlPdo(hst, ndb, user, pass);
|
||
|
||
$sql = "SET NAMES 'utf8'";
|
||
|
||
$pdo->query($sql);
|
||
|
||
$log = "";
|
||
$request = $data->request;
|
||
|
||
if($request == 'get_all'){
|
||
/*if($_SESSION['id'] == 19895){
|
||
ini_set('display_errors', 1);
|
||
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);
|
||
}*/
|
||
$start = microtime(true);
|
||
|
||
$user_id = null;
|
||
$funnel_id = false;
|
||
$client_id = false;
|
||
$filtr = array();
|
||
$page = 0;
|
||
$object_id = false;
|
||
$complex_room_id = false;
|
||
$reqs_id = false;
|
||
$is_cancel = false;
|
||
|
||
$agency = new User;
|
||
$agency->checkPermissions();
|
||
|
||
if(isset($data->user_id)){
|
||
$user_id = $data->user_id;
|
||
$sql_check_permissions = "SELECT `menu_all_submissions`, `menu_all_submissions_edit` FROM user_permissions WHERE user_id = $user_id";
|
||
$q_check_permissions = mysql_query($sql_check_permissions);
|
||
$r_check_permissions = mysql_fetch_assoc($q_check_permissions);
|
||
if ($_SESSION['users_admin'] || $r_check_permissions['menu_all_submissions'] == 1) {
|
||
$user_id = $agency->agencyId;
|
||
}
|
||
}
|
||
if(isset($data->funnel_id)){
|
||
$funnel_id = $data->funnel_id;
|
||
}
|
||
if(isset($data->client_id)){
|
||
$client_id = $data->client_id;
|
||
}
|
||
if(isset($data->filtr)){
|
||
$filtr = $data->filtr;
|
||
}
|
||
|
||
if(isset($data->page)){
|
||
$page = (int)$data->page;
|
||
}
|
||
|
||
if(isset($data->object_id)){
|
||
$object_id = $data->object_id;
|
||
}
|
||
|
||
if(isset($data->complex_room_id)){
|
||
$complex_room_id = $data->complex_room_id;
|
||
}
|
||
|
||
if(isset($data->reqs_id)){
|
||
$reqs_id = $data->reqs_id;
|
||
}
|
||
|
||
if(isset($data->is_cancel)){
|
||
$is_cancel = (bool)$data->is_cancel;
|
||
}
|
||
|
||
$req = new Requisitions($pdo);
|
||
if(isset($data->view)){
|
||
|
||
$req->set_view($data->view);
|
||
|
||
}
|
||
$req->set_agencyId($agency->agencyId);
|
||
$req->set_user($agency);
|
||
$req->set_page($page);
|
||
|
||
$htmlFilter = '';
|
||
//загружаем этапы воронки
|
||
$htmlFilter = $htmlFilter . '<select id="req_filter_etap" multiple="">';
|
||
if ($funnel_id == 0) {
|
||
$htmlFilter = $htmlFilter . '<option value="1">Новый</option>';
|
||
$htmlFilter = $htmlFilter . '<option value="2">В работе</option>';
|
||
$htmlFilter = $htmlFilter . '<option value="3">Презентация</option>';
|
||
$htmlFilter = $htmlFilter . '<option value="4">Показ</option>';
|
||
$htmlFilter = $htmlFilter . '<option value="5">Бронь</option>';
|
||
$htmlFilter = $htmlFilter . '<option value="6">Подаем на ипотеку</option>';
|
||
$htmlFilter = $htmlFilter . '<option value="7">Сделка</option>';
|
||
$htmlFilter = $htmlFilter . '<option value="8">Закрыт</option>';
|
||
} else {
|
||
$funnelStepsData = mysql_query("select * from funnel_steps WHERE deleted = 0 and funnel_id = $funnel_id order by id");
|
||
|
||
while ($funnelStep = mysql_fetch_assoc($funnelStepsData)) {
|
||
|
||
$htmlFilter = $htmlFilter . '<option value="' . $funnelStep['id'] . '">' . $funnelStep['name'] . '</option>';
|
||
}
|
||
}
|
||
$htmlFilter = $htmlFilter . '</select>';
|
||
|
||
if(isset($data->per_page) && $data->per_page>0){
|
||
$req->set_per_page($data->per_page);
|
||
}
|
||
$res = $req->get_all($user_id, $filtr, $funnel_id, $client_id, $object_id, true, $complex_room_id, $reqs_id, $is_cancel);
|
||
|
||
$end = round((microtime(true) - $start), 2) . "s.";
|
||
if (is_array($res))
|
||
$res['_time_overage'] = $end;
|
||
|
||
$res['step_filter'] = $htmlFilter;
|
||
|
||
echo json_encode($res);
|
||
exit();
|
||
}
|
||
|
||
// Добавление/редактирование заявки
|
||
if($request == 'add_edit') {
|
||
$params = array();
|
||
$params['user_id'] = $data->user_id;
|
||
$params['funnel_id'] = $funnel_id = (int)$data->funnel_id;
|
||
$params['name'] = $data->name;
|
||
$params['fio'] = $data->fio;
|
||
/*$params['fio'] = trim($data->last_name . ' ' . $data->first_name . ' ' . $data->middle_name);
|
||
$params['first_name'] = $data->first_name;
|
||
$params['last_name'] = $data->last_name;
|
||
$params['middle_name'] = $data->middle_name;*/
|
||
$params['email'] = $data->email;
|
||
$params['phone'] = $data->phone;
|
||
$params['opis'] = htmlspecialchars($data->opis);
|
||
$params['type_id'] = $data->type_id;
|
||
$params['object_id'] = $data->object_id;
|
||
$params['object_price'] = intval($data->price);
|
||
$params['object_prep_price'] = intval($data->prep_price);
|
||
$params['object_start_price'] = intval($data->start_price);
|
||
$params['object_fact_price'] = intval($data->fact_price);
|
||
$params['req_id'] = $data->req_id;
|
||
$params['client_id'] = $data->client_id;
|
||
$params['priority'] = $data->priority;
|
||
$params['who_work'] = $data->who_work;
|
||
$params['confirm'] = $data->confirm;
|
||
$params['old_whowork'] = $data->old_whowork;
|
||
$params['hot'] = $data->hot;
|
||
$params['activities'] = $data->activities;
|
||
$params['asfilter_id'] = (!empty($data->autosearch_filter_id) ? $data->autosearch_filter_id : 'NULL');
|
||
|
||
$params['employee_id'] = $data->employee_id;
|
||
$params['field_models'] = $data->field_models;
|
||
$params['contracts'] = $data->contracts;
|
||
$params['autosearch_enabled'] = $data->autosearch_enabled;
|
||
$params['newClientName'] = $data->newClientName;
|
||
$params['wazzap_channel_id'] = $data->wazzap_channel_id;
|
||
$params['wazzap_chat_id'] = $data->wazzap_chat_id;
|
||
$params['wazzap_chat_type'] = $data->wazzap_chat_type;
|
||
$params['wazzap_integration_id'] = $data->wazzap_integration_id;
|
||
$params['wazzap_user_id'] = $data->wazzap_user_id;
|
||
$params['status'] = $data->status;
|
||
$params['friend_client_id'] = $data->friend_client_id;
|
||
$params['confirm_recommendation'] = ((!empty($data->confirm_recommendation) && ($data->confirm_recommendation == 1 || $data->confirm_recommendation == 2)) ? $data->confirm_recommendation : 'NULL');
|
||
$params['is_manual'] = 0;
|
||
|
||
if($data->is_manual){
|
||
$params['is_manual'] = (int)$data->is_manual;
|
||
}
|
||
if($data->source){
|
||
$params['source'] = $data->source;
|
||
}
|
||
if ($data->complex_room_id) {
|
||
$params['complex_room_id'] = $data->complex_room_id;
|
||
}
|
||
|
||
$req = new Requisitions($pdo);
|
||
$result = $req->add_edit($params);
|
||
if(isset($result['error'])){
|
||
echo json_encode($result);
|
||
exit();
|
||
}
|
||
|
||
$res = $req->get_class_etap($result, $funnel_id);
|
||
|
||
$complex = new Complex();
|
||
$res['requisitions'] = $complex->get_room_requisitions($data->complex_room_id);
|
||
|
||
$reservations = $complex->get_room_reservations($data->complex_room_id, true);
|
||
$can_change_queue = $reservations['can_change_queue'];
|
||
|
||
unset($reservations['can_change_queue']);
|
||
|
||
$res['reservations']['data'] = $reservations;
|
||
$res['reservations']['can_change_queue'] = $can_change_queue;
|
||
|
||
//if($fu)
|
||
echo json_encode($res);
|
||
exit();
|
||
}
|
||
|
||
if($request == 'add_edit_stage'){
|
||
$req_id = $data->req_id;
|
||
$stage = $data->stage;
|
||
|
||
$in_sql = "UPDATE requisitions SET
|
||
stage={$stage}
|
||
WHERE id = {$req_id}";
|
||
|
||
$pdo->query($in_sql);
|
||
|
||
}
|
||
|
||
//Изменение заявки
|
||
if($request == 'update_req'){
|
||
$clientId = $data->client_id;
|
||
$req_id = $data->req_id;
|
||
$object_id = $data->object_id;
|
||
$objects = json_decode($object_id);
|
||
$object = 0;
|
||
if(!empty($objects)){
|
||
$object = $objects[0];
|
||
}
|
||
$req_id_arr = explode(',',$req_id);
|
||
foreach($req_id_arr as $req){
|
||
$object_id_req = 0;
|
||
$sql_req = "SELECT object_id, type_id FROM requisitions WHERE id = $req";
|
||
$req_temp = $pdo->fetch_assoc($pdo->query($sql_req));
|
||
if($req_temp['object_id'] > 0){
|
||
$object_id_req = $req_temp['object_id'];
|
||
} else if ($req_temp['type_id'] == 2) {
|
||
$object_id_req = $object;
|
||
}
|
||
$in_sql = "UPDATE requisitions SET
|
||
object_id=$object_id_req,
|
||
client_id=$clientId
|
||
WHERE id = $req ";
|
||
if($object_id_req == 0){
|
||
$in_sql = "UPDATE requisitions SET
|
||
client_id=$clientId
|
||
WHERE id = $req";
|
||
}
|
||
$pdo->query($in_sql);
|
||
|
||
}
|
||
exit();
|
||
}
|
||
|
||
//Заявка по id
|
||
if($request == 'get_req_id'){
|
||
$req_id = $data->req_id;
|
||
$is_kanban = false;
|
||
if(isset($data->is_kanban) && $data->is_kanban > 0){
|
||
$is_kanban = true;
|
||
}
|
||
$req = new Requisitions($pdo);
|
||
if(isset($data->user_id)){
|
||
$agency = new User;
|
||
$agency->get($data->user_id);
|
||
$req->set_user($agency);
|
||
$req->set_agencyId($agency->agencyId);
|
||
$req->set_userId($data->user_id);
|
||
}
|
||
$res = $req->get_req_id((int) str_replace('req', '', $req_id), false, $is_kanban);
|
||
echo json_encode($res);
|
||
exit();
|
||
}
|
||
|
||
//Проверка на сочитание клиент/объект тип заявки
|
||
if($request == 'check_object'){
|
||
$user_id = (int)$data->user_id;
|
||
$object_id = $data->object_id;
|
||
$req_id = $data->req_id;
|
||
$agency_id = $data->agency_id;
|
||
$agency = new User;
|
||
$agency->get($user_id);
|
||
|
||
|
||
$filtr = (object) array('object_id'=>$object_id, 'type' => [2]);
|
||
if ($req_id > 0) {
|
||
$filtr = (object) array('object_id'=>$req_id, 'not_id'=>$req_id, 'type' => [2]);
|
||
}
|
||
$res['result'] = 'done';
|
||
$req = new Requisitions($pdo);
|
||
$req->set_user($agency);
|
||
$req->set_agencyId($agency_id);
|
||
$req->set_userId($user_id);
|
||
$search = $req->get_all($agency_id, $filtr, false, false, false, false);
|
||
if (!empty($search['req'])) {
|
||
$res['result'] = 'error';
|
||
$res['mes'] = "Этот объект уже добавлен в заявку";
|
||
$keys = array_keys($search['req']);
|
||
$firstKey = $keys[0];
|
||
|
||
if (isset($search[$firstKey]['name'])) {
|
||
$res['mes'] .= " «".$search[$firstKey]['name']."»";
|
||
}
|
||
|
||
}
|
||
echo json_encode($res);
|
||
exit();
|
||
}
|
||
|
||
//Дополнительные поля
|
||
if($request == 'get_req_fields'){
|
||
$agency_id = (int)$data->agency_id;
|
||
$req_id = (int)$data->req_id;
|
||
$funnel_id = (int)$data->funnel_id;
|
||
$user_id = (int)$data->user_id;
|
||
|
||
$req = new Requisitions($pdo);
|
||
$res = $req->get_req_fields($agency_id, $req_id, $funnel_id, $user_id);
|
||
echo json_encode($res);
|
||
exit();
|
||
}
|
||
|
||
//Удалить заявку
|
||
if($request == 'cancel_req'){
|
||
$req_id = $data->req_id;
|
||
$req = new Requisitions($pdo);
|
||
$req->cancelReq($req_id);
|
||
}
|
||
|
||
//Восстановить заявку
|
||
if ($request == 'renew_req') {
|
||
|
||
$req_id = $data->req_id;
|
||
$user_id = $data->user_id;
|
||
|
||
$req = new Requisitions($pdo);
|
||
if ($req->renewReq($req_id, $user_id) === true) {
|
||
echo json_encode(['success' => true]);
|
||
} else {
|
||
echo json_encode(['success' => false]);
|
||
}
|
||
|
||
exit();
|
||
}
|
||
|
||
//Востановить несколько заявок
|
||
if ($request == 'renew_reqs') {
|
||
|
||
$reqs_id = $data->reqs_id;
|
||
$user_id = $data->user_id;
|
||
$all = $data->all;
|
||
$ids = array();
|
||
if(isset($data->ids_exception)){
|
||
$ids = $data->ids_exception;
|
||
}
|
||
|
||
$success = true;
|
||
$req = new Requisitions($pdo);
|
||
if($all == 1){
|
||
if(isset($_SESSION['where_req_campaigns'])){
|
||
$sql = $_SESSION['where_req_campaigns'];
|
||
if (!empty($ids)){
|
||
$sql .= " AND ID NOT IN (".implode(',', $ids).")";
|
||
}
|
||
$q = $pdo->query($sql);
|
||
while($r = $pdo->fetch_assoc($q)) {
|
||
$reqs_id[] = $r['id'];
|
||
}
|
||
} else {
|
||
exit();
|
||
}
|
||
}
|
||
foreach($reqs_id as $req_id){
|
||
if (!($req->renewReq($req_id, $user_id) === true)) {
|
||
$success = false;
|
||
}
|
||
}
|
||
|
||
if ($success) {
|
||
echo json_encode(['success' => true]);
|
||
} else {
|
||
echo json_encode(['success' => false]);
|
||
}
|
||
|
||
exit();
|
||
}
|
||
|
||
if ($request == 'take_from_closed_reqs') {
|
||
|
||
$reqs_id = $data->reqs_id;
|
||
$user_id = $_SESSION['id'];
|
||
$all = $data->all;
|
||
$ids = array();
|
||
if(isset($data->ids_exception)){
|
||
$ids = $data->ids_exception;
|
||
}
|
||
|
||
$success = true;
|
||
$req = new Requisitions($pdo);
|
||
if($all == 1){
|
||
if(isset($_SESSION['where_req_campaigns'])){
|
||
$sql = $_SESSION['where_req_campaigns'];
|
||
if (!empty($ids)){
|
||
$sql .= " AND ID NOT IN (".implode(',', $ids).")";
|
||
}
|
||
$q = $pdo->query($sql);
|
||
while($r = $pdo->fetch_assoc($q)) {
|
||
$reqs_id[] = $r['id'];
|
||
}
|
||
} else {
|
||
exit();
|
||
}
|
||
}
|
||
foreach($reqs_id as $req_id){
|
||
if (!($req->takeFromClosedReq($req_id, $user_id) === true)) {
|
||
$success = false;
|
||
}
|
||
}
|
||
|
||
if ($success) {
|
||
echo json_encode(['success' => true]);
|
||
} else {
|
||
echo json_encode(['success' => false]);
|
||
}
|
||
|
||
exit();
|
||
}
|
||
|
||
if($request == 'get_complex_room'){
|
||
$req_id = (int) str_replace('req', '', $data->req_id);
|
||
|
||
$sql_req = "SELECT complex_status_id, complex_room_id FROM requisitions WHERE id = $req_id";
|
||
$req_temp = $pdo->fetch_assoc($pdo->query($sql_req));
|
||
|
||
echo json_encode($req_temp);
|
||
exit();
|
||
}
|
||
|
||
if($request == 'get_bar_funnel'){
|
||
session_write_close();
|
||
$funnel_id = $data->funnel_id;
|
||
$req_id = $data->req_id;
|
||
$agency_id = 0;
|
||
if(isset($data->agency_id)){
|
||
$agency_id = (int)$data->agency_id;
|
||
}
|
||
$adjacent_id = 0;
|
||
if(isset($data->adjacent_id)){
|
||
$adjacent_id = (int)$data->adjacent_id;
|
||
}
|
||
$stage = false;
|
||
if(isset($data->stage)){
|
||
$stage = $data->stage;
|
||
}
|
||
if($adjacent_id > 0){
|
||
$funnelClass = new Funnel($pdo);
|
||
$res = $funnelClass->get_class_etap(array(), $req_id, $funnel_id, $adjacent_id);
|
||
|
||
} else {
|
||
$req = new Requisitions($pdo);
|
||
$res = $req->get_class_etap($req_id, $funnel_id, $stage);
|
||
$funnelClass = new Funnel($pdo);
|
||
$data = new stdClass();
|
||
$data->req_id = $req_id;
|
||
$adjacent = $funnelClass->get_adjacent_funnels_req($data);
|
||
if(!empty($adjacent)){
|
||
$res['funnels_adjacent'] = $adjacent['funnels_adjacent'];
|
||
$res['funnels_adjacent_text'] = $adjacent['funnels_adjacent_text'];
|
||
}
|
||
if($agency_id > 0){
|
||
$funnelClass->set_agency_id($agency_id);
|
||
$funnels = $funnelClass->get_funnels('requisitions');
|
||
$res['funnels'] = $funnels;
|
||
}
|
||
}
|
||
echo json_encode($res);
|
||
exit();
|
||
}
|
||
|
||
//Этапы воронки для канбана
|
||
if($request == 'get_step_funnel'){
|
||
$funnel_id = $data->funnel_id;
|
||
$req = new Requisitions($pdo);
|
||
$res = $req->get_etap_funnel($funnel_id);
|
||
echo json_encode($res);
|
||
exit();
|
||
}
|
||
|
||
//Получение клиента
|
||
if($request == 'get_client'){
|
||
$clientId = 0;
|
||
$objectId = 0;
|
||
if(isset($data->client_id)){
|
||
$clientId = $data->client_id;
|
||
}
|
||
if(isset($data->object_id)){
|
||
$objectId = $data->object_id;
|
||
}
|
||
|
||
$agencyId = User::getUserAgencyID();
|
||
|
||
$usersIds = array();
|
||
$usersIds[] = $agencyId;
|
||
$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 = mysql_query($sql_users);
|
||
while($r_users = mysql_fetch_assoc($q_users)){
|
||
$usersIds[] = (int)$r_users['id'];
|
||
}
|
||
|
||
$res = array();
|
||
$sql = '';
|
||
if($clientId > 0){
|
||
$sql = "SELECT `id`, fio, email, phone, objects FROM clients WHERE id=$clientId and (id_agent in (".implode(',', $usersIds).") or who_work in (".implode(',', $usersIds)."))";
|
||
} else if ($objectId > 0) {
|
||
$q_client = $pdo->query("SELECT client_id FROM client_objects WHERE object_id = {$objectId}");
|
||
$client_ids = array();
|
||
while($r_client = $pdo->fetch_assoc($q_client)){
|
||
$client_ids[] = $r_client['client_id'];
|
||
}
|
||
if(!empty($client_ids)){
|
||
$sql = "SELECT `id`, fio, email, phone, objects FROM `clients` WHERE id in (".implode(',', $client_ids).") and (id_agent in (".implode(',', $usersIds).") or who_work in (".implode(',', $usersIds).")) LIMIT 1";
|
||
}
|
||
}
|
||
if($sql != ''){
|
||
$q = $pdo -> query($sql);
|
||
if($pdo -> num_rows($q) > 0){
|
||
$r = $pdo -> fetch_assoc($q);
|
||
// Маскируем контактные данные клиента, если у пользователя включено скрытие
|
||
mask_client_contacts_inplace($r);
|
||
|
||
$res['value'] = $r['id'];
|
||
$res['text'] = $r['phone'].' '.htmlspecialchars_decode(trim($r['fio']));
|
||
$res['phone_email'] = $r['phone'];
|
||
//Не нужно менять - это клиенты
|
||
$res['fio'] = htmlspecialchars_decode(trim($r['fio']));
|
||
if(!empty($r['email'])){
|
||
$res['text'] = $r['phone'].' '.htmlspecialchars_decode(trim($r['fio'])).' ('.$r['email'].')';
|
||
$res['phone_email'] = $r['phone'].' '.$r['email'];
|
||
}
|
||
$res['phones_dop'] = '';
|
||
|
||
$sql_cl2 = "SELECT phone FROM `clients_phone2` WHERE client_id = {$r['id']}";
|
||
$q_cl2 = $pdo->query($sql_cl2);
|
||
while($r_cl2 = $pdo->fetch_assoc($q_cl2)){
|
||
if($res['phones_dop'] != '') $res['phones_dop'] .= ', ';
|
||
$res['phones_dop'] .= mask_phone_value_if_needed($r_cl2['phone']);
|
||
}
|
||
}
|
||
}
|
||
echo json_encode($res);
|
||
exit();
|
||
}
|
||
|
||
if($request == 'save_chat_id'){
|
||
|
||
echo "dd";
|
||
|
||
if(isset($data->telephone)) {
|
||
|
||
var_dump($data->telephone);
|
||
|
||
$clientId = 0;
|
||
$fio = '';
|
||
|
||
$agencyId = User::getUserAgencyID();
|
||
|
||
$usersIds = array();
|
||
$usersIds[] = $agencyId;
|
||
$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 = mysql_query($sql_users);
|
||
while($r_users = mysql_fetch_assoc($q_users)){
|
||
$usersIds[] = (int)$r_users['id'];
|
||
}
|
||
|
||
$sql_wazz = "SELECT id, fio FROM clients WHERE (id_agent in (".implode(',', $usersIds).") or who_work in (".implode(',', $usersIds).")) and phone LIKE '%" . $data->telephone . "%' LIMIT 1";
|
||
|
||
echo $sql_wazz;
|
||
|
||
$q_wazz = mysql_query($sql_wazz);
|
||
if (mysql_num_rows($q_wazz) > 0) {
|
||
$wazzapData = mysql_fetch_assoc($q_wazz);
|
||
$fio = $wazzapData['fio'];
|
||
$clientId = $wazzapData['id'];
|
||
}
|
||
|
||
if ($clientId && $fio) {
|
||
|
||
$sql_wazz = "SELECT * FROM client_data_wazzap WHERE chat_id = '$data->chatId' and client_id = " . $clientId;
|
||
$q_wazz = mysql_query($sql_wazz);
|
||
if (mysql_num_rows($q_wazz) <= 0) {
|
||
|
||
$post = [];
|
||
|
||
$post["wazzap_chat_type"] = $data->chatType;
|
||
$post["wazzap_chat_id"] = $data->chatId;
|
||
$post["wazzap_channel_id"] = $data->channelId;
|
||
$post["wazzap_user_id"] = $data->userId;
|
||
$post["wazzap_integration_id"] = $data->integrationId;
|
||
$post["fio"] = $fio;
|
||
|
||
Clients::createClientWazzapData($clientId, $post);
|
||
}
|
||
}
|
||
}
|
||
|
||
exit();
|
||
}
|
||
|
||
//Получение клиента
|
||
if($request == 'get_client_id'){
|
||
$id = $data->id;
|
||
$agency_id = $data->agency_id;
|
||
|
||
$agencyId = User::getUserAgencyID();
|
||
|
||
$usersIds = array();
|
||
$usersIds[] = $agencyId;
|
||
$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 = mysql_query($sql_users);
|
||
while($r_users = mysql_fetch_assoc($q_users)){
|
||
$usersIds[] = (int)$r_users['id'];
|
||
}
|
||
|
||
$sqlCheck = "SELECT `id` FROM `clients` WHERE id = $id and (id_agent in (".implode(',', $usersIds).") or who_work in (".implode(',', $usersIds)."))";
|
||
|
||
$qCheck = mysql_query($sqlCheck);
|
||
|
||
if (mysql_num_rows($qCheck) > 0) {
|
||
$client = new Clients();
|
||
$res = $client->get_client_id($id, $agency_id);
|
||
echo json_encode($res);
|
||
}
|
||
exit();
|
||
}
|
||
|
||
//Получение объета
|
||
if($request == 'get_object'){
|
||
$objectId = $data->object_id;
|
||
$res = array();
|
||
$sql_obj = "SELECT objects.*,
|
||
rayon.rayon,
|
||
DATE_FORMAT(objects.date_add,'%d.%m.%Y %H:%i') as date_add,
|
||
prices.prep_price as prep_price,
|
||
prices.start_price as start_price,
|
||
prices.fact_price as fact_price
|
||
FROM objects objects
|
||
LEFT JOIN rayon rayon on objects.rayon = rayon.id
|
||
LEFT JOIN sp_metro sp_metro on objects.id = sp_metro.id_obj
|
||
LEFT JOIN object_prices prices on objects.id = prices.object_id
|
||
WHERE objects.id = $objectId
|
||
GROUP BY objects.id";
|
||
|
||
$q_obj = $pdo->query($sql_obj);
|
||
if($pdo->num_rows($q_obj) > 0){
|
||
$obj = $pdo->fetch_assoc($q_obj);
|
||
$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 = $obj[id] ORDER BY oop.sort_order";
|
||
$rezPhotoInfo = $pdo->query($sqlPhotoInfo);
|
||
|
||
if ($pdo->num_rows($rezPhotoInfo) > 0) {
|
||
while ($photoInfo = $pdo->fetch_assoc($rezPhotoInfo)) {
|
||
$obj['photo' . $photoInfo['sort_order']] = $photoInfo['photo'];
|
||
}
|
||
}
|
||
|
||
list($dateAdd, $timeAdd) = explode(" ", $obj['date_add']);
|
||
list($d, $m, $y) = explode(".", $dateAdd);
|
||
$date_add = $d." ".getRusMonth($m)." ".$y;
|
||
$date = $date_add." ".$timeAdd;
|
||
$obj['date'] = $date;
|
||
$obj['disct'] = '';
|
||
if($obj['peshkom']) $obj['disct'] .= $obj['peshkom']." минут пешком";
|
||
if($obj['peshkom'] and $obj['transport']) $obj['disct'] .= " или ";
|
||
if($obj['transport']) $obj['disct'] .= $obj['transport']." минут на транспорте";
|
||
$res = $obj;
|
||
}
|
||
echo json_encode($res);
|
||
exit();
|
||
}
|
||
|
||
//Получение объета
|
||
if($request == 'get_objects_ids'){
|
||
error_reporting(E_ALL | E_STRICT);
|
||
ini_set('display_errors', 1);
|
||
|
||
$objectsId = $data->objects_id;
|
||
$res = array();
|
||
$sql_obj = "SELECT *
|
||
FROM objects
|
||
WHERE id in (".implode(',',$objectsId).")";
|
||
|
||
$q_obj = $pdo->query($sql_obj);
|
||
if($pdo->num_rows($q_obj) > 0){
|
||
while ($obj = $pdo->fetch_assoc($q_obj)){
|
||
|
||
|
||
$res[] = $obj;
|
||
}
|
||
}
|
||
echo json_encode($res);
|
||
exit();
|
||
}
|
||
|
||
if($request == 'get_object_prices') {
|
||
$userId = $data->user_id;
|
||
$objectId = $data->object_id;
|
||
$agencyId = User::getUserAgencyID();
|
||
$sql = "SELECT * FROM `object_prices` WHERE `object_id` = '$objectId' AND `agency_id` = '$agencyId' LIMIT 1";
|
||
$query = $pdo->query($sql);
|
||
if ($pdo->num_rows($query)) {
|
||
$res = $pdo->fetch_assoc($query);
|
||
echo json_encode($res);
|
||
exit();
|
||
}
|
||
}
|
||
|
||
if($request == 'get_objects'){
|
||
$userId = $data->user_id;
|
||
$objects = [];//json_decode(html_entity_decode($_POST['get_clients_objects']), true);
|
||
if ($userId) {
|
||
if (empty($objects)) {
|
||
$sql_obj = "SELECT objects.*, DATE_FORMAT(objects.date_add,'%d.%m.%Y %H:%i') as date_add FROM objects objects WHERE id_add_user = {$userId} ORDER BY UNIX_TIMESTAMP(objects.date_add) DESC";
|
||
} else {
|
||
$sql_obj = "SELECT objects.*, DATE_FORMAT(objects.date_add,'%d.%m.%Y %H:%i') as date_add FROM objects objects WHERE id_add_user = {$userId} or objects.id in (" . implode(', ', $objects) . ") ORDER BY UNIX_TIMESTAMP(objects.date_add) DESC";
|
||
}
|
||
// echo $sql_obj;
|
||
$q_obj = $pdo->query($sql_obj);
|
||
$count_obj = $pdo->num_rows($q_obj);
|
||
|
||
$activeRent = "";
|
||
$activeSell = "";
|
||
$archiveRent = "";
|
||
$archiveSell = "";
|
||
if ($count_obj > 0) {
|
||
while ($obj = $pdo->fetch_assoc($q_obj)) {
|
||
|
||
if ($obj['archive'] == 1) {
|
||
if ($obj['operation_type'] == 1) {
|
||
$archiveSell = $archiveSell . '<option icon="1" value="' . $obj['id'] . '">' . $obj['nazv'] . ' ' . $obj['adres'] . '</option>';
|
||
} else {
|
||
$archiveRent = $archiveRent . '<option icon="1" value="' . $obj['id'] . '">' . $obj['nazv'] . ' ' . $obj['adres'] . '</option>';
|
||
}
|
||
} else {
|
||
if ($obj['operation_type'] == 1) {
|
||
$activeSell = $activeSell . '<option icon="1" value="' . $obj['id'] . '">' . $obj['nazv'] . ' ' . $obj['adres'] . '</option>';
|
||
} else {
|
||
$activeRent = $activeRent . '<option icon="1" value="' . $obj['id'] . '">' . $obj['nazv'] . ' ' . $obj['adres'] . '</option>';
|
||
}
|
||
}
|
||
}
|
||
}
|
||
echo '<select id="req-new-object">';
|
||
|
||
echo "<optgroup><option value=0>Не выбран</option></optgroup>";
|
||
if ($activeRent) {
|
||
echo "<optgroup label='Активные-Аренд'>";
|
||
echo $activeRent;
|
||
echo "</optgroup>";
|
||
}
|
||
if ($activeSell) {
|
||
echo "<optgroup label='Активные-Продажа'>";
|
||
echo $activeSell;
|
||
echo "</optgroup>";
|
||
}
|
||
if ($archiveRent) {
|
||
echo "<optgroup label='Архивные-Аренда'>";
|
||
echo $archiveRent;
|
||
echo "</optgroup>";
|
||
}
|
||
if ($archiveSell) {
|
||
echo "<optgroup label='Архивные-Продажа'>";
|
||
echo $archiveSell;
|
||
echo "</optgroup>";
|
||
}
|
||
echo "</select>";
|
||
}
|
||
}
|
||
|
||
//Найденный объект
|
||
if($request == 'get_objects_find'){
|
||
$object_id = $data->object_id;
|
||
$sql_obj = "SELECT id, nazv, adres FROM objects objects WHERE id=$object_id";
|
||
$q_obj = $pdo->query($sql_obj);
|
||
$r_obj = $pdo->fetch_assoc($q_obj);
|
||
$res = array('id'=>$r_obj['id'], 'nazv'=>$r_obj['nazv'], 'adres'=>$r_obj['adres']);
|
||
echo json_encode($res);
|
||
exit();
|
||
}
|
||
|
||
//Фильтр по умолчанию
|
||
if($request == 'get_filtr'){
|
||
$user_id = $data->user_id;
|
||
$funnel_id = $data->funnel_id;
|
||
$req = new Requisitions($pdo);
|
||
$res = $req->get_filtr($user_id, $funnel_id);
|
||
echo json_encode($res);
|
||
exit();
|
||
}
|
||
|
||
//Получение типов заявок
|
||
if($request == 'get_type'){
|
||
/* error_reporting(E_ALL | E_STRICT);
|
||
ini_set('display_errors', 1);*/
|
||
$req = new Requisitions($pdo);
|
||
$setting = false;
|
||
$active = false;
|
||
$no_archive = false;
|
||
if(isset($data->setting)){
|
||
$setting = $data->setting;
|
||
}
|
||
if(isset($data->agency_id)){
|
||
$req->set_agencyId($data->agency_id);
|
||
}
|
||
if(isset($data->active)){
|
||
$active = true;
|
||
}
|
||
if(isset($data->no_archive)){
|
||
$no_archive = true;
|
||
}
|
||
$res = $req->get_type($setting,$active,$no_archive);
|
||
echo json_encode($res);
|
||
exit();
|
||
|
||
}
|
||
|
||
//Смена очереди
|
||
if($request == 'set_type_order'){
|
||
/*error_reporting(E_ALL | E_STRICT);
|
||
ini_set('display_errors', 1);*/
|
||
$id = (int)$data->id;
|
||
$sort_order = (int)$data->sort_order;
|
||
$direct = $data->direct;
|
||
$req = new Requisitions($pdo);
|
||
if(isset($data->agency_id)){
|
||
$req->set_agencyId($data->agency_id);
|
||
}
|
||
$res = $req->set_type_order($id, $sort_order, $direct);
|
||
|
||
echo json_encode($res);
|
||
exit();
|
||
}
|
||
|
||
//Редактирование/добавление типа
|
||
if($request == 'edit_add_type')
|
||
{
|
||
/* error_reporting(E_ALL | E_STRICT);
|
||
ini_set('display_errors', 1);*/
|
||
$result = array();
|
||
$agency_id = (int)$data->agency_id;
|
||
$user_id = (int)$data->user_id;
|
||
$id = (int)$data->id;
|
||
$type = $data->type;
|
||
$heir = $data->heir;
|
||
$order = $data->order;
|
||
$type_type = $data->type_type;
|
||
|
||
$req = new Requisitions($pdo);
|
||
$req->set_agencyId($agency_id);
|
||
$req->set_userId($user_id);
|
||
$result = $req->editAddType($id, $type, $heir, $order, $type_type);
|
||
|
||
echo json_encode($result, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
}
|
||
|
||
//Удаление типа заявки
|
||
if($request == 'del_type_req')
|
||
{
|
||
$result = array();
|
||
$agency_id = (int)$data->agency_id;
|
||
$user_id = (int)$data->user_id;
|
||
$id = (int)$data->id;
|
||
|
||
if($id > 0){
|
||
$req = new Requisitions($pdo);
|
||
$req->set_agencyId($agency_id);
|
||
$req->set_userId($user_id);
|
||
$result = $req->deletedType($id);
|
||
}
|
||
echo json_encode($result, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
}
|
||
|
||
//Архивирование типа заявки
|
||
if($request == 'archive_type_req')
|
||
{
|
||
$result = array();
|
||
$agency_id = (int)$data->agency_id;
|
||
$user_id = (int)$data->user_id;
|
||
$id = (int)$data->id;
|
||
$order = $data->order;
|
||
|
||
if($id > 0){
|
||
$req = new Requisitions($pdo);
|
||
$req->set_agencyId($agency_id);
|
||
$req->set_userId($user_id);
|
||
$result = $req->archiveType($id, $order);
|
||
}
|
||
echo json_encode($result, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
}
|
||
|
||
//Архивирование типа заявки
|
||
if($request == 'recover_type_req')
|
||
{
|
||
$result = array();
|
||
$agency_id = (int)$data->agency_id;
|
||
$user_id = (int)$data->user_id;
|
||
$id = (int)$data->id;
|
||
$order = $data->order;
|
||
|
||
if($id > 0){
|
||
$req = new Requisitions($pdo);
|
||
$req->set_agencyId($agency_id);
|
||
$req->set_userId($user_id);
|
||
$result = $req->recoverType($id, $order);
|
||
}
|
||
echo json_encode($result, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
}
|
||
|
||
//Установка причин закрытия
|
||
if($request == 'set_type_denial'){
|
||
$type_id = (int)$data->type_id;
|
||
$agency_id = (int)$data->agency_id;
|
||
$denial_id = (int)$data->denial_id;
|
||
$check = (int)$data->check;
|
||
$req = new Requisitions($pdo);
|
||
// echo $agency_id;
|
||
$req->set_agencyId($agency_id);
|
||
$req->set_type_denial($type_id, $denial_id, $check);
|
||
}
|
||
|
||
//Список причин
|
||
if($request == 'get_denials'){
|
||
$result = array();
|
||
$agency_id = (int)$data->agency_id;
|
||
$req = new Requisitions($pdo);
|
||
$req->set_agencyId($agency_id);
|
||
$result = $req->get_denial_work(1);
|
||
echo json_encode($result, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
}
|
||
|
||
|
||
//Редактирование причин закрытия
|
||
if($request == 'edit_denial'){
|
||
/*error_reporting(E_ALL | E_STRICT);
|
||
ini_set('display_errors', 1);*/
|
||
$result = array();
|
||
$agency_id = (int)$data->agency_id;
|
||
// $user_id = (int)$data->user_id;
|
||
$id = (int)$data->id;
|
||
$name = $data->name;
|
||
$req = new Requisitions($pdo);
|
||
$req->set_agencyId($agency_id);
|
||
// $req->set_userId($user_id);
|
||
$result = $req->editAddDenial($id, $name);
|
||
|
||
echo json_encode($result, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
}
|
||
|
||
//Удаление причины
|
||
if($request == 'del_denial'){
|
||
$result = array();
|
||
$agency_id = (int)$data->agency_id;
|
||
// $user_id = (int)$data->user_id;
|
||
$id = (int)$data->id;
|
||
|
||
$req = new Requisitions($pdo);
|
||
$req->set_agencyId($agency_id);
|
||
// $req->set_userId($user_id);
|
||
$result = $req->deleteDenial($id);
|
||
|
||
echo json_encode($result, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
|
||
}
|
||
|
||
//Подсчет количества заявок или клиентов
|
||
if($request == 'confirmation_total_item'){
|
||
/* error_reporting(E_ALL | E_STRICT);
|
||
ini_set('display_errors', 1);*/
|
||
$result = 0;
|
||
$razdel = $data->razdel;
|
||
$ids = array();
|
||
if(isset($data->ids_exception)){
|
||
$ids = $data->ids_exception;
|
||
}
|
||
$sql = '';
|
||
if($razdel == 'req'){
|
||
$sql = $_SESSION['where_req_campaigns'];
|
||
if (!empty($ids)){
|
||
$sql .= " AND ID NOT IN (".implode(',', $ids).")";
|
||
}
|
||
}
|
||
//echo $sql;
|
||
if($razdel == 'client'){
|
||
$where = $_SESSION['where_campaigns'];
|
||
$sql = "SELECT * FROM clients WHERE 1 ".$where;
|
||
}
|
||
|
||
if($sql != ''){
|
||
$q = $pdo->query($sql, true);
|
||
$rezult = $pdo->num_rows($q);
|
||
}
|
||
|
||
echo $rezult;
|
||
exit();
|
||
}
|
||
|
||
//Общая передача заявок
|
||
if ($request == 'confirm_reqs') {
|
||
/*error_reporting(E_ALL | E_STRICT);
|
||
ini_set('display_errors', 1);*/
|
||
$reqs = json_decode($data->reqs_id);
|
||
$user_id = $data->user_id;
|
||
$new_who_work = $data->who_work;
|
||
$all = $data->all;
|
||
$ids = array();
|
||
if(isset($data->ids_exception)){
|
||
$ids = $data->ids_exception;
|
||
}
|
||
|
||
|
||
$sql = "SELECT * FROM requisitions WHERE id in (".implode(',', $reqs).")";
|
||
if($all == 1){
|
||
if(isset($_SESSION['where_req_campaigns'])){
|
||
$sql = $_SESSION['where_req_campaigns'];
|
||
if (!empty($ids)){
|
||
$sql .= " AND ID NOT IN (".implode(',', $ids).")";
|
||
}
|
||
} else {
|
||
exit();
|
||
}
|
||
}
|
||
$q = $pdo->query($sql);
|
||
|
||
while($r = $pdo->fetch_assoc($q)) {
|
||
$confirm = 0;
|
||
if ($new_who_work == $user_id) {
|
||
$confirm = 1;
|
||
}
|
||
if ($r['who_work'] != $new_who_work) {
|
||
if (!$pdo->query("UPDATE requisitions SET who_work='{$new_who_work}', confirm={$confirm} WHERE id=".$r['id'])){
|
||
echo "error: ";
|
||
}
|
||
if ($confirm == 1) {
|
||
$sqlup = "UPDATE user_client_events SET user_id=".$new_who_work." WHERE req_id=".$r['id']." and `type` != 'step' and `type` != 'file'";
|
||
$rez = $pdo->query($sqlup);
|
||
} else if ($confirm == 0) {
|
||
$sql_conf = "INSERT INTO `events_clients` (`user_id`, `req_id`, `from_id`, `event`) VALUES (".$user_id.", ".$r['id'].", ".$new_who_work.", 'transmitted')";
|
||
//echo $sql_conf."\n";
|
||
$pdo->query($sql_conf);
|
||
if($new_who_work == 0){
|
||
$pdo->query("UPDATE requisitions SET deleted=0 WHERE id=".$r['id']);
|
||
$dop_text = "Переведена в общие";
|
||
$sql_ev = "INSERT INTO events_clients (req_id, event, dop_text, user_id) VALUES ({$r['id']}, 'update', '{$dop_text}', {$user_id})";
|
||
$pdo->query($sql_ev);
|
||
}
|
||
}
|
||
}
|
||
|
||
// Определяем историю как просмотренную, чтобы сбросить счётчик (если пользователь не открывал её перед передачей другому сотруднику)
|
||
$sql_up = "UPDATE `events_clients` SET `viewed` = 1 WHERE `req_id` = ".$r['id']." AND `user_id` = '$user_id' AND `from_id` = '$user_id' AND (`event` = 'accepted' OR `event` = 'accepted_doer')";
|
||
$pdo->query($sql_up);
|
||
}
|
||
}
|
||
|
||
// Передача закрытых заявок другому сотруднику
|
||
if ($request == 'transfer_closed_reqs') {
|
||
/*error_reporting(E_ALL | E_STRICT);
|
||
ini_set('display_errors', 1);*/
|
||
|
||
$reqs = $data->reqs_id;
|
||
$user_id = (int)$_SESSION['id'];
|
||
$new_who_work = (int)$data->to_user_id;
|
||
$all = (int)$data->all;
|
||
$ids = array();
|
||
if(isset($data->ids_exception)){
|
||
$ids = $data->ids_exception;
|
||
}
|
||
|
||
// Проверка прав: только админ, менеджер или с правом `on_can_transfer_closed_to_others`
|
||
$sql_check_permissions = "SELECT `menu_can_transfer_closed_to_others`, `daily_closed_transfer_limit`, `actual_daily_closed_transfers`
|
||
FROM user_permissions WHERE user_id = $user_id";
|
||
$q_check_permissions = $pdo->query($sql_check_permissions);
|
||
$r_check_permissions = $pdo->fetch_assoc($q_check_permissions);
|
||
|
||
if (!$_SESSION['users_admin'] && !$_SESSION['agency'] && $r_check_permissions['menu_can_transfer_closed_to_others'] != 1) {
|
||
echo json_encode([
|
||
'success' => false,
|
||
'error' => 'Недостаточно прав для передачи закрытых заявок.',
|
||
'debug' => [
|
||
'is_admin' => $_SESSION['users_admin'],
|
||
'is_agency' => $_SESSION['agency'],
|
||
'can_transfer_closed' => $r_check_permissions['menu_can_transfer_closed_to_others'],
|
||
'user_id' => $user_id
|
||
]
|
||
]);
|
||
exit();
|
||
}
|
||
|
||
// Проверка лимита (если не админ)
|
||
if (!$_SESSION['users_admin'] && !$_SESSION['agency']) {
|
||
$daily_limit = (int)$r_check_permissions['daily_closed_transfer_limit'];
|
||
$actual_transfer = (int)$r_check_permissions['actual_daily_closed_transfers'];
|
||
|
||
if ($actual_transfer >= $daily_limit) {
|
||
echo json_encode(['success' => false, 'error' => "Превышен дневной лимит передачи закрытых заявок: {$daily_limit} шт."]);
|
||
exit();
|
||
}
|
||
}
|
||
|
||
if($all == 1){
|
||
if(isset($_SESSION['where_req_campaigns'])){
|
||
$sql = $_SESSION['where_req_campaigns'] . " AND deleted = 1";
|
||
if (!empty($ids)){
|
||
$sql .= " AND ID NOT IN (".implode(',', $ids).")";
|
||
}
|
||
} else {
|
||
echo json_encode(['success' => false, 'error' => 'Ошибка фильтрации.']);
|
||
exit();
|
||
}
|
||
} else {
|
||
if (empty($reqs)) {
|
||
echo json_encode([
|
||
'success' => false,
|
||
'error' => 'Список заявок для передачи пуст.'
|
||
]);
|
||
exit();
|
||
}
|
||
|
||
$sql = "SELECT * FROM requisitions
|
||
WHERE id IN (" . implode(',', $reqs) . ") AND deleted = 1
|
||
ORDER BY FIELD(id, " . implode(',', $reqs) . ")";
|
||
}
|
||
|
||
$q = $pdo->query($sql);
|
||
$transferred_count = 0;
|
||
|
||
$remaining_limit = (int)$r_check_permissions['daily_closed_transfer_limit'] - (int)$r_check_permissions['actual_daily_closed_transfers'];
|
||
|
||
// ФИО отправителя
|
||
$sql_sender = "SELECT last_name, first_name, middle_name FROM users WHERE id = $user_id LIMIT 1";
|
||
$q_sender = $pdo->query($sql_sender);
|
||
$r_sender = $pdo->fetch_assoc($q_sender);
|
||
$sender_fio = $r_sender ? trim("{$r_sender['last_name']} {$r_sender['first_name']} {$r_sender['middle_name']}") : "Неизвестный пользователь";
|
||
|
||
// ФИО получателя
|
||
$sql_recipient = "SELECT last_name, first_name, middle_name FROM users WHERE id = $new_who_work LIMIT 1";
|
||
$q_recipient = $pdo->query($sql_recipient);
|
||
$r_recipient = $pdo->fetch_assoc($q_recipient);
|
||
$recipient_fio = $r_recipient ? trim("{$r_recipient['last_name']} {$r_recipient['first_name']} {$r_recipient['middle_name']}") : "Неизвестный пользователь";
|
||
|
||
while($r = $pdo->fetch_assoc($q)) {
|
||
|
||
if (!$_SESSION['users_admin'] && !$_SESSION['agency'] && $remaining_limit <= 0) {
|
||
break;
|
||
}
|
||
|
||
if ($r['funnel_id'] > 0) {
|
||
$sql_update = "UPDATE requisitions SET who_work = {$new_who_work}, deleted = 0, step_id = 1 WHERE id = {$r['id']}";
|
||
} else {
|
||
$sql_update = "UPDATE requisitions SET who_work = {$new_who_work}, deleted = 0, stage = 1 WHERE id = {$r['id']}";
|
||
}
|
||
|
||
if ($pdo->query($sql_update)) {
|
||
$transferred_count++;
|
||
|
||
// Логируем событие
|
||
$dop_text = "Закрытая заявка передана в работу сотруднику {$recipient_fio} сотрудником {$sender_fio}";
|
||
$sql_log = "INSERT INTO events_clients (req_id, event, dop_text, user_id, from_id, `read`)
|
||
VALUES ({$r['id']}, 'transfer_closed', '" . mysql_real_escape_string($dop_text) . "', {$new_who_work}, {$user_id}, 1)";
|
||
$pdo->query($sql_log);
|
||
|
||
// Обновляем счётчик лимита (если не админ)
|
||
if (!$_SESSION['users_admin'] && !$_SESSION['agency']) {
|
||
$sql_update_limit = "UPDATE user_permissions
|
||
SET actual_daily_closed_transfers = actual_daily_closed_transfers + 1
|
||
WHERE user_id = {$user_id}";
|
||
$pdo->query($sql_update_limit);
|
||
$remaining_limit--;
|
||
}
|
||
}
|
||
}
|
||
|
||
$not_transferred = count($reqs) - $transferred_count;
|
||
|
||
$message = "Успешно передано {$transferred_count} заявок.";
|
||
if ($not_transferred > 0) {
|
||
$message .= " {$not_transferred} заявок не были переданы из-за ограничения.";
|
||
}
|
||
|
||
echo json_encode([
|
||
'success' => true,
|
||
'message' => $message,
|
||
'transferred_count' => $transferred_count,
|
||
'notification_data' => [
|
||
'sender_user_id' => $user_id,
|
||
'recipient_user_id' => $new_who_work,
|
||
'transferred_req_ids' => $reqs,
|
||
'transferred_count' => $transferred_count,
|
||
'all' => $all,
|
||
'ids_exception' => $ids,
|
||
'actual_after' => !$_SESSION['users_admin'] && !$_SESSION['agency'] ? ((int)$r_check_permissions['actual_daily_closed_transfers'] + $transferred_count) : null,
|
||
'limit_after' => !$_SESSION['users_admin'] && !$_SESSION['agency'] ? (int)$r_check_permissions['daily_closed_transfer_limit'] : null,
|
||
]
|
||
]);
|
||
exit();
|
||
}
|
||
|
||
if ($request == 'send_transfer_closed_notifications') {
|
||
$sender_user_id = (int)$data->sender_user_id;
|
||
$recipient_user_id = (int)$data->recipient_user_id;
|
||
$transferred_req_ids = $data->transferred_req_ids; // array
|
||
$all = (int)$data->all;
|
||
$ids_exception = isset($data->ids_exception) ? $data->ids_exception : [];
|
||
$actual_after = isset($data->actual_after) ? (int)$data->actual_after : null;
|
||
$limit_after = isset($data->limit_after) ? (int)$data->limit_after : null;
|
||
|
||
$sql_sender = "SELECT CONCAT(last_name, ' ', first_name, ' ', middle_name) as fio FROM users WHERE id = $sender_user_id LIMIT 1";
|
||
$result_sender = $pdo->query($sql_sender);
|
||
$sender_data = $pdo->fetch_assoc($result_sender);
|
||
$sender_fio = isset($sender_data['fio']) ? $sender_data['fio'] : 'Сотрудник';
|
||
|
||
$sql_recipient = "SELECT telegramm_chat_id, max_user_id, max_notice CONCAT(last_name, ' ', first_name, ' ', middle_name) as fio FROM users WHERE id = $recipient_user_id LIMIT 1";
|
||
$result_recipient = $pdo->query($sql_recipient);
|
||
$recipient = $pdo->fetch_assoc($result_recipient);
|
||
|
||
$transferred_count = isset($data->transferred_count) ? (int)$data->transferred_count : count($transferred_req_ids);
|
||
|
||
// ID переданных заявок для уведомления (если <= 10)
|
||
$transferred_req_ids_for_msg = [];
|
||
if ($transferred_count <= 10) {
|
||
$sql_ids = "SELECT id FROM requisitions WHERE who_work = $recipient_user_id AND id IN (" . implode(',', $transferred_req_ids) . ") AND deleted = 0 ORDER BY id DESC LIMIT 10";
|
||
if ($all == 1 && isset($_SESSION['where_req_campaigns'])) {
|
||
$sql_ids = $_SESSION['where_req_campaigns'] . " AND deleted = 0 AND who_work = $recipient_user_id ORDER BY id DESC LIMIT 10";
|
||
if (!empty($ids_exception)) {
|
||
$sql_ids .= " AND ID NOT IN (" . implode(',', $ids_exception) . ")";
|
||
}
|
||
}
|
||
$q_ids = $pdo->query($sql_ids);
|
||
while ($row_id = $pdo->fetch_assoc($q_ids)) {
|
||
$transferred_req_ids_for_msg[] = $row_id['id'];
|
||
}
|
||
}
|
||
|
||
// Уведомление новому ответственному (с ID, если <= 10, без ID если > 10)
|
||
if ($recipient && !empty($recipient['telegramm_chat_id']) && $recipient['telegramm_chat_id'] > 0) {
|
||
$message_to_recipient = "Сотрудник {$sender_fio} передал вам ";
|
||
|
||
if ($transferred_count == 1) {
|
||
$message_to_recipient .= "1 заявку из Закрытых";
|
||
} else {
|
||
$message_to_recipient .= "{$transferred_count} заявки из Закрытых";
|
||
}
|
||
|
||
// Добавляем ID, только если их <= 10
|
||
if ($transferred_count <= 10 && !empty($transferred_req_ids_for_msg)) {
|
||
$message_to_recipient .= ": " . implode(', ', $transferred_req_ids_for_msg);
|
||
}
|
||
|
||
$tel = new Telegram(false);
|
||
try {
|
||
$tel->send($message_to_recipient, $recipient['telegramm_chat_id']);
|
||
} catch (Exception $e) {
|
||
file_put_contents(__DIR__ . '/debug_telegram.txt', "Telegram error: " . $e->getMessage() . "\n", FILE_APPEND);
|
||
}
|
||
}
|
||
// Уведомление новому ответственному (с ID, если <= 10, без ID если > 10) в макс
|
||
if ($recipient && !empty($recipient['max_user_id']) && $recipient['max_user_id'] > 0 && $recipient['max_notice'] > 0) {
|
||
$message_to_recipient = "Сотрудник {$sender_fio} передал вам ";
|
||
|
||
if ($transferred_count == 1) {
|
||
$message_to_recipient .= "1 заявку из Закрытых";
|
||
} else {
|
||
$message_to_recipient .= "{$transferred_count} заявки из Закрытых";
|
||
}
|
||
|
||
// Добавляем ID, только если их <= 10
|
||
if ($transferred_count <= 10 && !empty($transferred_req_ids_for_msg)) {
|
||
$message_to_recipient .= ": " . implode(', ', $transferred_req_ids_for_msg);
|
||
}
|
||
|
||
$max = new MaxClass();
|
||
try {
|
||
$max->send_messages_to_user($recipient['max_user_id'], $message_to_recipient);
|
||
} catch (Exception $e) {
|
||
file_put_contents(__DIR__ . '/debug_max.txt', "Max error: " . $e->getMessage() . "\n", FILE_APPEND);
|
||
}
|
||
}
|
||
|
||
|
||
// Уведомление директору/админу, если лимит исчерпан
|
||
if ($actual_after !== null && $limit_after !== null && $actual_after >= $limit_after) {
|
||
$send_agency_id = (int)$_SESSION['agency_id'];
|
||
$sql_admin = "SELECT telegramm_chat_id FROM users WHERE id = $send_agency_id AND telegramm_chat_id > 0 LIMIT 1";
|
||
$result_admin = $pdo->query($sql_admin);
|
||
$admin = $pdo->fetch_assoc($result_admin);
|
||
|
||
if ($admin && !empty($admin['telegramm_chat_id'])) {
|
||
$message_to_admin = "Сотрудник {$sender_fio} передал за сегодня {$actual_after} заявок из Закрытых";
|
||
|
||
$tel = new Telegram(false);
|
||
try {
|
||
$tel->send($message_to_admin, $admin['telegramm_chat_id']);
|
||
} catch (Exception $e) {
|
||
file_put_contents(__DIR__ . '/debug_telegram.txt', "Telegram error: " . $e->getMessage() . "\n", FILE_APPEND);
|
||
}
|
||
|
||
|
||
// Логирование для отладки
|
||
file_put_contents(__DIR__ . '/debug_telegram.txt', date('Y-m-d H:i:s') . " | Админ уведомлен: {$admin['telegramm_chat_id']} | Сообщение: {$message_to_admin}\n", FILE_APPEND);
|
||
} else {
|
||
file_put_contents(__DIR__ . '/debug_telegram.txt', date('Y-m-d H:i:s') . " | Админ не найден или нет chat_id\n", FILE_APPEND);
|
||
}
|
||
}
|
||
|
||
// Уведомление директору/админу, если лимит исчерпан в макс
|
||
if ($actual_after !== null && $limit_after !== null && $actual_after >= $limit_after) {
|
||
$send_agency_id = (int)$_SESSION['agency_id'];
|
||
$sql_admin = "SELECT max_user_id FROM users WHERE id = $send_agency_id AND max_user_id > 0 AND max_notice > 0 LIMIT 1";
|
||
$result_admin = $pdo->query($sql_admin);
|
||
$admin = $pdo->fetch_assoc($result_admin);
|
||
|
||
if ($admin && !empty($admin['max_user_id'])) {
|
||
$message_to_admin = "Сотрудник {$sender_fio} передал за сегодня {$actual_after} заявок из Закрытых";
|
||
|
||
$max = new MaxClass();
|
||
try {
|
||
$max->send_messages_to_user($admin['max_user_id'], $message_to_admin);
|
||
} catch (Exception $e) {
|
||
file_put_contents(__DIR__ . '/debug_max.txt', "Max error: " . $e->getMessage() . "\n", FILE_APPEND);
|
||
}
|
||
|
||
|
||
// Логирование для отладки
|
||
file_put_contents(__DIR__ . '/debug_max.txt', date('Y-m-d H:i:s') . " | Админ уведомлен: {$admin['max_user_id']} | Сообщение: {$message_to_admin}\n", FILE_APPEND);
|
||
} else {
|
||
file_put_contents(__DIR__ . '/debug_max.txt', date('Y-m-d H:i:s') . " | Админ не найден или нет max_user_id\n", FILE_APPEND);
|
||
}
|
||
}
|
||
|
||
echo json_encode(['success' => true, 'message' => 'Уведомления отправлены']);
|
||
exit();
|
||
}
|
||
|
||
//Общий прием заявок
|
||
if ($request == 'confirm_on_reqs') {
|
||
/*error_reporting(E_ALL | E_STRICT);
|
||
ini_set('display_errors', 1);*/
|
||
$reqs = $data->reqs_id;
|
||
$user_id = $data->user_id;
|
||
$all = $data->all;
|
||
$ids = array();
|
||
if(isset($data->ids_exception)){
|
||
$ids = $data->ids_exception;
|
||
}
|
||
//$new_who_work = $data->who_work;
|
||
|
||
$sql = "SELECT * FROM requisitions WHERE id in (".implode(',', $reqs).")";
|
||
if($all == 1){
|
||
if(isset($_SESSION['where_req_campaigns'])){
|
||
$sql = $_SESSION['where_req_campaigns'];
|
||
if (!empty($ids)){
|
||
$sql .= " AND ID NOT IN (".implode(',', $ids).")";
|
||
}
|
||
} else {
|
||
exit();
|
||
}
|
||
}
|
||
|
||
$q = $pdo->query($sql);
|
||
|
||
while($r = $pdo->fetch_assoc($q)) {
|
||
$confirm = 0;
|
||
if ($r['who_work'] == $user_id || $r['who_work'] == 0) {
|
||
$confirm = 1;
|
||
$sql = "UPDATE requisitions SET confirm=1, who_work=$user_id WHERE id=$r[id]";
|
||
$pdo->query($sql);
|
||
// echo $sql."\n";
|
||
|
||
$sql = "UPDATE user_client_events SET user_id=$user_id WHERE req_id=$r[id] and type != 'step' and type != 'file'";
|
||
$pdo->query($sql);
|
||
//echo $sql."\n";
|
||
$sql = "UPDATE `events_clients` set `read` = 1, date_update='".date('Y-m-d H:i:s')."' WHERE req_id=$r[id] and from_id = ".$user_id;
|
||
//echo $sql."\n";
|
||
$pdo->query($sql);
|
||
|
||
$accepted = 'accepted';
|
||
$sql = "INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`) VALUES ('".$user_id."', '".$r['id']."', '".$user_id."', '".$accepted."', '1')";
|
||
//echo $sql."\n";
|
||
$pdo->query($sql);
|
||
|
||
$sql_step = "SELECT * FROM clients_funnel_step WHERE req_id = {$r['id']}";
|
||
$q_step = $pdo->query($sql_step);
|
||
if($pdo->num_rows($q_step) > 0){
|
||
$sql_op_step = "UPDATE clients_funnel_step SET date_update = NOW() WHERE req_id = {$r['id']}";
|
||
$pdo->query($sql_op_step);
|
||
} else {
|
||
|
||
if($r['funnel_id'] > 0){
|
||
$pdo->query("INSERT INTO clients_funnel_step (req_id) VALUES ({$r['id']})");
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
|
||
}
|
||
}
|
||
|
||
//Общий прием клиентов
|
||
if ($request == 'confirm_on_clients') {
|
||
/*error_reporting(E_ALL | E_STRICT);
|
||
ini_set('display_errors', 1);*/
|
||
|
||
$clients = $data->clients_id;
|
||
$user_id = $data->user_id;
|
||
$all = $data->all;
|
||
$new_who_work = $data->who_work;
|
||
$sql = "SELECT * FROM clients WHERE id in (".implode(',', $clients).")";
|
||
if($all == 1){
|
||
if(isset($_SESSION['where_campaigns'])){
|
||
$where = $_SESSION['where_campaigns'];
|
||
$sql = "SELECT * FROM clients WHERE 1 ".$where;
|
||
} else {
|
||
exit();
|
||
}
|
||
}
|
||
|
||
$q = $pdo->query($sql);
|
||
|
||
while($r = $pdo->fetch_assoc($q)) {
|
||
$confirm = 0;
|
||
if ($r['who_work'] == $user_id || $r['who_work'] == 0) {
|
||
$confirm = 1;
|
||
$sql = "UPDATE clients SET confirm=1, who_work=$user_id WHERE id=$r[id]";
|
||
$pdo->query($sql);
|
||
//echo $sql."\n";
|
||
|
||
$sql = "UPDATE user_client_events SET user_id=$user_id WHERE client_id=$r[id] and type != 'step' and type != 'file'";
|
||
$pdo->query($sql);
|
||
//echo $sql."\n";
|
||
$sql = "UPDATE `events_clients` set `read` = 1, date_update='".date('Y-m-d H:i:s')."' WHERE client_id=$r[id] and from_id = ".$user_id;
|
||
// echo $sql."\n";
|
||
$pdo->query($sql);
|
||
|
||
$accepted = 'accepted';
|
||
$sql = "INSERT INTO `events_clients` (user_id, client_id, from_id, event, `read`) VALUES ('".$user_id."', '".$r['id']."', '".$user_id."', '".$accepted."', '1')";
|
||
// echo $sql."\n";
|
||
$pdo->query($sql);
|
||
|
||
$sql_step = "SELECT * FROM clients_funnel_step WHERE client_id = {$r['id']}";
|
||
$q_step = $pdo->query($sql_step);
|
||
if($pdo->num_rows($q_step) > 0){
|
||
$sql_op_step = "UPDATE clients_funnel_step SET date_update = NOW() WHERE client_id = {$r['id']}";
|
||
$pdo->query($sql_op_step);
|
||
} else {
|
||
|
||
if($r['funnel_id'] > 0){
|
||
$pdo->query("INSERT INTO clients_funnel_step (client_id) VALUES ({$r['id']})");
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
|
||
}
|
||
}
|
||
|
||
|
||
//Общая смена воронок
|
||
if($request == 'funnel_check') {
|
||
$reqs = json_decode($data->reqs_id);
|
||
$funnel_chech = $data->funnel_check;
|
||
|
||
$all = $data->all;
|
||
$ids = array();
|
||
if(isset($data->ids_exception)){
|
||
$ids = $data->ids_exception;
|
||
}
|
||
|
||
|
||
|
||
if($all == 1){
|
||
$reqs = array();
|
||
if(isset($_SESSION['where_req_campaigns'])){
|
||
$sql = $_SESSION['where_req_campaigns'];
|
||
if (!empty($ids)){
|
||
$sql .= " AND ID NOT IN (".implode(',', $ids).")";
|
||
}
|
||
$q = $pdo->query($sql);
|
||
while($r = $pdo->fetch_assoc($q)) {
|
||
$reqs[] = $r['id'];
|
||
}
|
||
} else {
|
||
exit();
|
||
}
|
||
}
|
||
|
||
|
||
$req = new Requisitions($pdo);
|
||
foreach($reqs as $req_id){
|
||
$req->updateFunnel($funnel_chech, $req_id);
|
||
}
|
||
}
|
||
|
||
//Смена воронки
|
||
if($request == 'funnel_change'){
|
||
$req_id = (int)$data->req_id;
|
||
$funnel_new = (int)$data->new_funnel_id;
|
||
$req = new Requisitions($pdo);
|
||
$req->updateFunnel($funnel_new, $req_id);
|
||
}
|
||
|
||
//Переименование клиента
|
||
if ($request == 'change_client_name') {
|
||
$new_client_name = $data->new_client_name;
|
||
$client_id = $data->client_id;
|
||
|
||
$agencyId = User::getUserAgencyID();
|
||
|
||
$usersIds = array();
|
||
$usersIds[] = $agencyId;
|
||
$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 = mysql_query($sql_users);
|
||
while($r_users = mysql_fetch_assoc($q_users)){
|
||
$usersIds[] = (int)$r_users['id'];
|
||
}
|
||
|
||
$sqlCheck = "SELECT `id` FROM `clients` WHERE id = $client_id and (id_agent in (".implode(',', $usersIds).") or who_work in (".implode(',', $usersIds)."))";
|
||
|
||
$qCheck = mysql_query($sqlCheck);
|
||
|
||
if (mysql_num_rows($qCheck) > 0) {
|
||
|
||
$sql = "UPDATE `clients` SET
|
||
`fio` = '$new_client_name'
|
||
WHERE `id` = '$client_id'";
|
||
|
||
echo json_encode([
|
||
'success' => $pdo->query($sql)
|
||
]);
|
||
}
|
||
exit();
|
||
}
|
||
|
||
//Добавление доп. телефона
|
||
if ($request == 'change_client_phone') {
|
||
$new_client_phone = $data->new_client_phone;
|
||
$client_id = (int)$data->client_id;
|
||
|
||
$agencyId = $data->agency_id;
|
||
|
||
// Защита: если у пользователя скрыты контакты, не позволяем перезаписать телефон
|
||
// маской/пустым значением. "Реальным" считаем телефон с минимум 4 цифрами.
|
||
if (function_exists('should_hide_contacts_for_current_user') && should_hide_contacts_for_current_user()) {
|
||
$rawPhone = is_string($new_client_phone) ? trim($new_client_phone) : '';
|
||
$digitsCount = preg_match_all('/\d/', $rawPhone, $m);
|
||
if ($digitsCount < 4) {
|
||
// Пользователь со скрытыми контактами отправил пустое/маску — не меняем БД
|
||
echo json_encode(array(
|
||
'success' => 'done',
|
||
'unchanged' => true,
|
||
));
|
||
exit();
|
||
}
|
||
}
|
||
|
||
if($client_id > 0 && $agencyId > 0 && !empty($new_client_phone)){
|
||
|
||
$usersIds = array();
|
||
$usersIds[] = $agencyId;
|
||
$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 = mysql_query($sql_users);
|
||
while($r_users = mysql_fetch_assoc($q_users)){
|
||
$usersIds[] = (int)$r_users['id'];
|
||
}
|
||
|
||
$sqlCheck = "SELECT `id` FROM `clients` WHERE (phone='$new_client_phone' OR id in (SELECT client_id FROM clients_phone2 WHERE phone = '$new_client_phone')) and (id_agent in (".implode(',', $usersIds).") or who_work in (".implode(',', $usersIds)."))";
|
||
|
||
|
||
$qCheck = mysql_query($sqlCheck);
|
||
|
||
if (mysql_num_rows($qCheck) > 0) {
|
||
|
||
$clintsIds = [];
|
||
while($rCheck = mysql_fetch_assoc($qCheck)){
|
||
$clintsIds[] = $rCheck['id'];
|
||
}
|
||
|
||
echo json_encode([
|
||
'success' => 'error',
|
||
'client' => $clintsIds
|
||
]);
|
||
} else {
|
||
$sql_dop = "INSERT INTO clients_phone2 (client_id, phone) VALUES ({$client_id}, '{$new_client_phone}')";
|
||
if(!mysql_query($sql_dop)){
|
||
echo json_encode([
|
||
'success' => mysql_errno(),
|
||
]);
|
||
} else {
|
||
$phones2 = [];
|
||
$sql_phones = "SELECT * FROM clients_phone2 WHERE client_id = {$client_id}";
|
||
$q_phones = mysql_query($sql_phones);
|
||
while($r_phones = mysql_fetch_assoc($q_phones)){
|
||
$phones2[] = $r_phones['phone'];
|
||
}
|
||
if(!empty($phones2)){
|
||
$p2 = htmlentities(json_encode($phones2));
|
||
$sql_cl = "UPDATE clients SET phone2='$p2' WHERE id={$client_id}";
|
||
$pdo->query($sql_cl);
|
||
}
|
||
echo json_encode([
|
||
'success' => 'done',
|
||
'sql' => $sql_cl,
|
||
]);
|
||
}
|
||
}
|
||
} else {
|
||
echo json_encode([
|
||
'success' => 'empty_data',
|
||
]);
|
||
}
|
||
exit();
|
||
}
|
||
|
||
//Сохранение тегов
|
||
if($request == 'save_activites') {
|
||
$req_id = (int)$data->req_id;
|
||
$activites = $data->activities;
|
||
if($req_id > 0){
|
||
$pdo->query("DELETE FROM requisitions_activities WHERE req_id = {$req_id}");
|
||
foreach($activites as $a){
|
||
$sql_in = "INSERT INTO requisitions_activities SET req_id = {$req_id}, activity_id={$a}";
|
||
$pdo->query($sql_in);
|
||
}
|
||
}
|
||
}
|
||
|
||
//получение договоров
|
||
if($request == 'get_contracts'){
|
||
$agency = new User;
|
||
$agency->checkPermissions();
|
||
$parent_id = $data->parent_id;
|
||
$parent_type = $data->type;
|
||
$parent = null;
|
||
$id = 0;
|
||
if($parent_type == 'req'){
|
||
$table = 'contracts_req';
|
||
$id = (int)str_replace('req', '', $parent_id);
|
||
$parent = 'req_id';
|
||
} else if ($parent_type == 'client') {
|
||
$table = 'contracts_client';
|
||
$id = (int)$parent_id;
|
||
$parent = 'client_id';
|
||
} else if ($parent_type == 'object') {
|
||
$table = 'contracts_object';
|
||
$id = (int)$parent_id;
|
||
$parent = 'object_id';
|
||
}
|
||
$contract = new Contract($pdo);
|
||
$contract->setAgencyId($agency->agencyId);
|
||
|
||
$typesContracs = $contract->getTypesName();
|
||
|
||
$result['contracts'] = array();
|
||
$result['contracts_name'] = '';
|
||
if($id > 0){
|
||
$sql = "SELECT * FROM $table WHERE {$parent} = {$id}";
|
||
$q = $pdo->query($sql);
|
||
while($r = $pdo->fetch_assoc($q)){
|
||
$name = $typesContracs[$r['type']]['type']." №".$r['number']." от ".date('d.m.Y',$r['date_start']). " по ".date('d.m.Y', $r['date_end']);
|
||
$expired = false;
|
||
$diff_date = ($r['date_end'] - time())/86400;
|
||
if($diff_date < (int)$r['days']){
|
||
$expired = true;
|
||
}
|
||
$result['contracts'][] = array('id'=>$r['id'], 'name'=>$name, 'expired'=>$expired);
|
||
if($result['contracts_name'] != '') $result['contracts_name'] .= ", ";
|
||
$result['contracts_name'] .= $name;
|
||
}
|
||
}
|
||
echo json_encode($result, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
|
||
}
|
||
|
||
//Поиск клиента по id заявки
|
||
if($request == 'get_clientid_req'){
|
||
$result = array();
|
||
$result['client_id'] = 0;
|
||
$req_id = 0;
|
||
if(isset($data->req_id)){
|
||
$req_id = (int)$data->req_id;
|
||
}
|
||
if($req_id > 0){
|
||
$sql = "SELECT client_id FROM requisitions WHERE id = {$req_id}";
|
||
$q = $pdo->query($sql);
|
||
if($r = $pdo->fetch_assoc($q)){
|
||
$client_id = (int)$r['client_id'];
|
||
$result['client_id'] = $client_id;
|
||
}
|
||
}
|
||
echo json_encode($result, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
}
|
||
|
||
|
||
//Клиенты
|
||
if($request == 'get_clients_list'){
|
||
$search = $data->search;
|
||
$searchUserId = $_SESSION['id'];
|
||
$adminDep = false;
|
||
|
||
$depClass = new Department();
|
||
$dep_user = $depClass->getDepartment((int)$_SESSION['id']);
|
||
|
||
$sql_check_permissions = "SELECT `menu_all_clients`, `menu_all_clients_edit` FROM user_permissions WHERE user_id = {$searchUserId}";
|
||
$q_check_permissions = mysql_query($sql_check_permissions);
|
||
$r_check_permissions = mysql_fetch_assoc($q_check_permissions);
|
||
|
||
// Определяем searchUserId по логике из первого примера
|
||
if ($_SESSION['users_admin']) {
|
||
$currentUser = new User;
|
||
$currentUser->checkPermissions();
|
||
$searchUserId = $currentUser->agencyId;
|
||
} else if ($r_check_permissions['menu_all_clients'] == 1) {
|
||
$currentUser = new User;
|
||
$currentUser->checkPermissions();
|
||
$searchUserId = $currentUser->agencyId;
|
||
} else if($dep_user['role'] == 'manager_office'){
|
||
$currentUser = new User;
|
||
$currentUser->checkPermissions();
|
||
$searchUserId = $dep_user['admin'];
|
||
$adminDep = true;
|
||
} else if($dep_user['role'] == 'manager_office_menager') {
|
||
$searchUserId = $_SESSION['id_manager'];
|
||
$adminDep = true;
|
||
}
|
||
|
||
|
||
$agencyId = User::getUserAgencyID();
|
||
|
||
$clients_all = array();
|
||
|
||
// Проверяем точное совпадение по телефону (без учета иерархии)
|
||
if(!empty($search)) {
|
||
$phone_clean = preg_replace('/[\(\)\-\s]/', '', $search);
|
||
|
||
$sql_exact_phone = "SELECT c.`id`, c.fio, c.email, c.phone, c.objects, c.deleted, c.confirm
|
||
FROM clients c
|
||
WHERE c.cancel=0 AND c.phone = '" . mysql_real_escape_string($phone_clean) . "'
|
||
AND (c.id_agent IN (WITH RECURSIVE user_tree AS (SELECT id FROM users WHERE id = {$agencyId}
|
||
UNION SELECT u.id FROM users u INNER JOIN user_tree ut ON u.id_manager = ut.id) SELECT id FROM user_tree)
|
||
OR c.who_work IN (WITH RECURSIVE user_tree AS (SELECT id FROM users WHERE id = {$agencyId} UNION SELECT u.id FROM users u INNER JOIN user_tree ut ON u.id_manager = ut.id) SELECT id FROM user_tree))
|
||
LIMIT 1";
|
||
|
||
$q_exact_phone = mysql_query($sql_exact_phone);
|
||
$exact_match = mysql_fetch_assoc($q_exact_phone);
|
||
|
||
if($exact_match) {
|
||
// Маскируем контактные данные клиента, если у пользователя включено скрытие
|
||
mask_client_contacts_inplace($exact_match);
|
||
|
||
$res['id'] = $exact_match['id'];
|
||
$res['color'] = '#000';
|
||
if($exact_match['deleted'] == 1){
|
||
$res['color'] = '#dd6360';
|
||
if($exact_match['confirm'] == 10){
|
||
$res['color'] = '#43A047';
|
||
}
|
||
}
|
||
|
||
$res['name'] = $exact_match['phone'].' '.$exact_match['fio'];
|
||
$res['fio'] = $exact_match['fio'];
|
||
|
||
if(!empty($exact_match['email'])){
|
||
$res['name'] = $exact_match['phone'].' '.$exact_match['fio'].' ('.$exact_match['email'].')';
|
||
}
|
||
|
||
$res['phones_dop'] = '';
|
||
|
||
$sql_cl2 = "SELECT phone FROM `clients_phone2` WHERE client_id = {$exact_match['id']}";
|
||
$q_cl2 = $pdo->query($sql_cl2);
|
||
while($r_cl2 = $pdo->fetch_assoc($q_cl2)){
|
||
if($res['phones_dop'] != '') $res['phones_dop'] .= ', ';
|
||
$res['phones_dop'] .= mask_phone_value_if_needed($r_cl2['phone']);
|
||
}
|
||
|
||
$clients_all[] = $res;
|
||
echo json_encode($clients_all, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
}
|
||
}
|
||
|
||
|
||
|
||
$bd_usl_managers = '';
|
||
$arrIdUser = array();
|
||
$usersId = array();
|
||
$usersPlan = array();
|
||
$wid = array();
|
||
|
||
// Получаем всех пользователей, которые относятся к searchUserId
|
||
$sql_users = "SELECT id FROM users WHERE id in (select id from users where id=$searchUserId or id_manager=$searchUserId or id_manager in
|
||
(select id from users where id_manager=$searchUserId or id_manager in
|
||
(select id from users where id_manager=$searchUserId)))";
|
||
|
||
$q_users = $pdo->query($sql_users);
|
||
while($r_users = $pdo->fetch_assoc($q_users)){
|
||
$usersIds[] = (int)$r_users['id'];
|
||
}
|
||
$usersIds = array_unique($usersIds);
|
||
|
||
foreach($usersIds as $mm2) {
|
||
$arrIdUser[] = $mm2;
|
||
//$wid[] = "doers like '%"".$mm2."":1%'";
|
||
|
||
}
|
||
|
||
$bd_usl_managers = " AND (who_work in (".implode(",",$arrIdUser).") or id_agent in (".implode(",",$arrIdUser)."))";
|
||
if(!empty($wid)){
|
||
$bd_usl_managers = " AND ((".implode(" OR ",$arrIdUser).") or (".implode(" OR ",$wid)."))";
|
||
}
|
||
|
||
// Формируем SQL запрос
|
||
$sql = "SELECT `id`, fio, email, phone, objects, deleted, confirm FROM clients WHERE cancel=0 $bd_usl_managers order by deleted limit 30";
|
||
if(!empty($search)){
|
||
$phone = preg_replace('/[+\-\(\)\/\?,.;:%№!\s]/', '', $search);
|
||
$sql = "SELECT `id`, fio, email, phone, objects, deleted, confirm FROM clients WHERE cancel=0 $bd_usl_managers AND (fio like '%{$search}%' or phone like '%{$phone}%' or email like '%{$search}%') order by deleted limit 20";
|
||
}
|
||
|
||
$clients_all = array();
|
||
$q = $pdo->query($sql);
|
||
while($r = $pdo->fetch_assoc($q)){
|
||
// Маскируем контактные данные клиента, если у пользователя включено скрытие
|
||
mask_client_contacts_inplace($r);
|
||
|
||
$res['id'] = $r['id'];
|
||
$res['color'] = '#000';
|
||
if($r['deleted'] == 1){
|
||
$res['color'] = '#dd6360';
|
||
if($r['confirm'] == 10){
|
||
$res['color'] = '#43A047';
|
||
}
|
||
}
|
||
|
||
$res['name'] = $r['phone'].' '.$r['fio'];
|
||
$res['fio'] = $r['fio'];
|
||
|
||
if(!empty($r['email'])){
|
||
$res['name'] = $r['phone'].' '.$r['fio'].' ('.$r['email'].')';
|
||
}
|
||
|
||
$res['phones_dop'] = '';
|
||
|
||
$sql_cl2 = "SELECT phone FROM `clients_phone2` WHERE client_id = {$r['id']}";
|
||
$q_cl2 = $pdo->query($sql_cl2);
|
||
while($r_cl2 = $pdo->fetch_assoc($q_cl2)){
|
||
if($res['phones_dop'] != '') $res['phones_dop'] .= ', ';
|
||
$res['phones_dop'] .= mask_phone_value_if_needed($r_cl2['phone']);
|
||
}
|
||
|
||
$clients_all[] = $res;
|
||
}
|
||
|
||
echo json_encode($clients_all, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
}
|
||
|
||
//Типы недвижимости
|
||
if($request == 'get_property_types'){
|
||
$result = array();
|
||
$sql = "SELECT * FROM `property_types`";
|
||
$q = $pdo->query($sql);
|
||
while($r = $pdo->fetch_assoc($q)){
|
||
$result[] = array('id'=>$r['id'], 'name'=>$r['name']);
|
||
}
|
||
echo json_encode($result, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
}
|
||
|
||
//Заявки для объединения
|
||
if($request == 'get_union_reqs') {
|
||
$result = array();
|
||
$reqs = $data->reqs;
|
||
$agency_id = $data->agency_id;
|
||
$user_id = $data->user_id;
|
||
if($agency_id > 0 && $user_id > 0 && !empty($reqs)){
|
||
$req = new Requisitions($pdo, true);
|
||
$req->set_agencyId($agency_id);
|
||
$req->set_userId($user_id);
|
||
$result = $req->get_union_reqs($reqs);
|
||
}
|
||
|
||
echo json_encode($result, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
|
||
}
|
||
|
||
//Сохранение объединения заявок
|
||
if($request == 'save_union_req'){
|
||
$main_id = $data->main_id;
|
||
$reqs = $data->reqs;
|
||
$user_id = (int)$data->user_id;
|
||
$agency_id = (int)$data->agency_id;
|
||
|
||
if($user_id > 0 && !empty($reqs) && $main_id > 0){
|
||
$req = new Requisitions($pdo, true);
|
||
$req->set_agencyId($agency_id);
|
||
$req->set_userId($user_id);
|
||
$result = $req->save_union_reqs($reqs, $main_id);
|
||
}
|
||
|
||
echo json_encode($result, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
}
|
||
|
||
//Список присоединенных заявок
|
||
if($request == 'get_reqs_joint'){
|
||
$result = array();
|
||
$req_id = (int)$data->req_id;
|
||
if($req_id > 0){
|
||
$sql = "SELECT * FROM union_requisitions WHERE main_id = {$req_id}";
|
||
$q = $pdo->query($sql);
|
||
while($r = $pdo->fetch_assoc($q)){
|
||
$result[] = (int)$r['req_id'];
|
||
}
|
||
}
|
||
echo json_encode($result, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
}
|
||
|
||
if ($request == 'mass_take_from_closed') {
|
||
$reqs = $data->reqs_id;
|
||
$user_id = $data->user_id;
|
||
$ids = array();
|
||
if(isset($data->ids_exception)){
|
||
$ids = $data->ids_exception;
|
||
}
|
||
//$new_who_work = $data->who_work;
|
||
|
||
$sql = "SELECT * FROM requisitions WHERE id in (".implode(',', $reqs).")";
|
||
|
||
$q = $pdo->query($sql);
|
||
|
||
while($r = $pdo->fetch_assoc($q)) {
|
||
$confirm = 0;
|
||
if ($r['who_work'] == $user_id || $r['who_work'] == 0) {
|
||
$confirm = 1;
|
||
$sql = "UPDATE requisitions SET confirm=1, who_work=$user_id WHERE id=$r[id]";
|
||
$pdo->query($sql);
|
||
// echo $sql."\n";
|
||
|
||
$sql = "UPDATE user_client_events SET user_id=$user_id WHERE req_id=$r[id] and type != 'step' and type != 'file'";
|
||
$pdo->query($sql);
|
||
//echo $sql."\n";
|
||
$sql = "UPDATE `events_clients` set `read` = 1, date_update='".date('Y-m-d H:i:s')."' WHERE req_id=$r[id] and from_id = ".$user_id;
|
||
//echo $sql."\n";
|
||
$pdo->query($sql);
|
||
|
||
$accepted = 'accepted';
|
||
$sql = "INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`) VALUES ('".$user_id."', '".$r['id']."', '".$user_id."', '".$accepted."', '1')";
|
||
//echo $sql."\n";
|
||
$pdo->query($sql);
|
||
|
||
$sql_step = "SELECT * FROM clients_funnel_step WHERE req_id = {$r['id']}";
|
||
$q_step = $pdo->query($sql_step);
|
||
if($pdo->num_rows($q_step) > 0){
|
||
$sql_op_step = "UPDATE clients_funnel_step SET date_update = NOW() WHERE req_id = {$r['id']}";
|
||
$pdo->query($sql_op_step);
|
||
} else {
|
||
|
||
if($r['funnel_id'] > 0){
|
||
$pdo->query("INSERT INTO clients_funnel_step (req_id) VALUES ({$r['id']})");
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
|
||
}
|
||
}
|
||
|
||
if($request == 'get_view_page'){
|
||
|
||
$user_id = (int)$data->user_id;
|
||
$viewPage = 'list';
|
||
$sql_view = "SELECT * FROM user_views_page WHERE user_id = {$user_id}";
|
||
|
||
|
||
$q_view = $pdo->query($sql_view);
|
||
if($pdo->num_rows($q_view) > 0){
|
||
$r_view = $pdo->fetch_assoc($q_view);
|
||
$viewPage = (!empty($r_view['view_req'])) ? $r_view['view_req'] : 'list';
|
||
}
|
||
echo json_encode(array('view'=>$viewPage), JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
}
|
||
|
||
/**
|
||
* Сохранение настроек вида страницы
|
||
*
|
||
*/
|
||
if($request == 'set_view_page'){
|
||
$user_id = (int)$data->user_id;
|
||
$view = $data->view;
|
||
|
||
$sql = "SELECT * FROM user_views_page WHERE user_id = {$user_id}";
|
||
$q = $pdo->query($sql);
|
||
if($pdo->num_rows($q) > 0){
|
||
$r = $pdo->fetch_assoc($q);
|
||
$sql_up = "UPDATE user_views_page SET view_req = '{$view}' WHERE id = {$r['id']}";
|
||
$pdo->query($sql_up);
|
||
} else {
|
||
$sql_in = "INSERT INTO user_views_page (user_id, view_req) values ({$user_id}, '{$view}')";
|
||
$pdo->query($sql_in);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Финансы
|
||
*/
|
||
if($request == 'req_finance_info'){
|
||
$is_block = false;
|
||
$html = '';
|
||
$req_id = (int)$data->req_id;
|
||
$expected_commission = 0;
|
||
$deposit = 0;
|
||
$nameEventDeposit = 'Аванс';
|
||
$idEventDeposit = 0;
|
||
$expenses = array();
|
||
$expensesTotal = 0;
|
||
$sql = "SELECT id, summa, deleted, expected_commission, confirm FROM requisitions WHERE id={$req_id}";
|
||
$q = $pdo->query($sql);
|
||
$r = $pdo->fetch_assoc($q);
|
||
|
||
if($r['deleted'] == 0 || ($r['deleted'] == 1 && $r['confirm'] == 10)){
|
||
if($r['expected_commission'] > 0){
|
||
$is_block = true;
|
||
$expected_commission = (float)$r['expected_commission'];
|
||
}
|
||
|
||
$sql_d = "SELECT id, deposit, step_id FROM deposits_clients_req WHERE req_id = {$req_id}";
|
||
$q_d = $pdo->query($sql_d);
|
||
$r_d = $pdo->fetch_assoc($q_d);
|
||
|
||
if($r_d['deposit'] > 0){
|
||
$is_block = true;
|
||
$deposit = (int)$r_d['deposit'];
|
||
$idEventDeposit = (int)$r_d['id'];
|
||
$sql_step = "SELECT * FROM `funnel_steps` WHERE id = {$r_d['step_id']}";
|
||
$q_step = $pdo->query($sql_step);
|
||
$r_step = $pdo->fetch_assoc($q_step);
|
||
|
||
$pole_end_list = json_decode(htmlspecialchars_decode($r_step['pole_end_list']), true);
|
||
|
||
foreach($pole_end_list as $pole){
|
||
if($pole['type'] == 'Задаток'){
|
||
$nameEventDeposit = $pole['name'];
|
||
}
|
||
}
|
||
}
|
||
|
||
$sql_ex = "SELECT * FROM expenses_req WHERE req_id = {$req_id}";
|
||
$q_ex = $pdo->query($sql_ex);
|
||
if($pdo->num_rows($q_ex) > 0){
|
||
$is_block = true;
|
||
$steps_ids = array();
|
||
$steps = array();
|
||
while($r_ex = $pdo->fetch_assoc($q_ex)){
|
||
$expenses[] = $r_ex;
|
||
$steps_ids[] = (int)$r_ex['step_id'];
|
||
}
|
||
|
||
if(!empty($steps_ids)){
|
||
$sql_step = "SELECT * FROM `funnel_steps` WHERE id in (".implode(',', $steps_ids).")";
|
||
$q_step = $pdo->query($sql_step);
|
||
while($r_step = $pdo->fetch_assoc($q_step)){
|
||
|
||
$pole_end_list = json_decode(htmlspecialchars_decode($r_step['pole_end_list']), true);
|
||
|
||
foreach($pole_end_list as $pole){
|
||
if($pole['type'] == 'Расходы'){
|
||
$steps[$r_step['id']] = $pole['name'];
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
foreach($expenses as $key => $expense){
|
||
$nameExpense = 'Расходы';
|
||
if(isset($steps[$expense['step_id']])){
|
||
$nameExpense = $steps[$expense['step_id']];
|
||
}
|
||
$expenses[$key]['name'] = $nameExpense;
|
||
$expensesTotal += $expense['amount'];
|
||
}
|
||
}
|
||
|
||
|
||
if($is_block){
|
||
if($expected_commission > 0){
|
||
|
||
if($r['deleted'] == 0) {
|
||
$html .= '<p>';
|
||
$html .= 'Ожидаемая комиссия '.$expected_commission;
|
||
|
||
$html .= '<a id="edit_expected_commission_req" title="Редактировать" href="javascript:{}" style="display: inline-block; margin: 0px 5px; border-bottom: none"><i class="ti-pencil"></i></a>';
|
||
|
||
$html .= '<input id="edit_expected_commission_req_input" type="number" value="'.$expected_commission.'" class="text" style="width: 160px; display:none; margin-left: 5px;">';
|
||
$html .= '<a data-id="'.$req_id.'" id="edit_expected_commission_req_save" href="javascript:{};" title="Сохранить" style="padding: 6px 8px; border: none; line-height: 34px;display:none"><i class="ti-save"></i></a>';
|
||
$html .= '</p>';
|
||
}
|
||
|
||
}
|
||
|
||
if($r['deleted'] == 1 && $r['confirm'] == 10){
|
||
$summa = (int)$r['summa'];
|
||
$html .= '<p>Фактическая комиссия '.$summa.'</p>';
|
||
}
|
||
|
||
if($deposit > 0){
|
||
$html .= '<p>'.$nameEventDeposit.' '.$deposit;
|
||
if($r['deleted'] == 0) {
|
||
$html .= '<a id="edit_deposit_req" title="Редактировать" href="javascript:{}" style="display: inline-block; margin: 0px 5px; border-bottom: none"><i class="ti-pencil"></i></a>';
|
||
$html .= '<input id="edit_deposit_req_input" type="number" value="'.$deposit.'" class="text" style="width: 160px; display:none; margin-left: 5px;">';
|
||
$html .= '<a data-id="'.$req_id.'" data-deposit="'.$idEventDeposit.'" id="edit_deposit_req_save" href="javascript:{};" title="Сохранить" style="padding: 6px 8px; border: none; line-height: 34px;display:none"><i class="ti-save"></i></a>';
|
||
}
|
||
$html .= '</p>';
|
||
}
|
||
|
||
if($expected_commission > 0 && $r['deleted'] == 0){
|
||
$surcharge = $expected_commission - $deposit;
|
||
$html .= '<p>Доплата '.$surcharge.'</p>';
|
||
|
||
}
|
||
|
||
if($expensesTotal > 0){
|
||
$html .= '<p><a id="toggle_block_expenses" href="javascript:{};">Расходы '.$expensesTotal.'</a></p>';
|
||
$html .= '<div id="div_toggle_block_expenses" style="display:none">';
|
||
foreach($expenses as $key => $expense){
|
||
$amount = rtrim(rtrim($expense['amount'], '0'), '.');
|
||
$html .= '<p>'.$expense['name'].' '.$amount.' Комментарий: '.$expense['comment'];
|
||
if($r['deleted'] == 0){
|
||
$html .= '<a data-id="'.$expense['id'].'" id="edit_expense_req_'.$expense['id'].'" class="edit_expense_req" title="Редактировать" href="javascript:{}" style="display: inline-block; margin: 0px 5px; border-bottom: none"><i class="ti-pencil"></i></a>';
|
||
|
||
$html .= '<input id="edit_expense_req_input_'.$expense['id'].'" type="number" value="'.$amount.'" class="text" style="width: 160px; display:none; margin-left: 5px;">';
|
||
$html .= '<input title="'.$expense['comment'].'" class="text" style="width: 160px; display:none; margin-left: 5px;" rows="4" id="edit_expense_req_textarea_'.$expense['id'].'" value="'.$expense['comment'].'">';
|
||
$html .= '<a data-id="'.$req_id.'" data-expense="'.$expense['id'].'" id="edit_expense_req_save_'.$expense['id'].'" class="edit_expense_req_save" href="javascript:{};" title="Сохранить" style="padding: 6px 8px; border: none; line-height: 34px;display:none"><i class="ti-save"></i></a>';
|
||
}
|
||
$html .= '</p>';
|
||
}
|
||
$html .= '</div>';
|
||
}
|
||
}
|
||
}
|
||
|
||
$result = array('is_block'=>$is_block, 'html'=>$html);
|
||
echo json_encode($result, JSON_UNESCAPED_UNICODE);
|
||
exit;
|
||
}
|
||
|
||
/**
|
||
* Редактирование финансов
|
||
*/
|
||
if($request == 'edit_req_finance_info'){
|
||
$reqId = (int)$data->req_id;
|
||
$userId = (int)$data->user_id;
|
||
$depositId = 0;
|
||
if(isset($data->deposit_id)){
|
||
$depositId = (int)$data->deposit_id;
|
||
}
|
||
$expenseId = 0;
|
||
if(isset($data->expense_id)){
|
||
$expenseId = (int)$data->expense_id;
|
||
}
|
||
|
||
$comment = '';
|
||
if(isset($data->comment)){
|
||
$comment = $data->comment;
|
||
$result = preg_replace('/"([^"]*)"/', '«$1»', $comment);
|
||
$result = str_replace("\"", "", $result);
|
||
$result = str_replace("'", "’", $result);
|
||
$comment = $result;
|
||
}
|
||
|
||
$field = $data->field;
|
||
$value = $data->value;
|
||
$sql_req = "SELECT expected_commission, id, who_work FROM requisitions WHERE id = {$reqId}";
|
||
$q_req = $pdo->query($sql_req);
|
||
$r_req = $pdo->fetch_assoc($q_req);
|
||
|
||
if($field == 'expected_commission'){
|
||
$text_commission = '';
|
||
if ($r_req['expected_commission'] != $value) {
|
||
$text_commission = "Изменено: Ожидаемая комиссия с {$r_req['expected_commission']} на {$value}";
|
||
$sql_up = "UPDATE requisitions SET expected_commission = {$value} WHERE id = {$reqId}";
|
||
if($pdo->query($sql_up)) {
|
||
$sql_event = "INSERT INTO events_clients (user_id, from_id, req_id, `event`, dop_text, `read`) VALUES ({$userId}, {$userId}, {$reqId}, 'update', '{$text_commission}', 1)";
|
||
|
||
$pdo->query($sql_event);
|
||
}
|
||
}
|
||
}
|
||
|
||
if($field == 'deposit'){
|
||
$who_work = $userId;
|
||
$nameEvent = "Аванс";
|
||
if($r_req['who_work'] > 0){
|
||
$who_work = (int)$r_req['who_work'];
|
||
}
|
||
$sql_d = "SELECT id, deposit, step_id FROM deposits_clients_req WHERE id = {$depositId}";
|
||
$q_d = $pdo->query($sql_d);
|
||
$deposit = (int)$value;
|
||
if($pdo->num_rows($q_d) > 0){
|
||
$r_d = $pdo->fetch_assoc($q_d);
|
||
|
||
$sql_step = "SELECT * FROM `funnel_steps` WHERE id = {$r_d['step_id']}";
|
||
$q_step = $pdo->query($sql_step);
|
||
$r_step = $pdo->fetch_assoc($q_step);
|
||
|
||
$pole_end_list = json_decode(htmlspecialchars_decode($r_step['pole_end_list']), true);
|
||
|
||
foreach($pole_end_list as $pole){
|
||
if($pole['type'] == 'Задаток'){
|
||
$nameEvent = $pole['name'];
|
||
}
|
||
}
|
||
|
||
$id_d = (int)$r_d['id'];
|
||
|
||
$sql_up_d = "UPDATE deposits_clients_req SET deposit = {$deposit}, created_at= NOW(), user_id={$who_work} WHERE id = {$id_d}";
|
||
$pdo->query($sql_up_d);
|
||
|
||
if((int)$r_d['deposit'] != $deposit){
|
||
$text_deposit = "Изменено: {$nameEvent} с {$r_d['deposit']} на {$deposit}";
|
||
$sql_event = "INSERT INTO events_clients (user_id, from_id, req_id, `event`, dop_text, `read`) VALUES ({$userId}, {$userId}, {$reqId}, 'update', '{$text_deposit}', 1)";
|
||
|
||
$pdo->query($sql_event);
|
||
}
|
||
|
||
|
||
}
|
||
}
|
||
|
||
if($field == 'expense'){
|
||
$who_work = $userId;
|
||
$nameEvent = "Расходы";
|
||
|
||
$sql_d = "SELECT * FROM expenses_req WHERE id = {$expenseId}";
|
||
$q_d = $pdo->query($sql_d);
|
||
$expense = (int)$value;
|
||
if($pdo->num_rows($q_d) > 0){
|
||
$r_d = $pdo->fetch_assoc($q_d);
|
||
|
||
$sql_step = "SELECT * FROM `funnel_steps` WHERE id = {$r_d['step_id']}";
|
||
$q_step = $pdo->query($sql_step);
|
||
$r_step = $pdo->fetch_assoc($q_step);
|
||
|
||
$pole_end_list = json_decode(htmlspecialchars_decode($r_step['pole_end_list']), true);
|
||
|
||
foreach($pole_end_list as $pole){
|
||
if($pole['type'] == 'Расходы'){
|
||
$nameEvent = $pole['name'];
|
||
}
|
||
}
|
||
$sql_up_d = "UPDATE expenses_req SET amount = '{$expense}', comment = '{$comment}' WHERE id = {$expenseId}";
|
||
$pdo->query($sql_up_d);
|
||
|
||
if((int)$r_d['amount'] != $expense){
|
||
$text_expense = "Изменено: {$nameEvent} с {$r_d['amount']} на {$expense}";
|
||
if(!empty($comment)){
|
||
$text_expense .= " Добавлен комментарий: ".$comment;
|
||
}
|
||
$sql_event = "INSERT INTO events_clients (user_id, from_id, req_id, `event`, dop_text, `read`) VALUES ({$userId}, {$userId}, {$reqId}, 'update', '{$text_expense}', 1)";
|
||
|
||
$pdo->query($sql_event);
|
||
}
|
||
|
||
|
||
}
|
||
}
|
||
|
||
|
||
}
|
||
|
||
if($request == 'get_deal_by_req'){
|
||
$req_id = intval($data->req_id);
|
||
$sql = "SELECT id FROM deals WHERE status != 2 AND (side_one_requisition_id = $req_id OR side_two_requisition_id = $req_id) LIMIT 1";
|
||
$q = $pdo->query($sql);
|
||
$deal_id = null;
|
||
if($q && $pdo->num_rows($q) > 0){
|
||
$r = $pdo->fetch_assoc($q);
|
||
$deal_id = (int)$r['id'];
|
||
}
|
||
echo json_encode(['deal_id' => $deal_id]);
|
||
exit();
|
||
}
|
||
|
||
?>
|