Joywork/api/v2/app/src/controllers/ClientsController.php
2026-06-28 10:56:29 +03:00

3855 lines
146 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\v2\Controller;
class ClientsController extends ApiController
{
public function getClients($app, $get = null, $post = null, $need_return = false) {
$start_time = microtime(true);
$error = false;
$errors = [];
$count_sql = "";
$main_sql = "";
if ($user_id = intval($_SESSION['id'])) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
//$pdo = $app->container->get('pdo');
$user = new \User();
$user->get($user_id);
$user->checkPermissions($user_id, false);
$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 '%&quot;{$user_id}&quot;: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;
$filters = [];
if (isset($get['filters']))
$filters = json_decode($get['filters'], true);
$users = [(int)$user_id];
$managers = [(int)$agency_id];
$activities = null;
$clients_activities = [];;
$bd_usl = " AND `clients`.`cancel` = 0";
$bd_user_j = "";
$clients_ids = [];
$req_ids = [];
$contracts = [];
$depClass = new \Department();
$dep_user = $depClass->getDepartment($user_id);
// Выборка с учётом агентства
if (count($filters)) {
// Ответственный
if (!empty($filters['employees'])) {
if (is_array($filters['employees'])) {
$where = [];
foreach($filters['employees'] as $employee) {
if (strpos($employee, "all_") !== false) {
$employee_id = str_replace('all_', '', $employee);
if (($filters['filter_stage'] && in_array('work_add', $filters['filter_stage'])) && !isset($filters['step']) && !isset($filters['sources'])) {
$where[] = " `clients`.`id_agent` IN (SELECT `id` FROM `users` WHERE `id`=$employee_id OR `id_manager`=$employee_id OR `id_manager` IN (SELECT `id` FROM `users` WHERE `id_manager`=$employee_id))";
} else {
$temp = " (`clients`.`who_work` IN (SELECT `id` FROM `users` WHERE `id`=$employee_id OR `id_manager`=$employee_id OR `id_manager` IN (SELECT `id` FROM `users` WHERE `id_manager`=$employee_id))";
if ($filters['employee'])
$temp .= " OR (`clients`.`doers` LIKE '%&quot;".$filters['employee']."&quot;%')";
$where[] = $temp .= ")";
}
} else {
if (($filters['filter_stage'] && in_array('work_add', $filters['filter_stage'])) && !isset($filters['step']) && !isset($filters['sources'])) {
$where[] = "`clients`.`id_agent` = '$employee'";
} else {
$where[] = "`clients`.`who_work` = '$employee'";
}
}
}
if (!empty($where))
$bd_usl .= " AND (" . implode(" OR ", $where) . ")";
} else {
$bd_usl .= " AND `clients`.`who_work` = '{$filters['employees']}'";
}
} else {
//$bd_user_j = " AND `clients`.`who_work` IN (". implode(',', array_merge($users, $managers)) .") ";
/*$bd_user_j = " `clients`.`who_work` IN (
SELECT id FROM `users` WHERE id=$agency_id OR id_manager=$agency_id OR id_manager IN (
SELECT id FROM users WHERE id_manager=$agency_id
)
)";*/
$searchUserId = $user_id;
if ($_SESSION['users_admin'] || $menuPermissions['menu_all_clients'] == 1) {
$currentUser = new \User;
$currentUser->checkPermissions($user_id, false);
$users[] = $agency_id;
} else if ($dep_user['role'] == 'manager_office') {
$currentUser = new \User;
$currentUser->checkPermissions($user_id, false);
$users[] = $currentUser->id_manager;
$searchUserId = $currentUser->id_manager;
} else if ($dep_user['role'] == 'manager_office_menager') {
$currentUser = new \User;
$currentUser->get($user_id);
$users[] = $currentUser->id_manager;
$searchUserId = $currentUser->id_manager;
}
//$bd_user_j = " `clients`.`who_work` IN (". implode(',', $users) .") ";
/*$bd_user_j = " `clients`.`who_work` IN (
SELECT id FROM `users` WHERE id = $user_id OR id_manager = $user_id OR id_manager IN (
SELECT id FROM `users` WHERE id_manager IN (". implode(',', $users) .")
)
) AND `clients`.`doers` LIKE '%&quot;".$user_id."&quot;%'";*/
if ($filters['status'] !== 'common_clients') {
if ($menuPermissions['menu_all_clients'] == 1 ) {
$userIds = array();
$query = mysql_query("SELECT id FROM `users` WHERE id = $agency_id OR id_manager = $agency_id OR id_manager IN (
SELECT id FROM `users` WHERE id_manager IN (". implode(',', $users) .")
)");
while($us = mysql_fetch_assoc($query)) {
$userIds[] = $us['id'];
}
$bd_user_j = " (`clients`.`who_work` IN (" . implode(", ", $userIds) . ") OR (`clients`.`doers` is not null AND `clients`.`doers` LIKE '%&quot;".$agency_id."&quot;:1%'))";
}
else if ($dep_user['role'] == 'manager_office') {
$userIds = array();
$query = mysql_query("SELECT id FROM `users` WHERE id = $searchUserId OR id_manager = $searchUserId OR id_manager IN (
SELECT id FROM `users` WHERE id_manager IN (". implode(',', $users) .")
)");
while($us = mysql_fetch_assoc($query)) {
$userIds[] = $us['id'];
}
$bd_user_j = " (`clients`.`who_work` IN (" . implode(", ", $userIds) . ") OR (`clients`.`doers` is not null AND `clients`.`doers` LIKE '%&quot;".$searchUserId."&quot;:1%'))";
}
else if ($dep_user['role'] == 'manager_office_menager') {
$userIds = array();
$query = mysql_query("SELECT id FROM `users` WHERE id = $searchUserId OR id_manager = $searchUserId OR id_manager IN (
SELECT id FROM `users` WHERE id_manager IN (". implode(',', $users) .")
)");
while($us = mysql_fetch_assoc($query)) {
$userIds[] = $us['id'];
}
$bd_user_j = " (`clients`.`who_work` IN (" . implode(", ", $userIds) . ") OR (`clients`.`doers` is not null AND `clients`.`doers` LIKE '%&quot;".$searchUserId."&quot;:1%'))";
}
else {
$userIds = array();
$query = mysql_query("SELECT id FROM `users` WHERE id = $user_id OR id_manager = $user_id OR id_manager IN (
SELECT id FROM `users` WHERE id_manager IN (". implode(',', $users) .")
)");
while($us = mysql_fetch_assoc($query)) {
$userIds[] = $us['id'];
}
$bd_user_j = " (`clients`.`who_work` IN (" . implode(", ", $userIds) . ") OR (`clients`.`doers` is not null AND `clients`.`doers` LIKE '%&quot;".$user_id."&quot;:1%'))";
}
}
}
// Воронка продаж
$funnel_id = 0;
if (!empty($filters['funnel_id'])) {
if (is_array($filters['funnel_id'])) {
$bd_usl .= " AND `clients`.`funnel_id` IN (" . implode(',', $filters['funnel_id']) . ")";
} else {
$bd_usl .= " AND `clients`.`funnel_id` = '{$filters['funnel_id']}'";
}
$funnel_id = $filters['funnel_id'];
} else {
$bd_usl .= " AND `clients`.`funnel_id` = 0";
}
// Статус
if (!empty($filters['status'])) {
if (!is_array($filters['status']))
$filters['status'] = [$filters['status']];
foreach ($filters['status'] as $status) {
switch ($status) {
case 'stage_work':
if (in_array('confirmed_clients', $filters['status']) || in_array('stage_send', $filters['status'])) {
$bd_usl .= " AND `clients`.`deleted` <> '1'";
} else {
$bd_usl .= " AND `clients`.`deleted` <> '1' AND `clients`.`confirm` > 0";
}
break;
case 'stage_hot':
if (in_array('stage_work', $filters['status'])) {
$bd_usl .= " OR `clients`.`hot` = 1";
} else {
$bd_usl .= " AND `clients`.`hot` = 1";
}
break;
case 'stage_close':
$bd_usl .= " AND `clients`.`deleted` = '1' AND `clients`.`confirm` <> '10'";
break;
case 'stage_hit':
$bd_usl .= " AND `clients`.`deleted` = '1' AND `clients`.`confirm` = 10";
break;
case 'stage_send':
$bd_usl .= " AND `clients`.`deleted` <> '1' AND `clients`.`confirm` = 0 AND `clients`.`who_work` != '$user_id'";
break;
case 'confirmed_clients':
$bd_usl .= " AND (`clients`.`who_work` = '$user_id' OR `clients`.`id_agent` = '$user_id') AND `clients`.`confirm` = 0 OR (`clients`.`doers_confirm` = 0 AND `clients`.`doers` LIKE '%&quot;$user_id&quot;:0%' AND `funnel_id`='$funnel_id')";
break;
case 'common_clients':
$bd_usl .= " AND `clients`.`who_work`=0 AND `clients`.`id_agent` IN
(SELECT `id` FROM `users` WHERE `id`='$agency_id' OR `id_manager`='$agency_id' OR `id_manager` IN (SELECT `id` FROM `users` WHERE `id_manager`='$agency_id') OR `id_manager` IN (SELECT `id` FROM `users` WHERE `id_manager` IN (SELECT `id` FROM `users` WHERE `id_manager`='$agency_id')))";
break;
default:
$bd_usl .= " AND `clients`.`deleted` <> '1'";
}
}
}
// Тип
if (!empty($filters['type'])) {
global $OBJECT_TYPES;
if (is_array($filters['type'])) {
$where = [];
foreach ($filters['type'] as $type) {
$type = $OBJECT_TYPES[(int)$type];
$where[] = "`clients`.`work_type` LIKE '%&quot;{$type}&quot;%'";
}
$bd_usl .= " AND (" . implode(" OR ", $where) . ")";
} else {
$type = $OBJECT_TYPES[(int)$filters['type']];
$bd_usl .= " AND `clients`.`work_type` = '{$type}'";
}
}
// Теги
if (!empty($filters['activities'])) {
if (is_array($filters['activities'])) {
$bd_usl .= " AND `id` IN (
SELECT `client_id` FROM `clients_activities`
WHERE `activity_id` IN (" . implode(", ", $filters['activities']) . ")
)";
} else {
$bd_usl .= " AND `id` IN (
SELECT `client_id` FROM `clients_activities`
WHERE `activity_id` = {$filters['activities']}
)";
}
}
// Тип недвижимости
if (!empty($filters['estate'])) {
global $TYPE_NEDV2_SORT;
if (is_array($filters['estate'])) {
$index = 1;
$estate_types = [];
foreach($TYPE_NEDV2_SORT as $key => $val) {
if (!empty($key)) {
$estate_types[$index] = $key;
}
$index++;
}
$where = [];
foreach ($filters['estate'] as $type_id) {
if (isset($estate_types[$type_id])) {
$type = $estate_types[$type_id];
$where[] = "`clients`.`type` LIKE '%&quot;{$type}&quot;%'";
}
}
if (!empty($where))
$bd_usl .= " AND (" . implode(" OR ", $where) . ")";
} else {
$index = 1;
$estate_types = [];
foreach($TYPE_NEDV2_SORT as $key => $val) {
if (!empty($key)) {
$estate_types[$index] = $key;
}
$index++;
}
$where = [];
$type_id = $filters['estate'];
if (isset($estate_types[$type_id])) {
$type = $estate_types[$type_id];
$where[] = "`clients`.`type` LIKE '%&quot;{$type}&quot;%'";
}
if (!empty($where))
$bd_usl .= " AND (" . implode(" OR ", $where) . ")";
}
}
// Роль клиента
if (!empty($filters['roles'])) {
global $ROLES_CLIENTS;
if (is_array($filters['roles'])) {
$roles = [];
foreach($filters['roles'] as $role) {
$role = $ROLES_CLIENTS[(int)$role];
$roles[] = "`clients`.`role` LIKE '%&quot;{$role}&quot;%'";
}
$bd_usl .= " AND (".implode(" OR ", $roles).")";
} else {
$role = $ROLES_CLIENTS[(int)$filters['roles']];
$bd_usl .= " AND `clients`.`role` = {$filters['roles']}";
}
}
// Источник
if (!empty($filters['sources'])) {
$where = [];
if (is_array($filters['sources'])) {
foreach($filters['sources'] as $source) {
if ($source == -1) {
$where[] = "`clients`.`source` is null";
$where[] = "`clients`.`source` = ''";
$where[] = "`clients`.`source` = 'null'";
$where[] = "`clients`.`source` = '0'";
} else {
$where[] = "`clients`.`source` = '{$source}'";
}
}
$bd_usl .= " AND (".implode(" OR ", $where).")";
} else {
$bd_usl .= " AND `clients`.`source` = '{$filters['sources']}'";
}
}
// Партнёр
if (!empty($filters['partners'])) {
if (is_array($filters['partners'])) {
$employees_ids = [];
$partners_inst = new \Partners();
foreach($filters['partners'] as $employee) {
if (preg_match('/all_(\d+)/', $employee, $matches)) {
if ($id = intval($matches[1])) {
$employees = $partners_inst->getEmployeesId($id, false);
foreach($employees as $employee) {
$employees_ids[] = "`clients`.`employee_id` = '{$employee}'";
}
}
} else {
if ($employee == 0) {
$employees_ids[] = "`clients`.`employee_id` IS NULL";
$employees_ids[] = "`clients`.`employee_id` = ''";
$employees_ids[] = "`clients`.`employee_id` = 'NULL'";
} else {
$employees_ids[] = "`clients`.`employee_id` = '{$employee}'";
}
}
}
$bd_usl .= " AND (" . implode(" OR ", $employees_ids) . ")";
} else {
$bd_usl .= " AND `clients`.`employee_id` = '{$filters['partners']}'";
}
}
// Этап
if (!empty($filters['stages'])) {
if ($funnel_id == 0) {
if (is_array($filters['stages'])) {
$bd_usl .= " AND `stage` IN (".implode(',', $filters['stages']).") AND deleted <> '1'";
} else {
$bd_usl .= " AND `stage` = '{$filters['stages']}' AND deleted <> '1'";
}
} else {
$stage_where = [];
$stages = $filters['stages'];
if (is_array($filters['stages']))
$stages = [$filters['stages']];
foreach ($stages as $stage) {
$query = mysql_query("SELECT * FROM `funnel_steps` WHERE `deleted`=0 AND `id` = ". $stage);
$step = mysql_fetch_assoc($query);
if ($step['branch'] == 1) {
$stage_where[] = " NOT EXISTS (SELECT `st`.`id` FROM `clients_funnel_step` `st` WHERE `st`.`client_id` = `clients`.`id`) ";
} else {
if ($step['stage'] == 'Закрыт')
$stage_where[] = " `id` IN (SELECT `client_id` FROM `clients_funnel_step` WHERE `step_id` = '$stage') ";
$query = mysql_query("SELECT * FROM `funnel_steps` WHERE `next_step` LIKE '%&quot;$step[id]&quot;%'");
while($prev_step = mysql_fetch_assoc($query)) {
if ($prev_step['next_step_change'] == 'Всегда один') {
$stage_where[] = " `id` IN (SELECT `client_id` FROM `clients_funnel_step` WHERE `step_id` = '$prev_step[id]') ";
} else {
$stage_where[] = " `id` IN (SELECT `client_id` FROM `clients_funnel_step` WHERE `next_id` = '$stage') ";
}
}
}
}
if (count($stage_where > 0))
$bd_usl .= " AND ( " . implode(" OR ", $stage_where) . ")";
}
}
// Шаг
if (!empty($filters['step'])) {
$bd_usl .= " AND `clients`.`step_id` = ".$post['step'];
}
// Есть объекты
if (!empty($filters['have_objects'])) {
$bd_usl .= " AND `clients`.`of_objects` > 0";
}
// Причина закрытия
if (!empty($filters['denials'])) {
if (is_array($filters['denials'])) {
$bd_usl .= " AND `denial` IN (".implode(',', $filters['denials']).")";
} else {
$bd_usl .= " AND `denial` = '{$filters['denials']}'";
}
}
// Категория клиента
if (!empty($filters['priority'])) {
if (is_array($filters['priority'])) {
$bd_usl .= " AND `clients`.`priority` IN (".implode(',', $filters['priority']).")";
} else {
$bd_usl .= " AND `clients`.`priority` = '{$filters['priority']}'";
}
}
// Договора
if (!empty($filters['is_contract'])) {
$part_where = " AND (SELECT count(`id`) FROM `contracts_client` AS `contracts` WHERE `client_id`=`clients`.`id`";
if (isset($filters['contract_number']) && !empty($filters['contract_number']))
$part_where .= " AND `contracts`.`number` LIKE '%{$filters['contract_number']}%'";
if (isset($filters['contract_type']) && !empty($filters['contract_type']))
$part_where .= " AND `contracts`.`type` IN (".implode(',', $filters['contract_type']).")";
if (isset($filters['contract_start']) && !empty($filters['contract_start'])) {
$date_start = strtotime($filters['contract_start']);
$part_where .= " AND `contracts`.`date_end` >= '$date_start'";
}
if (isset($filters['contract_end']) && !empty($filters['contract_end'])) {
$date_end = strtotime($filters['contract_end']);
$part_where .= " AND `contracts`.`date_end` <= '$date_end'";
}
$part_where .= ") > 0";
$bd_usl .= $part_where;
}
// Массив для сбора условий по задачам
$taskConditions = [];
// "С задачами"
if (!empty($filters['is_tasks'])) {
$taskConditions[] = "(SELECT count(id) FROM user_client_events
WHERE calendar_view = 0
AND schedule_date IS NOT NULL
AND cancel = 0
AND client_id = clients.id
AND schedule_date > '2001-03-10 17:16:18') > 0";
}
// "Без задач"
if (!empty($filters['is_no_tasks'])) {
$taskConditions[] = "(SELECT count(id) FROM user_client_events
WHERE calendar_view = 0
AND schedule_date IS NOT NULL
AND cancel = 0
AND client_id = clients.id) = 0";
}
// "Задачи на сегодня"
if (!empty($filters['is_today_tasks'])) {
$taskConditions[] = "(SELECT count(id) FROM user_client_events
WHERE calendar_view = 0
AND schedule_date IS NOT NULL
AND client_id = clients.id
AND cancel = 0
AND DATE(schedule_date) = CURDATE()) > 0";
}
// "Просроченные задачи"
if (!empty($filters['is_over_tasks'])) {
$taskConditions[] = "(SELECT count(id) FROM user_client_events
WHERE calendar_view = 0
AND schedule_date IS NOT NULL
AND client_id = clients.id
AND cancel = 0
AND schedule_date <= '".date("Y-m-d H:i:s")."') > 0";
}
// Формируем SQL
if (!empty($taskConditions)) {
// Если выбраны и "с задачами" и "без задач" - не добавляем условий по задачам
if (!empty($filters['is_tasks']) && !empty($filters['is_no_tasks'])) {
} else {
// Объединяем условия через OR
$bd_usl .= " AND (" . implode(" OR ", $taskConditions) . ")";
}
}
// Совместные клиенты
if (!empty($filters['is_partner'])) {
$bd_usl .= " AND `clients`.`doer_clients` = 1";
}
// Время добавления (период)
if (!empty($filters['period'])) {
switch ($filters['period']) {
case 1:
$filters['period'] = 'today';
break;
case 2:
$filters['period'] = 'week';
break;
case 3:
$filters['period'] = 'month';
break;
case 4:
$filters['period'] = '30days';
break;
case 5:
$filters['period'] = 'quarter';
break;
case 6:
$filters['period'] = '90days';
break;
case 7:
$filters['period'] = 'year';
break;
case 8:
$filters['period'] = 'all';
break;
case 9:
$filters['period'] = 'period';
break;
}
if ($filters['transmitted'] || $filters['accepted']) {
$dates = getPeriod($filters['period'], $filters['period_start'], $filters['period_end']);
$date_between = $dates['between'];
// $bd_usl .= " AND `clients`.`date_add` $date_between";
} else if ($filters['step'] || $filters['sources']) {
$dates = getPeriod($filters['period'], $filters['period_start'], $filters['period_end']);
$date_between = $dates['between'];
$bd_usl .= " AND `clients`.`date_add` $date_between";
} else if (isset($filters['status']['stage_close']) || isset($filters['status']['stage_hit'])) {
$dates = getPeriod($filters['period'], $filters['period_start'], $filters['period_end']);
$date_between = $dates['between'];
$bd_usl .= " AND (IF((SELECT count(*) FROM `events_clients` WHERE `client_id`=`clients`.`id` AND `event`='delete' AND `user_id`=`clients`.`who_delete` ORDER BY `id` DESC LIMIT 1) > 0, "
. "(SELECT `date_update` FROM `events_clients` WHERE `client_id`=`clients`.`id` AND `event`='delete' AND `user_id`=`clients`.`who_delete` ORDER BY `id` DESC LIMIT 1) $date_between, "
. "`clients`.`date_add` $date_between))";
} else {
if ($filters['period'] == 'period') {
$period_start = date('Y-m-d 00:00:00', strtotime($filters['period_start']));
if (empty($period_start))
$period_start = '1970-01-01 00:00:00';
if (!empty($filters['period_end']))
$period_end = date('Y-m-d 23:59:59', strtotime($filters['period_end']));
else
$period_end = date('Y-m-d 23:59:59');
if ($filters['filter_stage'] && in_array('filter_work_all_do', $filters['filter_stage']))
$bd_usl .= " AND `clients`.`date_add` < '{$period_start}'";
else
$bd_usl .= " AND (`clients`.`date_add` BETWEEN '{$period_start}' AND '{$period_end}')";
} else {
$dates = getPeriod($filters['period'], $filters['period_start'], $filters['period_end']);
$date_between = $dates['between'];
$date_start = $dates['dateStart'];
if ($filters['filter_stage'] && in_array('filter_work_all_do', $filters['filter_stage']))
$bd_usl .= " AND `clients`.`date_add` < {$date_start}";
else
$bd_usl .= " AND `clients`.`date_add` {$date_between}";
}
}
}
// Закрытые клиенты
if (!empty($filters['is_deleted']))
$bd_usl .= " AND `clients`.`confirm` > 0 AND `clients`.`deleted` = 1 ";
if (empty($filters['status'])) {
$agency_id = (int)$_SESSION['agency_id'];
$n_agents = "SELECT id FROM users
WHERE id IN (
SELECT id FROM users
WHERE id = $agency_id
OR id_manager = $agency_id
OR id_manager IN (
SELECT id FROM users
WHERE id_manager = $agency_id
OR id_manager IN (
SELECT id FROM users
WHERE id_manager = $agency_id
)
)
)
UNION
SELECT user_id FROM users_delete
WHERE agency_id = $agency_id
";
$n_agents_res = mysql_query($n_agents);
$n_agent_ids = [];
while ($row = mysql_fetch_assoc($n_agents_res)) {
$n_agent_ids[] = $row['id'];
}
$n_agent_ids_str = '(' . implode(',', $n_agent_ids) . ')';
$n_agent_ids_z = '(' . implode(',', array_merge([0], $n_agent_ids)) . ')';
$bd_user_j = "`clients`.`who_work` IN $n_agent_ids_z AND `clients`.`id_agent` IN $n_agent_ids_str";
}
} else {
$agency_id = (int)$_SESSION['agency_id'];
$n_agents = "SELECT id FROM users
WHERE id IN (
SELECT id FROM users
WHERE id = $agency_id
OR id_manager = $agency_id
OR id_manager IN (
SELECT id FROM users
WHERE id_manager = $agency_id
OR id_manager IN (
SELECT id FROM users
WHERE id_manager = $agency_id
)
)
)
UNION
SELECT user_id FROM users_delete
WHERE agency_id = $agency_id
";
$n_agents_res = mysql_query($n_agents);
$n_agent_ids = [];
while ($row = mysql_fetch_assoc($n_agents_res)) {
$n_agent_ids[] = $row['id'];
}
$n_agent_ids_str = '(' . implode(',', $n_agent_ids) . ')';
$n_agent_ids_z = '(' . implode(',', array_merge([0], $n_agent_ids)) . ')';
$bd_user_j = "`clients`.`who_work` IN $n_agent_ids_z AND `clients`.`id_agent` IN $n_agent_ids_str";
if (isset($get['clients_ids'])) { // особая разрешающая выборка внутри АН, если указан перечень ИД клиентов
$bd_user_j = " `clients`.`who_work` IN (
SELECT id FROM `users` WHERE id=$agency_id OR id_manager=$agency_id OR id_manager IN (
SELECT id FROM users WHERE id_manager=$agency_id
)
)";
}
}
// Фильтрация по ИД клиента(ов)
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 .= " AND `clients`.`id` IN (" . implode(',', $clients_ids) . ") ";
}
// Поисковый запрос
$query = trim($get['query']);
if (!empty($query)) {
$phone = preg_replace('/[+\-\(\)\/\?,.;:%№!\s]/', '', $get['query']);
$bd_usl .= " AND (`id`='".intval($query)."' OR `fio` LIKE '%$query%' OR `phone` LIKE '%$phone%' OR `phone2` LIKE '%$phone%' OR `email` LIKE '%$query%')";
}
// Сортировка результатов
if ($funnel_id == 0) {
$sort_order = " ORDER BY IF(
(SELECT `date_update` FROM `events_clients` WHERE `client_id` = `clients`.`id` AND (`event` = 'accepted' OR `event` = 'accepted_doer' OR `event` = 'restored') ORDER BY `id` DESC LIMIT 1) > `clients`.`date_add`,
(SELECT `date_update` FROM `events_clients` WHERE `client_id` = `clients`.`id` AND (`event` = 'accepted' OR `event` = 'accepted_doer' OR `event` = 'restored') ORDER BY `id` DESC LIMIT 1),
`clients`.`date_add`
) DESC";
} else {
$sort_order = " ORDER BY IF(
(SELECT `date_update` FROM `events_clients` WHERE `client_id` = `clients`.`id` AND (`event` = 'accepted' OR `event` = 'accepted_doer' OR `event` = 'restored') ORDER BY `id` DESC LIMIT 1) > `clients`.`date_add`,
(SELECT `date_update` FROM `events_clients` WHERE `client_id` = `clients`.`id` AND (`event` = 'accepted' OR `event` = 'accepted_doer' OR `event` = 'restored') ORDER BY `id` DESC LIMIT 1),
`clients`.`date_add`
) DESC";
}
if (!empty($get['sort_order'])) {
if ($get['sort_order'] == 'asc')
$sort_order = " ORDER BY `clients`.`id` ASC";
else if ($get['sort_order'] == 'desc')
$sort_order = " ORDER BY `clients`.`id` DESC";
}
// Постраничная навигация
$per_page = 5;
if (isset($get['per_page']))
$per_page = intval($get['per_page']);
$page = 1;
if (isset($get['page']))
$page = intval($get['page']);
$offset = $per_page * ($page - 1);
$limit = "LIMIT {$offset}, {$per_page}";
if (!empty($bd_usl))
$bd_usl = 'true ' . $bd_usl;
if (!empty($bd_usl) && !empty($bd_user_j))
$bd_usl = ' AND ' . $bd_usl;
if (empty($bd_user_j) && empty($bd_usl)) {
$bd_usl = "`clients`.`who_work` IN (
SELECT `id` FROM `users` WHERE `id`=$agency_id OR `id_manager`=$agency_id OR `id_manager` IN (
SELECT `id` FROM `users` WHERE `id_manager`=$agency_id
)
) OR `clients`.`id_agent` IN (
SELECT `id` FROM `users` WHERE `id`=$agency_id OR `id_manager`=$agency_id OR `id_manager` IN (
SELECT `id` FROM `users` WHERE `id_manager`=$agency_id
)
)";
}
if (!empty($bd_managers))
$sql = "SELECT count(*) AS total FROM `clients`
WHERE $bd_user_j $bd_usl AND `who_work` $bd_managers";
else
$sql = "SELECT count(*) AS total FROM `clients`
WHERE $bd_user_j $bd_usl";
$count_sql = $sql;
$total = 0;
if ($query = mysql_query($sql)) {
$results = mysql_result($query, 0);
$total = (int)$results;
} else {
$error = true;
$errors[] = mysql_error();
}
if ($total) {
$sql = "SELECT *,
DATE_FORMAT(`date_add`, '%d.%m.%Y') AS `date_add`,
`date_add` as `date_create`
FROM `clients`
WHERE $bd_user_j $bd_usl $sort_order $limit";
$main_sql = $sql;
if ($rez = mysql_query($sql)) {
$objects_inst = new ObjectsController();
$clients_ids = [];
$clients_list = [];
$users_ids = [];
$users = [];
$departments = [];
$sources_id = [];
$sources = [];
$doers_ids = [];
$doers = [];
// Собираем предварительные данные
while($row = mysql_fetch_assoc($rez)) {
$client_id = (int)$row['id'];
$clients_ids[] = $client_id;
$clients_list[$client_id] = $row;
if ($row["id_agent"])
$users_ids[] = $row["id_agent"];
if ($row["who_delete"])
$users_ids[] = $row["who_delete"];
if ($row["who_work"])
$users_ids[] = $row["who_work"];
if ($row["source"])
$sources_id[] = $row["source"];
if ($row["doers"]) {
$doers_list = json_decode(html_entity_decode($row['doers'], ENT_QUOTES), true);
if (count($doers_list))
$users_ids = array_merge($users_ids, array_keys($doers_list));
}
}
// Выделяем только уникальные
$users_ids = array_unique($users_ids);
$sources_id = array_unique($sources_id);
$clients_ids = array_unique($clients_ids);
// Заявки
if (!empty($clients_ids)) {
$sql = "SELECT `id`, `client_id` FROM `requisitions`
WHERE `confirm` <> 0 AND
`deleted` <> 1 AND
`client_id` IN (" . implode(',', $clients_ids) . ") ";
if ($query = mysql_query($sql)) {
while($row = mysql_fetch_assoc($query)) {
$client_id = (int)$row['client_id'];
$req_ids[$client_id][] = (int)$row['id'];
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
// Договоры
if (!empty($clients_ids)) {
$contracts_inst = new \Contract();
foreach ($clients_ids as $client_id) {
$contracts[$client_id] = $contracts_inst->getContracts($client_id, 'client');
foreach ($contracts[$client_id] as $key => $contract) {
if (isset($contract['date_start']))
$contracts[$client_id][$key]['date_start'] = date('Y-m-d H:i:s', strtotime($contract['date_start']));
if (isset($contract['date_end']))
$contracts[$client_id][$key]['date_end'] = date('Y-m-d H:i:s', strtotime($contract['date_end']));
}
}
}
// Формируем списки тегов под клиентов
if (count($clients_ids) > 0) {
$sql = "SELECT `activity_id`, `client_id`
FROM `clients_activities`
WHERE `client_id` IN (" . implode(", ", $clients_ids) . ")";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_assoc($query)) {
$clients_activities[$row['client_id']][] = $row['activity_id'];
}
}
}
}
// Формируем списки пользователей
if (count($users_ids) > 0) {
$sql = "SELECT id, agency, manager, agency_name, first_name, last_name, middle_name, role_id
FROM users WHERE id IN (" . implode(", ", $users_ids) . ")";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
while ($user = mysql_fetch_assoc($query)) {
$users[$user['id']] = $user;
}
}
}
}
// Формируем списки источников
if (count($sources_id) > 0) {
$sql = "SELECT *
FROM `advertising_sources`
WHERE `id` IN (" . implode(", ", $sources_id) . ")";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
while ($source = mysql_fetch_assoc($query)) {
$sources[$source['id']] = $source;
}
}
}
}
// Формируем списки отделов
$sql = "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 = '$agency_id'";
if ($query = mysql_query($sql)) {
while ($row = mysql_fetch_assoc($query)) {
$departments[$row['id']] = $row;
}
}
// Формируем список тегов
$commonController = new CommonController;
$activities = $commonController->getTags($app, ['with_managers' => true], $post, true);
// Подсчет событий по клиентам
$events_less = [];
$events_eq = [];
$events_more = [];
$sql = "SELECT count(`id`) AS `res`, `client_id`
FROM `user_client_events`
WHERE `calendar_view` = 0 AND
`cancel`=0 AND
`type` IN ('call', 'meet', 'show', 'deal', 'even') AND
`schedule_date` IS NOT NULL AND
`client_id` IN (" . implode(", ", $clients_ids) . ") AND
`schedule_date` < '" . date("Y-m-d H:i:s") . "'
GROUP BY `client_id`";
if ($query = mysql_query($sql)) {
if(mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_assoc($query)) {
$events_less[] = $row;
}
}
}
$sql = "SELECT count(id) as res, client_id
FROM user_client_events
WHERE calendar_view = 0 AND
cancel=0 AND
`type` IN ('call', 'meet', 'show', 'deal', 'even') AND
schedule_date IS NOT NULL AND
client_id IN (" . implode(", ", $clients_ids) . ") AND
DATE_FORMAT(schedule_date, '%Y-%m-%d') = '" . date("Y-m-d") . "' AND
schedule_date > '" . date("Y-m-d H:i:s") . "'
GROUP BY client_id";
if ($query = mysql_query($sql)) {
if(mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_assoc($query)) {
$events_eq[] = $row;
}
}
}
$sql = "SELECT count(id) as res, client_id
FROM user_client_events
WHERE calendar_view = 0 AND
cancel=0 AND
`type` IN ('call', 'meet', 'show', 'deal', 'even') AND
schedule_date IS NOT NULL AND
client_id IN (" . implode(", ", $clients_ids) . ") AND
DATE_FORMAT(schedule_date, '%Y-%m-%d') > '" . date("Y-m-d") . "'
GROUP BY client_id";
if ($query = mysql_query($sql)) {
if(mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_assoc($query)) {
$events_more[] = $row;
}
}
}
// Подсчет событий по заявкам
$events_req = [];
if (count($req_ids)) {
$where_req_ids = [];
foreach ($req_ids as $client_id => $ids) {
$where_req_ids = array_merge($where_req_ids, $ids);
}
if (count($where_req_ids)) {
$sql = "SELECT count(`id`) AS `res`, `req_id`
FROM `user_client_events`
WHERE `calendar_view` = 0 AND
`cancel` = 0 AND
`schedule_date` IS NOT NULL AND
`req_id` IN (" . implode(", ", $where_req_ids) . ") AND
`schedule_date` < '" . date("Y-m-d H:i:s") . "'
GROUP BY `req_id`";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query)) {
while ($row = mysql_fetch_assoc($query)) {
$events_req[] = $row;
}
}
}
}
}
if (count($clients_list)) {
foreach ($clients_list as $client) {
$old_activities = [];
if (!empty($client['activities']))
$old_activities = json_decode(html_entity_decode($client['activities'], ENT_QUOTES), true);
// Миксуем старые и новые теги
if (is_array($old_activities) && is_array($clients_activities[$client['id']]))
$client['activities'] = array_merge($old_activities, $clients_activities[$client['id']]);
else
$client['activities'] = $old_activities;
// Телефоны клиента
$phones = [];
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));
// Объекты клиента
$objects = [];
$obj_ids = json_decode(html_entity_decode($client['objects'], ENT_QUOTES), true);
if (is_array($obj_ids)) {
$obj_ids = array_unique(array_map('intval', $obj_ids));
if (count($obj_ids) > 0) {
$results = $objects_inst->getObjectsList($app, [
'objects_ids' => $obj_ids
], null, true);
if (!empty($results)) {
foreach ($results as $object) {
$objects[] = [
'id' => (int)$object['id'],
'title' => $object['title']
];
}
}
}
}
// Роль клиента
$roles = json_decode(html_entity_decode($client['role'], ENT_QUOTES), true);
// Тип клиента
$work_types = json_decode(html_entity_decode($client['work_type'], ENT_QUOTES), true);
// Это новый клиент?
$is_new = false;
if (isset($_SESSION['new_transfers']['clients'])) {
$is_new = in_array((int)$client["id"], $_SESSION['new_transfers']['clients']);
}
// Кто добавил клиента
$who_added = [];
if (isset($client['id_agent'])) {
if (isset($users[$client['id_agent']])) {
if ($user_who = $users[$client['id_agent']]) {
if ($user_who['agency']) {
$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)
$who_added['username'] = $departments[$user_who['role_id']]['role_name'] . ' ' . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']);
} else {
$who_added['name'] = "Агент " . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']);
if ($user_who['role_id'] > 0)
$who_added['name'] = $departments[$user_who['role_id']]['role_name'] . ' ' . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']);
}
$who_added['datetime'] = date('Y-m-d H:i:s', strtotime($client['date_add']));
$who_added['user_id'] = (int)$client['id_agent'];
}
}
}
// Кто закрыл (удалил) клиента
$who_delete = [];
if ((int)$client['deleted'] == 1 && isset($client['who_delete'])) {
if (isset($users[$client['who_delete']])) {
if ($user_who = $users[$client['who_delete']]) {
if ($user_who['agency']) {
$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 {
$who_delete['name'] = "Агент " . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']);
}
$sql = "SELECT `date_update`
FROM `events_clients`
WHERE `client_id`=$client[id] AND
`event`='delete' AND
`from_id`=$client[who_delete]
ORDER BY id DESC LIMIT 1";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
$row = mysql_fetch_assoc($query);
if ($row['date_update'] != '0000-00-00 00:00:00') {
$who_delete['datetime'] = date('Y-m-d H:i:s', strtotime($row['date_update']));
}
}
$who_delete['user_id'] = (int)$client['who_delete'];
}
}
}
// У кого в работе клиент
$who_work = [];
if ((int)$client['who_work'] > 0) {
if (isset($users[$client['who_work']])) {
if ($user_who = $users[$client['who_work']]) {
if ($user_who['agency']) {
$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']);
} else {
$who_work['name'] = "Менеджер " . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']);
}
} else {
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']);
} else {
$who_work['name'] = "Агент " . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']);
}
}
$sql = "SELECT `date_update` FROM `events_clients`
WHERE `client_id`=$client[id] AND event='accepted' AND user_id=$client[who_work]";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
$row = mysql_fetch_assoc($query);
if ($row['date_update'] != '0000-00-00 00:00:00') {
$who_work['datetime'] = date('Y-m-d H:i:s', strtotime($row['date_update']));
}
}
}
$who_work['user_id'] = (int)$client['who_work'];
}
}
}
// Совместная работа с клиентом
$doers_requests = [];
$doers_accepted = [];
if ($client['doer_clients'] == 1 && isset($client['doers'])) {
$doers = json_decode(html_entity_decode($client['doers'], ENT_QUOTES), true);
if (count($doers)) {
foreach($doers as $id => $status) {
$doers_request = [];
$doers_accept = [];
if (isset($users[$id])) {
$user_who = $users[$id];
if ($status == 0) {
if ($user_who['agency']) {
$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 {
$doers_request['name'] = "Агент " . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']);
}
$doers_request['user_id'] = (int)$id;
}
if ($status == 1) {
if ($user_who['agency']) {
$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 {
$doers_accept['name'] = "Агент " . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']);
}
$doers_accept['user_id'] = (int)$id;
}
}
if (!empty($doers_request))
$doers_requests[] = $doers_request;
if (!empty($doers_accept))
$doers_accepted[] = $doers_accept;
}
}
}
// Теги
$tags = [];
if (count($client['activities'])) {
$tags = array_map('intval', $client['activities']);
$tags = array_unique(array_values($tags));
}
// Подсчет новых событий в Истории и задачах
$events_expired = 0;
$events_today = 0;
$events_count = 0;
foreach ($events_less as $event) {
if ((int)$event["client_id"] == (int)$client["id"]) {
$events_expired = (int)$event["res"];
break;
}
}
foreach ($events_eq as $event) {
if ((int)$event["client_id"] == (int)$client["id"]) {
$events_today = (int)$event["res"];
break;
}
}
foreach ($events_more as $event) {
if ((int)$event["client_id"] == (int)$client["id"]) {
$events_count = (int)$event["res"];
break;
}
}
// Подсчет новых событий по заявкам для текущего клиента
$req_events_count = 0;
if (!empty($req_ids[$client['id']])) {
foreach ($events_req as $event) {
if (in_array((int)$event["req_id"], $req_ids[$client['id']])) {
$req_events_count += (int)$event["res"];
break;
}
}
/*foreach ($req_ids[$client['id']] as $req_id) {
foreach ($events_req as $event) {
if ($event["req_id"] == $req_id) {
$req_events_count += (int)$event["res"];
//break;
}
}
}*/
}
// Этапы воронки
$stage_name = null;
if (isset($client['stage'])) {
$stage_id = (int)$client['stage'];
if ((int)$client['deleted'] == 1)
$stage_id = 8;
if ($client['funnel_id'] == 0) {
// Этапы по-умолчанию
$stages = [
1 => [
'id' => 1,
'name' => 'Новый',
'is_active' => true,
'is_next' => false,
'is_main' => true,
'is_expired' => false,
],
2 => [
'id' => 2,
'name' => 'В работе',
'is_active' => ($stage_id >= 2),
'is_next' => (($stage_id+1) == 2),
'is_main' => true,
'is_expired' => false,
],
3 => [
'id' => 3,
'name' => 'Презентация',
'is_active' => ($stage_id >= 3),
'is_next' => (($stage_id+1) == 3),
'is_main' => true,
'is_expired' => false,
],
4 => [
'id' => 4,
'name' => 'Показ',
'is_active' => ($stage_id >= 4),
'is_next' => (($stage_id+1) == 4),
'is_main' => true,
'is_expired' => false,
],
5 => [
'id' => 5,
'name' => 'Бронь',
'is_active' => ($stage_id >= 5),
'is_next' => (($stage_id+1) == 5),
'is_main' => true,
'is_expired' => false,
],
6 => [
'id' => 6,
'name' => 'Подаем на ипотеку',
'is_active' => ($stage_id >= 6),
'is_next' => (($stage_id+1) == 6),
'is_main' => true,
'is_expired' => false,
],
7 => [
'id' => 7,
'name' => 'Сделка',
'is_active' => ($stage_id >= 7),
'is_next' => (($stage_id+1) == 7),
'is_main' => true,
'is_expired' => false,
],
8 => [
'id' => 8,
'name' => 'Закрыт',
'is_active' => ($stage_id >= 8),
'is_next' => (($stage_id+1) == 8),
'is_main' => true,
'is_expired' => false,
],
];
$stage_name = "Новый";
if (isset($stages[$stage_id]['name']))
$stage_name = $stages[$stage_id]['name'];
} else if ($client['funnel_id']) {
$stages = [];
$sql = "SELECT * FROM `clients_funnel_step` WHERE client_id = '{$client['id']}'";
if ($query = mysql_query($sql)) {
$next_id = 0;
$change_step = 0;
$steps_count = 0;
$step_date_update = null;
if (mysql_num_rows($query) > 0) {
$change_step = mysql_fetch_assoc($query);
$next_id = $change_step['next_id'];
$step_date_update = $change_step['date_update'];
}
$steps = [];
$next_steps = [];
$sql = "SELECT * FROM `funnel_steps`
WHERE `funnel_id` = '{$client['funnel_id']}' AND `deleted` = 0
ORDER BY `order_number`, `branch`";
$step_is_active = true;
if ((int)$change_step['step_id'] == 0)
$step_is_active = false;
if ($query = mysql_query($sql)) {
if ($stages_count = mysql_num_rows($query)) {
while ($step = mysql_fetch_assoc($query)) {
$step['isActive'] = (int)$step_is_active;
$step['nextStep'] = false;
if ($step['id'] == (int)$change_step['step_id']) {
$next_steps = json_decode(htmlspecialchars_decode($step['next_step']));
if ($next_id == 0)
$step_is_active = false;
} else if ($step['id'] == (int)$next_id) {
$step_is_active = false;
}
$steps[$step['id']] = $step;
}
if ($next_id != 0 && !empty($next_steps)) {
foreach ($next_steps as $step_id => $step) {
if ($step != $next_id) {
unset($next_steps[$step_id]);
}
}
}
foreach ($steps as $step_id => $step) {
$steps[$step_id]['isNext'] = 0;
if (in_array($step_id, $next_steps)) {
$stage_name = $step['name'];
$steps[$step_id]['isNext'] = 1;
}
}
$step_is_active = true;
foreach ($steps as $step_id => $step) {
$interval = 0;
if ($step_date_update)
$interval = date_diff(new \DateTime(), new \DateTime($step_date_update))->days;
$stages[$step_id] = [
'id' => intval($step['id']),
'name' => trim($step['name']),
'is_active' => boolval($step_is_active),
'is_next' => boolval($step['isNext'] == 1),
'is_main' => boolval($step['main'] == 1),
'is_expired' => boolval($interval >= $step['days_step']),
];
}
if ($client['deleted'] == 1 && $client['funnel_id'] > 0) {
$stage_name .= ' (закрыт)';
}
}
}
}
}
}
$user = new \User();
$user->get($user_id);
$r_check_permissions = $user->checkMenuPermissions();
$depClassPerm = new \Department();
$dep_user = $depClassPerm->getDepartment($_SESSION['id']);
$sql_check_manager = "SELECT `id_manager`, `department_id` FROM `users` WHERE `id` = ".$client['who_work'];
$result_check_manager = mysql_query($sql_check_manager);
$client_id_manager = mysql_fetch_assoc($result_check_manager);
$sql_user_missing_fields = "SELECT `id_manager`, `department_id` FROM `users` WHERE `id` = ".$_SESSION['id'];
$result_user_missing_fields = mysql_query($sql_user_missing_fields);
$user_missing_fields = mysql_fetch_assoc($result_user_missing_fields);
$user_allow_edit = false;
if ($_SESSION['agency'] || $_SESSION['users_admin'] || $r_check_permissions['menu_all_clients_edit'] == 1 || $_SESSION['id'] == $client['who_work']) {
$user_allow_edit = true;
} elseif (($dep_user['role'] == 'admin_department' || $dep_user['role'] == 'manager_office') && $client_id_manager['department_id'] == $user_missing_fields['department_id']) {
$user_allow_edit = true;
} elseif ($dep_user['role'] == 'manager' && $_SESSION['id'] == $client_id_manager['id_manager']) {
$user_allow_edit = true;
} elseif ($dep_user['role'] == 'manager_office_menager' && ($_SESSION['id'] == $client_id_manager['id_manager'] || $_SESSION['id_manager'] == $client_id_manager['id_manager'] || $_SESSION['id_manager'] == $client['who_work'])) {
$user_allow_edit = true;
} elseif (!($dep_user['role']) && ($_SESSION['manager'] && ($_SESSION['id'] == $client_id_manager['id_manager']))) {
$user_allow_edit = true;
}
$clientItem = [
'id' => (int)$client['id'],
'name' => $client['fio'],
'phones' => (!empty($phones)) ? $phones : null,
'email' => (!empty($client['email'])) ? $client['email'] : null,
'date_add' => $client['date_add'],
'date_create' => $client['date_create'],
'roles' => (!empty($roles)) ? $roles : null,
'types' => (!empty($work_types)) ? $work_types : null,
'objects' => (!empty($objects)) ? $objects : null,
'is_confirm' => !empty($client['confirm']) && boolval((int)$client['confirm']),
'is_deleted' => !empty($client['deleted']) && boolval((int)$client['deleted']),
'is_new' => $is_new,
'is_hot' => (!empty($client['hot'])) ? (bool)$client['hot'] : null,
'priority' => (!empty($client['priority'])) ? (int)$client['priority'] : null,
'who_added' => (!empty($who_added)) ? $who_added : null,
'who_delete' => (!empty($who_delete)) ? $who_delete : null,
'who_work' => (!empty($who_work)) ? $who_work : null,
'agent_id' => (!empty($client['id_agent'])) ? (int)$client['id_agent'] : null,
'source_id' => (!empty($client['source'])) ? (int)$client['source'] : null,
'partner_id' => (!empty($client['employee_id'])) ? (int)$client['employee_id'] : null,
'employee_id' => (!empty($client['who_work'])) ? (int)$client['who_work'] : null,
'tags' => (!empty($tags)) ? $tags : null,
'contracts' => (!empty($contracts[$client['id']]) > 0) ? $contracts[$client['id']] : [],
'budget' => (!empty($client['budget'])) ? (int)$client['budget'] : null,
'deal_price' => (!empty($client['summa'])) ? (int)$client['summa'] : null,
'funnel_id' => (!empty($client['funnel_id'])) ? (int)$client['funnel_id'] : null,
'stage_id' => (!empty($client['stage'])) ? (int)$client['stage'] : null,
'stage_name' => (!empty($stage_name)) ? $stage_name : null,
'stages' => (!empty($stages) && is_array($stages)) ? array_values($stages) : null,
'stages_count' => (!empty($stages_count)) ? $stages_count : null,
'events_count' => [
'clients' => [
'expired' => (!empty($events_expired)) ? $events_expired : 0,
'today' => (!empty($events_today)) ? $events_today : 0,
'total' => (!empty($events_count)) ? $events_count : 0
],
'requisitions' => (!empty($req_events_count)) ? $req_events_count : 0,
],
'requisitions' => (!empty($req_ids[$client['id']])) ? $req_ids[$client['id']] : 0,
'doers_requests' => (!empty($doers_requests)) ? $doers_requests : null,
'doers_accepted' => (!empty($doers_accepted)) ? $doers_accepted : null,
'description' => $client['opis'],
'published_at' => date('Y-m-d H:i:s', strtotime($client["date_add"])),
'this_user_can_edit_clients' => $user_allow_edit,
//'_raw' => $client,
];
// Маскируем phone/email/имя клиента, если у текущего пользователя
// включено право `user_permissions.hide_client_contacts`.
// Helper сам проверяет право — если выключено, ничего не делает.
mask_client_contacts_inplace($clientItem);
$clients[] = $clientItem;
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
$pagination = [
'current' => $page,
'pages' => ceil($total/$per_page),
'per_page' => $per_page,
];
}
if (!$error) {
if ($need_return) {
return $clients;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$sources = [
'count_sql' => str_replace(" ", " ", str_replace(["\n", "\r", "\t"], "", $count_sql)),
'main_sql' => str_replace(" ", " ", str_replace(["\n", "\r", "\t"], "", $main_sql)),
'success' => true,
'user_id' => (int)$user_id,
'count' => count($clients),
'total' => $total,
'page' => $page,
'clients' => $clients,
'clients_ids' => $clients_ids,
'pagination' => $pagination,
'tags_list' => $activities,
'overage_time' => round((microtime(true) - $start_time), 3) . " sec.",
];
$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([
'count_sql' => str_replace(" ", " ", str_replace(["\n", "\r", "\t"], "", $count_sql)),
'main_sql' => str_replace(" ", " ", str_replace(["\n", "\r", "\t"], "", $main_sql)),
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors,
'overage_time' => round((microtime(true) - $start_time), 3) . " sec.",
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getClient($app, $get = null, $post = null, $need_return = false) {
$start_time = microtime(true);
global $WORK_TYPES;
global $TYPE_NEDV2_SORT;
global $ROLES_CLIENTS;
$error = false;
$user_can_edit = false;
$errors = [];
$client_id = intval($get['client_id']);
$user_id = $_SESSION['id'];
//if (($user_id = $_SESSION['id']) && ($client_id && $client_id != 0)) {
if ($client_id && $client_id != 0) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('pdo');
$user = new \User();
$user->get($user_id);
$user->checkPermissions($user_id, false);
$menuPermissions = $user->checkMenuPermissions();
$agency_id = $_SESSION['agency_id'];
$users = [(int)$user_id];
$managers = [(int)$agency_id];
$client = [];
$client_inst = new \Clients();
$data = null;
if (!($data = (array)$client_inst->get($client_id))) {
$error = true;
$errors = $client_inst->errors;
}
if ($data['id']) {
if ($data['who_work'] == $user_id || $data['id_agent'] == $user_id || $menuPermissions['menu_all_clients_edit'] == 1) {
$user_can_edit = true;
} else {
if ($user->users_admin == 0 && $user->agency == 0 && $user->manager == 0) {
$user_can_edit = false;
} else {
if ($data['who_work'] > 0) {
$clientUser = new \User;
$clientUser->get($data['who_work']);
if (isset($clientUser->agencyId) && $clientUser->agencyId == $user->agencyId) {
$user_can_edit = true;
} else {
if ($user->agencyId == $data['who_work']) {
$user_can_edit = true;
}
}
} else if ($data['id_agent'] > 0) {
$clientUser = new \User;
$clientUser->get($data['who_work']);
if (isset($clientUser->agencyId) && $clientUser->agencyId == $user->agencyId) {
$user_can_edit = true;
} else {
if ($user->agencyId == $data['who_work']) {
$user_can_edit = true;
}
}
} else {
$user_can_edit = false;
}
}
}
} else {
$data = null;
$error = true;
$errors[] = 'Клиент не найден.';
}
if (!empty($data)) {
// Cleanup
foreach ($data as $key => $value) {
if (empty($value) || is_null($value) || strtolower($value) == 'null') {
$data[$key] = null;
}
}
// Тип клиента
$types = [];
if (isset($data["work_type"]) && !is_null($data["work_type"]) && strtolower($data["work_type"]) != 'null') {
foreach (json_decode($data["work_type"], true) as $type) {
if ($type_id = array_search($type, $WORK_TYPES))
$types[] = (int)$type_id;
}
}
// Роль клиента
$roles = [];
if (isset($data["role"]) && !is_null($data["role"]) && strtolower($data["role"]) != 'null') {
foreach (json_decode($data["role"], true) as $role) {
if ($role_id = array_search($role, $ROLES_CLIENTS))
$roles[] = (int)$role_id;
}
}
// Тип недвижимости
$estates = [];
if (isset($data["type"]) && !is_null($data["type"]) && strtolower($data["type"]) != 'null') {
$index = 1;
$estate_types = [];
foreach($TYPE_NEDV2_SORT as $key => $val) {
if (!empty($key)) {
$estate_types[$index] = $key;
}
$index++;
}
foreach (json_decode($data["type"], true) as $type) {
if ($type_id = array_search($type, $estate_types))
$estates[] = $type_id;
}
}
// Договоры
$contracts_inst = new \Contract();
$contracts = $contracts_inst->getContracts($client_id, 'client');
foreach ($contracts as $key => $contract) {
if (isset($contract['date_start']))
$contracts[$key]['date_start'] = date('Y-m-d H:i:s', strtotime($contract['date_start']));
if (isset($contract['date_end']))
$contracts[$key]['date_end'] = date('Y-m-d H:i:s', strtotime($contract['date_end']));
}
// Ипотека
//$hypothec2 = $this->getHypothec($app, ['client_id' => $data["id"]], null, true);
$rez = $this->getHypothec($app, ['client_id' => $data["id"]], null, true);
$hypothec = [
//'id' => $rez['id'],
//'client_id' => $rez['client_id'],
'is_primary' => (bool)$rez['rynok'],
'complexes' =>(isset($rez['jc'])) ? array_map('intval', json_decode($rez['jc'], true)) : null,
'is_object' => (bool)$rez['yes_object'],
'object_price' => (isset($rez['summa_object'])) ? (int)$rez['summa_object'] : null,
'first_pay' => (isset($rez['ante_pr'])) ? (int)$rez['ante_pr'] : null,
'first_pay_price' => (isset($rez['ante_rub'])) ? (int)$rez['ante_rub'] : null,
'borrower_age' => (isset($rez['age'])) ? (int)$rez['age'] : null,
'is_co_borrower' => (bool)$rez['yes_co_borrower'],
'co_borrower_relationship' => (isset($rez['relationship'])) ? $rez['relationship'] : null,
'co_borrower_name' => (isset($rez['co_borrower_fio'])) ? $rez['co_borrower_fio'] : null,
'co_borrower_age' => (isset($rez['co_borrower_age'])) ? (int)$rez['co_borrower_age'] : null,
'co_borrower_contacts' => (isset($rez['contacts'])) ? $rez['contacts'] : null,
'is_income_taken' => (bool)$rez['yes_co_dohod'],
'co_borrower_income' => (isset($rez['co_borrower_dohod'])) ? (int)$rez['co_borrower_dohod'] : null,
'borrower_income' => (isset($rez['income'])) ? (int)$rez['income'] : null,
'borrower_credit_load' => (isset($rez['credit_load'])) ? (int)$rez['credit_load'] : null,
'is_married' => (bool)$rez['yes_brak'],
'is_married_contract' => (bool)$rez['yes_brak_doc'],
'is_contract' => (bool)$rez['yes_doc'],
'contact_number' => (isset($rez['number_doc'])) ? trim($rez['number_doc']) : null,
'contact_date' => date('d.m.Y', strtotime($rez['date_doc'])),
'contact_commission' => (isset($rez['doc_komis_pr'])) ? (int)$rez['doc_komis_pr'] : null,
'contact_commission_price' => (isset($rez['doc_komis'])) ? (int)$rez['doc_komis'] : null,
'confirm_ndfl' => false,
'confirm_bank_form' => false,
'confirm_two_docs' => false,
'confirm_ip' => false,
'confirm_buss_owner' => false,
'bank_mother_capital' => false,
'bank_state_support' => false,
'bank_state_grant' => false,
'bank_standart' => false,
'is_bank' => (bool)$rez['yes_bank'],
'banks' => (isset($rez['banks'])) ? json_decode($rez['banks'], true) : [],
//'bank_employee' => (isset($rez['employee_bank'])) ? $rez['employee_bank'] : null,
//'bank_date' => (isset($rez['date_bank'])) ? date('d.m.Y', strtotime($rez['date_bank'])) : null,
'is_resolve' => (bool)$rez['yes_resolve'],
'resolve' => (isset($rez['resolve'])) ? json_decode($rez['resolve'], true) : [],
'denial' => (isset($rez['denial'])) ? json_decode($rez['denial'], true) : null,
'revisal' => (isset($rez['revisal'])) ? json_decode($rez['revisal'], true) : null,
'resolve_comment' => $rez['comment_resolve'],
'is_issue' => (bool)$rez['yes_issue'],
'bank_issue' => (isset($rez['bank_issue'])) ? json_decode($rez['bank_issue'], true) : null,
'issue_rate' => (isset($rez['rate_issue'])) ? trim($rez['rate_issue']) : null,
'issue_term' => (isset($rez['term_issue'])) ? trim($rez['term_issue']) : null,
'comment' => trim($rez['comment']),
'created_at' => date('d.m.Y', strtotime($rez['date_create'])),
'updated_at' => date('d.m.Y', strtotime($rez['date_update'])),
];
$overdue_credit = 0;
if ($data['overdue_credit'] === 'overdue_credit_yes')
$overdue_credit = 1;
else if ($data['overdue_credit'] === 'overdue_credit_history')
$overdue_credit = 2;
else if ($data['overdue_credit'] === 'overdue_credit_not')
$overdue_credit = 3;
$mfo_credit = 0;
if ($data['mfo_credit'] === 'mfo_credit_yes')
$mfo_credit = 1;
else if ($data['mfo_credit'] === 'mfo_credit_history')
$mfo_credit = 2;
else if ($data['mfo_credit'] === 'mfo_credit_not')
$mfo_credit = 3;
// Кредит
$credit = [
//'id' => !empty($data['id']) ? $data['id'] : null,
//'client_id' => !empty($data['client_id']) ? $data['client_id'] : null,
'product_id' => !empty($data['bancks_credit']) ? array_map('intval', json_decode($data['bancks_credit'], true)) : null,
'target' => !empty($data['cel_credit']) ? $data['cel_credit'] : null,
'age' => !empty($data['age_credit']) ? $data['age_credit'] : null,
'registration' => !empty($data['propiska_credit']) ? $data['propiska_credit'] : null,
'sum' => !empty($data['summa_credit']) ? (int)$data['summa_credit'] : null,
'commission' => !empty($data['komissiya_credit']) ? (int)$data['komissiya_credit'] : null,
'load' => !empty($data['nagruzka_credit']) ? (int)$data['nagruzka_credit'] : null,
'load_cards' => !empty($data['kol_nagruzka_credit']) ? (int)$data['kol_nagruzka_credit'] : null,
'income' => !empty($data['dohod_credit']) ? (int)$data['dohod_credit'] : null,
'verify_by_ndfl' => (!empty($data['dava_ndfl_credit']) && (bool)$data['dava_ndfl_credit']),
'verify_by_inquiry' => (!empty($data['spravka_credit']) && (bool)$data['spravka_credit']),
'verify_by_phone' => (!empty($data['phone_credit']) && (bool)$data['phone_credit']),
'query_count' => !empty($data['podachi_credit']) ? (int)$data['podachi_credit'] : null,
'owner_by_flat' => !empty($data['kvartira_credit']) && (bool)$data['kvartira_credit'],
'owner_by_house' => !empty($data['dom_credit']) && (bool)$data['dom_credit'],
'owner_by_area' => !empty($data['uchastok_credit']) && (bool)$data['uchastok_credit'],
'owner_by_car' => !empty($data['car_credit']) && (bool)$data['car_credit'],
'not_owner' => !empty($data['not_own_credit']) && (bool)$data['not_own_credit'],
'deduction' => !empty($data['yes_deduction_credit']) && (bool)$data['yes_deduction_credit'],
'overdue' => $overdue_credit,
'mfo' => $mfo_credit,
];
// Телефоны
$phones = [];
if (!empty($data['phone']))
$phones[] = $data['phone'];
if (isset($data["phone2"]) && !is_null($data["phone2"]) && strtolower($data["phone2"]) != 'null') {
foreach (json_decode(html_entity_decode($data["phone2"], ENT_QUOTES), true) as $phone) {
$phones[] = '+' . preg_replace('/[^0-9]/', '', $phone);
}
}
$is_new = false;
if (isset($_SESSION['new_transfers']['clients']))
$is_new = in_array((int)$data["id"], $_SESSION['new_transfers']['clients']);
// Формируем списки отделов
$sql = "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 = '$agency_id'";
if ($query = mysql_query($sql)) {
while ($row = mysql_fetch_assoc($query)) {
$departments[$row['id']] = $row;
}
}
// Кто добавил клиента
$who_added = [];
if (isset($data['id_agent'])) {
if (isset($users[$data['id_agent']])) {
if ($user_who = $users[$data['id_agent']]) {
if ($user_who['agency']) {
$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)
$who_added['username'] = $departments[$user_who['role_id']]['role_name'] . ' ' . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']);
} else {
$who_added['name'] = "Агент " . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']);
if ($user_who['role_id'] > 0)
$who_added['name'] = $departments[$user_who['role_id']]['role_name'] . ' ' . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']);
}
$who_added['datetime'] = date('Y-m-d H:i:s', strtotime($data['date_add']));
$who_added['user_id'] = (int)$data['id_agent'];
}
}
}
// Кто закрыл (удалил) клиента
$who_delete = [];
if ((int)$data['deleted'] == 1 && isset($data['who_delete'])) {
if (isset($users[$data['who_delete']])) {
if ($user_who = $users[$data['who_delete']]) {
if ($user_who['agency']) {
$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 {
$who_delete['name'] = "Агент " . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']);
}
$sql = "SELECT `date_update`
FROM `events_clients`
WHERE `client_id`=$data[id] AND
`event`='delete' AND
`from_id`=$data[who_delete]
ORDER BY id DESC LIMIT 1";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
$row = mysql_fetch_assoc($query);
if ($row['date_update'] != '0000-00-00 00:00:00') {
$who_delete['datetime'] = date('Y-m-d H:i:s', strtotime($row['date_update']));
}
}
$who_delete['user_id'] = (int)$data['who_delete'];
}
}
}
// У кого в работе клиент
$who_work = [];
if ((int)$data['who_work'] > 0) {
if (isset($users[$data['who_work']])) {
if ($user_who = $users[$data['who_work']]) {
if ($user_who['agency']) {
$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']);
} else {
$who_work['name'] = "Менеджер " . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']);
}
} else {
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']);
} else {
$who_work['name'] = "Агент " . trim($user_who['last_name'] . ' ' . $user_who['first_name'] . ' ' . $user_who['middle_name']);
}
}
$sql = "SELECT `date_update` FROM `events_clients`
WHERE `client_id`=$data[id] AND event='accepted' AND user_id=$data[who_work]";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
$row = mysql_fetch_assoc($query);
if ($row['date_update'] != '0000-00-00 00:00:00') {
$who_work['datetime'] = date('Y-m-d H:i:s', strtotime($row['date_update']));
}
}
}
$who_work['user_id'] = (int)$data['who_work'];
}
}
}
// Дополнительные поля
$fields = [];
$fields_inst = new FieldsController;
$fields = $fields_inst->getFields($app, [
'section' => 'clients',
'source_id' => (int)$data["id"],
], $post, true);
// Переменные для интерактивных документов
$docs_inst = new DocsController;
$variables = $docs_inst->getVariables($app, [
'section' => 'clients',
'source_id' => (int)$data["id"],
], $post, true);
// Этапы воронки
$stage_name = null;
if (isset($data['stage']) && !is_null($data["stage"]) && strtolower($data["stage"]) != 'null') {
$stage_id = (int)$data['stage'];
if ((int)$data['deleted'] == 1)
$stage_id = 8;
if ($data['funnel_id'] == 0) {
// Этапы по-умолчанию
$stages = [
1 => [
'id' => 1,
'name' => 'Новый',
'is_active' => true,
'is_next' => false,
'is_main' => true,
'is_expired' => false,
],
2 => [
'id' => 2,
'name' => 'В работе',
'is_active' => ($stage_id >= 2),
'is_next' => (($stage_id+1) == 2),
'is_main' => true,
'is_expired' => false,
],
3 => [
'id' => 3,
'name' => 'Презентация',
'is_active' => ($stage_id >= 3),
'is_next' => (($stage_id+1) == 3),
'is_main' => true,
'is_expired' => false,
],
4 => [
'id' => 4,
'name' => 'Показ',
'is_active' => ($stage_id >= 4),
'is_next' => (($stage_id+1) == 4),
'is_main' => true,
'is_expired' => false,
],
5 => [
'id' => 5,
'name' => 'Бронь',
'is_active' => ($stage_id >= 5),
'is_next' => (($stage_id+1) == 5),
'is_main' => true,
'is_expired' => false,
],
6 => [
'id' => 6,
'name' => 'Подаем на ипотеку',
'is_active' => ($stage_id >= 6),
'is_next' => (($stage_id+1) == 6),
'is_main' => true,
'is_expired' => false,
],
7 => [
'id' => 7,
'name' => 'Сделка',
'is_active' => ($stage_id >= 7),
'is_next' => (($stage_id+1) == 7),
'is_main' => true,
'is_expired' => false,
],
8 => [
'id' => 8,
'name' => 'Закрыт',
'is_active' => ($stage_id >= 8),
'is_next' => (($stage_id+1) == 8),
'is_main' => true,
'is_expired' => false,
],
];
$stage_name = "Новый";
if (isset($stages[$stage_id]['name']))
$stage_name = $stages[$stage_id]['name'];
} else if (intval($data['funnel_id'])) {
$stages = [];
$sql = "SELECT * FROM `clients_funnel_step` WHERE client_id = '{$data['id']}'";
if ($query = mysql_query($sql)) {
$next_id = 0;
$change_step = 0;
$steps_count = 0;
$step_date_update = null;
if (mysql_num_rows($query) > 0) {
$change_step = mysql_fetch_assoc($query);
$next_id = $change_step['next_id'];
$step_date_update = $change_step['date_update'];
}
$steps = [];
$next_steps = [];
$sql = "SELECT * FROM `funnel_steps`
WHERE `funnel_id` = '{$data['funnel_id']}' AND `deleted` = 0
ORDER BY `order_number`, `branch`";
$step_is_active = true;
if ((int)$change_step['step_id'] == 0)
$step_is_active = false;
if ($query = mysql_query($sql)) {
if ($stages_count = mysql_num_rows($query)) {
//var_export($steps) && die();
while ($step = mysql_fetch_assoc($query)) {
$step['isActive'] = (int)$step_is_active;
$step['nextStep'] = false;
if ($step['id'] == (int)$change_step['step_id']) {
$next_steps = json_decode(htmlspecialchars_decode($step['next_step']));
if ($next_id == 0)
$step_is_active = false;
} else if ($step['id'] == (int)$next_id) {
$step_is_active = false;
}
$steps[$step['id']] = $step;
}
//var_export($steps) && die();
if ($next_id != 0 && !empty($next_steps)) {
foreach ($next_steps as $step_id => $step) {
if ($step != $next_id) {
unset($next_steps[$step_id]);
}
}
}
foreach ($steps as $step_id => $step) {
$steps[$step_id]['isNext'] = 0;
if (in_array($step_id, $next_steps)) {
$stage_name = $step['name'];
$steps[$step_id]['isNext'] = 1;
}
}
$step_is_active = true;
foreach ($steps as $step_id => $step) {
$interval = 0;
if ($step_date_update)
$interval = date_diff(new \DateTime(), new \DateTime($step_date_update))->days;
$stages[$step_id] = [
'id' => intval($step['id']),
'name' => trim($step['name']),
'funnel_id' => intval($step['funnel_id']), // ИД воронки
'is_active' => boolval($step['isActive']),
'is_next' => boolval($step['isNext'] == 1),
'is_main' => boolval($step['main'] == 1),
'is_expired' => boolval($interval >= $step['days_step']),
'is_deleted' => boolval($step['deleted'] == 1),
'max_days' => intval($step['days_step']), // Дней на этап
'is_close_after' => boolval(($step['stage'] === 'В работе') ? 0 : 1), // При переходе на этап сменить статус
'is_parallel' => boolval($step['start_parallel'] == 1),
'branch_id' => intval($step['branch']),
];
}
if ($data['deleted'] == 1 && $data['funnel_id'] > 0) {
$stage_name .= ' (закрыт)';
}
}
}
}
}
}
// Формируем списки тегов под клиентов
$sql = "SELECT `activity_id`, `client_id`
FROM `clients_activities`
WHERE `client_id` = $data[id]";
$clients_activities = [];
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_assoc($query)) {
$clients_activities[] = $row['activity_id'];
}
}
}
$old_activities = [];
if (!empty($data['activities']))
$old_activities = json_decode(html_entity_decode($data['activities'], ENT_QUOTES), true);
// Миксуем старые и новые теги
if (is_array($old_activities) && is_array($clients_activities))
$data['activities'] = array_merge($old_activities, $clients_activities);
else
$data['activities'] = $old_activities;
$activities = array_unique($data['activities']);
$user = new \User();
$user->get($user_id);
$r_check_permissions = $user->checkMenuPermissions();
$depClassPerm = new \Department();
$dep_user = $depClassPerm->getDepartment($_SESSION['id']);
$sql_check_manager = "SELECT `id_manager`, `department_id` FROM `users` WHERE `id` = ".$data['who_work'];
$result_check_manager = mysql_query($sql_check_manager);
$client_id_manager = mysql_fetch_assoc($result_check_manager);
$sql_user_missing_fields = "SELECT `id_manager`, `department_id` FROM `users` WHERE `id` = ".$_SESSION['id'];
$result_user_missing_fields = mysql_query($sql_user_missing_fields);
$user_missing_fields = mysql_fetch_assoc($result_user_missing_fields);
$user_allow_edit = false;
if ($_SESSION['agency'] || $_SESSION['users_admin'] || $r_check_permissions['menu_all_clients_edit'] == 1 || $_SESSION['id'] == $data['who_work']) {
$user_allow_edit = true;
} elseif (($dep_user['role'] == 'admin_department' || $dep_user['role'] == 'manager_office') && $client_id_manager['department_id'] == $user_missing_fields['department_id']) {
$user_allow_edit = true;
} elseif ($dep_user['role'] == 'manager' && $_SESSION['id'] == $client_id_manager['id_manager']) {
$user_allow_edit = true;
} elseif ($dep_user['role'] == 'manager_office_menager' && ($_SESSION['id'] == $client_id_manager['id_manager'] || $_SESSION['id_manager'] == $client_id_manager['id_manager'] || $_SESSION['id_manager'] == $data['who_work'])) {
$user_allow_edit = true;
} elseif (!($dep_user['role']) && ($_SESSION['manager'] && ($_SESSION['id'] == $client_id_manager['id_manager']))) {
$user_allow_edit = true;
}
$source_see = 1;
if($data['source'] > 0){
$commonController = new CommonController();
$sql_source = "SELECT * FROM `advertising_sources` WHERE id = {$data['source']}";
$q_source = mysql_query($sql_source);
$r_source = mysql_fetch_assoc($q_source);
if($commonController->is_see($app, $r_source['is_no_see'], $r_source['users_no_see']) === false)
$source_see = 0;
}
$clients_dop_info = [
'persone_no_ip' => (int)$data['persone_no_ip'],
'passport' => $data['passport'],
'date_of_issue_passport' => (strtotime($data['date_of_issue_passport']) > 0) ? date('Y-m-d H:i',strtotime($data['date_of_issue_passport'])) : null ,
'passport_issued_by' => $data['passport_issued_by'],
'birthplace' => $data['birthplace'],
'registration_address' => $data['registration_address'],
'post_address' => $data['post_address'],
'persone_snils' => $data['persone_snils'],
'persone_nationality' => $data['persone_nationality'],
'persone_gender' => $data['persone_gender'],
'persone_full_name' => $data['persone_full_name'],
'persone_short_name' => $data['persone_short_name'],
'persone_ogrn' => $data['persone_ogrn'],
'persone_inn' => $data['persone_inn'],
'persone_kpp' => $data['persone_kpp'],
'persone_legal_address' => $data['persone_legal_address'],
'persone_fact_address' => $data['persone_fact_address'],
'persone_info_bank' => $data['persone_info_bank'],
'persone_name_bank' => $data['persone_name_bank'],
'persone_bik_bank' => $data['persone_bik_bank'],
'persone_rs_bank' => $data['persone_rs_bank'],
'persone_kors_bank' => $data['persone_kors_bank'],
'persone_fio_rukovod' => $data['persone_fio_rukovod'],
'persone_powers' => $data['persone_powers'],
'persone_kod_podrazdelenia' => $data['persone_kod_podrazdelenia'],
];
$client = [
'id' => (int)$data["id"],
'name' => $data["fio"],
'email' => $data["email"],
'phone' => '+' . preg_replace('/[^0-9]/', '', $data['phone']),
'phones' => !empty($phones) ? $phones : [],
'roles' => !empty($roles) ? $roles : null,
'types' => !empty($types) ? $types : null,
'estates' => !empty($estates) ? $estates : null,
'contracts' => (count($contracts) > 0) ? $contracts : [],
'objects' => (!empty($data["objects"]) && !is_null($data["objects"]) && strtolower($data["objects"]) != 'null') ? array_map('intval', json_decode($data["objects"], true)) : null,
'requisitions' => (!empty($data["req"]) && !is_null($data["req"]) && strtolower($data["req"]) != 'null') ? array_map('intval', json_decode("[".$data["req"]."]", true)) : null,
'budget' => (!empty($data['budget'])) ? (int)$data['budget'] : null,
'deal_price' => (!empty($data['summa'])) ? (int)$data['summa'] : null,
'source_id' => (!empty($data['source'])) ? (int)$data['source'] : null,
'source_see' => $source_see,
'partner_id' => (!empty($data['employee_id'])) ? (int)$data['employee_id'] : null,
'employee_id' => (!empty($data['who_work'])) ? (int)$data['who_work'] : null,
'birthday' => (!empty($data['birthday'])) ? date('Y-m-d H:i:s', strtotime($data["birthday"])) : null,
'funnel_id' => (int)$data['funnel_id'],
'agent_id' => (!empty($data['id_agent'])) ? (int)$data['id_agent'] : null,
'stage_id' => (!empty($data['stage'])) ? (int)$data['stage'] : null,
'stage_name' => (!empty($stage_name)) ? $stage_name : null,
'stages' => (!empty($stages) && is_array($stages)) ? array_values($stages) : null,
'stages_count' => (!empty($stages_count)) ? $stages_count : null,
'description' => $data["opis"],
'tags' => (!empty($activities)) ? array_map('intval', $activities) : null,
'confirm' => (int)$data['confirm'],
'is_confirm' => !empty($data['confirm']) && boolval((int)$data['confirm']),
'is_deleted' => !empty($data['deleted']) && boolval((int)$data['deleted']),
'is_new' => $is_new,
'is_hot' => (!empty($data['hot'])) ? (bool)$data['hot'] : false,
'priority' => (!empty($data['priority'])) ? (int)$data['priority'] : null,
'who_added' => (!empty($who_added)) ? $who_added : null,
'who_delete' => (!empty($who_delete)) ? $who_delete : null,
'who_work' => (!empty($who_work)) ? $who_work : null,
'fields' => !empty($fields) ? $fields : null,
'variables' => !empty($variables) ? $variables : null,
'hypothec' => !empty($hypothec) ? $hypothec : null,
'credit' => !empty($credit) ? $credit : null,
'published_at' => date('Y-m-d H:i:s', strtotime($data["date_add"])),
'this_user_can_edit_clients' => $user_allow_edit,
'passport' => (!empty($data['passport'])) ? $data['passport'] : null,
'clients_dop_info' => !empty($clients_dop_info) ? $clients_dop_info : null,
//'_raw' => $data,
];
// Маскируем phone/email/имя клиента, если у текущего пользователя
// включено право `user_permissions.hide_client_contacts`.
mask_client_contacts_inplace($client);
} else {
$error = true;
$errors[] = 'Клиент не найден.';
}
if (!$error) {
if ($need_return) {
return $client;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$errors,
'user_id' => (int)$user_id,
'item' => $client,
'user_can_edit' => $user_can_edit,
'overage_time' => round((microtime(true) - $start_time), 3) . " sec.",
], 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)$_SESSION['id'],
'user_can_edit' => $user_can_edit,
'errors' => $errors,
'overage_time' => round((microtime(true) - $start_time), 3) . " sec.",
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getHypothec($app, $get = null, $post = null, $has_return = false) {
$error = false;
$errors = [];
$client_id = intval($get['client_id']);
if (($user_id = $_SESSION['id']) && ($client_id && $client_id != 0)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$data = [];
$sql = "SELECT * FROM `ipoteka` WHERE `client_id` = '$client_id'";
if ($rez = mysql_query($sql)) {
if (mysql_num_rows($rez)) {
foreach (mysql_fetch_assoc($rez) as $key => $value) {
if (in_array($key, ['date_bank','date_doc']))
$value = date('d.m.Y', strtotime($value));
$data[$key] = html_entity_decode($value);
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
if (!$error && $has_return) {
return $data;
} else if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'data' => $data,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
if ($has_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'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getVariants($app, $get = null, $post = null, $has_return = false) {
$error = false;
$errors = [];
$client_id = null;
if ($get['client_id'])
$client_id = intval($get['client_id']);
if (($user_id = $_SESSION['id']) && ($client_id && $client_id != 0)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$variants = [];
// Распознавание найденных листингов парсера и витринный 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)) {
$pdf_date_old = "";
$total_sended = mysql_num_rows($query);
while($pdf = mysql_fetch_assoc($query)) {
if ($pdf['date_f'] . $pdf['send_type'] != $pdf_date_old) {
list($d, $m, $y) = explode(".", $pdf['date_f']);
$date_f = $d ." ". getRusMonth($m). " ". $y;
$pdf_date_old = $pdf['date_f'] . $pdf['send_type'];
$new_date = true;
$pdf_type = 'mail';
if (!empty($pdf['send_type']) && $pdf['send_type'] == 1) {
$pdf_type = 'whatsapp';
}
} else {
$new_date = false;
}
$toSend = []; // @todo
$variants[] = [
'id' => (int)$pdf['id'],
'sended_type' => $pdf_type,
'path' => trim($pdf['path']),
'filename' => trim($pdf['nazv']),
'date_string' => $date_f,
'time_string' => trim($pdf['time_f']),
'object_id' => intval($pdf['object_id']),
'object_title' => trim($pdf['object_title']),
'object_address' => trim($pdf['object_address']),
'object_owner' => trim($pdf['sobstv']),
'object_phone' => trim($pdf['phone']),
'is_newbuilding' => (bool)$pdf['newbild'],
'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;
$errors[] = mysql_error();
}
if (!$error && $has_return) {
return $variants;
} else if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'variants' => $variants,
'total_sended' => $total_sended,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
if ($has_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'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getHistory($app, $get = null, $post = null, $has_return = false) {
$error = false;
$errors = [];
$client_id = null;
if (isset($get['client_id']))
$client_id = intval($get['client_id']);
$requisition_id = null;
if (isset($get['requisition_id']))
$requisition_id = intval($get['requisition_id']);
if (($user_id = $_SESSION['id']) && ($client_id && $client_id != 0)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$user = new \User;
$user->get($user_id);
$gmtmsk =$user->gmtmsk;
$time_zone = '';
if($gmtmsk >= 0){
$time_zone = '+'.$gmtmsk.' hour';
} else {
$time_zone = '-'.$gmtmsk.' hour';
}
$history = [];
// copy_created / copy_from — лейбл пустой: текст идёт в dop_text, иначе в истории двоится.
$array_ev = [
'add'=>'Добавлен',
'transmitted' => 'Передан',
'parallel_del' => 'Удален из совместной работы',
'transmitted_parallel' => 'Приглашен к совместной работе',
'accepted' => 'Принят',
'accepted_doer'=>'Добавлен к совместной работе',
'notadopted' => 'Не принят',
'notadopted_doer' => 'Приглашение не принято',
'stageedit' => 'Изменен этап',
'delete' => 'Закрыт',
'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)
UNION (SELECT id, id as client_id, id_agent as user_id, 0 as from_id, 'add' as `event`, `date_add` as `date`, '' as `dop_text`, `of_objects`
FROM clients WHERE id = $client_id) ORDER BY `date` DESC";
if ($requisition_id > 0) {
$sql = "(SELECT id, id as client_id, user_id, from_id, `event`, `date`, `dop_text`, 0 as `of_objects` FROM events_clients WHERE req_id = $requisition_id)
UNION (SELECT id, id as client_id, user_id, 0 as from_id, 'add' as `event`, `created_at` as `date`, '' as `dop_text`, '' as `of_objects`
FROM requisitions WHERE id = $requisition_id) ORDER BY `date` DESC";
}
if ($query = mysql_query($sql)) {
while($r_ev = mysql_fetch_assoc($query)) {
$master = "";
if ($r_ev['user_id'] != 0) {
$sql_m = "SELECT agency, manager, agency_name, first_name, last_name, middle_name FROM users WHERE id=".$r_ev['user_id'];
if ($q_m = mysql_query($sql_m)) {
$mstr = mysql_fetch_assoc($q_m);
if ($mstr['agency'])
$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
$master = "Агент " . trim($mstr['last_name'] . ' ' . $mstr['first_name'] . ' ' . $mstr['middle_name']);
} else {
$error = true;
$errors[] = mysql_error();
}
}
$from_master = "";
if ($r_ev['from_id'] != 0) {
$sql_m = "SELECT agency, manager, agency_name, first_name, last_name, middle_name FROM users WHERE id=".$r_ev['from_id'];
if ($q_m = mysql_query($sql_m)) {
$mstr = mysql_fetch_assoc($q_m);
if ($mstr['agency'])
$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
$from_master = "агент " . trim($mstr['last_name'] . ' ' . $mstr['first_name'] . ' ' . $mstr['middle_name']);
} else {
$error = true;
$errors[] = mysql_error();
}
}
$udate = strtotime($time_zone, strtotime($r_ev['date']));
$date_row = date('d', $udate) . ' ' .getRusMonth(date('m', $udate)) . ' ' . date('Y', $udate);
$dop_text = '';
if ($r_ev['event'] == 'add' && $r_ev['of_objects'] > 1) {
$name = '';
$sql_o = "SELECT nazv, adres FROM objects WHERE id = ".$r_ev['of_objects'];
if ($q_o = mysql_query($sql_o)) {
$r_o = mysql_fetch_assoc($q_o);
if (!empty($r['nazv']))
$name .= $r_o['nazv'];
if (!empty($r_o['adres'])) {
if(!empty($name))
$name .= ' ';
$name .= $r_o['adres'];
}
} else {
$error = true;
$errors[] = mysql_error();
}
if (!empty($name))
$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' => $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 {
$error = true;
$errors[] = mysql_error();
}
if (!$error && $has_return) {
return $history;
} else if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'history' => $history,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
if ($has_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'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function checkPhoneUnique($app, $get = null, $post = null, $has_return = false) {
$error = false;
$errors = [];
/*error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('display_errors', 1);*/
$is_unique = true;
$agent_name = null;
$phone = null;
if ($get['phone'])
$phone = trim($get['phone']);
$client_id = null;
if ($get['client_id'])
$client_id = intval($get['client_id']);
$funnel_id = null;
if ($get['funnel_id'])
$funnel_id = intval($get['funnel_id']);
if (($user_id = $_SESSION['id']) && !is_null($phone)) {
$phone = preg_replace("/[^0-9]/", "", $phone);
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('pdo');
$user = new \User();
$agency_id = $user->getAgencyIdForUser($user_id);
$agency_users = [];
$agency_users[] = $agency_id;
$managers = $user->getAllManagers($agency_id);
if ($managers) {
$departments = new \Department();
foreach ($managers as $manager) {
$agency_users[] = $manager['id'];
if ((int)$manager['role_id'] > 0 && (int)$manager['department_id'] > 0) {
$role_user = $departments->getRole((int)$manager['role_id']);
if ($role_user['role'] == 'admin_department') {
$menagerDep = \User::getDepManagers($role_user['department_id']);
foreach($menagerDep as $md){
if (!in_array($md['id'], $agency_users))
$agency_users[] = $md['id'];
$thisAgents = \User::getAgentsOfAgency($md['id'], true);
foreach($thisAgents as $da){
if (!in_array($da['id'], $agency_users)) {
$agency_users[] = $da['id'];
}
}
}
}
}
}
}
$agents = $user->getAllAgents($agency_id);
if ($agents) {
foreach ($agents as $agent) {
$agency_users[] = $agent['id'];
}
}
$agency_users = array_unique(array_values($agency_users));
$agency_users = array_map('intval', $agency_users);
$sql = "SELECT id AS idc,
phone,
if(who_work = 0, id_agent, who_work) AS user_id,
(
SELECT concat(last_name, ' ', first_name, ' ', middle_name)
FROM users WHERE id = if(clients.who_work = 0, clients.id_agent, clients.who_work)
) AS fio
FROM clients WHERE cancel = 0 AND (clients.phone='+{$phone}' OR clients.phone LIKE '%$phone%' OR clients.phone2 LIKE '%&quot;$phone&quot;%')";
if (!is_null($client_id))
$sql .= " AND clients.id != $client_id";
if (is_null($funnel_id))
$funnel_id = 0;
$sql .= " AND clients.funnel_id = $funnel_id";
if (!empty($agency_users))
$sql .= " AND (who_work IN (".implode(',', $agency_users).") OR id_agent IN (".implode(',', $agency_users)."))";
$sth = $pdo->prepare($sql);
if ($sth->execute()) {
$count = $sth->rowCount();
if ($count > 0) {
while ($row = $sth->fetch(\PDO::FETCH_ASSOC)) {
if (in_array((int)$row['user_id'], $agency_users)) {
$is_unique = false;
$agent_name = trim($row['fio']);
}
}
}
}
if (!$error && $has_return) {
return $is_unique;
} else if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'is_unique' => $is_unique,
'agent_name' => $agent_name,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
if ($has_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)$_SESSION['id'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function checkClientOwner($app, $get = null, $post = null) {
$client_id = (int)$app->request->get('client_id');
$response = ['has_owner' => false, 'owner_name' => ''];
if ($client_id > 0) {
$pdo = $app->container->get('mypdo');
$sql = "SELECT u.first_name, u.last_name, u.middle_name
FROM clients r
JOIN users u ON r.who_work = u.id
WHERE r.id = $client_id AND r.who_work > 0";
$result = $pdo->query($sql);
if ($pdo->num_rows($result) > 0) {
$row = $pdo->fetch_assoc($result);
$response['has_owner'] = true;
$response['owner_name'] = trim($row['last_name'] . ' ' . $row['first_name'] . ' ' . $row['middle_name']);
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode($response, JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function setClientTransfers($app, $get = null, $post = null) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode(stripslashes($body), true);
$clients_ids = $data['clients_ids'];
if (!is_array($clients_ids) && !empty($clients_ids))
$clients_ids = [intval($clients_ids)];
if (($user_id = $_SESSION['id']) && is_array($clients_ids)) {
$employee_id = $user_id;
if (isset($data['employee_id']))
$employee_id = intval($data['employee_id']);
if($employee_id == -1)
$employee_id = 0;
// Открываем соединение с БД и Сфинкс
$mdb = $app->container->get('mysql');
$cancel_transfer = (bool)$data['cancel_transfer'];
if (!$cancel_transfer) {
if (count($clients_ids) > 0) {
$sql = "SELECT * FROM `clients` WHERE `id` IN (".implode(',', $clients_ids).")";
if ($query = mysql_query($sql)) {
while($row = mysql_fetch_assoc($query)) {
$confirm = 0;
if ($employee_id == $user_id)
$confirm = 1;
if ($row['who_work'] != $employee_id) {
if (!mysql_query("UPDATE `clients` SET `who_work`='{$employee_id}', `confirm`={$confirm} WHERE `id`=".$row['id']))
$errors[] = mysql_error();
if ($confirm == 1) {
$sql = "UPDATE `user_client_events` SET `user_id`=".$employee_id." WHERE `client_id`=".$row['id']." and `type` != 'step' and `type` != 'file'";
if (!mysql_query($sql))
$errors[] = mysql_error();
} else if ($confirm == 0) {
$sql = "INSERT INTO `events_clients` (`user_id`, `client_id`, `from_id`, `event`) VALUES (".$user_id.", ".$row['id'].", ".$employee_id.", 'transmitted')";
if (!mysql_query($sql))
$errors[] = mysql_error();
if($employee_id == 0){
if (!mysql_query("UPDATE clients SET deleted=0 WHERE id=".$row['id'])){
$errors[] = mysql_error();
}
$dop_text = "Переведен в общие";
$sql_ev = "INSERT INTO events_clients (client_id, event, dop_text, user_id) VALUES ({$row['id']}, 'update', '{$dop_text}', {$user_id})";
if (!mysql_query($sql_ev)){
$errors[] = mysql_error();
}
}
}
}
// Определяем историю как просмотренную, чтобы сбросить счётчик (если пользователь не открывал её перед передачей другому сотруднику)
$sql = "UPDATE `events_clients` SET `viewed` = 1 WHERE `client_id` = ".$row['id']." AND `user_id` = '$user_id' AND `from_id` = '$user_id' AND (`event` = 'accepted' OR `event` = 'accepted_doer')";
if (!mysql_query($sql))
$errors[] = mysql_error();
}
} else {
$errors[] = mysql_error();
}
} else {
$error = true;
}
}
if (count($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' => (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();
}
public function setClientClose($app, $get = null, $post = null) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode(stripslashes($body), true);
$clients_ids = [];
if (isset($data['clients_ids']))
$clients_ids = $data['clients_ids'];
if (!is_array($clients_ids) && !empty($clients_ids))
$clients_ids = [intval($clients_ids)];
$denial = null;
if (isset($data['denial']))
$denial = intval($data['denial']);
$comment = null;
if (isset($data['comment']))
$comment = trim($data['comment']);
$is_deal = null;
if (isset($data['is_deal']))
$is_deal = boolval($data['is_deal']);
$commission = null;
if (isset($data['commission']))
$commission = intval($data['commission']);
if (($user_id = $_SESSION['id']) && is_array($clients_ids)) {
$clients_ids = array_unique($clients_ids);
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
if (count($clients_ids)) {
foreach($clients_ids as $client_id) {
if ($client_id) {
$client = new \Clients;
if ($is_deal === true)
$comment = "";
$data = [
'denial' => (!empty($denial)) ? $denial : 0,
'reason' => (!empty($comment)) ? $comment : "",
'id_del_client' => (int)$client_id,
'summa' => (!empty($commission)) ? $commission : 0,
'luck' => ($is_deal) ? 10 : false,
];
$results = $client->delReason($data);
if (!($results === true))
$errors = $results;
}
}
}
if (count($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' => (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();
}
public function setClientName($app, $get = null, $post = null) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode(stripslashes($body), true);
$client_id = [];
if (isset($data['client_id']))
$client_id = (int)$data['client_id'];
$client_name = [];
if (isset($data['client_name']))
$client_name = trim($data['client_name']);
if (($user_id = $_SESSION['id']) && $client_id && !empty($client_name)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$new_client_name = $client_name;
$sql = "UPDATE `clients` SET
`fio` = '$new_client_name'
WHERE `id` = '$client_id'";
if (!mysql_query($sql))
$errors[] = mysql_error();
if (count($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' => (int)$user_id,
'new_name' => $new_client_name
], 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 setClientPhone($app, $get = null, $post = null) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode(stripslashes($body), true);
$client_id = [];
if (isset($data['client_id']))
$client_id = (int)$data['client_id'];
$client_phone = [];
if (isset($data['client_phone']))
$client_phone = trim($data['client_phone']);
if (($user_id = $_SESSION['id']) && $client_id && !empty($client_phone)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$user = new \User();
$user->get($user_id);
$agencyId = $user->agencyId;
$new_client_phone = str_replace(['-','(',')', ' '], '', $client_phone);
$usersIds = array();
$usersIds[] = $agencyId;
$sql_users = "SELECT id FROM users WHERE id in (select id from users where id=$agencyId or id_manager=$agencyId or id_manager in
(select id from users where id_manager=$agencyId or id_manager in
(select id from users where id_manager=$agencyId)))";
$q_users = mysql_query($sql_users);
while($r_users = mysql_fetch_assoc($q_users)){
$usersIds[] = (int)$r_users['id'];
}
$sqlCheck = "SELECT `id` FROM `clients` WHERE (phone='$new_client_phone' OR id in (SELECT client_id FROM clients_phone2 WHERE phone = '$new_client_phone')) and (id_agent in (".implode(',', $usersIds).") or who_work in (".implode(',', $usersIds)."))";
$qCheck = mysql_query($sqlCheck);
if (mysql_num_rows($qCheck) > 0) {
$clintsIds = [];
while($rCheck = mysql_fetch_assoc($qCheck)){
$clintsIds[] = $rCheck['id'];
}
$errors['client_ids'] = $clintsIds;
} else {
$sql_dop = "INSERT INTO clients_phone2 (client_id, phone) VALUES ({$client_id}, '{$new_client_phone}')";
if (!mysql_query($sql_dop))
$errors[] = mysql_error();
$phones2 = [];
$sql_phones = "SELECT * FROM clients_phone2 WHERE client_id = {$client_id}";
$q_phones = mysql_query($sql_phones);
while($r_phones = mysql_fetch_assoc($q_phones)){
$phones2[] = $r_phones['phone'];
}
if(!empty($phones2)){
$p2 = htmlentities(json_encode($phones2));
$sql_cl = "UPDATE clients SET phone2='$p2' WHERE id={$client_id}";
if (!mysql_query($sql_cl))
$errors[] = mysql_error();
}
}
if (count($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' => (int)$user_id,
'new_name' => $new_client_name
], 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 setClientRestored($app, $get = null, $post = null) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode(stripslashes($body), true);
$clients_ids = [];
if (isset($data['clients_ids']))
$clients_ids = $data['clients_ids'];
if (!is_array($clients_ids) && !empty($clients_ids))
$clients_ids = [intval($clients_ids)];
if (($user_id = $_SESSION['id']) && is_array($clients_ids)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
if (count($clients_ids)) {
foreach($clients_ids as $client_id) {
if ($client_id) {
$client = new \Clients;
$results = $client->restore($client_id);
if (!($results === true))
$errors = $results;
}
}
}
if (count($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' => (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();
}
public function deleteClient($app, $get = null, $post = null) {
$error = false;
$errors = [];
$client_id = null;
if (isset($get['client_id']))
$client_id = (int)$get['client_id'];
if (($user_id = $_SESSION['id']) && !is_null($client_id)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('pdo');
$client = new \Clients;
$client->del($client_id);
if (count($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' => (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();
}
public function addEditClient($app, $get = null, $post = null) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode($body, true);
if (($user_id = $_SESSION['id'])) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('pdo');
$client_id = null;
if (isset($data["id"]))
$client_id = intval($data["id"]);
$client_inst = new \Clients();
global $WORK_TYPES;
global $TYPE_NEDV2_SORT;
global $ROLES_CLIENTS;
// Тип клиента
$types = [];
if (isset($data["types"])) {
foreach ($data["types"] as $type_id) {
if (isset($WORK_TYPES[$type_id]))
$types[] = (string)$WORK_TYPES[$type_id];
}
}
// Тип недвижимости
$estates = [];
if (isset($data["estates"])) {
$index = 1;
$estate_types = [];
foreach($TYPE_NEDV2_SORT as $key => $val) {
if (!empty($key)) {
$estate_types[$index] = $key;
}
$index++;
}
foreach ($data["estates"] as $type_id) {
$estates[] = $estate_types[$type_id];
}
}
// Роль клиента
$roles = [];
if (isset($data["roles"])) {
foreach ($data["roles"] as $role_id) {
if (isset($ROLES_CLIENTS[$role_id]))
$roles[] = (string)$ROLES_CLIENTS[$role_id];
}
}
// Телефоны
$phones = [];
if (isset($data["phones"])) {
foreach ($data["phones"] as $phone) {
$phones[] = '+' . preg_replace('/[^0-9]/', '', $phone);
}
}
$objects = (isset($data['objects'])) ? array_map('strval', $data['objects']) : [];
$birthday = null;
if (isset($data['birthday']) && !empty($data['birthday'])) {
if (!in_array($data['birthday'], ["1970-01-01", "1970-01-01 00:00:00"])) {
$birthday = date('Y-m-d H:i:s', strtotime($data['birthday']));
}
}
$who_work = (isset($data['employee_id'])) ? (int)$data['employee_id'] : $user_id;
if($who_work == -1) $who_work = 0;
$client = [
'id' => $client_id,
'fio' => $data['name'],
'email' => $data['email'],
'phone' => '+' . preg_replace('/[^0-9]/', '', $data['phone']),
'phone2' => !empty($phones) ? htmlspecialchars(json_encode($phones, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') : null,
'birthday' => (isset($data['birthday']) && !empty($data['birthday'])) ? $birthday : null,
'hot' => (int)$data['is_hot'],
'priority' => (int)$data['priority'],
'funnel_id' => (int)$data["funnel_id"],
'stage' => (int)$data['stage_id'],
'work_type' => !empty($types) ? htmlspecialchars(json_encode($types, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') : null,
'role' => !empty($roles) ? htmlspecialchars(json_encode($roles, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') : null,
'type' => !empty($estates) ? htmlspecialchars(json_encode($estates, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') : null,
'contracts' => !empty($data['contracts']) ? htmlspecialchars(json_encode($data['contracts'], JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') : null,
'objects' => !empty($objects) ? htmlspecialchars(json_encode($objects, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') : null,
'activities' => (isset($data['tags'])) ? array_values($data['tags']) : null,
'source' => (isset($data['source_id'])) ? (int)$data['source_id'] : null,
'employee' => (isset($data['partner_id'])) ? (int)$data['partner_id'] : null,
'who_work' => $who_work,
'confirm' => (isset($data['confirm'])) ? (int)$data['confirm'] : null,
'budget' => (isset($data['budget'])) ? (int)$data['budget'] : null,
'opis' => trim($data['description']),
];
// Ипотека
if (isset($data['hypothec'])) {
$hypothec = $data['hypothec'];
$banks = [];
if (isset($hypothec['banks'])) {
foreach ($hypothec['banks'] as $bank_id => $bank) {
$bank_id = $bank['id'];
unset($bank['id']);
$banks[$bank_id] = $bank;
}
}
$resolve = [];
if (isset($hypothec['resolve'])) {
foreach ($hypothec['resolve'] as $bank_id => $bank) {
$bank_id = $bank['id'];
unset($bank['id']);
$resolve[$bank_id] = $bank;
}
}
$client['rynok'] = (isset($hypothec['is_primary'])) ? 1 : 0;
$client['yes_object'] = (isset($hypothec['is_object'])) ? 1 : 0;
$client['jc'] = (isset($hypothec['complexes'])) ? htmlspecialchars(json_encode(array_map('strval', $hypothec['complexes']), JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') : null;
$client['summa_object'] = (isset($hypothec['object_price'])) ? (int)$hypothec['object_price'] : null;
$client['ante_pr'] = (isset($hypothec['first_pay'])) ? (int)$hypothec['first_pay'] : null;
$client['ante_rub'] = (isset($hypothec['first_pay_price'])) ? (int)$hypothec['first_pay_price'] : null;
$client['age'] = (isset($hypothec['borrower_age'])) ? (int)$hypothec['borrower_age'] : 0;
$client['yes_brak'] = (isset($hypothec['is_married'])) ? 1 : 0;
$client['yes_brak_doc'] = (isset($hypothec['is_married_contract'])) ? 1 : 0;
$client['yes_co_borrower'] = (isset($hypothec['is_co_borrower'])) ? 1 : 0;
$client['relationship'] = (isset($hypothec['co_borrower_relationship'])) ? trim($hypothec['co_borrower_relationship']) : null;
$client['co_borrower_fio'] = (isset($hypothec['co_borrower_name'])) ? trim($hypothec['co_borrower_name']) : null;
$client['co_borrower_age'] = (isset($hypothec['co_borrower_age'])) ? (int)$hypothec['co_borrower_age'] : 0;
$client['contacts'] = (isset($hypothec['co_borrower_contacts'])) ? trim($hypothec['co_borrower_contacts']) : null;
$client['yes_co_dohod'] = (isset($hypothec['is_income_taken'])) ? 1 : 0;
$client['co_borrower_dohod'] = (isset($hypothec['co_borrower_income'])) ? (int)$hypothec['co_borrower_income'] : null;
$client['income'] = (isset($hypothec['borrower_income'])) ? (int)$hypothec['borrower_income'] : 0;
$client['credit_load'] = (isset($hypothec['borrower_credit_load'])) ? (int)$hypothec['borrower_credit_load'] : 0;
$client['yes_doc'] = (isset($hypothec['is_contract'])) ? 1 : 0;
$client['number_doc'] = (isset($hypothec['contact_number'])) ? trim($hypothec['contact_number']) : '';
$client['date_doc'] = (isset($hypothec['contact_date'])) ? date('d.m.Y', strtotime($hypothec['contact_date'])) : '';
$client['doc_komis_pr'] = (isset($hypothec['contact_commission'])) ? (int)$hypothec['contact_commission'] : '';
$client['doc_komis'] = (isset($hypothec['contact_commission_price'])) ? (int)$hypothec['contact_commission_price'] : '';
//$client['confirm_ndfl'] = 0;
//$client['confirm_bank_form'] = 0;
//$client['confirm_two_docs'] = 0;
//$client['confirm_ip'] = 0;
//$client['confirm_buss_owner'] = 0;
//$client['bank_mother_capital'] = 0,
//$client['bank_state_support'] = 0,
//$client['bank_state_grant'] = 0,
//$client['bank_standart'] = 0,
$client['yes_bank'] = (isset($hypothec['is_bank'])) ? 1 : 0;
$client['date_bank'] = (isset($hypothec['bank_date'])) ? date('d.m.Y', strtotime($hypothec['bank_date'])) : '';
$client['yes_resolve'] = (isset($hypothec['is_resolve'])) ? 1 : 0;
$client['comment_resolve'] = (isset($hypothec['resolve_comment'])) ? trim($hypothec['resolve_comment']) : '';
$client['yes_issue'] = (isset($hypothec['is_issue'])) ? 1 : 0;
$client['rate_issue'] = (isset($hypothec['issue_rate'])) ? intval($hypothec['issue_rate']) : null;
$client['term_issue'] = (isset($hypothec['issue_term'])) ? intval($hypothec['issue_term']) : null;
$client['employee_bank'] = (isset($hypothec['bank_employee'])) ? trim($hypothec['bank_employee']) : '';
$client['banks'] = (count($banks)) ? htmlspecialchars(json_encode($banks, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') : null;
$client['resolve'] = (count($resolve)) ? htmlspecialchars(json_encode($resolve, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') : null;
$client['denial'] = (isset($hypothec['denial'])) ? htmlspecialchars(json_encode(array_map('strval', $hypothec['denial']), JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') : null;
$client['revisal'] = (isset($hypothec['revisal'])) ? htmlspecialchars(json_encode(array_map('strval', $hypothec['revisal']), JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') : null;
$client['bank_issue'] = (isset($hypothec['bank_issue'])) ? htmlspecialchars(json_encode($hypothec['bank_issue'], JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') : null;
$client['comment_ipoteka'] = (isset($hypothec['comment'])) ? trim($hypothec['comment']) : '';
}
//var_export($client) && die();
// Кредит
if (isset($data['credit'])) {
$credit = $data['credit'];
$client['bancks_credit'] = (isset($credit['product_id'])) ? htmlspecialchars(json_encode($credit['product_id'], JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') : 'NULL';
$client['summa_credit'] = (isset($credit['sum'])) ? intval($credit['sum']) : '';
$client['komissiya_credit'] = (isset($credit['commission'])) ? intval($credit['commission']) : '';
$client['cel_credit'] = (isset($credit['target'])) ? trim($credit['target']) : '';
$client['age_credit'] = (isset($credit['age'])) ? trim($credit['age']) : '';
$client['nagruzka_credit'] = (isset($credit['load'])) ? intval($credit['load']) : '';
$client['kol_nagruzka_credit'] = (isset($credit['load_cards'])) ? intval($credit['load_cards']) : '';
$client['dohod_credit'] = (isset($credit['income'])) ? intval($credit['income']) : '';
$client['dava_ndfl_credit'] = (isset($credit['verify_by_ndfl'])) ? 1 : 0;
$client['spravka_credit'] = (isset($credit['verify_by_inquiry'])) ? 1 : 0;
$client['phone_credit'] = (isset($credit['verify_by_phone'])) ? 1 : 0;
$client['podachi_credit'] = (isset($credit['query_count'])) ? intval($credit['query_count']) : '';
$client['kvartira_credit'] = (isset($credit['owner_by_flat'])) ? 1 : 0;
$client['dom_credit'] = (isset($credit['owner_by_house'])) ? 1 : 0;
$client['uchastok_credit'] = (isset($credit['owner_by_area'])) ? 1 : 0;
$client['car_credit'] = (isset($credit['owner_by_car'])) ? 1 : 0;
$client['not_own_credit'] = (isset($credit['not_owner'])) ? 1 : 0;
$client['yes_deduction_credit'] = (isset($credit['deduction'])) ? 'no_yes_deduction_credit' : '';
$client['propiska_credit'] = (isset($credit['registration'])) ? trim($credit['registration']) : '';
$client['overdue_credit'] = null;
if ((int)$credit['overdue'] === 1)
$client['overdue_credit'] = 'overdue_credit_yes';
else if ((int)$credit['overdue'] === 2)
$client['overdue_credit'] = 'overdue_credit_history';
else if ((int)$credit['overdue'] === 3)
$client['overdue_credit'] = 'overdue_credit_not';
$client['mfo_credit'] = null;
if ((int)$credit['mfo'] === 1)
$client['mfo_credit'] = 'mfo_credit_yes';
else if ((int)$credit['mfo'] === 2)
$client['mfo_credit'] = 'mfo_credit_history';
else if ((int)$credit['mfo'] === 3)
$client['mfo_credit'] = 'mfo_credit_not';
}
//Доп информация
$clients_dop_info = (isset($data['clients_dop_info'])) ? $data['clients_dop_info'] : [];
$client['persone_no_ip'] = (isset($clients_dop_info['persone_no_ip'])) ? intval($clients_dop_info['persone_no_ip']) : 0;
$client['passport'] = (isset($clients_dop_info['passport'])) ? htmlspecialchars($clients_dop_info['passport'], ENT_QUOTES, 'UTF-8') : '';
$client['date_of_issue_passport'] = (isset($clients_dop_info['date_of_issue_passport']) && strtotime($clients_dop_info['date_of_issue_passport']) > 0) ? date('d.m.Y', strtotime($clients_dop_info['date_of_issue_passport'])) : '';
$client['passport_issued_by'] = (isset($clients_dop_info['passport_issued_by'])) ? htmlspecialchars($clients_dop_info['passport_issued_by'], ENT_QUOTES, 'UTF-8') : '';
$client['birthplace'] = (isset($clients_dop_info['birthplace'])) ? htmlspecialchars($clients_dop_info['birthplace'], ENT_QUOTES, 'UTF-8') : '';
$client['registration_address'] = (isset($clients_dop_info['registration_address'])) ? htmlspecialchars($clients_dop_info['registration_address'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_snils'] = (isset($clients_dop_info['persone_snils'])) ? htmlspecialchars($clients_dop_info['persone_snils'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_nationality'] = (isset($clients_dop_info['persone_nationality'])) ? htmlspecialchars($clients_dop_info['persone_nationality'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_gender'] = (isset($clients_dop_info['persone_gender'])) ? intval($clients_dop_info['persone_gender']) : 0;
$client['persone_full_name'] = (isset($clients_dop_info['persone_full_name'])) ? htmlspecialchars($clients_dop_info['persone_full_name'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_short_name'] = (isset($clients_dop_info['persone_short_name'])) ? htmlspecialchars($clients_dop_info['persone_short_name'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_ogrn'] = (isset($clients_dop_info['persone_ogrn'])) ? htmlspecialchars($clients_dop_info['persone_ogrn'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_inn'] = (isset($clients_dop_info['persone_inn'])) ? htmlspecialchars($clients_dop_info['persone_inn'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_kpp'] = (isset($clients_dop_info['persone_kpp'])) ? htmlspecialchars($clients_dop_info['persone_kpp'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_legal_address'] = (isset($clients_dop_info['persone_legal_address'])) ? htmlspecialchars($clients_dop_info['persone_legal_address'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_fact_address'] = (isset($clients_dop_info['persone_fact_address'])) ? htmlspecialchars($clients_dop_info['persone_fact_address'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_info_bank'] = (isset($clients_dop_info['persone_info_bank'])) ? htmlspecialchars($clients_dop_info['persone_info_bank'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_name_bank'] = (isset($clients_dop_info['persone_name_bank'])) ? htmlspecialchars($clients_dop_info['persone_name_bank'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_bik_bank'] = (isset($clients_dop_info['persone_bik_bank'])) ? htmlspecialchars($clients_dop_info['persone_bik_bank'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_rs_bank'] = (isset($clients_dop_info['persone_rs_bank'])) ? htmlspecialchars($clients_dop_info['persone_rs_bank'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_kors_bank'] = (isset($clients_dop_info['persone_kors_bank'])) ? htmlspecialchars($clients_dop_info['persone_kors_bank'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_fio_rukovod'] = (isset($clients_dop_info['persone_fio_rukovod'])) ? htmlspecialchars($clients_dop_info['persone_fio_rukovod'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_powers'] = (isset($clients_dop_info['persone_powers'])) ? htmlspecialchars($clients_dop_info['persone_powers'], ENT_QUOTES, 'UTF-8') : '';
$client['persone_kod_podrazdelenia'] = (isset($clients_dop_info['persone_kod_podrazdelenia'])) ? htmlspecialchars($clients_dop_info['persone_kod_podrazdelenia'], ENT_QUOTES, 'UTF-8') : '';
//var_export($client) && die();
// Если у текущего пользователя включено право `hide_client_contacts`,
// и форма пришла с пустым phone/email или с самой маской — НЕ перезаписываем существующие данные.
// Пользователь с этим правом видит замаскированные значения в форме,
// и сабмит без реальных правок не должен затирать БД.
// Для пользователей БЕЗ права — поведение прежнее (пустое = очистка).
if (should_hide_contacts_for_current_user()) {
$rawPhone = isset($data['phone']) ? trim($data['phone']) : '';
$rawEmail = isset($data['email']) ? trim($data['email']) : '';
// Phone считаем "реальным" только если в нём ≥4 цифр (отсекает '', '+', '+7',
// и саму маску '+7 *** *** ** **' где остаётся одна цифра 7).
$phoneDigits = preg_match_all('/\d/', $rawPhone, $m);
if ($phoneDigits < 4) {
unset($client['phone']);
}
// Email считаем "реальным" если содержит '@' и НЕ содержит '*' (отсекает маску
// 'i***@m***.ru' и пустое значение).
if ($rawEmail === '' || strpos($rawEmail, '@') === false || strpos($rawEmail, '*') !== false) {
unset($client['email']);
}
// phone2 (доп. телефоны) — если массив $phones пустой, поле уже null,
// общая очистка ниже его удалит. Дополнительной логики не требуется.
}
// Очистка от пустых значений для $client
foreach ($client as $prop => $value) {
if (is_array($value)) {
foreach ($value as $key => $val) {
if (is_null($val) || (empty($val) && $val != 0)) {
unset($client[$prop][$key]);
}
}
} else {
if (is_null($value) || (empty($value) && $value != 0)) {
unset($client[$prop]);
}
}
}
if ($results = $client_inst->addEdit($client, false)) {
if (!is_int($results)) {
$error = true;
$errors[] = $results;
} else {
$client_id = $results;
// Заявки
$requisitions = (isset($data['requisitions'])) ? $data['requisitions'] : [];
if ($client_id && count($requisitions)) {
$req = new \Requisitions($pdo);
if ($results = $req->updateReq($requisitions, $client_id)) {
if ($results['success'] == false) {
$errors[] = $results['errors'];
}
}
}
// Доп. поля
$fields = (isset($data['fields'])) ? $data['fields'] : [];
if (!empty($client_id) && count($fields)) {
$field_inst = new \Fields($pdo);
$dataf = [];
foreach ($fields as $field => $value) {
$type = 1;
if (strpos(trim($field), "modelp_") !== false)
$type = 2;
$field_id = str_replace('model_', '', trim($field));
$field_id = str_replace('modelp_', '', $field_id);
if (!isset($dataf[(int)$field_id])) {
$dataf[(int)$field_id] = [
'type' => $type,
'value' => $value,
];
}
}
$fields_result = $field_inst->add_edit_data('clients', $client_id, $dataf, $user_id);
if ($fields_result['success'] !== true)
$error = true;
if (isset($fields_result['errors']))
$errors = array_merge($errors, $fields_result['errors']);
}
// Переменные для документов
$variables = (isset($data['variables'])) ? $data['variables'] : [];
if ($client_id && count($variables)) {
$docs = new \Docs();
$docs->saveDocFields($client_id, 'clients', $variables);
}
}
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,
'who_work' => $who_work,
'client_id' => (int)$client_id,
'client' => $client,
], 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)$_SESSION['id'],
'errors' => $errors
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}