diff --git a/engine/classes/Requisitions.php b/engine/classes/Requisitions.php
index 3a3c772..6cf946a 100644
--- a/engine/classes/Requisitions.php
+++ b/engine/classes/Requisitions.php
@@ -4,7 +4,7 @@
*
* @author iren
*/
- class Requisitions{
+class Requisitions{
private $user;
private $roles_user = ['AGENCY', 'AGENT', 'MANAGER'];
private $role_user;
@@ -19,29 +19,29 @@
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'),
- );
+ 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($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);
}
@@ -102,51 +102,71 @@
$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']);
+ $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";
- }*/
+ /* 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($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);
+ $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']];
+ 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;
}
- $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){
+ $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']);
@@ -154,36 +174,16 @@
$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']);
}
- 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"]);
@@ -196,8 +196,8 @@
}
}
}
- // usort($result['type_archive'], "cmp");
- // $result['type'][] = array('code'=>'group'.$type['id'], 'type'=>'group', 'order'=>99, 'heir'=>0, 'name'=>'testG', 'agency_id'=>4135);
+ // 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']);
@@ -205,15 +205,15 @@
return $result;
}
- static function cmp($a, $b) {
- return strnatcmp($a["order"], $b["order"]);
- }
+ 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";
+ $sql = "SELECT * FROM denial_work WHERE agency_id = {$this->agencyId} AND del = 0";
}
if($default > 0){
$sql .= " AND default_val = 0";
@@ -275,8 +275,8 @@
//Редактирование/добавление типа договора
public function editAddType($type_id, $type, $heir, $order, $type_type){
- if($type_id == 0){
- $sql_in = "INSERT INTO requisitions_type SET
+ if($type_id == 0){
+ $sql_in = "INSERT INTO requisitions_type SET
agency_id = {$this->agencyId},
name = '{$type}',
heir = {$heir},
@@ -284,27 +284,27 @@
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());
+ if(!$this->db->query($sql_in)){
+ 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
+ } 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}',
@@ -314,39 +314,39 @@
created_at = NOW(),
created_by = {$this->user_id}";
- if(!$this->db->query($sql_in)){
- return array('source'=>'error', 'mes'=>$this->db->errorInfo());
+ 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');
- }
- }
+ /*$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)){
+ $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 {
- return array('source'=>'done');
- }
- } /*else if ($r['agency_id'] == 0) { //общий тип
+ } 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']}',
@@ -360,28 +360,28 @@
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)){
+ $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 {
- return array('source'=>'done');
- }
- } /*else if ($r['agency_id'] == 0) { //общий тип
+ } 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']}',
@@ -395,7 +395,7 @@
return array('source'=>'done');
}
}*/
- }
+ }
}
@@ -408,13 +408,13 @@
} 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');
- }
+ $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},
@@ -461,7 +461,7 @@
$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;
+ // echo $sql_in;
$this->db->query($sql_in);
}
@@ -479,7 +479,7 @@
$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;
+ // echo $sql_in;
$this->db->query($sql_in);
}
}
@@ -524,7 +524,7 @@
public function get_who($who_work, $req_id, $kanban, $departments, $usersToUse = []){
$master_work = '';
- $master_phone = null;
+ $master_phone = null;
$master_work_fio = '';
if ((int)$who_work > 0) {
@@ -585,7 +585,7 @@
public function get_who_delete($who_delete, $req_id, $kanban, $departments, $usersToUse = []){
$master_delete = '';
- $master_phone = null;
+ $master_phone = null;
if ((int)$who_delete > 0) {
@@ -596,7 +596,7 @@
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'];
+ $master_phone = $mstr['phone'];
if($kanban) {
$master_delete = trim($mstr['last_name'] . ' ' . $mstr['first_name'] . ' ' . $mstr['middle_name']);
@@ -637,7 +637,7 @@
}
- return ['id' => $who_delete, 'name' => strip_tags($master_delete), 'phone' => $master_phone];
+ return ['id' => $who_delete, 'name' => strip_tags($master_delete), 'phone' => $master_phone];
}
//Общее по одной заявке для канбана
@@ -677,7 +677,7 @@
} 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;
@@ -702,13 +702,13 @@
$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;
+ $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;
+ // Если заявка из общих
+ 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;
@@ -749,19 +749,19 @@
}
- /*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 ($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);
@@ -770,7 +770,7 @@
$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['steps'] = $this->get_class_etap($r['id'], $r['funnel_id'], $r['stage']);
$r['object'] = array();
$r['client'] = array();
$r['union_req'] = array();
@@ -814,7 +814,7 @@
}
if($r['activities_name'] != '') $r['activities_name'] .= ", ";
$r['activities_name'] .= $r_a_name['name'];
-
+
}
if($tv < count($r['activities'])){
@@ -845,20 +845,20 @@
'show' => ['label' => 'Показ', 'bg' => '#fff9c4', 'text' => '#f9a825'],
'meet' => ['label' => 'Встреча', 'bg' => '#f3e4f5', 'text' => '#7c1fa3']
];
-
+
$type = $row['type'];
// Унифицировано с датой заявки: DD.MM.YYYY HH:MM.
$scheduleDate = date('d.m.Y H:i', strtotime($row['schedule_date']));
$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'] : '',
@@ -867,7 +867,7 @@
'bgColor' => isset($bgColor) ? $bgColor : '',
'textColor' => isset($textColor) ? $textColor : ''
];
-
+
}
}
$r['is_deal'] = !empty($r['deal_id']) && $r['deal_id'] > 0 ? 1 : 0;
@@ -879,9 +879,9 @@
//Общее по одной заявке
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);
-
+ //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;
@@ -914,18 +914,18 @@
}
$r['can_edit'] = 0;
if($r['who_work'] == $this->user->id){
- $r['can_edit'] = 1;
+ $r['can_edit'] = 1;
} else if($this->user->agency > 0 || $_SESSION['users_admin'] > 0){
- $r['can_edit'] = 1;
+ $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) {
@@ -938,21 +938,21 @@
$r['is_deal'] = !empty($r['deal_id']) && $r['deal_id'] > 0 ? 1 : 0;
- $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;
+ $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->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 (!$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'])) {
@@ -1032,14 +1032,14 @@
$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['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']);
@@ -1051,10 +1051,10 @@
$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;
+ // Don`t remove (!)
+ $r['autosearch'] = array('error' => [], 'filter' => []);
+ $r['autosearch_id'] = null;
+ $r['autosearch_info'] = null;
//Теги
$r['activities'] = array() ;
@@ -1077,7 +1077,7 @@
}
if($r['activities_name'] != '') $r['activities_name'] .= ", ";
$r['activities_name'] .= $r_a_name['name'];
-
+
}
if($tv < count($r['activities'])){
@@ -1089,12 +1089,12 @@
$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']);
+ $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;
@@ -1132,19 +1132,19 @@
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();
+ $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);
+ $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);
@@ -1156,7 +1156,7 @@
- $r['who_work_id_manager'] = $who_work_id_manager['id_manager'];
+ $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)
@@ -1215,11 +1215,11 @@
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'];
+ $r['master_delete_id'] = $master_delete['id'];
+ $r['master_delete'] = $master_delete['name'];
+ $r['master_delete_phone'] = $master_delete['phone'];
- if ($r['confirm'] == 10) {
+ if ($r['confirm'] == 10) {
$r['reason'] = "Совершена сделка на ".$r['summa']." руб.";
}
}
@@ -1271,7 +1271,7 @@
} else {
$r['source_name'] = $r_source['source'];
$source = $r_source['source'];
-
+
}
}
}
@@ -1286,13 +1286,13 @@
$r['source_name'] .= ($partner) ? ((isset($source)) ? " | " : '') . $partner['name'] . ((!empty($partner['resident'])) ? ' (' . $partner['resident']. ')' : '') : '';
- $r['employe_name'] = null;
- if (isset($partner['fullname']))
- $r['employe_name'] = $partner['fullname'];
+ $r['employe_name'] = null;
+ if (isset($partner['fullname']))
+ $r['employe_name'] = $partner['fullname'];
- if(!empty($partner['position'])){
- $r['employe_name'] .= ", ".$partner['position'];
- }
+ if(!empty($partner['position'])){
+ $r['employe_name'] .= ", ".$partner['position'];
+ }
//Название воронки
if($r['funnel_id'] == 0){
@@ -1333,18 +1333,18 @@
$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}";
-
+ AND `object_id` = {$w_object_id}";
+
$watch_query =$this->db->query($watch_sql);
$watch_result = $this->db->fetch_assoc($watch_query);
if ($watch_result) {
@@ -1356,61 +1356,61 @@
- if ($filter = $this->autosearch_instce->getFilterByReq($r['id'], $_SESSION['id'], false, false, true)) {
+ 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']
- ];
+ 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 = '';
+ $comment = '';
- $info_ar = $this->autosearch_instce->getFilterInfo($filter, true, true);
+ $info_ar = $this->autosearch_instce->getFilterInfo($filter, true, true);
- foreach ($info_ar as $key => $filter) {
+ foreach ($info_ar as $key => $filter) {
- if (isset($filter['label']) && isset($filter['value'])) {
- if ($key === "comment")
- $comment = '' . $filter['label'] . ': ' . $filter['value'];
- else
- $info .= ' ' . $filter['label'] . ': ' . $filter['value'] . ';';
- }
+ if (isset($filter['label']) && isset($filter['value'])) {
+ if ($key === "comment")
+ $comment = '' . $filter['label'] . ': ' . $filter['value'];
+ else
+ $info .= ' ' . $filter['label'] . ': ' . $filter['value'] . ';';
+ }
- $r['autosearch']['filter'][$key] = [
- 'id' => $filter['id'],
- 'label' => $filter['label'],
- 'value' => $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));
+ 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 уточнений'])
- ];
+ $r['autosearch']['filter']['geo'] = [
+ 'id' => 'geo',
+ 'label' => 'Гео',
+ 'value' => declOfNum(count($geo), ['%d уточнение', '%d уточнения', '%d уточнений'])
+ ];
- $info .= ' Гео: ' . declOfNum(count($geo), ['%d уточнение', '%d уточнения', '%d уточнений']). ';';
- }
+ $info .= ' Гео: ' . declOfNum(count($geo), ['%d уточнение', '%d уточнения', '%d уточнений']). ';';
+ }
- if (!empty($info)) {
- $r['autosearch_info'] = rtrim(trim($info), ';');
- $r['autosearch_comment'] = trim($comment) ."
". 'ID фильтра: ' . $r['autosearch_id'];
- }
- }
- }
+ if (!empty($info)) {
+ $r['autosearch_info'] = rtrim(trim($info), ';');
+ $r['autosearch_comment'] = trim($comment) ."
". 'ID фильтра: ' . $r['autosearch_id'];
+ }
+ }
+ }
}
@@ -1459,7 +1459,7 @@
$lostDate = $r['created_at'];
$interval = date_diff(new DateTime(), new DateTime($lostDate))->days;
if($interval > $days_step){
- $expiredStagesRequisitions[] = $r['id'];
+ $expiredStagesRequisitions[] = $r['id'];
}
}
}
@@ -1475,42 +1475,42 @@
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 = '
+ $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)){
+ $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)){
+
+
+ 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
@@ -1527,13 +1527,13 @@
$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,
+ } 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,
@@ -1543,8 +1543,8 @@
'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,
+ //$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,
@@ -1555,36 +1555,36 @@
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)";
+
+ $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);
+ }
+ }
+ 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){
+ 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){
+ if($reqs_id){
unset($sqlPart1);
unset($sqlPart2);
if(!empty($reqs_id)){
@@ -1594,72 +1594,72 @@
$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=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'];
- }
+ if(!empty($filtr)){
- $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)){
+
+ 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();
@@ -1677,82 +1677,82 @@
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'){
+
+ 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;
@@ -1767,38 +1767,38 @@
$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'){
+ } 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;
@@ -1812,103 +1812,103 @@
$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[] = 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){
+ }
+ 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).")";
+ }
+ $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)){
+ 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 .= ")";
+ $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(!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";
+ $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";
+ $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).")";
+ // $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)";
}
@@ -1942,125 +1942,125 @@
$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
+ 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
+ // "Без задач"
+ 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
+ // "Задачи на сегодня"
+ 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
+ // "Просроченные задачи"
+ 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(!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(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;
- }
+ 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);
@@ -2069,21 +2069,21 @@
$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 ){
+ }
+
+ $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";
@@ -2094,43 +2094,43 @@
$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";
+ } 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){
+
+ $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){
@@ -2158,129 +2158,129 @@
}
}
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).")";
+ $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";
- }
+ }
+
+ 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";
+ }
+
+ 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";
+ }
+
+ if(isset($filtr->expired_stages) && $filtr->expired_stages > 0){
+ $expired_stages = 1;
+ }
- 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";
- }
-
- 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);
- }
- }
+ } else {
- if(isset($filtr->transmitted)){
+ 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";
+ $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";
- }
+ and events_clients.user_id=".$user." and events_clients.date $date_between and req_id=req.id) > 0";
+ }
- if(isset($filtr->accepted)){
+ 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";
+ $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){
+ 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){
@@ -2290,34 +2290,34 @@
}
$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))))";
+ $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";
+ $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
+ $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
+ $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
+ $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();
- }
+ (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 = [];
+ $userIds = [];
$wh = new WebHookIn();
$allUsersIds = array();
if($agencyId > 0){
@@ -2328,121 +2328,121 @@
$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))))";
- */
+ /*$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'];
+ if (($depUser['role'] == 'manager_office' || $depUser['role'] == 'admin_department') && (int)$depUser['admin'] > 0 && !$is_stats ) {
+ $admin = (int)$depUser['admin'];
- $userIds = array();
- $doerIds = array();
- $doerSql = '';
+ $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 = 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 = " . $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'];
- }
+ }
+ 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 (count($doerIds) > 0 ) {
+ $doerSql = " or (req.id in (" . implode(", ", $doerIds) . "))";
+ }
- if($is_stats){
+ 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 {
-
+ } 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'];
+ }
+ } 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 = '';
+ $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 = 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 = " . $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'];
- }
+ }
+ 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 (count($doerIds) > 0) {
+ $doerSql = " or (req.id in (" . implode(", ", $doerIds) . "))";
+ }
- if($is_stats){
+ 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 {
+ } 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%')";*/
+ }
+ } 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 = '';
+ $userIds = array();
+ $doerIds = array();
+ $doerSql = '';
- $query = mysql_query("select id from users where id=$user or id_manager=$user or id_manager in
+ $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'];
- }
+ 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");
+ $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'];
- }
+ }
+ 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 (count($doerIds) > 0) {
+ $doerSql = " or (req.id in (" . implode(", ", $doerIds) . "))";
+ }
- if($is_stats){
+ if($is_stats){
$where .= " AND ((who_work = $user))";
$wherePart1 .= " AND ((req.who_work = $user))";
$wherePart2 .= " AND ((a.who_work = $user))";
- } else {
+ } else {
$n_user_id = $_SESSION['agency_id'];
$n_agents = "SELECT id FROM users
WHERE id IN (
@@ -2465,7 +2465,7 @@
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'];
@@ -2486,115 +2486,115 @@
$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($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;
- if(isset($sqlExpectedCommissionTotalPart1) && isset($sqlExpectedCommissionTotalPart2)){
+ $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){
+ }
+ }
+
+
+
+ $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 ';
- }
- }
+ } else {
+ $order = 'desc';
+ }
- $result['filtr'] = $filtr->date_closer;
-
- $_SESSION['where_req_campaigns_order'] = $part_order.$order;
-
- if($this->view != 'kanban'){
- if(isset($sqlPart1) && isset($sqlPart2)){
+ 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;
-
+ $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'){
+
+ $typesReq = $this->get_type();
+
+ $this->funnels_adjacent = array();
+
+ if($this->view == 'kanban'){
$depClass = new Department;
$departments = $depClass->getDepartments();
@@ -2609,7 +2609,7 @@
}
//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";
@@ -2625,10 +2625,10 @@
$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)){
@@ -2644,12 +2644,12 @@
/* $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;
- }*/
+ /* if($_SESSION['id'] == 14050){
+ echo $sql_count_step;
+ }*/
//echo $sql_count_step;
$q_count_step = $this->db->query($sql_count_step);
@@ -2658,16 +2658,16 @@
$complex_room_ids = array();
$reqIds = array();
$requisitionData = array();
- // $start = microtime(true);
+ // $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";
+ /* 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 = '';*/
+ }
+ $sql2_new = '';*/
if(!isset($arrayCountSteps)){
$arrayCountSteps = array();
while($r_count_step = $this->db->fetch_assoc($q_count_step)){
@@ -2675,29 +2675,29 @@
$arrayCountSteps[$r_count_step['stage']] += (int)$r_count_step['total'];
}
}
- /* if($_SESSION['id'] == 14050){
- var_dump($arrayCountSteps);
- }*/
+ /* 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)";*/
+ // $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";
@@ -2728,9 +2728,9 @@
}
}
- /* if($_SESSION['id'] == 14050){
- echo $sql_2;
- }*/
+ /* if($_SESSION['id'] == 14050){
+ echo $sql_2;
+ }*/
$q = $this->db->query($sql_2);
@@ -2772,7 +2772,7 @@
$objectIds[] = $r['object_id'];
}
}
- $num_step++;
+ $num_step++;
}
}
$sqls2[] = $sql_2;
@@ -2831,19 +2831,19 @@
$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']]++;
- }
+ $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);
@@ -2851,15 +2851,15 @@
}*/
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);
- }
+ 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();
+ $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'];
@@ -2870,8 +2870,8 @@
$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();
@@ -2908,10 +2908,10 @@
$expenses_total[$expense['req_id']] += $expense['amount'];
}
-
+
}
}
-
+
foreach ($requisitionData as $r) {
if (should_hide_contacts_for_current_user()) {
@@ -2928,7 +2928,7 @@
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){
@@ -2949,25 +2949,25 @@
$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'][$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);
- }
+ 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;
@@ -2986,7 +2986,7 @@
}
}
- else {
+ else {
$result['req'] = array();
// Фильтр по ценам и бюджету автопоиска в зависимости от типа
@@ -3012,7 +3012,7 @@
break;
}
}
-
+
if($hasPodborType || $hasSprosType) {
if($from = intval($filtr->priceFrom)) {
$priceFromReq = '';
@@ -3039,7 +3039,7 @@
}
}
}
-
+
if (!empty($priceWhere)) {
$sql = str_replace('WHERE', 'WHERE ' . $priceWhere, $sql);
$sqlTotal = str_replace('WHERE', 'WHERE ' . $priceWhere, $sqlTotal);
@@ -3097,7 +3097,7 @@
//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;
@@ -3116,18 +3116,18 @@
}
- /* if($_SESSION['id'] == 5238){
- var_dump($this->funnels_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);
- }*/
+ /* if($_SESSION['id'] == 5238){
+ var_dump($typesContracs);
+ }*/
//Количество присоединенных заявок
$totalUnion = array();
@@ -3136,73 +3136,73 @@
$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']]++;
+ $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;
+ /**
+ * Финансы
+ * */
+ 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'];
+
}
- $expenses_req = array();
- $expenses = array();
-
- $expenses_total = array();
+ 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)){
- $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){
+ $pole_end_list = json_decode(htmlspecialchars_decode($r_step['pole_end_list']), true);
- $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($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($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();
@@ -3245,7 +3245,7 @@
}
if(isset($totalUnion[$requisition['id']])){
- $result['req']['req'.$requisition['id']]['union_total'] = $totalUnion[$requisition['id']];
+ $result['req']['req'.$requisition['id']]['union_total'] = $totalUnion[$requisition['id']];
} else {
$result['req']['req'.$requisition['id']]['union_total'] = 0;
}
@@ -3288,7 +3288,7 @@
$result['allPages'] = ceil($result['total_req']/$this->limit);
-
+
$result['activities'] = $arrActivities;
$result['activities_name'] = $arrActivitiesName;
}
@@ -3394,19 +3394,19 @@
$req_ids = array();
$req_ids_temp = array();
if(!empty($fieldsPod)){
- $ids = array();
+ $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;
- }
+ foreach ($arrVal as $val) {
+ if(!in_array($val, $values))
+ $values[] = $val;
+ }
} else {
- if(!in_array($fi['value'], $values))
- $values[] = $fi['value'];
+ 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).")";
@@ -3423,13 +3423,13 @@
$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;
- }
+ foreach ($arrVal as $val) {
+ if(!in_array($val, $values))
+ $values[] = $val;
+ }
} else {
- if(!in_array($fi['value'], $values))
- $values[] = $fi['value'];
+ 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).")";
@@ -3481,17 +3481,17 @@
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).")";
@@ -3548,7 +3548,7 @@
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);
@@ -3568,7 +3568,7 @@
if(in_array($user_id, $arrNoSeeUsers)){
$is_see = true;
}
-
+
}
if(!$is_see) continue;
@@ -3628,7 +3628,7 @@
// Заявка(ки) по status
public function getReqAndWhoWorkByStatusId($status_id, $is_interrupted = 0, $where_is_interrupted = true, $er_is_interrupted = 0, $where_er_is_interrupted = false)
{
- $result = [];
+ $result = [];
$sql = "SELECT
req.*,
@@ -3664,38 +3664,38 @@
// Заявка(ки) по id
public function get_req_id($req_id, $needAutoSearch = false, $is_kanban = false) {
- $result = [];
+ $result = [];
$typesReq = [];//$this->get_type();
if($this->agencyId > 0){
$typesReq = $this->get_type();
}
- if (is_array($req_id)) {
+ if (is_array($req_id)) {
- $sql = "SELECT
+ $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);
+ $q = $this->db->query($sql);
- while ($r = $this->db->fetch_assoc($q))
+ while ($r = $this->db->fetch_assoc($q))
{
-
+
$result['req' . $r['id']] = $this->get_req_details($r, false, [], [], [], $typesReq, [], $needAutoSearch);
- }
- } else {
-
- $sql = "SELECT
+ }
+ } 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);
+ $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);
@@ -3710,67 +3710,67 @@
}
/**
- * Финансы
- * */
-
- $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){
+ $deposits = array();
+ $depositArr = array();
+ $sql_deposit = "SELECT * FROM deposits_clients_req WHERE req_id = $req_id";
- $steps_ids = array();
- $steps = array();
- while($r_ex = $this->db->fetch_assoc($q_ex)){
- $expenses[] = $r_ex;
- $steps_ids[] = (int)$r_ex['step_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();
- 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)){
+ $expenses_total = array();
+ $sql_ex = "SELECT * FROM expenses_req WHERE req_id = $req_id";
+ $q_ex = $this->db->query($sql_ex);
- $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'];
- }
- }
+ 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'];
- }
-
-
}
+ }
+
+ 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();
@@ -3790,11 +3790,11 @@
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)){
@@ -3823,26 +3823,26 @@
$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['req' . $r['id']] = $this->get_req_details($r, false, [], [], [], $typesReq, [], $needAutoSearch);
}
- }
+ }
$result['is_kanban'] =$is_kanban;
$result['e'] = $events_res;
- return $result;
+ return $result;
}
- //Добавление/редактирование заявки
- public function add_edit($params) {
+ //Добавление/редактирование заявки
+ public function add_edit($params) {
- /* if($_SESSION['id'] == 22111){
- error_reporting(E_ALL | E_STRICT);
- ini_set('display_errors', 1);
- }*/
+ /* 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'])){
+ $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);
@@ -3851,113 +3851,113 @@
$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']]);
- }
+ 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);
+ //$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'];
+ $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'];
- }
+ // Исключаем текущую заявку при редактировании
+ 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 .= " AND type_id = " . (int)$params['type_id'] . " AND deleted=0 AND cancel=0 ";
- $sql_check_exist_object_in_req .= " LIMIT 1";
+ $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);
+ $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 (!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']."»";
- }
+ if (isset($search[$firstKey]['name'])) {
+ $res['mes'] .= " «".$search[$firstKey]['name']."»";
+ }
- return $res;
- }
- }
+ return $res;
+ }
+ }
- if ($hasSave) {
- $activities = htmlspecialchars(json_encode($params['activities']));
+ 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) {
+ 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)
- );
+ $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']);
+ 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) {
+ $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';*/
+ /*$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();
- }
- }
- }
+ $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 = 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_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);
+ $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;
+ $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 = 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;
+ $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)
+ $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]',
@@ -3976,7 +3976,7 @@
`complex_status_id` = '$params[status]',
complex_room_id = $complex_room_id,
friend_client_id = $friend_client_id,
- confirm_recommendation = $confirm_recommendation";
+ confirm_recommendation = $confirm_recommendation";
//Если передача в общие то восстанавливаем заявку
if($params['who_work'] == 0 && $params['confirm'] == 0){
$is_general = true;
@@ -3984,8 +3984,8 @@
$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]'";
@@ -4005,28 +4005,28 @@
}
- $new_req = false;
- $req_id = 0;
- if (!$this->db->query($in_sql))
- $errors[] = $this->db->errorInfo();
+ $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){
+ 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);
- }
+ }
+ } 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){
+ if(isset($params['newClientName']) && !empty($params['newClientName']) && $req_id > 0){
$client_id = (int)$params['client_id'];
if($client_id > 0){
$sql = "UPDATE `clients` SET
@@ -4039,97 +4039,97 @@
$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 (!isset($params['add_obj'])) {
- //Теги
- if ($req_id > 0) {
+ //Теги
+ if ($req_id > 0) {
- if (!$this->db->query("DELETE FROM requisitions_activities WHERE req_id = {$req_id}"))
- $errors[] = $this->db->errorInfo();
+ if (!$this->db->query("DELETE FROM requisitions_activities WHERE req_id = {$req_id}"))
+ $errors[] = $this->db->errorInfo();
- foreach($params['activities'] as $a) {
+ foreach($params['activities'] as $a) {
- $sql_in = "INSERT INTO requisitions_activities SET req_id = {$req_id}, activity_id={$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 (!$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['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']) {
+ //Добавляем событие передачи
+ 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);
- }
+ $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')";
+ //$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 (!$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)) {
+ 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));
+ $obj = htmlentities(json_encode($objectArr));
- $up_client = "UPDATE clients SET objects='$obj' where id = $params[client_id]";
+ $up_client = "UPDATE clients SET objects='$obj' where id = $params[client_id]";
- if (!$this->db->query($up_client))
- $errors[] = $this->db->errorInfo();
+ 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'];
+ // Сохранение данных предварительной оценки
+ 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` (
+
+ $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`,
@@ -4145,28 +4145,28 @@
'$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();
+ }
+ } 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();
- }
- }
- }
+ 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)){
+ //Поля которые может редактировать сотрудник
+ $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);
@@ -4189,10 +4189,10 @@
} else {
$fields_can_edid[] = (int)$r_fields['id'];
}
- }
+ }
- //Кастомные поля
- if(!empty($fields_can_edid)){
+ //Кастомные поля
+ 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))
@@ -4209,10 +4209,10 @@
$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'";
+ " req_id=$req_id, ".
+ " field_id=$field_id, ".
+ " type=$typeField, ".
+ " value='$value'";
if (!$this->db->query($sql_in))
$errors[] = $this->db->errorInfo();
@@ -4221,103 +4221,103 @@
}
}
- 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 ($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 (!$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']) {
+ if ($params['object_id'] > 0 && ($params['type_id'] == 2 || $parentType == 2)){
+ $this->contractInObject($req_id, $params['object_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
+ 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
- $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);
+ $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'];
- $client_id = (int)$params['client_id'];
- $agency_id = User::getUserAgencyID();
+ //связываем заявку с чатом 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);
- $wazzap = new Wazzap($agency_id, $this->db);
+ $client_id = (int)$params['client_id'];
+ $agency_id = User::getUserAgencyID();
- //проверяем, передавался ли клиент в 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 = new Wazzap($agency_id, $this->db);
- //связываем клиента с чатом 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
+ $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
- $wazzap->createWazzapContact($client_id, $wazzap_user_id, $r_cl_fio["fio"], $wazzap_chat_type, $wazzap_chat_id);
- }
+ //связываем клиента с чатом 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);
- $name = $params['name'];
- if (mb_strlen($name) > 200) {
- $name = mb_substr($name, 0, 195);
- }
+ //создаем его в wazzap
+ $wazzap->createWazzapContact($client_id, $wazzap_user_id, $r_cl_fio["fio"], $wazzap_chat_type, $wazzap_chat_id);
+ }
- //создаем сделку в wazzap
- $wazzap->createWazzapDeal($req_id, $wazzap_user_id, $name, $client_id);
- }
+ $name = $params['name'];
+ if (mb_strlen($name) > 200) {
+ $name = mb_substr($name, 0, 195);
+ }
- if(!isset($agency_id)){
+ //создаем сделку в 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){
+ if($agency_id == 13154){
$w = new WebHookSend($agency_id, 2, $req_id, 'req');
- }
- }
- }
+ }
+ }
+ }
- if (!empty($errors)){
+ if (!empty($errors)){
$result['error'] = $errors;
- return $result;
- }
+ return $result;
+ }
- return $req_id;
- }
- }
+ return $req_id;
+ }
+ }
// Копирование заявки в одной транзакции. Возвращает [success, id, error, code].
public function copy($srcId, $funnelId, $whoWorkId, $currentUserId) {
@@ -4678,7 +4678,7 @@
//Изменение воронки
public function updateFunnel($funnel_id, $req_id) {
- $errors = [];
+ $errors = [];
$sqlSelFun = "select funnel_id from requisitions WHERE id=$req_id";
$resSelFun = $this->db->query($sqlSelFun);
$rowSelFun = $this->db->fetch_assoc($resSelFun);
@@ -4697,76 +4697,76 @@
$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();
- }
+ 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();
- }
+ 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 (!$this->db->query($sql_conf)) {
+ if ($this->db->errorInfo())
+ $errors[] = $this->db->errorInfo();
+ }
}
- if (count($errors))
- return $errors;
- else
- return true;
+ if (count($errors))
+ return $errors;
+ else
+ return true;
}
- //
+ //
public function updateReq($req_id = [], $client_id = null, $object_id = null) {
- $errors = [];
+ $errors = [];
- if (!empty($req_id)) {
+ if (!empty($req_id)) {
- if (!is_array($req_id))
- $req_id = [$req_id];
+ if (!is_array($req_id))
+ $req_id = [$req_id];
- if (is_null($client_id))
- $client_id = 'NULL';
+ if (is_null($client_id))
+ $client_id = 'NULL';
- if (is_null($object_id))
- $object_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']);
- }*/
+ /* $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
+ 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 (!$this->db->query($sql)) {
+ $errors[] = $this->db->errorInfo();
+ }
+ }
- }
+ }
- if (count($errors))
- return [
- 'success' => false,
- 'errors' => $errors,
- ];
- else
- return [
- 'success' => true
- ];
+ if (count($errors))
+ return [
+ 'success' => false,
+ 'errors' => $errors,
+ ];
+ else
+ return [
+ 'success' => true
+ ];
}
//Закрытие заявки
@@ -4775,28 +4775,28 @@
$errors = [];
$dop_text = "";
$select_text = "";
- $is_deal = false;
+ $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");
+ // При закрытии отказом (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 );
+ $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']){
@@ -4806,29 +4806,29 @@
$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);
- }
+ $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;
+ $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();
+ 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;
+ $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();
+ if (!$this->db->query("UPDATE step_notify_closure SET text='{$text}', send=0 WHERE temp_id = {$post['tempid']}"))
+ $errors[] = $this->db->errorInfo();
}
}
@@ -4836,7 +4836,8 @@
$sql = "SELECT * FROM `requisitions` WHERE id = $id";
$requisistion = $this->db->fetch_assoc($this->db->query($sql));
- // Вычисляем последний этап воронки
+
+ // последний этап воронки
$lastStage = 8; // значение по умолчанию
$funnelId = intval($requisistion['funnel_id']);
if ($funnelId > 0) {
@@ -4848,7 +4849,7 @@
}
}
} else {
- // funnel_id = 0 — дефолтная воронка, берём по agency_id
+ // funnel_id = 0
$agencyId = $this->user->agencyId;
$q_default = $this->db->query("SELECT id FROM funnel_default WHERE agency_id = $agencyId LIMIT 1");
if ($q_default && $this->db->num_rows($q_default) > 0) {
@@ -4870,12 +4871,12 @@
{
$complexStatus = new ComplexStatus((int)$requisistion['complex_status_id']);
$complexStatus->updateRoomsStatus([
- 'new_status_id' => 4,
- 'complex_room_id' => $requisistion['complex_room_id']
- ], false, false);
+ '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=$lastStage, denial = $post[denial] WHERE id=$id";
+ $sql = "UPDATE requisitions SET reason='".$select_text.". ".$post['reason']."', who_delete = '$user_id', deleted=1, stage=$lastStage, denial = $post[denial] WHERE id=$id";
if(isset($post['summa']) && $post['luck']){
if($dop_text != '') $dop_text .= " ";
$commission = isset($post['commission']) ? intval($post['commission']) : 0;
@@ -4886,10 +4887,9 @@
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();
+ if (!$this->db->query($sql))
+ $errors[] = $this->db->errorInfo();
- // Обновление статуса сделки при закрытии заявки
if (!empty($requisistion['deal_id']) && $requisistion['deal_id'] > 0) {
$dealId = intval($requisistion['deal_id']);
// Проверяем, есть ли другие заявки в сделке, которые ещё не закрыты
@@ -4910,7 +4910,7 @@
$linkedReq = $this->db->fetch_assoc($this->db->query($linkedReqSql));
if ($linkedReq) {
- $reason = 'Закрыта, т.к. была смежной заявкой по сделке "' . addslashes($dealRow['title']) . '"';
+ $reason = 'Закрыта, т.к. была смежной заявкой по сделке ID: ' . $dealId;
$this->db->query("UPDATE requisitions SET deleted=1, confirm=10, reason='" . addslashes($reason) . "', who_delete=$user_id WHERE id=$linkedReqId");
@@ -4945,15 +4945,15 @@
$user->get($user_id);
if($user->agencyId == 13154){
$w = new WebHookSend($user->agencyId, 3, $id, 'req', $this->db, 'close');
- }
+ }
- if($is_deal === false){
+ if($is_deal === false){
$reqs = array($id);
$this->set_user($user);
$this->autoUnitReq(-1, $reqs);
- }
+ }
} else {
- $errors[] = $this->db->errorInfo();
+ $errors[] = $this->db->errorInfo();
}
if ($requisistion['complex_room_id'])
@@ -4962,24 +4962,24 @@
$complex->generate_room_reservations_positions($requisistion['complex_room_id']);
}
- if (!empty($errors))
- return $errors;
+ if (!empty($errors))
+ return $errors;
- return true;
+ 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();
- }
+ $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;
+ return true;
}
//Удаление заявок по клиенту
@@ -4995,49 +4995,49 @@
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();
- }
+ 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."')";
+ $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();
- }
+ if (!$this->db->query($sql)) {
+ return $this->db->errorInfo();
+ }
- return true;
+ return true;
}
- //Принятие заявки из закрытых
- public function takeFromClosedReq($req_id, $user_id){
+ //Принятие заявки из закрытых
+ 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);
+ $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;
- }
+ $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 = "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_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();
- }
+ $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;
- }
+ return true;
+ }
//Установка воронки
public function set_funnel($funnel_id){
@@ -5108,7 +5108,7 @@
$stage = '';
$stageId = 0;
if ((int)$change_step['step_id'] == 0) {
- $isActive = false;
+ $isActive = false;
}
$arr_steps = array();
$countStep = $this->db->num_rows($funnel_step);
@@ -5181,24 +5181,24 @@
$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);*/
+ /* 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";
+ // 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']));
@@ -5231,7 +5231,7 @@
}
$insert_ev = "INSERT INTO user_client_events {$set}";
- // echo $insert_ev;
+ // echo $insert_ev;
$this->db->query($insert_ev);
}
}
@@ -5262,7 +5262,7 @@
}
$insert_ev = "INSERT INTO user_client_events {$set}";
- // echo $insert_ev;
+ // echo $insert_ev;
$this->db->query($insert_ev);
}
}
@@ -5273,7 +5273,7 @@
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";
+ // $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);
@@ -5295,7 +5295,7 @@
$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));
+ // 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){
@@ -5365,7 +5365,7 @@
case 'files_attach': {
if(!$is_open_step){
if(!empty($value_pole)){
- // var_dump($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);
@@ -5468,7 +5468,7 @@
}
}
}
- // $sql = "INSERT INTO clients_files (guid, req_id, type, name, event_id) VALUES ('{$name}', '{$req_id}', '{$type}', '{$_FILES['file']['name']}', '{$_SESSION['event_id_temp']}')";
+ // $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;
}
@@ -5523,35 +5523,35 @@
break;
case 4:
switch ($obj['type_category']){
- case 1:
+ case 1:
$type = "Офис";
- break;
- case 2:
+ break;
+ case 2:
$type = "Склад";
- break;
- case 3:
+ break;
+ case 3:
$type = "Торговая площадь";
- break;
- case 4:
+ break;
+ case 4:
$type = "Производство";
- break;
- case 5:
+ break;
+ case 5:
$type = "Помещение свободного назначения";
- break;
- case 6:
+ break;
+ case 6:
$type = "Здание";
break;
- case 7:
+ case 7:
$type = "Гараж";
break;
- case 8:
+ case 8:
$type = "Готовый бизнес";
break;
- case 9:
+ case 9:
$type = "Коммерческая земля";
break;
- default: $type = "Помещение";
-
+ default: $type = "Помещение";
+
}
break;
case 5:
@@ -5617,7 +5617,7 @@
if(!$is_open_step){
if($pole_prev->is_adjacent_funnels > 0){
if(!empty($value_pole)){
-
+
$adjacent_funnels=$value_pole;
foreach($adjacent_funnels as $funnel){
@@ -5646,79 +5646,79 @@
//Синхронизация с объктом для Реализации объекта
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'];
+ /* 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}";
}
- $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'];
- }
+ $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)$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']}");
- }
+ $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']}");
+ }
+ }
+ }
}
- }
}
- }
}
//Тип недвижимости
@@ -5728,26 +5728,26 @@
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;
+ {
+ $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;
@@ -5850,303 +5850,303 @@
//Для периодов
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";
+ $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 >= 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'";
+ } 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;
+ $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 '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' : {
+ 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;
+ 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;
- }
+ } 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;
+ 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;
}
//Список доступных юзеров
@@ -6166,7 +6166,7 @@
$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){
@@ -6200,16 +6200,16 @@
* Поиск заявок для объединения
*/
public function get_union_reqs($reqs){
- /* ini_set('display_errors', 1);
-error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
+ /* 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}";
@@ -6217,7 +6217,7 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
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);
@@ -6229,8 +6229,8 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
}
}
}
- }
-
+ }
+
}
}
@@ -6238,23 +6238,23 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
}
-
+
/**
* Сохранение объединения заявок
*/
public function save_union_reqs($reqs, $main_id){
- /* ini_set('display_errors', 1);
-error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
+ /* 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)";
@@ -6268,13 +6268,13 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
}
$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']}')";
@@ -6282,24 +6282,24 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
}
//переносим события
-
+
foreach($reqs as $req_id){
- $sql_ev = "SELECT * FROM user_client_events WHERE req_id = {$req_id} AND type != 'file'";
+ $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
+ 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++;
}
@@ -6308,15 +6308,15 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
}
}
-
+
//Объединение тегов
-
+
$all_reqs_ids = $reqs;
- $all_reqs_ids[] = $main_id;
- $all_tags = array();
-
- if(!empty($all_reqs_ids)){
+ $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)){
@@ -6329,7 +6329,7 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
$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++;
@@ -6337,135 +6337,135 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
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);
- }
- }
-
- }
- }
+ // 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)){
@@ -6490,7 +6490,7 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
}
/**
- *
+ *
*/
private function get_req_main($req_id){
$sql = "SELECT * FROM requisitions as req WHERE id = {$req_id}";
@@ -6504,7 +6504,7 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
$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'];
}
@@ -6531,10 +6531,10 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
$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']] .= ', ';
@@ -6542,7 +6542,7 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
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);
@@ -6592,7 +6592,7 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
}
/**
- * Горячая по клиенту и ответственному
+ * Горячая по клиенту и ответственному
*/
private function get_hot_req($client_id, $who_work){
$req_id = 0;
@@ -6615,7 +6615,7 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
$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}";
@@ -6649,7 +6649,7 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
$q = $this->db->query($sql, true);
$key = 0;
while($req = $this->db->fetch_assoc($q)){
- // var_dump($req);
+ // var_dump($req);
if($key == 0 && $main_id == 0){
$main_id = (int)$req['id'];
} else {
@@ -6680,16 +6680,16 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
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 {
@@ -6698,7 +6698,7 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
$key++;
}
}
-
+
if(!empty($reqs_union) && $main_id > 0){
$this->save_union_reqs($reqs_union, $main_id);
} else {
@@ -6711,7 +6711,7 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
/**
* Объединение по активным
*/
-
+
private function union_active_req($req_id){
$main_id = 0;
$reqs_union = array();
@@ -6737,11 +6737,11 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
}
$main_id = 0;
$reqs = array();
- // if($hot_tag > 0){
+ // 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)){
@@ -6753,7 +6753,7 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
}
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)){
@@ -6767,8 +6767,8 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
$this->check_mesages($req_main, [], 0);
}
}
-
-
+
+
}
/**
@@ -6800,9 +6800,9 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
* Проверка на дополнительные уведомления
*/
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);
+ // 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){
@@ -6825,14 +6825,14 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
$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("
", "\n", $comments['text']);
+ $text .= "\n".str_replace("
", "\n", $comments['text']);
try {
$telega->send($text, $chat_id);
} catch(Exception $e){
@@ -6847,7 +6847,7 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
//$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("
", "\n", $comments['text']);
+ $text .= "\n".str_replace("
", "\n", $comments['text']);
try {
$max->send_messages_to_user($max_user_id, $text);
} catch(Exception $e){
@@ -6858,12 +6858,12 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
}
} 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);
@@ -6879,12 +6879,12 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
}
$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);
@@ -6902,15 +6902,15 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
//Проверка дублей горячих и входящих
$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();
+ $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);
@@ -6965,49 +6965,49 @@ error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
}
}
- public function getRequisitionsByStage($stageId, $funnelId = 0, $search = '', $period = '', $responsible = [], $offset = 0, $limit = 20) {
- $sql = "SELECT r.* FROM requisitions r
+ 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)";
- }
+ 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];
+ $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;
+ 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);
+ $stmt = $this->pdo->prepare($sql);
+ $stmt->execute($params);
- return [
- 'items' => $stmt->fetchAll(PDO::FETCH_ASSOC)
- ];
- }
- }
+ return [
+ 'items' => $stmt->fetchAll(PDO::FETCH_ASSOC)
+ ];
+ }
+}
// Базовый тип: 1=Подбор, 2=Реализация, 3=Другие услуги, 4=Спрос. heir != 0 — кастомный наследник.
function requisition_base_type_id($typeRow) {