container->get('mysql');
$manager_agents = null;
$agency_managers = [];
$department_managers = [];
$groups = [];
$employees = [];
// Текущий пользователь
$user = new \User;
$user->get($user_id);
$user->checkPermissions($user_id, false);
// Получаем список отделов
$dep = new \Department;
$departments = $dep->getDepartment($user_id);
$searchUserId = $user_id;
$list_type = '';
if(isset($get['list_type'])){
$list_type = $get['list_type'];
}
$onlyActive = true;
if (isset($get['active']))
$onlyActive = ($get['active'] == 'true');
$showBlocked = false;
if (isset($get['blocked']))
$showBlocked = ($get['blocked'] == 'true');
$selfExclude = false;
if (isset($get['self_exclude']))
$selfExclude = ($get['self_exclude'] == 'true');
$addGroups = false;
if (isset($get['add_groups']))
$addGroups = ($get['add_groups'] == 'true');
$includeIds = false;
if (isset($get['include_ids'])) {
if (count($get['include_ids'])) {
$includeIds = $get['include_ids'];
}
}
$list_type = 'clients';
if (isset($get['list_type'])) {
$list_type = $get['list_type'];
}
if ($showBlocked)
$onlyActive = false;
if (!$selfExclude && (!$includeIds || in_array($user_id, $includeIds))) {
$group_id = null;
if ($user->blocked)
$group_id = -1;
$employees[] = [
'id' => intval($user_id),
'name' => 'Я',
'department' => null,
'group_id' => $group_id,
'is_agent' => boolval($_SESSION['agent']),
'is_manager' => boolval($_SESSION['manager']),
];
}
$menuPermissions = $user->checkMenuPermissions();
if (($_SESSION['agency'] || $_SESSION['users_admin'] || $menuPermissions['menu_can_transfer_to_common'] == 1) && $list_type != 'objects') {
if ($list_type == 'objects') {
$agency_id = $_SESSION['agency_id'] ;
$sql_name_agency_id = "SELECT last_name, first_name, middle_name FROM users WHERE id = $agency_id";
if ($query_name_agency_id = mysql_query($sql_name_agency_id)) {
$name_agency_id_assoc = mysql_fetch_assoc($query_name_agency_id);
}
$name_agency_id = $name_agency_id_assoc['last_name']. ' '.$name_agency_id_assoc['first_name']. ' '.$name_agency_id_assoc['middle_name'];
$employees[] = [
'id' => $agency_id,
'name' => $name_agency_id,
'department' => null,
'group_id' => null,
'is_agent' => boolval($_SESSION['agent']),
'is_manager' => boolval($_SESSION['manager']),
];
} else {
$employees[] = [
'id' => -1,
'name' => 'Все агентство',
'department' => null,
'group_id' => null,
'is_agent' => boolval($_SESSION['agent']),
'is_manager' => boolval($_SESSION['manager']),
];
}
}
if ($user_id != $user->agencyId || $list_type == 'objects') {
$agency = $user->get($user->agencyId);
$group_id = null;
if ($agency->blocked)
$group_id = -1;
$employees[] = [
'id' => intval($user->agencyId),
'name' => $user->agencyName,
'department' => null,
'group_id' => $group_id,
'is_agent' => boolval($agency->agent),
'is_manager' => boolval($agency->manager),
];
}
$agentsOfManager = \User::getAllManagers($user->agencyId, $onlyActive);
if (isset($agentsOfManager)) {
foreach($agentsOfManager as $agent) {
$agent_id = (int)$agent['id'];
if ($user_id == $agent_id)
continue;
$role_id = $agent['role'];
$group_id = null;
if ($agent['blocked'])
$group_id = -1;
$employees[] = [
'id' => $agent_id,
'name' => trim($agent['last_name'] . ' ' . $agent['first_name'] . ' ' . $agent['middle_name']),
'department' => ($role_id > 0)
? $departments[$role_id]['role_name']
: null,
'group_id' => $group_id,
'is_agent' => boolval($agent['agent']),
'is_manager' => boolval($agent['manager']),
];
}
}
$agentsOfAgency = \User::getAllAgents($user->agencyId, $onlyActive);
if (isset($agentsOfAgency)) {
foreach($agentsOfAgency as $agent) {
$agent_id = (int)$agent['id'];
if ($user_id == $agent_id)
continue;
$role_id = $agent['role'];
$group_id = null;
if ($agent['blocked'])
$group_id = -1;
$employees[] = [
'id' => $agent_id,
'name' => trim($agent['last_name'] . ' ' . $agent['first_name'] . ' ' . $agent['middle_name']),
'department' => ($role_id > 0)
? $departments[$role_id]['role_name']
: null,
'group_id' => $group_id,
'is_agent' => boolval($agent['agent']),
'is_manager' => boolval($agent['manager']),
];
}
}
if (!$onlyActive || $showBlocked)
$groups[(int)'-1'] = 'Заблокированные/удаленные';
if (!$error && count($employees)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$sources = [
'success' => true,
'user_id' => (int)$user_id,
'list' => $employees
];
if ($addGroups)
$sources['groups'] = $groups;
$app->response->setBody(json_encode($sources, JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getResponsibles($app, $get = null, $post = null) {
$userIds = array();
$userId = $_SESSION['id'];
$mdb = $app->container->get('mysql');
$result = array();
$responsibles = array();
// Текущий пользователь
$user = new \User;
$user->get($userId);
$id = (int)$get['id'];
$section = $get['section'];
$userIds[] = $userId;
$who_work = 0;
if($id > 0){
// Найденный листинг парсера (offset-free): строки в objects нет — ни владельца, ни doers.
// Признак листинга — явный флаг is_external из запроса (id больше не диапазонный: el.id коллизит с objects.id).
// Ответственного выбираем по той же иерархии видимости, что и раздел «Задачи» (как на десктопе
// select_form_who_work_tasks.php): getUsersFilter вернёт подчинённых по правам (рядовой агент — только себя).
if($section == 'objects' && self::_request_flag($get, 'is_external')){
$cl = new \Clients();
$hierarchyIds = $cl->getUsersFilter(array(), $_SESSION['id'], $_SESSION['users_admin']);
if(is_array($hierarchyIds)){
foreach($hierarchyIds as $hid){
$userIds[] = (int)$hid;
}
}
} else {
$sql = "SELECT * FROM clients where id = {$id}";
if($section == 'requisitions'){
$sql = "SELECT * FROM requisitions where id = {$id}";
}
if($section == 'objects'){
$sql = "SELECT id, id_add_user as who_work FROM objects WHERE id = {$id}";
}
//echo $sql;
$q = mysql_query($sql);
$r = mysql_fetch_assoc($q);
if (isset($r['doers']) && !empty($r['doers'])) {
$doers = json_decode(html_entity_decode($r['doers']), true);
foreach ($doers as $user_id => $d){
if ($d == 1){
$userIds[] = (int)$user_id;
}
}
}
if($r['who_work'] > 0){
$userIds[] = (int)$r['who_work'];
$who_work = (int)$r['who_work'];
}
}
}
//Определение отделов
$sql_d = "SELECT d.name as dep_name, r.name as role_name, r.role, r.department_id, r.id FROM departments as d left join roles as r on d.id = r.department_id WHERE d.agency_id = ".$user->agencyId;
$q_d = mysql_query($sql_d);
$departments = array();
while($r_d = mysql_fetch_assoc($q_d)){
$departments[$r_d['id']] = $r_d;
}
$selected = '';
$userIds = array_unique($userIds);
$sql_users = "SELECT * FROM users WHERE id in (".implode(',',$userIds).") AND blocked = 0";
//echo $sql_users;
$q_users = mysql_query($sql_users);
while($r_user = mysql_fetch_assoc($q_users)){
$name = trim($r_user['last_name'] . ' ' . $r_user['first_name'] . ' ' . $r_user['middle_name']);
if($r_user['role_id'] > 0){
$name .= ' ('.$departments[$r_user['role_id']]['role_name']. ' ' . $departments[$r_user['role_id']]['dep_name'].')';
}
$responsibles[] = [
'id' => $r_user['id'],
'name' => $name,
];
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$userId,
'responsibles' => $responsibles,
'who_work' => $who_work,
'sql' => $sql,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getTypes($app, $get = null, $post = null, $need_return = false) {
global $OBJECT_TYPES;
global $WORK_TYPES;
global $REQ_TYPES;
global $SEARCH_TARGETS;
global $etaz_first_types;
global $TYPE_NEDV2_SORT;
global $BANK_PRODUKT;
$error = false;
$section = $get['section'];
if ($section && ($user_id = $_SESSION['id'])) {
$types = [];
switch ($section) {
case 'objects' :
foreach($OBJECT_TYPES as $key => $val) {
if (intval($key) > 0 && $key != 6) {
$types[] = ['id' => intval($key), 'name' => $val];
}
}
break;
case 'clients' :
foreach($WORK_TYPES as $key => $val) {
if (intval($key) > 0) {
$types[] = ['id' => intval($key), 'name' => $val];
}
}
break;
case 'search' :
case 'autosearch' :
foreach($SEARCH_TARGETS as $key => $val) {
if ($key == 4)
continue;
if (intval($key) > 0) {
$types[] = ['id' => intval($key), 'name' => $val];
}
}
$types[] = ['id' => 5, 'name' => 'Архив компании'];
if ($section == 'autosearch')
$types[] = ['id' => 6, 'name' => 'Собственники и объекты компании'];
break;
case 'requisitions' :
/*foreach($REQ_TYPES as $key => $val) {
if (intval($key) > 0) {
$types[] = ['id' => intval($key), 'name' => $val];
}
}*/
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
$requisitions_inst = new \Requisitions($pdo);
$users_inst = new \User();
$agency_id = $users_inst->getAgencyIdForUser($user_id);
$requisitions_inst->set_agencyId($agency_id);
$results = $requisitions_inst->get_type(false, true);
//var_dump($results);
//$types = $results['type'];
if (!empty($results['type'])) {
foreach ($results['type'] as $result) {
if ($result['order'] != -1 && $result['code'] != '-1' && !empty($result['name'])) {
$name_type = $result['name'];
if($result['archive'] == 1){
$name_type = $result['name']." (архивный)";
}
$types[] = [
'id' => intval($result['code']),
'heir' => intval($result['heir']),
'name' => $name_type,
'archive'=>$result['archive']
];
}
}
}
break;
case 'contract_types' :
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$user = new \User;
$user->get($user_id);
$agency_id = $user->getUserAgencyID();
$contracts = new \Contract();
$contracts->setAgencyId($agency_id);
$list = $contracts->getTypesName();
foreach($list as $item) {
$types[] = [
'id' => (int)$item['id'],
'name' => $item['type'],
'heir' => intval($item['heir']),
];
}
break;
case 'bank_products' :
foreach($BANK_PRODUKT as $key => $val) {
if (intval($key) > 0) {
$types[] = ['id' => intval($key), 'name' => $val];
}
}
break;
case 'operations' :
$types = [
[
'id' => 1,
'name' => 'Аренда'
], [
'id' => 2,
'name' => 'Продажа'
],
];
break;
case 'to_metro' :
$types = [
[
'id' => 1,
'name' => 'Пешком'
], [
'id' => 2,
'name' => 'На транспорте'
],
];
break;
case 'lease' :
$types = [
[
'id' => 2,
'name' => 'Длительно'
], [
'id' => 3,
'name' => 'Несколько месяцев'
], [
'id' => 1,
'name' => 'Посуточно'
],
];
break;
case 'first_floor' :
foreach($etaz_first_types as $key => $val) {
if (intval($key) > 0) {
$types[] = ['id' => intval($key), 'name' => $val];
}
}
break;
case 'estate_types' :
$index = 1;
foreach($TYPE_NEDV2_SORT as $key => $val) {
if (!empty($key)) {
$types[] = [
'id' => $index,
'name' => $val
];
}
$index++;
}
break;
case 'avito_room' :
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$sql = "SELECT * FROM avito_room_types ORDER BY name";
$rez = mysql_query($sql);
while($row = mysql_fetch_assoc($rez)) {
$types[] = [
'id' => (int)$row['id'],
'name' => $row['name']
];
}
break;
case 'deal_type' :
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$sql = "SELECT * FROM deal_type ORDER BY name";
$rez = mysql_query($sql);
while($row = mysql_fetch_assoc($rez)) {
$types[] = [
'id' => (int)$row['id'],
'name' => $row['name']
];
}
break;
case 'house_types' :
$mdb = $app->container->get('mysql');
$sql = "SELECT * FROM house_type ORDER BY name";
$rez = mysql_query($sql);
while($row = mysql_fetch_assoc($rez)) {
$types[] = [
'id' => (int)$row['id'],
'name' => $row['name']
];
}
break;
case 'house_materials' :
$mdb = $app->container->get('mysql');
$sql = "SELECT * FROM house_material ORDER BY name";
$rez = mysql_query($sql);
while($row = mysql_fetch_assoc($rez)) {
$types[] = [
'id' => (int)$row['id'],
'name' => $row['name']
];
}
break;
}
if (count($types)) {
if ($need_return) {
return $types;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'list' => $types
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getStatus($app, $get = null, $post = null) {
$errors = [];
$status = false;
$service = $get['service'];
if ($service) {
switch ($service) {
case 'api' :
$status = true;
/*if ($_SESSION['id'] == 5427)
$_SESSION['id'] = 5427;*/
break;
case 'mysql' :
try {
$pdo = $app->container->get('pdo');
$mdb = $app->container->get('mysql');
if ($pdo && $mdb)
$status = true;
} catch (Exception $e) {
$errors[] = $e;
}
break;
case 'sphinx' :
try {
$sphinx = $app->container->get('sphinx');
if ($sphinx)
$status = true;
} catch (Exception $e) {
$errors[] = $e;
}
$status = true;
break;
case 'sphinx2' :
try {
$sphinx2 = $app->container->get('sphinx2');
if ($sphinx2)
$status = true;
} catch (Exception $e) {
$errors[] = $e;
}
$status = true;
break;
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'status' => ($status) ? 'up' : 'down',
'service' => $service,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'service' => $service,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getTags($app, $get = null, $post = null, $need_return = false) {
$error = false;
if ($user_id = $_SESSION['id']) {
$pdo = $app->container->get('pdo');
$mdb = $app->container->get('mysql');
$list = [];
$user = new \User();
$user->get($user_id);
//$user->checkPermissions($user_id, false);
$agency_id = $user->getUserAgencyID();
if (boolval($get['with_managers'])) {
$sql = "SELECT * FROM `activities`
WHERE `user_id` = '".$user->id."' OR `manager_id` = '".$user->id."'";
if ($user->id_manager)
$sql .= " OR `manager_id` = '".$user->id_manager."' OR `user_id` = '".$user->id_manager."'";
if ($user->agencyId)
$sql .= " OR `manager_id` = '".$user->agencyId."' OR `user_id` = '".$user->agencyId."'";
} else {
$sql = "SELECT * FROM `activities` WHERE `user_id` = '".$user_id."' OR `manager_id` = '".$user_id."'";
if ($agency_id)
$sql .= " OR `manager_id` = '".$agency_id."' OR `user_id` = '".$agency_id."'";
}
$sql .= ' GROUP BY `id` ORDER BY `name`';
$sth = $pdo->prepare($sql);
if ($sth->execute()) {
while($row = $sth->fetch(\PDO::FETCH_BOTH)) {
if (intval($row["id"]) && !empty($row["name"])) {
$list[] = [
'id' => intval($row["id"]),
'name' => $row["name"],
'color' => $row["color"]
];
}
}
} else {
$error = true;
}
if (!$error) {
if ($need_return) {
return $list;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'count' => count($list),
//'$sql' => $sql,
'list' => $list
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getClients($app, $get = null, $post = null, $need_return = false) {
$error = false;
$errors = [];
if ($user_id = $_SESSION['id']) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$user = new \User();
$user->checkPermissions($user_id, false);
$agency_id = $_SESSION['agency_id'];
$menuPermissions = $user->checkMenuPermissions();
$clients = [];
$filters = [];
if (isset($get['filters']))
$filters = json_decode($get['filters'], true);
$only_active = true;
if (isset($get['only_active']))
$only_active = ($get['only_active'] == 'true');
$offset = null;
if (isset($get['offset']))
$offset = intval($get['offset']);
$search_query = '';
if (isset($get['search_query']))
$search_query = trim($get['search_query']);
// Проверяем точное совпадение по телефону (без учета иерархии)
if(!empty($search_query)) {
$phone_clean = preg_replace('/[\(\)\-\s]/', '', $search_query);
$sql_exact_phone = "SELECT `id`, `email`, `fio`, `phone`, `phone2`,
DATE_FORMAT(`date_add`, '%d.%m.%Y') AS `date_add`,
`objects`, `deleted`, `confirm`
FROM `clients`
WHERE cancel = 0 AND `phone` = '".mysql_real_escape_string($phone_clean)."'
LIMIT 1";
if ($rez = mysql_query($sql_exact_phone)) {
$exact_match = mysql_fetch_assoc($rez);
if($exact_match) {
$phones = [];
$phones_dop = [];
if (!empty($exact_match['phone']))
$phones[] = $exact_match['phone'];
if (!empty($exact_match['phone2']))
$phones = array_merge($phones, json_decode(html_entity_decode($exact_match['phone2'], ENT_QUOTES), true));
if (!empty($exact_match['phone2']))
$phones_dop = array_merge($phones_dop, json_decode(html_entity_decode($exact_match['phone2'], ENT_QUOTES), true));
// Маскируем телефоны клиента в массиве phones_dop до implode,
// если у текущего пользователя включено `hide_client_contacts`.
if (!empty($phones_dop)) {
foreach ($phones_dop as &$_pdop) {
$_pdop = mask_phone_value_if_needed($_pdop);
}
unset($_pdop);
}
$clientItem = [
'id' => (int)$exact_match['id'],
'name' => $exact_match['fio'],
'phone' => $exact_match['phone'],
'phones' => !empty($phones) ? $phones : null,
'phones_dop' => (!empty($phones_dop)) ? implode(', ', $phones_dop) : '',
'email' => !empty($exact_match['email']) ? $exact_match['email'] : null,
'date_add' => $exact_match['date_add']
];
// Маскируем phone/email/имя клиента, если у текущего пользователя
// включено право `user_permissions.hide_client_contacts`.
// Helper сам проверяет право — если выключено, ничего не делает.
mask_client_contacts_inplace($clientItem);
$response = [
'success' => true,
'user_id' => $user_id,
'count' => 1,
'list' => [$clientItem],
'exact_match' => true
];
if ($need_return) return $response;
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode($response, JSON_UNESCAPED_UNICODE));
$app->stop();
return;
}
}
}
$users = [(int)$user_id];
$managers = [(int)$agency_id];
$bd_usl = " AND cancel = 0";
$clients_ids = [];
$bd_managers = '';
$bd_user_j = '';
$searchUserId = $_SESSION['id'];
$adminDep = false;
$depClass = new \Department();
$dep_user = $depClass->getDepartment((int)$_SESSION['id']);
if ($_SESSION['users_admin']) {
$currentUser = new \User();
$currentUser->checkPermissions();
$searchUserId = $currentUser->agencyId;
} else if ($menuPermissions['menu_all_clients'] == 1) {
$currentUser = new \User();
$currentUser->checkPermissions();
$searchUserId = $currentUser->agencyId;
} else if($dep_user['role'] == 'manager_office'){
$currentUser = new \User();
$currentUser->checkPermissions();
$searchUserId = $dep_user['admin'];
$adminDep = true;
} else if($dep_user['role'] == 'manager_office_menager') {
$searchUserId = $_SESSION['id_manager'];
$adminDep = true;
}
if (!empty($search_query)) {
$phone = preg_replace('/[+\-\(\)\/\?,.;:%№!\s]/', '', $search_query);
$bd_usl .= " AND (`fio` LIKE '%$search_query%' OR `phone` LIKE '%$phone%' OR `email` LIKE '%$phone%')";
// $sql_users = "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)))";
$sql_users = "SELECT id FROM users WHERE id in (select id from users where id=$searchUserId or id_manager=$searchUserId or id_manager in
(select id from users where id_manager=$searchUserId or id_manager in
(select id from users where id_manager=$searchUserId)))";
if ($rez = mysql_query($sql_users)) {
while($r_users = mysql_fetch_assoc($rez)){
$users[] = (int)$r_users['id'];
}
}
$users = array_unique($users);
}
$bd_user = " (`who_work` IN (". implode(',', $users) .") or `id_agent` IN (". implode(',', $users) ."))";
if (!empty($filters['employees'])) {
$users = [];
$managers = [];
$employees = array_unique($filters['employees']);
foreach ($employees as $employee) {
if (strripos($employee, 'u'))
$users[] = preg_replace('/[^0-9]/', '', $employee);
if (strripos($employee, 'm'))
$managers[] = preg_replace('/[^0-9]/', '', $employee);
}
if ($managers) {
/*$bd_managers_j = " AND id_agent IN (SELECT id FROM `users` WHERE id IN (". implode(',', $managers) .") OR
id_manager IN (". implode(',', $managers) .") OR
id_manager IN (SELECT id FROM users WHERE id_manager IN (". implode(',', $managers) .")))";*/
$bd_managers = " IN (". implode(',', $managers) .")";
}
if ($users) {
$bd_user_j = " `who_work` IN (". implode(',', $users) .") OR
`id_agent` IN (SELECT `id` FROM `users` WHERE `id` IN (". implode(',', $users) .") OR
`id_manager` IN (". implode(',', $users) .") OR
`id_manager` IN (SELECT `id` FROM `users` WHERE `id_manager` IN (". implode(',', $users) .")))";
}
} else {
if ($menuPermissions['menu_all_clients'] == 1 ) {
$users[] = $agency_id;
}
$bd_user_j = " (`who_work` IN (". implode(',', $users) .") or `id_agent` IN (". implode(',', $users) ."))";
if (isset($get['client_id']))
$clients_ids[] = $get['client_id'];
elseif (isset($get['clients_ids']))
$clients_ids = (array)$get['clients_ids'];
if (count($clients_ids) > 0) {
$bd_usl = " `id` IN (" . implode(',', $clients_ids) . ") ";
$bd_user_j = '';
}
}
if (!empty($filters['types'])) {
$where = [];
$types = $filters['types'];
foreach ($types as $type) {
$where[] = "`work_type` LIKE '%" {$type}"%'";
}
$bd_usl .= " AND (".implode(" OR ",$where).")";
}
if (!empty($filters['tags'])) {
$tags_ids = $filters['tags'];
$bd_usl .= " AND `id` IN (
SELECT `client_id` FROM `clients_activities`
WHERE `activity_id` IN (" . implode(", ", $tags_ids) . ")
)";
}
if (!empty($filters['source'])) {
$sources = $filters['source'];
$where = [];
foreach ($sources as $source) {
if ($source == 0) {
$where[] = "`source` IS NULL";
$where[] = "`source` = ''";
$where[] = "`source` = 'null'";
} else {
$where[] = "`source` = ' {$source}'";
}
}
$bd_usl .= " AND (" . implode(" OR ", $where) . ")";
}
if (!empty($filters['clients_ids'])) {
$clients_ids = $filters['clients_ids'];
$bd_usl .= " AND `id` IN (" . implode(", ", $clients_ids) . ")";
}
if (!empty($filters['is_deleted']))
$bd_usl .= " AND `confirm` > 0 AND `deleted` = 1 ";
else if (empty($clients_ids))
$bd_usl .= " AND `confirm` > 0 ";
else if ($only_active)
$bd_usl .= " AND `deleted` <> 1 ";
if (in_array(6358, $managers) || in_array(93, $managers)) {
$sql = "SELECT `id`, `email`, `fio`, `phone`, `phone2`, DATE_FORMAT(`date_add`, '%d.%m.%Y') AS `date_add`, `objects`, `deleted`, `confirm`
FROM `clients`
WHERE (
(true $bd_user) OR
(`clients`.`who_work` = 0 AND `clients`.`id_agent` IN (
SELECT id FROM `users` WHERE `id` $bd_managers OR `id_manager` $bd_managers OR `id_manager` IN (
SELECT `id` FROM `users` WHERE `id_manager` $bd_managers))
)
) $bd_usl
ORDER BY `clients`.`id` DESC";
} else {
$sql = "SELECT `id`, `email`, `fio`, `phone`, `phone2`, DATE_FORMAT(`date_add`, '%d.%m.%Y') AS `date_add`, `objects`, `deleted`, `confirm`
FROM `clients`
WHERE $bd_user_j $bd_usl
ORDER BY `clients`.`id` DESC";
}
if ($offset)
$sql .= " LIMIT $offset, 10";
else if ($offset == 0)
$sql .= " LIMIT 0, 10";
else
$sql .= " LIMIT 100";
if ($rez = mysql_query($sql)) {
while($client = mysql_fetch_assoc($rez)) {
// Телефоны клиента
$phones = [];
$phones_dop = [];
if (!empty($client['phone']))
$phones[] = $client['phone'];
if (!empty($client['phone2']))
$phones = array_merge($phones, json_decode(html_entity_decode($client['phone2'], ENT_QUOTES), true));
if (!empty($client['phone2']))
$phones_dop = array_merge($phones_dop, json_decode(html_entity_decode($client['phone2'], ENT_QUOTES), true));
if (empty($phones))
$phones = null;
// Маскируем телефоны клиента в массиве phones_dop до implode,
// если у текущего пользователя включено `hide_client_contacts`.
if (!empty($phones_dop)) {
foreach ($phones_dop as &$_pdop) {
$_pdop = mask_phone_value_if_needed($_pdop);
}
unset($_pdop);
}
$clientItem = [
'id' => (int)$client['id'],
'name' => $client['fio'],
'phone' => $client['phone'],
'phones' => $phones,
'phones_dop' => (!empty($phones_dop)) ? implode(', ', $phones_dop) : '',
'email' => (!empty($client['email'])) ? $client['email'] : null,
'date_add' => $client['date_add'],
/*'objects' => $client['objects'],
'is_deleted' => boolval($client['deleted']),
'is_confirm' => boolval($client['confirm']),
'id_agent' => $client['id_agent'],
'who_work' => $client['who_work'],
'source' => $client['source'],*/
];
// Маскируем phone/email/имя клиента, если у текущего пользователя
// включено право `user_permissions.hide_client_contacts`.
// Helper сам проверяет право — если выключено, ничего не делает.
mask_client_contacts_inplace($clientItem);
$clients[] = $clientItem;
}
} else {
$error = true;
$errors[] = mysql_error();
}
if (!$error) {
$sources = [
'success' => true,
'user_id' => $user_id,
'count' => count($clients),
'list' => $clients,
'$sql' => $sql,
'$get' => $get,
];
if ($need_return) {
return $sources;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode($sources, JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getСommercialTypes($app, $get = null, $post = null) {
$error = false;
if ($user_id = $_SESSION['id']) {
$pdo = $app->container->get('pdo');
$list = [];
$sql = "SELECT * FROM commercial_object";
$sql .= ' GROUP BY `id` ORDER BY `name`';
$sth = $pdo->prepare($sql);
if ($sth->execute()) {
while($row = $sth->fetch(\PDO::FETCH_BOTH)) {
$list[] = ['id' => intval($row["id"]), 'name' => $row["name"]];
}
} else {
$error = true;
}
if (!$error && count($list)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'list' => $list
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getRegions($app, $get = null, $post = null) {
$error = false;
$sub_regions = false;
if (isset($get['sub_regions']))
$sub_regions = true;
if ($user_id = $_SESSION['id']) {
$pdo = $app->container->get('pdo');
$list = [];
if ($sub_regions)
$sql = "SELECT * FROM rf_regions ";
else
$sql = "SELECT * FROM rf_regions WHERE parent = 0";
$sql .= ' GROUP BY `id` ORDER BY `id`, `name`';
$sth = $pdo->prepare($sql);
if ($sth->execute()) {
while($row = $sth->fetch(\PDO::FETCH_BOTH)) {
$kladr = [];
if (intval($row["kladr"])) {
$kladr[] = $row["kladr"];
} else {
if (intval($row["id"]) == 1) { // Москва и Московская область
$kladr = [
'7700000000000',
'5000000000000'
];
} else if (intval($row["id"]) == 2) { // Санкт-Петербург и Ленинградская обл
$kladr = [
'7800000000000',
'4700000000000'
];
} else if (intval($row["id"]) == 3) { // Крым и Севастополь
$kladr = [
'9100000000000',
'9200000000000'
];
}
}
$list[] = [
'id' => intval($row["id"]),
'name' => $row["name"],
'kladr' => $kladr,
'code_id' => intval($row["code"]),
'parent_id' => intval($row["parent"]),
];
}
} else {
$error = true;
}
if (!$error && count($list)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'list' => $list
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getDistricts($app, $get = null, $post = null) {
$error = false;
$errors = [];
if ($user_id = $_SESSION['id']) {
$region_rf_id = null;
if (isset($get['region_id']))
$region_rf_id = $get['region_id'];
$list = [];
$groups = [];
$mdb = $app->container->get('mysql');
$region = [];
if ($region_rf_id) {
if (is_array($region_rf_id)) {
if (in_array(80, $region_rf_id))
$region_rf_id[] = 1;
if (in_array(81, $region_rf_id))
$region_rf_id[] = 2;
$sql = "SELECT rf_regions.* FROM rf_regions AS parent
JOIN rf_regions ON rf_regions.parent = parent.id
WHERE parent.id IN (" . implode(',', $region_rf_id) . ") ORDER BY id ASC";
} else {
$sql = "SELECT rf_regions.* FROM rf_regions AS parent
JOIN rf_regions ON rf_regions.parent = parent.id
WHERE parent.id = $region_rf_id ORDER BY id ASC";
}
} else {
$sql = "SELECT rf_regions.* FROM rf_regions AS parent
JOIN rf_regions ON rf_regions.parent = parent.id
LEFT JOIN users ON users.region_rf_id = parent.id
WHERE users.id = $user_id ORDER BY id ASC";
}
if ($rez = mysql_query($sql)) {
while($row = mysql_fetch_assoc($rez)) {
$region[] = $row;
}
} else {
$error = true;
$errors[] = mysql_error();
}
if (empty($region)) {
$region = [
[
'id' => 47,
'name' => 'Ленинградская обл',
'kladr' => '4700000000000',
'parent' => 94,
'code' => 47
], [
'id' => 78,
'name' => 'Санкт-Петербург',
'kladr' => '7800000000000',
'parent' => 94,
'code' => 78
]
];
}
if ($region[1]['code'] == 78) {
$sql = "SELECT * FROM rayon WHERE id IN (15,3,6,7,1,23,13,22,33,25,11,10,8,26,12,27,5,2,28,9) OR is_lo = 1 ORDER BY is_lo, rayon";
if ($rez = mysql_query($sql)) {
$group_id = (int)$region[1]['id'];
$group_name = 'Санкт-Петербург';
while($rayon = mysql_fetch_assoc($rez)) {
if ($rayon['is_lo'] == 1)
$group_name = 'Ленинградская область';
$list[] = ['id' => (int)$rayon['id'], 'name' => $rayon['rayon'], 'group_id' => (int)$group_id];
}
$groups[] = ['id' => $group_id, 'name' => $group_name];
} else {
$error = true;
$errors[] = mysql_error();
}
} else if ($region[1]['code'] == 77) {
$group_id = (int)$region[1]['id'];
$groups[] = ['id' => $group_id, 'name' => $region[1]['name']];
$sql = "SELECT * FROM rf_regions WHERE parent = $group_id";
if ($rez = mysql_query($sql)) {
if (mysql_num_rows($rez) > 0) {
while($sub_region = mysql_fetch_assoc($rez)) {
$group_id = $sub_region['id'];
$groups[] = ['id' => $group_id, 'name' => $sub_region['name']];
$sql = "SELECT * FROM rayon WHERE id IN (SELECT rayon_id FROM rf_region_rayons WHERE rf_region_id = $group_id)";
$rez_rayon = mysql_query($sql);
while ($rayon = mysql_fetch_assoc($rez_rayon)) {
$list[] = ['id' => (int)$rayon['id'], 'name' => $rayon['rayon'], 'group_id' => (int)$group_id];
}
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
} else {
$group_id = (int)$region[1]['id'];
$groups[] = ['id' => $group_id, 'name' => $region[1]['name']];
$sql = "SELECT * FROM rayon WHERE id IN (SELECT rayon_id FROM rf_region_rayons WHERE rf_region_id = $group_id)";
if ($rez = mysql_query($sql)) {
if (mysql_num_rows($rez) > 0) {
while($rayon = mysql_fetch_assoc($rez)) {
$list[] = ['id' => (int)$rayon['id'], 'name' => $rayon['rayon'], 'group_id' => (int)$group_id];
}
} else {
$list[] = ['id' => 0, 'name' => 'Весь город', 'group_id' => (int)$group_id];
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
if (!empty($region[0]['id']) && isset($group_id)) {
$sql = "SELECT * FROM rayon where id in (SELECT rayon_id FROM rf_region_rayons WHERE rf_region_id = ".$region[0]['id'].")";
if ($rez = mysql_query($sql)) {
if (mysql_num_rows($rez) > 0) {
while($rayon = mysql_fetch_assoc($rez)) {
$list[] = ['id' => (int)$rayon['id'], 'name' => $rayon['rayon'], 'group_id' => (int)$group_id];
}
} else {
$list[] = ['id' => 0, 'name' => 'Весь город', 'group_id' => (int)$group_id];
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
if (!is_array($region_rf_id)) {
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'count' => count($list),
'list' => $list,
'groups' => $groups,
'parent_region' => (int)$region[1]['parent'],
'region_type' => (int)$region[1]['id'],
], JSON_UNESCAPED_UNICODE));
} else {
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'count' => count($list),
'list' => $list,
'groups' => $groups,
'sql' => $sql,
], JSON_UNESCAPED_UNICODE));
}
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getMetro($app, $get = null, $post = null) {
$error = false;
$errors = [];
if ($user_id = $_SESSION['id']) {
$region_rf_id = null;
if (isset($get['region_id']))
$region_rf_id = $get['region_id'];
$list = [];
$mdb = $app->container->get('mysql');
$region = [];
if ($region_rf_id) {
if (is_array($region_rf_id)) {
$sql = "SELECT rf_regions.* FROM rf_regions AS parent
JOIN rf_regions ON rf_regions.parent = parent.id
WHERE parent.id IN (" . implode(',', $region_rf_id) . ") ORDER BY id ASC";
} else {
$sql = "SELECT rf_regions.* FROM rf_regions AS parent
JOIN rf_regions ON rf_regions.parent = parent.id
WHERE parent.id = $region_rf_id ORDER BY id ASC";
}
} else {
$sql = "SELECT rf_regions.* FROM rf_regions AS parent
JOIN rf_regions ON rf_regions.parent = parent.id
LEFT JOIN users ON users.region_rf_id = parent.id
WHERE users.id = $user_id ORDER BY id ASC";
}
if ($rez = mysql_query($sql)) {
while($row = mysql_fetch_assoc($rez)) {
$region[] = $row;
}
} else {
$error = true;
$errors[] = mysql_error();
}
if (empty($region)) {
$region[0] = array(
'id' => 47,
'name' => 'Ленинградская обл',
'kladr' => '4700000000000',
'parent' => 94,
'code' => 47
);
$region[1] = array(
'id' => 78,
'name' => 'Санкт-Петербург',
'kladr' => '7800000000000',
'parent' => 94,
'code' => 78
);
}
$sql = "SELECT * FROM metro WHERE region_rf_id = ".$region[0]['id'];
if (isset($region[1]))
$sql .=" OR region_rf_id = ".$region[1]['id'];
if ($rez = mysql_query($sql)) {
if (mysql_num_rows($rez) > 0) {
if ($region[1]['code'] !== 78) {
while ($metro = mysql_fetch_assoc($rez)) {
$list[] = ['id' => (int)$metro['id'], 'name' => $metro['metro']];
}
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'count' => count($list),
'list' => $list,
'sql' => $sql,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getHighway($app, $get = null, $post = null) {
$error = false;
$errors = [];
if ($user_id = $_SESSION['id']) {
$region_rf_id = null;
if (isset($get['region_id']))
$region_rf_id = $get['region_id'];
$list = [];
$mdb = $app->container->get('mysql');
$region = [];
if ($region_rf_id) {
$sql = "SELECT highways.* FROM highways
WHERE highways.region_id = $region_rf_id";
} else {
$sql = "SELECT highways.* FROM highways AS h
LEFT JOIN users ON users.region_rf_id = h.region_id
WHERE users.id = $user_id AND h.region_id=users.region_rf_id ORDER BY id ASC";
}
if ($rez = mysql_query($sql)) {
if (mysql_num_rows($rez) > 0) {
while ($highway = mysql_fetch_assoc($rez)) {
$list[] = ['id' => (int)$highway['cian_id'], 'name' => $highway['name']];
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'count' => count($list),
'list' => $list,
'sql' => $sql,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getLayouts($app, $get = null, $post = null) {
$error = false;
if ($user_id = $_SESSION['id']) {
$pdo = $app->container->get('pdo');
$list = [];
$sql = "SELECT * FROM layout_object";
$sql .= ' GROUP BY `id` ORDER BY `name`';
$sth = $pdo->prepare($sql);
if ($sth->execute()) {
while($row = $sth->fetch(\PDO::FETCH_BOTH)) {
$list[] = ['id' => intval($row["id"]), 'name' => $row["name"]];
}
} else {
$error = true;
}
if (!$error && count($list)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'list' => $list
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function is_see($app, $is_no_see, $users_no_see){
$mdb = $app->container->get('mysql');
$is_see = true;
$tempArrNoSee = json_decode($users_no_see, true);
if($is_no_see == 1 && !empty($users_no_see) && !empty($tempArrNoSee)){
$is_see = false;
$arrNoSeeUsers = array();
foreach($tempArrNoSee as $u){
if(strpos($u, 'all_') !== false){
$manId = str_replace('all_', '', $u);
$sql_u = "SELECT id FROM `users`
WHERE id = $manId OR
id_manager = $manId OR
id_manager IN (SELECT id FROM users WHERE id_manager = $manId)";
$q_u = mysql_query($sql_u);
while($r_u = mysql_fetch_row($q_u)){
$arrNoSeeUsers[] = (int)$r_u[0];
}
} else {
$arrNoSeeUsers[] = (int)$u;
}
}
if(in_array($_SESSION['id'], $arrNoSeeUsers)){
$is_see = true;
}
}
return $is_see;
}
public function getRoles($app, $get = null, $post = null) {
global $ROLES_CLIENTS;
$error = false;
$section = $get['section'];
if ($section && ($user_id = $_SESSION['id'])) {
$roles = [];
switch ($section) {
case 'clients' :
if ($_SESSION['agency_id'] == 7911 && !in_array("Страхование", $ROLES_CLIENTS))
$ROLES_CLIENTS[] = "Страхование";
if ($_SESSION['agency_id'] == 7911 && !in_array("Путевки", $ROLES_CLIENTS))
$ROLES_CLIENTS[] = "Путевки";
if ($_SESSION['agency_id'] == 7911 && !in_array("Юр.услуги", $ROLES_CLIENTS))
$ROLES_CLIENTS[] = "Юр.услуги";
foreach($ROLES_CLIENTS as $key => $val) {
if (intval($key) > 0) {
$roles[] = ['id' => intval($key), 'name' => $val];
}
}
break;
}
if (count($roles)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'list' => $roles
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getRequisitions($app, $get = null, $post = null) {
$error = false;
$errors = [];
if ($user_id = $_SESSION['id']) {
$requisitions = [];
$mdb = $app->container->get('mysql');
$users_ids[] = (int)$user_id;
$user = new \User();
$user->get($user_id);
if ($_SESSION['users_admin'])
$user_id = $user->getUserAgencyID();
$users_ids[] = $user_id;
if ($user->get($user_id)) {
if ($user->agency) {
if ($query = mysql_query("SELECT `id` FROM `users` WHERE `id_manager`='$user_id' AND `manager`=1")) {
while ($row = mysql_fetch_row($query)) {
if (!empty($row[0])) {
$users_ids[] = $row[0];
if ($query2 = mysql_query("SELECT `id` FROM `users` WHERE `id_manager`='$row[0]'")) {
while ($row2 = mysql_fetch_row($query2)) {
if (!empty($row[0]))
$users_ids[] = $row2[0];
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
} else if ($user->manager) {
if ($query = mysql_query("SELECT `id` FROM `users` WHERE `id_manager`='$user_id'")) {
while ($row = mysql_fetch_row($query)) {
if (!empty($row[0]))
$users_ids[] = $row[0];
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
}
$users_ids = array_unique($users_ids);
$bd_usl_managers = " AND `user_id` IN (" . implode(',', $users_ids) . ")";
$sql = "SELECT `id`, `name`, `client_id` FROM `requisitions` WHERE 1 $bd_usl_managers AND `deleted` <> 1";
if (isset($post['ids']) && count($post['ids'])) {
$sql = "SELECT `id`, `name`, `client_id` FROM `requisitions` WHERE `id` IN (" . implode(',', $post['ids']) . ")";
}
if ($query = mysql_query($sql)) {
while ($row = mysql_fetch_assoc($query)) {
$requisitions[] = [
'id' => (int)$row['id'],
'name' => $row['name'],
];
}
} else {
$error = true;
$errors[] = mysql_error();
}
if (count($requisitions)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'list' => $requisitions,
'errors' => $errors
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$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 getSources($app, $get = null, $post = null) {
$error = false;
if ($user_id = $_SESSION['id']) {
// Открываем соединение с БД
$pdo = $app->container->get('pdo');
$mdb = $app->container->get('mysql');
$user = new \User;
$user->get($user_id);
$sources = [];
$search = null;
$page = 1;
if (isset($get['page']))
$page = $get['page'];
// Number of records fetch
$numberOfRecords = 1000;
if (isset($get['searchTerm']))
$search = $get['searchTerm']; // Search text
if ($search == null || strpos("объекты нашей компании", strtolower($search)) !== false) {
$sources[] = array(
"id" => 10000,
"name" => "Объекты нашей компании",
"source_see" => 1
);
$numberOfRecords--;
}
$list = [];
$sql_where = " `user_id` = '".$user->id."' or `manager_id` = '".$user->id."'";
if ($user->id_manager)
$sql_where .= " or `manager_id` = '".$user->id_manager."' or `user_id` = '".$user->id_manager."'";
if ($user -> agencyId)
$sql_where .= " or `manager_id` = '".$user -> agencyId."' or `user_id` = '".$user -> agencyId."'";
if ($search == null)
$sqlCount = "SELECT COUNT(id) FROM `advertising_sources` WHERE $sql_where";
else
$sqlCount = "SELECT COUNT(id) FROM `advertising_sources` WHERE ($sql_where) AND source LIKE '%" . trim($search) . "%'";
$rez = mysql_query($sqlCount); // @todo: implement to PDO
$all_count = mysql_result($rez, 0);
$all_pages = ceil($all_count / $numberOfRecords);
$limit = ($page - 1) * $numberOfRecords;
if ($search == null) {
$sql = "SELECT *
FROM `advertising_sources`
WHERE $sql_where ORDER BY source, id
LIMIT $limit, $numberOfRecords";
} else {
$sql = "SELECT *
FROM `advertising_sources`
WHERE ($sql_where) AND source LIKE '%" . trim($search) . "%'
ORDER BY source, id LIMIT $limit, $numberOfRecords";
}
if ($rez = mysql_query($sql)) { // @todo: implement to PDO
while ($block = mysql_fetch_assoc($rez)) {
$block['source_see'] = 1;
if($this->is_see($app, $block['is_no_see'], $block['users_no_see']) === false){
$block['source_see'] = 0;
}
$list[] = $block;
}
} else {
$error = true;
}
// Read Data
foreach ($list as $item) {
$sources[] = [
"id" => intval($item['id']),
"name" => $item['source'],
"source_see" => $item['source_see']
];
}
if ($search == null || strpos("источник не выбран", strtolower($search)) !== false) {
$sources[] = [
"id" => 0,
"name" => "Источник не выбран",
"source_see" => 1
];
}
if (count($sources)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'total_count' => $all_count,
'list' => $sources
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getFunnels($app, $get = null, $post = null, $need_return = false) {
$error = false;
$errors = [];
if ($user_id = $_SESSION['id']) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$user = new \User();
$user->get($user_id);
$agency_id = $user->agencyId;
$funnels = [];
$section = $get['section']; // requisitions, clients
$filters = $get['filters'];
$use_counters = $get['use_counters'] || null;
if (!in_array($agency_id, [6841, 6426, 7384, 7478, 8353, 8867, 9588]))
$use_custom = true;
else
$use_custom = false;
$default = "Обычные";
$sql = "SELECT * FROM `funnel_default` WHERE `agency_id` = '$agency_id'";
if ($section == 'requisitions')
$sql = "SELECT * FROM `funnel_default` WHERE `agency_id` = '$agency_id'";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
$row = mysql_fetch_assoc($query);
if (!empty($row['name']))
$default = $row['name'];
if ($section == 'clients' && $row['is_client'] == 0)
$use_custom = false;
if ($section == 'requisitions' && $row['is_req'] == 0)
$use_custom = false;
}
} else {
$error = true;
$errors[] = mysql_error();
}
$new_ids = [];
$funnelCounts = [];
// Счётчики в воронках
if ($use_counters) {
if ($section == 'clients')
$_SESSION['new_transfers']['clients'] = null;
else if ($section == 'requisitions')
$_SESSION['new_transfers']['requisitions'] = null;
if ($section == 'clients') {
$bd_stage = "";
if ($filters['filter_stage_work']) {
if ($filters['is_confirm'] || $filters['stage_send']) {
$bd_stage = " AND `clients`.`deleted` <> '1'";
} else {
$bd_stage = " AND `clients`.`deleted` <> '1' AND `clients`.`confirm` > 0";
}
}
if ($filters['is_hot'])
$bd_stage .= " AND `clients`.`hot` = 1";
if (empty($bd_stage))
$bd_stage = " AND `clients`.`deleted` = '0'";
$sql1 = "SELECT `clients`.`funnel_id`, COUNT(DISTINCT `clients`.`id`) AS `count`
FROM `events_clients` AS `events`
LEFT JOIN `clients` AS `clients` ON `clients`.`id` = `events`.`client_id`
WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND
(`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 $bd_stage AND
(`clients`.`who_work` = '$user_id' OR `clients`.`doers` LIKE '%"".$user_id."":1%') AND
`clients`.`funnel_id` = 0
GROUP BY `clients`.`funnel_id`";
$sql1_list = "SELECT `clients`.`funnel_id`, `clients`.`id`
FROM `events_clients` AS `events`
LEFT JOIN `clients` AS `clients` ON `clients`.`id` = `events`.`client_id`
WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND
(`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 $bd_stage AND
(`clients`.`who_work` = '$user_id' OR `clients`.`doers` LIKE '%"".$user_id."":1%') AND
`clients`.`funnel_id` = 0";
$sql2 = "SELECT `clients`.`funnel_id`, COUNT(DISTINCT `clients`.`id`) AS `count`
FROM `events_clients` AS `events`
LEFT JOIN `clients` AS `clients` ON `clients`.`id` = `events`.`client_id`
JOIN `funnel` AS `funnel`
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 $bd_stage AND
(`clients`.`who_work` = '$user_id' OR `clients`.`doers` LIKE '%"".$user_id."":1%') AND
`clients`.`funnel_id` = `funnel`.`id` AND
`funnel`.`agency_id` = '$agency_id' AND `funnel`.`deleted` = 0
GROUP BY `clients`.`funnel_id`";
$sql2_list = "SELECT `clients`.`funnel_id`, `clients`.`id`
FROM `events_clients` AS `events`
LEFT JOIN `clients` AS `clients` ON `clients`.`id` = `events`.`client_id`
JOIN `funnel` AS `funnel`
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 $bd_stage AND
(`clients`.`who_work` = '$user_id' OR `clients`.`doers` LIKE '%"".$user_id."":1%') AND
`clients`.`funnel_id` = `funnel`.`id` AND
`funnel`.`agency_id` = '$agency_id' AND `funnel`.`deleted` = 0";
} else if ($section == 'requisitions') {
$sql1 = "SELECT `req`.`funnel_id`, COUNT(DISTINCT `req`.`id`) AS `count`
FROM `events_clients` AS `events`
LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `events`.`req_id`
WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND
(`events`.`event` = 'accepted' OR `events`.`event` = 'accepted_doer') AND
`events`.`viewed` = 0 AND `events`.`read` = 1 AND
(`req`.`confirm` = 1 OR `req`.`doers_confirm` = 1) AND
`events`.`client_id` = 0 AND `req`.`deleted` = 0 AND
(`req`.`who_work` = '$user_id' OR `req`.`doers` LIKE '%"".$user_id."":1%') AND
`req`.`funnel_id` = 0
GROUP BY `req`.`funnel_id`";
$sql1_list = "SELECT `req`.`funnel_id`, `req`.`id`
FROM `events_clients` AS `events`
LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `events`.`req_id`
WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND
(`events`.`event` = 'accepted' OR `events`.`event` = 'accepted_doer') AND
`events`.`viewed` = 0 AND `events`.`read` = 1 AND
(`req`.`confirm` = 1 OR `req`.`doers_confirm` = 1) AND
`events`.`client_id` = 0 AND `req`.`deleted` = 0 AND
(`req`.`who_work` = '$user_id' OR `req`.`doers` LIKE '%"".$user_id."":1%') AND
`req`.`funnel_id` = 0";
$sql2 = "SELECT `req`.`funnel_id`, COUNT(DISTINCT `req`.`id`) AS `count`
FROM `events_clients` AS `events`
LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `events`.`req_id`
JOIN `funnel` AS `funnel`
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
(`req`.`confirm` = 1 OR `req`.`doers_confirm` = 1) AND
`events`.`client_id` = 0 AND `req`.`deleted` = 0 AND
(`req`.`who_work` = '$user_id' OR `req`.`doers` LIKE '%"".$user_id."":1%') AND
`req`.`funnel_id` = `funnel`.`id` AND
`funnel`.`agency_id` = '$agency_id' AND `funnel`.`deleted` = 0
GROUP BY `req`.`funnel_id`";
$sql2_list = "SELECT `req`.`funnel_id`, `req`.`id`
FROM `events_clients` AS `events`
LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `events`.`req_id`
JOIN `funnel` AS `funnel`
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
(`req`.`confirm` = 1 OR `req`.`doers_confirm` = 1) AND
`events`.`client_id` = 0 AND `req`.`deleted` = 0 AND
(`req`.`who_work` = '$user_id' OR `req`.`doers` LIKE '%"".$user_id."":1%') AND
`req`.`funnel_id` = `funnel`.`id` AND
`funnel`.`agency_id` = '$agency_id' AND `funnel`.`deleted` = 0";
}
$res1 = mysql_query($sql1);
if (mysql_num_rows($res1)) {
while($counter = mysql_fetch_assoc($res1)) {
$funnelCounts[$counter['funnel_id']] = $counter['count'];
}
}
$res1_list = mysql_query($sql1_list);
if (mysql_num_rows($res1_list)) {
while($row = mysql_fetch_assoc($res1_list)) {
$new_ids[] = $row['id'];
}
}
$res2 = mysql_query($sql2);
if (mysql_num_rows($res2)) {
while($counter = mysql_fetch_assoc($res2)) {
$funnelCounts[$counter['funnel_id']] = $counter['count'];
}
}
$res2_list = mysql_query($sql2_list);
if (mysql_num_rows($res2_list)) {
while($row = mysql_fetch_assoc($res2_list)) {
$new_ids[] = $row['id'];
}
}
if (count($new_ids) > 0) {
if (($section == 'clients'))
$_SESSION['new_transfers']['clients'] = $new_ids;
else if (($section == 'requisitions'))
$_SESSION['new_transfers']['requisitions'] = $new_ids;
}
}
$is_default = false;
/*if ($use_custom) {
$is_default = true;
$funnels[] = [
'id' => 0,
'name' => $default,
'count' => ($funnelCounts[0] > 0) ? intval($funnelCounts[0]) : null,
'is_default' => $is_default
];
}
$sql = "SELECT * FROM `funnel` WHERE `agency_id` = '$agency_id'";
if ($section == 'clients')
$sql .= " AND `is_client` = 1";
elseif ($section == 'requisitions')
$sql .= " AND `is_req` = 1";
if (!empty($filters['is_deleted']))
$sql .= " AND `deleted` == 1";
else
$sql .= " AND `deleted` <> 1";
$sql .= " ORDER BY `id`";
if ($query = mysql_query($sql)) {
while($funnel = mysql_fetch_assoc($query)) {
$is_default_custom = false;
if (!$is_default && (int)$funnel['$funnel'] == 0) {
$is_default_custom = true;
$is_default = true;
}
$funnels[] = [
'id' => (int)$funnel['id'],
'name' => $funnel['name'],
'count' => ($funnelCounts[intval($funnel['id'])] > 0) ? intval($funnelCounts[intval($funnel['id'])]) : null,
'is_default' => $is_default_custom
];
}
} else {
$error = true;
$errors[] = mysql_error();
}*/
$funnelClass = new \Funnel();
$funnelClass->set_agency_id($agency_id);
$funnelClass->set_user_id($user_id);
$funnelsRaw = $funnelClass->get_funnels($section);
$funnels = array();
if (is_array($funnelsRaw)) {
foreach ($funnelsRaw as $rF) {
$is_default_custom = false;
if (!$is_default && (int)$rF['$funnel'] == 0) {
$is_default_custom = true;
$is_default = true;
}
$funnels[] = array(
'id' => (int)$rF['id'],
'name' => (isset($rF['name']) && $rF['name'] !== null && $rF['name'] !== '')
? (string)$rF['name']
: 'Обычные',
'count' => ($funnelCounts[intval($rF['id'])] > 0) ? intval($funnelCounts[intval($rF['id'])]) : null,
'is_default' => $is_default_custom
);
}
}
if (!$error) {
if ($need_return) {
return $funnels;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'count' => count($funnels),
'list' => $funnels
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getAllFunnelsData($app, $get = null, $post = null, $need_return = false) {
$error = false;
$errors = [];
$only_active = $get['only_active'] || true;
$section = $get['section']; // requisitions, clients
if ($user_id = $_SESSION['id']) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
$users_inst = new \User();
$agency_id = $users_inst->getAgencyIdForUser($user_id);
/*error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);*/
$items = [];
$response = [];
// Нулевая воронка
$sql = "SELECT * FROM `funnel_default` WHERE `agency_id` = {$agency_id}";
if ($query = $pdo->query($sql)) {
$default_steps = [
1 => [
'id' => 1,
'name' => 'Новый',
],
2 => [
'id' => 2,
'name' => 'В работе',
],
3 => [
'id' => 3,
'name' => 'Презентация',
],
4 => [
'id' => 4,
'name' => 'Показ',
],
5 => [
'id' => 5,
'name' => 'Бронь',
],
6 => [
'id' => 6,
'name' => 'Подаем на ипотеку',
],
7 => [
'id' => 7,
'name' => 'Сделка',
],
8 => [
'id' => 8,
'name' => 'Закрыт',
],
];
if ($pdo->num_rows($query)) {
$row = $pdo->fetch_assoc($query);
$name = 'Обычные';
if (!empty($row['name']))
$name = $row['name'];
$items[] = [
'id' => 0,
'name' => $name,
'is_default' => true,
'is_client' => (bool)$row['is_client'],
'is_req' => (bool)$row['is_req'],
'is_stage' => (bool)$row['is_stage'],
'is_show_funnels' => (bool)$row['is_show_funnels'],
'steps' => $default_steps,
'order' => 0,
];
} else {
$items[] = [
'id' => 0,
'name' => 'Обычные',
'is_default' => true,
'is_client' => true,
'is_req' => true,
'is_stage' => true,
'is_show_funnels' => true,
'steps' => $default_steps,
'order' => 0,
];
}
} else {
$error = true;
}
// Остальные (кастомные) воронки
if ($only_active)
$sql = "SELECT * FROM `funnel` WHERE `agency_id` = {$agency_id} AND `deleted` = 0";
else
$sql = "SELECT * FROM `funnel` WHERE `agency_id` = {$agency_id}";
if ($section == 'clients')
$sql .= " AND `is_client` = 1";
else if ($section == 'requisitions')
$sql .= " AND `is_req` = 1";
$sql .= " ORDER BY `id`";
if ($query = $pdo->query($sql)) {
if ($pdo->num_rows($query)) {
while($row = $pdo->fetch_assoc($query)) {
$row['date'] = date('d.m.Y H:i:s', strtotime($row['date_create']));
$row['role'] = htmlspecialchars_decode($row['role']);
$row['client_type'] = htmlspecialchars_decode($row['client_type']);
$row['main_step'] = '';
$row['is_default'] = 0;
// Этапы по воронкам
$sql = "SELECT * FROM `funnel_steps` WHERE `funnel_id` = ".$row['id']." AND deleted = 0 ORDER BY `main` DESC";
if ($steps = $pdo->query($sql)) {
if ($pdo->num_rows($steps)) {
$prev_steps = [];
$steps_data = [];
while($step = $pdo->fetch_assoc($steps)) {
$steps_data[(int)$step['id']] = $step;
}
foreach ($steps_data as $step_id => $step) {
$step['name_number'] = $step['name'];
if ($step['main'] == 1)
$step['name_number'] = '1. '.$step['name'];
else if ($step['order_number'] > 0)
$step['name_number'] = $step['order_number'].'. '.$step['name'];
if (!empty($step['next_step'])) {
$next_steps_ids = json_decode(html_entity_decode($step['next_step']), ENT_QUOTES);
foreach ($next_steps_ids as $next_step_id) {
$prev_steps[(int)$next_step_id][] = ['id' => (int)$step['id'], 'name' => $step['name']];
}
}
$row['branches'][$step['branch']][$step['id']] = self::clearInputArray($step);
$row['steps'][$step['id']] = self::clearInputArray($step);
if (!empty($row['steps'][$step['id']]['users_mes']))
$row['steps'][$step['id']]['users_mes'] = json_decode($row['steps'][$step['id']]['users_mes'], true);
if (!empty($row['steps'][$step['id']]['arr_next_steps'])) {
$arr_next_steps = json_decode($row['steps'][$step['id']]['arr_next_steps'], true);
$row['steps'][$step['id']]['arr_next_steps'] = [];
if (is_array($arr_next_steps)) {
foreach ($arr_next_steps as $arr_next_step) {
if (!empty($arr_next_step['id'])) {
$next_step = $arr_next_step['id'];
$row['steps'][$step['id']]['arr_next_steps'][] = [
'id' => (int)$next_step['id'],
'name' => trim($next_step['name'])
];
}
}
}
} else {
$row['steps'][$step['id']]['arr_next_steps'] = [];
$next_steps_ids = json_decode(html_entity_decode($step['next_step']), ENT_QUOTES);
foreach ($next_steps_ids as $next_step_id) {
$next_step = $steps_data[$next_step_id];
if (!empty($next_step)) {
$row['steps'][$step['id']]['arr_next_steps'][] = ['id' => (int)$next_step['id'], 'name' => $next_step['name']];
}
}
}
if (!empty($prev_steps[(int)$step['id']]))
$row['steps'][$step['id']]['arr_prev_steps'] = $prev_steps[(int)$step['id']];
else
$row['steps'][$step['id']]['arr_prev_steps'] = [];
$files = [];
$sql = "SELECT * FROM `funnel_files` WHERE `etap_id` = '".$step['id']."' AND `funnel_id` = ".$row['id'];
if ($query_files = $pdo->query($sql)) {
if ($pdo->num_rows($query_files)) {
while($file_row = $pdo->fetch_assoc($query_files)) {
$path = "https://uf.joywork.ru/upload/funnels/".$row['id']."/".$file_row['guid'].".".$file_row['type'];
$files[] = ['guid' => $file_row['guid'], 'isUpload' => true, 'uploads' => false, 'name' => $file_row['name']];
}
}
}
$row['steps'][$step['id']]['files'] = $files;
$row['main_steps'][] = ['id' => $step['id'], 'name' => $step['name']];
if ($step['main'] == 1)
$row['main_step'] = ['id' => $step['id'], 'name' => $step['name']];
}
}
} else {
$error = true;
}
$items[] = $row;
}
}
} else {
$error = true;
}
if (!empty($items)) {
foreach($items as $item) {
$steps = [];
foreach($item['steps'] as $step_id => $step) {
$steps[] = [
'id' => (int)$step_id,
'name' => $step['name'],
'prev_steps' => (!empty($step['arr_prev_steps'])) ? $step['arr_prev_steps'] : ((!empty($default_steps[(int)$step_id-1]) && $item['is_default']) ? [$default_steps[(int)$step_id-1]] : null),
'next_steps' => (!empty($step['arr_next_steps'])) ? $step['arr_next_steps'] : ((!empty($default_steps[(int)$step_id+1]) && $item['is_default']) ? [$default_steps[(int)$step_id+1]] : null),
'files' => (!empty($step['files'])) ? $step['files'] : [],
'tasks' => (!empty($step['tasks_list'])) ? json_decode($step['tasks_list']) : null,
'fields' => (!empty($step['pole_end_list'])) ? json_decode($step['pole_end_list']) : null,
'doers' => (!empty($step['doers'])) ? json_decode($step['doers']) : [null],
'is_next_variable' => ($step['next_step_change'] === "Зависит от поля Ветвление этапов"),
];
}
$response[] = [
'id' => (int)$item['id'],
'name' => trim($item['name']),
'order' => (!empty($item['order_number'])) ? (int)$item['order_number'] : 0,
'is_client' => (bool)$item['is_client'],
'is_default' => (bool)$item['is_default'],
'is_deleted' => (bool)$item['deleted'],
'is_req' => (bool)$item['is_req'],
'steps' => $steps,
'client_types' => (!empty($item['client_type'])) ? json_decode($item['client_type']) : null,
'roles' => (!empty($item['role'])) ? json_decode($item['role']) : null,
'agency_id' => (int)$item['agency_id'],
'created_by' => (int)$item['user_id'],
'created_at' => $item['date_create'],
];
}
}
if (!$error) {
if ($need_return) {
return $response;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'list' => $response,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getList($app, $get = null, $post = null, $need_return = false) {
$error = false;
$errors = [];
if ($user_id = $_SESSION['id']) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$sql = "";
$list = [];
$section = $get['section'];
switch ($section) {
case 'rooms_count' :
$ROOMS_COUNT = [
1 => "1 комн.",
2 => "2 комн.",
3 => "3 комн.",
4 => "4+ комн.",
5 => "Студия",
];
$list = [];
foreach($ROOMS_COUNT as $key => $value) {
$list[$key] = [
'id' => $key,
'name' => $value
];
}
break;
case 'complexes':
$sql = "SELECT `id`, `name` FROM `blocks` ORDER BY `name`";
break;
case 'banks_list':
$sql = "SELECT `id`, `name` FROM `banks` ORDER BY `name`";
break;
case 'denial_work':
{
$user = new \User;
$user->get($user_id);
$agency_id = $user->agencyId;
$sql = "SELECT `id`, `name` FROM `denial_work` WHERE (agency_id = 0 or agency_id={$agency_id}) and del = 0";
}
break;
case 'floor_materials':
$sql = "SELECT `id`, `name` FROM `floor_material`";
break;
case 'house_categories':
$sql = "SELECT `id`, `name` FROM `house_category`";
break;
case 'commerce_portal':
$sql = "SELECT `id`, `name` FROM `commerc_portal`";
break;
case 'commerce_purpose':
$sql = "SELECT `id`, `name` FROM `commerc_purpose`";
break;
case 'commerce_land_categories':
$sql = "SELECT `id`, `name` FROM `commerc_land_category`";
break;
case 'commerce_permitted_use':
$sql = "SELECT `id`, `name` FROM `commerc_permitted_use`";
break;
case 'commerce_electricity':
$sql = "SELECT `id`, `name` FROM `commerc_electricity`";
break;
case 'electricity_types':
$sql = "SELECT `id`, `name` FROM `electricity_type` order by `id`";
break;
case 'commerce_gas':
$sql = "SELECT `id`, `name` FROM `commerc_gas`";
break;
case 'gas_types':
$sql = "SELECT `id`, `name` FROM `gas_type` order by `id`";
break;
case 'commerce_water':
$sql = "SELECT `id`, `name` FROM `commerc_gas`";
break;
case 'commerce_sewage':
$sql = "SELECT `id`, `name` FROM `commerc_gas`";
break;
case 'sewerage_types':
$sql = "SELECT `id`, `name` FROM `sewerage_type` order by `id`";
break;
case 'commerce_driveways':
$sql = "SELECT `id`, `name` FROM `commerc_driveways`";
break;
case 'commerce_services':
$sql = "SELECT `id`, `name` FROM `commerc_services`";
break;
case 'building_types' :
$sql = "SELECT `id`, `name` FROM `commerc_building_type`";
break;
case 'building_classes' :
$sql = "SELECT `id`, `name` FROM `commerc_building_class`";
break;
case 'houseline_types' :
$sql = "SELECT `id`, `name` FROM `commerc_houselinetype`";
break;
case 'building_categories' :
$sql = "SELECT `id`, `name` FROM `commerc_building_category`";
break;
case 'entrance_types' :
$sql = "SELECT `id`, `name` FROM `commerc_opened`";
break;
case 'building_ventilations' :
$list = [
[
'id' => 0,
'name' => 'Нет',
], [
'id' => 1,
'name' => 'Естественная',
], [
'id' => 2,
'name' => 'Приточная',
],
];
break;
case 'periods' :
$list = [
[
'id' => 1,
'name' => 'Сегодня',
], [
'id' => 2,
'name' => 'Неделя',
], [
'id' => 3,
'name' => 'Месяц',
], [
'id' => 4,
'name' => 'Последние 30 дней',
], [
'id' => 5,
'name' => 'Квартал',
], [
'id' => 6,
'name' => 'Последние 90 дней',
], [
'id' => 7,
'name' => 'Год',
], [
'id' => 8,
'name' => 'Все время',
], [
'id' => 9,
'name' => 'Период',
],
];
break;
case 'building_conditioning' :
$list = [
[
'id' => 0,
'name' => 'Нет',
], [
'id' => 1,
'name' => 'Местное',
], [
'id' => 2,
'name' => 'Центральное',
],
];
break;
case 'building_heating' :
$list = [
[
'id' => 0,
'name' => 'Нет',
], [
'id' => 1,
'name' => 'Автономное',
], [
'id' => 2,
'name' => 'Центральное',
],
];
break;
case 'building_firefighting' :
$list = [
[
'id' => 0,
'name' => 'Нет',
], [
'id' => 1,
'name' => 'Гидрантная',
], [
'id' => 2,
'name' => 'Спринклерная',
], [
'id' => 3,
'name' => 'Порошковая',
], [
'id' => 4,
'name' => 'Газовая',
], [
'id' => 5,
'name' => 'Сигнализация',
],
];
break;
case 'garages' :
$sql = "SELECT `id`, `name` FROM `garage_type`";
break;
case 'garages_types' :
$sql = "SELECT `id`, `name` FROM `garage_vid`";
break;
case 'boxes_types' :
$list = [
[
'id' => 1,
'name' => 'Кирпичный',
], [
'id' => 2,
'name' => 'Металлический',
], [
'id' => 3,
'name' => 'Железобетонный',
],
];
break;
case 'commerce_status' :
$sql = "SELECT `id`, `name` FROM `commerc_status`";
break;
case 'commerce_specifications' :
$sql = "SELECT `id`, `name` FROM `commerc_specifications`";
break;
case 'commerce_infrastructures' :
$sql = "SELECT `id`, `name` FROM `commerc_infrastructure` WHERE id < 27";
break;
case 'commerce_infrastructures2' :
$sql = "SELECT `id`, `name` FROM `commerc_infrastructure` WHERE `vid` = 1";
break;
case 'commerce_infrastructures3' :
$sql = "SELECT `id`, `name` FROM `commerc_infrastructure` WHERE `vid1` = 1";
break;
case 'sale_types' :
$list = [
[
'id' => 1,
'name' => 'Договор уступки права требования',
], [
'id' => 2,
'name' => 'Договор ЖСК',
], [
'id' => 3,
'name' => 'Свободная продажа',
], [
'id' => 4,
'name' => '214-ФЗ',
], [
'id' => 5,
'name' => 'Договор инвестирования',
], [
'id' => 6,
'name' => 'Предварительный договор купли-продажи',
],
];
break;
case 'legal_address' :
$list = [
[
'id' => 1,
'name' => 'Предоставляется',
], [
'id' => 2,
'name' => 'Не предоставляется',
],
];
break;
case 'decoration_types' :
$sql = "SELECT `id`, `name` FROM `avito_decoration_types` ORDER BY `id`";
break;
case 'flat_types' :
$sql = "SELECT `id`, `name` FROM `zipal_new_flat_type` ORDER BY `id`";
break;
case 'investor_types' :
$sql = "SELECT `id`, `name` FROM `investor_type` ORDER BY `id`";
break;
case 'access' :
$list = [
[
'id' => 1,
'name' => 'Свободный',
], [
'id' => 2,
'name' => 'Пропускная система',
],
];
break;
case 'conditions' :
$sql = "SELECT `id`, `name` FROM `commer_condition` ORDER BY `id`";
break;
case 'furnitures' :
$list = [
[
'id' => 1,
'name' => 'Нет',
], [
'id' => 2,
'name' => 'Есть',
],
];
break;
case 'layouts' :
$sql = "SELECT `id`, `name` FROM `layout_object` ORDER BY `id`";
break;
case 'occupieds' :
$list = [
[
'id' => 1,
'name' => 'Не занято',
], [
'id' => 2,
'name' => 'Занято',
],
];
break;
case 'property_types' :
$sql = "SELECT `id`, `name` FROM `property_type` ORDER BY `id`";
break;
case 'rent_house_types' :
$sql = "SELECT `id`, `name` FROM `house_type` ORDER BY `id`";
break;
case 'wall_types' :
$sql = "SELECT `id`, `name` FROM `wall_type` ORDER BY `id`";
break;
case 'house_wcs_types' :
$sql = "SELECT `id`, `name` FROM `house_wcs_type` ORDER BY `id`";
break;
case 'land_purposes_types' :
$sql = "SELECT `id`, `name` FROM `land_purpose` ORDER BY `id`";
break;
case 'shape_types' :
$sql = "SELECT `id`, `name` FROM `shape_type` ORDER BY `id`";
break;
case 'plumbing_types' :
$sql = "SELECT `id`, `name` FROM `plumbing_type` ORDER BY `id`";
break;
case 'relief_types' :
$sql = "SELECT `id`, `name` FROM `relief_type` ORDER BY `id`";
break;
case 'land_usage_types' :
$sql = "SELECT `id`, `name` FROM `land_usage_type` ORDER BY `id`";
break;
case 'lease_deposit_types' :
$sql = "SELECT `id`, `name` FROM `lease_deposit` ORDER BY `id`";
break;
case 'window_view_types' :
$sql = "SELECT `id`, `name` FROM `window_view` ORDER BY `id`";
break;
case 'renovation_types' :
$sql = "SELECT `id`, `name` FROM `renovation` ORDER BY `id`";
break;
case 'bathroom_types' :
$sql = "SELECT `id`, `name` FROM `bath_type` ORDER BY `id`";
break;
case 'hot_water_types' :
$sql = "SELECT `id`, `name` FROM `hot_water` ORDER BY `id`";
break;
case 'parking_types' :
$sql = "SELECT `id`, `name` FROM `parking_type` ORDER BY `id`";
break;
case 'parking_types1' :
$sql = "SELECT * FROM parking_type where vid = 0 ORDER BY id";
break;
case 'parking_types2' :
$sql = "SELECT * FROM parking_type where vid1 = 1 ORDER BY id";
break;
case 'parking_types3' :
$sql = "SELECT * FROM parking_type where vid = 1 ORDER BY id";
break;
case 'vat_types' :
$sql = "SELECT `id`, `name` FROM `vat_type` ORDER BY `id`";
break;
case 'wet_spots' :
$list = [
[
'id' => 1,
'name' => '1',
], [
'id' => 2,
'name' => '2',
], [
'id' => 3,
'name' => '3',
], [
'id' => 4,
'name' => '4',
], [
'id' => 5,
'name' => 'Нет',
],
];
break;
case 'countries' :
$sql = "SELECT * FROM `country_list` WHERE `id` = 171 UNION SELECT * FROM `country_list` WHERE `id` <> 1 ORDER BY `id`";
break;
case 'cottage_village' :
$sql = "SELECT * FROM cottage_village order by id";
}
if (!isset($list) || empty($list)) {
$list = array();
}
if (!empty($sql)) {
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_assoc($query)) {
if($section == 'cottage_village') {
if(!isset($list[$row['region_id']])) $list[$row['region_id']] = array();
$list[$row['region_id']][] = [
'value' => (int)$row['id'],
'name' => trim($row['name']),
];
} else
$list[] = [
'id' => (int)$row['id'],
'name' => trim($row['name']),
];
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
if (!$error) {
if (count($list) && $section == 'denial_work') {
$list[] = [
'id' => 0,
'name' => 'Другое',
];
}
if ($need_return) {
return $list;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'count' => count($list),
'list' => $list
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getLists($app, $get = null, $post = null) {
$lists = [];
if ($user_id = $_SESSION['id']) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$sections = $get['sections'];
foreach ($sections as $section) {
$list = $this->getList($app, ['section' => $section], null, true);
if ($list)
$lists[$section] = $list;
else
$lists[$section] = false;
}
}
if (count($lists)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'lists' => $lists
], JSON_UNESCAPED_UNICODE));
$app->stop();
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getFiles($app, $get = null, $post = null) {
$error = false;
$errors = [];
$source_id = null;
if (isset($get['source_id']))
$source_id = (int)$get['source_id'];
$section = null;
if (isset($get['section']))
$section = trim($get['section']);
if (($user_id = $_SESSION['id']) && $source_id && $section) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
$list = [];
$row = [];
$field = '';
$table = 'user_client_events';
if ($section == 'clients') {
$field = 'client_id';
$table = 'user_client_events';
} else if ($section == 'requisitions') {
$field = 'req_id';
$table = 'user_client_events';
} else if ($section == 'objects') {
$field = 'object_id';
$table = 'user_object_events';
}
if (!empty($field) && !empty($table)) {
$protocol = (self::is_ssl()) ? 'https://' : 'http://';
$host = $protocol . $_SERVER['SERVER_NAME'];
// Найденный листинг парсера (offset-free): событие-родитель файла лежит в external_listing_events,
// event_id и object_id хранятся как РЕАЛЬНЫЕ el.id (без смещения) — валидируем владение по листинговой
// таблице. Признак листинга — явный флаг is_external из запроса (id больше не диапазонный: коллизит с objects.id).
if ($section == 'objects' && self::_request_flag($get, 'is_external')) {
$sql = "SELECT * FROM clients_files as c
WHERE object_id = {$source_id} AND event_id > 0 AND (SELECT id FROM external_listing_events WHERE id = c.event_id) > 0";
} else {
$sql = "SELECT * FROM clients_files as c
WHERE {$field} = {$source_id} AND event_id > 0 AND (SELECT id from {$table} WHERE id = c.event_id) > 0";
}
if ($q = $pdo->query($sql)) {
if ($pdo->num_rows($q) > 0) {
while ($r = $pdo->fetch_assoc($q)) {
if (!empty($r['name'])) {
$file = $_SERVER['DOCUMENT_ROOT'] . "/upload/";
if ($r['client_id'] > 0)
$file .= "clients/" . $r['client_id'] . "/";
else if ($r['req_id'] > 0)
$file .= "reqs/" . $r['req_id'] . "/";
else if ($r['object_id'] > 0)
$file .= "objects/" . $r['object_id'] . "/";
$file .= $r['guid'] . '.' . $r['type'];
$r['type'] = 'id';
$r['link'] = $host . '/download_file.php?id=' . $r['id'];
$unix_time = !empty($r['created_at']) ? strtotime($r['created_at']) : @filemtime($file);
$r['date'] = date('d.m.Y в H:i', $unix_time);
if (!isset($list['names'][$r['name_id']]))
$list['names'][$r['name_id']] = array('type' => 'id', 'from' => $section, 'from_id' => $source_id, 'id' => (int)$r['name_id']);
if (!empty($r['guid']))
$row[$r['name_id']][] = $r;
}
}
}
} else {
$error = true;
$errors[] = $q->pdo->errorInfo();
}
if ($section == 'clients' || $section == 'requisitions' || $section == 'free') {
$sql = "SELECT * FROM `funnel_files` WHERE {$field} = {$source_id}";
if ($q = $pdo->query($sql)) {
if ($pdo->num_rows($q) > 0) {
while ($r = $pdo->fetch_assoc($q)) {
if (!empty($r['name'])) {
$file = $_SERVER['DOCUMENT_ROOT'] . "/upload/funnels/";
if ($r['client_id'] > 0)
$file .= "clients/" . $r['client_id'] . "/";
else if ($r['req_id'] > 0)
$file .= "req/" . $r['req_id'] . "/";
$file .= $r['guid'] . '.' . $r['type'];
$r['type'] = 'guid';
$r['link'] = $host . '/download_file.php?guid=' . $r['guid'];
$unix_time = !empty($r['created_at']) ? strtotime($r['created_at']) : @filemtime($file);
$r['date'] = date('d.m.Y в H:i', $unix_time);
if (!isset($list['names'][$r['etap_id']]))
$list['names'][$r['etap_id']] = array('type' => 'guid', 'from' => $section, 'from_id' => $source_id, 'id' => (int)$r['etap_id']);
if (!empty($r['guid']))
$row[$r['etap_id']][] = $r;
}
}
}
} else {
$error = true;
$errors[] = $q->pdo->errorInfo();
}
}
if ($section == 'requisitions') {
//поиск файлов по объекту
$sql = "SELECT id, type_id, object_id FROM requisitions WHERE id = {$source_id}";
if ($q = $pdo->query($sql)) {
$r = $pdo->fetch_assoc($q);
if ($r['type_id'] == 2 && $r['object_id'] > 0) {
$sql = "SELECT * FROM `clients_files` as c WHERE object_id = {$r['object_id']} AND (SELECT id from user_object_events WHERE id=c.event_id)>0";
if ($q = $pdo->query($sql)) {
if ($pdo->num_rows($q) > 0) {
while ($r = $pdo->fetch_assoc($q)) {
if (!empty($r['name'])) {
$file = $_SERVER['DOCUMENT_ROOT'] . "/upload/";
if ($r['object_id'] > 0)
$file .= "objects/" . $r['object_id'] . "/";
$file .= $r['guid'] . '.' . $r['type'];
$r['type'] = 'id';
$r['link'] = $host . '/download_file.php?id=' . $r['id'];
$unix_time = !empty($r['created_at']) ? strtotime($r['created_at']) : @filemtime($file);
$r['date'] = date('d.m.Y в H:i', $unix_time);
if (!isset($list['names'][$r['name_id']]))
$list['names'][$r['name_id']] = array('type' => 'id', 'from' => 'object', 'from_id' => $r['object_id'], 'id' => (int)$r['name_id']);
if (!empty($r['guid']))
$row[$r['name_id']][] = $r;
}
}
}
} else {
$error = true;
$errors[] = $q->pdo->errorInfo();
}
}
} else {
$error = true;
$errors[] = $q->pdo->errorInfo();
}
}
if ($section == 'objects') {
//Поиск файлов по заявкам
$sql_r = "SELECT id, type_id, object_id FROM requisitions WHERE object_id = {$source_id} AND type_id = 2 and deleted = 0";
if ($q_r = $pdo->query($sql_r)) {
if ($pdo->num_rows($q_r) > 0) {
$req = $pdo->fetch_assoc($q_r);
$sql = "SELECT * FROM `clients_files` as c WHERE req_id = {$req['id']} AND (SELECT id from user_client_events WHERE id=c.event_id)>0";
if ($q = $pdo->query($sql)) {
if ($pdo->num_rows($q) > 0) {
while ($r = $pdo->fetch_assoc($q)) {
if (!empty($r['name'])) {
$file = $_SERVER['DOCUMENT_ROOT'] . "/upload/";
if ($r['req_id'] > 0)
$file .= "reqs/" . $req['id'] . "/";
$file .= $r['guid'] . '.' . $r['type'];
$r['type'] = 'id';
$r['link'] = $host . '/download_file.php?id=' . $r['id'];
$unix_time = !empty($r['created_at']) ? strtotime($r['created_at']) : @filemtime($file);
$r['date'] = date('d.m.Y в H:i', $unix_time);
if (!isset($list['names'][$r['name_id']]))
$list['names'][$r['name_id']] = array('type' => 'id', 'from' => 'req', 'from_id' => $req['id'], 'id' => (int)$r['name_id']);
if (!empty($r['guid']))
$row[$r['name_id']][] = $r;
}
}
}
} else {
$error = true;
$errors[] = $q->pdo->errorInfo();
}
$sql = "SELECT * FROM `funnel_files` WHERE req_id = {$req['id']}";
$q = $pdo->query($sql);
if ($pdo->num_rows($q) > 0) {
while ($r = $pdo->fetch_assoc($q)) {
if (!empty($r['name'])) {
$file = $_SERVER['DOCUMENT_ROOT'] . "/upload/funnels/";
if ($r['req_id'] > 0) {
$file .= "req/" . $r['req_id'] . "/";
}
$file .= $r['guid'] . '.' . $r['type'];
$r['type'] = 'guid';
$r['link'] = $host . '/download_file.php?guid=' . $r['guid'];
$unix_time = !empty($r['created_at']) ? strtotime($r['created_at']) : @filemtime($file);
$r['date'] = date('d.m.Y в H:i', $unix_time);
if (!isset($list['names'][$r['etap_id']])) {
$list['names'][$r['etap_id']] = array('type' => 'guid', 'from' => 'req', 'from_id' => $req['id'], 'id' => (int)$r['etap_id']);
}
if (!empty($r['guid'])) {
$row[$r['etap_id']][] = $r;
}
}
}
}
}
} else {
$error = true;
$errors[] = $q_r->pdo->errorInfo();
}
}
$list['files'] = $row;
foreach ($list['names'] as $key => $res) {
if ($res['type'] == 'id') {
if ($key == 0) {
$list['names'][$key]['name'] = "Без названия";
} else {
$sql_n = "SELECT * FROM names_client_files WHERE id={$key}";
if ($q_n = $pdo->query($sql_n)) {
$r_n = $pdo->fetch_assoc($q_n);
$list['names'][$key]['name'] = $r_n['name'];
} else {
$error = true;
$errors[] = $q_n->pdo->errorInfo();
}
}
} else if ($res['type'] == 'guid') {
$sql_n = "SELECT * FROM funnel_steps WHERE id={$key}";
if ($q_n = $pdo->query($sql_n)) {
$r_n = $pdo->fetch_assoc($q_n);
$list['names'][$key]['name'] = $r_n['name'];
} else {
$error = true;
$errors[] = $q_n->pdo->errorInfo();
}
}
}
}
if (!empty($errors))
$error = true;
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => $user_id,
'section' => $section,
'list' => $list
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getEvents($app, $get = null, $post = null) {
$error = false;
if ($user_id = $_SESSION['id']) {
// Открываем соединение с БД
$pdo = $app->container->get('pdo');
$events = [];
// Выборка событий о передачи объектов, объектов с клиентами
$sth = $pdo->prepare("SELECT * FROM objects_to_send WHERE new_user_id = ".$user_id." AND `accept_state` = 'NEW'");
if ($sth->execute()) {
if ($sth->rowCount() > 0) {
while($row = $sth->fetch(\PDO::FETCH_ASSOC)) {
$sql_in = "SELECT `agency_name`, `first_name`, `last_name`, `middle_name`, `agency`, `manager` FROM `users` WHERE `id` = '".$row['sended_user_id']."'";
$sth_in = $pdo->prepare($sql_in);
if ($sth_in->execute()) {
if ($r_in = $sth_in->fetch(\PDO::FETCH_ASSOC)) {
$sender_name = trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']);
if ($r_in['agency'] == 1) {
$sender_name = "Агентство " . $r_in['agency_name'];
} else {
if ($r_in['manager'] == 1) {
$sender_name = "Менеджер " . trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']);
}
}
$clientsNum = 0;
$clientsString = '';
$sql_clients = "SELECT `id`, `fio`, `email` FROM `clients` WHERE `objects` LIKE '%"".$row['object_id'].""%'";
$sth_clients = $pdo->prepare($sql_clients);
if ($sth_clients->execute()) {
if ($sth_clients->rowCount() > 0) {
while($client = $sth_clients->fetch(\PDO::FETCH_ASSOC)) {
$clientsNum++;
$clientsString = $clientsString . ($clientsNum > 1 ? ", " : "") . $client['fio'];
}
}
} else {
$error = true;
}
$sql_obj = "SELECT nazv FROM `objects` WHERE id= $row[object_id]";
$sth_obj = $pdo->prepare($sql_obj);
if ($sth_obj->execute()) {
if ($row_obj = $sth_obj->fetch(\PDO::FETCH_ASSOC)) {
$first_line = "передал Вам объект `" . $row_obj['nazv'] . "`";
$sec_line = "Взять ";
$subject = "Передача объекта";
if ($clientsNum > 0) {
if ($clientsNum > 1) {
$subject = "Передача объекта\клиентов";
$first_line = $first_line . " и клиентов " . $clientsString . ".";
$sec_line = $sec_line . " объект и клиентов в работу?";
} else {
$subject = "Передача объекта\клиента";
$first_line = $first_line . " и клиента " . $clientsString . ".";
$sec_line = $sec_line . " объект и клиента в работу?";
}
} else {
$first_line = $first_line . ".";
$sec_line = $sec_line . " в работу?";
}
$source_id = $row['id'];
$events[] = [
'id' => $source_id,
'type' => 'transfer-object',
'object_id' => $row['object_id'],
'sender_id' => $row['sended_user_id'],
'datetime' => $row['create_date'],
'subject' => $subject,
'sender_name' => $sender_name,
'message' => $sender_name . ' ' .$first_line . '
' . $sec_line
];
}
} else {
$error = true;
}
}
} else {
$error = true;
}
}
}
} else {
$error = true;
}
// Выборка событий о передачи клиентов, заявок
$sth = $pdo->prepare("SELECT * FROM events_clients WHERE from_id = ".$user_id." AND `read` = 0");
if ($sth->execute()) {
if ($sth->rowCount() > 0) {
while($r = $sth->fetch(\PDO::FETCH_ASSOC)) {
$sql_in = "SELECT `agency_name`, `first_name`, `last_name`, `middle_name`, `agency`, `manager` FROM `users` WHERE `id` = '".$r['user_id']."'";
$sth_in = $pdo->prepare($sql_in);
if ($sth_in->execute()) {
if ($r_in = $sth_in->fetch(\PDO::FETCH_ASSOC)) {
$sender_name = "Сотрудник ";
if ($r_in['agency'] == 1)
$sender_name = "Агентство ";
else if ($r_in['manager'] == 1)
$sender_name = "Менеджер ";
$sql_cl = "SELECT `fio` FROM `clients` WHERE `id` = ".$r['client_id'];
if ($r['req_id'] > 0)
$sql_cl = "SELECT `name` as `fio`, object_id, type_id FROM `requisitions` WHERE `id` = ".$r['req_id'];
$sth_cl = $pdo->prepare($sql_cl);
if ($sth_cl->execute()) {
if ($r_cl = $sth_cl->fetch(\PDO::FETCH_ASSOC)) {
$tr = 0;
$objectString = '';
$objectNum = 0;
$type_req = 0;
if ($r['event'] == 'transmitted_parallel') {
$tr = 1;
} else {
if ($r['req_id'] > 0 && $r_cl['object_id'] > 0) {
$objectNum++;
$sql_obj = "SELECT nazv FROM `objects` WHERE id= $r_cl[object_id]";
$sth_obj = $pdo->prepare($sql_obj);
if ($sth_obj->execute()) {
if ($r_obj = $sth_obj->fetch(\PDO::FETCH_ASSOC)) {
$type_req = $r_cl['type_id'];
$objectString = $objectString . ($objectNum > 1 ? ", " : "") . $r_obj['nazv'];
}
} else {
$error = true;
}
} else {
$sql_client = "SELECT objects FROM clients WHERE id=$r[client_id]";
$sth_client = $pdo->prepare($sql_client);
if ($sth_client->execute()) {
if ($r_client = $sth_client->fetch(\PDO::FETCH_ASSOC)) {
$objects = json_decode(html_entity_decode($r_client['objects']), true);
foreach ($objects as $object) {
$objectNum++;
$sql_obj = "SELECT nazv FROM `objects` WHERE id= $object";
$sth_obj = $pdo->prepare($sql_obj);
if ($sth_obj->execute()) {
if ($r_obj = $sth_obj->fetch(\PDO::FETCH_ASSOC)) {
$objectString = $objectString . ($objectNum > 1 ? ", " : "") . "`".$r_obj['nazv']."`";
}
} else {
$error = true;
}
}
}
} else {
$error = true;
}
}
}
if ($tr == 1) {
$first_line = "приглашает Вас к совместной работе.";
$subject = "Приглашение";
} else {
$first_line = "передал Вам";
$subject = "Передача клиента";
}
$sec_line = "";
if ($objectNum > 1) {
if ($r['req_id'] > 0) {
if ($tr != 1)
$subject = 'Передача заявки/объектов';
if (!empty($objectString)) {
if ($tr != 1)
$first_line .= ' заявку и объекты.';
$sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` и объекты ' . $objectString . ' в работу?';
} else {
if ($tr != 1)
$first_line .= ' заявку.';
$sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` в работу?';
}
} else {
if ($tr != 1)
$subject = 'Передача клиента/объектов';
if (!empty($objectString)) {
if ($tr != 1)
$first_line .= ' клиента и объекты.';
$sec_line .= ' Взять клиента `' . $r_cl['fio'] . '` и объекты ' . $objectString . ' в работу?';
} else {
if ($tr != 1)
$first_line .= ' клиента.';
$sec_line .= ' Взять клиента `' . $r_cl['fio'] . '` в работу?';
}
}
} else {
if ($r['req_id'] > 0) {
if ($tr != 1)
$subject = 'Передача заявки/объекта';
if (!empty($objectString)) {
if ($tr != 1)
$first_line .= ' заявку и объект.';
$sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` и объект ' . $objectString . ' в работу?';
} else {
if ($tr != 1)
$first_line .= ' заявку.';
$sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` в работу?';
}
} else {
if ($tr != 1)
$subject = 'Передача клиента/объекта';
if (!empty($objectString)) {
if ($tr != 1)
$first_line .= ' клиента и объект.';
$sec_line .= ' Взять клиента `' . $r_cl['fio'] . '` и объект ' . $objectString . ' в работу?';
} else {
if ($tr != 1)
$first_line .= ' клиента.';
$sec_line .= ' Взять клиента `' . $r_cl['fio'] . '` в работу?';
}
}
}
if ($r['req_id'] > 0 && $type_req == 4) {
$subject = 'Передача заявки';
$first_line .= ' заявку.';
if (!empty($objectString))
$sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` по объекту ' . $objectString . ' в работу?';
else
$sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` по объекту в работу?';
}
$sender_name .= trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']);
if ($r_in['agency'] == 1)
$sender_name .= $r_in['agency_name'];
$source_id = $r['id'];
$events[] = [
'id' => $source_id,
'type' => 'transfer-client',
'datetime' => $r['date'],
'subject' => $subject,
'sender_id' => $r['user_id'],
'sender_name' => $sender_name,
'client_id' => $r['client_id'],
'requisition_id' => $r['req_id'],
'tr' => $tr, // @todo: tr ??
'message' => $sender_name . ' ' . $first_line . '
' . $sec_line
];
}
} else {
$error = true;
}
}
} else {
$error = true;
}
}
}
} else {
$error = true;
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !($error),
'user_id' => (int)$user_id,
'count' => count($events),
'events' => $events,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getObjectReasons($app, $get = null, $post = null) {
$error = false;
$reasons = [];
if ($user_id = $_SESSION['id']) {
// Открываем соединение с БД
$pdo = $app->container->get('pdo');
// Выборка событий о передачи объектов, объектов с клиентами
$sth = $pdo->prepare("SELECT * FROM archive_object_reason order by id");
if ($sth->execute()) {
if ($sth->rowCount() > 0) {
while($row = $sth->fetch(\PDO::FETCH_ASSOC)) {
$reasons[] = $row;
}
}
} else {
$error = true;
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !($error),
'user_id' => (int)$user_id,
'count' => count($reasons),
'list' => $reasons,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getNewBuilding($app, $get = null, $post = null) {
$errors = [];
if ($user_id = $_SESSION['id']) {
$list = [];
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$id = null;
if (isset($get['id']))
$id = trim($get['id']);
if (!$id) {
$errors[] = "Нет ИД";
}
$sql = "SELECT * FROM `newbuildings` WHERE ";
$sql .= " `id` = '" . trim($id) . "'";
$sql .= " ORDER BY `name`, `id`";
if ($query = mysql_query($sql)) {
while ($block = mysql_fetch_assoc($query)) {
$list[] = $block;
}
} else {
$errors[] = mysql_error();
}
if (!(count($errors))) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'list' => $list
], 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 getNewBuildings($app, $get = null, $post = null) {
$errors = [];
if ($user_id = $_SESSION['id']) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$list = [];
$where = '';
$total = 0;
$all_pages = 0;
$search = null;
if (isset($get['search']))
$search = trim($get['search']);
$page = 1;
if (isset($get['page']))
$page = (int)$get['page'];
$per_page = 10;
if (isset($get['per_page']))
$per_page = (int)$get['per_page'];
$region_id = null;
if (isset($get['region_id']))
$region_id = (int)$get['region_id'];
if ($region_id == null) {
$curUser = new \User();
$curUser->get($user_id);
$region_id = $curUser->region_rf_id;
}
$where = '`rf_region_id` = ' . $region_id;
if ($region_id == 1 || $region_id == 2 || $region_id == 3)
$where = '(`rf_region_id` IN (SELECT `id` FROM `rf_regions` WHERE `parent` = ' . $region_id . '))';
$sql = "SELECT count(id) FROM `newbuildings` WHERE ". $where;
if ($search != null)
$sql .= " AND `name` LIKE '%" . trim($search) . "%'";
$sql .= " ORDER BY `name`, `id`";
if ($query = mysql_query($sql)) {
$total = mysql_result($query, 0);
$all_pages = ceil($total / $per_page);
$offset = ($page - 1) * $per_page;
$sql = "SELECT * FROM `newbuildings` WHERE ". $where;
if ($search != null)
$sql .= " AND `name` LIKE '%" . trim($search) . "%'";
$sql .= " ORDER BY `name`, `id` LIMIT $offset, $per_page";
if ($query = mysql_query($sql)) {
while ($block = mysql_fetch_assoc($query)) {
$list[] = $block;
}
} else {
$errors[] = mysql_error();
}
} else {
$errors[] = mysql_error();
}
if (!(count($errors))) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'list' => $list,
'total' => $total,
'page' => $page,
'all_pages' => $all_pages,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function setEventState($app, $get = null, $post = null) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode(stripcslashes($body), true);
if (($user_id = $_SESSION['id']) && isset($data['type']) && isset($data['state']) && isset($data['event_id'])) {
$type = $data['type'];
$state = $data['state'];
$event_id = $data['event_id'];
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$db_sphinx = $app->container->get('sphinx2');
if ($event_id && $type == 'transfer-object' && isset($data['object_id'])) {
$object_id = (int)$data['object_id'];
// Защитный отказ — приём передачи владения на найденном листинге парсера недоступен (offset-free).
// Признак листинга — явный флаг is_external из запроса. Передачи листинга быть не должно (инициация
// загейчена), гейтим от рассинхрона. Делать ДО UPDATE objects.
if (self::_request_flag($data, 'is_external')) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(403);
$app->response->setBody(json_encode([
'success' => false,
'errors' => ['Действие недоступно для найденного листинга. Скопируйте объект в свои, чтобы управлять им.'],
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$sql = "SELECT * FROM objects_to_send WHERE id = $event_id AND object_id = $object_id";
if ($rez = mysql_query($sql)) {
$row = mysql_fetch_assoc($rez);
$source_id = $row['id'];
if ($source_id && $state == 'accepted') {
$new_user_id = (int)$row['new_user_id'];
$object_id = (int)$row['object_id'];
$new_user = new \User;
$new_user->get($new_user_id);
if (!$new_user->agencyId)
$new_user->agencyId = $new_user_id;
$current_user = new \User;
$current_user->get($user_id);
if (!$current_user->agencyId)
$current_user->agencyId = $user_id;
$phone = $new_user->phone;
$num_search = \User::num_search($phone);
/*if(!empty($new_user->phone2)){
$phone = $phone.' '.$new_user->phone2;
}*/
$sobstv = trim($new_user->last_name . ' ' . $new_user->first_name . ' ' . $new_user->middle_name);
if ($new_user->agency == 0) {
$sql = "SELECT * FROM users WHERE id=$new_user->id_manager";
if ($rez = mysql_query($sql))
$manager = mysql_fetch_assoc($rez);
else
$errors[] = mysql_error();
if ($manager['id_manager'])
$agency = mysql_fetch_assoc(mysql_query("SELECT * FROM users WHERE id=$manager[id_manager]"));
else
$agency = $manager;
if ($agency)
$sobstv = trim($current_user->last_name . ' ' . $current_user->first_name . ' ' . $current_user->middle_name) . ", агентство " . $agency['agency_name'];
} else {
$sobstv = $sobstv . ", агентство " . $new_user->agency_name;
}
// перенос всех объектов
$sql = "UPDATE objects SET id_add_user = $new_user->id, phone = '$phone', phone_search = '$num_search', sobstv = '$sobstv' WHERE id=$object_id";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
//Запись в сфинкс
$sql_sph = "UPDATE objects SET id_add_user = $new_user->id, phone_search = '$num_search' WHERE id=$object_id";
if (!$db_sphinx->query($sql_sph)) {
$error = true;
$errors[] = mysql_error();
}
//перенос событий объектов
$sql = "UPDATE user_object_events SET user_id = $new_user->id WHERE object_id = $object_id";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
//перенос комментариев объектов
$sql = "UPDATE user_object_comments SET user_id = $new_user->id WHERE object_id = $object_id";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
// перенос Зипал
$sql = "UPDATE zipal_objects SET user_id = $new_user->id, send_to_update = 1 WHERE object_id = $object_id";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
$sql = "UPDATE advertising_package_object_publish SET send_to_update = '1', error_when_send_to_update = '' WHERE object_id = $object_id";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
/**
* Передача заявок Реализация
*/
$sql_req = "SELECT id, `name`, object_id, type_id, who_work, funnel_id, confirm FROM `requisitions` WHERE object_id = {$object_id} AND cancel=0 AND deleted=0 AND (type_id = 2 or (SELECT heir FROM requisitions_type WHERE id = requisitions.type_id) = 2) AND who_work != '".$new_user->id."'";
//echo $sql_req."\n";
$q_req = mysql_query($sql_req);
if(mysql_num_rows($q_req) > 0){
while($r_req = mysql_fetch_assoc($q_req)){
$sql_up = "UPDATE requisitions SET confirm=1, who_work={$new_user->id} WHERE id={$r_req['id']}";
//echo $sql_up."\n";
if(mysql_query($sql_up)){
$sql_ev = "INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`, dop_text) VALUES ('".$user_id."', '{$r_req['id']}', '".$new_user->id."', 'update', '1', 'Переведена на ответственного при принятии объекта ID {$object_id}')";
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/log_task_telega.txt", date('d.m.y H:i:s').' chat_id '.$chatId.' id:'.$event_id." ". $sql_ev."\n", FILE_APPEND);
mysql_query($sql_ev);
}
}
}
//передаем клиентов
/*$sql_clients = "SELECT `id`, `fio`, `email` FROM `clients` WHERE `objects` LIKE '%"".$object_id.""%'";
$q_client = mysql_query($sql_clients);
if (mysql_num_rows($q_client) > 0) {
while($client = mysql_fetch_assoc($q_client)) {
$sql = "UPDATE clients SET confirm = 1, who_work = $new_user->id WHERE id = $client[id]";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
$sql="UPDATE user_client_events SET user_id = $new_user->id WHERE client_id = $client[id]";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
$sql = "UPDATE `events_clients` SET `read` = 1, date_update = '".date('Y-m-d H:i:s')."' WHERE client_id = $client[id] and from_id = ".$user_id;
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
$sql = "INSERT INTO `events_clients` (user_id, client_id, from_id, event, `read`) VALUES ('".$user_id."', '".$client['id']."', '".$user_id."', 'accepted', '1')";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
}*/
$sql = "UPDATE objects_to_send SET accept_date = NOW(), accept_state='ACCEPTED' WHERE id = $source_id AND object_id=$object_id";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
} else if ($source_id && $state == 'rejected') {
$sql = "UPDATE objects_to_send SET accept_date = NOW(), accept_state='REJECTED' WHERE id=$source_id AND object_id=$object_id";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
} else {
$errors[] = mysql_error();
}
} else if ($type == 'transfer-client' && (isset($data['client_id']) || isset($data['req_id']))) {
$tr = $data['tr']; // @todo: `tr` ???
$who_work = $user_id;
$sender_id = (int)$data['sender_id'];
$client_id = (int)$data['client_id'];
$requisition_id = (int)$data['requisition_id'];
if ($state == 'accepted') {
if ($tr != 1) {
$sql = "UPDATE clients SET confirm=1, who_work=$who_work WHERE id=$client_id";
if ($requisition_id > 0)
$sql = "UPDATE requisitions SET confirm=1, who_work=$who_work WHERE id=$requisition_id";
if (mysql_query($sql)) {
// Автопривязка ответственного по заявке к клиенту из заявки
if ($requisition_id > 0) {
$sql = "UPDATE `clients`
JOIN `requisitions` AS `req` ON
`clients`.`id` = `req`.`client_id` AND
`clients`.`who_work` = 0 AND
`clients`.`confirm` = 0 AND
`req`.`id` = '$requisition_id' AND
`clients`.`who_work` = 0 AND
`clients`.`confirm` = 0
SET `clients`.`who_work` = '$who_work',
`clients`.`confirm` = 1";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
} else {
$sql_client = "SELECT doers, who_work FROM clients WHERE id=$client_id";
if ($requisition_id > 0)
$sql_client = "SELECT doers, who_work FROM requisitions WHERE id=$requisition_id";
if ($q_client = mysql_query($sql_client)) {
$r_client = mysql_fetch_assoc($q_client);
if (!empty($r_client['doers'])) {
$confirm = 1;
$doers = json_decode(html_entity_decode($r_client['doers']), true);
$doers[$user_id] = 1;
foreach($doers as $doer) {
if ($doer == 0)
$confirm = 0;
}
$sql = "UPDATE clients SET doers = '".self::clearInput(json_encode($doers))."', doers_confirm = $confirm WHERE id = $client_id";
if ($requisition_id > 0)
$sql = "UPDATE requisitions SET doers = '".self::clearInput(json_encode($doers))."', doers_confirm = $confirm WHERE id = $requisition_id";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
$sql = "UPDATE doers_emp_client SET confirm = 1 WHERE client_id = $client_id AND who_work = $r_client[who_work] AND doer_id = $user_id";
if ($requisition_id > 0)
$sql = "UPDATE doers_emp_client SET confirm = 1 WHERE req_id = $requisition_id AND who_work = $r_client[who_work] AND doer_id = $user_id";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
// синкаем нормализованную таблицу, которую читает десктоп (Clients → clients_doers WHERE confirm=1)
$sql = "UPDATE clients_doers SET confirm = 1 WHERE client_id = $client_id AND user_id = $user_id";
if ($requisition_id > 0)
$sql = "UPDATE requisition_doers SET confirm = 1 WHERE requisition_id = $requisition_id AND user_id = $user_id";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
if ($tr != 1) {
$sql = "UPDATE user_client_events SET user_id = $who_work WHERE client_id = $client_id AND type != 'step' AND type != 'file'";
if ($requisition_id > 0)
$sql = "UPDATE user_client_events SET user_id = $who_work WHERE req_id = $requisition_id AND type != 'step' AND type != 'file'";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
$sql = "UPDATE `events_clients` SET `read` = 1, date_update = '".date('Y-m-d H:i:s')."' WHERE client_id = $client_id AND from_id = $user_id";
if ($requisition_id > 0)
$sql = "UPDATE `events_clients` SET `read` = 1, date_update = '".date('Y-m-d H:i:s')."' WHERE req_id = $requisition_id AND from_id = $user_id";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
$accepted = 'accepted';
if ($tr == 1)
$accepted = 'accepted_doer';
$sql = "INSERT INTO `events_clients` (user_id, client_id, from_id, event, `read`) VALUES ('".$user_id."', '".$client_id."', '".$user_id."', '".$accepted."', '1')";
if ($requisition_id > 0)
$sql = "INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`) VALUES ('".$user_id."', '".$requisition_id."', '".$user_id."', '".$accepted."', '1')";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
$rUser = null;
$sobstv = '';
$sqlUser = "SELECT `first_name`, `last_name`, `middle_name`, `phone` FROM `users` WHERE id=".$user_id;
if ($qUser = mysql_query($sqlUser)) {
$rUser = mysql_fetch_assoc($qUser);
$sobstv = trim($rUser['last_name'] . ' ' . $rUser['first_name'] . ' ' . $rUser['middle_name']);
if ($_SESSION['agency']) {
$sobstv = $sobstv . ", агентство " . $rUser['agency_name'];
} else {
$agency = new \User;
if (isset($agency->agencyName)) {
$sobstv = trim($rUser['last_name'] . ' ' . $rUser['first_name'] . ' ' . $rUser['middle_name']) . ", агентство " . $agency->agencyName;
} else {
$sobstv = trim($rUser['last_name'] . ' ' . $rUser['first_name'] . ' ' . $rUser['middle_name']);
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
if ($rUser && $tr != 1) {
//$num_search = num_search($rUser['phone']);
//Передача объекта
if ($requisition_id > 0) {
$sql_cl = "SELECT `name` as `fio`, object_id, type_id FROM `requisitions` WHERE `id` = ".$requisition_id;
$q_cl = mysql_query($sql_cl);
$r_cl = mysql_fetch_assoc($q_cl);
if ($r_cl['object_id'] && $r_cl['type_id'] != 4) {
$sql = "UPDATE objects SET id_add_user = '".$user_id."', phone='".$rUser['phone']."', sobstv='".$sobstv."' WHERE id = ".$r_cl['object_id'];
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
} else {
$sql_client = "SELECT objects FROM clients WHERE id=$client_id";
$q_client = mysql_query($sql_client);
$r_client = mysql_fetch_assoc($q_client);
$objects = json_decode(html_entity_decode($r_client['objects']), true);
foreach($objects as $object) {
$sql = "UPDATE objects SET id_add_user = '".$user_id."', phone='".$rUser['phone']."', sobstv='".$sobstv."' WHERE id = ".$object;
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
}
}
} else if ($state == 'rejected') {
if ($tr != 1) {
$confirm = 0;
if ($user_id == $who_work)
$confirm = 1;
$sql = "UPDATE clients SET confirm=$confirm, who_work=$who_work WHERE id=$client_id";
if ($requisition_id > 0)
$sql = "UPDATE requisitions SET confirm=$confirm, who_work=$who_work WHERE id=$requisition_id";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
} else {
$sql_client = "SELECT doers, who_work FROM clients WHERE id=$client_id";
if ($requisition_id > 0)
$sql_client = "SELECT doers, who_work FROM requisitions WHERE id=$requisition_id";
if ($q_client = mysql_query($sql_client)) {
$r_client = mysql_fetch_assoc($q_client);
$doer_clients = 0;
if (!empty($r_client['doers'])) {
$confirm = 1;
$doers = json_decode(html_entity_decode($r_client['doers']), true);
unset($doers[$user_id]);
if (empty($doers)) {
$confirm = 1;
} else {
foreach($doers as $id_user => $doer) {
if ($doer == 0)
$confirm = 0;
if ($id_user != $r_client['who_work'])
$doer_clients = 1;
}
}
$sql = "UPDATE clients SET doers='".self::clearInput(json_encode($doers))."', doers_confirm=$confirm, doer_clients=$doer_clients WHERE id=$client_id";
if ($requisition_id > 0)
$sql = "UPDATE requisitions SET doers='".self::clearInput(json_encode($doers))."', doers_confirm=$confirm, doer_clients=$doer_clients WHERE id=$requisition_id";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
$from = $user_id;
if ($event_id) {
$sql_from = "SELECT user_id FROM `events_clients` WHERE `id` = $event_id";
if ($q_from = mysql_query($sql_from)) {
$r_from = mysql_fetch_assoc($q_from);
$from = $r_from['user_id'];
$sql = "UPDATE `events_clients` set `read` = 1, `date_update`='".date('Y-m-d H:i:s')."' WHERE `id` = $event_id";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
} else {
$error = true;
$errors[] = mysql_error();
}
} else {
$sql_from = "SELECT id, user_id FROM `events_clients` WHERE `read` = 0 AND `client_id` = $client_id AND `from_id` = $from";
if ($requisition_id > 0)
$sql_from = "SELECT id, user_id FROM `events_clients` WHERE `read` = 0 AND `req_id` = $requisition_id AND `from_id` = $from";
if ($q_from = mysql_query($sql_from)) {
$r_from = mysql_fetch_assoc($q_from);
$from = $r_from['user_id'];
$id_event = $r_from['id'];
$sql = "UPDATE `events_clients` SET `read` = 1, `date_update`='".date('Y-m-d H:i:s')."' WHERE `id` = $id_event";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
$read = 0;
if ($from == $user_id || $tr == 1)
$read = 1;
$event = 'notadopted';
if ($tr == 1) {
$read = 1;
$event = 'notadopted_doer';
}
$sql = "INSERT INTO `events_clients` (user_id, client_id, from_id, event, `read`, send_telegramm) VALUES ('".$user_id."', '".$client_id."', '".$from."', '".$event."', '".$read."', '1')";
if ($requisition_id > 0)
$sql = "INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`, send_telegramm) VALUES ('".$user_id."', '".$requisition_id."', '".$from."', '".$event."', '".$read."', '1')";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
}
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function setViewed($app, $get = null, $post = null) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode(stripcslashes($body), true);
$object_id = null;
if (isset($data['object_id']))
$object_id = (int)$data['object_id'];
$client_id = null;
if (isset($data['client_id']))
$client_id = (int)$data['client_id'];
$requisition_id = null;
if (isset($data['requisition_id']))
$requisition_id = (int)$data['requisition_id'];
if (($user_id = $_SESSION['id']) && ($object_id || $client_id || $requisition_id)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
if ($object_id && in_array($object_id, $_SESSION['new_transfers']['objects'])) {
$key = array_search($object_id, $_SESSION['new_transfers']['objects']);
if ($key !== false) {
unset($_SESSION['new_transfers']['objects'][$key]);
}
}
if ($client_id && in_array($client_id, $_SESSION['new_transfers']['clients'])) {
$key = array_search($client_id, $_SESSION['new_transfers']['clients']);
if ($key !== false) {
unset($_SESSION['new_transfers']['clients'][$key]);
}
}
if ($requisition_id && in_array($requisition_id, $_SESSION['new_transfers']['requisitions'])) {
$key = array_search($requisition_id, $_SESSION['new_transfers']['requisitions']);
if ($key !== false) {
unset($_SESSION['new_transfers']['requisitions'][$key]);
}
}
// Обновление инфо о том, что клиент/заявка были просмотрены пользователем
if ($client_id > 0) {
$sql = "UPDATE `events_clients` SET `viewed` = 1
WHERE `viewed` = 0 AND `read` = 1 AND
`user_id` = '$user_id' AND
`client_id` = '$client_id' AND
`from_id` = '$user_id' AND
(`event` = 'accepted' OR `event` = 'accepted_doer')";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
if ($requisition_id > 0) {
$sql = "UPDATE `events_clients` SET `viewed` = 1
WHERE `viewed` = 0 AND `read` = 1 AND
`user_id` = '$user_id' AND
`req_id` = '$requisition_id' AND
`from_id` = '$user_id' AND
(`event` = 'accepted' OR `event` = 'accepted_doer')";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
if (!$errors) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$errors,
'user_id' => (int)$user_id,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'errors' => $errors
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function setFunnels($app, $get = null, $post = null) {
$body = $app->request->getBody();
$data = json_decode(stripcslashes($body), true);
$errors = [];
$section = null;
if (isset($data['section']))
$section = trim($data['section']);
$clients_ids = null;
if (isset($data['sources_ids']) && $section == 'clients')
$clients_ids = $data['sources_ids'];
$req_ids = null;
if (isset($data['sources_ids']) && $section == 'requisitions')
$req_ids = $data['sources_ids'];
$funnel_id = null;
if (isset($data['funnel_id']))
$funnel_id = (int)$data['funnel_id'];
if (($user_id = $_SESSION['id']) && $section && !empty($funnel_id) && ($req_ids || $clients_ids)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
if ($clients_ids && $section == 'clients') {
if (!is_array($clients_ids))
$clients_ids = [$clients_ids];
$client_inst = new \Clients();
foreach ($clients_ids as $client_id) {
$result = $client_inst->updateFunnel([
'id' => $client_id,
'new_funnel_id' => $funnel_id,
]);
if ($result !== true)
$errors[] = $result;
}
} else if ($req_ids && $section == 'requisitions') {
if (!is_array($req_ids))
$req_ids = [$req_ids];
// Открываем соединение с БД
$pdo = $app->container->get('mypdo');
$req_inst = new \Requisitions($pdo);
foreach ($req_ids as $req_id) {
$result = $req_inst->updateFunnel($funnel_id, $req_id);
if ($result !== true)
$errors[] = $result;
}
}
if (!count($errors)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function setTags($app, $get = null, $post = null, $need_return = false) {
if (!empty($post)) {
$data = $post;
} else {
$body = $app->request->getBody();
$data = json_decode(stripcslashes($body), true);
}
if (($user_id = $_SESSION['id']) && isset($data['section']) && isset($data['source_id']) && isset($data['tags_list'])) {
// Открываем соединение с БД
$pdo = $app->container->get('pdo');
$section = (string)$data['section'];
$source_id = (int)$data['source_id'];
$tags_list = (array)$data['tags_list'];
$set = [];
$tags = [];
foreach ($tags_list as $tag) {
if (boolval($tag['isChecked'])) {
$tag_id = (isset($tag['value'])) ? (int)$tag['value'] : (int)$tag['id'];
$tags[] = $tag_id;
$set[] = "('$source_id', '$tag_id')";
}
}
list($sql, $sql2) = ['' , ''];
switch ($section) {
case 'objects' :
$sql = "DELETE FROM `objects_activities` WHERE `object_id` = '".$source_id."'";
if (count($set) > 0)
$sql2 = "INSERT INTO `objects_activities` (`object_id`, `activity_id`) VALUES " . implode(', ', $set);
break;
case 'clients' :
$sql = "DELETE FROM `clients_activities` WHERE `client_id` = '".$source_id."'";
if (count($set) > 0)
$sql2 = "INSERT INTO `clients_activities` (`client_id`, `activity_id`) VALUES " . implode(', ', $set);
break;
case 'requisitions' :
$sql = "DELETE FROM `requisitions_activities` WHERE `req_id` = '".$source_id."'";
if (count($set) > 0)
$sql2 = "INSERT INTO `requisitions_activities` (`req_id`, `activity_id`) VALUES " . implode(', ', $set);
break;
}
$error = false;
if (!empty($sql)) {
if (!$pdo->query($sql))
$error = true;
}
if (!empty($sql2)) {
if (!$pdo->query($sql2))
$error = true;
}
if ($need_return) {
if (!empty($error))
return false;
else
return $tags;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'tags_ids' => $tags,
'tags_list' => $tags_list
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id']
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getPresentationLink($app, $get = null, $post = null) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode($body, true);
if (($user_id = $_SESSION['id']) && (isset($data['object_id']) || isset($data['newbuilding_id']))) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$object_id = null;
if (isset($data['object_id']))
$object_id = (int)$data['object_id'];
$newbuilding_id = null;
if (isset($data['newbuilding_id']))
$newbuilding_id = (int)$data['newbuilding_id'];
$client_id = null;
if (isset($data['client_id']))
$client_id = (int)$data['client_id'];
$hide_contacts = [];
if (isset($data['hide_contacts']))
$hide_contacts = array_unique(array_map('intval', $data['hide_contacts']));
$send_type = null;
if (isset($data['with']))
$send_type = (int)$data['with'];
$new_prices = [];
$descriptions = [];
if (isset($data['descriptions'])) {
$array = (array)$data['descriptions'];
foreach ($array as $object_id => $value) {
$object_id = str_replace('object_', '', $object_id);
if (isset($value['description']))
$descriptions[intval($object_id)] = $value['description'];
if (isset($value['price']))
$new_prices[intval($object_id)] = $value['price'];
};
}
$link = null;
if (!is_null($object_id) || !is_null($newbuilding_id)) {
/*error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('display_errors', 1);*/
if (!is_null($object_id)) {
// Найденный листинг парсера (offset-free): строки в objects нет, образ собираем из external_listings
// по РЕАЛЬНОМУ el.id. Признак листинга — явный флаг is_external из запроса (id коллизит с objects.id).
require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/helpers/external_listing_legacy.php';
$is_listing = self::_request_flag($data, 'is_external');
$obj = false;
$obj_found = false;
if ($is_listing) {
$obj = \external_listing_object_row($object_id, false);
if (is_null($obj)) {
// Листинг удалён по TTL — отвечаем ошибкой, как для ненайденного объекта.
$error = true;
$errors[] = 'Объявление снято с публикации';
} else {
// Поля внешнего источника экранируем для прямой подстановки в SQL.
$obj['nazv'] = mysql_real_escape_string($obj['nazv']);
$obj['adres'] = mysql_real_escape_string($obj['adres']);
$obj_found = true;
}
} else {
$sql = "SELECT * FROM objects WHERE id=$object_id";
if ($rez = mysql_query($sql)) {
$obj = mysql_fetch_assoc($rez);
$obj_found = true;
}
}
if ($obj_found) {
// Листинг адресуется явным маркером src=ext (bare id уже не различает листинг от своего объекта).
$src_marker = $is_listing ? '&src=ext' : '';
if ($send_type == 2) {
$pdfs = $this->_getPDF([$object_id], $descriptions, $new_prices, $hide_contacts, $is_listing ? [$object_id] : []);
if (isset($pdfs[$object_id]['link']))
$linkUrl = $pdfs[$object_id]['link'];
} else {
if (self::is_ssl())
$linkUrl = "https://joywork.ru/object-view.php?id=$object_id&token=" . md5($user_id) . $src_marker;
else
$linkUrl = "http://joywork.ru/object-view.php?id=$object_id&token=" . md5($user_id) . $src_marker;
}
$new_price = 0;
if (isset($new_prices[$object_id]))
$new_price = $new_prices[$object_id];
if (!is_null($client_id))
$linkUrl .= "&client=" . md5($client_id);
else
$client_id = "0";
$close_contact = 0;
if (in_array($object_id, $hide_contacts))
$close_contact = 1;
// Для найденного листинга флаг скрытия контакта не пишем — его контакт скрыт всегда.
if (!$is_listing) {
$sql_up = "INSERT INTO user_object_contact_close SET close={$close_contact}, user_id={$user_id}, object_id = {$object_id}, client_id = {$client_id}";
if (!mysql_query($sql_up)) {
$error = true;
$errors[] = mysql_error();
}
}
$token = md5(microtime());
// Per-send описание, переданное mJW в POST-параметре `descriptions`.
$descriptionForInsert = "NULL";
if (isset($descriptions[intval($object_id)]) && $descriptions[intval($object_id)] !== '') {
$cleanedDesc = cleanHtml($descriptions[intval($object_id)], '
') === false && strpos($cleanedDesc, ' ') === false && strpos($cleanedDesc, ' ') === false && strpos($cleanedDesc, ' ') === false && strpos($cleanedDesc, ' ') === false && strpos($cleanedDesc, ' ') === false && strpos($cleanedDesc, ' ') === false && strpos($cleanedDesc, ' ') === false && strpos($cleanedDesc, ' '.$field_models['label'].': '.clearInputElement($val).' '.$field_models['label'].': ';
$value = (int)$field_models['value'];
if($value == 1){
$text .= 'Да '.$field_models['label'].': '.clearInputElement($value).' ' . $event['label'] . ': ' . date('d.m.Y', strtotime($event['value'])) . ' ' . $event['label'] . ': ' . $doc['name'] . ' ' . $event['label'] . ': ' . $doc['name'] . ' ' . $event['label'] . ': ' . self::clearInput($event['value']) . ' '.$event['label'].': '.trim($event['value']).' '.$event['label'].': '.$event['value']['summa'];
if(!empty($event['value']['comment'])){
$text .= ' Комментарий: '.clearInputElement($event['value']['comment']);
}
$sql_ex = "SELECT * FROM expenses_req WHERE req_id = {$requisition_id} AND funnel_id = {$funnel_id} AND step_id = {$step_id}";
$q_ex = mysql_query($sql_ex);
if(mysql_num_rows($q_ex) > 0){
$r_ex = mysql_fetch_assoc($q_ex);
$comment = mysql_real_escape_string($event['value']['comment']);
$sql_up = "UPDATE expenses_req SET amount = '{$event['value']['summa']}', comment = '{$comment}' where id = {$r_ex['id']}";
mysql_query($sql_up);
$amount = rtrim(rtrim((float)$r_ex['amount'], '0'), '.');
if($amount != (float)$event['value']['summa']){
$text_expenses = "Изменено: {$event['label']} с {$amount} на {$event['value']['summa']}";
if(!empty($event['value']['comment'])){
$text_expenses .= " Добавлен комментарий: ".$event['value']['comment'];
}
$sql_event = "INSERT INTO events_clients (user_id, from_id, req_id, `event`, dop_text, `read`) VALUES ({$user_id}, {$user_id}, {$requisition_id}, 'update', '{$text_expenses}', 1)";
mysql_query($sql_event);
}
} else {
$comment = mysql_real_escape_string(trim($event['value']['comment']));
$sql_in = "INSERT INTO `expenses_req`(`user_id`, `req_id`, `amount`, `comment`, `funnel_id`, `step_id`) VALUES ({$userId}, {$requisition_id}, {$event['value']['summa']}, '{$comment}', {$funnel_id}, {$step_id})";
mysql_query($sql_in);
$text_expenses = "Добавлено: {$event['label']} - {$event['value']['summa']}";
if(!empty($event['value']['comment'])){
$text_expenses .= " Добавлен комментарий: ".$event['value']['comment'];
}
$sql_event = "INSERT INTO events_clients (user_id, from_id, req_id, `event`, dop_text, `read`) VALUES ({$user_id}, {$user_id}, {$requisition_id}, 'update', '{$text_expenses}', 1)";
mysql_query($sql_event);
}
} else if (!is_null($event['value'])) {
$text .= ' ' . $event['label'] . ': ' . trim($event['value']) . '
,
// чтобы абзацы не склеились в одну строку при отображении через echo $obj['opis'] в object-view.php.
if ($cleanedDesc !== '' && strpos($cleanedDesc, '
response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'link' => $link
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'errors' => $errors
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getCatalogLink($app, $get = null, $post = null, $need_return = false) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode($body, true);
if (($user_id = $_SESSION['id']) && (isset($data['objects_ids']) || isset($data['external_objects_ids']) || isset($data['newbuildings_ids']))) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$objects_ids = [];
if (isset($data['objects_ids']))
$objects_ids = array_unique(array_map('intval', (array)$data['objects_ids']));
// Offset-free: листинги парсера приходят ОТДЕЛЬНЫМ массивом реальных el.id (objects_ids — только свои объекты).
// Разделить по диапазону id больше нельзя — el.id коллизит с objects.id.
$external_objects_ids = [];
if (isset($data['external_objects_ids']))
$external_objects_ids = array_unique(array_map('intval', (array)$data['external_objects_ids']));
$newbuildings_ids = [];
if (isset($data['newbuildings_ids']))
$newbuildings_ids = array_unique(array_map('intval', (array)$data['newbuildings_ids']));
$clients_ids = [];
if (isset($data['clients_ids']))
$clients_ids = array_unique(array_map('intval', (array)$data['clients_ids']));
if (empty($clients_ids))
$clients_ids = [0];
$catalog_id = null;
if (isset($data['catalog_id']))
$catalog_id = (int)$data['catalog_id'];
$hide_contacts = [];
if (isset($data['hide_contacts']))
$hide_contacts = array_unique(array_map('intval', (array)$data['hide_contacts']));
$hide_address = [];
if (isset($data['hide_address']))
$hide_address = array_unique(array_map('intval', (array)$data['hide_address']));
$send_type = 0;
if (isset($data['with']))
$send_type = (int)$data['with'];
$new_prices = [];
$descriptions = [];
if (isset($data['descriptions'])) {
$array = (array)$data['descriptions'];
foreach ($array as $object_id => $value) {
$object_id = str_replace('object_', '', $object_id);
if (isset($value['description']))
$descriptions[intval($object_id)] = $value['description'];
if (isset($value['price']))
$new_prices[intval($object_id)] = $value['price'];
};
}
$link = null;
if (!empty($objects_ids) || !empty($external_objects_ids) || !empty($newbuildings_ids)) {
/*error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('display_errors', 1);*/
$is_close_contacts = !empty($hide_contacts) ? 1 : 0;
if (is_null($catalog_id)) {
$sql = "INSERT INTO sent_catalog(agent_id, close_contact, date_send) VALUES ('$user_id', '$is_close_contacts', NOW())";
if (mysql_query($sql)) {
$catalog_id = mysql_insert_id();
} else {
$error = true;
$errors[] = mysql_error();
}
} else {
$sql1 = "UPDATE sent_catalog SET agent_id = '$user_id', close_contact = '$is_close_contacts', date_send = NOW() WHERE id = '$catalog_id'";
$sql2 = "DELETE FROM sended_pdf WHERE sent_catalog_id = '$catalog_id'";
if (!mysql_query($sql1) || !mysql_query($sql2)) {
$error = true;
$errors[] = mysql_error();
}
}
if (!empty($objects_ids) || !empty($external_objects_ids)) {
// Offset-free: свои объекты и найденные листинги парсера приходят РАЗНЫМИ массивами реальных id.
// objects_ids — только свои (objects), external_objects_ids — листинги (external_listings, ключ = el.id).
require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/helpers/external_listing_legacy.php';
$listing_ids = $external_objects_ids;
$own_object_ids = $objects_ids;
if (!empty($own_object_ids)) {
$sql = "SELECT `id`, `nazv`, `adres`, `phone`, `sobstv` FROM `objects` WHERE `id` IN (".implode(',', $own_object_ids).")";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
while ($object = mysql_fetch_assoc($query)) {
$object_id = (int)$object['id'];
foreach ($clients_ids as $client_id) {
$new_price = isset($new_prices[$object_id]) ? $new_prices[$object_id] : 0;
$is_hide_contacts = in_array($object_id, $hide_contacts) ? 1 : 0;
$is_hide_address = in_array($object_id, $hide_address) ? 1 : 0;
if ($is_hide_contacts) {
$sql = "INSERT INTO `user_object_contact_close` SET `close`='{$is_hide_contacts}', `user_id`='{$user_id}', `object_id` = '{$object_id}', `client_id` = '{$client_id}'";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
// Per-send описание, переданное mJW в POST-параметре `descriptions`.
$descriptionForInsert = "NULL";
if (isset($descriptions[intval($object_id)]) && $descriptions[intval($object_id)] !== '') {
$cleanedDesc = cleanHtml($descriptions[intval($object_id)], '
,
// чтобы абзацы не склеились в одну строку при отображении через echo $obj['opis'] в object-view.php.
if ($cleanedDesc !== '' && strpos($cleanedDesc, '
,
// чтобы абзацы не склеились в одну строку при отображении через echo $obj['opis'] в object-view.php.
if ($cleanedDesc !== '' && strpos($cleanedDesc, '
response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'link' => $link,
'catalog_id' => $catalog_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'errors' => $errors
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
// Образы строк найденных листингов парсера (offset-free, ключ = реальный el.id) для общего цикла сборки PDF-презентаций:
// строк в objects нет, образ собирается из external_listings; фото подгружаются сразу (photo1..N — полные CDN-URL).
// На вход — массив РЕАЛЬНЫХ el.id листингов (потребитель отделяет их от своих объектов на уровне запроса).
// Дозаполняет поля, которых нет у листинга, и переводит код района в название (как ждёт сборка адреса).
// Умерший по TTL листинг в выборку не попадает — вызывающий цикл пропустит его как ненайденный.
private static function _listingRowsForPdf($external_objects_ids) {
require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/helpers/external_listing_legacy.php';
$listing_ids = array_unique(array_map('intval', (array)$external_objects_ids));
$rows = [];
if (!count($listing_ids))
return $rows;
foreach (\external_listing_object_rows($listing_ids, true) as $row) {
// Полей метро/площади комнат у листинга нет — общий цикл сборки PDF читает эти ключи.
$row['peshkom'] = 0;
$row['transport'] = 0;
$row['ploshad_komn'] = '';
// район в образе листинга уже разрешён в название (external_listing_object_rows) — повторный резолв не нужен
$rows[] = $row;
}
return $rows;
}
private function _getPDF($objects_ids = [], $descriptions = [], $new_prices = [], $hide_contacts = false, $external_ids = []) {
global $app;
require_once ROOT_PATH . '/../../ajax/engine/pdf_functions.php';
require_once ROOT_PATH . '/../../ajax/engine/props.php';
global $SROK_ARENDY;
$error = false;
$errors = [];
$pdf_ready = [];
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$result = \SelectelApi::getTokenAndUrl();
$token = $result[0];
$storageUrl = $result[1];
if (($user_id = $_SESSION['id']) && count($objects_ids) > 0) {
/*error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('display_errors', 1);*/
// Offset-free: своё и листинг различаем по входному набору ($external_ids — реальные el.id листингов),
// а НЕ по диапазону id (el.id коллизит с objects.id). Свои тянем из objects (только own-id, иначе листинг
// со совпавшим id задвоился бы), листинги — из external_listings.
$external_ids = array_values(array_unique(array_map('intval', (array)$external_ids)));
$own_ids = array_values(array_diff(array_map('intval', (array)$objects_ids), $external_ids));
$pdf_rows = [];
if (count($own_ids)) {
$sql = "SELECT objects.id, objects.operation_type, objects.nazv, objects.etazh, objects.etazh_iz, objects.stoim,
objects.peshkom, objects.transport, objects.adres, objects.dom, objects.korpus, objects.litera,
objects.id_rf_region, rayon.rayon, objects.ploshad, objects.ploshad_komn, objects.ploshad_k, objects.srok, objects.opis,
objects.type, objects.type_category
FROM objects
LEFT JOIN rayon rayon on objects.rayon = rayon.id
WHERE objects.id IN (".implode(',', $own_ids).")";
if ($query = mysql_query($sql)) {
while ($pdf_row = mysql_fetch_assoc($query))
$pdf_rows[] = $pdf_row;
} else {
$error = true;
$errors[] = $sql;
$errors[] = mysql_error();
}
}
// Найденные листинги парсера: их нет в objects — добавляем образы строк из external_listings
// (умерший по TTL листинг в выборку не попадает и пропускается как ненайденный).
$pdf_rows = array_merge($pdf_rows, self::_listingRowsForPdf($external_ids));
foreach ($pdf_rows as $obj) {
$id = $obj['id'];
$object_id = $obj['id'];
$arrTop = [];
$arrTop['type'] = $obj['type'];
$close_contacts = in_array($id, $hide_contacts);
if ($obj['type'] == 4) {
$sqlCommerce = "SELECT * FROM commercial_object";
$resultCommerce = mysql_query($sqlCommerce);
$arrTypeCommerc = [];
while ($rCommerc = mysql_fetch_assoc($resultCommerce)) {
$arrTypeCommerc[$rCommerc['id']] = $rCommerc['name'];
}
if (isset($arrTypeCommerc[$obj['type_category']])) {
$arrTop['commerce_type'] = $arrTypeCommerc[$obj['type_category']];
}
}
$arrTop['operation_type'] = $obj['operation_type'];
$arrTop['nazv'] = \Filter::name($obj['nazv']);
if ($obj['etazh']*1 != 0) {
$arrTop['etazh'] = $obj['etazh'];
}
if ($obj['etazh_iz']*1 != 0)
$arrTop['etazh_iz'] = $obj['etazh_iz'];
if (!$obj['etazh'])
$arrTop['etazh'] = \Filter::getFloorFromName($arrTop['nazv'],true);
else
\Filter::getFloorFromName($arrTop['nazv'],true);
if (!$obj['etazh_iz'])
$arrTop['etazh_iz'] = \Filter::getMaxFloorFromName($arrTop['nazv'],true);
else
\Filter::getMaxFloorFromName($arrTop['nazv'],true);
\Filter::getSpaceFromName($arrTop['nazv'],true);
$new_price = 0;
$arrTop['stoim'] = number_format($obj['stoim'], 0, ',', ' ');
if (isset($new_prices[$object_id])) {
$new_price = $new_prices[$object_id];
$arrTop['stoim'] = number_format($new_price, 0, ',', ' ');
}
// Для листинга objects-only подзапросы (метро/локация/план/комментарий) по el.id коллизят с objects.id →
// гейтим через $objSubId=-1 (пусто): адрес берётся из образа листинга, план — из первого фото, метро/коммент отсутствуют.
$objSubId = empty($obj['is_external']) ? (int)$obj['id'] : -1;
$mtr = [];
$sql = "SELECT metro.metro FROM metro, sp_metro
WHERE sp_metro.id_metro = metro.id AND sp_metro.id_obj = $objSubId";
if ($result = mysql_query($sql)) {
while($m = mysql_fetch_row($result)) $mtr[] = $m[0];
$metro_str = implode(", ",$mtr);
$do_metro = '';
if ($obj['peshkom'])
$do_metro = $obj['peshkom']." минут пешком";
if ($obj['peshkom'] and $obj['transport'])
$do_metro .= " или ";
if ($obj['transport'])
$do_metro .= $obj['transport']." минут на транспорте";
$arrTop['metrostr'] = $metro_str;
$arrTop['way'] = $do_metro;
} else {
$error = true;
$errors[] = mysql_error();
}
$sqlLocationInfo = "SELECT * FROM object_location WHERE object_id=".$objSubId;
if ($rezLocationInfo = mysql_query($sqlLocationInfo)) {
if (mysql_num_rows($rezLocationInfo) > 0) {
$objLocationInfo = mysql_fetch_assoc($rezLocationInfo);
$adr = $objLocationInfo['address'];
} else {
$address = $obj['adres'];
$adr = '';
if ($obj['id_rf_region'] == 81) {
if (strpos($address, "Санкт-Петербург") === false) {
$adr .= "Санкт-Петербург, ";
}
if ($obj['rayon']) {
$arrTop['rayon'] = str_replace([' район', 'район', ' р-н', 'р-н'], '', $obj['rayon']).' район';
} else {
$arrTop['rayon'] = '';
}
}
$adr .= $address;
}
} else{
$error = true;
$errors[] = mysql_error();
}
$arrTop['address'] = $adr;
if ($obj['ploshad']*1 != 0) {
$obj['ploshad'] *= 1;
$arrTop['ploshad'] = $obj['ploshad'];
} else {
$arrTop['ploshad'] = '';
}
if ($obj['ploshad_komn']*1 != 0) {
if (stripos($obj['ploshad_komn'],"+") == false)
$obj['ploshad_komn'] *= 1;
$arrTop['ploshad_komn'] = $obj['ploshad_komn'];
} else {
$arrTop['ploshad_komn'] = '';
}
if ($obj['ploshad_k']*1 != 0) {
$obj['ploshad_k'] *= 1;
$arrTop['ploshad_k'] = $obj['ploshad_k'];
} else {
$arrTop['ploshad_k'] = '';
}
if ($obj['operation_type']==0) {
$arrTop['sdelka'] = 'Сдается '.$SROK_ARENDY["$obj[srok]"];
} else {
$arrTop['sdelka'] = 'Продажа';
}
$useLocalPhoto = true;
if ($useLocalPhoto) {
$photos = [];
$sqlPhotoInfo = "SELECT oop.sort_order, p.photo FROM objects_object_photo oop, object_photo p WHERE p.id = oop.object_photo_id AND oop.object_id = $id ORDER BY oop.sort_order";
if (!empty($obj['is_external'])) {
// Фото листинга — готовые CDN-URL (photo1..N из образа строки), mpdf скачает их по сети.
for ($ph_i = 1; $ph_i <= 40; $ph_i++) {
if (!empty($obj['photo' . $ph_i]))
array_push($photos, $obj['photo' . $ph_i]);
}
} else if ($rezPhotoInfo = mysql_query($sqlPhotoInfo)) {
if (mysql_num_rows($rezPhotoInfo) > 0) {
while ($photoInfo = mysql_fetch_assoc($rezPhotoInfo)) {
$p = $photoInfo['photo'];
if (stripos($photoInfo['photo'], "http://") === false && stripos($photoInfo['photo'], "https://") === false) {
$p = "https://joywork.ru/photos/" . $photoInfo['photo'];
}
array_push($photos, $p);
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
$arrTop['replace_plan'] = false;
$sql = "SELECT * FROM objects_plan WHERE object_id = $objSubId";
if ($rez_plan = mysql_query($sql)) {
if (mysql_num_rows($rez_plan) > 0) {
$obj_plan = mysql_fetch_assoc($rez_plan);
if ($obj_plan['img_plan'] != '') {
if (stripos($obj_plan['img_plan'], "http://") === false && stripos($obj_plan['img_plan'], "https://") === false) {
if (self::is_ssl())
$obj_plan['img_plan'] = "https://joywork.ru/photos/" . $obj_plan['img_plan'];
else
$obj_plan['img_plan'] = "http://joywork.ru/photos/" . $obj_plan['img_plan'];
}
$arrTop['plan'] = $obj_plan['img_plan'];
} else { // если все же там пусто
if (is_array($photos) && count($photos) > 0) {
$arrTop['replace_plan'] = true;
$arrTop['plan'] = array_shift($photos); // вместо плана берем первую фотографию из всех фото
}
}
} else {
if (is_array($photos) && count($photos) > 0) {
$arrTop['replace_plan'] = true;
$arrTop['plan'] = array_shift($photos); // вместо плана берем первую фотографию из всех фото
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
$sqlComment = "SELECT * FROM user_object_comments WHERE user_id = '$_SESSION[id]' AND object_id='$objSubId'";
if ($rezComment = mysql_query($sqlComment)) {
if (mysql_num_rows($rezComment) > 0) {
$commentRow = mysql_fetch_assoc($rezComment);
$obj['opis'] = $commentRow['comment'];
}
} else {
$error = true;
$errors[] = mysql_error();
}
$opis = '';
if (isset($descriptions[intval($obj['id'])]))
$opis = cleanHtml($descriptions[intval($obj['id'])], '
", $data['message'] . "
") : "Уважаемый клиент, отправляю Вам варианты объектов недвижимости. С удовольствием отвечу на ваши вопросы.
";
}
if ($send_type == 1) {
$message .= "Каталог объектов";
} else {
$message .= "Вы можете посмотреть каталог по ссылке " . $catalog_link . "\r\n";
}
if ($send_type == 1) { // E-mail
foreach ($clients_ids as $client_id) {
$email = mysql_result(mysql_query("SELECT `email` FROM clients WHERE `deleted` <> 1 AND `id` = $client_id"),0);
mailClientByIdWithConfirm($user_id, trim($email), $subject, $message, [], []);
sleep(1);
}
} else if ($send_type == 2) { // WhatsApp
foreach ($clients_ids as $client_id) {
$phone = mysql_result(mysql_query("SELECT `phone` FROM `clients` WHERE `deleted` <> 1 AND `id` = '$client_id'"),0);
$text = !empty($data['message']) ? str_replace("\n", "
", $data['message'] . "
") : "Уважаемый клиент, отправляю Вам варианты объектов недвижимости. С удовольствием отвечу на ваши вопросы.
";
$text = $text . " " . $message;
$links[] = "whatsapp://send?text=" .
urlencode(strip_tags(preg_replace('//', '$1', trim($text)))) . "&phone=+" . preg_replace("/[^,.0-9]/", '', $phone) . "";
}
} else if ($send_type == 3) { // Telegram
foreach ($clients_ids as $client_id) {
$phone = mysql_result(mysql_query("SELECT `phone` FROM `clients` WHERE `deleted` <> 1 AND `id` = '$client_id'"),0);
$text = !empty($data['message']) ? str_replace("\n", "
", $data['message'] . "\n") : "Уважаемый клиент, отправляю Вам варианты объектов недвижимости.\nС удовольствием отвечу на ваши вопросы.\n";
$text = $text . " " . str_replace("
","\n", $message);
$links[] = "tg://msg?text=" .
urlencode(strip_tags(preg_replace('//', '$1', trim($text)))) . "&to=+" . preg_replace("/[^,.0-9]/", '', $phone) . "";
}
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'catalog_link' => $catalog_link,
'links' => $links
], JSON_UNESCAPED_UNICODE));
$app->stop();
} else { // Отправка вложением pdf, списком ссылок на презентации
// Хелперы найденных листингов парсера (offset-free): их нет в objects, образ строки берём из external_listings по реальному el.id.
require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/helpers/external_listing_legacy.php';
$pdf_ready = [];
$token = md5(microtime());
$theme = !empty($subject) ? $subject : "Презентации объектов недвижимости";
if ($send_type == 1) {
$message = !empty(trim($data['message'])) ? str_replace("\n", "
", trim($data['message']) . "
") : "Уважаемый клиент, отправляю Вам варианты объектов недвижимости. С удовольствием отвечу на Ваши вопросы.
";
}
if (!empty(trim($message)) && $provide == 1)
$message = $message . '
';
if (count($objects_ids) > 0 || count($external_objects_ids) > 0 || count($newbuildings_ids) > 0) {
/*error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('display_errors', 1);*/
// Запрос objects — только по своим id (offset-free: листинги собираем отдельно из external_listings).
// Гейт по непустому списку: IN() с пустым набором = синтаксическая ошибка SQL.
$pdf_rows = [];
if (count($objects_ids) > 0) {
$sql = "SELECT objects.id, objects.operation_type, objects.nazv, objects.etazh, objects.etazh_iz, objects.stoim,
objects.peshkom, objects.transport, objects.adres, objects.dom, objects.korpus, objects.litera,
objects.id_rf_region, rayon.rayon, objects.ploshad, objects.ploshad_komn, objects.ploshad_k, objects.srok, objects.opis,
objects.type, objects.type_category
FROM objects
LEFT JOIN rayon rayon on objects.rayon = rayon.id
WHERE objects.id IN (".implode(',', $objects_ids).")";
if ($query = mysql_query($sql)) {
while ($pdf_row = mysql_fetch_assoc($query))
$pdf_rows[] = $pdf_row;
} else {
$error = true;
$errors[] = $sql;
$errors[] = mysql_error();
}
}
// Найденные листинги парсера (offset-free): их нет в objects — добавляем образы строк
// из external_listings по реальным el.id (умерший по TTL листинг в выборку не попадает и пропускается как ненайденный).
$pdf_rows = array_merge($pdf_rows, self::_listingRowsForPdf($external_objects_ids));
foreach ($pdf_rows as $obj) {
$id = $obj['id'];
$arrTop = [];
$arrTop['type'] = $obj['type'];
$close_contacts = in_array($id, $hide_contacts);
if ($obj['type'] == 4) {
$sqlCommerce = "SELECT * FROM commercial_object";
$resultCommerce = mysql_query($sqlCommerce);
$arrTypeCommerc = [];
while ($rCommerc = mysql_fetch_assoc($resultCommerce)) {
$arrTypeCommerc[$rCommerc['id']] = $rCommerc['name'];
}
if (isset($arrTypeCommerc[$obj['type_category']])) {
$arrTop['commerce_type'] = $arrTypeCommerc[$obj['type_category']];
}
}
$arrTop['operation_type'] = $obj['operation_type'];
$arrTop['nazv'] = \Filter::name($obj['nazv']);
if ($obj['etazh']*1 != 0) {
$arrTop['etazh'] = $obj['etazh'];
}
if ($obj['etazh_iz']*1 != 0)
$arrTop['etazh_iz'] = $obj['etazh_iz'];
if (!$obj['etazh'])
$arrTop['etazh'] = \Filter::getFloorFromName($arrTop['nazv'],true);
else
\Filter::getFloorFromName($arrTop['nazv'],true);
if (!$obj['etazh_iz'])
$arrTop['etazh_iz'] = \Filter::getMaxFloorFromName($arrTop['nazv'],true);
else
\Filter::getMaxFloorFromName($arrTop['nazv'],true);
\Filter::getSpaceFromName($arrTop['nazv'],true);
$new_price = 0;
$arrTop['stoim'] = number_format($obj['stoim'], 0, ',', ' ');
if (isset($new_prices[$object_id])) {
$new_price = $new_prices[$object_id];
$arrTop['stoim'] = number_format($new_price, 0, ',', ' ');
}
// Для листинга objects-only подзапросы (метро/локация/план/комментарий) по el.id коллизят с objects.id →
// гейтим через $objSubId=-1 (пусто): адрес берётся из образа листинга, план — из первого фото, метро/коммент отсутствуют.
$objSubId = empty($obj['is_external']) ? (int)$obj['id'] : -1;
$mtr = [];
$sql = "SELECT metro.metro FROM metro, sp_metro
WHERE sp_metro.id_metro = metro.id AND sp_metro.id_obj = $objSubId";
if ($result = mysql_query($sql)) {
while($m = mysql_fetch_row($result)) $mtr[] = $m[0];
$metro_str = implode(", ",$mtr);
$do_metro = '';
if ($obj['peshkom'])
$do_metro = $obj['peshkom']." минут пешком";
if ($obj['peshkom'] and $obj['transport'])
$do_metro .= " или ";
if ($obj['transport'])
$do_metro .= $obj['transport']." минут на транспорте";
$arrTop['metrostr'] = $metro_str;
$arrTop['way'] = $do_metro;
} else {
$error = true;
$errors[] = mysql_error();
}
$sqlLocationInfo = "SELECT * FROM object_location WHERE object_id=".$objSubId;
if ($rezLocationInfo = mysql_query($sqlLocationInfo)) {
if (mysql_num_rows($rezLocationInfo) > 0) {
$objLocationInfo = mysql_fetch_assoc($rezLocationInfo);
$adr = $objLocationInfo['address'];
} else {
$address = $obj['adres'];
$adr = '';
if ($obj['id_rf_region'] == 81) {
if (strpos($address, "Санкт-Петербург") === false) {
$adr .= "Санкт-Петербург, ";
}
if ($obj['rayon']) {
$arrTop['rayon'] = str_replace([' район', 'район', ' р-н', 'р-н'], '', $obj['rayon']).' район';
} else {
$arrTop['rayon'] = '';
}
}
$adr .= $address;
}
} else{
$error = true;
$errors[] = mysql_error();
}
$arrTop['address'] = $adr;
if ($obj['ploshad']*1 != 0) {
$obj['ploshad'] *= 1;
$arrTop['ploshad'] = $obj['ploshad'];
} else {
$arrTop['ploshad'] = '';
}
if ($obj['ploshad_komn']*1 != 0) {
if (stripos($obj['ploshad_komn'],"+") == false)
$obj['ploshad_komn'] *= 1;
$arrTop['ploshad_komn'] = $obj['ploshad_komn'];
} else {
$arrTop['ploshad_komn'] = '';
}
if ($obj['ploshad_k']*1 != 0) {
$obj['ploshad_k'] *= 1;
$arrTop['ploshad_k'] = $obj['ploshad_k'];
} else {
$arrTop['ploshad_k'] = '';
}
if ($obj['operation_type']==0) {
$arrTop['sdelka'] = 'Сдается '.$SROK_ARENDY["$obj[srok]"];
} else {
$arrTop['sdelka'] = 'Продажа';
}
$useLocalPhoto = true;
if ($useLocalPhoto) {
$photos = [];
$sqlPhotoInfo = "SELECT oop.sort_order, p.photo FROM objects_object_photo oop, object_photo p WHERE p.id = oop.object_photo_id AND oop.object_id = $id ORDER BY oop.sort_order";
if (!empty($obj['is_external'])) {
// Фото листинга — готовые CDN-URL (photo1..N из образа строки), mpdf скачает их по сети.
for ($ph_i = 1; $ph_i <= 40; $ph_i++) {
if (!empty($obj['photo' . $ph_i]))
array_push($photos, $obj['photo' . $ph_i]);
}
} else if ($rezPhotoInfo = mysql_query($sqlPhotoInfo)) {
if (mysql_num_rows($rezPhotoInfo) > 0) {
while ($photoInfo = mysql_fetch_assoc($rezPhotoInfo)) {
$p = $photoInfo['photo'];
if (stripos($photoInfo['photo'], "http://") === false && stripos($photoInfo['photo'], "https://") === false) {
$p = "https://joywork.ru/photos/" . $photoInfo['photo'];
}
array_push($photos, $p);
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
$arrTop['replace_plan'] = false;
$sql = "SELECT * FROM objects_plan WHERE object_id = $objSubId";
if ($rez_plan = mysql_query($sql)) {
if (mysql_num_rows($rez_plan) > 0) {
$obj_plan = mysql_fetch_assoc($rez_plan);
if ($obj_plan['img_plan'] != '') {
if (stripos($obj_plan['img_plan'], "http://") === false && stripos($obj_plan['img_plan'], "https://") === false) {
if (self::is_ssl())
$obj_plan['img_plan'] = "https://joywork.ru/photos/" . $obj_plan['img_plan'];
else
$obj_plan['img_plan'] = "http://joywork.ru/photos/" . $obj_plan['img_plan'];
}
$arrTop['plan'] = $obj_plan['img_plan'];
} else { // если все же там пусто
if (is_array($photos) && count($photos) > 0) {
$arrTop['replace_plan'] = true;
$arrTop['plan'] = array_shift($photos); // вместо плана берем первую фотографию из всех фото
}
}
} else {
if (is_array($photos) && count($photos) > 0) {
$arrTop['replace_plan'] = true;
$arrTop['plan'] = array_shift($photos); // вместо плана берем первую фотографию из всех фото
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
$sqlComment = "SELECT * FROM user_object_comments WHERE user_id = '$_SESSION[id]' AND object_id='$objSubId'";
if ($rezComment = mysql_query($sqlComment)) {
if (mysql_num_rows($rezComment) > 0) {
$commentRow = mysql_fetch_assoc($rezComment);
$obj['opis'] = $commentRow['comment'];
}
} else {
$error = true;
$errors[] = mysql_error();
}
$opis = '';
if (isset($descriptions[intval($obj['id'])]))
$opis = cleanHtml($descriptions[intval($obj['id'])], '
$manager
" . $user->phone . "
" . $user->email;
if ($_SESSION['individual'] == 0)
$footer .= "
$title
$phone";
$pdfs = $adresses = [];
if (count($objects_ids) || count($external_objects_ids)) {
// Offset-free: общий проход по своим объектам и листингам (объединённый список реальных id),
// признак листинга — по сету external_objects_ids, а не по диапазону id (коллизия el.id == objects.id).
foreach (array_merge($objects_ids, $external_objects_ids) as $object_id) {
// Найденный листинг парсера: строки в objects нет, образ собираем из external_listings по реальному el.id.
$listing_row = null;
if (isset($listing_id_set[$object_id])) {
$listing_row = \external_listing_object_row($object_id, false);
// Листинг удалён по TTL — пропускаем до накопления вложений (pdfs/adresses идут парами).
if (is_null($listing_row))
continue;
// Поля внешнего источника экранируем для прямой подстановки в SQL.
$listing_row['nazv'] = mysql_real_escape_string($listing_row['nazv']);
$listing_row['adres'] = mysql_real_escape_string($listing_row['adres']);
}
$pdf_path = $_SERVER['DOCUMENT_ROOT'] . "/pdf/$object_id-$user_id.pdf";
$pdfs[] = $pdf_path;
if ($pdf_ready[$object_id] && file_exists($pdf_path)) {
$name = "$object_id-$user_id.pdf";
$x = mb_substr($name,0,1);
$y = mb_substr($name,1,1);
$z = mb_substr($name,2,1);
$dstFile = "$x/$y/$z/$name";
if (\SelectelApi::uploadPdfFile($storageUrl, $token, $pdf_path, $dstFile)) {
$link = "https://pdf.joywork.ru/" . $dstFile;
$pdfs_links[$object_id] = $link;
} else {
if (self::is_ssl())
$pdfs_links[$object_id] = "https://joywork.ru/pdf/$object_id-$user_id.pdf";
else
$pdfs_links[$object_id] = "http://joywork.ru/pdf/$object_id-$user_id.pdf";
}
} else {
$pdfs_links[$object_id] = null;
}
// Найденный листинг парсера: пишем историю отправки и снапшот по реальному el.id, контакта нет.
if (!is_null($listing_row)) {
$obj = $listing_row;
$adresses[] = $obj['nazv'];
// Снапшот листинга в archive: phone/sobstv пустые (контакт скрыт по 152-ФЗ).
$sql = "SELECT * FROM `archive` WHERE `id_obj` = '$object_id'";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query)) {
$sql = "UPDATE `archive` SET `nazv`='$obj[nazv]', `adres`='$obj[adres]', `phone`='', `sobstv`='' WHERE `id_obj` = '$object_id'";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
} else {
$sql = "INSERT INTO archive(nazv, adres, phone, sobstv, id_obj) VALUES('$obj[nazv]', '$obj[adres]', '', '', '$object_id')";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
$new_price = 0;
if (isset($new_prices[$object_id])) {
$new_price = $new_prices[$object_id];
}
foreach ($clients_ids as $client_id) {
$lnk = $pdfs_links[$object_id];
// Per-send описание, переданное mJW в POST-параметре `descriptions`.
$descriptionForInsert = "NULL";
if (isset($descriptions[intval($object_id)]) && $descriptions[intval($object_id)] !== '') {
$cleanedDesc = cleanHtml($descriptions[intval($object_id)], '
,
// чтобы абзацы не склеились в одну строку при отображении через echo $obj['opis'] в object-view.php.
if ($cleanedDesc !== '' && strpos($cleanedDesc, '
0) {
$asfilter = new \AutoSearch();
foreach ($asfilter_objects as $filter_id => $object_id) {
if (!is_null($filter_id) && !is_null($object_id))
$asfilter->addObjectToSended($filter_id, $object_id);
}
}
continue;
}
$sql = "SELECT * FROM objects WHERE id=$object_id";
if ($rez = mysql_query($sql)) {
$obj = mysql_fetch_assoc($rez);
//Доп обработка
if (!$obj['etazh'])
$obj['etazh'] = \Filter::getFloorFromName($obj['nazv'], true);
else
\Filter::getFloorFromName($obj['nazv'], true);
if (!$obj['etazh_iz'])
$obj['etazh_iz'] = \Filter::getMaxFloorFromName($obj['nazv'], true);
else
\Filter::getMaxFloorFromName($obj['nazv'], true);
\Filter::getSpaceFromName($obj['nazv'], true);
$obj['nazv'] = \Filter::name($obj['nazv']);
$adresses[] = $obj['nazv'];
$sql = "SELECT * FROM `archive` WHERE `id_obj` = '$object_id'";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query)) {
$sql = "UPDATE `archive` SET `nazv`='$obj[nazv]', `adres`='$obj[adres]', `phone`='$obj[phone]', `sobstv`='$obj[sobstv]' WHERE `id_obj` = '$object_id'";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
} else {
$sql = "INSERT INTO archive(nazv, adres, phone, sobstv, id_obj) VALUES('$obj[nazv]', '$obj[adres]', '$obj[phone]', '$obj[sobstv]', '$object_id')";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
$new_price = 0;
if (isset($new_prices[$object_id])) {
$new_price = $new_prices[$object_id];
}
foreach ($clients_ids as $client_id) {
$lnk = $pdfs_links[$object_id];
// Per-send описание, переданное mJW в POST-параметре `descriptions`.
$descriptionForInsert = "NULL";
if (isset($descriptions[intval($object_id)]) && $descriptions[intval($object_id)] !== '') {
$cleanedDesc = cleanHtml($descriptions[intval($object_id)], '
,
// чтобы абзацы не склеились в одну строку при отображении через echo $obj['opis'] в object-view.php.
if ($cleanedDesc !== '' && strpos($cleanedDesc, '
0) {
$asfilter = new AutoSearch();
foreach ($asfilter_objects as $filter_id => $object_id) {
if (!is_null($filter_id) && !is_null($object_id))
$asfilter->addObjectToSended($filter_id, $object_id);
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
}
if (count($newbuildings_ids)) {
foreach ($newbuildings_ids as $object_id) {
if (self::is_ssl())
$linkUrl = "https://joywork.ru/newbuilding-view.php?id=$object_id&token=" . md5($user_id);
else
$linkUrl = "http://joywork.ru/newbuilding-view.php?id=$object_id&token=" . md5($user_id);
$sql = "SELECT a.id, a.number, b.name, b.address FROM apartments a, blocks b WHERE b.id = a.block_id AND a.id='$object_id'";
if ($rez = mysql_query($sql)) {
if (mysql_num_rows($rez) > 0) {
$obj = mysql_fetch_assoc($rez);
$nazv = "Квартира №$obj[number] в комплексе $obj[name]";
if ($send_type == 1) {
$txt .= "
$nazv
";
} else {
$txt .= $nazv . " " . $linkUrl;
}
foreach ($clients_ids as $client_id) {
$sql = "INSERT INTO sended_pdf_newbuildings(id_agent, id_object, date_send, id_client, nazv, path, send_type) VALUES('$user_id', '$object_id', NOW(), '$client_id', '$nazv $obj[address]', '$linkUrl', $send_type)";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
if (count($asfilter_objects) > 0) {
$asfilter = new \AutoSearch();
foreach ($asfilter_objects as $filter_id => $object_id) {
if (!is_null($filter_id) && !is_null($object_id))
$asfilter->addObjectToSended($filter_id, $object_id);
}
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
}
$txt .= $footer;
$address = [];
$attachments = [];
for ($i = 0; $i < count($pdfs); $i++) {
$num = $i + 1;
$attachments[$x][] = $pdfs[$i];
$address[$x][] = $adresses[$i];
if ($num % 5 == 0)
$x++;
}
try {
foreach ($clients_ids as $client_id) {
$email = mysql_result(mysql_query("SELECT email FROM clients WHERE deleted <> 1 AND id = $client_id"), 0);
if (isset($attachments)) {
foreach ($attachments as $x => $attachment) {
mailClientByIdWithConfirm($user_id, trim($email), $theme, $txt, $attachment, $address[$x]);
if ($token && $storageUrl) {
foreach ($attachment as $i => $path) {
//удаляем файл с локального сервера
unlink($path);
}
}
sleep(1);
}
} else {
mailClientByIdWithConfirm($user_id, trim($email), $theme, $txt, [], []);
}
}
} catch (\Exception $e) {
$error = true;
$errors[] = $e;
}
} else if ($send_type && $provide == 1) { // send as links
$txt = $message;
$toSendASFilter = [];
if (isset($_SESSION['to_send_asfilter']))
$toSendASFilter = $_SESSION['to_send_asfilter'];
$_SESSION['to_send'] = [];
$_SESSION['to_send_newbuilding'] = [];
$_SESSION['to_send_asfilter'] = [];
// Сбрасываем черновики per-send описаний вместе с корзиной.
$_SESSION['to_send_descriptions'] = [];
if (count($objects_ids) || count($external_objects_ids)) {
if ($send_type == 1)
$txt .= '';
// Offset-free: общий проход по своим объектам и листингам (объединённый список реальных id),
// признак листинга — по сету external_objects_ids, а не по диапазону id (коллизия el.id == objects.id).
foreach (array_merge($objects_ids, $external_objects_ids) as $object_id) {
// Листинг адресуется явным маркером src=ext (bare id уже не различает листинг от своего объекта).
// Для листинга эта ссылка всё равно перезаписывается токеновой ниже, но держим инвариант offset-free.
$src_marker = isset($listing_id_set[$object_id]) ? '&src=ext' : '';
if (self::is_ssl())
$linkUrl = "https://joywork.ru/object-view.php?id=$object_id&token=" . md5($user_id) . $src_marker;
else
$linkUrl = "http://joywork.ru/object-view.php?id=$object_id&token=" . md5($user_id) . $src_marker;
// Найденный листинг парсера: образ строки из external_listings по реальному el.id,
// ссылка клиенту — по токену записи отправки (md5 от id строки sended_pdf).
if (isset($listing_id_set[$object_id])) {
$obj = \external_listing_object_row($object_id, false);
if (is_null($obj)) {
// Листинг удалён по TTL — пропускаем, в письмо и историю не попадает.
continue;
}
// Поля внешнего источника экранируем для прямой подстановки в SQL.
$obj['nazv'] = mysql_real_escape_string($obj['nazv']);
$obj['adres'] = mysql_real_escape_string($obj['adres']);
// Снапшот листинга в archive: phone/sobstv пустые (контакт скрыт по 152-ФЗ).
$sql = "SELECT * FROM `archive` WHERE `id_obj` = '$object_id'";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query)) {
$sql = "UPDATE `archive` SET `nazv`='$obj[nazv]', `adres`='$obj[adres]', `phone`='', `sobstv`='' WHERE `id_obj` = '$object_id'";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
} else {
$sql = "INSERT INTO archive(nazv, adres, phone, sobstv, id_obj) VALUES('$obj[nazv]', '$obj[adres]', '', '', '$object_id')";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
foreach ($clients_ids as $client_id) {
$linkUrl .= "&client=".md5($client_id);
$close_contact = 0;
if (in_array($object_id, $hide_contacts))
$close_contact = 1;
// user_object_contact_close для листинга не пишем — его контакт скрыт всегда.
$new_price = 0;
if (isset($new_prices[$object_id])) {
$new_price = $new_prices[$object_id];
}
// Per-send описание, переданное mJW в POST-параметре `descriptions`.
$descriptionForInsert = "NULL";
if (isset($descriptions[intval($object_id)]) && $descriptions[intval($object_id)] !== '') {
$cleanedDesc = cleanHtml($descriptions[intval($object_id)], '
,
// чтобы абзацы не склеились в одну строку при отображении через echo $obj['opis'] в object-view.php.
if ($cleanedDesc !== '' && strpos($cleanedDesc, '
0) {
$asfilter = new \AutoSearch();
foreach ($toSendASFilter as $filter_id => $object_id) {
if (!is_null($filter_id) && !is_null($object_id))
$asfilter->addObjectToSended($filter_id, $object_id);
}
}
if ($send_type == 1) {
$txt .= "
';
}
if (count($newbuildings_ids)) {
if ($send_type == 1)
$txt .= '
,
// чтобы абзацы не склеились в одну строку при отображении через echo $obj['opis'] в object-view.php.
if ($cleanedDesc !== '' && strpos($cleanedDesc, '
0) {
$asfilter = new \AutoSearch();
foreach ($toSendASFilter as $filter_id => $object_id) {
if (!is_null($filter_id) && !is_null($object_id))
$asfilter->addObjectToSended($filter_id, $object_id);
}
}
if ($send_type == 1) {
$txt .= "';
foreach ($newbuildings_ids as $object_id) {
if (self::is_ssl())
$linkUrl = "https://joywork.ru/newbuilding-view.php?id=$object_id&token=" . md5($user_id);
else
$linkUrl = "http://joywork.ru/newbuilding-view.php?id=$object_id&token=" . md5($user_id);
$sql = "SELECT a.id, a.number, b.name, b.address FROM apartments a, blocks b WHERE b.id = a.block_id AND a.id='$object_id'";
if ($rez = mysql_query($sql)) {
if (mysql_num_rows($rez) > 0) {
$obj = mysql_fetch_assoc($rez);
$nazv = "Квартира №$obj[number] в комплексе $obj[name]";
foreach ($clients_ids as $client_id) {
$linkUrl .= "&client=".md5($client_id);
$close_contact = 0;
if (in_array($object_id, $hide_contacts))
$close_contact = 1;
$sql_up = "INSERT INTO user_object_contact_close SET close={$close_contact}, user_id={$user_id}, object_id = {$object_id}, client_id = {$client_id}";
if (!mysql_query($sql_up)) {
$error = true;
$errors[] = mysql_error();
}
// Per-send описание, переданное mJW в POST-параметре `descriptions`.
$descriptionForInsert = "NULL";
if (isset($descriptions[intval($object_id)]) && $descriptions[intval($object_id)] !== '') {
$cleanedDesc = cleanHtml($descriptions[intval($object_id)], '
';
}
if ($send_type == 1) {
if ($_SESSION['individual']) {
$txt .= "
,
// чтобы абзацы не склеились в одну строку при отображении через echo $obj['opis'] в object-view.php.
if ($cleanedDesc !== '' && strpos($cleanedDesc, '
0) {
$asfilter = new \AutoSearch();
foreach ($toSendASFilter as $filter_id => $object_id) {
if (!is_null($filter_id) && !is_null($object_id))
$asfilter->addObjectToSended($filter_id, $object_id);
}
}
if ($send_type == 1) {
$txt .= "
$manager
".$user->phone."
".$user->email;
} else {
$txt .= "
$manager
".$user->phone."
".$user->email."
$title
$phone";
}
}
if ($send_type == 1) {
try {
foreach ($clients_ids as $client_id) {
$email = mysql_result(mysql_query("SELECT email FROM clients WHERE deleted <> 1 AND id = $client_id"), 0);
mailClientByIdWithConfirm($user_id, trim($email), $theme, $txt, [], []);
sleep(1);
}
} catch (\Exception $e) {
$error = true;
$errors[] = $e;
}
} else if ($send_type == 2) {
$phone = mysql_result(mysql_query("SELECT phone FROM clients WHERE deleted <> 1 AND id = $clients_ids[0]"), 0);
$text = !empty(trim($data['message'])) ? str_replace("\n", "
", trim($data['message']) . "
") : "Уважаемый клиент, отправляю Вам варианты объектов недвижимости. С удовольствием отвечу на ваши вопросы.
";
$txt = $text . " " . $txt;
/*if ($_SESSION['meta']['isStandalone']) { //whatsapp: 'whatsapp://send?text={message}&phone=+{phone}',
$links[] = "whatsapp://send?text=" .
urlencode(strip_tags(preg_replace('//', '$1', trim($txt)))) . "&phone=+" . preg_replace("/[^,.0-9]/", '', $phone) . "";
} else {
$links[] = "https://wa.me/" . preg_replace("/[^,.0-9]/", '', $phone) . "?text=" .
urlencode(strip_tags(preg_replace('//', '$1', trim($txt)))) . " ";
}*/
$links[] = "whatsapp://send?text=" .
urlencode(strip_tags(preg_replace('//', '$1', trim($txt)))) . "&phone=+" . preg_replace("/[^,.0-9]/", '', $phone) . "";
} else if ($send_type == 3) {
//$phone = mysql_result(mysql_query("SELECT phone FROM clients WHERE deleted <> 1 AND id = $clients_ids[0]"), 0);
$text = !empty(trim($data['message'])) ? str_replace("\n", "
", trim($data['message']) . "
") : "Уважаемый клиент, отправляю Вам варианты объектов недвижимости. С удовольствием отвечу на ваши вопросы.
";
$txt = $text . " " . $txt;
/*if ($_SESSION['meta']['isStandalone']) { //telegram: 'tg://msg?text={message}&to=+{phone}',
$links[] = "tg://msg?text=" .
urlencode(strip_tags(preg_replace('//', '$1', trim($txt)))) . " ";
} else {
$links[] = "https://telegram.me/share/url?url=%20&text=" .
urlencode(strip_tags(preg_replace('//', '$1', trim($txt)))) . " ";
}*/
$links[] = "tg://msg?text=" .
urlencode(strip_tags(preg_replace('//', '$1', trim($txt)))) . "&to=+" . preg_replace("/[^,.0-9]/", '', $phone) . "";
}
}
}
if (!count($errors)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'pdfs_links' => $pdfs_links,
'presentations' => $presentations,
'links' => $links,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'errors' => $errors
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function crossPosting($app, $get = null, $post = null) {
$error = false;
$errors = [];
if ($user_id = $_SESSION['id']) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$body = $app->request->getBody();
$data = json_decode($body, true);
$object_id = null;
if (isset($data['object_id']))
$object_id = intval($data['object_id']);
// Найденный листинг парсера read-only: публикация в ВК недоступна (паритет с десктопом addVkPost).
// Признак листинга — явный флаг is_external из запроса (offset-free: id коллизит с objects.id).
if ($object_id && self::_request_flag($data, 'is_external')) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(403);
$app->response->setBody(json_encode([
'success' => false,
'errors' => ['Действие недоступно для найденного листинга. Скопируйте объект в свои, чтобы управлять им.'],
], JSON_UNESCAPED_UNICODE));
return;
}
$message = null;
if (isset($data['message']))
$message = trim($data['message']);
$section = null;
if (isset($data['section']))
$section = trim($data['section']);
if (!is_null($object_id) && !is_null($section) && !empty($message)) {
$files = [];
if ($section == 'vkontakte') {
$targets = null;
if (isset($data['targets']))
$targets = $data['targets'];
$sql = "SELECT * FROM objects WHERE objects.id = $object_id";
if (count($targets) && $query = mysql_query($sql)) {
$obj = mysql_fetch_assoc($query);
if ($obj) {
$sql = "SELECT oop.sort_order, p.photo FROM objects_object_photo oop, object_photo p WHERE p.id = oop.object_photo_id AND oop.object_id = $obj[id] ORDER BY oop.sort_order";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
while ($photo = mysql_fetch_assoc($query)) {
$obj['photo' . $photo['sort_order']] = $photo['photo'];
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
$user = null;
$sql = "SELECT * FROM users WHERE id = $user_id";
if ($query = mysql_query($sql)) {
$user = mysql_fetch_assoc($query);
} else {
$error = true;
$errors[] = mysql_error();
}
if (isset($user['vk_token'])) {
$config['access_token'] = $user['vk_token'];
require_once($_SERVER['DOCUMENT_ROOT'] . '/vk.php');
$v = new \Vk($config);
if (!is_dir($_SERVER['DOCUMENT_ROOT'] . "/photos")) {
@mkdir($_SERVER['DOCUMENT_ROOT'] . "/photos", 0777);
@chmod($_SERVER['DOCUMENT_ROOT'] . "/photos", 0777);
}
if (!is_dir($_SERVER['DOCUMENT_ROOT'] . "/photos/vk_temp")) {
@mkdir($_SERVER['DOCUMENT_ROOT'] . "/photos/vk_temp", 0777);
@chmod($_SERVER['DOCUMENT_ROOT'] . "/photos/vk_temp", 0777);
}
for ($num = 1; $num <= 20; $num++) {
if (isset($obj['photo' . $num]) && $obj['photo' . $num]) {
if (stripos($obj['photo' . $num], "http://") === false && stripos($obj['photo' . $num], "https://") === false) {
if (substr($obj['photo' . $num], -1) == '.') {
$pathInfo = pathinfo($obj['photo' . $num]);
file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/photos/vk_temp/" . $pathInfo['basename'] . 'jpg', file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/photos/' . $obj['photo' . $num]));
$obj['photo' . $num] = $_SERVER['DOCUMENT_ROOT'] . '/photos/vk_temp/' . $pathInfo['basename'] . 'jpg';
} else {
$obj['photo' . $num] = $_SERVER['DOCUMENT_ROOT'] . '/photos/' . $obj['photo' . $num];
}
} else {
$pathInfo = pathinfo($obj['photo' . $num]);
$filename = $pathInfo['basename'];
if (substr($obj['photo' . $num], -1) == '.') {
$filename = $pathInfo['basename'] . 'jpg';
}
file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/photos/vk_temp/" . $filename, file_get_contents($obj['photo' . $num]));
$obj['photo' . $num] = $_SERVER['DOCUMENT_ROOT'] . '/photos/vk_temp/' . $filename;
}
$files[] = $obj['photo' . $num];
if (count($files) == 5) {
break;
}
}
}
$vk_group_ids = explode(",", trim($user['vk_group_id'], ","));
if (count($vk_group_ids)) {
foreach ($vk_group_ids as $vk_group_id) {
if (in_array(trim($vk_group_id), $targets)) {
$method = 'wall.post';
$params = []; //в этом массиве - параметры, которые мы отправляем
$params['message'] = $message; //в данном случае - только само сообщение
$params['owner_id'] = '-' . trim($vk_group_id); //Ид группы
if (isset($user['vk_post_as_group']) && $user['vk_post_as_group'] == 1)
$params['from_group'] = '1'; //От имени группы
$response = null;
try {
if ($files && count($files) > 0)
$responseImg = $v->upload_photo(trim($vk_group_id), $user['vk_user_id'], $files); //выполняем
if (isset($responseImg) && count($responseImg) > 0)
$params['attachments'] = implode(",", $responseImg); //картинки
$response = $v->api($method, $params); //выполняем
/*if ($_SESSION['id'] == 5427) {
var_export($params);
var_export($response);
die();
}*/
} catch (\Exception $e) {
$error = true;
$errors[] = $e->getMessage();
}
if (isset($response['error'])) {
$error = true;
$errors[] = 'Ошибка добавления поста в группу: ' . $response['error']['error_msg'];
}
}
}
}
if (in_array(trim($user['vk_user_id']), $targets)) {
$method = 'wall.post';
$params = []; //в этом массиве - параметры, которые мы отправляем
$params['message'] = $message; //в данном случае - только само сообщение
$params['owner_id'] = $user['vk_user_id']; //Ид пользователя
$response = null;
try {
if ($files && count($files) > 0)
$responseImg = $v->upload_photo("", $user['vk_user_id'], $files); //выполняем
if (isset($responseImg) && count($responseImg) > 0)
$params['attachments'] = implode(",", $responseImg); //картинки
$response = $v->api($method, $params); //выполняем
/*if ($_SESSION['id'] == 5427) {
var_export($params);
var_export($response);
die();
}*/
} catch (\Exception $e) {
$error = true;
$errors[] = $e->getMessage();
}
if (isset($response['error'])) {
$error = true;
$errors[] = 'Ошибка добавления поста на стену пользователя: ' . $response['error']['error_msg'];
}
}
} else {
$error = true;
$errors[] = 'Не указан токен API ВКонтакте.';
}
} else {
$error = true;
$errors[] = 'Не найден объект для публикации.';
}
} else {
$error = true;
$errors[] = mysql_error();
}
} else {
$error = true;
$errors[] = 'Не выбрана площадка для публикации.';
}
// удаляем файлы
if ($section == 'vkontakte') {
foreach ($files as $name) {
if (stripos($name, "vk_temp") !== false) {
unlink($name);
}
}
}
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => $user_id,
'object_id' => $object_id,
'targets' => $targets,
'section' => $section,
'message' => $message,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'object_id' => $object_id,
'targets' => $targets,
'section' => $section,
'message' => $message,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function deleteFile($app, $get = null, $post = null) {
$error = false;
$errors = [];
$section = null;
if (isset($get['section']))
$section = $get['section'];
$object_id = null;
if (isset($get['object_id']))
$object_id = intval($get['object_id']);
$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']);
$funnel_id = null;
if (isset($get['funnel_id']))
$funnel_id = intval($get['funnel_id']);
$event_id = null;
if (isset($get['event_id']))
$event_id = intval($get['event_id']);
$filename = null;
if (isset($get['filename']))
$filename = $get['filename'];
$is_temp = false;
if (isset($get['is_temp']))
$is_temp = ($get['is_temp'] == 'true');
$temp_path = null;
$object_photo_id = null;
if (($user_id = intval($_SESSION['id'])) && $section && $filename) {
$result = \SelectelApi::getTokenAndUrl();
$token = $result[0];
$storageUrl = $result[1];
if (in_array($section, ['photo', 'photoDom', 'img_plan', 'tasks', 'clients', 'funnels'])) {
if ($section == 'tasks' || in_array($section, ['photo', 'photoDom', 'img_plan'])) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
}
$path_parts = pathinfo($filename);
$basename = $path_parts['basename'];
$extension = $path_parts['extension'];
$guid = md5($basename);
$temp_dir = null;
if ($section == 'clients' && $client_id) {
$temp_dir = "/upload/clients/" . trim($client_id);
} else if ($section == 'funnels' && $funnel_id) {
$temp_dir = "/upload/funnels/" . trim($funnel_id);
} else if (in_array($section, ['photo', 'photoDom', 'img_plan'])) {
$temp_dir = "/photos/";
} else if ($section == 'tasks' && ($object_id || $client_id || $requisition_id)) {
if ($client_id > 0) {
$temp_dir = "/upload/clients/" . $client_id;
} else if ($requisition_id > 0) {
$temp_dir = "/upload/reqs/" . $requisition_id;
} else if ($object_id > 0) {
$temp_dir = "/upload/objects/" . $object_id;
}
}
if ($section == 'clients' && $client_id) {
$temp_path = $_SERVER['DOCUMENT_ROOT'] . $temp_dir . "/" . $guid . '.' . $extension;
} else if ($section == 'tasks') {
if ($client_id > 0) {
$sql = "WHERE `event_id` = '{$event_id}' AND `client_id` = '{$client_id}' AND `name` = '{$filename}' LIMIT 1";
} else if ($requisition_id > 0) {
$sql = "WHERE `event_id` = '{$event_id}' AND `req_id` = '{$requisition_id}' AND `name` = '{$filename}' LIMIT 1";
} else if ($object_id > 0) {
$sql = "WHERE `event_id` = '{$event_id}' AND `object_id` = '{$object_id}' AND `name` = '{$filename}' LIMIT 1";
}
if (!empty($sql)) {
if ($query = mysql_query("SELECT * FROM `clients_files` " . $sql)) {
$row = mysql_fetch_assoc($query);
if (isset($row['guid'])) {
$guid = $row['guid'];
$get['guid'] = $guid;
$temp_path = $_SERVER['DOCUMENT_ROOT'] . $temp_dir . "/" . $guid.'.'.$extension;
if (!mysql_query("DELETE FROM `clients_files` " . $sql)) {
$error = true;
$errors[] = mysql_error();
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
} else if (in_array($section, ['photo', 'photoDom', 'img_plan'])) {
$one = mb_substr($basename, 0, 1);
$two = mb_substr($basename, 1, 1);
$three = mb_substr($basename, 3, 1);
$path = "$one/$two/$three/$basename";
if ($is_temp) {
$temp_path = $_SERVER['DOCUMENT_ROOT'] . $temp_dir . $path;
} else {
if (!is_null($object_id)) {
if (in_array($section, ['photo', 'photoDom'])) {
$sql = "SELECT `photos`.`id`,
`photos`.`object_photo_id`,
`photo`.`photo` AS `path`
FROM `objects_object_photo` AS `photos`
LEFT JOIN `object_photo` AS `photo` ON `photo`.`id` = `photos`.`object_photo_id`
WHERE `photos`.`object_id` = '$object_id' AND `photo`.`photo` LIKE '%$filename%' LIMIT 1";
if ($query = mysql_query($sql)) {
$photo = mysql_fetch_assoc($query);
if (!empty($photo["path"])) {
$object_photo_id = (int)$photo["object_photo_id"];
$temp_photo_path = str_replace("http://c01.joywork.ru/photos/", "", $photo["path"]);
$temp_photo_path = str_replace("https://data.joywork.ru/", "", $temp_photo_path);
$temp_path = $temp_dir . $temp_photo_path;
}
} else {
$error = true;
$errors[] = mysql_error();
}
} else {
//todo
$sql = "SELECT *
FROM `objects_plan` AS `plan` WHERE `plan`.`object_id` = '$object_id' AND `plan`.`img_plan` LIKE '%$filename%' LIMIT 1";
if ($query = mysql_query($sql)) {
$photo = mysql_fetch_assoc($query);
if (!empty($photo["img_plan"])) {
$temp_photo_path = str_replace("http://c01.joywork.ru/photos/", "", $photo["img_plan"]);
$temp_photo_path = str_replace("https://data.joywork.ru/", "", $temp_photo_path);
$temp_path = $temp_dir . $temp_photo_path;
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
} else {
$error = true;
$errors[] = 'Object ID is required for not temporary photos.';
}
}
} else {
$temp_path = $_SERVER['DOCUMENT_ROOT'] . $temp_dir . "/" . $basename;
}
if (!$is_temp && !empty($temp_path) && in_array($section, ['photo', 'photoDom', 'img_plan'])) {
$nfp = str_replace("https://data.joywork.ru/", "", $temp_path);
$nfp = str_replace("http://c01.joywork.ru/photos/", "", $nfp);
$nfp = str_replace("https://joywork.ru/photos/", "", $nfp);
$nfp = str_replace("/photos/", "", $nfp);
\SelectelApi::deleteFile($storageUrl, $token, $nfp);
if ($object_photo_id && in_array($section, ['photo', 'photoDom'])) {
if (!mysql_query("DELETE FROM object_photo WHERE id = '$object_photo_id'")) {
$error = true;
$errors[] = mysql_error();
}
if (!mysql_query("DELETE FROM objects_object_photo WHERE object_id = '$object_id' AND object_photo_id = '$object_photo_id'")) {
$error = true;
$errors[] = mysql_error();
}
} else {
if ($section == 'img_plan') {
if (!mysql_query("DELETE FROM objects_plan WHERE object_id = '$object_id'")) {
$error = true;
$errors[] = mysql_error();
}
}
}
} else if ($is_temp && !empty($temp_path) && in_array($section, ['photo', 'photoDom', 'img_plan'])) {
if (file_exists($temp_path)) { // Удаляем загруженное и сохраненное фото
if (!unlink($temp_path)) {
$error = true;
$errors[] = "Delete file error.";
} else {
$nfp = str_replace("https://data.joywork.ru/", "", $temp_path);
$nfp = str_replace("http://c01.joywork.ru/photos/", "", $nfp);
$nfp = str_replace("https://joywork.ru/photos/", "", $nfp);
$nfp = str_replace("/photos/", "", $nfp);
\SelectelApi::deleteFile($storageUrl, $token, $nfp);
}
} else { // Значит удаляем только что загруженное фото
$temp_path = $_SERVER['DOCUMENT_ROOT'] . '/photos/obj_temp/' . $user_id . '/' . $basename;
if (file_exists($temp_path)) {
if (!unlink($temp_path)) {
$error = true;
$errors[] = "Delete file error.";
}
}
}
} else if (file_exists($temp_path)) {
if (!unlink($temp_path)) {
$error = true;
$errors[] = "Delete file error.";
} else if (in_array($section, ['photo', 'photoDom', 'img_plan'])) {
$nfp = str_replace("https://data.joywork.ru/", "", $temp_path);
\SelectelApi::deleteFile($storageUrl, $token, $nfp);
}
} else {
$error = true;
$errors[] = "File not exists.";
}
}
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => $user_id,
'section' => $section,
'object_id' => $object_id,
'object_photo_id' => $object_photo_id,
'get' => $get,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'errors' => $errors,
'temp_path' => $temp_path,
'object_photo_id' => $object_photo_id,
'get' => $get,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function uploadFile($app, $get = null, $post = null, $files = null) {
$mdb = $app->container->get('mysql');
$error = false;
$errors = [];
//$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === 0 ? 'https://' : 'http://';
$protocol = (self::is_ssl()) ? 'https://' : 'http://';
$host = $protocol . $_SERVER['SERVER_NAME'];
$section = null;
if (isset($post['section']))
$section = $post['section'];
$object_id = null;
if (isset($post['object_id']))
$object_id = intval($post['object_id']);
// Найденный листинг парсера — read-only: привязка файлов/фото к нему запрещена.
// Признак листинга — явный флаг is_external из запроса (offset-free: id коллизит с objects.id).
// clients_files.object_id остаётся обычным INT — листинговый id сюда не попадает (привязка запрещена ниже).
if ($object_id && self::_request_flag($post, 'is_external')) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$_SESSION['id'],
'errors' => ['Прикрепление файлов к найденному листингу недоступно'],
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$client_id = null;
if (isset($post['client_id']))
$client_id = intval($post['client_id']);
$requisition_id = null;
if (isset($post['requisition_id']))
$requisition_id = intval($post['requisition_id']);
$funnel_id = null;
if (isset($post['funnel_id']))
$funnel_id = intval($post['funnel_id']);
$event_id = null;
if (isset($post['event_id']))
$event_id = intval($post['event_id']);
$stage_id = null;
if (isset($post['stage_id']))
$stage_id = intval($post['stage_id']);
if (($user_id = $_SESSION['id']) && count($files) > 0 && $section) {
if (in_array($section, ['photo', 'photoDom', 'img_plan'])) {
$result = \SelectelApi::getTokenAndUrl();
$token = $result[0];
$storageUrl = $result[1];
}
if (in_array($section, ['tasks', 'funnels'])) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
}
$list = [];
if (in_array($section, ['photo', 'photoDom', 'img_plan', 'clients', 'requisitions', 'tasks', 'funnels'])) {
$temp_dir = null;
if ($section == 'clients' && $client_id) {
$temp_dir = "/upload/funnels/clients/" . $client_id;
} else if ($section == 'funnels' && $funnel_id) {
if ($client_id || $requisition_id) {
if ($client_id > 0)
$temp_dir = "/upload/funnels/" . $client_id;
if ($requisition_id > 0)
$temp_dir = "/upload/funnels/" . $requisition_id;
} else {
$temp_dir = "/upload/funnels/" . $funnel_id;
}
} else if (in_array($section, ['photo', 'photoDom', 'img_plan'])) {
$temp_dir = "/photos/obj_temp/" . $user_id;
} else if ($section == 'tasks' && ($object_id || $client_id || $requisition_id)) {
if ($object_id > 0)
$temp_dir = "/upload/objects/" . $object_id;
if ($client_id > 0)
$temp_dir = "/upload/clients/" . $client_id;
if ($requisition_id > 0)
$temp_dir = "/upload/reqs/" . $requisition_id;
} else if ($section == 'requisitions' && $requisition_id) {
if ($requisition_id > 0)
$temp_dir = "/upload/funnels/req/" . $requisition_id;
}
$upload_max = self::returnBytes(ini_get('upload_max_filesize'));
$post_max = self::returnBytes(ini_get('post_max_size'));
$max_filesize = ($post_max < $upload_max) ? $post_max : $upload_max;
if ($temp_dir && isset($files[$section])) {
for ($i = 0; $i < count($files[$section]['name']); $i++) {
if ($files[$section]['name'][$i] && $files[$section]['tmp_name'][$i]) {
$tmp_name = $files[$section]['tmp_name'][$i];
$filename = $files[$section]['name'][$i];
$mimetype = $files[$section]['type'][$i];
$filesize = $files[$section]['size'][$i];
if ($filesize > $max_filesize) {
$error = true;
$errors[] = 'Размер файла превышает допустимый размер для загрузки.';
continue;
}
if ($files[$section]['error'][$i] == 0) {
if (!is_dir($_SERVER['DOCUMENT_ROOT'] . $temp_dir))
mkdir($_SERVER['DOCUMENT_ROOT'] . $temp_dir, 0777, true);
if (!is_dir($_SERVER['DOCUMENT_ROOT'] . $temp_dir))
mkdir($_SERVER['DOCUMENT_ROOT'] . $temp_dir, 0777, true);
$guid = md5($filename);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
if ($section == 'tasks') {
if ($client_id > 0) {
$guid = md5($_FILES['file']['name'].$_FILES['file']['size']."clients".$client_id.time());
} else if ($requisition_id > 0) {
$guid = md5($_FILES['file']['name'].$_FILES['file']['size']."clients".$requisition_id.time());
} else if ($object_id > 0) {
$guid = md5($_FILES['file']['name'].$_FILES['file']['size']."clients".$object_id.time());
}
}
if (in_array($section, ['clients', 'funnels', 'tasks', 'requisitions', 'clients']) && ($object_id || $client_id || $requisition_id))
$path = $temp_dir . "/" . $guid.'.'.$extension;
else
$path = $temp_dir . "/" . $filename;
if (!(false === move_uploaded_file($tmp_name, $_SERVER['DOCUMENT_ROOT'] . $path))) {
if ($guid && $section == 'tasks' && $event_id) {
if ($client_id > 0) {
$sql = "INSERT INTO clients_files (guid, client_id, type, name, event_id)
VALUES ('{$guid}', '{$client_id}', '{$extension}', '{$filename}', '{$event_id}')";
//отпрвляем файл в Селектел
// токен Selectel в запросе не нужен: заливку делает фоновый крон offloadFilesToSelectel.php
$contType = "application/octet-stream";
if ($extension) {
$extension = strtolower($extension);
}
if ($extension === "doc") {
$contType = "application/msword";
}
if ($extension === "docx") {
$contType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
if ($extension === "xls") {
$contType = "application/vnd.ms-excel";
}
if ($extension === "xlsx") {
$contType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
if ($extension === "pdf") {
$contType = "application/pdf";
}
if ($extension === "jpeg" || $extension === "jpg") {
$contType = "image/jpeg";
}
if ($extension === "gif") {
$contType = "image/gif";
}
if ($extension === "png") {
$contType = "image/png";
}
if ($extension === "mp3") {
$contType = "audio/mpeg";
}
if ($extension === "zip") {
$contType = "application/zip";
}
if ($extension === "rar") {
$contType = "application/vnd.rar";
}
$new_path = "/upload/clients/". $client_id . "/" . $guid . '.' . $extension;
// синхронная заливка в Selectel убрана; файл подхватит фоновый крон (reconcile → offloadFilesToSelectel)
} else if ($requisition_id > 0) {
$sql = "INSERT INTO clients_files (guid, req_id, type, name, event_id)
VALUES ('{$guid}', '{$requisition_id}', '{$extension}', '{$filename}', '{$event_id}')";
//отпрвляем файл в Селектел
// токен Selectel в запросе не нужен: заливку делает фоновый крон offloadFilesToSelectel.php
$contType = "application/octet-stream";
if ($extension) {
$extension = strtolower($extension);
}
if ($extension === "doc") {
$contType = "application/msword";
}
if ($extension === "docx") {
$contType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
if ($extension === "xls") {
$contType = "application/vnd.ms-excel";
}
if ($extension === "xlsx") {
$contType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
if ($extension === "pdf") {
$contType = "application/pdf";
}
if ($extension === "jpeg" || $extension === "jpg") {
$contType = "image/jpeg";
}
if ($extension === "gif") {
$contType = "image/gif";
}
if ($extension === "png") {
$contType = "image/png";
}
if ($extension === "mp3") {
$contType = "audio/mpeg";
}
if ($extension === "zip") {
$contType = "application/zip";
}
if ($extension === "rar") {
$contType = "application/vnd.rar";
}
$new_path = "/upload/reqs/". $requisition_id . "/" . $guid . '.' . $extension;
// синхронная заливка в Selectel убрана; файл подхватит фоновый крон (reconcile → offloadFilesToSelectel)
} else if ($object_id > 0) {
$sql = "INSERT INTO clients_files (guid, object_id, type, name, event_id)
VALUES ('{$guid}', '{$object_id}', '{$extension}', '{$filename}', '{$event_id}')";
//отпарвляем файл в Селектел
// токен Selectel в запросе не нужен: заливку делает фоновый крон offloadFilesToSelectel.php
$contType = "application/octet-stream";
if ($extension) {
$extension = strtolower($extension);
}
if ($extension === "doc") {
$contType = "application/msword";
}
if ($extension === "docx") {
$contType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
if ($extension === "xls") {
$contType = "application/vnd.ms-excel";
}
if ($extension === "xlsx") {
$contType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
if ($extension === "pdf") {
$contType = "application/pdf";
}
if ($extension === "jpeg" || $extension === "jpg") {
$contType = "image/jpeg";
}
if ($extension === "gif") {
$contType = "image/gif";
}
if ($extension === "png") {
$contType = "image/png";
}
if ($extension === "mp3") {
$contType = "audio/mpeg";
}
if ($extension === "zip") {
$contType = "application/zip";
}
if ($extension === "rar") {
$contType = "application/vnd.rar";
}
$new_path = "/upload/objects/". $object_id . "/" . $guid . '.' . $extension;
// синхронная заливка в Selectel убрана; файл подхватит фоновый крон (reconcile → offloadFilesToSelectel)
}
if (!empty($sql)) {
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
}
if ($guid && in_array($section, ['funnels', 'requisitions', 'clients']) && $funnel_id && $stage_id) {
$sql = "SELECT id
FROM funnel_files
WHERE guid = '{$guid}' AND
funnel_id = '{$funnel_id}' AND
etap_id = '{$stage_id}'";
if ($client_id > 0) {
$sql .= " AND client_id = '{$client_id}'";
} else if ($requisition_id > 0) {
$sql .= " AND req_id = '{$requisition_id}'";
}
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) == 0) {
$sql = "INSERT INTO funnel_files (
guid,
funnel_id,
type,
etap_id,
name
) VALUES (
'{$guid}',
'{$funnel_id}',
'{$extension}',
'{$stage_id}',
'{$filename}'
)";
if ($client_id > 0) {
$sql = "INSERT INTO funnel_files (
guid,
funnel_id,
type,
etap_id,
client_id,
name
) VALUES (
'{$guid}',
'{$funnel_id}',
'{$extension}',
'{$stage_id}',
'{$client_id}',
'{$filename}'
)";
//отпрвляем файл в Селектел
// токен Selectel в запросе не нужен: заливку делает фоновый крон offloadFilesToSelectel.php
$contType = "application/octet-stream";
if ($extension) {
$extension = strtolower($extension);
}
if ($extension === "doc") {
$contType = "application/msword";
}
if ($extension === "docx") {
$contType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
if ($extension === "xls") {
$contType = "application/vnd.ms-excel";
}
if ($extension === "xlsx") {
$contType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
if ($extension === "pdf") {
$contType = "application/pdf";
}
if ($extension === "jpeg" || $extension === "jpg") {
$contType = "image/jpeg";
}
if ($extension === "gif") {
$contType = "image/gif";
}
if ($extension === "png") {
$contType = "image/png";
}
if ($extension === "mp3") {
$contType = "audio/mpeg";
}
if ($extension === "zip") {
$contType = "application/zip";
}
if ($extension === "rar") {
$contType = "application/vnd.rar";
}
$new_path = "/upload/funnels/clients/". $client_id . "/" . $guid . '.' . $extension;
// синхронная заливка в Selectel убрана; файл подхватит фоновый крон (reconcile → offloadFilesToSelectel)
} else if ($requisition_id > 0) {
$sql = "INSERT INTO funnel_files (
guid,
funnel_id,
type,
etap_id,
req_id,
name
) VALUES (
'{$guid}',
'{$funnel_id}',
'{$extension}',
'{$stage_id}',
'{$requisition_id}',
'{$filename}'
)";
//отпрвляем файл в Селектел
// токен Selectel в запросе не нужен: заливку делает фоновый крон offloadFilesToSelectel.php
$contType = "application/octet-stream";
if ($extension) {
$extension = strtolower($extension);
}
if ($extension === "doc") {
$contType = "application/msword";
}
if ($extension === "docx") {
$contType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
if ($extension === "xls") {
$contType = "application/vnd.ms-excel";
}
if ($extension === "xlsx") {
$contType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
if ($extension === "pdf") {
$contType = "application/pdf";
}
if ($extension === "jpeg" || $extension === "jpg") {
$contType = "image/jpeg";
}
if ($extension === "gif") {
$contType = "image/gif";
}
if ($extension === "png") {
$contType = "image/png";
}
if ($extension === "mp3") {
$contType = "audio/mpeg";
}
if ($extension === "zip") {
$contType = "application/zip";
}
if ($extension === "rar") {
$contType = "application/vnd.rar";
}
$new_path = "/upload/funnels/req/". $requisition_id . "/" . $guid . '.' . $extension;
// синхронная заливка в Selectel убрана; файл подхватит фоновый крон (reconcile → offloadFilesToSelectel)
} else {
//отпрвляем файл в Селектел
// токен Selectel в запросе не нужен: заливку делает фоновый крон offloadFilesToSelectel.php
$contType = "application/octet-stream";
if ($extension) {
$extension = strtolower($extension);
}
if ($extension === "doc") {
$contType = "application/msword";
}
if ($extension === "docx") {
$contType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
if ($extension === "xls") {
$contType = "application/vnd.ms-excel";
}
if ($extension === "xlsx") {
$contType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
if ($extension === "pdf") {
$contType = "application/pdf";
}
if ($extension === "jpeg" || $extension === "jpg") {
$contType = "image/jpeg";
}
if ($extension === "gif") {
$contType = "image/gif";
}
if ($extension === "png") {
$contType = "image/png";
}
if ($extension === "mp3") {
$contType = "audio/mpeg";
}
if ($extension === "zip") {
$contType = "application/zip";
}
if ($extension === "rar") {
$contType = "application/vnd.rar";
}
$new_path = "/upload/funnels/". $funnel_id . "/" . $guid . '.' . $extension;
// синхронная заливка в Selectel убрана; файл подхватит фоновый крон (reconcile → offloadFilesToSelectel)
}
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
$list[] = [
'guid' => $guid,
'filename' => $filename,
'extension' => $extension,
'mimetype' => $mimetype,
'path' => $host . $path,
'is_temp' => true,
'is_editable' => true,
];
} else {
$error = true;
$errors[] = $files[$section]["file"]["error"][$i];
}
} else {
$errors[] = 'An error occurred while uploading the file `' . $filename . '`!';
}
} else {
$errors[] = $files[$section]['error'];
}
}
} else {
$errors[] = 'Empty files.';
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'section' => $section,
'files' => $list,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
/*public function editPhoto($app, $get = null, $post = null) {
$error = false;
$photo_path = false;
if (isset($get['photo_path']))
$photo_path = $get['photo_path'];
if (($user_id = $_SESSION['id']) && $photo_path) {
// ....
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'files' => $photo_path,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id']
], JSON_UNESCAPED_UNICODE));
$app->stop();
}*/
public function getTasks($app, $get = null, $post = null, $need_return = false) {
$error = false;
$errors = [];
$tasks = [];
if ($user_id = $_SESSION['id']) {
$protocol = (self::is_ssl()) ? 'https://' : 'http://';
$host = $protocol . $_SERVER['SERVER_NAME'];
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$object_id = null;
if (isset($get['object_id'])) {
$section = 'objects';
$object_id = intval($get['object_id']);
}
$client_id = null;
if (isset($get['client_id'])) {
$section = 'clients';
$client_id = intval($get['client_id']);
}
$requisition_id = null;
if (isset($get['requisition_id'])) {
$section = 'requisitions';
$requisition_id = intval($get['requisition_id']);
}
$user = new \User;
$user->get($user_id);
$gmtmsk =$user->gmtmsk;
$time_zone = '';
if($gmtmsk >= 0){
$time_zone = '+'.$gmtmsk.' hour';
} else {
$time_zone = '-'.$gmtmsk.' hour';
}
$user->checkPermissions($user_id, false);
$agency_id = $user->agencyId;
// Offset-free: признак листинга — явный флаг is_external из запроса (echo'ит mJW). object_id = реальный el.id.
// Для каждой эмитируемой задачи листинга помечаем is_external_listing_event=true, чтобы CRUD (правка/удаление/
// завершение/суб-коммент) маршрутизировался в листинговую таблицу без диапазонного признака id.
$is_listing_tasks = self::_request_flag($get, 'is_external');
if ($object_id && $section == 'objects') {
$sql = '';
// Хелперы событий найденных листингов парсера (offset-free, ключ — реальный el.id).
require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/helpers/external_listing_events.php';
if ($is_listing_tasks) {
// Найденный листинг парсера: лента событий из external_listing_events (ключ — реальный el.id, без смещения).
// Суб-комменты листинга — section_id = 4 (общий section_id = 1 коллидировал бы по event_id
// с суб-комментами задач из user_object_events). У листинга нет cancel/sum/document_id — отдаём 0/NULL,
// чтобы общий цикл обработки ниже не менялся.
$listing_real_id = (int)$object_id;
if ($_SESSION['agency'] || $_SESSION['manager'] || $_SESSION['users_admin']) {
$agent_ids = [$user_id];
$searchUserId = $user_id;
if ($_SESSION['users_admin']) {
$user = new \User;
$user->checkPermissions($user_id, false);
$searchUserId = $user->agencyId;
$agent_ids[] = $user->agencyId;
}
$agents = \User::getAllAgents($searchUserId);
foreach ($agents as $agent) {
if (!in_array($agent['id'], $agent_ids))
$agent_ids[] = $agent['id'];
}
if ($_SESSION['agency'] || $_SESSION['users_admin']) {
$agents = \User::getAllManagers($searchUserId);
foreach ($agents as $agent) {
if (!in_array($agent['id'], $agent_ids))
$agent_ids[] = $agent['id'];
}
}
// + удалённые сотрудники компании: их события на ЭТОМ листинге видны команде (история сохраняется,
// авторство не меняем). Это лента ОДНОГО листинга для агентства, не фильтруемый список задач.
$agent_ids = array_values(array_unique(array_merge($agent_ids, \external_listing_notes_scope_user_ids($user_id))));
$listing_user_filter = "(e.user_id IN (" . implode(',', $agent_ids) . ") OR e.from_id IN (" . implode(',', $agent_ids) . "))";
} else {
$listing_user_filter = "(e.user_id = '$user_id' OR e.from_id = '$user_id')";
}
// Offset-free: id события — реальный e.id (без смещения), различитель листинга = is_external_listing_event ниже.
$sql = "SELECT e.id AS id,
e.type,
e.user_id,
e.from_id,
e.comment,
e.address,
e.schedule_date,
NULL AS schedule_date_to,
e.name,
e.calendar_view,
e.create_date,
0 AS cancel,
0 AS `sum`,
NULL AS document_id,
IF(IFNULL(s.id, '') = '', 0, s.id) AS sub_id,
IF(IFNULL(s.sub_comment, '') = '', NULL, s.sub_comment) AS sub_comment,
IF(s.created_by <> 0, (
SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name)
FROM users AS u WHERE u.id = s.created_by
), NULL) AS sub_comment_author,
IF(IFNULL(s.created_by, '') = '', 0, s.created_by) AS sub_comment_author_id,
IF(s.user_for <> 0, (
SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name)
FROM users AS u WHERE u.id = s.user_for
), NULL) AS sub_comment_user_for,
IF(IFNULL(s.user_for, '') = '', 0, s.user_for) AS sub_comment_user_for_id
FROM external_listing_events AS e
LEFT JOIN user_sub_comments AS s ON s.event_id = e.id AND s.section_id = 4
WHERE {$listing_user_filter} AND
e.external_listing_id = {$listing_real_id}
GROUP BY e.id
ORDER BY e.create_date ASC";
} else if ($_SESSION['agency'] || $_SESSION['manager'] || $_SESSION['users_admin']) {
$agent_ids = [$user_id];
$searchUserId = $user_id;
if ($_SESSION['users_admin']) {
$user = new \User;
$user->checkPermissions($user_id, false);
$searchUserId = $user->agencyId;
$agent_ids[] = $user->agencyId;
}
$agents = \User::getAllAgents($searchUserId);
foreach ($agents as $agent) {
if (!in_array($agent['id'], $agent_ids)) {
$agent_ids[] = $agent['id'];
}
}
if ($_SESSION['agency'] || $_SESSION['users_admin']) {
$agents = \User::getAllManagers($searchUserId);
foreach ($agents as $agent) {
if (!in_array($agent['id'], $agent_ids)) {
$agent_ids[] = $agent['id'];
}
}
}
$sql = "SELECT e.*,
if (
e.from_id <> 0,
(SELECT u.user_logo FROM users AS u WHERE u.id = e.from_id),
(SELECT u.user_logo FROM users AS u WHERE u.id = e.user_id)
) AS user_logo,
if (
e.from_id <> 0,
(SELECT u.fio FROM users AS u WHERE u.id = e.from_id),
(SELECT u.fio FROM users AS u WHERE u.id = e.user_id)
) AS user_fio,
IF(IFNULL(s.id, '') = '', 0, s.id) AS sub_id,
IF(IFNULL(s.sub_comment, '') = '', NULL, s.sub_comment) AS sub_comment,
IF(s.created_by <> 0, (
SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name)
FROM users as u WHERE u.id = s.created_by
), NULL
) as sub_comment_author,
IF(IFNULL(s.created_by, '') = '', 0, s.created_by) AS sub_comment_author_id,
IF(s.user_for <> 0, (
SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name)
FROM users as u WHERE u.id = s.user_for
), NULL
) as sub_comment_user_for,
IF(IFNULL(s.user_for, '') = '', 0, s.user_for) AS sub_comment_user_for_id
FROM user_object_events AS e
LEFT JOIN user_sub_comments AS s ON s.event_id = e.id AND s.section_id = 1
WHERE (e.user_id IN (" . implode(',', $agent_ids) . ") OR e.from_id IN (" . implode(',', $agent_ids) . ")) AND
e.object_id = '$object_id'
GROUP BY e.id
ORDER BY e.create_date ASC";
} else {
$sql = "SELECT e.*,
IF(
e.from_id <> 0,
(SELECT u.user_logo FROM users AS u WHERE u.id = e.from_id),
(SELECT u.user_logo FROM users AS u WHERE u.id = e.user_id)
) AS user_logo,
IF(
e.from_id <> 0,
(SELECT u.fio FROM users AS u WHERE u.id = e.from_id),
(SELECT u.fio FROM users AS u WHERE u.id = e.user_id)
) AS user_fio,
IF(IFNULL(s.id, '') = '', 0, s.id) AS sub_id,
IF(IFNULL(s.sub_comment, '') = '', NULL, s.sub_comment) AS sub_comment,
IF(s.created_by <> 0, (
SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name)
FROM users as u WHERE u.id = s.created_by
), NULL
) as sub_comment_author,
IF(IFNULL(s.created_by, '') = '', 0, s.created_by) AS sub_comment_author_id,
IF(s.user_for <> 0, (
SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name)
FROM users as u WHERE u.id = s.user_for
), NULL
) as sub_comment_user_for,
IF(IFNULL(s.user_for, '') = '', 0, s.user_for) AS sub_comment_user_for_id
FROM user_object_events AS e
LEFT JOIN user_sub_comments AS s ON s.event_id = e.id AND s.section_id = 1
WHERE (e.user_id = '$user_id' OR e.from_id = '$user_id') AND
e.object_id = '$object_id'
GROUP BY e.id
ORDER BY e.create_date ASC";
}
if (!empty($sql)) {
$createDate = null;
if ($query = mysql_query($sql)) {
while ($event = mysql_fetch_assoc($query)) {
if ($createDate == null || $createDate != date("d.m.Y", strtotime($event['create_date']))) {
$createDate = date("d.m.Y", strtotime($event['create_date']));
if ($createDate == date("d.m.Y")) {
$event['chat_date'] = 'Сегодня';
} else if ($createDate == date("d.m.Y", strtotime("-1 DAY"))) {
$event['chat_date'] = 'Вчера';
} else {
list($d, $m, $y) = explode(".", $createDate);
if ($y == date("Y"))
$y = "";
$event['chat_date'] = trim($d . " " . getRusMonth($m) . " " . $y);
}
}
$from_id = $event['user_id'];
$event['chat_position'] = "right";
if (!empty($event['from_id']))
$from_id = $event['from_id'];
if ($_SESSION['id'] == $from_id)
$event['chat_position'] = "left";
$sql_user = "SELECT user_logo, CONCAT(last_name, ' ', first_name, ' ', middle_name) as user_fio FROM users WHERE id = {$from_id}
UNION SELECT user_logo, CONCAT(last_name, ' ', first_name, ' ', middle_name, ' (удален)') as user_fio FROM users_delete WHERE user_id = {$from_id}";
$from_user = mysql_fetch_assoc(mysql_query($sql_user));
$event['user_logo'] = $from_user['user_logo'];
$event['user_fio'] = $from_user['user_fio'];
$sql_who_work = "SELECT user_logo, CONCAT(last_name, ' ', first_name, ' ', middle_name) as user_fio FROM users WHERE id = {$event['user_id']}
UNION SELECT user_logo, CONCAT(last_name, ' ', first_name, ' ', middle_name, ' (удален)') as user_fio FROM users_delete WHERE user_id = {$event['user_id']}";
$from_who_work = mysql_fetch_assoc(mysql_query($sql_who_work));
$event['who_work'] = $from_who_work['user_fio'];
$data = [];
$data['moved_on_copy'] = !empty($event['moved_on_copy']) ? 1 : 0; //перенесено в объект при копировании из Поиска (бейдж)
//$data['_raw'] = $event;
$event_type = isset($event['type']) ? $event['type'] : null;
switch ($event['type']) {
case 'even':
case 'event':
$data['title'] = trim($event['name']);
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['time'] = date("H:i", strtotime($time_zone, strtotime($event['create_date'])));
$data['comment'] = trim($event['comment']);
break;
case 'comment':
$data['time'] = date("H:i", strtotime($time_zone,strtotime($event['create_date'])));
$data['comment'] = trim($event['comment']);
break;
case 'file':
$data['title'] = trim($event['name']);
$file_list = [];
$docs_q = mysql_query("SELECT * FROM clients_files WHERE event_id = '".$event['id']."'");
$name_files = '';
while ($file = mysql_fetch_assoc($docs_q)) {
if ($file['name_id'] > 0 && $name_files == '') {
$sql_n = "SELECT * FROM names_client_files WHERE id={$file['name_id']}";
$q_n = mysql_query($sql_n);
if (mysql_num_rows($q_n) > 0) {
$r_n = mysql_fetch_assoc($q_n);
$name_files = $r_n['name'];
}
}
$temp_dir = null;
if ($file['object_id'] > 0)
$temp_dir = "https://uf.joywork.ru/upload/objects/" . $file['object_id'];
if ($file['client_id'] > 0)
$temp_dir = "https://uf.joywork.ru/upload/clients/" . $file['client_id'];
if ($file['requisition_id'] > 0)
$temp_dir = "https://uf.joywork.ru/upload/reqs/" . $file['requisition_id'];
if (!is_null($temp_dir)) {
$data['_temp_dir'] = $temp_dir;
$data['_file'] = $file;
if ($file['requisition_id'] > 0 || $file['object_id'] > 0 || $file['client_id'] > 0) {
$file_list[] = [
'id' => intval($file['id']),
'filename' => $file['name'],
//'path' => $host . '/download_file.php?id=' . $file['id'],
'path' => $temp_dir . '/' . $file['guid'] . '.' . $file['type'],
];
} else {
$name_doc = $_SERVER['DOCUMENT_ROOT'] . $temp_dir . '/' . $file['guid'] . '.' . $file['type'];
if (file_exists($name_doc)) {
$file_path = $temp_dir . '/' . $file['guid'] . '.' . $file['type'];
$data['_file_path'] = $file_path;
if (!empty($file_path) && !empty($file['name'])) {
$file_list[] = [
'id' => intval($file['id']),
'filename' => $file['name'],
//'path' => $host . '/download_file.php?id=' . $file['id'],
'path' => $host . $file_path,
];
}
}
}
}
}
$data['file_list'] = $file_list;
$data['comment'] = trim($event['comment']);
break;
case 'call':
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['time'] = date("H:i", strtotime($time_zone, strtotime($event['create_date'])));
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$data['comment'] = trim($event['comment']);
break;
case 'meet':
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['address'] = trim($event['address']);
$data['time'] = date("H:i", strtotime($time_zone, strtotime($event['create_date'])));
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$data['comment'] = trim($event['comment']);
break;
case 'show': // Показ
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['address'] = trim($event['address']);
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$data['comment'] = trim($event['comment']);
break;
case 'deal': // Сделка
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['summ'] = floatval($event['sum']);
$data['time'] = date("H:i", strtotime($time_zone, strtotime($event['create_date'])));
$deal_id_val = !empty($event['deal_id']) ? intval($event['deal_id']) : null;
$data['deal'] = null;
if ($deal_id_val) {
$sql_deal = "SELECT * FROM deals WHERE id = " . $deal_id_val . " AND status != 2 LIMIT 1";
$rez_deal = mysql_query($sql_deal);
if ($rez_deal && mysql_num_rows($rez_deal) > 0) {
$deal_row = mysql_fetch_assoc($rez_deal);
$data['deal']['id'] = intval($deal_row['id']);
$data['deal']['contract_price'] = floatval($deal_row['contract_price']);
$data['deal']['agent_commission'] = floatval($deal_row['agent_commission']);
$deal_sides = [];
foreach (['one', 'two'] as $side_num) {
$side_text = !empty($deal_row['side_' . $side_num]) ? $deal_row['side_' . $side_num] : '';
$side_data = [
'name' => $side_text,
'requisition_id' => null,
'requisition_name' => null,
'client_id' => null,
'client_name' => null,
'object_id' => null,
'object_name' => null,
'object_address' => null,
];
$req_id_val = !empty($deal_row['side_' . $side_num . '_requisition_id']) ? intval($deal_row['side_' . $side_num . '_requisition_id']) : null;
if ($req_id_val) {
$sql_req = "SELECT name, client_id FROM requisitions WHERE id = " . $req_id_val . " LIMIT 1";
$rez_req = mysql_query($sql_req);
if ($rez_req && mysql_num_rows($rez_req) > 0) {
$row_req = mysql_fetch_assoc($rez_req);
$side_data['requisition_id'] = $req_id_val;
$side_data['requisition_name'] = $row_req['name'];
if (!empty($row_req['client_id'])) {
$side_data['client_id'] = intval($row_req['client_id']);
$sql_cl = "SELECT id, fio FROM clients WHERE id = " . intval($row_req['client_id']) . " LIMIT 1";
$rez_cl = mysql_query($sql_cl);
if ($rez_cl && mysql_num_rows($rez_cl) > 0) {
$row_cl = mysql_fetch_assoc($rez_cl);
$side_data['client_name'] = $row_cl['fio'];
}
}
}
}
$obj_id_val = !empty($deal_row['side_' . $side_num . '_object_id']) ? intval($deal_row['side_' . $side_num . '_object_id']) : null;
if ($obj_id_val) {
$side_data['object_id'] = $obj_id_val;
$sql_obj = "SELECT id, nazv, adres FROM objects WHERE id = " . $obj_id_val . " LIMIT 1";
$rez_obj = mysql_query($sql_obj);
if ($rez_obj && mysql_num_rows($rez_obj) > 0) {
$row_obj = mysql_fetch_assoc($rez_obj);
$side_data['object_name'] = $row_obj['nazv'];
$side_data['object_address'] = $row_obj['adres'];
}
}
$deal_sides[$side_num] = $side_data;
}
$data['deal']['sides'] = $deal_sides;
$deal_docs = [];
$sql_ddocs = "SELECT d.id, d.name FROM inner_docs d JOIN deal_inner_doc did ON did.inner_doc_id = d.id WHERE did.deal_id = " . $deal_id_val;
$rez_ddocs = mysql_query($sql_ddocs);
if ($rez_ddocs && mysql_num_rows($rez_ddocs) > 0) {
while ($dd_row = mysql_fetch_assoc($rez_ddocs)) {
$deal_docs[] = [
'id' => intval($dd_row['id']),
'name' => $dd_row['name'],
'url' => $host . '/ajax/getInnerDoc.php?id=' . intval($dd_row['id']) . '&download_pdf=true&t=' . time(),
];
}
}
$data['deal']['documents'] = $deal_docs;
}
}
$data['document'] = null;
if (!$deal_id_val && isset($event['document_id'])) {
$doc_id = $event['document_id'];
if ($doc = \Docs::getInnerDoc(null, $doc_id)) {
$data['document']['id'] = intval($doc['id']);
$data['document']['name'] = trim($doc['name']);
$data['document']['url'] = $host . '/ajax/getInnerDoc.php?id=' . intval($doc['id']) . '&download_pdf=true&t=' . time();
if (isset($doc['params'])) {
if ($params = json_decode($doc['params'], true)) {
if ($params['client_id'] && $params['object_id']) {
$doc_parties = [];
if (isset($params['client_id'])) {
$sql_cl = "SELECT id, fio, phone, email FROM `clients` WHERE `id` = '$params[client_id]' LIMIT 1";
$rez_cl = mysql_query($sql_cl);
if ($doc_cl = mysql_fetch_assoc($rez_cl)) {
// Маскируем email/phone клиента, если у текущего пользователя
// включено `hide_client_contacts`. Helper сам проверяет право.
$cl_contacts = [];
if ($doc_cl['email'])
$cl_contacts[] = mask_email_value_if_needed($doc_cl['email']);
if ($doc_cl['phone'])
$cl_contacts[] = mask_phone_value_if_needed($doc_cl['phone']);
$doc_party = [
'client_id' => $doc_cl['id'],
'object_id' => $params['object_id'],
'title' => $doc_cl['fio'],
'contacts' => ((!empty($cl_contacts)) ? ' (' . implode(', ', $cl_contacts) . ')' : ''),
];
// Маскируем title (fio), если он вида "Новый клиент +7...".
$doc_party['title'] = mask_fio_if_contains_phone($doc_party['title']);
$doc_parties[] = $doc_party;
}
}
if (isset($params['object_id'])) {
$sql_obj = "SELECT id, nazv, adres FROM `objects` WHERE `id` = '$params[object_id]' LIMIT 1";
$rez_obj = mysql_query($sql_obj);
if ($doc_obj = mysql_fetch_assoc($rez_obj)) {
$doc_parties[] = [
'object_id' => $doc_obj['id'],
'client_id' => $params['client_id'],
'title' => $doc_obj['nazv'],
'address' => $doc_obj['adres'],
];
}
}
$data['document']['parties'] = $doc_parties;
}
}
}
}
}
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$data['comment'] = trim($event['comment']);
break;
case 'moderation':
$event_type = 'pending_moderation';
$who_user = null;
$sql_who = "SELECT CONCAT(last_name, ' ', first_name, ' ', middle_name) as who_fio FROM users WHERE id = {$event['user_id']}";
$who_user = mysql_fetch_assoc(mysql_query($sql_who));
if ($who_user)
$data['employee_name'] = $who_user['who_fio'];
else
$data['employee_name'] = null;
$data['schedule_date'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' .date("H:i", strtotime($event['schedule_date']));
$data['services_list'] = [];
if (!empty($event['platforms_advert'])) {
$platforms = json_decode($event['platforms_advert']);
foreach ($platforms as $platform) {
switch ($platform->platform) {
case 'add_to_yandex_feed':
$data['services_list'][] = 'Бесплатные';
break;
case 'add_to_avito_feed':
$data['services_list'][] = 'Авито';
break;
case 'add_to_cian_feed':
$data['services_list'][] = 'Циан';
break;
case 'add_to_domclick_feed':
$data['services_list'][] = 'ДомКлик';
break;
case 'add_to_emls_feed':
$data['services_list'][] = 'Jcat';
break;
case 'add_to_bn_feed':
$data['services_list'][] = 'Яндекс';
break;
}
}
} else {
$sql_moderation = "SELECT * FROM objects_moderation_advert WHERE object_id = {$event['object_id']}";
$q_moderation = mysql_query($sql_moderation);
$r_moderation = mysql_fetch_assoc($q_moderation);
if (!empty($r_moderation)) {
if ($r_moderation['add_to_yandex_feed'] > 0)
$data['services_list'][] = 'Бесплатные';
if ($r_moderation['add_to_avito_feed'] > 0)
$data['services_list'][] = 'Авито';
if ($r_moderation['add_to_cian_feed'] > 0)
$data['services_list'][] = 'Циан';
if ($r_moderation['add_to_domclick_feed'] > 0)
$data['services_list'][] = 'ДомКлик';
if ($r_moderation['add_to_emls_feed'] > 0)
$data['services_list'][] = 'Jcat';
if ($r_moderation['add_to_bn_feed'] > 0)
$data['services_list'][] = 'Яндекс';
}
}
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1); // @todo: уточнить необходимость, потому что используется в контексте Клиентов и Заявок
if (!empty($event['comment']))
$data['comment'] = trim($event['comment']);
break;
case 'comment_moderation':
$event_type = 'accepted_moderation';
$data['accepted_date'] = date("d.m.Y H:i", strtotime($time_zone, strtotime($event['create_date'])));
if (!empty($event['comment']))
$data['comment'] = trim($event['comment']);
break;
}
if (isset($event['sub_id'])) {
if (isset($event['sub_id']))
$data['sub_comment']['id'] = intval($event['sub_id']);
if (isset($event['sub_comment']))
$data['sub_comment']['comment'] = trim($event['sub_comment']);
if (isset($event['sub_comment_author']))
$data['sub_comment']['author'] = trim($event['sub_comment_author']);
if (isset($event['sub_comment_author_id']))
$data['sub_comment']['author_id'] = (int)$event['sub_comment_author_id'];
if (isset($event['sub_comment_user_for']))
$data['sub_comment']['user_for'] = trim($event['sub_comment_user_for']);
if (isset($event['sub_comment_user_for_id']))
$data['sub_comment']['user_for_id'] = (int)$event['sub_comment_user_for_id'];
}
$tasks[] = [
'id' => intval($event['id']),
// Offset-free: id события — реальный e.id; различитель листинга — явный флаг (echo'ит mJW в CRUD).
'is_external_listing_event' => $is_listing_tasks,
'chat_date' => isset($event['chat_date']) ? $event['chat_date'] : null,
'chat_position' => isset($event['chat_position']) ? $event['chat_position'] : null,
'user_id' => intval($from_id),
'user_name' => isset($event['user_fio']) ? $event['user_fio'] : null,
'who_work' => isset($event['who_work']) ? $event['who_work'] : null,
'user_logo' => (!empty($event['user_logo'])) ? $host . '/photos/agency/' . $event['user_logo'] . '?=' . time() : null,
'type' => $event_type,
'event' => $data,
'created_at' => isset($event['create_date']) ? date('Y.m.d H:i:s', strtotime($time_zone, strtotime($event['create_date']))) : null,
'time' => isset($event['create_date']) ? date("H:i", strtotime($time_zone, strtotime($event['create_date']))) : null,
];
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
} else if ($client_id || $requisition_id) {
$sql = '';
if ($section == 'clients') {
$sql = "SELECT e.id,
e.comment,
e.name,
e.create_date,
e.checklist,
e.type,
e.type_call,
e.user_id,
e.record,
e.client_id,
e.req_id,
e.document_id,
e.schedule_date,
e.schedule_date_to,
e.address,
e.sum,
e.from_id,
e.calendar_view,
e.megafon,
e.telphin,
e.beeline,
e.mts,
e.tele2,
e.tracking,
e.cancel,
e.deal_id,
if (
e.from_id <> 0,
(SELECT u.user_logo FROM users as u WHERE u.id = e.from_id),
(SELECT u.user_logo FROM users as u WHERE u.id = e.user_id)
) as user_logo,
if (
e.from_id <> 0,
(SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name) FROM users as u WHERE u.id = e.from_id),
(SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name) FROM users as u WHERE u.id = e.user_id)
) as user_fio
FROM user_client_events as e
WHERE e.client_id = '$client_id'
UNION SELECT ev.id,
'' as comment,
'' as name,
ev.date as create_date,
0 as checklist,
'partner' as `type`,
NULL as type_call,
ev.user_id,
'' as record,
ev.client_id,
ev.req_id,
'' as document_id,
ev.date as schedule_date,
'' as schedule_date_to,
'' as address,
'' as `sum`,
ev.from_id,
'' as calendar_view,
'' as `megafon`,
'' as telphin,
'' as beeline,
'' as mts,
'' as tele2,
'' as tracking,
0 as cancel,
if (
ev.from_id <> 0,
(SELECT u.user_logo FROM users as u WHERE u.id = ev.from_id),
(SELECT u.user_logo FROM users as u WHERE u.id = ev.user_id)
) as user_logo,
if (
ev.from_id <> 0,
(SELECT u.fio FROM users as u WHERE u.id = ev.from_id),
(SELECT u.fio FROM users as u WHERE u.id = ev.user_id)
) as user_fio
FROM events_clients as ev
WHERE ev.client_id = '$client_id' and event = 'transmitted_parallel'
ORDER BY create_date ASC";
} else if ($section == 'requisitions') {
$sql = "SELECT e.id,
e.comment,
e.name,
e.create_date,
e.checklist,
e.type,
e.type_call,
e.user_id,
e.record,
e.client_id,
e.req_id,
e.document_id,
e.schedule_date,
e.schedule_date_to,
e.address,
e.sum,
e.from_id,
e.calendar_view,
e.megafon,
e.telphin,
e.beeline,
e.mts,
e.tele2,
e.tracking,
e.cancel,
e.deal_id,
if (
e.from_id <> 0,
(SELECT u.user_logo FROM users as u WHERE u.id = e.from_id),
(SELECT u.user_logo FROM users as u WHERE u.id = e.user_id)
) as user_logo,
if (
e.from_id <> 0,
(SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name) FROM users as u WHERE u.id = e.from_id),
(SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name) FROM users as u WHERE u.id = e.user_id)
) as user_fio
FROM user_client_events as e
WHERE e.req_id = '$requisition_id'
UNION SELECT ev.id,
'' as comment,
'' as name,
ev.date as create_date,
0 as checklist,
'partner' as `type`,
NULL as type_call,
ev.user_id,
'' as record,
ev.client_id,
ev.req_id,
'' as document_id,
ev.date as schedule_date,
'' as schedule_date_to,
'' as address,
'' as `sum`,
ev.from_id,
'' as calendar_view,
'' as `megafon`,
'' as telphin,
'' as beeline,
'' as mts,
'' as tele2,
'' as tracking,
0 as cancel,
if (
ev.from_id <> 0,
(SELECT u.user_logo FROM users as u WHERE u.id = ev.from_id),
(SELECT u.user_logo FROM users as u WHERE u.id = ev.user_id)
) as user_logo,
if (
ev.from_id <> 0,
(SELECT u.fio FROM users as u WHERE u.id = ev.from_id),
(SELECT u.fio FROM users as u WHERE u.id = ev.user_id)
) as user_fio
FROM events_clients as ev
WHERE ev.req_id = '$requisition_id' and event = 'transmitted_parallel'
ORDER BY create_date ASC";
}
if (!empty($sql)) {
$createDate = null;
if ($query = mysql_query($sql)) {
while ($event = mysql_fetch_assoc($query)) {
$sql_who_work = "SELECT user_logo, id, CONCAT(last_name, ' ', first_name, ' ', middle_name) as user_fio FROM users WHERE id = {$event['user_id']}
UNION SELECT user_logo, id, CONCAT(last_name, ' ', first_name, ' ', middle_name, ' (удален)') as user_fio FROM users_delete WHERE user_id = {$event['user_id']}";
$from_who_work = mysql_fetch_assoc(mysql_query($sql_who_work));
$event['who_work'] = $from_who_work['id'];
$event['who_work_fio'] = $from_who_work['user_fio'];
if ($createDate == null || $createDate != date("d.m.Y", strtotime($event['create_date']))) {
$createDate = date("d.m.Y", strtotime($event['create_date']));
if ($createDate == date("d.m.Y")) {
$event['chat_date'] = 'Сегодня';
} else if ($createDate == date("d.m.Y", strtotime("-1 DAY"))) {
$event['chat_date'] = 'Вчера';
} else {
list($d, $m, $y) = explode(".", $createDate);
if ($y == date("Y"))
$y = "";
$event['chat_date'] = trim($d . " " . getRusMonth($m) . " " . $y);
}
}
$from_id = $event['user_id'];
$event['chat_position'] = "right";
if (!empty($event['from_id']))
$from_id = $event['from_id'];
if ($_SESSION['id'] == $from_id)
$event['chat_position'] = "left";
$data = [
'id' => $event['id']
];
switch ($event['type']) {
case 'comment':
$data['time'] = date("H:i", strtotime($time_zone, strtotime($event['create_date'])));
$data['comment'] = trim($event['comment']);
break;
case 'file':
case 'partner_id':
$data['title'] = trim($event['name']);
$file_list = [];
$docs_q = mysql_query("SELECT * FROM clients_files WHERE event_id = '".$event['id']."'");
$name_files = '';
while ($file = mysql_fetch_assoc($docs_q)) {
if ($file['name_id'] > 0 && $name_files == '') {
$sql_n = "SELECT * FROM names_client_files WHERE id={$file['name_id']}";
$q_n = mysql_query($sql_n);
if (mysql_num_rows($q_n) > 0) {
$r_n = mysql_fetch_assoc($q_n);
$name_files = $r_n['name'];
}
}
$name_doc = $_SERVER['DOCUMENT_ROOT'].'/upload/clients/'.$file['client_id'].'/'.$file['guid'].'.'.$file['type'];
if ($file['req_id'] > 0) {
$file_path = 'https://uf.joywork.ru/upload/reqs/' . $file['req_id'] . '/' . $file['guid'] . '.' . $file['type'];
$file_list[] = [
'id' => intval($file['id']),
'filename' => $file['name'],
'path' => $file_path,
];
} else {
if ($file['client_id'] > 0) {
$file_path = 'https://uf.joywork.ru/upload/clients/' . $file['client_id'] . '/' . $file['guid'] . '.' . $file['type'];
$file_list[] = [
'id' => intval($file['id']),
'filename' => $file['name'],
'path' => $file_path,
];
} else {
if (file_exists($name_doc)) {
$file_path = '';
if ($file['client_id'] > 0)
$file_path = '/upload/clients/' . $file['client_id'] . '/' . $file['guid'] . '.' . $file['type'];
if ($file['req_id'] > 0)
$file_path = '/upload/reqs/' . $file['req_id'] . '/' . $file['guid'] . '.' . $file['type'];
if (!empty($file_path) && !empty($file['name'])) {
$file_list[] = [
'id' => intval($file['id']),
'filename' => $file['name'],
//'path' => $host . '/download_file.php?id=' . $file['id'],
'path' => $host . $file_path,
];
}
}
}
}
}
$data['file_list'] = $file_list;
$data['comment'] = trim($event['comment']);
break;
case 'call':
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_to'] = date('Y-m-d H:i:s', strtotime($event['schedule_date_to']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['time'] = date("H:i", strtotime($time_zone, strtotime($event['create_date'])));
if (!empty($event['record'])) {
if ($event['megafon'] == 1) {
$oper = 'mega';
$path = '/server/mega/';
if (!file_exists($_SERVER['DOCUMENT_ROOT'].$path.$event['record'])) {
$href = 'https://voice.joywork.ru/mega/';
$Headers = @get_headers($href.$event['record']);
if (strpos($Headers[0],'200')) {
$path = $href;
} else {
$path = '';
}
}
if (!empty($path)) {
$data['records'][] = [
'operator' => $oper,
'source_path' => $path . $event['record']
];
}
} else {
$arr_rec = json_decode($event['record']);
if (!empty($arr_rec)) {
foreach ($arr_rec as $rec) {
if (!empty($rec)) {
$oper = null;
$path = '';
if ($event['telphin'] == 1) {
$oper = 'telphin';
$path = '/server/telphin/';
if (!file_exists($_SERVER['DOCUMENT_ROOT'].$path.$rec.'.mp3')) {
$href = 'https://voice.joywork.ru/telphin/';
$Headers = @get_headers($href.$rec.'.mp3');
if (strpos($Headers[0],'200')) {
$path = $href;
} else {
$path = '';
}
}
} else if ($event['beeline'] == 1) {
$oper = 'beeline';
$path = '/server/beeline/';
if (!file_exists($_SERVER['DOCUMENT_ROOT'].$path.$rec.'.mp3')) {
$href = 'https://voice.joywork.ru/beeline/';
$Headers = @get_headers($href.$rec.'.mp3');
if (strpos($Headers[0],'200')) {
$path = $href;
} else {
$path = '';
}
}
} else if ($event['mts'] == 1) {
$oper = 'mts';
$path = '/server/mts/'.$user->agencyId."/";
if (!file_exists($_SERVER['DOCUMENT_ROOT'].$path.$rec.'.mp3')) {
$href = 'https://voice.joywork.ru/mts/'.$user->agencyId.'/';
$Headers = @get_headers($href.$rec.'.mp3');
if (strpos($Headers[0],'200')) {
$path = $href;
} else {
$path = '';
}
}
} else if ($event['tele2'] == 1) {
$oper = 'tele2';
$date_patch = date('Ymd', strtotime($event['create_date']));
$path = '/server/tele2/'.$user->agencyId.'/'.$date_patch.'/';
if (!file_exists($_SERVER['DOCUMENT_ROOT'].$path.$rec.'.mp3')) {
$href = 'https://voice.joywork.ru/tele2/'.$user->agencyId.'/'.$date_patch.'/';
$Headers = @get_headers($href.$rec.'.mp3');
if (strpos($Headers[0],'200')) {
$path = $href;
} else {
$path = '';
}
}
} else {
$oper = 'mango';
$path = '/server/mango/';
if (!file_exists($_SERVER['DOCUMENT_ROOT'].$path.$rec.'.mp3')) {
$href = 'https://voice.joywork.ru/mango/';
$Headers = @get_headers($href.$rec.'.mp3');
if (strpos($Headers[0],'200')) {
$path = $href;
} else {
$path = '';
}
}
}
if (!empty($path)) {
$data['records'][] = [
'operator' => $oper,
'source_path' => $path . $rec . '.mp3'
];
}
}
}
}
}
} else {
$data['records'] = null;
}
$data['is_tracking'] = ($event['tracking'] == 1);
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$pattern = '/(https?:\/\/\S+)/i';
$comment = preg_replace($pattern, 'ссылка', $event['comment']);
$data['comment'] = trim($comment);
break;
case 'meet':
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['address'] = trim($event['address']);
$data['time'] = date("H:i", strtotime($time_zone, strtotime($event['create_date'])));
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$pattern = '/(https?:\/\/\S+)/i';
$comment = preg_replace($pattern, 'ссылка', $event['comment']);
$data['comment'] = trim($comment);
break;
case 'show': // Показ
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['address'] = trim($event['address']);
$data['time'] = date("H:i", strtotime($time_zone, strtotime($event['create_date'])));
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$pattern = '/(https?:\/\/\S+)/i';
$comment = preg_replace($pattern, 'ссылка', $event['comment']);
$data['comment'] = trim($comment);
break;
case 'deal': // Сделка
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['summ'] = floatval($event['sum']);
$data['time'] = date("H:i", strtotime($time_zone, strtotime($event['create_date'])));
$deal_id_val = !empty($event['deal_id']) ? intval($event['deal_id']) : null;
$data['deal'] = null;
if ($deal_id_val) {
$sql_deal = "SELECT * FROM deals WHERE id = " . $deal_id_val . " AND status != 2 LIMIT 1";
$rez_deal = mysql_query($sql_deal);
if ($rez_deal && mysql_num_rows($rez_deal) > 0) {
$deal_row = mysql_fetch_assoc($rez_deal);
$data['deal']['id'] = intval($deal_row['id']);
$data['deal']['contract_price'] = floatval($deal_row['contract_price']);
$data['deal']['agent_commission'] = floatval($deal_row['agent_commission']);
$deal_sides = [];
foreach (['one', 'two'] as $side_num) {
$side_text = !empty($deal_row['side_' . $side_num]) ? $deal_row['side_' . $side_num] : '';
$side_data = [
'name' => $side_text,
'requisition_id' => null,
'requisition_name' => null,
'client_id' => null,
'client_name' => null,
'object_id' => null,
'object_name' => null,
'object_address' => null,
];
$req_id_val = !empty($deal_row['side_' . $side_num . '_requisition_id']) ? intval($deal_row['side_' . $side_num . '_requisition_id']) : null;
if ($req_id_val) {
$sql_req = "SELECT name, client_id FROM requisitions WHERE id = " . $req_id_val . " LIMIT 1";
$rez_req = mysql_query($sql_req);
if ($rez_req && mysql_num_rows($rez_req) > 0) {
$row_req = mysql_fetch_assoc($rez_req);
$side_data['requisition_id'] = $req_id_val;
$side_data['requisition_name'] = $row_req['name'];
if (!empty($row_req['client_id'])) {
$side_data['client_id'] = intval($row_req['client_id']);
$sql_cl = "SELECT id, fio FROM clients WHERE id = " . intval($row_req['client_id']) . " LIMIT 1";
$rez_cl = mysql_query($sql_cl);
if ($rez_cl && mysql_num_rows($rez_cl) > 0) {
$row_cl = mysql_fetch_assoc($rez_cl);
$side_data['client_name'] = $row_cl['fio'];
}
}
}
}
$obj_id_val = !empty($deal_row['side_' . $side_num . '_object_id']) ? intval($deal_row['side_' . $side_num . '_object_id']) : null;
if ($obj_id_val) {
$side_data['object_id'] = $obj_id_val;
$sql_obj = "SELECT id, nazv, adres FROM objects WHERE id = " . $obj_id_val . " LIMIT 1";
$rez_obj = mysql_query($sql_obj);
if ($rez_obj && mysql_num_rows($rez_obj) > 0) {
$row_obj = mysql_fetch_assoc($rez_obj);
$side_data['object_name'] = $row_obj['nazv'];
$side_data['object_address'] = $row_obj['adres'];
}
}
$deal_sides[$side_num] = $side_data;
}
$data['deal']['sides'] = $deal_sides;
$deal_docs = [];
$sql_ddocs = "SELECT d.id, d.name FROM inner_docs d JOIN deal_inner_doc did ON did.inner_doc_id = d.id WHERE did.deal_id = " . $deal_id_val;
$rez_ddocs = mysql_query($sql_ddocs);
if ($rez_ddocs && mysql_num_rows($rez_ddocs) > 0) {
while ($dd_row = mysql_fetch_assoc($rez_ddocs)) {
$deal_docs[] = [
'id' => intval($dd_row['id']),
'name' => $dd_row['name'],
'url' => $host . '/ajax/getInnerDoc.php?id=' . intval($dd_row['id']) . '&download_pdf=true&t=' . time(),
];
}
}
$data['deal']['documents'] = $deal_docs;
}
}
$data['document'] = null;
if (!$deal_id_val && isset($event['document_id'])) {
$doc_id = $event['document_id'];
if ($doc = \Docs::getInnerDoc(null, $doc_id)) {
$data['document']['id'] = intval($doc['id']);
$data['document']['name'] = trim($doc['name']);
$data['document']['url'] = $host . '/ajax/getInnerDoc.php?id=' . intval($doc['id']) . '&download_pdf=true&t=' . time();
if (isset($doc['params'])) {
if ($params = json_decode($doc['params'], true)) {
if ($params['client_id'] && $params['object_id']) {
$doc_parties = [];
if (isset($params['client_id'])) {
$sql_cl = "SELECT id, fio, phone, email FROM `clients` WHERE `id` = '$params[client_id]' LIMIT 1";
$rez_cl = mysql_query($sql_cl);
if ($doc_cl = mysql_fetch_assoc($rez_cl)) {
// Маскируем email/phone клиента, если у текущего пользователя
// включено `hide_client_contacts`. Helper сам проверяет право.
$cl_contacts = [];
if ($doc_cl['email'])
$cl_contacts[] = mask_email_value_if_needed($doc_cl['email']);
if ($doc_cl['phone'])
$cl_contacts[] = mask_phone_value_if_needed($doc_cl['phone']);
$doc_party = [
'client_id' => $doc_cl['id'],
'object_id' => $params['object_id'],
'title' => $doc_cl['fio'],
'contacts' => ((!empty($cl_contacts)) ? ' (' . implode(', ', $cl_contacts) . ')' : ''),
];
// Маскируем title (fio), если он вида "Новый клиент +7...".
$doc_party['title'] = mask_fio_if_contains_phone($doc_party['title']);
$doc_parties[] = $doc_party;
}
}
if (isset($params['object_id'])) {
$sql_obj = "SELECT id, nazv, adres FROM `objects` WHERE `id` = '$params[object_id]' LIMIT 1";
$rez_obj = mysql_query($sql_obj);
if ($doc_obj = mysql_fetch_assoc($rez_obj)) {
$doc_parties[] = [
'object_id' => $doc_obj['id'],
'client_id' => $params['client_id'],
'title' => $doc_obj['nazv'],
'address' => $doc_obj['adres'],
];
}
}
$data['document']['parties'] = $doc_parties;
}
}
}
}
}
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$pattern = '/(https?:\/\/\S+)/i';
$comment = preg_replace($pattern, 'ссылка', $event['comment']);
$data['comment'] = trim($comment);
break;
case 'even':
$data['title'] = trim($event['name']);
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['summ'] = floatval($event['sum']);
$data['address'] = trim($event['address']);
$data['time'] = date("H:i", strtotime($time_zone, strtotime($event['create_date'])));
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$pattern = '/(https?:\/\/\S+)/i';
$comment = preg_replace($pattern, 'ссылка', $event['comment']);
$data['comment'] = trim($comment);
break;
case 'step':
$data['time'] = date("H:i", strtotime($time_zone, strtotime($event['create_date'])));
$data['title'] = trim($event['name']);
$data['is_checklist'] = !($event['checklist'] == 0);
$data['is_completed'] = (isset($doers[$event['from_id']]) && $doers[$event['from_id']] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$data['comment'] = trim($event['comment']);
break;
case 'partner':
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$doers = [];
if (!empty($client->doers)) {
$doers_arr = json_decode(html_entity_decode($client->doers));
foreach ($doers_arr as $key => $doer) {
$doers[$key] = $doer;
}
} else if ((isset($get['req_id']) && $get['req_id'] > 0) && !empty($client['doers'])) {
$doers_arr = json_decode(html_entity_decode($client['doers']));
foreach ($doers_arr as $key => $doer) {
$doers[$key] = $doer;
}
}
$data['comment'] = 'Добавлен к совместной работе.';
$data['doers_id'] = $doers;
break;
}
$chat_date = isset($event['chat_date']) ? $event['chat_date'] : '';
$tasks[] = [
'id' => intval($event['id']),
// Клиент/заявка — не листинг; флаг держим для единообразия формы ответа.
'is_external_listing_event' => false,
'chat_date' => isset($event['chat_date']) ? $event['chat_date'] : null,
'chat_position' => isset($event['chat_position']) ? $event['chat_position'] : null,
'user_id' => intval($from_id),
'user_name' => isset($event['user_fio']) ? $event['user_fio'] : null,
'who_work' => isset($event['who_work']) ? $event['who_work'] : null,
'who_work_fio' => isset($event['who_work_fio']) ? $event['who_work_fio'] : null,
'user_logo' => (!empty($event['user_logo'])) ? $host . '/photos/agency/' . $event['user_logo'] . '?=' . time() : null,
'type' => isset($event['type']) ? $event['type'] : null,
'type_call' => isset($event['type_call']) ? $event['type_call'] : null,
'event' => $data,
'created_at' => isset($event['create_date']) ? date('Y.m.d H:i:s', strtotime($time_zone, strtotime($event['create_date']))) : null,
'time' => isset($event['create_date']) ? date("H:i", strtotime($time_zone, strtotime($event['create_date']))) : null,
];
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
}
if ($need_return && !$error) {
return $tasks;
} else if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => $user_id,
'section' => $section,
'tasks' => $tasks,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getTask($app, $get = null, $post = null, $need_return = false) {
$error = false;
$errors = [];
$task = [];
if ($user_id = $_SESSION['id']) {
$protocol = (self::is_ssl()) ? 'https://' : 'http://';
$host = $protocol . $_SERVER['SERVER_NAME'];
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$event_id = null;
if (isset($get['event_id'])) {
$event_id = intval($get['event_id']);
}
$event_type = null;
if (isset($get['event_type'])) {
$event_type = trim($get['event_type']);
}
$section = null;
if (isset($get['section'])) {
$section = trim($get['section']);
}
$user = new \User;
$user->get($user_id);
$user->checkPermissions($user_id, false);
$agency_id = $user->agencyId;
// Offset-free: признак события листинга — явный флаг is_external_listing_event из запроса (echo'ит mJW).
// event_id = реальный e.id (без смещения), коллизия с id события своего объекта снимается этим флагом.
$is_listing_task = self::_request_flag($get, 'is_external_listing_event');
$sql = '';
if ($section == 'objects') {
$sql = '';
// Хелперы событий найденных листингов парсера (offset-free, ключ — реальный el event id).
require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/helpers/external_listing_events.php';
if ($is_listing_task) {
// Найденный листинг парсера: одиночное событие из external_listing_events (реальный id = event_id, без смещения).
// cancel/sum/document_id у листинга нет — отдаём 0/NULL.
$listing_real_id = (int)$event_id;
if ($_SESSION['agency'] || $_SESSION['manager'] || $_SESSION['users_admin']) {
$agent_ids = [$user_id];
$searchUserId = $user_id;
if ($_SESSION['users_admin']) {
$user = new \User;
$user->checkPermissions($user_id, false);
$searchUserId = $user->agencyId;
$agent_ids[] = $user->agencyId;
}
$agents = \User::getAllAgents($searchUserId);
foreach ($agents as $agent) {
if (!in_array($agent['id'], $agent_ids))
$agent_ids[] = $agent['id'];
}
if ($_SESSION['agency'] || $_SESSION['users_admin']) {
$agents = \User::getAllManagers($searchUserId);
foreach ($agents as $agent) {
if (!in_array($agent['id'], $agent_ids))
$agent_ids[] = $agent['id'];
}
}
$listing_user_filter = "e.user_id IN (" . implode(',', $agent_ids) . ")";
} else {
$listing_user_filter = "e.user_id = '$user_id'";
}
// Offset-free: id события — реальный e.id (без смещения), различитель листинга = is_external_listing_event ниже.
$sql = "SELECT e.id AS id,
e.type, e.user_id, e.from_id, e.comment, e.address,
e.schedule_date, NULL AS schedule_date_to, e.name, e.calendar_view, e.create_date,
0 AS cancel, 0 AS `sum`, NULL AS document_id,
IF(e.from_id <> 0, (SELECT u.user_logo FROM users AS u WHERE u.id = e.from_id), (SELECT u.user_logo FROM users AS u WHERE u.id = e.user_id)) AS user_logo,
IF(e.from_id <> 0, (SELECT u.fio FROM users AS u WHERE u.id = e.from_id), (SELECT u.fio FROM users AS u WHERE u.id = e.user_id)) AS user_fio
FROM external_listing_events AS e
WHERE {$listing_user_filter} AND
e.id = {$listing_real_id}";
if ($event_type)
$sql .= " AND e.type = '$event_type'";
$sql .= " LIMIT 1";
} else if ($_SESSION['agency'] || $_SESSION['manager'] || $_SESSION['users_admin']) {
$agent_ids = [$user_id];
$searchUserId = $user_id;
if ($_SESSION['users_admin']) {
$user = new \User;
$user->checkPermissions($user_id, false);
$searchUserId = $user->agencyId;
$agent_ids[] = $user->agencyId;
}
$agents = \User::getAllAgents($searchUserId);
foreach ($agents as $agent) {
if (!in_array($agent['id'], $agent_ids)) {
$agent_ids[] = $agent['id'];
}
}
if ($_SESSION['agency'] || $_SESSION['users_admin']) {
$agents = \User::getAllManagers($searchUserId);
foreach ($agents as $agent) {
if (!in_array($agent['id'], $agent_ids)) {
$agent_ids[] = $agent['id'];
}
}
}
$sql = "SELECT *,
if (
e.from_id <> 0,
(SELECT u.user_logo FROM users AS u WHERE u.id = e.from_id),
(SELECT u.user_logo FROM users AS u WHERE u.id = e.user_id)
) AS user_logo,
if (
e.from_id <> 0,
(SELECT u.fio FROM users AS u WHERE u.id = e.from_id),
(SELECT u.fio FROM users AS u WHERE u.id = e.user_id)
) AS user_fio
FROM user_object_events AS e
WHERE user_id IN (" . implode(',', $agent_ids) . ") AND
e.id = '$event_id'";
if ($event_type)
$sql .= " AND e.type = '$event_type'";
$sql .= " LIMIT 1";
} else {
$sql = "SELECT *,
if (
e.from_id <> 0,
(SELECT u.user_logo FROM users AS u WHERE u.id = e.from_id),
(SELECT u.user_logo FROM users AS u WHERE u.id = e.user_id)
) AS user_logo,
if (
e.from_id <> 0,
(SELECT u.fio FROM users AS u WHERE u.id = e.from_id),
(SELECT u.fio FROM users AS u WHERE u.id = e.user_id)
) AS user_fio
FROM user_object_events AS e
WHERE e.user_id = '$user_id' AND
e.id = '$event_id'";
if ($event_type)
$sql .= " AND e.type = '$event_type'";
$sql .= " LIMIT 1";
}
if (!empty($sql)) {
$createDate = null;
if ($query = mysql_query($sql)) {
while ($event = mysql_fetch_assoc($query)) {
if ($createDate == null || $createDate != date("d.m.Y", strtotime($event['create_date']))) {
$createDate = date("d.m.Y", strtotime($event['create_date']));
if ($createDate == date("d.m.Y")) {
$event['chat_date'] = 'Сегодня';
} else if ($createDate == date("d.m.Y", strtotime("-1 DAY"))) {
$event['chat_date'] = 'Вчера';
} else {
list($d, $m, $y) = explode(".", $createDate);
if ($y == date("Y"))
$y = "";
$event['chat_date'] = trim($d . " " . getRusMonth($m) . " " . $y);
}
}
$from_id = $event['user_id'];
$event['chat_position'] = "right";
if (!empty($event['from_id']))
$from_id = $event['from_id'];
if ($_SESSION['id'] == $from_id)
$event['chat_position'] = "left";
$data = [];
switch ($event['type']) {
case 'comment':
$data['time'] = date("H:i", strtotime($event['create_date']));
$data['comment'] = trim($event['comment']);
break;
case 'file':
$data['title'] = trim($event['name']);
$file_list = [];
$docs_q = mysql_query("SELECT * FROM clients_files WHERE event_id = '".$event['id']."'");
$name_files = '';
while ($file = mysql_fetch_assoc($docs_q)) {
if ($file['name_id'] > 0 && $name_files == '') {
$sql_n = "SELECT * FROM names_client_files WHERE id={$file['name_id']}";
$q_n = mysql_query($sql_n);
if (mysql_num_rows($q_n) > 0) {
$r_n = mysql_fetch_assoc($q_n);
$name_files = $r_n['name'];
}
}
$temp_dir = null;
if ($file['object_id'] > 0)
$temp_dir = "https://uf.joywork.ru/upload/objects/" . $file['object_id'];
if (!is_null($temp_dir)) {
$data['_temp_dir'] = $temp_dir;
$data['_file'] = $file;
if ($file['object_id'] > 0) {
$file_list[] = [
'id' => intval($file['id']),
'filename' => $file['name'],
//'path' => $host . '/download_file.php?id=' . $file['id'],
'path' => $temp_dir . '/' . $file['guid'] . '.' . $file['type'],
];
} else {
$name_doc = $_SERVER['DOCUMENT_ROOT'] . '/upload/objects/'.$file['object_id'].'/'.$file['guid'].'.'.$file['type'];
if (file_exists($name_doc)) {
$file_path = '';
if ($file['object_id'] > 0)
$file_path = '/upload/objects/'.$file['object_id'].'/'.$file['guid'].'.'.$file['type'];
if (!empty($file_path) && !empty($file['name'])) {
$file_list[] = [
'id' => intval($file['id']),
'filename' => $file['name'],
//'path' => $host . '/download_file.php?id=' . $file['id'],
'path' => $host . $file_path,
];
}
}
}
}
}
$data['file_list'] = $file_list;
$data['comment'] = trim($event['comment']);
break;
case 'call':
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['time'] = date("H:i", strtotime($event['create_date']));
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$data['comment'] = trim($event['comment']);
break;
case 'meet':
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['address'] = trim($event['address']);
$data['time'] = date("H:i", strtotime($event['create_date']));
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$data['comment'] = trim($event['comment']);
break;
case 'show': // Показ
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['address'] = trim($event['address']);
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$data['comment'] = trim($event['comment']);
break;
case 'deal': // Сделка
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['summ'] = floatval($event['sum']);
$data['time'] = date("H:i", strtotime($event['create_date']));
$data['document'] = null;
if (isset($event['document_id'])) {
$doc_id = $event['document_id'];
if ($doc = \Docs::getInnerDoc(null, $doc_id)) {
$data['document']['id'] = intval($doc['id']);
$data['document']['name'] = trim($doc['name']);
$data['document']['url'] = $host . '/ajax/getInnerDoc.php?id=' . intval($doc['id']) . '&download_pdf=true&t=' . time();
if (isset($doc['params'])) {
if ($params = json_decode($doc['params'], true)) {
if ($params['client_id'] && $params['object_id']) {
$doc_parties = [];
if (isset($params['client_id'])) {
$sql_cl = "SELECT id, fio, phone, email FROM `clients` WHERE `id` = '$params[client_id]' LIMIT 1";
$rez_cl = mysql_query($sql_cl);
if ($doc_cl = mysql_fetch_assoc($rez_cl)) {
// Маскируем email/phone клиента, если у текущего пользователя
// включено `hide_client_contacts`. Helper сам проверяет право.
$cl_contacts = [];
if ($doc_cl['email'])
$cl_contacts[] = mask_email_value_if_needed($doc_cl['email']);
if ($doc_cl['phone'])
$cl_contacts[] = mask_phone_value_if_needed($doc_cl['phone']);
$doc_party = [
'client_id' => $doc_cl['id'],
'object_id' => $params['object_id'],
'title' => $doc_cl['fio'],
'contacts' => ((!empty($cl_contacts)) ? ' (' . implode(', ', $cl_contacts) . ')' : ''),
];
// Маскируем title (fio), если он вида "Новый клиент +7...".
$doc_party['title'] = mask_fio_if_contains_phone($doc_party['title']);
$doc_parties[] = $doc_party;
}
}
if (isset($params['object_id'])) {
$sql_obj = "SELECT id, nazv, adres FROM `objects` WHERE `id` = '$params[object_id]' LIMIT 1";
$rez_obj = mysql_query($sql_obj);
if ($doc_obj = mysql_fetch_assoc($rez_obj)) {
$doc_parties[] = [
'object_id' => $doc_obj['id'],
'client_id' => $params['client_id'],
'title' => $doc_obj['nazv'],
'address' => $doc_obj['adres'],
];
}
}
$data['document']['parties'] = $doc_parties;
}
}
}
}
}
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$data['comment'] = trim($event['comment']);
break;
}
$task = [
'id' => intval($event['id']),
// Offset-free: id события — реальный e.id; различитель листинга — явный флаг (echo'ит mJW в CRUD).
'is_external_listing_event' => $is_listing_task,
'chat_date' => isset($event['chat_date']) ? $event['chat_date'] : null,
'chat_position' => isset($event['chat_position']) ? $event['chat_position'] : null,
'user_id' => intval($from_id),
'user_name' => isset($event['user_fio']) ? $event['user_fio'] : null,
'who_work' => isset($event['who_work']) ? $event['who_work'] : null,
'user_logo' => (!empty($event['user_logo'])) ? $host . '/photos/agency/' . $event['user_logo'] . '?=' . time() : null,
'type' => isset($event['type']) ? $event['type'] : null,
'event' => $data,
'created_at' => isset($event['create_date']) ? date('Y.m.d H:i:s', strtotime($event['create_date'])) : null,
'time' => isset($event['create_date']) ? date("H:i", strtotime($event['create_date'])) : null,
];
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
} else if ($section == 'clients' || $section == 'requisitions' || $section == 'free') {
if ($section == 'clients') {
$sql = "SELECT e.id,
e.comment,
e.name,
e.create_date,
e.checklist,
e.type,
e.user_id,
e.record,
e.client_id,
e.document_id,
e.schedule_date,
e.schedule_date_to,
e.address,
e.sum,
e.from_id,
e.calendar_view,
e.megafon,
e.telphin,
e.beeline,
e.mts,
e.tele2,
e.tracking,
e.cancel,
if (
e.from_id <> 0,
(SELECT u.user_logo FROM users as u WHERE u.id = e.from_id),
(SELECT u.user_logo FROM users as u WHERE u.id = e.user_id)
) as user_logo,
if (
e.from_id <> 0,
(SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name) FROM users as u WHERE u.id = e.from_id),
(SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name) FROM users as u WHERE u.id = e.user_id)
) as user_fio
FROM user_client_events as e
WHERE e.id = '$event_id'";
if ($event_type)
$sql .= " AND e.type = '$event_type'";
$sql .= " UNION SELECT ev.id,
'' as comment,
'' as name,
ev.date as create_date,
0 as checklist,
'partner' as `type`,
ev.user_id,
'' as record,
ev.client_id,
'' as document_id,
ev.date as schedule_date,
'' as schedule_date_to,
'' as address,
'' as `sum`,
ev.from_id,
'' as calendar_view,
'' as `megafon`,
'' as telphin,
'' as beeline,
'' as mts,
'' as tele2,
'' as tracking,
0 as cancel,
if (
ev.from_id <> 0,
(SELECT u.user_logo FROM users as u WHERE u.id = ev.from_id),
(SELECT u.user_logo FROM users as u WHERE u.id = ev.user_id)
) as user_logo,
if (
ev.from_id <> 0,
(SELECT u.fio FROM users as u WHERE u.id = ev.from_id),
(SELECT u.fio FROM users as u WHERE u.id = ev.user_id)
) as user_fio
FROM events_clients as ev
WHERE ev.client_id = client_id AND event = 'transmitted_parallel'";
$sql .= " LIMIT 1";
} else if ($section == 'requisitions') {
$sql = "SELECT e.id,
e.comment,
e.name,
e.create_date,
e.checklist,
e.type,
e.user_id,
e.record,
e.client_id,
e.document_id,
e.schedule_date,
e.schedule_date_to,
e.address,
e.sum,
e.from_id,
e.calendar_view,
e.megafon,
e.telphin,
e.beeline,
e.mts,
e.tele2,
e.tracking,
e.cancel,
if (
e.from_id <> 0,
(SELECT u.user_logo FROM users as u WHERE u.id = e.from_id),
(SELECT u.user_logo FROM users as u WHERE u.id = e.user_id)
) as user_logo,
if (
e.from_id <> 0,
(SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name) FROM users as u WHERE u.id = e.from_id),
(SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name) FROM users as u WHERE u.id = e.user_id)
) as user_fio
FROM user_client_events as e
WHERE e.id = '$event_id'";
if ($event_type)
$sql .= " AND e.type = '$event_type'";
$sql .= " UNION SELECT ev.id,
'' as comment,
'' as name,
ev.date as create_date,
0 as checklist,
'partner' as `type`,
ev.user_id,
'' as record,
ev.client_id,
'' as document_id,
ev.date as schedule_date,
'' as schedule_date_to,
'' as address,
'' as `sum`,
ev.from_id,
'' as calendar_view,
'' as `megafon`,
'' as telphin,
'' as beeline,
'' as mts,
'' as tele2,
'' as tracking,
0 as cancel,
if (
ev.from_id <> 0,
(SELECT u.user_logo FROM users as u WHERE u.id = ev.from_id),
(SELECT u.user_logo FROM users as u WHERE u.id = ev.user_id)
) as user_logo,
if (
ev.from_id <> 0,
(SELECT u.fio FROM users as u WHERE u.id = ev.from_id),
(SELECT u.fio FROM users as u WHERE u.id = ev.user_id)
) as user_fio
FROM events_clients as ev
WHERE ev.req_id = req_id AND event = 'transmitted_parallel'";
$sql .= " LIMIT 1";
} else if($section == 'free'){
$sql = "SELECT e.id,
e.comment,
e.name,
e.create_date,
e.checklist,
e.type,
e.user_id,
e.record,
e.client_id,
e.document_id,
e.schedule_date,
e.schedule_date_to,
e.address,
e.sum,
e.from_id,
e.calendar_view,
e.megafon,
e.telphin,
e.beeline,
e.mts,
e.tele2,
e.tracking,
e.cancel,
if (
e.from_id <> 0,
(SELECT u.user_logo FROM users as u WHERE u.id = e.from_id),
(SELECT u.user_logo FROM users as u WHERE u.id = e.user_id)
) as user_logo,
if (
e.from_id <> 0,
(SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name) FROM users as u WHERE u.id = e.from_id),
(SELECT CONCAT(u.last_name, ' ', u.first_name, ' ', u.middle_name) FROM users as u WHERE u.id = e.user_id)
) as user_fio
FROM user_client_events as e
WHERE e.id = '$event_id'";
}
if (!empty($sql)) {
$createDate = null;
if ($query = mysql_query($sql)) {
while ($event = mysql_fetch_assoc($query)) {
if ($createDate == null || $createDate != date("d.m.Y", strtotime($event['create_date']))) {
$createDate = date("d.m.Y", strtotime($event['create_date']));
if ($createDate == date("d.m.Y")) {
$event['chat_date'] = 'Сегодня';
} else if ($createDate == date("d.m.Y", strtotime("-1 DAY"))) {
$event['chat_date'] = 'Вчера';
} else {
list($d, $m, $y) = explode(".", $createDate);
if ($y == date("Y"))
$y = "";
$event['chat_date'] = trim($d . " " . getRusMonth($m) . " " . $y);
}
}
$from_id = $event['user_id'];
$event['chat_position'] = "right";
if (!empty($event['from_id']))
$from_id = $event['from_id'];
if ($_SESSION['id'] == $from_id)
$event['chat_position'] = "left";
$data = [];
switch ($event['type']) {
case 'comment':
$data['time'] = date("H:i", strtotime($event['create_date']));
$data['comment'] = trim($event['comment']);
break;
case 'file':
case 'partner_id':
$data['title'] = trim($event['name']);
$file_list = [];
$docs_q = mysql_query("SELECT * FROM clients_files WHERE event_id = '".$event['id']."'");
$name_files = '';
while ($file = mysql_fetch_assoc($docs_q)) {
if ($file['name_id'] > 0 && $name_files == '') {
$sql_n = "SELECT * FROM names_client_files WHERE id={$file['name_id']}";
$q_n = mysql_query($sql_n);
if (mysql_num_rows($q_n) > 0) {
$r_n = mysql_fetch_assoc($q_n);
$name_files = $r_n['name'];
}
}
$name_doc = $_SERVER['DOCUMENT_ROOT'].'/upload/clients/'.$file['client_id'].'/'.$file['guid'].'.'.$file['type'];
if ($file['req_id'] > 0) {
$file_path = 'https://uf.joywork.ru/upload/reqs/' . $file['req_id'] . '/' . $file['guid'] . '.' . $file['type'];
$file_list[] = [
'id' => intval($file['id']),
'filename' => $file['name'],
'path' => $file_path,
];
} else {
if ($file['client_id'] > 0) {
$file_path = 'https://uf.joywork.ru/upload/clients/' . $file['client_id'] . '/' . $file['guid'] . '.' . $file['type'];
$file_list[] = [
'id' => intval($file['id']),
'filename' => $file['name'],
'path' => $file_path,
];
} else {
if (file_exists($name_doc)) {
$file_path = '';
if ($file['client_id'] > 0)
$file_path = '/upload/clients/' . $file['client_id'] . '/' . $file['guid'] . '.' . $file['type'];
if ($file['req_id'] > 0)
$file_path = '/upload/reqs/' . $file['req_id'] . '/' . $file['guid'] . '.' . $file['type'];
if (!empty($file_path) && !empty($file['name'])) {
$file_list[] = [
'id' => intval($file['id']),
'filename' => $file['name'],
//'path' => $host . '/download_file.php?id=' . $file['id'],
'path' => $host . $file_path,
];
}
}
}
}
}
$data['file_list'] = $file_list;
$data['comment'] = trim($event['comment']);
break;
case 'call':
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_to'] = date('Y-m-d H:i:s', strtotime($event['schedule_date_to']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['time'] = date("H:i", strtotime($event['create_date']));
if (!empty($event['record'])) {
if ($event['megafon'] == 1) {
$oper = 'mega';
$path = '/server/mega/';
if (!file_exists($_SERVER['DOCUMENT_ROOT'].$path.$event['record'])) {
$href = 'https://voice.joywork.ru/mega/';
$Headers = @get_headers($href.$event['record']);
if (strpos($Headers[0],'200')) {
$path = $href;
} else {
$path = '';
}
}
if (!empty($path)) {
$data['records'][] = [
'operator' => $oper,
'source_path' => $path . $event['record']
];
}
} else {
$arr_rec = json_decode($event['record']);
if (!empty($arr_rec)) {
foreach ($arr_rec as $rec) {
if (!empty($rec)) {
$oper = null;
$path = '';
if ($event['telphin'] == 1) {
$oper = 'telphin';
$path = '/server/telphin/';
if (!file_exists($_SERVER['DOCUMENT_ROOT'].$path.$rec.'.mp3')) {
$href = 'https://voice.joywork.ru/telphin/';
$Headers = @get_headers($href.$rec.'.mp3');
if (strpos($Headers[0],'200')) {
$path = $href;
} else {
$path = '';
}
}
} else if ($event['beeline'] == 1) {
$oper = 'beeline';
$path = '/server/beeline/';
if (!file_exists($_SERVER['DOCUMENT_ROOT'].$path.$rec.'.mp3')) {
$href = 'https://voice.joywork.ru/beeline/';
$Headers = @get_headers($href.$rec.'.mp3');
if (strpos($Headers[0],'200')) {
$path = $href;
} else {
$path = '';
}
}
} else if ($event['mts'] == 1) {
$oper = 'mts';
$path = '/server/mts/'.$user->agencyId."/";
if (!file_exists($_SERVER['DOCUMENT_ROOT'].$path.$rec.'.mp3')) {
$href = 'https://voice.joywork.ru/mts/'.$user->agencyId.'/';
$Headers = @get_headers($href.$rec.'.mp3');
if (strpos($Headers[0],'200')) {
$path = $href;
} else {
$path = '';
}
}
} else if ($event['tele2'] == 1) {
$oper = 'tele2';
$date_patch = date('Ymd', strtotime($event['create_date']));
$path = '/server/tele2/'.$user->agencyId.'/'.$date_patch.'/';
if (!file_exists($_SERVER['DOCUMENT_ROOT'].$path.$rec.'.mp3')) {
$href = 'https://voice.joywork.ru/tele2/'.$user->agencyId.'/'.$date_patch.'/';
$Headers = @get_headers($href.$rec.'.mp3');
if (strpos($Headers[0],'200')) {
$path = $href;
} else {
$path = '';
}
}
} else {
$oper = 'mango';
$path = '/server/mango/';
if (!file_exists($_SERVER['DOCUMENT_ROOT'].$path.$rec.'.mp3')) {
$href = 'https://voice.joywork.ru/mango/';
$Headers = @get_headers($href.$rec.'.mp3');
if (strpos($Headers[0],'200')) {
$path = $href;
} else {
$path = '';
}
}
}
if (!empty($path)) {
$data['records'][] = [
'operator' => $oper,
'source_path' => $path . $rec . '.mp3'
];
}
}
}
}
}
} else {
$data['records'] = null;
}
$data['is_tracking'] = ($event['tracking'] == 1);
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$data['comment'] = trim($event['comment']);
break;
case 'meet':
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['address'] = trim($event['address']);
$data['time'] = date("H:i", strtotime($event['create_date']));
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$data['comment'] = trim($event['comment']);
break;
case 'show': // Показ
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['address'] = trim($event['address']);
$data['time'] = date("H:i", strtotime($event['create_date']));
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$data['comment'] = trim($event['comment']);
break;
case 'deal': // Сделка
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['summ'] = floatval($event['sum']);
$data['time'] = date("H:i", strtotime($event['create_date']));
$data['document'] = null;
if (isset($event['document_id'])) {
$doc_id = $event['document_id'];
if ($doc = \Docs::getInnerDoc(null, $doc_id)) {
$data['document']['id'] = intval($doc['id']);
$data['document']['name'] = trim($doc['name']);
$data['document']['url'] = $host . '/ajax/getInnerDoc.php?id=' . intval($doc['id']) . '&download_pdf=true&t=' . time();
if (isset($doc['params'])) {
if ($params = json_decode($doc['params'], true)) {
if ($params['client_id'] && $params['object_id']) {
$doc_parties = [];
if (isset($params['client_id'])) {
$sql_cl = "SELECT id, fio, phone, email FROM `clients` WHERE `id` = '$params[client_id]' LIMIT 1";
$rez_cl = mysql_query($sql_cl);
if ($doc_cl = mysql_fetch_assoc($rez_cl)) {
// Маскируем email/phone клиента, если у текущего пользователя
// включено `hide_client_contacts`. Helper сам проверяет право.
$cl_contacts = [];
if ($doc_cl['email'])
$cl_contacts[] = mask_email_value_if_needed($doc_cl['email']);
if ($doc_cl['phone'])
$cl_contacts[] = mask_phone_value_if_needed($doc_cl['phone']);
$doc_party = [
'client_id' => $doc_cl['id'],
'object_id' => $params['object_id'],
'title' => $doc_cl['fio'],
'contacts' => ((!empty($cl_contacts)) ? ' (' . implode(', ', $cl_contacts) . ')' : ''),
];
// Маскируем title (fio), если он вида "Новый клиент +7...".
$doc_party['title'] = mask_fio_if_contains_phone($doc_party['title']);
$doc_parties[] = $doc_party;
}
}
if (isset($params['object_id'])) {
$sql_obj = "SELECT id, nazv, adres FROM `objects` WHERE `id` = '$params[object_id]' LIMIT 1";
$rez_obj = mysql_query($sql_obj);
if ($doc_obj = mysql_fetch_assoc($rez_obj)) {
$doc_parties[] = [
'object_id' => $doc_obj['id'],
'client_id' => $params['client_id'],
'title' => $doc_obj['nazv'],
'address' => $doc_obj['adres'],
];
}
}
$data['document']['parties'] = $doc_parties;
}
}
}
}
}
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$data['comment'] = trim($event['comment']);
break;
case 'even':
$data['title'] = trim($event['name']);
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$data['schedule_date'] = date('Y-m-d H:i:s', strtotime($event['schedule_date']));
$data['schedule_date_string'] = $d . ' ' . getRusMonth($m) . ' ' . $y . ' в ' . date("H:i", strtotime($event['schedule_date']));
$data['summ'] = floatval($event['sum']);
$data['address'] = trim($event['address']);
$data['time'] = date("H:i", strtotime($event['create_date']));
$data['is_completed'] = ($event['calendar_view'] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$data['comment'] = trim($event['comment']);
break;
case 'step':
$data['time'] = date("H:i", strtotime($event['create_date']));
$data['title'] = trim($event['name']);
$data['is_checklist'] = !($event['checklist'] == 0);
$data['is_completed'] = (isset($doers[$event['from_id']]) && $doers[$event['from_id']] == 1);
$data['is_cancel'] = ($event['cancel'] == 1);
$data['comment'] = trim($event['comment']);
break;
case 'partner':
$schedule_date = date("d.m.Y", strtotime($event['schedule_date']));
list($d, $m, $y) = explode(".", $schedule_date);
$doers = [];
if (!empty($client->doers)) {
$doers_arr = json_decode(html_entity_decode($client->doers));
foreach ($doers_arr as $key => $doer) {
$doers[$key] = $doer;
}
} else if ((isset($get['req_id']) && $get['req_id'] > 0) && !empty($client['doers'])) {
$doers_arr = json_decode(html_entity_decode($client['doers']));
foreach ($doers_arr as $key => $doer) {
$doers[$key] = $doer;
}
}
$data['comment'] = 'Добавлен к совместной работе.';
$data['doers_id'] = $doers;
break;
}
$task = [
'id' => intval($event['id']),
// Клиент/заявка — не листинг; флаг держим для единообразия формы ответа.
'is_external_listing_event' => false,
'chat_date' => isset($event['chat_date']) ? $event['chat_date'] : null,
'chat_position' => isset($event['chat_position']) ? $event['chat_position'] : null,
'user_id' => intval($from_id),
'user_name' => isset($event['user_fio']) ? $event['user_fio'] : null,
'who_work' => isset($event['who_work']) ? $event['who_work'] : null,
'user_logo' => (!empty($event['user_logo'])) ? $host . '/photos/agency/' . $event['user_logo'] . '?=' . time() : null,
'type' => isset($event['type']) ? $event['type'] : null,
'event' => $data,
//'is_new' => $data,
'created_at' => isset($event['create_date']) ? date('Y.m.d H:i:s', strtotime($event['create_date'])) : null,
'time' => isset($event['create_date']) ? date("H:i", strtotime($event['create_date'])) : null,
];
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
}
if ($need_return && !$error) {
return $task;
} else if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => $user_id,
'section' => $section,
'task' => $task,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function setTaskState($app, $get = null, $post = null) {
$error = false;
$errors = [];
if ($user_id = $_SESSION['id']) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$body = $app->request->getBody();
$data = json_decode(stripcslashes($body), true);
$object_id = null;
if (isset($data['object_id']))
$object_id = intval($data['object_id']);
$client_id = null;
if (isset($data['client_id']))
$client_id = intval($data['client_id']);
$requisition_id = null;
if (isset($data['requisition_id']))
$requisition_id = intval($data['requisition_id']);
$event_id = null;
if (isset($data['event_id']))
$event_id = intval($data['event_id']);
$state = null;
if (isset($data['state']))
$state = intval($data['state']);
$action = null;
if (isset($data['action']))
$action = trim($data['action']);
$section = null;
if(isset($data['section'])){
$section = $data['section'];
}
if (!is_null($event_id)) {
// Offset-free: событие листинга различаем по явному флагу is_external_listing_event из запроса (echo'ит mJW).
// event_id = реальный id в external_listing_events (без смещения; коллизию с id своего объекта снимает флаг).
require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/helpers/external_listing_events.php';
if (self::_request_flag($data, 'is_external_listing_event')) {
$listing_done = false;
if ($action == 'state' && !is_null($state)) {
$state = $state ? 1 : 0;
$listing_done = (bool)mysql_query("UPDATE `external_listing_events` SET `calendar_view` = {$state} WHERE `id` = " . (int)$event_id . \external_listing_events_scope_clause()); // scope агентства — нельзя тогглить чужое событие
}
// Действие cancel к событиям листинга неприменимо — флага cancel в их таблице нет.
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => $listing_done,
'user_id' => $user_id,
'section' => 'objects',
'tasks' => null,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
if ($action == 'state') {
if ($object_id) {
$section = 'objects';
$sql = "UPDATE `user_object_events` SET `calendar_view` = {$state} WHERE `id` = {$event_id} AND `object_id` = {$object_id}";
}
if ($client_id) {
$section = 'clients';
$sql = "UPDATE `user_client_events` SET `calendar_view` = {$state} WHERE `id` = {$event_id} AND `client_id` = {$client_id}";
}
if ($requisition_id) {
$section = 'requisitions';
$sql = "UPDATE `user_client_events` SET `calendar_view` = {$state} WHERE `id` = {$event_id} AND `req_id` = {$requisition_id}";
}
if($section == 'free'){
$sql = "UPDATE `user_client_events` SET `calendar_view` = {$state} WHERE `id` = {$event_id}";
}
if (!empty($sql)) {
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
} else {
$error = true;
}
} else if ($action == 'cancel') {
if ($client_id) {
$section = 'clients';
$sql = "UPDATE `user_client_events` SET `cancel` = 1 WHERE `id` = {$event_id} AND `client_id` = {$client_id}";
}
if ($requisition_id) {
$section = 'requisitions';
$sql = "UPDATE `user_client_events` SET `cancel` = 1 WHERE `id` = {$event_id} AND `req_id` = {$requisition_id}";
}
if($section == 'free'){
$sql = "UPDATE `user_client_events` SET `cancel` = 1 WHERE `id` = {$event_id}";
}
if (!empty($sql)) {
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
} else {
$error = true;
}
}
if (!$error) {
$tasks = [];
if ($section == 'objects')
$tasks = self::getTasks($app, ['object_id' => $object_id], null, true);
else if ($section == 'clients')
$tasks = self::getTasks($app, ['client_id' => $client_id], null, true);
else if ($section == 'requisitions')
$tasks = self::getTasks($app, ['requisition_id' => $requisition_id], null, true);
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => $user_id,
'section' => $section,
'tasks' => (!empty($tasks)) ? $tasks : null,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function deleteTask($app, $get = null, $post = null) {
$error = false;
$errors = [];
if ($user_id = $_SESSION['id']) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$object_id = null;
if (isset($get['object_id']))
$object_id = intval($get['object_id']);
$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']);
$event_id = null;
if (isset($get['event_id']))
$event_id = intval($get['event_id']);
$section = null;
if (!is_null($event_id)) {
// Offset-free: событие листинга различаем по явному флагу is_external_listing_event из запроса (echo'ит mJW) —
// удаляем из external_listing_events по реальному id (event_id, без смещения).
require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/helpers/external_listing_events.php';
if (self::_request_flag($get, 'is_external_listing_event')) {
$listing_where = "`id` = " . (int)$event_id . \external_listing_events_scope_clause(); // scope агентства — нельзя удалить чужое событие листинга
// Если фронт прислал и сам листинг (object_id = реальный el.id, флаг is_external) — сверяем принадлежность события.
if ($object_id && self::_request_flag($get, 'is_external'))
$listing_where .= " AND `external_listing_id` = " . (int)$object_id;
if (!mysql_query("DELETE FROM `external_listing_events` WHERE " . $listing_where)) {
$error = true;
$errors[] = mysql_error();
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => $user_id,
'section' => 'objects',
'tasks' => null,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
if ($object_id) {
$section = 'objects';
$sql = "DELETE FROM `user_object_events` WHERE `id` = '{$event_id}' AND `object_id` = '{$object_id}'";
}
if ($client_id) {
$section = 'clients';
$sql = "DELETE FROM `user_client_events` WHERE `id` = '{$event_id}' AND `client_id` = '{$client_id}'";
}
if ($requisition_id) {
$section = 'requisitions';
$sql = "DELETE FROM `user_client_events` WHERE `id` = '{$event_id}' AND `req_id` = '{$requisition_id}'";
}
if (!empty($sql)) {
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
} else {
$error = true;
}
if (!$error) {
$tasks = [];
if ($section == 'objects')
$tasks = self::getTasks($app, ['object_id' => $object_id], null, true);
else if ($section == 'clients')
$tasks = self::getTasks($app, ['client_id' => $client_id], null, true);
else if ($section == 'requisitions')
$tasks = self::getTasks($app, ['requisition_id' => $requisition_id], null, true);
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => $user_id,
'section' => $section,
'tasks' => (!empty($tasks)) ? $tasks : null,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function addEditTask($app, $get = null, $post = null) {
$error = false;
$sqls = [];
$errors = [];
if ($user_id = intval($_SESSION['id'])) {
date_default_timezone_set('Europe/Moscow');
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$body = $app->request->getBody();
$data = json_decode(stripcslashes($body), true);
/*error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('display_errors', 1);*/
$event_id = null;
if (isset($data['event_id']))
$event_id = intval($data['event_id']);
$who_work_event = 0;
// if(is_null($event_id))
$who_work_event = (int)$data['who_work'];
$event_type = null;
if (isset($data['event_type']))
$event_type = trim(strtolower($data['event_type']));
$object_id = null;
if (isset($data['object_id'])) {
$object_id = intval($data['object_id']);
}
// Offset-free: листинг и его событие различаем по явным флагам из запроса (echo'ит mJW), а не по диапазону id.
// is_external — объект-листинг (object_id = реальный el.id); is_external_listing_event — событие листинга (event_id = реальный el event id).
$is_listing_object = self::_request_flag($data, 'is_external');
$is_listing_event = self::_request_flag($data, 'is_external_listing_event');
$client_id = null;
if (isset($data['client_id'])) {
$client_id = intval($data['client_id']);
}
$requisition_id = null;
if (isset($data['requisition_id'])) {
$requisition_id = intval($data['requisition_id']);
}
$section = null;
if ($object_id)
$section = 'objects';
if ($client_id)
$section = 'clients';
if ($requisition_id)
$section = 'requisitions';
if($section == null){
if($data['section']){
$section = $data['section'];
}
}
$task = null;
if (isset($data['task']))
$task = $data['task'];
if (!empty($section) && !empty($task)) {
$schedule_date = 'NULL';
if (isset($task['schedule_date'])) {
if ($date_time = strtotime($task['schedule_date']))
$schedule_date = date("Y-m-d H:i:s", $date_time);
}
$schedule_date_to = 'NULL';
if (isset($task['schedule_date_to'])) {
if ($date_time = strtotime($task['schedule_date_to']))
$schedule_date_to = date("Y-m-d H:i:s", $date_time);
}
$title = '';
if (isset($task['title']))
$title = trim($task['title']);
$comment = '';
if (isset($task['comment']))
$comment = trim($task['comment']);
$summ = 'NULL';
if (isset($task['summ']))
$summ = intval($task['summ']);
$address = 'NULL';
if (isset($task['address']))
$address = trim($task['address']);
$document_id = 'NULL';
if (isset($task['document_id']) && $object_id) {
if ($document = \Docs::fillInnerDocument($task['document_id'], $task['client_id'], $object_id))
$document_id = $document['doc_id'];
} else if (isset($task['document_id']) && $client_id) {
if ($document = \Docs::fillInnerDocument($task['document_id'], $client_id, $task['object_id']))
$document_id = $document['doc_id'];
}
// Хелперы событий найденных листингов парсера (offset-free, ключ — реальный el.id).
require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/helpers/external_listing_events.php';
// Найденный листинг парсера: события живут в external_listing_events (ключ — реальный el.id, без смещения).
// Признак листинга/его события — явные флаги из запроса (echo'ит mJW); object_id/event_id — реальные id.
// При создании наружу возвращаем реальный id + is_external_listing_event=true (см. ответ ниже).
if ($object_id && $section == 'objects' && $is_listing_object) {
if ($event_type == 'deal' || $event_type == 'file') {
// На найденном листинге недоступны: сделка (сначала копирование в свои объекты) и прикрепление файла
// (read-only, clients_files к листингу не привязываем). UI оба пункта прячет; это серверный гард.
$error = true;
$errors[] = ($event_type == 'file') ? 'Прикрепление файлов к найденному листингу недоступно' : 'Сделка на найденном листинге недоступна';
} else if ($event_id && $is_listing_event && $event_type) {
// Правка существующего события листинга (набор полей — как у обычного объекта).
$listing_fields = [
'schedule_date' => ($schedule_date === 'NULL') ? 'NULL' : "'" . $schedule_date . "'",
'comment' => "'" . mysql_real_escape_string($comment) . "'",
'address' => ($address === 'NULL' || $address === '') ? 'NULL' : "'" . mysql_real_escape_string($address) . "'",
'name' => ($title !== '') ? "'" . mysql_real_escape_string($title) . "'" : 'NULL',
];
if (!\update_external_listing_event((int)$event_id, $listing_fields)) {
$error = true;
$errors[] = mysql_error();
}
} else if (!$event_id && $event_type) {
// Новое событие на листинге: ответственный — выбранный исполнитель либо автор (владельца у листинга нет).
$who_work_id = ($who_work_event > 0) ? $who_work_event : $user_id;
$inserted_id = \insert_external_listing_event(
(int)$object_id,
$who_work_id,
$user_id,
$event_type,
($comment !== '') ? $comment : null,
($address !== 'NULL' && $address !== '') ? $address : null,
($schedule_date !== 'NULL') ? "'" . $schedule_date . "'" : null,
($title !== '') ? $title : null
);
if ($inserted_id === false) {
$error = true;
$errors[] = mysql_error();
} else {
// Наружу id события — реальный e.id (offset-free); признак листинга вернём флагом is_external_listing_event.
$event_id = (int)$inserted_id;
}
} else {
// Несогласованные идентификаторы: правка события листинга требует флага is_external_listing_event при заданном event_id.
$error = true;
$errors[] = 'Некорректный id события листинга';
}
} else if ($object_id && $section == 'objects') {
$sql = "SELECT `id_add_user` FROM `objects` WHERE `id` = '$object_id'";
$who_work_id = intval($user_id);
$sqls[] = $sql;
if ($query = mysql_query($sql)) {
$obj = mysql_fetch_assoc($query);
if ($obj['id_add_user'] > 0) {
$who_work_id = intval($obj['id_add_user']);
}
} else {
$error = true;
$errors[] = mysql_error();
}
if($who_work_event > 0){
$who_work_id = $who_work_event;
}
$calendar_view = 0;
/*if ($user_id == $from_id)
$calendar_view = 1;*/
$user_object_events = [
'user_id' => $who_work_id,
'from_id' => $user_id,
'object_id' => ($object_id) ? $object_id : 'NULL',
'type' => $event_type,
'sum' => $summ,
'address' => $address,
'comment' => $comment,
'name' => ($title) ? $title : null,
'document_id' => ($document_id) ? $document_id : 'NULL',
'schedule_date' => $schedule_date,
'calendar_view' => $calendar_view,
'create_date' => date('Y-m-d H:i:s'),
];
if ($event_id && $event_type) {
$db_values = [];
foreach ($user_object_events as $key => $value) {
if ($key == 'client_id' && is_null($value))
$db_values[] = "0";
else if (is_null($value))
$db_values[] = "`$key` = NULL";
else if (!$value || $value === 0)
$db_values[] = "`$key` = 0";
else if (is_int($value))
$db_values[] = "`$key` = $value";
else
$db_values[] = "`$key` = '$value'";
}
$sql = "UPDATE `user_object_events`";
$sql .= " SET " . implode(',', $db_values);
$sql .= " WHERE `id` = '$event_id' AND `type` = '$event_type'";
} else if ($event_type) {
$db_keys = [];
$db_values = [];
foreach ($user_object_events as $key => $value) {
$db_keys[] = "`$key`";
if ($key == 'client_id' && is_null($value))
$db_values[] = "0";
else if (is_null($value))
$db_values[] = "NULL";
else if (!$value || $value === 0)
$db_values[] = "0";
else if (is_int($value))
$db_values[] = "$value";
else
$db_values[] = "'$value'";
}
$sql = "INSERT INTO `user_object_events`";
$sql .= " (" . implode(',', $db_keys) . ")";
$sql .= " VALUES (" . implode(',', $db_values) . ")";
}
$sqls[] = $sql;
if ($query = mysql_query($sql)) {
if (!$event_id)
$event_id = mysql_insert_id();
if ($event_type == 'file' && !empty($task['files'])) {
foreach($task['files'] as $file) {
$guid = $file['guid'];
$extension = $file['type'];
$filename = $file['name'];
$sql = "INSERT INTO `names_client_files` SET `name` = '{$filename}'";
$sqls[] = $sql;
if (mysql_query($sql)) {
$id_name = mysql_insert_id();
$sql = "UPDATE `clients_files` SET `name_id` = {$id_name} WHERE `event_id` = {$event_id}";
$sqls[] = $sql;
if ($query = mysql_query($sql)) {
if (mysql_affected_rows($query) == 0 && $guid && $extension && $filename) {
if ($object_id > 0) {
$sql = "INSERT INTO clients_files (guid, object_id, type, name, event_id, name_id)
VALUES ('{$guid}', '{$object_id}', '{$extension}', '{$filename}', '{$event_id}', {$id_name})";
}
$sqls[] = $sql;
if (!empty($sql)) {
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
}
$client = mysql_fetch_assoc($query);
if ($client['who_work'] > 0 && $client['doer_clients'] == 0) {
$who_work_id = intval($client['who_work']);
}
} else {
$error = true;
$errors[] = mysql_error();
}
} else if (($client_id && $section == 'clients') || ($requisition_id && $section == 'requisitions')) {
$sql = "SELECT * FROM clients WHERE id = '$client_id'";
if ($requisition_id > 0)
$sql = "SELECT * FROM requisitions WHERE id = '$requisition_id'";
$funnel_id = 0;
$step_id_event = 0;
$who_work_id = intval($user_id);
$sqls[] = $sql;
if ($query = mysql_query($sql)) {
$client = mysql_fetch_assoc($query);
if ($client['who_work'] > 0 && $client['doer_clients'] == 0) {
$who_work_id = intval($client['who_work']);
}
$funnel_id = (int)$client['funnel_id'];
$step_id_event = (int)$client['step_id'];
} else {
$error = true;
$errors[] = mysql_error();
}
if($who_work_event > 0){
$who_work_id = $who_work_event;
}
$calendar_view = 0;
if ($event_type) {
if ($event_type == 'partner_id' && isset($task['partner_id'])) {
$doers = $task['partner_id'];
$doers_old = [];
$sql = "SELECT c.doers, c.doers_confirm, c.funnel_id, c.stage, c.step_id, c.deleted, c.who_work, f.name
FROM clients as c
LEFT JOIN funnel_steps as f on f.id = c.step_id
WHERE c.id = ".$client_id;
if ($requisition_id > 0) {
$sql = "SELECT c.doers, c.doers_confirm, c.funnel_id, c.stage, c.step_id, c.deleted, c.who_work, f.name
FROM requisitions as c
LEFT JOIN funnel_steps as f on f.id = c.step_id
WHERE c.id = ".$requisition_id;
}
if ($query = mysql_query($sql)) {
$client = mysql_fetch_assoc($query);
if (!empty($client['doers']))
$doers_old = json_decode(html_entity_decode($client['doers']), true);
$confirm = 1;
$stages = [
1 => "Новый",
2 => "В работе",
3 => "Презентация",
4 => "Показ",
5 => "Бронь",
6 => "Подаем на ипотеку",
7 => "Сделка",
8 => "Закрыт"
];
$agency = [];
if (isset($doers_old[$user_id]))
$agency[$user_id] = 1;
foreach($doers as $doer) {
if (isset($doer->code))
$doer = $doer->code;
if ($doer != $user_id) {
if (isset($doers_old[$doer])) {
$agency[$doer] = $doers_old[$doer];
} else {
$agency[$doer] = 0;
$confirm = 0;
$sql_conf = "INSERT INTO `events_clients` (`user_id`, `client_id`, `from_id`, `event`) VALUES (".$user_id.", ".$client_id.", ".$doer.", 'transmitted_parallel')";
if ($requisition_id > 0)
$sql_conf = "INSERT INTO `events_clients` (`user_id`, `req_id`, `from_id`, `event`) VALUES (".$user_id.", ".$requisition_id.", ".$doer.", 'transmitted_parallel')";
if (!mysql_query($sql_conf)) {
$error = true;
$errors[] = mysql_error();
}
if ($client['funnel_id'] == 0) {
$step_id = $client['stage'];
$step_name = $stages[$step_id];
} else {
$step_id = $client['step_id'];
$step_name = $client['name'];
}
if (!$step_id)
$step_id = 0;
if (!$step_name)
$step_name = '';
$sql_step = "INSERT INTO `doers_emp_client` (`user_id`, `doer_id`, `who_work`, `client_id`, `funnel_id`, `step_id`, `step_name`,`start_date`) VALUES (".$user_id.", ".$doer.",".$client['who_work'].", ".$client_id.", ".$client['funnel_id'].", ".$step_id.", '".$step_name."', '".date('Y-m-d H:i:s')."')";
if ($requisition_id > 0)
$sql_step = "INSERT INTO `doers_emp_client` (`user_id`, `doer_id`, `who_work`, `req_id`, `funnel_id`, `step_id`, `step_name`,`start_date`) VALUES (".$user_id.", ".$doer.",".$client['who_work'].", ".$requisition_id.", ".$client['funnel_id'].", ".$step_id.", '".$step_name."', '".date('Y-m-d H:i:s')."')";
if (!mysql_query($sql_step)) {
$error = true;
$errors[] = mysql_error();
$errors[] = $sql_step;
}
}
}
}
foreach($doers_old as $doer_id => $doer) {
if (!isset($agency[$doer_id])) {
$sql_conf = "INSERT INTO `events_clients` (`user_id`, `client_id`, `from_id`, `event`, `read`, `send_telegramm`) VALUES (".$user_id.", ".$client_id.", ".$doer_id.", 'parallel_del', 1, 1)";
if ($requisition_id > 0)
$sql_conf = "INSERT INTO `events_clients` (`user_id`, `req_id`, `from_id`, `event`, `read`, `send_telegramm`) VALUES (".$user_id.", ".$requisition_id.", ".$doer_id.", 'parallel_del', 1, 1)";
if (!mysql_query($sql_conf)) {
$error = true;
$errors[] = mysql_error();
}
$sql_s = "SELECT id FROM doers_emp_client WHERE user_id = ".$user_id." and client_id=".$client_id." and doer_id = ".$doer_id." ORDER BY id desc";
if ($requisition_id > 0)
$sql_s = "SELECT id FROM doers_emp_client WHERE user_id = ".$user_id." and req_id=".$requisition_id." and doer_id = ".$doer_id." ORDER BY id desc";
if ($q_s = mysql_query($sql_s)) {
$r_s = mysql_fetch_assoc($q_s);
$sql_up = "UPDATE doers_emp_client SET end_date = '".date('Y-m-d H:i:s')."' WHERE id = ".$r_s['id'];
if (!mysql_query($sql_up)) {
$error = true;
$errors[] = mysql_error();
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
}
$count = 0;
foreach($agency as $key => $agent) {
if ($key != $user_id) {
$count++;
}
}
$doers_up = self::clearInput(json_encode($agency));
$doer_clients = 1;
if ($count == 0) {
$doers_up = '';
$doer_clients = 0;
}
$sql = "UPDATE clients SET doers_confirm = ".$confirm.", doer_clients = ".$doer_clients.", doers = '". $doers_up."' WHERE id = ".$client_id;
if ($requisition_id > 0)
$sql = "UPDATE requisitions SET doers_confirm = ".$confirm.", doer_clients = ".$doer_clients.", doers = '". $doers_up."' WHERE id = ".$requisition_id;
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
} else {
$error = true;
$errors[] = mysql_error();
}
} else {
$user_client_events = [
'user_id' => $who_work_id,
'from_id' => $user_id,
'client_id' => ($client_id) ? $client_id : 0,
'req_id' => ($requisition_id) ? $requisition_id : 0,
'type' => $event_type,
'sum' => ($summ) ? $summ : null,
'address' => ($address) ? $address : null,
'document_id' => ($document_id) ? $document_id : null,
'name' => ($title) ? $title : null,
'comment' => $comment,
'schedule_date' => ($schedule_date) ? $schedule_date : null,
'schedule_date_to' => ($schedule_date_to) ? $schedule_date_to : null,
'calendar_view' => $calendar_view,
'tracking' => (isset($task['is_tracking']) ? intval($task['is_tracking']) : 0),
'create_date' => date('Y-m-d H:i:s'),
];
/*if ($_SESSION['id'] == 5427)
var_export($user_client_events) && die();*/
if ($event_id) {
$db_values = [];
foreach ($user_client_events as $key => $value) {
if (is_null($value) || ($value === 'NULL'))
$db_values[] = "`$key` = NULL";
else if (!$value)
$db_values[] = "`$key` = 0";
else if (is_int($value))
$db_values[] = "`$key` = $value";
else
$db_values[] = "`$key` = '$value'";
}
$sql = "UPDATE `user_client_events`";
$sql .= " SET " . implode(',', $db_values);
$sql .= " WHERE `id` = '$event_id' AND `type` = '$event_type'";
} else {
$user_client_events['funnel_id'] = $funnel_id;
$user_client_events['step_id'] = $step_id_event;
$db_keys = [];
$db_values = [];
foreach ($user_client_events as $key => $value) {
$db_keys[] = "`$key`";
if (is_null($value) || ($value === 'NULL'))
$db_values[] = "NULL";
else if (!$value)
$db_values[] = "0";
else if (is_int($value))
$db_values[] = "$value";
else
$db_values[] = "'$value'";
}
$sql = "INSERT INTO `user_client_events`";
$sql .= " (" . implode(',', $db_keys) . ")";
$sql .= " VALUES (" . implode(',', $db_values) . ")";
}
$sqls[] = $sql;
if (mysql_query($sql)) {
if (!$event_id)
$event_id = mysql_insert_id();
if ($event_type == 'deal' && isset($task['schedule_date'])) {
$date = \DateTime::createFromFormat('Y-m-d H:i', $task['schedule_date']);
$dop_text = "Запланирована сделка на " . date("Y-m-d H:i:s", $date->getTimestamp());
if (!is_null($document)) {
$dop_text .= ", сформирован документ: " . '
' . $document['doc_name'] . '
.';
} else {
$dop_text .= ".";
}
$dop_text .= "
От ";
$events_clients = [
'user_id' => $who_work_id,
'from_id' => $user_id,
'client_id' => $client_id || 'NULL',
'req_id' => $requisition_id || 'NULL',
'event' => 'add_deal',
'dop_text' => "'$dop_text'",
'read' => '1',
];
$db_keys = [];
$db_values = [];
foreach ($events_clients as $key => $value) {
$db_keys[] = "`$key`";
if (is_null($value))
$db_values[] = "NULL";
else if (!$value || $value === 0)
$db_values[] = "0";
else if (is_int($value))
$db_values[] = "$value";
else
$db_values[] = "'$value'";
}
$sql = "INSERT INTO `events_clients`";
$sql .= " (" . implode(',', $db_keys) . ")";
$sql .= " VALUES (" . implode(',', $db_values) . ")";
$sqls[] = $sql;
if (mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
} else if ($event_type == 'file' && !empty($task['files'])) {
foreach($task['files'] as $file) {
$guid = $file['guid'];
$extension = $file['type'];
$filename = $file['name'];
$sql = "INSERT INTO `names_client_files` SET `name` = '{$filename}'";
$sqls[] = $sql;
if (mysql_query($sql)) {
$id_name = mysql_insert_id();
$sql = "UPDATE `clients_files` SET `name_id` = {$id_name} WHERE `event_id` = {$event_id}";
$sqls[] = $sql;
if ($query = mysql_query($sql)) {
if (mysql_affected_rows($query) == 0 && $guid && $extension && $filename) {
if ($client_id > 0) {
$sql = "INSERT INTO clients_files (guid, client_id, type, name, event_id, name_id)
VALUES ('{$guid}', '{$client_id}', '{$extension}', '{$filename}', '{$event_id}', {$id_name})";
} else if ($requisition_id > 0) {
$sql = "INSERT INTO clients_files (guid, req_id, type, name, event_id, name_id)
VALUES ('{$guid}', '{$requisition_id}', '{$extension}', '{$filename}', '{$event_id}', {$id_name})";
} else if ($object_id > 0) {
$sql = "INSERT INTO clients_files (guid, object_id, type, name, event_id, name_id)
VALUES ('{$guid}', '{$object_id}', '{$extension}', '{$filename}', '{$event_id}', {$id_name})";
}
$sqls[] = $sql;
if (!empty($sql)) {
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
}
} else {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
}
}
} else if($section == 'free'){
if(!empty($data['responsibles'])){
$userIds = $data['responsibles'];
foreach($userIds as $who_work_id){
$calendar_view = 0;
$user_client_events = [
'user_id' => $who_work_id,
'from_id' => $user_id,
'client_id' => ($client_id) ? $client_id : 0,
'req_id' => ($requisition_id) ? $requisition_id : 0,
'type' => $event_type,
'sum' => ($summ) ? $summ : null,
'address' => ($address) ? $address : null,
'document_id' => ($document_id) ? $document_id : null,
'name' => ($title) ? $title : null,
'comment' => $comment,
'schedule_date' => ($schedule_date) ? $schedule_date : null,
'schedule_date_to' => ($schedule_date_to) ? $schedule_date_to : null,
'calendar_view' => $calendar_view,
'tracking' => (isset($task['is_tracking']) ? intval($task['is_tracking']) : 0),
'create_date' => date('Y-m-d H:i:s'),
];
if ($event_id) {
$db_values = [];
foreach ($user_client_events as $key => $value) {
if (is_null($value) || ($value === 'NULL'))
$db_values[] = "`$key` = NULL";
else if (!$value)
$db_values[] = "`$key` = 0";
else if (is_int($value))
$db_values[] = "`$key` = $value";
else
$db_values[] = "`$key` = '$value'";
}
$sql = "UPDATE `user_client_events`";
$sql .= " SET " . implode(',', $db_values);
$sql .= " WHERE `id` = '$event_id' AND `type` = '$event_type'";
} else {
$db_keys = [];
$db_values = [];
foreach ($user_client_events as $key => $value) {
$db_keys[] = "`$key`";
if (is_null($value) || ($value === 'NULL'))
$db_values[] = "NULL";
else if (!$value)
$db_values[] = "0";
else if (is_int($value))
$db_values[] = "$value";
else
$db_values[] = "'$value'";
}
$sql = "INSERT INTO `user_client_events`";
$sql .= " (" . implode(',', $db_keys) . ")";
$sql .= " VALUES (" . implode(',', $db_values) . ")";
}
$sqls[] = $db_values;
$sqls[] = $sql;
if (mysql_query($sql)) {
/*if (!$event_id)
$event_id = mysql_insert_id();*/
if ($event_type == 'deal' && isset($task['schedule_date'])) {
$date = \DateTime::createFromFormat('Y-m-d H:i', $task['schedule_date']);
$dop_text = "Запланирована сделка на " . date("Y-m-d H:i:s", $date->getTimestamp());
if (!is_null($document)) {
$dop_text .= ", сформирован документ: " . '
' . $document['doc_name'] . '
.';
} else {
$dop_text .= ".";
}
$dop_text .= "
От ";
$events_clients = [
'user_id' => $who_work_id,
'from_id' => $user_id,
'client_id' => $client_id || 'NULL',
'req_id' => $requisition_id || 'NULL',
'event' => 'add_deal',
'dop_text' => "'$dop_text'",
'read' => '1',
];
$db_keys = [];
$db_values = [];
foreach ($events_clients as $key => $value) {
$db_keys[] = "`$key`";
if (is_null($value))
$db_values[] = "NULL";
else if (!$value || $value === 0)
$db_values[] = "0";
else if (is_int($value))
$db_values[] = "$value";
else
$db_values[] = "'$value'";
}
$sql = "INSERT INTO `events_clients`";
$sql .= " (" . implode(',', $db_keys) . ")";
$sql .= " VALUES (" . implode(',', $db_values) . ")";
$sqls[] = $sql;
if (mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
}
}
}
}
}
if (!$error) {
$tasks = [];
$history = [];
if ($section == 'objects') {
// Offset-free: для листинга прокидываем флаг is_external, чтобы getTasks читал external_listing_events.
$tasks = self::getTasks($app, ['object_id' => $object_id, 'is_external' => $is_listing_object], null, true);
$history = ClientsController::getHistory($app, ['object_id' => $object_id], null, true);
} else if ($section == 'clients') {
$tasks = self::getTasks($app, ['client_id' => $client_id], null, true);
$history = ClientsController::getHistory($app, ['client_id' => $client_id], null, true);
} else if ($section == 'requisitions') {
$tasks = self::getTasks($app, ['requisition_id' => $requisition_id], null, true);
$history = ClientsController::getHistory($app, ['requisition_id' => $requisition_id], null, true);
}
foreach ($tasks as $key => $task) {
// Сверяем по реальному id и одинаковой природе события (листинг vs свой объект) — id коллизит между пространствами.
$same_kind = ((bool)$is_listing_object === !empty($task['is_external_listing_event']));
if ($same_kind && $task['id'] == $event_id)
$tasks[$key]['is_new'] = true;
else
$tasks[$key]['is_new'] = false;
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => $user_id,
'event_id' => $event_id,
// Признак события листинга — наружу явным флагом (mJW echo'ит его обратно в правке/удалении/завершении).
'is_external_listing_event' => $is_listing_object,
'event_type' => $event_type,
'section' => $section,
//'sqls' => $sqls,
'tasks' => (!empty($tasks)) ? $tasks : null,
'history' => (!empty($history)) ? $history : null,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
//'sqls' => $sqls,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function addSubComment($app, $get = null, $post = null) {
$error = false;
$errors = [];
if ($user_id = intval($_SESSION['id'])) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$body = $app->request->getBody();
$data = json_decode(stripcslashes($body), true);
$section = null;
if (isset($data['section']))
$section = trim($data['section']);
$event_id = null;
if (isset($data['event_id']))
$event_id = intval($data['event_id']);
$object_id = null;
if (isset($data['object_id']))
$object_id = intval($data['object_id']);
$client_id = null;
if (isset($data['client_id']))
$client_id = intval($data['client_id']);
$requisition_id = null;
if (isset($data['requisition_id']))
$requisition_id = intval($data['requisition_id']);
$sub_comment = null;
if (isset($data['comment']))
$sub_comment = trim($data['comment']);
$employee_id = null;
if (isset($data['employee_id']))
$employee_id = intval($data['employee_id']);
$sub_id = null;
if (isset($data['sub_id']))
$sub_id = intval($data['sub_id']);
// Offset-free: суб-комменты листинга различаем по явным флагам из запроса (echo'ит mJW), не по диапазону id.
$is_listing_event = self::_request_flag($data, 'is_external_listing_event');
$is_listing_object = self::_request_flag($data, 'is_external');
require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/helpers/external_listing_events.php';
if (!is_null($section) && !is_null($event_id) && !is_null($sub_comment)) {
if ($section == "objects") {
if ($is_listing_event || $is_listing_object) {
// Найденный листинг парсера: суб-комменты под section_id = 4, ключ — реальный el event id (без смещения;
// section_id = 1 коллидировал бы по event_id с суб-комментами задач своих объектов из user_object_events).
$real_event_id = (int)$event_id;
$real_listing_id = (int)$object_id;
// Изоляция компаний: суб-коммент можно писать только к событию листинга своего агентства
// (листинг общий → иначе запись коммента к чужой задаче по угадываемому event_id). Зеркало desktop addEventSubComment.
if (!\external_listing_event_in_scope($real_event_id, $user_id)) {
$error = true;
$errors[] = 'Нет доступа к событию листинга';
} else if (!empty($employee_id)) {
if ($sub_id > 0) {
$sql = "UPDATE user_sub_comments SET sub_comment='{$sub_comment}', user_for='{$employee_id}' WHERE id={$sub_id}";
} else {
$sql = "INSERT INTO `user_sub_comments` (`event_id`, `req_id`, `section_id`, `sub_comment`, `created_by`, `user_for`) VALUES ('$real_event_id', '$real_listing_id', 4, '$sub_comment', '$user_id', '$employee_id')";
}
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
} else {
$sql = "DELETE FROM `user_sub_comments` WHERE `event_id` = '$real_event_id' AND `section_id` = 4 AND `created_by` = '$user_id'";
$sql2 = "INSERT INTO `user_sub_comments` (`event_id`, `req_id`, `section_id`, `sub_comment`, `created_by`) VALUES ('$real_event_id', '$real_listing_id', 4, '$sub_comment', '$user_id')";
if (!mysql_query($sql) || !mysql_query($sql2)) {
$error = true;
$errors[] = mysql_error();
}
}
} else if (!empty($employee_id)) {
if ($sub_id > 0) {
$sql = "UPDATE user_sub_comments SET sub_comment='{$sub_comment}', user_for='{$employee_id}' WHERE id={$sub_id}";
} else {
$sql = "INSERT INTO `user_sub_comments` (`event_id`, `req_id`, `section_id`, `sub_comment`, `created_by`, `user_for`) VALUES ('$event_id', '$object_id', 1, '$sub_comment', '$user_id', '$employee_id')";
}
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
} else {
$sql = "DELETE FROM `user_sub_comments` WHERE `event_id` = '$event_id' AND `section_id` = 1 AND `created_by` = '$user_id'";
$sql2 = "INSERT INTO `user_sub_comments` (`event_id`, `req_id`, `section_id`, `sub_comment`, `created_by`) VALUES ('$event_id', '$object_id', 1, '$sub_comment', '$user_id')";
if (!mysql_query($sql) || !mysql_query($sql2)) {
$error = true;
$errors[] = mysql_error();
}
}
} else if ($section == "clients") {
$sql = "DELETE FROM `user_sub_comments` WHERE `event_id` = '$event_id' AND `section_id` = 2 AND `created_by` = '$user_id'";
$sql2 = "INSERT INTO `user_sub_comments` (`event_id`, `req_id`, `section_id`, `sub_comment`, `created_by`) VALUES ('$event_id', '$client_id', 2, '$sub_comment', '$user_id')";
if (!mysql_query($sql) || !mysql_query($sql2)) {
$error = true;
$errors[] = mysql_error();
}
} else if ($section == "requisitions") {
$sql = "DELETE FROM `user_sub_comments` WHERE `event_id` = '$event_id' AND `section_id` = 3 AND `created_by` = '$user_id'";
$sql2 = "INSERT INTO `user_sub_comments` (`event_id`, `req_id`, `section_id`, `sub_comment`, `created_by`) VALUES ('$event_id', '$requisition_id', 3, '$sub_comment', '$user_id')";
if (!mysql_query($sql) || !mysql_query($sql2)) {
$error = true;
$errors[] = mysql_error();
}
}
if ($requisition_id > 0) {
$sql = "INSERT INTO `events_clients` (`user_id`, `req_id`, `from_id`, `event`, `read`, `dop_text`) VALUES ('$user_id', '$requisition_id', '0', 'sub_comment', '1', '{$sub_comment}')";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
}
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'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 deleteSubComment($app, $get = null, $post = null) {
$error = false;
$errors = [];
if ($user_id = intval($_SESSION['id'])) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$section = null;
if (isset($get['section']))
$section = trim($get['section']);
$event_id = null;
if (isset($get['event_id']))
$event_id = intval($get['event_id']);
$sub_id = null;
if (isset($get['sub_id']))
$sub_id = intval($get['sub_id']);
// Offset-free: суб-коммент листинга различаем по явному флагу is_external_listing_event из запроса (echo'ит mJW).
$is_listing_event = self::_request_flag($get, 'is_external_listing_event');
require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/helpers/external_listing_events.php';
if (!is_null($section) && !is_null($event_id)) {
if ($section == "objects") {
if ($sub_id > 0) {
// Удаление по id корректно для любой таблицы (id суб-коммента — без смещения).
$sql = "DELETE FROM `user_sub_comments` WHERE id='$sub_id'";
} else if ($is_listing_event) {
// Найденный листинг парсера: суб-комменты под section_id = 4, ключ — реальный el event id (без смещения).
$real_event_id = (int)$event_id;
$sql = "DELETE FROM `user_sub_comments` WHERE `event_id` = '$real_event_id' AND `section_id` = 4 AND `created_by` ='$user_id'";
} else {
$sql = "DELETE FROM `user_sub_comments` WHERE `event_id` = '$event_id' AND `section_id` = 1 AND `created_by` ='$user_id'";
}
} else if ($section == "clients") {
$sql = "DELETE FROM `user_sub_comments` WHERE `event_id` = '$event_id' AND `section_id` = 2 AND `created_by` = '$user_id'";
} else if ($section == "requisitions") {
$sql = "DELETE FROM `user_sub_comments` WHERE `event_id` = '$event_id' AND `section_id` = 3 AND `created_by` = '$user_id'";
}
if (!empty($sql)) {
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
} else {
$error = true;
}
}
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
], 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 getStageDetails($app, $get = null, $post = null, $need_return = false) {
$error = false;
$errors = [];
if ($user_id = $_SESSION['id']) {
$protocol = (self::is_ssl()) ? 'https://' : 'http://';
$host = $protocol . $_SERVER['SERVER_NAME'];
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$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']);
$step_id = null;
if (isset($get['step_id']))
$step_id = intval($get['step_id']);
if (!is_null($step_id) && (!is_null($client_id) || !is_null($requisition_id))) {
$details = [];
if (!is_null($client_id)) {
$sql = "SELECT * FROM `clients_funnel_step` WHERE client_id = {$client_id}";
} elseif (!is_null($requisition_id)) {
$sql = "SELECT * FROM `clients_funnel_step` WHERE req_id = {$requisition_id}";
}
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
$row = mysql_fetch_assoc($query);
if (!empty($row['values'])) {
try {
$array = json_decode($row['values'],true);
$res = [];
foreach ($array as $key => $value) {
$res[$key] = htmlspecialchars_decode($value);
}
if (isset($res[$step_id])) {
$data = [];
$values = json_decode($res[$step_id], true);
foreach ($values as $key => $value) {
$field_name = self::translit($value['name'], '_');
$data[$field_name] = $value;
}
$details = $data;
}
} catch (\Exception $e) {
$error = true;
$errors[] = $e->getMessage();
}
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
if ($need_return) {
return $details;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'details' => $details,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getStagesList($app, $get = null, $post = null, $has_return = false) {
$error = false;
$errors = [];
if ($user_id = $_SESSION['id']) {
$protocol = (self::is_ssl()) ? 'https://' : 'http://';
$host = $protocol . $_SERVER['SERVER_NAME'];
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
// Этапы по-умолчанию
$stages = [
[
'id' => 1,
'name' => 'Новый',
], [
'id' => 2,
'name' => 'В работе',
], [
'id' => 3,
'name' => 'Презентация',
], [
'id' => 4,
'name' => 'Показ',
], [
'id' => 5,
'name' => 'Бронь',
], [
'id' => 6,
'name' => 'Подаем на ипотеку',
], [
'id' => 7,
'name' => 'Сделка',
], [
'id' => 8,
'name' => 'Закрыт',
],
];
if (isset($get['funnel_id'])) {
$funnel_id = (int)$get['funnel_id'];
if ($funnel_id) {
$stages = [];
$sql = "SELECT `id`, `name` FROM `funnel_steps`
WHERE `funnel_id` = '$funnel_id' AND `deleted` = 0
ORDER BY `order_number`, `branch`";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query)) {
while ($step = mysql_fetch_assoc($query)) {
$sql_file = "SELECT * FROM funnel_files WHERE etap_id = '".$step['id']."' AND funnel_id = ".$step['funnel_id'];
$q_file = mysql_query($sql_file);
$files = [];
while($file_r = mysql_fetch_assoc($q_file)) {
$path = "https://uf.joywork.ru/upload/funnels/".$step['funnel_id']."/".$file_r['guid'].".".$file_r['type'];
$files[] = array('guid' => $file_r['guid'],'isUpload' => true, 'uploads' => false, 'name' => $file_r['name'], 'path' => $path);
}
$stages[] = [
'id' => intval($step['id']),
'name' => trim($step['name']),
//'funnel_id' => intval($step['funnel_id']),
'funnel_id' => $funnel_id,
'stage' => trim($step['stage']),
'branch' => intval($step['branch']),
'max_days' => intval($step['days_step']),
'color' => trim($step['color_step']),
'next_step_id' => json_decode($step['next_step'], true),
'next_stages' => json_decode($step['arr_next_steps'], true),
'tasks_list' => json_decode($step['tasks_list'], true),
'doers' => json_decode($step['doers'], true),
'files' => $files,
'order' => intval($step['order_number']),
'is_main' => intval($step['main']),
'is_deleted' => intval($step['deleted']),
];
}
}
} else {
$errors[] = mysql_error();
$error = true;
}
}
}
if (!$error) {
if ($has_return) {
return $stages;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'count' => count($stages),
'list' => $stages
], 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)$user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getPrevStage($app, $get = null, $post = null, $need_return = false) {
$error = false;
$errors = [];
$task = [];
if ($user_id = $_SESSION['id']) {
$client_id = 0;
if (isset($get['client_id'])) {
$client_id = intval($get['client_id']);
}
$requisition_id = 0;
if (isset($get['requisition_id'])) {
$requisition_id = intval($get['requisition_id']);
}
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
if ($client_id > 0) {
$section = 'clients';
$sql = "SELECT cfs.*, fs.name FROM `clients_funnel_step` as `cfs`
LEFT JOIN `funnel_steps` as `fs` on cfs.step_id = fs.id
WHERE cfs.client_id = {$client_id}";
} else if($requisition_id > 0) {
$section = 'requisitions';
$sql = "SELECT cfs.*, fs.name FROM `clients_funnel_step` as `cfs`
LEFT JOIN `funnel_steps` as `fs` on cfs.step_id = fs.id
WHERE cfs.req_id = {$requisition_id}";
}
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
$row = mysql_fetch_assoc($query);
$task = $row;
}
} else {
$error = true;
$errors[] = mysql_error();
}
if (empty($errors)) {
if ($need_return) {
return $task;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => $_SESSION['id'],
'task' => $task,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getStages($app, $get = null, $post = null, $has_return = false) {
$error = false;
$errors = [];
$funnel_id = null;
if (isset($get['funnel_id']))
$funnel_id = intval($get['funnel_id']);
$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']);
$object_id = null;
if (isset($get['object_id']))
$object_id = intval($get['object_id']);
$mode = 'all';
if (isset($get['mode'])) {
if (in_array(trim($get['mode']), ['all', 'only_current', 'only_next']))
$mode = trim($get['mode']);
}
if (($user_id = $_SESSION['id']) && !is_null($funnel_id) && ($client_id || $requisition_id || $object_id)) {
$protocol = (self::is_ssl()) ? 'https://' : 'http://';
$host = $protocol . $_SERVER['SERVER_NAME'];
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$stages = [];
$sql = "SELECT * FROM `clients_funnel_step` WHERE client_id = '$client_id'";
if ($requisition_id > 0)
$sql = "SELECT * FROM `clients_funnel_step` WHERE req_id = '$requisition_id'";
if ($query = mysql_query($sql)) {
$next_id = 0;
$change_step = 0;
$steps_count = 0;
$step_date_update = null;
$steps = [];
$next_steps = [];
if ($funnel_id == 0) { // Воронка по-умолчанию
$stage_id = 1;
$sql = "SELECT * FROM `clients`
WHERE `funnel_id` = '$funnel_id' AND `id` = '$client_id'";
if ($requisition_id > 0)
$sql = "SELECT * FROM `requisitions`
WHERE `funnel_id` = '$funnel_id' AND `id` = '$requisition_id'";
if ($query = mysql_query($sql)) {
$client = mysql_fetch_assoc($query);
$stage_id = (int)$client['stage'];
}
$data = [
1 => [
'id' => 1,
'name' => 'Новый',
'is_next' => ($stage_id == 1),
'is_main' => true,
'prev_step_id' => null,
'prev_step_name' => null,
'branch' => 0
], 2 => [
'id' => 2,
'name' => 'В работе',
'is_next' => ($stage_id == 2),
'is_main' => false,
'prev_step_id' => 1,
'prev_step_name' => 'Новый',
'branch' => 0
], 3 => [
'id' => 3,
'name' => 'Презентация',
'is_next' => ($stage_id == 3),
'is_main' => false,
'prev_step_id' => 2,
'prev_step_name' => 'В работе',
'branch' => 0
], 4 => [
'id' => 4,
'name' => 'Показ',
'is_next' => ($stage_id == 4),
'is_main' => false,
'prev_step_id' => 3,
'prev_step_name' => 'Презентация',
'branch' => 0
], 5 => [
'id' => 5,
'name' => 'Бронь',
'is_next' => ($stage_id == 5),
'is_main' => false,
'prev_step_id' => 4,
'prev_step_name' => 'Показ',
'branch' => 0
], 6 => [
'id' => 6,
'name' => 'Подаем на ипотеку',
'is_next' => ($stage_id == 6),
'is_main' => false,
'prev_step_id' => 5,
'prev_step_name' => 'Бронь',
'branch' => 0
], 7 => [
'id' => 7,
'name' => 'Сделка',
'is_next' => ($stage_id == 7),
'is_main' => false,
'prev_step_id' => 6,
'prev_step_name' => 'Подаем на ипотеку',
'branch' => 0
], 8 => [
'id' => 8,
'name' => 'Закрыт',
'is_next' => ($stage_id == 8),
'is_main' => false,
'prev_step_id' => 7,
'prev_step_name' => 'Сделка',
'branch' => 0
],
];
$prev_step_id = null;
/*foreach ($data as $step) {
$step_id = $step['id'];
$step['prev_steps'] = [];
if (isset($data[$prev_step_id])) {
foreach ($data as $row) {
if ($row['id'] < $prev_step_id) {
$step['prev_steps'][] = $row;
}
}
}
$step['prev_step_id'] = $prev_step_id;
if (
($mode == 'only_current' && boolval($step['isActive'])) ||
($mode == 'only_next' && (boolval($step['is_next']) || boolval($step['main'])))
) {
$stages = $step;
break;
} else if ($mode == 'all' && boolval($step['isActive'])) {
$stages[$step_id] = $step;
}
}*/
$prev_step_id = null;
$prev_steps = [];
foreach ($data as $step) {
$step_id = $step['id'];
if ($step_id <= $stage_id) {
$prev_steps[] = $step;
if ($step_id < $stage_id)
$prev_step_id = $step_id;
}
}
$stages = $data[$stage_id];
$stages['prev_steps'] = $prev_steps;
$stages['prev_step_id'] = $prev_step_id;
} else if ($funnel_id > 0) { // Кастомные воронки
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'];
}
$sql = "SELECT * FROM `funnel_steps`
WHERE `funnel_id` = '$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;
$steps[$step['id']]['prev_step_id'] = (int)$change_step['prev_id'];
}
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;
}
}
$prev_step_id = null;
foreach ($steps as $step_id => $step) {
/*error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('display_errors', 1);*/
$interval = 0;
if ($step_date_update)
$interval = date_diff(new \DateTime(), new \DateTime($step_date_update))->days;
$next_steps_list = [];
if (isset($step['arr_next_steps'])) {
$next_steps = json_decode(htmlspecialchars_decode($step['arr_next_steps']), true);
foreach ($next_steps as $key => $next) {
$next_steps_list[] = [
'id' => $next['id']['id'],
'name' => trim($next['id']['name']),
'linked' => trim($next['name']),
];
}
}
$details = CommonController::getStageDetails($app, [
'client_id' => $client_id,
'step_id' => $step_id,
], null, true);
$fields_list = [];
if (isset($step['pole_end_list'])) {
$fields = json_decode(htmlspecialchars_decode($step['pole_end_list']), true);
foreach ($fields as $field) {
$field_type = 'text';
switch (trim($field['type'])) {
case 'Строка':
$field_type = 'text';
break;
case 'Текст':
$field_type = 'textarea';
break;
case 'Дата':
$field_type = 'datetime';
break;
case 'Файл':
$field_type = 'file';
break;
case 'Ветвление этапов':
$field_type = 'select';
break;
case 'Выпадающий список':
$field_type = 'select';
break;
case 'Задача на выбор':
$field_type = 'checkbox';
break;
case 'Поле с галочкой':
$field_type = 'checkbox';
break;
case 'Задаток':
$field_type = 'deposit';
break;
case 'Ожидаемая комиссия':
$field_type = 'commission';
break;
case 'Расходы':{
$field_type = 'expenses';
}
break;
}
$field_name = self::translit(trim($field['name']), '_');
$value = null;
if($field_type == 'expenses'){
$value = array('summa'=>null, 'comment'=>null);
}
if (isset($details[$field_name])) {
if ($details[$field_name]['type'] == $field_type) {
if (isset($details[$field_name]['value'])) {
$field_name = self::translit($details[$field_name]['name'], '_');
$field_type = trim($details[$field_name]['type']);
if ($field_type == 'file') { // Список прикрепленных к полю файлов
$file = $details[$field_name]['value'];
$name_doc = $_SERVER['DOCUMENT_ROOT'].'/upload/clients/'.$client_id.'/'.$file['guid'].'.'.$file['typeFile'];
if ($requisition_id > 0) {
$name_doc = 'https://uf.joywork.ru/upload/reqs/' . $requisition_id . '/' . $file['guid'] . '.' . $file['typeFile'];
$value[] = [
'guid' => trim($file['guid']),
'name' => trim($file['name']),
'type' => trim($file['typeFile']),
'is_upload' => boolval($file['isUpload']),
'path' => $name_doc,
];
} else {
if ($client_id > 0) {
$name_doc = 'https://uf.joywork.ru/upload/clients/' . $client_id . '/' . $file['guid'] . '.' . $file['typeFile'];
$value[] = [
'guid' => trim($file['guid']),
'name' => trim($file['name']),
'type' => trim($file['typeFile']),
'is_upload' => boolval($file['isUpload']),
'path' => $name_doc,
];
} else {
if (!file_exists($name_doc))
$file_path = false;
$file_path = '';
if ($client_id > 0)
$file_path = '/upload/clients/' . $client_id . '/' . $file['guid'] . '.' . $file['typeFile'];
if ($requisition_id > 0)
$file_path = '/upload/reqs/' . $requisition_id . '/' . $file['guid'] . '.' . $file['typeFile'];
if (!empty($file_path) && !empty($file['name'])) {
$value[] = [
'guid' => trim($file['guid']),
'name' => trim($file['name']),
'type' => trim($file['typeFile']),
'is_upload' => boolval($file['isUpload']),
'path' => ($file_path) ? $host . $file_path : null,
];
}
}
}
} else {
$value = $details[$field_name]['value'];
}
}
}
}
$selected_value = '';
$data = [
'name' => $field_name,
'label' => trim($field['name']),
'type' => $field_type,
'is_required' => boolval($field['binding']),
'value' => $value,
'view_next' => $field['view_next']
];
if ($field_type == 'select' && isset($field['dopSettings']['select']['options'])) {
$options = (array)$field['dopSettings']['select']['options'];
$keys = array_keys($options);
$selected_value = null;
$data['select'] = array_combine(
$keys,
array_map(function($v, $key) use ($value) {
$selected = false;
if ($v == $value["name"])
$selected = true;
return [
'id' => $key,
'name' => $v,
'selected' => $selected,
];
}, $options, $keys)
);
}
if ($field_type == 'radio' && isset($field['dopSettings']['radio'])) // @todo: не нашел вхождений
$data['radio'] = $field['dopSettings']['radio'];
$fields_list[] = $data;
}
}
$linking_steps = array(); //Сопряженные кастомные поля
$list_linking = array();
$user = new \User;
$user->get($user_id);
$agency_id = $user->agencyId;
//$linking_steps[] = $agency_id;
$linkingClass = new \LinkingClass();
$fields = $linkingClass->getFixFields();
$sql_check = "SELECT * FROM linking_steps_client_req WHERE step_id = {$step_id}";
if($requisition_id > 0){
$sql_req = "SELECT * FROM requisitions WHERE id = {$reqId}";
$req = mysql_fetch_assoc(mysql_query($sql_req));
$sql_check .= " AND is_req > 0";
$reqClass = new \Requisitions(null, true);
$fields_req = $reqClass->get_req_fields($agency_id, $requisition_id);
//($fields_req);
$linking_steps['values'] = $fields_req['values'];
}
if($clientId > 0) {
$sql_check .= " AND is_client > 0";
}
$q_check = mysql_query($sql_check);
while($r_check = mysql_fetch_assoc($q_check)){
//var_dump($r_check);
if(is_numeric($r_check['field_id'])){
if($requisition_id > 0){
foreach($fields_req['fields'] as $key => $fr){
$req_types = array();
// echo $key."\n";
//var_dump($fr);
if($fr['id'] == $r_check['field_id']){
//var_dump($fr['req_type']);
if($fr['req_type'] === 0 || empty($field['req_type'])){
//var_dump($fr['req_type']);
$fr['is_required'] = $r_check['is_required'];
$fr['view_next'] = json_decode($r_check['view_next'], true);
$r_check = $fr;
$linking_steps['fields'][] = $r_check;
} else if(!empty($fr['req_type'])){
$req_types = json_decode($fr['req_type'], true);
// var_dump($req_types);
if(in_array((int)$req['type_id'], $req_types)){
$fr['is_required'] = $r_check['is_required'];
$fr['view_next'] = json_decode($r_check['view_next'], true);
$r_check = $fr;
$linking_steps['fields'][] = $r_check;
}
}
// var_dump($fr);
break;
}
}
}
} else {
foreach($fields as $field){
$req_types = array();
if($requisition_id > 0){
if($field['is_req'] > 0 && $r_check['field_id'] == $field['id']){
if(isset($field['table'])){
if(isset($req[$field['ident']]) && !empty($req[$field['ident']])){
$sql_dop_table = "SELECT {$field['id']} FROM `{$field['table']}` WHERE `{$field['ident']}` = {$req[$field['ident']]}";
//echo $sql_dop_table;
$q_dop_table = mysql_query($sql_dop_table);
$r_dop_table = mysql_fetch_assoc($q_dop_table);
if($r_dop_table){
$linking_steps['values']['model_'.$field['id']] = $r_dop_table[$field['id']];
}
}
} else {
if(isset($req[$field['id']])){
$linking_steps['values']['model_'.$field['id']] = $req[$field['id']];
} else if($field['id'] == 'client_contract'){
$result = null;
$sql_d = "SELECT * FROM persons_contract WHERE req_id = {$reqId} ORDER by id DESC limit 1";
$q_d = mysql_query($sql_d);
if(mysql_num_rows($q_d) > 0){
$r_d = mysql_fetch_assoc($q_d);
$sql_cl = "SELECT fio, phone, email FROM clients WHERE id = {$r_d['client_id']}";
$q_cl = mysql_query($sql_cl);
$r_cl = mysql_fetch_assoc($q_cl);
// Маскируем телефон и fio клиента, если у текущего пользователя
// включено `hide_client_contacts`. Helper сам проверяет право.
$cl_phone_masked = mask_phone_value_if_needed($r_cl['phone']);
$cl_fio_masked = mask_fio_if_contains_phone($r_cl['fio']);
$client_name = $cl_phone_masked.' '.$cl_fio_masked;
$result = array('id' => $r_d['client_id'], 'name' => $client_name, 'color'=>'#000');
}
$linking_steps['values']['model_'.$field['id']] = $result;
}
}
if($field['req_type'] === 0 || empty($field['req_type'])){
$field['is_required'] = $r_check['is_required'];
$field['view_next'] = json_decode($r_check['view_next'], true);
$linking_steps['fields'][] = $field;
} else if(!empty($field['req_type'])){
$req_types = json_decode($field['req_type'], true);
if(in_array((int)$req['type_id'], $req_types)){
$field['is_required'] = $r_check['is_required'];
$field['view_next'] = json_decode($r_check['view_next'], true);
$linking_steps['fields'][] = $field;
}
}
break;
}
}
}
}
}
foreach ($linking_steps['fields'] as $field) {
$field_id = (int)$field['id'];
$values = null;
if ((bool)$field['is_podgroup'])
$values = (isset($linking_steps['values']['modelp_'.$field_id])) ? $linking_steps['values']['modelp_'.$field_id] : null;
else
$values = (isset($linking_steps['values']['model_'.$field_id])) ? $linking_steps['values']['model_'.$field_id] : null;
$value = json_decode($values, true);
$sub_groups = [];
if (!empty($field['podgroups'])) {
foreach ($field['podgroups'] as $key => $group) {
$sub_group['id'] = $group['id'];
$sub_group['name'] = ($group['title']) ? trim($group['title']) : null;
$sub_group['value'] = ($group['id']) ? (int)$group['id'] : null;
$sub_group['type'] = ($group['type']) ? (int)$group['type'] : 0;
if (!empty($field['podgroups_select'])) {
foreach ($field['podgroups_select'] as $select) {
if ($group['id'] == $select['id']) {
$sub_group['is_active'] = true;
} else {
$sub_group['is_active'] = false;
}
}
} else {
$sub_group['is_active'] = false;
}
if (isset($group['params'])) {
if (is_array($group['params']['items'])) {
$sub_group['params']['items'] = [];
foreach ($group['params']['items'] as $option) {
$sub_group['options'][] = [
'name' => ($option['name']) ? trim($option['name']) : null,
'value' => ($option['value']) ? (int)$option['value'] : null,
'mode' => ($option['mode']) ? (int)$option['mode'] : null,
];
}
}
}
$sub_group['is_required'] = boolval($group['is_required']);
$sub_group['created_by'] = ($group['created_by']) ? (int)$group['created_by'] : null;
$sub_group['updated_by'] = ($group['updated_by']) ? (int)$group['updated_by'] : null;
$sub_groups['modelp_' . $group['id']] = $sub_group;
}
}
// if (!$filtrable || ($filtrable === true && (bool)$field['is_filtrable'])) {
$list_linking['model_' . $field_id] = [
'id' => (int)$field_id,
'label' => $field['title'],
'type' => (int)$field['type'],
'is_for_clients' => (bool)$field['is_client'],
'is_for_requisitions' => (bool)$field['is_req'],
'is_sub_group' => (bool)$field['is_podgroup'],
'is_required' => (bool)$field['is_required'],
'is_filtrable' => (bool)$field['is_filtrable'],
'requisition_type' => ((bool)$field['is_req'] && isset($field['req_type'])) ? json_decode($field['req_type']) : null,
'value' => $value,
'params' => (!empty((bool)$field['is_podgroup'])) ? ['items' => $sub_groups] : $field['params'],
'created_at' => $field['created_at'],
'created_by' => ($field['created_by']) ? $field['created_by'] : null,
'updated_at' => $field['updated_at'],
'updated_by' => ($field['updated_by']) ? $field['updated_by'] : null,
'view_next' => ($field['view_next']) ? $field['view_next'] : null,
];
//}
}
$doers = [];
if (isset($step['pole_end_list'])) {
$employees = json_decode(htmlspecialchars_decode($step['doers']), true);
foreach ($employees as $employee) {
$doers[] = intval($employee['id']);
}
$doers = array_unique($doers);
}
$files_list = [];
$sql_file = "SELECT * FROM funnel_files WHERE etap_id = '".$step['id']."' AND funnel_id = ".$step['funnel_id'];
if ($q_file = mysql_query($sql_file)) {
while($file_r = mysql_fetch_assoc($q_file)) {
$path = "https://uf.joywork.ru/upload/funnels/".$step['funnel_id']."/".$file_r['guid'].".".$file_r['type'];
$files_list[] = [
'guid' => $file_r['guid'],
'is_upload' => true,
'uploads' => false,
'file_name' => $file_r['name'],
'file_type' => $file_r['type'],
'path' => $path
];
}
} else {
$error = true;
$errors[] = mysql_error();
}
$prev_steps = [];
$sql = "SELECT * FROM funnel_steps
WHERE funnel_id = ".$funnel_id." AND
id != {$step['id']} AND
branch <= {$step['branch']} AND
deleted = 0
ORDER BY order_number DESC,
branch DESC";
if ($query = mysql_query($sql)) {
while ($row = mysql_fetch_assoc($query)) {
$prev_steps[] = [
'id' => (int)$row['id'],
'name' => trim($row['name']),
'branch' => (int)$row['branch'],
];
}
}
if (
$mode == 'all' ||
($mode == 'only_current' && boolval($step['isActive'])) ||
($mode == 'only_next' && (boolval($step['isNext']) || boolval($step['main'])))
) {
$data = [
'id' => intval($step['id']),
'name' => trim($step['name']), // Название этапа
'funnel_id' => intval($step['funnel_id']), // ИД воронки
'is_close_after' => boolval(($step['stage'] === 'В работе') ? 0 : 1), // При переходе на этап сменить статус
'is_active' => boolval($step['isActive']),
'is_next' => boolval($step['isNext'] == 1),
'is_parallel' => boolval($step['start_parallel'] == 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']), // Дней на этап
'branch' => intval($step['branch']),
'create_deal' => intval($step['create_deal']),
'prev_steps' => $prev_steps, // Предыдущие этапы, доступные для выбора
'prev_step_id' => $prev_step_id, // Предыдущий этап
'next_steps_list' => $next_steps_list, // Следующий этап после закрытия
'next_steps_ids' => array_map('intval', json_decode(html_entity_decode($step['next_step']))),
'fields_list' => $fields_list, // Список полей для заполнения при завершении этапа
'files_list' => $files_list, // Файлы для скачивания
'doers' => $doers, // Ответственные
'linking_steps' => $list_linking, //Сопряженные кастомные поля
];
// Дополнительные действия при закрытии этапа
/*if ($mode == 'only_next') {
$data['after_close'] = [
'use_in_advert_off' => false,
'autosearch_off' => false,
'add_activity' => false,
'add_contract' => false,
];
}*/
if (
($mode == 'only_current' && boolval($step['isActive'])) ||
($mode == 'only_next' && (boolval($step['isNext']) || boolval($step['main'])))
) {
// Доп. действия при закрытии этапа
if (!empty($step['pole_dop'])) {
$pole_dop = array_map('intval', json_decode(html_entity_decode($step['pole_dop']), true));
$data['after_close'] = [
'use_in_advert_turn_off' => (bool)$pole_dop['advert_close'],
'autosearch_turn_off' => (bool)$pole_dop['avtopoisk_close'],
'add_activity' => (bool)$pole_dop['add_activity_close_step'],
'add_contract' => (bool)$pole_dop['add_contract_close_step'],
];
} else {
$data['after_close'] = null;
}
$stages = $data;
} else {
$stages[$step_id] = $data;
}
}
$prev_stage = $this->getPrevStage($app, ['client_id' => $client_id, 'requisition_id' => $requisition_id], null, true);
if (isset($prev_stage['id']))
$prev_step_id = (int)$prev_stage['step_id'];
else
$prev_step_id = $step_id;
}
/*if ($client['deleted'] == 1 && $client['funnel_id'] > 0) {
$stage_name .= ' (закрыт)';
}*/
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
if (!$error && $has_return) {
return $stages;
} 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,
'funnel_id' => $funnel_id,
'client_id' => $client_id,
'requisition_id' => $requisition_id,
'stage_id' => $stage_id,
'stages' => $stages,
], 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 setCloseStage($app, $get = null, $post = null) {
require_once($_SERVER['DOCUMENT_ROOT']."/ajax/vue_php_function.php");
date_default_timezone_set('Europe/Moscow');
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode(stripcslashes($body), true);
$section = null;
if (isset($data['section']))
$section = trim($data['section']);
$funnel_id = null;
if (isset($data['funnel_id']))
$funnel_id = intval($data['funnel_id']);
$client_id = null;
if (isset($data['client_id']))
$client_id = intval($data['client_id']);
$requisition_id = null;
if (isset($data['requisition_id']))
$requisition_id = intval($data['requisition_id']);
$stage = null;
if (isset($data['stage']))
$stage = (array)$data['stage'];
if (($user_id = $_SESSION['id']) && !is_null($section) && !is_null($funnel_id) && ($client_id || $requisition_id)) {
$temp_id = 0;
$step_id = 0;
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$db_sphinx = $app->container->get('sphinx2');
/*error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);*/
if ($funnel_id == 0) { // Воронка по-умолчанию
$date = time();
$create_at = date('Y-m-d H:i:s');
$step_id = intval($stage['id']);
$step_name = trim($stage['name']);
$next_step = 0;
if ($step_id > 0 && $step_id < 8) {
$next_step = $step_id + 1;
}
$def_stages = ['', 'Новый', 'В работе', 'Презентация', 'Показ', 'Бронь', 'Подаем на ипотеку', 'Сделка', 'Закрыт'];
$sql = "SELECT `stage`, `deleted` FROM clients WHERE id = {$client_id}";
if ($requisition_id > 0)
$sql = "SELECT `stage`, `deleted` FROM requisitions WHERE id = {$requisition_id}";
if ($query = mysql_query($sql)) {
$row = mysql_fetch_assoc($query);
if ($row['deleted'] > 0)
$row['stage'] = 8;
$prev_stage = $def_stages[intval($row['stage'])];
$text = 'c «'.$prev_stage.'» на «'.$def_stages[intval($step_id)].'»';
$sql = "UPDATE `clients` SET `stage` = '{$next_step}', `deleted` = 0 WHERE `id` = {$client_id}";
if ($requisition_id > 0)
$sql = "UPDATE `requisitions` SET `stage` = '{$next_step}', `deleted` = 0 WHERE `id` = {$requisition_id}";
if (mysql_query($sql)) {
$sql = "INSERT INTO `events_clients` (`user_id`, `client_id`, `from_id`, `event`, `read`, `dop_text`) VALUES (".$user_id.", {$client_id}, '0', 'stageedit', '1', '{$text}')";
$in_history = "INSERT INTO `steps_history`(`client_id`, `step_id`, `date`, `type`, `user_id`, `created_at`)
VALUES ({$client_id}, {$row['stage']}, {$date}, 1, {$user_id}, '{$create_at}')";
if($step_id > $row['stage']){
for($i=($row['stage']+1); $i<$step_id; $i++){
$in_history .= ", ({$client_id}, {$i}, {$date}, 1, {$user_id}, '{$create_at}')";
}
}
if ($requisition_id > 0){
$sql = "INSERT INTO `events_clients` (`user_id`, `req_id`, `from_id`, `event`, `read`, `dop_text`) VALUES (".$user_id.", {$requisition_id}, '0', 'stageedit', '1', '{$text}')";
$in_history = "INSERT INTO `steps_history`(`req_id`, `step_id`, `date`, `type`, `user_id`, `created_at`)
VALUES ({$requisition_id}, {$row['stage']}, {$date}, 1, {$user_id}, '{$create_at}')";
if($step_id > $row['stage']){
for($i=($row['stage']+1); $i<$step_id; $i++){
$in_history .= ", ({$requisition_id}, {$i}, {$date}, 1, {$user_id}, '{$create_at}')";
}
}
}
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
mysql_query($in_history);
if (isset($stage['turn'])) {
$set_turns = json_decode(html_entity_decode($stage['turn']), ENT_QUOTES);
$time = time();
foreach($set_turns as $key => $turn) {
$sql = "UPDATE `clients` SET `turntime` = ".$time.", `turn` = ".$turn." WHERE `id` = {$key}";
if ($requisition_id > 0)
$sql = "UPDATE `requisitions` SET `turntime` = ".$time.", `turn` = ".$turn." WHERE `id` = {$key}";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
} else {
$error = true;
$errors[] = mysql_error();
}
} else if ($funnel_id > 0) { // Кастомные воронки
if (boolval($stage['is_next']) || boolval($stage['is_main'])) {
$prev_id = 0;
$prev_next_id = 0;
$step_id = intval($stage['id']);
$step_name = trim($stage['name']);
$next_step_id = 0;
if (isset($stage['next_step_id']))
$next_step_id = intval($stage['next_step_id']);
$next_step_name = null;
if (isset($stage['next_step_name']))
$next_step_name = trim($stage['next_step_name']);
if ($step_id && intval($stage['funnel_id']) == $funnel_id) {
$fields = [];
$fields_list = [];
$events_client = [];
if (isset($stage['fields_list'])) {
$fields_list = $stage['fields_list'];
$events_client = $stage['fields_list'];
foreach ($fields_list as $field) {
$value = $field['value'];
if ($field['type'] == 'select' && !empty($field['select'])) {
$value = [
'name' => trim($field['value']),
'id' => [
'id' => $next_step_id,
'name' => $next_step_name,
],
];
}
$data = [
'name' => $field['label'],
'type' => $field['type'],
'value' => $value,
];
$fields[] = $data;
}
}
$sql = "SELECT `id`, `step_id`, `next_id`, `values` FROM `clients_funnel_step` WHERE client_id = ".$client_id;
if ($client_id <= 0 && $requisition_id > 0)
$sql = "SELECT `id`, `step_id`, `next_id`, `values` FROM `clients_funnel_step` WHERE req_id = ".$requisition_id;
if ($query = mysql_query($sql)) {
$next_id = 0;
if (isset($stage['next_step_id']))
$next_id = (int)$stage['next_step_id'];
$sql = '';
if (mysql_num_rows($query) > 0) {
$row = mysql_fetch_assoc($query);
$prev_id = (int)$row['step_id'];
$prev_next_id = (int)$row['next_id'];
$fields['prev_id'] = $prev_id;
$fields['prev_next_id'] = $prev_next_id;
$fields['next_step_select'] = $next_step_id;
$val_array = [];
if (!empty($row['values']))
$val_array = json_decode($row['values'],true);
$val_array[$step_id] = self::clearInput(json_encode($fields, JSON_UNESCAPED_UNICODE));
$values = json_encode($val_array, JSON_UNESCAPED_UNICODE);
if ($client_id > 0) {
$sql = "UPDATE `clients_funnel_step`
SET `step_id` = ".$step_id.",
`next_id` = '".$next_id."',
`prev_id` = '".$prev_id."',
`prev_next_id` = '".$prev_next_id."',
`values` = '".$values."'
WHERE `client_id` = ".$client_id;
} else if ($client_id == 0 && $requisition_id > 0) {
$sql = "UPDATE `clients_funnel_step`
SET `step_id` = ".$step_id.",
`next_id` = '".$next_id."',
`prev_id` = '".$prev_id."',
`prev_next_id` = '".$prev_next_id."',
`values` = '".$values."'
WHERE `req_id` = ".$requisition_id;
}
} else {
$fields['prev_id'] = $prev_id;
$fields['prev_next_id'] = $prev_next_id;
$fields['next_step_select'] = $next_step_id;
$val_array = [];
$val_array[$step_id] = self::clearInput(json_encode($fields, JSON_UNESCAPED_UNICODE));
$values = json_encode($val_array, JSON_UNESCAPED_UNICODE);
if ($client_id > 0) {
$sql = "INSERT INTO `clients_funnel_step`
SET `client_id` = ".$client_id.",
`step_id` = ".$step_id.",
`next_id` = '".$next_id."',
`prev_id` = '".$prev_id."',
`prev_next_id` = '".$prev_next_id."',
`values` = '".$values."'";
} else if ($client_id == 0 && $requisition_id > 0) {
$sql = "INSERT INTO `clients_funnel_step`
SET `req_id` = ".$requisition_id.",
`step_id` = ".$step_id.",
`next_id` = '".$next_id."',
`prev_id` = '".$prev_id."',
`prev_next_id` = '".$prev_next_id."',
`values` = '".$values."'";
}
}
/*var_export($sql);
die();*/
if (!empty($sql)) {
if (mysql_query($sql)) {
// Дополнительные действия при закрытии этапа
if (isset($stage['after_close']) && !empty($stage['after_close_do'])) {
/*if ($requisition_id > 0) {
if ($query = mysql_query("SELECT * FROM `requisitions` WHERE id = ".$requisition_id)) {
if (mysql_num_rows($query) > 0) {
$req = mysql_fetch_assoc($query);
if (boolval($stage['after_close']['use_in_advert_turn_off'])) {
$sql_adv = "use_in_advert = 0, add_to_bn_feed = 0, add_to_yandex_feed = 0, add_to_domclick_feed = 0, add_to_avito_feed = 0, add_to_emls_feed = 0, add_to_cian_feed = 0, add_to_zipal = 0";
if (($req['type_id'] == 2 || $req['heir'] == 2) && $req['object_id'] > 0) {
mysql_query("UPDATE objects SET $sql_adv WHERE id = {$req['object_id']}");
$db_sphinx->query("UPDATE objects SET $sql_adv WHERE id=$req[object_id]", true);
}
}
if (boolval($stage['after_close']['autosearch_turn_off'])) {
if ($req['type_id'] == 1 || $req['heir'] == 1 || $req['type_id'] == 4 || $req['heir'] == 4) {
}
}
}
}
}*/
// Добавление тегов
if (($client_id > 0 || $requisition_id > 0) && boolval($stage['after_close']['add_activity']) && !empty($stage['after_close_do']['tags'])) {
$tags = $stage['after_close_do']['tags'];
if (count($tags) > 0) {
$source_id = null;
if ($client_id > 0)
$source_id = (int)$client_id;
else if ($requisition_id > 0)
$source_id = (int)$requisition_id;
$tags_list = [];
$tags = array_map('intval', $tags);
$all_tags = $this->getTags($app, null, $post, true);
foreach ($all_tags as $tag) {
if (in_array((int)$tag['id'], $tags))
$tag['isChecked'] = true;
else
$tag['isChecked'] = false;
$tags_list[] = $tag;
}
$this->setTags($app, null, [
'section' => $section,
'source_id' => $source_id,
'tags_list' => $tags_list
], true);
}
}
// Добавление договоров
if (($client_id > 0 || $requisition_id > 0) && boolval($stage['after_close']['add_contract']) && !empty($stage['after_close_do']['contracts'])) {
$contracts = $stage['after_close_do']['contracts'];
$contracts_inst = new ContractsController();
foreach ($contracts as $contract) {
$source_id = null;
if ($client_id > 0)
$source_id = (int)$client_id;
else if ($requisition_id > 0)
$source_id = (int)$requisition_id;
$contracts_inst->addEditContract($app, null, [
'section' => $section,
'source_id' => $source_id,
'id' => (isset($contract['id'])) ? $contract['id'] : null,
'parent_id' => (isset($contract['parent_id'])) ? $contract['parent_id'] : null,
'type' => (isset($contract['type'])) ? $contract['type'] : null,
'number' => (isset($contract['number'])) ? $contract['number'] : null,
'date_start' => (isset($contract['date_start'])) ? $contract['date_start'] : null,
'date_end' => (isset($contract['date_end'])) ? $contract['date_end'] : null,
'notify_days' => (isset($contract['days'])) ? $contract['days'] : null,
'is_notified' => (isset($contract['send'])) ? $contract['send'] : null,
'object' => (isset($contract['object'])) ? $contract['object'] : null,
'requisitions' => (isset($contract['requisitions'])) ? $contract['requisitions'] : null,
], true);
}
}
}
if (boolval($stage['is_close_after'])) {
$closed_stage = '2';
/*if (true != true) // @todo: заявки часть2 (4280e3f67ae5a04b48c3659a0a57443ec4994994)
$closed_stage = '8';*/
if ($client_id > 0) {
if (!mysql_query("UPDATE `clients` SET stage='$closed_stage', deleted=1, confirm=1 WHERE id = {$client_id}")) {
$error = true;
$errors[] = mysql_error();
}
} else if ($client_id == 0 && $requisition_id > 0) {
if (!mysql_query("UPDATE `requisitions` SET stage='$closed_stage', deleted=1, confirm=1 WHERE id = {$requisition_id}")) {
$error = true;
$errors[] = mysql_error();
}
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
// Отправка уведомлений и запись истории
if (!$error && $step_id) {
$date = time();
$create_at = date('Y-m-d H:i:s');
if($client_id > 0){
$in_history = "INSERT INTO `steps_history`(`client_id`, `step_id`, `date`, `type`, `user_id`, `created_at`)
VALUES ({$client_id}, {$step_id}, {$date}, 1, {$user_id}, '{$create_at}')";
mysql_query($in_history);
} else if($requisition_id > 0){
$in_history = "INSERT INTO `steps_history`(`req_id`, `step_id`, `date`, `type`, `user_id`, `created_at`)
VALUES ({$requisition_id}, {$step_id}, {$date}, 1, {$user_id}, '{$create_at}')";
mysql_query($in_history);
}
$close = false;
$next_step = 0;
if ($next_id != 0) {
$next_step = (int)$next_id;
} else if (!empty($stage['next_steps_ids'])) {
$next_step = (int)$stage['next_steps_ids'][0];
} else if (!empty($stage['prev_steps'][0]['next_steps'][0]['id'])) {
$next_step = (int)$stage['prev_steps'][0]['next_steps'][0]['id'];
}
$next_name = [];
if ($next_step != 0) {
$sql = "SELECT `name`, `id` FROM `funnel_steps` WHERE `id` = {$next_step}";
if ($query = mysql_query($sql)) {
$next_name = mysql_fetch_assoc($query);
} else {
$error = true;
$errors[] = mysql_error();
}
}
// Отправлять ли уведомление
$sql = "SELECT `is_mes`, `users_mes`, `name` FROM `funnel_steps` WHERE `id` = {$step_id}";
if ($query = mysql_query($sql)) {
$row = mysql_fetch_assoc($query);
if ($row['is_mes'] > 0) {
$users_mes = json_decode($row['users_mes'], true);
if (!empty($users_mes)) {
$who_work = 0;
$user1 = mysql_fetch_assoc(mysql_query("SELECT * FROM users WHERE id = {$user_id}"));
$post = "Сотрудник";
if ($user1['agency'] == 1) {
$post = "Агенство";
} else if ($user1['manager'] == 1) {
$post = "Менеджер";
}
$text = "".$post . " " . trim($user1['last_name'] . ' ' . $user1['first_name'] . ' ' . $user1['middle_name'])."
закрыл(а) этап «".$step_name."» ";
if ($client_id == 0 && $requisition_id > 0) {
$sql = "SELECT * FROM `requisitions` WHERE `id` = {$requisition_id}";
if ($query = mysql_query($sql)) {
$req = mysql_fetch_assoc($query);
$who_work = $req['who_work'];
$text .= "
по заявке " . $req['name'] . "
";
if ($next_step != 0) {
$text .= "Заявка перешла на этап «" . $next_name['name'] . "»
";
}
$sql = "SELECT * FROM `clients` WHERE `id` = {$req['client_id']}";
if ($query = mysql_query($sql)) {
$client_req = mysql_fetch_assoc($query);
$text .= "Клиент: " . $client_req['fio'] . " тел. " . $client_req['phone'];
if ($req['type_id'] == 2 && $req['object_id'] > 0) {
$sql = "SELECT `id`, `adres`, `stoim`, `type`, `komnat` FROM `objects` WHERE `id` = {$req['object_id']}";
if ($query = mysql_query($sql)) {
if ($obj = mysql_fetch_assoc($query)) {
switch ($obj['type']) {
case 1:
if ($obj['komnat'] == 1 && $obj['studio_flag']) {
$type = "Квартира-студия";
} else {
$type = "$obj[komnat]-комнатная квартира";
}
break;
case 2:
$type = "Комната в $obj[komnat]-комнатной квартире";
break;
case 3:
$type = "$obj[komnat]-комнатный дом";
break;
case 4:
switch ($obj['type_category']){
case 1:
$type = "Офис";
break;
case 2:
$type = "Склад";
break;
case 3:
$type = "Торговая площадь";
break;
case 4:
$type = "Производство";
break;
case 5:
$type = "Помещение свободного назначения";
break;
case 6:
$type = "Здание";
break;
case 7:
$type = "Гараж";
break;
case 8:
$type = "Готовый бизнес";
break;
case 9:
$type = "Коммерческая земля";
break;
default: $type = "Помещение";
}
break;
case 5:
$type = "Часть дома";
break;
case 6:
$type = "Комплекс";
break;
case 7:
$type = "Участок";
break;
default:
$type = "$obj[komnat]-комнатная квартира";
}
$text .= '
Объект: ID:' . $obj['id'] . ' ' . $obj['adres'] . ', ' . $type . ' ' . $obj['stoim'];
}
}
}
if ($req['deleted'] > 0)
$close = true;
} else {
$error = true;
$errors[] = mysql_error();
}
} else {
$error = true;
$errors[] = mysql_error();
}
} else if ($client_id > 0) {
$sql = "SELECT * FROM `clients` WHERE `id` = {$client_id}";
if ($query = mysql_query($sql)) {
$client = mysql_fetch_assoc($query);
$who_work = $client['who_work'];
$text .= "
по клиенту: " . $client['fio'] . " тел. " . $client['phone'];
if ($next_step != 0) {
$text .= "
Клиент перешел на этап «" . $next_name['name'] . "»";
}
if ($client['deleted'] > 0) {
$close = true;
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
$text = htmlspecialchars($text);
$user_messaged = [];
$send = 0;
if ($close) {
$temp_id = time();
$send = 1;
}
foreach ($users_mes as $user_id_mes) {
if ($user_id_mes == 0)
$user_id_mes = $who_work;
if (!in_array($user_id_mes, $user_messaged) && $user_id_mes != $user_id) {
$sql = "INSERT INTO `step_notify_closure`
SET `user_id` = {$user_id_mes},
`from_id` = {$user_id},
`step_id` = {$step_id},
`text` = '{$text}',
`send` = {$send},
`temp_id` = {$temp_id}";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
$user_messaged[] = $user_id_mes;
}
}
}
}
}
$text = '';
if(isset($stage['linking_steps'])){
//var_dump($stage['linking_steps']);
foreach($stage['linking_steps'] as $key => $field_models){
$arrField = explode("_", $key, 2);
$typeField = 1;
if($arrField[0] == 'modelp'){
$typeField = 2;
}
$fieldId = $arrField[1];
if(is_numeric($fieldId)){
$field_id = (int)$fieldId;
$value = $field_models['value'];
if($field_models['type'] == 2){
$value = $field_models['value'];
if(isset($field_models['params']['items'])){
foreach($field_models['params']['items'] as $item){
if($item['value'] == $value){
$val = $item['name'];
}
}
//$val = $pd['params']['items'][$arrFields_models['modelp_'.$value]]['name'];
}
$text .= '