diff --git a/api/v2/app/src/controllers/AdvertsController.php b/api/v2/app/src/controllers/AdvertsController.php index 2a98374..a43ae71 100644 --- a/api/v2/app/src/controllers/AdvertsController.php +++ b/api/v2/app/src/controllers/AdvertsController.php @@ -6,6 +6,25 @@ use Complex\Exception; class AdvertsController extends ApiController { + // Найденный листинг парсера read-only: рекламные действия недоступны + // (паритет с десктопом, где switchAdvert*/addPromotion и т.п. отбивают листинг). Вернёт true + 403, если листинг. + // Offset-free: после снятия смещения id листинга (= реальный external_listings.id) коллизит с objects.id, + // поэтому различить листинг по id нельзя. Признак приходит явным флагом is_external из запроса + // (фронт знает, что действие над найденным листингом). Сервер по id отличить листинг уже не может. + private function _rejectIfExternalListing($app, $is_external) + { + if (!empty($is_external)) { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(403); + $app->response->setBody(json_encode([ + 'success' => false, + 'errors' => ['Действие недоступно для найденного листинга. Скопируйте объект в свои, чтобы управлять им.'], + ], JSON_UNESCAPED_UNICODE)); + return true; + } + return false; + } + public function getPublishedPackages($app, $get, $post) { $error = false; @@ -90,6 +109,9 @@ class AdvertsController extends ApiController if (isset($data['object_id'])) $object_id = $data['object_id']; + // Признак найденного листинга — явный флаг из запроса (offset-free: id листинга коллизит с objects.id) + if ($this->_rejectIfExternalListing($app, isset($data['is_external']) ? $data['is_external'] : null)) return; + $service = null; if (isset($data['service'])) $service = $data['service']; @@ -1814,6 +1836,9 @@ class AdvertsController extends ApiController if (isset($get['object_id'])) $object_id = $get['object_id']; + // Признак найденного листинга — явный флаг из запроса (offset-free: id листинга коллизит с objects.id) + if ($this->_rejectIfExternalListing($app, isset($get['is_external']) ? $get['is_external'] : null)) return; + if (($user_id = $_SESSION['id']) && !is_null($object_id)) { // Открываем соединение с БД @@ -1867,6 +1892,9 @@ class AdvertsController extends ApiController if (isset($data['object_id'])) $object_id = $data['object_id']; + // Признак найденного листинга — явный флаг из запроса (offset-free: id листинга коллизит с objects.id) + if ($this->_rejectIfExternalListing($app, isset($data['is_external']) ? $data['is_external'] : null)) return; + $packages = null; if (isset($data['packages'])) $packages = $data['packages']; @@ -2036,6 +2064,9 @@ class AdvertsController extends ApiController if (isset($data['object_id'])) $object_id = $data['object_id']; + // Признак найденного листинга — явный флаг из запроса (offset-free: id листинга коллизит с objects.id) + if ($this->_rejectIfExternalListing($app, isset($data['is_external']) ? $data['is_external'] : null)) return; + $price = null; if (isset($data['price'])) $price = $data['price']; @@ -2131,6 +2162,9 @@ class AdvertsController extends ApiController if (isset($data['object_id'])) $object_id = $data['object_id']; + // Признак найденного листинга — явный флаг из запроса (offset-free: id листинга коллизит с objects.id) + if ($this->_rejectIfExternalListing($app, isset($data['is_external']) ? $data['is_external'] : null)) return; + $price = null; if (isset($data['price'])) $price = $data['price']; @@ -2597,6 +2631,9 @@ class AdvertsController extends ApiController if (isset($data['object_id'])) $object_id = $data['object_id']; + // Признак найденного листинга — явный флаг из запроса (offset-free: id листинга коллизит с objects.id) + if ($this->_rejectIfExternalListing($app, isset($data['is_external']) ? $data['is_external'] : null)) return; + $services = null; if (isset($data['services'])) $services = $data['services']; @@ -2647,6 +2684,9 @@ class AdvertsController extends ApiController if (isset($data['object_id'])) $object_id = $data['object_id']; + // Признак найденного листинга — явный флаг из запроса (offset-free: id листинга коллизит с objects.id) + if ($this->_rejectIfExternalListing($app, isset($data['is_external']) ? $data['is_external'] : null)) return; + $employee_ids = null; if (isset($data['employee_ids'])) $employee_ids = $data['employee_ids']; diff --git a/api/v2/app/src/controllers/ClientsController.php b/api/v2/app/src/controllers/ClientsController.php index cbce10a..1c00f21 100644 --- a/api/v2/app/src/controllers/ClientsController.php +++ b/api/v2/app/src/controllers/ClientsController.php @@ -25,6 +25,16 @@ class ClientsController extends ApiController $menuPermissions = $user->checkMenuPermissions(); $agency_id = $_SESSION['agency_id']; + // Наполняем new_transfers для is_new здесь, не полагаясь на getFunnels + $nt_agency_id = \User::getUserAgencyID($user_id); + $nt_ids = []; + $nt_sql = "SELECT DISTINCT `clients`.`id` FROM `events_clients` AS `events` LEFT JOIN `clients` AS `clients` ON `clients`.`id` = `events`.`client_id` LEFT JOIN `funnel` AS `funnel` ON `funnel`.`id` = `clients`.`funnel_id` WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND (`events`.`event` = 'accepted' OR `events`.`event` = 'accepted_doer') AND `events`.`viewed` = 0 AND `events`.`read` = 1 AND (`clients`.`confirm` = 1 OR `clients`.`doers_confirm` = 1) AND `events`.`req_id` = 0 AND `clients`.`deleted` <> '1' AND (`clients`.`who_work` = '$user_id' OR `clients`.`doers` LIKE '%"{$user_id}":1%') AND (`clients`.`funnel_id` = 0 OR (`funnel`.`agency_id` = '$nt_agency_id' AND `funnel`.`deleted` = 0))"; + if ($nt_q = mysql_query($nt_sql)) { + while ($nt_row = mysql_fetch_assoc($nt_q)) + $nt_ids[] = $nt_row['id']; + } + $_SESSION['new_transfers']['clients'] = $nt_ids; + $clients = []; $pagination = null; @@ -1092,7 +1102,7 @@ class ClientsController extends ApiController if (isset($users[$client['id_agent']])) { if ($user_who = $users[$client['id_agent']]) { if ($user_who['agency']) { - $who_added['name'] = "Агентство {$user_who['agency_name']}"; + $who_added['name'] = trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']) ?: "Агентство {$user_who['agency_name']}"; } else if ($user_who['manager']) { $who_added['name'] = "Менеджер " . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']); if ($user_who['role_id'] > 0) @@ -1117,7 +1127,7 @@ class ClientsController extends ApiController if ($user_who = $users[$client['who_delete']]) { if ($user_who['agency']) { - $who_delete['name'] = "Агентство {$user_who['agency_name']}"; + $who_delete['name'] = trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']) ?: "Агентство {$user_who['agency_name']}"; } else if ($user_who['manager']) { $who_delete['name'] = "Менеджер " . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']); } else { @@ -1151,7 +1161,7 @@ class ClientsController extends ApiController if ($user_who = $users[$client['who_work']]) { if ($user_who['agency']) { - $who_work['name'] = "Агентство {$user_who['agency_name']}"; + $who_work['name'] = trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']) ?: "Агентство {$user_who['agency_name']}"; } else if ($user_who['manager']) { if ($user_who['role_id'] > 0) { $who_work['name'] = $departments[$user_who['role_id']]['role_name'] . ' ' . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']); @@ -1197,7 +1207,7 @@ class ClientsController extends ApiController $user_who = $users[$id]; if ($status == 0) { if ($user_who['agency']) { - $doers_request['name'] = "Агентство {$user_who['agency_name']}"; + $doers_request['name'] = trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']) ?: "Агентство {$user_who['agency_name']}"; } else if ($user_who['manager']) { $doers_request['name'] = "Менеджер " . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']); } else { @@ -1208,7 +1218,7 @@ class ClientsController extends ApiController } if ($status == 1) { if ($user_who['agency']) { - $doers_accept['name'] = "Агентство {$user_who['agency_name']}"; + $doers_accept['name'] = trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']) ?: "Агентство {$user_who['agency_name']}"; } else if ($user_who['manager']) { $doers_accept['name'] = "Менеджер " . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']); } else { @@ -1886,7 +1896,7 @@ class ClientsController extends ApiController if (isset($users[$data['id_agent']])) { if ($user_who = $users[$data['id_agent']]) { if ($user_who['agency']) { - $who_added['name'] = "Агентство {$user_who['agency_name']}"; + $who_added['name'] = trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']) ?: "Агентство {$user_who['agency_name']}"; } else if ($user_who['manager']) { $who_added['name'] = "Менеджер " . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']); if ($user_who['role_id'] > 0) @@ -1911,7 +1921,7 @@ class ClientsController extends ApiController if ($user_who = $users[$data['who_delete']]) { if ($user_who['agency']) { - $who_delete['name'] = "Агентство {$user_who['agency_name']}"; + $who_delete['name'] = trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']) ?: "Агентство {$user_who['agency_name']}"; } else if ($user_who['manager']) { $who_delete['name'] = "Менеджер " . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']); } else { @@ -1945,7 +1955,7 @@ class ClientsController extends ApiController if ($user_who = $users[$data['who_work']]) { if ($user_who['agency']) { - $who_work['name'] = "Агентство {$user_who['agency_name']}"; + $who_work['name'] = trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']) ?: "Агентство {$user_who['agency_name']}"; } else if ($user_who['manager']) { if ($user_who['role_id'] > 0) { $who_work['name'] = $departments[$user_who['role_id']]['role_name'] . ' ' . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']); @@ -2446,33 +2456,64 @@ class ClientsController extends ApiController $variants = []; - $sql = "SELECT `sended_pdf`.*, - 0 AS `close_contact`, - 0 AS `new_price`, - DATE_FORMAT(`sended_pdf`.`date_send`, '%d.%m.%Y') AS `date_f`, - DATE_FORMAT(`sended_pdf`.`date_send`, '%H:%i') AS `time_f`, - `archive`.`phone`, - `archive`.`sobstv`, - `archive`.`id` as `object_id`, - `archive`.`nazv` as `object_title`, - `archive`.`adres` as `object_address`, - 0 as `newbild` - FROM `sended_pdf`, `archive` - WHERE `sended_pdf`.`id_client` = '$client_id' AND - `archive`.`id_obj`=`sended_pdf`.`id_object` - UNION ALL SELECT `sended_pdf_newbuildings`.*, - 0 AS `close_contact`, - 0 AS `new_price`, - DATE_FORMAT(`sended_pdf_newbuildings`.`date_send`, '%d.%m.%Y') AS `date_f`, - DATE_FORMAT(`sended_pdf_newbuildings`.`date_send`, '%H:%i') AS `time_f`, - null as `phone`, - null as `sobstv`, - null as `object_id`, - null as `object_title`, - null as `object_address`, - 1 as `newbild` - FROM `sended_pdf_newbuildings` - WHERE `sended_pdf_newbuildings`.`id_client` = '$client_id' + // Распознавание найденных листингов парсера и витринный EXT-id. + // Offset-free: id_object для листинга = реальный external_listings.id, + // он коллизит с objects.id. Листинг различаем по флагу sended_pdf.is_external; + // витринный id собираем как 'EXT-{el.id}' напрямую (listing_guard.php тут больше не нужен). + $ext_variant_rows = []; // позиция в $variants => реальный el.id листинга + $ext_title_fallback = []; // позиция в $variants => запасной заголовок из снапшота отправки + + // Три ветки UNION: + // 1) свои объекты (is_external=0) — INNER JOIN archive по id_object (даёт телефон/собственника/адрес снапшота); + // 2) найденные листинги (is_external=1) — БЕЗ join к archive: id_object = реальный el.id коллизит с + // objects.id, join к archive подцепил бы чужой одноимённый снапшот; адрес/заголовок добиваются батчем + // из external_listings после цикла; + // 3) новостройки (sended_pdf_newbuildings) — листингами никогда не бывают. + $sql = "SELECT `sended_pdf`.`id`, `sended_pdf`.`id_agent`, `sended_pdf`.`id_object`, `sended_pdf`.`date_send`, `sended_pdf`.`id_client`, `sended_pdf`.`nazv`, `sended_pdf`.`path`, `sended_pdf`.`send_type`, `sended_pdf`.`close_contact`, `sended_pdf`.`hide_address`, `sended_pdf`.`new_price`, `sended_pdf`.`description`, `sended_pdf`.`token`, `sended_pdf`.`id_request`, `sended_pdf`.`sent_catalog_id`, `sended_pdf`.`is_favorite`, + 0 AS `close_contact`, + 0 AS `new_price`, + DATE_FORMAT(`sended_pdf`.`date_send`, '%d.%m.%Y') AS `date_f`, + DATE_FORMAT(`sended_pdf`.`date_send`, '%H:%i') AS `time_f`, + `archive`.`phone`, + `archive`.`sobstv`, + `archive`.`id` as `object_id`, + `archive`.`nazv` as `object_title`, + `archive`.`adres` as `object_address`, + 0 as `newbild`, + 0 as `is_external` + FROM `sended_pdf`, `archive` + WHERE `sended_pdf`.`id_client` = '$client_id' AND + `sended_pdf`.`is_external` = 0 AND + `archive`.`id_obj`=`sended_pdf`.`id_object` + UNION ALL SELECT `sended_pdf`.`id`, `sended_pdf`.`id_agent`, `sended_pdf`.`id_object`, `sended_pdf`.`date_send`, `sended_pdf`.`id_client`, `sended_pdf`.`nazv`, `sended_pdf`.`path`, `sended_pdf`.`send_type`, `sended_pdf`.`close_contact`, `sended_pdf`.`hide_address`, `sended_pdf`.`new_price`, `sended_pdf`.`description`, `sended_pdf`.`token`, `sended_pdf`.`id_request`, `sended_pdf`.`sent_catalog_id`, `sended_pdf`.`is_favorite`, + 0 AS `close_contact`, + 0 AS `new_price`, + DATE_FORMAT(`sended_pdf`.`date_send`, '%d.%m.%Y') AS `date_f`, + DATE_FORMAT(`sended_pdf`.`date_send`, '%H:%i') AS `time_f`, + null as `phone`, + null as `sobstv`, + null as `object_id`, + null as `object_title`, + null as `object_address`, + 0 as `newbild`, + 1 as `is_external` + FROM `sended_pdf` + WHERE `sended_pdf`.`id_client` = '$client_id' AND + `sended_pdf`.`is_external` = 1 + UNION ALL SELECT `sended_pdf_newbuildings`.`id`, `sended_pdf_newbuildings`.`id_agent`, `sended_pdf_newbuildings`.`id_object`, `sended_pdf_newbuildings`.`date_send`, `sended_pdf_newbuildings`.`id_client`, `sended_pdf_newbuildings`.`nazv`, `sended_pdf_newbuildings`.`path`, `sended_pdf_newbuildings`.`send_type`, `sended_pdf_newbuildings`.`close_contact`, `sended_pdf_newbuildings`.`hide_address`, `sended_pdf_newbuildings`.`new_price`, null as `description`, `sended_pdf_newbuildings`.`token`, `sended_pdf_newbuildings`.`id_request`, `sended_pdf_newbuildings`.`sent_catalog_id`, `sended_pdf_newbuildings`.`is_favorite`, + 0 AS `close_contact`, + 0 AS `new_price`, + DATE_FORMAT(`sended_pdf_newbuildings`.`date_send`, '%d.%m.%Y') AS `date_f`, + DATE_FORMAT(`sended_pdf_newbuildings`.`date_send`, '%H:%i') AS `time_f`, + null as `phone`, + null as `sobstv`, + null as `object_id`, + null as `object_title`, + null as `object_address`, + 1 as `newbild`, + 0 as `is_external` + FROM `sended_pdf_newbuildings` + WHERE `sended_pdf_newbuildings`.`id_client` = '$client_id' ORDER BY `date_send` DESC"; if ($query = mysql_query($sql)) { @@ -2513,6 +2554,58 @@ class ClientsController extends ApiController 'is_sended' => in_array($pdf['id_object'], $toSend), 'is_new' => $new_date, ]; + + // Найденный листинг парсера: строки в objects нет, помечаем элемент и + // запоминаем позицию — дообогащение из external_listings батчем после цикла. + // Offset-free: листинг различаем по флагу is_external (Sphinx/БД-атрибут), id_object — + // уже реальный external_listings.id, его и кладём как ключ дообогащения. + if ((int)$pdf['is_external'] === 1) { + $ext_idx = count($variants) - 1; + $ext_real_id = (int)$pdf['id_object']; + $variants[$ext_idx]['is_external'] = true; + $variants[$ext_idx]['display_id'] = 'EXT-' . $ext_real_id; + $variants[$ext_idx]['is_removed'] = false; + $ext_variant_rows[$ext_idx] = $ext_real_id; + $ext_title_fallback[$ext_idx] = trim($pdf['nazv']); + } + } + + // Дообогащение строк-листингов: заголовок/адрес берём из external_listings одним батчем. + // Offset-free: ключ — реальный external_listings.id (без смещения), запрашиваем и индексируем по нему. + if (!empty($ext_variant_rows)) { + // мягкая деградация: проблема с external_listings не должна валить историю отправок + try { + $pdo = $app->container->get('pdo'); + $ext_real_ids = array_map('intval', array_values($ext_variant_rows)); + + $ext_sth = $pdo->prepare("SELECT id, address_text, price FROM external_listings WHERE id IN (" . implode(',', array_unique($ext_real_ids)) . ")"); + if ($ext_sth->execute()) { + + // Мапа листингов ключуется на реальный el.id и держится ОТДЕЛЬНО от objects — + // одноимённый objects.id сюда не попадает (запрос только по external_listings). + $ext_by_id = []; + while ($ext_row = $ext_sth->fetch(\PDO::FETCH_ASSOC)) + $ext_by_id[(int)$ext_row['id']] = $ext_row; + + foreach ($ext_variant_rows as $ext_idx => $ext_real_id) { + if (isset($ext_by_id[$ext_real_id])) { + // живой листинг: пустые заголовок/адрес добиваем адресом первоисточника + $ext_address = trim($ext_by_id[$ext_real_id]['address_text']); + if ($variants[$ext_idx]['object_title'] === '') + $variants[$ext_idx]['object_title'] = $ext_address; + if ($variants[$ext_idx]['object_address'] === '') + $variants[$ext_idx]['object_address'] = $ext_address; + } else { + // объявление снято с публикации: остаётся nazv-снапшот из истории отправки + $variants[$ext_idx]['is_removed'] = true; + if ($variants[$ext_idx]['object_title'] === '') + $variants[$ext_idx]['object_title'] = $ext_title_fallback[$ext_idx]; + } + } + } + } catch (\Exception $e) { + // данных по листингам нет — строки остаются с пометкой is_external без дообогащения + } } } else { $error = true; @@ -2579,6 +2672,7 @@ class ClientsController extends ApiController $history = []; + // copy_created / copy_from — лейбл пустой: текст идёт в dop_text, иначе в истории двоится. $array_ev = [ 'add'=>'Добавлен', 'transmitted' => 'Передан', @@ -2590,7 +2684,10 @@ class ClientsController extends ApiController 'notadopted_doer' => 'Приглашение не принято', 'stageedit' => 'Изменен этап', 'delete' => 'Закрыт', - 'double_client' => 'Повторное обращение' + 'double_client' => 'Повторное обращение', + // copy_* — плейсхолдер {N} подменяется ниже на кликабельный ID из dop_text. + 'copy_created' => 'Создана копия → ID {N}', + 'copy_from' => 'Создана как копия заявки ID {N}' ]; $sql = "(SELECT id, client_id, user_id, from_id, `event`, `date`, `dop_text`, 0 as `of_objects` FROM events_clients WHERE client_id = $client_id) @@ -2614,7 +2711,7 @@ class ClientsController extends ApiController $mstr = mysql_fetch_assoc($q_m); if ($mstr['agency']) - $master = "Агентство $mstr[agency_name]"; + $master = trim($mstr['last_name'] . ' ' . $mstr['first_name'] . ' ' . $mstr['middle_name']) ?: "Агентство {$mstr['agency_name']}"; else if ($mstr['manager']) $master = "Менеджер " . trim($mstr['last_name'] . ' ' . $mstr['first_name'] . ' ' . $mstr['middle_name']); else @@ -2634,7 +2731,7 @@ class ClientsController extends ApiController $mstr = mysql_fetch_assoc($q_m); if ($mstr['agency']) - $from_master = "агентство $mstr[agency_name]"; + $from_master = trim($mstr['last_name'] . ' ' . $mstr['first_name'] . ' ' . $mstr['middle_name']) ?: "агентство {$mstr['agency_name']}"; else if($mstr['manager']) $from_master = "менеджер " . trim($mstr['last_name'] . ' ' . $mstr['first_name'] . ' ' . $mstr['middle_name']); else @@ -2676,13 +2773,23 @@ class ClientsController extends ApiController $dop_text .= ' по звонку по объекту '.$name; } + // copy_* — рендерим label-шаблон, подставляя int-id из dop_text. + $event_label = $array_ev[$r_ev['event']]; + if (in_array($r_ev['event'], ['copy_from', 'copy_created'], true)) { + $linkId = (int)$r_ev['dop_text']; + if ($linkId > 0) { + $event_label = str_replace('{N}', (string)$linkId, $event_label); + $r_ev['dop_text'] = ''; // весь текст уже в label + } + } + $history[] = [ 'datetime' => date('Y-m-d H:i:s', $udate), 'date_string' => $date_row, 'time_string' => date('H:i:s', $udate), 'to_user' => $master, 'from_user' => $from_master, - 'event' => $array_ev[$r_ev['event']] ." ". (function_exists('mask_text_for_hide_user') ? mask_text_for_hide_user($dop_text . $r_ev['dop_text']) : ($dop_text . $r_ev['dop_text'])) ." ". $from_master, + 'event' => $event_label ." ". (function_exists('mask_text_for_hide_user') ? mask_text_for_hide_user($dop_text . $r_ev['dop_text']) : ($dop_text . $r_ev['dop_text'])) ." ". $from_master, ]; } } else { diff --git a/api/v2/app/src/controllers/CommonController.php b/api/v2/app/src/controllers/CommonController.php old mode 100644 new mode 100755 index 7669984..cc9b062 --- a/api/v2/app/src/controllers/CommonController.php +++ b/api/v2/app/src/controllers/CommonController.php @@ -3,70 +3,70 @@ namespace App\v2\Controller; class CommonController extends ApiController - { +{ - // Offset-free: листинг парсера (external_listings) различается по ЯВНОМУ флагу из запроса. - // Реальный el.id листинга коллизит с objects.id, поэтому различить его по id нельзя. - // Канон полей: is_external — объект-листинг; is_external_listing_event — событие листинга (echo'ит mJW обратно). - // Хелпер приводит присланный флаг (1 / '1' / true / 'true') к булеву признаку. - private static function _request_flag($src, $key) { - if (!is_array($src) || !isset($src[$key])) - return false; - $v = $src[$key]; - return ($v === true || $v === 1 || $v === '1' || $v === 'true'); - } + // Offset-free: листинг парсера (external_listings) различается по ЯВНОМУ флагу из запроса. + // Реальный el.id листинга коллизит с objects.id, поэтому различить его по id нельзя. + // Канон полей: is_external — объект-листинг; is_external_listing_event — событие листинга (echo'ит mJW обратно). + // Хелпер приводит присланный флаг (1 / '1' / true / 'true') к булеву признаку. + private static function _request_flag($src, $key) { + if (!is_array($src) || !isset($src[$key])) + return false; + $v = $src[$key]; + return ($v === true || $v === 1 || $v === '1' || $v === 'true'); + } - public function getEmployees($app, $get = null, $post = null) { + public function getEmployees($app, $get = null, $post = null) { - $error = false; - if ($user_id = $_SESSION['id']) { + $error = false; + if ($user_id = $_SESSION['id']) { - // Открываем соединение с БД - $mdb = $app->container->get('mysql'); + // Открываем соединение с БД + $mdb = $app->container->get('mysql'); - $manager_agents = null; - $agency_managers = []; - $department_managers = []; + $manager_agents = null; + $agency_managers = []; + $department_managers = []; - $groups = []; - $employees = []; + $groups = []; + $employees = []; - // Текущий пользователь - $user = new \User; - $user->get($user_id); - $user->checkPermissions($user_id, false); + // Текущий пользователь + $user = new \User; + $user->get($user_id); + $user->checkPermissions($user_id, false); - // Получаем список отделов - $dep = new \Department; - $departments = $dep->getDepartment($user_id); - $searchUserId = $user_id; + // Получаем список отделов + $dep = new \Department; + $departments = $dep->getDepartment($user_id); + $searchUserId = $user_id; - $list_type = ''; - if(isset($get['list_type'])){ - $list_type = $get['list_type']; - } - $onlyActive = true; - if (isset($get['active'])) - $onlyActive = ($get['active'] == 'true'); + $list_type = ''; + if(isset($get['list_type'])){ + $list_type = $get['list_type']; + } + $onlyActive = true; + if (isset($get['active'])) + $onlyActive = ($get['active'] == 'true'); - $showBlocked = false; - if (isset($get['blocked'])) - $showBlocked = ($get['blocked'] == 'true'); + $showBlocked = false; + if (isset($get['blocked'])) + $showBlocked = ($get['blocked'] == 'true'); - $selfExclude = false; - if (isset($get['self_exclude'])) - $selfExclude = ($get['self_exclude'] == 'true'); + $selfExclude = false; + if (isset($get['self_exclude'])) + $selfExclude = ($get['self_exclude'] == 'true'); - $addGroups = false; - if (isset($get['add_groups'])) - $addGroups = ($get['add_groups'] == 'true'); + $addGroups = false; + if (isset($get['add_groups'])) + $addGroups = ($get['add_groups'] == 'true'); - $includeIds = false; - if (isset($get['include_ids'])) { - if (count($get['include_ids'])) { - $includeIds = $get['include_ids']; - } - } + $includeIds = false; + if (isset($get['include_ids'])) { + if (count($get['include_ids'])) { + $includeIds = $get['include_ids']; + } + } $list_type = 'clients'; if (isset($get['list_type'])) { @@ -74,24 +74,24 @@ class CommonController extends ApiController } - if ($showBlocked) - $onlyActive = false; + if ($showBlocked) + $onlyActive = false; - if (!$selfExclude && (!$includeIds || in_array($user_id, $includeIds))) { + if (!$selfExclude && (!$includeIds || in_array($user_id, $includeIds))) { - $group_id = null; - if ($user->blocked) - $group_id = -1; + $group_id = null; + if ($user->blocked) + $group_id = -1; - $employees[] = [ - 'id' => intval($user_id), - 'name' => 'Я', - 'department' => null, - 'group_id' => $group_id, - 'is_agent' => boolval($_SESSION['agent']), - 'is_manager' => boolval($_SESSION['manager']), - ]; - } + $employees[] = [ + 'id' => intval($user_id), + 'name' => 'Я', + 'department' => null, + 'group_id' => $group_id, + 'is_agent' => boolval($_SESSION['agent']), + 'is_manager' => boolval($_SESSION['manager']), + ]; + } $menuPermissions = $user->checkMenuPermissions(); if (($_SESSION['agency'] || $_SESSION['users_admin'] || $menuPermissions['menu_can_transfer_to_common'] == 1) && $list_type != 'objects') { @@ -122,671 +122,671 @@ class CommonController extends ApiController } } - if ($user_id != $user->agencyId || $list_type == 'objects') { - $agency = $user->get($user->agencyId); + if ($user_id != $user->agencyId || $list_type == 'objects') { + $agency = $user->get($user->agencyId); - $group_id = null; - if ($agency->blocked) - $group_id = -1; + $group_id = null; + if ($agency->blocked) + $group_id = -1; - $employees[] = [ - 'id' => intval($user->agencyId), - 'name' => $user->agencyName, - 'department' => null, - 'group_id' => $group_id, - 'is_agent' => boolval($agency->agent), - 'is_manager' => boolval($agency->manager), - ]; - } + $employees[] = [ + 'id' => intval($user->agencyId), + 'name' => $user->agencyName, + 'department' => null, + 'group_id' => $group_id, + 'is_agent' => boolval($agency->agent), + 'is_manager' => boolval($agency->manager), + ]; + } - $agentsOfManager = \User::getAllManagers($user->agencyId, $onlyActive); - if (isset($agentsOfManager)) { - foreach($agentsOfManager as $agent) { + $agentsOfManager = \User::getAllManagers($user->agencyId, $onlyActive); + if (isset($agentsOfManager)) { + foreach($agentsOfManager as $agent) { - $agent_id = (int)$agent['id']; - if ($user_id == $agent_id) - continue; + $agent_id = (int)$agent['id']; + if ($user_id == $agent_id) + continue; - $role_id = $agent['role']; + $role_id = $agent['role']; - $group_id = null; - if ($agent['blocked']) - $group_id = -1; + $group_id = null; + if ($agent['blocked']) + $group_id = -1; - $employees[] = [ - 'id' => $agent_id, - 'name' => trim($agent['last_name'] . ' ' . $agent['first_name'] . ' ' . $agent['middle_name']), - 'department' => ($role_id > 0) - ? $departments[$role_id]['role_name'] - : null, - 'group_id' => $group_id, - 'is_agent' => boolval($agent['agent']), - 'is_manager' => boolval($agent['manager']), - ]; - } - } + $employees[] = [ + 'id' => $agent_id, + 'name' => trim($agent['last_name'] . ' ' . $agent['first_name'] . ' ' . $agent['middle_name']), + 'department' => ($role_id > 0) + ? $departments[$role_id]['role_name'] + : null, + 'group_id' => $group_id, + 'is_agent' => boolval($agent['agent']), + 'is_manager' => boolval($agent['manager']), + ]; + } + } - $agentsOfAgency = \User::getAllAgents($user->agencyId, $onlyActive); - if (isset($agentsOfAgency)) { - foreach($agentsOfAgency as $agent) { + $agentsOfAgency = \User::getAllAgents($user->agencyId, $onlyActive); + if (isset($agentsOfAgency)) { + foreach($agentsOfAgency as $agent) { - $agent_id = (int)$agent['id']; - if ($user_id == $agent_id) - continue; + $agent_id = (int)$agent['id']; + if ($user_id == $agent_id) + continue; - $role_id = $agent['role']; + $role_id = $agent['role']; - $group_id = null; - if ($agent['blocked']) - $group_id = -1; + $group_id = null; + if ($agent['blocked']) + $group_id = -1; - $employees[] = [ - 'id' => $agent_id, - 'name' => trim($agent['last_name'] . ' ' . $agent['first_name'] . ' ' . $agent['middle_name']), - 'department' => ($role_id > 0) - ? $departments[$role_id]['role_name'] - : null, - 'group_id' => $group_id, - 'is_agent' => boolval($agent['agent']), - 'is_manager' => boolval($agent['manager']), - ]; - } - } + $employees[] = [ + 'id' => $agent_id, + 'name' => trim($agent['last_name'] . ' ' . $agent['first_name'] . ' ' . $agent['middle_name']), + 'department' => ($role_id > 0) + ? $departments[$role_id]['role_name'] + : null, + 'group_id' => $group_id, + 'is_agent' => boolval($agent['agent']), + 'is_manager' => boolval($agent['manager']), + ]; + } + } - if (!$onlyActive || $showBlocked) - $groups[(int)'-1'] = 'Заблокированные/удаленные'; + if (!$onlyActive || $showBlocked) + $groups[(int)'-1'] = 'Заблокированные/удаленные'; - if (!$error && count($employees)) { + if (!$error && count($employees)) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); - $sources = [ - 'success' => true, - 'user_id' => (int)$user_id, - 'list' => $employees - ]; + $sources = [ + 'success' => true, + 'user_id' => (int)$user_id, + 'list' => $employees + ]; - if ($addGroups) - $sources['groups'] = $groups; + if ($addGroups) + $sources['groups'] = $groups; $app->response->setBody(json_encode($sources, JSON_UNESCAPED_UNICODE)); $app->stop(); } } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } - public function getResponsibles($app, $get = null, $post = null) { - $userIds = array(); - $userId = $_SESSION['id']; - $mdb = $app->container->get('mysql'); - $result = array(); - $responsibles = array(); + public function getResponsibles($app, $get = null, $post = null) { + $userIds = array(); + $userId = $_SESSION['id']; + $mdb = $app->container->get('mysql'); + $result = array(); + $responsibles = array(); - // Текущий пользователь - $user = new \User; - $user->get($userId); - - $id = (int)$get['id']; - $section = $get['section']; - $userIds[] = $userId; - $who_work = 0; - if($id > 0){ + // Текущий пользователь + $user = new \User; + $user->get($userId); - // Найденный листинг парсера (offset-free): строки в objects нет — ни владельца, ни doers. - // Признак листинга — явный флаг is_external из запроса (id больше не диапазонный: el.id коллизит с objects.id). - // Ответственного выбираем по той же иерархии видимости, что и раздел «Задачи» (как на десктопе - // select_form_who_work_tasks.php): getUsersFilter вернёт подчинённых по правам (рядовой агент — только себя). - if($section == 'objects' && self::_request_flag($get, 'is_external')){ - $cl = new \Clients(); - $hierarchyIds = $cl->getUsersFilter(array(), $_SESSION['id'], $_SESSION['users_admin']); - if(is_array($hierarchyIds)){ - foreach($hierarchyIds as $hid){ - $userIds[] = (int)$hid; - } - } - } else { - $sql = "SELECT * FROM clients where id = {$id}"; - if($section == 'requisitions'){ - $sql = "SELECT * FROM requisitions where id = {$id}"; - } - if($section == 'objects'){ - $sql = "SELECT id, id_add_user as who_work FROM objects WHERE id = {$id}"; - } - //echo $sql; - $q = mysql_query($sql); - $r = mysql_fetch_assoc($q); + $id = (int)$get['id']; + $section = $get['section']; + $userIds[] = $userId; + $who_work = 0; + if($id > 0){ - if (isset($r['doers']) && !empty($r['doers'])) { - $doers = json_decode(html_entity_decode($r['doers']), true); + // Найденный листинг парсера (offset-free): строки в objects нет — ни владельца, ни doers. + // Признак листинга — явный флаг is_external из запроса (id больше не диапазонный: el.id коллизит с objects.id). + // Ответственного выбираем по той же иерархии видимости, что и раздел «Задачи» (как на десктопе + // select_form_who_work_tasks.php): getUsersFilter вернёт подчинённых по правам (рядовой агент — только себя). + if($section == 'objects' && self::_request_flag($get, 'is_external')){ + $cl = new \Clients(); + $hierarchyIds = $cl->getUsersFilter(array(), $_SESSION['id'], $_SESSION['users_admin']); + if(is_array($hierarchyIds)){ + foreach($hierarchyIds as $hid){ + $userIds[] = (int)$hid; + } + } + } else { + $sql = "SELECT * FROM clients where id = {$id}"; + if($section == 'requisitions'){ + $sql = "SELECT * FROM requisitions where id = {$id}"; + } + if($section == 'objects'){ + $sql = "SELECT id, id_add_user as who_work FROM objects WHERE id = {$id}"; + } + //echo $sql; + $q = mysql_query($sql); + $r = mysql_fetch_assoc($q); - foreach ($doers as $user_id => $d){ - if ($d == 1){ - $userIds[] = (int)$user_id; - } - } - } - if($r['who_work'] > 0){ - $userIds[] = (int)$r['who_work']; - $who_work = (int)$r['who_work']; - } - } + if (isset($r['doers']) && !empty($r['doers'])) { + $doers = json_decode(html_entity_decode($r['doers']), true); - } + foreach ($doers as $user_id => $d){ + if ($d == 1){ + $userIds[] = (int)$user_id; + } + } + } + if($r['who_work'] > 0){ + $userIds[] = (int)$r['who_work']; + $who_work = (int)$r['who_work']; + } + } - //Определение отделов - $sql_d = "SELECT d.name as dep_name, r.name as role_name, r.role, r.department_id, r.id FROM departments as d left join roles as r on d.id = r.department_id WHERE d.agency_id = ".$user->agencyId; + } - $q_d = mysql_query($sql_d); - $departments = array(); - while($r_d = mysql_fetch_assoc($q_d)){ - $departments[$r_d['id']] = $r_d; - } - $selected = ''; + //Определение отделов + $sql_d = "SELECT d.name as dep_name, r.name as role_name, r.role, r.department_id, r.id FROM departments as d left join roles as r on d.id = r.department_id WHERE d.agency_id = ".$user->agencyId; - $userIds = array_unique($userIds); - $sql_users = "SELECT * FROM users WHERE id in (".implode(',',$userIds).") AND blocked = 0"; - //echo $sql_users; - $q_users = mysql_query($sql_users); - while($r_user = mysql_fetch_assoc($q_users)){ - $name = trim($r_user['last_name'] . ' ' . $r_user['first_name'] . ' ' . $r_user['middle_name']); + $q_d = mysql_query($sql_d); + $departments = array(); + while($r_d = mysql_fetch_assoc($q_d)){ + $departments[$r_d['id']] = $r_d; + } + $selected = ''; - if($r_user['role_id'] > 0){ - $name .= ' ('.$departments[$r_user['role_id']]['role_name']. ' ' . $departments[$r_user['role_id']]['dep_name'].')'; - } - $responsibles[] = [ - 'id' => $r_user['id'], - 'name' => $name, - - ]; - } + $userIds = array_unique($userIds); + $sql_users = "SELECT * FROM users WHERE id in (".implode(',',$userIds).") AND blocked = 0"; + //echo $sql_users; + $q_users = mysql_query($sql_users); + while($r_user = mysql_fetch_assoc($q_users)){ + $name = trim($r_user['last_name'] . ' ' . $r_user['first_name'] . ' ' . $r_user['middle_name']); - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => true, - 'user_id' => (int)$userId, - 'responsibles' => $responsibles, - 'who_work' => $who_work, - 'sql' => $sql, - ], JSON_UNESCAPED_UNICODE)); + if($r_user['role_id'] > 0){ + $name .= ' ('.$departments[$r_user['role_id']]['role_name']. ' ' . $departments[$r_user['role_id']]['dep_name'].')'; + } + $responsibles[] = [ + 'id' => $r_user['id'], + 'name' => $name, + + ]; + } + + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => true, + 'user_id' => (int)$userId, + 'responsibles' => $responsibles, + 'who_work' => $who_work, + 'sql' => $sql, + ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + $app->stop(); + } - public function getTypes($app, $get = null, $post = null, $need_return = false) { + public function getTypes($app, $get = null, $post = null, $need_return = false) { - global $OBJECT_TYPES; - global $WORK_TYPES; - global $REQ_TYPES; - global $SEARCH_TARGETS; - global $etaz_first_types; - global $TYPE_NEDV2_SORT; - global $BANK_PRODUKT; + global $OBJECT_TYPES; + global $WORK_TYPES; + global $REQ_TYPES; + global $SEARCH_TARGETS; + global $etaz_first_types; + global $TYPE_NEDV2_SORT; + global $BANK_PRODUKT; - $error = false; - $section = $get['section']; - if ($section && ($user_id = $_SESSION['id'])) { + $error = false; + $section = $get['section']; + if ($section && ($user_id = $_SESSION['id'])) { - $types = []; - switch ($section) { - case 'objects' : - foreach($OBJECT_TYPES as $key => $val) { - if (intval($key) > 0 && $key != 6) { - $types[] = ['id' => intval($key), 'name' => $val]; - } - } + $types = []; + switch ($section) { + case 'objects' : + foreach($OBJECT_TYPES as $key => $val) { + if (intval($key) > 0 && $key != 6) { + $types[] = ['id' => intval($key), 'name' => $val]; + } + } - break; + break; - case 'clients' : - foreach($WORK_TYPES as $key => $val) { - if (intval($key) > 0) { - $types[] = ['id' => intval($key), 'name' => $val]; - } - } + case 'clients' : + foreach($WORK_TYPES as $key => $val) { + if (intval($key) > 0) { + $types[] = ['id' => intval($key), 'name' => $val]; + } + } - break; + break; - case 'search' : - case 'autosearch' : - foreach($SEARCH_TARGETS as $key => $val) { + case 'search' : + case 'autosearch' : + foreach($SEARCH_TARGETS as $key => $val) { - if ($key == 4) - continue; + if ($key == 4) + continue; - if (intval($key) > 0) { - $types[] = ['id' => intval($key), 'name' => $val]; - } - } + if (intval($key) > 0) { + $types[] = ['id' => intval($key), 'name' => $val]; + } + } - $types[] = ['id' => 5, 'name' => 'Архив компании']; + $types[] = ['id' => 5, 'name' => 'Архив компании']; - if ($section == 'autosearch') - $types[] = ['id' => 6, 'name' => 'Собственники и объекты компании']; + if ($section == 'autosearch') + $types[] = ['id' => 6, 'name' => 'Собственники и объекты компании']; - break; + break; - case 'requisitions' : + case 'requisitions' : - /*foreach($REQ_TYPES as $key => $val) { + /*foreach($REQ_TYPES as $key => $val) { if (intval($key) > 0) { $types[] = ['id' => intval($key), 'name' => $val]; } }*/ - // Открываем соединение с БД - $mdb = $app->container->get('mysql'); - $pdo = $app->container->get('mypdo'); + // Открываем соединение с БД + $mdb = $app->container->get('mysql'); + $pdo = $app->container->get('mypdo'); - $requisitions_inst = new \Requisitions($pdo); + $requisitions_inst = new \Requisitions($pdo); - $users_inst = new \User(); - $agency_id = $users_inst->getAgencyIdForUser($user_id); - $requisitions_inst->set_agencyId($agency_id); - $results = $requisitions_inst->get_type(false, true); - //var_dump($results); - //$types = $results['type']; - if (!empty($results['type'])) { - foreach ($results['type'] as $result) { - if ($result['order'] != -1 && $result['code'] != '-1' && !empty($result['name'])) { - $name_type = $result['name']; - if($result['archive'] == 1){ - $name_type = $result['name']." (архивный)"; - } - $types[] = [ - 'id' => intval($result['code']), - 'heir' => intval($result['heir']), - 'name' => $name_type, - 'archive'=>$result['archive'] - ]; - } - } - } + $users_inst = new \User(); + $agency_id = $users_inst->getAgencyIdForUser($user_id); + $requisitions_inst->set_agencyId($agency_id); + $results = $requisitions_inst->get_type(false, true); + //var_dump($results); + //$types = $results['type']; + if (!empty($results['type'])) { + foreach ($results['type'] as $result) { + if ($result['order'] != -1 && $result['code'] != '-1' && !empty($result['name'])) { + $name_type = $result['name']; + if($result['archive'] == 1){ + $name_type = $result['name']." (архивный)"; + } + $types[] = [ + 'id' => intval($result['code']), + 'heir' => intval($result['heir']), + 'name' => $name_type, + 'archive'=>$result['archive'] + ]; + } + } + } - break; + break; - case 'contract_types' : - // Открываем соединение с БД - $mdb = $app->container->get('mysql'); + case 'contract_types' : + // Открываем соединение с БД + $mdb = $app->container->get('mysql'); - $user = new \User; - $user->get($user_id); - $agency_id = $user->getUserAgencyID(); + $user = new \User; + $user->get($user_id); + $agency_id = $user->getUserAgencyID(); - $contracts = new \Contract(); - $contracts->setAgencyId($agency_id); + $contracts = new \Contract(); + $contracts->setAgencyId($agency_id); - $list = $contracts->getTypesName(); - foreach($list as $item) { - $types[] = [ - 'id' => (int)$item['id'], - 'name' => $item['type'], - 'heir' => intval($item['heir']), - ]; - } - break; + $list = $contracts->getTypesName(); + foreach($list as $item) { + $types[] = [ + 'id' => (int)$item['id'], + 'name' => $item['type'], + 'heir' => intval($item['heir']), + ]; + } + break; - case 'bank_products' : - foreach($BANK_PRODUKT as $key => $val) { - if (intval($key) > 0) { - $types[] = ['id' => intval($key), 'name' => $val]; - } - } + case 'bank_products' : + foreach($BANK_PRODUKT as $key => $val) { + if (intval($key) > 0) { + $types[] = ['id' => intval($key), 'name' => $val]; + } + } - break; + break; - case 'operations' : - $types = [ - [ - 'id' => 1, - 'name' => 'Аренда' - ], [ - 'id' => 2, - 'name' => 'Продажа' - ], - ]; + case 'operations' : + $types = [ + [ + 'id' => 1, + 'name' => 'Аренда' + ], [ + 'id' => 2, + 'name' => 'Продажа' + ], + ]; - break; + break; - case 'to_metro' : - $types = [ - [ - 'id' => 1, - 'name' => 'Пешком' - ], [ - 'id' => 2, - 'name' => 'На транспорте' - ], - ]; + case 'to_metro' : + $types = [ + [ + 'id' => 1, + 'name' => 'Пешком' + ], [ + 'id' => 2, + 'name' => 'На транспорте' + ], + ]; - break; + break; - case 'lease' : - $types = [ - [ - 'id' => 2, - 'name' => 'Длительно' - ], [ - 'id' => 3, - 'name' => 'Несколько месяцев' - ], [ - 'id' => 1, - 'name' => 'Посуточно' - ], - ]; + case 'lease' : + $types = [ + [ + 'id' => 2, + 'name' => 'Длительно' + ], [ + 'id' => 3, + 'name' => 'Несколько месяцев' + ], [ + 'id' => 1, + 'name' => 'Посуточно' + ], + ]; - break; + break; - case 'first_floor' : + case 'first_floor' : - foreach($etaz_first_types as $key => $val) { - if (intval($key) > 0) { - $types[] = ['id' => intval($key), 'name' => $val]; - } - } + foreach($etaz_first_types as $key => $val) { + if (intval($key) > 0) { + $types[] = ['id' => intval($key), 'name' => $val]; + } + } - break; + break; - case 'estate_types' : + case 'estate_types' : - $index = 1; - foreach($TYPE_NEDV2_SORT as $key => $val) { - if (!empty($key)) { - $types[] = [ - 'id' => $index, - 'name' => $val - ]; - } - $index++; - } + $index = 1; + foreach($TYPE_NEDV2_SORT as $key => $val) { + if (!empty($key)) { + $types[] = [ + 'id' => $index, + 'name' => $val + ]; + } + $index++; + } - break; + break; - case 'avito_room' : - // Открываем соединение с БД - $mdb = $app->container->get('mysql'); - $sql = "SELECT * FROM avito_room_types ORDER BY name"; - $rez = mysql_query($sql); - while($row = mysql_fetch_assoc($rez)) { - $types[] = [ - 'id' => (int)$row['id'], - 'name' => $row['name'] - ]; - } + case 'avito_room' : + // Открываем соединение с БД + $mdb = $app->container->get('mysql'); + $sql = "SELECT * FROM avito_room_types ORDER BY name"; + $rez = mysql_query($sql); + while($row = mysql_fetch_assoc($rez)) { + $types[] = [ + 'id' => (int)$row['id'], + 'name' => $row['name'] + ]; + } - break; + break; - case 'deal_type' : - // Открываем соединение с БД - $mdb = $app->container->get('mysql'); - $sql = "SELECT * FROM deal_type ORDER BY name"; - $rez = mysql_query($sql); - while($row = mysql_fetch_assoc($rez)) { - $types[] = [ - 'id' => (int)$row['id'], - 'name' => $row['name'] - ]; - } + case 'deal_type' : + // Открываем соединение с БД + $mdb = $app->container->get('mysql'); + $sql = "SELECT * FROM deal_type ORDER BY name"; + $rez = mysql_query($sql); + while($row = mysql_fetch_assoc($rez)) { + $types[] = [ + 'id' => (int)$row['id'], + 'name' => $row['name'] + ]; + } - break; + break; - case 'house_types' : - $mdb = $app->container->get('mysql'); - $sql = "SELECT * FROM house_type ORDER BY name"; - $rez = mysql_query($sql); - while($row = mysql_fetch_assoc($rez)) { - $types[] = [ - 'id' => (int)$row['id'], - 'name' => $row['name'] - ]; - } + case 'house_types' : + $mdb = $app->container->get('mysql'); + $sql = "SELECT * FROM house_type ORDER BY name"; + $rez = mysql_query($sql); + while($row = mysql_fetch_assoc($rez)) { + $types[] = [ + 'id' => (int)$row['id'], + 'name' => $row['name'] + ]; + } - break; + break; - case 'house_materials' : - $mdb = $app->container->get('mysql'); - $sql = "SELECT * FROM house_material ORDER BY name"; - $rez = mysql_query($sql); - while($row = mysql_fetch_assoc($rez)) { - $types[] = [ - 'id' => (int)$row['id'], - 'name' => $row['name'] - ]; - } + case 'house_materials' : + $mdb = $app->container->get('mysql'); + $sql = "SELECT * FROM house_material ORDER BY name"; + $rez = mysql_query($sql); + while($row = mysql_fetch_assoc($rez)) { + $types[] = [ + 'id' => (int)$row['id'], + 'name' => $row['name'] + ]; + } - break; - } + break; + } - if (count($types)) { - if ($need_return) { - return $types; - } else { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => !$error, - 'user_id' => (int)$user_id, - 'list' => $types - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + if (count($types)) { + if ($need_return) { + return $types; + } else { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => !$error, + 'user_id' => (int)$user_id, + 'list' => $types + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } } } - if ($need_return) { - return false; - } else { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } + if ($need_return) { + return false; + } else { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } - public function getStatus($app, $get = null, $post = null) { + public function getStatus($app, $get = null, $post = null) { - $errors = []; - $status = false; - $service = $get['service']; - if ($service) { + $errors = []; + $status = false; + $service = $get['service']; + if ($service) { - switch ($service) { - case 'api' : + switch ($service) { + case 'api' : - $status = true; + $status = true; - /*if ($_SESSION['id'] == 5427) + /*if ($_SESSION['id'] == 5427) $_SESSION['id'] = 5427;*/ - break; + break; - case 'mysql' : + case 'mysql' : - try { - $pdo = $app->container->get('pdo'); - $mdb = $app->container->get('mysql'); - if ($pdo && $mdb) - $status = true; + try { + $pdo = $app->container->get('pdo'); + $mdb = $app->container->get('mysql'); + if ($pdo && $mdb) + $status = true; - } catch (Exception $e) { - $errors[] = $e; - } + } catch (Exception $e) { + $errors[] = $e; + } - break; + break; - case 'sphinx' : + case 'sphinx' : - try { - $sphinx = $app->container->get('sphinx'); - if ($sphinx) - $status = true; + try { + $sphinx = $app->container->get('sphinx'); + if ($sphinx) + $status = true; - } catch (Exception $e) { - $errors[] = $e; - } + } catch (Exception $e) { + $errors[] = $e; + } - $status = true; - break; + $status = true; + break; - case 'sphinx2' : + case 'sphinx2' : - try { - $sphinx2 = $app->container->get('sphinx2'); - if ($sphinx2) - $status = true; + try { + $sphinx2 = $app->container->get('sphinx2'); + if ($sphinx2) + $status = true; - } catch (Exception $e) { - $errors[] = $e; - } + } catch (Exception $e) { + $errors[] = $e; + } - $status = true; - break; + $status = true; + break; - } + } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => true, - 'status' => ($status) ? 'up' : 'down', - 'service' => $service, - 'errors' => $errors, - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => true, + 'status' => ($status) ? 'up' : 'down', + 'service' => $service, + 'errors' => $errors, + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'service' => $service, - 'errors' => $errors, - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'service' => $service, + 'errors' => $errors, + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } - public function getTags($app, $get = null, $post = null, $need_return = false) { + public function getTags($app, $get = null, $post = null, $need_return = false) { - $error = false; - if ($user_id = $_SESSION['id']) { + $error = false; + if ($user_id = $_SESSION['id']) { - $pdo = $app->container->get('pdo'); - $mdb = $app->container->get('mysql'); + $pdo = $app->container->get('pdo'); + $mdb = $app->container->get('mysql'); - $list = []; - $user = new \User(); - $user->get($user_id); - //$user->checkPermissions($user_id, false); - $agency_id = $user->getUserAgencyID(); + $list = []; + $user = new \User(); + $user->get($user_id); + //$user->checkPermissions($user_id, false); + $agency_id = $user->getUserAgencyID(); - if (boolval($get['with_managers'])) { + if (boolval($get['with_managers'])) { - $sql = "SELECT * FROM `activities` + $sql = "SELECT * FROM `activities` WHERE `user_id` = '".$user->id."' OR `manager_id` = '".$user->id."'"; - if ($user->id_manager) - $sql .= " OR `manager_id` = '".$user->id_manager."' OR `user_id` = '".$user->id_manager."'"; + if ($user->id_manager) + $sql .= " OR `manager_id` = '".$user->id_manager."' OR `user_id` = '".$user->id_manager."'"; - if ($user->agencyId) - $sql .= " OR `manager_id` = '".$user->agencyId."' OR `user_id` = '".$user->agencyId."'"; + if ($user->agencyId) + $sql .= " OR `manager_id` = '".$user->agencyId."' OR `user_id` = '".$user->agencyId."'"; - } else { - $sql = "SELECT * FROM `activities` WHERE `user_id` = '".$user_id."' OR `manager_id` = '".$user_id."'"; + } else { + $sql = "SELECT * FROM `activities` WHERE `user_id` = '".$user_id."' OR `manager_id` = '".$user_id."'"; - if ($agency_id) - $sql .= " OR `manager_id` = '".$agency_id."' OR `user_id` = '".$agency_id."'"; - } + if ($agency_id) + $sql .= " OR `manager_id` = '".$agency_id."' OR `user_id` = '".$agency_id."'"; + } - $sql .= ' GROUP BY `id` ORDER BY `name`'; + $sql .= ' GROUP BY `id` ORDER BY `name`'; - $sth = $pdo->prepare($sql); - if ($sth->execute()) { - while($row = $sth->fetch(\PDO::FETCH_BOTH)) { - if (intval($row["id"]) && !empty($row["name"])) { - $list[] = [ - 'id' => intval($row["id"]), - 'name' => $row["name"], - 'color' => $row["color"] - ]; - } - } - } else { - $error = true; - } + $sth = $pdo->prepare($sql); + if ($sth->execute()) { + while($row = $sth->fetch(\PDO::FETCH_BOTH)) { + if (intval($row["id"]) && !empty($row["name"])) { + $list[] = [ + 'id' => intval($row["id"]), + 'name' => $row["name"], + 'color' => $row["color"] + ]; + } + } + } else { + $error = true; + } - if (!$error) { - if ($need_return) { - return $list; - } else { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => true, - 'user_id' => (int)$user_id, - 'count' => count($list), - //'$sql' => $sql, - 'list' => $list - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + if (!$error) { + if ($need_return) { + return $list; + } else { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => true, + 'user_id' => (int)$user_id, + 'count' => count($list), + //'$sql' => $sql, + 'list' => $list + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } } } - if ($need_return) { - return false; - } else { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } + if ($need_return) { + return false; + } else { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } - public function getClients($app, $get = null, $post = null, $need_return = false) { + public function getClients($app, $get = null, $post = null, $need_return = false) { - $error = false; - $errors = []; - if ($user_id = $_SESSION['id']) { + $error = false; + $errors = []; + if ($user_id = $_SESSION['id']) { - // Открываем соединение с БД - $mdb = $app->container->get('mysql'); + // Открываем соединение с БД + $mdb = $app->container->get('mysql'); - $user = new \User(); - $user->checkPermissions($user_id, false); - $agency_id = $_SESSION['agency_id']; + $user = new \User(); + $user->checkPermissions($user_id, false); + $agency_id = $_SESSION['agency_id']; - $menuPermissions = $user->checkMenuPermissions(); + $menuPermissions = $user->checkMenuPermissions(); - $clients = []; - $filters = []; - if (isset($get['filters'])) - $filters = json_decode($get['filters'], true); + $clients = []; + $filters = []; + if (isset($get['filters'])) + $filters = json_decode($get['filters'], true); - $only_active = true; - if (isset($get['only_active'])) - $only_active = ($get['only_active'] == 'true'); + $only_active = true; + if (isset($get['only_active'])) + $only_active = ($get['only_active'] == 'true'); - $offset = null; - if (isset($get['offset'])) - $offset = intval($get['offset']); + $offset = null; + if (isset($get['offset'])) + $offset = intval($get['offset']); - $search_query = ''; - if (isset($get['search_query'])) - $search_query = trim($get['search_query']); + $search_query = ''; + if (isset($get['search_query'])) + $search_query = trim($get['search_query']); // Проверяем точное совпадение по телефону (без учета иерархии) if(!empty($search_query)) { @@ -802,13 +802,13 @@ class CommonController extends ApiController $exact_match = mysql_fetch_assoc($rez); if($exact_match) { $phones = []; - $phones_dop = []; + $phones_dop = []; if (!empty($exact_match['phone'])) $phones[] = $exact_match['phone']; if (!empty($exact_match['phone2'])) $phones = array_merge($phones, json_decode(html_entity_decode($exact_match['phone2'], ENT_QUOTES), true)); - if (!empty($exact_match['phone2'])) - $phones_dop = array_merge($phones_dop, json_decode(html_entity_decode($exact_match['phone2'], ENT_QUOTES), true)); + if (!empty($exact_match['phone2'])) + $phones_dop = array_merge($phones_dop, json_decode(html_entity_decode($exact_match['phone2'], ENT_QUOTES), true)); // Маскируем телефоны клиента в массиве phones_dop до implode, // если у текущего пользователя включено `hide_client_contacts`. @@ -853,13 +853,13 @@ class CommonController extends ApiController } - $users = [(int)$user_id]; - $managers = [(int)$agency_id]; + $users = [(int)$user_id]; + $managers = [(int)$agency_id]; - $bd_usl = " AND cancel = 0"; - $clients_ids = []; - $bd_managers = ''; - $bd_user_j = ''; + $bd_usl = " AND cancel = 0"; + $clients_ids = []; + $bd_managers = ''; + $bd_user_j = ''; $searchUserId = $_SESSION['id']; $adminDep = false; @@ -905,100 +905,100 @@ class CommonController extends ApiController $users = array_unique($users); } - $bd_user = " (`who_work` IN (". implode(',', $users) .") or `id_agent` IN (". implode(',', $users) ."))"; + $bd_user = " (`who_work` IN (". implode(',', $users) .") or `id_agent` IN (". implode(',', $users) ."))"; - if (!empty($filters['employees'])) { + if (!empty($filters['employees'])) { - $users = []; - $managers = []; - $employees = array_unique($filters['employees']); - foreach ($employees as $employee) { + $users = []; + $managers = []; + $employees = array_unique($filters['employees']); + foreach ($employees as $employee) { - if (strripos($employee, 'u')) - $users[] = preg_replace('/[^0-9]/', '', $employee); + if (strripos($employee, 'u')) + $users[] = preg_replace('/[^0-9]/', '', $employee); - if (strripos($employee, 'm')) - $managers[] = preg_replace('/[^0-9]/', '', $employee); + if (strripos($employee, 'm')) + $managers[] = preg_replace('/[^0-9]/', '', $employee); - } + } - if ($managers) { - /*$bd_managers_j = " AND id_agent IN (SELECT id FROM `users` WHERE id IN (". implode(',', $managers) .") OR + if ($managers) { + /*$bd_managers_j = " AND id_agent IN (SELECT id FROM `users` WHERE id IN (". implode(',', $managers) .") OR id_manager IN (". implode(',', $managers) .") OR id_manager IN (SELECT id FROM users WHERE id_manager IN (". implode(',', $managers) .")))";*/ - $bd_managers = " IN (". implode(',', $managers) .")"; - } + $bd_managers = " IN (". implode(',', $managers) .")"; + } - if ($users) { - $bd_user_j = " `who_work` IN (". implode(',', $users) .") OR + if ($users) { + $bd_user_j = " `who_work` IN (". implode(',', $users) .") OR `id_agent` IN (SELECT `id` FROM `users` WHERE `id` IN (". implode(',', $users) .") OR `id_manager` IN (". implode(',', $users) .") OR `id_manager` IN (SELECT `id` FROM `users` WHERE `id_manager` IN (". implode(',', $users) .")))"; - } + } - } else { - if ($menuPermissions['menu_all_clients'] == 1 ) { + } else { + if ($menuPermissions['menu_all_clients'] == 1 ) { $users[] = $agency_id; } - $bd_user_j = " (`who_work` IN (". implode(',', $users) .") or `id_agent` IN (". implode(',', $users) ."))"; + $bd_user_j = " (`who_work` IN (". implode(',', $users) .") or `id_agent` IN (". implode(',', $users) ."))"; - if (isset($get['client_id'])) - $clients_ids[] = $get['client_id']; - elseif (isset($get['clients_ids'])) - $clients_ids = (array)$get['clients_ids']; + if (isset($get['client_id'])) + $clients_ids[] = $get['client_id']; + elseif (isset($get['clients_ids'])) + $clients_ids = (array)$get['clients_ids']; - if (count($clients_ids) > 0) { - $bd_usl = " `id` IN (" . implode(',', $clients_ids) . ") "; - $bd_user_j = ''; - } - } + if (count($clients_ids) > 0) { + $bd_usl = " `id` IN (" . implode(',', $clients_ids) . ") "; + $bd_user_j = ''; + } + } - if (!empty($filters['types'])) { - $where = []; - $types = $filters['types']; - foreach ($types as $type) { - $where[] = "`work_type` LIKE '%" {$type}"%'"; - } - $bd_usl .= " AND (".implode(" OR ",$where).")"; - } + if (!empty($filters['types'])) { + $where = []; + $types = $filters['types']; + foreach ($types as $type) { + $where[] = "`work_type` LIKE '%" {$type}"%'"; + } + $bd_usl .= " AND (".implode(" OR ",$where).")"; + } - if (!empty($filters['tags'])) { - $tags_ids = $filters['tags']; - $bd_usl .= " AND `id` IN ( + if (!empty($filters['tags'])) { + $tags_ids = $filters['tags']; + $bd_usl .= " AND `id` IN ( SELECT `client_id` FROM `clients_activities` WHERE `activity_id` IN (" . implode(", ", $tags_ids) . ") )"; - } + } - if (!empty($filters['source'])) { - $sources = $filters['source']; - $where = []; - foreach ($sources as $source) { - if ($source == 0) { - $where[] = "`source` IS NULL"; - $where[] = "`source` = ''"; - $where[] = "`source` = 'null'"; - } else { - $where[] = "`source` = ' {$source}'"; - } - } - $bd_usl .= " AND (" . implode(" OR ", $where) . ")"; - } + if (!empty($filters['source'])) { + $sources = $filters['source']; + $where = []; + foreach ($sources as $source) { + if ($source == 0) { + $where[] = "`source` IS NULL"; + $where[] = "`source` = ''"; + $where[] = "`source` = 'null'"; + } else { + $where[] = "`source` = ' {$source}'"; + } + } + $bd_usl .= " AND (" . implode(" OR ", $where) . ")"; + } - if (!empty($filters['clients_ids'])) { - $clients_ids = $filters['clients_ids']; - $bd_usl .= " AND `id` IN (" . implode(", ", $clients_ids) . ")"; - } + if (!empty($filters['clients_ids'])) { + $clients_ids = $filters['clients_ids']; + $bd_usl .= " AND `id` IN (" . implode(", ", $clients_ids) . ")"; + } - if (!empty($filters['is_deleted'])) - $bd_usl .= " AND `confirm` > 0 AND `deleted` = 1 "; - else if (empty($clients_ids)) - $bd_usl .= " AND `confirm` > 0 "; - else if ($only_active) - $bd_usl .= " AND `deleted` <> 1 "; + if (!empty($filters['is_deleted'])) + $bd_usl .= " AND `confirm` > 0 AND `deleted` = 1 "; + else if (empty($clients_ids)) + $bd_usl .= " AND `confirm` > 0 "; + else if ($only_active) + $bd_usl .= " AND `deleted` <> 1 "; - if (in_array(6358, $managers) || in_array(93, $managers)) { - $sql = "SELECT `id`, `email`, `fio`, `phone`, `phone2`, DATE_FORMAT(`date_add`, '%d.%m.%Y') AS `date_add`, `objects`, `deleted`, `confirm` + if (in_array(6358, $managers) || in_array(93, $managers)) { + $sql = "SELECT `id`, `email`, `fio`, `phone`, `phone2`, DATE_FORMAT(`date_add`, '%d.%m.%Y') AS `date_add`, `objects`, `deleted`, `confirm` FROM `clients` WHERE ( (true $bd_user) OR @@ -1008,130 +1008,130 @@ class CommonController extends ApiController ) ) $bd_usl ORDER BY `clients`.`id` DESC"; - } else { - $sql = "SELECT `id`, `email`, `fio`, `phone`, `phone2`, DATE_FORMAT(`date_add`, '%d.%m.%Y') AS `date_add`, `objects`, `deleted`, `confirm` + } else { + $sql = "SELECT `id`, `email`, `fio`, `phone`, `phone2`, DATE_FORMAT(`date_add`, '%d.%m.%Y') AS `date_add`, `objects`, `deleted`, `confirm` FROM `clients` WHERE $bd_user_j $bd_usl ORDER BY `clients`.`id` DESC"; - } + } - if ($offset) - $sql .= " LIMIT $offset, 10"; - else if ($offset == 0) - $sql .= " LIMIT 0, 10"; - else - $sql .= " LIMIT 100"; + if ($offset) + $sql .= " LIMIT $offset, 10"; + else if ($offset == 0) + $sql .= " LIMIT 0, 10"; + else + $sql .= " LIMIT 100"; - if ($rez = mysql_query($sql)) { - while($client = mysql_fetch_assoc($rez)) { + if ($rez = mysql_query($sql)) { + while($client = mysql_fetch_assoc($rez)) { - // Телефоны клиента - $phones = []; - $phones_dop = []; - if (!empty($client['phone'])) - $phones[] = $client['phone']; + // Телефоны клиента + $phones = []; + $phones_dop = []; + if (!empty($client['phone'])) + $phones[] = $client['phone']; - if (!empty($client['phone2'])) - $phones = array_merge($phones, json_decode(html_entity_decode($client['phone2'], ENT_QUOTES), true)); + if (!empty($client['phone2'])) + $phones = array_merge($phones, json_decode(html_entity_decode($client['phone2'], ENT_QUOTES), true)); - if (!empty($client['phone2'])) - $phones_dop = array_merge($phones_dop, json_decode(html_entity_decode($client['phone2'], ENT_QUOTES), true)); + if (!empty($client['phone2'])) + $phones_dop = array_merge($phones_dop, json_decode(html_entity_decode($client['phone2'], ENT_QUOTES), true)); - if (empty($phones)) - $phones = null; + if (empty($phones)) + $phones = null; - // Маскируем телефоны клиента в массиве phones_dop до implode, - // если у текущего пользователя включено `hide_client_contacts`. - if (!empty($phones_dop)) { - foreach ($phones_dop as &$_pdop) { - $_pdop = mask_phone_value_if_needed($_pdop); - } - unset($_pdop); - } + // Маскируем телефоны клиента в массиве phones_dop до implode, + // если у текущего пользователя включено `hide_client_contacts`. + if (!empty($phones_dop)) { + foreach ($phones_dop as &$_pdop) { + $_pdop = mask_phone_value_if_needed($_pdop); + } + unset($_pdop); + } - $clientItem = [ - 'id' => (int)$client['id'], - 'name' => $client['fio'], - 'phone' => $client['phone'], - 'phones' => $phones, - 'phones_dop' => (!empty($phones_dop)) ? implode(', ', $phones_dop) : '', - 'email' => (!empty($client['email'])) ? $client['email'] : null, - 'date_add' => $client['date_add'], - /*'objects' => $client['objects'], + $clientItem = [ + 'id' => (int)$client['id'], + 'name' => $client['fio'], + 'phone' => $client['phone'], + 'phones' => $phones, + 'phones_dop' => (!empty($phones_dop)) ? implode(', ', $phones_dop) : '', + 'email' => (!empty($client['email'])) ? $client['email'] : null, + 'date_add' => $client['date_add'], + /*'objects' => $client['objects'], 'is_deleted' => boolval($client['deleted']), 'is_confirm' => boolval($client['confirm']), 'id_agent' => $client['id_agent'], 'who_work' => $client['who_work'], 'source' => $client['source'],*/ - ]; - // Маскируем phone/email/имя клиента, если у текущего пользователя - // включено право `user_permissions.hide_client_contacts`. - // Helper сам проверяет право — если выключено, ничего не делает. - mask_client_contacts_inplace($clientItem); - $clients[] = $clientItem; - } - } else { - $error = true; - $errors[] = mysql_error(); - } + ]; + // Маскируем phone/email/имя клиента, если у текущего пользователя + // включено право `user_permissions.hide_client_contacts`. + // Helper сам проверяет право — если выключено, ничего не делает. + mask_client_contacts_inplace($clientItem); + $clients[] = $clientItem; + } + } else { + $error = true; + $errors[] = mysql_error(); + } - if (!$error) { + if (!$error) { - $sources = [ - 'success' => true, - 'user_id' => $user_id, - 'count' => count($clients), - 'list' => $clients, - '$sql' => $sql, - '$get' => $get, - ]; + $sources = [ + 'success' => true, + 'user_id' => $user_id, + 'count' => count($clients), + 'list' => $clients, + '$sql' => $sql, + '$get' => $get, + ]; - if ($need_return) { - return $sources; - } else { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode($sources, JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } - } + if ($need_return) { + return $sources; + } else { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode($sources, JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } + } - if ($need_return) { - return false; - } else { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => $user_id, - 'errors' => $errors, - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } + if ($need_return) { + return false; + } else { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => $user_id, + 'errors' => $errors, + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } - public function getСommercialTypes($app, $get = null, $post = null) { + public function getСommercialTypes($app, $get = null, $post = null) { - $error = false; - if ($user_id = $_SESSION['id']) { + $error = false; + if ($user_id = $_SESSION['id']) { - $pdo = $app->container->get('pdo'); + $pdo = $app->container->get('pdo'); - $list = []; - $sql = "SELECT * FROM commercial_object"; - $sql .= ' GROUP BY `id` ORDER BY `name`'; + $list = []; + $sql = "SELECT * FROM commercial_object"; + $sql .= ' GROUP BY `id` ORDER BY `name`'; - $sth = $pdo->prepare($sql); - if ($sth->execute()) { - while($row = $sth->fetch(\PDO::FETCH_BOTH)) { - $list[] = ['id' => intval($row["id"]), 'name' => $row["name"]]; - } - } else { - $error = true; - } + $sth = $pdo->prepare($sql); + if ($sth->execute()) { + while($row = $sth->fetch(\PDO::FETCH_BOTH)) { + $list[] = ['id' => intval($row["id"]), 'name' => $row["name"]]; + } + } else { + $error = true; + } - if (!$error && count($list)) { + if (!$error && count($list)) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ @@ -1143,75 +1143,75 @@ class CommonController extends ApiController } } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } - public function getRegions($app, $get = null, $post = null) { + public function getRegions($app, $get = null, $post = null) { - $error = false; + $error = false; - $sub_regions = false; - if (isset($get['sub_regions'])) - $sub_regions = true; + $sub_regions = false; + if (isset($get['sub_regions'])) + $sub_regions = true; - if ($user_id = $_SESSION['id']) { + if ($user_id = $_SESSION['id']) { - $pdo = $app->container->get('pdo'); + $pdo = $app->container->get('pdo'); - $list = []; + $list = []; - if ($sub_regions) - $sql = "SELECT * FROM rf_regions "; - else - $sql = "SELECT * FROM rf_regions WHERE parent = 0"; + if ($sub_regions) + $sql = "SELECT * FROM rf_regions "; + else + $sql = "SELECT * FROM rf_regions WHERE parent = 0"; - $sql .= ' GROUP BY `id` ORDER BY `id`, `name`'; + $sql .= ' GROUP BY `id` ORDER BY `id`, `name`'; - $sth = $pdo->prepare($sql); - if ($sth->execute()) { - while($row = $sth->fetch(\PDO::FETCH_BOTH)) { + $sth = $pdo->prepare($sql); + if ($sth->execute()) { + while($row = $sth->fetch(\PDO::FETCH_BOTH)) { - $kladr = []; - if (intval($row["kladr"])) { - $kladr[] = $row["kladr"]; - } else { - if (intval($row["id"]) == 1) { // Москва и Московская область - $kladr = [ - '7700000000000', - '5000000000000' - ]; - } else if (intval($row["id"]) == 2) { // Санкт-Петербург и Ленинградская обл - $kladr = [ - '7800000000000', - '4700000000000' - ]; - } else if (intval($row["id"]) == 3) { // Крым и Севастополь - $kladr = [ - '9100000000000', - '9200000000000' - ]; - } - } + $kladr = []; + if (intval($row["kladr"])) { + $kladr[] = $row["kladr"]; + } else { + if (intval($row["id"]) == 1) { // Москва и Московская область + $kladr = [ + '7700000000000', + '5000000000000' + ]; + } else if (intval($row["id"]) == 2) { // Санкт-Петербург и Ленинградская обл + $kladr = [ + '7800000000000', + '4700000000000' + ]; + } else if (intval($row["id"]) == 3) { // Крым и Севастополь + $kladr = [ + '9100000000000', + '9200000000000' + ]; + } + } - $list[] = [ - 'id' => intval($row["id"]), - 'name' => $row["name"], - 'kladr' => $kladr, - 'code_id' => intval($row["code"]), - 'parent_id' => intval($row["parent"]), - ]; - } - } else { - $error = true; - } + $list[] = [ + 'id' => intval($row["id"]), + 'name' => $row["name"], + 'kladr' => $kladr, + 'code_id' => intval($row["code"]), + 'parent_id' => intval($row["parent"]), + ]; + } + } else { + $error = true; + } - if (!$error && count($list)) { + if (!$error && count($list)) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ @@ -1223,275 +1223,275 @@ class CommonController extends ApiController } } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } - public function getDistricts($app, $get = null, $post = null) { + public function getDistricts($app, $get = null, $post = null) { - $error = false; - $errors = []; - if ($user_id = $_SESSION['id']) { + $error = false; + $errors = []; + if ($user_id = $_SESSION['id']) { - $region_rf_id = null; - if (isset($get['region_id'])) - $region_rf_id = $get['region_id']; + $region_rf_id = null; + if (isset($get['region_id'])) + $region_rf_id = $get['region_id']; - $list = []; - $groups = []; + $list = []; + $groups = []; - $mdb = $app->container->get('mysql'); + $mdb = $app->container->get('mysql'); - $region = []; - if ($region_rf_id) { - if (is_array($region_rf_id)) { + $region = []; + if ($region_rf_id) { + if (is_array($region_rf_id)) { - if (in_array(80, $region_rf_id)) - $region_rf_id[] = 1; + if (in_array(80, $region_rf_id)) + $region_rf_id[] = 1; - if (in_array(81, $region_rf_id)) - $region_rf_id[] = 2; + if (in_array(81, $region_rf_id)) + $region_rf_id[] = 2; - $sql = "SELECT rf_regions.* FROM rf_regions AS parent + $sql = "SELECT rf_regions.* FROM rf_regions AS parent JOIN rf_regions ON rf_regions.parent = parent.id WHERE parent.id IN (" . implode(',', $region_rf_id) . ") ORDER BY id ASC"; - } else { - $sql = "SELECT rf_regions.* FROM rf_regions AS parent + } else { + $sql = "SELECT rf_regions.* FROM rf_regions AS parent JOIN rf_regions ON rf_regions.parent = parent.id WHERE parent.id = $region_rf_id ORDER BY id ASC"; - } - } else { - $sql = "SELECT rf_regions.* FROM rf_regions AS parent + } + } else { + $sql = "SELECT rf_regions.* FROM rf_regions AS parent JOIN rf_regions ON rf_regions.parent = parent.id LEFT JOIN users ON users.region_rf_id = parent.id WHERE users.id = $user_id ORDER BY id ASC"; - } + } - if ($rez = mysql_query($sql)) { - while($row = mysql_fetch_assoc($rez)) { - $region[] = $row; - } - } else { - $error = true; - $errors[] = mysql_error(); - } + if ($rez = mysql_query($sql)) { + while($row = mysql_fetch_assoc($rez)) { + $region[] = $row; + } + } else { + $error = true; + $errors[] = mysql_error(); + } - if (empty($region)) { - $region = [ - [ - 'id' => 47, - 'name' => 'Ленинградская обл', - 'kladr' => '4700000000000', - 'parent' => 94, - 'code' => 47 - ], [ - 'id' => 78, - 'name' => 'Санкт-Петербург', - 'kladr' => '7800000000000', - 'parent' => 94, - 'code' => 78 - ] - ]; - } + if (empty($region)) { + $region = [ + [ + 'id' => 47, + 'name' => 'Ленинградская обл', + 'kladr' => '4700000000000', + 'parent' => 94, + 'code' => 47 + ], [ + 'id' => 78, + 'name' => 'Санкт-Петербург', + 'kladr' => '7800000000000', + 'parent' => 94, + 'code' => 78 + ] + ]; + } - if ($region[1]['code'] == 78) { + if ($region[1]['code'] == 78) { - $sql = "SELECT * FROM rayon WHERE id IN (15,3,6,7,1,23,13,22,33,25,11,10,8,26,12,27,5,2,28,9) OR is_lo = 1 ORDER BY is_lo, rayon"; - if ($rez = mysql_query($sql)) { - $group_id = (int)$region[1]['id']; - $group_name = 'Санкт-Петербург'; + $sql = "SELECT * FROM rayon WHERE id IN (15,3,6,7,1,23,13,22,33,25,11,10,8,26,12,27,5,2,28,9) OR is_lo = 1 ORDER BY is_lo, rayon"; + if ($rez = mysql_query($sql)) { + $group_id = (int)$region[1]['id']; + $group_name = 'Санкт-Петербург'; - while($rayon = mysql_fetch_assoc($rez)) { - if ($rayon['is_lo'] == 1) - $group_name = 'Ленинградская область'; + while($rayon = mysql_fetch_assoc($rez)) { + if ($rayon['is_lo'] == 1) + $group_name = 'Ленинградская область'; - $list[] = ['id' => (int)$rayon['id'], 'name' => $rayon['rayon'], 'group_id' => (int)$group_id]; - } + $list[] = ['id' => (int)$rayon['id'], 'name' => $rayon['rayon'], 'group_id' => (int)$group_id]; + } - $groups[] = ['id' => $group_id, 'name' => $group_name]; - } else { - $error = true; - $errors[] = mysql_error(); - } - } else if ($region[1]['code'] == 77) { + $groups[] = ['id' => $group_id, 'name' => $group_name]; + } else { + $error = true; + $errors[] = mysql_error(); + } + } else if ($region[1]['code'] == 77) { - $group_id = (int)$region[1]['id']; - $groups[] = ['id' => $group_id, 'name' => $region[1]['name']]; + $group_id = (int)$region[1]['id']; + $groups[] = ['id' => $group_id, 'name' => $region[1]['name']]; - $sql = "SELECT * FROM rf_regions WHERE parent = $group_id"; - if ($rez = mysql_query($sql)) { - if (mysql_num_rows($rez) > 0) { - while($sub_region = mysql_fetch_assoc($rez)) { + $sql = "SELECT * FROM rf_regions WHERE parent = $group_id"; + if ($rez = mysql_query($sql)) { + if (mysql_num_rows($rez) > 0) { + while($sub_region = mysql_fetch_assoc($rez)) { - $group_id = $sub_region['id']; - $groups[] = ['id' => $group_id, 'name' => $sub_region['name']]; + $group_id = $sub_region['id']; + $groups[] = ['id' => $group_id, 'name' => $sub_region['name']]; - $sql = "SELECT * FROM rayon WHERE id IN (SELECT rayon_id FROM rf_region_rayons WHERE rf_region_id = $group_id)"; - $rez_rayon = mysql_query($sql); - while ($rayon = mysql_fetch_assoc($rez_rayon)) { - $list[] = ['id' => (int)$rayon['id'], 'name' => $rayon['rayon'], 'group_id' => (int)$group_id]; - } - } - } - } else { - $error = true; - $errors[] = mysql_error(); - } - } else { + $sql = "SELECT * FROM rayon WHERE id IN (SELECT rayon_id FROM rf_region_rayons WHERE rf_region_id = $group_id)"; + $rez_rayon = mysql_query($sql); + while ($rayon = mysql_fetch_assoc($rez_rayon)) { + $list[] = ['id' => (int)$rayon['id'], 'name' => $rayon['rayon'], 'group_id' => (int)$group_id]; + } + } + } + } else { + $error = true; + $errors[] = mysql_error(); + } + } else { - $group_id = (int)$region[1]['id']; - $groups[] = ['id' => $group_id, 'name' => $region[1]['name']]; + $group_id = (int)$region[1]['id']; + $groups[] = ['id' => $group_id, 'name' => $region[1]['name']]; - $sql = "SELECT * FROM rayon WHERE id IN (SELECT rayon_id FROM rf_region_rayons WHERE rf_region_id = $group_id)"; - if ($rez = mysql_query($sql)) { - if (mysql_num_rows($rez) > 0) { - while($rayon = mysql_fetch_assoc($rez)) { - $list[] = ['id' => (int)$rayon['id'], 'name' => $rayon['rayon'], 'group_id' => (int)$group_id]; - } - } else { - $list[] = ['id' => 0, 'name' => 'Весь город', 'group_id' => (int)$group_id]; - } - } else { - $error = true; - $errors[] = mysql_error(); - } - } + $sql = "SELECT * FROM rayon WHERE id IN (SELECT rayon_id FROM rf_region_rayons WHERE rf_region_id = $group_id)"; + if ($rez = mysql_query($sql)) { + if (mysql_num_rows($rez) > 0) { + while($rayon = mysql_fetch_assoc($rez)) { + $list[] = ['id' => (int)$rayon['id'], 'name' => $rayon['rayon'], 'group_id' => (int)$group_id]; + } + } else { + $list[] = ['id' => 0, 'name' => 'Весь город', 'group_id' => (int)$group_id]; + } + } else { + $error = true; + $errors[] = mysql_error(); + } + } - if (!empty($region[0]['id']) && isset($group_id)) { - $sql = "SELECT * FROM rayon where id in (SELECT rayon_id FROM rf_region_rayons WHERE rf_region_id = ".$region[0]['id'].")"; - if ($rez = mysql_query($sql)) { - if (mysql_num_rows($rez) > 0) { - while($rayon = mysql_fetch_assoc($rez)) { - $list[] = ['id' => (int)$rayon['id'], 'name' => $rayon['rayon'], 'group_id' => (int)$group_id]; - } - } else { - $list[] = ['id' => 0, 'name' => 'Весь город', 'group_id' => (int)$group_id]; - } - } else { - $error = true; - $errors[] = mysql_error(); - } - } + if (!empty($region[0]['id']) && isset($group_id)) { + $sql = "SELECT * FROM rayon where id in (SELECT rayon_id FROM rf_region_rayons WHERE rf_region_id = ".$region[0]['id'].")"; + if ($rez = mysql_query($sql)) { + if (mysql_num_rows($rez) > 0) { + while($rayon = mysql_fetch_assoc($rez)) { + $list[] = ['id' => (int)$rayon['id'], 'name' => $rayon['rayon'], 'group_id' => (int)$group_id]; + } + } else { + $list[] = ['id' => 0, 'name' => 'Весь город', 'group_id' => (int)$group_id]; + } + } else { + $error = true; + $errors[] = mysql_error(); + } + } - if (!$error) { + if (!$error) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); - if (!is_array($region_rf_id)) { - $app->response->setBody(json_encode([ - 'success' => true, - 'user_id' => (int)$user_id, - 'count' => count($list), - 'list' => $list, - 'groups' => $groups, - 'parent_region' => (int)$region[1]['parent'], - 'region_type' => (int)$region[1]['id'], - ], JSON_UNESCAPED_UNICODE)); - } else { - $app->response->setBody(json_encode([ - 'success' => true, - 'user_id' => (int)$user_id, - 'count' => count($list), - 'list' => $list, - 'groups' => $groups, - 'sql' => $sql, - ], JSON_UNESCAPED_UNICODE)); - } + if (!is_array($region_rf_id)) { + $app->response->setBody(json_encode([ + 'success' => true, + 'user_id' => (int)$user_id, + 'count' => count($list), + 'list' => $list, + 'groups' => $groups, + 'parent_region' => (int)$region[1]['parent'], + 'region_type' => (int)$region[1]['id'], + ], JSON_UNESCAPED_UNICODE)); + } else { + $app->response->setBody(json_encode([ + 'success' => true, + 'user_id' => (int)$user_id, + 'count' => count($list), + 'list' => $list, + 'groups' => $groups, + 'sql' => $sql, + ], JSON_UNESCAPED_UNICODE)); + } $app->stop(); } } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } - public function getMetro($app, $get = null, $post = null) { + public function getMetro($app, $get = null, $post = null) { - $error = false; - $errors = []; - if ($user_id = $_SESSION['id']) { + $error = false; + $errors = []; + if ($user_id = $_SESSION['id']) { - $region_rf_id = null; - if (isset($get['region_id'])) - $region_rf_id = $get['region_id']; + $region_rf_id = null; + if (isset($get['region_id'])) + $region_rf_id = $get['region_id']; - $list = []; - $mdb = $app->container->get('mysql'); + $list = []; + $mdb = $app->container->get('mysql'); - $region = []; - if ($region_rf_id) { - if (is_array($region_rf_id)) { - $sql = "SELECT rf_regions.* FROM rf_regions AS parent + $region = []; + if ($region_rf_id) { + if (is_array($region_rf_id)) { + $sql = "SELECT rf_regions.* FROM rf_regions AS parent JOIN rf_regions ON rf_regions.parent = parent.id WHERE parent.id IN (" . implode(',', $region_rf_id) . ") ORDER BY id ASC"; - } else { - $sql = "SELECT rf_regions.* FROM rf_regions AS parent + } else { + $sql = "SELECT rf_regions.* FROM rf_regions AS parent JOIN rf_regions ON rf_regions.parent = parent.id WHERE parent.id = $region_rf_id ORDER BY id ASC"; - } - } else { - $sql = "SELECT rf_regions.* FROM rf_regions AS parent + } + } else { + $sql = "SELECT rf_regions.* FROM rf_regions AS parent JOIN rf_regions ON rf_regions.parent = parent.id LEFT JOIN users ON users.region_rf_id = parent.id WHERE users.id = $user_id ORDER BY id ASC"; - } + } - if ($rez = mysql_query($sql)) { - while($row = mysql_fetch_assoc($rez)) { - $region[] = $row; - } - } else { - $error = true; - $errors[] = mysql_error(); - } + if ($rez = mysql_query($sql)) { + while($row = mysql_fetch_assoc($rez)) { + $region[] = $row; + } + } else { + $error = true; + $errors[] = mysql_error(); + } - if (empty($region)) { - $region[0] = array( - 'id' => 47, - 'name' => 'Ленинградская обл', - 'kladr' => '4700000000000', - 'parent' => 94, - 'code' => 47 - ); - $region[1] = array( - 'id' => 78, - 'name' => 'Санкт-Петербург', - 'kladr' => '7800000000000', - 'parent' => 94, - 'code' => 78 - ); - } + if (empty($region)) { + $region[0] = array( + 'id' => 47, + 'name' => 'Ленинградская обл', + 'kladr' => '4700000000000', + 'parent' => 94, + 'code' => 47 + ); + $region[1] = array( + 'id' => 78, + 'name' => 'Санкт-Петербург', + 'kladr' => '7800000000000', + 'parent' => 94, + 'code' => 78 + ); + } - $sql = "SELECT * FROM metro WHERE region_rf_id = ".$region[0]['id']; + $sql = "SELECT * FROM metro WHERE region_rf_id = ".$region[0]['id']; - if (isset($region[1])) - $sql .=" OR region_rf_id = ".$region[1]['id']; + if (isset($region[1])) + $sql .=" OR region_rf_id = ".$region[1]['id']; - if ($rez = mysql_query($sql)) { - if (mysql_num_rows($rez) > 0) { - if ($region[1]['code'] !== 78) { - while ($metro = mysql_fetch_assoc($rez)) { - $list[] = ['id' => (int)$metro['id'], 'name' => $metro['metro']]; - } - } - } - } else { - $error = true; - $errors[] = mysql_error(); - } + if ($rez = mysql_query($sql)) { + if (mysql_num_rows($rez) > 0) { + if ($region[1]['code'] !== 78) { + while ($metro = mysql_fetch_assoc($rez)) { + $list[] = ['id' => (int)$metro['id'], 'name' => $metro['metro']]; + } + } + } + } else { + $error = true; + $errors[] = mysql_error(); + } - if (!$error) { + if (!$error) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ @@ -1505,56 +1505,56 @@ class CommonController extends ApiController } } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id, - 'errors' => $errors - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id, + 'errors' => $errors + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } - - public function getHighway($app, $get = null, $post = null) { - $error = false; - $errors = []; - if ($user_id = $_SESSION['id']) { + public function getHighway($app, $get = null, $post = null) { - $region_rf_id = null; - if (isset($get['region_id'])) - $region_rf_id = $get['region_id']; + $error = false; + $errors = []; + if ($user_id = $_SESSION['id']) { - $list = []; - $mdb = $app->container->get('mysql'); + $region_rf_id = null; + if (isset($get['region_id'])) + $region_rf_id = $get['region_id']; - $region = []; - if ($region_rf_id) { - - $sql = "SELECT highways.* FROM highways + $list = []; + $mdb = $app->container->get('mysql'); + + $region = []; + if ($region_rf_id) { + + $sql = "SELECT highways.* FROM highways WHERE highways.region_id = $region_rf_id"; - - } else { - $sql = "SELECT highways.* FROM highways AS h + + } else { + $sql = "SELECT highways.* FROM highways AS h LEFT JOIN users ON users.region_rf_id = h.region_id WHERE users.id = $user_id AND h.region_id=users.region_rf_id ORDER BY id ASC"; - } + } - if ($rez = mysql_query($sql)) { - if (mysql_num_rows($rez) > 0) { - - while ($highway = mysql_fetch_assoc($rez)) { - $list[] = ['id' => (int)$highway['cian_id'], 'name' => $highway['name']]; - } - - } - } else { - $error = true; - $errors[] = mysql_error(); - } + if ($rez = mysql_query($sql)) { + if (mysql_num_rows($rez) > 0) { - if (!$error) { + while ($highway = mysql_fetch_assoc($rez)) { + $list[] = ['id' => (int)$highway['cian_id'], 'name' => $highway['name']]; + } + + } + } else { + $error = true; + $errors[] = mysql_error(); + } + + if (!$error) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ @@ -1568,37 +1568,37 @@ class CommonController extends ApiController } } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id, - 'errors' => $errors - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id, + 'errors' => $errors + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } - public function getLayouts($app, $get = null, $post = null) { + public function getLayouts($app, $get = null, $post = null) { - $error = false; - if ($user_id = $_SESSION['id']) { + $error = false; + if ($user_id = $_SESSION['id']) { - $pdo = $app->container->get('pdo'); + $pdo = $app->container->get('pdo'); - $list = []; - $sql = "SELECT * FROM layout_object"; - $sql .= ' GROUP BY `id` ORDER BY `name`'; + $list = []; + $sql = "SELECT * FROM layout_object"; + $sql .= ' GROUP BY `id` ORDER BY `name`'; - $sth = $pdo->prepare($sql); - if ($sth->execute()) { - while($row = $sth->fetch(\PDO::FETCH_BOTH)) { - $list[] = ['id' => intval($row["id"]), 'name' => $row["name"]]; - } - } else { - $error = true; - } + $sth = $pdo->prepare($sql); + if ($sth->execute()) { + while($row = $sth->fetch(\PDO::FETCH_BOTH)) { + $list[] = ['id' => intval($row["id"]), 'name' => $row["name"]]; + } + } else { + $error = true; + } - if (!$error && count($list)) { + if (!$error && count($list)) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ @@ -1610,392 +1610,392 @@ class CommonController extends ApiController } } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } - public function is_see($app, $is_no_see, $users_no_see){ - $mdb = $app->container->get('mysql'); - $is_see = true; - $tempArrNoSee = json_decode($users_no_see, true); - if($is_no_see == 1 && !empty($users_no_see) && !empty($tempArrNoSee)){ - $is_see = false; - $arrNoSeeUsers = array(); - - foreach($tempArrNoSee as $u){ - if(strpos($u, 'all_') !== false){ - $manId = str_replace('all_', '', $u); - $sql_u = "SELECT id FROM `users` + public function is_see($app, $is_no_see, $users_no_see){ + $mdb = $app->container->get('mysql'); + $is_see = true; + $tempArrNoSee = json_decode($users_no_see, true); + if($is_no_see == 1 && !empty($users_no_see) && !empty($tempArrNoSee)){ + $is_see = false; + $arrNoSeeUsers = array(); + + foreach($tempArrNoSee as $u){ + if(strpos($u, 'all_') !== false){ + $manId = str_replace('all_', '', $u); + $sql_u = "SELECT id FROM `users` WHERE id = $manId OR id_manager = $manId OR id_manager IN (SELECT id FROM users WHERE id_manager = $manId)"; - $q_u = mysql_query($sql_u); - while($r_u = mysql_fetch_row($q_u)){ - $arrNoSeeUsers[] = (int)$r_u[0]; - } - } else { - $arrNoSeeUsers[] = (int)$u; - } - } - - if(in_array($_SESSION['id'], $arrNoSeeUsers)){ - $is_see = true; - } - } - - return $is_see; - } + $q_u = mysql_query($sql_u); + while($r_u = mysql_fetch_row($q_u)){ + $arrNoSeeUsers[] = (int)$r_u[0]; + } + } else { + $arrNoSeeUsers[] = (int)$u; + } + } - public function getRoles($app, $get = null, $post = null) { + if(in_array($_SESSION['id'], $arrNoSeeUsers)){ + $is_see = true; + } + } - global $ROLES_CLIENTS; - $error = false; - $section = $get['section']; - if ($section && ($user_id = $_SESSION['id'])) { + return $is_see; + } - $roles = []; - switch ($section) { - case 'clients' : + public function getRoles($app, $get = null, $post = null) { - if ($_SESSION['agency_id'] == 7911 && !in_array("Страхование", $ROLES_CLIENTS)) - $ROLES_CLIENTS[] = "Страхование"; + global $ROLES_CLIENTS; + $error = false; + $section = $get['section']; + if ($section && ($user_id = $_SESSION['id'])) { - if ($_SESSION['agency_id'] == 7911 && !in_array("Путевки", $ROLES_CLIENTS)) - $ROLES_CLIENTS[] = "Путевки"; + $roles = []; + switch ($section) { + case 'clients' : - if ($_SESSION['agency_id'] == 7911 && !in_array("Юр.услуги", $ROLES_CLIENTS)) - $ROLES_CLIENTS[] = "Юр.услуги"; + if ($_SESSION['agency_id'] == 7911 && !in_array("Страхование", $ROLES_CLIENTS)) + $ROLES_CLIENTS[] = "Страхование"; - foreach($ROLES_CLIENTS as $key => $val) { - if (intval($key) > 0) { - $roles[] = ['id' => intval($key), 'name' => $val]; - } - } + if ($_SESSION['agency_id'] == 7911 && !in_array("Путевки", $ROLES_CLIENTS)) + $ROLES_CLIENTS[] = "Путевки"; - break; - } + if ($_SESSION['agency_id'] == 7911 && !in_array("Юр.услуги", $ROLES_CLIENTS)) + $ROLES_CLIENTS[] = "Юр.услуги"; - if (count($roles)) { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => !$error, - 'user_id' => (int)$user_id, - 'list' => $roles - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } + foreach($ROLES_CLIENTS as $key => $val) { + if (intval($key) > 0) { + $roles[] = ['id' => intval($key), 'name' => $val]; + } + } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + break; + } - public function getRequisitions($app, $get = null, $post = null) { + if (count($roles)) { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => !$error, + 'user_id' => (int)$user_id, + 'list' => $roles + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } - $error = false; - $errors = []; + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } - if ($user_id = $_SESSION['id']) { + public function getRequisitions($app, $get = null, $post = null) { - $requisitions = []; - $mdb = $app->container->get('mysql'); - $users_ids[] = (int)$user_id; + $error = false; + $errors = []; - $user = new \User(); - $user->get($user_id); - if ($_SESSION['users_admin']) - $user_id = $user->getUserAgencyID(); + if ($user_id = $_SESSION['id']) { - $users_ids[] = $user_id; - if ($user->get($user_id)) { - if ($user->agency) { - if ($query = mysql_query("SELECT `id` FROM `users` WHERE `id_manager`='$user_id' AND `manager`=1")) { - while ($row = mysql_fetch_row($query)) { - if (!empty($row[0])) { - $users_ids[] = $row[0]; + $requisitions = []; + $mdb = $app->container->get('mysql'); + $users_ids[] = (int)$user_id; - if ($query2 = mysql_query("SELECT `id` FROM `users` WHERE `id_manager`='$row[0]'")) { - while ($row2 = mysql_fetch_row($query2)) { + $user = new \User(); + $user->get($user_id); + if ($_SESSION['users_admin']) + $user_id = $user->getUserAgencyID(); - if (!empty($row[0])) - $users_ids[] = $row2[0]; + $users_ids[] = $user_id; + if ($user->get($user_id)) { + if ($user->agency) { + if ($query = mysql_query("SELECT `id` FROM `users` WHERE `id_manager`='$user_id' AND `manager`=1")) { + while ($row = mysql_fetch_row($query)) { + if (!empty($row[0])) { + $users_ids[] = $row[0]; - } - } else { - $error = true; - $errors[] = mysql_error(); - } - } - } - } else { - $error = true; - $errors[] = mysql_error(); - } - } else if ($user->manager) { - if ($query = mysql_query("SELECT `id` FROM `users` WHERE `id_manager`='$user_id'")) { - while ($row = mysql_fetch_row($query)) { + if ($query2 = mysql_query("SELECT `id` FROM `users` WHERE `id_manager`='$row[0]'")) { + while ($row2 = mysql_fetch_row($query2)) { - if (!empty($row[0])) - $users_ids[] = $row[0]; + if (!empty($row[0])) + $users_ids[] = $row2[0]; - } - } else { - $error = true; - $errors[] = mysql_error(); - } - } - } + } + } else { + $error = true; + $errors[] = mysql_error(); + } + } + } + } else { + $error = true; + $errors[] = mysql_error(); + } + } else if ($user->manager) { + if ($query = mysql_query("SELECT `id` FROM `users` WHERE `id_manager`='$user_id'")) { + while ($row = mysql_fetch_row($query)) { - $users_ids = array_unique($users_ids); - $bd_usl_managers = " AND `user_id` IN (" . implode(',', $users_ids) . ")"; + if (!empty($row[0])) + $users_ids[] = $row[0]; - $sql = "SELECT `id`, `name`, `client_id` FROM `requisitions` WHERE 1 $bd_usl_managers AND `deleted` <> 1"; - if (isset($post['ids']) && count($post['ids'])) { - $sql = "SELECT `id`, `name`, `client_id` FROM `requisitions` WHERE `id` IN (" . implode(',', $post['ids']) . ")"; - } + } + } else { + $error = true; + $errors[] = mysql_error(); + } + } + } - if ($query = mysql_query($sql)) { - while ($row = mysql_fetch_assoc($query)) { - $requisitions[] = [ - 'id' => (int)$row['id'], - 'name' => $row['name'], - ]; - } - } else { - $error = true; - $errors[] = mysql_error(); - } + $users_ids = array_unique($users_ids); + $bd_usl_managers = " AND `user_id` IN (" . implode(',', $users_ids) . ")"; - if (count($requisitions)) { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => !$error, - 'user_id' => (int)$user_id, - 'list' => $requisitions, - 'errors' => $errors - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } + $sql = "SELECT `id`, `name`, `client_id` FROM `requisitions` WHERE 1 $bd_usl_managers AND `deleted` <> 1"; + if (isset($post['ids']) && count($post['ids'])) { + $sql = "SELECT `id`, `name`, `client_id` FROM `requisitions` WHERE `id` IN (" . implode(',', $post['ids']) . ")"; + } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$_SESSION['id'], - 'errors' => $errors - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + if ($query = mysql_query($sql)) { + while ($row = mysql_fetch_assoc($query)) { + $requisitions[] = [ + 'id' => (int)$row['id'], + 'name' => $row['name'], + ]; + } + } else { + $error = true; + $errors[] = mysql_error(); + } - public function getSources($app, $get = null, $post = null) { + if (count($requisitions)) { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => !$error, + 'user_id' => (int)$user_id, + 'list' => $requisitions, + 'errors' => $errors + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } - $error = false; - if ($user_id = $_SESSION['id']) { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$_SESSION['id'], + 'errors' => $errors + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } - // Открываем соединение с БД - $pdo = $app->container->get('pdo'); - $mdb = $app->container->get('mysql'); + public function getSources($app, $get = null, $post = null) { - $user = new \User; - $user->get($user_id); + $error = false; + if ($user_id = $_SESSION['id']) { - $sources = []; - $search = null; + // Открываем соединение с БД + $pdo = $app->container->get('pdo'); + $mdb = $app->container->get('mysql'); - $page = 1; - if (isset($get['page'])) - $page = $get['page']; + $user = new \User; + $user->get($user_id); - // Number of records fetch - $numberOfRecords = 1000; + $sources = []; + $search = null; - if (isset($get['searchTerm'])) - $search = $get['searchTerm']; // Search text + $page = 1; + if (isset($get['page'])) + $page = $get['page']; - if ($search == null || strpos("объекты нашей компании", strtolower($search)) !== false) { - $sources[] = array( - "id" => 10000, - "name" => "Объекты нашей компании", - "source_see" => 1 - ); - $numberOfRecords--; - } + // Number of records fetch + $numberOfRecords = 1000; - $list = []; + if (isset($get['searchTerm'])) + $search = $get['searchTerm']; // Search text - $sql_where = " `user_id` = '".$user->id."' or `manager_id` = '".$user->id."'"; - if ($user->id_manager) - $sql_where .= " or `manager_id` = '".$user->id_manager."' or `user_id` = '".$user->id_manager."'"; + if ($search == null || strpos("объекты нашей компании", strtolower($search)) !== false) { + $sources[] = array( + "id" => 10000, + "name" => "Объекты нашей компании", + "source_see" => 1 + ); + $numberOfRecords--; + } - if ($user -> agencyId) - $sql_where .= " or `manager_id` = '".$user -> agencyId."' or `user_id` = '".$user -> agencyId."'"; + $list = []; - if ($search == null) - $sqlCount = "SELECT COUNT(id) FROM `advertising_sources` WHERE $sql_where"; - else - $sqlCount = "SELECT COUNT(id) FROM `advertising_sources` WHERE ($sql_where) AND source LIKE '%" . trim($search) . "%'"; + $sql_where = " `user_id` = '".$user->id."' or `manager_id` = '".$user->id."'"; + if ($user->id_manager) + $sql_where .= " or `manager_id` = '".$user->id_manager."' or `user_id` = '".$user->id_manager."'"; - $rez = mysql_query($sqlCount); // @todo: implement to PDO - $all_count = mysql_result($rez, 0); - $all_pages = ceil($all_count / $numberOfRecords); - $limit = ($page - 1) * $numberOfRecords; + if ($user -> agencyId) + $sql_where .= " or `manager_id` = '".$user -> agencyId."' or `user_id` = '".$user -> agencyId."'"; - if ($search == null) { - $sql = "SELECT * + if ($search == null) + $sqlCount = "SELECT COUNT(id) FROM `advertising_sources` WHERE $sql_where"; + else + $sqlCount = "SELECT COUNT(id) FROM `advertising_sources` WHERE ($sql_where) AND source LIKE '%" . trim($search) . "%'"; + + $rez = mysql_query($sqlCount); // @todo: implement to PDO + $all_count = mysql_result($rez, 0); + $all_pages = ceil($all_count / $numberOfRecords); + $limit = ($page - 1) * $numberOfRecords; + + if ($search == null) { + $sql = "SELECT * FROM `advertising_sources` WHERE $sql_where ORDER BY source, id LIMIT $limit, $numberOfRecords"; - } else { - $sql = "SELECT * + } else { + $sql = "SELECT * FROM `advertising_sources` WHERE ($sql_where) AND source LIKE '%" . trim($search) . "%' ORDER BY source, id LIMIT $limit, $numberOfRecords"; - } + } - if ($rez = mysql_query($sql)) { // @todo: implement to PDO - while ($block = mysql_fetch_assoc($rez)) { - $block['source_see'] = 1; + if ($rez = mysql_query($sql)) { // @todo: implement to PDO + while ($block = mysql_fetch_assoc($rez)) { + $block['source_see'] = 1; if($this->is_see($app, $block['is_no_see'], $block['users_no_see']) === false){ $block['source_see'] = 0; - + } - $list[] = $block; - - - } - } else { - $error = true; - } + $list[] = $block; - // Read Data - foreach ($list as $item) { - $sources[] = [ - "id" => intval($item['id']), - "name" => $item['source'], - "source_see" => $item['source_see'] - ]; - } - if ($search == null || strpos("источник не выбран", strtolower($search)) !== false) { - $sources[] = [ - "id" => 0, - "name" => "Источник не выбран", - "source_see" => 1 - ]; - } + } + } else { + $error = true; + } - if (count($sources)) { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => !$error, - 'user_id' => (int)$user_id, - 'total_count' => $all_count, - 'list' => $sources - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } + // Read Data + foreach ($list as $item) { + $sources[] = [ + "id" => intval($item['id']), + "name" => $item['source'], + "source_see" => $item['source_see'] + ]; + } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + if ($search == null || strpos("источник не выбран", strtolower($search)) !== false) { + $sources[] = [ + "id" => 0, + "name" => "Источник не выбран", + "source_see" => 1 + ]; + } - public function getFunnels($app, $get = null, $post = null, $need_return = false) { + if (count($sources)) { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => !$error, + 'user_id' => (int)$user_id, + 'total_count' => $all_count, + 'list' => $sources + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } - $error = false; - $errors = []; - if ($user_id = $_SESSION['id']) { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } - // Открываем соединение с БД - $mdb = $app->container->get('mysql'); + public function getFunnels($app, $get = null, $post = null, $need_return = false) { - $user = new \User(); - $user->get($user_id); - $agency_id = $user->agencyId; + $error = false; + $errors = []; + if ($user_id = $_SESSION['id']) { - $funnels = []; - $section = $get['section']; // requisitions, clients - $filters = $get['filters']; - $use_counters = $get['use_counters'] || null; + // Открываем соединение с БД + $mdb = $app->container->get('mysql'); - if (!in_array($agency_id, [6841, 6426, 7384, 7478, 8353, 8867, 9588])) - $use_custom = true; - else - $use_custom = false; + $user = new \User(); + $user->get($user_id); + $agency_id = $user->agencyId; - $default = "Обычные"; - $sql = "SELECT * FROM `funnel_default` WHERE `agency_id` = '$agency_id'"; + $funnels = []; + $section = $get['section']; // requisitions, clients + $filters = $get['filters']; + $use_counters = $get['use_counters'] || null; - if ($section == 'requisitions') - $sql = "SELECT * FROM `funnel_default` WHERE `agency_id` = '$agency_id'"; + if (!in_array($agency_id, [6841, 6426, 7384, 7478, 8353, 8867, 9588])) + $use_custom = true; + else + $use_custom = false; - if ($query = mysql_query($sql)) { - if (mysql_num_rows($query) > 0) { + $default = "Обычные"; + $sql = "SELECT * FROM `funnel_default` WHERE `agency_id` = '$agency_id'"; - $row = mysql_fetch_assoc($query); - if (!empty($row['name'])) - $default = $row['name']; + if ($section == 'requisitions') + $sql = "SELECT * FROM `funnel_default` WHERE `agency_id` = '$agency_id'"; - if ($section == 'clients' && $row['is_client'] == 0) - $use_custom = false; + if ($query = mysql_query($sql)) { + if (mysql_num_rows($query) > 0) { - if ($section == 'requisitions' && $row['is_req'] == 0) - $use_custom = false; + $row = mysql_fetch_assoc($query); + if (!empty($row['name'])) + $default = $row['name']; - } - } else { - $error = true; - $errors[] = mysql_error(); - } + if ($section == 'clients' && $row['is_client'] == 0) + $use_custom = false; - $new_ids = []; - $funnelCounts = []; + if ($section == 'requisitions' && $row['is_req'] == 0) + $use_custom = false; - // Счётчики в воронках - if ($use_counters) { + } + } else { + $error = true; + $errors[] = mysql_error(); + } - if ($section == 'clients') - $_SESSION['new_transfers']['clients'] = null; - else if ($section == 'requisitions') - $_SESSION['new_transfers']['requisitions'] = null; + $new_ids = []; + $funnelCounts = []; - if ($section == 'clients') { + // Счётчики в воронках + if ($use_counters) { - $bd_stage = ""; - if ($filters['filter_stage_work']) { - if ($filters['is_confirm'] || $filters['stage_send']) { - $bd_stage = " AND `clients`.`deleted` <> '1'"; - } else { - $bd_stage = " AND `clients`.`deleted` <> '1' AND `clients`.`confirm` > 0"; - } - } + if ($section == 'clients') + $_SESSION['new_transfers']['clients'] = null; + else if ($section == 'requisitions') + $_SESSION['new_transfers']['requisitions'] = null; - if ($filters['is_hot']) - $bd_stage .= " AND `clients`.`hot` = 1"; + if ($section == 'clients') { - if (empty($bd_stage)) - $bd_stage = " AND `clients`.`deleted` = '0'"; + $bd_stage = ""; + if ($filters['filter_stage_work']) { + if ($filters['is_confirm'] || $filters['stage_send']) { + $bd_stage = " AND `clients`.`deleted` <> '1'"; + } else { + $bd_stage = " AND `clients`.`deleted` <> '1' AND `clients`.`confirm` > 0"; + } + } - $sql1 = "SELECT `clients`.`funnel_id`, COUNT(DISTINCT `clients`.`id`) AS `count` + if ($filters['is_hot']) + $bd_stage .= " AND `clients`.`hot` = 1"; + + if (empty($bd_stage)) + $bd_stage = " AND `clients`.`deleted` = '0'"; + + $sql1 = "SELECT `clients`.`funnel_id`, COUNT(DISTINCT `clients`.`id`) AS `count` FROM `events_clients` AS `events` LEFT JOIN `clients` AS `clients` ON `clients`.`id` = `events`.`client_id` WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND @@ -2007,7 +2007,7 @@ class CommonController extends ApiController `clients`.`funnel_id` = 0 GROUP BY `clients`.`funnel_id`"; - $sql1_list = "SELECT `clients`.`funnel_id`, `clients`.`id` + $sql1_list = "SELECT `clients`.`funnel_id`, `clients`.`id` FROM `events_clients` AS `events` LEFT JOIN `clients` AS `clients` ON `clients`.`id` = `events`.`client_id` WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND @@ -2018,7 +2018,7 @@ class CommonController extends ApiController (`clients`.`who_work` = '$user_id' OR `clients`.`doers` LIKE '%"".$user_id."":1%') AND `clients`.`funnel_id` = 0"; - $sql2 = "SELECT `clients`.`funnel_id`, COUNT(DISTINCT `clients`.`id`) AS `count` + $sql2 = "SELECT `clients`.`funnel_id`, COUNT(DISTINCT `clients`.`id`) AS `count` FROM `events_clients` AS `events` LEFT JOIN `clients` AS `clients` ON `clients`.`id` = `events`.`client_id` JOIN `funnel` AS `funnel` @@ -2032,7 +2032,7 @@ class CommonController extends ApiController `funnel`.`agency_id` = '$agency_id' AND `funnel`.`deleted` = 0 GROUP BY `clients`.`funnel_id`"; - $sql2_list = "SELECT `clients`.`funnel_id`, `clients`.`id` + $sql2_list = "SELECT `clients`.`funnel_id`, `clients`.`id` FROM `events_clients` AS `events` LEFT JOIN `clients` AS `clients` ON `clients`.`id` = `events`.`client_id` JOIN `funnel` AS `funnel` @@ -2045,8 +2045,8 @@ class CommonController extends ApiController `clients`.`funnel_id` = `funnel`.`id` AND `funnel`.`agency_id` = '$agency_id' AND `funnel`.`deleted` = 0"; - } else if ($section == 'requisitions') { - $sql1 = "SELECT `req`.`funnel_id`, COUNT(DISTINCT `req`.`id`) AS `count` + } else if ($section == 'requisitions') { + $sql1 = "SELECT `req`.`funnel_id`, COUNT(DISTINCT `req`.`id`) AS `count` FROM `events_clients` AS `events` LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `events`.`req_id` WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND @@ -2058,7 +2058,7 @@ class CommonController extends ApiController `req`.`funnel_id` = 0 GROUP BY `req`.`funnel_id`"; - $sql1_list = "SELECT `req`.`funnel_id`, `req`.`id` + $sql1_list = "SELECT `req`.`funnel_id`, `req`.`id` FROM `events_clients` AS `events` LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `events`.`req_id` WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND @@ -2069,7 +2069,7 @@ class CommonController extends ApiController (`req`.`who_work` = '$user_id' OR `req`.`doers` LIKE '%"".$user_id."":1%') AND `req`.`funnel_id` = 0"; - $sql2 = "SELECT `req`.`funnel_id`, COUNT(DISTINCT `req`.`id`) AS `count` + $sql2 = "SELECT `req`.`funnel_id`, COUNT(DISTINCT `req`.`id`) AS `count` FROM `events_clients` AS `events` LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `events`.`req_id` JOIN `funnel` AS `funnel` @@ -2083,7 +2083,7 @@ class CommonController extends ApiController `funnel`.`agency_id` = '$agency_id' AND `funnel`.`deleted` = 0 GROUP BY `req`.`funnel_id`"; - $sql2_list = "SELECT `req`.`funnel_id`, `req`.`id` + $sql2_list = "SELECT `req`.`funnel_id`, `req`.`id` FROM `events_clients` AS `events` LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `events`.`req_id` JOIN `funnel` AS `funnel` @@ -2096,46 +2096,46 @@ class CommonController extends ApiController `req`.`funnel_id` = `funnel`.`id` AND `funnel`.`agency_id` = '$agency_id' AND `funnel`.`deleted` = 0"; - } + } - $res1 = mysql_query($sql1); - if (mysql_num_rows($res1)) { - while($counter = mysql_fetch_assoc($res1)) { - $funnelCounts[$counter['funnel_id']] = $counter['count']; - } - } + $res1 = mysql_query($sql1); + if (mysql_num_rows($res1)) { + while($counter = mysql_fetch_assoc($res1)) { + $funnelCounts[$counter['funnel_id']] = $counter['count']; + } + } - $res1_list = mysql_query($sql1_list); - if (mysql_num_rows($res1_list)) { - while($row = mysql_fetch_assoc($res1_list)) { - $new_ids[] = $row['id']; - } - } + $res1_list = mysql_query($sql1_list); + if (mysql_num_rows($res1_list)) { + while($row = mysql_fetch_assoc($res1_list)) { + $new_ids[] = $row['id']; + } + } - $res2 = mysql_query($sql2); - if (mysql_num_rows($res2)) { - while($counter = mysql_fetch_assoc($res2)) { - $funnelCounts[$counter['funnel_id']] = $counter['count']; - } - } + $res2 = mysql_query($sql2); + if (mysql_num_rows($res2)) { + while($counter = mysql_fetch_assoc($res2)) { + $funnelCounts[$counter['funnel_id']] = $counter['count']; + } + } - $res2_list = mysql_query($sql2_list); - if (mysql_num_rows($res2_list)) { - while($row = mysql_fetch_assoc($res2_list)) { - $new_ids[] = $row['id']; - } - } + $res2_list = mysql_query($sql2_list); + if (mysql_num_rows($res2_list)) { + while($row = mysql_fetch_assoc($res2_list)) { + $new_ids[] = $row['id']; + } + } - if (count($new_ids) > 0) { - if (($section == 'clients')) - $_SESSION['new_transfers']['clients'] = $new_ids; - else if (($section == 'requisitions')) - $_SESSION['new_transfers']['requisitions'] = $new_ids; - } - } + if (count($new_ids) > 0) { + if (($section == 'clients')) + $_SESSION['new_transfers']['clients'] = $new_ids; + else if (($section == 'requisitions')) + $_SESSION['new_transfers']['requisitions'] = $new_ids; + } + } - $is_default = false; - /*if ($use_custom) { + $is_default = false; + /*if ($use_custom) { $is_default = true; $funnels[] = [ 'id' => 0, @@ -2181,1565 +2181,1565 @@ class CommonController extends ApiController $errors[] = mysql_error(); }*/ - $funnelClass = new \Funnel(); - $funnelClass->set_agency_id($agency_id); - $funnelClass->set_user_id($user_id); - $funnelsRaw = $funnelClass->get_funnels($section); - $funnels = array(); - if (is_array($funnelsRaw)) { - foreach ($funnelsRaw as $rF) { - $is_default_custom = false; - if (!$is_default && (int)$rF['$funnel'] == 0) { - $is_default_custom = true; - $is_default = true; - } - $funnels[] = array( - 'id' => (int)$rF['id'], - 'name' => (isset($rF['name']) && $rF['name'] !== null && $rF['name'] !== '') - ? (string)$rF['name'] - : 'Обычные', - 'count' => ($funnelCounts[intval($rF['id'])] > 0) ? intval($funnelCounts[intval($rF['id'])]) : null, - 'is_default' => $is_default_custom - ); - } - } + $funnelClass = new \Funnel(); + $funnelClass->set_agency_id($agency_id); + $funnelClass->set_user_id($user_id); + $funnelsRaw = $funnelClass->get_funnels($section); + $funnels = array(); + if (is_array($funnelsRaw)) { + foreach ($funnelsRaw as $rF) { + $is_default_custom = false; + if (!$is_default && (int)$rF['$funnel'] == 0) { + $is_default_custom = true; + $is_default = true; + } + $funnels[] = array( + 'id' => (int)$rF['id'], + 'name' => (isset($rF['name']) && $rF['name'] !== null && $rF['name'] !== '') + ? (string)$rF['name'] + : 'Обычные', + 'count' => ($funnelCounts[intval($rF['id'])] > 0) ? intval($funnelCounts[intval($rF['id'])]) : null, + 'is_default' => $is_default_custom + ); + } + } - if (!$error) { - if ($need_return) { - return $funnels; - } else { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => true, - 'user_id' => (int)$user_id, - 'count' => count($funnels), - 'list' => $funnels - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } - } + if (!$error) { + if ($need_return) { + return $funnels; + } else { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => true, + 'user_id' => (int)$user_id, + 'count' => count($funnels), + 'list' => $funnels + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } + } - if ($need_return) { - return false; - } else { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id, - 'errors' => $errors, - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } + if ($need_return) { + return false; + } else { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id, + 'errors' => $errors, + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } - public function getAllFunnelsData($app, $get = null, $post = null, $need_return = false) { + public function getAllFunnelsData($app, $get = null, $post = null, $need_return = false) { - $error = false; - $errors = []; + $error = false; + $errors = []; - $only_active = $get['only_active'] || true; - $section = $get['section']; // requisitions, clients + $only_active = $get['only_active'] || true; + $section = $get['section']; // requisitions, clients - if ($user_id = $_SESSION['id']) { + if ($user_id = $_SESSION['id']) { - // Открываем соединение с БД - $mdb = $app->container->get('mysql'); - $pdo = $app->container->get('mypdo'); + // Открываем соединение с БД + $mdb = $app->container->get('mysql'); + $pdo = $app->container->get('mypdo'); - $users_inst = new \User(); - $agency_id = $users_inst->getAgencyIdForUser($user_id); - /*error_reporting(E_ALL | E_STRICT); + $users_inst = new \User(); + $agency_id = $users_inst->getAgencyIdForUser($user_id); + /*error_reporting(E_ALL | E_STRICT); ini_set('display_errors', 1);*/ - $items = []; - $response = []; + $items = []; + $response = []; - // Нулевая воронка - $sql = "SELECT * FROM `funnel_default` WHERE `agency_id` = {$agency_id}"; - if ($query = $pdo->query($sql)) { + // Нулевая воронка + $sql = "SELECT * FROM `funnel_default` WHERE `agency_id` = {$agency_id}"; + if ($query = $pdo->query($sql)) { - $default_steps = [ - 1 => [ - 'id' => 1, - 'name' => 'Новый', - ], - 2 => [ - 'id' => 2, - 'name' => 'В работе', - ], - 3 => [ - 'id' => 3, - 'name' => 'Презентация', - ], - 4 => [ - 'id' => 4, - 'name' => 'Показ', - ], - 5 => [ - 'id' => 5, - 'name' => 'Бронь', - ], - 6 => [ - 'id' => 6, - 'name' => 'Подаем на ипотеку', - ], - 7 => [ - 'id' => 7, - 'name' => 'Сделка', - ], - 8 => [ - 'id' => 8, - 'name' => 'Закрыт', - ], - ]; + $default_steps = [ + 1 => [ + 'id' => 1, + 'name' => 'Новый', + ], + 2 => [ + 'id' => 2, + 'name' => 'В работе', + ], + 3 => [ + 'id' => 3, + 'name' => 'Презентация', + ], + 4 => [ + 'id' => 4, + 'name' => 'Показ', + ], + 5 => [ + 'id' => 5, + 'name' => 'Бронь', + ], + 6 => [ + 'id' => 6, + 'name' => 'Подаем на ипотеку', + ], + 7 => [ + 'id' => 7, + 'name' => 'Сделка', + ], + 8 => [ + 'id' => 8, + 'name' => 'Закрыт', + ], + ]; - if ($pdo->num_rows($query)) { + if ($pdo->num_rows($query)) { - $row = $pdo->fetch_assoc($query); + $row = $pdo->fetch_assoc($query); - $name = 'Обычные'; - if (!empty($row['name'])) - $name = $row['name']; + $name = 'Обычные'; + if (!empty($row['name'])) + $name = $row['name']; - $items[] = [ - 'id' => 0, - 'name' => $name, - 'is_default' => true, - 'is_client' => (bool)$row['is_client'], - 'is_req' => (bool)$row['is_req'], - 'is_stage' => (bool)$row['is_stage'], - 'is_show_funnels' => (bool)$row['is_show_funnels'], - 'steps' => $default_steps, - 'order' => 0, - ]; - } else { - $items[] = [ - 'id' => 0, - 'name' => 'Обычные', - 'is_default' => true, - 'is_client' => true, - 'is_req' => true, - 'is_stage' => true, - 'is_show_funnels' => true, - 'steps' => $default_steps, - 'order' => 0, - ]; - } - } else { - $error = true; - } + $items[] = [ + 'id' => 0, + 'name' => $name, + 'is_default' => true, + 'is_client' => (bool)$row['is_client'], + 'is_req' => (bool)$row['is_req'], + 'is_stage' => (bool)$row['is_stage'], + 'is_show_funnels' => (bool)$row['is_show_funnels'], + 'steps' => $default_steps, + 'order' => 0, + ]; + } else { + $items[] = [ + 'id' => 0, + 'name' => 'Обычные', + 'is_default' => true, + 'is_client' => true, + 'is_req' => true, + 'is_stage' => true, + 'is_show_funnels' => true, + 'steps' => $default_steps, + 'order' => 0, + ]; + } + } else { + $error = true; + } - // Остальные (кастомные) воронки - if ($only_active) - $sql = "SELECT * FROM `funnel` WHERE `agency_id` = {$agency_id} AND `deleted` = 0"; - else - $sql = "SELECT * FROM `funnel` WHERE `agency_id` = {$agency_id}"; + // Остальные (кастомные) воронки + if ($only_active) + $sql = "SELECT * FROM `funnel` WHERE `agency_id` = {$agency_id} AND `deleted` = 0"; + else + $sql = "SELECT * FROM `funnel` WHERE `agency_id` = {$agency_id}"; - if ($section == 'clients') - $sql .= " AND `is_client` = 1"; - else if ($section == 'requisitions') - $sql .= " AND `is_req` = 1"; + if ($section == 'clients') + $sql .= " AND `is_client` = 1"; + else if ($section == 'requisitions') + $sql .= " AND `is_req` = 1"; - $sql .= " ORDER BY `id`"; + $sql .= " ORDER BY `id`"; - if ($query = $pdo->query($sql)) { - if ($pdo->num_rows($query)) { - while($row = $pdo->fetch_assoc($query)) { + if ($query = $pdo->query($sql)) { + if ($pdo->num_rows($query)) { + while($row = $pdo->fetch_assoc($query)) { - $row['date'] = date('d.m.Y H:i:s', strtotime($row['date_create'])); - $row['role'] = htmlspecialchars_decode($row['role']); - $row['client_type'] = htmlspecialchars_decode($row['client_type']); - $row['main_step'] = ''; - $row['is_default'] = 0; + $row['date'] = date('d.m.Y H:i:s', strtotime($row['date_create'])); + $row['role'] = htmlspecialchars_decode($row['role']); + $row['client_type'] = htmlspecialchars_decode($row['client_type']); + $row['main_step'] = ''; + $row['is_default'] = 0; - // Этапы по воронкам - $sql = "SELECT * FROM `funnel_steps` WHERE `funnel_id` = ".$row['id']." AND deleted = 0 ORDER BY `main` DESC"; - if ($steps = $pdo->query($sql)) { - if ($pdo->num_rows($steps)) { + // Этапы по воронкам + $sql = "SELECT * FROM `funnel_steps` WHERE `funnel_id` = ".$row['id']." AND deleted = 0 ORDER BY `main` DESC"; + if ($steps = $pdo->query($sql)) { + if ($pdo->num_rows($steps)) { - $prev_steps = []; - $steps_data = []; + $prev_steps = []; + $steps_data = []; - while($step = $pdo->fetch_assoc($steps)) { - $steps_data[(int)$step['id']] = $step; - } + while($step = $pdo->fetch_assoc($steps)) { + $steps_data[(int)$step['id']] = $step; + } - foreach ($steps_data as $step_id => $step) { + foreach ($steps_data as $step_id => $step) { - $step['name_number'] = $step['name']; + $step['name_number'] = $step['name']; - if ($step['main'] == 1) - $step['name_number'] = '1. '.$step['name']; - else if ($step['order_number'] > 0) - $step['name_number'] = $step['order_number'].'. '.$step['name']; + if ($step['main'] == 1) + $step['name_number'] = '1. '.$step['name']; + else if ($step['order_number'] > 0) + $step['name_number'] = $step['order_number'].'. '.$step['name']; - if (!empty($step['next_step'])) { - $next_steps_ids = json_decode(html_entity_decode($step['next_step']), ENT_QUOTES); - foreach ($next_steps_ids as $next_step_id) { - $prev_steps[(int)$next_step_id][] = ['id' => (int)$step['id'], 'name' => $step['name']]; - } - } + if (!empty($step['next_step'])) { + $next_steps_ids = json_decode(html_entity_decode($step['next_step']), ENT_QUOTES); + foreach ($next_steps_ids as $next_step_id) { + $prev_steps[(int)$next_step_id][] = ['id' => (int)$step['id'], 'name' => $step['name']]; + } + } - $row['branches'][$step['branch']][$step['id']] = self::clearInputArray($step); - $row['steps'][$step['id']] = self::clearInputArray($step); + $row['branches'][$step['branch']][$step['id']] = self::clearInputArray($step); + $row['steps'][$step['id']] = self::clearInputArray($step); - if (!empty($row['steps'][$step['id']]['users_mes'])) - $row['steps'][$step['id']]['users_mes'] = json_decode($row['steps'][$step['id']]['users_mes'], true); + if (!empty($row['steps'][$step['id']]['users_mes'])) + $row['steps'][$step['id']]['users_mes'] = json_decode($row['steps'][$step['id']]['users_mes'], true); - if (!empty($row['steps'][$step['id']]['arr_next_steps'])) { - $arr_next_steps = json_decode($row['steps'][$step['id']]['arr_next_steps'], true); - $row['steps'][$step['id']]['arr_next_steps'] = []; - if (is_array($arr_next_steps)) { - foreach ($arr_next_steps as $arr_next_step) { - if (!empty($arr_next_step['id'])) { - $next_step = $arr_next_step['id']; - $row['steps'][$step['id']]['arr_next_steps'][] = [ - 'id' => (int)$next_step['id'], - 'name' => trim($next_step['name']) - ]; - } - } - } - } else { - $row['steps'][$step['id']]['arr_next_steps'] = []; - $next_steps_ids = json_decode(html_entity_decode($step['next_step']), ENT_QUOTES); - foreach ($next_steps_ids as $next_step_id) { - $next_step = $steps_data[$next_step_id]; - if (!empty($next_step)) { - $row['steps'][$step['id']]['arr_next_steps'][] = ['id' => (int)$next_step['id'], 'name' => $next_step['name']]; - } - } - } + if (!empty($row['steps'][$step['id']]['arr_next_steps'])) { + $arr_next_steps = json_decode($row['steps'][$step['id']]['arr_next_steps'], true); + $row['steps'][$step['id']]['arr_next_steps'] = []; + if (is_array($arr_next_steps)) { + foreach ($arr_next_steps as $arr_next_step) { + if (!empty($arr_next_step['id'])) { + $next_step = $arr_next_step['id']; + $row['steps'][$step['id']]['arr_next_steps'][] = [ + 'id' => (int)$next_step['id'], + 'name' => trim($next_step['name']) + ]; + } + } + } + } else { + $row['steps'][$step['id']]['arr_next_steps'] = []; + $next_steps_ids = json_decode(html_entity_decode($step['next_step']), ENT_QUOTES); + foreach ($next_steps_ids as $next_step_id) { + $next_step = $steps_data[$next_step_id]; + if (!empty($next_step)) { + $row['steps'][$step['id']]['arr_next_steps'][] = ['id' => (int)$next_step['id'], 'name' => $next_step['name']]; + } + } + } - if (!empty($prev_steps[(int)$step['id']])) - $row['steps'][$step['id']]['arr_prev_steps'] = $prev_steps[(int)$step['id']]; - else - $row['steps'][$step['id']]['arr_prev_steps'] = []; + if (!empty($prev_steps[(int)$step['id']])) + $row['steps'][$step['id']]['arr_prev_steps'] = $prev_steps[(int)$step['id']]; + else + $row['steps'][$step['id']]['arr_prev_steps'] = []; - $files = []; - $sql = "SELECT * FROM `funnel_files` WHERE `etap_id` = '".$step['id']."' AND `funnel_id` = ".$row['id']; - if ($query_files = $pdo->query($sql)) { - if ($pdo->num_rows($query_files)) { - while($file_row = $pdo->fetch_assoc($query_files)) { - $path = "https://uf.joywork.ru/upload/funnels/".$row['id']."/".$file_row['guid'].".".$file_row['type']; + $files = []; + $sql = "SELECT * FROM `funnel_files` WHERE `etap_id` = '".$step['id']."' AND `funnel_id` = ".$row['id']; + if ($query_files = $pdo->query($sql)) { + if ($pdo->num_rows($query_files)) { + while($file_row = $pdo->fetch_assoc($query_files)) { + $path = "https://uf.joywork.ru/upload/funnels/".$row['id']."/".$file_row['guid'].".".$file_row['type']; $files[] = ['guid' => $file_row['guid'], 'isUpload' => true, 'uploads' => false, 'name' => $file_row['name']]; } - } - } + } + } - $row['steps'][$step['id']]['files'] = $files; - $row['main_steps'][] = ['id' => $step['id'], 'name' => $step['name']]; + $row['steps'][$step['id']]['files'] = $files; + $row['main_steps'][] = ['id' => $step['id'], 'name' => $step['name']]; - if ($step['main'] == 1) - $row['main_step'] = ['id' => $step['id'], 'name' => $step['name']]; + if ($step['main'] == 1) + $row['main_step'] = ['id' => $step['id'], 'name' => $step['name']]; - } - } - } else { - $error = true; - } + } + } + } else { + $error = true; + } - $items[] = $row; - } - } - } else { - $error = true; - } + $items[] = $row; + } + } + } else { + $error = true; + } - if (!empty($items)) { - foreach($items as $item) { + if (!empty($items)) { + foreach($items as $item) { - $steps = []; - foreach($item['steps'] as $step_id => $step) { - $steps[] = [ - 'id' => (int)$step_id, - 'name' => $step['name'], - 'prev_steps' => (!empty($step['arr_prev_steps'])) ? $step['arr_prev_steps'] : ((!empty($default_steps[(int)$step_id-1]) && $item['is_default']) ? [$default_steps[(int)$step_id-1]] : null), - 'next_steps' => (!empty($step['arr_next_steps'])) ? $step['arr_next_steps'] : ((!empty($default_steps[(int)$step_id+1]) && $item['is_default']) ? [$default_steps[(int)$step_id+1]] : null), - 'files' => (!empty($step['files'])) ? $step['files'] : [], - 'tasks' => (!empty($step['tasks_list'])) ? json_decode($step['tasks_list']) : null, - 'fields' => (!empty($step['pole_end_list'])) ? json_decode($step['pole_end_list']) : null, - 'doers' => (!empty($step['doers'])) ? json_decode($step['doers']) : [null], - 'is_next_variable' => ($step['next_step_change'] === "Зависит от поля Ветвление этапов"), - ]; - } + $steps = []; + foreach($item['steps'] as $step_id => $step) { + $steps[] = [ + 'id' => (int)$step_id, + 'name' => $step['name'], + 'prev_steps' => (!empty($step['arr_prev_steps'])) ? $step['arr_prev_steps'] : ((!empty($default_steps[(int)$step_id-1]) && $item['is_default']) ? [$default_steps[(int)$step_id-1]] : null), + 'next_steps' => (!empty($step['arr_next_steps'])) ? $step['arr_next_steps'] : ((!empty($default_steps[(int)$step_id+1]) && $item['is_default']) ? [$default_steps[(int)$step_id+1]] : null), + 'files' => (!empty($step['files'])) ? $step['files'] : [], + 'tasks' => (!empty($step['tasks_list'])) ? json_decode($step['tasks_list']) : null, + 'fields' => (!empty($step['pole_end_list'])) ? json_decode($step['pole_end_list']) : null, + 'doers' => (!empty($step['doers'])) ? json_decode($step['doers']) : [null], + 'is_next_variable' => ($step['next_step_change'] === "Зависит от поля Ветвление этапов"), + ]; + } - $response[] = [ - 'id' => (int)$item['id'], - 'name' => trim($item['name']), - 'order' => (!empty($item['order_number'])) ? (int)$item['order_number'] : 0, - 'is_client' => (bool)$item['is_client'], - 'is_default' => (bool)$item['is_default'], - 'is_deleted' => (bool)$item['deleted'], - 'is_req' => (bool)$item['is_req'], - 'steps' => $steps, - 'client_types' => (!empty($item['client_type'])) ? json_decode($item['client_type']) : null, - 'roles' => (!empty($item['role'])) ? json_decode($item['role']) : null, - 'agency_id' => (int)$item['agency_id'], - 'created_by' => (int)$item['user_id'], - 'created_at' => $item['date_create'], - ]; - } - } + $response[] = [ + 'id' => (int)$item['id'], + 'name' => trim($item['name']), + 'order' => (!empty($item['order_number'])) ? (int)$item['order_number'] : 0, + 'is_client' => (bool)$item['is_client'], + 'is_default' => (bool)$item['is_default'], + 'is_deleted' => (bool)$item['deleted'], + 'is_req' => (bool)$item['is_req'], + 'steps' => $steps, + 'client_types' => (!empty($item['client_type'])) ? json_decode($item['client_type']) : null, + 'roles' => (!empty($item['role'])) ? json_decode($item['role']) : null, + 'agency_id' => (int)$item['agency_id'], + 'created_by' => (int)$item['user_id'], + 'created_at' => $item['date_create'], + ]; + } + } - if (!$error) { - if ($need_return) { - return $response; - } else { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => true, - 'user_id' => (int)$user_id, - 'list' => $response, - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } - } + if (!$error) { + if ($need_return) { + return $response; + } else { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => true, + 'user_id' => (int)$user_id, + 'list' => $response, + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } + } - if ($need_return) { - return false; - } else { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id, - 'errors' => $errors, - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } + if ($need_return) { + return false; + } else { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id, + 'errors' => $errors, + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } - public function getList($app, $get = null, $post = null, $need_return = false) { + public function getList($app, $get = null, $post = null, $need_return = false) { - $error = false; - $errors = []; - if ($user_id = $_SESSION['id']) { + $error = false; + $errors = []; + if ($user_id = $_SESSION['id']) { - // Открываем соединение с БД - $mdb = $app->container->get('mysql'); + // Открываем соединение с БД + $mdb = $app->container->get('mysql'); - $sql = ""; - $list = []; - $section = $get['section']; - switch ($section) { + $sql = ""; + $list = []; + $section = $get['section']; + switch ($section) { - case 'rooms_count' : + case 'rooms_count' : - $ROOMS_COUNT = [ - 1 => "1 комн.", - 2 => "2 комн.", - 3 => "3 комн.", - 4 => "4+ комн.", - 5 => "Студия", - ]; + $ROOMS_COUNT = [ + 1 => "1 комн.", + 2 => "2 комн.", + 3 => "3 комн.", + 4 => "4+ комн.", + 5 => "Студия", + ]; - $list = []; - foreach($ROOMS_COUNT as $key => $value) { - $list[$key] = [ - 'id' => $key, - 'name' => $value - ]; - } + $list = []; + foreach($ROOMS_COUNT as $key => $value) { + $list[$key] = [ + 'id' => $key, + 'name' => $value + ]; + } - break; + break; - case 'complexes': - $sql = "SELECT `id`, `name` FROM `blocks` ORDER BY `name`"; - break; + case 'complexes': + $sql = "SELECT `id`, `name` FROM `blocks` ORDER BY `name`"; + break; - case 'banks_list': - $sql = "SELECT `id`, `name` FROM `banks` ORDER BY `name`"; - break; + case 'banks_list': + $sql = "SELECT `id`, `name` FROM `banks` ORDER BY `name`"; + break; - case 'denial_work': - { - $user = new \User; - $user->get($user_id); - $agency_id = $user->agencyId; - $sql = "SELECT `id`, `name` FROM `denial_work` WHERE (agency_id = 0 or agency_id={$agency_id}) and del = 0"; + case 'denial_work': + { + $user = new \User; + $user->get($user_id); + $agency_id = $user->agencyId; + $sql = "SELECT `id`, `name` FROM `denial_work` WHERE (agency_id = 0 or agency_id={$agency_id}) and del = 0"; - } - break; + } + break; - case 'floor_materials': - $sql = "SELECT `id`, `name` FROM `floor_material`"; - break; + case 'floor_materials': + $sql = "SELECT `id`, `name` FROM `floor_material`"; + break; - case 'house_categories': - $sql = "SELECT `id`, `name` FROM `house_category`"; - break; + case 'house_categories': + $sql = "SELECT `id`, `name` FROM `house_category`"; + break; - case 'commerce_portal': - $sql = "SELECT `id`, `name` FROM `commerc_portal`"; - break; + case 'commerce_portal': + $sql = "SELECT `id`, `name` FROM `commerc_portal`"; + break; - case 'commerce_purpose': - $sql = "SELECT `id`, `name` FROM `commerc_purpose`"; - break; + case 'commerce_purpose': + $sql = "SELECT `id`, `name` FROM `commerc_purpose`"; + break; - case 'commerce_land_categories': - $sql = "SELECT `id`, `name` FROM `commerc_land_category`"; - break; + case 'commerce_land_categories': + $sql = "SELECT `id`, `name` FROM `commerc_land_category`"; + break; - case 'commerce_permitted_use': - $sql = "SELECT `id`, `name` FROM `commerc_permitted_use`"; - break; + case 'commerce_permitted_use': + $sql = "SELECT `id`, `name` FROM `commerc_permitted_use`"; + break; - case 'commerce_electricity': - $sql = "SELECT `id`, `name` FROM `commerc_electricity`"; - break; + case 'commerce_electricity': + $sql = "SELECT `id`, `name` FROM `commerc_electricity`"; + break; case 'electricity_types': $sql = "SELECT `id`, `name` FROM `electricity_type` order by `id`"; break; - case 'commerce_gas': - $sql = "SELECT `id`, `name` FROM `commerc_gas`"; - break; + case 'commerce_gas': + $sql = "SELECT `id`, `name` FROM `commerc_gas`"; + break; case 'gas_types': $sql = "SELECT `id`, `name` FROM `gas_type` order by `id`"; break; - case 'commerce_water': - $sql = "SELECT `id`, `name` FROM `commerc_gas`"; - break; + case 'commerce_water': + $sql = "SELECT `id`, `name` FROM `commerc_gas`"; + break; - case 'commerce_sewage': - $sql = "SELECT `id`, `name` FROM `commerc_gas`"; - break; + case 'commerce_sewage': + $sql = "SELECT `id`, `name` FROM `commerc_gas`"; + break; case 'sewerage_types': $sql = "SELECT `id`, `name` FROM `sewerage_type` order by `id`"; break; - case 'commerce_driveways': - $sql = "SELECT `id`, `name` FROM `commerc_driveways`"; - break; + case 'commerce_driveways': + $sql = "SELECT `id`, `name` FROM `commerc_driveways`"; + break; - case 'commerce_services': - $sql = "SELECT `id`, `name` FROM `commerc_services`"; - break; + case 'commerce_services': + $sql = "SELECT `id`, `name` FROM `commerc_services`"; + break; - case 'building_types' : - $sql = "SELECT `id`, `name` FROM `commerc_building_type`"; - break; + case 'building_types' : + $sql = "SELECT `id`, `name` FROM `commerc_building_type`"; + break; - case 'building_classes' : - $sql = "SELECT `id`, `name` FROM `commerc_building_class`"; - break; + case 'building_classes' : + $sql = "SELECT `id`, `name` FROM `commerc_building_class`"; + break; - case 'houseline_types' : - $sql = "SELECT `id`, `name` FROM `commerc_houselinetype`"; - break; + case 'houseline_types' : + $sql = "SELECT `id`, `name` FROM `commerc_houselinetype`"; + break; - case 'building_categories' : - $sql = "SELECT `id`, `name` FROM `commerc_building_category`"; - break; + case 'building_categories' : + $sql = "SELECT `id`, `name` FROM `commerc_building_category`"; + break; - case 'entrance_types' : - $sql = "SELECT `id`, `name` FROM `commerc_opened`"; - break; + case 'entrance_types' : + $sql = "SELECT `id`, `name` FROM `commerc_opened`"; + break; - case 'building_ventilations' : - $list = [ - [ - 'id' => 0, - 'name' => 'Нет', - ], [ - 'id' => 1, - 'name' => 'Естественная', - ], [ - 'id' => 2, - 'name' => 'Приточная', - ], - ]; - break; + case 'building_ventilations' : + $list = [ + [ + 'id' => 0, + 'name' => 'Нет', + ], [ + 'id' => 1, + 'name' => 'Естественная', + ], [ + 'id' => 2, + 'name' => 'Приточная', + ], + ]; + break; - case 'periods' : - $list = [ - [ - 'id' => 1, - 'name' => 'Сегодня', - ], [ - 'id' => 2, - 'name' => 'Неделя', - ], [ - 'id' => 3, - 'name' => 'Месяц', - ], [ - 'id' => 4, - 'name' => 'Последние 30 дней', - ], [ - 'id' => 5, - 'name' => 'Квартал', - ], [ - 'id' => 6, - 'name' => 'Последние 90 дней', - ], [ - 'id' => 7, - 'name' => 'Год', - ], [ - 'id' => 8, - 'name' => 'Все время', - ], [ - 'id' => 9, - 'name' => 'Период', - ], - ]; - break; + case 'periods' : + $list = [ + [ + 'id' => 1, + 'name' => 'Сегодня', + ], [ + 'id' => 2, + 'name' => 'Неделя', + ], [ + 'id' => 3, + 'name' => 'Месяц', + ], [ + 'id' => 4, + 'name' => 'Последние 30 дней', + ], [ + 'id' => 5, + 'name' => 'Квартал', + ], [ + 'id' => 6, + 'name' => 'Последние 90 дней', + ], [ + 'id' => 7, + 'name' => 'Год', + ], [ + 'id' => 8, + 'name' => 'Все время', + ], [ + 'id' => 9, + 'name' => 'Период', + ], + ]; + break; - case 'building_conditioning' : - $list = [ - [ - 'id' => 0, - 'name' => 'Нет', - ], [ - 'id' => 1, - 'name' => 'Местное', - ], [ - 'id' => 2, - 'name' => 'Центральное', - ], - ]; - break; + case 'building_conditioning' : + $list = [ + [ + 'id' => 0, + 'name' => 'Нет', + ], [ + 'id' => 1, + 'name' => 'Местное', + ], [ + 'id' => 2, + 'name' => 'Центральное', + ], + ]; + break; - case 'building_heating' : - $list = [ - [ - 'id' => 0, - 'name' => 'Нет', - ], [ - 'id' => 1, - 'name' => 'Автономное', - ], [ - 'id' => 2, - 'name' => 'Центральное', - ], - ]; - break; + case 'building_heating' : + $list = [ + [ + 'id' => 0, + 'name' => 'Нет', + ], [ + 'id' => 1, + 'name' => 'Автономное', + ], [ + 'id' => 2, + 'name' => 'Центральное', + ], + ]; + break; - case 'building_firefighting' : - $list = [ - [ - 'id' => 0, - 'name' => 'Нет', - ], [ - 'id' => 1, - 'name' => 'Гидрантная', - ], [ - 'id' => 2, - 'name' => 'Спринклерная', - ], [ - 'id' => 3, - 'name' => 'Порошковая', - ], [ - 'id' => 4, - 'name' => 'Газовая', - ], [ - 'id' => 5, - 'name' => 'Сигнализация', - ], - ]; - break; + case 'building_firefighting' : + $list = [ + [ + 'id' => 0, + 'name' => 'Нет', + ], [ + 'id' => 1, + 'name' => 'Гидрантная', + ], [ + 'id' => 2, + 'name' => 'Спринклерная', + ], [ + 'id' => 3, + 'name' => 'Порошковая', + ], [ + 'id' => 4, + 'name' => 'Газовая', + ], [ + 'id' => 5, + 'name' => 'Сигнализация', + ], + ]; + break; - case 'garages' : - $sql = "SELECT `id`, `name` FROM `garage_type`"; - break; + case 'garages' : + $sql = "SELECT `id`, `name` FROM `garage_type`"; + break; - case 'garages_types' : - $sql = "SELECT `id`, `name` FROM `garage_vid`"; - break; + case 'garages_types' : + $sql = "SELECT `id`, `name` FROM `garage_vid`"; + break; - case 'boxes_types' : - $list = [ - [ - 'id' => 1, - 'name' => 'Кирпичный', - ], [ - 'id' => 2, - 'name' => 'Металлический', - ], [ - 'id' => 3, - 'name' => 'Железобетонный', - ], - ]; - break; + case 'boxes_types' : + $list = [ + [ + 'id' => 1, + 'name' => 'Кирпичный', + ], [ + 'id' => 2, + 'name' => 'Металлический', + ], [ + 'id' => 3, + 'name' => 'Железобетонный', + ], + ]; + break; - case 'commerce_status' : - $sql = "SELECT `id`, `name` FROM `commerc_status`"; - break; + case 'commerce_status' : + $sql = "SELECT `id`, `name` FROM `commerc_status`"; + break; - case 'commerce_specifications' : - $sql = "SELECT `id`, `name` FROM `commerc_specifications`"; - break; + case 'commerce_specifications' : + $sql = "SELECT `id`, `name` FROM `commerc_specifications`"; + break; - case 'commerce_infrastructures' : - $sql = "SELECT `id`, `name` FROM `commerc_infrastructure` WHERE id < 27"; - break; + case 'commerce_infrastructures' : + $sql = "SELECT `id`, `name` FROM `commerc_infrastructure` WHERE id < 27"; + break; - case 'commerce_infrastructures2' : - $sql = "SELECT `id`, `name` FROM `commerc_infrastructure` WHERE `vid` = 1"; - break; + case 'commerce_infrastructures2' : + $sql = "SELECT `id`, `name` FROM `commerc_infrastructure` WHERE `vid` = 1"; + break; - case 'commerce_infrastructures3' : - $sql = "SELECT `id`, `name` FROM `commerc_infrastructure` WHERE `vid1` = 1"; - break; + case 'commerce_infrastructures3' : + $sql = "SELECT `id`, `name` FROM `commerc_infrastructure` WHERE `vid1` = 1"; + break; - case 'sale_types' : - $list = [ - [ - 'id' => 1, - 'name' => 'Договор уступки права требования', - ], [ - 'id' => 2, - 'name' => 'Договор ЖСК', - ], [ - 'id' => 3, - 'name' => 'Свободная продажа', - ], [ - 'id' => 4, - 'name' => '214-ФЗ', - ], [ - 'id' => 5, - 'name' => 'Договор инвестирования', - ], [ - 'id' => 6, - 'name' => 'Предварительный договор купли-продажи', - ], - ]; - break; + case 'sale_types' : + $list = [ + [ + 'id' => 1, + 'name' => 'Договор уступки права требования', + ], [ + 'id' => 2, + 'name' => 'Договор ЖСК', + ], [ + 'id' => 3, + 'name' => 'Свободная продажа', + ], [ + 'id' => 4, + 'name' => '214-ФЗ', + ], [ + 'id' => 5, + 'name' => 'Договор инвестирования', + ], [ + 'id' => 6, + 'name' => 'Предварительный договор купли-продажи', + ], + ]; + break; - case 'legal_address' : - $list = [ - [ - 'id' => 1, - 'name' => 'Предоставляется', - ], [ - 'id' => 2, - 'name' => 'Не предоставляется', - ], - ]; - break; + case 'legal_address' : + $list = [ + [ + 'id' => 1, + 'name' => 'Предоставляется', + ], [ + 'id' => 2, + 'name' => 'Не предоставляется', + ], + ]; + break; - case 'decoration_types' : - $sql = "SELECT `id`, `name` FROM `avito_decoration_types` ORDER BY `id`"; - break; + case 'decoration_types' : + $sql = "SELECT `id`, `name` FROM `avito_decoration_types` ORDER BY `id`"; + break; - case 'flat_types' : - $sql = "SELECT `id`, `name` FROM `zipal_new_flat_type` ORDER BY `id`"; - break; + case 'flat_types' : + $sql = "SELECT `id`, `name` FROM `zipal_new_flat_type` ORDER BY `id`"; + break; - case 'investor_types' : - $sql = "SELECT `id`, `name` FROM `investor_type` ORDER BY `id`"; - break; + case 'investor_types' : + $sql = "SELECT `id`, `name` FROM `investor_type` ORDER BY `id`"; + break; - case 'access' : - $list = [ - [ - 'id' => 1, - 'name' => 'Свободный', - ], [ - 'id' => 2, - 'name' => 'Пропускная система', - ], - ]; - break; + case 'access' : + $list = [ + [ + 'id' => 1, + 'name' => 'Свободный', + ], [ + 'id' => 2, + 'name' => 'Пропускная система', + ], + ]; + break; - case 'conditions' : - $sql = "SELECT `id`, `name` FROM `commer_condition` ORDER BY `id`"; - break; + case 'conditions' : + $sql = "SELECT `id`, `name` FROM `commer_condition` ORDER BY `id`"; + break; - case 'furnitures' : - $list = [ - [ - 'id' => 1, - 'name' => 'Нет', - ], [ - 'id' => 2, - 'name' => 'Есть', - ], - ]; - break; + case 'furnitures' : + $list = [ + [ + 'id' => 1, + 'name' => 'Нет', + ], [ + 'id' => 2, + 'name' => 'Есть', + ], + ]; + break; - case 'layouts' : - $sql = "SELECT `id`, `name` FROM `layout_object` ORDER BY `id`"; - break; + case 'layouts' : + $sql = "SELECT `id`, `name` FROM `layout_object` ORDER BY `id`"; + break; - case 'occupieds' : - $list = [ - [ - 'id' => 1, - 'name' => 'Не занято', - ], [ - 'id' => 2, - 'name' => 'Занято', - ], - ]; - break; + case 'occupieds' : + $list = [ + [ + 'id' => 1, + 'name' => 'Не занято', + ], [ + 'id' => 2, + 'name' => 'Занято', + ], + ]; + break; - case 'property_types' : - $sql = "SELECT `id`, `name` FROM `property_type` ORDER BY `id`"; - break; + case 'property_types' : + $sql = "SELECT `id`, `name` FROM `property_type` ORDER BY `id`"; + break; - case 'rent_house_types' : - $sql = "SELECT `id`, `name` FROM `house_type` ORDER BY `id`"; - break; + case 'rent_house_types' : + $sql = "SELECT `id`, `name` FROM `house_type` ORDER BY `id`"; + break; - case 'wall_types' : - $sql = "SELECT `id`, `name` FROM `wall_type` ORDER BY `id`"; - break; + case 'wall_types' : + $sql = "SELECT `id`, `name` FROM `wall_type` ORDER BY `id`"; + break; - case 'house_wcs_types' : - $sql = "SELECT `id`, `name` FROM `house_wcs_type` ORDER BY `id`"; - break; + case 'house_wcs_types' : + $sql = "SELECT `id`, `name` FROM `house_wcs_type` ORDER BY `id`"; + break; - case 'land_purposes_types' : - $sql = "SELECT `id`, `name` FROM `land_purpose` ORDER BY `id`"; - break; + case 'land_purposes_types' : + $sql = "SELECT `id`, `name` FROM `land_purpose` ORDER BY `id`"; + break; - case 'shape_types' : - $sql = "SELECT `id`, `name` FROM `shape_type` ORDER BY `id`"; - break; + case 'shape_types' : + $sql = "SELECT `id`, `name` FROM `shape_type` ORDER BY `id`"; + break; - case 'plumbing_types' : - $sql = "SELECT `id`, `name` FROM `plumbing_type` ORDER BY `id`"; - break; + case 'plumbing_types' : + $sql = "SELECT `id`, `name` FROM `plumbing_type` ORDER BY `id`"; + break; - case 'relief_types' : - $sql = "SELECT `id`, `name` FROM `relief_type` ORDER BY `id`"; - break; + case 'relief_types' : + $sql = "SELECT `id`, `name` FROM `relief_type` ORDER BY `id`"; + break; - case 'land_usage_types' : - $sql = "SELECT `id`, `name` FROM `land_usage_type` ORDER BY `id`"; - break; + case 'land_usage_types' : + $sql = "SELECT `id`, `name` FROM `land_usage_type` ORDER BY `id`"; + break; - case 'lease_deposit_types' : - $sql = "SELECT `id`, `name` FROM `lease_deposit` ORDER BY `id`"; - break; + case 'lease_deposit_types' : + $sql = "SELECT `id`, `name` FROM `lease_deposit` ORDER BY `id`"; + break; - case 'window_view_types' : - $sql = "SELECT `id`, `name` FROM `window_view` ORDER BY `id`"; - break; + case 'window_view_types' : + $sql = "SELECT `id`, `name` FROM `window_view` ORDER BY `id`"; + break; - case 'renovation_types' : - $sql = "SELECT `id`, `name` FROM `renovation` ORDER BY `id`"; - break; + case 'renovation_types' : + $sql = "SELECT `id`, `name` FROM `renovation` ORDER BY `id`"; + break; - case 'bathroom_types' : - $sql = "SELECT `id`, `name` FROM `bath_type` ORDER BY `id`"; - break; + case 'bathroom_types' : + $sql = "SELECT `id`, `name` FROM `bath_type` ORDER BY `id`"; + break; - case 'hot_water_types' : - $sql = "SELECT `id`, `name` FROM `hot_water` ORDER BY `id`"; - break; + case 'hot_water_types' : + $sql = "SELECT `id`, `name` FROM `hot_water` ORDER BY `id`"; + break; - case 'parking_types' : - $sql = "SELECT `id`, `name` FROM `parking_type` ORDER BY `id`"; - break; + case 'parking_types' : + $sql = "SELECT `id`, `name` FROM `parking_type` ORDER BY `id`"; + break; - case 'parking_types1' : - $sql = "SELECT * FROM parking_type where vid = 0 ORDER BY id"; - break; + case 'parking_types1' : + $sql = "SELECT * FROM parking_type where vid = 0 ORDER BY id"; + break; - case 'parking_types2' : - $sql = "SELECT * FROM parking_type where vid1 = 1 ORDER BY id"; - break; + case 'parking_types2' : + $sql = "SELECT * FROM parking_type where vid1 = 1 ORDER BY id"; + break; - case 'parking_types3' : - $sql = "SELECT * FROM parking_type where vid = 1 ORDER BY id"; - break; + case 'parking_types3' : + $sql = "SELECT * FROM parking_type where vid = 1 ORDER BY id"; + break; - case 'vat_types' : - $sql = "SELECT `id`, `name` FROM `vat_type` ORDER BY `id`"; - break; + case 'vat_types' : + $sql = "SELECT `id`, `name` FROM `vat_type` ORDER BY `id`"; + break; - case 'wet_spots' : - $list = [ - [ - 'id' => 1, - 'name' => '1', - ], [ - 'id' => 2, - 'name' => '2', - ], [ - 'id' => 3, - 'name' => '3', - ], [ - 'id' => 4, - 'name' => '4', - ], [ - 'id' => 5, - 'name' => 'Нет', - ], - ]; - break; + case 'wet_spots' : + $list = [ + [ + 'id' => 1, + 'name' => '1', + ], [ + 'id' => 2, + 'name' => '2', + ], [ + 'id' => 3, + 'name' => '3', + ], [ + 'id' => 4, + 'name' => '4', + ], [ + 'id' => 5, + 'name' => 'Нет', + ], + ]; + break; - case 'countries' : - $sql = "SELECT * FROM `country_list` WHERE `id` = 171 UNION SELECT * FROM `country_list` WHERE `id` <> 1 ORDER BY `id`"; - break; - case 'cottage_village' : - $sql = "SELECT * FROM cottage_village order by id"; + case 'countries' : + $sql = "SELECT * FROM `country_list` WHERE `id` = 171 UNION SELECT * FROM `country_list` WHERE `id` <> 1 ORDER BY `id`"; + break; + case 'cottage_village' : + $sql = "SELECT * FROM cottage_village order by id"; - } + } if (!isset($list) || empty($list)) { $list = array(); } - if (!empty($sql)) { - if ($query = mysql_query($sql)) { - if (mysql_num_rows($query) > 0) { - while ($row = mysql_fetch_assoc($query)) { - if($section == 'cottage_village') { - if(!isset($list[$row['region_id']])) $list[$row['region_id']] = array(); - $list[$row['region_id']][] = [ - 'value' => (int)$row['id'], - 'name' => trim($row['name']), - ]; - } else - $list[] = [ - 'id' => (int)$row['id'], - 'name' => trim($row['name']), - ]; - } - } - } else { - $error = true; - $errors[] = mysql_error(); - } - } - - if (!$error) { - - if (count($list) && $section == 'denial_work') { - $list[] = [ - 'id' => 0, - 'name' => 'Другое', - ]; - } - - if ($need_return) { - return $list; - } else { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => true, - 'user_id' => (int)$user_id, - 'count' => count($list), - 'list' => $list - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } - } - - if ($need_return) { - return false; - } else { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id, - 'errors' => $errors, - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } - - public function getLists($app, $get = null, $post = null) { - - $lists = []; - if ($user_id = $_SESSION['id']) { - - // Открываем соединение с БД - $mdb = $app->container->get('mysql'); - - $sections = $get['sections']; - foreach ($sections as $section) { - - $list = $this->getList($app, ['section' => $section], null, true); - if ($list) - $lists[$section] = $list; - else - $lists[$section] = false; - - } - } - - if (count($lists)) { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => true, - 'user_id' => (int)$user_id, - 'lists' => $lists - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } else { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } - - public function getFiles($app, $get = null, $post = null) { - - $error = false; - $errors = []; - - $source_id = null; - if (isset($get['source_id'])) - $source_id = (int)$get['source_id']; - - $section = null; - if (isset($get['section'])) - $section = trim($get['section']); - - if (($user_id = $_SESSION['id']) && $source_id && $section) { - - // Открываем соединение с БД - $mdb = $app->container->get('mysql'); - $pdo = $app->container->get('mypdo'); - - $list = []; - $row = []; - - $field = ''; - $table = 'user_client_events'; - if ($section == 'clients') { - $field = 'client_id'; - $table = 'user_client_events'; - } else if ($section == 'requisitions') { - $field = 'req_id'; - $table = 'user_client_events'; - } else if ($section == 'objects') { - $field = 'object_id'; - $table = 'user_object_events'; - } - - if (!empty($field) && !empty($table)) { - - $protocol = (self::is_ssl()) ? 'https://' : 'http://'; - $host = $protocol . $_SERVER['SERVER_NAME']; - - // Найденный листинг парсера (offset-free): событие-родитель файла лежит в external_listing_events, - // event_id и object_id хранятся как РЕАЛЬНЫЕ el.id (без смещения) — валидируем владение по листинговой - // таблице. Признак листинга — явный флаг is_external из запроса (id больше не диапазонный: коллизит с objects.id). - if ($section == 'objects' && self::_request_flag($get, 'is_external')) { - $sql = "SELECT * FROM clients_files as c - WHERE object_id = {$source_id} AND event_id > 0 AND (SELECT id FROM external_listing_events WHERE id = c.event_id) > 0"; - } else { - $sql = "SELECT * FROM clients_files as c - WHERE {$field} = {$source_id} AND event_id > 0 AND (SELECT id from {$table} WHERE id = c.event_id) > 0"; - } - - if ($q = $pdo->query($sql)) { - if ($pdo->num_rows($q) > 0) { - while ($r = $pdo->fetch_assoc($q)) { - if (!empty($r['name'])) { - - $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/"; - if ($r['client_id'] > 0) - $file .= "clients/" . $r['client_id'] . "/"; - else if ($r['req_id'] > 0) - $file .= "reqs/" . $r['req_id'] . "/"; - else if ($r['object_id'] > 0) - $file .= "objects/" . $r['object_id'] . "/"; - - $file .= $r['guid'] . '.' . $r['type']; - - $r['type'] = 'id'; - $r['link'] = $host . '/download_file.php?id=' . $r['id']; - - $unix_time = filemtime($file); - $r['date'] = date('d.m.Y в H:i', $unix_time); - - if (!isset($list['names'][$r['name_id']])) - $list['names'][$r['name_id']] = array('type' => 'id', 'from' => $section, 'from_id' => $source_id, 'id' => (int)$r['name_id']); - - if (file_exists($file)) - $row[$r['name_id']][] = $r; - - } - } - } - } else { - $error = true; - $errors[] = $q->pdo->errorInfo(); - } - - if ($section == 'clients' || $section == 'requisitions' || $section == 'free') { - - $sql = "SELECT * FROM `funnel_files` WHERE {$field} = {$source_id}"; - - if ($q = $pdo->query($sql)) { - if ($pdo->num_rows($q) > 0) { - while ($r = $pdo->fetch_assoc($q)) { - if (!empty($r['name'])) { - $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/funnels/"; - - if ($r['client_id'] > 0) - $file .= "clients/" . $r['client_id'] . "/"; - else if ($r['req_id'] > 0) - $file .= "req/" . $r['req_id'] . "/"; - - $file .= $r['guid'] . '.' . $r['type']; - - $r['type'] = 'guid'; - $r['link'] = $host . '/download_file.php?guid=' . $r['guid']; - - $unix_time = filemtime($file); - $r['date'] = date('d.m.Y в H:i', $unix_time); - - if (!isset($list['names'][$r['etap_id']])) - $list['names'][$r['etap_id']] = array('type' => 'guid', 'from' => $section, 'from_id' => $source_id, 'id' => (int)$r['etap_id']); - - if (file_exists($file)) - $row[$r['etap_id']][] = $r; - - } - } - } - } else { - $error = true; - $errors[] = $q->pdo->errorInfo(); - } - } - - if ($section == 'requisitions') { - - //поиск файлов по объекту - $sql = "SELECT id, type_id, object_id FROM requisitions WHERE id = {$source_id}"; - - if ($q = $pdo->query($sql)) { - $r = $pdo->fetch_assoc($q); - if ($r['type_id'] == 2 && $r['object_id'] > 0) { - - $sql = "SELECT * FROM `clients_files` as c WHERE object_id = {$r['object_id']} AND (SELECT id from user_object_events WHERE id=c.event_id)>0"; - if ($q = $pdo->query($sql)) { - if ($pdo->num_rows($q) > 0) { - while ($r = $pdo->fetch_assoc($q)) { - if (!empty($r['name'])) { - - $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/"; - if ($r['object_id'] > 0) - $file .= "objects/" . $r['object_id'] . "/"; - - $file .= $r['guid'] . '.' . $r['type']; - - $r['type'] = 'id'; - $r['link'] = $host . '/download_file.php?id=' . $r['id']; - - $unix_time = filemtime($file); - $r['date'] = date('d.m.Y в H:i', $unix_time); - if (!isset($list['names'][$r['name_id']])) - $list['names'][$r['name_id']] = array('type' => 'id', 'from' => 'object', 'from_id' => $r['object_id'], 'id' => (int)$r['name_id']); - - if (file_exists($file)) - $row[$r['name_id']][] = $r; - - } - } - } - } else { - $error = true; - $errors[] = $q->pdo->errorInfo(); - } - } - } else { - $error = true; - $errors[] = $q->pdo->errorInfo(); - } - } - - if ($section == 'objects') { - - //Поиск файлов по заявкам - $sql_r = "SELECT id, type_id, object_id FROM requisitions WHERE object_id = {$source_id} AND type_id = 2 and deleted = 0"; - - if ($q_r = $pdo->query($sql_r)) { - if ($pdo->num_rows($q_r) > 0) { - $req = $pdo->fetch_assoc($q_r); - - $sql = "SELECT * FROM `clients_files` as c WHERE req_id = {$req['id']} AND (SELECT id from user_client_events WHERE id=c.event_id)>0"; - if ($q = $pdo->query($sql)) { - if ($pdo->num_rows($q) > 0) { - while ($r = $pdo->fetch_assoc($q)) { - if (!empty($r['name'])) { - - $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/"; - if ($r['req_id'] > 0) - $file .= "reqs/" . $req['id'] . "/"; - - $file .= $r['guid'] . '.' . $r['type']; - - $r['type'] = 'id'; - $r['link'] = $host . '/download_file.php?id=' . $r['id']; - - $unix_time = filemtime($file); - $r['date'] = date('d.m.Y в H:i', $unix_time); - - if (!isset($list['names'][$r['name_id']])) - $list['names'][$r['name_id']] = array('type' => 'id', 'from' => 'req', 'from_id' => $req['id'], 'id' => (int)$r['name_id']); - - if (file_exists($file)) - $row[$r['name_id']][] = $r; - - } - } - } - } else { - $error = true; - $errors[] = $q->pdo->errorInfo(); - } - - $sql = "SELECT * FROM `funnel_files` WHERE req_id = {$req['id']}"; - - $q = $pdo->query($sql); - if ($pdo->num_rows($q) > 0) { - while ($r = $pdo->fetch_assoc($q)) { - if (!empty($r['name'])) { - $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/funnels/"; - if ($r['req_id'] > 0) { - $file .= "req/" . $r['req_id'] . "/"; - } - $file .= $r['guid'] . '.' . $r['type']; - $r['type'] = 'guid'; - $r['link'] = $host . '/download_file.php?guid=' . $r['guid']; - $unix_time = filemtime($file); - $r['date'] = date('d.m.Y в H:i', $unix_time); - if (!isset($list['names'][$r['etap_id']])) { - - $list['names'][$r['etap_id']] = array('type' => 'guid', 'from' => 'req', 'from_id' => $req['id'], 'id' => (int)$r['etap_id']); - } - if (file_exists($file)) { - $row[$r['etap_id']][] = $r; - } - } - } - } - } - } else { - $error = true; - $errors[] = $q_r->pdo->errorInfo(); - } - } - - $list['files'] = $row; - foreach ($list['names'] as $key => $res) { - - if ($res['type'] == 'id') { - if ($key == 0) { - $list['names'][$key]['name'] = "Без названия"; - } else { - - $sql_n = "SELECT * FROM names_client_files WHERE id={$key}"; - - if ($q_n = $pdo->query($sql_n)) { - $r_n = $pdo->fetch_assoc($q_n); - $list['names'][$key]['name'] = $r_n['name']; - } else { - $error = true; - $errors[] = $q_n->pdo->errorInfo(); - } - } - } else if ($res['type'] == 'guid') { - - $sql_n = "SELECT * FROM funnel_steps WHERE id={$key}"; - - if ($q_n = $pdo->query($sql_n)) { - $r_n = $pdo->fetch_assoc($q_n); - $list['names'][$key]['name'] = $r_n['name']; - } else { - $error = true; - $errors[] = $q_n->pdo->errorInfo(); - } - } - } - } - - if (!empty($errors)) - $error = true; - - if (!$error) { - - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => true, - 'user_id' => $user_id, - 'section' => $section, - 'list' => $list - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } - - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id, - 'errors' => $errors - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - - public function getEvents($app, $get = null, $post = null) { - - $error = false; - if ($user_id = $_SESSION['id']) { - - // Открываем соединение с БД - $pdo = $app->container->get('pdo'); - - $events = []; - - // Выборка событий о передачи объектов, объектов с клиентами - $sth = $pdo->prepare("SELECT * FROM objects_to_send WHERE new_user_id = ".$user_id." AND `accept_state` = 'NEW'"); - if ($sth->execute()) { - if ($sth->rowCount() > 0) { - while($row = $sth->fetch(\PDO::FETCH_ASSOC)) { - - $sql_in = "SELECT `agency_name`, `first_name`, `last_name`, `middle_name`, `agency`, `manager` FROM `users` WHERE `id` = '".$row['sended_user_id']."'"; - $sth_in = $pdo->prepare($sql_in); - if ($sth_in->execute()) { - if ($r_in = $sth_in->fetch(\PDO::FETCH_ASSOC)) { - - $sender_name = trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']); - if ($r_in['agency'] == 1) { - $sender_name = "Агентство " . $r_in['agency_name']; - } else { - if ($r_in['manager'] == 1) { - $sender_name = "Менеджер " . trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']); - } - } - - $clientsNum = 0; - $clientsString = ''; - $sql_clients = "SELECT `id`, `fio`, `email` FROM `clients` WHERE `objects` LIKE '%"".$row['object_id'].""%'"; - $sth_clients = $pdo->prepare($sql_clients); - if ($sth_clients->execute()) { - if ($sth_clients->rowCount() > 0) { - while($client = $sth_clients->fetch(\PDO::FETCH_ASSOC)) { - $clientsNum++; - $clientsString = $clientsString . ($clientsNum > 1 ? ", " : "") . $client['fio']; - } - } - } else { - $error = true; - } - - $sql_obj = "SELECT nazv FROM `objects` WHERE id= $row[object_id]"; - $sth_obj = $pdo->prepare($sql_obj); - if ($sth_obj->execute()) { - if ($row_obj = $sth_obj->fetch(\PDO::FETCH_ASSOC)) { - $first_line = "передал Вам объект `" . $row_obj['nazv'] . "`"; - $sec_line = "Взять "; - $subject = "Передача объекта"; - if ($clientsNum > 0) { - if ($clientsNum > 1) { - $subject = "Передача объекта\клиентов"; - $first_line = $first_line . " и клиентов " . $clientsString . "."; - $sec_line = $sec_line . " объект и клиентов в работу?"; - } else { - $subject = "Передача объекта\клиента"; - $first_line = $first_line . " и клиента " . $clientsString . "."; - $sec_line = $sec_line . " объект и клиента в работу?"; - } - } else { - $first_line = $first_line . "."; - $sec_line = $sec_line . " в работу?"; - } - - $source_id = $row['id']; - $events[] = [ - 'id' => $source_id, - 'type' => 'transfer-object', - 'object_id' => $row['object_id'], - 'sender_id' => $row['sended_user_id'], - 'datetime' => $row['create_date'], - 'subject' => $subject, - 'sender_name' => $sender_name, - 'message' => $sender_name . ' ' .$first_line . '
' . $sec_line - ]; - } - } else { - $error = true; - } - } - } else { - $error = true; - } - } - } - } else { - $error = true; - } - - // Выборка событий о передачи клиентов, заявок - $sth = $pdo->prepare("SELECT * FROM events_clients WHERE from_id = ".$user_id." AND `read` = 0"); - if ($sth->execute()) { - if ($sth->rowCount() > 0) { - while($r = $sth->fetch(\PDO::FETCH_ASSOC)) { - $sql_in = "SELECT `agency_name`, `first_name`, `last_name`, `middle_name`, `agency`, `manager` FROM `users` WHERE `id` = '".$r['user_id']."'"; - $sth_in = $pdo->prepare($sql_in); - if ($sth_in->execute()) { - if ($r_in = $sth_in->fetch(\PDO::FETCH_ASSOC)) { - - $sender_name = "Сотрудник "; - if ($r_in['agency'] == 1) - $sender_name = "Агентство "; - else if ($r_in['manager'] == 1) - $sender_name = "Менеджер "; - - $sql_cl = "SELECT `fio` FROM `clients` WHERE `id` = ".$r['client_id']; - if ($r['req_id'] > 0) - $sql_cl = "SELECT `name` as `fio`, object_id, type_id FROM `requisitions` WHERE `id` = ".$r['req_id']; - - $sth_cl = $pdo->prepare($sql_cl); - if ($sth_cl->execute()) { - if ($r_cl = $sth_cl->fetch(\PDO::FETCH_ASSOC)) { - - $tr = 0; - $objectString = ''; - $objectNum = 0; - $type_req = 0; - if ($r['event'] == 'transmitted_parallel') { - $tr = 1; - } else { - if ($r['req_id'] > 0 && $r_cl['object_id'] > 0) { - $objectNum++; - $sql_obj = "SELECT nazv FROM `objects` WHERE id= $r_cl[object_id]"; - $sth_obj = $pdo->prepare($sql_obj); - if ($sth_obj->execute()) { - if ($r_obj = $sth_obj->fetch(\PDO::FETCH_ASSOC)) { - $type_req = $r_cl['type_id']; - $objectString = $objectString . ($objectNum > 1 ? ", " : "") . $r_obj['nazv']; - } - } else { - $error = true; - } - } else { - $sql_client = "SELECT objects FROM clients WHERE id=$r[client_id]"; - - $sth_client = $pdo->prepare($sql_client); - if ($sth_client->execute()) { - if ($r_client = $sth_client->fetch(\PDO::FETCH_ASSOC)) { - $objects = json_decode(html_entity_decode($r_client['objects']), true); - foreach ($objects as $object) { - $objectNum++; - $sql_obj = "SELECT nazv FROM `objects` WHERE id= $object"; - $sth_obj = $pdo->prepare($sql_obj); - if ($sth_obj->execute()) { - if ($r_obj = $sth_obj->fetch(\PDO::FETCH_ASSOC)) { - $objectString = $objectString . ($objectNum > 1 ? ", " : "") . "`".$r_obj['nazv']."`"; - } - } else { - $error = true; - } - } - } - } else { - $error = true; - } - } - } - - if ($tr == 1) { - $first_line = "приглашает Вас к совместной работе."; - $subject = "Приглашение"; - } else { - $first_line = "передал Вам"; - $subject = "Передача клиента"; - } - - $sec_line = ""; - - if ($objectNum > 1) { - if ($r['req_id'] > 0) { - - if ($tr != 1) - $subject = 'Передача заявки/объектов'; - - if (!empty($objectString)) { - - if ($tr != 1) - $first_line .= ' заявку и объекты.'; - - $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` и объекты ' . $objectString . ' в работу?'; - } else { - - if ($tr != 1) - $first_line .= ' заявку.'; - - $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` в работу?'; - } - } else { - - if ($tr != 1) - $subject = 'Передача клиента/объектов'; - - if (!empty($objectString)) { - - if ($tr != 1) - $first_line .= ' клиента и объекты.'; - - $sec_line .= ' Взять клиента `' . $r_cl['fio'] . '` и объекты ' . $objectString . ' в работу?'; - } else { - - if ($tr != 1) - $first_line .= ' клиента.'; - - $sec_line .= ' Взять клиента `' . $r_cl['fio'] . '` в работу?'; - } - } - } else { - if ($r['req_id'] > 0) { - - if ($tr != 1) - $subject = 'Передача заявки/объекта'; - - if (!empty($objectString)) { - - if ($tr != 1) - $first_line .= ' заявку и объект.'; - - $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` и объект ' . $objectString . ' в работу?'; - } else { - - if ($tr != 1) - $first_line .= ' заявку.'; - - $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` в работу?'; - } - } else { - - if ($tr != 1) - $subject = 'Передача клиента/объекта'; - - if (!empty($objectString)) { - - if ($tr != 1) - $first_line .= ' клиента и объект.'; - - $sec_line .= ' Взять клиента `' . $r_cl['fio'] . '` и объект ' . $objectString . ' в работу?'; - } else { - - if ($tr != 1) - $first_line .= ' клиента.'; - - $sec_line .= ' Взять клиента `' . $r_cl['fio'] . '` в работу?'; - } - } - } - - if ($r['req_id'] > 0 && $type_req == 4) { - $subject = 'Передача заявки'; - $first_line .= ' заявку.'; - if (!empty($objectString)) - $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` по объекту ' . $objectString . ' в работу?'; - else - $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` по объекту в работу?'; - } - - $sender_name .= trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']); - if ($r_in['agency'] == 1) - $sender_name .= $r_in['agency_name']; - - $source_id = $r['id']; - $events[] = [ - 'id' => $source_id, - 'type' => 'transfer-client', - 'datetime' => $r['date'], - 'subject' => $subject, - 'sender_id' => $r['user_id'], - 'sender_name' => $sender_name, - 'client_id' => $r['client_id'], - 'requisition_id' => $r['req_id'], - 'tr' => $tr, // @todo: tr ?? - 'message' => $sender_name . ' ' . $first_line . '
' . $sec_line - ]; - } - } else { - $error = true; - } - } - } else { - $error = true; - } - } - } - } else { - $error = true; - } - - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => !($error), - 'user_id' => (int)$user_id, - 'count' => count($events), - 'events' => $events, - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - - public function getObjectReasons($app, $get = null, $post = null) { - - $error = false; - $reasons = []; + if (!empty($sql)) { + if ($query = mysql_query($sql)) { + if (mysql_num_rows($query) > 0) { + while ($row = mysql_fetch_assoc($query)) { + if($section == 'cottage_village') { + if(!isset($list[$row['region_id']])) $list[$row['region_id']] = array(); + $list[$row['region_id']][] = [ + 'value' => (int)$row['id'], + 'name' => trim($row['name']), + ]; + } else + $list[] = [ + 'id' => (int)$row['id'], + 'name' => trim($row['name']), + ]; + } + } + } else { + $error = true; + $errors[] = mysql_error(); + } + } + + if (!$error) { + + if (count($list) && $section == 'denial_work') { + $list[] = [ + 'id' => 0, + 'name' => 'Другое', + ]; + } + + if ($need_return) { + return $list; + } else { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => true, + 'user_id' => (int)$user_id, + 'count' => count($list), + 'list' => $list + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } + } + + if ($need_return) { + return false; + } else { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id, + 'errors' => $errors, + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } + + public function getLists($app, $get = null, $post = null) { + + $lists = []; if ($user_id = $_SESSION['id']) { - // Открываем соединение с БД - $pdo = $app->container->get('pdo'); + // Открываем соединение с БД + $mdb = $app->container->get('mysql'); + + $sections = $get['sections']; + foreach ($sections as $section) { + + $list = $this->getList($app, ['section' => $section], null, true); + if ($list) + $lists[$section] = $list; + else + $lists[$section] = false; + + } + } + + if (count($lists)) { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => true, + 'user_id' => (int)$user_id, + 'lists' => $lists + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } else { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } + + public function getFiles($app, $get = null, $post = null) { + + $error = false; + $errors = []; + + $source_id = null; + if (isset($get['source_id'])) + $source_id = (int)$get['source_id']; + + $section = null; + if (isset($get['section'])) + $section = trim($get['section']); + + if (($user_id = $_SESSION['id']) && $source_id && $section) { + + // Открываем соединение с БД + $mdb = $app->container->get('mysql'); + $pdo = $app->container->get('mypdo'); + + $list = []; + $row = []; + + $field = ''; + $table = 'user_client_events'; + if ($section == 'clients') { + $field = 'client_id'; + $table = 'user_client_events'; + } else if ($section == 'requisitions') { + $field = 'req_id'; + $table = 'user_client_events'; + } else if ($section == 'objects') { + $field = 'object_id'; + $table = 'user_object_events'; + } + + if (!empty($field) && !empty($table)) { + + $protocol = (self::is_ssl()) ? 'https://' : 'http://'; + $host = $protocol . $_SERVER['SERVER_NAME']; + + // Найденный листинг парсера (offset-free): событие-родитель файла лежит в external_listing_events, + // event_id и object_id хранятся как РЕАЛЬНЫЕ el.id (без смещения) — валидируем владение по листинговой + // таблице. Признак листинга — явный флаг is_external из запроса (id больше не диапазонный: коллизит с objects.id). + if ($section == 'objects' && self::_request_flag($get, 'is_external')) { + $sql = "SELECT * FROM clients_files as c + WHERE object_id = {$source_id} AND event_id > 0 AND (SELECT id FROM external_listing_events WHERE id = c.event_id) > 0"; + } else { + $sql = "SELECT * FROM clients_files as c + WHERE {$field} = {$source_id} AND event_id > 0 AND (SELECT id from {$table} WHERE id = c.event_id) > 0"; + } + + if ($q = $pdo->query($sql)) { + if ($pdo->num_rows($q) > 0) { + while ($r = $pdo->fetch_assoc($q)) { + if (!empty($r['name'])) { + + $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/"; + if ($r['client_id'] > 0) + $file .= "clients/" . $r['client_id'] . "/"; + else if ($r['req_id'] > 0) + $file .= "reqs/" . $r['req_id'] . "/"; + else if ($r['object_id'] > 0) + $file .= "objects/" . $r['object_id'] . "/"; + + $file .= $r['guid'] . '.' . $r['type']; + + $r['type'] = 'id'; + $r['link'] = $host . '/download_file.php?id=' . $r['id']; + + $unix_time = !empty($r['created_at']) ? strtotime($r['created_at']) : @filemtime($file); + $r['date'] = date('d.m.Y в H:i', $unix_time); + + if (!isset($list['names'][$r['name_id']])) + $list['names'][$r['name_id']] = array('type' => 'id', 'from' => $section, 'from_id' => $source_id, 'id' => (int)$r['name_id']); + + if (!empty($r['guid'])) + $row[$r['name_id']][] = $r; + + } + } + } + } else { + $error = true; + $errors[] = $q->pdo->errorInfo(); + } + + if ($section == 'clients' || $section == 'requisitions' || $section == 'free') { + + $sql = "SELECT * FROM `funnel_files` WHERE {$field} = {$source_id}"; + + if ($q = $pdo->query($sql)) { + if ($pdo->num_rows($q) > 0) { + while ($r = $pdo->fetch_assoc($q)) { + if (!empty($r['name'])) { + $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/funnels/"; + + if ($r['client_id'] > 0) + $file .= "clients/" . $r['client_id'] . "/"; + else if ($r['req_id'] > 0) + $file .= "req/" . $r['req_id'] . "/"; + + $file .= $r['guid'] . '.' . $r['type']; + + $r['type'] = 'guid'; + $r['link'] = $host . '/download_file.php?guid=' . $r['guid']; + + $unix_time = !empty($r['created_at']) ? strtotime($r['created_at']) : @filemtime($file); + $r['date'] = date('d.m.Y в H:i', $unix_time); + + if (!isset($list['names'][$r['etap_id']])) + $list['names'][$r['etap_id']] = array('type' => 'guid', 'from' => $section, 'from_id' => $source_id, 'id' => (int)$r['etap_id']); + + if (!empty($r['guid'])) + $row[$r['etap_id']][] = $r; + + } + } + } + } else { + $error = true; + $errors[] = $q->pdo->errorInfo(); + } + } + + if ($section == 'requisitions') { + + //поиск файлов по объекту + $sql = "SELECT id, type_id, object_id FROM requisitions WHERE id = {$source_id}"; + + if ($q = $pdo->query($sql)) { + $r = $pdo->fetch_assoc($q); + if ($r['type_id'] == 2 && $r['object_id'] > 0) { + + $sql = "SELECT * FROM `clients_files` as c WHERE object_id = {$r['object_id']} AND (SELECT id from user_object_events WHERE id=c.event_id)>0"; + if ($q = $pdo->query($sql)) { + if ($pdo->num_rows($q) > 0) { + while ($r = $pdo->fetch_assoc($q)) { + if (!empty($r['name'])) { + + $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/"; + if ($r['object_id'] > 0) + $file .= "objects/" . $r['object_id'] . "/"; + + $file .= $r['guid'] . '.' . $r['type']; + + $r['type'] = 'id'; + $r['link'] = $host . '/download_file.php?id=' . $r['id']; + + $unix_time = !empty($r['created_at']) ? strtotime($r['created_at']) : @filemtime($file); + $r['date'] = date('d.m.Y в H:i', $unix_time); + if (!isset($list['names'][$r['name_id']])) + $list['names'][$r['name_id']] = array('type' => 'id', 'from' => 'object', 'from_id' => $r['object_id'], 'id' => (int)$r['name_id']); + + if (!empty($r['guid'])) + $row[$r['name_id']][] = $r; + + } + } + } + } else { + $error = true; + $errors[] = $q->pdo->errorInfo(); + } + } + } else { + $error = true; + $errors[] = $q->pdo->errorInfo(); + } + } + + if ($section == 'objects') { + + //Поиск файлов по заявкам + $sql_r = "SELECT id, type_id, object_id FROM requisitions WHERE object_id = {$source_id} AND type_id = 2 and deleted = 0"; + + if ($q_r = $pdo->query($sql_r)) { + if ($pdo->num_rows($q_r) > 0) { + $req = $pdo->fetch_assoc($q_r); + + $sql = "SELECT * FROM `clients_files` as c WHERE req_id = {$req['id']} AND (SELECT id from user_client_events WHERE id=c.event_id)>0"; + if ($q = $pdo->query($sql)) { + if ($pdo->num_rows($q) > 0) { + while ($r = $pdo->fetch_assoc($q)) { + if (!empty($r['name'])) { + + $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/"; + if ($r['req_id'] > 0) + $file .= "reqs/" . $req['id'] . "/"; + + $file .= $r['guid'] . '.' . $r['type']; + + $r['type'] = 'id'; + $r['link'] = $host . '/download_file.php?id=' . $r['id']; + + $unix_time = !empty($r['created_at']) ? strtotime($r['created_at']) : @filemtime($file); + $r['date'] = date('d.m.Y в H:i', $unix_time); + + if (!isset($list['names'][$r['name_id']])) + $list['names'][$r['name_id']] = array('type' => 'id', 'from' => 'req', 'from_id' => $req['id'], 'id' => (int)$r['name_id']); + + if (!empty($r['guid'])) + $row[$r['name_id']][] = $r; + + } + } + } + } else { + $error = true; + $errors[] = $q->pdo->errorInfo(); + } + + $sql = "SELECT * FROM `funnel_files` WHERE req_id = {$req['id']}"; + + $q = $pdo->query($sql); + if ($pdo->num_rows($q) > 0) { + while ($r = $pdo->fetch_assoc($q)) { + if (!empty($r['name'])) { + $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/funnels/"; + if ($r['req_id'] > 0) { + $file .= "req/" . $r['req_id'] . "/"; + } + $file .= $r['guid'] . '.' . $r['type']; + $r['type'] = 'guid'; + $r['link'] = $host . '/download_file.php?guid=' . $r['guid']; + $unix_time = !empty($r['created_at']) ? strtotime($r['created_at']) : @filemtime($file); + $r['date'] = date('d.m.Y в H:i', $unix_time); + if (!isset($list['names'][$r['etap_id']])) { + + $list['names'][$r['etap_id']] = array('type' => 'guid', 'from' => 'req', 'from_id' => $req['id'], 'id' => (int)$r['etap_id']); + } + if (!empty($r['guid'])) { + $row[$r['etap_id']][] = $r; + } + } + } + } + } + } else { + $error = true; + $errors[] = $q_r->pdo->errorInfo(); + } + } + + $list['files'] = $row; + foreach ($list['names'] as $key => $res) { + + if ($res['type'] == 'id') { + if ($key == 0) { + $list['names'][$key]['name'] = "Без названия"; + } else { + + $sql_n = "SELECT * FROM names_client_files WHERE id={$key}"; + + if ($q_n = $pdo->query($sql_n)) { + $r_n = $pdo->fetch_assoc($q_n); + $list['names'][$key]['name'] = $r_n['name']; + } else { + $error = true; + $errors[] = $q_n->pdo->errorInfo(); + } + } + } else if ($res['type'] == 'guid') { + + $sql_n = "SELECT * FROM funnel_steps WHERE id={$key}"; + + if ($q_n = $pdo->query($sql_n)) { + $r_n = $pdo->fetch_assoc($q_n); + $list['names'][$key]['name'] = $r_n['name']; + } else { + $error = true; + $errors[] = $q_n->pdo->errorInfo(); + } + } + } + } + + if (!empty($errors)) + $error = true; + + if (!$error) { + + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => true, + 'user_id' => $user_id, + 'section' => $section, + 'list' => $list + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } + + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id, + 'errors' => $errors + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + + public function getEvents($app, $get = null, $post = null) { + + $error = false; + if ($user_id = $_SESSION['id']) { + + // Открываем соединение с БД + $pdo = $app->container->get('pdo'); + + $events = []; + + // Выборка событий о передачи объектов, объектов с клиентами + $sth = $pdo->prepare("SELECT * FROM objects_to_send WHERE new_user_id = ".$user_id." AND `accept_state` = 'NEW'"); + if ($sth->execute()) { + if ($sth->rowCount() > 0) { + while($row = $sth->fetch(\PDO::FETCH_ASSOC)) { + + $sql_in = "SELECT `agency_name`, `first_name`, `last_name`, `middle_name`, `agency`, `manager` FROM `users` WHERE `id` = '".$row['sended_user_id']."'"; + $sth_in = $pdo->prepare($sql_in); + if ($sth_in->execute()) { + if ($r_in = $sth_in->fetch(\PDO::FETCH_ASSOC)) { + + $sender_name = trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']); + if ($r_in['agency'] == 1) { + $sender_name = "Агентство " . $r_in['agency_name']; + } else { + if ($r_in['manager'] == 1) { + $sender_name = "Менеджер " . trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']); + } + } + + $clientsNum = 0; + $clientsString = ''; + $sql_clients = "SELECT `id`, `fio`, `email` FROM `clients` WHERE `objects` LIKE '%"".$row['object_id'].""%'"; + $sth_clients = $pdo->prepare($sql_clients); + if ($sth_clients->execute()) { + if ($sth_clients->rowCount() > 0) { + while($client = $sth_clients->fetch(\PDO::FETCH_ASSOC)) { + $clientsNum++; + $clientsString = $clientsString . ($clientsNum > 1 ? ", " : "") . $client['fio']; + } + } + } else { + $error = true; + } + + $sql_obj = "SELECT nazv FROM `objects` WHERE id= $row[object_id]"; + $sth_obj = $pdo->prepare($sql_obj); + if ($sth_obj->execute()) { + if ($row_obj = $sth_obj->fetch(\PDO::FETCH_ASSOC)) { + $first_line = "передал Вам объект `" . $row_obj['nazv'] . "`"; + $sec_line = "Взять "; + $subject = "Передача объекта"; + if ($clientsNum > 0) { + if ($clientsNum > 1) { + $subject = "Передача объекта\клиентов"; + $first_line = $first_line . " и клиентов " . $clientsString . "."; + $sec_line = $sec_line . " объект и клиентов в работу?"; + } else { + $subject = "Передача объекта\клиента"; + $first_line = $first_line . " и клиента " . $clientsString . "."; + $sec_line = $sec_line . " объект и клиента в работу?"; + } + } else { + $first_line = $first_line . "."; + $sec_line = $sec_line . " в работу?"; + } + + $source_id = $row['id']; + $events[] = [ + 'id' => $source_id, + 'type' => 'transfer-object', + 'object_id' => $row['object_id'], + 'sender_id' => $row['sended_user_id'], + 'datetime' => $row['create_date'], + 'subject' => $subject, + 'sender_name' => $sender_name, + 'message' => $sender_name . ' ' .$first_line . '
' . $sec_line + ]; + } + } else { + $error = true; + } + } + } else { + $error = true; + } + } + } + } else { + $error = true; + } + + // Выборка событий о передачи клиентов, заявок + $sth = $pdo->prepare("SELECT * FROM events_clients WHERE from_id = ".$user_id." AND `read` = 0"); + if ($sth->execute()) { + if ($sth->rowCount() > 0) { + while($r = $sth->fetch(\PDO::FETCH_ASSOC)) { + $sql_in = "SELECT `agency_name`, `first_name`, `last_name`, `middle_name`, `agency`, `manager` FROM `users` WHERE `id` = '".$r['user_id']."'"; + $sth_in = $pdo->prepare($sql_in); + if ($sth_in->execute()) { + if ($r_in = $sth_in->fetch(\PDO::FETCH_ASSOC)) { + + $sender_name = "Сотрудник "; + if ($r_in['agency'] == 1) + $sender_name = "Агентство "; + else if ($r_in['manager'] == 1) + $sender_name = "Менеджер "; + + $sql_cl = "SELECT `fio` FROM `clients` WHERE `id` = ".$r['client_id']; + if ($r['req_id'] > 0) + $sql_cl = "SELECT `name` as `fio`, object_id, type_id FROM `requisitions` WHERE `id` = ".$r['req_id']; + + $sth_cl = $pdo->prepare($sql_cl); + if ($sth_cl->execute()) { + if ($r_cl = $sth_cl->fetch(\PDO::FETCH_ASSOC)) { + + $tr = 0; + $objectString = ''; + $objectNum = 0; + $type_req = 0; + if ($r['event'] == 'transmitted_parallel') { + $tr = 1; + } else { + if ($r['req_id'] > 0 && $r_cl['object_id'] > 0) { + $objectNum++; + $sql_obj = "SELECT nazv FROM `objects` WHERE id= $r_cl[object_id]"; + $sth_obj = $pdo->prepare($sql_obj); + if ($sth_obj->execute()) { + if ($r_obj = $sth_obj->fetch(\PDO::FETCH_ASSOC)) { + $type_req = $r_cl['type_id']; + $objectString = $objectString . ($objectNum > 1 ? ", " : "") . $r_obj['nazv']; + } + } else { + $error = true; + } + } else { + $sql_client = "SELECT objects FROM clients WHERE id=$r[client_id]"; + + $sth_client = $pdo->prepare($sql_client); + if ($sth_client->execute()) { + if ($r_client = $sth_client->fetch(\PDO::FETCH_ASSOC)) { + $objects = json_decode(html_entity_decode($r_client['objects']), true); + foreach ($objects as $object) { + $objectNum++; + $sql_obj = "SELECT nazv FROM `objects` WHERE id= $object"; + $sth_obj = $pdo->prepare($sql_obj); + if ($sth_obj->execute()) { + if ($r_obj = $sth_obj->fetch(\PDO::FETCH_ASSOC)) { + $objectString = $objectString . ($objectNum > 1 ? ", " : "") . "`".$r_obj['nazv']."`"; + } + } else { + $error = true; + } + } + } + } else { + $error = true; + } + } + } + + if ($tr == 1) { + $first_line = "приглашает Вас к совместной работе."; + $subject = "Приглашение"; + } else { + $first_line = "передал Вам"; + $subject = "Передача клиента"; + } + + $sec_line = ""; + + if ($objectNum > 1) { + if ($r['req_id'] > 0) { + + if ($tr != 1) + $subject = 'Передача заявки/объектов'; + + if (!empty($objectString)) { + + if ($tr != 1) + $first_line .= ' заявку и объекты.'; + + $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` и объекты ' . $objectString . ' в работу?'; + } else { + + if ($tr != 1) + $first_line .= ' заявку.'; + + $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` в работу?'; + } + } else { + + if ($tr != 1) + $subject = 'Передача клиента/объектов'; + + if (!empty($objectString)) { + + if ($tr != 1) + $first_line .= ' клиента и объекты.'; + + $sec_line .= ' Взять клиента `' . $r_cl['fio'] . '` и объекты ' . $objectString . ' в работу?'; + } else { + + if ($tr != 1) + $first_line .= ' клиента.'; + + $sec_line .= ' Взять клиента `' . $r_cl['fio'] . '` в работу?'; + } + } + } else { + if ($r['req_id'] > 0) { + + if ($tr != 1) + $subject = 'Передача заявки/объекта'; + + if (!empty($objectString)) { + + if ($tr != 1) + $first_line .= ' заявку и объект.'; + + $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` и объект ' . $objectString . ' в работу?'; + } else { + + if ($tr != 1) + $first_line .= ' заявку.'; + + $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` в работу?'; + } + } else { + + if ($tr != 1) + $subject = 'Передача клиента/объекта'; + + if (!empty($objectString)) { + + if ($tr != 1) + $first_line .= ' клиента и объект.'; + + $sec_line .= ' Взять клиента `' . $r_cl['fio'] . '` и объект ' . $objectString . ' в работу?'; + } else { + + if ($tr != 1) + $first_line .= ' клиента.'; + + $sec_line .= ' Взять клиента `' . $r_cl['fio'] . '` в работу?'; + } + } + } + + if ($r['req_id'] > 0 && $type_req == 4) { + $subject = 'Передача заявки'; + $first_line .= ' заявку.'; + if (!empty($objectString)) + $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` по объекту ' . $objectString . ' в работу?'; + else + $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` по объекту в работу?'; + } + + $sender_name .= trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']); + if ($r_in['agency'] == 1) + $sender_name .= $r_in['agency_name']; + + $source_id = $r['id']; + $events[] = [ + 'id' => $source_id, + 'type' => 'transfer-client', + 'datetime' => $r['date'], + 'subject' => $subject, + 'sender_id' => $r['user_id'], + 'sender_name' => $sender_name, + 'client_id' => $r['client_id'], + 'requisition_id' => $r['req_id'], + 'tr' => $tr, // @todo: tr ?? + 'message' => $sender_name . ' ' . $first_line . '
' . $sec_line + ]; + } + } else { + $error = true; + } + } + } else { + $error = true; + } + } + } + } else { + $error = true; + } + + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => !($error), + 'user_id' => (int)$user_id, + 'count' => count($events), + 'events' => $events, + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + + public function getObjectReasons($app, $get = null, $post = null) { + + $error = false; + $reasons = []; + if ($user_id = $_SESSION['id']) { + + // Открываем соединение с БД + $pdo = $app->container->get('pdo'); // Выборка событий о передачи объектов, объектов с клиентами - $sth = $pdo->prepare("SELECT * FROM archive_object_reason order by id"); - if ($sth->execute()) { - if ($sth->rowCount() > 0) { - while($row = $sth->fetch(\PDO::FETCH_ASSOC)) { + $sth = $pdo->prepare("SELECT * FROM archive_object_reason order by id"); + if ($sth->execute()) { + if ($sth->rowCount() > 0) { + while($row = $sth->fetch(\PDO::FETCH_ASSOC)) { $reasons[] = $row; - } - } - } else { - $error = true; - } + } + } + } else { + $error = true; + } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => !($error), - 'user_id' => (int)$user_id, - 'count' => count($reasons), - 'list' => $reasons, - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => !($error), + 'user_id' => (int)$user_id, + 'count' => count($reasons), + 'list' => $reasons, + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } public function getNewBuilding($app, $get = null, $post = null) { $errors = []; @@ -3792,242 +3792,242 @@ class CommonController extends ApiController $app->stop(); } - public function getNewBuildings($app, $get = null, $post = null) { + public function getNewBuildings($app, $get = null, $post = null) { - $errors = []; - if ($user_id = $_SESSION['id']) { + $errors = []; + if ($user_id = $_SESSION['id']) { - // Открываем соединение с БД - $mdb = $app->container->get('mysql'); + // Открываем соединение с БД + $mdb = $app->container->get('mysql'); - $list = []; - $where = ''; - $total = 0; - $all_pages = 0; + $list = []; + $where = ''; + $total = 0; + $all_pages = 0; - $search = null; - if (isset($get['search'])) - $search = trim($get['search']); + $search = null; + if (isset($get['search'])) + $search = trim($get['search']); - $page = 1; - if (isset($get['page'])) - $page = (int)$get['page']; + $page = 1; + if (isset($get['page'])) + $page = (int)$get['page']; - $per_page = 10; - if (isset($get['per_page'])) - $per_page = (int)$get['per_page']; + $per_page = 10; + if (isset($get['per_page'])) + $per_page = (int)$get['per_page']; - $region_id = null; - if (isset($get['region_id'])) - $region_id = (int)$get['region_id']; + $region_id = null; + if (isset($get['region_id'])) + $region_id = (int)$get['region_id']; - if ($region_id == null) { - $curUser = new \User(); - $curUser->get($user_id); - $region_id = $curUser->region_rf_id; - } + if ($region_id == null) { + $curUser = new \User(); + $curUser->get($user_id); + $region_id = $curUser->region_rf_id; + } - $where = '`rf_region_id` = ' . $region_id; - if ($region_id == 1 || $region_id == 2 || $region_id == 3) - $where = '(`rf_region_id` IN (SELECT `id` FROM `rf_regions` WHERE `parent` = ' . $region_id . '))'; + $where = '`rf_region_id` = ' . $region_id; + if ($region_id == 1 || $region_id == 2 || $region_id == 3) + $where = '(`rf_region_id` IN (SELECT `id` FROM `rf_regions` WHERE `parent` = ' . $region_id . '))'; - $sql = "SELECT count(id) FROM `newbuildings` WHERE ". $where; + $sql = "SELECT count(id) FROM `newbuildings` WHERE ". $where; - if ($search != null) - $sql .= " AND `name` LIKE '%" . trim($search) . "%'"; + if ($search != null) + $sql .= " AND `name` LIKE '%" . trim($search) . "%'"; - $sql .= " ORDER BY `name`, `id`"; + $sql .= " ORDER BY `name`, `id`"; - if ($query = mysql_query($sql)) { - $total = mysql_result($query, 0); - $all_pages = ceil($total / $per_page); - $offset = ($page - 1) * $per_page; + if ($query = mysql_query($sql)) { + $total = mysql_result($query, 0); + $all_pages = ceil($total / $per_page); + $offset = ($page - 1) * $per_page; - $sql = "SELECT * FROM `newbuildings` WHERE ". $where; + $sql = "SELECT * FROM `newbuildings` WHERE ". $where; - if ($search != null) - $sql .= " AND `name` LIKE '%" . trim($search) . "%'"; + if ($search != null) + $sql .= " AND `name` LIKE '%" . trim($search) . "%'"; - $sql .= " ORDER BY `name`, `id` LIMIT $offset, $per_page"; - if ($query = mysql_query($sql)) { - while ($block = mysql_fetch_assoc($query)) { - $list[] = $block; - } - } else { - $errors[] = mysql_error(); - } - } else { - $errors[] = mysql_error(); - } + $sql .= " ORDER BY `name`, `id` LIMIT $offset, $per_page"; + if ($query = mysql_query($sql)) { + while ($block = mysql_fetch_assoc($query)) { + $list[] = $block; + } + } else { + $errors[] = mysql_error(); + } + } else { + $errors[] = mysql_error(); + } - if (!(count($errors))) { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => true, - 'user_id' => (int)$user_id, - 'list' => $list, - 'total' => $total, - 'page' => $page, - 'all_pages' => $all_pages, - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } + if (!(count($errors))) { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => true, + 'user_id' => (int)$user_id, + 'list' => $list, + 'total' => $total, + 'page' => $page, + 'all_pages' => $all_pages, + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id, - 'errors' => $errors, - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id, + 'errors' => $errors, + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } public function setEventState($app, $get = null, $post = null) { - $error = false; - $errors = []; - $body = $app->request->getBody(); - $data = json_decode(stripcslashes($body), true); + $error = false; + $errors = []; + $body = $app->request->getBody(); + $data = json_decode(stripcslashes($body), true); - if (($user_id = $_SESSION['id']) && isset($data['type']) && isset($data['state']) && isset($data['event_id'])) { + if (($user_id = $_SESSION['id']) && isset($data['type']) && isset($data['state']) && isset($data['event_id'])) { - $type = $data['type']; - $state = $data['state']; - $event_id = $data['event_id']; + $type = $data['type']; + $state = $data['state']; + $event_id = $data['event_id']; - // Открываем соединение с БД - $mdb = $app->container->get('mysql'); - $db_sphinx = $app->container->get('sphinx2'); + // Открываем соединение с БД + $mdb = $app->container->get('mysql'); + $db_sphinx = $app->container->get('sphinx2'); - if ($event_id && $type == 'transfer-object' && isset($data['object_id'])) { + if ($event_id && $type == 'transfer-object' && isset($data['object_id'])) { - $object_id = (int)$data['object_id']; + $object_id = (int)$data['object_id']; - // Защитный отказ — приём передачи владения на найденном листинге парсера недоступен (offset-free). - // Признак листинга — явный флаг is_external из запроса. Передачи листинга быть не должно (инициация - // загейчена), гейтим от рассинхрона. Делать ДО UPDATE objects. - if (self::_request_flag($data, 'is_external')) { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(403); - $app->response->setBody(json_encode([ - 'success' => false, - 'errors' => ['Действие недоступно для найденного листинга. Скопируйте объект в свои, чтобы управлять им.'], - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + // Защитный отказ — приём передачи владения на найденном листинге парсера недоступен (offset-free). + // Признак листинга — явный флаг is_external из запроса. Передачи листинга быть не должно (инициация + // загейчена), гейтим от рассинхрона. Делать ДО UPDATE objects. + if (self::_request_flag($data, 'is_external')) { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(403); + $app->response->setBody(json_encode([ + 'success' => false, + 'errors' => ['Действие недоступно для найденного листинга. Скопируйте объект в свои, чтобы управлять им.'], + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } - $sql = "SELECT * FROM objects_to_send WHERE id = $event_id AND object_id = $object_id"; - if ($rez = mysql_query($sql)) { - $row = mysql_fetch_assoc($rez); - $source_id = $row['id']; + $sql = "SELECT * FROM objects_to_send WHERE id = $event_id AND object_id = $object_id"; + if ($rez = mysql_query($sql)) { + $row = mysql_fetch_assoc($rez); + $source_id = $row['id']; - if ($source_id && $state == 'accepted') { + if ($source_id && $state == 'accepted') { - $new_user_id = (int)$row['new_user_id']; - $object_id = (int)$row['object_id']; + $new_user_id = (int)$row['new_user_id']; + $object_id = (int)$row['object_id']; - $new_user = new \User; - $new_user->get($new_user_id); + $new_user = new \User; + $new_user->get($new_user_id); - if (!$new_user->agencyId) - $new_user->agencyId = $new_user_id; + if (!$new_user->agencyId) + $new_user->agencyId = $new_user_id; - $current_user = new \User; - $current_user->get($user_id); + $current_user = new \User; + $current_user->get($user_id); - if (!$current_user->agencyId) - $current_user->agencyId = $user_id; + if (!$current_user->agencyId) + $current_user->agencyId = $user_id; - $phone = $new_user->phone; - $num_search = \User::num_search($phone); - /*if(!empty($new_user->phone2)){ + $phone = $new_user->phone; + $num_search = \User::num_search($phone); + /*if(!empty($new_user->phone2)){ $phone = $phone.' '.$new_user->phone2; }*/ - $sobstv = trim($new_user->last_name . ' ' . $new_user->first_name . ' ' . $new_user->middle_name); + $sobstv = trim($new_user->last_name . ' ' . $new_user->first_name . ' ' . $new_user->middle_name); - if ($new_user->agency == 0) { - $sql = "SELECT * FROM users WHERE id=$new_user->id_manager"; - if ($rez = mysql_query($sql)) - $manager = mysql_fetch_assoc($rez); - else - $errors[] = mysql_error(); + if ($new_user->agency == 0) { + $sql = "SELECT * FROM users WHERE id=$new_user->id_manager"; + if ($rez = mysql_query($sql)) + $manager = mysql_fetch_assoc($rez); + else + $errors[] = mysql_error(); - if ($manager['id_manager']) - $agency = mysql_fetch_assoc(mysql_query("SELECT * FROM users WHERE id=$manager[id_manager]")); - else - $agency = $manager; + if ($manager['id_manager']) + $agency = mysql_fetch_assoc(mysql_query("SELECT * FROM users WHERE id=$manager[id_manager]")); + else + $agency = $manager; - if ($agency) - $sobstv = trim($current_user->last_name . ' ' . $current_user->first_name . ' ' . $current_user->middle_name) . ", агентство " . $agency['agency_name']; + if ($agency) + $sobstv = trim($current_user->last_name . ' ' . $current_user->first_name . ' ' . $current_user->middle_name) . ", агентство " . $agency['agency_name']; - } else { - $sobstv = $sobstv . ", агентство " . $new_user->agency_name; - } + } else { + $sobstv = $sobstv . ", агентство " . $new_user->agency_name; + } - // перенос всех объектов - $sql = "UPDATE objects SET id_add_user = $new_user->id, phone = '$phone', phone_search = '$num_search', sobstv = '$sobstv' WHERE id=$object_id"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } + // перенос всех объектов + $sql = "UPDATE objects SET id_add_user = $new_user->id, phone = '$phone', phone_search = '$num_search', sobstv = '$sobstv' WHERE id=$object_id"; + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } - //Запись в сфинкс - $sql_sph = "UPDATE objects SET id_add_user = $new_user->id, phone_search = '$num_search' WHERE id=$object_id"; - if (!$db_sphinx->query($sql_sph)) { - $error = true; - $errors[] = mysql_error(); - } + //Запись в сфинкс + $sql_sph = "UPDATE objects SET id_add_user = $new_user->id, phone_search = '$num_search' WHERE id=$object_id"; + if (!$db_sphinx->query($sql_sph)) { + $error = true; + $errors[] = mysql_error(); + } - //перенос событий объектов - $sql = "UPDATE user_object_events SET user_id = $new_user->id WHERE object_id = $object_id"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } + //перенос событий объектов + $sql = "UPDATE user_object_events SET user_id = $new_user->id WHERE object_id = $object_id"; + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } - //перенос комментариев объектов - $sql = "UPDATE user_object_comments SET user_id = $new_user->id WHERE object_id = $object_id"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } + //перенос комментариев объектов + $sql = "UPDATE user_object_comments SET user_id = $new_user->id WHERE object_id = $object_id"; + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } - // перенос Зипал - $sql = "UPDATE zipal_objects SET user_id = $new_user->id, send_to_update = 1 WHERE object_id = $object_id"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } + // перенос Зипал + $sql = "UPDATE zipal_objects SET user_id = $new_user->id, send_to_update = 1 WHERE object_id = $object_id"; + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } - $sql = "UPDATE advertising_package_object_publish SET send_to_update = '1', error_when_send_to_update = '' WHERE object_id = $object_id"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } + $sql = "UPDATE advertising_package_object_publish SET send_to_update = '1', error_when_send_to_update = '' WHERE object_id = $object_id"; + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } - /** - * Передача заявок Реализация - */ - $sql_req = "SELECT id, `name`, object_id, type_id, who_work, funnel_id, confirm FROM `requisitions` WHERE object_id = {$object_id} AND cancel=0 AND deleted=0 AND (type_id = 2 or (SELECT heir FROM requisitions_type WHERE id = requisitions.type_id) = 2) AND who_work != '".$new_user->id."'"; - //echo $sql_req."\n"; - $q_req = mysql_query($sql_req); - if(mysql_num_rows($q_req) > 0){ - while($r_req = mysql_fetch_assoc($q_req)){ - $sql_up = "UPDATE requisitions SET confirm=1, who_work={$new_user->id} WHERE id={$r_req['id']}"; - //echo $sql_up."\n"; - if(mysql_query($sql_up)){ - $sql_ev = "INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`, dop_text) VALUES ('".$user_id."', '{$r_req['id']}', '".$new_user->id."', 'update', '1', 'Переведена на ответственного при принятии объекта ID {$object_id}')"; - //file_put_contents($_SERVER['DOCUMENT_ROOT']."/log_task_telega.txt", date('d.m.y H:i:s').' chat_id '.$chatId.' id:'.$event_id." ". $sql_ev."\n", FILE_APPEND); - mysql_query($sql_ev); - } - } - } + /** + * Передача заявок Реализация + */ + $sql_req = "SELECT id, `name`, object_id, type_id, who_work, funnel_id, confirm FROM `requisitions` WHERE object_id = {$object_id} AND cancel=0 AND deleted=0 AND (type_id = 2 or (SELECT heir FROM requisitions_type WHERE id = requisitions.type_id) = 2) AND who_work != '".$new_user->id."'"; + //echo $sql_req."\n"; + $q_req = mysql_query($sql_req); + if(mysql_num_rows($q_req) > 0){ + while($r_req = mysql_fetch_assoc($q_req)){ + $sql_up = "UPDATE requisitions SET confirm=1, who_work={$new_user->id} WHERE id={$r_req['id']}"; + //echo $sql_up."\n"; + if(mysql_query($sql_up)){ + $sql_ev = "INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`, dop_text) VALUES ('".$user_id."', '{$r_req['id']}', '".$new_user->id."', 'update', '1', 'Переведена на ответственного при принятии объекта ID {$object_id}')"; + //file_put_contents($_SERVER['DOCUMENT_ROOT']."/log_task_telega.txt", date('d.m.y H:i:s').' chat_id '.$chatId.' id:'.$event_id." ". $sql_ev."\n", FILE_APPEND); + mysql_query($sql_ev); + } + } + } - //передаем клиентов - /*$sql_clients = "SELECT `id`, `fio`, `email` FROM `clients` WHERE `objects` LIKE '%"".$object_id.""%'"; + //передаем клиентов + /*$sql_clients = "SELECT `id`, `fio`, `email` FROM `clients` WHERE `objects` LIKE '%"".$object_id.""%'"; $q_client = mysql_query($sql_clients); if (mysql_num_rows($q_client) > 0) { while($client = mysql_fetch_assoc($q_client)) { @@ -4057,41 +4057,41 @@ class CommonController extends ApiController } }*/ - $sql = "UPDATE objects_to_send SET accept_date = NOW(), accept_state='ACCEPTED' WHERE id = $source_id AND object_id=$object_id"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } - } else if ($source_id && $state == 'rejected') { - $sql = "UPDATE objects_to_send SET accept_date = NOW(), accept_state='REJECTED' WHERE id=$source_id AND object_id=$object_id"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } - } - } else { - $errors[] = mysql_error(); - } - } else if ($type == 'transfer-client' && (isset($data['client_id']) || isset($data['req_id']))) { + $sql = "UPDATE objects_to_send SET accept_date = NOW(), accept_state='ACCEPTED' WHERE id = $source_id AND object_id=$object_id"; + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } + } else if ($source_id && $state == 'rejected') { + $sql = "UPDATE objects_to_send SET accept_date = NOW(), accept_state='REJECTED' WHERE id=$source_id AND object_id=$object_id"; + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } + } + } else { + $errors[] = mysql_error(); + } + } else if ($type == 'transfer-client' && (isset($data['client_id']) || isset($data['req_id']))) { - $tr = $data['tr']; // @todo: `tr` ??? - $who_work = $user_id; - $sender_id = (int)$data['sender_id']; - $client_id = (int)$data['client_id']; - $requisition_id = (int)$data['requisition_id']; - if ($state == 'accepted') { - if ($tr != 1) { + $tr = $data['tr']; // @todo: `tr` ??? + $who_work = $user_id; + $sender_id = (int)$data['sender_id']; + $client_id = (int)$data['client_id']; + $requisition_id = (int)$data['requisition_id']; + if ($state == 'accepted') { + if ($tr != 1) { - $sql = "UPDATE clients SET confirm=1, who_work=$who_work WHERE id=$client_id"; - if ($requisition_id > 0) - $sql = "UPDATE requisitions SET confirm=1, who_work=$who_work WHERE id=$requisition_id"; + $sql = "UPDATE clients SET confirm=1, who_work=$who_work WHERE id=$client_id"; + if ($requisition_id > 0) + $sql = "UPDATE requisitions SET confirm=1, who_work=$who_work WHERE id=$requisition_id"; - if (mysql_query($sql)) { + if (mysql_query($sql)) { - // Автопривязка ответственного по заявке к клиенту из заявки - if ($requisition_id > 0) { - $sql = "UPDATE `clients` + // Автопривязка ответственного по заявке к клиенту из заявки + if ($requisition_id > 0) { + $sql = "UPDATE `clients` JOIN `requisitions` AS `req` ON `clients`.`id` = `req`.`client_id` AND `clients`.`who_work` = 0 AND @@ -4102,1150 +4102,1150 @@ class CommonController extends ApiController SET `clients`.`who_work` = '$who_work', `clients`.`confirm` = 1"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } - } - } else { - $error = true; - $errors[] = mysql_error(); - } - } else { - $sql_client = "SELECT doers, who_work FROM clients WHERE id=$client_id"; - if ($requisition_id > 0) - $sql_client = "SELECT doers, who_work FROM requisitions WHERE id=$requisition_id"; + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } + } + } else { + $error = true; + $errors[] = mysql_error(); + } + } else { + $sql_client = "SELECT doers, who_work FROM clients WHERE id=$client_id"; + if ($requisition_id > 0) + $sql_client = "SELECT doers, who_work FROM requisitions WHERE id=$requisition_id"; - if ($q_client = mysql_query($sql_client)) { - $r_client = mysql_fetch_assoc($q_client); + if ($q_client = mysql_query($sql_client)) { + $r_client = mysql_fetch_assoc($q_client); - if (!empty($r_client['doers'])) { - $confirm = 1; - $doers = json_decode(html_entity_decode($r_client['doers']), true); + if (!empty($r_client['doers'])) { + $confirm = 1; + $doers = json_decode(html_entity_decode($r_client['doers']), true); - $doers[$user_id] = 1; - foreach($doers as $doer) { - if ($doer == 0) - $confirm = 0; - } + $doers[$user_id] = 1; + foreach($doers as $doer) { + if ($doer == 0) + $confirm = 0; + } - $sql = "UPDATE clients SET doers = '".self::clearInput(json_encode($doers))."', doers_confirm = $confirm WHERE id = $client_id"; - if ($requisition_id > 0) - $sql = "UPDATE requisitions SET doers = '".self::clearInput(json_encode($doers))."', doers_confirm = $confirm WHERE id = $requisition_id"; + $sql = "UPDATE clients SET doers = '".self::clearInput(json_encode($doers))."', doers_confirm = $confirm WHERE id = $client_id"; + if ($requisition_id > 0) + $sql = "UPDATE requisitions SET doers = '".self::clearInput(json_encode($doers))."', doers_confirm = $confirm WHERE id = $requisition_id"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } - $sql = "UPDATE doers_emp_client SET confirm = 1 WHERE client_id = $client_id AND who_work = $r_client[who_work] AND doer_id = $user_id"; - if ($requisition_id > 0) - $sql = "UPDATE doers_emp_client SET confirm = 1 WHERE req_id = $requisition_id AND who_work = $r_client[who_work] AND doer_id = $user_id"; + $sql = "UPDATE doers_emp_client SET confirm = 1 WHERE client_id = $client_id AND who_work = $r_client[who_work] AND doer_id = $user_id"; + if ($requisition_id > 0) + $sql = "UPDATE doers_emp_client SET confirm = 1 WHERE req_id = $requisition_id AND who_work = $r_client[who_work] AND doer_id = $user_id"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } - // синкаем нормализованную таблицу, которую читает десктоп (Clients → clients_doers WHERE confirm=1) - $sql = "UPDATE clients_doers SET confirm = 1 WHERE client_id = $client_id AND user_id = $user_id"; - if ($requisition_id > 0) - $sql = "UPDATE requisition_doers SET confirm = 1 WHERE requisition_id = $requisition_id AND user_id = $user_id"; + // синкаем нормализованную таблицу, которую читает десктоп (Clients → clients_doers WHERE confirm=1) + $sql = "UPDATE clients_doers SET confirm = 1 WHERE client_id = $client_id AND user_id = $user_id"; + if ($requisition_id > 0) + $sql = "UPDATE requisition_doers SET confirm = 1 WHERE requisition_id = $requisition_id AND user_id = $user_id"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } - } - } else { - $error = true; - $errors[] = mysql_error(); - } - } + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } + } + } else { + $error = true; + $errors[] = mysql_error(); + } + } - if ($tr != 1) { + if ($tr != 1) { - $sql = "UPDATE user_client_events SET user_id = $who_work WHERE client_id = $client_id AND type != 'step' AND type != 'file'"; - if ($requisition_id > 0) - $sql = "UPDATE user_client_events SET user_id = $who_work WHERE req_id = $requisition_id AND type != 'step' AND type != 'file'"; + $sql = "UPDATE user_client_events SET user_id = $who_work WHERE client_id = $client_id AND type != 'step' AND type != 'file'"; + if ($requisition_id > 0) + $sql = "UPDATE user_client_events SET user_id = $who_work WHERE req_id = $requisition_id AND type != 'step' AND type != 'file'"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } - } + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } + } - $sql = "UPDATE `events_clients` SET `read` = 1, date_update = '".date('Y-m-d H:i:s')."' WHERE client_id = $client_id AND from_id = $user_id"; - if ($requisition_id > 0) - $sql = "UPDATE `events_clients` SET `read` = 1, date_update = '".date('Y-m-d H:i:s')."' WHERE req_id = $requisition_id AND from_id = $user_id"; + $sql = "UPDATE `events_clients` SET `read` = 1, date_update = '".date('Y-m-d H:i:s')."' WHERE client_id = $client_id AND from_id = $user_id"; + if ($requisition_id > 0) + $sql = "UPDATE `events_clients` SET `read` = 1, date_update = '".date('Y-m-d H:i:s')."' WHERE req_id = $requisition_id AND from_id = $user_id"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } - $accepted = 'accepted'; - if ($tr == 1) - $accepted = 'accepted_doer'; + $accepted = 'accepted'; + if ($tr == 1) + $accepted = 'accepted_doer'; - $sql = "INSERT INTO `events_clients` (user_id, client_id, from_id, event, `read`) VALUES ('".$user_id."', '".$client_id."', '".$user_id."', '".$accepted."', '1')"; - if ($requisition_id > 0) - $sql = "INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`) VALUES ('".$user_id."', '".$requisition_id."', '".$user_id."', '".$accepted."', '1')"; + $sql = "INSERT INTO `events_clients` (user_id, client_id, from_id, event, `read`) VALUES ('".$user_id."', '".$client_id."', '".$user_id."', '".$accepted."', '1')"; + if ($requisition_id > 0) + $sql = "INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`) VALUES ('".$user_id."', '".$requisition_id."', '".$user_id."', '".$accepted."', '1')"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } - $rUser = null; - $sobstv = ''; - $sqlUser = "SELECT `first_name`, `last_name`, `middle_name`, `phone` FROM `users` WHERE id=".$user_id; - if ($qUser = mysql_query($sqlUser)) { - $rUser = mysql_fetch_assoc($qUser); - $sobstv = trim($rUser['last_name'] . ' ' . $rUser['first_name'] . ' ' . $rUser['middle_name']); - if ($_SESSION['agency']) { - $sobstv = $sobstv . ", агентство " . $rUser['agency_name']; - } else { - $agency = new \User; - if (isset($agency->agencyName)) { - $sobstv = trim($rUser['last_name'] . ' ' . $rUser['first_name'] . ' ' . $rUser['middle_name']) . ", агентство " . $agency->agencyName; - } else { - $sobstv = trim($rUser['last_name'] . ' ' . $rUser['first_name'] . ' ' . $rUser['middle_name']); - } - } - } else { - $error = true; - $errors[] = mysql_error(); - } + $rUser = null; + $sobstv = ''; + $sqlUser = "SELECT `first_name`, `last_name`, `middle_name`, `phone` FROM `users` WHERE id=".$user_id; + if ($qUser = mysql_query($sqlUser)) { + $rUser = mysql_fetch_assoc($qUser); + $sobstv = trim($rUser['last_name'] . ' ' . $rUser['first_name'] . ' ' . $rUser['middle_name']); + if ($_SESSION['agency']) { + $sobstv = $sobstv . ", агентство " . $rUser['agency_name']; + } else { + $agency = new \User; + if (isset($agency->agencyName)) { + $sobstv = trim($rUser['last_name'] . ' ' . $rUser['first_name'] . ' ' . $rUser['middle_name']) . ", агентство " . $agency->agencyName; + } else { + $sobstv = trim($rUser['last_name'] . ' ' . $rUser['first_name'] . ' ' . $rUser['middle_name']); + } + } + } else { + $error = true; + $errors[] = mysql_error(); + } - if ($rUser && $tr != 1) { + if ($rUser && $tr != 1) { - //$num_search = num_search($rUser['phone']); + //$num_search = num_search($rUser['phone']); - //Передача объекта - if ($requisition_id > 0) { - $sql_cl = "SELECT `name` as `fio`, object_id, type_id FROM `requisitions` WHERE `id` = ".$requisition_id; - $q_cl = mysql_query($sql_cl); - $r_cl = mysql_fetch_assoc($q_cl); - if ($r_cl['object_id'] && $r_cl['type_id'] != 4) { - $sql = "UPDATE objects SET id_add_user = '".$user_id."', phone='".$rUser['phone']."', sobstv='".$sobstv."' WHERE id = ".$r_cl['object_id']; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } - } - } else { - $sql_client = "SELECT objects FROM clients WHERE id=$client_id"; - $q_client = mysql_query($sql_client); - $r_client = mysql_fetch_assoc($q_client); - $objects = json_decode(html_entity_decode($r_client['objects']), true); - foreach($objects as $object) { - $sql = "UPDATE objects SET id_add_user = '".$user_id."', phone='".$rUser['phone']."', sobstv='".$sobstv."' WHERE id = ".$object; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } - } - } - } - } else if ($state == 'rejected') { + //Передача объекта + if ($requisition_id > 0) { + $sql_cl = "SELECT `name` as `fio`, object_id, type_id FROM `requisitions` WHERE `id` = ".$requisition_id; + $q_cl = mysql_query($sql_cl); + $r_cl = mysql_fetch_assoc($q_cl); + if ($r_cl['object_id'] && $r_cl['type_id'] != 4) { + $sql = "UPDATE objects SET id_add_user = '".$user_id."', phone='".$rUser['phone']."', sobstv='".$sobstv."' WHERE id = ".$r_cl['object_id']; + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } + } + } else { + $sql_client = "SELECT objects FROM clients WHERE id=$client_id"; + $q_client = mysql_query($sql_client); + $r_client = mysql_fetch_assoc($q_client); + $objects = json_decode(html_entity_decode($r_client['objects']), true); + foreach($objects as $object) { + $sql = "UPDATE objects SET id_add_user = '".$user_id."', phone='".$rUser['phone']."', sobstv='".$sobstv."' WHERE id = ".$object; + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } + } + } + } + } else if ($state == 'rejected') { - if ($tr != 1) { + if ($tr != 1) { - $confirm = 0; - if ($user_id == $who_work) - $confirm = 1; + $confirm = 0; + if ($user_id == $who_work) + $confirm = 1; - $sql = "UPDATE clients SET confirm=$confirm, who_work=$who_work WHERE id=$client_id"; - if ($requisition_id > 0) - $sql = "UPDATE requisitions SET confirm=$confirm, who_work=$who_work WHERE id=$requisition_id"; + $sql = "UPDATE clients SET confirm=$confirm, who_work=$who_work WHERE id=$client_id"; + if ($requisition_id > 0) + $sql = "UPDATE requisitions SET confirm=$confirm, who_work=$who_work WHERE id=$requisition_id"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } - } else { + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } + } else { - $sql_client = "SELECT doers, who_work FROM clients WHERE id=$client_id"; - if ($requisition_id > 0) - $sql_client = "SELECT doers, who_work FROM requisitions WHERE id=$requisition_id"; + $sql_client = "SELECT doers, who_work FROM clients WHERE id=$client_id"; + if ($requisition_id > 0) + $sql_client = "SELECT doers, who_work FROM requisitions WHERE id=$requisition_id"; - if ($q_client = mysql_query($sql_client)) { + if ($q_client = mysql_query($sql_client)) { - $r_client = mysql_fetch_assoc($q_client); + $r_client = mysql_fetch_assoc($q_client); - $doer_clients = 0; - if (!empty($r_client['doers'])) { + $doer_clients = 0; + if (!empty($r_client['doers'])) { - $confirm = 1; - $doers = json_decode(html_entity_decode($r_client['doers']), true); - unset($doers[$user_id]); + $confirm = 1; + $doers = json_decode(html_entity_decode($r_client['doers']), true); + unset($doers[$user_id]); - if (empty($doers)) { - $confirm = 1; - } else { - foreach($doers as $id_user => $doer) { + if (empty($doers)) { + $confirm = 1; + } else { + foreach($doers as $id_user => $doer) { - if ($doer == 0) - $confirm = 0; + if ($doer == 0) + $confirm = 0; - if ($id_user != $r_client['who_work']) - $doer_clients = 1; + if ($id_user != $r_client['who_work']) + $doer_clients = 1; - } - } + } + } - $sql = "UPDATE clients SET doers='".self::clearInput(json_encode($doers))."', doers_confirm=$confirm, doer_clients=$doer_clients WHERE id=$client_id"; - if ($requisition_id > 0) - $sql = "UPDATE requisitions SET doers='".self::clearInput(json_encode($doers))."', doers_confirm=$confirm, doer_clients=$doer_clients WHERE id=$requisition_id"; + $sql = "UPDATE clients SET doers='".self::clearInput(json_encode($doers))."', doers_confirm=$confirm, doer_clients=$doer_clients WHERE id=$client_id"; + if ($requisition_id > 0) + $sql = "UPDATE requisitions SET doers='".self::clearInput(json_encode($doers))."', doers_confirm=$confirm, doer_clients=$doer_clients WHERE id=$requisition_id"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } - } - } else { - $error = true; - $errors[] = mysql_error(); - } - } + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } + } + } else { + $error = true; + $errors[] = mysql_error(); + } + } - $from = $user_id; - if ($event_id) { - $sql_from = "SELECT user_id FROM `events_clients` WHERE `id` = $event_id"; - if ($q_from = mysql_query($sql_from)) { - $r_from = mysql_fetch_assoc($q_from); - $from = $r_from['user_id']; - $sql = "UPDATE `events_clients` set `read` = 1, `date_update`='".date('Y-m-d H:i:s')."' WHERE `id` = $event_id"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } - } else { - $error = true; - $errors[] = mysql_error(); - } - } else { + $from = $user_id; + if ($event_id) { + $sql_from = "SELECT user_id FROM `events_clients` WHERE `id` = $event_id"; + if ($q_from = mysql_query($sql_from)) { + $r_from = mysql_fetch_assoc($q_from); + $from = $r_from['user_id']; + $sql = "UPDATE `events_clients` set `read` = 1, `date_update`='".date('Y-m-d H:i:s')."' WHERE `id` = $event_id"; + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } + } else { + $error = true; + $errors[] = mysql_error(); + } + } else { - $sql_from = "SELECT id, user_id FROM `events_clients` WHERE `read` = 0 AND `client_id` = $client_id AND `from_id` = $from"; - if ($requisition_id > 0) - $sql_from = "SELECT id, user_id FROM `events_clients` WHERE `read` = 0 AND `req_id` = $requisition_id AND `from_id` = $from"; + $sql_from = "SELECT id, user_id FROM `events_clients` WHERE `read` = 0 AND `client_id` = $client_id AND `from_id` = $from"; + if ($requisition_id > 0) + $sql_from = "SELECT id, user_id FROM `events_clients` WHERE `read` = 0 AND `req_id` = $requisition_id AND `from_id` = $from"; - if ($q_from = mysql_query($sql_from)) { - $r_from = mysql_fetch_assoc($q_from); - $from = $r_from['user_id']; - $id_event = $r_from['id']; - $sql = "UPDATE `events_clients` SET `read` = 1, `date_update`='".date('Y-m-d H:i:s')."' WHERE `id` = $id_event"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } - } else { - $error = true; - $errors[] = mysql_error(); - } - } + if ($q_from = mysql_query($sql_from)) { + $r_from = mysql_fetch_assoc($q_from); + $from = $r_from['user_id']; + $id_event = $r_from['id']; + $sql = "UPDATE `events_clients` SET `read` = 1, `date_update`='".date('Y-m-d H:i:s')."' WHERE `id` = $id_event"; + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } + } else { + $error = true; + $errors[] = mysql_error(); + } + } - $read = 0; - if ($from == $user_id || $tr == 1) - $read = 1; + $read = 0; + if ($from == $user_id || $tr == 1) + $read = 1; - $event = 'notadopted'; - if ($tr == 1) { - $read = 1; - $event = 'notadopted_doer'; - } + $event = 'notadopted'; + if ($tr == 1) { + $read = 1; + $event = 'notadopted_doer'; + } - $sql = "INSERT INTO `events_clients` (user_id, client_id, from_id, event, `read`, send_telegramm) VALUES ('".$user_id."', '".$client_id."', '".$from."', '".$event."', '".$read."', '1')"; - if ($requisition_id > 0) - $sql = "INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`, send_telegramm) VALUES ('".$user_id."', '".$requisition_id."', '".$from."', '".$event."', '".$read."', '1')"; + $sql = "INSERT INTO `events_clients` (user_id, client_id, from_id, event, `read`, send_telegramm) VALUES ('".$user_id."', '".$client_id."', '".$from."', '".$event."', '".$read."', '1')"; + if ($requisition_id > 0) + $sql = "INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`, send_telegramm) VALUES ('".$user_id."', '".$requisition_id."', '".$from."', '".$event."', '".$read."', '1')"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } - } - } + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } + } + } - if (!$error) { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => true, - 'user_id' => (int)$user_id - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } + if (!$error) { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => true, + 'user_id' => (int)$user_id + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => (int)$user_id, - 'errors' => $errors - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => (int)$user_id, + 'errors' => $errors + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } public function setViewed($app, $get = null, $post = null) { - $error = false; - $errors = []; + $error = false; + $errors = []; - $body = $app->request->getBody(); - $data = json_decode(stripcslashes($body), true); + $body = $app->request->getBody(); + $data = json_decode(stripcslashes($body), true); - $object_id = null; - if (isset($data['object_id'])) - $object_id = (int)$data['object_id']; + $object_id = null; + if (isset($data['object_id'])) + $object_id = (int)$data['object_id']; - $client_id = null; - if (isset($data['client_id'])) - $client_id = (int)$data['client_id']; + $client_id = null; + if (isset($data['client_id'])) + $client_id = (int)$data['client_id']; - $requisition_id = null; - if (isset($data['requisition_id'])) - $requisition_id = (int)$data['requisition_id']; + $requisition_id = null; + if (isset($data['requisition_id'])) + $requisition_id = (int)$data['requisition_id']; - if (($user_id = $_SESSION['id']) && ($object_id || $client_id || $requisition_id)) { + if (($user_id = $_SESSION['id']) && ($object_id || $client_id || $requisition_id)) { - // Открываем соединение с БД - $mdb = $app->container->get('mysql'); + // Открываем соединение с БД + $mdb = $app->container->get('mysql'); - if ($object_id && in_array($object_id, $_SESSION['new_transfers']['objects'])) { - $key = array_search($object_id, $_SESSION['new_transfers']['objects']); - if ($key !== false) { - unset($_SESSION['new_transfers']['objects'][$key]); - } - } + if ($object_id && in_array($object_id, $_SESSION['new_transfers']['objects'])) { + $key = array_search($object_id, $_SESSION['new_transfers']['objects']); + if ($key !== false) { + unset($_SESSION['new_transfers']['objects'][$key]); + } + } - if ($client_id && in_array($client_id, $_SESSION['new_transfers']['clients'])) { - $key = array_search($client_id, $_SESSION['new_transfers']['clients']); - if ($key !== false) { - unset($_SESSION['new_transfers']['clients'][$key]); - } - } + if ($client_id && in_array($client_id, $_SESSION['new_transfers']['clients'])) { + $key = array_search($client_id, $_SESSION['new_transfers']['clients']); + if ($key !== false) { + unset($_SESSION['new_transfers']['clients'][$key]); + } + } - if ($requisition_id && in_array($requisition_id, $_SESSION['new_transfers']['requisitions'])) { - $key = array_search($requisition_id, $_SESSION['new_transfers']['requisitions']); - if ($key !== false) { - unset($_SESSION['new_transfers']['requisitions'][$key]); - } - } + if ($requisition_id && in_array($requisition_id, $_SESSION['new_transfers']['requisitions'])) { + $key = array_search($requisition_id, $_SESSION['new_transfers']['requisitions']); + if ($key !== false) { + unset($_SESSION['new_transfers']['requisitions'][$key]); + } + } - // Обновление инфо о том, что клиент/заявка были просмотрены пользователем - if ($client_id > 0) { - $sql = "UPDATE `events_clients` SET `viewed` = 1 + // Обновление инфо о том, что клиент/заявка были просмотрены пользователем + if ($client_id > 0) { + $sql = "UPDATE `events_clients` SET `viewed` = 1 WHERE `viewed` = 0 AND `read` = 1 AND `user_id` = '$user_id' AND `client_id` = '$client_id' AND `from_id` = '$user_id' AND (`event` = 'accepted' OR `event` = 'accepted_doer')"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } - } + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } + } - if ($requisition_id > 0) { - $sql = "UPDATE `events_clients` SET `viewed` = 1 + if ($requisition_id > 0) { + $sql = "UPDATE `events_clients` SET `viewed` = 1 WHERE `viewed` = 0 AND `read` = 1 AND `user_id` = '$user_id' AND `req_id` = '$requisition_id' AND `from_id` = '$user_id' AND (`event` = 'accepted' OR `event` = 'accepted_doer')"; - if (!mysql_query($sql)) { - $error = true; - $errors[] = mysql_error(); - } - } + if (!mysql_query($sql)) { + $error = true; + $errors[] = mysql_error(); + } + } - if (!$errors) { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => !$errors, - 'user_id' => (int)$user_id, - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } + if (!$errors) { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => !$errors, + 'user_id' => (int)$user_id, + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => $_SESSION['id'], - 'errors' => $errors - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => $_SESSION['id'], + 'errors' => $errors + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); } public function setFunnels($app, $get = null, $post = null) { - $body = $app->request->getBody(); - $data = json_decode(stripcslashes($body), true); + $body = $app->request->getBody(); + $data = json_decode(stripcslashes($body), true); - $errors = []; + $errors = []; - $section = null; - if (isset($data['section'])) - $section = trim($data['section']); + $section = null; + if (isset($data['section'])) + $section = trim($data['section']); - $clients_ids = null; - if (isset($data['sources_ids']) && $section == 'clients') - $clients_ids = $data['sources_ids']; + $clients_ids = null; + if (isset($data['sources_ids']) && $section == 'clients') + $clients_ids = $data['sources_ids']; - $req_ids = null; - if (isset($data['sources_ids']) && $section == 'requisitions') - $req_ids = $data['sources_ids']; + $req_ids = null; + if (isset($data['sources_ids']) && $section == 'requisitions') + $req_ids = $data['sources_ids']; - $funnel_id = null; - if (isset($data['funnel_id'])) - $funnel_id = (int)$data['funnel_id']; + $funnel_id = null; + if (isset($data['funnel_id'])) + $funnel_id = (int)$data['funnel_id']; - if (($user_id = $_SESSION['id']) && $section && !empty($funnel_id) && ($req_ids || $clients_ids)) { + if (($user_id = $_SESSION['id']) && $section && !empty($funnel_id) && ($req_ids || $clients_ids)) { - // Открываем соединение с БД - $mdb = $app->container->get('mysql'); + // Открываем соединение с БД + $mdb = $app->container->get('mysql'); - if ($clients_ids && $section == 'clients') { + if ($clients_ids && $section == 'clients') { - if (!is_array($clients_ids)) - $clients_ids = [$clients_ids]; + if (!is_array($clients_ids)) + $clients_ids = [$clients_ids]; - $client_inst = new \Clients(); - foreach ($clients_ids as $client_id) { + $client_inst = new \Clients(); + foreach ($clients_ids as $client_id) { - $result = $client_inst->updateFunnel([ - 'id' => $client_id, - 'new_funnel_id' => $funnel_id, - ]); + $result = $client_inst->updateFunnel([ + 'id' => $client_id, + 'new_funnel_id' => $funnel_id, + ]); - if ($result !== true) - $errors[] = $result; + if ($result !== true) + $errors[] = $result; - } - } else if ($req_ids && $section == 'requisitions') { + } + } else if ($req_ids && $section == 'requisitions') { - if (!is_array($req_ids)) - $req_ids = [$req_ids]; + if (!is_array($req_ids)) + $req_ids = [$req_ids]; - // Открываем соединение с БД - $pdo = $app->container->get('mypdo'); - $req_inst = new \Requisitions($pdo); - foreach ($req_ids as $req_id) { + // Открываем соединение с БД + $pdo = $app->container->get('mypdo'); + $req_inst = new \Requisitions($pdo); + foreach ($req_ids as $req_id) { - $result = $req_inst->updateFunnel($funnel_id, $req_id); - if ($result !== true) - $errors[] = $result; + $result = $req_inst->updateFunnel($funnel_id, $req_id); + if ($result !== true) + $errors[] = $result; - } - } + } + } - if (!count($errors)) { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => true, - 'user_id' => (int)$user_id, - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } + if (!count($errors)) { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => true, + 'user_id' => (int)$user_id, + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => $_SESSION['id'], - 'errors' => $errors, - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => $_SESSION['id'], + 'errors' => $errors, + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); } public function setTags($app, $get = null, $post = null, $need_return = false) { - if (!empty($post)) { - $data = $post; - } else { - $body = $app->request->getBody(); - $data = json_decode(stripcslashes($body), true); - } + if (!empty($post)) { + $data = $post; + } else { + $body = $app->request->getBody(); + $data = json_decode(stripcslashes($body), true); + } if (($user_id = $_SESSION['id']) && isset($data['section']) && isset($data['source_id']) && isset($data['tags_list'])) { - // Открываем соединение с БД - $pdo = $app->container->get('pdo'); + // Открываем соединение с БД + $pdo = $app->container->get('pdo'); - $section = (string)$data['section']; - $source_id = (int)$data['source_id']; - $tags_list = (array)$data['tags_list']; + $section = (string)$data['section']; + $source_id = (int)$data['source_id']; + $tags_list = (array)$data['tags_list']; - $set = []; - $tags = []; - foreach ($tags_list as $tag) { - if (boolval($tag['isChecked'])) { - $tag_id = (isset($tag['value'])) ? (int)$tag['value'] : (int)$tag['id']; - $tags[] = $tag_id; - $set[] = "('$source_id', '$tag_id')"; - } - } + $set = []; + $tags = []; + foreach ($tags_list as $tag) { + if (boolval($tag['isChecked'])) { + $tag_id = (isset($tag['value'])) ? (int)$tag['value'] : (int)$tag['id']; + $tags[] = $tag_id; + $set[] = "('$source_id', '$tag_id')"; + } + } - list($sql, $sql2) = ['' , '']; - switch ($section) { - case 'objects' : - $sql = "DELETE FROM `objects_activities` WHERE `object_id` = '".$source_id."'"; - if (count($set) > 0) - $sql2 = "INSERT INTO `objects_activities` (`object_id`, `activity_id`) VALUES " . implode(', ', $set); + list($sql, $sql2) = ['' , '']; + switch ($section) { + case 'objects' : + $sql = "DELETE FROM `objects_activities` WHERE `object_id` = '".$source_id."'"; + if (count($set) > 0) + $sql2 = "INSERT INTO `objects_activities` (`object_id`, `activity_id`) VALUES " . implode(', ', $set); - break; - case 'clients' : - $sql = "DELETE FROM `clients_activities` WHERE `client_id` = '".$source_id."'"; - if (count($set) > 0) - $sql2 = "INSERT INTO `clients_activities` (`client_id`, `activity_id`) VALUES " . implode(', ', $set); + break; + case 'clients' : + $sql = "DELETE FROM `clients_activities` WHERE `client_id` = '".$source_id."'"; + if (count($set) > 0) + $sql2 = "INSERT INTO `clients_activities` (`client_id`, `activity_id`) VALUES " . implode(', ', $set); - break; - case 'requisitions' : - $sql = "DELETE FROM `requisitions_activities` WHERE `req_id` = '".$source_id."'"; - if (count($set) > 0) - $sql2 = "INSERT INTO `requisitions_activities` (`req_id`, `activity_id`) VALUES " . implode(', ', $set); + break; + case 'requisitions' : + $sql = "DELETE FROM `requisitions_activities` WHERE `req_id` = '".$source_id."'"; + if (count($set) > 0) + $sql2 = "INSERT INTO `requisitions_activities` (`req_id`, `activity_id`) VALUES " . implode(', ', $set); - break; + break; - } + } - $error = false; - if (!empty($sql)) { - if (!$pdo->query($sql)) - $error = true; - } - if (!empty($sql2)) { - if (!$pdo->query($sql2)) - $error = true; - } + $error = false; + if (!empty($sql)) { + if (!$pdo->query($sql)) + $error = true; + } + if (!empty($sql2)) { + if (!$pdo->query($sql2)) + $error = true; + } - if ($need_return) { - if (!empty($error)) - return false; - else - return $tags; - } else { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => !$error, - 'user_id' => (int)$user_id, - 'tags_ids' => $tags, - 'tags_list' => $tags_list - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } + if ($need_return) { + if (!empty($error)) + return false; + else + return $tags; + } else { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => !$error, + 'user_id' => (int)$user_id, + 'tags_ids' => $tags, + 'tags_list' => $tags_list + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } } - if ($need_return) { - return false; - } else { - $app->response->header('Content-Type', 'application/json'); - $app->response->setStatus(200); - $app->response->setBody(json_encode([ - 'success' => false, - 'user_id' => $_SESSION['id'] - ], JSON_UNESCAPED_UNICODE)); - $app->stop(); - } - } + if ($need_return) { + return false; + } else { + $app->response->header('Content-Type', 'application/json'); + $app->response->setStatus(200); + $app->response->setBody(json_encode([ + 'success' => false, + 'user_id' => $_SESSION['id'] + ], JSON_UNESCAPED_UNICODE)); + $app->stop(); + } + } - public function getPresentationLink($app, $get = null, $post = null) { + public function getPresentationLink($app, $get = null, $post = null) { - $error = false; - $errors = []; + $error = false; + $errors = []; - $body = $app->request->getBody(); - $data = json_decode($body, true); + $body = $app->request->getBody(); + $data = json_decode($body, true); if (($user_id = $_SESSION['id']) && (isset($data['object_id']) || isset($data['newbuilding_id']))) { - // Открываем соединение с БД - $mdb = $app->container->get('mysql'); + // Открываем соединение с БД + $mdb = $app->container->get('mysql'); - $object_id = null; - if (isset($data['object_id'])) - $object_id = (int)$data['object_id']; + $object_id = null; + if (isset($data['object_id'])) + $object_id = (int)$data['object_id']; - $newbuilding_id = null; - if (isset($data['newbuilding_id'])) - $newbuilding_id = (int)$data['newbuilding_id']; + $newbuilding_id = null; + if (isset($data['newbuilding_id'])) + $newbuilding_id = (int)$data['newbuilding_id']; - $client_id = null; - if (isset($data['client_id'])) - $client_id = (int)$data['client_id']; + $client_id = null; + if (isset($data['client_id'])) + $client_id = (int)$data['client_id']; - $hide_contacts = []; - if (isset($data['hide_contacts'])) - $hide_contacts = array_unique(array_map('intval', $data['hide_contacts'])); + $hide_contacts = []; + if (isset($data['hide_contacts'])) + $hide_contacts = array_unique(array_map('intval', $data['hide_contacts'])); - $send_type = null; - if (isset($data['with'])) - $send_type = (int)$data['with']; + $send_type = null; + if (isset($data['with'])) + $send_type = (int)$data['with']; - $new_prices = []; - $descriptions = []; - if (isset($data['descriptions'])) { - $array = (array)$data['descriptions']; - foreach ($array as $object_id => $value) { + $new_prices = []; + $descriptions = []; + if (isset($data['descriptions'])) { + $array = (array)$data['descriptions']; + foreach ($array as $object_id => $value) { - $object_id = str_replace('object_', '', $object_id); - if (isset($value['description'])) - $descriptions[intval($object_id)] = $value['description']; + $object_id = str_replace('object_', '', $object_id); + if (isset($value['description'])) + $descriptions[intval($object_id)] = $value['description']; - if (isset($value['price'])) - $new_prices[intval($object_id)] = $value['price']; + if (isset($value['price'])) + $new_prices[intval($object_id)] = $value['price']; - }; - } + }; + } - $link = null; - if (!is_null($object_id) || !is_null($newbuilding_id)) { + $link = null; + if (!is_null($object_id) || !is_null($newbuilding_id)) { - /*error_reporting(E_ERROR | E_WARNING | E_PARSE); + /*error_reporting(E_ERROR | E_WARNING | E_PARSE); ini_set('display_errors', 1);*/ - if (!is_null($object_id)) { + if (!is_null($object_id)) { - // Найденный листинг парсера (offset-free): строки в objects нет, образ собираем из external_listings - // по РЕАЛЬНОМУ el.id. Признак листинга — явный флаг is_external из запроса (id коллизит с objects.id). - require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/helpers/external_listing_legacy.php'; - $is_listing = self::_request_flag($data, 'is_external'); + // Найденный листинг парсера (offset-free): строки в objects нет, образ собираем из external_listings + // по РЕАЛЬНОМУ el.id. Признак листинга — явный флаг is_external из запроса (id коллизит с objects.id). + require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/helpers/external_listing_legacy.php'; + $is_listing = self::_request_flag($data, 'is_external'); - $obj = false; - $obj_found = false; - if ($is_listing) { - $obj = \external_listing_object_row($object_id, false); - if (is_null($obj)) { - // Листинг удалён по TTL — отвечаем ошибкой, как для ненайденного объекта. - $error = true; - $errors[] = 'Объявление снято с публикации'; - } else { - // Поля внешнего источника экранируем для прямой подстановки в SQL. - $obj['nazv'] = mysql_real_escape_string($obj['nazv']); - $obj['adres'] = mysql_real_escape_string($obj['adres']); - $obj_found = true; - } - } else { - $sql = "SELECT * FROM objects WHERE id=$object_id"; - if ($rez = mysql_query($sql)) { - $obj = mysql_fetch_assoc($rez); - $obj_found = true; - } - } + $obj = false; + $obj_found = false; + if ($is_listing) { + $obj = \external_listing_object_row($object_id, false); + if (is_null($obj)) { + // Листинг удалён по TTL — отвечаем ошибкой, как для ненайденного объекта. + $error = true; + $errors[] = 'Объявление снято с публикации'; + } else { + // Поля внешнего источника экранируем для прямой подстановки в SQL. + $obj['nazv'] = mysql_real_escape_string($obj['nazv']); + $obj['adres'] = mysql_real_escape_string($obj['adres']); + $obj_found = true; + } + } else { + $sql = "SELECT * FROM objects WHERE id=$object_id"; + if ($rez = mysql_query($sql)) { + $obj = mysql_fetch_assoc($rez); + $obj_found = true; + } + } - if ($obj_found) { + if ($obj_found) { - // Листинг адресуется явным маркером src=ext (bare id уже не различает листинг от своего объекта). - $src_marker = $is_listing ? '&src=ext' : ''; + // Листинг адресуется явным маркером src=ext (bare id уже не различает листинг от своего объекта). + $src_marker = $is_listing ? '&src=ext' : ''; - if ($send_type == 2) { + if ($send_type == 2) { - $pdfs = $this->_getPDF([$object_id], $descriptions, $new_prices, $hide_contacts, $is_listing ? [$object_id] : []); - if (isset($pdfs[$object_id]['link'])) - $linkUrl = $pdfs[$object_id]['link']; + $pdfs = $this->_getPDF([$object_id], $descriptions, $new_prices, $hide_contacts, $is_listing ? [$object_id] : []); + if (isset($pdfs[$object_id]['link'])) + $linkUrl = $pdfs[$object_id]['link']; - } else { + } else { - if (self::is_ssl()) - $linkUrl = "https://joywork.ru/object-view.php?id=$object_id&token=" . md5($user_id) . $src_marker; - else - $linkUrl = "http://joywork.ru/object-view.php?id=$object_id&token=" . md5($user_id) . $src_marker; + if (self::is_ssl()) + $linkUrl = "https://joywork.ru/object-view.php?id=$object_id&token=" . md5($user_id) . $src_marker; + else + $linkUrl = "http://joywork.ru/object-view.php?id=$object_id&token=" . md5($user_id) . $src_marker; - } + } - $new_price = 0; - if (isset($new_prices[$object_id])) - $new_price = $new_prices[$object_id]; + $new_price = 0; + if (isset($new_prices[$object_id])) + $new_price = $new_prices[$object_id]; - if (!is_null($client_id)) - $linkUrl .= "&client=" . md5($client_id); - else - $client_id = "0"; + if (!is_null($client_id)) + $linkUrl .= "&client=" . md5($client_id); + else + $client_id = "0"; - $close_contact = 0; - if (in_array($object_id, $hide_contacts)) - $close_contact = 1; + $close_contact = 0; + if (in_array($object_id, $hide_contacts)) + $close_contact = 1; - // Для найденного листинга флаг скрытия контакта не пишем — его контакт скрыт всегда. - if (!$is_listing) { - $sql_up = "INSERT INTO user_object_contact_close SET close={$close_contact}, user_id={$user_id}, object_id = {$object_id}, client_id = {$client_id}"; - if (!mysql_query($sql_up)) { - $error = true; - $errors[] = mysql_error(); - } - } + // Для найденного листинга флаг скрытия контакта не пишем — его контакт скрыт всегда. + if (!$is_listing) { + $sql_up = "INSERT INTO user_object_contact_close SET close={$close_contact}, user_id={$user_id}, object_id = {$object_id}, client_id = {$client_id}"; + if (!mysql_query($sql_up)) { + $error = true; + $errors[] = mysql_error(); + } + } - $token = md5(microtime()); + $token = md5(microtime()); - // Per-send описание, переданное mJW в POST-параметре `descriptions`. - $descriptionForInsert = "NULL"; - if (isset($descriptions[intval($object_id)]) && $descriptions[intval($object_id)] !== '') { - $cleanedDesc = cleanHtml($descriptions[intval($object_id)], '