Joywork/api/v2/app/src/controllers/RequisitionsController.php
2026-07-10 18:07:56 +03:00

2925 lines
110 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

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

<?php
namespace App\v2\Controller;
class RequisitionsController extends ApiController
{
// Гейтинг найденных листингов парсера: заявку нельзя привязать к чужому объявлению —
// оно read-only, сначала копирование объекта в свои.
// Offset-free: после снятия смещения id листинга (= реальный external_listings.id) коллизит
// с objects.id, поэтому различить листинг по id нельзя. Признак — явный флаг is_external
// из запроса (фронт знает, что заявку привязывают к найденному листингу).
// Возвращает true, если запрос отклонён (вызывающий метод делает return).
private function _rejectIfExternalListing($app, $is_external)
{
if (!empty($is_external)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(403);
$app->response->setBody(json_encode([
'success' => false,
'errors' => ['Действие недоступно для найденного листинга. Скопируйте объект в свои, чтобы управлять им.'],
], JSON_UNESCAPED_UNICODE));
return true;
}
return false;
}
public function getRequisitions($app, $get = null, $post = null, $need_return = false) {
$start_time = microtime(true);
$error = false;
if ($user_id = $_SESSION['id']) {
/*error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('display_errors', 1);*/
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
$filters = [];
if (isset($get['filters'])) {
if (!is_array($get['filters']))
$filters = json_decode($get['filters'], true);
else
$filters = (array)$get['filters'];
}
$need_autosearch = false;
if (isset($get['need_autosearch']))
$need_autosearch = true;
$sort_order = null;
if (isset($get['sort_order']))
$sort_order = mb_strtolower(trim($get['sort_order']));
$req_filter = [
'order' => (($sort_order == 'desc') ? 2 : (($sort_order == 'asc') ? 1 : null)),
'search' => '',
'stages' => [
'work' => 0,
'hot' => 0,
'close' => 0,
'hit' => 0,
'ahency' => 0,
'confirm' => 0,
],
'emp' => null,
'type' => null,
'step' => null,
'priority' => null,
'send' => 0,
'denial' => null,
'source' => null,
'object_id' => null,
//'date_closer' => 10,
//'id' => null,
//'not_id' => null,
'is_contract' => false,
'type_contract' => [],
'numder_contract' => null,
'onDateContract' => null,
'offDateContract' => null,
'is_tasks' => false,
'noTasks' => false,
'todayTasks' => false,
'overTasks' => false,
'isPartner' => false,
//'expired_stages' => false,
'period' => 'all',
'activities' => null,
'employee_id' => null,
'fields' => null,
'is_date_step' => false,
'onDateStep' => null,
'offDateStep' => null,
];
$page = 1;
if (isset($get['page']))
$page = intval($get['page']);
$per_page = 10;
if (isset($get['per_page']))
$per_page = intval($get['per_page']);
$query = null;
if (isset($get['query']))
$query = trim($get['query']);
// Запрос поиска
if (!empty($query)) {
$req_filter['search'] = $query;
}
if (empty($query)) {
$funnel_id = 0;
if (isset($get['funnel_id']))
$funnel_id = intval($get['funnel_id']);
else if (isset($filters['funnel_id']))
$funnel_id = intval($filters['funnel_id']);
else {
/*$users = new \User();
$agency_id = $users->getUserAgencyID($user_id);
$sql = "SELECT * FROM funnel_default WHERE agency_id = {$agency_id} AND is_req = 1";
$query = $pdo->query($sql);
if ($pdo->num_rows($query) != 0) {
$row = $pdo->fetch_assoc($query);
//$funnel_id = (int)$row['id'];
}*/
}
} else {
$funnel_id = 'all';
}
$client_id = null;
if (isset($get['client_id']))
$client_id = intval($get['client_id']);
$object_id = null;
if (isset($get['object_id']))
$object_id = intval($get['object_id']);
$extended = false;
if (isset($get['extended']))
$extended = boolval($get['extended']);
$agency = new \User;
$agency->get($user_id);
$agency->checkPermissions($user_id, false);
$req_inst = new \Requisitions($pdo);
$sql_permissions = "SELECT * FROM user_permissions WHERE user_id = {$user_id}";
$q_permissions = mysql_query($sql_permissions);
$r_permissions = mysql_fetch_assoc($q_permissions);
$search_user_id = $user_id;
if ($agency->users_admin || $r_permissions['menu_all_submissions'] == 1) {
$search_user_id = $agency->getUserAgencyID();
$req_inst->set_agencyId($search_user_id);
}
$req_inst->set_user($agency);
$req_inst->set_page($page);
$req_inst->set_per_page(10);
// Статус заявки (В работе, Горичий, Закрытые, Успешные...)
if (isset($filters['status'])) {
switch (trim($filters['status'])) {
case 'stage_work':
$req_filter['stages']['work'] = 1;
break;
case 'stage_hot':
$req_filter['stages']['hot'] = 1;
break;
case 'stage_close':
$req_filter['stages']['close'] = 1;
break;
case 'stage_hit':
$req_filter['stages']['hit'] = 1;
break;
case 'confirmed_clients':
$req_filter['stages']['confirm'] = 1;
break;
case 'common_clients':
$req_filter['stages']['ahency'] = 1;
break;
}
}
// ИД объекта
if (isset($filters['object_id']))
$req_filter['object_id'] = trim($filters['object_id']);
// Приоритет
if (isset($filters['priority'])) {
$req_filter['priority'] = [
1 => intval($filters['priority'][1]) ? 1 : 0,
2 => intval($filters['priority'][2]) ? 1 : 0,
3 => intval($filters['priority'][3]) ? 1 : 0,
4 => intval($filters['priority'][4]) ? 1 : 0,
];
}
// Ответственный
if (isset($filters['employees']))
$req_filter['emp'] = array_values($filters['employees']);
// Тип заявки
if (isset($filters['type']))
$req_filter['type'] = array_values($filters['type']);
// Этап
if (isset($filters['stages']))
$req_filter['step'] = array_values($filters['stages']);
// Теги
if (isset($filters['activities']))
$req_filter['activities'] = array_values($filters['activities']);
// Причина закрытия
if (isset($filters['denials']))
$req_filter['denial'] = array_values($filters['denials']);
// Источники
if (isset($filters['sources']))
$req_filter['source'] = array_values($filters['sources']);
// Контракты
if (isset($filters['is_contract'])) {
if ((int)$filters['is_contract'] && isset($filters['is_contract']))
$req_filter['is_contract'] = boolval($filters['is_contract']);
if ((int)$filters['is_contract'] && isset($filters['contract_type']))
$req_filter['type_contract'] = array_values($filters['contract_type']);
if ((int)$filters['is_contract'] && isset($filters['contract_number']))
$req_filter['numder_contract'] = trim($filters['contract_number']);
if ((int)$filters['is_contract'] && isset($filters['contract_date_end_from']))
$req_filter['onDateContract'] = trim($filters['contract_date_end_from']);
if ((int)$filters['is_contract'] && isset($filters['contract_date_end_to']))
$req_filter['offDateContract'] = trim($filters['contract_date_end_to']);
}
// Договора
if (!empty($filters['is_contract'])) {
if ((int)$filters['is_contract'] && isset($filters['is_contract']))
$req_filter['is_contract'] = boolval($filters['is_contract']);
if ($req_filter['is_contract']) {
if (isset($filters['contract_number']) && !empty($filters['contract_number']))
$req_filter['numder_contract'] = trim($filters['contract_number']);
if (isset($filters['contract_type']) && !is_array($filters['contract_type']))
$req_filter['type_contract'] = $filters['contract_type'];
if (isset($filters['contract_start']) && !empty($filters['contract_start']))
$req_filter['onDateContract'] = date('Y-m-d ', strtotime($filters['contract_start']));
if (isset($filters['contract_end']) && !empty($filters['contract_end']))
$req_filter['offDateContract'] = date('Y-m-d ', strtotime($filters['contract_end']));
}
}
//Этапы
if(!empty($filters['is_date_step'])){
$req_filter['is_date_step'] = $filters['is_date_step'];
if (isset($filters['onDateStep']) && !empty($filters['onDateStep']))
$req_filter['onDateStep'] = date('Y-m-d ', strtotime($filters['onDateStep']));
if (isset($filters['offDateStep']) && !empty($filters['offDateStep']))
$req_filter['offDateStep'] = date('Y-m-d ', strtotime($filters['offDateStep']));
}
// Время добавления (период)
if (!empty($filters['period'])) {
if ((int)$filters['period'] && isset($filters['period']))
$req_filter['period'] = $filters['period'];
if (!empty($req_filter['period'])) {
switch ($req_filter['period']) {
case 1:
$req_filter['period'] = 'today';
break;
case 2:
$req_filter['period'] = 'week';
break;
case 3:
$req_filter['period'] = 'month';
break;
case 4:
$req_filter['period'] = '30days';
break;
case 5:
$req_filter['period'] = 'quarter';
break;
case 6:
$req_filter['period'] = '90days';
break;
case 7:
$req_filter['period'] = 'year';
break;
case 8:
$req_filter['period'] = 'all';
break;
case 9:
$req_filter['period'] = 'period';
break;
}
if ($req_filter['period'] == 'period') {
if (isset($filters['period_start']) && !empty($filters['period_start']))
$req_filter['onDate'] = date('Y-m-d ', strtotime($filters['period_start']));
if (isset($filters['period_end']) && !empty($filters['period_end']))
$req_filter['offDate'] = date('Y-m-d ', strtotime($filters['period_end']));
if (!empty($req_filter['onDate']) && empty($req_filter['offDate']))
$req_filter['offDate'] = date('Y-m-d ');
}
}
// Снимаем воронку, если выборка с периодом
$funnel_id = 0;
}
// Партнёры/сотрудники партнёра
if (isset($filters['partners']))
$req_filter['employee_id'] = array_values($filters['partners']);
// С задачами
if (isset($filters['is_tasks'])) {
$req_filter['is_tasks'] = boolval($filters['is_tasks']);
}
// Без задач
if (isset($filters['is_no_tasks']))
$req_filter['noTasks'] = boolval($filters['is_no_tasks']);
// С задачами на сегодня
if (isset($filters['is_today_tasks']))
$req_filter['todayTasks'] = boolval($filters['is_today_tasks']);
// С просроченными задачами
if (isset($filters['is_over_tasks']))
$req_filter['overTasks'] = boolval($filters['is_over_tasks']);
// Совместные заявки
if (isset($filters['is_partner']))
$req_filter['isPartner'] = boolval($filters['is_partner']);
if (isset($filters['is_deal']))
$req_filter['is_deal'] = boolval($filters['is_deal']);
// Цены на объекты в заявках
if (isset($filters['priceFrom']))
$req_filter['priceFrom'] = intval($filters['priceFrom']);
if (isset($filters['priceTo']))
$req_filter['priceTo'] = intval($filters['priceTo']);
// Кастомные поля
if (isset($filters['fields'])) {
$fields = [];
foreach ($filters['fields'] as $field => $value) {
if (is_null($value) || (empty($value) && $value != 0)) {
unset($filters['fields'][$field]);
} else {
$fields[$field] = $value;
}
}
if (!empty($fields)) {
$req_filter['fields'] = $fields;
}
}
$req_filter['funnel_id'] = $funnel_id;
// Очистка от пустых значений
foreach ($req_filter as $prop => $value) {
if (is_null($value) || (empty($value) && $value != 0)) {
unset($req_filter[$prop]);
}
}
$req_filter['stages'] = (object)$req_filter['stages'];
// Наполняем new_transfers для is_new здесь, не полагаясь на getFunnels
$nt_agency_id = \User::getUserAgencyID($user_id);
$nt_ids = [];
$nt_sql = "SELECT DISTINCT `req`.`id` FROM `events_clients` AS `events` LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `events`.`req_id` LEFT JOIN `funnel` AS `funnel` ON `funnel`.`id` = `req`.`funnel_id` WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND (`events`.`event` = 'accepted' OR `events`.`event` = 'accepted_doer') AND `events`.`viewed` = 0 AND `events`.`read` = 1 AND (`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 '%&quot;{$user_id}&quot;:1%') AND (`req`.`funnel_id` = 0 OR (`funnel`.`agency_id` = '$nt_agency_id' AND `funnel`.`deleted` = 0))";
if ($nt_q = mysql_query($nt_sql)) {
while ($nt_row = mysql_fetch_assoc($nt_q))
$nt_ids[] = $nt_row['id'];
}
$_SESSION['new_transfers']['requisitions'] = $nt_ids;
$results = $req_inst->get_all($search_user_id, (object)$req_filter, (string)$funnel_id, $client_id, $object_id, $need_autosearch);
$pagination = [
'pages' => (int)$results['allPages'],
'page' => $page,
'per_page' => $per_page,
'_time_overage' => (int)$results['_time_overage'],
'total' => (int)$results['total_req'],
'count' => (int)$results['count'],
];
$results = array_values($results['req']);
$req_ids = [];
foreach ($results as $req) {
$req_ids[] = (int)$req['id'];
}
// Подсчет событий по заявкам
$events_less = [];
$events_eq = [];
$events_more = [];
$req_activities = [];
if (count($req_ids) > 0) {
$sql = "SELECT count(`id`) AS `res`, `req_id`
FROM `user_client_events`
WHERE `calendar_view` = 0 AND
`cancel`=0 AND
`type` IN ('call', 'meet', 'show', 'deal', 'even') AND
`schedule_date` IS NOT NULL AND
`req_id` IN (" . implode(", ", $req_ids) . ") AND
`schedule_date` < '" . date("Y-m-d H:i:s") . "'
GROUP BY `req_id`";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_assoc($query)) {
$events_less[] = $row;
}
}
}
$sql = "SELECT count(id) as res, req_id
FROM user_client_events
WHERE calendar_view = 0 AND
cancel=0 AND
`type` IN ('call', 'meet', 'show', 'deal', 'even') AND
schedule_date IS NOT NULL AND
req_id IN (" . implode(", ", $req_ids) . ") AND
DATE_FORMAT(schedule_date, '%Y-%m-%d') = '" . date("Y-m-d") . "' AND
schedule_date > '" . date("Y-m-d H:i:s") . "'
GROUP BY req_id";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_assoc($query)) {
$events_eq[] = $row;
}
}
}
$sql = "SELECT count(id) as res, req_id
FROM user_client_events
WHERE calendar_view = 0 AND
cancel=0 AND
`type` IN ('call', 'meet', 'show', 'deal', 'even') AND
schedule_date IS NOT NULL AND
req_id IN (" . implode(", ", $req_ids) . ") AND
DATE_FORMAT(schedule_date, '%Y-%m-%d') > '" . date("Y-m-d") . "'
GROUP BY req_id";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_assoc($query)) {
$events_more[] = $row;
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
// Формируем список тегов под заявки
$sql = "SELECT `activity_id`, `req_id`
FROM `requisitions_activities`
WHERE `req_id` IN (" . implode(", ", $req_ids) . ")";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_assoc($query)) {
$req_activities[$row['req_id']][] = $row['activity_id'];
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
// Договоры
if ($extended) {
$contracts = [];
if (!empty($req_ids)) {
$contracts_inst = new \Contract();
foreach ($req_ids as $req_id) {
$contracts[$req_id] = $contracts_inst->getContracts($req_id, 'req');
foreach ($contracts[$req_id] as $key => $contract) {
if (isset($contract['date_start']))
$contracts[$req_id][$key]['date_start'] = date('Y-m-d H:i:s', strtotime($contract['date_start']));
if (isset($contract['date_end']))
$contracts[$req_id][$key]['date_end'] = date('Y-m-d H:i:s', strtotime($contract['date_end']));
}
}
}
}
$requisitions = [];
$clients_ids = [];
$objects_ids = [];
foreach ($results as $req) {
// Подсчет новых событий в Истории и задачах
$events_expired = 0;
$events_today = 0;
$events_count = 0;
foreach ($events_less as $event) {
if ((int)$event["req_id"] == (int)$req["id"]) {
$events_expired = (int)$event["res"];
break;
}
}
foreach ($events_eq as $event) {
if ((int)$event["req_id"] == (int)$req["id"]) {
$events_today = (int)$event["res"];
break;
}
}
foreach ($events_more as $event) {
if ((int)$event["req_id"] == (int)$req["id"]) {
$events_count = (int)$event["res"];
break;
}
}
// Совместная работа с Заявкой
$doers_ids = [];
$accepted_doers_ids = [];
$requested_doers_ids = [];
if (isset($req['doers'])) {
$doers = json_decode(html_entity_decode($req['doers'], ENT_QUOTES), true);
if (is_array($doers)) {
foreach ($doers as $doer_id => $is_accept) {
$doers_ids[] = $doer_id;
if ((int)$is_accept == 1)
$accepted_doers_ids[] = $doer_id;
else
$requested_doers_ids[] = $doer_id;
}
$doers_ids = array_unique(array_map('intval', $doers_ids));
$accepted_doers_ids = array_unique(array_map('intval', $accepted_doers_ids));
$requested_doers_ids = array_unique(array_map('intval', $requested_doers_ids));
}
}
// Миксуем старые и новые теги
if (is_array($req['activities']) && is_array($req_activities[$req['id']]))
$req['activities'] = array_merge($req['activities'], $req_activities[$req['id']]);
// Теги
$tags = [];
if (count($req['activities_temp'])) {
$tags = array_map('intval', $req['activities_temp']);
$tags = array_unique(array_values($tags));
}
if (isset($req['client_id']))
$clients_ids[] = (int)$req['client_id'];
if (isset($req['object_id']))
$objects_ids[] = (int)$req['object_id'];
$autosearch_id = null;
if (isset($req['autosearch_id']))
$autosearch_id = (int)$req['autosearch_id'];
if (!$autosearch_id && isset($req['asfilter_id']))
$autosearch_id = (int)$req['asfilter_id'];
$sql_check_manager = "SELECT `id_manager`, `department_id` FROM `users` WHERE `id` = ".$req['who_work'];
$result_check_manager = mysql_query($sql_check_manager);
$req_id_manager = mysql_fetch_assoc($result_check_manager);
$user = new \User();
$user->get($user_id);
$r_check_permissions = $user->checkMenuPermissions();
$depClassPerm = new \Department();
$dep_user = $depClassPerm->getDepartment($_SESSION['id']);
$sql_user_missing_fields = "SELECT `id_manager`, `department_id` FROM `users` WHERE `id` = ".$_SESSION['id'];
$result_user_missing_fields = mysql_query($sql_user_missing_fields);
$user_missing_fields = mysql_fetch_assoc($result_user_missing_fields);
$user_allow_edit = false;
if ($_SESSION['agency'] || $_SESSION['users_admin'] || $r_check_permissions['menu_all_submissions_edit'] == 1 || $_SESSION['id'] == $req['who_work']) {
$user_allow_edit = true;
} elseif (($dep_user['role'] == 'admin_department' || $dep_user['role'] == 'manager_office') && $req_id_manager['department_id'] == $user_missing_fields['department_id']) {
$user_allow_edit = true;
} elseif ($dep_user['role'] == 'manager' && $user->id == $req_id_manager['id_manager']) {
$user_allow_edit = true;
} elseif ($dep_user['role'] == 'manager_office_menager' && ($user->id == $req_id_manager['id_manager'] || $_SESSION['id_manager'] == $req_id_manager['id_manager'] || $_SESSION['id_manager'] == $req['who_work'])) {
$user_allow_edit = true;
} elseif (!($dep_user['role']) && ($_SESSION['manager'] && ($_SESSION['id'] == $req_id_manager['id_manager']))) {
$user_allow_edit = true;
}
$requisitions[] = [
'id' => (int)$req['id'],
'name' => trim($req['name']),
'created_at' => date('d.m.Y H:i:s', strtotime(trim($req['created_at']))),
'client_id' => (int)$req['client_id'],
'object_id' => (int)$req['object_id'],
'funnel_id' => (int)$req['funnel_id'],
'type_id' => (int)$req['type_id'],
'heir_type_id' => (int)$req['heir_type'],
'step_id' => (int)$req['step_id'],
'user_id' => (int)$req['user_id'],
'object' => $req['object'],
'client' => $req['client'],
'description' => trim($req['description']),
'is_confirm' => (bool)$req['confirm'],
'is_hot' => (bool)$req['hot'],
'priority' => (int)$req['priority'],
'is_new' => (bool)$req['is_new'],
'is_deleted' => isset($req['deleted']) && $req['deleted'] > 0 && $req['confirm'] != 10,
'is_completed' => isset($req['deleted']) && $req['deleted'] > 0 && $req['confirm'] == 10,
'is_canceled' => (bool)$req['cancel'],
'close_reason' => (isset($req['reason'])) ? trim($req['reason']) : null,
'is_no_confirm' => (bool)$req['no_confirm'],
'is_no_confirm_doer' => (bool)$req['no_conf_doer'],
'is_can_see' => (bool)$req['can_see'],
'is_can_see_other' => (bool)$req['can_see_other'],
'is_can_edit' => (bool)$req['can_edit'],
'see_client' => (bool)$req['see_client'],
'stage_id' => (int)$req['steps']['stageId'],
'stage_name' => !empty(trim($req['steps']['stage'])) ? trim($req['steps']['stage']) : (($req['deleted'] > 0 && $req['confirm'] == 10) ? 'Закрыт' : 'Новый'),
'source_id' => (int)$req['source'],
'contracts' => (isset($req['contracts'])) ? $req['contracts'] : [],
'events_count' => [
'requisitions' => [
'expired' => $events_expired,
'today' => $events_today,
'total' => $events_count,
]
],
'tags' => (!empty($tags)) ? $tags : null,
'who_work' => (int)$req['who_work'],
'can_see_contact_closed' => (bool)$r_permissions['menu_can_take_from_closed'],
'can_see_contact_common' => (bool)($_SESSION['agency'] || $_SESSION['users_admin']),
'employee_id' => (isset($req['who_work'])) ? intval($req['who_work']) : 0,
'manager' => (isset($req['manager'])) ? trim($req['manager']) : null,
'manager_phone' => (isset($req['manager_phone'])) ? trim($req['manager_phone']) : null,
'master_work_id' => (isset($req['master_work_id'])) ? (int)trim($req['master_work_id']) : null,
'master_work' => (isset($req['master_work'])) ? trim($req['master_work']) : null,
'master_work_phone' => (isset($req['master_work_phone'])) ? trim($req['master_work_phone']) : null,
'master_delete' => (isset($req['master_delete'])) ? trim($req['master_delete']) : null,
'master_delete_phone' => (isset($req['master_delete_phone'])) ? trim($req['master_delete_phone']) : null,
'doers_ids' => $doers_ids,
'requested_doers_ids' => $requested_doers_ids,
'requested_doers' => (!empty($req['doer_no'])) ? implode(', ', $req['doer_no']) : null,
'accepted_doers_ids' => $accepted_doers_ids,
'accepted_doers' => (!empty($req['doer_yes'])) ? implode(', ', $req['doer_yes']) : null,
'partner_id' => (int)$req['employee_id'],
'autosearch_id' => $autosearch_id,
'autosearch' => $req['autosearch'],
'autosearch_info' => trim($req['autosearch_info']),
'this_user_can_edit_req' => $user_allow_edit,
'expected_commission' => $req['expected_commission'],
'expenses_total' => $req['expenses_total'],
'expenses' => $req['expenses'],
'deposit' => (int)$req['deposit'],
'summa' => (!empty($req['summa'])) ? $req['summa'] : null,
'depositArr' => $req['depositArr'],
'is_deal' => !empty($req['deal_id']) && $req['deal_id'] > 0 ? 1 : 0,
'deal_id' => !empty($req['deal_id']) && $req['deal_id'] > 0 ? (int)$req['deal_id'] : 0,
//'_RAW' => $req,
];
}
if ($extended) {
$clients_list = null;
if (count($clients_ids)) {
$clientsController = new ClientsController();
$clients_list = $clientsController->getClients(
$app,
['clients_ids' => $clients_ids],
null,
true
);
}
$funnels_list = null;
$commonController = new CommonController();
$funnels_list = $commonController->getFunnels(
$app,
[
'section' => 'requisitions',
'filters' => []
],
null,
true
);
$objects_list = null;
if (count($objects_ids)) {
$objectsController = new ObjectsController();
$objects_list = $objectsController->getObjects(
$app,
['objects_ids' => $objects_ids],
null,
true
);
if ($objects_list)
$objects_list = $objects_list['objects'];
}
$types_list = $commonController->getTypes(
$app,
['section' => 'requisitions'],
null,
true
);
// Формируем список тегов
$commonController = new CommonController;
$activities = $commonController->getTags($app, ['with_managers' => true], $post, true);
}
$data = [
'success' => !$error,
'user_id' => (int)$user_id,
'overage_time' => round((microtime(true) - $start_time), 3) . " sec.",
'is_extended' => $extended,
'req_filter' => $req_filter,
'pagination' => $pagination,
'count' => count($requisitions),
'list' => $requisitions,
];
if ($extended) {
$data['contracts_list'] = (!empty($contracts[$req['id']]) > 0) ? $contracts[$req['id']] : [];
$data['clients_list'] = $clients_list;
$data['funnels_list'] = $funnels_list;
$data['objects_list'] = $objects_list;
$data['types_list'] = $types_list;
$data['tags_list'] = $activities;
}
if ($need_return) {
return $data;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode($data, JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'overage_time' => round((microtime(true) - $start_time), 3) . " sec.",
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getRequisition($app, $get = null, $post = null) {
$start_time = microtime(true);
$error = false;
$results = [];
$requisition = [];
$req_id = false;
if (isset($get['requisition_id']))
$req_id = intval($get['requisition_id']);
if (($user_id = $_SESSION['id']) && $req_id) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
$users_inst = new \User();
$agency_id = $users_inst->getAgencyIdForUser($user_id);
$users_inst->get($user_id);
$req_inst = new \Requisitions($pdo);
$req_inst->set_user($users_inst);
$need_autosearch = false;
if (isset($get['need_autosearch']))
$need_autosearch = true;
$results = $req_inst->get_req_id($req_id, $need_autosearch);
if (!count($results)) {
$error = true;
} else if (isset($results["req".$req_id])) {
$req = $results["req".$req_id];
// Подсчет событий по заявкам
$events_less = [];
$events_eq = [];
$events_more = [];
$req_activities = [];
$sql = "SELECT count(`id`) AS `res`, `req_id`
FROM `user_client_events`
WHERE `calendar_view` = 0 AND
`cancel` = 0 AND
`type` IN ('call', 'meet', 'show', 'deal', 'even') AND
`schedule_date` IS NOT NULL AND
`req_id` = '$req_id' AND
`schedule_date` < '" . date("Y-m-d H:i:s") . "'
GROUP BY `req_id`";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_assoc($query)) {
$events_less[] = $row;
}
}
}
$sql = "SELECT count(id) as res, req_id
FROM user_client_events
WHERE calendar_view = 0 AND
cancel=0 AND
`type` IN ('call', 'meet', 'show', 'deal', 'even') AND
schedule_date IS NOT NULL AND
`req_id` = '$req_id' AND
DATE_FORMAT(schedule_date, '%Y-%m-%d') = '" . date("Y-m-d") . "' AND
schedule_date > '" . date("Y-m-d H:i:s") . "'
GROUP BY req_id";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_assoc($query)) {
$events_eq[] = $row;
}
}
}
$sql = "SELECT count(id) as res, req_id
FROM user_client_events
WHERE calendar_view = 0 AND
cancel=0 AND
`type` IN ('call', 'meet', 'show', 'deal', 'even') AND
schedule_date IS NOT NULL AND
`req_id` = '$req_id' AND
DATE_FORMAT(schedule_date, '%Y-%m-%d') > '" . date("Y-m-d") . "'
GROUP BY req_id";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_assoc($query)) {
$events_more[] = $row;
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
// Совместная работа с Заявкой
$doers_ids = [];
$accepted_doers_ids = [];
$requested_doers_ids = [];
if (isset($req['doers'])) {
$doers = json_decode(html_entity_decode($req['doers'], ENT_QUOTES), true);
if (is_array($doers)) {
foreach ($doers as $doer_id => $is_accept) {
$doers_ids[] = $doer_id;
if ((int)$is_accept == 1)
$accepted_doers_ids[] = $doer_id;
else
$requested_doers_ids[] = $doer_id;
}
$doers_ids = array_unique(array_map('intval', $doers_ids));
$accepted_doers_ids = array_unique(array_map('intval', $accepted_doers_ids));
$requested_doers_ids = array_unique(array_map('intval', $requested_doers_ids));
}
}
// Формируем список тегов под зявку
$sql = "SELECT `activity_id`, `req_id`
FROM `requisitions_activities`
WHERE `req_id` = '$req_id'";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_assoc($query)) {
$req_activities[$row['req_id']][] = $row['activity_id'];
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
$events_expired = 0;
$events_today = 0;
$events_count = 0;
foreach ($events_less as $event) {
if ((int)$event["req_id"] == (int)$req["id"]) {
$events_expired = (int)$event["res"];
break;
}
}
foreach ($events_eq as $event) {
if ((int)$event["req_id"] == (int)$req["id"]) {
$events_today = (int)$event["res"];
break;
}
}
foreach ($events_more as $event) {
if ((int)$event["req_id"] == (int)$req["id"]) {
$events_count = (int)$event["res"];
break;
}
}
// Миксуем старые и новые теги
if (is_array($req['activities']) && is_array($req_activities[$req['id']]))
$req['activities'] = array_merge($req['activities'], $req_activities[$req['id']]);
// Теги
$tags = [];
if (count($req['activities_temp'])) {
$tags = array_map('intval', $req['activities_temp']);
$tags = array_unique(array_values($tags));
}
// Договоры
$contracts_inst = new \Contract();
$contracts = $contracts_inst->getContracts((int)$req['id'], 'req');
foreach ($contracts as $key => $contract) {
if (isset($contract['date_start']))
$contracts[$key]['date_start'] = date('Y-m-d H:i:s', strtotime($contract['date_start']));
if (isset($contract['date_end']))
$contracts[$key]['date_end'] = date('Y-m-d H:i:s', strtotime($contract['date_end']));
}
// Дополнительные поля
$fields = [];
$fields_res = [];
$user = new \User();
$user->get($user_id);
if ($agency_id = $user->getUserAgencyID()) {
$fields_inst = new \Fields($pdo);
$fields_res = $fields_inst->get_req_fields($agency_id, (int)$req['id']);
if (!empty($fields_res['values'])) {
$fields = array_map('json_decode', $fields_res['values']);
}
}
/*$user = new \User();
$user->get($user_id);*/
$r_check_permissions = $user->checkMenuPermissions();
$depClassPerm = new \Department();
$dep_user = $depClassPerm->getDepartment($_SESSION['id']);
$sql_check_manager = "SELECT `id_manager`, `department_id` FROM `users` WHERE `id` = ".$req['who_work'];
$result_check_manager = mysql_query($sql_check_manager);
$req_id_manager = mysql_fetch_assoc($result_check_manager);
$sql_user_missing_fields = "SELECT `id_manager`, `department_id` FROM `users` WHERE `id` = ".$_SESSION['id'];
$result_user_missing_fields = mysql_query($sql_user_missing_fields);
$user_missing_fields = mysql_fetch_assoc($result_user_missing_fields);
$user_allow_edit = false;
if ($_SESSION['agency'] || $_SESSION['users_admin'] || $r_check_permissions['menu_all_submissions_edit'] == 1 || $_SESSION['id'] == $req['who_work']) {
$user_allow_edit = true;
} elseif (($dep_user['role'] == 'admin_department' || $dep_user['role'] == 'manager_office') && $req_id_manager['department_id'] == $user_missing_fields['department_id']) {
$user_allow_edit = true;
} elseif ($dep_user['role'] == 'manager' && $user->id == $req_id_manager['id_manager']) {
$user_allow_edit = true;
} elseif ($dep_user['role'] == 'manager_office_menager' && ($user->id == $req_id_manager['id_manager'] || $_SESSION['id_manager'] == $req_id_manager['id_manager'] || $_SESSION['id_manager'] == $req['who_work'])) {
$user_allow_edit = true;
} elseif (!($dep_user['role']) && ($_SESSION['manager'] && ($_SESSION['id'] == $req_id_manager['id_manager']))) {
$user_allow_edit = true;
}
$source_see = 1;
if($req['source'] > 0){
$commonController = new CommonController();
$sql_source = "SELECT * FROM `advertising_sources` WHERE id = {$req['source']}";
$q_source = mysql_query($sql_source);
$r_source = mysql_fetch_assoc($q_source);
if($commonController->is_see($app, $r_source['is_no_see'], $r_source['users_no_see']) === false)
$source_see = 0;
}
$requisition = [
'id' => (int)$req['id'],
'name' => trim($req['name']),
'created_at' => date('d.m.Y H:i:s', strtotime(trim($req['created_at']))),
'client_id' => (int)$req['client_id'],
'object_id' => (int)$req['object_id'],
'funnel_id' => (int)$req['funnel_id'],
'type_id' => (int)$req['type_id'],
'heir_type_id' => (int)$req['heir_type'],
'step_id' => (int)$req['step_id'],
'user_id' => (int)$req['user_id'],
//'object' => $req['object'],
//'client' => $req['client'],
'description' => trim($req['description']),
'is_confirm' => (bool)$req['confirm'],
'is_hot' => (bool)$req['hot'],
'priority' => (int)$req['priority'],
'is_new' => (bool)$req['is_new'],
'is_deleted' => isset($req['deleted']) && $req['deleted'] > 0 && $req['confirm'] != 10,
'is_completed' => isset($req['deleted']) && $req['deleted'] > 0 && $req['confirm'] == 10,
'is_canceled' => (bool)$req['cancel'],
'is_no_confirm' => (bool)$req['no_confirm'],
'is_no_confirm_doer' => (bool)$req['no_conf_doer'],
'is_can_see' => (bool)$req['can_see'],
'is_can_edit' => (bool)$req['can_edit'],
'see_client' => (bool)$req['see_client'],
'stage_id' => (int)$req['steps']['stageId'],
'stage_name' => !empty(trim($req['steps']['stage'])) ? trim($req['steps']['stage']) : (($req['deleted'] > 0 && $req['confirm'] == 10) ? 'Закрыт' : 'Новый'),
'source_id' => (int)$req['source'],
'source_see' => $source_see,
'employee_id' => (int)$req['who_work'],
'events_count' => [
'requisitions' => [
'expired' => $events_expired,
'today' => $events_today,
'total' => $events_count,
]
],
'manager' => (isset($req['manager'])) ? trim($req['manager']) : null,
'manager_phone' => (isset($req['manager_phone'])) ? trim($req['manager_phone']) : null,
'master_work' => (isset($req['master_work'])) ? trim($req['master_work']) : null,
'master_work_phone' => (isset($req['master_work_phone'])) ? trim($req['master_work_phone']) : null,
'master_delete' => (isset($req['master_delete'])) ? trim($req['master_delete']) : null,
'master_delete_phone' => (isset($req['master_delete_phone'])) ? trim($req['master_delete_phone']) : null,
'tags' => (!empty($tags)) ? $tags : null,
'contracts' => (!empty($contracts)) ? $contracts : [],
'fields' => (!empty($fields)) ? $fields : null,
'doers_ids' => $doers_ids,
'requested_doers_ids' => $requested_doers_ids,
'requested_doers' => (!empty($req['doer_no'])) ? implode(', ', $req['doer_no']) : null,
'accepted_doers_ids' => $accepted_doers_ids,
'accepted_doers' => (!empty($req['doer_yes'])) ? implode(', ', $req['doer_yes']) : null,
'partner_id' => (int)$req['employee_id'],
'autosearch_id' => (isset($req['autosearch_id'])) ? (int)$req['autosearch_id'] : null,
'autosearch' => $req['autosearch'],
'autosearch_info' => trim($req['autosearch_info']),
'this_user_can_edit_req' => $user_allow_edit,
'expected_commission' => $req['expected_commission'],
'expenses_total' => $req['expenses_total'],
'expenses' => $req['expenses'],
'deposit' => (int)$req['deposit'],
'summa' => (!empty($req['summa'])) ? $req['summa'] : null,
'depositArr' => $req['depositArr'],
'deal_id' => !empty($req['deal_id']) && $req['deal_id'] > 0 ? (int)$req['deal_id'] : 0,
//'_RAW' => $req,
];
}
}
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,
'item' => $requisition,
'overage_time' => round((microtime(true) - $start_time), 3) . " sec.",
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'overage_time' => round((microtime(true) - $start_time), 3) . " sec.",
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function addEditRequisition($app, $get = null, $post = null, $need_return = false) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode($body, true);
$requisition_id = null;
if ($user_id = $_SESSION['id']) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
$who_work = (isset($data['employee_id'])) ? (int)$data['employee_id'] : null;
if($who_work == -1) $who_work = 0;
$params = [
'req_id' => (isset($data['id'])) ? (int)$data['id'] : null,
'user_id' => $user_id,
'old_whowork' => $user_id,
'funnel_id' => (isset($data['funnel_id'])) ? $data['funnel_id'] : 0,
'name' => (isset($data['name'])) ? $data['name'] : null,
//'fio' => "",
'email' => (isset($data['email'])) ? $data['email'] : "",
'phone' => (isset($data['phone'])) ? $data['phone'] : "",
'opis' => (isset($data['description'])) ? html_entity_decode($data['description']) : "",
'type_id' => (isset($data['type_id'])) ? (int)$data['type_id'] : 0,
'object_price' => (isset($data['price'])) ? (int)$data['price'] : "",
'object_prep_price' => (isset($data['prep_price'])) ? (int)$data['prep_price'] : "",
'object_start_price' => (isset($data['start_price'])) ? (int)$data['start_price'] : "",
'object_fact_price' => (isset($data['fact_price'])) ? (int)$data['fact_price'] : "",
'client_id' => (isset($data['client_id'])) ? (int)$data['client_id'] : null,
'object_id' => (isset($data['object_id'])) ? (int)$data['object_id'] : 0,
'priority' => (isset($data['priority'])) ? (int)$data['priority'] : 0,
'confirm' => (isset($data['is_confirm'])) ? (int)$data['is_confirm'] : 1,
'who_work' => $who_work,
//'old_whowork' => null,
'hot' => (isset($data['is_hot'])) ? (int)$data['is_hot'] : 0,
'activities' => (isset($data['tags'])) ? (array)$data['tags'] : null,
'asfilter_id' => (isset($data['autosearch_id'])) ? (int)$data['autosearch_id'] : 'NULL',
//'autosearch_filter' => [],
'source' => (isset($data['source_id'])) ? (int)$data['source_id'] : null,
'employee_id' => (isset($data['partner_id'])) ? (int)$data['partner_id'] : null,
'autosearch_enabled' => (isset($data['autosearch_enabled'])) ? (int)$data['autosearch_enabled'] : 0,
'is_manual' => (isset($data['is_manual'])) ? (int)$data['is_manual'] : 0,
//'field_models' => (isset($data['fields'])) ? (array)$data['fields'] : null,
//'contracts' => null,
];
$fields_result = null;
// Заявку нельзя привязать к найденному листингу парсера — листинг read-only.
// Признак найденного листинга — явный флаг из запроса (offset-free: id листинга коллизит с objects.id).
if ($this->_rejectIfExternalListing($app, isset($data['is_external']) ? $data['is_external'] : null))
return;
$req = new \Requisitions($pdo);
$result = $req->add_edit($params);
if (isset($result['errors'])) {
$errors = $result['errors'];
} else {
$requisition_id = (int)$result;
// Доп. поля
$fields = (isset($data['fields'])) ? $data['fields'] : [];
if (!empty($requisition_id) && count($fields)) {
$field_inst = new \Fields($pdo);
$data = [];
foreach ($fields as $field => $value) {
$type = 1;
if (strpos(trim($field), "modelp_") !== false)
$type = 2;
$field_id = str_replace('model_', '', trim($field));
$field_id = str_replace('modelp_', '', $field_id);
if (!isset($data[(int)$field_id])) {
$data[(int)$field_id] = [
'type' => $type,
'value' => $value,
];
}
}
$fields_result = $field_inst->add_edit_data('requisitions', $requisition_id, $data);
if ($fields_result['success'] !== true)
$error = true;
if (isset($fields_result['errors']))
$errors = array_merge($errors, $fields_result['errors']);
}
}
if (count($errors))
$error = true;
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'requisition_id' => $requisition_id,
'fields_result' => $fields_result
], 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 toggleWatched($app) {
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
$data = json_decode(file_get_contents("php://input"), true);
$is_watched = $data['is_watched'];
$watched_req_id = $data['watched_req_id'];
$watched_obj_id = $data['watched_obj_id'];
$watched_user_id = $data['watched_user_id'];
if ($is_watched !== null) {
if (!$watched_req_id || !$watched_obj_id || !$watched_user_id) {
echo json_encode(['status' => 'error', 'message' => 'Missing parameters']);
exit;
}
$sql_check = "SELECT id FROM watched_requisitions
WHERE user_id = $watched_user_id AND req_id = $watched_req_id AND object_id = $watched_obj_id";
$result = $pdo->query($sql_check);
if ($result->rowCount() > 0) {
$sql_update = "UPDATE watched_requisitions
SET watched = $is_watched
WHERE user_id = $watched_user_id AND req_id = $watched_req_id AND object_id = $watched_obj_id";
mysql_query($sql_update);
} else {
$sql_insert = "INSERT INTO watched_requisitions (user_id, req_id, object_id, watched)
VALUES ($watched_user_id, $watched_req_id, $watched_obj_id, $is_watched)";
$pdo->query($sql_insert);
}
echo json_encode(['status' => 'success', 'watched' => $is_watched]);
}
}
public function checkRequisitionOwner($app, $get = null, $post = null) {
$requisition_id = (int)$app->request->get('requisition_id');
$response = ['has_owner' => false, 'owner_name' => ''];
if ($requisition_id > 0) {
$pdo = $app->container->get('mypdo');
$sql = "SELECT u.first_name, u.last_name, u.middle_name
FROM requisitions r
JOIN users u ON r.who_work = u.id
WHERE r.id = $requisition_id AND r.who_work > 0";
$result = $pdo->query($sql);
if ($pdo->num_rows($result) > 0) {
$row = $pdo->fetch_assoc($result);
$response['has_owner'] = true;
$response['owner_name'] = trim($row['last_name'] . ' ' . $row['first_name'] . ' ' . $row['middle_name']);
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode($response, JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function setRequisitionTransfers($app, $get = null, $post = null) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode(stripslashes($body), true);
$requisitions_ids = $data['requisitions_ids'];
if (!is_array($requisitions_ids) && !empty($requisitions_ids))
$requisitions_ids = [intval($requisitions_ids)];
if (($user_id = $_SESSION['id']) && is_array($requisitions_ids)) {
$employee_id = $user_id;
if (isset($data['employee_id']))
$employee_id = intval($data['employee_id']);
if($employee_id == -1)
$employee_id = 0;
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
$cancel_transfer = (bool)$data['cancel_transfer'];
if (!$cancel_transfer) {
if (count($requisitions_ids) > 0) {
$new_who_work = $employee_id;
$sql = "SELECT * FROM requisitions WHERE id in (".implode(',', $requisitions_ids).")";
$query = $pdo->query($sql);
while($row = $pdo->fetch_assoc($query)) {
$confirm = 0;
if ($new_who_work == $user_id)
$confirm = 1;
$sql = "UPDATE requisitions SET who_work='{$new_who_work}', confirm={$confirm} WHERE id=".$row['id'];
if ($pdo->query($sql)) {
if ($confirm) {
$sql2 = "UPDATE `clients`
JOIN `requisitions` AS `req` ON
`clients`.`id` = `req`.`client_id` AND
`clients`.`who_work` = 0 AND
`clients`.`confirm` = 0 AND
`req`.`id` = '$row[id]' AND
`clients`.`who_work` = 0 AND
`clients`.`confirm` = 0
SET `clients`.`who_work` = '$new_who_work',
`clients`.`confirm` = 1";
if (!$pdo->query($sql2)) {
$error = true;
$errors[] = $pdo->db->error();
}
}
} else {
$error = true;
$errors[] = $pdo->db->error();
}
if ($confirm == 1) {
$sqlup = "UPDATE user_client_events SET user_id=".$new_who_work." WHERE req_id=".$row['id']." and `type` != 'step' and `type` != 'file'";
if (!$pdo->query($sqlup)) {
$error = true;
$errors[] = $pdo->db->error();
}
} else if ($confirm == 0) {
$sql_conf = "INSERT INTO `events_clients` (`user_id`, `req_id`, `from_id`, `event`) VALUES (".$user_id.", ".$row['id'].", ".$new_who_work.", 'transmitted')";
if (!$pdo->query($sql_conf)) {
$error = true;
$errors[] = $pdo->db->error();
}
if($new_who_work == 0){
if (!$pdo->query("UPDATE requisitions SET deleted=0 WHERE id=".$row['id'])){
$error = true;
$errors[] = $pdo->db->error();
}
$dop_text = "Переведена в общие";
$sql_ev = "INSERT INTO events_clients (req_id, event, dop_text, user_id) VALUES ({$row['id']}, 'update', '{$dop_text}', {$user_id})";
if (!$pdo->query($sql_ev)){
$error = true;
$errors[] = $pdo->db->error();
}
}
}
// Определяем историю как просмотренную, чтобы сбросить счётчик (если пользователь не открывал её перед передачей другому сотруднику)
$sql = "UPDATE `events_clients` SET `viewed` = 1 WHERE `req_id` = ".$row['id']." AND `user_id` = '$user_id' AND `from_id` = '$user_id' AND (`event` = 'accepted' OR `event` = 'accepted_doer')";
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
}
} else {
$error = true;
}
}
if (count($errors))
$error = true;
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function setRequisitionTakeFromClosed($app, $get = null, $post = null) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode(stripslashes($body), true);
$requisitions_ids = $data['requisitions_ids'];
$user_id = $_SESSION['id'];
if (is_array($requisitions_ids)) {
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
$sql_check_permissions = "SELECT * FROM user_permissions WHERE user_id = $user_id";
$query_check_permissions = $pdo->query($sql_check_permissions);
$r_check_permissions = $pdo->fetch_assoc($query_check_permissions);
if (count($requisitions_ids) > 0) {
$available = $r_check_permissions['daily_closed_req_limit'] - $r_check_permissions['actual_daily_closed_req'];
if (count($requisitions_ids) > $available) {
$error = true;
$errors[] = "Превышен лимит. Можно взять только {$available} заявок.";
} else {
$sql = "SELECT * FROM requisitions WHERE id in (" . implode(',', $requisitions_ids) . ")";
$query = $pdo->query($sql);
while ($row = $pdo->fetch_assoc($query)) {
$sql = "UPDATE requisitions SET deleted=0, reason='', confirm = 1, who_work=$user_id, who_delete=NULL WHERE id=" . $row['id'];
if (!$pdo->query($sql)) {
$error = true;
$errors[] = $pdo->db->error();
}
$sql_2 = "INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`) VALUES ('" . $user_id . "', '" . $row['id'] . "', '" . $user_id . "', 'taken_from_closed', '1')";
if (!$pdo->query($sql_2)) {
$error = true;
$errors[] = $pdo->db->error();
}
}
$sql_counter = "UPDATE user_permissions SET actual_daily_closed_req = actual_daily_closed_req + " . count($requisitions_ids) . " WHERE user_id = $user_id";
if (!$pdo->query($sql_counter)) {
$error = true;
$errors[] = $pdo->db->error();
}
}
} else {
$error = true;
}
if (count($errors))
$error = true;
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
} 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();
}
}
$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 setRequisitionClose($app, $get = null, $post = null) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode(stripslashes($body), true);
$requisitions_ids = [];
if (isset($data['requisitions_ids']))
$requisitions_ids = $data['requisitions_ids'];
if (!is_array($requisitions_ids) && !empty($requisitions_ids))
$requisitions_ids = [intval($requisitions_ids)];
$denial = null;
if (isset($data['denial']))
$denial = intval($data['denial']);
$comment = null;
if (isset($data['comment']))
$comment = trim($data['comment']);
$is_deal = null;
if (isset($data['is_deal']))
$is_deal = boolval($data['is_deal']);
$commission = null;
if (isset($data['commission']))
$commission = intval($data['commission']);
$deal_date = null;
if (isset($data['deal_date']))
$deal_date = trim($data['deal_date']);
if (($user_id = $_SESSION['id']) && is_array($requisitions_ids)) {
$requisitions_ids = array_unique($requisitions_ids);
// Открываем соединение с БД
//$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
$req_inst = new \Requisitions($pdo);
if (count($requisitions_ids)) {
foreach($requisitions_ids as $requisition_id) {
if ($requisition_id) {
$req_inst->deleteReq($requisition_id, $user_id, [
'id_del_client',
'reason' => $comment,
'req_id' => $requisition_id,
'tempid' => 0,
'luck' => ($is_deal) ? 10 : 0,
'denial' => $denial,
'summa' => isset($data['summa']) ? intval($data['summa']) : $commission,
'commission' => $commission,
'deal_date' => $deal_date,
]);
}
}
}
if (count($errors))
$error = true;
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function setRequisitionRestored($app, $get = null, $post = null) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode(stripslashes($body), true);
$requisitions_ids = [];
if (isset($data['requisitions_ids']))
$requisitions_ids = $data['requisitions_ids'];
if (!is_array($requisitions_ids) && !empty($requisitions_ids))
$requisitions_ids = [intval($requisitions_ids)];
if (($user_id = $_SESSION['id']) && is_array($requisitions_ids)) {
// Открываем соединение с БД
//$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
if (count($requisitions_ids)) {
foreach($requisitions_ids as $requisition_id) {
if ($requisition_id) {
$req_inst = new \Requisitions($pdo);
$results = $req_inst->renewReq($requisition_id, $user_id);
if (!($results === true))
$errors = $results;
}
}
}
if (count($errors))
$error = true;
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function deleteRequisition($app, $get = null, $post = null) {
$error = false;
$errors = [];
$requisition_id = null;
if (isset($get['requisition_id']))
$requisition_id = (int)$get['requisition_id'];
if (($user_id = $_SESSION['id']) && !is_null($requisition_id)) {
// Открываем соединение с БД
//$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
$req_inst = new \Requisitions($pdo);
$results = $req_inst->cancelReq($requisition_id);
if ($results !== true)
$errors[] = $results;
if (count($errors))
$error = true;
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getFunnels($app, $get = null, $post = null) {
$start_time = microtime(true);
$error = false;
if ($user_id = $_SESSION['id']) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$user = new \User();
$user->checkPermissions($user_id, false);
$agency_id = $user->agency_id;
$section = $get['section'];
$filter = $get['filter'];
$useCustomFunnel = boolval($get['use_custom']);
if (!in_array($agency_id, [6841, 6426, 7384, 7478, 8353, 8867, 9588]))
$useCustomFunnel = true;
$_SESSION['new_transfers']['clients'] = null;
$_SESSION['new_transfers']['requisitions'] = null;
$funnels = [];
$counts = [];
if ($section == 'clients'/* && ($filter['stage_work'] || $filter['stage_hot'])*/) {
$bd_stage = "";
if ($filter['stage_work']) {
if ($filter['confirm'] || $filter['stage_send']) {
$bd_stage = " AND `clients`.`deleted` <> '1'";
} else {
$bd_stage = " AND `clients`.`deleted` <> '1' AND `clients`.`confirm` > 0";
}
}
if ($filter['stage_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 '%&quot;".$user_id."&quot;: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 '%&quot;".$user_id."&quot;: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 '%&quot;".$user_id."&quot;: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 '%&quot;".$user_id."&quot;:1%') AND
`clients`.`funnel_id` = `funnel`.`id` AND
`funnel`.`agency_id` = '$agency_id' AND `funnel`.`deleted` = 0";
} else if ($section == 'requisitions'/* && ($filter['stage_work'] || $filter['stage_hot'])*/) {
$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 '%&quot;".$user_id."&quot;: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 '%&quot;".$user_id."&quot;: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 '%&quot;".$user_id."&quot;: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 '%&quot;".$user_id."&quot;:1%') AND
`req`.`funnel_id` = `funnel`.`id` AND
`funnel`.`agency_id` = '$agency_id' AND `funnel`.`deleted` = 0";
} else {
// ...
}
$new_ids = [];
if (!($res1 = mysql_query($sql1)))
$error = true;
if (mysql_num_rows($res1)) {
while($counter = mysql_fetch_assoc($res1)) {
$counts[$counter['funnel_id']] = $counter['count'];
}
}
if (!($res1_list = mysql_query($sql1_list)))
$error = true;
if (mysql_num_rows($res1_list)) {
while($row = mysql_fetch_assoc($res1_list)) {
$new_ids[] = $row['id'];
}
}
if (!($res2 = mysql_query($sql2)))
$error = true;
if (mysql_num_rows($res2)) {
while($counter = mysql_fetch_assoc($res2)) {
$counts[$counter['funnel_id']] = $counter['count'];
}
}
if (!($res2_list = mysql_query($sql2_list)))
$error = true;
if (mysql_num_rows($res2_list)) {
while($row = mysql_fetch_assoc($res2_list)) {
$new_ids[] = $row['id'];
}
}
if (count($new_ids) > 0) {
if (($section == 'clients'))
$_SESSION['new_transfers']['clients'] = $new_ids;
else if (($section == 'requisitions'))
$_SESSION['new_transfers']['requisitions'] = $new_ids;
}
if ($useCustomFunnel || $_SESSION['agency_id'] == 8353) {
$funnels[] = [
'value' => 0,
'name' => 'Обычные',
'count' => intval($counts[0]),
'stages' => [
'1' => [
'value' => 1,
'name' => 'Новый',
],
'2' => [
'value' => 2,
'name' => 'В работе',
],
'3' => [
'value' => 3,
'name' => 'Презентация',
],
'4' => [
'value' => 4,
'name' => 'Показ',
],
'5' => [
'value' => 5,
'name' => 'Бронь',
],
'6' => [
'value' => 6,
'name' => 'Подаем на ипотеку',
],
'7' => [
'value' => 7,
'name' => 'Сделка',
],
'8' => [
'value' => 8,
'name' => 'Закрыт',
],
]
];
}
$sql = "SELECT * FROM `funnel`
WHERE `agency_id` = '$agency_id' AND `deleted`= 0
ORDER BY `id`";
if (!($data = mysql_query($sql)))
$error = true;
$i = 0;
while($funnel = mysql_fetch_assoc($data)) {
$funnel_id = intval($funnel['id']);
$funnels[$funnel_id] = [
'value' => intval($funnel_id),
'name' => $funnel['name'],
'count' => intval($counts[$funnel['id']]),
'stages' => []
];
$i++;
}
$sql = "SELECT `id`, `name`, `main`, `funnel_id`
FROM `funnel_steps`
WHERE `funnel_id` IN (".implode(',', array_keys($funnels)).") AND `deleted` = 0";
if (!($data = mysql_query($sql)))
$error = true;
while($step = mysql_fetch_assoc($data)) {
$funnel_id = intval($step['funnel_id']);
$step_id = intval($step['id']);
$funnels[$funnel_id]['stages'][$step_id] = [
'value' => $step_id,
'name' => $step['name'],
'is_main' => boolval($step['main']),
];
$i++;
}
$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($funnels),
'list' => $funnels,
'overage_time' => round((microtime(true) - $start_time), 3) . " sec.",
], 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,
'overage_time' => round((microtime(true) - $start_time), 3) . " sec.",
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function checkObject($app, $get = null, $post = null) {
/*ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);*/
//var_dump($_SESSION['id']);
if ($user_id = $_SESSION['id']) {
$res = [];
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
//die("2");
$user = new \User();
$user->get($user_id);
$object_id = 0;
if(isset($get['object_id'])){
$object_id = (int)$get['object_id'];
}
// $req_id = 0;
// $agency_id = $user->agencyId;
// $filtr = (object) array('object_id'=>$object_id, 'type' => [2]);
// if ($req_id > 0) {
// $filtr = (object) array('object_id'=>$req_id, 'not_id'=>$req_id, 'type' => [2]);
// }
$res['result'] = 'done';
//$req = new \Requisitions($pdo, true);
//$search = $req->get_all($agency_id, $filtr, false, false, false, false);
$sql_check_exist_object_in_req = "SELECT * FROM requisitions WHERE object_id = {$object_id}";
$sql_check_exist_object_in_req .= " LIMIT 1";
$q_check_exist_object_in_req = mysql_query($sql_check_exist_object_in_req);
$search = mysql_fetch_assoc($q_check_exist_object_in_req);
if (!empty($search)) {
$res['result'] = 'error';
$res['mes'] = "Этот объект уже добавлен в заявку";
$keys = array_keys($search['req']);
$firstKey = $keys[0];
if (isset($search[$firstKey]['name'])) {
$res['mes'] .= " &laquo;".$search[$firstKey]['name']."&raquo;";
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'res' => $res,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function transferClosedRequisitions($app, $get = null, $post = null) {
$body = $app->request->getBody();
$data = json_decode($body, true);
$reqs = isset($data['reqs_id']) ? $data['reqs_id'] : [];
$user_id = (int)(isset($_SESSION['id']) ? $_SESSION['id'] : 0);
$new_who_work = (int)(isset($data['to_user_id']) ? $data['to_user_id'] : 0);
$all = (int)(isset($data['all']) ? $data['all'] : 0);
$ids = isset($data['ids_exception']) ? $data['ids_exception'] : [];
if ($user_id <= 0) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(401);
$app->response->setBody(json_encode([
'success' => false,
'error' => 'Пользователь не авторизован'
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
$sql_check_permissions = "SELECT `menu_can_transfer_closed_to_others`, `daily_closed_transfer_limit`, `actual_daily_closed_transfers`
FROM user_permissions WHERE user_id = $user_id";
$q_check_permissions = mysql_query($sql_check_permissions);
$r_check_permissions = mysql_fetch_assoc($q_check_permissions);
$can_transfer = ($_SESSION['users_admin'] == 1) || ($_SESSION['agency'] == 1) || ($r_check_permissions['menu_can_transfer_closed_to_others'] == 1);
if (!$can_transfer) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'error' => 'Недостаточно прав для передачи закрытых заявок.',
'debug' => [
'is_admin' => $_SESSION['users_admin'],
'is_agency' => $_SESSION['agency'],
'can_transfer_closed' => $r_check_permissions['menu_can_transfer_closed_to_others'],
'user_id' => $user_id,
'r_check_permissions' => $r_check_permissions
]
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
// Проверка лимита
if (!$_SESSION['users_admin'] && !$_SESSION['agency']) {
$daily_limit = (int)$r_check_permissions['daily_closed_transfer_limit'];
$actual_transfer = (int)$r_check_permissions['actual_daily_closed_transfers'];
if ($actual_transfer >= $daily_limit) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'error' => "Превышен дневной лимит передачи закрытых заявок: {$daily_limit} шт."
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
if (empty($reqs) && $all == 0) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'error' => 'Список заявок для передачи пуст.'
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$sql = "SELECT * FROM requisitions
WHERE id IN (" . implode(',', $reqs) . ") AND deleted = 1
ORDER BY FIELD(id, " . implode(',', $reqs) . ")";
if($all == 1){
if(isset($_SESSION['where_req_campaigns'])){
$sql = $_SESSION['where_req_campaigns'] . " AND deleted = 1";
if (!empty($ids)){
$sql .= " AND ID NOT IN (".implode(',', $ids).")";
}
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'error' => 'Ошибка фильтрации.'
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$q = mysql_query($sql);
$transferred_count = 0;
$remaining_limit = (int)$r_check_permissions['daily_closed_transfer_limit'] - (int)$r_check_permissions['actual_daily_closed_transfers'];
// ФИО отправителя
$sql_sender = "SELECT last_name, first_name, middle_name FROM users WHERE id = $user_id LIMIT 1";
$q_sender = mysql_query($sql_sender);
$r_sender = mysql_fetch_assoc($q_sender);
$sender_fio = $r_sender ? trim("{$r_sender['last_name']} {$r_sender['first_name']} {$r_sender['middle_name']}") : "Неизвестный пользователь";
// ФИО получателя
$sql_recipient = "SELECT last_name, first_name, middle_name FROM users WHERE id = $new_who_work LIMIT 1";
$q_recipient = mysql_query($sql_recipient);
$r_recipient = mysql_fetch_assoc($q_recipient);
$recipient_fio = $r_recipient ? trim("{$r_recipient['last_name']} {$r_recipient['first_name']} {$r_recipient['middle_name']}") : "Неизвестный пользователь";
while($r = mysql_fetch_assoc($q)) {
if (!$_SESSION['users_admin'] && !$_SESSION['agency'] && $remaining_limit <= 0) {
break;
}
if ($r['funnel_id'] > 0) {
$sql_update = "UPDATE requisitions SET who_work = {$new_who_work}, deleted = 0, step_id = 1 WHERE id = {$r['id']}";
} else {
$sql_update = "UPDATE requisitions SET who_work = {$new_who_work}, deleted = 0, stage = 1 WHERE id = {$r['id']}";
}
if (mysql_query($sql_update)) {
$transferred_count++;
// Логируем событие
$dop_text = "Закрытая заявка передана в работу сотруднику {$recipient_fio} сотрудником {$sender_fio}";
$sql_log = "INSERT INTO events_clients (req_id, event, dop_text, user_id, from_id, `read`)
VALUES ({$r['id']}, 'transfer_closed', '" . mysql_real_escape_string($dop_text) . "', {$new_who_work}, {$user_id}, 1)";
mysql_query($sql_log);
// Обновляем счётчик лимита (если не админ)
if (!$_SESSION['users_admin'] && !$_SESSION['agency']) {
$sql_update_limit = "UPDATE user_permissions
SET actual_daily_closed_transfers = actual_daily_closed_transfers + 1
WHERE user_id = {$user_id}";
mysql_query($sql_update_limit);
$remaining_limit--;
}
}
}
$not_transferred = count($reqs) - $transferred_count;
$message = "Успешно передано {$transferred_count} заявок.";
if ($not_transferred > 0) {
$message .= " {$not_transferred} заявок не были переданы из-за ограничения.";
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'message' => $message,
'transferred_count' => $transferred_count,
'notification_data' => [
'sender_user_id' => $user_id,
'recipient_user_id' => $new_who_work,
'transferred_req_ids' => $reqs,
'transferred_count' => $transferred_count,
'all' => $all,
'ids_exception' => $ids,
'actual_after' => !$_SESSION['users_admin'] && !$_SESSION['agency'] ? ((int)$r_check_permissions['actual_daily_closed_transfers'] + $transferred_count) : null,
'limit_after' => !$_SESSION['users_admin'] && !$_SESSION['agency'] ? (int)$r_check_permissions['daily_closed_transfer_limit'] : null,
]
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function sendTransferClosedNotifications($app, $get = null, $post = null) {
$body = $app->request->getBody();
$data = json_decode($body, true);
// Извлекаем данные из запроса
$sender_user_id = (int)(isset($data['sender_user_id']) ? $data['sender_user_id'] : 0);
$recipient_user_id = (int)(isset($data['recipient_user_id']) ? $data['recipient_user_id'] : 0);
$transferred_req_ids = isset($data['transferred_req_ids']) ? $data['transferred_req_ids'] : [];
$all = (int)(isset($data['all']) ? $data['all'] : 0);
$ids_exception = isset($data['ids_exception']) ? $data['ids_exception'] : [];
$actual_after = isset($data['actual_after']) ? $data['actual_after'] : null;
$limit_after = isset($data['limit_after']) ? $data['limit_after'] : null;
// Проверка обязательных параметров
if ($sender_user_id <= 0 || $recipient_user_id <= 0) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(400);
$app->response->setBody(json_encode([
'success' => false,
'error' => 'Некорректные ID пользователей'
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
// Получаем ФИО отправителя
$sql_sender = "SELECT CONCAT(last_name, ' ', first_name, ' ', middle_name) as fio FROM users WHERE id = $sender_user_id LIMIT 1";
$result_sender = mysql_query($sql_sender);
$sender_data = mysql_fetch_assoc($result_sender);
$sender_fio = isset($sender_data['fio']) ? $sender_data['fio'] : 'Сотрудник';
// Получаем данные получателя (нового ответственного)
$sql_recipient = "SELECT telegramm_chat_id, max_user_id, max_notice CONCAT(last_name, ' ', first_name, ' ', middle_name) as fio FROM users WHERE id = $recipient_user_id LIMIT 1";
$result_recipient = mysql_query($sql_recipient);
$recipient = mysql_fetch_assoc($result_recipient);
$transferred_count = isset($data['transferred_count']) ? (int)$data['transferred_count'] : count($transferred_req_ids);
// ID переданных заявок для уведомления (если <= 10)
$transferred_req_ids_for_msg = [];
if ($transferred_count <= 10) {
$sql_ids = "SELECT id FROM requisitions WHERE who_work = $recipient_user_id AND id IN (" . implode(',', $transferred_req_ids) . ") AND deleted = 0 ORDER BY id DESC LIMIT 10";
if ($all == 1 && isset($_SESSION['where_req_campaigns'])) {
$sql_ids = $_SESSION['where_req_campaigns'] . " AND deleted = 0 AND who_work = $recipient_user_id ORDER BY id DESC LIMIT 10";
if (!empty($ids_exception)) {
$sql_ids .= " AND ID NOT IN (" . implode(',', $ids_exception) . ")";
}
}
$q_ids = mysql_query($sql_ids);
while ($row_id = mysql_fetch_assoc($q_ids)) {
$transferred_req_ids_for_msg[] = $row_id['id'];
}
}
// Сообщение новому ответственному
if ($recipient && !empty($recipient['telegramm_chat_id']) && $recipient['telegramm_chat_id'] > 0) {
$message_to_recipient = "Сотрудник {$sender_fio} передал вам ";
if ($transferred_count == 1) {
$message_to_recipient .= "1 заявку из Закрытых";
} else {
$message_to_recipient .= "{$transferred_count} заявки из Закрытых";
}
if ($transferred_count <= 10 && !empty($transferred_req_ids_for_msg)) {
$message_to_recipient .= ": " . implode(', ', $transferred_req_ids_for_msg);
}
$tel = new \Telegram(false);
try {
$tel->send($message_to_recipient, $recipient['telegramm_chat_id']);
} catch (\Exception $e) {
// Логируем ошибку, но не прерываем выполнение
error_log("Ошибка отправки Telegram-уведомления получателю: " . $e->getMessage());
}
}
// Уведомление новому ответственному (с ID, если <= 10, без ID если > 10) в макс
if ($recipient && !empty($recipient['max_user_id']) && $recipient['max_user_id'] > 0 && $recipient['max_notice'] > 0) {
$message_to_recipient = "Сотрудник {$sender_fio} передал вам ";
if ($transferred_count == 1) {
$message_to_recipient .= "1 заявку из Закрытых";
} else {
$message_to_recipient .= "{$transferred_count} заявки из Закрытых";
}
// Добавляем ID, только если их <= 10
if ($transferred_count <= 10 && !empty($transferred_req_ids_for_msg)) {
$message_to_recipient .= ": " . implode(', ', $transferred_req_ids_for_msg);
}
$max = new \MaxClass();
try {
$max->send_messages_to_user($recipient['max_user_id'], $message_to_recipient);
} catch (\Exception $e) {
file_put_contents(__DIR__ . '/debug_max.txt', "Max error: " . $e->getMessage() . "\n", FILE_APPEND);
}
}
// Уведомление директору/админу, если лимит исчерпан
if ($actual_after !== null && $limit_after !== null && $actual_after >= $limit_after) {
$send_agency_id = (int)$_SESSION['agency_id'];
$sql_admin = "SELECT telegramm_chat_id FROM users WHERE id = $send_agency_id AND telegramm_chat_id > 0 LIMIT 1";
$result_admin = mysql_query($sql_admin);
$admin = mysql_fetch_assoc($result_admin);
if ($admin && !empty($admin['telegramm_chat_id'])) {
$message_to_admin = "Сотрудник {$sender_fio} передал за сегодня {$actual_after} заявок из Закрытых";
$tel = new \Telegram(false);
try {
$tel->send($message_to_admin, $admin['telegramm_chat_id']);
} catch (\Exception $e) {
file_put_contents(__DIR__ . '/debug_telegram.txt', "Telegram error: " . $e->getMessage() . "\n", FILE_APPEND);
}
}
}
// Уведомление директору/админу, если лимит исчерпан в макс
if ($actual_after !== null && $limit_after !== null && $actual_after >= $limit_after) {
$send_agency_id = (int)$_SESSION['agency_id'];
$sql_admin = "SELECT max_user_id FROM users WHERE id = $send_agency_id AND max_user_id > 0 AND max_notice > 0 LIMIT 1";
$result_admin = mysql_query($sql_admin);
$admin = mysql_fetch_assoc($result_admin);
if ($admin && !empty($admin['max_user_id'])) {
$message_to_admin = "Сотрудник {$sender_fio} передал за сегодня {$actual_after} заявок из Закрытых";
$max = new \MaxClass();
try {
$max->send_messages_to_user($admin['max_user_id'], $message_to_admin);
} catch (\Exception $e) {
file_put_contents(__DIR__ . '/debug_max.txt', "Max error: " . $e->getMessage() . "\n", FILE_APPEND);
}
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'message' => 'Уведомления отправлены'
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function editFinanceRequisition($app, $get = null, $post = null){
$body = $app->request->getBody();
$data = json_decode($body, true);
$userId = (int)(isset($_SESSION['id']) ? $_SESSION['id'] : 0);
$reqId = (int)$data['req_id'];
$depositId = 0;
if(isset($data['deposit_id'])){
$depositId = (int)$data['deposit_id'];
}
$expenseId = 0;
if(isset($data['expense_id'])){
$expenseId = (int)$data['expense_id'];
}
$comment = '';
if(isset($data['comment'])){
$comment = $data['comment'];
$result = preg_replace('/"([^"]*)"/', '«$1»', $comment);
$result = str_replace("\"", "", $result);
$result = str_replace("'", "", $result);
$comment = $result;
}
$field = $data['field'];
$value = $data['value'];
if ($userId <= 0) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(401);
$app->response->setBody(json_encode([
'success' => false,
'error' => 'Пользователь не авторизован'
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
$sql_req = "SELECT expected_commission, id, who_work FROM requisitions WHERE id = {$reqId}";
$q_req = $pdo->query($sql_req);
$r_req = $pdo->fetch_assoc($q_req);
if($field == 'expected_commission'){
$text_commission = '';
if ($r_req['expected_commission'] != $value) {
$text_commission = "Изменено: Ожидаемая комиссия с {$r_req['expected_commission']} на {$value}";
$sql_up = "UPDATE requisitions SET expected_commission = {$value} WHERE id = {$reqId}";
if($pdo->query($sql_up)) {
$sql_event = "INSERT INTO events_clients (user_id, from_id, req_id, `event`, dop_text, `read`) VALUES ({$userId}, {$userId}, {$reqId}, 'update', '{$text_commission}', 1)";
$pdo->query($sql_event);
}
}
}
if($field == 'deposit'){
$who_work = $userId;
$nameEvent = "Аванс";
if($r_req['who_work'] > 0){
$who_work = (int)$r_req['who_work'];
}
$sql_d = "SELECT id, deposit, step_id FROM deposits_clients_req WHERE id = {$depositId}";
$q_d = $pdo->query($sql_d);
$deposit = (int)$value;
if($pdo->num_rows($q_d) > 0){
$r_d = $pdo->fetch_assoc($q_d);
$sql_step = "SELECT * FROM `funnel_steps` WHERE id = {$r_d['step_id']}";
$q_step = $pdo->query($sql_step);
$r_step = $pdo->fetch_assoc($q_step);
$pole_end_list = json_decode(htmlspecialchars_decode($r_step['pole_end_list']), true);
foreach($pole_end_list as $pole){
if($pole['type'] == 'Задаток'){
$nameEvent = $pole['name'];
}
}
$id_d = (int)$r_d['id'];
$sql_up_d = "UPDATE deposits_clients_req SET deposit = {$deposit}, created_at= NOW(), user_id={$who_work} WHERE id = {$id_d}";
$pdo->query($sql_up_d);
if((int)$r_d['deposit'] != $deposit){
$text_deposit = "Изменено: {$nameEvent} с {$r_d['deposit']} на {$deposit}";
$sql_event = "INSERT INTO events_clients (user_id, from_id, req_id, `event`, dop_text, `read`) VALUES ({$userId}, {$userId}, {$reqId}, 'update', '{$text_deposit}', 1)";
$pdo->query($sql_event);
}
}
}
if($field == 'expense'){
$who_work = $userId;
$nameEvent = "Расходы";
$sql_d = "SELECT * FROM expenses_req WHERE id = {$expenseId}";
$q_d = $pdo->query($sql_d);
$expense = (int)$value;
if($pdo->num_rows($q_d) > 0){
$r_d = $pdo->fetch_assoc($q_d);
$sql_step = "SELECT * FROM `funnel_steps` WHERE id = {$r_d['step_id']}";
$q_step = $pdo->query($sql_step);
$r_step = $pdo->fetch_assoc($q_step);
$pole_end_list = json_decode(htmlspecialchars_decode($r_step['pole_end_list']), true);
foreach($pole_end_list as $pole){
if($pole['type'] == 'Расходы'){
$nameEvent = $pole['name'];
}
}
$sql_up_d = "UPDATE expenses_req SET amount = '{$expense}', comment = '{$comment}' WHERE id = {$expenseId}";
$pdo->query($sql_up_d);
if((int)$r_d['amount'] != $expense){
$text_expense = "Изменено: {$nameEvent} с {$r_d['amount']} на {$expense}";
if(!empty($comment)){
$text_expense .= " Добавлен комментарий: ".$comment;
}
$sql_event = "INSERT INTO events_clients (user_id, from_id, req_id, `event`, dop_text, `read`) VALUES ({$userId}, {$userId}, {$reqId}, 'update', '{$text_expense}', 1)";
$pdo->query($sql_event);
}
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'field ' => $field
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
/**
* Установка новой воронки
*/
public function funnel_change($app, $get = null, $post = null){
$body = $app->request->getBody();
$data = json_decode($body, true);
$userId = (int)(isset($_SESSION['id']) ? $_SESSION['id'] : 0);
$reqId = (int)$data['req_id'];
$funnel_id = (int)$data['funnel_id'];
if ($userId <= 0) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(401);
$app->response->setBody(json_encode([
'success' => false,
'error' => 'Пользователь не авторизован'
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
$req = new \Requisitions($pdo);
$req->updateFunnel($funnel_id, $reqId);
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'funnel_id ' => $funnel_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
// POST /api/v2/requisitions/copy-preview — дефолты модалки + embed funnels/employees (1 round-trip для mJW).
public function copyPreview($app, $get = null, $post = null, $need_return = false) {
$body = $app->request->getBody();
$data = json_decode($body, true);
$user_id = isset($_SESSION['id']) ? (int)$_SESSION['id'] : 0;
if ($user_id <= 0) {
$app->response->setStatus(401);
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode(['success' => false, 'error' => 'unauthorized'], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$srcId = isset($data['req_id']) ? (int)$data['req_id'] : 0;
if ($srcId <= 0) {
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode(['success' => false, 'error' => 'Заявка обязательна'], JSON_UNESCAPED_UNICODE));
$app->stop();
}
// mysql-сервис нужен: User::getAll* используют mysql_*.
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
$src = mysql_fetch_assoc(mysql_query("SELECT * FROM requisitions WHERE id = {$srcId} LIMIT 1"));
if (!$src) {
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode(['success' => false, 'error' => 'Заявка не найдена'], JSON_UNESCAPED_UNICODE));
$app->stop();
}
if ((int)$src['deleted'] === 1) {
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode(['success' => false, 'error' => 'Заявка удалена'], JSON_UNESCAPED_UNICODE));
$app->stop();
}
// set_user — для checkMenuPermissions внутри user_can_edit_req.
$req = new \Requisitions($pdo);
$userForCheck = new \User();
$userForCheck->checkPermissions();
$req->set_user($userForCheck);
if (!$req->user_can_edit_req($src, $user_id)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode(['success' => false, 'error' => 'Нет прав на копирование'], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$srcTypeId = (int)$src['type_id'];
$typeRow = mysql_fetch_assoc(mysql_query("SELECT id, heir FROM requisitions_type WHERE id = {$srcTypeId} LIMIT 1"));
$baseTypeId = $typeRow ? requisition_base_type_id($typeRow) : 0;
// warning contract_without_object — object_id не копируется, но у исходника есть договор продажи.
$warnings = array();
if (!requisition_should_copy_object($baseTypeId) && (int)$src['object_id'] > 0) {
$hasSaleContract = mysql_fetch_assoc(
mysql_query("SELECT id FROM contracts_req WHERE req_id = {$srcId} AND type = 2 LIMIT 1")
);
if ($hasSaleContract) {
$warnings[] = 'contract_without_object';
}
}
// Канонический источник воронок: Funnel::get_funnels (включает дефолт id=0 и visibility).
$userAgency = (int)$_SESSION['agency_id'];
$funnelClass = new \Funnel($pdo);
$funnelClass->set_agency_id($userAgency);
$funnelClass->set_user_id($user_id);
$funnelsRaw = $funnelClass->get_funnels('requisitions');
$funnels = array();
if (is_array($funnelsRaw)) {
foreach ($funnelsRaw as $rF) {
$funnels[] = array(
'id' => (int)$rF['id'],
'name' => (isset($rF['name']) && $rF['name'] !== null && $rF['name'] !== '')
? (string)$rF['name']
: 'Обычные',
);
}
}
// Сотрудники: Я + «Всё агентство» (если разрешено) + менеджеры + агенты.
$employees = array(array('id' => $user_id, 'name' => 'Я'));
$r_perm = mysql_fetch_assoc(
mysql_query("SELECT menu_can_transfer_to_common FROM user_permissions WHERE user_id = {$user_id} LIMIT 1")
);
if (
!empty($_SESSION['agency'])
|| !empty($_SESSION['users_admin'])
|| ($r_perm && (int)$r_perm['menu_can_transfer_to_common'] === 1)
) {
$employees[] = array('id' => 0, 'name' => 'Всё агентство');
}
$managers = \User::getAllManagers($userAgency);
if ($managers) {
foreach ($managers as $m) {
$employees[] = array(
'id' => (int)$m['id'],
'name' => trim($m['last_name'] . ' ' . $m['first_name'] . ' ' . $m['middle_name']),
'group' => 'Менеджеры',
);
}
}
$agents = \User::getAllAgents($userAgency);
if ($agents) {
foreach ($agents as $a) {
$employees[] = array(
'id' => (int)$a['id'],
'name' => trim($a['last_name'] . ' ' . $a['first_name'] . ' ' . $a['middle_name']),
'group' => 'Агенты',
);
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode(array(
'success' => true,
'default_funnel_id' => (int)$src['funnel_id'],
'default_who_work_id' => (int)$src['who_work'],
'base_type_id' => $baseTypeId,
'warnings' => $warnings,
'funnels' => $funnels,
'employees' => $employees,
), JSON_UNESCAPED_UNICODE));
$app->stop();
}
// POST /api/v2/requisitions/copy — создание копии заявки.
public function copy($app, $get = null, $post = null, $need_return = false) {
$body = $app->request->getBody();
$data = json_decode($body, true);
$currentId = isset($_SESSION['id']) ? (int)$_SESSION['id'] : 0;
if ($currentId <= 0) {
$app->response->setStatus(401);
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode(['success' => false, 'error' => 'unauthorized'], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$srcId = isset($data['req_id']) ? (int)$data['req_id'] : 0;
$funnelId = isset($data['funnel_id']) ? (int)$data['funnel_id'] : 0;
$whoWorkId = isset($data['who_work_id']) ? (int)$data['who_work_id'] : 0;
$userAgency = (int)$_SESSION['agency_id'];
// funnel_id = 0 — дефолтная воронка (funnel_default).
if ($srcId <= 0 || $funnelId < 0 || $whoWorkId <= 0) {
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode(array(
'success' => false,
'error' => 'req_id, funnel_id, who_work_id обязательны',
'code' => 'bad_payload',
), JSON_UNESCAPED_UNICODE));
$app->stop();
}
// mysql-сервис нужен: legacy-SQL ниже + User::* внутри валидаций.
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
$src = mysql_fetch_assoc(mysql_query("SELECT * FROM requisitions WHERE id = {$srcId} LIMIT 1"));
if (!$src) {
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode(array(
'success' => false,
'error' => 'Заявка не найдена',
'code' => 'src_not_found',
), JSON_UNESCAPED_UNICODE));
$app->stop();
}
if ((int)$src['deleted'] === 1) {
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode(array(
'success' => false,
'error' => 'Заявка удалена',
'code' => 'src_not_found',
), JSON_UNESCAPED_UNICODE));
$app->stop();
}
// set_user — для checkMenuPermissions внутри user_can_edit_req.
$req = new \Requisitions($pdo);
$userForCheck = new \User();
$userForCheck->checkPermissions();
$req->set_user($userForCheck);
// Право на копирование == право на редактирование исходника.
if (!$req->user_can_edit_req($src, $currentId)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode(array(
'success' => false,
'error' => 'Нет прав на копирование',
'code' => 'no_edit_right',
), JSON_UNESCAPED_UNICODE));
$app->stop();
}
// Доступ к воронке. funnel_id=0 — проверяем funnel_default.is_req.
if ($funnelId === 0) {
$funnelDef = mysql_fetch_assoc(mysql_query(
"SELECT `is_req` FROM `funnel_default`
WHERE `agency_id` = {$userAgency}
LIMIT 1"
));
if ($funnelDef && (int)$funnelDef['is_req'] === 0) {
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode(array(
'success' => false,
'error' => 'Воронка недоступна',
'code' => 'funnel_forbidden',
), JSON_UNESCAPED_UNICODE));
$app->stop();
}
} else {
// Проверка доступности — через канонический Funnel::get_funnels() (учитывает is_no_see + раскрытие 'all_X').
$funnelCheckClass = new \Funnel($pdo);
$funnelCheckClass->set_agency_id($userAgency);
$funnelCheckClass->set_user_id($currentId);
$availableFunnels = $funnelCheckClass->get_funnels('requisitions');
$isFunnelAvailable = false;
if (is_array($availableFunnels)) {
foreach ($availableFunnels as $af) {
if ((int)$af['id'] === $funnelId) { $isFunnelAvailable = true; break; }
}
}
if (!$isFunnelAvailable) {
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode(array(
'success' => false,
'error' => 'Воронка недоступна',
'code' => 'funnel_forbidden',
), JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
// Ответственный. Себя всегда можно назначить.
if ($whoWorkId !== $currentId) {
if ($funnelId === 0) {
// user_can_be_responsible требует funnel_id > 0 — для дефолтной проверяем вручную (agency + blocked).
$candidateAgency = (int)\User::getUserAgencyID($whoWorkId);
if ($candidateAgency !== $userAgency) {
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode(array(
'success' => false,
'error' => 'Выбранный ответственный недоступен',
'code' => 'who_work_forbidden',
), JSON_UNESCAPED_UNICODE));
$app->stop();
}
$blockedRow = mysql_fetch_assoc(mysql_query(
"SELECT `blocked` FROM `users` WHERE `id` = {$whoWorkId} LIMIT 1"
));
if (!$blockedRow || (int)$blockedRow['blocked'] === 1) {
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode(array(
'success' => false,
'error' => 'Выбранный ответственный недоступен',
'code' => 'who_work_forbidden',
), JSON_UNESCAPED_UNICODE));
$app->stop();
}
} else if (!$req->user_can_be_responsible($whoWorkId, $userAgency, $funnelId)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode(array(
'success' => false,
'error' => 'Выбранный ответственный недоступен',
'code' => 'who_work_forbidden',
), JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$result = $req->copy($srcId, $funnelId, $whoWorkId, $currentId);
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode($result, JSON_UNESCAPED_UNICODE));
$app->stop();
}
}