2026-05-22 20:21:54 +02:00
< ? php
/**
* Description of Requisitions
*
* @ author iren
*/
class Requisitions {
private $user ;
private $roles_user = [ 'AGENCY' , 'AGENT' , 'MANAGER' ];
private $role_user ;
private $funnel_id = 0 ;
private $db = null ;
private $autosearch_instce = null ;
private $view = 'list' ;
private $limit = 10 ;
private $page = 1 ;
private $allPages = 0 ;
private $agencyId = 0 ;
private $user_id = 0 ;
public $steps = array (
0 => array ( 'id' => 1 , 'name' => 'Новый' , 'title' => 'Новый клиент' , 'classF' => 'stage-new' ),
1 => array ( 'id' => 2 , 'name' => 'В работе' , 'title' => 'В работе' , 'classF' => 'stage-work' ),
2 => array ( 'id' => 3 , 'name' => 'Презентация' , 'title' => 'Презентация' , 'classF' => 'stage-offer' ),
3 => array ( 'id' => 4 , 'name' => 'Показ' , 'title' => 'Показ' , 'classF' => 'stage-showing' ),
4 => array ( 'id' => 5 , 'name' => 'Бронь' , 'title' => 'Бронь' , 'classF' => 'stage-reservation' ),
5 => array ( 'id' => 6 , 'name' => 'Подаем на ипотеку' , 'title' => 'Подаем на ипотеку' , 'classF' => 'stage-meet' ),
6 => array ( 'id' => 7 , 'name' => 'Сделка' , 'title' => 'Сделка' , 'classF' => 'stage-deal' ),
7 => array ( 'id' => 8 , 'name' => 'Закрыт' , 'title' => 'Клиент закрыт' , 'classF' => 'stage-end' ),
);
private $funnels_adjacent = array ();
private $userIdsWork = array ();
public function __construct ( $db = null , $no_autosearch = false ){
if ( $db ){
$this -> db = $db ;
} else {
$pdo = new MysqlPdo ( hst , ndb , user , pass );
$sql = " SET NAMES 'utf8' " ;
$pdo -> query ( $sql );
$this -> db = $pdo ;
}
if ( ! $no_autosearch ){
$this -> autosearch_instce = new AutoSearch ( $this -> db );
}
}
//установка вида вывода
public function set_view ( $view ){
$this -> view = $view ;
}
//установка страницы
public function set_page ( $page ){
$this -> page = $page ;
}
// Установка кол-ва на страницу
public function set_per_page ( $per_page ) {
$this -> limit = intval ( $per_page );
}
//Установка id агентства
public function set_agencyId ( $agencyId ){
$this -> agencyId = $agencyId ;
}
//Установка пользователя
public function set_user ( $user ){
$this -> user = $user ;
if ( $user -> id > 0 ){
$this -> set_userId ( $user -> id );
}
if ( $user -> agencyId > 0 ){
$this -> set_agencyId ( $user -> agencyId );
}
}
//Установка user_id
public function set_userId ( $user_id ){
$this -> user_id = $user_id ;
}
//Получение типов заявки
public function get_type ( $settings = false , $active = false , $no_archive = false ){
$denial_typereq = array ();
$sql_d = " SELECT * FROM denial_typereq WHERE agency_id = { $this -> agencyId } " ;
$q_d = $this -> db -> query ( $sql_d );
while ( $r_d = $this -> db -> fetch_assoc ( $q_d )){
$denial_typereq [ $r_d [ 'type_id' ]][ $r_d [ 'denial_id' ]] = $r_d [ 'checked' ];
}
$denial = $this -> get_denial_work ();
$common = array ();
$temp_result = array ();
$archive_type = array ();
$result = array ();
$sql = " SELECT * FROM requisitions_type WHERE agency_id = 0 " ;
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q )){
$common [ $r [ 'id' ]] = $r ;
$result [ 'heir' ][] = array ( 'code' => $r [ 'id' ], 'name' => $r [ 'name' ]);
}
$sql = " SELECT * FROM requisitions_type WHERE agency_id = { $this -> agencyId } and del = 0 order by order_number, id " ;
/* if ( $active ){
$sql = " SELECT * FROM requisitions_type WHERE agency_id = { $this -> agencyId } and del = 0 order by order_number, id " ;
} */
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q )){
if ( $r [ 'parent_id' ] > 0 ){
$common [ $r [ 'parent_id' ]] = $r ;
} else {
$common [ $r [ 'id' ]] = $r ;
}
}
if ( ! $settings ){
$result [ 'type' ][] = array ( 'code' => 0 , 'name' => '' , 'order' =>- 1 , 'heir' => 0 , 'archive' => 0 , 'type' => 'label' , 'agency_id' => $this -> agencyId );
}
foreach ( $common as $key => $type ){
$order [ $key ][] = $type [ 'order_number' ];
if ( $type [ 'del' ] == 0 ){
if ( $settings ){
// var_dump($denial_typereq);
$denial_this_type = array ();
foreach ( $denial as $id_d => $d ){
if ( isset ( $denial_typereq [ $type [ 'id' ]][ $d [ 'id' ]])){
$d [ 'check' ] = $denial_typereq [ $type [ 'id' ]][ $d [ 'id' ]];
}
$denial_this_type [ $id_d ] = $d ;
}
if ( $type [ 'archive' ] == 0 ){
$result [ 'type' ][] = array ( 'code' => $type [ 'id' ], 'order' => $type [ 'order_number' ], 'type' => $type [ 'type' ], 'heir' => $type [ 'heir' ], 'name' => $type [ 'name' ], 'agency_id' => $type [ 'agency_id' ], 'denial' => $denial_this_type );
} else {
$result [ 'type_archive' ][] = array ( 'code' => $type [ 'id' ], 'order' => $type [ 'order_number' ], 'type' => $type [ 'type' ], 'heir' => $type [ 'heir' ], 'name' => $type [ 'name' ], 'agency_id' => $type [ 'agency_id' ], 'denial' => $denial_this_type );
}
} else {
if ( $active ){
if ( $type [ 'archive' ] == 0 ){
if ( $type [ 'parent_id' ] > 0 ){
$result [ 'type' ][] = array ( 'code' => $type [ 'parent_id' ], 'type' => $type [ 'type' ], 'order' => $type [ 'order_number' ], 'heir' => $type [ 'heir' ], 'name' => $type [ 'name' ], 'agency_id' => $type [ 'agency_id' ], 'archive' => $type [ 'archive' ]);
} else {
$result [ 'type' ][] = array ( 'code' => $type [ 'id' ], 'type' => $type [ 'type' ], 'order' => $type [ 'order_number' ], 'heir' => $type [ 'heir' ], 'name' => $type [ 'name' ], 'agency_id' => $type [ 'agency_id' ], 'archive' => $type [ 'archive' ]);
}
} else {
if ( $type [ 'parent_id' ] > 0 ){
$archive_type [] = array ( 'code' => $type [ 'parent_id' ], 'type' => $type [ 'type' ], 'order' => $type [ 'order_number' ], 'heir' => $type [ 'heir' ], 'name' => $type [ 'name' ], 'agency_id' => $type [ 'agency_id' ], 'archive' => $type [ 'archive' ]);
} else {
$archive_type [] = array ( 'code' => $type [ 'id' ], 'type' => $type [ 'type' ], 'order' => $type [ 'order_number' ], 'heir' => $type [ 'heir' ], 'name' => $type [ 'name' ], 'agency_id' => $type [ 'agency_id' ], 'archive' => $type [ 'archive' ]);
}
}
} else {
if ( $type [ 'parent_id' ] > 0 ){
$result [ 'type' ][] = array ( 'code' => $type [ 'parent_id' ], 'type' => $type [ 'type' ], 'order' => $type [ 'order_number' ], 'heir' => $type [ 'heir' ], 'name' => $type [ 'name' ], 'agency_id' => $type [ 'agency_id' ], 'archive' => $type [ 'archive' ]);
} else {
$result [ 'type' ][] = array ( 'code' => $type [ 'id' ], 'type' => $type [ 'type' ], 'order' => $type [ 'order_number' ], 'heir' => $type [ 'heir' ], 'name' => $type [ 'name' ], 'agency_id' => $type [ 'agency_id' ], 'archive' => $type [ 'archive' ]);
}
}
}
if ( $type [ 'parent_id' ] > 0 ){
$result [ 'names_type' ][ $type [ 'parent_id' ]] = array ( 'heir' => $type [ 'heir' ], 'name' => $type [ 'name' ]);
}
$result [ 'names_type' ][ $type [ 'id' ]] = array ( 'heir' => $type [ 'heir' ], 'name' => $type [ 'name' ]);
//$result['names_type'][$type['parent_id']] = array('heir'=>$type['heir'], 'name'=>$type['name']);
}
}
usort ( $result [ 'type' ], [ Requisitions :: class , " cmp " ]);
if ( $active && ! $no_archive ){
if ( ! empty ( $archive_type )){
$result [ 'type' ][] = array ( 'code' =>- 1 , 'type' => 'group' , 'order' => 0 , 'heir' => 0 , 'name' => 'Архив' , 'agency_id' => $this -> agencyId , 'archive' => 0 );
foreach ( $archive_type as $at ){
$result [ 'type' ][] = $at ;
}
}
}
// usort($result['type_archive'], "cmp");
// $result['type'][] = array('code'=>'group'.$type['id'], 'type'=>'group', 'order'=>99, 'heir'=>0, 'name'=>'testG', 'agency_id'=>4135);
//$result['type'] = array_multisort($order, SORT_ASC, $result['type']);
return $result ;
}
static function cmp ( $a , $b ) {
return strnatcmp ( $a [ " order " ], $b [ " order " ]);
}
public function get_denial_work ( $default = 0 ){
$result = array ();
$sql = " SELECT * FROM denial_work WHERE (agency_id = { $this -> agencyId } or agency_id = 0) AND del = 0 " ;
if ( $this -> agencyId == 19895 ){
$sql = " SELECT * FROM denial_work WHERE agency_id = { $this -> agencyId } AND del = 0 " ;
}
if ( $default > 0 ){
$sql .= " AND default_val = 0 " ;
}
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q )){
if ( $r [ 'default_val' ] == 1 )
$r [ 'check' ] = 1 ;
else
$r [ 'check' ] = 0 ;
$result [ $r [ 'id' ]] = $r ;
}
return $result ;
}
//очередь
public function set_type_order ( $id , $sort_order , $direct ){
$agency_id = $this -> agencyId ;
$update_pid = '' ;
$update_other = '' ;
if ( $direct == 'up' ) {
$update_pid = '-' ;
$update_other = '+' ;
$sort_other = $sort_order - 1 ;
} elseif ( $direct == 'down' ) {
$update_pid = '+' ;
$update_other = '-' ;
$sort_other = $sort_order + 1 ;
}
if ( ! empty ( $update_pid )) {
$sql = " UPDATE `requisitions_type`
SET `order_number` = `order_number` $update_other 1
WHERE `order_number` = '$sort_other' AND `agency_id` = '$agency_id' " ;
$sql2 = " UPDATE `requisitions_type`
SET `order_number` = `order_number` $update_pid 1
WHERE `id` = '$id' AND `agency_id` = '$agency_id' " ;
}
if ( empty ( $sql ) || empty ( $sql2 ))
exit ();
if ( $this -> db -> query ( $sql ) && $this -> db -> query ( $sql2 )) {
$sql3_1 = " SET @block_order:=0 " ;
$sql3_2 = " UPDATE `requisitions_type` SET `order_number`=@block_order:=@block_order+1 WHERE `agency_id` = ' $agency_id ' and del=0 ORDER BY `order_number`, `id` " ;
//echo $sql3_2;
$this -> db -> query ( $sql3_1 ) && $this -> db -> query ( $sql3_2 );
//echo json_encode(['success' => true]);
} else {
//echo json_encode(['success' => false, 'error' => $this->db->errorInfo()]);
}
$result = $this -> get_type ( true );
return $result ;
}
//Редактирование/добавление типа договора
public function editAddType ( $type_id , $type , $heir , $order , $type_type ){
if ( $type_id == 0 ){
$sql_in = " INSERT INTO requisitions_type SET
agency_id = { $this -> agencyId },
name = '{$type}' ,
heir = { $heir },
order_number = { $order },
type = '{$type_type}' ,
created_at = NOW (),
created_by = { $this -> user_id } " ;
if ( ! $this -> db -> query ( $sql_in )){
return array ( 'source' => 'error' , 'mes' => $this -> db -> errorInfo ());
} else {
return array ( 'source' => 'done' );
}
} else {
$sql = " SELECT * FROM requisitions_type WHERE id = { $type_id } " ;
$q = $this -> db -> query ( $sql );
if ( ! $q ){
return array ( 'source' => 'error' , 'mes' => $this -> db -> errorInfo ());
} else {
$r = $this -> db -> fetch_assoc ( $q );
if ( $r [ 'agency_id' ] > 0 && $r [ 'agency_id' ] == $this -> agencyId ){
$sql_up = " UPDATE requisitions_type SET name=' { $type } ', heir= { $heir } , type = ' { $type_type } ', updated_by= { $this -> user_id } , updated_at=NOW() WHERE id= { $type_id } " ;
if ( ! $this -> db -> query ( $sql_up )){
return array ( 'source' => 'error' , 'mes' => $this -> db -> errorInfo ());
} else {
return array ( 'source' => 'done' );
}
} else if ( $r [ 'agency_id' ] == 0 ) { //общий тип
$sql_in = " INSERT INTO requisitions_type SET
agency_id = { $this -> agencyId },
parent_id = { $type_id },
name = '{$type}' ,
heir = { $heir },
order_number = { $order },
type = '{$type_type}' ,
created_at = NOW (),
created_by = { $this -> user_id } " ;
if ( ! $this -> db -> query ( $sql_in )){
return array ( 'source' => 'error' , 'mes' => $this -> db -> errorInfo ());
/* $sql3_1 = " SET @block_order:=0 " ;
$sql3_2 = " UPDATE `requisitions_type` SET `order_number`=@block_order:=@block_order+1 WHERE `agency_id` = ' { $this -> agency_id } ' and del=0 ORDER BY `order_number`, `id` " ;
//echo $sql3_2;
$this -> db -> query ( $sql3_1 ) && $this -> db -> query ( $sql3_2 ); */
} else {
return array ( 'source' => 'done' );
}
}
}
}
}
//Удаление типа
public function deletedType ( $type_id )
{
$sql = " SELECT * FROM requisitions_type WHERE id = { $type_id } " ;
$q = $this -> db -> query ( $sql );
if ( ! $q ){
return array ( 'source' => 'error' , 'mes' => $this -> db -> errorInfo ());
} else {
$r = $this -> db -> fetch_assoc ( $q );
if ( $r [ 'agency_id' ] > 0 && $r [ 'agency_id' ] == $this -> agencyId ){
$sql_up = " UPDATE requisitions_type SET del=1, updated_by= { $this -> user_id } , updated_at=NOW() WHERE id= { $type_id } " ;
echo $sql_up ;
if ( ! $this -> db -> query ( $sql_up )){
return array ( 'source' => 'error' , 'mes' => $this -> db -> errorInfo ());
} else {
return array ( 'source' => 'done' );
}
} /* else if ( $r [ 'agency_id' ] == 0 ) { //общий тип
$sql_in = " INSERT INTO contract_types SET
agency_id = { $this -> agency_id },
type = '{$r[' type ']}' ,
parent_id = { $type_id },
del = 1 ,
created_at = NOW (),
created_by = { $this -> user_id } " ;
if ( ! $this -> db -> query ( $sql_in )){
return array ( 'source' => 'error' , 'mes' => $this -> db -> errorInfo ());
} else {
return array ( 'source' => 'done' );
}
} */
}
}
//Архивирование типа
public function archiveType ( $type_id , $order )
{
$sql = " SELECT * FROM requisitions_type WHERE id = { $type_id } " ;
$q = $this -> db -> query ( $sql );
if ( ! $q ){
return array ( 'source' => 'error' , 'mes' => $this -> db -> errorInfo ());
} else {
$r = $this -> db -> fetch_assoc ( $q );
if ( $r [ 'agency_id' ] > 0 && $r [ 'agency_id' ] == $this -> agencyId ){
$sql_up = " UPDATE requisitions_type SET archive=1, order_number= { $order } , updated_by= { $this -> user_id } , updated_at=NOW() WHERE id= { $type_id } " ;
// echo $sql_up;
if ( ! $this -> db -> query ( $sql_up )){
return array ( 'source' => 'error' , 'mes' => $this -> db -> errorInfo ());
} else {
return array ( 'source' => 'done' );
}
} /* else if ( $r [ 'agency_id' ] == 0 ) { //общий тип
$sql_in = " INSERT INTO contract_types SET
agency_id = { $this -> agency_id },
type = '{$r[' type ']}' ,
parent_id = { $type_id },
del = 1 ,
created_at = NOW (),
created_by = { $this -> user_id } " ;
if ( ! $this -> db -> query ( $sql_in )){
return array ( 'source' => 'error' , 'mes' => $this -> db -> errorInfo ());
} else {
return array ( 'source' => 'done' );
}
} */
}
}
//Восстановление из архива
public function recoverType ( $type_id , $order ){
$sql = " SELECT * FROM requisitions_type WHERE id = { $type_id } " ;
$q = $this -> db -> query ( $sql );
if ( ! $q ){
return array ( 'source' => 'error' , 'mes' => $this -> db -> errorInfo ());
} else {
$r = $this -> db -> fetch_assoc ( $q );
if ( $r [ 'agency_id' ] > 0 && $r [ 'agency_id' ] == $this -> agencyId ){
$sql_up = " UPDATE requisitions_type SET archive=0, order_number= { $order } , updated_by= { $this -> user_id } , updated_at=NOW() WHERE id= { $type_id } " ;
//echo $sql_up;
if ( ! $this -> db -> query ( $sql_up )){
return array ( 'source' => 'error' , 'mes' => $this -> db -> errorInfo ());
} else {
return array ( 'source' => 'done' );
}
} /* else if ( $r [ 'agency_id' ] == 0 ) { //общий тип
$sql_in = " INSERT INTO contract_types SET
agency_id = { $this -> agency_id },
type = '{$r[' type ']}' ,
parent_id = { $type_id },
del = 1 ,
created_at = NOW (),
created_by = { $this -> user_id } " ;
if ( ! $this -> db -> query ( $sql_in )){
return array ( 'source' => 'error' , 'mes' => $this -> db -> errorInfo ());
} else {
return array ( 'source' => 'done' );
}
} */
}
}
//Массив типов для фильтра
public function get_types_type ( $types ){
$result = array ();
if ( ! empty ( $types )){
$sql = " SELECT id, parent_id FROM requisitions_type WHERE id in ( " . implode ( ',' , $types ) . " ) " ;
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q )){
$result [] = ( int ) $r [ 'id' ];
if ( $r [ 'parent_id' ] > 0 ) {
$result [] = ( int ) $r [ 'parent_id' ];
}
}
}
$result = array_unique ( $result );
return $result ;
}
//Установка причин закрытия
public function set_type_denial ( $type_id , $denial_id , $check ){
if ( $this -> agencyId > 0 ){
$sql = " SELECT id FROM `denial_typereq` where agency_id = { $this -> agencyId } AND type_id = { $type_id } AND denial_id = { $denial_id } " ;
$q = $this -> db -> query ( $sql );
if ( $this -> db -> num_rows ( $q ) > 0 ){
$r = $this -> db -> fetch_assoc ( $q );
$sql_up = " UPDATE denial_typereq SET checked= { $check } WHERE id = { $r [ 'id' ] } " ;
$this -> db -> query ( $sql_up );
} else {
$sql_in = " INSERT INTO denial_typereq SET agency_id = { $this -> agencyId } , type_id = { $type_id } , denial_id = { $denial_id } , checked= { $check } " ;
// echo $sql_in;
$this -> db -> query ( $sql_in );
}
//Проверка наследника
$sql_heir = " SELECT * FROM requisitions_type WHERE id = { $type_id } " ;
$q_heir = $this -> db -> query ( $sql_heir );
$r_heir = $this -> db -> fetch_assoc ( $q_heir );
if ( isset ( $r_heir [ 'parent_id' ]) && $r_heir [ 'parent_id' ] > 0 ){
$parent_id = ( int ) $r_heir [ 'parent_id' ];
$sql = " SELECT id FROM `denial_typereq` where agency_id = { $this -> agencyId } AND type_id = { $parent_id } AND denial_id = { $denial_id } " ;
$q = $this -> db -> query ( $sql );
if ( $this -> db -> num_rows ( $q ) > 0 ){
$r = $this -> db -> fetch_assoc ( $q );
$sql_up = " UPDATE denial_typereq SET checked= { $check } WHERE id = { $r [ 'id' ] } " ;
$this -> db -> query ( $sql_up );
} else {
$sql_in = " INSERT INTO denial_typereq SET agency_id = { $this -> agencyId } , type_id = { $parent_id } , denial_id = { $denial_id } , checked= { $check } " ;
// echo $sql_in;
$this -> db -> query ( $sql_in );
}
}
}
}
//Причины закрытия
public function editAddDenial ( $id , $name ){
$result = array ();
if ( $this -> agencyId > 0 ){
if ( $id == 0 ){
$sql = " INSERT INTO denial_work (name, default_val, agency_id) VALUES (' { $name } ', 0, { $this -> agencyId } ) " ;
$this -> db -> query ( $sql );
} else {
$sql = " UPDATE denial_work SET name = ' { $name } ', default_val = 0 WHERE id = { $id } " ;
//echo $sql;
$this -> db -> query ( $sql );
}
$result = $this -> get_denial_work ( 1 );
}
return $result ;
}
//Удаление причины
public function deleteDenial ( $id ){
$result = array ();
if ( $this -> agencyId > 0 ){
if ( $id > 0 ){
$sql = " UPDATE denial_work SET del = 1 WHERE id = { $id } " ;
//echo $sql;
$this -> db -> query ( $sql );
}
}
$result = $this -> get_denial_work ( 1 );
return $result ;
}
//У кого в работе
public function get_who ( $who_work , $req_id , $kanban , $departments , $usersToUse = []){
$master_work = '' ;
$master_phone = null ;
$master_work_fio = '' ;
if (( int ) $who_work > 0 ) {
if ( isset ( $usersToUse ) && isset ( $usersToUse [ $who_work ])) {
$mstr = $usersToUse [ $who_work ];
} else {
$mstr = $this -> db -> fetch_assoc ( $this -> db -> query ( " SELECT agency, manager, agency_name, first_name, last_name, middle_name, role_id, phone, 0 as del FROM users WHERE id= $who_work UNION
SELECT agency , manager , agency_name , first_name , last_name , middle_name , role_id , phone , 1 as del FROM users_delete WHERE user_id = $who_work " ));
}
$master_phone = $mstr [ 'phone' ];
$master_work_fio = trim ( $mstr [ 'last_name' ] . ' ' . $mstr [ 'first_name' ] . ' ' . $mstr [ 'middle_name' ]);
if ( $kanban ) {
$master_work = trim ( $mstr [ 'last_name' ] . ' ' . $mstr [ 'first_name' ] . ' ' . $mstr [ 'middle_name' ]);
} else {
if ( $mstr [ 'agency' ]) {
2026-06-20 10:19:54 +02:00
$master_work = trim ( $mstr [ 'last_name' ] . ' ' . $mstr [ 'first_name' ] . ' ' . $mstr [ 'middle_name' ]) ? : " агентство { $mstr [ 'agency_name' ] } " ;
2026-05-22 20:21:54 +02:00
}
elseif ( $mstr [ 'manager' ]) {
if ( $mstr [ 'role_id' ] > 0 ) {
$master_work = $departments [ $mstr [ 'role_id' ]][ 'role_name' ] . ' ' . trim ( $mstr [ 'last_name' ] . ' ' . $mstr [ 'first_name' ] . ' ' . $mstr [ 'middle_name' ]);
} else {
$master_work = " менеджер " . trim ( $mstr [ 'last_name' ] . ' ' . $mstr [ 'first_name' ] . ' ' . $mstr [ 'middle_name' ]);
}
} else {
if ( $mstr [ 'role_id' ] > 0 ) {
$master_work = $departments [ $mstr [ 'role_id' ]][ 'role_name' ] . ' ' . trim ( $mstr [ 'last_name' ] . ' ' . $mstr [ 'first_name' ] . ' ' . $mstr [ 'middle_name' ]);
} else {
$master_work = " агент " . trim ( $mstr [ 'last_name' ] . ' ' . $mstr [ 'first_name' ] . ' ' . $mstr [ 'middle_name' ]);
}
}
if ( $mstr [ 'del' ] == 1 ) {
$master_work .= " (удален) " ;
}
$sql_work = " SELECT `date_update` FROM `events_clients` WHERE `req_id`= $req_id and event='accepted' and user_id= $who_work " ;
$q_work = $this -> db -> query ( $sql_work );
if ( $this -> db -> num_rows ( $q_work ) > 0 ) {
$r_work = $this -> db -> fetch_assoc ( $q_work );
if ( $r_work [ 'date_update' ] != '0000-00-00 00:00:00' ) {
$master_work .= ' <span> c ' . date ( 'd.m.Y H:i' , strtotime ( $r_work [ 'date_update' ])) . '</span>' ;
}
}
}
} else {
$master_work .= 'В с е агентство' ;
}
return [ 'id' => $who_work , 'name' => strip_tags ( $master_work ), 'phone' => $master_phone , 'fio' => $master_work_fio ];
}
public function get_who_delete ( $who_delete , $req_id , $kanban , $departments , $usersToUse = []){
$master_delete = '' ;
$master_phone = null ;
if (( int ) $who_delete > 0 ) {
if ( isset ( $usersToUse ) && isset ( $usersToUse [ $who_delete ])) {
$mstr = $usersToUse [ $who_delete ];
} else {
$mstr = $this -> db -> fetch_assoc ( $this -> db -> query ( " SELECT agency, manager, agency_name, first_name, last_name, middle_name, role_id, phone, 0 as del FROM users WHERE id= $who_delete UNION
SELECT agency , manager , agency_name , first_name , last_name , middle_name , role_id , phone , 1 as del FROM users_delete WHERE user_id = $who_delete " ));
}
$master_phone = $mstr [ 'phone' ];
if ( $kanban ) {
$master_delete = trim ( $mstr [ 'last_name' ] . ' ' . $mstr [ 'first_name' ] . ' ' . $mstr [ 'middle_name' ]);
} else {
if ( $mstr [ 'agency' ]) {
2026-06-20 10:19:54 +02:00
$master_delete = trim ( $mstr [ 'last_name' ] . ' ' . $mstr [ 'first_name' ] . ' ' . $mstr [ 'middle_name' ]) ? : " агентство { $mstr [ 'agency_name' ] } " ;
2026-05-22 20:21:54 +02:00
}
elseif ( $mstr [ 'manager' ]) {
if ( $mstr [ 'role_id' ] > 0 ) {
$master_delete = $departments [ $mstr [ 'role_id' ]][ 'role_name' ] . ' ' . trim ( $mstr [ 'last_name' ] . ' ' . $mstr [ 'first_name' ] . ' ' . $mstr [ 'middle_name' ]);
} else {
$master_delete = " менеджер " . trim ( $mstr [ 'last_name' ] . ' ' . $mstr [ 'first_name' ] . ' ' . $mstr [ 'middle_name' ]);
}
} else {
if ( $mstr [ 'role_id' ] > 0 ) {
$master_delete = $departments [ $mstr [ 'role_id' ]][ 'role_name' ] . ' ' . trim ( $mstr [ 'last_name' ] . ' ' . $mstr [ 'first_name' ] . ' ' . $mstr [ 'middle_name' ]);
} else {
$master_delete = " агент " . trim ( $mstr [ 'last_name' ] . ' ' . $mstr [ 'first_name' ] . ' ' . $mstr [ 'middle_name' ]);
}
}
if ( $mstr [ 'del' ] == 1 ) {
$master_delete .= " (удален) " ;
}
$sql_delete = " SELECT `date_update` FROM `events_clients` WHERE `req_id`= $req_id and event='delete' and user_id= $who_delete order by id desc limit 1 " ;
$q_delete = $this -> db -> query ( $sql_delete );
if ( $this -> db -> num_rows ( $q_delete ) > 0 ) {
$r_delete = $this -> db -> fetch_assoc ( $q_delete );
if ( $r_delete [ 'date_update' ] != '0000-00-00 00:00:00' ) {
$master_delete .= ' <span> ' . date ( 'd.m.Y H:i' , strtotime ( $r_delete [ 'date_update' ])) . '</span>' ;
}
}
}
}
return [ 'id' => $who_delete , 'name' => strip_tags ( $master_delete ), 'phone' => $master_phone ];
}
//Общее по одной заявке для канбана
private function get_req_details_kanban ( $r , $kanban = false , $usersToUse = [], $departments = [], $typesReq = array (), $events_res = array ()){
2026-06-20 10:19:54 +02:00
// Унифицировано с форматом даты задачи: DD.MM.YYYY.
$date_add = date ( " d.m.Y " , strtotime ( $r [ 'created_at' ]));
2026-05-22 20:21:54 +02:00
if ( ! isset ( $r [ 'funnel_type' ])){
$r [ 'funnel_type' ] = 'main' ;
}
$r [ 'date_add' ] = $date_add ;
$r [ 'isMainInfo' ] = false ;
$r [ 'is_new' ] = false ;
if ( isset ( $_SESSION [ 'new_transfers' ][ 'requisitions' ]))
$r [ 'is_new' ] = in_array ( $r [ 'id' ], $_SESSION [ 'new_transfers' ][ 'requisitions' ]);
$noConfirm = 0 ;
$noConfDoer = 0 ;
if ( $r [ 'confirm' ] == '0' && ( $r [ 'who_work' ] == $_SESSION [ 'id' ] or $r [ 'user_id' ] == $_SESSION [ 'id' ] or $r [ 'who_work' ] == 0 )) {
$noConfirm = 1 ;
} else if ( $r [ 'doers_confirm' ] == 0 && ! empty ( $r [ 'doers' ])) {
$doers = json_decode ( html_entity_decode ( $r [ 'doers' ]), true );
if ( isset ( $doers [ $_SESSION [ 'id' ]]) && $doers [ $_SESSION [ 'id' ]] == 0 ) {
$noConfDoer = 1 ;
}
}
$canSee = true ;
//у Рослекс из общих могут забирать только менеджеры или агентство
if ( $this -> user -> id != 6358 && $this -> agencyId == 6358 && $this -> user -> manager == 0
&& $r [ 'confirm' ] == 0 && $r [ 'who_work' ] == 0 ) {
$canSee = false ;
}
$r [ 'can_edit' ] = 0 ;
if ( $r [ 'who_work' ] == $this -> user -> id ){
$r [ 'can_edit' ] = 1 ;
} else if ( $this -> user -> manager > 0 || $this -> user -> agency > 0 || $_SESSION [ 'users_admin' ] > 0 ){
$r [ 'can_edit' ] = 1 ;
} else if ( $r [ 'doers_confirm' ] == 0 && ! empty ( $r [ 'doers' ])){
$doers1 = json_decode ( html_entity_decode ( $r [ 'doers' ]), true );
if ( isset ( $doers1 [ $_SESSION [ 'id' ]]) && $doers1 [ $_SESSION [ 'id' ]] == 1 ) {
$r [ 'can_edit' ] = 1 ;
}
}
$r [ 'no_confirm' ] = $noConfirm ;
$r [ 'no_conf_doer' ] = $noConfDoer ;
$r [ 'can_see' ] = $canSee ;
$r [ 'can_del' ] = 1 ;
if ( $r [ 'confirm' ] == '0' && $r [ 'who_work' ] == 0 ){
$r [ 'can_del' ] = 0 ;
if ( $this -> user -> agency > 0 || $_SESSION [ 'users_admin' ] > 0 ){
$r [ 'can_del' ] = 1 ;
}
} else if ( $r [ 'funnel_type' ] == 'adjacent' ){
$r [ 'can_del' ] = 0 ;
}
$r [ 'can_see_joint' ] = 0 ;
if ( $this -> user -> agency > 0 || $_SESSION [ 'users_admin' ] > 0 ){
$r [ 'can_see_joint' ] = 1 ;
}
$r [ 'can_see_other' ] = false ;
if ( $r [ 'can_edit' ] || $r [ 'who_work' ] == $this -> user -> id || $r [ 'user_id' ] == $this -> user -> id )
$r [ 'can_see_other' ] = true ;
// Если заявка из общих
if ( $r [ 'deleted' ] == 0 && $r [ 'confirm' ] == 0 && $r [ 'who_work' ] == 0 )
$r [ 'can_see_other' ] = true ;
$r [ 'can_see_contact_closed' ] = false ;
$r [ 'can_take_from_closed' ] = false ;
$r_check_permissions = $this -> user -> checkMenuPermissions ();
$sql_check_manager = " SELECT `id_manager`, `department_id` FROM `users` WHERE `id` = " . $r [ 'who_work' ];
$result_check_manager = mysql_query ( $sql_check_manager );
$req_id_manager = mysql_fetch_assoc ( $result_check_manager );
$depClassPerm = new \Department ();
$dep_user = $depClassPerm -> getDepartment ( $_SESSION [ 'id' ]);
$sql_user_missing_fields = " SELECT `id_manager`, `department_id` FROM `users` WHERE `id` = " . $_SESSION [ 'id' ];
$result_user_missing_fields = mysql_query ( $sql_user_missing_fields );
$user_missing_fields = mysql_fetch_assoc ( $result_user_missing_fields );
if ( $_SESSION [ 'agency' ] || $_SESSION [ 'users_admin' ] || $r_check_permissions [ 'menu_all_submissions_edit' ] == 1 || $_SESSION [ 'id' ] == $r [ 'who_work' ]) {
$r [ 'can_see_contact_closed' ] = true ;
} elseif (( $dep_user [ 'role' ] == 'admin_department' || $dep_user [ 'role' ] == 'manager_office' ) && $req_id_manager [ 'department_id' ] == $user_missing_fields [ 'department_id' ]) {
$r [ 'can_see_contact_closed' ] = true ;
} elseif ( $dep_user [ 'role' ] == 'manager' && $this -> user -> id == $req_id_manager [ 'id_manager' ]) {
$r [ 'can_see_contact_closed' ] = true ;
} elseif ( $dep_user [ 'role' ] == 'manager_office_menager' && ( $this -> user -> id == $req_id_manager [ 'id_manager' ] || $_SESSION [ 'id_manager' ] == $req_id_manager [ 'id_manager' ] || $_SESSION [ 'id_manager' ] == $r [ 'who_work' ])) {
$r [ 'can_see_contact_closed' ] = true ;
} elseif ( ! ( $dep_user [ 'role' ]) && ( $_SESSION [ 'manager' ] && ( $_SESSION [ 'id' ] == $req_id_manager [ 'id_manager' ]))) {
$r [ 'can_see_contact_closed' ] = true ;
}
$daily_closed_req_left = $r_check_permissions [ 'daily_closed_req_limit' ] - $r_check_permissions [ 'actual_daily_closed_req' ];
if (( $_SESSION [ 'agency' ] || $_SESSION [ 'users_admin' ] || ( $r_check_permissions [ 'menu_can_take_from_closed' ] == 1 && $daily_closed_req_left > 0 )) && $r [ 'confirm' ] == 1 ) {
$r [ 'can_take_from_closed' ] = true ;
}
$r [ 'daily_closed_req_left' ] = $daily_closed_req_left ;
$r [ 'r_check_permissions' ] = $r_check_permissions ;
$r [ 'can_see_contact_common' ] = false ;
if ( $_SESSION [ 'agency' ] || $_SESSION [ 'users_admin' ]) {
$r [ 'can_see_contact_common' ] = true ;
}
/* if ( $this -> user -> manager > 0 || $this -> user -> agency > 0 || $_SESSION [ 'users_admin' ] > 0 ) {
$sql = " SELECT id FROM `users`
WHERE id = { $this -> user -> id } OR
id_manager = { $this -> user -> id } OR
id_manager IN (
SELECT id FROM users WHERE id_manager = { $this -> user -> id }
) OR
id_manager IN (
SELECT id FROM users WHERE id_manager IN (
SELECT id FROM users WHERE id_manager = { $this -> user -> id }
)
) " ;
} */
if ( $r [ 'funnel_type' ] == 'adjacent' ){
$funnelClass = new Funnel ( $this -> db );
$r [ 'steps' ] = $funnelClass -> get_class_etap ( array (), $r [ 'id' ], $r [ 'funnel_id' ]);
} else {
$r [ 'steps' ] = $this -> get_class_etap ( $r [ 'id' ], $r [ 'funnel_id' ], $r [ 'stage' ]);
}
// $r['steps'] = $this->get_class_etap($r['id'], $r['funnel_id'], $r['stage']);
$r [ 'object' ] = array ();
$r [ 'client' ] = array ();
$r [ 'union_req' ] = array ();
$r [ 'autosearch' ] = array ( 'filter' => []);
$r [ 'autosearch_id' ] = null ;
$r [ 'autosearch_info' ] = null ;
$r [ 'add_tag' ] = false ;
$r [ 'add_tag_contract' ] = false ;
$r [ 'description' ] = html_entity_decode ( $r [ 'description' ]);
$who_work = $this -> get_who ( $r [ 'who_work' ], $r [ 'id' ], $kanban , $departments , $usersToUse );
$r [ 'master_work_id' ] = $who_work [ 'id' ];
$r [ 'master_work' ] = $who_work [ 'name' ];
$r [ 'master_work_name' ] = $who_work [ 'name' ];
$r [ 'master_work_fio' ] = $who_work [ 'fio' ];
//Тип заявки
$typesReqNames = $typesReq [ 'names_type' ];
$r [ 'name_type' ] = $typesReqNames [ $r [ 'type_id' ]][ 'name' ];
$r [ 'heir_type' ] = $typesReqNames [ $r [ 'type_id' ]][ 'heir' ];
$r [ 'activities' ] = array () ;
$r [ 'activities_visible' ] = array () ;
$r [ 'activities_temp' ] = array ();
$r [ 'activities_name' ] = '' ;
$r [ 'activities_rest' ] = 0 ;
$sql_a = " SELECT * FROM requisitions_activities WHERE req_id = { $r [ 'id' ] } " ;
$q_a = $this -> db -> query ( $sql_a );
$tv = 0 ;
while ( $r_a = $this -> db -> fetch_assoc ( $q_a )){
$r [ 'activities_temp' ][] = $r_a [ 'activity_id' ];
$sql_a_name = " SELECT * FROM activities WHERE id = { $r_a [ 'activity_id' ] } " ;
$q_a_name = $this -> db -> query ( $sql_a_name );
$r_a_name = $this -> db -> fetch_assoc ( $q_a_name );
$r [ 'activities' ][] = $r_a_name ;
if ( count ( $r [ 'activities_visible' ]) < 2 ){
$r [ 'activities_visible' ][] = $r_a_name ;
$tv ++ ;
}
if ( $r [ 'activities_name' ] != '' ) $r [ 'activities_name' ] .= " , " ;
$r [ 'activities_name' ] .= $r_a_name [ 'name' ];
}
if ( $tv < count ( $r [ 'activities' ])){
$r [ 'activities_rest' ] = count ( $r [ 'activities' ]) - $tv ;
}
$r [ 'e' ] = $events_res ;
if ( isset ( $events_res ) && ! empty ( $events_res )){
$r [ 'events_res' ] = $events_res [ $r [ 'id' ]][ 'events_res' ];
$r [ 'events_res1' ] = $events_res [ $r [ 'id' ]][ 'events_res1' ];
$r [ 'events_res2' ] = $events_res [ $r [ 'id' ]][ 'events_res2' ];
}
$tasks_sql = " SELECT schedule_date, comment, user_id, name,type
FROM user_client_events
WHERE req_id = { $r [ 'id' ]} AND type IN ( 'even' , 'call' , 'deal' , 'show' , 'meet' ) AND calendar_view = 0
ORDER BY schedule_date ASC " ;
$tasks_result = mysql_query ( $tasks_sql );
if ( $tasks_result ) {
while ( $row = mysql_fetch_assoc ( $tasks_result )) {
$sql_user = " SELECT CONCAT(last_name, ' ', first_name, ' ', middle_name) as user_fio
FROM users
WHERE id = { $row [ 'user_id' ]} " ;
$responsible = mysql_fetch_assoc ( mysql_query ( $sql_user ))[ 'user_fio' ];
$typeMap = [
'call' => [ 'label' => 'Звонок' , 'bg' => '#dbedc7' , 'text' => '#458c46' ],
'deal' => [ 'label' => 'Сделка' , 'bg' => '#fcd9dd' , 'text' => '#e57373' ],
'show' => [ 'label' => 'Показ' , 'bg' => '#fff9c4' , 'text' => '#f9a825' ],
'meet' => [ 'label' => 'Встреча' , 'bg' => '#f3e4f5' , 'text' => '#7c1fa3' ]
];
$type = $row [ 'type' ];
2026-06-20 10:19:54 +02:00
// Унифицировано с датой заявки: DD.MM.YYYY HH:MM.
$scheduleDate = date ( 'd.m.Y H:i' , strtotime ( $row [ 'schedule_date' ]));
2026-05-22 20:21:54 +02:00
$taskName = $row [ 'name' ];
$bgColor = '#e2e9f5' ;
$textColor = '#76a7fa' ;
if ( isset ( $typeMap [ $type ])) {
$taskName = $type == 'even' ? $row [ 'name' ] : $typeMap [ $type ][ 'label' ];
$bgColor = $typeMap [ $type ][ 'bg' ];
$textColor = $typeMap [ $type ][ 'text' ];
}
$r [ 'tasks_data' ][] = [
'schedule_date' => isset ( $scheduleDate ) ? $scheduleDate : '' ,
'comment' => isset ( $row [ 'comment' ]) ? $row [ 'comment' ] : '' ,
'name' => isset ( $taskName ) ? $taskName : '' ,
'responsible' => isset ( $responsible ) ? $responsible : '' ,
'bgColor' => isset ( $bgColor ) ? $bgColor : '' ,
'textColor' => isset ( $textColor ) ? $textColor : ''
];
}
}
2026-06-20 10:19:54 +02:00
$r [ 'is_deal' ] = ! empty ( $r [ 'deal_id' ]) && $r [ 'deal_id' ] > 0 ? 1 : 0 ;
2026-05-22 20:21:54 +02:00
$result = $r ;
return $result ;
}
//Общее по одной заявке
private function get_req_details ( $r , $kanban = false , $usersToUse = [], $sourcesToUse = [], $typesContracs = [], $typesReq = array (), $departments = array (), $needAutoSearch = true ) {
//error_reporting(E_ALL | E_STRICT);
//ini_set('display_errors', 1);
$dateAdd = date ( " d.m.Y " , strtotime ( $r [ 'created_at' ]));
list ( $d , $m , $y ) = explode ( " . " , $dateAdd );
$date_add = $d . " " . getRusMonth ( $m ) . " " . $y ;
if ( ! isset ( $r [ 'funnel_type' ])){
$r [ 'funnel_type' ] = 'main' ;
}
$r [ 'date_add' ] = $date_add ;
$r [ 'isMainInfo' ] = false ;
$r [ 'is_new' ] = false ;
if ( isset ( $_SESSION [ 'new_transfers' ][ 'requisitions' ]))
$r [ 'is_new' ] = in_array ( $r [ 'id' ], $_SESSION [ 'new_transfers' ][ 'requisitions' ]);
$noConfirm = 0 ;
$noConfDoer = 0 ;
if ( $r [ 'confirm' ] == '0' && ( $r [ 'who_work' ] == $_SESSION [ 'id' ] or $r [ 'user_id' ] == $_SESSION [ 'id' ] or $r [ 'who_work' ] == 0 )) {
$noConfirm = 1 ;
} else if ( $r [ 'doers_confirm' ] == 0 && ! empty ( $r [ 'doers' ])) {
$doers = json_decode ( html_entity_decode ( $r [ 'doers' ]), true );
if ( isset ( $doers [ $_SESSION [ 'id' ]]) && $doers [ $_SESSION [ 'id' ]] == 0 ) {
$noConfDoer = 1 ;
}
}
$canSee = true ;
//у Рослекс из общих могут забирать только менеджеры или агентство
if ( $this -> user -> id != 6358 && $this -> agencyId == 6358 && $this -> user -> manager == 0
&& $r [ 'confirm' ] == 0 && $r [ 'who_work' ] == 0 ) {
$canSee = false ;
}
$r [ 'can_edit' ] = 0 ;
if ( $r [ 'who_work' ] == $this -> user -> id ){
$r [ 'can_edit' ] = 1 ;
} else if ( $this -> user -> agency > 0 || $_SESSION [ 'users_admin' ] > 0 ){
$r [ 'can_edit' ] = 1 ;
} else if ( $this -> user -> manager > 0 ){
if ( ! empty ( $this -> userIdsWork )){
if ( in_array ( $r [ 'who_work' ], $this -> userIdsWork )){
$r [ 'can_edit' ] = 1 ;
}
}
} else if ( ! empty ( $r [ 'doers' ])){
$doers1 = json_decode ( html_entity_decode ( $r [ 'doers' ]), true );
$r [ 'doers1' ] = $doers1 ;
if ( isset ( $doers1 [ $_SESSION [ 'id' ]]) && $doers1 [ $_SESSION [ 'id' ]] == 1 ) {
$r [ 'can_edit' ] = 1 ;
}
}
$r [ 'no_confirm' ] = $noConfirm ;
$r [ 'no_conf_doer' ] = $noConfDoer ;
$r [ 'can_see' ] = $canSee ;
2026-06-20 10:19:54 +02:00
$r [ 'is_deal' ] = ! empty ( $r [ 'deal_id' ]) && $r [ 'deal_id' ] > 0 ? 1 : 0 ;
2026-05-22 20:21:54 +02:00
$r [ 'can_see_other' ] = false ;
if ( $r [ 'can_edit' ] && (( int ) $r [ 'who_work' ] == ( int ) $this -> user -> id || ( int ) $r [ 'user_id' ] == ( int ) $this -> user -> id ))
$r [ 'can_see_other' ] = true ;
if ( ! $r [ 'can_see_other' ] && ( $this -> user -> agency > 0 || $_SESSION [ 'users_admin' ] > 0 ))
$r [ 'can_see_other' ] = true ;
// Если пользователь менеджер и заявка е г о подчиненного
if ( ! $r [ 'can_see_other' ] && ( $this -> user -> manager > 0 )) {
if ( ! empty ( $this -> user -> manager_users )) {
if ( in_array (( int ) $r [ 'who_work' ], $this -> user -> manager_users ) || in_array (( int ) $r [ 'user_id' ], $this -> user -> manager_users )) {
$r [ 'can_see_other' ] = true ;
}
}
}
if ( ! isset ( $this -> user ) || $this -> user === null ) {
if ( isset ( $_SESSION [ 'id' ]) && is_numeric ( $_SESSION [ 'id' ])) {
$this -> user = new User ();
} else {
http_response_code ( 500 );
echo json_encode ([ 'error' => 'User authentication required' ]);
exit ();
}
}
$r [ 'can_see_contact_closed' ] = false ;
$r [ 'can_take_from_closed' ] = false ;
$r_check_permissions = $this -> user -> checkMenuPermissions ();
$sql_check_manager = " SELECT `id_manager`, `department_id` FROM `users` WHERE `id` = " . $r [ 'who_work' ];
$result_check_manager = mysql_query ( $sql_check_manager );
$req_id_manager = mysql_fetch_assoc ( $result_check_manager );
$depClassPerm = new \Department ();
$dep_user = $depClassPerm -> getDepartment ( $_SESSION [ 'id' ]);
$sql_user_missing_fields = " SELECT `id_manager`, `department_id` FROM `users` WHERE `id` = " . $_SESSION [ 'id' ];
$result_user_missing_fields = mysql_query ( $sql_user_missing_fields );
$user_missing_fields = mysql_fetch_assoc ( $result_user_missing_fields );
if ( $_SESSION [ 'agency' ] || $_SESSION [ 'users_admin' ] || $r_check_permissions [ 'menu_all_submissions_edit' ] == 1 || $_SESSION [ 'id' ] == $r [ 'who_work' ]) {
$r [ 'can_see_contact_closed' ] = true ;
$r [ 'can_edit' ] = 1 ;
} elseif (( $dep_user [ 'role' ] == 'admin_department' || $dep_user [ 'role' ] == 'manager_office' ) && $req_id_manager [ 'department_id' ] == $user_missing_fields [ 'department_id' ]) {
$r [ 'can_see_contact_closed' ] = true ;
} elseif ( $dep_user [ 'role' ] == 'manager' && $this -> user -> id == $req_id_manager [ 'id_manager' ]) {
$r [ 'can_see_contact_closed' ] = true ;
} elseif ( $dep_user [ 'role' ] == 'manager_office_menager' && ( $this -> user -> id == $req_id_manager [ 'id_manager' ] || $_SESSION [ 'id_manager' ] == $req_id_manager [ 'id_manager' ] || $_SESSION [ 'id_manager' ] == $r [ 'who_work' ])) {
$r [ 'can_see_contact_closed' ] = true ;
} elseif ( ! ( $dep_user [ 'role' ]) && ( $_SESSION [ 'manager' ] && ( $_SESSION [ 'id' ] == $req_id_manager [ 'id_manager' ]))) {
$r [ 'can_see_contact_closed' ] = true ;
}
$daily_closed_req_left = $r_check_permissions [ 'daily_closed_req_limit' ] - $r_check_permissions [ 'actual_daily_closed_req' ];
if (( $_SESSION [ 'agency' ] || $_SESSION [ 'users_admin' ] || ( $r_check_permissions [ 'menu_can_take_from_closed' ] == 1 && $daily_closed_req_left > 0 )) && $r [ 'confirm' ] == 1 ) {
$r [ 'can_take_from_closed' ] = true ;
}
$r [ 'daily_closed_req_left' ] = $daily_closed_req_left ;
$r [ 'r_check_permissions' ] = $r_check_permissions ;
$see_client = true ;
$see_info = true ;
if ( $this -> user -> agencyId == 8826 || $this -> user -> agencyId == 19895 ){
if ( $r [ 'who_work' ] == 0 && $r [ 'confirm' ] == 0 ){
$see_client = false ;
$see_info = false ;
}
}
if ( $r [ 'deleted' ] == 1 && ! $r [ 'can_see_contact_closed' ]) {
$see_info = false ;
}
$r [ 'can_see_contact_common' ] = false ;
if ( $_SESSION [ 'agency' ] || $_SESSION [ 'users_admin' ]) {
$r [ 'can_see_contact_common' ] = true ;
}
$r [ 'see_client' ] = $see_client ;
$r [ 'see_info' ] = $see_info ;
$r [ 'can_del' ] = 1 ;
$r [ 'can_see_joint' ] = 0 ;
if ( $this -> user -> agency > 0 || $_SESSION [ 'users_admin' ] > 0 ){
$r [ 'can_see_joint' ] = 1 ;
}
if ( $r [ 'confirm' ] == '0' && $r [ 'who_work' ] == 0 ){
$r [ 'can_del' ] = 0 ;
if ( $this -> user -> agency > 0 || $_SESSION [ 'users_admin' ] > 0 ){
$r [ 'can_del' ] = 1 ;
}
} else if ( $r [ 'funnel_type' ] == 'adjacent' ){
$r [ 'can_del' ] = 0 ;
}
// Если заявка из общих
if ( $r [ 'deleted' ] == 0 && $r [ 'confirm' ] == 0 && $r [ 'who_work' ] == 0 ) {
$r [ 'can_see_other' ] = true ;
if ( $this -> user -> agencyId != 8826 ){
$r [ 'can_edit' ] = true ;
}
}
if ( $r [ 'funnel_type' ] == 'adjacent' ){
$funnelClass = new Funnel ( $this -> db );
$r [ 'steps' ] = $funnelClass -> get_class_etap ( array (), $r [ 'id' ], $r [ 'funnel_id' ]);
} else {
$r [ 'steps' ] = $this -> get_class_etap ( $r [ 'id' ], $r [ 'funnel_id' ], $r [ 'stage' ]);
}
$r [ 'object' ] = array ();
$r [ 'client' ] = array ();
$r [ 'union_req' ] = array ();
$r [ 'is_main_union_req' ] = 0 ;
// Don`t remove (!)
$r [ 'autosearch' ] = array ( 'error' => [], 'filter' => []);
$r [ 'autosearch_id' ] = null ;
$r [ 'autosearch_info' ] = null ;
//Теги
$r [ 'activities' ] = array () ;
$r [ 'activities_visible' ] = array () ;
$r [ 'activities_temp' ] = array ();
$r [ 'activities_name' ] = '' ;
$r [ 'activities_rest' ] = 0 ;
$sql_a = " SELECT * FROM requisitions_activities WHERE req_id = { $r [ 'id' ] } " ;
$q_a = $this -> db -> query ( $sql_a );
$tv = 0 ;
while ( $r_a = $this -> db -> fetch_assoc ( $q_a )){
$r [ 'activities_temp' ][] = $r_a [ 'activity_id' ];
$sql_a_name = " SELECT * FROM activities WHERE id = { $r_a [ 'activity_id' ] } " ;
$q_a_name = $this -> db -> query ( $sql_a_name );
$r_a_name = $this -> db -> fetch_assoc ( $q_a_name );
$r [ 'activities' ][] = $r_a_name ;
if ( count ( $r [ 'activities_visible' ]) < 3 ){
$r [ 'activities_visible' ][] = $r_a_name ;
$tv ++ ;
}
if ( $r [ 'activities_name' ] != '' ) $r [ 'activities_name' ] .= " , " ;
$r [ 'activities_name' ] .= $r_a_name [ 'name' ];
}
if ( $tv < count ( $r [ 'activities' ])){
$r [ 'activities_rest' ] = count ( $r [ 'activities' ]) - $tv ;
}
$r [ 'contracts' ] = array ();
$r [ 'contracts_name' ] = '' ;
$sql_a = " SELECT * FROM contracts_req WHERE req_id = { $r [ 'id' ] } " ;
$q_a = $this -> db -> query ( $sql_a );
while ( $r_a = $this -> db -> fetch_assoc ( $q_a )){
$expired = false ;
$diff_date = ( $r_a [ 'date_end' ] - time ()) / 86400 ;
if ( $diff_date < ( int ) $r_a [ 'days' ]){
$expired = true ;
}
$name = $typesContracs [ $r_a [ 'type' ]][ 'type' ] . " № " . $r_a [ 'number' ] . " от " . date ( 'd.m.Y' , $r_a [ 'date_start' ]) . " по " . date ( 'd.m.Y' , $r_a [ 'date_end' ]);
$r [ 'contracts' ][] = array ( 'id' => $r_a [ 'id' ], 'name' => $name , 'expired' => $expired );
if ( $r [ 'contracts_name' ] != '' ) $r [ 'contracts_name' ] .= " , " ;
$r [ 'contracts_name' ] .= $name ;
}
$r [ 'add_tag' ] = false ;
$r [ 'popup_tag' ] = false ;
$r [ 'add_tag_contract' ] = false ;
$r [ 'description' ] = html_entity_decode ( $r [ 'description' ]);
if ( isset ( $usersToUse ) && isset ( $usersToUse [ $r [ 'user_id' ]])) {
$r_m = $usersToUse [ $r [ 'user_id' ]];
} else {
$sql_m = " SELECT agency, manager, agency_name, first_name, last_name, middle_name, role_id, phone FROM users WHERE id= " . $r [ 'user_id' ];
$q_m = $this -> db -> query ( $sql_m );
$r_m = $this -> db -> fetch_assoc ( $q_m );
}
if ( ! isset ( $departments ) || count ( $departments ) == 0 ) {
$depClass = new Department ;
$departments = $depClass -> getDepartments ();
}
$r [ 'no_can_edit_hot' ] = 0 ;
$r [ 'see_modal_client' ] = 1 ;
if ( $r_m [ 'agency' ]) {
2026-06-20 10:19:54 +02:00
$master = trim ( $r_m [ 'last_name' ] . ' ' . $r_m [ 'first_name' ] . ' ' . $r_m [ 'middle_name' ]) ? : " Агентство { $r_m [ 'agency_name' ] } " ;
2026-05-22 20:21:54 +02:00
} else if ( $r_m [ 'manager' ]) {
$master = " Менеджер " . trim ( $r_m [ 'last_name' ] . ' ' . $r_m [ 'first_name' ] . ' ' . $r_m [ 'middle_name' ]);
if ( $r_m [ 'role_id' ] > 0 ) {
$master = $departments [ $r_m [ 'role_id' ]][ 'role_name' ] . ' ' . trim ( $r_m [ 'last_name' ] . ' ' . $r_m [ 'first_name' ] . ' ' . $r_m [ 'middle_name' ]);
}
} else {
$master = " Агент " . trim ( $r_m [ 'last_name' ] . ' ' . $r_m [ 'first_name' ] . ' ' . $r_m [ 'middle_name' ]);
if ( $r_m [ 'role_id' ] > 0 ) {
$master = $departments [ $r_m [ 'role_id' ]][ 'role_name' ] . ' ' . trim ( $r_m [ 'last_name' ] . ' ' . $r_m [ 'first_name' ] . ' ' . $r_m [ 'middle_name' ]);
}
}
//check edit
$r [ 'allow_edit' ] = 0 ;
if ( isset ( $this -> user )){
$r_check_permissions = $this -> user -> checkMenuPermissions ();
$sql_check_manager = " SELECT `id_manager`, `department_id` FROM `users` WHERE `id` = " . $r [ 'who_work' ];
$depClassPerm = new Department ();
$dep_user_perm = $depClassPerm -> getDepartment ( $this -> user -> id );
$result_check_manager = mysql_query ( $sql_check_manager );
$who_work_id_manager = mysql_fetch_assoc ( $result_check_manager );
$sql_check_user_department_id = " SELECT `department_id` FROM `users` WHERE `id` = " . $this -> user -> id ;
$result_check_user_department_id = mysql_query ( $sql_check_user_department_id );
$user_department_id = mysql_fetch_assoc ( $result_check_user_department_id );
$sql_check_user_users_admin = " SELECT `users_admin` FROM `users` WHERE `id` = " . $this -> user -> id ;
$result_check_user_users_admin = mysql_query ( $sql_check_user_users_admin );
$check_user_users_admin = mysql_fetch_assoc ( $result_check_user_users_admin );
$r [ 'who_work_id_manager' ] = $who_work_id_manager [ 'id_manager' ];
$r [ 'who_work_department_id' ] = $who_work_id_manager [ 'department_id' ];
//($dep_user_perm['role'] == 'admin_department' && $who_work_id_manager['department_id'] == $this->user->department_id)
$r [ 'user_department_id' ] = $user_department_id [ 'department_id' ];
$r [ 'user_role' ] = $dep_user_perm [ 'role' ];
if ( $this -> user -> agency == 1 || $check_user_users_admin [ 'users_admin' ] == 1 || $r_check_permissions [ 'menu_all_submissions_edit' ] == 1 || $this -> user -> id == $r [ 'who_work' ]) {
$r [ 'allow_edit' ] = 1 ;
} else if (( $dep_user_perm [ 'role' ] == 'admin_department' || $dep_user_perm [ 'role' ] == 'manager_office' ) && $who_work_id_manager [ 'department_id' ] == $user_department_id [ 'department_id' ]) {
$r [ 'allow_edit' ] = 1 ;
} elseif (( $dep_user_perm [ 'role' ] == 'manager_office_menager' || $dep_user_perm [ 'role' ] == 'manager' ) && ( $_SESSION [ 'id' ] == $who_work_id_manager [ 'id_manager' ] || $_SESSION [ 'id_manager' ] == $who_work_id_manager [ 'id_manager' ] || $_SESSION [ 'id_manager' ] == $r [ 'who_work' ])) {
$r [ 'allow_edit' ] = 1 ;
} elseif ( ! ( $dep_user_perm [ 'role' ]) && ( $_SESSION [ 'manager' ] && ( $_SESSION [ 'id' ] == $who_work_id_manager [ 'id_manager' ]))) {
$r [ 'allow_edit' ] = 1 ;
}
}
if ( $this -> agencyId == 19895 ){
$r [ 'no_can_edit_hot' ] = 1 ;
$r [ 'see_modal_client' ] = 0 ;
if ( $this -> user -> agency == 1 || $check_user_users_admin [ 'users_admin' ] == 1 || $r_check_permissions [ 'menu_all_submissions_edit' ] == 1 ) {
$r [ 'no_can_edit_hot' ] = 0 ;
$r [ 'see_modal_client' ] = 1 ;
}
else if (( $dep_user_perm [ 'role' ] == 'admin_department' || $dep_user_perm [ 'role' ] == 'manager_office' ) && $who_work_id_manager [ 'department_id' ] == $user_department_id [ 'department_id' ]) {
$r [ 'no_can_edit_hot' ] = 0 ;
$r [ 'see_modal_client' ] = 1 ;
}
elseif ( $dep_user_perm [ 'role' ] == 'manager_office_menager' && ( $_SESSION [ 'id' ] == $who_work_id_manager [ 'id_manager' ] || $_SESSION [ 'id_manager' ] == $who_work_id_manager [ 'id_manager' ] || $_SESSION [ 'id_manager' ] == $r [ 'who_work' ])) {
$r [ 'no_can_edit_hot' ] = 0 ;
$r [ 'see_modal_client' ] = 1 ;
}
elseif ( ! ( $dep_user_perm [ 'role' ]) && ( $_SESSION [ 'manager' ] && ( $_SESSION [ 'id' ] == $who_work_id_manager [ 'id_manager' ]))){
$r [ 'no_can_edit_hot' ] = 0 ;
$r [ 'see_modal_client' ] = 1 ;
}
}
$r [ 'user' ] = $this -> user ;
$r [ 'manager_id' ] = $r [ 'user_id' ];
$r [ 'manager' ] = $master ;
$r [ 'manager_phone' ] = $r_m [ 'phone' ];
$master_work = $this -> get_who ( $r [ 'who_work' ], $r [ 'id' ], $kanban , $departments , $usersToUse );
$r [ 'master_work_id' ] = $master_work [ 'id' ];
$r [ 'master_work' ] = $master_work [ 'name' ];
$r [ 'master_work_phone' ] = $master_work [ 'phone' ];
$r [ 'master_work_fio' ] = $master_work [ 'fio' ];
$r [ 'master_delete_id' ] = null ;
$r [ 'master_delete' ] = '' ;
$r [ 'master_delete_phone' ] = null ;
if ( $r [ 'deleted' ] > 0 ) {
$master_delete = $this -> get_who_delete ( $r [ 'who_delete' ], $r [ 'id' ], $kanban , $departments , $usersToUse );
$r [ 'master_delete_id' ] = $master_delete [ 'id' ];
$r [ 'master_delete' ] = $master_delete [ 'name' ];
$r [ 'master_delete_phone' ] = $master_delete [ 'phone' ];
if ( $r [ 'confirm' ] == 10 ) {
$r [ 'reason' ] = " Совершена сделка на " . $r [ 'summa' ] . " р у б . " ;
}
}
$doer_yes = array ();
$doer_no = array ();
if ( $r [ 'doer_clients' ] == 1 ){
$doers = array ();
$doers_arr = json_decode ( html_entity_decode ( $r [ 'doers' ]));
foreach ( $doers_arr as $key => $doer ){
if ( $key > 0 ){
$sql_user = " SELECT agency_name, first_name, last_name, middle_name from users WHERE id = " . $key ;
$q_user = $this -> db -> query ( $sql_user );
$r_user = $this -> db -> fetch_assoc ( $q_user );
if ( $doer == 1 ) $doer_yes [] = trim ( $r_user [ 'last_name' ] . ' ' . $r_user [ 'first_name' ] . ' ' . $r_user [ 'middle_name' ]);
if ( $doer == 0 ) $doer_no [] = trim ( $r_user [ 'last_name' ] . ' ' . $r_user [ 'first_name' ] . ' ' . $r_user [ 'middle_name' ]);
}
}
}
$r [ 'doer_yes' ] = $doer_yes ;
$r [ 'doer_no' ] = $doer_no ;
$r [ 'source_see' ] = 1 ;
$r [ 'source_name' ] = $source = '' ;
if ( $r [ 'source' ] > 0 ){
if ( $r [ 'source' ] == 10000 ) {
$r [ 'source_name' ] = 'Объект нашей компании' ;
$source = 'Объект нашей компании' ;
}
else {
if ( isset ( $sourcesToUse ) && isset ( $sourcesToUse [ $r [ 'source' ]])) {
$r [ 'source_name' ] = $sourcesToUse [ $r [ 'source' ]][ 'source' ];
$source = $sourcesToUse [ $r [ 'source' ]][ 'source' ];
$r [ 'source_see' ] = $sourcesToUse [ $r [ 'source' ]][ 'source_see' ];
if ( $r [ 'source_see' ] == 0 ) $r [ 'source_name' ] = '' ;
} else {
$sql_source = " SELECT * FROM advertising_sources WHERE id = $r[source] " ;
$q_source = $this -> db -> query ( $sql_source );
if ( $this -> db -> num_rows ( $q_source ) > 0 ) {
$r_source = $this -> db -> fetch_assoc ( $q_source );
if ( is_see ( $r_source [ 'is_no_see' ], $r_source [ 'users_no_see' ]) === false ){
$r [ 'source_name' ] = '' ;
$source = '' ;
$r [ 'source_see' ] = 0 ;
} else {
$r [ 'source_name' ] = $r_source [ 'source' ];
$source = $r_source [ 'source' ];
}
}
}
}
}
$partner = " " ;
if ( isset ( $r [ 'employee_id' ]) && $r [ 'employee_id' ] > 0 ) {
$partners = new Partners ;
$partner = $partners -> getPartnerByEmployee ( intval ( $r [ 'employee_id' ]));
}
$r [ 'source_name' ] .= ( $partner ) ? (( isset ( $source )) ? " | " : '' ) . $partner [ 'name' ] . (( ! empty ( $partner [ 'resident' ])) ? ' <span class="stagebar-title">(' . $partner [ 'resident' ] . ')</span>' : '' ) : '' ;
$r [ 'employe_name' ] = null ;
if ( isset ( $partner [ 'fullname' ]))
$r [ 'employe_name' ] = $partner [ 'fullname' ];
if ( ! empty ( $partner [ 'position' ])){
$r [ 'employe_name' ] .= " , " . $partner [ 'position' ];
}
//Название воронки
if ( $r [ 'funnel_id' ] == 0 ){
$r [ 'name_funnel' ] = " Обычные " ;
} else {
$sql_fun = " SELECT name FROM funnel WHERE id = " . $r [ 'funnel_id' ];
$r [ 'name_funnel' ] = $this -> db -> fetch_assoc ( $this -> db -> query ( $sql_fun ))[ 'name' ];
}
//Тип заявки
$typesReqNames = $typesReq [ 'names_type' ];
$r [ 'name_type' ] = $typesReqNames [ $r [ 'type_id' ]][ 'name' ];
$r [ 'heir_type' ] = $typesReqNames [ $r [ 'type_id' ]][ 'heir' ];
//Смежные воронки
$r [ 'funnels_adjacent' ] = array ();
$r [ 'funnels_adjacent_text' ] = '' ;
$r [ 'is_active_funnels_adjacent' ] = false ;
$r [ 'is_watched' ] = false ;
if ( $r [ 'funnel_type' ] == 'main' && isset ( $this -> funnels_adjacent [ $r [ 'id' ]])){
$r [ 'funnels_adjacent' ] = $this -> funnels_adjacent [ $r [ 'id' ]];
$new_total = count ( $r [ 'funnels_adjacent' ]);
if ( count ( $r [ 'funnels_adjacent' ]) > 0 ){
$new_text = 'Ещё ' . $new_total ;
if ( $new_total == 1 ){
$new_text .= ' воронка' ;
} else if ( $new_total > 1 && $new_total < 5 ){
$new_text .= ' воронки' ;
} else if ( $new_total > 4 ){
$new_text .= ' воронок' ;
}
$r [ 'funnels_adjacent_text' ] = $new_text ;
}
}
// Получаем данные о просмотренных заявках конкретного объекта
$r [ 'watched_data' ] = null ;
$w_payload = file_get_contents ( " php://input " );
$w_data = json_decode ( $w_payload , true );
$w_object_id = $w_data [ 'object_id' ]; // ID объекта взятый из запроса
if ( $w_object_id === null ) {
$w_object_id = $_GET [ 'object_id' ];
}
$w_user_id = isset ( $_COOKIE [ 'user_id' ]) ? $_COOKIE [ 'user_id' ] : ( isset ( $_SESSION [ 'id' ]) ? $_SESSION [ 'id' ] : null );
if ( $w_object_id !== null ){
$watch_sql = " SELECT * FROM `watched_requisitions`
WHERE `req_id` = { $r [ 'id' ]}
AND `user_id` = { $w_user_id }
AND `object_id` = { $w_object_id } " ;
$watch_query = $this -> db -> query ( $watch_sql );
$watch_result = $this -> db -> fetch_assoc ( $watch_query );
if ( $watch_result ) {
$r [ 'watched_data' ] = $watch_result ;
}
}
if (( $needAutoSearch === true ) && ( $r [ 'type_id' ] == 1 || $r [ 'heir_type' ] == 1 || $r [ 'type_id' ] == 4 || $r [ 'heir_type' ] == 4 )) {
if ( $filter = $this -> autosearch_instce -> getFilterByReq ( $r [ 'id' ], $_SESSION [ 'id' ], false , false , true )) {
if ( isset ( $filter [ 'id' ])) {
$r [ 'autosearch_id' ] = intval ( $filter [ 'id' ]);
$r [ 'autosearch' ] = [
'active' => intval ( $filter [ 'is_active' ]),
'count' => $filter [ 'count' ],
'is_search' => intval ( $filter [ 'is_search' ]),
'is_reverse' => intval ( $filter [ 'is_reverse' ]),
'total' => $filter [ 'total' ],
'error' => $filter [ 'error' ]
];
$info = '' ;
$comment = '' ;
$info_ar = $this -> autosearch_instce -> getFilterInfo ( $filter , true , true );
foreach ( $info_ar as $key => $filter ) {
if ( isset ( $filter [ 'label' ]) && isset ( $filter [ 'value' ])) {
if ( $key === " comment " )
$comment = '<b>' . $filter [ 'label' ] . ':</b> ' . $filter [ 'value' ];
else
$info .= ' <b>' . $filter [ 'label' ] . ':</b> ' . $filter [ 'value' ] . ';' ;
}
$r [ 'autosearch' ][ 'filter' ][ $key ] = [
'id' => $filter [ 'id' ],
'label' => $filter [ 'label' ],
'value' => $filter [ 'value' ]
];
}
if ( ! empty ( $filter [ 'geo' ])) {
$geo = ( array ) json_decode ( $filter [ 'geo' ], true );
$geo = array_filter ( array_map ( function ( $item ) {
return ! empty ( $item );
}, $geo ));
$r [ 'autosearch' ][ 'filter' ][ 'geo' ] = [
'id' => 'geo' ,
'label' => 'Гео' ,
'value' => declOfNum ( count ( $geo ), [ '%d уточнение' , '%d уточнения' , '%d уточнений' ])
];
$info .= ' <b>Гео:</b> ' . declOfNum ( count ( $geo ), [ '%d уточнение' , '%d уточнения' , '%d уточнений' ]) . ';' ;
}
if ( ! empty ( $info )) {
$r [ 'autosearch_info' ] = rtrim ( trim ( $info ), ';' );
$r [ 'autosearch_comment' ] = trim ( $comment ) . " <br/> " . '<b>ID фильтра:</b> ' . $r [ 'autosearch_id' ];
}
}
}
}
$result = $r ;
return $result ;
}
//Получение id заявок с просроченными этапами
public function getIdExpiredStages ( $where ){
$expiredStagesRequisitions = array ();
$stepIds = array ();
$stepDays = array ();
$funnelIds = array ();
if ( $this -> agencyId > 0 ){
$agency_id = $this -> agencyId ;
//Этапы
$sql_f = " SELECT id FROM `funnel` WHERE agency_id= $agency_id AND deleted = 0 " ;
$q_f = $this -> db -> query ( $sql_f );
while ( $r_f = $this -> db -> fetch_assoc ( $q_f )){
$funnelIds [] = ( int ) $r_f [ 'id' ];
}
$sql_st = " SELECT id, days_step FROM funnel_steps WHERE funnel_id in ( " . implode ( ',' , $funnelIds ) . " ) " ;
$q_st = $this -> db -> query ( $sql_st );
while ( $r_st = $this -> db -> fetch_assoc ( $q_st )){
$stepDays [( int ) $r_st [ 'id' ]] = $r_st [ 'days_step' ];
}
$sql = " SELECT id, step_id, created_at, (SELECT date_update FROM clients_funnel_step WHERE req_id=req.id) as date_update FROM requisitions as req WHERE 1 $where AND funnel_id > 0 AND step_id > 0 " ;
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q )){
if ( $stepDays [( int ) $r [ 'step_id' ]] > 0 ){
$days_step = $stepDays [( int ) $r [ 'step_id' ]];
if ( ! empty ( $r [ 'date_update' ])){
$lostDate = $r [ 'date_update' ];
$interval = date_diff ( new DateTime (), new DateTime ( $lostDate )) -> days ;
if ( $interval > $days_step ){
$expiredStagesRequisitions [] = $r [ 'id' ];
}
} else {
$lostDate = $r [ 'created_at' ];
$interval = date_diff ( new DateTime (), new DateTime ( $lostDate )) -> days ;
if ( $interval > $days_step ){
$expiredStagesRequisitions [] = $r [ 'id' ];
}
}
}
}
}
return $expiredStagesRequisitions ;
}
//В с е заявки
public function get_all ( $user = null , $filtr = array (), $funnelId = false , $clientId = false , $objectId = false , $needAutoSearch = true , $complexRoomId = false , $reqs_id = false , $is_cancel = false ){
/* if ( $_SESSION [ 'id' ] == 19895 ){
error_reporting ( E_ALL | E_STRICT );
ini_set ( 'display_errors' , 1 );
} */
$starttime = microtime ( true );
$type = 'list' ;
$order = null ;
$result = array ();
$join = '' ;
if ( $filtr -> stages -> ahency == 1 ) {
$join .= " LEFT JOIN events_clients ON events_clients.id = (SELECT id FROM events_clients WHERE events_clients.req_id = req.id AND (events_clients.event='accepted' or events_clients.event='add' or events_clients.event='update') ORDER BY id DESC LIMIT 1) " ;
}
$priceSelect = '' ;
$priceJoin = '' ;
if ( intval ( $filtr -> priceFrom ) || intval ( $filtr -> priceTo )) {
$priceSelect = ', o.stoim, af.stoim_ot, af.stoim_do' ;
$priceJoin = '
LEFT JOIN objects AS o
ON req . object_id = o . id
LEFT JOIN autosearch_filters AS af
ON req . id = af . req_id ' ;
}
$propertyTypeJoin = '' ;
if ( ! empty ( $filtr -> property_type )){
if ( $priceJoin == '' ){
$propertyTypeJoin = ' LEFT JOIN autosearch_filters AS af
ON req . id = af . req_id ' ;
}
}
if ( $funnelId === 'all' || $funnelId === false ){
$sql = " SELECT req.* $priceSelect FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE 1 " ;
$sqlTotal = " SELECT count(*) as total FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE 1 " ;
$sqlExpectedCommissionTotal = " SELECT sum(req.expected_commission) as total FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE deleted=0 " ;
} else if ( $funnelId == 0 || empty ( $funnelId )){
$funnelId = 0 ;
$sql = " SELECT req.* $priceSelect
FROM requisitions as req
$priceJoin
$propertyTypeJoin
$join WHERE funnel_id in ( $funnelId ) " ;
$sqlTotal = " SELECT count(*) as total
FROM requisitions as req
$priceJoin
$propertyTypeJoin
$join WHERE funnel_id in ( $funnelId ) " ;
$sqlExpectedCommissionTotal = " SELECT sum(req.expected_commission) as total FROM requisitions as req
$priceJoin
$propertyTypeJoin
$join WHERE funnel_id in ( $funnelId ) AND deleted = 0 " ;
} else {
$sql = " SELECT req.* $priceSelect FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE funnel_id in ( $funnelId ) " ;
$sqlTotal = " SELECT count(*) as total FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE funnel_id in ( $funnelId ) " ;
$sqlExpectedCommissionTotal = " SELECT sum(req.expected_commission) as total FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE funnel_id in ( $funnelId ) AND deleted=0 " ;
if ( $funnelId > 0 ){
$sqlPart1 = " SELECT req.id, req.name, req.user_id, req.created_at, req.client_id,
req . object_id , req . type_id , req . funnel_id , req . step_id , req . who_work , req . who_delete ,
req . confirm , req . description ,
req . stage , req . deleted , req . cancel , req . priority , req . doer_clients ,
req . hot , req . reason , req . denial , req . summa , req . expected_commission , req . activities , req . asfilter_id ,
req . source , req . doers , req . doers_confirm , req . employee_id , req . property_type_id ,
2026-06-20 10:19:54 +02:00
req . integration , req . call_id , req . friend_client_id , req . confirm_recommendation , req . deal_id , req . id as reqid ,
2026-05-22 20:21:54 +02:00
'main' as funnel_type ,
req . complex_room_id $priceSelect
FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE funnel_id in ( $funnelId ) " ;
//$sql .= ' UNION ';
$sqlPart2 = " SELECT req.id, req.name, req.user_id, req.created_at, req.client_id,
req . object_id , req . type_id , a . funnel_id , a . step_id_active as step_id ,
a . who_work as who_work , req . who_delete , a . confirm , req . description ,
req . stage , req . deleted , req . cancel , req . priority , req . doer_clients ,
req . hot , req . reason , req . denial , req . summa , req . expected_commission , req . activities , req . asfilter_id ,
req . source , req . doers , req . doers_confirm , req . employee_id , req . property_type_id ,
2026-06-20 10:19:54 +02:00
req . integration , req . call_id , 0 as friend_client_id , 0 as confirm_recommendation , req . deal_id , req . id as reqid ,
2026-05-22 20:21:54 +02:00
'adjacent' as funnel_type ,
req . complex_room_id $priceSelect
FROM adjacent_funnels as a
LEFT JOIN requisitions as req on a . req_id = req . id $priceJoin $propertyTypeJoin $join WHERE a . funnel_id in ( $funnelId ) " ;
$sqlTotalPart1 = " SELECT count(*) as total FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE funnel_id in ( $funnelId ) " ;
$sqlTotalPart2 = " SELECT count(*) as total FROM adjacent_funnels as a LEFT JOIN requisitions as req on a.req_id = req.id $priceJoin $propertyTypeJoin $join WHERE a.funnel_id in ( $funnelId ) " ;
$sqlExpectedCommissionTotalPart1 = " SELECT sum(req.expected_commission) as total FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE funnel_id in ( $funnelId ) AND deleted=0 " ;
$sqlExpectedCommissionTotalPart2 = " SELECT sum(req.expected_commission) as total FROM adjacent_funnels as a LEFT JOIN requisitions as req on a.req_id = req.id $priceJoin $propertyTypeJoin $join WHERE a.funnel_id in ( $funnelId ) AND deleted=0 " ;
}
}
if ( $clientId ){
unset ( $sqlPart1 );
unset ( $sqlPart2 );
$sql = " SELECT req.* $priceSelect FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE client_id= $clientId " ;
$sqlTotal = " SELECT count(*) as total FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE client_id= $clientId " ;
}
if ( $objectId ){
unset ( $sqlPart1 );
unset ( $sqlPart2 );
$sql = " SELECT req.* $priceSelect FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE (type_id = 4 or type_id in (SELECT id FROM requisitions_type WHERE heir = 4 AND agency_id = { $this -> agencyId } )) and object_id= $objectId " ;
$sqlTotal = " SELECT count(*) as total FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE (type_id = 4 or type_id in (SELECT id FROM requisitions_type WHERE heir = 4 AND agency_id = { $this -> agencyId } )) and object_id= $objectId " ;
}
if ( $complexRoomId ){
unset ( $sqlPart1 );
unset ( $sqlPart2 );
$sql = " SELECT req.* $priceSelect FROM requisitions as req $priceJoin $propertyTypeJoin $join where `complex_room_id` = $complexRoomId " ;
$sqlTotal = " SELECT count(*) as total FROM requisitions as req $priceJoin $propertyTypeJoin $join where `complex_room_id` = $complexRoomId " ;
}
if ( $reqs_id ){
unset ( $sqlPart1 );
unset ( $sqlPart2 );
if ( ! empty ( $reqs_id )){
$sql = " SELECT req.* $priceSelect FROM requisitions as req $priceJoin $propertyTypeJoin $join where `id` in ( " . implode ( ',' , $reqs_id ) . " ) " ;
$sqlTotal = " SELECT count(*) as total FROM requisitions as req $priceJoin $propertyTypeJoin $join where `id` in ( " . implode ( ',' , $reqs_id ) . " ) " ;
} else {
$sql = " SELECT req.* $priceSelect FROM requisitions as req $priceJoin $propertyTypeJoin $join where `id` in (0) " ;
$sqlTotal = " SELECT count(*) as total FROM requisitions as req $priceJoin $propertyTypeJoin $join where `id` in (0) " ;
}
}
// $result['sql'] = $sql;
//Фильтры
$where = " AND cancel=0 " ;
$wherePart1 = " AND cancel=0 " ;
$wherePart2 = " AND cancel=0 " ;
if ( $is_cancel ){
$where = " AND cancel=1 " ;
$wherePart1 = " AND cancel=1 " ;
$wherePart2 = " AND cancel=1 " ;
}
if ( ! empty ( $filtr )){
if ( isset ( $filtr -> order )){
if ( $filtr -> order == 1 ){
$order = 'asc' ;
} else if ( $filtr -> order == 2 ) {
$order = 'desc' ;
} else {
$order = null ;
}
}
if ( ! empty ( $filtr -> search )){
$filtr -> search = mb_strtolower ( trim ( $filtr -> search ), " UTF-8 " );
$phone = preg_replace ( '/[+\-\(\)\/\?,.;:%№!\s]/' , '' , $filtr -> search );
$sql_cl = " SELECT id FROM clients WHERE phone like '% " . $phone . " %' " ;
$q_cl = $this -> db -> query ( $sql_cl );
$clients = array ();
while ( $r_cl = $this -> db -> fetch_assoc ( $q_cl )){
$clients [] = ( int ) $r_cl [ 'id' ];
}
$sql_cl_phone2 = " SELECT DISTINCT client_id FROM clients_phone2 WHERE phone like '% " . $phone . " %' " ;
$q_cl_phone2 = $this -> db -> query ( $sql_cl_phone2 );
while ( $r_cl_phone2 = $this -> db -> fetch_assoc ( $q_cl_phone2 )) {
$clients [] = ( int ) $r_cl_phone2 [ 'client_id' ];
}
$clients = array_unique ( $clients );
$where .= " AND (name like '% " . $filtr -> search . " %' " ;
$wherePart1 .= " AND (name like '% " . $filtr -> search . " %' " ;
$wherePart2 .= " AND (name like '% " . $filtr -> search . " %' " ;
if ( ! empty ( $clients )){
$where .= " or req.client_id in ( " . implode ( ',' , $clients ) . " ) " ;
$wherePart1 .= " or req.client_id in ( " . implode ( ',' , $clients ) . " ) " ;
$wherePart2 .= " or req.client_id in ( " . implode ( ',' , $clients ) . " ) " ;
}
if ( preg_match ( '/^\d+$/' , $filtr -> search )){
$where .= " or req.id = " . $filtr -> search ;
$wherePart1 .= " or req.id = " . $filtr -> search ;
$wherePart2 .= " or req.id = " . $filtr -> search ;
}
$where .= " ) " ;
$wherePart1 .= " ) " ;
$wherePart2 .= " ) " ;
}
if ( isset ( $filtr -> stages )){
$uIds = array ();
$query = mysql_query ( " select id from users where id= $user or id_manager= $user or id_manager in
( select id from users where id_manager = $user or id_manager in
( select id from users where id_manager = $user )) " );
while ( $us = mysql_fetch_assoc ( $query )) {
$uIds [] = $us [ 'id' ];
}
$all_null = true ;
foreach ( $filtr -> stages as $value ) {
if (( int ) $value !== 0 ) {
$all_null = false ;
break ;
}
}
if ( isset ( $filtr -> filter_stage ) && $filtr -> filter_stage == 'filter_stage_work' ){
$where .= " AND deleted = 0 " ;
$wherePart1 .= " AND deleted = 0 " ;
$wherePart2 .= " AND deleted = 0 " ;
} else {
foreach ( $filtr -> stages as $key => $stage ){
if ( $stage == 1 ){
switch ( $key ) {
case 'work' : {
$where .= " AND deleted = 0 AND confirm = 1 " ;
$wherePart1 .= " AND deleted = 0 AND req.confirm = 1 " ;
$wherePart2 .= " AND deleted = 0 AND a.confirm = 1 " ;
break ;
}
case 'hot' : {
$where .= " AND deleted = 0 AND hot > 0 AND confirm = 1 " ;
$wherePart1 .= " AND deleted = 0 AND hot > 0 AND req.confirm = 1 " ;
$wherePart2 .= " AND deleted = 0 AND hot > 0 AND a.confirm = 1 " ;
break ;
}
case 'close' : {
$where .= " AND deleted = 1 AND confirm <> 10 " ;
$wherePart1 .= " AND deleted = 1 AND req.confirm <> 10 " ;
$wherePart2 .= " AND deleted = 1 AND a.confirm <> 10 " ;
break ;
}
case 'hit' : {
$where .= " AND deleted = 1 AND confirm = 10 " ;
$wherePart1 .= " AND deleted = 1 AND req.confirm = 10 " ;
$wherePart2 .= " AND deleted = 1 AND a.confirm = 10 " ;
break ;
}
case 'ahency' : {
$where .= " AND deleted = 0 AND confirm = 0 AND who_work = 0 " ;
$wherePart1 .= " AND deleted = 0 AND req.confirm = 0 AND req.who_work = 0 " ;
$wherePart2 .= " AND deleted = 0 AND a.confirm = 0 AND a.who_work = 0 " ;
break ;
}
case 'confirm' : {
$where .= " AND deleted = 0 AND confirm = 0 AND who_work <> 0 " ;
$wherePart1 .= " AND deleted = 0 AND req.confirm = 0 AND req.who_work <> 0 " ;
$wherePart2 .= " AND deleted = 0 AND a.confirm = 0 AND a.who_work <> 0 " ;
break ;
}
case 'send' : {
$where .= " AND deleted = 0 AND confirm = 0 AND who_work <> $user " ;
$wherePart1 .= " AND deleted = 0 AND req.confirm = 0 AND req.who_work <> $user " ;
$wherePart2 .= " AND deleted = 0 AND a.confirm = 0 AND a.who_work <> $user " ;
break ;
}
}
}
}
}
} else {
$where .= " AND deleted = 0 " ;
$wherePart1 .= " AND deleted = 0 " ;
$wherePart2 .= " AND deleted = 0 " ;
}
if ( ! empty ( $filtr -> emp )){
//var_dump($filtr->emp);
if ( $filtr -> stages -> ahency ) {
$empwho = array ();
foreach ( $filtr -> emp as $empId ) {
if ( strpos ( $empId , " all_ " ) !== false ){
$agencyId = str_replace ( 'all_' , '' , $empId );
$sqId = " 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 in (select id from users where id_manager= $agencyId )) " ;
$sqIdQuery = mysql_query ( $sqId );
while ( $idRow = mysql_fetch_array ( $sqIdQuery )) {
$empwho [] = intval ( $idRow [ 'id' ]);
}
} else if ( $empId == 'del_all' ){
$user_agency = new User ;
$user_agency -> get ( $_SESSION [ 'id' ]);
$agencyId = $user_agency -> agencyId ;
$sqId = " 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 in (select id from users where id_manager= $agencyId ))) AND blocked=1 " ;
$sqIdQuery = mysql_query ( $sqId );
while ( $idRow = mysql_fetch_array ( $sqIdQuery )) {
$empwho [] = intval ( $idRow [ 'id' ]);
}
$sqlDel = " SELECT user_id FROM users_delete WHERE agency_id = { $agencyId } " ;
$qDel = mysql_query ( $sqlDel );
while ( $rDel = mysql_fetch_assoc ( $qDel )){
$empwho [] = intval ( $rDel [ 'user_id' ]);
}
} else {
$empwho [] = intval ( $empId );
}
}
if ( ! empty ( $empwho )) {
$empwho = array_unique ( $empwho );
$where .= " AND (events_clients.user_id IN ( " . implode ( ',' , $empwho ) . " )) " ;
$wherePart1 .= " AND (events_clients.user_id IN ( " . implode ( ',' , $empwho ) . " )) " ;
$wherePart2 .= " AND (events_clients.user_id IN ( " . implode ( ',' , $empwho ) . " )) " ;
}
} else {
$empwho = array ();
$empwho1 = array ();
$empwho2 = array ();
foreach ( $filtr -> emp as $empId ){
$temp_where = '' ;
//$empwho[] = "id_agent = $empId";
if ( strpos ( $empId , " all_ " ) !== false ){
$agencyId = str_replace ( 'all_' , '' , $empId );
$stremp = " (who_work 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 in (select id from users where id_manager= $agencyId ))) " ;
$stremp1 = " (req.who_work 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 in (select id from users where id_manager= $agencyId ))) " ;
$stremp2 = " (a.who_work 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 in (select id from users where id_manager= $agencyId ))) " ;
/* if ( $post [ 'emp' ]){
$stremp .= " or (doers like '%" " . $post [ 'emp' ] . " "%') " ;
} */
$empwho [] = $stremp .= " ) " ;
$empwho1 [] = $stremp1 .= " ) " ;
$empwho2 [] = $stremp2 .= " ) " ;
} else if ( $empId == 'del_all' ){
$user_agency = new User ;
$user_agency -> get ( $_SESSION [ 'id' ]);
$agencyId = $user_agency -> agencyId ;
$sqId = " 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 in (select id from users where id_manager= $agencyId ))) AND blocked=1 " ;
$sqIdQuery = mysql_query ( $sqId );
while ( $idRow = mysql_fetch_array ( $sqIdQuery )) {
$empwho [] = " who_work = " . ( intval ( $idRow [ 'id' ]));
$empwho1 [] = " req.who_work = " . ( intval ( $idRow [ 'id' ]));
$empwho2 [] = " a.who_work = " . ( intval ( $idRow [ 'id' ]));
}
$sqlDel = " SELECT user_id FROM users_delete WHERE agency_id = { $agencyId } " ;
$qDel = mysql_query ( $sqlDel );
while ( $rDel = mysql_fetch_assoc ( $qDel )){
// $empwho[] = intval($rDel['user_id']);
$empwho [] = " who_work = " . intval ( $rDel [ 'user_id' ]);
$empwho1 [] = " req.who_work = " . intval ( $rDel [ 'user_id' ]);
$empwho2 [] = " a.who_work = " . intval ( $rDel [ 'user_id' ]);
}
}
else {
$empwho [] = " who_work = $empId " ;
$empwho1 [] = " req.who_work = $empId " ;
$empwho2 [] = " a.who_work = $empId " ;
}
}
if ( ! empty ( $empwho )){
$where .= " AND ( " . implode ( " OR " , $empwho ) . " ) " ;
}
if ( ! empty ( $empwho1 )){
$wherePart1 .= " AND ( " . implode ( " OR " , $empwho1 ) . " ) " ;
}
if ( ! empty ( $empwho2 )){
$wherePart2 .= " AND ( " . implode ( " OR " , $empwho2 ) . " ) " ;
}
//$where .= " AND who_work in (".implode(',',$filtr->emp).")";
}
}
if ( ! empty ( $filtr -> type )){
$types_req = $this -> get_types_type ( $filtr -> type );
$where .= " AND req.type_id in ( " . implode ( ',' , $types_req ) . " ) " ;
$wherePart1 .= " AND req.type_id in ( " . implode ( ',' , $types_req ) . " ) " ;
$wherePart2 .= " AND req.type_id in ( " . implode ( ',' , $types_req ) . " ) " ;
}
if ( ! empty ( $filtr -> property_type )){
$search_p_t = $filtr -> property_type ;
$search_au_t = [];
if ( in_array ( 10 , $search_p_t )){ //Если выбран тип "квартира"
array_push ( $search_p_t , 1 , 2 , 3 , 4 , 5 );
}
if ( in_array ( 1 , $search_p_t )){ //Если выбран тип "квартира"
array_push ( $search_p_t , 11 );
}
$search_p_t = array_unique ( $search_p_t );
foreach ( $search_p_t as $pr ){
if ( in_array ( $pr , [ 1 , 2 , 3 , 4 , 5 ])){
$search_au_t [] = 'JSON_CONTAINS(af.rooms, \'"' . $pr . '"\')' ;
}
}
$where .= " AND (req.property_type_id in ( " . implode ( ',' , $search_p_t ) . " ) " ;
$wherePart1 .= " AND (req.property_type_id in ( " . implode ( ',' , $search_p_t ) . " ) " ;
$wherePart2 .= " AND (req.property_type_id in ( " . implode ( ',' , $search_p_t ) . " ) " ;
if ( ! empty ( $search_au_t )){
$where .= " OR ( " . implode ( ' OR ' , $search_au_t ) . " ) " ;
$wherePart1 .= " OR ( " . implode ( ' OR ' , $search_au_t ) . " ) " ;
$wherePart2 .= " OR ( " . implode ( ' OR ' , $search_au_t ) . " ) " ;
}
$where .= " ) " ;
$wherePart1 .= " ) " ;
$wherePart2 .= " ) " ;
// AND (req.property_type_id in (1) or ( JSON_CONTAINS(af.rooms, '"1"') or JSON_CONTAINS(af.rooms, '"4"')))
}
if ( ! empty ( $filtr -> step )){
// var_dump($filtr->step);
if ( isset ( $filtr -> is_date_step ) && $filtr -> is_date_step > 0 ){
$req_ids_step = array ();
$sql_step = " SELECT * FROM steps_history WHERE req_id > 0 AND step_id in ( " . implode ( ',' , $filtr -> step ) . " ) " ;
if ( isset ( $filtr -> onDateStep ) && $filtr -> onDateStep > 0 ){
$date_on = strtotime ( $filtr -> onDateStep . " 00:00:00 " );
$sql_step .= " AND date >= $date_on " ;
}
if ( isset ( $filtr -> offDateStep ) && $filtr -> offDateStep > 0 ){
$date_off = strtotime ( $filtr -> offDateStep . " 23:59:59 " );
$sql_step .= " AND date <= $date_off " ;
}
$q_step = $this -> db -> query ( $sql_step );
while ( $r_step = $this -> db -> fetch_assoc ( $q_step )){
$req_ids_step [] = $r_step [ 'req_id' ];
}
// $part_where_step = " AND req.id in (".implode(',', $req_ids_step).")";
if ( ! empty ( $req_ids_step )){
$where .= " AND id in ( " . implode ( ',' , $req_ids_step ) . " ) " ;
$wherePart1 .= " AND req.id in ( " . implode ( ',' , $req_ids_step ) . " ) " ;
$wherePart2 .= " AND req.id in ( " . implode ( ',' , $req_ids_step ) . " ) " ;
} else {
$where .= " AND id in (0) " ;
$wherePart1 .= " AND req.id in (0) " ;
$wherePart2 .= " AND req.id in (0) " ;
}
} else {
if ( $funnelId == 0 ){
$where .= " AND stage in ( " . implode ( ',' , $filtr -> step ) . " ) " ;
$wherePart1 .= " AND stage in ( " . implode ( ',' , $filtr -> step ) . " ) " ;
$wherePart2 .= " AND stage in ( " . implode ( ',' , $filtr -> step ) . " ) " ;
} else if ( $funnelId > 0 ){
$where .= " AND step_id in ( " . implode ( ',' , $filtr -> step ) . " ) " ;
$wherePart1 .= " AND req.step_id in ( " . implode ( ',' , $filtr -> step ) . " ) " ;
$wherePart2 .= " AND a.step_id in ( " . implode ( ',' , $filtr -> step ) . " ) " ;
}
}
} else if ( isset ( $filtr -> step_id ) && $filtr -> step_id !== 'all' ){
if ( $funnelId == 0 ){
$where .= " AND stage in ( " . $filtr -> step_id . " ) " ;
$wherePart1 .= " AND stage in ( " . $filtr -> step_id . " ) " ;
$wherePart2 .= " AND stage in ( " . $filtr -> step_id . " ) " ;
} else if ( $funnelId > 0 ){
$where .= " AND step_id in ( " . $filtr -> step_id . " ) " ;
$wherePart1 .= " AND req.step_id in ( " . $filtr -> step_id . " ) " ;
$wherePart2 .= " AND a.step_id in ( " . $filtr -> step_id . " ) " ;
}
}
if ( isset ( $filtr -> total_union ) && $filtr -> total_union != '' && $filtr -> total_union != 'null' && ! is_null ( $filtr -> total_union )){
$total_union = ( int ) $filtr -> total_union ;
$where .= " AND (SELECT count(id) as total_union FROM union_requisitions WHERE union_requisitions.main_id = req.id) = { $total_union } " ;
$wherePart1 .= " AND (SELECT count(id) as total_union FROM union_requisitions WHERE union_requisitions.main_id = req.id) = { $total_union } " ;
$wherePart2 .= " AND (SELECT count(id) as total_union FROM union_requisitions WHERE union_requisitions.main_id = a.id) = { $total_union } " ;
}
if ( isset ( $filtr -> denial ) && ! empty ( $filtr -> denial )){
$where .= " AND denial in ( " . implode ( ',' , $filtr -> denial ) . " ) " ;
$wherePart1 .= " AND denial in ( " . implode ( ',' , $filtr -> denial ) . " ) " ;
$wherePart2 .= " AND denial in ( " . implode ( ',' , $filtr -> denial ) . " ) " ;
}
$priority_where = '' ;
if ( isset ( $filtr -> priority )){
foreach ( $filtr -> priority as $key => $pr ){
if ( $pr > 0 ){
if ( $priority_where == '' ){
$priority_where .= " AND (priority = " . $key ;
} else {
$priority_where .= " or priority = " . $key ;
}
}
}
}
if ( $priority_where != '' ){
$priority_where .= " ) " ;
$where .= $priority_where ;
$wherePart1 .= $priority_where ;
$wherePart2 .= $priority_where ;
}
if ( ! empty ( $filtr -> object_id )){
$where .= " AND object_id = " . ( int ) $filtr -> object_id ;
$wherePart1 .= " AND object_id = " . ( int ) $filtr -> object_id ;
$wherePart2 .= " AND object_id = " . ( int ) $filtr -> object_id ;
}
$tasksConditions = [];
// "С задачами"
if ( isset ( $filtr -> is_tasks ) && $filtr -> is_tasks ) {
$tasksConditions [] = " (SELECT count(id) FROM user_client_events WHERE calendar_view = 0
and schedule_date is not null and req_id = req . id and schedule_date > '2001-03-10 17:16:18' ) > 0 " ;
}
// "Без задач"
if ( isset ( $filtr -> noTasks ) && $filtr -> noTasks ) {
$tasksConditions [] = " (SELECT count(id) FROM user_client_events WHERE calendar_view = 0
and schedule_date is not null and req_id = req . id ) = 0 " ;
}
// "Задачи на сегодня"
if ( isset ( $filtr -> todayTasks ) && $filtr -> todayTasks ) {
$tasksConditions [] = " (SELECT count(id) FROM user_client_events WHERE calendar_view = 0
and schedule_date is not null and req_id = req . id
and DATE_FORMAT ( schedule_date , '%Y-%m-%d' ) = '".date("Y-m-d")."' ) > 0 " ;
}
// "Просроченные задачи"
if ( isset ( $filtr -> overTasks ) && $filtr -> overTasks ) {
if ( empty ( $this -> userIdsWork )) {
$this -> getIdsUsers ( $this -> user -> id );
}
$tasksConditions [] = " (SELECT count(id) FROM user_client_events
WHERE user_id in ( " .implode(',', $this->userIdsWork ). " )
and type != 'comment' and calendar_view = 0 and cancel = 0
and schedule_date is not null and req_id = req . id
and schedule_date <= '".date("Y-m-d H:i:s")."' ) > 0 " ;
}
if ( ! empty ( $tasksConditions )) {
// Если только одно условие - добавляем е г о напрямую
if ( count ( $tasksConditions ) === 1 ) {
$condition = $tasksConditions [ 0 ];
$where .= " AND $condition " ;
$wherePart1 .= " AND $condition " ;
$wherePart2 .= " AND $condition " ;
}
// Если несколько условий - объединяем через OR
else {
$combinedCondition = " ( " . implode ( " OR " , $tasksConditions ) . " ) " ;
$where .= " AND $combinedCondition " ;
$wherePart1 .= " AND $combinedCondition " ;
$wherePart2 .= " AND $combinedCondition " ;
}
}
if ( isset ( $filtr -> is_contract ) && $filtr -> is_contract > 0 ){
$part_where = " AND (SELECT count(id) FROM contracts_req WHERE req_id=req.id " ;
if ( isset ( $filtr -> numder_contract ) && ! empty ( $filtr -> numder_contract )){
$part_where .= " AND number like '% { $filtr -> numder_contract } %' " ;
}
if ( isset ( $filtr -> type_contract ) && ! empty ( $filtr -> type_contract )){
$part_where .= " AND type in ( " . implode ( ',' , $filtr -> type_contract ) . " ) " ;
}
if ( isset ( $filtr -> onDateContract ) && $filtr -> onDateContract > 0 ){
$date_on = strtotime ( $filtr -> onDateContract . " 00:00:00 " );
$part_where .= " AND date_end >= $date_on " ;
}
if ( isset ( $filtr -> offDateContract ) && $filtr -> offDateContract > 0 ){
$date_off = strtotime ( $filtr -> offDateContract . " 23:59:59 " );
$part_where .= " AND date_end <= $date_off " ;
}
$part_where .= " ) > 0 " ;
$where .= $part_where ;
$wherePart1 .= $part_where ;
$wherePart2 .= $part_where ;
}
if ( isset ( $filtr -> period ) && $filtr -> period ){
$onDate = null ; $offDate = null ;
if ( $filtr -> period == 'period' ){
if ( ! empty ( $filtr -> onDate ) || ! empty ( $filtr -> offDate )){
if ( $filtr -> onDate != '' ){
$onDate = $filtr -> onDate ;
}
if ( $filtr -> offDate != '' ){
$offDate = $filtr -> offDate ;
}
} else if (( isset ( $filtr -> date_start ) && ! empty ( $filtr -> date_start )) || ( isset ( $filtr -> date_end ) && ! empty ( $filtr -> date_end ))){
if ( isset ( $filtr -> date_start ) && ! empty ( $filtr -> date_start )){
$onDate = date ( 'd.m.Y H:i:s' , $filtr -> date_start );
}
if ( isset ( $filtr -> date_end ) && ! empty ( $filtr -> date_end )){
$offDate = date ( 'd.m.Y H:i:s' , $filtr -> date_end );
}
}
}
$dates = $this -> getPeriod ( $filtr -> period , $onDate , $offDate );
$date_between = $dates [ 'between' ];
$whereTasks = $dates [ 'whereTasks' ];
if ( isset ( $filtr -> filter_stage ) && $filtr -> filter_stage == 'filter_work_all_do' ){
$where .= " AND req.created_at < ' $dates[dateStart] ' " ;
$wherePart1 .= " AND req.created_at < ' $dates[dateStart] ' " ;
$wherePart2 .= " AND req.created_at < ' $dates[dateStart] ' " ;
} else if ( isset ( $filtr -> stages ) && $filtr -> stages -> hit > 0 ){
$where .= " AND ((SELECT date_update FROM `events_clients` WHERE req_id=req.id and event='delete' order by id desc limit 1) $date_between ) " ;
$wherePart1 .= " AND ((SELECT date_update FROM `events_clients` WHERE req_id=req.id and event='delete' order by id desc limit 1) $date_between ) " ;
$wherePart2 .= " AND ((SELECT date_update FROM `events_clients` WHERE req_id=req.id and event='delete' order by id desc limit 1) $date_between ) " ;
} else if ( isset ( $filtr -> stages ) && $filtr -> stages -> close > 0 ){
if ( isset ( $filtr -> date_closer ) && ( int ) $filtr -> date_closer == 11 ){
$where .= " AND req.created_at $date_between " ;
$wherePart1 .= " AND req.created_at $date_between " ;
$wherePart2 .= " AND req.created_at $date_between " ;
} else {
$where .= " AND ((SELECT date_update FROM `events_clients` WHERE req_id=req.id and event='delete' order by id desc limit 1) $date_between ) " ;
$wherePart1 .= " AND ((SELECT date_update FROM `events_clients` WHERE req_id=req.id and event='delete' order by id desc limit 1) $date_between ) " ;
$wherePart2 .= " AND ((SELECT date_update FROM `events_clients` WHERE req_id=req.id and event='delete' order by id desc limit 1) $date_between ) " ;
}
} else {
$where .= " AND req.created_at " . $date_between ;
$wherePart1 .= " AND req.created_at " . $date_between ;
$wherePart2 .= " AND req.created_at " . $date_between ;
}
}
if ( isset ( $filtr -> activities ) && ! empty ( $filtr -> activities )){
$activity_req = array ();
/* foreach ( $filtr -> activities as $tag ){
$activitieArr [] = " `activities` like '%" { $tag } "%' " ;
}
$where .= " AND ( " . implode ( " OR " , $activitieArr ) . " ) " ; */
$sql_a = " SELECT req_id FROM requisitions_activities as a LEFT JOIN requisitions as r on r.id=a.req_id WHERE a.activity_id in ( " . implode ( ',' , $filtr -> activities ) . " ) AND r.cancel = 0 " ;
/* if ( $_SESSION [ 'id' ] == 19895 ){
echo $sql_a ;
} */
$q_a = $this -> db -> query ( $sql_a );
while ( $r_a = $this -> db -> fetch_assoc ( $q_a )){
$activity_req [] = $r_a [ 'req_id' ];
}
if ( ! empty ( $activity_req )){
$where .= " AND req.id in ( " . implode ( " , " , $activity_req ) . " ) " ;
$wherePart1 .= " AND req.id in ( " . implode ( " , " , $activity_req ) . " ) " ;
$wherePart2 .= " AND req.id in ( " . implode ( " , " , $activity_req ) . " ) " ;
} else {
$where .= " AND id in (0) " ;
$wherePart1 .= " AND id in (0) " ;
$wherePart2 .= " AND id in (0) " ;
}
}
if ( isset ( $filtr -> source ) && $filtr -> source != - 1 ){
$source_filter = array ();
foreach ( $filtr -> source as $source ){
if ( strpos ( $source , 'all_' ) === false ){
$source_filter [] = $source ;
} else {
$source_group = ( int ) str_replace ( 'all_' , '' , $source );
if ( $source_group > 0 ){
$sql_adv = " SELECT * FROM `advertising_sources` WHERE group_id = { $source_group } " ;
$q_adv = $this -> db -> query ( $sql_adv );
while ( $r_adv = $this -> db -> fetch_assoc ( $q_adv )){
$source_filter [] = ( int ) $r_adv [ 'id' ];
}
} else if ( $source_group == 0 ){
$users_ids_this = array ();
$CallEvents = new CallEvents ();
$user_this = new User ;
$user_this -> get ( $_SESSION [ 'id' ]);
$users_ids_this = array_keys ( $CallEvents -> getAllUserAgency ( $user_this -> agencyId , $users_ids_this ));
$sql_adv = " SELECT * FROM `advertising_sources` WHERE group_id = { $source_group } AND (user_id in ( " . implode ( ',' , $users_ids_this ) . " ) or manager_id in ( " . implode ( ',' , $users_ids_this ) . " )) " ;
$q_adv = $this -> db -> query ( $sql_adv );
while ( $r_adv = $this -> db -> fetch_assoc ( $q_adv )){
$source_filter [] = ( int ) $r_adv [ 'id' ];
}
}
}
}
if ( ! empty ( $source_filter )){
$where .= " AND source in ( " . implode ( ',' , $source_filter ) . " ) " ;
$wherePart1 .= " AND source in ( " . implode ( ',' , $source_filter ) . " ) " ;
$wherePart2 .= " AND source in ( " . implode ( ',' , $source_filter ) . " ) " ;
}
}
if ( isset ( $filtr -> employee_id ) && $filtr -> employee_id != - 1 ){
$filter_partners = $filtr -> employee_id ;
$employees_ids = [];
$partners = new Partners ();
foreach ( $filter_partners as $employee ) {
if ( preg_match ( '/all_(\d+)/' , $employee , $matches )) {
if ( $id = intval ( $matches [ 1 ])) {
$employees = $partners -> getEmployeesId ( $id , false );
foreach ( $employees as $employee ) {
$employees_ids [] = $employee ;
}
}
} else {
$employees_ids [] = $employee ;
}
}
$where .= " AND employee_id in ( " . implode ( " , " , $employees_ids ) . " ) " ;
$wherePart1 .= " AND employee_id in ( " . implode ( " , " , $employees_ids ) . " ) " ;
$wherePart2 .= " AND employee_id in ( " . implode ( " , " , $employees_ids ) . " ) " ;
}
if ( isset ( $filtr -> fields ) && ! empty (( array ) $filtr -> fields ) && count (( array ) $filtr -> fields ) > 0 ){
$partWhere = $this -> queryField ( $filtr -> fields );
$where .= $partWhere ;
$wherePart1 .= $partWhere ;
$wherePart2 .= $partWhere ;
}
if ( ! empty ( $filtr -> id )) {
if ( is_array ( $filtr -> id )){
$where .= " AND id IN ( " . implode ( ',' , $filtr -> id ) . " ) " ;
$wherePart1 .= " AND req.id IN ( " . implode ( ',' , $filtr -> id ) . " ) " ;
$wherePart2 .= " AND req.id IN ( " . implode ( ',' , $filtr -> id ) . " ) " ;
}
else {
$where .= " AND id = " . $filtr -> id ;
$wherePart1 .= " AND req.id = " . $filtr -> id ;
$wherePart2 .= " AND req.id = " . $filtr -> id ;
}
}
if ( ! empty ( $filtr -> not_id )) {
if ( is_array ( $filtr -> not_id )){
$where .= " AND id NOT IN ( " . implode ( ',' , $filtr -> not_id ) . " ) " ;
$wherePart1 .= " AND req.id NOT IN ( " . implode ( ',' , $filtr -> not_id ) . " ) " ;
$wherePart2 .= " AND req.id NOT IN ( " . implode ( ',' , $filtr -> not_id ) . " ) " ;
}
else {
$where .= " AND id != " . $filtr -> not_id ;
$wherePart1 .= " AND req.id != " . $filtr -> not_id ;
$wherePart2 .= " AND req.id != " . $filtr -> not_id ;
}
}
if ( isset ( $filtr -> isPartner ) && $filtr -> isPartner > 0 ){
$where .= " AND doer_clients = 1 " ;
$wherePart1 .= " AND doer_clients = 1 " ;
$wherePart2 .= " AND doer_clients = 1 " ;
}
2026-06-18 13:16:44 +02:00
if ( isset ( $filtr -> is_deal ) && $filtr -> is_deal ){
$where .= " AND req.deal_id IS NOT NULL AND req.deal_id > 0 " ;
$wherePart1 .= " AND req.deal_id IS NOT NULL AND req.deal_id > 0 " ;
$wherePart2 .= " AND req.deal_id IS NOT NULL AND req.deal_id > 0 " ;
}
2026-05-22 20:21:54 +02:00
if ( isset ( $filtr -> expired_stages ) && $filtr -> expired_stages > 0 ){
$expired_stages = 1 ;
}
// echo $sql;
} else {
if ( $clientId ){
$where .= " " ;
} else if ( $objectId ){
$where .= " " ;
} else if ( $reqs_id ){
$where .= " " ;
} else {
$where .= " AND deleted = 0 AND confirm = 1 " ;
}
//$sql .= $where;
}
$is_stats = false ;
if ( isset ( $filtr -> is_stats )){
$is_stats = true ;
}
if ( isset ( $filtr -> userId )){
$user = $filtr -> userId ;
if ( strpos ( $user , " I_ " ) !== false ){
$user = str_replace ( 'I_' , '' , $user );
}
}
if ( isset ( $filtr -> transmitted )){
$where .= " AND (SELECT count(id) FROM events_clients WHERE event='transmitted'
and events_clients . user_id = " . $user . " and events_clients . date $date_between and req_id = req . id ) > 0 " ;
$wherePart1 .= " AND (SELECT count(id) FROM events_clients WHERE event='transmitted'
and events_clients . user_id = " . $user . " and events_clients . date $date_between and req_id = req . id ) > 0 " ;
$wherePart2 .= " AND (SELECT count(id) FROM events_clients WHERE event='transmitted'
and events_clients . user_id = " . $user . " and events_clients . date $date_between and req_id = req . id ) > 0 " ;
}
if ( isset ( $filtr -> accepted )){
$where .= " AND (SELECT count(id) FROM events_clients WHERE event='accepted'
and events_clients . user_id = " . $user . " and events_clients . date $date_between and req_id = req . id ) > 0 " ;
$wherePart1 .= " AND (SELECT count(id) FROM events_clients WHERE event='accepted'
and events_clients . user_id = " . $user . " and events_clients . date $date_between and req_id = req . id ) > 0 " ;
$wherePart2 .= " AND (SELECT count(id) FROM events_clients WHERE event='accepted'
and events_clients . user_id = " . $user . " and events_clients . date $date_between and req_id = req . id ) > 0 " ;
}
if (( isset ( $filtr -> filter_stage ) && $filtr -> filter_stage == 'filter_work_add' ) || $filtr -> transmitted || $filtr -> accepted ){
if ( $is_stats ){
if ( $filtr -> transmitted || $filtr -> accepted ){
if ( $this -> agencyId > 0 ){
$agencyId = $this -> agencyId ;
} else {
$agencyId = User :: getUserAgencyID ();
}
$where .= " AND (req.user_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 in (select id from users where id_manager= $agencyId )))) " ;
$wherePart1 .= " AND (req.user_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 in (select id from users where id_manager= $agencyId )))) " ;
$wherePart2 .= " AND (req.user_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 in (select id from users where id_manager= $agencyId )))) " ;
} else {
$where .= " AND req.user_id = $user " ;
$wherePart1 .= " AND req.user_id = $user " ;
$wherePart2 .= " AND req.user_id = $user " ;
}
} else {
$where .= " AND req.user_id in (select id from users where id= $user or id_manager= $user or id_manager in
( select id from users where id_manager = $user ) or id_manager in
( select id from users where id_manager = $user )) " ;
$wherePart1 .= " AND req.user_id in (select id from users where id= $user or id_manager= $user or id_manager in
( select id from users where id_manager = $user ) or id_manager in
( select id from users where id_manager = $user )) " ;
$wherePart2 .= " AND req.user_id in (select id from users where id= $user or id_manager= $user or id_manager in
( select id from users where id_manager = $user ) or id_manager in
( select id from users where id_manager = $user )) " ;
}
} else if ( $user ) {
//если общие или закрытые - показываем от всего агентства
$r_check_permissions = $this -> user -> checkMenuPermissions ();
if ( $filtr -> stages -> ahency == 1 || ( $filtr -> stages -> close == 1 && $r_check_permissions [ 'menu_can_take_from_closed' ] == 1 )) {
if ( $this -> agencyId > 0 ){
$agencyId = $this -> agencyId ;
} else {
$agencyId = User :: getUserAgencyID ();
}
$userIds = [];
$wh = new WebHookIn ();
$allUsersIds = array ();
if ( $agencyId > 0 ){
$allUsersIds = $wh -> getAllUserAgency ( $agencyId );
}
$where .= " AND (req.user_id in ( " . implode ( ',' , $allUsersIds ) . " )) " ;
$wherePart1 .= " AND (req.user_id in ( " . implode ( ',' , $allUsersIds ) . " )) " ;
$wherePart2 .= " AND (req.user_id in ( " . implode ( ',' , $allUsersIds ) . " )) " ;
/* $where .= " AND (req.user_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 in (select id from users where id_manager= $agencyId )))) " ;
$wherePart1 .= " AND (req.user_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 in (select id from users where id_manager= $agencyId )))) " ;
$wherePart2 .= " AND (req.user_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 in (select id from users where id_manager= $agencyId )))) " ;
*/
} else {
$depClass = new Department ();
$depUser = $depClass -> getDepartment ( $user );
if (( $depUser [ 'role' ] == 'manager_office' || $depUser [ 'role' ] == 'admin_department' ) && ( int ) $depUser [ 'admin' ] > 0 && ! $is_stats ) {
$admin = ( int ) $depUser [ 'admin' ];
$userIds = array ();
$doerIds = array ();
$doerSql = '' ;
$query = mysql_query ( " select id from users where id= $admin or id_manager= $admin or id_manager in (select id from users where id_manager= $admin ) " );
while ( $us = mysql_fetch_assoc ( $query )) {
$userIds [] = $us [ 'id' ];
}
$query_d = mysql_query ( " select rd.requisition_id from requisition_doers rd where rd.user_id = " . $user . " and rd.confirm = 1 " );
if ( ! empty ( $userIds )){
$query_d = mysql_query ( " select rd.requisition_id from requisition_doers rd where rd.user_id in ( " . implode ( " , " , $userIds ) . " ) and rd.confirm = 1 " );
}
while ( $us_d = mysql_fetch_assoc ( $query_d )) {
$doerIds [] = $us_d [ 'requisition_id' ];
}
if ( count ( $doerIds ) > 0 ) {
$doerSql = " or (req.id in ( " . implode ( " , " , $doerIds ) . " )) " ;
}
if ( $is_stats ){
$where .= " AND ((req.user_id in ( " . implode ( " , " , $userIds ) . " ) AND who_work = $user )) " ;
$wherePart1 .= " AND ((req.user_id in ( " . implode ( " , " , $userIds ) . " ) AND req.who_work = $user )) " ;
$wherePart2 .= " AND ((req.user_id in ( " . implode ( " , " , $userIds ) . " ) AND a.who_work = $user )) " ;
} else {
$where .= " AND ((req.user_id in ( " . implode ( " , " , $userIds ) . " ) or who_work in ( " . implode ( " , " , $userIds ) . " )) " . $doerSql . " ) " ;
$wherePart1 .= " AND ((req.user_id in ( " . implode ( " , " , $userIds ) . " ) or req.who_work in ( " . implode ( " , " , $userIds ) . " )) " . $doerSql . " ) " ;
$wherePart2 .= " AND ((req.user_id in ( " . implode ( " , " , $userIds ) . " ) or a.who_work in ( " . implode ( " , " , $userIds ) . " )) " . $doerSql . " ) " ;
}
} else if (( $depUser [ 'role' ] == 'manager_office_menager' ) && ( int ) $depUser [ 'admin' ] > 0 && ! $is_stats ) {
//$admin = (int)$depUser['admin'];
$admin = $_SESSION [ 'id_manager' ];
$userIds = array ();
$doerIds = array ();
$doerSql = '' ;
$query = mysql_query ( " select id from users where id= $admin or id_manager= $admin or id_manager in (select id from users where id_manager= $admin ) " );
while ( $us = mysql_fetch_assoc ( $query )) {
$userIds [] = $us [ 'id' ];
}
$query_d = mysql_query ( " select rd.requisition_id from requisition_doers rd where rd.user_id = " . $user . " and rd.confirm = 1 " );
if ( ! empty ( $userIds )){
$query_d = mysql_query ( " select rd.requisition_id from requisition_doers rd where rd.user_id in ( " . implode ( " , " , $userIds ) . " ) and rd.confirm = 1 " );
}
while ( $us_d = mysql_fetch_assoc ( $query_d )) {
$doerIds [] = $us_d [ 'requisition_id' ];
}
if ( count ( $doerIds ) > 0 ) {
$doerSql = " or (req.id in ( " . implode ( " , " , $doerIds ) . " )) " ;
}
if ( $is_stats ){
$where .= " AND ((req.user_id in ( " . implode ( " , " , $userIds ) . " ) AND who_work = $user )) " ;
$wherePart1 .= " AND ((req.user_id in ( " . implode ( " , " , $userIds ) . " ) AND req.who_work = $user )) " ;
$wherePart2 .= " AND ((req.user_id in ( " . implode ( " , " , $userIds ) . " ) AND a.who_work = $user )) " ;
} else {
$where .= " AND ((req.user_id in ( " . implode ( " , " , $userIds ) . " ) or who_work in ( " . implode ( " , " , $userIds ) . " )) " . $doerSql . " ) " ;
$wherePart1 .= " AND ((req.user_id in ( " . implode ( " , " , $userIds ) . " ) or req.who_work in ( " . implode ( " , " , $userIds ) . " )) " . $doerSql . " ) " ;
$wherePart2 .= " AND ((req.user_id in ( " . implode ( " , " , $userIds ) . " ) or a.who_work in ( " . implode ( " , " , $userIds ) . " )) " . $doerSql . " ) " ;
}
} else {
/* $where .= " AND ((user_id in (select id from users where id= $user or id_manager= $user or id_manager in
( select id from users where id_manager = $user or id_manager in
( select id from users where id_manager = $user ))) or who_work in ( select id from users where id = $user or id_manager = $user or id_manager in
( select id from users where id_manager = $user or id_manager in
( select id from users where id_manager = $user )))) or doers like '%"" . $user . "":1%' ) " ;*/
$userIds = array ();
$doerIds = array ();
$doerSql = '' ;
$query = mysql_query ( " select id from users where id= $user or id_manager= $user or id_manager in
( select id from users where id_manager = $user or id_manager in
( select id from users where id_manager = $user ))
UNION SELECT user_id FROM users_delete where user_id = $user or id_manager = $user or id_manager in
( select user_id from users_delete where id_manager = $user or id_manager in
( select user_id from users_delete where id_manager = $user ))
" );
while ( $us = mysql_fetch_assoc ( $query )) {
$userIds [] = $us [ 'id' ];
}
$query_d = mysql_query ( " select rd.requisition_id from requisition_doers rd where rd.user_id = " . $user . " and rd.confirm = 1 " );
if ( ! empty ( $userIds )){
$query_d = mysql_query ( " select rd.requisition_id from requisition_doers rd where rd.user_id in ( " . implode ( " , " , $userIds ) . " ) and rd.confirm = 1 " );
}
while ( $us_d = mysql_fetch_assoc ( $query_d )) {
$doerIds [] = $us_d [ 'requisition_id' ];
}
if ( count ( $doerIds ) > 0 ) {
$doerSql = " or (req.id in ( " . implode ( " , " , $doerIds ) . " )) " ;
}
if ( $is_stats ){
$where .= " AND ((who_work = $user )) " ;
$wherePart1 .= " AND ((req.who_work = $user )) " ;
$wherePart2 .= " AND ((a.who_work = $user )) " ;
} else {
$n_user_id = $_SESSION [ 'agency_id' ];
$n_agents = " SELECT id FROM users
WHERE id IN (
SELECT id FROM users
WHERE id = $n_user_id
OR id_manager = $n_user_id
OR id_manager IN (
SELECT id FROM users
WHERE id_manager = $n_user_id
OR id_manager IN (
SELECT id FROM users
WHERE id_manager = $n_user_id
)
)
)
UNION
SELECT user_id FROM users_delete
WHERE agency_id = $n_user_id
" ;
$n_agents_res = mysql_query ( $n_agents );
$n_agent_ids = [];
while ( $row = mysql_fetch_assoc ( $n_agents_res )) {
$n_agent_ids [] = $row [ 'id' ];
}
if ( $all_null ) {
$where .= " AND (who_work in (0, " . implode ( " , " , $userIds ) . " ) " . $doerSql . " ) " ;
$where .= " AND user_id IN ( " . implode ( " , " , $n_agent_ids ) . " ) " ;;
$wherePart1 .= " AND (req.who_work in (0, " . implode ( " , " , $userIds ) . " ) " . $doerSql . " ) " ;
$wherePart1 .= " AND req.user_id IN ( " . implode ( " , " , $n_agent_ids ) . " ) " ;;
$wherePart2 .= " AND (a.who_work in (0, " . implode ( " , " , $userIds ) . " ) " . $doerSql . " ) " ;
$wherePart2 .= " AND req.user_id IN ( " . implode ( " , " , $n_agent_ids ) . " ) " ;;
} else {
$where .= " AND ((who_work in ( " . implode ( " , " , $userIds ) . " )) " . $doerSql . " ) " ;
$wherePart1 .= " AND ((req.who_work in ( " . implode ( " , " , $userIds ) . " )) " . $doerSql . " ) " ;
$wherePart2 .= " AND ((a.who_work in ( " . implode ( " , " , $userIds ) . " )) " . $doerSql . " ) " ;
}
}
}
}
}
//С просроченными этапами
if ( isset ( $expired_stages )){
$idExpiredStages = $this -> getIdExpiredStages ( $where );
if ( ! empty ( $idExpiredStages )){
$where = " AND id in ( " . implode ( ',' , $idExpiredStages ) . " ) " ;
$wherePart1 = " AND req.id in ( " . implode ( ',' , $idExpiredStages ) . " ) " ;
$wherePart2 = " AND req.id in ( " . implode ( ',' , $idExpiredStages ) . " ) " ;
}
}
$sql .= $where ;
$_SESSION [ 'where_req_campaigns' ] = $sql ;
$sqlTotal .= $where ;
$sqlExpectedCommissionTotal .= $where ;
if ( $this -> view != 'kanban' ){
if ( isset ( $sqlPart1 ) && isset ( $sqlPart2 )){
$sql = $sqlPart1 ;
$sql .= $wherePart1 ;
$sql .= " UNION " ;
$sql .= $sqlPart2 ;
$sql .= $wherePart2 ;
$sqlTotal = $sqlTotalPart1 ;
$sqlTotal .= $wherePart1 ;
$sqlTotal .= " UNION " ;
$sqlTotal .= $sqlTotalPart2 ;
$sqlTotal .= $wherePart2 ;
}
if ( isset ( $sqlExpectedCommissionTotalPart1 ) && isset ( $sqlExpectedCommissionTotalPart2 )){
$sqlExpectedCommissionTotal = $sqlExpectedCommissionTotalPart1 ;
$sqlExpectedCommissionTotal .= $wherePart1 ;
$sqlExpectedCommissionTotal .= " UNION " ;
$sqlExpectedCommissionTotal .= $sqlExpectedCommissionTotalPart2 ;
$sqlExpectedCommissionTotal .= $wherePart2 ;
}
}
$limitSql = " " ;
if ( $this -> page > 0 ){
$limitSql = ' limit ' . ( $this -> page - 1 ) * $this -> limit . ', ' . $this -> limit ;
}
$part_order = " ORDER BY if ((SELECT date_update from events_clients where req_id=req.id AND (event = 'accepted' OR event = 'restored' OR event = 'accepted_doer') order by id desc limit 1) > req.created_at, "
. " (SELECT date_update from events_clients where req_id=req.id AND (event = 'accepted' OR event = 'restored' OR event = 'accepted_doer') order by id desc limit 1) ,req.created_at) " ;
$part_order1 = " ORDER BY if ((SELECT date_update from events_clients where req_id=reqid AND (event = 'accepted' OR event = 'restored' OR event = 'accepted_doer') order by id desc limit 1) > created_at, "
. " (SELECT date_update from events_clients where req_id=reqid AND (event = 'accepted' OR event = 'restored' OR event = 'accepted_doer') order by id desc limit 1) ,created_at) " ;
if ( $order ){
$part_order = ' ORDER BY req.created_at ' ;
$part_order1 = ' ORDER BY created_at ' ;
} else {
$order = 'desc' ;
}
if ( $filtr -> stages -> close > 0 ) {
$part_order = " ORDER BY (SELECT date_update FROM `events_clients` WHERE req_id=req.id and event='delete' order by id desc limit 1) " ;
$part_order1 = " ORDER BY (SELECT date_update FROM `events_clients` WHERE req_id=reqid and event='delete' order by id desc limit 1) " ;
if (( int ) $filtr -> date_closer == 11 ){
$part_order = " ORDER BY req.created_at " ;
$part_order1 = ' ORDER BY created_at ' ;
}
}
$result [ 'filtr' ] = $filtr -> date_closer ;
$_SESSION [ 'where_req_campaigns_order' ] = $part_order . $order ;
if ( $this -> view != 'kanban' ){
if ( isset ( $sqlPart1 ) && isset ( $sqlPart2 )){
// $_SESSION['where_req_campaigns_order'] = $part_order1.$order;
$sql .= $part_order1 . $order ;
} else {
$sql .= $part_order . $order ;
}
} else {
$sql .= $part_order . $order ;
}
$_SESSION [ 'where_req' ] = $sql ;
$sql .= $limitSql ;
$result [ 'sql' ] = $sql ;
/* if ( $_SESSION [ 'id' ] == 19895 ) {
echo $sql ;
} */
$typesReq = $this -> get_type ();
$this -> funnels_adjacent = array ();
if ( $this -> view == 'kanban' ){
$depClass = new Department ;
$departments = $depClass -> getDepartments ();
$count_step = array ();
$limitSql = " " ;
if ( $this -> page > 0 ){
if ( $this -> page == 1 ){
$limitSql = ' limit ' . (( $this -> page - 1 ) * 4 ) . ', 4' ;
} else if ( $this -> page > 1 ) {
$limitSql = ' limit ' . (( $this -> page - 1 ) * 1 + 3 ) . ', 1' ;
}
}
//echo $funnelId;
$start = microtime ( true );
if ( $funnelId !== false ){
if ( $funnelId === 'all' ) {
$sql_count_step = " SELECT stage, count(*) as total FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE 1 $where group by stage " ;
} else {
if ( $funnelId == 0 || empty ( $funnelId )) {
$sql_count_step = " SELECT stage, count(*) as total FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE funnel_id= $funnelId $where group by stage " ;
//echo $sql_count_step;
} else if ( $funnelId > 0 ) {
$arrayCountSteps = array ();
$sql_stage = " SELECT * FROM `funnel_steps` WHERE funnel_id= $funnelId AND deleted = 0 " ;
$q_stage = $this -> db -> query ( $sql_stage );
while ( $r_stage = $this -> db -> fetch_assoc ( $q_stage )){
$arrayCountSteps [ $r_stage [ 'id' ]] = 0 ;
}
$sql_count_step = " SELECT step_id as stage, count(*) as total FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE funnel_id= $funnelId $where group by step_id " ;
if ( isset ( $sqlPart1 ) && isset ( $sqlPart2 )){
$sql_count_step1 = " SELECT req.step_id as stage, count(*) as total FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE req.funnel_id = $funnelId $wherePart1 group by req.step_id " ;
$q_count_step1 = $this -> db -> query ( $sql_count_step1 );
while ( $r_count_step1 = $this -> db -> fetch_assoc ( $q_count_step1 )){
if ( ! isset ( $arrayCountSteps [ $r_count_step1 [ 'stage' ]])) $arrayCountSteps [ $r_count_step1 [ 'stage' ]] = 0 ;
$arrayCountSteps [ $r_count_step1 [ 'stage' ]] += ( int ) $r_count_step1 [ 'total' ];
}
$sql_count_step2 = " SELECT a.step_id_active as stage, count(*) as total FROM adjacent_funnels as a LEFT JOIN requisitions as req on a.req_id = req.id $priceJoin $propertyTypeJoin $join WHERE a.funnel_id = $funnelId $wherePart2 group by a.step_id_active " ;
$q_count_step2 = $this -> db -> query ( $sql_count_step2 );
while ( $r_count_step2 = $this -> db -> fetch_assoc ( $q_count_step2 )){
if ( ! isset ( $arrayCountSteps [ $r_count_step2 [ 'stage' ]])) $arrayCountSteps [ $r_count_step2 [ 'stage' ]] = 0 ;
$arrayCountSteps [ $r_count_step2 [ 'stage' ]] += ( int ) $r_count_step2 [ 'total' ];
}
/* $sqlTotalPart1 = " SELECT step_id as stage, count(*) as total FROM requisitions as req $join WHERE funnel_id = $funnelId $ " ;
$sqlTotalPart2 = " SELECT step_id as stage, count(*) as total FROM adjacent_funnels as a LEFT JOIN requisitions as req on a.req_id = req.id $join WHERE a.funnel_id in ( $funnelId ) " ; */
}
}
}
/* if ( $_SESSION [ 'id' ] == 14050 ){
echo $sql_count_step ;
} */
//echo $sql_count_step;
$q_count_step = $this -> db -> query ( $sql_count_step );
$clientIds = array ();
$objectIds = array ();
$complex_room_ids = array ();
$reqIds = array ();
$requisitionData = array ();
// $start = microtime(true);
/* if ( $funnelId == 'all' ) {
$sql_2_part = " SELECT * FROM requisitions as req WHERE 1 $where " ;
} else {
$sql_2_part = " SELECT * FROM requisitions as req WHERE funnel_id= $funnelId $where " ;
}
$sql2_new = '' ; */
if ( ! isset ( $arrayCountSteps )){
$arrayCountSteps = array ();
while ( $r_count_step = $this -> db -> fetch_assoc ( $q_count_step )){
if ( ! isset ( $arrayCountSteps [ $r_count_step [ 'stage' ]])) $arrayCountSteps [ $r_count_step [ 'stage' ]] = 0 ;
$arrayCountSteps [ $r_count_step [ 'stage' ]] += ( int ) $r_count_step [ 'total' ];
}
}
/* if ( $_SESSION [ 'id' ] == 14050 ){
var_dump ( $arrayCountSteps );
} */
$num_step = 0 ;
foreach ( $arrayCountSteps as $step_id => $countSteps ){
if ( $step_id > 0 ){
$count_step [ $step_id ] = $countSteps ;
if ( $countSteps > 0 ){
// $start = microtime(true);
/* if ( $num_step > 0 ){
$sql2_new .= " UNION " ;
}
$sql2_new .= " ( " . $sql_2_part ;
if ( $funnelId == 0 ) {
$sql2_new .= " and stage = $r_count_step[stage] " ;
} else if ( $funnelId > 0 ) {
$sql2_new .= " and step_id = $r_count_step[stage] " ;
}
$sql2_new .= " $part_order $order $limitSql ) " ; */
if ( $funnelId === 'all' || $funnelId === false ){
$sql_2 = " SELECT req.* $priceSelect FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE 1 $where and stage = $step_id $part_order $order $limitSql " ;
} else {
$sql_2 = " SELECT req.* $priceSelect FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE funnel_id= $funnelId $where and stage = $step_id $part_order $order $limitSql " ;
if ( $funnelId > 0 ) {
$sql_2 = " SELECT req.* $priceSelect FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE funnel_id= $funnelId $where and step_id = $step_id $part_order $order $limitSql " ;
if ( isset ( $sqlPart1 ) && isset ( $sqlPart2 )){
$sql_2 = " SELECT req.id, req.name, req.user_id, req.created_at, req.client_id,
req . object_id , req . type_id , req . funnel_id , req . step_id , req . who_work , req . who_delete ,
req . confirm , req . description ,
req . stage , req . deleted , req . cancel , req . priority , req . doer_clients ,
req . hot , req . reason , req . denial , req . summa , req . expected_commission , req . activities , req . asfilter_id ,
req . source , req . doers , req . doers_confirm , req . employee_id , req . property_type_id ,
2026-06-20 10:19:54 +02:00
req . integration , req . call_id , req . friend_client_id , req . confirm_recommendation , req . deal_id , req . id as reqid , 'main' as funnel_type $priceSelect FROM requisitions as req $priceJoin $propertyTypeJoin $join WHERE req . funnel_id = $funnelId $wherePart1 and req . step_id = $step_id " ;
2026-05-22 20:21:54 +02:00
$sql_2 .= " UNION " ;
$sql_2 .= " SELECT req.id, req.name, req.user_id, req.created_at, req.client_id,
req . object_id , req . type_id , a . funnel_id , a . step_id_active as step_id ,
a . who_work as who_work , req . who_delete , a . confirm , req . description ,
req . stage , req . deleted , req . cancel , req . priority , req . doer_clients ,
req . hot , req . reason , req . denial , req . summa , req . expected_commission , req . activities , req . asfilter_id ,
req . source , req . doers , req . doers_confirm , req . employee_id , req . property_type_id ,
2026-06-20 10:19:54 +02:00
req . integration , req . call_id , 0 as friend_client_id , 0 as confirm_recommendation , req . deal_id , req . id as reqid , 'adjacent' as funnel_type $priceSelect
2026-05-22 20:21:54 +02:00
FROM adjacent_funnels as a
LEFT JOIN requisitions as req on a . req_id = req . id $priceJoin $propertyTypeJoin $join WHERE a . funnel_id = $funnelId $wherePart2 and a . step_id_active = $step_id " ;
$sql_2 .= " ORDER BY created_at $order $limitSql " ;
}
}
}
/* if ( $_SESSION [ 'id' ] == 14050 ){
echo $sql_2 ;
} */
$q = $this -> db -> query ( $sql_2 );
/* while ( $r = $this -> db -> fetch_assoc ( $q )){
$sql_cl = " SELECT id, fio, phone FROM clients WHERE id = $r[client_id] " ;
$q_cl = $this -> db -> query ( $sql_cl );
while ( $r_cl = $this -> db -> fetch_assoc ( $q_cl )){
$r [ 'phone' ] = preg_replace ( " /[^,.0-9]/ " , '' , $r_cl [ 'phone' ]);
$r [ 'fio' ] = $r_cl [ 'fio' ];
}
if ( $r [ 'object_id' ] > 0 ){
$sql_ob = " SELECT id, nazv FROM objects WHERE id = $r[object_id] " ;
$q_ob = $this -> db -> query ( $sql_ob );
while ( $r_ob = $this -> db -> fetch_assoc ( $q_ob )){
$r [ 'nazv' ] = $r_ob [ 'nazv' ];
}
}
$details = $this -> get_req_details ( $r , true );
$result [ 'req' ][ $r_count_step [ 'stage' ]][ 'req' . $r [ 'id' ]] = $details ;
$result [ 'req' ][ 'req' . $r [ 'id' ]] = $details ;
} */
while ( $r = $this -> db -> fetch_assoc ( $q )){
//$time = microtime(true) - $start;
$reqIds [] = $r [ 'id' ];
$events_res [ $r [ 'id' ]] = array ( 'events_res' => 0 , 'events_res1' => 0 , 'events_res2' => 0 );
$r [ 'stage' ] = $step_id ;
$requisitionData [] = $r ;
$clientIds [] = $r [ 'client_id' ];
if ( $r [ 'complex_room_id' ] > 0 ){
$complex_room_ids [] = $r [ 'complex_room_id' ];
}
if ( $r [ 'object_id' ] > 0 ){
$objectIds [] = $r [ 'object_id' ];
}
}
$num_step ++ ;
}
}
$sqls2 [] = $sql_2 ;
}
$clients = [];
if ( count ( $clientIds ) > 0 ) {
$sql_cl = " SELECT id, fio, phone FROM clients WHERE id in ( " . implode ( " , " , $clientIds ) . " ) " ;
$q_cl = $this -> db -> query ( $sql_cl );
while ( $r_cl = $this -> db -> fetch_assoc ( $q_cl )) {
$clients [ $r_cl [ 'id' ]] = $r_cl ;
}
}
$objects = [];
if ( count ( $objectIds ) > 0 ) {
$sql_ob = " SELECT id, nazv FROM objects WHERE id in ( " . implode ( " , " , $objectIds ) . " ) " ;
$q_ob = $this -> db -> query ( $sql_ob );
while ( $r_ob = $this -> db -> fetch_assoc ( $q_ob )){
$objects [ $r_ob [ 'id' ]] = $r_ob ;
}
}
$complex_rooms = [];
if ( count ( $complex_room_ids ) > 0 ) {
$sql_room = " SELECT id, `number` FROM complex_rooms WHERE id in ( " . implode ( " , " , $complex_room_ids ) . " ) " ;
$q_room = $this -> db -> query ( $sql_room );
while ( $r_room = $this -> db -> fetch_assoc ( $q_room )){
$complex_rooms [ $r_room [ 'id' ]] = $r_room ;
}
}
if ( ! empty ( $reqIds )){
$events = " SELECT count(id) as res, req_id FROM user_client_events WHERE calendar_view = 0
and schedule_date is not null and req_id in ( " .implode(',', $reqIds ). " ) and schedule_date < '" . date("Y-m-d H:i:s") . "' and type in ( 'call' , 'meet' , 'show' , 'deal' , 'even' ) and schedule_date <> '0000-00-00 00:00:00' and cancel = 0 group by req_id " ;
$events1 = " SELECT count(id) as res, req_id FROM user_client_events WHERE calendar_view = 0
and schedule_date is not null and req_id in ( " .implode(',', $reqIds ). " ) and DATE_FORMAT ( schedule_date , '%Y-%m-%d' ) = '" . date("Y-m-d") . "' and type in ( 'call' , 'meet' , 'show' , 'deal' , 'even' ) and schedule_date <> '0000-00-00 00:00:00' and cancel = 0 group by req_id " ;
$events2 = " SELECT count(id) as res, req_id FROM user_client_events WHERE calendar_view = 0
and schedule_date is not null and req_id in ( " .implode(',', $reqIds ). " ) and DATE_FORMAT ( schedule_date , '%Y-%m-%d' ) > '" . date("Y-m-d") . "' and type in ( 'call' , 'meet' , 'show' , 'deal' , 'even' ) and schedule_date <> '0000-00-00 00:00:00' and cancel = 0 group by req_id " ;
$q_events = $this -> db -> query ( $events );
while ( $event_res = $this -> db -> fetch_assoc ( $q_events )){
$events_res [ $event_res [ 'req_id' ]][ 'events_res' ] = ( int ) $event_res [ 'res' ];
}
$q_events1 = $this -> db -> query ( $events1 );
while ( $event_res1 = $this -> db -> fetch_assoc ( $q_events1 )){
$events_res [ $event_res1 [ 'req_id' ]][ 'events_res1' ] = ( int ) $event_res1 [ 'res' ];
}
$q_events2 = $this -> db -> query ( $events2 );
while ( $event_res2 = $this -> db -> fetch_assoc ( $q_events2 )){
$events_res [ $event_res2 [ 'req_id' ]][ 'events_res2' ] = ( int ) $event_res2 [ 'res' ];
}
}
//Количество присоединенных заявок
$totalUnion = array ();
if ( ! empty ( $reqIds )){
$sql_total_union = " SELECT * FROM union_requisitions WHERE main_id in ( " . implode ( ',' , $reqIds ) . " ) " ;
$q_total_union = $this -> db -> query ( $sql_total_union , true );
while ( $r_total_union = $this -> db -> fetch_assoc ( $q_total_union )){
if ( ! isset ( $totalUnion [ $r_total_union [ 'main_id' ]])) $totalUnion [ $r_total_union [ 'main_id' ]] = 0 ;
$totalUnion [ $r_total_union [ 'main_id' ]] ++ ;
}
}
/* if ( $_SESSION [ 'id' ] == 5238 ){
var_dump ( $events2 );
var_dump ( $events_res );
} */
if ( $_SESSION [ 'id' ] == 12071 ){
$time = microtime ( true ) - $start ;
file_put_contents ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /callevents/log_req.txt " , date ( 'd.m.Y H:i:s' ) . " - 1. " . $time . " \n " , FILE_APPEND );
}
/**
* Финансы
* */
if ( ! empty ( $reqIds )){
$deposits = array ();
$sql_deposit = " SELECT * FROM deposits_clients_req WHERE req_id in ( " . implode ( ',' , $reqIds ) . " ) " ;
$q_deposit = $this -> db -> query ( $sql_deposit );
while ( $r_deposit = $this -> db -> fetch_assoc ( $q_deposit )){
$deposits [ $r_deposit [ 'req_id' ]] = $r_deposit [ 'deposit' ];
}
$expenses_req = array ();
$expenses = array ();
$expenses_total = array ();
$sql_ex = " SELECT * FROM expenses_req WHERE req_id in ( " . implode ( ',' , $reqIds ) . " ) " ;
$q_ex = $this -> db -> query ( $sql_ex );
if ( $this -> db -> num_rows ( $q_ex ) > 0 ){
$steps_ids = array ();
$steps = array ();
while ( $r_ex = $this -> db -> 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 = $this -> db -> query ( $sql_step );
while ( $r_step = $this -> db -> 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' ]];
}
$expense [ 'name' ] = $nameExpense ;
$expense [ 'amount' ] = rtrim ( rtrim ( $expense [ 'amount' ], '0' ), '.' );
$expenses_req [ $expense [ 'req_id' ]][] = $expense ;
if ( ! isset ( $expenses_total [ $expense [ 'req_id' ]])) $expenses_total [ $expense [ 'req_id' ]] = 0 ;
$expenses_total [ $expense [ 'req_id' ]] += $expense [ 'amount' ];
}
}
}
foreach ( $requisitionData as $r ) {
if ( should_hide_contacts_for_current_user ()) {
// hide_client_contacts: маскируем телефон и (если в ФИО есть номер) — ФИО
$r [ 'phone' ] = mask_client_phone ( $clients [ $r [ 'client_id' ]][ 'phone' ]);
$r [ 'fio' ] = mask_fio_if_contains_phone ( $clients [ $r [ 'client_id' ]][ 'fio' ]);
} else {
$r [ 'phone' ] = preg_replace ( " /[^,.0-9]/ " , '' , $clients [ $r [ 'client_id' ]][ 'phone' ]);
$r [ 'fio' ] = $clients [ $r [ 'client_id' ]][ 'fio' ];
}
if ( $r [ 'complex_room_id' ] > 0 ){
$r [ 'complex_room_number' ] = $complex_rooms [ $r [ 'complex_room_id' ]][ 'number' ];
}
if ( $r [ 'object_id' ] > 0 ){
$r [ 'nazv' ] = $objects [ $r [ 'object_id' ]][ 'nazv' ];
}
$details = $this -> get_req_details_kanban ( $r , true , [], $departments , $typesReq , $events_res );
if ( $filtr -> stages -> ahency == 1 ){
$details [ 'can_del' ] = 0 ;
}
$details [ 'deposit' ] = 0 ;
$details [ 'expenses' ] = array ();
$details [ 'expenses_total' ] = 0 ;
if ( isset ( $deposits [ $details [ 'id' ]])){
$details [ 'deposit' ] = $deposits [ $details [ 'id' ]];
}
if ( isset ( $expenses_req [ $details [ 'id' ]])){
$details [ 'expenses' ] = $expenses_req [ $details [ 'id' ]];
}
if ( isset ( $expenses_total [ $details [ 'id' ]])){
$details [ 'expenses_total' ] = $expenses_total [ $details [ 'id' ]];
}
$result [ 'req' ][ $r [ 'stage' ]][ 'req' . $r [ 'id' ]] = $details ;
$result [ 'req' ][ 'req' . $r [ 'id' ]] = $details ;
if ( isset ( $totalUnion [ $r [ 'id' ]])){
$result [ 'req' ][ $r [ 'stage' ]][ 'req' . $r [ 'id' ]][ 'union_total' ] = $totalUnion [ $r [ 'id' ]];
$result [ 'req' ][ 'req' . $r [ 'id' ]][ 'union_total' ] = $totalUnion [ $r [ 'id' ]];
} else {
$result [ 'req' ][ $r [ 'stage' ]][ 'req' . $r [ 'id' ]][ 'union_total' ] = 0 ;
$result [ 'req' ][ 'req' . $r [ 'id' ]][ 'union_total' ] = 0 ;
}
}
if ( $_SESSION [ 'id' ] == 12071 ){
$time = microtime ( true ) - $start ;
file_put_contents ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /callevents/log_req.txt " , date ( 'd.m.Y H:i:s' ) . " - 2. " . $time . " \n " , FILE_APPEND );
}
}
$result [ 'req' ][ 'count' ] = $count_step ;
if ( $this -> page == 1 ){
$result [ 'total_req' ] = 0 ;
$qTotal = $this -> db -> query ( $sqlTotal );
while ( $rTotal = $this -> db -> fetch_assoc ( $qTotal )){
$result [ 'total_req' ] += ( int ) $rTotal [ 'total' ];
}
$result [ 'total_comission' ] = 0 ;
$qExpectedCommissionTotal = $this -> db -> query ( $sqlExpectedCommissionTotal );
while ( $rExpectedCommissionTotal = $this -> db -> fetch_assoc ( $qExpectedCommissionTotal )){
$result [ 'total_comission' ] += ( int ) $rExpectedCommissionTotal [ 'total' ];
}
}
}
else {
$result [ 'req' ] = array ();
// Фильтр по ценам и бюджету автопоиска в зависимости от типа
if (( isset ( $filtr -> priceFrom ) || isset ( $filtr -> priceTo )) && ! empty ( $filtr -> type )) {
$priceWhere = '' ;
$hasSprosType = false ;
$hasPodborType = false ;
$typeQuery = ' SELECT `id` , `heir`
FROM requisitions_type
WHERE `id` IN ( '.implode(' , ',$filtr->type).' ) ' ;
$types = $this -> db -> query ( $typeQuery );
// Идентифицируем, есть ли типы, при которых нужно включать поиск по цене
while ( $type = $this -> db -> fetch_assoc ( $types )) {
if ( $type [ 'id' ] == 1 || $type [ 'heir' ] == 1 ) { // Подбор объекта
$hasPodborType = true ;
}
if ( $type [ 'id' ] == 4 || $type [ 'heir' ] == 4 ) { // Спрос по нашему объекту
$hasSprosType = true ;
}
if ( $hasPodborType && $hasSprosType ) {
break ;
}
}
if ( $hasPodborType || $hasSprosType ) {
if ( $from = intval ( $filtr -> priceFrom )) {
$priceFromReq = '' ;
if ( $hasSprosType ) {
$priceFromReq .= " o.stoim >= $from " ;
}
if ( $hasPodborType ) {
$priceFromReq .= ( $hasSprosType ? ' and ' : '' ) . " af.stoim_do >= $from " ;
}
if ( ! empty ( $priceFromReq )) {
$priceWhere .= " ( $priceFromReq ) AND " ;
}
}
if ( $to = intval ( $filtr -> priceTo )) {
$priceToReq = '' ;
if ( $hasSprosType ) {
$priceToReq .= " o.stoim <= $to " ;
}
if ( $hasPodborType ) {
$priceToReq .= ( $hasSprosType ? ' and ' : '' ) . " af.stoim_do <= $to " ;
}
if ( ! empty ( $priceToReq )) {
$priceWhere .= " ( $priceToReq ) AND " ;
}
}
}
if ( ! empty ( $priceWhere )) {
$sql = str_replace ( 'WHERE' , 'WHERE ' . $priceWhere , $sql );
$sqlTotal = str_replace ( 'WHERE' , 'WHERE ' . $priceWhere , $sqlTotal );
$sqlExpectedCommissionTotal = str_replace ( 'WHERE' , 'WHERE ' . $priceWhere , $sqlExpectedCommissionTotal );
}
}
$q = $this -> db -> query ( $sql );
$requestList = [];
$usersToUse = [];
$sourcesToUse = [];
$userIdsForRead = [];
$sourceIdsForRead = [];
$requestIds = [];
//первый цикл для запоминания и формирования списков ИД
while ( $r = $this -> db -> fetch_assoc ( $q )){
$requestList [] = $r ;
$requestIds [] = $r [ 'id' ];
if ( $r [ " user_id " ]) {
$userIdsForRead [] = $r [ " user_id " ];
}
if ( $r [ " who_delete " ]) {
$userIdsForRead [] = $r [ " who_delete " ];
}
if ( $r [ " who_work " ]) {
$userIdsForRead [] = $r [ " who_work " ];
}
if ( $r [ " source " ]) {
$sourceIdsForRead [] = $r [ " source " ];
}
}
//выделяем только уникальные
$userIdsForRead = array_unique ( $userIdsForRead );
$sourceIdsForRead = array_unique ( $sourceIdsForRead );
//формируем списки пользователей
if ( count ( $userIdsForRead ) > 0 ) {
$usersQuery = " SELECT id, agency, manager, agency_name, first_name, last_name, middle_name, role_id, phone FROM users WHERE id in ( " . implode ( " , " , $userIdsForRead ) . " ) " ;
$resultUsers = $this -> db -> query ( $usersQuery );
if ( $this -> db -> num_rows ( $resultUsers ) > 0 ) {
while ( $userRes = $this -> db -> fetch_assoc ( $resultUsers )) {
$usersToUse [ $userRes [ 'id' ]] = $userRes ;
}
}
}
//формируем списки источников
if ( count ( $sourceIdsForRead ) > 0 ) {
$sourcesQuery = " SELECT * FROM `advertising_sources` WHERE `id` in ( " . implode ( " , " , $sourceIdsForRead ) . " ) " ;
$resultSources = $this -> db -> query ( $sourcesQuery );
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
if ( $this -> db -> num_rows ( $resultSources ) > 0 ) {
while ( $sourceRes = $this -> db -> fetch_assoc ( $resultSources )) {
$sourceRes [ 'source_see' ] = 1 ;
if ( is_see ( $sourceRes [ 'is_no_see' ], $sourceRes [ 'users_no_see' ]) === false ){
$sourceRes [ 'source_see' ] = 0 ;
}
$sourcesToUse [ $sourceRes [ 'id' ]] = $sourceRes ;
}
}
}
if ( ! empty ( $requestIds )){
$sql_funnels_adjacent = " SELECT id, req_id FROM adjacent_funnels WHERE req_id in ( " . implode ( ',' , $requestIds ) . " ) " ;
$q_funnel_adjacent = $this -> db -> query ( $sql_funnels_adjacent );
while ( $r_funnel_adjacent = $this -> db -> fetch_assoc ( $q_funnel_adjacent )){
$this -> funnels_adjacent [ $r_funnel_adjacent [ 'req_id' ]][] = $r_funnel_adjacent ;
}
}
/* if ( $_SESSION [ 'id' ] == 5238 ){
var_dump ( $this -> funnels_adjacent );
} */
//Типы договоров
$contract = new Contract ( $this -> db );
$contract -> setAgencyId ( $this -> agencyId );
$typesContracs = $contract -> getTypesName ();
/* if ( $_SESSION [ 'id' ] == 5238 ){
var_dump ( $typesContracs );
} */
//Количество присоединенных заявок
$totalUnion = array ();
if ( ! empty ( $requestIds )){
$sql_total_union = " SELECT * FROM union_requisitions WHERE main_id in ( " . implode ( ',' , $requestIds ) . " ) " ;
$q_total_union = $this -> db -> query ( $sql_total_union , true );
while ( $r_total_union = $this -> db -> fetch_assoc ( $q_total_union )){
if ( ! isset ( $totalUnion [ $r_total_union [ 'main_id' ]])) $totalUnion [ $r_total_union [ 'main_id' ]] = 0 ;
$totalUnion [ $r_total_union [ 'main_id' ]] ++ ;
}
}
/**
* Финансы
* */
if ( ! empty ( $requestIds )){
$deposits = array ();
$depositArr = array ();
$sql_deposit = " SELECT * FROM deposits_clients_req WHERE req_id in ( " . implode ( ',' , $requestIds ) . " ) " ;
$q_deposit = $this -> db -> query ( $sql_deposit );
while ( $r_deposit = $this -> db -> fetch_assoc ( $q_deposit )){
$deposits [ $r_deposit [ 'req_id' ]] = $r_deposit [ 'deposit' ];
$depositArr [ $r_deposit [ 'req_id' ]] = $r_deposit ;
}
$expenses_req = array ();
$expenses = array ();
$expenses_total = array ();
$sql_ex = " SELECT * FROM expenses_req WHERE req_id in ( " . implode ( ',' , $requestIds ) . " ) " ;
$q_ex = $this -> db -> query ( $sql_ex );
if ( $this -> db -> num_rows ( $q_ex ) > 0 ){
$steps_ids = array ();
$steps = array ();
while ( $r_ex = $this -> db -> 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 = $this -> db -> query ( $sql_step );
while ( $r_step = $this -> db -> 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' ]];
}
$expense [ 'name' ] = $nameExpense ;
$expense [ 'amount' ] = rtrim ( rtrim ( $expense [ 'amount' ], '0' ), '.' );
$expenses_req [ $expense [ 'req_id' ]][] = $expense ;
if ( ! isset ( $expenses_total [ $expense [ 'req_id' ]])) $expenses_total [ $expense [ 'req_id' ]] = 0 ;
$expenses_total [ $expense [ 'req_id' ]] += $expense [ 'amount' ];
}
}
}
$depClass = new Department ;
$departments = $depClass -> getDepartments ();
//Для доступных юзеров
$this -> getIdsUsers ( $_SESSION [ 'id' ]);
//цикл формирования
foreach ( $requestList as $requisition ) {
$starttime2 = microtime ( true );
$details = $this -> get_req_details ( $requisition , false , $usersToUse , $sourcesToUse , $typesContracs , $typesReq , $departments , $needAutoSearch );
$details [ 'deposit' ] = 0 ;
$details [ 'depositArr' ] = array ( 'id' => 0 );
$details [ 'expenses' ] = array ();
if ( isset ( $deposits [ $details [ 'id' ]])){
$details [ 'deposit' ] = $deposits [ $details [ 'id' ]];
}
if ( isset ( $depositArr [ $details [ 'id' ]])){
$details [ 'depositArr' ] = $depositArr [ $details [ 'id' ]];
}
if ( isset ( $expenses_req [ $details [ 'id' ]])){
$details [ 'expenses' ] = $expenses_req [ $details [ 'id' ]];
}
if ( isset ( $expenses_total [ $details [ 'id' ]])){
$details [ 'expenses_total' ] = $expenses_total [ $details [ 'id' ]];
}
$result [ 'req' ][ 'req' . $requisition [ 'id' ]] = $details ;
$endtime3 = microtime ( true );
if ( $filtr -> stages -> ahency == 1 ){
$result [ 'req' ][ 'req' . $requisition [ 'id' ]][ 'can_del' ] = 0 ;
}
if ( $requisition [ 'complex_room_id' ] > 0 ){
$sql_room = " SELECT id, `number` FROM complex_rooms WHERE id = { $requisition [ 'complex_room_id' ] } " ;
$q_room = $this -> db -> query ( $sql_room );
$r_room = $this -> db -> fetch_assoc ( $q_room );
if ( $r_room ) {
$result [ 'req' ][ 'req' . $requisition [ 'id' ]][ 'complex_room_number' ] = $r_room [ 'number' ];
}
}
if ( isset ( $totalUnion [ $requisition [ 'id' ]])){
$result [ 'req' ][ 'req' . $requisition [ 'id' ]][ 'union_total' ] = $totalUnion [ $requisition [ 'id' ]];
} else {
$result [ 'req' ][ 'req' . $requisition [ 'id' ]][ 'union_total' ] = 0 ;
}
$t3 = $endtime3 - $starttime2 ;
$result [ 'req' ][ 'req' . $requisition [ 'id' ]][ 'time' ] = $t3 ;
}
//Теги
$arrActivities = array ();
$arrActivitiesName = array ();
$sql_adv = " SELECT * FROM `activities` WHERE `user_id` = ' " . $this -> user -> id . " ' OR `manager_id` = ' " . $this -> user -> id . " ' " ;
if ( $this -> user -> id_manager )
$sql_adv .= " OR `manager_id` = ' " . $this -> user -> id_manager . " ' OR `user_id` = ' " . $this -> user -> id_manager . " ' " ;
if ( $this -> agencyId )
$sql_adv .= " OR `manager_id` = ' " . $this -> agencyId . " ' OR `user_id` = ' " . $this -> agencyId . " ' " ;
$sql_adv .= ' ORDER BY `name`' ;
$q_adv = $this -> db -> query ( $sql_adv );
$rows_adv = $this -> db -> num_rows ( $q_adv );
if ( $rows_adv > 0 ) {
while ( $r_adv = $this -> db -> fetch_assoc ( $q_adv )) {
$arrActivities [] = array ( 'id' => $r_adv [ 'id' ], 'name' => trim ( $r_adv [ 'name' ]), 'color' => $r_adv [ 'color' ]);
$arrActivitiesName [ 'act' . $r_adv [ 'id' ]] = trim ( $r_adv [ 'name' ]);
}
}
$result [ 'total_req' ] = 0 ;
$qTotal = $this -> db -> query ( $sqlTotal );
while ( $rTotal = $this -> db -> fetch_assoc ( $qTotal )){
$result [ 'total_req' ] += ( int ) $rTotal [ 'total' ];
}
$result [ 'total_comission' ] = 0 ;
$qExpectedCommissionTotal = $this -> db -> query ( $sqlExpectedCommissionTotal );
while ( $rExpectedCommissionTotal = $this -> db -> fetch_assoc ( $qExpectedCommissionTotal )){
$result [ 'total_comission' ] += ( int ) $rExpectedCommissionTotal [ 'total' ];
}
$result [ 'allPages' ] = ceil ( $result [ 'total_req' ] / $this -> limit );
$result [ 'activities' ] = $arrActivities ;
$result [ 'activities_name' ] = $arrActivitiesName ;
}
$endtime2 = microtime ( true );
$t2 = $endtime2 - $starttime ;
$result [ 'after_cycle' ] = $t2 ;
$result [ 'sql2' ] = $sqls2 ;
$result [ 'sql_total' ] = $sqlTotal ;
$result [ 'funnel_id' ] = $funnelId ;
$result [ 'comission' ] = $sqlExpectedCommissionTotal ;
return $result ;
}
public function queryField ( $fields ){
$query = " " ;
$user = new User ;
$user -> get ( $_SESSION [ 'id' ]);
$agencyId = $user -> agencyId ;
$agencyFielsds = array ();
$sql = " SELECT * FROM client_req_fields WHERE `agency_id`= $agencyId order by id desc " ;
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q )){
$agencyFielsds [ $r [ 'id' ]] = $r ;
}
$agencyFielsdsP = array ();
$sql = " SELECT * FROM client_req_fields_podgroup WHERE `agency_id`= $agencyId order by id desc " ;
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q )){
$agencyFielsdsP [ $r [ 'id' ]] = $r ;
}
$fieldsJson = array ();
$fieldsInt = array ();
$fieldsString = array ();
$fieldsPod = array ();
$search = false ;
if ( ! empty ( $agencyFielsds )) {
foreach ( $fields as $key => $field ){
$arrField = explode ( " _ " , $key );
$typeField = 1 ;
if ( $arrField [ 0 ] == 'modelp' ){
$typeField = 2 ;
}
$field_id = ( int ) $arrField [ 1 ];
$value = trim ( json_encode ( $field , JSON_UNESCAPED_UNICODE ), '"' );
$fids = array ();
$sql = " SELECT id, field_id FROM requisition_data WHERE field_id = $field_id AND type = $typeField " ;
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q )){
$type = - 1 ;
if ( $typeField == 1 ){
if ( $agencyFielsds [ $r [ 'field_id' ]][ 'is_podgroup' ] == 0 ){
$type = $agencyFielsds [ $r [ 'field_id' ]][ 'type' ];
} else {
$type = 10 ;
}
} else if ( $typeField == 2 ){
$type = $agencyFielsdsP [ $r [ 'field_id' ]][ 'type' ];
}
if ( $type == 0 || $type == 5 ){
$fieldsString [] = array ( 'data_id' => $r [ 'id' ], 'value' => $value );
} else if ( $type == 3 ){
$fieldsJson [] = array ( 'data_id' => $r [ 'id' ], 'value' => $value );
}
else if ( $type == 1 || $type == 2 || $type == 4 ){
$fieldsInt [] = array ( 'data_id' => $r [ 'id' ], 'value' => $value );
} else if ( $type == 10 ){
$fieldsPod [] = array ( 'data_id' => $r [ 'id' ], 'value' => $value );
}
}
}
}
$req_ids = array ();
$req_ids_temp = array ();
if ( ! empty ( $fieldsPod )){
$ids = array ();
$values = array ();
foreach ( $fieldsPod as $fi ){
$ids [] = $fi [ 'data_id' ];
$arrVal = json_decode ( $fi [ 'value' ], true );
if ( is_array ( $arrVal )){
foreach ( $arrVal as $val ) {
if ( ! in_array ( $val , $values ))
$values [] = $val ;
}
} else {
if ( ! in_array ( $fi [ 'value' ], $values ))
$values [] = $fi [ 'value' ];
}
}
$sql = " SELECT req_id FROM requisition_data WHERE id in ( " . implode ( ',' , $ids ) . " ) AND value in ( " . implode ( ',' , $values ) . " ) " ;
//echo $sql;
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q )){
$req_ids_temp [] = $r [ 'req_id' ];
}
}
if ( ! empty ( $fieldsInt )){
$ids = array ();
$values = array ();
foreach ( $fieldsInt as $fi ){
$ids [] = $fi [ 'data_id' ];
$arrVal = json_decode ( $fi [ 'value' ], true );
if ( is_array ( $arrVal )){
foreach ( $arrVal as $val ) {
if ( ! in_array ( $val , $values ))
$values [] = $val ;
}
} else {
if ( ! in_array ( $fi [ 'value' ], $values ))
$values [] = $fi [ 'value' ];
}
}
$sql = " SELECT req_id FROM requisition_data WHERE id in ( " . implode ( ',' , $ids ) . " ) AND value in ( " . implode ( ',' , $values ) . " ) " ;
if ( ! empty ( $req_ids_temp )){
$sql .= " AND req_id in ( " . implode ( ',' , $req_ids_temp ) . " ) " ;
}
//echo $sql;
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q )){
$req_ids [] = $r [ 'req_id' ];
}
}
if ( ! empty ( $fieldsString )){
$ids = array ();
$values = '' ;
foreach ( $fieldsString as $fi ){
$ids [] = $fi [ 'data_id' ];
if ( $values != '' ){
$values .= ' OR ' ;
}
$values .= " value like '% " . $fi [ 'value' ] . " %' " ;
}
$sql = " SELECT req_id FROM requisition_data WHERE id in ( " . implode ( ',' , $ids ) . " ) AND ( $values ) " ;
if ( ! empty ( $req_ids_temp )){
$sql .= " AND req_id in ( " . implode ( ',' , $req_ids_temp ) . " ) " ;
}
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q )){
$req_ids [] = $r [ 'req_id' ];
}
}
if ( ! empty ( $fieldsJson )){
$ids = array ();
$values = '' ;
$arr_values = array ();
foreach ( $fieldsJson as $fi ){
$ids [] = $fi [ 'data_id' ];
if ( ! in_array ( $fi [ 'value' ], $arr_values )){
$arr_values [] = $fi [ 'value' ];
if ( $values != '' ){
$values .= ' OR ' ;
}
$values .= " JSON_CONTAINS(`value`, ' " . $fi [ 'value' ] . " ') > 0 " ;
}
}
$sql1 = " SELECT req_id FROM requisition_data WHERE id in ( " . implode ( ',' , $ids ) . " ) AND value != 'Array' AND value != '' AND value is not null AND ( $values ) " ;
if ( ! empty ( $req_ids_temp )){
$sql1 .= " AND req_id in ( " . implode ( ',' , $req_ids_temp ) . " ) " ;
}
$q1 = $this -> db -> query ( $sql1 );
while ( $r1 = $this -> db -> fetch_assoc ( $q1 )){
$req_ids [] = $r1 [ 'req_id' ];
}
}
if ( ! empty ( $req_ids )){
$query = " AND req.id in ( " . implode ( ',' , $req_ids ) . " ) " ;
} else if (( empty ( $fieldsJson ) && empty ( $fieldsInt ) && empty ( $fieldsString )) && ! empty ( $req_ids_temp )){
$query = " AND req.id in ( " . implode ( ',' , $req_ids_temp ) . " ) " ;
} else {
$query = " AND req.id in (0) " ;
}
return $query ;
}
public function get_req_fields ( $agency_id , $req_id = 0 , $funnel_id = 0 , $user_id = 0 ){
if ( $user_id == 0 ){
$user_id = ( int ) $_SESSION [ 'id' ];
}
$result = array ();
$result [ 'fields' ] = array ();
$steps_funnel = array ();
$linking_fields = array ();
$steps = array ();
if ( $user_id == 0 ){
$user_id = ( int ) $_SESSION [ 'id' ];
}
if ( $funnel_id > 0 ){
//В с е этапы воронки
$sql_funnel_step = " SELECT * FROM `funnel_steps` WHERE funnel_id = { $funnel_id } AND deleted=0 " ;
$q_funnel_step = $this -> db -> query ( $sql_funnel_step );
while ( $r_funnel_step = $this -> db -> fetch_assoc ( $q_funnel_step )){
$steps_funnel [ $r_funnel_step [ 'id' ]] = $r_funnel_step ;
$steps [] = ( int ) $r_funnel_step [ 'id' ];
}
//Выбор полей закрываемых на этапах
if ( ! empty ( $steps )){
$sql_linking = " SELECT * FROM `linking_steps_client_req` WHERE step_id in ( " . implode ( ',' , $steps ) . " ) " ;
$q_linking = $this -> db -> query ( $sql_linking );
while ( $r_linking = $this -> db -> fetch_assoc ( $q_linking )){
$linking_fields [] = $r_linking [ 'field_id' ];
}
}
}
if ( $agency_id > 0 ){
$sql = " SELECT * FROM client_req_fields WHERE agency_id = $agency_id AND is_req > 0 " ;
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q )){
$is_see = true ;
$tempArrNoSee = json_decode ( $r [ 'users_no_see' ], true );
if ( $r [ 'is_no_see' ] == 1 && ! empty ( $r [ 'users_no_see' ]) && ! empty ( $tempArrNoSee )){
$is_see = false ;
$arrNoSeeUsers = array ();
foreach ( $tempArrNoSee as $u ){
if ( strpos ( $u , 'all_' ) !== false ){
$manId = str_replace ( 'all_' , '' , $u );
$sql_u = " SELECT id FROM `users`
WHERE id = $manId OR
id_manager = $manId OR
id_manager IN ( SELECT id FROM users WHERE id_manager = $manId ) " ;
$q_u = mysql_query ( $sql_u );
while ( $r_u = mysql_fetch_row ( $q_u )){
$arrNoSeeUsers [] = ( int ) $r_u [ 0 ];
}
} else {
$arrNoSeeUsers [] = ( int ) $u ;
}
}
if ( in_array ( $user_id , $arrNoSeeUsers )){
$is_see = true ;
}
}
if ( ! $is_see ) continue ;
$r [ 'is_close_step' ] = 0 ;
if ( in_array ( $r [ 'id' ], $linking_fields )){
$r [ 'is_close_step' ] = 1 ;
}
if ( ! empty ( $r [ 'params' ])){
$r [ 'params' ] = json_decode ( $r [ 'params' ], true );
}
if ( ! $r [ 'params' ] || $r [ 'params' ] == null ) {
$r [ 'params' ] = [];
}
if ( $r [ 'is_podgroup' ] > 0 ){
$r [ 'podgroups' ] = array ();
$r [ 'podgroups_select' ] = array ();
$sql_p = " SELECT * FROM client_req_fields_podgroup WHERE group_id = $r[id] AND agency_id = $agency_id " ;
$q_p = $this -> db -> query ( $sql_p );
while ( $r_p = $this -> db -> fetch_assoc ( $q_p )){
if ( ! empty ( $r_p [ 'params' ])){
$r_p [ 'params' ] = json_decode ( $r_p [ 'params' ], true );
}
if ( ! $r_p [ 'params' ] || $r_p [ 'params' ] == null ) {
$r_p [ 'params' ] = [];
}
$r [ 'podgroups_select' ][] = array ( 'id' => $r_p [ 'id' ], 'title' => $r_p [ 'title' ]);
$r [ 'podgroups' ][] = $r_p ;
}
}
$result [ 'fields' ][] = $r ;
}
//Значения
$values = array ();
if ( $req_id > 0 ){
$sql_val = " SELECT * FROM requisition_data WHERE req_id= $req_id " ;
$q_val = $this -> db -> query ( $sql_val );
while ( $r_val = $this -> db -> fetch_assoc ( $q_val )){
if ( $r_val [ 'type' ] == 1 ){
$values [ 'model_' . $r_val [ 'field_id' ]] = $r_val [ 'value' ];
} else if ( $r_val [ 'type' ] == 2 ){
$values [ 'modelp_' . $r_val [ 'field_id' ]] = $r_val [ 'value' ];
}
}
}
$result [ 'values' ] = $values ;
$result [ 'linking_fields' ] = $linking_fields ;
$result [ 'sql' ] = $sql_funnel_step ;
}
return $result ;
}
// Заявка(ки) по status
public function getReqAndWhoWorkByStatusId ( $status_id , $is_interrupted = 0 , $where_is_interrupted = true , $er_is_interrupted = 0 , $where_er_is_interrupted = false )
{
$result = [];
$sql = " SELECT
req .* ,
req . id as req_id ,
user .* ,
user . id as user_id ,
cr . number as complex_room_number ,
cl . name as complex_name
FROM requisitions AS req
LEFT JOIN users AS user on user . id = req . who_work
JOIN complex_rooms cr on cr . id = req . complex_room_id
JOIN complex_floors cf on cf . id = cr . floor_id
JOIN complex_entrances ce on ce . id = cf . complex_entrance_id
JOIN complex_houses ch on ch . id = ce . complex_house_id
JOIN complex_list cl on cl . id = ch . complex_id
WHERE " ;
$sql .= is_array ( $status_id ) ? " req.complex_status_id IN ( " . implode ( ',' , $status_id ) . " ) " : " req.complex_status_id = $status_id " ;
$sql .= $where_is_interrupted ? " AND req.is_interrupted = $is_interrupted " : " " ;
$sql .= $where_er_is_interrupted ? " AND req.er_is_interrupted = $er_is_interrupted " : " " ;
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q ))
{
$result [] = $r ;
}
return $result ;
}
// Заявка(ки) по id
public function get_req_id ( $req_id , $needAutoSearch = false , $is_kanban = false ) {
$result = [];
$typesReq = []; //$this->get_type();
if ( $this -> agencyId > 0 ){
$typesReq = $this -> get_type ();
}
if ( is_array ( $req_id )) {
$sql = " SELECT
req .* ,
cr . `number` as complex_room_number
FROM requisitions AS req
LEFT JOIN complex_rooms AS cr ON cr . `id` = req . `complex_room_id`
WHERE req . `id` IN ( " . implode(',', $req_id ) . " ) " ;
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q ))
{
$result [ 'req' . $r [ 'id' ]] = $this -> get_req_details ( $r , false , [], [], [], $typesReq , [], $needAutoSearch );
}
} else {
$sql = " SELECT
req .* ,
cr . `number` as complex_room_number
FROM requisitions as req
LEFT JOIN complex_rooms AS cr ON cr . `id` = req . `complex_room_id`
WHERE req . `id` = $req_id " ;
$q = $this -> db -> query ( $sql );
$r = $this -> db -> fetch_assoc ( $q );
if ( $r [ 'client_id' ] > 0 ){
$sql_cl = " SELECT id, fio, phone FROM clients WHERE id = { $r [ 'client_id' ] } " ;
$q_cl = $this -> db -> query ( $sql_cl );
$r_cl = $this -> db -> fetch_assoc ( $q_cl );
if ( should_hide_contacts_for_current_user ()) {
$r [ 'phone' ] = mask_client_phone ( $r_cl [ 'phone' ]);
$r [ 'fio' ] = mask_fio_if_contains_phone ( $r_cl [ 'fio' ]);
} else {
$r [ 'phone' ] = preg_replace ( " /[^,.0-9]/ " , '' , $r_cl [ 'phone' ]);
$r [ 'fio' ] = $r_cl [ 'fio' ];
}
}
/**
* Финансы
* */
$deposits = array ();
$depositArr = array ();
$sql_deposit = " SELECT * FROM deposits_clients_req WHERE req_id = $req_id " ;
$q_deposit = $this -> db -> query ( $sql_deposit );
while ( $r_deposit = $this -> db -> fetch_assoc ( $q_deposit )){
$deposits [ $r_deposit [ 'req_id' ]] = $r_deposit [ 'deposit' ];
$depositArr [ $r_deposit [ 'req_id' ]] = $r_deposit ;
}
$expenses_req = array ();
$expenses = array ();
$expenses_total = array ();
$sql_ex = " SELECT * FROM expenses_req WHERE req_id = $req_id " ;
$q_ex = $this -> db -> query ( $sql_ex );
if ( $this -> db -> num_rows ( $q_ex ) > 0 ){
$steps_ids = array ();
$steps = array ();
while ( $r_ex = $this -> db -> 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 = $this -> db -> query ( $sql_step );
while ( $r_step = $this -> db -> 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' ]];
}
$expense [ 'name' ] = $nameExpense ;
$expense [ 'is_edit' ] = false ;
$expense [ 'amount' ] = rtrim ( rtrim ( $expense [ 'amount' ], '0' ), '.' );
$expenses_req [ $expense [ 'req_id' ]][] = $expense ;
if ( ! isset ( $expenses_total [ $expense [ 'req_id' ]])) $expenses_total [ $expense [ 'req_id' ]] = 0 ;
$expenses_total [ $expense [ 'req_id' ]] += $expense [ 'amount' ];
}
}
$r [ 'deposit' ] = 0 ;
$r [ 'expenses' ] = array ();
$r [ 'expenses_total' ] = 0 ;
$r [ 'depositArr' ] = array ( 'id' => 0 );
if ( isset ( $deposits [ $r [ 'id' ]])){
$r [ 'deposit' ] = $deposits [ $r [ 'id' ]];
}
if ( isset ( $depositArr [ $r [ 'id' ]])){
$r [ 'depositArr' ] = $depositArr [ $r [ 'id' ]];
}
if ( isset ( $expenses_req [ $r [ 'id' ]])){
$r [ 'expenses' ] = $expenses_req [ $r [ 'id' ]];
}
if ( isset ( $expenses_total [ $r [ 'id' ]])){
$r [ 'expenses_total' ] = $expenses_total [ $r [ 'id' ]];
}
if ( $is_kanban ){
$reqIds [] = $req_id ;
$events_res [ $r [ 'id' ]] = array ( 'events_res' => 0 , 'events_res1' => 0 , 'events_res2' => 0 );
if ( ! empty ( $reqIds )){
$events = " SELECT count(id) as res, req_id FROM user_client_events WHERE calendar_view = 0
and schedule_date is not null and req_id in ( " .implode(',', $reqIds ). " ) and schedule_date < '" . date("Y-m-d H:i:s") . "' and type in ( 'call' , 'meet' , 'show' , 'deal' , 'even' ) and schedule_date <> '0000-00-00 00:00:00' and cancel = 0 group by req_id " ;
$events1 = " SELECT count(id) as res, req_id FROM user_client_events WHERE calendar_view = 0
and schedule_date is not null and req_id in ( " .implode(',', $reqIds ). " ) and DATE_FORMAT ( schedule_date , '%Y-%m-%d' ) = '" . date("Y-m-d") . "' and type in ( 'call' , 'meet' , 'show' , 'deal' , 'even' ) and schedule_date <> '0000-00-00 00:00:00' and cancel = 0 group by req_id " ;
$events2 = " SELECT count(id) as res, req_id FROM user_client_events WHERE calendar_view = 0
and schedule_date is not null and req_id in ( " .implode(',', $reqIds ). " ) and DATE_FORMAT ( schedule_date , '%Y-%m-%d' ) > '" . date("Y-m-d") . "' and type in ( 'call' , 'meet' , 'show' , 'deal' , 'even' ) and schedule_date <> '0000-00-00 00:00:00' and cancel = 0 group by req_id " ;
$q_events = $this -> db -> query ( $events );
while ( $event_res = $this -> db -> fetch_assoc ( $q_events )){
$events_res [ $event_res [ 'req_id' ]][ 'events_res' ] = ( int ) $event_res [ 'res' ];
}
$q_events1 = $this -> db -> query ( $events1 );
while ( $event_res1 = $this -> db -> fetch_assoc ( $q_events1 )){
$events_res [ $event_res1 [ 'req_id' ]][ 'events_res1' ] = ( int ) $event_res1 [ 'res' ];
}
$q_events2 = $this -> db -> query ( $events2 );
while ( $event_res2 = $this -> db -> fetch_assoc ( $q_events2 )){
$events_res [ $event_res2 [ 'req_id' ]][ 'events_res2' ] = ( int ) $event_res2 [ 'res' ];
}
}
$result [ 'req' . $r [ 'id' ]] = $this -> get_req_details_kanban ( $r , true , [], [], $typesReq , $events_res );
} else {
$result [ 'req' . $r [ 'id' ]] = $this -> get_req_details ( $r , false , [], [], [], $typesReq , [], $needAutoSearch );
}
}
$result [ 'is_kanban' ] = $is_kanban ;
$result [ 'e' ] = $events_res ;
return $result ;
}
//Добавление/редактирование заявки
public function add_edit ( $params ) {
/* if ( $_SESSION [ 'id' ] == 22111 ){
error_reporting ( E_ALL | E_STRICT );
ini_set ( 'display_errors' , 1 );
} */
$errors = [];
$hasSave = true ;
//var_dump($params);
if ( ! isset ( $params [ 'add_obj' ])){
$sql_type = " SELECT * FROM requisitions_type WHERE id = { $params [ 'type_id' ] } " ;
$q_type = $this -> db -> query ( $sql_type );
$r_type = $this -> db -> fetch_assoc ( $q_type );
$parentType = $params [ 'type_id' ];
if ( $r_type [ 'heir' ] > 0 ){
$parentType = $r_type [ 'heir' ];
}
}
if ( $params [ 'object_id' ] > 0 && ( $params [ 'type_id' ] == 2 || $parentType == 2 )) {
$filtr = ( object ) array ( 'object_id' => $params [ 'object_id' ], 'type' => [ $params [ 'type_id' ]]);
if ( isset ( $params [ 'req_id' ])) {
$filtr = ( object ) array ( 'object_id' => $params [ 'object_id' ], 'not_id' => $params [ 'req_id' ], 'type' => [ $params [ 'type_id' ]]);
}
//$search = $this->get_all($user = $params['user_id'], $filtr);
$sql_check_exist_object_in_req = " SELECT * FROM requisitions WHERE object_id = " . ( int ) $params [ 'object_id' ];
// Исключаем текущую заявку при редактировании
if ( isset ( $params [ 'req_id' ]) && ( int ) $params [ 'req_id' ] > 0 ) {
$sql_check_exist_object_in_req .= " AND id != " . ( int ) $params [ 'req_id' ];
}
//Фильтр по типу заявки
$sql_check_exist_object_in_req .= " AND type_id = " . ( int ) $params [ 'type_id' ] . " AND deleted=0 AND cancel=0 " ;
$sql_check_exist_object_in_req .= " LIMIT 1 " ;
$q_check_exist_object_in_req = $this -> db -> query ( $sql_check_exist_object_in_req );
$search = $this -> db -> fetch_assoc ( $q_check_exist_object_in_req );
if ( ! empty ( $search )) {
$hasSave = false ;
$res [ 'error' ] = 1001 ;
$res [ 'mes' ] = " Этот объект уже добавлен в заявку " ;
$keys = array_keys ( $search [ 'req' ]);
$firstKey = $keys [ 0 ];
if ( isset ( $search [ $firstKey ][ 'name' ])) {
$res [ 'mes' ] .= " « " . $search [ $firstKey ][ 'name' ] . " » " ;
}
return $res ;
}
}
if ( $hasSave ) {
$activities = htmlspecialchars ( json_encode ( $params [ 'activities' ]));
if ( $params [ 'type_id' ] == 4 || $parentType == 4 ) {
if ( intval ( $params [ 'autosearch_enabled' ]) == 1 && intval ( $params [ 'object_id' ]) > 0 ) {
$objToFilter = $this -> autosearch_instce -> syncObjectToFilter (
intval ( $params [ 'asfilter_id' ]),
intval ( $params [ 'object_id' ]),
intval ( $params [ 'req_id' ]),
( intval ( $params [ 'asfilter_id' ]) > 0 )
);
if ( $objToFilter [ 'success' ])
$params [ 'asfilter_id' ] = $objToFilter [ 'filter_id' ];
else
$errors = array_merge ( $errors , $objToFilter [ 'errors' ]);
$asfilter_sql = " UPDATE `autosearch_filters` SET `is_reverse` = 1 WHERE `id` = " . $params [ 'asfilter_id' ];
if ( ! $this -> db -> query ( $asfilter_sql )) {
$errors [] = $this -> db -> errorInfo ();
}
} else if ( intval ( $params [ 'autosearch_enabled' ]) == 0 ) {
/* $this -> autosearch_instce -> deleteFilter ( intval ( $params [ 'asfilter_id' ]), $_SESSION [ 'id' ]);
$params [ 'asfilter_id' ] = '0' ; */
$asfilter_sql = " UPDATE `autosearch_filters` SET `is_reverse` = 0 WHERE `id` = " . $params [ 'asfilter_id' ];
if ( ! $this -> db -> query ( $asfilter_sql )) {
$errors [] = $this -> db -> errorInfo ();
}
}
}
$property_type_id = 0 ;
if ( $params [ 'object_id' ] > 0 ){
$property_type_id = $this -> check_property_type ( $params [ 'object_id' ]);
}
$complex_room_id = $params [ 'complex_room_id' ] ? $params [ 'complex_room_id' ] : 'NULL' ;
$friend_client_id = $params [ 'friend_client_id' ] ? $params [ 'friend_client_id' ] : 0 ;
$confirm_recommendation = $params [ 'confirm_recommendation' ] && ( $params [ 'confirm_recommendation' ] == 1 || $params [ 'confirm_recommendation' ] == 2 ) ? $params [ 'confirm_recommendation' ] : 'NULL' ;
$complex = new Complex ();
$reservations = $complex -> get_room_reservations ( $complex_room_id );
$last_requisition = $reservations [ count ( $reservations ) - 1 ];
$position = $last_requisition && $last_requisition [ 'position' ] ? (( int ) $last_requisition [ 'position' ] + 1 ) : 1 ;
$is_manual = 0 ;
if ( isset ( $params [ 'is_manual' ])){
$is_manual = $params [ 'is_manual' ];
}
$agency = new User ;
if ( isset ( $_SESSION [ 'id' ])) {
$agency -> get ( $_SESSION [ 'id' ]);
} else {
$agency -> get ( $params [ 'user_id' ]);
}
$agency_id = $agency -> agencyId ;
$is_general = false ;
$in_sql = " INSERT INTO requisitions (user_id, funnel_id, name, description, asfilter_id, type_id, object_id, client_id, stage, priority, confirm, who_work, hot, activities, source, employee_id, property_type_id, `complex_status_id`, complex_room_id, friend_client_id, confirm_recommendation, position, is_manual)
values ( $params [ user_id ], $params [ funnel_id ], '$params[name]' , '$params[opis]' , '$params[asfilter_id]' , $params [ type_id ], $params [ object_id ], $params [ client_id ], 1 , $params [ priority ], $params [ confirm ], $params [ who_work ], $params [ hot ], '$activities' , '$params[source]' , '$params[employee_id]' , $property_type_id , '$params[status]' , $complex_room_id , $friend_client_id , $confirm_recommendation , $position , $is_manual ) " ;
if ( $params [ 'req_id' ] > 0 && ! isset ( $params [ 'add_obj' ])) {
$in_sql = " UPDATE requisitions SET
funnel_id = $params [ funnel_id ],
name = '$params[name]' ,
description = '".mysql_real_escape_string($params[' opis '])."' ,
asfilter_id = $params [ asfilter_id ],
type_id = $params [ type_id ],
object_id = $params [ object_id ],
client_id = $params [ client_id ],
priority = $params [ priority ],
confirm = $params [ confirm ],
who_work = $params [ who_work ],
hot = $params [ hot ],
activities = '$activities' ,
employee_id = '$params[employee_id]' ,
property_type_id = $property_type_id ,
`complex_status_id` = '$params[status]' ,
complex_room_id = $complex_room_id ,
friend_client_id = $friend_client_id ,
confirm_recommendation = $confirm_recommendation " ;
//Если передача в общие то восстанавливаем заявку
if ( $params [ 'who_work' ] == 0 && $params [ 'confirm' ] == 0 ){
$is_general = true ;
$in_sql .= " , deleted=0 " ;
$dop_text = " Переведена в общие " ;
$sql_ev = " INSERT INTO events_clients (req_id, event, dop_text, user_id) VALUES ( { $params [ 'req_id' ] } , 'update', ' { $dop_text } ', { $params [ 'user_id' ] } ) " ;
$this -> db -> query ( $sql_ev );
}
//echo $in_sql;
if ( isset ( $params [ 'source' ])){
$in_sql .= " , source=' $params[source] ' " ;
}
$in_sql .= " WHERE id = $params[req_id] " ;
$this -> updateFunnel ( $params [ 'funnel_id' ], $params [ 'req_id' ]);
} else if ( isset ( $params [ 'add_obj' ])) {
$in_sql = " UPDATE requisitions SET
object_id = $params [ object_id ],
property_type_id = $property_type_id
WHERE id = $params [ req_id ] " ;
}
if ( $params [ 'complex_room_id' ] && $params [ 'status' ]) {
$this -> db -> query ( " UPDATE complex_rooms SET `complex_status_id` = ' $params[status] ' WHERE id = { $params [ 'complex_room_id' ] } " );
}
$new_req = false ;
$req_id = 0 ;
if ( ! $this -> db -> query ( $in_sql ))
$errors [] = $this -> db -> errorInfo ();
if ( $params [ 'req_id' ] > 0 ) {
$req_id = ( int ) $params [ 'req_id' ];
if ( $is_general ){
$reqs = array ( $req_id );
$this -> set_user ( $agency );
$this -> autoUnitReq ( 0 , $reqs );
}
} else {
$req_id = $this -> db -> insert_id ();
$new_req = true ;
$temp_req = $params ;
$temp_req [ 'id' ] = $req_id ;
$this -> set_user ( $agency );
$this -> check_mesages ( $temp_req , [], 2 );
}
if ( isset ( $params [ 'newClientName' ]) && ! empty ( $params [ 'newClientName' ]) && $req_id > 0 ){
$client_id = ( int ) $params [ 'client_id' ];
if ( $client_id > 0 ){
$sql = " UPDATE `clients` SET
`fio` = '{$params[' newClientName ']}'
WHERE `id` = '$client_id' " ;
$this -> db -> query ( $sql );
if ( $params [ 'type_id' ] > 0 ){
$name_type = $this -> db -> fetch_assoc ( $this -> db -> query ( " SELECT name FROM requisitions_type WHERE id = { $params [ 'type_id' ] } " ))[ 'name' ];
}
$new_req_name = $name_type . ' для ' . $params [ 'newClientName' ];
$this -> db -> query ( " UPDATE requisitions SET name = ' { $new_req_name } ' WHERE id= { $req_id } " );
}
}
if ( ! isset ( $params [ 'add_obj' ])) {
//Теги
if ( $req_id > 0 ) {
if ( ! $this -> db -> query ( " DELETE FROM requisitions_activities WHERE req_id = { $req_id } " ))
$errors [] = $this -> db -> errorInfo ();
foreach ( $params [ 'activities' ] as $a ) {
$sql_in = " INSERT INTO requisitions_activities SET req_id = { $req_id } , activity_id= { $a } " ;
if ( ! $this -> db -> query ( $sql_in ))
$errors [] = $this -> db -> errorInfo ();
}
}
if ( $params [ 'type_id' ] == 1 || $params [ 'type_id' ] == 4 || $parentType == 1 || $parentType == 4 ) {
if ( isset ( $params [ 'asfilter_id' ]) && $req_id !== 0 ) {
$this -> autosearch_instce -> setReqToFilter ( $req_id , intval ( $params [ 'asfilter_id' ]), $_SESSION [ 'id' ]);
}
}
//Добавляем событие передачи
if ( $params [ 'confirm' ] == 0 && $params [ 'old_whowork' ] != $params [ 'who_work' ]) {
$new_owner_id_check_event = intval ( $params [ 'who_work' ]);
if ( $req_id > 0 && $new_owner_id_check_event > 0 ) {
$sql_clear = " UPDATE events_clients SET `read` = 1, date_update = NOW() WHERE req_id = $req_id AND event = 'transmitted' " ;
mysql_query ( $sql_clear );
}
//$sql_conf = "INSERT INTO `events_clients` (`user_id`, `req_id`, `from_id`, `event`) VALUES (".$params['old_whowork'].", ".$req_id.", ".$params['who_work'].", 'transmitted')";
$sql_conf = " INSERT INTO `events_clients` (`user_id`, `req_id`, `from_id`, `event`) VALUES ( " . $_SESSION [ 'id' ] . " , " . $req_id . " , " . $params [ 'who_work' ] . " , 'transmitted') " ;
if ( ! $this -> db -> query ( $sql_conf ))
$errors [] = $this -> db -> errorInfo ();
}
if ( $params [ 'object_id' ] > 0 && $params [ 'client_id' ] > 0 && $params [ 'type_id' ] != 4 && $parentType != 4 ) {
$objectArr = array ();
$sql_cl = " SELECT objects FROM clients WHERE id= $params[client_id] " ;
$q_cl = $this -> db -> query ( $sql_cl );
$r_cl = $this -> db -> fetch_assoc ( $q_cl );
if ( ! empty ( $r_cl [ 'objects' ])) {
$arrObj = json_decode ( html_entity_decode ( $r_cl [ 'objects' ]), ENT_QUOTES );
foreach ( $arrObj as $oneObj ) {
$objectArr [] = strval ( $oneObj );
}
if ( ! in_array ( $params [ 'object_id' ], $objectArr )) {
$objectArr [] = strval ( $params [ 'object_id' ]);
}
} else {
$objectArr [] = strval ( $params [ 'object_id' ]);
}
if ( ! empty ( $objectArr )) {
$cl = new Clients ();
$cl -> update_objects ( $params [ 'client_id' ], null , $objectArr );
$obj = htmlentities ( json_encode ( $objectArr ));
$up_client = " UPDATE clients SET objects=' $obj ' where id = $params[client_id] " ;
if ( ! $this -> db -> query ( $up_client ))
$errors [] = $this -> db -> errorInfo ();
}
}
// Сохранение данных предварительной оценки
if (
//!is_null($params['object_price']) ||
! is_null ( $params [ 'object_prep_price' ]) ||
! is_null ( $params [ 'object_start_price' ]) ||
! is_null ( $params [ 'object_fact_price' ])
) {
$price = ( isset ( $params [ 'object_price' ])) ? $params [ 'object_price' ] : " NULL " ;
$prep_price = ( isset ( $params [ 'object_prep_price' ])) ? $params [ 'object_prep_price' ] : " NULL " ;
$start_price = ( isset ( $params [ 'object_start_price' ])) ? $params [ 'object_start_price' ] : " NULL " ;
$fact_price = ( isset ( $params [ 'object_fact_price' ])) ? $params [ 'object_fact_price' ] : " NULL " ;
$object_id = $params [ 'object_id' ];
$sqlCheck = " SELECT * FROM `object_prices` WHERE `object_id` = $object_id AND `agency_id` = ' $agency_id ' " ;
$resCheck = $this -> db -> query ( $sqlCheck );
if ( $this -> db -> num_rows ( $resCheck ) == 0 ) {
$sql = " INSERT INTO `object_prices` (
`object_id` ,
`price` ,
`prep_price` ,
`start_price` ,
`fact_price` ,
`agency_id`
) VALUES (
'$object_id' ,
'$price' ,
'$prep_price' ,
'$start_price' ,
'$fact_price' ,
'$agency_id'
) " ;
if ( ! $this -> db -> query ( $sql )) {
$errors [] = $this -> db -> errorInfo ();
}
} else {
$sql = " UPDATE `object_prices` SET `prep_price` = ' $prep_price ', `start_price` = ' $start_price ', `fact_price` = ' $fact_price ' WHERE `object_id` = ' $object_id ' and `agency_id` = ' $agency_id ' " ;
if ( ! $this -> db -> query ( $sql )) {
$errors [] = $this -> db -> errorInfo ();
}
}
}
//Поля которые может редактировать сотрудник
$fields_can_edid = array ();
$sql_field = " SELECT * FROM `client_req_fields` WHERE agency_id = { $agency_id } " ;
$q_fields = $this -> db -> query ( $sql_field );
while ( $r_fields = $this -> db -> fetch_assoc ( $q_fields )){
$tempArrNoSee = json_decode ( $r_fields [ 'users_no_see' ], true );
if ( $r_fields [ 'is_no_see' ] == 1 && ! empty ( $r_fields [ 'users_no_see' ]) && ! empty ( $tempArrNoSee )){
$arrNoSeeUsers = array ();
foreach ( $tempArrNoSee as $u ){
if ( strpos ( $u , 'all_' ) !== false ){
$manId = str_replace ( 'all_' , '' , $u );
$sql_u = " SELECT id FROM `users`
WHERE id = $manId OR
id_manager = $manId OR
id_manager IN ( SELECT id FROM users WHERE id_manager = $manId ) " ;
$q_u = mysql_query ( $sql_u );
while ( $r_u = mysql_fetch_row ( $q_u )){
$arrNoSeeUsers [] = ( int ) $r_u [ 0 ];
}
} else {
$arrNoSeeUsers [] = ( int ) $u ;
}
}
if ( in_array ( $_SESSION [ 'id' ], $arrNoSeeUsers )){
$fields_can_edid [] = ( int ) $r_fields [ 'id' ];
}
} else {
$fields_can_edid [] = ( int ) $r_fields [ 'id' ];
}
}
//Кастомные поля
if ( ! empty ( $fields_can_edid )){
$sql_del = " DELETE FROM requisition_data WHERE req_id= $req_id and field_id in ( " . implode ( ',' , $fields_can_edid ) . " ) " ;
if ( ! $this -> db -> query ( $sql_del ))
$errors [] = $this -> db -> errorInfo ();
if ( ! empty ( $params [ 'field_models' ])) {
foreach ( $params [ 'field_models' ] as $key => $field_models ) {
$arrField = explode ( " _ " , $key );
$typeField = 1 ;
if ( $arrField [ 0 ] == 'modelp' ) {
$typeField = 2 ;
}
$value = json_encode ( $field_models , JSON_UNESCAPED_UNICODE );
$field_id = ( int ) $arrField [ 1 ];
$sql_in = " INSERT INTO requisition_data SET " .
" req_id= $req_id , " .
" field_id= $field_id , " .
" type= $typeField , " .
" value=' $value ' " ;
if ( ! $this -> db -> query ( $sql_in ))
$errors [] = $this -> db -> errorInfo ();
}
}
}
if ( $req_id > 0 ) {
if ( ! empty ( $params [ 'contracts' ])) {
foreach ( $params [ 'contracts' ] as $contract ) {
if ( ! isset ( $contract -> id )) {
$date_start = strtotime ( $contract -> date_start );
$date_end = strtotime ( $contract -> date_end );
$sql = " INSERT INTO contracts_req SET " .
" req_id = { $req_id } , " .
" type = { $contract -> type } , " .
" date_start = { $date_start } , " .
" date_end = { $date_end } , " .
" number = ' { $contract -> number } ', " .
" days = { $contract -> days_mes_end } , " .
" send = { $contract -> no_mes_end } " ;
if ( ! $this -> db -> query ( $sql ))
$errors [] = $this -> db -> errorInfo ();
}
}
}
if ( $params [ 'object_id' ] > 0 && ( $params [ 'type_id' ] == 2 || $parentType == 2 )){
$this -> contractInObject ( $req_id , $params [ 'object_id' ]);
}
//сохраняем данные wazzap
if ( isset ( $params [ 'wazzap_chat_type' ]) && $params [ 'wazzap_chat_type' ] &&
isset ( $params [ 'wazzap_chat_id' ]) && $params [ 'wazzap_chat_id' ] &&
isset ( $params [ 'wazzap_channel_id' ]) && $params [ 'wazzap_channel_id' ]) {
$wazzap_chat_type = $params [ 'wazzap_chat_type' ];
$wazzap_chat_id = $params [ 'wazzap_chat_id' ];
$wazzap_channel_id = $params [ 'wazzap_channel_id' ];
$wazzap_user_id = $params [ 'wazzap_user_id' ];
$wazzap_integration_id = $params [ 'wazzap_integration_id' ];
//связываем заявку с чатом wazzap
$sql = " INSERT INTO `requisition_data_wazzap` (`requisition_id`, `chat_type`, `chat_id`, `channel_id`, `user_id`, `integration_id`) VALUES (' $req_id ', ' $wazzap_chat_type ', ' $wazzap_chat_id ', ' $wazzap_channel_id ', ' $wazzap_user_id ', ' $wazzap_integration_id ') " ;
$this -> db -> query ( $sql );
$client_id = ( int ) $params [ 'client_id' ];
$agency_id = User :: getUserAgencyID ();
$wazzap = new Wazzap ( $agency_id , $this -> db );
//проверяем, передавался ли клиент в wazzap
$sqlCheck = " SELECT * FROM `client_data_wazzap` WHERE `client_id` = $client_id " ;
$resCheck = $this -> db -> query ( $sqlCheck );
if ( $this -> db -> num_rows ( $resCheck ) == 0 ) {
$sql_cl_fio = " SELECT fio FROM clients WHERE id = $client_id " ;
$q_cl_fio = $this -> db -> query ( $sql_cl_fio );
$r_cl_fio = $this -> db -> fetch_assoc ( $q_cl_fio );
//связываем клиента с чатом wazzap
$sql2 = " INSERT INTO `client_data_wazzap` (`client_id`, `chat_type`, `chat_id`, `channel_id`, `user_id`, `integration_id`) VALUES (' $client_id ', ' $wazzap_chat_type ', ' $wazzap_chat_id ', ' $wazzap_channel_id ', ' $wazzap_user_id ', ' $wazzap_integration_id ') " ;
$this -> db -> query ( $sql2 );
//создаем е г о в wazzap
$wazzap -> createWazzapContact ( $client_id , $wazzap_user_id , $r_cl_fio [ " fio " ], $wazzap_chat_type , $wazzap_chat_id );
}
$name = $params [ 'name' ];
if ( mb_strlen ( $name ) > 200 ) {
$name = mb_substr ( $name , 0 , 195 );
}
//создаем сделку в wazzap
$wazzap -> createWazzapDeal ( $req_id , $wazzap_user_id , $name , $client_id );
}
if ( ! isset ( $agency_id )){
$agency = new User ;
$agency -> get ( $_SESSION [ 'id' ]);
$agency_id = $agency -> agencyId ;
}
/* if ( $agency_id == 5238 ){
$w = new WebHookSend ( $agency_id , 2 , $req_id , 'req' );
} */
if ( $agency_id == 13154 ){
$w = new WebHookSend ( $agency_id , 2 , $req_id , 'req' );
}
}
}
if ( ! empty ( $errors )){
$result [ 'error' ] = $errors ;
return $result ;
}
return $req_id ;
}
}
2026-06-20 10:19:54 +02:00
// Копирование заявки в одной транзакции. Возвращает [success, id, error, code].
public function copy ( $srcId , $funnelId , $whoWorkId , $currentUserId ) {
$srcId = ( int ) $srcId ;
$funnelId = ( int ) $funnelId ;
$whoWorkId = ( int ) $whoWorkId ;
$currentUserId = ( int ) $currentUserId ;
$qSrc = $this -> db -> query ( " SELECT * FROM requisitions WHERE id = { $srcId } LIMIT 1 " );
$src = $this -> db -> fetch_assoc ( $qSrc );
if ( ! $src ) {
return array (
'success' => false ,
'error' => 'Исходная заявка не найдена' ,
'code' => 'src_not_found' ,
'id' => null ,
);
}
if (( int ) $src [ 'deleted' ] === 1 ) {
return array (
'success' => false ,
'error' => 'Нельзя копировать закрытую заявку' ,
'code' => 'src_deleted' ,
'id' => null ,
);
}
$srcTypeId = ( int ) $src [ 'type_id' ];
$qType = $this -> db -> query ( " SELECT id, heir FROM requisitions_type WHERE id = { $srcTypeId } LIMIT 1 " );
$typeRow = $this -> db -> fetch_assoc ( $qType );
$baseTypeId = $typeRow ? requisition_base_type_id ( $typeRow ) : 0 ;
// funnel_id=0 — дефолтная воронка без funnel_steps; step_id=1 («Новый»).
if ( $funnelId === 0 ) {
$newStepId = 1 ;
} else {
$qStep = $this -> db -> query (
" SELECT id FROM funnel_steps WHERE funnel_id = { $funnelId } AND deleted = 0 ORDER BY order_number, branch LIMIT 1 "
);
$firstStep = $this -> db -> fetch_assoc ( $qStep );
if ( ! $firstStep ) {
return array (
'success' => false ,
'error' => 'В выбранной воронке нет этапов' ,
'code' => 'no_steps' ,
'id' => null ,
);
}
$newStepId = ( int ) $firstStep [ 'id' ];
}
$srcName = isset ( $src [ 'name' ]) ? ( string ) $src [ 'name' ] : '' ;
$newName = ( trim ( $srcName ) === '' ) ? '' : 'Копия: ' . $srcName ;
$copyObject = requisition_should_copy_object ( $baseTypeId );
$newObjectId = $copyObject ? ( int ) $src [ 'object_id' ] : 0 ;
$copyFilters = requisition_should_copy_search_filters ( $baseTypeId );
// ВАЖНО: нативный PDO begin/commit (query("BEGIN") глотает PDOException). Даты через NOW() — TZ-смещение.
try {
$this -> db -> beginTransaction ();
$now = date ( 'Y-m-d H:i:s' );
$nameSql = mysql_real_escape_string ( $newName );
$sourceVal = ( int ) $src [ 'source' ];
$hot = ( int ) $src [ 'hot' ];
$priority = ( int ) $src [ 'priority' ];
$clientId = ( int ) $src [ 'client_id' ];
$descriptionSql = mysql_real_escape_string (( string ) $src [ 'description' ]);
// Теги читаются из requisitions_activities (junction-таблица), а не из колонки activities.
$insSql = " INSERT INTO requisitions
( user_id , who_work , funnel_id , step_id , stage , name , type_id , source ,
priority , hot , client_id , object_id , description , created_at , confirm , deleted , cancel )
VALUES
({ $currentUserId }, { $whoWorkId }, { $funnelId }, { $newStepId }, 1 ,
'{$nameSql}' , { $srcTypeId }, { $sourceVal },
{ $priority }, { $hot }, { $clientId }, { $newObjectId }, '{$descriptionSql}' , NOW (), 1 , 0 , 0 ) " ;
if ( ! $this -> db -> query ( $insSql )) {
throw new Exception ( 'INSERT requisitions завершился ошибкой' );
}
$newId = ( int ) $this -> db -> insert_id ();
if ( $newId <= 0 ) {
throw new Exception ( 'INSERT requisitions не вернул id' );
}
// autosearch_filters — копируем для всех типов кроме «Подбор объекта» (base=1).
$srcAsfilterId = isset ( $src [ 'asfilter_id' ]) ? ( int ) $src [ 'asfilter_id' ] : 0 ;
if ( $copyFilters && $srcAsfilterId > 0 ) {
$qFilter = $this -> db -> query ( " SELECT * FROM autosearch_filters WHERE id = { $srcAsfilterId } LIMIT 1 " );
$filterRow = $this -> db -> fetch_assoc ( $qFilter );
if ( $filterRow ) {
unset ( $filterRow [ 'id' ]);
if ( array_key_exists ( 'deleted' , $filterRow )) $filterRow [ 'deleted' ] = 0 ;
if ( array_key_exists ( 'archived' , $filterRow )) $filterRow [ 'archived' ] = 0 ;
$filterRow [ 'req_id' ] = $newId ;
$filterRow [ 'created_at' ] = $now ;
$filterRow [ 'created_by' ] = $currentUserId ;
$filterRow [ 'updated_at' ] = $now ;
$filterRow [ 'updated_by' ] = $currentUserId ;
$cols = array ();
$vals = array ();
foreach ( $filterRow as $col => $val ) {
$cols [] = " ` { $col } ` " ;
if ( $col === 'created_at' || $col === 'updated_at' ) {
$vals [] = 'NOW()' ;
} elseif ( $val === null ) {
$vals [] = 'NULL' ;
} else {
$vals [] = " ' " . mysql_real_escape_string (( string ) $val ) . " ' " ;
}
}
$filterInsSql = " INSERT INTO autosearch_filters ( " . implode ( ',' , $cols ) . " ) "
. " VALUES ( " . implode ( ',' , $vals ) . " ) " ;
if ( ! $this -> db -> query ( $filterInsSql )) {
throw new Exception ( 'INSERT autosearch_filters завершился ошибкой' );
}
$newAsfilterId = ( int ) $this -> db -> insert_id ();
if ( $newAsfilterId <= 0 ) {
throw new Exception ( 'INSERT autosearch_filters не вернул id' );
}
if ( ! $this -> db -> query ( " UPDATE requisitions SET asfilter_id = { $newAsfilterId } WHERE id = { $newId } " )) {
throw new Exception ( 'UPDATE requisitions.asfilter_id завершился ошибкой' );
}
}
}
$qTags = $this -> db -> query ( " SELECT activity_id FROM requisitions_activities WHERE req_id = { $srcId } " );
while ( $tag = $this -> db -> fetch_assoc ( $qTags )) {
$aid = ( int ) $tag [ 'activity_id' ];
if ( ! $this -> db -> query ( " INSERT INTO requisitions_activities SET req_id = { $newId } , activity_id = { $aid } " )) {
throw new Exception ( 'INSERT requisitions_activities завершился ошибкой' );
}
}
// contracts_req: date_start/date_end — unix-timestamp (int), не DATETIME.
$hasSaleContract = false ;
$qContracts = $this -> db -> query ( " SELECT * FROM contracts_req WHERE req_id = { $srcId } " );
while ( $c = $this -> db -> fetch_assoc ( $qContracts )) {
$cType = ( int ) $c [ 'type' ];
$cNumber = mysql_real_escape_string (( string ) $c [ 'number' ]);
$cStart = ( int ) $c [ 'date_start' ];
$cEnd = ( int ) $c [ 'date_end' ];
$cDays = ( int ) $c [ 'days' ];
$cSend = ( int ) $c [ 'send' ];
$cAgency = ( int ) $c [ 'agency_id' ];
$contractInsSql = " INSERT INTO contracts_req
( req_id , type , number , date_start , date_end , days , send , agency_id )
VALUES
({ $newId }, { $cType }, '{$cNumber}' , { $cStart }, { $cEnd }, { $cDays }, { $cSend }, { $cAgency }) " ;
if ( ! $this -> db -> query ( $contractInsSql )) {
throw new Exception ( 'INSERT contracts_req завершился ошибкой' );
}
if ( $cType === 2 ) {
$hasSaleContract = true ;
}
}
// Cross-link contracts_object — только если есть договор type=2 (продажа).
if ( $copyObject && $newObjectId > 0 && $hasSaleContract ) {
$this -> contractInObject ( $newId , $newObjectId );
}
// copy_created: историческое событие в исходнике (без уведомления). dop_text = id новой заявки.
$sqlEvSrc = " INSERT INTO events_clients
( req_id , event , dop_text , user_id , from_id , date , send_telegramm , send_max , `read` )
VALUES
({ $srcId }, 'copy_created' , '{$newId}' , { $currentUserId }, 0 , NOW (), 1 , 1 , 1 ) " ;
if ( ! $this -> db -> query ( $sqlEvSrc )) {
throw new Exception ( 'INSERT events_clients (copy_created) завершился ошибкой' );
}
// copy_from: событие в копии. read=1 всегда — копия не передача, поллер не должен показывать модалку «Передача заявки».
// send_telegramm/send_max=0 при копировании на другого сотрудника — cron отдельно шлёт уведомление в TG/MAX.
$skipTgMax = ( $whoWorkId === $currentUserId ) ? 1 : 0 ;
$sqlEvNew = " INSERT INTO events_clients
( req_id , event , dop_text , user_id , from_id , date , send_telegramm , send_max , `read` )
VALUES
({ $newId }, 'copy_from' , '{$srcId}' , { $currentUserId }, { $whoWorkId }, NOW (), { $skipTgMax }, { $skipTgMax }, 1 ) " ;
if ( ! $this -> db -> query ( $sqlEvNew )) {
throw new Exception ( 'INSERT events_clients (copy_from) завершился ошибкой' );
}
$this -> db -> commit ();
return array (
'success' => true ,
'id' => $newId ,
'error' => null ,
'code' => null ,
);
} catch ( Exception $e ) {
// inTransaction() — защита от двойного rollback (DDL-ошибки откатывают сами).
if ( $this -> db -> inTransaction ()) {
$this -> db -> rollBack ();
}
return array (
'success' => false ,
'error' => 'Ошибка при создании копии: ' . $e -> getMessage (),
'code' => 'exception' ,
'id' => null ,
);
}
}
// Право на редактирование/копирование заявки. Без $_SESSION (для cron). TODO: унифицировать с дубликатами в этом классе.
public function user_can_edit_req ( $srcRow , $userId ) {
$userId = ( int ) $userId ;
if ( $userId <= 0 ) {
return false ;
}
if ( isset ( $srcRow [ 'who_work' ]) && ( int ) $srcRow [ 'who_work' ] === $userId ) {
return true ;
}
$sql = " SELECT u.`agency`, u.`users_admin`, p.`menu_all_submissions_edit`
FROM `users` u
LEFT JOIN `user_permissions` p ON p . `user_id` = u . `id`
WHERE u . `id` = { $userId }
LIMIT 1 " ;
$result = mysql_query ( $sql );
if ( ! $result ) {
return false ;
}
$u = mysql_fetch_assoc ( $result );
if ( ! $u ) {
return false ;
}
if (( int ) $u [ 'agency' ] === 1
|| ( int ) $u [ 'users_admin' ] === 1
|| ( int ) $u [ 'menu_all_submissions_edit' ] === 1 ) {
return true ;
}
// doers (соисполнители): doers_confirm=0 И userId — ключ в JSON с о значением 1.
$doersConfirm = isset ( $srcRow [ 'doers_confirm' ]) ? ( int ) $srcRow [ 'doers_confirm' ] : 0 ;
$doersRaw = isset ( $srcRow [ 'doers' ]) ? $srcRow [ 'doers' ] : '' ;
if ( $doersConfirm === 0 && $doersRaw !== '' ) {
$doers = json_decode ( html_entity_decode (( string ) $doersRaw ), true );
if ( is_array ( $doers ) && isset ( $doers [ $userId ]) && ( int ) $doers [ $userId ] === 1 ) {
return true ;
}
}
// admin_department / manager_office своего отдела (по users.department_id ответственного).
$whoWorkId = isset ( $srcRow [ 'who_work' ]) ? ( int ) $srcRow [ 'who_work' ] : 0 ;
if ( $whoWorkId <= 0 ) {
return false ;
}
$depHelper = new Department ();
$callerDep = $depHelper -> getDepartment ( $userId );
if ( ! is_array ( $callerDep ) || ! isset ( $callerDep [ 'role' ])) {
return false ;
}
$callerRole = $callerDep [ 'role' ];
if ( $callerRole === 'admin_department' || $callerRole === 'manager_office' ) {
$q = mysql_query (
" SELECT u_caller.`department_id` AS caller_dep,
u_responsible . `department_id` AS resp_dep
FROM `users` u_caller
LEFT JOIN `users` u_responsible ON u_responsible . `id` = { $whoWorkId }
WHERE u_caller . `id` = { $userId }
LIMIT 1 "
);
$deps = $q ? mysql_fetch_assoc ( $q ) : null ;
if ( ! $deps ) {
return false ;
}
$callerDepId = ( int ) $deps [ 'caller_dep' ];
$respDepId = ( int ) $deps [ 'resp_dep' ];
if ( $callerDepId > 0 && $callerDepId === $respDepId ) {
return true ;
}
return false ;
}
// manager / manager_office_menager в цепочке id_manager ответственного.
if ( $callerRole === 'manager' || $callerRole === 'manager_office_menager' ) {
$qm = mysql_query (
" SELECT u_caller.`id_manager` AS caller_mgr,
u_responsible . `id_manager` AS resp_mgr
FROM `users` u_caller
LEFT JOIN `users` u_responsible ON u_responsible . `id` = { $whoWorkId }
WHERE u_caller . `id` = { $userId }
LIMIT 1 "
);
$mgrs = $qm ? mysql_fetch_assoc ( $qm ) : null ;
if ( ! $mgrs ) {
return false ;
}
$callerMgr = ( int ) $mgrs [ 'caller_mgr' ];
$respMgr = ( int ) $mgrs [ 'resp_mgr' ];
if ( $respMgr > 0 && $respMgr === $userId ) {
return true ;
}
if ( $callerMgr > 0 && $callerMgr === $respMgr ) {
return true ;
}
if ( $callerMgr > 0 && $callerMgr === $whoWorkId ) {
return true ;
}
}
return false ;
}
// Может ли $userId быть ответственным: agency-tree + blocked=0 + Н Е в funnel.users_no_see.
public function user_can_be_responsible ( $userId , $agencyId , $funnelId ) {
$userId = ( int ) $userId ;
$agencyId = ( int ) $agencyId ;
$funnelId = ( int ) $funnelId ;
if ( $userId <= 0 || $agencyId <= 0 || $funnelId <= 0 ) {
return false ;
}
if (( int ) User :: getUserAgencyID ( $userId ) !== $agencyId ) {
return false ;
}
$blockedQ = mysql_query ( " SELECT `blocked` FROM `users` WHERE `id` = { $userId } LIMIT 1 " );
$blockedRow = mysql_fetch_assoc ( $blockedQ );
if ( ! $blockedRow || ( int ) $blockedRow [ 'blocked' ] === 1 ) {
return false ;
}
$sql = " SELECT `users_no_see` FROM `funnel` WHERE `id` = { $funnelId } LIMIT 1 " ;
$result = mysql_query ( $sql );
if ( ! $result ) {
return false ;
}
$funnelRow = mysql_fetch_assoc ( $result );
if ( ! $funnelRow ) {
return false ;
}
if ( ! empty ( $funnelRow [ 'users_no_see' ])) {
$hidden = json_decode ( $funnelRow [ 'users_no_see' ], true );
if ( is_array ( $hidden )) {
$hiddenInt = array_map ( 'intval' , $hidden );
if ( in_array ( $userId , $hiddenInt , true )) {
return false ;
}
}
}
return true ;
}
2026-05-22 20:21:54 +02:00
//Изменение воронки
public function updateFunnel ( $funnel_id , $req_id ) {
$errors = [];
$sqlSelFun = " select funnel_id from requisitions WHERE id= $req_id " ;
$resSelFun = $this -> db -> query ( $sqlSelFun );
$rowSelFun = $this -> db -> fetch_assoc ( $resSelFun );
$funnel = $rowSelFun [ 'funnel_id' ];
$newFunnel = ( int ) $funnel_id ;
if ( $funnel != $newFunnel ) {
$funnelName = " Обычные " ;
if ( $newFunnel > 0 ) {
$sqlFunnel = " SELECT name FROM funnel WHERE id = $newFunnel " ;
$resFunnel = $this -> db -> query ( $sqlFunnel );
$phRow = $this -> db -> fetch_assoc ( $resFunnel );
$funnelName = $phRow [ 'name' ];
}
$sql = " UPDATE requisitions SET funnel_id = ' $newFunnel ', `stage`='1' WHERE id= $req_id " ;
if ( ! $this -> db -> query ( $sql )) {
if ( $this -> db -> errorInfo ())
$errors [] = $this -> db -> errorInfo ();
}
$sqlDeleteOldFunnel = " delete from clients_funnel_step where req_id = $req_id " ;
if ( ! $this -> db -> query ( $sqlDeleteOldFunnel )) {
if ( $this -> db -> errorInfo ())
$errors [] = $this -> db -> errorInfo ();
}
$this -> get_class_etap ( $req_id , $newFunnel );
$sql_conf = " INSERT INTO `events_clients` (`user_id`, `req_id`, `from_id`, `event`, `dop_text`, `read`) VALUES ( " . $_SESSION [ 'id' ] . " , " . $req_id . " , '0', 'update', 'Передан в воронку « " . $funnelName . " »', '1') " ;
if ( ! $this -> db -> query ( $sql_conf )) {
if ( $this -> db -> errorInfo ())
$errors [] = $this -> db -> errorInfo ();
}
}
if ( count ( $errors ))
return $errors ;
else
return true ;
}
//
public function updateReq ( $req_id = [], $client_id = null , $object_id = null ) {
$errors = [];
if ( ! empty ( $req_id )) {
if ( ! is_array ( $req_id ))
$req_id = [ $req_id ];
if ( is_null ( $client_id ))
$client_id = 'NULL' ;
if ( is_null ( $object_id ))
$object_id = 'NULL' ;
/* $property_type_id = 0 ;
if ( $params [ 'object_id' ] > 0 ){
$property_type_id = $this -> check_property_type ( $params [ 'object_id' ]);
} */
foreach ( $req_id as $req ) {
$sql = " UPDATE `requisitions` SET
`object_id` = '$object_id' ,
`client_id` = '$client_id'
WHERE `id` = '$req' " ;
if ( ! $this -> db -> query ( $sql )) {
$errors [] = $this -> db -> errorInfo ();
}
}
}
if ( count ( $errors ))
return [
'success' => false ,
'errors' => $errors ,
];
else
return [
'success' => true
];
}
//Закрытие заявки
public function deleteReq ( $id , $user_id , $post ){
$errors = [];
$dop_text = " " ;
$select_text = " " ;
$is_deal = false ;
if ( $post [ 'note' ] == 1 ){
// При закрытии отказом (denial) JS передаёт текущую дату в $post['datazakl'],
// парсить её не нужно — используем текущее время напрямую.
$t = date_create ();
$formatted_date = date_format ( $t , " Y-m-d H:i:s " );
$formatted_dateZajavki = date_format ( $t , " d.m.Y " );
} else {
$test = substr ( $post [ 'datazakl' ], 0 , - 3 );
$dateZajavki = date ( 'd.m.Y' , intval ( $test ));
if ( $dateZajavki == '01.01.1970' ){
$dateZajavki = date ( 'd.m.Y' );
}
$phpdate = strtotime ( $dateZajavki );
$formatted_d = date ( 'Y-m-d' , $phpdate );
$today = date ( 'Y-m-d' );
if ( $today == $formatted_d ){
$formatted_date = date ( 'Y-m-d H:i:s' );
} else {
$formatted_date = date ( 'Y-m-d H:i:s' , $phpdate );
}
$formatted_dateZajavki = date ( 'd.m.Y' , $phpdate );
}
if ( $post [ 'denial' ]){
$sql_d = " SELECT * FROM denial_work WHERE id = " . $post [ 'denial' ];
$q_d = $this -> db -> query ( $sql_d );
$r_d = $this -> db -> fetch_assoc ( $q_d );
$select_text = $r_d [ 'name' ];
}
if ( $post [ 'tempid' ]){
$sql_mes = " SELECT * FROM step_notify_closure WHERE temp_id = { $post [ 'tempid' ] } " ;
$q_mes = $this -> db -> query ( $sql_mes );
if ( $this -> db -> num_rows ( $q_mes ) > 0 ){
$mes = $this -> db -> fetch_assoc ( $q_mes );
}
}
if ( ! empty ( $post [ 'reason' ]) || $select_text != " " ){
$dop_text .= " Причина: « " . $select_text . " .» Комментарий: « " . $post [ 'reason' ] . " » " ;
if ( isset ( $mes )){
$text = $mes [ 'text' ] . " <br>Закрыта. " . $dop_text ;
if ( ! $this -> db -> query ( " UPDATE step_notify_closure SET text=' { $text } ', send=0 WHERE temp_id = { $post [ 'tempid' ] } " ))
$errors [] = $this -> db -> errorInfo ();
}
} else if ( isset ( $post [ 'summa' ]) && $post [ 'luck' ]){
$is_deal = true ;
$dop_text .= " $post[reason] Совершена сделка на " . $post [ 'summa' ] . " р у б . " . $formatted_dateZajavki ;
if ( isset ( $mes )){
$text = $mes [ 'text' ] . " <br>Закрыта. Совершена сделка на " . $post [ 'summa' ] . " р у б . " . $formatted_dateZajavki ;
if ( ! $this -> db -> query ( " UPDATE step_notify_closure SET text=' { $text } ', send=0 WHERE temp_id = { $post [ 'tempid' ] } " ))
$errors [] = $this -> db -> errorInfo ();
}
}
$sql = " SELECT * FROM `requisitions` WHERE id = $id " ;
$requisistion = $this -> db -> fetch_assoc ( $this -> db -> query ( $sql ));
if ( $requisistion [ 'complex_status_id' ] && $requisistion [ 'complex_room_id' ])
{
$complexStatus = new ComplexStatus (( int ) $requisistion [ 'complex_status_id' ]);
$complexStatus -> updateRoomsStatus ([
'new_status_id' => 4 ,
'complex_room_id' => $requisistion [ 'complex_room_id' ]
], false , false );
}
$sql = " UPDATE requisitions SET reason=' " . $select_text . " . " . $post [ 'reason' ] . " ', who_delete = ' $user_id ', deleted=1, stage=8, denial = $post[denial] WHERE id= $id " ;
if ( isset ( $post [ 'summa' ]) && $post [ 'luck' ]){
if ( $dop_text != '' ) $dop_text .= " " ;
$dop_text1 .= " Совершена сделка на " . $post [ 'summa' ] . " р у б . " . $formatted_dateZajavki ;
$sql = " UPDATE requisitions SET reason=' $post[reason] ', who_delete = ' $user_id ', deleted=1, summa=' $post[summa] ', confirm=' $post[luck] ' WHERE id= $id " ;
}
if ( $this -> db -> query ( $sql )) {
$sql = " INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`, `dop_text`, `date_update`) VALUES (' " . $user_id . " ', ' " . $id . " ', ' " . $user_id . " ', 'delete', '1', ' " . $dop_text1 . " ', ' " . $formatted_date . " ') " ;
if ( ! $this -> db -> query ( $sql ))
$errors [] = $this -> db -> errorInfo ();
2026-06-21 10:40:06 +02:00
// Обновление статуса сделки при закрытии заявки
if ( ! empty ( $requisistion [ 'deal_id' ]) && $requisistion [ 'deal_id' ] > 0 ) {
$dealId = intval ( $requisistion [ 'deal_id' ]);
// Проверяем, есть ли другие заявки в сделке, которые ещё не закрыты
$otherReqsSql = " SELECT COUNT(*) as cnt FROM requisitions WHERE deal_id = $dealId AND deleted = 0 AND id != $id " ;
$otherReqsRow = $this -> db -> fetch_assoc ( $this -> db -> query ( $otherReqsSql ));
$otherReqsOpen = $otherReqsRow [ 'cnt' ] > 0 ;
if ( $is_deal || ! $otherReqsOpen ) {
// Если сделка (is_deal=true) ИЛИ все заявки закрыты — ставим статус 1 (успешная)
$this -> db -> query ( " UPDATE deals SET status = 1 WHERE id = $dealId AND status != 2 " );
// Запись в историю сделки
$userObj = new User ;
$userObj -> get ( $user_id );
$comment = " Заявка # $id закрыта. " ;
if ( $is_deal && isset ( $post [ 'summa' ])) {
$comment .= " Совершена сделка на " . $post [ 'summa' ] . " р у б . " ;
}
if ( ! $otherReqsOpen ) {
$comment .= " В с е заявки сделки закрыты. Сделка завершена. " ;
}
$this -> db -> query ( " INSERT INTO user_client_events (user_id, req_id, type, name, comment, create_date) VALUES ( $user_id , $id , 'deal', 'Закрытие сделки', ' " . addslashes ( $comment ) . " ', NOW()) " );
}
}
2026-05-22 20:21:54 +02:00
// Удаление фильтра автопоиска
$autosearch_instce = $this -> autosearch_instce ;
$autosearch_instce -> deleteFilterByReq ( $id , $user_id );
$user = new User ;
$user -> get ( $user_id );
if ( $user -> agencyId == 13154 ){
$w = new WebHookSend ( $user -> agencyId , 3 , $id , 'req' , $this -> db , 'close' );
}
if ( $is_deal === false ){
$reqs = array ( $id );
$this -> set_user ( $user );
$this -> autoUnitReq ( - 1 , $reqs );
}
} else {
$errors [] = $this -> db -> errorInfo ();
}
if ( $requisistion [ 'complex_room_id' ])
{
$complex = new Complex ();
$complex -> generate_room_reservations_positions ( $requisistion [ 'complex_room_id' ]);
}
if ( ! empty ( $errors ))
return $errors ;
return true ;
}
//Удаление заявки
public function cancelReq ( $req_id ){
$sql = " UPDATE requisitions SET cancel=1 WHERE id= $req_id " ;
if ( $this -> db -> query ( $sql )) {
// Удаление фильтра автопоиска
$autosearch_instce = $this -> autosearch_instce ;
$autosearch_instce -> deleteFilterByReq ( $req_id , $_SESSION [ 'id' ]);
} else {
return $this -> db -> errorInfo ();
}
return true ;
}
//Удаление заявок по клиенту
public function cancelReqsClient ( $client_id ){
$sql = " SELECT id FROM requisitions WHERE client_id = $client_id " ;
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q )){
$this -> cancelReq ( $r [ 'id' ]);
}
}
//Восстановление заявки
public function renewReq ( $req_id , $user_id ){
$sql = " UPDATE requisitions SET deleted=0, reason='', confirm = 1, who_delete=NULL WHERE id= $req_id " ;
if ( ! $this -> db -> query ( $sql )) {
return $this -> db -> errorInfo ();
}
$dop_text = " Восстановлен из закрытых. " ;
$sql = " INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`, `dop_text`) VALUES (' " . $user_id . " ', ' " . $req_id . " ', ' " . $user_id . " ', 'restored', '1', ' " . $dop_text . " ') " ;
if ( ! $this -> db -> query ( $sql )) {
return $this -> db -> errorInfo ();
}
return true ;
}
//Принятие заявки из закрытых
public function takeFromClosedReq ( $req_id , $user_id ){
$sql_check_permissions = " SELECT `daily_closed_req_limit`, `actual_daily_closed_req` 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 );
$daily_closed_req_left = $r_check_permissions [ 'daily_closed_req_limit' ] - $r_check_permissions [ 'actual_daily_closed_req' ];
if ( $daily_closed_req_left <= 0 ) {
exit ;
}
$sql = " UPDATE requisitions SET deleted=0, reason='', confirm = 1, who_work= $user_id , who_delete=NULL WHERE id= $req_id " ;
if ( ! $this -> db -> query ( $sql )) {
return $this -> db -> errorInfo ();
}
$sql_2 = " INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`) VALUES (' " . $user_id . " ', ' " . $req_id . " ', ' " . $user_id . " ', 'taken_from_closed', '1') " ;
if ( ! $this -> db -> query ( $sql_2 )) {
return $this -> db -> errorInfo ();
}
$sql_3 = " UPDATE user_permissions SET actual_daily_closed_req=actual_daily_closed_req + 1 WHERE user_id = $user_id " ;
if ( ! $this -> db -> query ( $sql_3 )) {
return $this -> db -> errorInfo ();
}
return true ;
}
//Установка воронки
public function set_funnel ( $funnel_id ){
$this -> funnel_id = $funnel_id ;
}
//этапы воронки
public function get_etap_funnel ( $funnelId ) {
$res = array ();
if ( $funnelId == 0 ){
$steps = $this -> steps ;
$res = $steps ;
} else {
$funnel_sql = " SELECT * FROM funnel_steps WHERE funnel_id = " . $funnelId . " and deleted=0 order by order_number, branch " ;
$funnel_step = $this -> db -> query ( $funnel_sql );
while ( $step = $this -> db -> fetch_assoc ( $funnel_step )) {
$steps [ 'step_' . $step [ 'id' ]] = $step ;
}
$res = $steps ;
}
return $res ;
}
//Определение воронки
public function get_class_etap ( $reqId , $funnelId , $stageId = 0 ) {
$res = array ( 'bar' => array ());
$res [ 'req_id' ] = $reqId ;
if ( $funnelId == 0 ){
$steps = $this -> steps ;
$stage = " Новый " ;
foreach ( $steps as $step ){
if ( $step [ 'id' ] == $stageId ){
$stage = $step [ 'name' ];
}
}
$res [ 'bar' ] = $steps ;
$res [ 'stage' ] = $stage ;
$res [ 'stageId' ] = $stageId ;
return $res ;
} else {
$change_step_query = $this -> db -> query ( " SELECT * FROM clients_funnel_step WHERE req_id = " . $reqId );
$next_id = 0 ;
$change_step = array ( 'step_id' => 0 );
//$lostDate = $client['date_create'];
if ( $this -> db -> num_rows ( $change_step_query ) > 0 ) {
$change_step = $this -> db -> fetch_assoc ( $change_step_query );
$next_id = $change_step [ 'next_id' ];
$lostDate = $change_step [ 'date_update' ];
} else {
$sql_req = " SELECT created_at FROM requisitions WHERE id = $reqId " ;
$q_req = $this -> db -> query ( $sql_req );
$r_req = $this -> db -> fetch_assoc ( $q_req );
$lostDate = $r_req [ 'created_at' ];
}
$next_steps = array ();
$funnel_sql = " SELECT * FROM funnel_steps WHERE funnel_id = " . $funnelId . " and deleted=0 order by order_number, branch " ;
$funnel_step = $this -> db -> query ( $funnel_sql );
$isActive = true ;
$classF = ' active' ;
$stage = '' ;
$stageId = 0 ;
if (( int ) $change_step [ 'step_id' ] == 0 ) {
$isActive = false ;
}
$arr_steps = array ();
$countStep = $this -> db -> num_rows ( $funnel_step );
while ( $step = $this -> db -> fetch_assoc ( $funnel_step )) {
$step [ 'isActive' ] = ( int ) $isActive ;
$step [ 'nextStep' ] = false ;
if ( $step [ 'main' ] == 1 && ! $isActive ) {
$next_steps [] = $step [ 'id' ];
}
if ( $step [ 'id' ] == ( int ) $change_step [ 'step_id' ]) {
//$stage = $step['name'];
$next_steps = json_decode ( htmlspecialchars_decode ( $step [ 'next_step' ]));
if ( $next_id == 0 ) {
//$stage = $step['name'];
//$next_steps = json_decode( htmlspecialchars_decode($step['next_step']));
//if($step['branch'] < $branch){
$isActive = false ;
// }
}
} else if ( $step [ 'id' ] == ( int ) $next_id ) {
$isActive = false ;
}
$arr_steps [ $step [ 'id' ]] = $step ;
}
if ( $next_id != 0 && ! empty ( $next_steps )) {
foreach ( $next_steps as $key => $st ) {
if ( $st != $next_id ) {
unset ( $next_steps [ $key ]);
}
}
}
foreach ( $arr_steps as $idstep => $step ) {
$arr_steps [ $idstep ][ 'isNext' ] = 0 ;
if ( in_array ( $idstep , $next_steps )) {
$stage = $step [ 'name' ];
$stageId = $step [ 'id' ];
$arr_steps [ $idstep ][ 'isNext' ] = 1 ;
}
}
$isActive = true ;
foreach ( $arr_steps as $idstep => $step ) {
$classF = '' ;
if ( $isActive ) $classF = ' active' ;
if ( $step [ 'isNext' ] == 1 ) {
$classF = ' nextStep' ;
$isActive = false ;
}
// Покажет сколько мне дней
if ( ! isset ( $lostDate )) $lostDate = date ( 'd.m.Y H:i:s' );
$interval = date_diff ( new DateTime (), new DateTime ( $lostDate )) -> days ;
if ( $interval >= $step [ 'days_step' ]) {
$classF .= ' expired' ;
}
$step [ 'classF' ] = $classF ;
$res [ 'bar' ][] = $step ;
$res [ 'stage' ] = $stage ;
$res [ 'stageId' ] = $stageId ;
}
if ( $stageId == 0 ) $stageId = - 1 ;
$sql = " UPDATE requisitions SET step_id = { $stageId } WHERE id = { $reqId } " ;
$this -> db -> query ( $sql );
$sqld = " SELECT deleted FROM requisitions WHERE id = { $reqId } " ;
$qd = $this -> db -> query ( $sqld );
$rd = $this -> db -> fetch_assoc ( $qd );
$res [ 'req_deleted' ] = $rd [ 'deleted' ];
$res [ 'sql' ] = $sqld ;
return $res ;
}
}
public function prev_step_event ( $reqId , $stepId , $is_open_step = false ){
/* error_reporting ( E_ALL | E_STRICT );
ini_set ( 'display_errors' , 1 ); */
$db_sphinx = new MysqlPdo ( hstsph2 , null , null , null , true , '9306' );
$sql = " SELECT * FROM funnel_steps WHERE id = $stepId " ;
// echo $sql."\n";
$q = $this -> db -> query ( $sql );
$r = $this -> db -> fetch_assoc ( $q );
$sql_req = " SELECT *, (SELECT heir FROM requisitions_type WHERE id = req.type_id) as heir FROM requisitions as req WHERE id= $reqId " ;
$q_req = $this -> db -> query ( $sql_req );
$req = $this -> db -> fetch_assoc ( $q_req );
if ( ! empty ( $r [ 'pole_prev' ])){
if ( strpos ( $r [ 'pole_prev' ], '{"' ) !== false ){
$pole_prev = json_decode ( htmlspecialchars_decode ( $r [ 'pole_prev' ]));
} else {
$pole_prev = json_decode ( $r [ 'pole_prev' ]);
}
foreach ( $pole_prev as $pole => $value_pole ){
switch ( $pole ){
case 'tasks' : {
if ( ! $is_open_step ){
$name = '' ;
if ( $req [ 'who_work' ] > 0 ){
foreach ( $value_pole as $vp ){
if ( ! empty ( $vp -> type )){
$set = " SET req_id = { $reqId } " ;
if ( ! empty ( $vp -> name )){
$name = $vp -> name ;
} else if ( $vp -> type == 'even' ){
$name = " Мероприятие " ;
}
$date_time = date ( 'Y-m-d H:i:s' );
if ( ! empty ( $vp -> time )){
$date_time = date ( 'Y-m-d H:i:s' , strtotime ( $vp -> time ));
}
$set .= " , user_id = { $req [ 'who_work' ] } , type = ' { $vp -> type } ', comment=' { $vp -> comment } ', schedule_date = ' { $date_time } ', from_id = { $req [ 'who_work' ] } , open_step=1 " ;
if ( ! empty ( $name )){
$set .= " , name=' { $name } ' " ;
}
$insert_ev = " INSERT INTO user_client_events { $set } " ;
// echo $insert_ev;
$this -> db -> query ( $insert_ev );
}
}
}
}
break ;
}
case 'tasks_all' : {
if ( ! $is_open_step ){
$name = '' ;
if ( $req [ 'who_work' ] > 0 ){
foreach ( $value_pole as $vp ){
if ( ! empty ( $vp -> type )){
$set = " SET req_id = { $reqId } " ;
if ( ! empty ( $vp -> name )){
$name = $vp -> name ;
} else if ( $vp -> type == 'even' ){
$name = " Мероприятие " ;
}
$date_time = date ( 'Y-m-d H:i:s' );
if ( ! empty ( $vp -> time )){
$date_time = date ( 'Y-m-d H:i:s' , strtotime ( $vp -> time ));
}
$set .= " , user_id = { $req [ 'who_work' ] } , type = ' { $vp -> type } ', comment=' { $vp -> comment } ', schedule_date = ' { $date_time } ', from_id = { $req [ 'who_work' ] } , open_step=1 " ;
if ( ! empty ( $name )){
$set .= " , name=' { $name } ' " ;
}
$insert_ev = " INSERT INTO user_client_events { $set } " ;
// echo $insert_ev;
$this -> db -> query ( $insert_ev );
}
}
}
}
break ;
}
case 'comment' : {
if ( ! $is_open_step ){
if ( ! empty ( $value_pole )){
// $set .= ", user_id = {$req['who_work']}, type = '{$vp->type}', comment='{$vp->comment}', schedule_date = '{$date_time}', from_id = {$req['who_work']}, open_step=1";
$insert_ev = " INSERT INTO user_client_events SET req_id = { $reqId } , user_id = { $req [ 'who_work' ] } , type = 'comment', comment=' { $value_pole } ', from_id = { $req [ 'who_work' ] } , open_step=1 " ;
//echo $insert_ev;
$this -> db -> query ( $insert_ev );
}
}
break ;
}
case 'new_who_work' : {
//Добавляем событие передачи
if ( ! $is_open_step ){
if ( $pole_prev -> is_new_who_work != 0 && ! empty ( $value_pole ) && ( int ) $value_pole != 0 ){
$confirm = 0 ;
if ( $req [ 'who_work' ] == $value_pole ) {
$confirm = 1 ;
}
if ( $confirm == 0 ) {
$sql_req_up = " UPDATE requisitions SET who_work= { $value_pole } , confirm=0 WHERE id = { $reqId } " ;
$this -> db -> query ( $sql_req_up );
$sql_conf = " INSERT INTO `events_clients` (`user_id`, `req_id`, `from_id`, `dop_text`, `event`) VALUES ( { $req [ 'who_work' ] } , { $reqId } , { $value_pole } , '(автоматическая передача при переходе на этап)', 'transmitted') " ;
// var_dump(($pole_prev));
$this -> db -> query ( $sql_conf );
if ( $pole_prev -> is_new_who_work_object > 0 && $req [ 'object_id' ] > 0 ){
if ( $req [ 'type_id' ] == 2 || $req [ 'heir' ] == 2 ){
$sqlUser = " SELECT `first_name`, `last_name`, `middle_name`, `phone` FROM `users` where id= " . $value_pole ;
$qUser = $this -> db -> query ( $sqlUser );
$rUser = $this -> db -> fetch_assoc ( $qUser );
$sobstv = trim ( $rUser [ 'last_name' ] . ' ' . $rUser [ 'first_name' ] . ' ' . $rUser [ 'middle_name' ]);
if ( $_SESSION [ 'agency' ]) {
$sobstv = $sobstv . " , агентство " . $rUser [ 'agency_name' ];
} else {
$agency = new User ;
$agency -> get ( $value_pole );
if ( isset ( $agency -> agencyName )) {
$sobstv = trim ( $rUser [ 'last_name' ] . ' ' . $rUser [ 'first_name' ] . ' ' . $rUser [ 'middle_name' ]) . " , агентство " . $agency -> agencyName ;
} else {
$sobstv = trim ( $rUser [ 'last_name' ] . ' ' . $rUser [ 'first_name' ] . ' ' . $rUser [ 'middle_name' ]);
}
}
//Передача объекта
$sql_up = " UPDATE objects SET id_add_user = ' " . $value_pole . " ', phone=' " . $rUser [ 'phone' ] . " ', sobstv=' " . $sobstv . " ' WHERE id = " . $req [ 'object_id' ];
//echo $sql_up;
$this -> db -> query ( $sql_up );
$sql_sph = " UPDATE objects SET id_add_user = { $value_pole } WHERE id = " . $req [ 'object_id' ];
$db_sphinx -> query ( $sql_sph );
}
}
}
}
}
break ;
}
case 'new_doers' : {
if ( ! $is_open_step )
{
if ( $pole_prev -> is_new_doers > 0 ){
if ( ! empty ( $value_pole )){
$doers = array ();
$doers_confirm = $req [ 'doers_confirm' ];
//$doer_clients = $req['doer_clients'];
if ( ! empty ( $req [ 'doers' ])){
$doers = json_decode ( htmlspecialchars_decode ( $req [ 'doers' ]), true );
}
foreach ( $value_pole as $doer_id ){
if ( ! isset ( $doers [ $doer_id ]) && $doer_id != $req [ 'who_work' ]){
$doers_confirm = 0 ;
$doers [ $doer_id ] = 0 ;
$sql_conf = " INSERT INTO `events_clients` (`user_id`, `req_id`, `from_id`, `dop_text`, `event`) VALUES ( { $req [ 'who_work' ] } , { $reqId } , { $doer_id } , '(автоматически при переходе на этап)','transmitted_parallel') " ;
$this -> db -> query ( $sql_conf );
}
}
if ( ! empty ( $doers )){
$sql_up_doer = " UPDATE requisitions SET doers_confirm = { $doers_confirm } , doers = ' " . clearInputElement ( json_encode ( $doers )) . " ' WHERE id = " . $reqId ;
$this -> db -> query ( $sql_up_doer );
}
}
}
}
break ;
}
case 'files_attach' : {
if ( ! $is_open_step ){
if ( ! empty ( $value_pole )){
// var_dump($value_pole);
foreach ( $value_pole as $vp ){
$sql_file = " SELECT * FROM files_steps_funnel_prev WHERE id = { $vp -> id } " ;
$q_file = $this -> db -> query ( $sql_file );
while ( $r_file = $this -> db -> fetch_assoc ( $q_file )){
$patch_new = $_SERVER [ 'DOCUMENT_ROOT' ] . " /upload/reqs/ " . $reqId ;
//echo $patch_new;
if ( ! file_exists ( $patch_new )){
mkdir ( $patch_new , 0777 );
}
$patch = $_SERVER [ 'DOCUMENT_ROOT' ] . " /upload/funnels/prev_steps/ " . $r_file [ 'funnel_id' ];
$name = $r_file [ 'guid' ] . '.' . $r_file [ 'type' ];
// Источник может быть только в Селектеле — локальную копию удаляет
// cron clearFunnelPrevStepFilesExistsInSelectel.php после заливки в облако.
$source_local = $patch . " / " . $name ;
$source_cdn = " https://uf.joywork.ru/upload/funnels/prev_steps/ " . $r_file [ 'funnel_id' ] . " / " . $name ;
$source_content = false ;
if ( file_exists ( $source_local )) {
$source_content = @ file_get_contents ( $source_local );
} else {
// Один HTTP-запрос вместо HEAD+GET. При 404/timeout — false.
$ctx = stream_context_create ([ 'http' => [ 'timeout' => 15 ]]);
$source_content = @ file_get_contents ( $source_cdn , false , $ctx );
if ( $source_content === '' ) {
$source_content = false ;
}
}
if ( $source_content !== false ) {
$name_new = md5 ( time () . $name );
@ file_put_contents ( $patch_new . " / " . $name_new . " . " . $r_file [ 'type' ], $source_content );
$sql_event_file = " INSERT INTO user_client_events SET req_id = { $reqId } , user_id = { $req [ 'who_work' ] } , type = 'file', comment = ' { $vp -> comment } ', from_id = { $req [ 'who_work' ] } , open_step=1 " ;
$this -> db -> query ( $sql_event_file );
$event_id = $this -> db -> insert_id ();
$sql_in_file = " INSERT INTO clients_files (guid, req_id, type, name, event_id)
VALUES ( '{$name_new}' , '{$reqId}' , '{$r_file[' type ']}' , '{$r_file[' name ']}' , '{$event_id}' ) " ;
$this -> db -> query ( $sql_in_file );
$client_file_id = $this -> db -> insert_id ();
if ( ! empty ( $vp -> name )){
$sql = " INSERT INTO names_client_files SET name = ' { $vp -> name } ' " ;
$this -> db -> query ( $sql );
$id_name = $this -> db -> insert_id ();
$sql = " UPDATE `clients_files` SET `name_id` = { $id_name } WHERE `id` = { $client_file_id } " ;
$this -> db -> query ( $sql );
}
$type = $r_file [ 'type' ];
//отправляем файл в Селектел (токен получаем один раз на все файлы этапа)
if ( empty ( $token )) {
$token = SelectelApi :: getNewToken ();
}
$contType = " application/octet-stream " ;
if ( $type ) {
$type = strtolower ( $type );
}
if ( $type === " doc " ) {
$contType = " application/msword " ;
}
if ( $type === " docx " ) {
$contType = " application/vnd.openxmlformats-officedocument.wordprocessingml.document " ;
}
if ( $type === " xls " ) {
$contType = " application/vnd.ms-excel " ;
}
if ( $type === " xlsx " ) {
$contType = " application/vnd.openxmlformats-officedocument.spreadsheetml.sheet " ;
}
if ( $type === " pdf " ) {
$contType = " application/pdf " ;
}
if ( $type === " jpeg " || $type === " jpg " ) {
$contType = " image/jpeg " ;
}
if ( $type === " gif " ) {
$contType = " image/gif " ;
}
if ( $type === " png " ) {
$contType = " image/png " ;
}
if ( $type === " mp3 " ) {
$contType = " audio/mpeg " ;
}
if ( $type === " zip " ) {
$contType = " application/zip " ;
}
if ( $type === " rar " ) {
$contType = " application/vnd.rar " ;
}
$new_path = " /upload/reqs/ " . $reqId . " / " . $name_new . '.' . $type ;
$r = SelectelApi :: uploadUserFile ( $token , $patch_new . " / " . $name_new . " . " . $type , $new_path , $contType );
} else {
error_log ( " prev_step_event(req= { $reqId } ): files_attach source missing local= { $source_local } cdn= { $source_cdn } " );
}
}
}
}
}
// $sql = "INSERT INTO clients_files (guid, req_id, type, name, event_id) VALUES ('{$name}', '{$req_id}', '{$type}', '{$_FILES['file']['name']}', '{$_SESSION['event_id_temp']}')";
break ;
}
case 'list_users_select' : {
if ( $pole_prev -> is_mes > 0 ){
if ( ! empty ( $value_pole )){
$tempid = 0 ;
$users_mes = $value_pole ;
$userId = ( int ) $_SESSION [ 'id' ];
$who_work = 0 ;
$user1 = $this -> db -> fetch_assoc ( $this -> db -> query ( " SELECT * FROM users WHERE id = { $userId } " ));
$post = " Сотрудник " ;
if ( $user1 [ 'agency' ] == 1 ) {
$post = " Агенство " ;
} else if ( $user1 [ 'manager' ] == 1 ) {
$post = " Менеджер " ;
}
$text = " <b> " . $post . " " . trim ( $user1 [ 'last_name' ] . ' ' . $user1 [ 'first_name' ] . ' ' . $user1 [ 'middle_name' ]) . " </b><br>перевел(а ) заявку на этап « " . $r [ 'name' ] . " » " ;
if ( $is_open_step ){
$text .= " (этап открыт повторно) " ;
}
$who_work = $req [ 'who_work' ];
$text .= " <br><i>Заявка: </i> " . $req [ 'name' ] . " ID: " . $req [ 'id' ] . " <br> " ;
$client_req = $this -> db -> fetch_assoc ( $this -> db -> query ( " SELECT * FROM clients WHERE id = { $req [ 'client_id' ] } " ));
// hide_client_contacts: уведомление уходит who_work — маскируем по нему.
$cl_fio_notif = should_hide_contacts_for_user_id ( $who_work ) ? mask_fio_if_contains_phone ( $client_req [ 'fio' ]) : $client_req [ 'fio' ];
$cl_phone_notif = should_hide_contacts_for_user_id ( $who_work ) ? mask_client_phone ( $client_req [ 'phone' ]) : $client_req [ 'phone' ];
$text .= " <i>Клиент: </i> " . $cl_fio_notif . " тел. " . $cl_phone_notif ;
if ( $req [ 'object_id' ] > 0 ){
$obj = $this -> db -> fetch_assoc ( $this -> db -> query ( " SELECT id, adres, stoim, type, komnat FROM objects WHERE id = { $req [ 'object_id' ] } " ));
if ( $obj ){
switch ( $obj [ 'type' ]) {
case 1 :
if ( $obj [ 'komnat' ] == 1 && $obj [ 'studio_flag' ]) {
$type = " Квартира-студия " ;
} else {
$type = " $obj[komnat] -комнатная квартира " ;
}
break ;
case 2 :
$type = " Комната в $obj[komnat] -комнатной квартире " ;
break ;
case 3 :
$type = " $obj[komnat] -комнатный дом " ;
break ;
case 4 :
switch ( $obj [ 'type_category' ]){
case 1 :
$type = " Офис " ;
break ;
case 2 :
$type = " Склад " ;
break ;
case 3 :
$type = " Торговая площадь " ;
break ;
case 4 :
$type = " Производство " ;
break ;
case 5 :
$type = " Помещение свободного назначения " ;
break ;
case 6 :
$type = " Здание " ;
break ;
case 7 :
$type = " Гараж " ;
break ;
case 8 :
$type = " Готовый бизнес " ;
break ;
case 9 :
$type = " Коммерческая земля " ;
break ;
default : $type = " Помещение " ;
}
break ;
case 5 :
$type = " Часть дома " ;
break ;
case 6 :
$type = " Комплекс " ;
break ;
case 7 :
$type = " Участок " ;
break ;
default :
$type = " $obj[komnat] -комнатная квартира " ;
}
$text .= '<br><i>Объект:</i> ID:' . $obj [ 'id' ] . ' ' . $obj [ 'adres' ] . ', ' . $type . ' ' . $obj [ 'stoim' ];
}
}
if ( $req [ 'deleted' ] > 0 ){
$close = true ;
}
}
$text = htmlspecialchars ( $text );
$userMes = array ();
$send = 0 ;
if ( $close ){
$tempid = time ();
$send = 1 ;
}
// $user_id_mes = false;
foreach ( $users_mes as $key => $user_id_mes_ ) {
unset ( $user_id_mes );
if ( $users_mes [ $key ] === 'manager' ) {
$managerWhoWork = $this -> db -> fetch_assoc ( $this -> db -> query ( " SELECT * FROM users WHERE id = { $who_work } " ));
$user_id_mes = $managerWhoWork [ 'id_manager' ];
} else if ( $users_mes [ $key ] == 0 ){
$user_id_mes = $who_work ;
} else {
$user_id_mes = $user_id_mes_ ;
}
if ( ! in_array ( $user_id_mes , $userMes ) && $user_id_mes != $_SESSION [ 'id' ]){
$sqlMesIn = " INSERT INTO step_notify_closure SET user_id = { $user_id_mes } , from_id= { $userId } , step_id= { $stepId } , text=' { $text } ', send= { $send } , temp_id= { $tempid } " ;
$this -> db -> query ( $sqlMesIn );
$userMes [] = $user_id_mes ;
}
}
}
break ;
}
case 'adjacent_funnels' : {
if ( ! $is_open_step ){
if ( $pole_prev -> is_adjacent_funnels > 0 ){
if ( ! empty ( $value_pole )){
$adjacent_funnels = $value_pole ;
foreach ( $adjacent_funnels as $funnel ){
$sql_a_f = " SELECT id FROM adjacent_funnels WHERE funnel_id = { $funnel } AND req_id = { $reqId } " ;
$row_a_f = $this -> db -> num_rows ( $this -> db -> query ( $sql_a_f ));
if ( $row_a_f == 0 ){
$this -> db -> query ( " INSERT INTO adjacent_funnels (funnel_id, req_id, parent_funnel_id, parent_step_id) VALUES ( { $funnel } , { $reqId } , { $req [ 'funnel_id' ] } , { $req [ 'step_id' ] } ) " );
$comment = " Заявка переведена в смежную воронку " ;
$sql_funnel = " SELECT name FROM funnel WHERE id = { $funnel } " ;
$nameFunnel = " « " . $this -> db -> fetch_assoc ( $this -> db -> query ( $sql_funnel ))[ 'name' ] . " » " ;
$comment = $comment . ' ' . $nameFunnel ;
$sql_event_adj = " INSERT INTO user_client_events SET req_id = { $reqId } , user_id = { $req [ 'who_work' ] } , type = 'comment', comment = ' { $comment } ', from_id = { $req [ 'who_work' ] } , open_step=1 " ;
$this -> db -> query ( $sql_event_adj );
}
}
}
}
}
break ;
}
}
}
}
}
//Синхронизация с объктом для Реализации объекта
public function contractInObject ( $req_id , $object_id , $id_contract_obj = 0 ){
/* error_reporting ( E_ALL | E_STRICT );
ini_set ( 'display_errors' , 1 ); */
$objectId = ( int ) $object_id ;
if ( $objectId > 0 ){
$sql = " SELECT * FROM contracts_req WHERE req_id = { $req_id } " ;
if ( $id_contract_obj > 0 ){
$sql .= " AND contract_object_id = { $id_contract_obj } " ;
}
$q = $this -> db -> query ( $sql );
if ( $this -> db -> num_rows ( $q ) > 0 ){
$params = array ();
while ( $r = $this -> db -> fetch_assoc ( $q )){
$id = 0 ;
$sql_o = " SELECT id FROM contracts_object WHERE contract_req_id = { $r [ 'id' ] } " ;
$q_o = $this -> db -> query ( $sql_o );
if ( $this -> db -> num_rows ( $q_o ) > 0 ){
$r_o = $this -> db -> fetch_assoc ( $q_o );
$id = ( int ) $r_o [ 'id' ];
}
$params [ 'id' ] = $id ;
$params [ 'parent_id' ] = ( int ) $objectId ;
$params [ 'parent_type' ] = 'object' ;
$params [ 'type' ] = $r [ 'type' ];
$params [ 'date_start' ] = date ( " d.m.Y H:i:s " , $r [ 'date_start' ]);
$params [ 'date_end' ] = date ( " d.m.Y H:i:s " , $r [ 'date_end' ]);
$params [ 'number' ] = $r [ 'number' ];
$params [ 'days_mes_end' ] = $r [ 'days' ];
$params [ 'no_mes_end' ] = $r [ 'send' ];
$params [ 'contract_req_id' ] = ( int ) $r [ 'id' ];
$contractClass = new Contract ( $this -> db );
$contractClass -> setAgencyId ( $this -> agencyId );
$id_oc = $contractClass -> editAdd ( $params , true );
if ( $r [ 'contract_object_id' ] == 0 && $id_oc [ 'id' ] > 0 ){
$this -> db -> query ( " UPDATE contracts_req SET contract_object_id = { $id_oc [ 'id' ] } WHERE id = { $r [ 'id' ] } " );
}
}
} else {
$sql = " SELECT * FROM contracts_object WHERE object_id = { $objectId } " ;
$q = $this -> db -> query ( $sql );
if ( $this -> db -> num_rows ( $q ) > 0 ){
$params = array ();
while ( $r = $this -> db -> fetch_assoc ( $q )){
$id = 0 ;
$sql_o = " SELECT id FROM contracts_req WHERE contract_object_id = { $r [ 'id' ] } " ;
$q_o = $this -> db -> query ( $sql_o );
if ( $this -> db -> num_rows ( $q_o ) > 0 ){
$r_o = $this -> db -> fetch_assoc ( $q_o );
$id = ( int ) $r_o [ 'id' ];
}
$params [ 'id' ] = $id ;
$params [ 'parent_id' ] = ( int ) $req_id ;
$params [ 'parent_type' ] = 'req' ;
$params [ 'type' ] = $r [ 'type' ];
$params [ 'date_start' ] = date ( " d.m.Y H:i:s " , $r [ 'date_start' ]);
$params [ 'date_end' ] = date ( " d.m.Y H:i:s " , $r [ 'date_end' ]);
$params [ 'number' ] = $r [ 'number' ];
$params [ 'days_mes_end' ] = $r [ 'days' ];
$params [ 'no_mes_end' ] = $r [ 'send' ];
$params [ 'contract_object_id' ] = ( int ) $r [ 'id' ];
$contractClass = new Contract ( $this -> db );
$contractClass -> setAgencyId ( $this -> agencyId );
$id_oc = $contractClass -> editAdd ( $params , true );
if ( $r [ 'contract_req_id' ] == 0 && $id_oc [ 'id' ] > 0 ){
$this -> db -> query ( " UPDATE contracts_object SET contract_req_id = { $id_oc [ 'id' ] } WHERE id = { $r [ 'id' ] } " );
}
}
}
}
}
}
//Тип недвижимости
public function check_property_type ( $object_id ){
$type_id = 0 ;
$object = $this -> db -> fetch_assoc ( $this -> db -> query ( " SELECT * FROM objects WHERE id = { $object_id } " ));
if ( isset ( $object [ 'id' ])){
switch ( $object [ 'type' ]) {
case 1 :
{
$type_id = 10 ;
if ( $object [ 'komnat' ] == 1 ){
$type_id = 1 ;
} else if ( $object [ 'komnat' ] == 2 ){
$type_id = 2 ;
} else if ( $object [ 'komnat' ] == 3 ){
$type_id = 3 ;
} else if ( $object [ 'komnat' ] == 4 ){
$type_id = 4 ;
} else if ( $object [ 'komnat' ] > 4 ){
$type_id = 5 ;
}
if ( $object [ 'studio_flag' ] == 1 ){
$type_id = 11 ;
}
break ;
}
case 2 :
$type_id = 12 ;
break ;
case 3 : {
$type_id = 13 ;
$sqlAddInfo = " SELECT object_id, house_category FROM objects_additional_information WHERE object_id = { $object [ 'id' ] } " ;
$qAddInfo = $this -> db -> query ( $sqlAddInfo );
$rAddInfo = $this -> db -> fetch_assoc ( $qAddInfo );
if ( isset ( $rAddInfo [ 'object_id' ])){
if ( $rAddInfo [ 'house_category' ] == 1 ){
$type_id = 14 ;
} else if ( $rAddInfo [ 'house_category' ] == 2 ){
$type_id = 15 ;
} else if ( $rAddInfo [ 'house_category' ] == 3 ){
$type_id = 16 ;
}
}
break ;
}
case 4 :
$type_id = 23 ;
if ( $object [ 'type_category' ] == 1 ){
$type_id = 19 ;
} else if ( $object [ 'type_category' ] == 2 ){
$type_id = 20 ;
} else if ( $object [ 'type_category' ] == 3 ){
$type_id = 21 ;
} else if ( $object [ 'type_category' ] == 4 ){
$type_id = 22 ;
} else if ( $object [ 'type_category' ] == 6 ){
$type_id = 24 ;
} else if ( $object [ 'type_category' ] == 7 ){
$type_id = 25 ;
} else if ( $object [ 'type_category' ] == 8 ){
$type_id = 26 ;
} else if ( $object [ 'type_category' ] == 9 ){
$type_id = 27 ;
}
break ;
case 5 :
$type_id = 17 ;
break ;
case 6 :
$type_id = 23 ;
break ;
case 7 :
$type_id = 18 ;
break ;
}
}
return $type_id ;
}
//Фильтр
public function get_filtr ( $user_id , $funnel_id ){
$result [ 'search' ] = '' ;
$result [ 'stages' ] = array ( 'work' => 1 , 'hot' => 0 , 'close' => 0 , 'hit' => 0 , 'ahency' => 0 , 'confirm' => 0 , 'send' => 0 );
if ( $funnel_id == 'all' ){
$sqlt = " SELECT count(*) as total from requisitions WHERE 1 AND deleted=0 AND (who_work = " . $user_id . " ) AND `confirm` = 0 AND (user_id= $user_id or who_work= $user_id ) " ;
} else {
$sqlt = " SELECT count(*) as total from requisitions WHERE 1 AND funnel_id in ( $funnel_id ) AND deleted=0 AND (who_work = " . $user_id . " ) AND `confirm` = 0 AND (user_id= $user_id or who_work= $user_id ) " ;
}
$qt = $this -> db -> query ( $sqlt );
$totalt = ( int ) $this -> db -> fetch_assoc ( $qt )[ 'total' ];
$result [ 'confirm' ] = $totalt ;
if ( $funnel_id == 'all' ){
$sqlt = " SELECT count(*) as total from requisitions WHERE 1 AND deleted=0 AND (who_work <> " . $user_id . " ) AND `confirm` = 0 AND (user_id= $user_id or who_work= $user_id ) " ;
} else {
$sqlt = " SELECT count(*) as total from requisitions WHERE 1 AND funnel_id in ( $funnel_id ) AND deleted=0 AND (who_work <> " . $user_id . " ) AND `confirm` = 0 AND (user_id= $user_id or who_work= $user_id ) " ;
}
$qt = $this -> db -> query ( $sqlt );
$totalt = ( int ) $this -> db -> fetch_assoc ( $qt )[ 'total' ];
$result [ 'send' ] = $totalt ;
$result [ 'emp' ] = array ();
$result [ 'type' ] = array ();
$result [ 'step' ] = array ();
$result [ 'priority' ] = array ( 1 => 0 , 2 => 0 , 3 => 0 , 4 => 0 );
$result [ 'object_id' ] = '' ;
$result [ 'is_tasks' ] = false ;
$result [ 'noTasks' ] = false ;
$result [ 'todayTasks' ] = false ;
$result [ 'overTasks' ] = false ;
$result [ 'period' ] = 'all' ;
$result [ 'onDate' ] = '' ;
$result [ 'offDate' ] = '' ;
$result [ 'denial' ] = array ();
$result [ 'activities' ] = array ();
$result [ 'order' ] = 0 ;
$result [ 'isPartner' ] = false ;
2026-06-18 13:16:44 +02:00
$result [ 'is_deal' ] = false ;
2026-05-22 20:21:54 +02:00
$result [ 'source' ] = - 1 ;
$result [ 'employee_id' ] = - 1 ;
$result [ 'fields' ] = array ();
return $result ;
}
//Для периодов
function getPeriod ( $period , $onDate = null , $offDate = null ){
$mounthArrray = [ " Январь " , " Февраль " , " Март " , " Апрель " , " Май " , " Июнь " , " Июль " , " Август " , " Сентябрь " , " Октябрь " , " Ноябрь " , " Декабрь " ];
$treplace = array (
" Январь " => " января " ,
" Февраль " => " февраля " ,
" Март " => " марта " ,
" Апрель " => " апреля " ,
" Май " => " мая " ,
" Июнь " => " июня " ,
" Июль " => " июля " ,
" Август " => " августа " ,
" Сентябрь " => " сентября " ,
" Октябрь " => " октября " ,
" Ноябрь " => " ноября " ,
" Декабрь " => " декабря " );
$months = array ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 );
$years = array ();
$firstDay = '' ;
$lastDay = '' ;
$totalDays = 365 ;
$readPeriod = '' ;
$diffDays = 0 ;
$firstNameMonth = $lastNameMonth = $nameMonth = '' ;
$years [] = date ( 'Y' );
$date_between = " between '1970-01-01 00:00:00' AND '3000-12-31 23:59:59' " ;
$dateStart = " 1970-01-01 00:00:00 " ;
$dateEnd = " 3000-12-31 23:59:59 " ;
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between '1970-01-01 00:00:00' AND '3000-12-31 23:59:59' " ;
if ( $period == 'period' ) $period = 'dates' ;
switch ( $period ){
case 'today' : {
$months = array ();
$months [] = ( int ) date ( 'm' );
$firstDay = date ( 'd' );
$totalDays = cal_days_in_month ( CAL_GREGORIAN , ( int ) date ( 'm' ), date ( 'Y' ));
$readPeriod = $mounthArrray [( int ) date ( 'm' ) - 1 ] . ' ' . date ( 'Y' ) . ' года' ;
$datetime1 = new DateTime ( date ( 'Y-m-d' ));
$datetime2 = new DateTime ( date ( 'Y-m-d' ));
$difference = $datetime1 -> diff ( $datetime2 );
$diffDays = $difference -> d ;
$lastDay = $totalDays ;
$procentDays = ( int )(( $diffDays / $totalDays ) * 100 );
$firstNameMonth = $lastNameMonth = $nameMonth = $treplace [ $mounthArrray [( int ) date ( 'm' ) - 1 ]];
$date_between = " between ' " . date ( " Y-m-d " ) . " 00:00:00' AND ' " . date ( " Y-m-d " ) . " 23:59:59' " ;
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between ' " . date ( " Y-m-d " ) . " 00:00:00' AND ' " . date ( " Y-m-d " ) . " 23:59:59' " ;
$dateStart = date ( " Y-m-d " ) . " 00:00:00 " ;
$dateEnd = date ( " Y-m-d " ) . " 23:59:59 " ;
break ;
}
case 'month' : {
$months = array ();
$months [] = ( int ) date ( 'm' );
$firstDay = '01' ;
$totalDays = cal_days_in_month ( CAL_GREGORIAN , ( int ) date ( 'm' ), date ( 'Y' ));
$readPeriod = $mounthArrray [( int ) date ( 'm' ) - 1 ] . ' ' . date ( 'Y' ) . ' года' ;
$datetime1 = new DateTime ( date ( 'Y' ) . '-' . date ( 'm' ) . '-01' );
$datetime2 = new DateTime ( date ( 'Y-m-d' ));
$difference = $datetime1 -> diff ( $datetime2 );
$diffDays = $difference -> d ;
$lastDay = $totalDays ;
$procentDays = ( int )(( $diffDays / $totalDays ) * 100 );
$firstNameMonth = $lastNameMonth = $nameMonth = $treplace [ $mounthArrray [( int ) date ( 'm' ) - 1 ]];
$date_between = " between ' " . date ( 'Y' ) . " - " . date ( 'm' ) . " -01 00:00:00' AND ' " . date ( 'Y' ) . " - " . date ( 'm' ) . " - " . $lastDay . " 23:59:59' " ;
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between ' " . date ( 'Y' ) . " - " . date ( 'm' ) . " -01 00:00:00' AND ' " . date ( 'Y' ) . " - " . date ( 'm' ) . " - " . $lastDay . " 23:59:59' " ;
$dateStart = date ( 'Y' ) . " - " . date ( 'm' ) . " -01 00:00:00 " ;
$dateEnd = date ( 'Y' ) . " - " . date ( 'm' ) . " - " . $lastDay . " 23:59:59 " ;
break ;
}
case 'quarter' : {
$nowMounth = ( int ) date ( 'm' );
if ( $nowMounth < 4 ) {
$months = array ();
$months [] = 1 ;
$months [] = 2 ;
$months [] = 3 ;
$years [] = date ( 'Y' );
$firstDay = '01' ;
$lastDay = '31' ;
$firstNameMonth = $treplace [ $mounthArrray [ 0 ]];
$nameMonth = $treplace [ $mounthArrray [( int ) date ( 'm' ) - 1 ]];
$lastNameMonth = $treplace [ $mounthArrray [ 2 ]];
$datetime1 = new DateTime ( date ( 'Y' ) . '-01-01' );
$datetime2 = new DateTime ( date ( 'Y' ) . '-03-31' );
$difference = $datetime1 -> diff ( $datetime2 );
$totalDays = $difference -> days + 1 ;
$datetime1 = new DateTime ( date ( 'Y' ) . '-01-01' );
$datetime2 = new DateTime ( date ( 'Y-m-d' ));
$difference = $datetime1 -> diff ( $datetime2 );
$diffDays = $difference -> days ;
$procentDays = ( int )(( $diffDays / $totalDays ) * 100 );
$date_between = " between ' " . date ( 'Y' ) . " -01-01 00:00:00' AND ' " . date ( 'Y' ) . " -03-31 23:59:59' " ;
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between ' " . date ( 'Y' ) . " -01-01 00:00:00' AND ' " . date ( 'Y' ) . " -03-31 23:59:59' " ;
$dateStart = date ( 'Y' ) . " -01-01 00:00:00 " ;
$dateEnd = date ( 'Y' ) . " -03-31 23:59:59 " ;
} else if ( $nowMounth >= 4 && $nowMounth < 7 ){
$months = array ();
$months [] = 4 ;
$months [] = 5 ;
$months [] = 6 ;
$years [] = date ( 'Y' );
$firstDay = '01' ;
$lastDay = '30' ;
$firstNameMonth = $treplace [ $mounthArrray [ 3 ]];
$nameMonth = $treplace [ $mounthArrray [( int ) date ( 'm' ) - 1 ]];
$lastNameMonth = $treplace [ $mounthArrray [ 5 ]];
$datetime1 = new DateTime ( date ( 'Y' ) . '-04-01' );
$datetime2 = new DateTime ( date ( 'Y' ) . '-06-30' );
$difference = $datetime1 -> diff ( $datetime2 );
$totalDays = $difference -> days + 1 ;
$datetime1 = new DateTime ( date ( 'Y' ) . '-04-01' );
$datetime2 = new DateTime ( date ( 'Y-m-d' ));
$difference = $datetime1 -> diff ( $datetime2 );
$diffDays = $difference -> days ;
$procentDays = ( int )(( $diffDays / $totalDays ) * 100 );
$date_between = " between ' " . date ( 'Y' ) . " -04-01 00:00:00' AND ' " . date ( 'Y' ) . " -06-30 23:59:59' " ;
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between ' " . date ( 'Y' ) . " -04-01 00:00:00' AND ' " . date ( 'Y' ) . " -06-30 23:59:59' " ;
$dateStart = date ( 'Y' ) . " -04-01 00:00:00 " ;
$dateEnd = date ( 'Y' ) . " -06-30 23:59:59 " ;
} else if ( $nowMounth >= 7 && $nowMounth < 10 ){
$months = array ();
$months [] = 7 ;
$months [] = 8 ;
$months [] = 9 ;
$years [] = date ( 'Y' );
$firstDay = '01' ;
$lastDay = '30' ;
$firstNameMonth = $treplace [ $mounthArrray [ 6 ]];
$nameMonth = $treplace [ $mounthArrray [( int ) date ( 'm' ) - 1 ]];
$lastNameMonth = $treplace [ $mounthArrray [ 8 ]];
$datetime1 = new DateTime ( date ( 'Y' ) . '-07-01' );
$datetime2 = new DateTime ( date ( 'Y' ) . '-09-30' );
$difference = $datetime1 -> diff ( $datetime2 );
$totalDays = $difference -> days + 1 ;
$datetime1 = new DateTime ( date ( 'Y' ) . '-07-01' );
$datetime2 = new DateTime ( date ( 'Y-m-d' ));
$difference = $datetime1 -> diff ( $datetime2 );
$diffDays = $difference -> days ;
$procentDays = ( int )(( $diffDays / $totalDays ) * 100 );
$date_between = " between ' " . date ( 'Y' ) . " -07-01 00:00:00' AND ' " . date ( 'Y' ) . " -09-30 23:59:59' " ;
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between ' " . date ( 'Y' ) . " -07-01 00:00:00' AND ' " . date ( 'Y' ) . " -09-30 23:59:59' " ;
$dateStart = date ( 'Y' ) . " -07-01 00:00:00 " ;
$dateEnd = date ( 'Y' ) . " -09-30 23:59:59 " ;
} else if ( $nowMounth >= 10 && $nowMounth < 13 ){
$months = array ();
$months [] = 10 ;
$months [] = 11 ;
$months [] = 12 ;
$years [] = date ( 'Y' );
$firstDay = '01' ;
$lastDay = '31' ;
$firstNameMonth = $treplace [ $mounthArrray [ 9 ]];
$nameMonth = $treplace [ $mounthArrray [( int ) date ( 'm' ) - 1 ]];
$lastNameMonth = $treplace [ $mounthArrray [ 11 ]];
$readPeriod = 'c ' . $firstDay . ' ' . $firstNameMonth . ' по ' . $lastDay . ' ' . $lastNameMonth ;
$datetime1 = new DateTime ( date ( 'Y' ) . '-10-01' );
$datetime2 = new DateTime ( date ( 'Y' ) . '-12-31' );
$difference = $datetime1 -> diff ( $datetime2 );
$totalDays = $difference -> days + 1 ;
$datetime1 = new DateTime ( date ( 'Y' ) . '-10-01' );
$datetime2 = new DateTime ( date ( 'Y-m-d' ));
$difference = $datetime1 -> diff ( $datetime2 );
$diffDays = $difference -> days ;
$procentDays = ( int )(( $diffDays / $totalDays ) * 100 );
$date_between = " between ' " . date ( 'Y' ) . " -10-01 00:00:00' AND ' " . date ( 'Y' ) . " -12-31 23:59:59' " ;
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between ' " . date ( 'Y' ) . " -10-01 00:00:00' AND ' " . date ( 'Y' ) . " -12-31 23:59:59' " ;
$dateStart = date ( 'Y' ) . " -10-01 00:00:00 " ;
$dateEnd = date ( 'Y' ) . " -12-31 23:59:59 " ;
}
break ;
}
case 'week' : {
$months = array ();
$months [] = ( int ) date ( 'm' );
$years = array ();
$years [] = date ( 'Y' );
$firstDay = date ( " d " , strtotime ( " monday this week " ));
$lastDay = date ( " d " , strtotime ( " sunday this week " ));
$firstNameMonth = $treplace [ $mounthArrray [( int ) date ( " m " , strtotime ( " monday this week " )) - 1 ]];
$nameMonth = $treplace [ $mounthArrray [( int ) date ( 'm' ) - 1 ]];
$lastNameMonth = $treplace [ $mounthArrray [( int ) date ( " m " , strtotime ( " sunday this week " )) - 1 ]];
$readPeriod = 'c ' . $firstDay . ' ' . $firstNameMonth . ' по ' . $lastDay . ' ' . $lastNameMonth ;
$datetime1 = new DateTime ( date ( " Y-m-d " , strtotime ( " monday this week " )));
$datetime2 = new DateTime ( date ( " Y-m-d " , strtotime ( " sunday this week " )));
$difference = $datetime1 -> diff ( $datetime2 );
$totalDays = $difference -> days + 1 ;
$datetime1 = new DateTime ( date ( " Y-m-d " , strtotime ( " monday this week " )));
$datetime2 = new DateTime ( date ( 'Y-m-d' ));
$difference = $datetime1 -> diff ( $datetime2 );
$diffDays = $difference -> days ;
$procentDays = ( int )(( $diffDays / $totalDays ) * 100 );
$date_between = " between ' " . date ( " Y-m-d 00:00:00 " , strtotime ( " monday this week " )) . " ' AND ' " . date ( " Y-m-d 23:59:59 " , strtotime ( " sunday this week " )) . " ' " ;
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between ' " . date ( " Y-m-d 00:00:00 " , strtotime ( " monday this week " )) . " ' AND ' " . date ( " Y-m-d 23:59:59 " , strtotime ( " sunday this week " )) . " ' " ;
$dateStart = date ( " Y-m-d 00:00:00 " , strtotime ( " monday this week " ));
$dateEnd = date ( " Y-m-d 23:59:59 " , strtotime ( " sunday this week " ));
break ;
}
case 'dates' : {
if ( empty ( $offDate )) $offDate = date ( 'Y-m-d 23:59:59' );
$months = array ();
$years = array ();
$months [] = date ( " m " , strtotime ( $onDate ));
$months [] = date ( " m " , strtotime ( $offDate ));
$years [] = date ( " Y " , strtotime ( $onDate ));
$years [] = date ( " Y " , strtotime ( $offDate ));
$firstDay = date ( " d " , strtotime ( $onDate ));
$lastDay = date ( " d " , strtotime ( $offDate ));
$firstNameMonth = $treplace [ $mounthArrray [( int ) date ( " m " , strtotime ( $onDate )) - 1 ]];
$nameMonth = $treplace [ $mounthArrray [( int ) date ( 'm' ) - 1 ]];
$lastNameMonth = $treplace [ $mounthArrray [( int ) date ( " m " , strtotime ( $offDate )) - 1 ]];
$readPeriod = 'c ' . $firstDay . ' ' . $firstNameMonth . ' по ' . $lastDay . ' ' . $lastNameMonth ;
$datetime1 = new DateTime ( date ( " Y-m-d " , strtotime ( $onDate )));
$datetime2 = new DateTime ( date ( " Y-m-d " , strtotime ( $offDate )));
$difference = $datetime1 -> diff ( $datetime2 );
$totalDays = $difference -> days + 1 ;
$datetime1 = new DateTime ( date ( " Y-m-d " , strtotime ( $onDate )));
$datetime2 = new DateTime ( date ( 'Y-m-d' ));
if ( $datetime1 < $datetime2 ){
$difference = $datetime1 -> diff ( $datetime2 );
$diffDays = $difference -> days ;
$procentDays = ( int )(( $diffDays / $totalDays ) * 100 );
}
$procentDays = 0 ;
$date_between = " between ' " . date ( " Y-m-d 00:00:00 " , strtotime ( $onDate )) . " ' AND ' " . date ( " Y-m-d 23:59:59 " , strtotime ( $offDate )) . " ' " ;
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between ' " . date ( " Y-m-d 00:00:00 " , strtotime ( $onDate )) . " ' AND ' " . date ( " Y-m-d 23:59:59 " , strtotime ( $offDate )) . " ' " ;
$dateStart = date ( " Y-m-d 00:00:00 " , strtotime ( $onDate ));
$dateEnd = date ( " Y-m-d 23:59:59 " , strtotime ( $offDate ));
break ;
} case '30days' : {
$months = array ();
$months [] = ( int ) date ( 'm' );
$firstDay = date ( 'd' );
$totalDays = 30 ;
$datetime1 = new DateTime ( date ( 'Y-m-d' , strtotime ( '-30 day' )));
$readPeriod = $mounthArrray [( int ) date ( 'm' ) - 1 ] . ' ' . date ( 'Y' ) . ' года' ;
//$datetime1 = new DateTime(date('Y-m-d'));
$datetime2 = new DateTime ( date ( 'Y-m-d' ));
$difference = $datetime1 -> diff ( $datetime2 );
$diffDays = $difference -> d ;
$lastDay = $totalDays ;
$procentDays = ( int )(( $diffDays / $totalDays ) * 100 );
$firstNameMonth = $lastNameMonth = $nameMonth = $treplace [ $mounthArrray [( int ) date ( 'm' ) - 1 ]];
$date_between = " between ' " . date ( 'Y-m-d' , strtotime ( '-30 day' )) . " 00:00:00' AND ' " . date ( " Y-m-d " ) . " 23:59:59' " ;
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between ' " . date ( 'Y-m-d' , strtotime ( '-30 day' )) . " 00:00:00' AND ' " . date ( " Y-m-d " ) . " 23:59:59' " ;
$dateStart = date ( 'Y-m-d' , strtotime ( '-30 day' )) . " 00:00:00 " ;
$dateEnd = date ( " Y-m-d " ) . " 23:59:59 " ;
break ;
} case '90days' : {
$months = array ();
$months [] = ( int ) date ( 'm' );
$firstDay = date ( 'd' );
$totalDays = 90 ;
$datetime1 = new DateTime ( date ( 'Y-m-d' , strtotime ( '-30 day' )));
$readPeriod = $mounthArrray [( int ) date ( 'm' ) - 1 ] . ' ' . date ( 'Y' ) . ' года' ;
//$datetime1 = new DateTime(date('Y-m-d'));
$datetime2 = new DateTime ( date ( 'Y-m-d' ));
$difference = $datetime1 -> diff ( $datetime2 );
$diffDays = $difference -> d ;
$lastDay = $totalDays ;
$procentDays = ( int )(( $diffDays / $totalDays ) * 100 );
$firstNameMonth = $lastNameMonth = $nameMonth = $treplace [ $mounthArrray [( int ) date ( 'm' ) - 1 ]];
$date_between = " between ' " . date ( 'Y-m-d' , strtotime ( '-90 day' )) . " 00:00:00' AND ' " . date ( " Y-m-d " ) . " 23:59:59' " ;
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between ' " . date ( 'Y-m-d' , strtotime ( '-90 day' )) . " 00:00:00' AND ' " . date ( " Y-m-d " ) . " 23:59:59' " ;
$dateStart = date ( 'Y-m-d' , strtotime ( '-90 day' )) . " 00:00:00 " ;
$dateEnd = date ( " Y-m-d " ) . " 23:59:59 " ;
break ;
}
default : {
$firstDay = '01' ;
$lastDay = '31' ;
$firstNameMonth = $treplace [ $mounthArrray [ 0 ]];
$nameMonth = $treplace [ $mounthArrray [( int ) date ( 'm' ) - 1 ]];
$lastNameMonth = $treplace [ $mounthArrray [ 11 ]];
$readPeriod = date ( 'Y' ) . ' год' ;
$datetime1 = new DateTime ( date ( 'Y' ) . '-01-01' );
$datetime2 = new DateTime ( date ( 'Y' ) . '-12-31' );
$difference = $datetime1 -> diff ( $datetime2 );
$totalDays = $difference -> days + 1 ;
$datetime1 = new DateTime ( date ( 'Y' ) . '-01-01' );
$datetime2 = new DateTime ( date ( 'Y-m-d' ));
$difference = $datetime1 -> diff ( $datetime2 );
$diffDays = $difference -> days ;
$procentDays = ( int )(( $diffDays / $totalDays ) * 100 );
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between ' " . date ( 'Y' ) . " -01-01 00:00:00' AND ' " . date ( 'Y' ) . " -12-31 23:59:59' " ;
$dateStart = date ( 'Y' ) . " -01-01 00:00:00 " ;
$dateEnd = date ( 'Y' ) . " -12-31 23:59:59 " ;
break ;
}
}
$result = array ( 'between' => $date_between , 'whereTasks' => $whereTasks , 'dateStart' => $dateStart , 'dateEnd' => $dateEnd );
return $result ;
}
//Список доступных юзеров
public function getIdsUsers ( $user_id ){
if (( int ) $user_id == 0 ) die ();
$usersIds = array ();
$search_user_id = ( int ) $user_id ;
$usersIds [] = $search_user_id ;
$sql = " SELECT * FROM users WHERE id = { $user_id } " ;
$q = $this -> db -> query ( $sql , true );
$user = $this -> db -> fetch_assoc ( $q );
if ( $user [ 'role_id' ] > 0 ){
$dep = new Department ();
$res = $dep -> getDepartment ( $user_id );
//var_dump($res);
if ( $res [ 'role' ] == 'manager_office' || $res [ 'role' ] == 'manager_office_menager' || $res [ 'role' ] == 'user_admin' ){
$search_user_id = ( int ) $res [ 'admin' ];
}
//manager_office_menager
}
$sql_user = " SELECT id from users WHERE id in (select id from users where id= { $search_user_id } or id_manager= { $search_user_id } or id_manager in (select id from users where id_manager= { $search_user_id } or id_manager in (select id from users where id_manager= { $search_user_id } ))) " ;
if ( $_SESSION [ 'id' ] == 21444 ){
file_put_contents ( __DIR__ . '/log_req.txt' , json_encode ( $res , JSON_UNESCAPED_UNICODE ) . " \n " , FILE_APPEND );
file_put_contents ( __DIR__ . '/log_req.txt' , $sql_user . " \n " , FILE_APPEND );
}
$q_user = $this -> db -> query ( $sql_user , true );
while ( $r_user = $this -> db -> fetch_assoc ( $q_user )){
if ( ! in_array (( int ) $r_user [ 'id' ], $usersIds )){
$usersIds [] = ( int ) $r_user [ 'id' ];
}
}
$this -> userIdsWork = $usersIds ;
return $usersIds ;
}
public function update_reservation_is_interrupted ( $req_id , $bool = true )
{
$sql = " UPDATE `requisitions` SET `is_interrupted` = $bool WHERE id = $req_id " ;
try {
$this -> db -> query ( $sql );
return [ 'status' => true ];
} catch ( \Throwable $th ) {
return [ 'status' => false ];
}
}
/**
* Поиск заявок для объединения
*/
public function get_union_reqs ( $reqs ){
/* ini_set ( 'display_errors' , 1 );
error_reporting ( E_ALL & ~ E_DEPRECATED & ~ E_STRICT & ~ E_NOTICE ); */
$result = array ();
if ( $this -> user_id > 0 && $this -> agencyId > 0 && ! empty ( $reqs )){
$usersIds = array ();
$webHookIn = new WebHookIn ();
$usersIds = $webHookIn -> getAllUserAgency ( $this -> agencyId );
if ( ! empty ( $usersIds )){
$types = [ 0 , 1 , 3 ];
$sql_type = " SELECT id FROM requisitions_type WHERE heir in (1,3) AND agency_id = { $this -> agencyId } " ;
$q_type = $this -> db -> query ( $sql_type , true );
while ( $r_type = $this -> db -> fetch_assoc ( $q_type )){
$types [] = ( int ) $r_type [ 'id' ];
}
$sql = " SELECT * FROM requisitions WHERE user_id in ( " . implode ( ',' , $usersIds ) . " ) AND type_id in ( " . implode ( ',' , $types ) . " ) AND deleted=0 AND cancel=0 AND confirm=1 " ;
//echo $sql;
$q = $this -> db -> query ( $sql , true );
while ( $r = $this -> db -> fetch_assoc ( $q )){
foreach ( $reqs as $key => $req ){
if (( int ) $req -> id != ( int ) $r [ 'id' ] && $req -> type_id != 2 && $req -> type_id != 4 && $req -> heir_type != 4 && $req -> heir_type != 2 ){
if ( $req -> who_work == $r [ 'who_work' ] && $req -> client_id == $r [ 'client_id' ]){
$result [ $key ][] = ( int ) $r [ 'id' ];
}
}
}
}
}
}
return $result ;
}
/**
* Сохранение объединения заявок
*/
public function save_union_reqs ( $reqs , $main_id ){
/* ini_set ( 'display_errors' , 1 );
error_reporting ( E_ALL & ~ E_DEPRECATED & ~ E_STRICT & ~ E_NOTICE ); */
$result = array ();
$done = false ;
if ( $this -> user_id > 0 && $main_id > 0 && ! empty ( $reqs )){
$req_main = $this -> get_req_main ( $main_id );
$reqs = array_unique ( $reqs );
$comments = $this -> get_comment_reqs ( $reqs );
$dop_text = " Присоединены заявки c ID: " . implode ( ', ' , $reqs );
if ( $req_main [ 'who_work' ] > 0 ){
$in_ev = " INSERT INTO `events_clients` (`user_id`, `from_id`, `req_id`, `event`, `dop_text`, `read`, send_telegramm) VALUES (' { $this -> user_id } ', ' { $req_main [ 'who_work' ] } ', ' $main_id ', 'update', ' { $dop_text } ', 1, 1) " ;
$dop_text2 = " Основная заявка ID: " . $main_id ;
if ( ! empty ( $req_main [ 'name_activity2' ])){
$dop_text2 .= ' по ' . $req_main [ 'name_activity2' ];
}
$dop_text2 .= '<br>К ней добавлена заявка: <br>' ;
if ( isset ( $comments [ 'text2' ]) && ! empty ( $comments [ 'text2' ])){
$dop_text2 .= $comments [ 'text2' ];
}
$in_ev2 = " INSERT INTO `events_clients` (`user_id`, `from_id`, `req_id`, `event`, `dop_text`, `read`, is_not_show) VALUES (' { $this -> user_id } ', ' { $req_main [ 'who_work' ] } ', ' $main_id ', 'union', ' { $dop_text2 } ', 1, 1) " ;
} else {
$in_ev = " INSERT INTO `events_clients` (`user_id`, `req_id`, `event`, `dop_text`, `read`) VALUES (' { $this -> user_id } ', ' $main_id ', 'update', ' { $dop_text } ', 1) " ;
} //$in_ev = "INSERT INTO `events_clients` (`user_id`, `req_id`, `event`, `dop_text`, `read`) VALUES ('{$this->user_id}', '$main_id', 'union', '{$dop_text}', 0)";
if ( ! empty ( $comments [ 'comment' ])){
$in_comment = " INSERT INTO `user_client_events` (`user_id`, `req_id`, `type`, `comment`) VALUES (' { $this -> user_id } ', { $main_id } , 'comment' ,' { $comments [ 'comment' ] } ') " ;
$q_comment = $this -> db -> query ( $in_comment );
}
//переносим события
foreach ( $reqs as $req_id ){
$sql_ev = " SELECT * FROM user_client_events WHERE req_id = { $req_id } AND type != 'file' " ;
$q_ev = $this -> db -> query ( $sql_ev , true );
$sql = " INSERT INTO `user_client_events` (`user_id`, `client_id`, `req_id`, `old_req_id`, `create_date`, `type`, `checklist`, `address`, `sum`, `document_id`, `name`, `schedule_date_to`, `schedule_date`, `comment`, `calendar_view`, `from_id`, `partner_id`, `tracking`, `tel`, `mango`, `megafon`, `telphin`, `beeline`, `mts`, `tele2`, `allo`, `open_step`, `record`, `cancel`) VALUE " ;
$key_req = 0 ;
while ( $r_ev = $this -> db -> fetch_assoc ( $q_ev )){
if ( $key_req == 5 ){
$this -> db -> query ( $sql , true );
$key_req = 0 ;
$sql = " INSERT INTO `user_client_events` (`user_id`, `client_id`, `req_id`, `old_req_id`, `create_date`, `type`, `checklist`, `address`, `sum`, `document_id`, `name`, `schedule_date_to`, `schedule_date`, `comment`, `calendar_view`, `from_id`, `partner_id`, `tracking`, `tel`, `mango`, `megafon`, `telphin`, `beeline`, `mts`, `tele2`, `allo`, `open_step`, `record`, `cancel`) VALUE " ;
}
if ( $key_req > 0 ) $sql .= " , " ;
if ( $r_ev [ 'calendar_view' ] == 1 || $r_ev [ 'cancel' ] == 1 || $r_ev [ 'type' ] == 'comment' )
$sql .= " ( $r_ev[user_id] , $r_ev[client_id] , { $main_id } , $r_ev[req_id] , ' $r_ev[create_date] ', ' $r_ev[type] ', ' $r_ev[checklist] ', ' $r_ev[address] ', ' $r_ev[sum] ', ' $r_ev[document_id] ', ' $r_ev[name] ', ' $r_ev[schedule_date_to] ', ' $r_ev[schedule_date] ', ' $r_ev[comment] ', ' $r_ev[calendar_view] ', ' $r_ev[from_id] ', ' $r_ev[partner_id] ', ' $r_ev[tracking] ', ' $r_ev[tel] ', ' $r_ev[mango] ', ' $r_ev[megafon] ', ' $r_ev[telphin] ', ' $r_ev[beeline] ', ' $r_ev[mts] ', ' $r_ev[tele2] ', ' $r_ev[allo] ', ' $r_ev[open_step] ', ' $r_ev[record] ', ' $r_ev[cancel] ') " ;
else
$sql .= " ( { $this -> user_id } , $r_ev[client_id] , { $main_id } , $r_ev[req_id] , ' $r_ev[create_date] ', ' $r_ev[type] ', ' $r_ev[checklist] ', ' $r_ev[address] ', ' $r_ev[sum] ', ' $r_ev[document_id] ', ' $r_ev[name] ', ' $r_ev[schedule_date_to] ', ' $r_ev[schedule_date] ', ' $r_ev[comment] ', ' $r_ev[calendar_view] ', { $this -> user_id } , ' $r_ev[partner_id] ', ' $r_ev[tracking] ', ' $r_ev[tel] ', ' $r_ev[mango] ', ' $r_ev[megafon] ', ' $r_ev[telphin] ', ' $r_ev[beeline] ', ' $r_ev[mts] ', ' $r_ev[tele2] ', ' $r_ev[allo] ', ' $r_ev[open_step] ', ' $r_ev[record] ', ' $r_ev[cancel] ') " ;
$key_req ++ ;
}
if ( $key_req > 0 ){
$this -> db -> query ( $sql , true );
}
}
//Объединение тегов
$all_reqs_ids = $reqs ;
$all_reqs_ids [] = $main_id ;
$all_tags = array ();
if ( ! empty ( $all_reqs_ids )){
$sql_ak = " SELECT * FROM requisitions_activities WHERE req_id in ( " . implode ( ',' , $all_reqs_ids ) . " ) " ;
$q_ak = $this -> db -> query ( $sql_ak );
while ( $r_ak = $this -> db -> fetch_assoc ( $q_ak )){
if ( ! in_array (( int ) $r_ak [ 'activity_id' ], $all_tags ))
$all_tags [] = ( int ) $r_ak [ 'activity_id' ];
}
$all_tags = array_unique ( $all_tags );
if ( ! empty ( $all_tags )){
$this -> db -> query ( " DELETE FROM requisitions_activities WHERE req_id = { $main_id } " );
$sql_ak_in = " INSERT INTO requisitions_activities (`req_id`, `activity_id`) VALUES " ;
$key_tag = 0 ;
foreach ( $all_tags as $tag ){
if ( $key_tag > 0 ) $sql_ak_in .= " , " ;
$sql_ak_in .= " ( { $main_id } , { $tag } ) " ;
$key_tag ++ ;
}
if ( $key_tag > 0 ){
$this -> db -> query ( $sql_ak_in );
}
}
}
// if($this->db->query($sql, true)){
// $done = true;
if ( ! $this -> db -> query ( $in_ev , true ))
$done = false ;
else {
if ( isset ( $in_ev2 )){
$this -> db -> query ( $in_ev2 , true );
}
if ( isset ( $in_ev3 )){
$this -> db -> query ( $in_ev3 , true );
}
$sql_req = " UPDATE requisitions SET cancel=1 WHERE id in ( " . implode ( ',' , $reqs ) . " ) " ;
if ( ! $this -> db -> query ( $sql_req , true )){
$done = false ;
} else {
$sql_in_union = " INSERT INTO union_requisitions (`main_id`, `req_id`, `user_id`, `agency_id`) VALUES " ;
foreach ( $reqs as $key => $req_id ){
if ( $key > 0 ) $sql_in_union .= " , " ;
$sql_in_union .= " ( { $main_id } , { $req_id } , { $this -> user_id } , { $this -> agencyId } ) " ;
}
if ( ! $this -> db -> query ( $sql_in_union )){
$done = false ;
}
//Отправка уведомления менеджеру
$this -> check_mesages ( $req_main , $comments );
//Объединение файлов
$sql_file = " SELECT *, fc.type as type_file, fc.guid, fc.id as file_id, uc.id as event_id FROM `user_client_events` as uc LEFT JOIN clients_files as fc ON uc.id=fc.event_id WHERE uc.type = 'file' AND uc.req_id in ( " . implode ( ',' , $reqs ) . " ) " ;
//echo $sql_file."\n";
$q_file = $this -> db -> query ( $sql_file , true );
while ( $r_file = $this -> db -> fetch_assoc ( $q_file )){
$sql_in_file = " INSERT INTO `user_client_events` (`user_id`, `client_id`, `req_id`, `old_req_id`, `create_date`, `type`, `checklist`, `address`, `sum`, `document_id`, `name`, `schedule_date_to`, `schedule_date`, `comment`, `calendar_view`, `from_id`, `partner_id`, `tracking`, `tel`, `mango`, `megafon`, `telphin`, `beeline`, `mts`, `tele2`, `allo`, `open_step`, `record`, `cancel`)
SELECT `user_id` , `client_id` , { $main_id }, { $r_file [ 'req_id' ]}, `create_date` , `type` , `checklist` , `address` , `sum` , `document_id` , `name` , `schedule_date_to` , `schedule_date` , `comment` , `calendar_view` , `from_id` , `partner_id` , `tracking` , `tel` , `mango` , `megafon` , `telphin` , `beeline` , `mts` , `tele2` , `allo` , `open_step` , `record` , `cancel`
FROM `user_client_events` WHERE id = { $r_file [ 'event_id' ]} " ;
$this -> db -> query ( $sql_in_file , true );
$event_id = $this -> db -> insert_id ();
$sql_cl_file = " INSERT INTO `clients_files`(`guid`, `funnel_id`, `etap_id`, `type`, `name`, `event_id`, `req_id`, `name_id`)
SELECT `guid` , `funnel_id` , `etap_id` , `type` , `name` , { $event_id }, { $main_id }, `name_id` FROM `clients_files` WHERE id = { $r_file [ 'file_id' ]} " ;
//echo $sql_cl_file."\n";
$this -> db -> query ( $sql_cl_file , true );
$path = $_SERVER [ 'DOCUMENT_ROOT' ] . " /upload/reqs/ " . $main_id ;
if ( ! file_exists ( $path )){
mkdir ( $path , 0777 );
}
$old_path = $_SERVER [ 'DOCUMENT_ROOT' ] . " /upload/reqs/ " . $r_file [ 'req_id' ];
$name = $r_file [ 'guid' ] . '.' . $r_file [ 'type_file' ];
//echo $path."/".$name."\n";
if ( ! file_exists ( $path . " / " . $name ) && file_exists ( $old_path . " / " . $name )){
if ( ! copy ( $old_path . " / " . $name , $path . " / " . $name )){
$done = false ;
} else {
$type = $r_file [ 'type_file' ];
//отпарвляем файл в Селектел
$token = SelectelApi :: getNewToken ();
$contType = " application/octet-stream " ;
if ( $type ) {
$type = strtolower ( $type );
}
if ( $type === " doc " ) {
$contType = " application/msword " ;
}
if ( $type === " docx " ) {
$contType = " application/vnd.openxmlformats-officedocument.wordprocessingml.document " ;
}
if ( $type === " xls " ) {
$contType = " application/vnd.ms-excel " ;
}
if ( $type === " xlsx " ) {
$contType = " application/vnd.openxmlformats-officedocument.spreadsheetml.sheet " ;
}
if ( $type === " pdf " ) {
$contType = " application/pdf " ;
}
if ( $type === " jpeg " || $type === " jpg " ) {
$contType = " image/jpeg " ;
}
if ( $type === " gif " ) {
$contType = " image/gif " ;
}
if ( $type === " png " ) {
$contType = " image/png " ;
}
if ( $type === " mp3 " ) {
$contType = " audio/mpeg " ;
}
if ( $type === " zip " ) {
$contType = " application/zip " ;
}
if ( $type === " rar " ) {
$contType = " application/vnd.rar " ;
}
$new_path = " /upload/reqs/ " . $main_id . " / " . $name ;
// echo $new_path."\n";
$r = SelectelApi :: uploadUserFile ( $token , $path . " / " . $name , $new_path , $contType );
//var_dump($r);
}
}
}
}
}
}
$result [ 'done' ] = $done ;
return $result ;
}
/**
* Автоматическое объединение заявок
*/
public function autoUnitReq ( $rang , $reqs ) {
//echo $this->agencyId." ".$this->user_id ." ". is_numeric($rang)." ".!empty($reqs);
//var_dump(($this->agencyId && $this->user_id && is_numeric($rang) && !empty($reqs)));
if ( $this -> agencyId && $this -> user_id && is_numeric ( $rang ) && ! empty ( $reqs )){
if ( $this -> agencyId == 19895 ){
switch ( $rang ){
case - 1 : { //В с е закрытые. Главная, которая создана последней
$this -> union_closes_req ( $reqs );
break ;
}
case 0 : { //общие с закрытыми
$this -> union_general_req ( $reqs );
break ;
}
case 1 : { //Активные
$this -> union_active_req ( $reqs );
break ;
}
}
}
}
}
/**
*
*/
private function get_req_main ( $req_id ){
$sql = " SELECT * FROM requisitions as req WHERE id = { $req_id } " ;
$q = $this -> db -> query ( $sql , true );
$req_main = $this -> db -> fetch_assoc ( $q );
$req_main [ 'name_activity' ] = '' ;
$req_main [ 'name_activity2' ] = '' ;
$sql_a = " SELECT *, (SELECT name FROM activities WHERE activities.id = requisitions_activities.activity_id) as name FROM requisitions_activities WHERE req_id = { $req_id } " ;
$activites_name = [];
$q_a = $this -> db -> query ( $sql_a , true );
while ( $r_a = $this -> db -> fetch_assoc ( $q_a )){
if ( $req_main [ 'name_activity' ] == '' ){
$req_main [ 'name_activity' ] = $r_a [ 'name' ];
}
if ( count ( $activites_name ) < 2 ){
$activites_name [] = $r_a [ 'name' ];
}
}
if ( ! empty ( $activites_name )){
$req_main [ 'name_activity2' ] = implode ( ', ' , $activites_name );
}
return $req_main ;
}
/**
* Формирование комментария с ответсвенным и тегами
*/
private function get_comment_reqs ( $reqs ){
$comments [ 'comment' ] = '' ;
$comments [ 'text' ] = '' ;
$comments [ 'text2' ] = '' ;
if ( ! empty ( $reqs )){
$arr_name_activities = array ();
$arr_name_first_activity = array ();
$arr_name_two_activity = array ();
$sql_a = " SELECT *, (SELECT name FROM activities WHERE activities.id = requisitions_activities.activity_id) as name FROM requisitions_activities WHERE req_id in ( " . implode ( ',' , $reqs ) . " ) " ;
$q_a = $this -> db -> query ( $sql_a );
while ( $r_a = $this -> db -> fetch_assoc ( $q_a )){
if ( ! isset ( $arr_name_activities [ $r_a [ 'req_id' ]])) $arr_name_activities [ $r_a [ 'req_id' ]] = '' ;
if ( $arr_name_activities [ $r_a [ 'req_id' ]] != '' ) $arr_name_activities [ $r_a [ 'req_id' ]] .= ', ' ;
$arr_name_activities [ $r_a [ 'req_id' ]] .= $r_a [ 'name' ];
if ( ! isset ( $arr_name_first_activity [ $r_a [ 'req_id' ]])) $arr_name_first_activity [ $r_a [ 'req_id' ]] = $r_a [ 'name' ];
if ( ! isset ( $arr_name_two_activity [ $r_a [ 'req_id' ]])) $arr_name_two_activity [ $r_a [ 'req_id' ]] = [];
if ( count ( $arr_name_two_activity [ $r_a [ 'req_id' ]]) < 2 ) $arr_name_two_activity [ $r_a [ 'req_id' ]][] = $r_a [ 'name' ];
}
$sql = " SELECT *, if (who_work > 0, (SELECT CONCAT(last_name, ' ', first_name, ' ', middle_name) FROM users WHERE requisitions.who_work = users.id), (SELECT (SELECT CONCAT(last_name, ' ', first_name, ' ', middle_name) as fio FROM users WHERE events_clients.user_id = users.id) FROM events_clients WHERE requisitions.id = events_clients.req_id AND event = 'transmitted' order by id desc limit 1)) as fio FROM requisitions WHERE id in ( " . implode ( ',' , $reqs ) . " ) " ;
$q = $this -> db -> query ( $sql );
$comments [ 'comment' ] .= " Присоединены следующие заявки <br> " ;
$k = 0 ;
while ( $r = $this -> db -> fetch_assoc ( $q )){
if ( $k > 0 ) {
$comments [ 'comment' ] .= " <br> " ;
$comments [ 'text' ] .= " <br> " ;
$comments [ 'text2' ] .= " <br> " ;
}
$fio = " из общих " ;
if ( ! empty ( $r [ 'fio' ])){
$fio = $r [ 'fio' ];
}
$comments [ 'comment' ] .= " ID: " . $r [ 'id' ];
$comments [ 'comment' ] .= " ; ответственный: " . $fio ;
if ( isset ( $arr_name_activities [ $r [ 'id' ]])){
$comments [ 'comment' ] .= " ; теги: " . $arr_name_activities [ $r [ 'id' ]];
}
$comments [ 'text' ] .= " ID: " . $r [ 'id' ];
$comments [ 'text2' ] .= " ID: " . $r [ 'id' ];
if ( isset ( $arr_name_first_activity [ $r [ 'id' ]])){
$comments [ 'text' ] .= " по " . $arr_name_first_activity [ $r [ 'id' ]];
}
if ( isset ( $arr_name_two_activity [ $r [ 'id' ]]) && ! empty ( $arr_name_two_activity [ $r [ 'id' ]])){
$comments [ 'text2' ] .= " по " . implode ( ', ' , $arr_name_two_activity [ $r [ 'id' ]]);
}
$k ++ ;
}
}
return $comments ;
}
/**
* Активные по клиенту и поиск самой старшей
*/
private function get_active_req ( $client_id ){
$req_id = 0 ;
$sql = " SELECT * FROM requisitions WHERE client_id = { $client_id } AND deleted = 0 AND who_work <> 0 AND is_manual = 0 AND cancel = 0 order by created_at asc LIMIT 1 " ;
$q = $this -> db -> query ( $sql , true );
$req = $this -> db -> fetch_assoc ( $q );
if ( $req && $req [ 'id' ]){
$req_id = ( int ) $req [ 'id' ];
}
return $req_id ;
}
/**
* Горячая по клиенту и ответственному
*/
private function get_hot_req ( $client_id , $who_work ){
$req_id = 0 ;
}
/**
* Поиск тега Горячий
*/
private function get_hot_tag ( $req_id ){
$result = false ;
$hot_tag = 0 ;
if ( $this -> agencyId > 0 ){
if ( $this -> agencyId == 19895 ){
$hot_tag = 3039 ;
$enter_tag = 3043 ;
}
else if ( $this -> agencyId == 117 ){
$hot_tag = 3232 ;
} else if ( $this -> agencyId == 5238 ){
$hot_tag = 338 ;
}
}
if ( $hot_tag > 0 && $req_id > 0 ){
$sql = " SELECT * FROM requisitions_activities WHERE req_id = { $req_id } AND activity_id = { $hot_tag } " ;
$q = $this -> db -> query ( $sql );
if ( $this -> db -> num_rows ( $q ) > 0 ){
$result = true ;
}
}
return $result ;
}
/**
* Объединение по рангу - 1
*/
private function union_closes_req ( $reqs ){
$main_id = 0 ;
$reqs_union = array ();
//Определяем что с чем объединять
if ( ! empty ( $reqs )){
foreach ( $reqs as $req_id ){
$req_main = $this -> get_req_main ( $req_id );
$client_id = ( int ) $req_main [ 'client_id' ];
$who_work = ( int ) $req_main [ 'who_work' ];
//Поиск активной заявки и определение самой старой
$main_id = $this -> get_active_req ( $client_id );
$sql = " SELECT * FROM requisitions WHERE client_id = { $client_id } AND ((deleted = 1 AND confirm = 1) OR (deleted = 0 AND who_work=0 AND confirm=0)) AND cancel = 0 order by created_at desc " ;
//echo $sql."\n";
$q = $this -> db -> query ( $sql , true );
$key = 0 ;
while ( $req = $this -> db -> fetch_assoc ( $q )){
// var_dump($req);
if ( $key == 0 && $main_id == 0 ){
$main_id = ( int ) $req [ 'id' ];
} else {
$reqs_union [] = ( int ) $req [ 'id' ];
}
$key ++ ;
}
}
if ( ! empty ( $reqs_union ) && $main_id > 0 && $who_work > 0 ){
$this -> save_union_reqs ( $reqs_union , $main_id );
} else {
$req_main = $this -> get_req_main ( $reqs [ 0 ]);
$this -> check_mesages ( $req_main , [], 0 );
}
}
}
/**
* Объединение по рангу 0
*/
private function union_general_req ( $reqs ){
$main_id = 0 ;
$reqs_union = array ();
//Определяем что с чем объединять
if ( ! empty ( $reqs )){
foreach ( $reqs as $req_id ){
$req_main = $this -> get_req_main ( $req_id );
$client_id = ( int ) $req_main [ 'client_id' ];
//Поиск активной заявки и определение самой старой
$main_id = $this -> get_active_req ( $client_id );
$sql = " SELECT * FROM requisitions WHERE client_id = { $client_id } AND ((deleted = 1 AND confirm = 1) OR (deleted = 0 AND who_work=0 AND confirm=0)) AND cancel = 0 order by created_at desc " ;
$q = $this -> db -> query ( $sql , true );
$key = 0 ;
while ( $req = $this -> db -> fetch_assoc ( $q )){
if ( $req [ 'who_work' ] == 0 && $req [ 'confirm' ] == 0 && $main_id == 0 ){
$main_id = ( int ) $req [ 'id' ];
} else {
$reqs_union [] = ( int ) $req [ 'id' ];
}
$key ++ ;
}
}
if ( ! empty ( $reqs_union ) && $main_id > 0 ){
$this -> save_union_reqs ( $reqs_union , $main_id );
} else {
$req_main = $this -> get_req_main ( $reqs [ 0 ]);
$this -> check_mesages ( $req_main , [], 0 );
}
}
}
/**
* Объединение по активным
*/
private function union_active_req ( $req_id ){
$main_id = 0 ;
$reqs_union = array ();
$req_main = $this -> get_req_main ( $req_id );
$is_rang_2 = false ;
$is_rang_3 = false ;
$client_id = ( int ) $req_main [ 'client_id' ];
if ( $req_main [ 'who_work' ] == 0 && $req_main [ 'confirm' ] == 0 ){ //Заявка общая объединяем по рангу 0
$this -> union_general_req ( array ( $req_id ));
} else {
//ищем другие по ответственному
$hot_tag = 0 ;
$enter_tag = 0 ;
if ( $this -> agencyId == 19895 ){
$hot_tag = 3039 ;
$enter_tag = 3043 ;
}
else if ( $this -> agencyId == 117 ){
$hot_tag = 3232 ;
$enter_tag = 3233 ;
} else if ( $this -> agencyId == 5238 ){
$hot_tag = 338 ;
}
$main_id = 0 ;
$reqs = array ();
// if($hot_tag > 0){
$sql_hot = " SELECT *, (SELECT activity_id FROM requisitions_activities as ra WHERE ra.req_id = req.id AND activity_id = { $hot_tag } limit 1) as hot_tag " ;
if ( $enter_tag > 0 ){
$sql_hot .= " , (SELECT activity_id FROM requisitions_activities as ra WHERE ra.req_id = req.id AND activity_id = { $enter_tag } limit 1) as enter_tag " ;
}
$sql_hot .= " FROM requisitions as req WHERE client_id = { $client_id } AND who_work = { $req_main [ 'who_work' ] } AND confirm = 1 AND deleted = 0 AND cancel = 0 AND is_manual = 0 order by created_at asc " ;
$q_hot = $this -> db -> query ( $sql_hot , true );
while ( $r_hot = $this -> db -> fetch_assoc ( $q_hot )){
if ( $main_id == 0 && ( $r_hot [ 'hot_tag' ] > 0 || $r_hot [ 'enter_tag' ] > 0 )){
$main_id = ( int ) $r_hot [ 'id' ];
} else {
$reqs [] = ( int ) $r_hot [ 'id' ];
}
}
if ( $main_id > 0 ){ // Общие и удаленные
$sql = " SELECT * FROM requisitions WHERE client_id = { $client_id } AND ((deleted = 1 AND confirm = 1) OR (deleted = 0 AND who_work=0 AND confirm=0)) AND cancel = 0 order by created_at desc " ;
$q = $this -> db -> query ( $sql , true );
while ( $r = $this -> db -> fetch_assoc ( $q )){
$reqs [] = ( int ) $r [ 'id' ];
}
}
if ( $main_id > 0 && ! empty ( $reqs )){
$this -> save_union_reqs ( $reqs , $main_id );
} else {
$req_main = $this -> get_req_main ( $req_id );
$this -> check_mesages ( $req_main , [], 0 );
}
}
}
/**
* Получение чат ид
*/
public function get_caht_id ( $user_id ){
$chat_id = 0 ;
$sql = " SELECT * FROM users WHERE id = { $user_id } " ;
$q = $this -> db -> query ( $sql );
$r = $this -> db -> fetch_assoc ( $q );
if ( $r ) $chat_id = ( int ) $r [ 'telegramm_chat_id' ];
return $chat_id ;
}
/**
* Получение user ид
*/
public function get_user_id_max ( $user_id ){
$user_id = 0 ;
$sql = " SELECT * FROM users WHERE id = { $user_id } " ;
$q = $this -> db -> query ( $sql );
$r = $this -> db -> fetch_assoc ( $q );
if ( $r && $r [ 'max_notice' ] > 0 ) $user_id = ( int ) $r [ 'max_user_id' ];
return $user_id ;
}
/**
* Проверка на дополнительные уведомления
*/
private function check_mesages ( $req_main , $comments , $type = 1 ){
if ( $this -> agencyId == 19895 ){
// file_put_contents(__DIR__.'/log_test_union.txt', date('d.m.Y').' '.$this->agencyId. "\n", FILE_APPEND);
$hot_tag = 0 ;
$enter_tag = 0 ;
if ( $this -> agencyId == 19895 ){
$hot_tag = 3039 ;
$enter_tag = 3043 ;
}
else if ( $this -> agencyId == 117 ){
$hot_tag = 3232 ;
$enter_tag = 3233 ;
} else if ( $this -> agencyId == 5238 ){
$hot_tag = 338 ;
}
$telega = new Telegram ();
$max = new MaxClass ();
if ( $type == 1 ) {
$sql_user = " SELECT * FROM users WHERE id = { $req_main [ 'who_work' ] } " ;
//file_put_contents(__DIR__.'/log_test_union.txt', date('d.m.Y').' '.$sql_user. "\n", FILE_APPEND);
$q_user = $this -> db -> query ( $sql_user );
$r_user = $this -> db -> fetch_assoc ( $q_user );
if ( $r_user [ 'manager' ] != 1 && $r_user [ 'agency' ] != 1 && $r_user [ 'id_manager' ] > 0 ){
$chat_id = $this -> get_caht_id ( $r_user [ 'id_manager' ]);
if ( $chat_id > 0 ){
//$telega = new Telegram();
$fio = $r_user [ 'last_name' ] . ' ' . $r_user [ 'first_name' ] . ' ' . $r_user [ 'middle_name' ];
$text = " К заявке ID { $req_main [ 'id' ] } вашего сотрудника { $fio } автоматически присоединена другая заявка: " ;
$text .= " \n " . str_replace ( " <br> " , " \n " , $comments [ 'text' ]);
try {
$telega -> send ( $text , $chat_id );
} catch ( Exception $e ){
}
//file_put_contents(__DIR__.'/log_test_union.txt', $req_main['id'].' '.$chat_id. ' ' .$text. "\n", FILE_APPEND);
}
$max_user_id = $this -> get_user_id_max ( $r_user [ 'id_manager' ]);
if ( $max_user_id > 0 ){
//$telega = new Telegram();
$fio = $r_user [ 'last_name' ] . ' ' . $r_user [ 'first_name' ] . ' ' . $r_user [ 'middle_name' ];
$text = " К заявке ID { $req_main [ 'id' ] } вашего сотрудника { $fio } автоматически присоединена другая заявка: " ;
$text .= " \n " . str_replace ( " <br> " , " \n " , $comments [ 'text' ]);
try {
$max -> send_messages_to_user ( $max_user_id , $text );
} catch ( Exception $e ){
}
//file_put_contents(__DIR__.'/log_test_union.txt', $req_main['id'].' '.$chat_id. ' ' .$text. "\n", FILE_APPEND);
}
}
} else if ( $type == 2 ) { //Проверка ручной заявки
$chat_id = $this -> get_caht_id ( $this -> agencyId );
if ( $chat_id > 0 ){
//$telega = new Telegram();
if ( $req_main [ 'id' ] > 0 && $req_main [ 'who_work' ] > 0 && $req_main [ 'client_id' ] > 0 ){
$sql = " SELECT *, (SELECT CONCAT(last_name, ' ', first_name, ' ', middle_name) FROM users WHERE requisitions.who_work = users.id) as fio FROM requisitions WHERE client_id= { $req_main [ 'client_id' ] } AND who_work= { $req_main [ 'who_work' ] } AND cancel = 0 AND deleted=0 AND confirm=1 order by id desc limit 1 " ;
$q = $this -> db -> query ( $sql );
if ( $this -> db -> num_rows ( $q )){
$r = $this -> db -> fetch_assoc ( $q );
$text = " Сотрудник " . $r [ 'fio' ] . " создал дубль. ID " . $req_main [ 'id' ];
//file_put_contents(__DIR__.'/log_test_union.txt', date('d.m.Y').' '.$req_main['id'].' '.$chat_id. ' ' .$text. "\n", FILE_APPEND);
try {
$telega -> send ( $text , $chat_id );
} catch ( Exception $e ){
}
}
}
}
$max_user_id = $this -> get_user_id_max ( $this -> agencyId );
if ( $max_user_id > 0 ){
//$telega = new Telegram();
if ( $req_main [ 'id' ] > 0 && $req_main [ 'who_work' ] > 0 && $req_main [ 'client_id' ] > 0 ){
$sql = " SELECT *, (SELECT CONCAT(last_name, ' ', first_name, ' ', middle_name) FROM users WHERE requisitions.who_work = users.id) as fio FROM requisitions WHERE client_id= { $req_main [ 'client_id' ] } AND who_work= { $req_main [ 'who_work' ] } AND cancel = 0 AND deleted=0 AND confirm=1 order by id desc limit 1 " ;
$q = $this -> db -> query ( $sql );
if ( $this -> db -> num_rows ( $q )){
$r = $this -> db -> fetch_assoc ( $q );
$text = " Сотрудник " . $r [ 'fio' ] . " создал дубль. ID " . $req_main [ 'id' ];
//file_put_contents(__DIR__.'/log_test_union.txt', date('d.m.Y').' '.$req_main['id'].' '.$chat_id. ' ' .$text. "\n", FILE_APPEND);
try {
$max -> send_messages_to_user ( $max_user_id , $text );
} catch ( Exception $e ){
}
}
}
}
}
//Проверка дублей горячих и входящих
$chat_id = $this -> get_caht_id ( $this -> agencyId );
$max_user_id = $this -> get_user_id_max ( $this -> agencyId );
$reqs_duble = array ();
$reqs_duble_hot = array ();
$who_work_double = array ();
$is_hot = false ;
if ( $chat_id > 0 || $max_user_id > 0 ){
$sql_hot = " SELECT *, (SELECT activity_id FROM requisitions_activities as ra WHERE ra.req_id = req.id AND activity_id = { $hot_tag } limit 1) as hot_tag " ;
if ( $enter_tag > 0 ){
$sql_hot .= " , (SELECT activity_id FROM requisitions_activities as ra WHERE ra.req_id = req.id AND activity_id = { $enter_tag } limit 1) as enter_tag " ;
}
$sql_hot .= " FROM requisitions as req WHERE client_id = { $req_main [ 'client_id' ] } AND confirm = 1 AND deleted = 0 AND cancel = 0 order by created_at asc " ;
//file_put_contents(__DIR__.'/log_test_union.txt', date('d.m.Y').' '.$sql_hot. "\n", FILE_APPEND);
$q_hot = $this -> db -> query ( $sql_hot , true );
while ( $r_hot = $this -> db -> fetch_assoc ( $q_hot )){
if (( $r_hot [ 'hot_tag' ] > 0 )){
$reqs_duble_hot [] = $r_hot [ 'id' ];
$reqs_duble [] = $r_hot [ 'id' ];
} else if ( $r_hot [ 'enter_tag' ] > 0 ){
$reqs_duble [] = $r_hot [ 'id' ];
}
}
if ( count ( $reqs_duble_hot ) > 1 ){
$text = " Найден дубль «Горячих» заявок у разных сотрудников: \n " ;
$text .= " ID " . implode ( " , ID " , $reqs_duble_hot );
if ( $chat_id > 0 ){
try {
$telega -> send ( $text , $chat_id );
} catch ( Exception $e ){
}
}
if ( $max_user_id > 0 ){
try {
$max -> send_messages_to_user ( $max_user_id , $text );
} catch ( Exception $e ){
}
}
}
if ( count ( $reqs_duble ) > 1 && count ( $reqs_duble ) > count ( $reqs_duble_hot )){
$text = " Найден дубль заявок у разных сотрудников: \n " ;
$text .= " ID " . implode ( " , ID " , $reqs_duble );
if ( $chat_id > 0 ){
try {
$telega -> send ( $text , $chat_id );
} catch ( Exception $e ){
}
}
if ( $max_user_id > 0 ){
try {
$max -> send_messages_to_user ( $max_user_id , $text );
} catch ( Exception $e ){
}
}
}
}
}
}
2026-06-20 10:19:54 +02:00
public function getRequisitionsByStage ( $stageId , $funnelId = 0 , $search = '' , $period = '' , $responsible = [], $offset = 0 , $limit = 20 ) {
$sql = " SELECT r.* FROM requisitions r
WHERE r . stage = ? AND r . deleted = 0 " ;
if ( $funnelId > 0 ) {
$sql .= " AND r.funnel_id = ? " ;
}
if ( ! empty ( $search )) {
$sql .= " AND (r.fio LIKE ? OR r.phone LIKE ?) " ;
}
if ( ! empty ( $period )) {
// добавьте свою логику по периоду
}
if ( ! empty ( $responsible )) {
$placeholders = str_repeat ( '?,' , count ( $responsible ) - 1 ) . '?' ;
$sql .= " AND r.users_id IN ( $placeholders ) " ;
}
$sql .= " ORDER BY r.id DESC LIMIT ? OFFSET ? " ;
$params = [ $stageId ];
if ( $funnelId > 0 ) $params [] = $funnelId ;
if ( ! empty ( $search )) {
$like = '%' . $search . '%' ;
$params [] = $like ;
$params [] = $like ;
}
if ( ! empty ( $responsible )) {
foreach ( $responsible as $uid ) {
$params [] = ( int ) $uid ;
}
}
$params [] = $limit ;
$params [] = $offset ;
$stmt = $this -> pdo -> prepare ( $sql );
$stmt -> execute ( $params );
return [
'items' => $stmt -> fetchAll ( PDO :: FETCH_ASSOC )
];
}
2026-05-22 20:21:54 +02:00
}
2026-06-20 10:19:54 +02:00
// Базовый тип: 1=Подбор, 2=Реализация, 3=Другие услуги, 4=Спрос. heir != 0 — кастомный наследник.
function requisition_base_type_id ( $typeRow ) {
$heir = isset ( $typeRow [ 'heir' ]) ? ( int ) $typeRow [ 'heir' ] : 0 ;
if ( $heir !== 0 ) {
return $heir ;
}
return ( int ) $typeRow [ 'id' ];
}
// object_id копируется только для типов 3 и 4.
function requisition_should_copy_object ( $baseTypeId ) {
return in_array (( int ) $baseTypeId , [ 3 , 4 ], true );
}
// Фильтры поиска копируются для всех типов кроме 1 (Подбор).
function requisition_should_copy_search_filters ( $baseTypeId ) {
return ( int ) $baseTypeId !== 1 ;
}
2026-05-22 20:21:54 +02:00
?>