2953 lines
125 KiB
PHP
2953 lines
125 KiB
PHP
<?php
|
||
require_once($_SERVER['DOCUMENT_ROOT']."/ajax/vue_php_function.php");
|
||
|
||
/*error_reporting(E_ALL | E_STRICT);
|
||
ini_set('display_errors', 1);*/
|
||
|
||
$data = json_decode(file_get_contents("php://input"));
|
||
$request = $data->request;
|
||
|
||
if($request == 'save_steps_client'){
|
||
$tempid = 0;
|
||
$userId = $data->user_id;
|
||
$stepId = $data->step_id;
|
||
$agency_id = $data->agency_id;
|
||
$stepName = $data->step_name;
|
||
$complexRoomId = $data->complex_room_id;
|
||
$complexStatusId = $data->complex_status_id;
|
||
$transactionAmount = $data->transaction_amount;
|
||
$selectedRoomName = $data->selected_room_name;
|
||
|
||
$clientId = 0;
|
||
if(isset($data->client_id)){
|
||
$clientId = $data->client_id;
|
||
}
|
||
$reqId = 0;
|
||
if(isset($data->req_id)){
|
||
$reqId = $data->req_id;
|
||
}
|
||
$adjacentId = 0;
|
||
if(isset($data->adjacent_id)){
|
||
$adjacentId = (int)$data->adjacent_id;
|
||
}
|
||
$funnelId = $data->funnel_id;
|
||
$next_step_select = $data->next_step_select;
|
||
$nextStep = $data->next_step;
|
||
$values = $data->values;
|
||
|
||
$activites_close_step_val = $data->activites_close_step_val;
|
||
$next_id = 0;
|
||
$stage = '';
|
||
$is_closet = $data->is_closet;
|
||
if(is_object($next_step_select)){
|
||
$next_id = $next_step_select -> id -> id;
|
||
}
|
||
|
||
$fields_models = $data->field_models;
|
||
$resVal = json_decode($values, true);
|
||
|
||
|
||
|
||
foreach($resVal as $key => $poles){
|
||
$resultName = preg_replace('/"([^"]*)"/', '«$1»', $poles['name']);
|
||
$resultName = str_replace("\"", "", $resultName);
|
||
$resultName = str_replace("'", "’", $resultName);
|
||
$resVal[$key]['name'] = $resultName;
|
||
if($poles['type'] == 'expenses'){
|
||
if(isset($poles['value']['comment']) && !empty($poles['value']['comment'])){
|
||
$result = preg_replace('/"([^"]*)"/', '«$1»', $poles['value']['comment']);
|
||
$result = str_replace("\"", "", $result);
|
||
$result = str_replace("'", "’", $result);
|
||
$resVal[$key]['value']['comment'] = $result;
|
||
}
|
||
}
|
||
}
|
||
|
||
$events_client = $resVal;
|
||
|
||
$date = time();
|
||
$create_at = date('Y-m-d H:i:s');
|
||
|
||
$history_requisition = [];
|
||
|
||
if ($reqId)
|
||
{
|
||
$sql = "SELECT `client_id`, `complex_room_id`, `complex_status_id`, `reservation_updated_at` FROM `requisitions` WHERE id = {$reqId}";
|
||
$requisition = mysql_fetch_assoc(mysql_query($sql));
|
||
$req_complex_room_id = $requisition['complex_room_id'];
|
||
$req_complex_status_id = $requisition['complex_status_id'];
|
||
$req_reservation_updated_at = $requisition['reservation_updated_at'];
|
||
|
||
$history_requisition = [
|
||
'step_id' => $stepId,
|
||
'complex_room_id' => $req_complex_room_id ?: 'NULL',
|
||
'complex_status_id' => $req_complex_status_id ?: 'NULL',
|
||
'reservation_updated_at' => $req_reservation_updated_at ?: 'NULL',
|
||
];
|
||
|
||
if ($complexRoomId)
|
||
{
|
||
mysql_query("UPDATE `requisitions` SET `complex_room_id` = $complexRoomId, `object_id` = 0 WHERE id = {$reqId}");
|
||
}
|
||
|
||
if ($complexStatusId)
|
||
{
|
||
mysql_query("UPDATE `requisitions` SET `complex_status_id` = $complexStatusId WHERE id = {$reqId}");
|
||
}
|
||
|
||
if ($complexRoomId && $complexStatusId)
|
||
{
|
||
$complexStatus = new ComplexStatus((int)$complexStatusId);
|
||
|
||
$create_date = (new DateTime("now"))->format('Y-m-d H:i:s');
|
||
|
||
if ($complexStatus->status === 'sold')
|
||
{
|
||
mysql_query("UPDATE `requisitions` SET `reservation_updated_at` = '{$create_date}' WHERE id = {$reqId}");
|
||
|
||
$complexStatus->updateRoomsStatus([
|
||
'new_status_id' => $complexStatusId,
|
||
'complex_room_id' => $complexRoomId
|
||
], false, false);
|
||
|
||
$sql = "SELECT
|
||
requisitions.`id` AS req_id,
|
||
requisitions.`client_id`,
|
||
users.*
|
||
FROM `requisitions`
|
||
LEFT JOIN `users` ON users.`id` = requisitions.`who_work`
|
||
WHERE `complex_room_id` = {$complexRoomId}
|
||
AND requisitions.`id` <> $reqId
|
||
AND requisitions.`deleted` = 0
|
||
";
|
||
|
||
$requisitions = $complexStatus::$db->query($sql)->fetchAll();
|
||
|
||
foreach($requisitions as $req)
|
||
{
|
||
$text = "Заявка была исключена из очереди на бронирование.";
|
||
|
||
$req_id = $req['req_id'];
|
||
$client_id = $req['client_id'];
|
||
$user_id = $_SESSION['id'];
|
||
$create_date = (new DateTime("now"))->format('Y-m-d H:i:s');
|
||
|
||
$complexStatus::$db->query("INSERT INTO `user_client_events` (
|
||
`user_id`,
|
||
`req_id`,
|
||
`client_id`,
|
||
`type`,
|
||
`comment`,
|
||
`create_date`
|
||
)
|
||
VALUES (
|
||
$user_id,
|
||
$req_id,
|
||
$client_id,
|
||
'comment',
|
||
'{$text}',
|
||
'{$create_date}'
|
||
)
|
||
");
|
||
|
||
if($req['telegramm_notice']
|
||
&& $req['telegramm_notice'] == 1
|
||
&& $req['telegramm_chat_id']
|
||
&& $req['telegramm_chat_id'] > 0
|
||
){
|
||
$text = "Заявка ID $req_id была исключена из очереди на бронирование.";
|
||
|
||
$complex = new Complex();
|
||
$complex->sendMessageToTelegram($req['telegramm_chat_id'], $text);
|
||
}
|
||
|
||
if($req['max_notice']
|
||
&& $req['max_notice'] == 1
|
||
&& $req['max_user_id']
|
||
&& $req['max_user_id'] > 0
|
||
){
|
||
$text = "Заявка ID $req_id была исключена из очереди на бронирование.";
|
||
|
||
$complex = new Complex();
|
||
$complex->sendMessageToMax($req['max_user_id'], $text);
|
||
}
|
||
|
||
mysql_query("UPDATE `requisitions` SET `complex_status_id` = 0, `complex_room_id` = NULL WHERE id = {$req_id}");
|
||
}
|
||
}
|
||
else
|
||
{
|
||
$sql_funnel_step = mysql_query("SELECT `is_select_room` FROM funnel_steps WHERE id = {$stepId}");
|
||
$funnel_step = mysql_fetch_assoc($sql_funnel_step);
|
||
|
||
if ($funnel_step['is_select_room'])
|
||
{
|
||
$text = $text = "Выбран объект: $selectedRoomName <br/> Статус объекта: $complexStatus->name";
|
||
|
||
if ($complexStatus->status === 'reservation')
|
||
{
|
||
$old_complex_status = new ComplexStatus((int)$req_complex_status_id);
|
||
|
||
if (!$old_complex_status->status || ($old_complex_status->status && $old_complex_status->status !== 'reservation'))
|
||
{
|
||
$complex = new Complex();
|
||
$reservations = $complex->get_room_reservations($complexRoomId);
|
||
|
||
$position = count($reservations) + 1;
|
||
mysql_query("UPDATE `requisitions` SET `position` = $position WHERE id = {$reqId}");
|
||
}
|
||
|
||
$booking_date = new DateTime("now");
|
||
|
||
if (!empty($complexStatus->booking_day))
|
||
{
|
||
$booking_date = $booking_date->modify('+' . $complexStatus->booking_day . ' day');
|
||
}
|
||
|
||
if (!empty($complexStatus->booking_hour))
|
||
{
|
||
$booking_date = $booking_date->modify('+' . $complexStatus->booking_hour . ' hour');
|
||
}
|
||
|
||
$text .= ", до " . $booking_date->format('d.m.Y H:i:s') . ".";
|
||
|
||
$complexStatus->updateRoomsStatus([
|
||
'new_status_id' => $complexStatusId,
|
||
'complex_room_id' => $complexRoomId
|
||
], false, false);
|
||
|
||
}
|
||
|
||
$reservation_updated_at = (new DateTime("now"))->format('Y-m-d H:i:s');
|
||
mysql_query("UPDATE `requisitions` SET `reservation_updated_at` = '{$reservation_updated_at}' WHERE id = {$reqId}");
|
||
|
||
$client_id = $requisition['client_id'];
|
||
$user_id = $_SESSION['id'];
|
||
|
||
$complexStatus::$db->query("INSERT INTO `user_client_events` (
|
||
`user_id`,
|
||
`req_id`,
|
||
`client_id`,
|
||
`type`,
|
||
`comment`,
|
||
`create_date`
|
||
)
|
||
VALUES (
|
||
$user_id,
|
||
$reqId,
|
||
$client_id,
|
||
'comment',
|
||
'{$text}',
|
||
'{$create_date}'
|
||
)
|
||
");
|
||
}
|
||
}
|
||
}
|
||
|
||
if ($complexRoomId)
|
||
{
|
||
$complex = new Complex();
|
||
$complex->generate_room_reservations_positions($complexRoomId);
|
||
}
|
||
}
|
||
|
||
$sql = "SELECT `id`, `step_id`, `next_id`, `values`, `history_requisition` FROM clients_funnel_step WHERE client_id = ".$clientId;
|
||
if($adjacentId > 0){
|
||
$sql = "SELECT `id`, `step_id`, `next_id`, `values`, `funnel_id` FROM adjacent_funnels WHERE id = ".$adjacentId;
|
||
} else
|
||
if($clientId <= 0 && $reqId > 0){
|
||
$sql = "SELECT `id`, `step_id`, `next_id`, `values`, `history_requisition` FROM clients_funnel_step WHERE req_id = ".$reqId;
|
||
}
|
||
|
||
$prev_id = 0;
|
||
$prev_next_id = 0;
|
||
$q = mysql_query($sql);
|
||
if(mysql_num_rows($q) > 0){
|
||
$r = mysql_fetch_assoc($q);
|
||
|
||
$prev_id = (int)$r['step_id'];
|
||
$prev_next_id = (int)$r['next_id'];
|
||
$resVal['prev_id'] = $prev_id;
|
||
$resVal['prev_next_id'] = $prev_next_id;
|
||
$resVal['next_step_select'] = $next_step_select;
|
||
// var_dump($r['values']);
|
||
if(!empty($r['values'])){
|
||
$valarr = json_decode($r['values'],true);
|
||
} else {
|
||
$valarr = array();
|
||
}
|
||
|
||
$historyRequisition = !empty($r['history_requisition']) ? json_decode($r['history_requisition'], true) : [];
|
||
// Create a combined array
|
||
$combined = !empty($historyRequisition) ? [[$history_requisition], $historyRequisition] : [[$history_requisition]];
|
||
|
||
$flattenedArray = [];
|
||
$stepIds = [];
|
||
|
||
foreach ($combined as $subArray)
|
||
{
|
||
foreach ($subArray as $item)
|
||
{
|
||
// If it's an object, cast to array
|
||
if (!in_array($item['step_id'], $stepIds))
|
||
{
|
||
$flattenedArray[] = is_object($item) ? (array) $item : $item;
|
||
$stepIds[] = $item['step_id'];
|
||
}
|
||
}
|
||
}
|
||
|
||
$historyRequisition = json_encode($flattenedArray, JSON_UNESCAPED_UNICODE);
|
||
|
||
$valarr[$stepId] = clearInputElement(json_encode($resVal, JSON_UNESCAPED_UNICODE));
|
||
|
||
$val = json_encode($valarr, JSON_UNESCAPED_UNICODE);
|
||
$sql='';
|
||
if($adjacentId > 0){
|
||
$sql = "UPDATE adjacent_funnels SET step_id = ".$stepId.", next_id = '".$next_id."', `prev_id` = '".$prev_id."', `prev_next_id` = '".$prev_next_id."', `values` = '".$val."' WHERE id = ".$adjacentId;
|
||
} else if($clientId > 0){
|
||
$sql = "UPDATE clients_funnel_step SET step_id = ".$stepId.", next_id = '".$next_id."', `prev_id` = '".$prev_id."', `prev_next_id` = '".$prev_next_id."', `values` = '".$val."', `history_requisition` = '{$historyRequisition}', `transaction_amount` = '$transactionAmount' WHERE client_id = ".$clientId;
|
||
} else if($clientId == 0 && $reqId > 0){
|
||
$sql = "UPDATE clients_funnel_step SET step_id = ".$stepId.", next_id = '".$next_id."', `prev_id` = '".$prev_id."', `prev_next_id` = '".$prev_next_id."', `values` = '".$val."', `history_requisition` = '{$historyRequisition}', `transaction_amount` = '$transactionAmount' WHERE req_id = ".$reqId;
|
||
}
|
||
} else {
|
||
$resVal['prev_id'] = $prev_id;
|
||
$resVal['prev_next_id'] = $prev_next_id;
|
||
$resVal['next_step_select'] = $next_step_select;
|
||
$valarr[$stepId] = clearInputElement(json_encode($resVal, JSON_UNESCAPED_UNICODE));
|
||
$val = json_encode($valarr, JSON_UNESCAPED_UNICODE);
|
||
$historyRequisition = json_encode([$history_requisition], JSON_UNESCAPED_UNICODE);
|
||
|
||
$sql = "INSERT INTO clients_funnel_step SET step_id = ".$stepId.", client_id = ".$clientId.", next_id = '".$next_id."', `prev_id` = '".$prev_id."', `prev_next_id` = '".$prev_next_id."', `values` = '".$val."', `history_requisition` = '{$historyRequisition}', `transaction_amount` = '$transactionAmount'";
|
||
if($clientId == 0 && $reqId > 0){
|
||
$sql = "INSERT INTO clients_funnel_step SET step_id = ".$stepId.", req_id = ".$reqId.", next_id = '".$next_id."', `prev_id` = '".$prev_id."', `prev_next_id` = '".$prev_next_id."', `values` = '".$val."', `history_requisition` = '{$historyRequisition}', `transaction_amount` = '$transactionAmount'";
|
||
}
|
||
}
|
||
|
||
//if($reqId > 0 && $adjacentId == 0){
|
||
$section = 'client';
|
||
$parentId = 'client_id = '.$clientId;
|
||
$pole_parent = 'client_id';
|
||
$pole_parent_val = $clientId;
|
||
if($adjacentId > 0){
|
||
$section = 'adjacent';
|
||
$parentId = 'adjacent_id = '.$adjacentId;
|
||
$pole_parent = 'adjacent_id';
|
||
$pole_parent_val = $adjacentId;
|
||
} else if($reqId > 0){
|
||
$section = 'req';
|
||
$parentId = 'req_id = '.$reqId;
|
||
$pole_parent = 'req_id';
|
||
$pole_parent_val = $reqId;
|
||
}
|
||
$base_event = array();
|
||
$numders_event = array();
|
||
$sql_base_event = "SELECT * FROM steps_data WHERE section='{$section}' AND step_id = {$stepId} AND {$parentId} AND del = 0";
|
||
$q_base_event = mysql_query($sql_base_event);
|
||
while($r_base_event = mysql_fetch_assoc($q_base_event)){
|
||
$base_event[$r_base_event['number']] = $r_base_event;
|
||
|
||
}
|
||
foreach($events_client as $number => $event){
|
||
|
||
$numders_event[] = (int)$number;
|
||
$name_pole = Docs::stringToTranslit($event['name']);
|
||
$value_pole = mysql_real_escape_string($event['value']);
|
||
if(($event['type'] == 'file' || $event['type'] == 'checkbox' || $event['type'] == 'select') && !empty($event['value'])){
|
||
$value_pole = mysql_real_escape_string(json_encode($event['value'], JSON_UNESCAPED_UNICODE));
|
||
}
|
||
if(isset($base_event[$number])){
|
||
if($base_event[$number]['type'] != $event['type'] || $base_event[$number]['pole_name_en'] != $name_pole || $base_event[$number]['value'] != $value_pole){
|
||
$sql_up_step = "UPDATE steps_data_req SET type = '{$event['type']}', pole_name_en = '{$name_pole}', name= '{$event['name']}', value='{$value_pole}', del=0 WHERE step_id = {$stepId} AND {$parentId} AND number = {$number}";
|
||
mysql_query($sql_up_step);
|
||
}
|
||
} else {
|
||
$sql_save_step = "INSERT INTO steps_data (step_id, {$pole_parent}, section, type, number, pole_name_en, name, value) VALUES ({$stepId}, {$pole_parent_val}, '{$section}', '{$event['type']}', '{$number}', '{$name_pole}', '{$event['name']}', '{$value_pole}')";
|
||
// echo $sql_save_step."\n";
|
||
mysql_query($sql_save_step);
|
||
}
|
||
|
||
|
||
}
|
||
if(!empty($numders_event)){
|
||
$sql_updel_step = "UPDATE steps_data SET del = 1 WHERE step_id = {$stepId} AND {$parentId} AND section = '{$section}' AND number NOT IN (".implode(',', $numders_event).")";
|
||
|
||
mysql_query($sql_updel_step);
|
||
} else {
|
||
$sql_updel_step = "UPDATE steps_data SET del = 1 WHERE step_id = {$stepId} AND {$parentId} AND section = '{$section}'";
|
||
|
||
mysql_query($sql_updel_step);
|
||
}
|
||
//}
|
||
|
||
if(!mysql_query($sql)){
|
||
echo mysql_error();
|
||
|
||
} else {
|
||
if($adjacentId == 0){
|
||
if($is_closet == 'Закрыт'){
|
||
if($clientId == 0){
|
||
mysql_query("UPDATE requisitions SET stage = '8', deleted=1, confirm=1 WHERE id = {$reqId}");
|
||
|
||
$autosearch_instce = new AutoSearch();
|
||
$autosearch_instce->deleteFilterByReq($reqId, $userId);
|
||
} else {
|
||
mysql_query("UPDATE clients SET stage = '8', deleted=1, confirm=1 WHERE id = {$clientId}");
|
||
}
|
||
|
||
|
||
} else {
|
||
if($clientId == 0){
|
||
mysql_query("UPDATE requisitions SET stage = '2', deleted=0, confirm=1 WHERE id = {$reqId}");
|
||
} else {
|
||
mysql_query("UPDATE clients SET stage = '2', deleted=0, confirm=1 WHERE id = {$clientId}");
|
||
}
|
||
}
|
||
}
|
||
$close = false;
|
||
$nextEtap = 0;
|
||
if($next_id != 0){
|
||
$nextEtap = (int)$next_id;
|
||
} else if(!empty($nextStep)){
|
||
$nextEtap = (int)$nextStep[0];
|
||
}
|
||
|
||
if($nextEtap != 0){
|
||
//'c «» на «»'
|
||
$sqlname = mysql_query("SELECT `name`, `id` FROM funnel_steps WHERE id = {$nextEtap}");
|
||
$nextName = mysql_fetch_assoc($sqlname);
|
||
}
|
||
|
||
|
||
if(!empty($activites_close_step_val)){
|
||
if($reqId > 0){
|
||
mysql_query("DELETE FROM requisitions_activities WHERE req_id = {$reqId}");
|
||
|
||
foreach($activites_close_step_val as $a) {
|
||
|
||
$sql_in = "INSERT INTO requisitions_activities SET req_id = {$reqId}, activity_id={$a}";
|
||
|
||
mysql_query($sql_in);
|
||
|
||
|
||
}
|
||
} else if($clientId > 0){
|
||
mysql_query("DELETE FROM clients_activities WHERE client_id = {$clientId}");
|
||
|
||
foreach($activites_close_step_val as $a) {
|
||
|
||
$sql_in = "INSERT INTO clients_activities SET client_id = {$clientId}, activity_id={$a}";
|
||
|
||
mysql_query($sql_in);
|
||
|
||
|
||
}
|
||
}
|
||
}
|
||
//Отправлять ли уведомление
|
||
$sqlStep = "SELECT is_mes, users_mes, name FROM funnel_steps WHERE id = {$stepId}";
|
||
$qStep = mysql_query($sqlStep);
|
||
$rStep = mysql_fetch_assoc($qStep);
|
||
if($rStep['is_mes'] > 0){
|
||
$users_mes = json_decode($rStep['users_mes'], true);
|
||
if(!empty($users_mes)){
|
||
$req = false;
|
||
$client = false;
|
||
$who_work = 0;
|
||
|
||
$user1 = mysql_fetch_assoc(mysql_query("SELECT * FROM users WHERE id = {$userId}"));
|
||
$post = "Сотрудник";
|
||
if ($user1['agency'] == 1) {
|
||
$post = "Агенство";
|
||
} else if ($user1['manager'] == 1) {
|
||
$post = "Менеджер";
|
||
}
|
||
$text = "<b>".$post . " " . trim($user1['last_name'] . ' ' . $user1['first_name'] . ' ' . $user1['middle_name'])."</b><br>закрыл(а) этап «".$stepName."» ";
|
||
|
||
|
||
if($clientId == 0 && $reqId > 0){
|
||
$req = mysql_fetch_assoc(mysql_query("SELECT * FROM requisitions WHERE id = {$reqId}"));
|
||
$who_work = $req['who_work'];
|
||
$text .= "<br>по заявке ".$req['name']."<br>";
|
||
if($nextEtap != 0 ){
|
||
$text .= "Заявка перешла на этап «".$nextName['name']."»<br>";
|
||
}
|
||
$client_req = mysql_fetch_assoc(mysql_query("SELECT * FROM clients WHERE id = {$req['client_id']}"));
|
||
$text .="<i>Клиент: </i>".$client_req['fio']." тел. ".$client_req['phone'];
|
||
if($req['type_id'] == 2 && $req['object_id'] > 0){
|
||
$obj = mysql_fetch_assoc(mysql_query("SELECT id, adres, stoim, type, komnat FROM objects WHERE id = {$req['object_id']}"));
|
||
if($obj){
|
||
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:
|
||
if ($obj['komnat'] == 0) {
|
||
$type = "Помещение";
|
||
} else {
|
||
$type = "$obj[komnat]-комнатное помещение";
|
||
}
|
||
break;
|
||
case 5:
|
||
$type = "Часть дома";
|
||
break;
|
||
case 6:
|
||
$type = "Комплекс";
|
||
break;
|
||
case 7:
|
||
$type = "Участок";
|
||
break;
|
||
default:
|
||
$type = "$obj[komnat]-комнатная квартира";
|
||
}
|
||
$text .= '<br><i>Объект:</i> ID:'.$obj['id'].' '.$obj['adres'].', '.$type.' '.$obj['stoim'];
|
||
}
|
||
}
|
||
|
||
if($req['deleted'] > 0){
|
||
/*if($req['confirm'] == 10){
|
||
$text .= "<br>Закрыта. Совершена сделка на ".$req['summa']." руб";
|
||
} else {
|
||
$denial = mysql_fetch_assoc(mysql_query("SELECT name FROM denial_work WHERE id = {$req['denial']}"));
|
||
$text .= "<br>Закрыта. ".$denial['name'];
|
||
}*/
|
||
$close = true;
|
||
}
|
||
|
||
} else if ($clientId > 0) {
|
||
$client = mysql_fetch_assoc(mysql_query("SELECT * FROM clients WHERE id = {$clientId}"));
|
||
$who_work = $client['who_work'];
|
||
$text .= "<br>по клиенту: ".$client['fio']. " тел. ".$client['phone'];
|
||
if($nextEtap !=0 ){
|
||
$text .= "<br>Клиент перешел на этап «".$nextName['name']."»";
|
||
}
|
||
if($client['deleted'] > 0){
|
||
$close = true;
|
||
}
|
||
|
||
}
|
||
$text = htmlspecialchars($text);
|
||
|
||
$userMes = array();
|
||
$send = 0;
|
||
if($close){
|
||
$tempid = time();
|
||
$send = 1;
|
||
}
|
||
// $user_id_mes = false;
|
||
foreach ($users_mes as $key => $user_id_mes_) {
|
||
unset($user_id_mes);
|
||
|
||
if ($users_mes[$key] === 'manager') {
|
||
|
||
$managerWhoWork = mysql_fetch_assoc(mysql_query("SELECT * FROM users WHERE id = {$who_work}"));
|
||
|
||
$user_id_mes = $managerWhoWork['id_manager'];
|
||
} else if($users_mes[$key] == 0){
|
||
$user_id_mes = $who_work;
|
||
} else {
|
||
$user_id_mes = $user_id_mes_;
|
||
}
|
||
|
||
|
||
if(!in_array($user_id_mes, $userMes) && $user_id_mes != $_SESSION['id']){
|
||
|
||
$sqlMesIn = "INSERT INTO step_notify_closure SET user_id = {$user_id_mes}, from_id={$userId}, step_id={$stepId}, text='{$text}', send={$send}, temp_id={$tempid}";
|
||
|
||
mysql_query($sqlMesIn);
|
||
$userMes[] = $user_id_mes;
|
||
}
|
||
|
||
}
|
||
}
|
||
/* if($_SESSION['id'] == 5238){
|
||
var_dump($userMes);
|
||
}*/
|
||
}
|
||
|
||
//Отправка уведомлений по смежным воронкам
|
||
if($adjacentId > 0){
|
||
$text = '';
|
||
|
||
$who_work = 0;
|
||
|
||
if($clientId > 0 && $reqId == 0){
|
||
$sql_req_client = "SELECT * FROM clients WHERE id = {$clientId}";
|
||
} else if ($reqId > 0){
|
||
$sql_req_client = "SELECT * FROM requisitions WHERE id = {$reqId}";
|
||
}
|
||
|
||
|
||
|
||
$q_req_client = mysql_query($sql_req_client);
|
||
|
||
|
||
//$users_mes = array();
|
||
if($r_req_client = mysql_fetch_assoc($q_req_client)){
|
||
$sql_f = "SELECT * FROM funnel WHERE id = {$r['funnel_id']}";
|
||
|
||
$q_f = mysql_query($sql_f);
|
||
$name_funel = '';
|
||
if($r_f = mysql_fetch_assoc($q_f)){
|
||
$name_funel = $r_f['name'];
|
||
}
|
||
if(!empty($name_funel)){
|
||
$text_funnel .= "в смежной воронке <b>«".$name_funel."»</b><br>";
|
||
}
|
||
|
||
$user1 = mysql_fetch_assoc(mysql_query("SELECT * FROM users WHERE id = {$userId}"));
|
||
$post = "Сотрудник";
|
||
if ($user1['agency'] == 1) {
|
||
$post = "Агенство";
|
||
} else if ($user1['manager'] == 1) {
|
||
$post = "Менеджер";
|
||
}
|
||
$text = "<b>".$post . " " . trim($user1['last_name'] . ' ' . $user1['first_name'] . ' ' . $user1['middle_name'])."</b><br>закрыл(а) этап «".$stepName."» ";
|
||
|
||
|
||
if($clientId == 0 && $reqId > 0){
|
||
|
||
$who_work = $r_req_client['who_work'];
|
||
$text .= "<br>по заявке ".$r_req_client['name']."<br>";
|
||
if($nextEtap !=0 ){
|
||
$text .= "Заявка перешла на этап «".$nextName['name']."»<br>";
|
||
|
||
}
|
||
$text .= $text_funnel;
|
||
$client_req = mysql_fetch_assoc(mysql_query("SELECT * FROM clients WHERE id = {$r_req_client['client_id']}"));
|
||
$text .="<i>Клиент: </i>".$client_req['fio']." тел. ".$client_req['phone'];
|
||
if($req['type_id'] == 2 && $req['object_id'] > 0){
|
||
$obj = mysql_fetch_assoc(mysql_query("SELECT id, adres, stoim, type, komnat FROM objects WHERE id = {$r_req_client['object_id']}"));
|
||
if($obj){
|
||
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 .= '<br><i>Объект:</i> ID:'.$obj['id'].' '.$obj['adres'].', '.$type.' '.$obj['stoim'];
|
||
}
|
||
}
|
||
|
||
/* if($r_req_client['deleted'] > 0){
|
||
/*if($req['confirm'] == 10){
|
||
$text .= "<br>Закрыта. Совершена сделка на ".$req['summa']." руб";
|
||
} else {
|
||
$denial = mysql_fetch_assoc(mysql_query("SELECT name FROM denial_work WHERE id = {$req['denial']}"));
|
||
$text .= "<br>Закрыта. ".$denial['name'];
|
||
}
|
||
//$close = true;
|
||
}*/
|
||
|
||
} else if ($clientId > 0) {
|
||
|
||
$who_work = $r_req_client['who_work'];
|
||
$text .= "<br>по клиенту: ".$client['fio']. " тел. ".$client['phone'];
|
||
if($nextEtap !=0 ){
|
||
$text .= "<br>Клиент перешел на этап «".$nextName['name']."»";
|
||
}
|
||
$text .= $text_funnel;
|
||
/* if($client['deleted'] > 0){
|
||
$close = true;
|
||
}*/
|
||
|
||
}
|
||
$text = htmlspecialchars($text);
|
||
if($who_work > 0){
|
||
$sqlMesIn = "INSERT INTO step_notify_closure SET user_id = {$who_work}, from_id={$userId}, step_id={$stepId}, text='{$text}', send=0";
|
||
|
||
mysql_query($sqlMesIn);
|
||
}
|
||
|
||
/* $userMes = array();
|
||
$send = 0;
|
||
if($close){
|
||
$tempid = time();
|
||
$send = 1;
|
||
}
|
||
// $user_id_mes = false;
|
||
foreach ($users_mes as $key => $user_id_mes_) {
|
||
unset($user_id_mes);
|
||
|
||
if ($users_mes[$key] === 'manager') {
|
||
|
||
$managerWhoWork = mysql_fetch_assoc(mysql_query("SELECT * FROM users WHERE id = {$who_work}"));
|
||
|
||
$user_id_mes = $managerWhoWork['id_manager'];
|
||
} else if($users_mes[$key] == 0){
|
||
$user_id_mes = $who_work;
|
||
} else {
|
||
$user_id_mes = $user_id_mes_;
|
||
}
|
||
|
||
|
||
if(!in_array($user_id_mes, $userMes) && $user_id_mes != $_SESSION['id']){
|
||
|
||
$sqlMesIn = "INSERT INTO step_notify_closure SET user_id = {$user_id_mes}, from_id={$userId}, step_id={$stepId}, text='{$text}', send={$send}, temp_id={$tempid}";
|
||
|
||
mysql_query($sqlMesIn);
|
||
$userMes[] = $user_id_mes;
|
||
}
|
||
|
||
}
|
||
}
|
||
/* if($_SESSION['id'] == 5238){
|
||
var_dump($userMes);
|
||
}*/
|
||
}
|
||
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
$text = '';
|
||
//Кастомные поля в закрытии этапа
|
||
if($clientId == 0 && $reqId > 0){
|
||
|
||
if(!empty($fields_models)){
|
||
// var_dump($fields_models);
|
||
$linkingClass = new LinkingClass();
|
||
$reqClass = new Requisitions(null, true);
|
||
$fields_req = $reqClass->get_req_fields($agency_id, $reqId);
|
||
$arrFields_models = (array)$fields_models;
|
||
foreach($fields_models as $key => $field_models) {
|
||
|
||
$arrField = explode("_", $key, 2);
|
||
$typeField = 1;
|
||
if($arrField[0] == 'modelp'){
|
||
$typeField = 2;
|
||
}
|
||
$fieldId = $arrField[1];
|
||
|
||
|
||
if(is_numeric($fieldId)){
|
||
$value = json_encode($field_models, JSON_UNESCAPED_UNICODE);
|
||
|
||
|
||
$field_id = (int)$arrField[1];
|
||
//Поиск поля и запись текста
|
||
// var_dump($fields_req['fields']);
|
||
foreach($fields_req['fields'] as $fr){
|
||
|
||
if($fr['id'] === $field_id){
|
||
|
||
// var_dump($fr);
|
||
|
||
if($fr['is_podgroup'] > 0){
|
||
if($fr['is_podgroup_multiselect'] == 1){
|
||
$values = json_decode($value, true);
|
||
$tempTitle = '';
|
||
$tempText = '';
|
||
if(!empty($values)){
|
||
|
||
foreach($fr['podgroups'] as $pd){
|
||
if(in_array($pd['id'], $values)){
|
||
|
||
if($tempTitle != '') $tempTitle .= ', ';
|
||
$tempTitle .= clearInputElement($pd['title']);
|
||
// $text .= '<p><b>'.$fr['title'].'</b>: '.clearInputElement($pd['title']).'</p>';
|
||
if(isset($arrFields_models['modelp_'.$pd['id']])){
|
||
$val = $arrFields_models['modelp_'.$pd['id']];
|
||
if(isset($pd['params']['items'])){
|
||
foreach($pd['params']['items'] as $item){
|
||
if($item['value'] == $arrFields_models['modelp_'.$pd['id']]){
|
||
$val = $item['name'];
|
||
}
|
||
}
|
||
//$val = $pd['params']['items'][$arrFields_models['modelp_'.$value]]['name'];
|
||
}
|
||
$tempText .= '<p><b>'.$pd['title'].'</b>: '.clearInputElement($val).'</p>';
|
||
}
|
||
}
|
||
}
|
||
if(!empty($tempTitle)){
|
||
$text .= '<p><b>'.$fr['title'].'</b>: '.$tempTitle.'</p>';
|
||
}
|
||
if(!empty($tempText)){
|
||
$text .= $tempText;
|
||
}
|
||
}
|
||
|
||
} else {
|
||
foreach($fr['podgroups'] as $pd){
|
||
if($pd['id'] == (int)$value){
|
||
//var_dump($pd);
|
||
|
||
$text .= '<p><b>'.$fr['title'].'</b>: '.clearInputElement($pd['title']).'</p>';
|
||
if(isset($arrFields_models['modelp_'.$value])){
|
||
$val = $arrFields_models['modelp_'.$value];
|
||
if(isset($pd['params']['items'])){
|
||
foreach($pd['params']['items'] as $item){
|
||
if($item['value'] == $arrFields_models['modelp_'.$value]){
|
||
$val = $item['name'];
|
||
}
|
||
}
|
||
//$val = $pd['params']['items'][$arrFields_models['modelp_'.$value]]['name'];
|
||
}
|
||
$text .= '<p><b>'.$pd['title'].'</b>: '.clearInputElement($val).'</p>';
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
} else if($fr['type'] == 2){
|
||
$val = $value;
|
||
if(isset($fr['params']['items'])){
|
||
foreach($fr['params']['items'] as $item){
|
||
if($item['value'] == $value){
|
||
$val = $item['name'];
|
||
}
|
||
}
|
||
//$val = $pd['params']['items'][$arrFields_models['modelp_'.$value]]['name'];
|
||
}
|
||
$text .= '<p><b>'.$fr['title'].'</b>: '.clearInputElement($val).'</p>';
|
||
} else if($fr['type'] == 3){
|
||
$val = '';
|
||
$vals = json_decode($value, true);
|
||
|
||
if(isset($fr['params']['items'])){
|
||
foreach($vals as $v){
|
||
foreach($fr['params']['items'] as $item){
|
||
if($item['value'] == $v){
|
||
if($val != '') $val .= ', ';
|
||
$val .= $item['name'];
|
||
}
|
||
}
|
||
//$val = $pd['params']['items'][$arrFields_models['modelp_'.$value]]['name'];
|
||
}
|
||
}
|
||
$text .= '<p><b>'.$fr['title'].'</b>: '.$val.'</p>';
|
||
}
|
||
else if($fr['type'] == 4){
|
||
$text .= '<p><b>'.$fr['title'].'</b>: ';
|
||
if($value == 1){
|
||
$text .= 'Да</p>';
|
||
} else {
|
||
$text .= 'Нет</p>';
|
||
}
|
||
}
|
||
else {
|
||
|
||
$text .= '<p><b>'.$fr['title'].'</b>: '.clearInputElement($value).'</p>';
|
||
}
|
||
|
||
//var_dump($text);
|
||
// break;
|
||
}
|
||
}
|
||
|
||
|
||
$sql_req_data = "SELECT id FROM requisition_data WHERE req_id = {$reqId} AND field_id = {$field_id} AND type = {$typeField}";
|
||
$q_req_data = mysql_query($sql_req_data);
|
||
if(mysql_num_rows($q_req_data) > 0){
|
||
$r_req_data = mysql_fetch_assoc($q_req_data);
|
||
$sql_up_req_data = "UPDATE requisition_data SET value = '$value' where req_id = {$reqId} AND field_id = {$field_id} AND type = {$typeField}";
|
||
|
||
mysql_query($sql_up_req_data);
|
||
} else {
|
||
|
||
$sql_in = "INSERT INTO requisition_data SET ".
|
||
" req_id=$reqId, ".
|
||
" field_id=$field_id, ".
|
||
" type=$typeField, ".
|
||
" value='$value'";
|
||
|
||
mysql_query($sql_in);
|
||
}
|
||
} else if(!empty($fieldId)){
|
||
|
||
$field = $linkingClass->field_find($fieldId);
|
||
|
||
//var_dump($field);
|
||
if(isset($field['ident'])){
|
||
|
||
//Поиск доп поля в заявке
|
||
$req_dop = mysql_fetch_assoc(mysql_query("SELECT * FROM requisitions WHERE id={$reqId}"));
|
||
if(isset($req_dop[$field['ident']]) && !empty($req_dop[$field['ident']])){
|
||
if(isset($field['table'])){
|
||
$sql_dop_table = "SELECT id FROM `{$field['table']}` WHERE `{$field['ident']}` = {$req_dop[$field['ident']]}";
|
||
$q_dop_table = mysql_query($sql_dop_table);
|
||
if(mysql_num_rows($q_dop_table) > 0){
|
||
$sql_in_dop_field = "UPDATE `{$field['table']}` SET `$fieldId`= '{$field_models}' WHERE `{$field['ident']}` = {$req_dop[$field['ident']]}";
|
||
|
||
mysql_query($sql_in_dop_field);
|
||
} else {
|
||
if($field['table'] == 'object_prices'){
|
||
$user = new User();
|
||
$user->get($_SESSION['id']);
|
||
$agency_id = $user->agencyId;
|
||
}
|
||
$sql_in_dop_field = "INSERT INTO `{$field['table']}` SET `{$field['ident']}` = {$req_dop[$field['ident']]}, `$fieldId`= '{$field_models}'";
|
||
if(isset($agency_id)){
|
||
$sql_in_dop_field .= ", agency_id = {$agency_id}";
|
||
}
|
||
mysql_query($sql_in_dop_field);
|
||
}
|
||
$text .= '<p><b>'.$field['title'].'</b>: '.clearInputElement($field_models).'</p>';
|
||
} else {
|
||
|
||
}
|
||
} else {
|
||
|
||
}
|
||
} else {
|
||
// echo $field_id;
|
||
if($fieldId == 'client_contract'){
|
||
// $value = json_encode($field_models, JSON_UNESCAPED_UNICODE);
|
||
$sql_person = "SELECT * FROM `persons_contract` WHERE req_id={$reqId} AND client_id = {$field_models->id}";
|
||
//echo $sql_person;
|
||
$q_person = mysql_query($sql_person);
|
||
if(mysql_num_rows($q_person) == 0){
|
||
$sql_in_person = "INSERT INTO `persons_contract` set req_id={$reqId}, client_id = {$field_models->id}, name='Лицо по договору'";
|
||
mysql_query($sql_in_person);
|
||
}
|
||
|
||
$text .= '<p><b>'.$field['title'].'</b>: '.clearInputElement($field_models->name).'</p>';
|
||
|
||
//$field_models
|
||
} else {
|
||
$sql_in_dop_field = "UPDATE `requisitions` SET `$fieldId`= '{$field_models}' WHERE id={$reqId}";
|
||
//echo $sql_in_dop_field;
|
||
mysql_query($sql_in_dop_field);
|
||
$text .= '<p><b>'.$field['title'].'</b>: '.clearInputElement($field_models).'</p>';
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
} else if ($clientId > 0 && $reqId == 0) {
|
||
}
|
||
|
||
//Запись событий этапа
|
||
if(!empty($events_client)){
|
||
unset($events_client['prev_id']);
|
||
unset($events_client['prev_next_id']);
|
||
unset($events_client['next_step_select']);
|
||
|
||
//$text = '';
|
||
foreach($events_client as $event){
|
||
|
||
if($event['type'] == 'select'){
|
||
$text .= '';
|
||
} else if($event['type'] == 'date'){
|
||
$text .= '<p><b>'.$event['name'].'</b>: '.date('d.m.Y', strtotime($event['value'])).'</p>';
|
||
} else if($event['type'] == 'checkbox'){
|
||
$text .= '';
|
||
/* if($event['value'] == 1){
|
||
$text .= '<p><b>'.$event['name'].'</b>: Да</p>';
|
||
} else {
|
||
$text .= '<p><b>'.$event['name'].'</b>: Нет</p>';
|
||
}*/
|
||
} else if($event['type'] == 'file' && isset($event['value']['guid'])){
|
||
$doc_q = mysql_query("SELECT * FROM funnel_files WHERE guid = '".$event['value']['guid']."' and etap_id = {$stepId} and client_id = '".$clientId."'");
|
||
if($reqId > 0){
|
||
$doc_q = mysql_query("SELECT * FROM funnel_files WHERE guid = '".$event['value']['guid']."' and etap_id = {$stepId} and req_id = '".$reqId."'");
|
||
|
||
}
|
||
if(mysql_num_rows($doc_q) > 0){
|
||
$doc = mysql_fetch_assoc($doc_q);
|
||
$name_doc = 'https://uf.joywork.ru/upload/funnels/clients/'.$clientId.'/'.$doc['guid'].'.'.$doc['type'];
|
||
if($reqId > 0){
|
||
$name_doc = 'https://uf.joywork.ru/upload/funnels/req/'.$reqId.'/'.$doc['guid'].'.'.$doc['type'];
|
||
}
|
||
|
||
$text .= '<p><b>'.$event['name'].'</b>: <a title="Скачать" download href="/download_file.php?guid='.$doc['guid'].'">'.$doc['name'].'</a></p>';
|
||
}
|
||
} else if($event['type'] == 'deposit' && (int)$event['value'] > 0){
|
||
$text .= '<p><b>'.$event['name'].'</b>: '.clearInputElement($event['value']).'</p>';
|
||
if($clientId > 0){
|
||
$who_work = $userId;
|
||
$sql_cl = "SELECT id, who_work FROM clients WHERE id = {$clientId}";
|
||
$q_cl = mysql_query($sql_cl);
|
||
$r_cl = mysql_fetch_assoc($q_cl);
|
||
if($r_cl['who_work'] > 0){
|
||
$who_work = (int)$r_cl['who_work'];
|
||
}
|
||
$sql_d = "SELECT id FROM deposits_clients_req WHERE client_id = {$clientId} AND funnel_id={$funnelId} AND step_id = {$stepId}";
|
||
$q_d = mysql_query($sql_d);
|
||
$deposit = (int)$event['value'];
|
||
if(mysql_num_rows($q_d) > 0){
|
||
$id_d = mysql_result($q_d, 0);
|
||
|
||
$sql_up_d = "UPDATE deposits_clients_req SET deposit = {$deposit}, created_at= NOW(), user_id={$who_work} WHERE id = {$id_d}";
|
||
mysql_query($sql_up_d);
|
||
|
||
} else {
|
||
$sql_in_d = "INSERT INTO deposits_clients_req SET deposit = {$deposit}, funnel_id={$funnelId}, step_id={$stepId}, user_id={$who_work}, client_id={$clientId}";
|
||
mysql_query($sql_in_d);
|
||
}
|
||
}
|
||
if($reqId > 0){
|
||
/**
|
||
* 28.07.2023 Игорь по согласованию со Станиславом сказал задатки на ответственных фиксировать
|
||
*/
|
||
$who_work = $userId;
|
||
$sql_req = "SELECT id, who_work FROM requisitions WHERE id = {$reqId}";
|
||
$q_req = mysql_query($sql_req);
|
||
$r_req = mysql_fetch_assoc($q_req);
|
||
if($r_req['who_work'] > 0){
|
||
$who_work = (int)$r_req['who_work'];
|
||
}
|
||
$sql_d = "SELECT id, deposit FROM deposits_clients_req WHERE req_id = {$reqId} AND funnel_id={$funnelId} AND step_id = {$stepId}";
|
||
$q_d = mysql_query($sql_d);
|
||
$deposit = (int)$event['value'];
|
||
if(mysql_num_rows($q_d) > 0){
|
||
$r_d = mysql_fetch_assoc($q_d);
|
||
$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}";
|
||
mysql_query($sql_up_d);
|
||
if((int)$r_d['deposit'] != $deposit){
|
||
$text_deposit = "Изменено: {$event['name']} с {$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)";
|
||
|
||
mysql_query($sql_event);
|
||
}
|
||
|
||
|
||
} else {
|
||
$sql_in_d = "INSERT INTO deposits_clients_req SET deposit = {$deposit}, funnel_id={$funnelId}, step_id = {$stepId}, user_id={$who_work}, req_id={$reqId}";
|
||
mysql_query($sql_in_d);
|
||
$text_deposit = "Добавлено: {$event['name']} - {$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)";
|
||
|
||
mysql_query($sql_event);
|
||
}
|
||
}
|
||
} else if ($event['type'] == 'commission' && (int)$event['value'] > 0 && $reqId > 0){ // Только для заявок
|
||
$text .= '<p><b>'.$event['name'].'</b>: '.clearInputElement($event['value']).'</p>';
|
||
$sql_req = "SELECT expected_commission FROM requisitions WHERE id = {$reqId}";
|
||
$q_req = mysql_query($sql_req);
|
||
$r_req = mysql_fetch_assoc($q_req);
|
||
$text_commission = '';
|
||
if(empty($r_req['expected_commission'])){
|
||
$text_commission = "Добавлено: {$event['name']} - {$event['value']}";
|
||
$sql_up = "UPDATE requisitions SET expected_commission = {$event['value']} WHERE id = {$reqId}";
|
||
if(mysql_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)";
|
||
|
||
mysql_query($sql_event);
|
||
}
|
||
} else if ($r_req['expected_commission'] != $event['value']) {
|
||
$text_commission = "Изменено: {$event['name']} с {$r_req['expected_commission']} на {$event['value']}";
|
||
$sql_up = "UPDATE requisitions SET expected_commission = {$event['value']} WHERE id = {$reqId}";
|
||
if(mysql_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)";
|
||
|
||
mysql_query($sql_event);
|
||
}
|
||
}
|
||
|
||
} else if ($event['type'] == 'expenses' && (float)$event['value']['summa'] > 0 && $reqId > 0){ // Только для заявок
|
||
$text .= '<p><b>'.$event['name'].'</b>: '.$event['value']['summa'];
|
||
if(!empty($event['value']['comment'])){
|
||
$text .= ' <b>Комментарий: </b>'.clearInputElement($event['value']['comment']);
|
||
}
|
||
$sql_ex = "SELECT * FROM expenses_req WHERE req_id = {$reqId} AND funnel_id = {$funnelId} AND step_id = {$stepId}";
|
||
$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 ({$userId}, {$userId}, {$reqId}, 'update', '{$text_expenses}', 1)";
|
||
|
||
mysql_query($sql_event);
|
||
}
|
||
} else {
|
||
$comment = mysql_real_escape_string($event['value']['comment']);
|
||
|
||
$sql_in = "INSERT INTO `expenses_req`(`user_id`, `req_id`, `amount`, `comment`, `funnel_id`, `step_id`) VALUES ({$userId}, {$reqId}, {$event['value']['summa']}, '{$comment}', {$funnelId}, {$stepId})";
|
||
mysql_query($sql_in);
|
||
$text_expenses = "Добавлено: {$event['name']} - {$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 ({$userId}, {$userId}, {$reqId}, 'update', '{$text_expenses}', 1)";
|
||
mysql_query($sql_event);
|
||
}
|
||
} else {
|
||
$text .= '<p><b>'.$event['name'].'</b>: '.clearInputElement($event['value']).'</p>';
|
||
}
|
||
|
||
}
|
||
// $text = clearInputElement($text);
|
||
|
||
}
|
||
|
||
|
||
if($text != ''){
|
||
$sql_e = "INSERT INTO user_client_events SET user_id = {$userId}, client_id = {$clientId}, type='step', name = '{$stepName}', comment = '{$text}'";
|
||
if($reqId > 0){
|
||
$sql_e = "INSERT INTO user_client_events SET user_id = {$userId}, req_id = {$reqId}, type='step', name = '{$stepName}', comment = '{$text}'";
|
||
}
|
||
|
||
if(!mysql_query($sql_e)){
|
||
echo mysql_error();
|
||
}
|
||
}
|
||
|
||
//Запись события перехода на этап
|
||
|
||
|
||
if($nextEtap != 0){
|
||
//'c «» на «»'
|
||
$dop_text = 'c «'.$stepName.'» на «'.$nextName['name'].'»';
|
||
// echo "INSERT INTO `events_clients` SET user_id = {$userId}, client_id = {$clientId}, event='stageedit', read=1, dop_text='{$dop_text}'";
|
||
$sql_in_ev = "INSERT INTO `events_clients` SET user_id = {$userId}, client_id = {$clientId}, event='stageedit', `read`=1, from_id = 0, dop_text='{$dop_text}'";
|
||
$in_history = "INSERT INTO `steps_history`(`client_id`, `step_id`, `date`, `type`, `user_id`, `created_at`)
|
||
VALUES ({$clientId}, {$stepId}, {$date}, 1, {$userId}, '{$create_at}')";
|
||
if($reqId > 0){
|
||
$sql_in_ev = "INSERT INTO `events_clients` SET user_id = {$userId}, req_id = {$reqId}, event='stageedit', `read`=1, from_id = 0, dop_text='{$dop_text}'";
|
||
$in_history = "INSERT INTO `steps_history`(`req_id`, `step_id`, `date`, `type`, `user_id`, `created_at`)
|
||
VALUES ({$reqId}, {$stepId}, {$date}, 1, {$userId}, '{$create_at}')";
|
||
}
|
||
mysql_query($sql_in_ev);
|
||
mysql_query($in_history);
|
||
//Запись дополнительных ответственных
|
||
$sql_cl = "SELECT id, doer_clients, doers, who_work, funnel_id FROM clients WHERE id = {$clientId}";
|
||
$q_cl = mysql_query($sql_cl);
|
||
$client = mysql_fetch_assoc($q_cl);
|
||
if($client['doer_clients'] > 0){
|
||
$doers = json_decode(html_entity_decode($client['doers']), true);
|
||
foreach($doers as $doer_id => $doer){
|
||
if($doer == 1){
|
||
$sql_up_doer = "INSERT INTO doers_emp_client (user_id, client_id, funnel_id, step_id, step_name, who_work, doer_id, confirm, start_date) ".
|
||
"values ({$userId}, {$clientId}, ".$client['funnel_id'].", {$nextEtap}, '".$nextName['name']."', ".$client['who_work'].", {$doer_id}, 1, NOW())";
|
||
|
||
mysql_query($sql_up_doer);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
if($adjacentId > 0){
|
||
$res['client_id'] = $clientId;
|
||
$res['req_id'] = $reqId;
|
||
$res['adjacent_id'] = $adjacentId;
|
||
} else if($clientId > 0){
|
||
$res = get_class_etap($clientId, $funnelId);
|
||
$cl = new Clients();
|
||
$cl->prev_step_event($clientId, $res['stageId']);
|
||
} else if($reqId > 0) {
|
||
$req = new Requisitions(null, true);
|
||
$res = $req->get_class_etap($reqId, $funnelId);
|
||
//if($_SESSION['id'] == 5238){
|
||
$req->prev_step_event($reqId, $res['stageId']);
|
||
|
||
// }
|
||
}
|
||
$res['tempid'] = $tempid;
|
||
if($agency_id == 13154 && $reqId > 0 && $funnelId == 699 && $stepId == 4447){
|
||
$w = new WebHookSend($agency_id, 3, $reqId, 'req');
|
||
}
|
||
|
||
if($reqId > 0 && $funnelId > 0){
|
||
$dataWhook = array('action'=>'close_step','funnel_id'=>$funnelId, 'step_id'=>$stepId, 'new_step_id'=>$res['stageId'], 'req_id'=>$reqId, 'section'=>'req');
|
||
$w_in = new WebHookIn(null, $agency_id);
|
||
$w_in->check_send($dataWhook);
|
||
}
|
||
echo json_encode($res);
|
||
exit();
|
||
}
|
||
|
||
if($request == 'save_check_list'){
|
||
$userId = $_SESSION['id'];
|
||
|
||
$stepId = $data->step_id;
|
||
|
||
$clientId = 0;
|
||
if(isset($data->client_id)){
|
||
$clientId = $data->client_id;
|
||
}
|
||
$reqId = 0;
|
||
if(isset($data->req_id)){
|
||
$reqId = $data->req_id;
|
||
}
|
||
$funnelId = $data->funnel_id;
|
||
|
||
|
||
$values = $data->values;
|
||
$pole = $data->pole;
|
||
$resVal = json_decode($values, true);
|
||
|
||
$events_client[] = $resVal[$pole];
|
||
|
||
$sql_st = "SELECT name FROM funnel_steps WHERE id=$stepId";
|
||
$q_st = mysql_query($sql_st);
|
||
$r_st = mysql_fetch_assoc($q_st);
|
||
$stepName = $r_st['name'];
|
||
|
||
|
||
$sql = "SELECT `id`, `step_id`, `next_id`, `values` FROM clients_funnel_step WHERE client_id = ".$clientId;
|
||
if($clientId == 0){
|
||
$sql = "SELECT `id`, `step_id`, `next_id`, `values` FROM clients_funnel_step WHERE req_id = ".$reqId;
|
||
}
|
||
//echo $sql;
|
||
$prev_id = 0;
|
||
$prev_next_id = 0;
|
||
$next_id = 0;
|
||
$q = mysql_query($sql);
|
||
if(mysql_num_rows($q) > 0){
|
||
$r = mysql_fetch_assoc($q);
|
||
|
||
// var_dump($r['values']);
|
||
if(!empty($r['values'])){
|
||
$valarr = json_decode($r['values'],true);
|
||
$valArr = deClearInputElements($valarr);
|
||
$valArrStep = array();
|
||
if(isset($valArr[$stepId])){
|
||
$valArrStep = json_decode($valArr[$stepId],true);
|
||
}
|
||
$valArrStep[$pole] = $resVal[$pole];
|
||
} else {
|
||
$valarr = array();
|
||
}
|
||
|
||
$valarr[$stepId] = clearInputElement(json_encode($valArrStep, JSON_UNESCAPED_UNICODE));
|
||
|
||
$val = json_encode($valarr, JSON_UNESCAPED_UNICODE);
|
||
$sql = '';
|
||
if($clientId > 0) {
|
||
$sql = "UPDATE clients_funnel_step SET `values` = '".$val."' WHERE client_id = ".$clientId;
|
||
}
|
||
else if($clientId <= 0 && $reqId > 0){
|
||
$sql = "UPDATE clients_funnel_step SET `values` = '".$val."' WHERE req_id = ".$reqId;
|
||
}
|
||
} else {
|
||
|
||
$valarr[$stepId] = clearInputElement(json_encode($resVal, JSON_UNESCAPED_UNICODE));
|
||
$val = json_encode($valarr, JSON_UNESCAPED_UNICODE);
|
||
$sql = "INSERT INTO clients_funnel_step SET step_id = 0, client_id = ".$clientId.", next_id = 0, `prev_id` = 0, `prev_next_id` = 0, `values` = '".$val."'";
|
||
if($clientId == 0 && $reqId > 0){
|
||
$sql = "INSERT INTO clients_funnel_step SET step_id = 0, req_id = ".$reqId.", next_id = 0, `prev_id` = 0, `prev_next_id` = 0, `values` = '".$val."'";
|
||
|
||
}
|
||
}
|
||
|
||
if(!mysql_query($sql)){
|
||
echo mysql_error();
|
||
|
||
}
|
||
//Запись событий этапа
|
||
if(!empty($events_client)){
|
||
unset($events_client['prev_id']);
|
||
unset($events_client['prev_next_id']);
|
||
unset($events_client['next_step_select']);
|
||
|
||
$text = '';
|
||
foreach($events_client as $event){
|
||
|
||
if($event['type'] == 'select'){
|
||
$text .= '';
|
||
} else if($event['type'] == 'date'){
|
||
$text .= '<p><b>'.$event['name'].'</b>: '.date('d.m.Y', strtotime($event['value'])).'</p>';
|
||
} else if($event['type'] == 'checkbox'){
|
||
$text .= '';
|
||
|
||
} else if($event['type'] == 'file' && isset($event['value']['guid'])){
|
||
$doc_q = mysql_query("SELECT * FROM funnel_files WHERE guid = '".$event['value']['guid']."' and etap_id = {$stepId} and client_id = '".$clientId."'");
|
||
if($reqId > 0){
|
||
$doc_q = mysql_query("SELECT * FROM funnel_files WHERE guid = '".$event['value']['guid']."' and etap_id = {$stepId} and req_id = '".$reqId."'");
|
||
|
||
}
|
||
if(mysql_num_rows($doc_q) > 0){
|
||
$doc = mysql_fetch_assoc($doc_q);
|
||
$name_doc = 'https://uf.joywork.ru/upload/funnels/clients/'.$clientId.'/'.$doc['guid'].'.'.$doc['type'];
|
||
if($reqId > 0){
|
||
$name_doc = 'https://uf.joywork.ru/upload/funnels/req/'.$reqId.'/'.$doc['guid'].'.'.$doc['type'];
|
||
}
|
||
|
||
$text .= '<p><b>'.$event['name'].'</b>: <a title="Скачать" download href="/download_file.php?guid='.$doc['guid'].'">'.$doc['name'].'</a></p>';
|
||
}
|
||
} else if($event['type'] == 'deposit' && (int)$event['value'] > 0){
|
||
$text .= '<p><b>'.$event['name'].'</b>: '.clearInputElement($event['value']).'</p>';
|
||
if($clientId > 0){
|
||
/**
|
||
* 28.07.2023 Игорь по согласованию со Станиславом сказал задатки на ответственных фиксировать
|
||
*/
|
||
$who_work = $userId;
|
||
$sql_cl = "SELECT id, who_work FROM clients WHERE id = {$clientId}";
|
||
$q_cl = mysql_query($sql_cl);
|
||
$r_cl = mysql_fetch_assoc($q_cl);
|
||
if($r_cl['who_work'] > 0){
|
||
$who_work = (int)$r_cl['who_work'];
|
||
}
|
||
$sql_d = "SELECT id FROM deposits_clients_req WHERE client_id = {$clientId} AND funnel_id={$funnelId} AND step_id = {$stepId}";
|
||
$q_d = mysql_query($sql_d);
|
||
$deposit = (int)$event['value'];
|
||
if(mysql_num_rows($q_d) > 0){
|
||
$id_d = mysql_result($q_d, 0);
|
||
|
||
$sql_up_d = "UPDATE deposits_clients_req SET deposit = {$deposit}, created_at= NOW(), user_id={$who_work} WHERE id = {$id_d}";
|
||
mysql_query($sql_up_d);
|
||
|
||
} else {
|
||
$sql_in_d = "INSERT INTO deposits_clients_req SET deposit = {$deposit}, funnel_id={$funnelId}, step_id={$stepId}, user_id={$who_work}, client_id={$clientId}";
|
||
mysql_query($sql_in_d);
|
||
}
|
||
}
|
||
if($reqId > 0){
|
||
|
||
/**
|
||
* 28.07.2023 Игорь по согласованию со Станиславом сказал задатки на ответственных фиксировать
|
||
*/
|
||
$who_work = $userId;
|
||
$sql_req = "SELECT id, who_work FROM requisitions WHERE id = {$reqId}";
|
||
$q_req = mysql_query($sql_req);
|
||
$r_req = mysql_fetch_assoc($q_req);
|
||
if($r_req['who_work'] > 0){
|
||
$who_work = (int)$r_req['who_work'];
|
||
}
|
||
|
||
$sql_d = "SELECT id FROM deposits_clients_req WHERE req_id = {$reqId} AND funnel_id={$funnelId} AND step_id = {$stepId}";
|
||
$q_d = mysql_query($sql_d);
|
||
$deposit = (int)$event['value'];
|
||
if(mysql_num_rows($q_d) > 0){
|
||
$id_d = mysql_result($q_d, 0);
|
||
|
||
$sql_up_d = "UPDATE deposits_clients_req SET deposit = {$deposit}, created_at= NOW(), user_id={$who_work} WHERE id = {$id_d}";
|
||
mysql_query($sql_up_d);
|
||
|
||
} else {
|
||
$sql_in_d = "INSERT INTO deposits_clients_req SET deposit = {$deposit}, funnel_id={$funnelId}, step_id = {$stepId}, user_id={$who_work}, req_id={$reqId}";
|
||
mysql_query($sql_in_d);
|
||
}
|
||
}
|
||
} else {
|
||
$text .= '<p><b>'.$event['name'].'</b>: '.clearInputElement($event['value']).'</p>';
|
||
}
|
||
|
||
}
|
||
// $text = clearInputElement($text);
|
||
if($text != ''){
|
||
$sql_e = "INSERT INTO user_client_events SET user_id = {$userId}, client_id = {$clientId}, type='step', checklist=1, name = '{$stepName}', comment = '{$text}'";
|
||
if($reqId > 0){
|
||
$sql_e = "INSERT INTO user_client_events SET user_id = {$userId}, req_id = {$reqId}, type='step', checklist=1, name = '{$stepName}', comment = '{$text}'";
|
||
}
|
||
if(!mysql_query($sql_e)){
|
||
echo mysql_error();
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
|
||
/* $res = get_class_etap($clientId, $funnelId);
|
||
echo json_encode($res);*/
|
||
echo 1;
|
||
exit();
|
||
}
|
||
|
||
|
||
if($request == 'saveUpdateUser'){
|
||
$userId = $data->user_id;
|
||
$doers = $data->doers;
|
||
$clientId = 0;
|
||
$reqId = 0;
|
||
if(isset($data->client_id)){
|
||
$clientId = (int)$data->client_id;
|
||
}
|
||
|
||
if(isset($data->req_id)){
|
||
$reqId = (int)$data->req_id;
|
||
}
|
||
$userObj = $data->user_obj;
|
||
$objects = $data->objects;
|
||
$agency = array();
|
||
if($clientId > 0 || $reqId > 0){
|
||
foreach($doers as $doer){
|
||
if($doer->id != $userId){
|
||
/* if($doer -> isManager !== false){
|
||
$agency[$doer ->manager ->id] = 0;
|
||
$sql_conf = "INSERT INTO `events_clients` (`user_id`, `client_id`, `from_id`, `event`) VALUES (".$userId.", ".$clientId.", ".$doer ->manager ->id.", 'transmitted_parallel')";
|
||
mysql_query($sql_conf);
|
||
}*/
|
||
// if($doer->isAgents !== false){
|
||
// foreach($doer->agents as $ag){
|
||
$agency[$doer->id] = 0;
|
||
$sql_conf = "INSERT INTO `events_clients` (`user_id`, `client_id`, `from_id`, `event`) VALUES (".$userId.", ".$clientId.", ".$doer->id.", 'transmitted_parallel')";
|
||
if($reqId > 0){
|
||
$sql_conf = "INSERT INTO `events_clients` (`user_id`, `req_id`, `from_id`, `event`) VALUES (".$userId.", ".$reqId.", ".$doer->id.", 'transmitted_parallel')";
|
||
|
||
}
|
||
mysql_query($sql_conf);
|
||
// }
|
||
// }
|
||
}
|
||
}
|
||
// doers = только партнёры (в дополнение к ответственному who_work).
|
||
// Если реальных партнёров нет (список пуст или содержит только самого инициатора) —
|
||
// не трогаем doers/requisition_doers/clients_doers: инициатор уже видит заявку через who_work/user_id.
|
||
if (!empty($agency)) {
|
||
$sql = "UPDATE clients SET doers_confirm = 0, doer_clients= 0, doers = '". clearInputElement(json_encode($agency))."' WHERE id = ".$clientId;
|
||
if($reqId > 0){
|
||
$sql = "UPDATE requisitions SET doers_confirm = 0, doer_clients= 0, doers = '". clearInputElement(json_encode($agency))."' WHERE id = ".$reqId;
|
||
}
|
||
// echo $sql;
|
||
if(!mysql_query($sql)){
|
||
echo mysql_error();
|
||
} else {
|
||
//пишем в отдельную таблицу
|
||
if($clientId > 0){
|
||
mysql_query("DELETE FROM clients_doers WHERE client_id = {$clientId}");
|
||
foreach($agency as $key => $agent){
|
||
$sql_i = "INSERT INTO clients_doers (client_id, user_id, confirm) VALUES (" . $clientId . ", ". $key . ", " . $agent . ")";
|
||
|
||
if(!mysql_query($sql_i)) {
|
||
echo mysql_error();
|
||
}
|
||
}
|
||
}
|
||
if($reqId > 0){
|
||
//сначала чистим
|
||
mysql_query("DELETE FROM requisition_doers WHERE requisition_id = {$reqId}");
|
||
//потом вставлям новое
|
||
foreach($agency as $key => $agent){
|
||
$sql_i = "INSERT INTO requisition_doers (requisition_id, user_id, confirm) VALUES (" . $reqId . ", ". $key . ", " . $agent . ")";
|
||
if(!mysql_query($sql_i)) {
|
||
echo mysql_error();
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
//Передача объекта
|
||
if($userObj != 'no'){
|
||
|
||
$sql_user = "SELECT id, phone, agency_name, first_name, last_name, middle_name, agency FROM users WHERE id = ".(int)$userObj;
|
||
$q_user = mysql_query($sql_user);
|
||
$r_user = mysql_fetch_assoc($q_user);
|
||
$sobstv = trim($r_user['last_name'] . ' ' . $r_user['first_name'] . ' ' . $r_user['middle_name']);
|
||
if($r_user['agency'] == 1){
|
||
$sobstv = $sobstv . ', агентство ' . $r_user['agency_name'];
|
||
}
|
||
$dop_text = "Переданы объект(ы): ";
|
||
foreach ($objects as $object) {
|
||
$sql_up = "UPDATE objects SET id_add_user = '".(int)$userObj."', phone='".$r_user['phone']."', sobstv='".$sobstv."' WHERE id = ".$object->id;
|
||
if($dop_text != 'Переданы объект(ы): ') $dop_text .= ', ';
|
||
$dop_text .= $object->nazv.' ('.$object->adres.' '.$object->dom.')';
|
||
if(mysql_query($sql_up)){
|
||
$sql_conf = "INSERT INTO `events_clients` (`user_id`, `client_id`, `from_id`, `event`, `dop_text`, `read`) VALUES
|
||
(".$userId.", ".$clientId.", ".(int)$userObj.", 'update', '".$dop_text."', '1')";
|
||
mysql_query($sql_conf);
|
||
}
|
||
}
|
||
//$sql_up = "UPDATE objects SET id_add_user = '".(int)$userObj."', phone='".$r_user['phone']."', sobstv='".$sobstv."' WHERE id = ".$object;
|
||
//echo $sql_up;
|
||
//mysql_query($sql_up);
|
||
}
|
||
}
|
||
}
|
||
|
||
//Объекты клиента для передачи
|
||
if($request == 'get_objects'){
|
||
$clientId = $data->client_id;
|
||
$is_confirm = false;
|
||
$return_null = false;
|
||
if(isset($data->is_confirm)){
|
||
$is_confirm = (bool)$data->is_confirm;
|
||
}
|
||
$objects = [];
|
||
$sql = "SELECT * FROM `client_objects` WHERE client_id = {$clientId}";
|
||
$q = mysql_query($sql);
|
||
while($r = mysql_fetch_assoc($q)){
|
||
$objects[] = (int)$r['object_id'];
|
||
}
|
||
if(!empty($objects)){
|
||
if($is_confirm){
|
||
$sql_con = "SELECT * FROM client_confirm_objects WHERE client_id = {$clientId} AND status = 0";
|
||
$q_con = mysql_query($sql_con);
|
||
if(mysql_num_rows($q_con) > 0){
|
||
$return_null = true;
|
||
}
|
||
}
|
||
|
||
if(!$return_null){
|
||
$sql_o = "SELECT id, nazv, adres, dom FROM objects WHERE id in (".implode(',', $objects).")";
|
||
$q_o = mysql_query($sql_o);
|
||
$res = [];
|
||
while ($r_o = mysql_fetch_assoc($q_o)) {
|
||
$res[] = $r_o;
|
||
}
|
||
echo json_encode($res);
|
||
exit();
|
||
|
||
} else {
|
||
echo 0;
|
||
exit();
|
||
}
|
||
} else {
|
||
echo 0;
|
||
exit();
|
||
}
|
||
}
|
||
|
||
//Данные, ранее сохраненные, по этапу
|
||
if($request == 'openDetailsStep'){
|
||
|
||
/*if($_SESSION['id'] == 5238){
|
||
error_reporting(E_ALL | E_STRICT);
|
||
ini_set('display_errors', 1);
|
||
}*/
|
||
|
||
|
||
|
||
|
||
$clientId = 0;
|
||
if(isset($data->client_id)){
|
||
$clientId = $data->client_id;
|
||
}
|
||
$stepId = $data->step_id;
|
||
$req_id = 0;
|
||
if(isset($data->req_id)){
|
||
$req_id = $data->req_id;
|
||
}
|
||
$adjacent_id = 0;
|
||
if(isset($data->adjacent_id)){
|
||
$adjacent_id = (int)$data->adjacent_id;
|
||
}
|
||
|
||
$section = 'client';
|
||
$parentId = 'client_id = '.$clientId;
|
||
$pole_parent = 'client_id';
|
||
|
||
$pole_parent_val = $clientId;
|
||
if($adjacent_id > 0) {
|
||
$section = 'adjacent';
|
||
$parentId = 'adjacent_id = '.$adjacent_id;
|
||
$pole_parent = 'adjacent_id';
|
||
$pole_parent_val = $adjacent_id;
|
||
} else if($req_id > 0) {
|
||
$section = 'req';
|
||
$parentId = 'req_id = '.$req_id;
|
||
$pole_parent = 'req_id';
|
||
$pole_parent_val = $req_id;
|
||
}
|
||
|
||
$sql = "SELECT * FROM `clients_funnel_step` WHERE client_id = {$clientId}";
|
||
if($clientId == 0){
|
||
$sql = "SELECT
|
||
req.`complex_room_id`,
|
||
req.`complex_status_id`,
|
||
cfs.*,
|
||
cr.`id` AS room_id,
|
||
cr.`type` AS room_type,
|
||
cr.`number` AS room_number,
|
||
cr.`floor_id` AS room_floor_id,
|
||
cr.`total_amount` AS room_total_amount,
|
||
cf.`complex_entrance_id` AS room_complex_entrance_id,
|
||
ch.`id` AS house_id,
|
||
ch.`name` AS house_name,
|
||
cl.`id` AS complex_id,
|
||
cl.`name` AS complex_name,
|
||
MAX(c_house_p_i.url) as plan_url
|
||
FROM `requisitions` AS req
|
||
LEFT JOIN `clients_funnel_step` AS cfs ON cfs.req_id = req.id
|
||
LEFT JOIN `complex_rooms` AS cr ON cr.id = req.complex_room_id
|
||
LEFT JOIN `complex_floors` AS cf ON cf.id = cr.floor_id
|
||
LEFT JOIN `complex_entrances` AS ce ON ce.id = cf.complex_entrance_id
|
||
LEFT JOIN `complex_houses` AS ch ON ch.id = ce.complex_house_id
|
||
LEFT JOIN `complex_list` AS cl ON cl.id = ch.complex_id
|
||
LEFT JOIN `complex_rooms_plans` AS c_room_p ON c_room_p.room_id = cr.id
|
||
LEFT JOIN `complex_house_plans_images` AS c_house_p_i ON c_room_p.plan_id = c_house_p_i.plan_id AND c_house_p_i.position = 1
|
||
WHERE req.`id` = {$req_id}";
|
||
}
|
||
|
||
if($adjacent_id > 0){
|
||
$sql = "SELECT * FROM adjacent_funnels WHERE id = {$adjacent_id}";
|
||
}
|
||
|
||
|
||
|
||
$base_event = array();
|
||
$numders_event = array();
|
||
$sql_base_event = "SELECT * FROM steps_data WHERE section='{$section}' AND step_id = {$stepId} AND {$parentId} AND del = 0 order by number";
|
||
$q_base_event = mysql_query($sql_base_event);
|
||
while($r_base_event = mysql_fetch_assoc($q_base_event)){
|
||
$base_event[$r_base_event['number']] = $r_base_event;
|
||
}
|
||
|
||
|
||
//Проверка на смежную воронку
|
||
if($adjacent_id == 0){
|
||
$sqla = "SELECT * FROM adjacent_funnels WHERE";
|
||
if($req_id > 0){
|
||
$sqla .= " req_id = {$req_id}";
|
||
} else if($client_id > 0){
|
||
$sqla .= "client_id = {$client_id}";
|
||
}
|
||
//echo $sqla;
|
||
$adjacent_funnels = array();
|
||
$qa = mysql_query($sqla);
|
||
if(mysql_num_rows($qa) > 0){
|
||
while($ra = mysql_fetch_assoc($qa)){
|
||
if($ra['step_id_active'] > -1){
|
||
$ra['users'] = array();
|
||
$sql_funnel = "SELECT * FROM funnel WHERE id = {$ra['funnel_id']}";
|
||
$q_funnel = mysql_query($sql_funnel);
|
||
$funnel = mysql_fetch_assoc($q_funnel);
|
||
$funnel_sql_steps = "SELECT * FROM funnel_steps WHERE id=$stepId";
|
||
$close_step = false;
|
||
$close_step_active = false;
|
||
$funnel_step = mysql_query($funnel_sql_steps);
|
||
$step = mysql_fetch_assoc($funnel_step);
|
||
//if($_SESSION['id'] == 5238){
|
||
/* error_reporting(E_ALL | E_STRICT);
|
||
ini_set('display_errors', 1);*/
|
||
$pole_prev = json_decode(htmlspecialchars_decode($step['pole_prev']), true);
|
||
//var_dump($pole_prev);
|
||
if(isset($pole_prev['steps_close_main_funnel']) && !empty($pole_prev['steps_close_main_funnel'])){
|
||
foreach($pole_prev['steps_close_main_funnel'] as $funnel_step){
|
||
if($funnel_step['funnel'] == $funnel['id']){
|
||
$close_step = $funnel_step['step'];
|
||
}
|
||
}
|
||
}
|
||
// }
|
||
if($close_step){
|
||
$funnelClass = new Funnel();
|
||
$res = $funnelClass->get_class_etap(array(), $req_id, $funnel['id'], $adjacent_id);
|
||
foreach($res['bar'] as $bar_step){
|
||
if($bar_step['id'] == $close_step){
|
||
if($bar_step['isActive'] > 0){
|
||
$close_step_active = true;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
$ra['funnel_name'] = $funnel['name'];
|
||
$ra['who_work'] = (int)$ra['who_work'];
|
||
$ra['users'][] = array('code'=>0, 'name'=>'Весь отдел (общие)');
|
||
$ra['save_whowork_adjacent'] = false;
|
||
$ra['load_save_whowork_adjacent'] = false;
|
||
if(!empty($funnel['users_no_see'])){
|
||
$ids_users = json_decode($funnel['users_no_see']);
|
||
if(!empty($ids_users)){
|
||
$sql_users = "SELECT * FROM users WHERE id in (".implode(',', $ids_users).")";
|
||
$q_users = mysql_query($sql_users);
|
||
while($r_users = mysql_fetch_assoc($q_users)){
|
||
$fio = trim($r_users['last_name'] . ' ' . $r_users['first_name'] . ' ' . $r_users['middle_name']);
|
||
$ra['users'][] = array('code'=>(int)$r_users['id'], 'name'=>$fio);
|
||
}
|
||
}
|
||
}
|
||
if(!$close_step_active){
|
||
$adjacent_funnels[] = $ra;
|
||
}
|
||
}
|
||
}
|
||
if(count($adjacent_funnels) > 0){
|
||
$stepArr = array();
|
||
$stepArr['adjacent_funnels'] = $adjacent_funnels;
|
||
$stepArr['no_close_step'] = true;
|
||
|
||
echo json_encode($stepArr, JSON_UNESCAPED_UNICODE);
|
||
exit();
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
try{
|
||
$q = mysql_query($sql);
|
||
if(mysql_num_rows($q) > 0){
|
||
$r = mysql_fetch_assoc($q);
|
||
if(!empty($r['values'])){
|
||
/*if($r['req_id'] == 598157){
|
||
var_dump($r['values']);
|
||
}*/
|
||
//$r['values'] = str_replace("\n"," ",$r['values']);
|
||
$str_value = htmlspecialchars_decode($r['values']);
|
||
$str_value = str_replace("\\n", " ", $str_value);
|
||
$str_value = str_replace("\n", " ", $str_value);
|
||
$str_value = str_replace("\\\"", "", $str_value);
|
||
// $str_value = str_replace("\\", "", $str_value);
|
||
|
||
$str_value = stripcslashes($str_value);
|
||
$str_value = str_replace(['"{', '}"'], ['{', '}'], $str_value);
|
||
$str_value = str_replace("\\", "-", $str_value);
|
||
|
||
$valarr = json_decode($str_value,true);
|
||
// $r['values'] = str_replace("\\","/",$r['values']);
|
||
// $valarr = json_decode($r['values'],true);
|
||
|
||
/*if($r['req_id'] == 598157){
|
||
var_dump($valarr);
|
||
}*/
|
||
$arr = $valarr;
|
||
if(isset($arr[$stepId])){
|
||
$temp_step = $arr[$stepId];
|
||
foreach ($temp_step as $step_key => $step) {
|
||
if($step['type'] == "checkbox"){
|
||
if(isset($step['value']) && !empty($step['value'])){
|
||
foreach($step['value'] as $key => $task){
|
||
$date_task = date('Y-m-d H:i:s', strtotime($task['date']));
|
||
$sql_tsk = "SELECT id FROM user_client_events WHERE type = '{$task['type']}' and schedule_date='{$date_task}'";
|
||
if($req_id > 0){
|
||
$sql_tsk .= " and req_id = {$req_id}";
|
||
} else if($client_id > 0){
|
||
$sql_tsk .= " and client_id = {$client_id}";
|
||
}
|
||
//echo $sql_tsk."\n";
|
||
$q_tsk = mysql_query($sql_tsk);
|
||
if(mysql_num_rows($q_tsk) == 0){
|
||
unset($temp_step[$step_key]['value'][$key]);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if(isset($temp_step['next_step_select']) && !is_array($temp_step['next_step_select'])){
|
||
if($temp_step['next_step_select'] > 0){
|
||
$sql_s = "SELECT * FROM funnel_steps WHERE id = {$temp_step['next_step_select']} AND deleted=0";
|
||
//echo $sql_s."\n";
|
||
$q_s = mysql_query($sql_s);
|
||
if(mysql_num_rows($q_s) > 0){
|
||
$r_s = mysql_fetch_assoc($q_s);
|
||
$temp_next = array();
|
||
$temp_next['id'] = array('id'=>$r_s['id'], 'name'=>$r_s['name']);
|
||
// $temp_next['name'] = $r_s['name'];
|
||
$temp_step['next_step_select'] = $temp_next;
|
||
//var_dump($temp_step['next_step_select']);
|
||
} else {
|
||
$temp_step['next_step_select'] = '';
|
||
}
|
||
} else {
|
||
// unset('next')
|
||
$temp_step['next_step_select'] = '';
|
||
}
|
||
$r = array_merge($r, $temp_step);
|
||
}
|
||
}
|
||
}
|
||
|
||
echo json_encode($r, JSON_UNESCAPED_UNICODE);
|
||
exit();
|
||
} else {
|
||
echo 0;
|
||
exit();
|
||
}
|
||
} catch (Exception $ex){
|
||
echo $ex->getMessage();
|
||
exit();
|
||
}
|
||
|
||
}
|
||
|
||
|
||
// Определение предыдущего этапа для открытия
|
||
if($request == 'openPrevStep'){
|
||
|
||
$reqId = 0;
|
||
$clientId = 0;
|
||
if(isset($data->client_id)){
|
||
$clientId = $data->client_id;
|
||
}
|
||
if(isset($data->req_id)){
|
||
$reqId = $data->req_id;
|
||
}
|
||
$adjacentId = 0;
|
||
if(isset($data->adjacent_id)){
|
||
$adjacentId = (int)$data->adjacent_id;
|
||
}
|
||
$funnelId = 0;
|
||
$stepId = 0;
|
||
if($adjacentId > 0){
|
||
$sql = "SELECT cfs.*, fs.name FROM `adjacent_funnels` as `cfs` LEFT JOIN `funnel_steps` as `fs` on cfs.step_id = fs.id WHERE cfs.id = {$adjacentId}";
|
||
$sql_funnel = "SELECT funnel_id, step_id FROM adjacent_funnels WHERE id = {$adjacentId}";
|
||
} else if($clientId > 0){
|
||
$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 = {$clientId}";
|
||
$sql_funnel = "SELECT funnel_id, step_id FROM clients WHERE id = {$clientId}";
|
||
} else if($reqId > 0){
|
||
$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 = {$reqId}";
|
||
$sql_funnel = "SELECT funnel_id, step_id FROM requisitions WHERE id = {$reqId}";
|
||
}
|
||
$funnelId = 0;
|
||
|
||
$q_funnel = mysql_query($sql_funnel);
|
||
$r_funnel = mysql_fetch_assoc($q_funnel);
|
||
if($r_funnel['funnel_id']) {
|
||
$funnelId = (int)$r_funnel['funnel_id'];
|
||
$stepId = (int)$r_funnel['step_id'];
|
||
}
|
||
$steps = array();
|
||
$temp_steps = array();
|
||
//echo $sql;
|
||
$funnel_sql = "SELECT * FROM funnel_steps WHERE funnel_id = " . $funnelId . " and deleted=0 order by order_number, branch";
|
||
/*if($_SESSION['id'] == 5238){
|
||
echo $funnel_sql;
|
||
}*/
|
||
|
||
|
||
$funnel_step = mysql_query($funnel_sql);
|
||
while ($step = mysql_fetch_assoc($funnel_step)) {
|
||
$steps[] = $step;
|
||
$st = deClearInputElements($step);
|
||
$next_step = json_decode($st['next_step'], true);
|
||
if($st['next_step_change'] == "Всегда один" && !empty($next_step) && isset($next_step[0])){
|
||
$temp_steps[$next_step[0]] = $step['id'];
|
||
}
|
||
}
|
||
|
||
/* if($_SESSION['id'] == 5238){
|
||
var_dump($temp_steps);
|
||
}*/
|
||
|
||
|
||
|
||
$r = array();
|
||
try{
|
||
$q = mysql_query($sql);
|
||
if(mysql_num_rows($q) > 0){
|
||
$r['res'] = mysql_fetch_assoc($q);
|
||
|
||
} else {
|
||
|
||
$r['res'] = 0;
|
||
|
||
}
|
||
$arr_steps = array();
|
||
foreach($steps as $step) {
|
||
$step_temp = array();
|
||
//if(isset($r['res']['step_id']) && )
|
||
if($step['id'] == $stepId){
|
||
//$steps[] = array('id'=>$step['id'], 'name'=>$step['name']);
|
||
break;
|
||
} else if($step['next_step_change'] == "Всегда один" || $step['main'] == 1) {
|
||
$step_temp = array('id'=>$step['id'], 'name'=>$step['name']);
|
||
if($step['main'] == 1) {
|
||
$step_temp['prev_step'] = 0;
|
||
} else if(isset($temp_steps[$step['id']])){
|
||
$step_temp['prev_step'] = (int)$temp_steps[$step['id']];
|
||
}
|
||
if(isset($step_temp['prev_step'])){
|
||
$arr_steps[] = $step_temp;
|
||
}
|
||
}
|
||
}
|
||
$r['steps'] = $arr_steps;
|
||
|
||
// Проверяем, есть ли сделка у заявки
|
||
$r['has_deal'] = false;
|
||
if ($reqId > 0) {
|
||
$sql_deal_check = mysql_query("SELECT id FROM deals WHERE (side_one_requisition_id = {$reqId} OR side_two_requisition_id = {$reqId}) AND status != 2 LIMIT 1");
|
||
if ($sql_deal_check && mysql_num_rows($sql_deal_check) > 0) {
|
||
$r['has_deal'] = true;
|
||
}
|
||
}
|
||
|
||
echo json_encode($r);
|
||
} catch (Exception $ex){
|
||
echo $ex->getMessage();
|
||
exit();
|
||
}
|
||
}
|
||
|
||
//Сопряженные поля
|
||
if($request == 'openLinkingStep'){
|
||
$reqId = 0;
|
||
$clientId = 0;
|
||
$step_id = 0;
|
||
$agency_id = (int)$data->agency_id;
|
||
$linking_steps = array();
|
||
if(isset($data->client_id)){
|
||
$clientId = $data->client_id;
|
||
}
|
||
if(isset($data->req_id)){
|
||
$reqId = $data->req_id;
|
||
}
|
||
if(isset($data->step_id)){
|
||
$step_id = (int)$data->step_id;
|
||
}
|
||
|
||
$linkingClass = new LinkingClass();
|
||
$fields = $linkingClass->getFixFields();
|
||
$forms = $linkingClass->getFixetForm();
|
||
//$fields = array();
|
||
$req = array();
|
||
//типы заявок для заявок
|
||
if($reqId > 0){
|
||
$sql_req = "SELECT * FROM requisitions WHERE id = {$reqId}";
|
||
$req = mysql_fetch_assoc(mysql_query($sql_req));
|
||
}
|
||
|
||
$sql_check = "SELECT * FROM linking_steps_client_req WHERE step_id = {$step_id}";
|
||
|
||
if($reqId > 0){
|
||
$sql_check .= " AND is_req > 0";
|
||
$reqClass = new Requisitions();
|
||
$fields_req = $reqClass->get_req_fields($agency_id, $reqId);
|
||
//($fields_req);
|
||
$linking_steps['values'] = $fields_req['values'];
|
||
|
||
|
||
|
||
}
|
||
$linking_steps['forms'] = array();
|
||
|
||
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($reqId > 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'] = !empty($r_check['view_next']) ? json_decode($r_check['view_next'], true) : null;
|
||
$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'] = !empty($r_check['view_next']) ? json_decode($r_check['view_next'], true) : null;
|
||
$r_check = $fr;
|
||
$linking_steps['fields'][] = $r_check;
|
||
}
|
||
}
|
||
|
||
// var_dump($fr);
|
||
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
} else {
|
||
foreach($fields as $field){
|
||
$req_types = array();
|
||
if($reqId > 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);
|
||
// Маскируем контактные данные клиента, если у пользователя включено скрытие
|
||
mask_client_contacts_inplace($r_cl);
|
||
$client_name = $r_cl['phone'].' '.$r_cl['fio'];
|
||
$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'] = !empty($r_check['view_next']) ? json_decode($r_check['view_next'], true) : null;
|
||
$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'] = !empty($r_check['view_next']) ? json_decode($r_check['view_next'], true) : null;
|
||
$linking_steps['fields'][] = $field;
|
||
}
|
||
}
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
$sql_check = "SELECT * FROM linkingform_steps_client_req WHERE step_id = {$step_id}";
|
||
|
||
if($reqId > 0){
|
||
$sql_check .= " AND is_req > 0";
|
||
|
||
}
|
||
|
||
if($clientId > 0) {
|
||
$sql_check .= " AND is_client > 0";
|
||
}
|
||
|
||
$q_check = mysql_query($sql_check);
|
||
while($r_check = mysql_fetch_assoc($q_check)){
|
||
foreach($forms as $form){
|
||
$req_types = array();
|
||
if($reqId > 0){
|
||
|
||
if($form['is_req'] > 0 && $r_check['form_id'] == $form['id']){
|
||
if($form['req_type'] === 0 || empty($form['req_type'])){
|
||
|
||
$linking_steps['forms'][] = $form;
|
||
} else if(!empty($form['req_type'])){
|
||
$req_types = json_decode($form['req_type'], true);
|
||
|
||
if(in_array((int)$req['type_id'], $req_types)){
|
||
$linking_steps['forms'][] = $form;
|
||
}
|
||
}
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
//var_dump($linking_steps['values']);
|
||
//$linking_steps['value'] = array();
|
||
|
||
echo json_encode($linking_steps, JSON_UNESCAPED_UNICODE);
|
||
exit();
|
||
|
||
}
|
||
|
||
//Сохранение открытия этапа.
|
||
if($request == 'saveOpenPrevStep'){
|
||
/*error_reporting(E_ALL | E_STRICT);
|
||
ini_set('display_errors', 1);*/
|
||
$nowStepId = (int)$data->now_step_id;
|
||
$userId = $data->user_id;
|
||
$reqId = 0;
|
||
$clientId = 0;
|
||
$stepId = 0;
|
||
$is_Other_prev_step = (int)$data->is_Other_prev_step;
|
||
$stepInfo = $data->stepInfo;
|
||
if(isset($data->client_id)){
|
||
$clientId = $data->client_id;
|
||
}
|
||
if(isset($data->req_id)){
|
||
$reqId = $data->req_id;
|
||
}
|
||
|
||
$adjacentId = 0;
|
||
if(isset($data->adjacent_id)){
|
||
$adjacentId = (int)$data->adjacent_id;
|
||
}
|
||
|
||
|
||
$id = $data->step_id;
|
||
$sql = "SELECT cfs.*, fs.name, fs.stage, fs.funnel_id FROM `clients_funnel_step` as `cfs` LEFT JOIN `funnel_steps` as `fs` on cfs.step_id = fs.id ";
|
||
if($clientId > 0){
|
||
$sql .= " WHERE cfs.client_id = {$clientId}";
|
||
|
||
} else if ($reqId > 0){
|
||
$sql .= " WHERE cfs.req_id = {$reqId}";
|
||
}
|
||
|
||
if($adjacentId > 0){
|
||
$sql = "SELECT cfs.*, fs.name, fs.stage, fs.funnel_id FROM `adjacent_funnels` as `cfs` LEFT JOIN `funnel_steps` as `fs` on cfs.step_id = fs.id WHERE cfs.id = {$adjacentId}";
|
||
|
||
}
|
||
|
||
$q = mysql_query($sql);
|
||
if(mysql_num_rows($q) > 0){
|
||
$r = mysql_fetch_assoc($q);
|
||
$funnelId = $r['funnel_id'];
|
||
$id = $r['id'];
|
||
$stepId = (int)$r['step_id'];
|
||
$is_other = false;
|
||
if($is_Other_prev_step > 0){
|
||
$is_other = true;
|
||
}
|
||
if(!empty($r['values']) || $is_other){
|
||
$valarr = json_decode(str_replace(["\n","\t","\r"],"",$r['values']),true);
|
||
$arr = deClearInputElements($valarr);
|
||
$stepArr = json_decode(str_replace(["\n","\t","\r"],"",$arr[$r['step_id']]),true);
|
||
|
||
|
||
if(isset($stepArr['prev_id']) || $is_other){
|
||
$prev_id = false;
|
||
$prev_next_id = 0;
|
||
if($is_other){
|
||
//var_dump($stepInfo);
|
||
$prev_id = $stepInfo->prev_step;
|
||
$prev_next_id = $stepInfo->id;
|
||
} else if(isset($stepArr['prev_id'])) {
|
||
$prev_id = (int)$stepArr['prev_id'];
|
||
$prev_next_id = $stepArr['prev_next_id'];
|
||
}
|
||
|
||
if($prev_id !== false){
|
||
|
||
$sql = "UPDATE clients_funnel_step SET step_id = ".$prev_id.", next_id = '".$prev_next_id."' WHERE id = ".$id;
|
||
if($adjacentId > 0){
|
||
$sql = "UPDATE adjacent_funnels SET step_id = ".$prev_id.", next_id = '".$prev_next_id."' WHERE id = ".$adjacentId;
|
||
}
|
||
// echo $sql;
|
||
|
||
mysql_query($sql);
|
||
|
||
$sqlSelectRequisition = mysql_query("SELECT `complex_room_id` FROM `requisitions` WHERE id = {$reqId}");
|
||
$requisition = mysql_fetch_assoc($sqlSelectRequisition);
|
||
|
||
if ($requisition['complex_room_id'])
|
||
{
|
||
$complex = new Complex();
|
||
$complex->generate_room_reservations_positions($requisition['complex_room_id']);
|
||
}
|
||
|
||
$historyRequisition = !empty($r['history_requisition']) ? json_decode($r['history_requisition']) : [];
|
||
$currentComplexData = (object)[];
|
||
$newHistoryRequisition = [];
|
||
|
||
foreach ($historyRequisition as $history)
|
||
{
|
||
if ($history->step_id == $stepId)
|
||
{
|
||
$currentComplexData = $history;
|
||
}
|
||
|
||
if ($history->step_id != $stepId)
|
||
{
|
||
$newHistoryRequisition[] = $history;
|
||
}
|
||
}
|
||
|
||
$newHistoryRequisition = json_encode($newHistoryRequisition, JSON_UNESCAPED_UNICODE);
|
||
|
||
$sqlClientsFunnelStepUpdate = "UPDATE `clients_funnel_step` SET `history_requisition` = '{$newHistoryRequisition}' WHERE `id` = $id";
|
||
mysql_query($sqlClientsFunnelStepUpdate);
|
||
|
||
if ($currentComplexData)
|
||
{
|
||
if (array_key_exists('complex_room_id', $currentComplexData) || array_key_exists('complex_status_id', $currentComplexData) || array_key_exists('reservation_updated_at', $currentComplexData))
|
||
{
|
||
mysql_query("UPDATE `requisitions` SET `complex_room_id` = $currentComplexData->complex_room_id, `complex_status_id` = $currentComplexData->complex_status_id, `reservation_updated_at` = '{$currentComplexData->reservation_updated_at}' WHERE id = {$reqId}");
|
||
}
|
||
else
|
||
{
|
||
mysql_query("UPDATE `requisitions` SET `complex_room_id` = NULL, `complex_status_id` = NULL, `reservation_updated_at` = NULL WHERE id = {$reqId}");
|
||
}
|
||
|
||
if (!empty($currentComplexData->complex_room_id))
|
||
{
|
||
$complex = new Complex();
|
||
$complex->generate_room_reservations_positions($currentComplexData->complex_room_id);
|
||
}
|
||
}
|
||
|
||
foreach ($stepArr as $step) {
|
||
|
||
if(isset($step['type']) && $step['type'] == 'deposit'){
|
||
|
||
if($clientId > 0 && $stepId > 0){
|
||
|
||
$sql_del = "DELETE FROM deposits_clients_req WHERE client_id={$clientId} AND funnel_id = {$funnelId} AND step_id = {$stepId}";
|
||
|
||
mysql_query($sql_del);
|
||
} else if($reqId > 0 && $stepId > 0) {
|
||
|
||
$sql_del = "DELETE FROM deposits_clients_req WHERE req_id={$reqId} AND funnel_id = {$funnelId} AND step_id = {$stepId}";
|
||
$text_deposit = "Удалено: {$step['name']} при повторном открытии этапа «{$r['name']}»";
|
||
$sql_event = "INSERT INTO events_clients (user_id, from_id, req_id, `event`, dop_text, `read`) VALUES ({$userId}, {$userId}, {$reqId}, 'update', '{$text_deposit}', 1)";
|
||
|
||
|
||
mysql_query($sql_del);
|
||
mysql_query($sql_event);
|
||
}
|
||
} else if (isset($step['type']) && $step['type'] == 'commission'){
|
||
$sql_up = "UPDATE requisitions SET expected_commission = NULL WHERE id = {$reqId}";
|
||
mysql_query($sql_up);
|
||
$text_commission = "Удалено: {$step['name']} при повторном открытии этапа «{$r['name']}»";
|
||
$sql_event = "INSERT INTO events_clients (user_id, from_id, req_id, `event`, dop_text, `read`) VALUES ({$userId}, {$userId}, {$reqId}, 'update', '{$text_commission}', 1)";
|
||
mysql_query($sql_event);
|
||
} else if (isset($step['type']) && $step['type'] == 'expenses'){
|
||
$sql_del = "DELETE FROM expenses_req WHERE req_id={$reqId} AND funnel_id = {$funnelId} AND step_id = {$stepId}";
|
||
$text_expenses = "Удалено: {$step['name']} при повторном открытии этапа «{$r['name']}»";
|
||
$sql_event = "INSERT INTO events_clients (user_id, from_id, req_id, `event`, dop_text, `read`) VALUES ({$userId}, {$userId}, {$reqId}, 'update', '{$text_expenses}', 1)";
|
||
mysql_query($sql_del);
|
||
mysql_query($sql_event);
|
||
}
|
||
}
|
||
$sqlname = mysql_query("SELECT `name`, `id`, `funnel_id`,`stage` FROM funnel_steps WHERE id = ".$prev_id);
|
||
$prev = mysql_fetch_assoc($sqlname);
|
||
|
||
|
||
if($prev['stage'] == 'В работе' && $adjacentId == 0){
|
||
if($clientId > 0){
|
||
$sql_open = "UPDATE clients SET deleted = 0, stage = 1, confirm = 1 WHERE id = ".$clientId;
|
||
} else if($reqId > 0){
|
||
$sql_open = "UPDATE requisitions SET deleted = 0, stage = 1, confirm = 1 WHERE id = ".$reqId;
|
||
}
|
||
mysql_query($sql_open);
|
||
|
||
}
|
||
|
||
|
||
$prev_etap = $nowStepId;
|
||
if($adjacentId > 0){
|
||
$prev_etap = $r['step_id_active'];
|
||
}
|
||
$sqlname = mysql_query("SELECT `name`, `id`, `funnel_id`,`stage` FROM funnel_steps WHERE id = {$prev_etap}");
|
||
$prevName = mysql_fetch_assoc($sqlname);
|
||
|
||
|
||
$dop_text = 'c «'.$prevName['name'].'» на «'.$r['name'].'» (Этап открыт повторно)';
|
||
if($clientId > 0){
|
||
$sql_in ="INSERT INTO `events_clients` SET user_id = {$userId}, client_id = {$clientId}, event='stageedit', `read`=1, from_id = 0, dop_text='{$dop_text}'";
|
||
} else if($reqId >0){
|
||
$sql_in ="INSERT INTO `events_clients` SET user_id = {$userId}, req_id = {$reqId}, event='stageedit', `read`=1, from_id = 0, dop_text='{$dop_text}'";
|
||
|
||
}
|
||
mysql_query($sql_in);
|
||
|
||
// Отмена сделки при возврате этапа
|
||
$is_cancel_deal = isset($data->is_cancel_deal) ? (int)$data->is_cancel_deal : 0;
|
||
if ($is_cancel_deal && $reqId > 0) {
|
||
// Находим сделку, связанную с заявкой
|
||
$sql_deal = mysql_query("SELECT id, side_one_requisition_id, side_two_requisition_id FROM deals WHERE (side_one_requisition_id = {$reqId} OR side_two_requisition_id = {$reqId}) AND status != 2 LIMIT 1");
|
||
if ($sql_deal && mysql_num_rows($sql_deal) > 0) {
|
||
$row_deal = mysql_fetch_assoc($sql_deal);
|
||
$dealId = (int)$row_deal['id'];
|
||
// Ставим статус 2 (отменена)
|
||
mysql_query("UPDATE deals SET status = 2 WHERE id = {$dealId}");
|
||
// Обнуляем deal_id у связанных заявок
|
||
$linkedReqs = array_filter(array_map('intval', [$row_deal['side_one_requisition_id'], $row_deal['side_two_requisition_id']]));
|
||
if (!empty($linkedReqs)) {
|
||
mysql_query("UPDATE requisitions SET deal_id = NULL WHERE id IN (" . implode(',', $linkedReqs) . ")");
|
||
}
|
||
// Запись в историю
|
||
//mysql_query("INSERT INTO user_client_events (user_id, req_id, deal_id, type, name, comment, create_date) VALUES ({$userId}, {$reqId}, {$dealId}, 'deal', 'Отмена сделки', 'Сделка отменена при возврате на предыдущий этап', NOW())");
|
||
}
|
||
}
|
||
|
||
if($clientId > 0){
|
||
if((int)$funnelId == 0){
|
||
$sql_f = "SELECT funnel_id FROM clients WHERE id = {$clientId}";
|
||
$q_f = mysql_query($sql_f);
|
||
$r_f = mysql_fetch_assoc($q_f);
|
||
if($r_f['funnel_id'] > 0) $funnelId = (int)$r_f['funnel_id'];
|
||
}
|
||
|
||
$res = get_class_etap($clientId, $funnelId);
|
||
$cl = new Clients();
|
||
$cl->prev_step_event($clientId, $res['stageId']);
|
||
|
||
echo json_encode($res);
|
||
} else if ($reqId > 0){
|
||
$req = new Requisitions(null, true);
|
||
$res = $req->get_class_etap($reqId, $funnelId);
|
||
$req->prev_step_event($reqId, $res['stageId'], true);
|
||
|
||
echo 1;
|
||
} else {
|
||
echo 1;
|
||
}
|
||
exit();
|
||
} else {
|
||
echo 0;
|
||
exit();
|
||
}
|
||
}
|
||
} else {
|
||
echo 0;
|
||
exit();
|
||
}
|
||
// $sql = "UPDATE clients_funnel_step SET step_id = ".$stepId.", next_id = '".$next_id."' WHERE id = ".$id;
|
||
|
||
if ($reqId)
|
||
{
|
||
mysql_query("UPDATE `requisitions` SET `complex_room_id` = NULL, `complex_status_id` = NULL WHERE id = {$reqId}");
|
||
}
|
||
}
|
||
}
|
||
|
||
//Дополнительные настройки при закрытии этапа
|
||
if($request == 'get_pole_dop_details'){
|
||
$result = array();
|
||
$req_id = 0;
|
||
$client_id = 0;
|
||
$pole_dop = $data->pole_dop;
|
||
$user_id = $data->user_id;
|
||
if(isset($data->req_id)){
|
||
$req_id = (int)$data->req_id;
|
||
}
|
||
if(isset($data->client_id)){
|
||
$client_id = $data->client_id;
|
||
}
|
||
if(isset($pole_dop->add_contract_close_step) && $pole_dop->add_contract_close_step > 0){
|
||
$parent_id = 0;
|
||
$type_contract = '';
|
||
if($client_id > 0){
|
||
$parent_id = $client_id;
|
||
$type_contract = 'client';
|
||
} else if ($req_id>0){
|
||
$parent_id = $req_id;
|
||
$type_contract = 'req';
|
||
}
|
||
$result['add_contract_close_step'] = array('parent_id'=>$parent_id, 'type'=>$type_contract);
|
||
}
|
||
if(isset($pole_dop->add_activity_close_step) && $pole_dop->add_activity_close_step){
|
||
$user = new User();
|
||
$user->get($user_id);
|
||
//Теги
|
||
$arrActivities = array();
|
||
$arrActivitiesName = array();
|
||
$arrActivitiesVal = array();
|
||
$sql_adv = "SELECT * FROM `activities` WHERE `user_id` = '".$user->id."' OR `manager_id` = '".$user->id."'";
|
||
if ($user->id_manager)
|
||
$sql_adv .= " OR `manager_id` = '".$user->id_manager."' OR `user_id` = '".$user->id_manager."'";
|
||
|
||
// if ($this->agencyId)
|
||
$sql_adv .= " OR `manager_id` = '".$user->agencyId."' OR `user_id` = '".$user->agencyId."'";
|
||
|
||
$sql_adv .= ' ORDER BY `name`';
|
||
$q_adv = mysql_query($sql_adv);
|
||
$rows_adv = mysql_num_rows($q_adv);
|
||
if ($rows_adv > 0) {
|
||
while ($r_adv = mysql_fetch_assoc($q_adv)) {
|
||
$arrActivities[] = array('id'=>$r_adv['id'], 'name'=>trim($r_adv['name']));
|
||
$arrActivitiesName['act'.$r_adv['id']] = trim($r_adv['name']);
|
||
//$arrActivitiesVal[] = $r_adv['id'];
|
||
}
|
||
}
|
||
|
||
//теги текущей заявки или клиента
|
||
$sql_a = '';
|
||
if($req_id > 0){
|
||
$sql_a = "SELECT * FROM requisitions_activities WHERE req_id = {$req_id}";
|
||
} else if($client_id > 0){
|
||
$sql_a = "SELECT * FROM clients_activities WHERE client_id = {$client_id}";
|
||
}
|
||
$q_a = mysql_query($sql_a);
|
||
while($r_a = mysql_fetch_assoc($q_a)){
|
||
$arrActivitiesVal[] = $r_a['activity_id'];
|
||
}
|
||
|
||
$result['add_activity_close_step'] = array('on'=>1,'activites'=>$arrActivities, 'activities_name'=>$arrActivitiesName, 'activities_val'=>$arrActivitiesVal);
|
||
}
|
||
|
||
if($req_id > 0 && $client_id == 0){
|
||
$sql_req = "SELECT *, (SELECT heir FROM requisitions_type WHERE id = requisitions.type_id) as heir FROM requisitions WHERE id={$req_id}";
|
||
$q_req = mysql_query($sql_req);
|
||
$req = mysql_fetch_assoc($q_req);
|
||
|
||
if(isset($pole_dop->advert_close) && $pole_dop->advert_close > 0){
|
||
if(($req['type_id'] == 2 || $req['heir'] == 2) && $req['object_id'] > 0){
|
||
$sql_obj = "SELECT * FROM objects WHERE id = {$req['object_id']}";
|
||
$q_obj = mysql_query($sql_obj);
|
||
$obj = mysql_fetch_assoc($q_obj);
|
||
$result['object'] = $obj;
|
||
}
|
||
}
|
||
if(isset($pole_dop->avtopoisk_close) && $pole_dop->avtopoisk_close > 0){
|
||
|
||
$autosearch_instce = new AutoSearch();
|
||
if($req['type_id'] == 1 || $req['heir'] == 1 || $req['type_id'] == 4 || $req['heir'] == 4){
|
||
$req['autoSearchEnabled'] = 0;
|
||
if ($filter = $autosearch_instce->getFilterByReq($req['id'], $user_id, false)) {
|
||
|
||
if (isset($filter['id'])) {
|
||
$req['autosearch_id'] = intval($filter['id']);
|
||
$req['autosearch'] = [
|
||
'active' => intval($filter['is_active']),
|
||
'count' => $filter['count'],
|
||
'is_search' => intval($filter['is_search']),
|
||
'is_reverse' => intval($filter['is_reverse']),
|
||
'total' => $filter['total'],
|
||
'error' => $filter['error']
|
||
];
|
||
|
||
if($req['autosearch_id'] > 0){
|
||
$req['autoSearchEnabled'] = 1;
|
||
}
|
||
|
||
$info = '';
|
||
$comment = '';
|
||
$info_ar = $autosearch_instce->getFilterInfo($filter, true, true);
|
||
foreach ($info_ar as $key => $filter) {
|
||
|
||
if (isset($filter['label']) && isset($filter['value'])) {
|
||
if ($key === "comment")
|
||
$comment = '<b>' . $filter['label'] . ':</b> ' . $filter['value'];
|
||
else
|
||
$info .= ' <b>' . $filter['label'] . ':</b> ' . $filter['value'] . ';';
|
||
}
|
||
|
||
$req['autosearch']['filter'][$key] = [
|
||
'id' => $filter['id'],
|
||
'label' => $filter['label'],
|
||
'value' => $filter['value']
|
||
];
|
||
}
|
||
|
||
if (!empty($filter['geo'])) {
|
||
$geo = (array)json_decode($filter['geo'], true);
|
||
$geo = array_filter(array_map(function($item) {
|
||
return !empty($item);
|
||
}, $geo));
|
||
|
||
$req['autosearch']['filter']['geo'] = [
|
||
'id' => 'geo',
|
||
'label' => 'Гео',
|
||
'value' => declOfNum(count($geo), ['%d уточнение', '%d уточнения', '%d уточнений'])
|
||
];
|
||
|
||
$info .= ' <b>Гео:</b> ' . declOfNum(count($geo), ['%d уточнение', '%d уточнения', '%d уточнений']). ';';
|
||
}
|
||
|
||
if (!empty($info)) {
|
||
$req['autosearch_info'] = rtrim(trim($info), ';');
|
||
$req['autosearch_comment'] = trim($comment) ."<br/>". '<b>ID фильтра:</b> ' . $req['autosearch_id'];
|
||
}
|
||
}
|
||
}
|
||
$result['req'] = $req;
|
||
}
|
||
}
|
||
}
|
||
echo json_encode($result);
|
||
}
|
||
|
||
//Установка автопоиска в этапе
|
||
if($request == 'set_autosearch_pole_dop'){
|
||
/*error_reporting(E_ALL | E_STRICT);
|
||
ini_set('display_errors', 1);*/
|
||
$req_id = $data->req_id;
|
||
$autosearch_enabled = $data->autosearch_enabled;
|
||
$user_id = $data->user_id;
|
||
$asfilter_id = $data->asfilter_id;
|
||
$sql_req = "SELECT *, (SELECT heir FROM requisitions_type WHERE id = requisitions.type_id) as heir FROM requisitions WHERE id={$req_id}";
|
||
$q_req = mysql_query($sql_req);
|
||
$req = mysql_fetch_assoc($q_req);
|
||
$autosearch_instce = new AutoSearch();
|
||
if ($req['type_id'] == 1 || $req['heir'] == 1 || $req['type_id'] == 4 || $req['heir'] == 4) {
|
||
if ($autosearch_enabled == 1 && intval($req['object_id']) > 0) {
|
||
|
||
$objToFilter = $autosearch_instce->syncObjectToFilter(
|
||
intval($req['asfilter_id']),
|
||
intval($req['object_id']),
|
||
intval($req['id']),
|
||
(intval($req['asfilter_id']) > 0)
|
||
);
|
||
|
||
if ($objToFilter['success'])
|
||
$req['asfilter_id'] = $objToFilter['filter_id'];
|
||
else
|
||
$errors = array_merge($errors, $objToFilter['errors']);
|
||
|
||
} else if ($autosearch_enabled == 0) {
|
||
$res = $autosearch_instce->deleteFilter(intval($asfilter_id), $user_id);
|
||
|
||
$req['asfilter_id'] = '0';
|
||
}
|
||
mysql_query("UPDATE requisitions SET asfilter_id = {$req['asfilter_id']} WHERE id = {$req['id']}");
|
||
echo json_encode($req);
|
||
}
|
||
}
|
||
|
||
//Получение объекта
|
||
if($request == 'get_object_pole_dop'){
|
||
$object_id = $data->object_id;
|
||
$sql_obj = "SELECT * FROM objects WHERE id = {$object_id}";
|
||
$q_obj = mysql_query($sql_obj);
|
||
$obj = mysql_fetch_assoc($q_obj);
|
||
echo json_encode($obj);
|
||
exit();
|
||
}
|
||
|
||
//смена имени файла
|
||
if($request == 'edit_file_name'){
|
||
$guid = $data->guid;
|
||
$name = $data->name;
|
||
$sql = "UPDATE clients_files SET name = '{$name}' WHERE guid = '{$guid}'";
|
||
mysql_query($sql);
|
||
|
||
}
|
||
|
||
//Добавление партнера
|
||
if($request == 'savePartnerUser'){
|
||
$userId = $data->user_id;
|
||
$doers = $data->doers;
|
||
$clientId =$data->client_id;
|
||
$reqId = $data->req_id;
|
||
$doers_old = array();
|
||
$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 = ".$clientId;
|
||
if($reqId > 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 = ".$reqId;
|
||
}
|
||
$q = mysql_query($sql);
|
||
$client = mysql_fetch_assoc($q);
|
||
|
||
if(!empty($client['doers'])){
|
||
$doers_old = json_decode(html_entity_decode($client['doers']), true);
|
||
}
|
||
|
||
/* if ($_SESSION['id'] == 21484) {
|
||
var_dump($doers_old);
|
||
}*/
|
||
$confirm = 1;
|
||
|
||
/*foreach($doers_old as $doer_old){
|
||
if($doer == 0) $confirm = 0;
|
||
}*/
|
||
$arrayStage = array(
|
||
1=>"Новый",
|
||
2=>"В работе",
|
||
3=>"Презентация",
|
||
4=>"Показ",
|
||
5=>"Бронь",
|
||
6=>"Подаем на ипотеку",
|
||
7=>"Сделка",
|
||
8=>"Закрыт"
|
||
);
|
||
|
||
|
||
$agency = array();
|
||
if (isset($doers_old[$userId])){
|
||
$agency[$userId] = 1;
|
||
}
|
||
foreach($doers as $doer){
|
||
//var_dump($doer);
|
||
if(isset($doer->code)) $doer = $doer->code;
|
||
if($doer != $userId){
|
||
|
||
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 (".$userId.", ".$clientId.", ".$doer.", 'transmitted_parallel')";
|
||
if($reqId > 0){
|
||
$sql_conf = "INSERT INTO `events_clients` (`user_id`, `req_id`, `from_id`, `event`) VALUES (".$userId.", ".$reqId.", ".$doer.", 'transmitted_parallel')";
|
||
|
||
}
|
||
mysql_query($sql_conf);
|
||
if($client['funnel_id'] == 0){
|
||
$step_id = $client['stage'];
|
||
$step_name = $arrayStage[$step_id];
|
||
} else {
|
||
$step_id = $client['step_id'];
|
||
$step_name = $client['name'];
|
||
}
|
||
$sql_stap = "INSERT INTO `doers_emp_client` (`user_id`, `doer_id`, `who_work`, `client_id`, `funnel_id`, `step_id`, `step_name`,`start_date`) VALUES ".
|
||
"(".$userId.", ".$doer.",".$client['who_work'].", ".$clientId.", ".$client['funnel_id'].", ".$step_id.", '".$step_name."', NOW())";
|
||
if($reqId > 0){
|
||
$sql_stap = "INSERT INTO `doers_emp_client` (`user_id`, `doer_id`, `who_work`, `req_id`, `funnel_id`, `step_id`, `step_name`,`start_date`) VALUES ".
|
||
"(".$userId.", ".$doer.",".$client['who_work'].", ".$reqId.", ".$client['funnel_id'].", ".$step_id.", '".$step_name."', NOW())";
|
||
|
||
}
|
||
mysql_query($sql_stap);
|
||
}
|
||
|
||
}
|
||
}
|
||
|
||
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 (".$userId.", ".$clientId.", ".$doer_id.", 'parallel_del', 1,1)";
|
||
if($reqId > 0){
|
||
$sql_conf = "INSERT INTO `events_clients` (`user_id`, `req_id`, `from_id`, `event`, `read`, `send_telegramm`) VALUES (".$userId.", ".$reqId.", ".$doer_id.", 'parallel_del', 1,1)";
|
||
|
||
}
|
||
mysql_query($sql_conf);
|
||
$sql_s = "SELECT id FROM doers_emp_client WHERE user_id = ".$userId." and client_id=".$clientId." and doer_id = ".$doer_id." order by id desc";
|
||
//echo $sql_s;
|
||
if($reqId > 0){
|
||
$sql_s = "SELECT id FROM doers_emp_client WHERE user_id = ".$userId." and req_id=".$reqId." and doer_id = ".$doer_id." order by id desc";
|
||
}
|
||
$q_s = mysql_query($sql_s);
|
||
$r_s = mysql_fetch_assoc($q_s);
|
||
|
||
$sql_up = "UPDATE doers_emp_client SET end_date = NOW() WHERE id = ".$r_s['id'];
|
||
//echo $sql_up;
|
||
|
||
mysql_query($sql_up);
|
||
|
||
}
|
||
}
|
||
|
||
$count = 0;
|
||
foreach($agency as $key => $agent){
|
||
// if($key != $userId){
|
||
$count++;
|
||
// }
|
||
}
|
||
|
||
$doers_up = clearInputElement(json_encode($agency));
|
||
|
||
if ($_SESSION['id'] == 21484) {
|
||
var_dump($doers_up);
|
||
var_dump($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 = ".$clientId;
|
||
// echo $sql;
|
||
if($reqId > 0){
|
||
$sql = "UPDATE requisitions SET doers_confirm = ".$confirm.", doer_clients = ".$doer_clients.", doers = '". $doers_up."' WHERE id = ".$reqId;
|
||
}
|
||
if(!mysql_query($sql)){
|
||
echo mysql_error();
|
||
} else {
|
||
//пишем в отдельную таблицу
|
||
if($clientId > 0){
|
||
mysql_query("DELETE FROM clients_doers WHERE client_id = {$clientId}");
|
||
foreach($agency as $key => $agent){
|
||
$sql_i = "INSERT INTO clients_doers (client_id, user_id, confirm) VALUES (" . $clientId . ", ". $key . ", " . $agent . ")";
|
||
|
||
if(!mysql_query($sql_i)) {
|
||
echo mysql_error();
|
||
}
|
||
}
|
||
}
|
||
if($reqId > 0){
|
||
//сначала чистим
|
||
mysql_query("DELETE FROM requisition_doers WHERE requisition_id = {$reqId}");
|
||
//потом вставлям новое
|
||
foreach($agency as $key => $agent){
|
||
$sql_i = "INSERT INTO requisition_doers (requisition_id, user_id, confirm) VALUES (" . $reqId . ", ". $key . ", " . $agent . ")";
|
||
if(!mysql_query($sql_i)) {
|
||
echo mysql_error();
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
/**
|
||
* Добавление собственника объекта
|
||
*/
|
||
if($request == 'save_client_req_bind'){
|
||
$user_id = (int)$data->user_id;
|
||
$agency_id = (int)$data->agency_id;
|
||
$req_id = $data->req_id;
|
||
$client_id = (int)$data->client_id;
|
||
$object_id = (int)$data->object_id;
|
||
$funnel_id = (int)$data->funnel_id;
|
||
$rez = array();
|
||
if($client_id > 0 && $object_id > 0 && $user_id > 0) {
|
||
$objectArr = array();
|
||
$sql_cl = "SELECT id, objects, fio FROM clients WHERE id in ({$client_id})";
|
||
$q_cl = mysql_query($sql_cl);
|
||
while($r_cl = mysql_fetch_assoc($q_cl)){
|
||
if(!empty($r_cl['objects'])){
|
||
$arrObj = json_decode(html_entity_decode($r_cl['objects']), ENT_QUOTES);
|
||
foreach($arrObj as $oneObj){
|
||
$objectArr[] = strval($oneObj);
|
||
}
|
||
if(!in_array($object_id,$objectArr)){
|
||
$objectArr[] = strval($object_id);
|
||
}
|
||
} else {
|
||
$objectArr[] = strval($object_id);
|
||
}
|
||
|
||
if(!empty($objectArr)){
|
||
$clclass = new Clients();
|
||
$clclass->update_objects($r_cl['id'], null, $objectArr);
|
||
$objList = htmlentities(json_encode($objectArr));
|
||
$up_client = "UPDATE clients SET objects='$objList' where id = {$r_cl['id']}";
|
||
mysql_query($up_client);
|
||
}
|
||
|
||
$client_fio = $r_cl['fio'];
|
||
}
|
||
|
||
if($req_id !== null && $client_id > 0){
|
||
|
||
if($req_id == 'new'){
|
||
$req_funnel_id = $funnel_id;
|
||
$params = array();
|
||
$params['user_id'] = $user_id;
|
||
$params['funnel_id'] = $req_funnel_id;
|
||
$params['name'] = "Реализация объекта для ".$client_fio;
|
||
$params['opis'] = "Создана из объекта ID: ".$object_id;
|
||
$params['type_id'] = 2;
|
||
$params['object_id'] = $object_id;
|
||
$params['asfilter_id'] = 'NULL';
|
||
$params['req_id'] = 0;
|
||
$params['client_id'] = $client_id;
|
||
$params['who_work'] = $user_id;
|
||
$params['priority'] = 0;
|
||
$params['confirm'] = 1;
|
||
$params['hot'] = 0;
|
||
$params['source'] = 0;
|
||
$params['employee_id'] = 0;
|
||
$reqcl = new Requisitions(null, true);
|
||
$result = $reqcl->add_edit($params);
|
||
|
||
if(!isset($result['error'])){
|
||
|
||
$com = 'Добавлена заявка ID '.$result;
|
||
|
||
$sql = "INSERT INTO user_object_events(user_id, object_id, create_date, type, address, sum, schedule_date, comment, calendar_view)
|
||
VALUES({$user_id}, '{$object_id}', NOW(), 'comment', NULL, NULL, NULL, '$com', '1')";
|
||
// file_put_contents(__DIR__.'/log_obj.txt', $sql. "\n", FILE_APPEND);
|
||
mysql_query($sql);
|
||
}
|
||
|
||
} else {
|
||
$params = array();
|
||
$params['add_obj'] = 1;
|
||
$params['object_id'] = $object_id;
|
||
|
||
$params['req_id'] = $req_id;
|
||
$reqcl = new Requisitions(null, true);
|
||
$result = $reqcl->add_edit($params);
|
||
if(!isset($result['error'])){
|
||
$com = 'Пивязан к заявке ID '.$result;
|
||
|
||
$sql = "INSERT INTO user_object_events(user_id, object_id, create_date, type, address, sum, schedule_date, comment, calendar_view)
|
||
VALUES({$user_id}, '{$object_id}', NOW(), 'comment', NULL, NULL, NULL, '$com', '1')";
|
||
// file_put_contents(__DIR__.'/log_obj.txt', $sql. "\n", FILE_APPEND);
|
||
mysql_query($sql);
|
||
}
|
||
}
|
||
|
||
$sql_req = "SELECT id, funnel_id, stage FROM requisitions WHERE object_id = $object_id AND (type_id = 2 or type_id in (SELECT id FROM requisitions_type WHERE heir = 2 AND agency_id = {$agency_id})) AND deleted = 0 AND cancel = 0 LIMIT 1";
|
||
//echo $sql_req;
|
||
$q_req = mysql_query($sql_req);
|
||
if(mysql_num_rows($q_req) > 0){
|
||
$req = mysql_fetch_assoc($q_req);
|
||
}
|
||
if($req != null){
|
||
$rez['html'] =
|
||
'<div class="label-view clients" style="margin-bottom: 0px; float: left;">'
|
||
.'<div class="additional-info" style="padding: 15px 0px 5px">'
|
||
.'<div style="display: flex; justify-content: flex-start; flex-wrap: nowrap; flex-direction: row; min-width: 350px;" data-req="'.$req['id'].'" data-funnel="'.$req['funnel_id'].'" data-stage="'.$req['stage'].'" id="stagebar__'.$req['id'].'" class="stagebar">'
|
||
.'<div v-if="funnelId == 0" class="crm__small-stagebar" style="width: 80%; margin-right: 5px;">
|
||
<table>
|
||
<tbody>
|
||
<tr>
|
||
<td v-for="(step, id) in steps.bar" class="stage" :class="[{ active: step.id <= steps.stageId }, step.classF]" :title="step.title">
|
||
<div :data-stage="step.id" :data-req="'.$req['id'].'" class="crm__small-stage"></div>
|
||
<span class="next-stage" v-html="step.name"></span>
|
||
</td>
|
||
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<div v-else-if="funnelId > 0" class="crm__small-stagebar" style="width: 80%; margin-right: 5px;">
|
||
<table>
|
||
<tbody>
|
||
<tr>
|
||
<td v-for="(step, id) in steps.bar" :class="\'stage stage-funnel\'+step.classF+\' stageFunnel__\'+step.id"
|
||
:title="step.name">
|
||
<div :data-stage="step.id"
|
||
:data-req="reqId"
|
||
:data-main="step.main"
|
||
class="crm__small-step">
|
||
</div>
|
||
<span class="next-stage">{{ step.name }}</span>
|
||
</td>
|
||
</tr>
|
||
<tr>
|
||
<td :colspan="bars">
|
||
<span class="stepError" :id="\'step_funnel_error\'+reqId"></span>
|
||
</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<div class="action-button" title="Изменить воронку" @click="is_edit_funnel = !is_edit_funnel">
|
||
<i class="fa fa-pencil" style="font-size: 14px; color: gray; position: absolute; margin-top: -4px;"></i>
|
||
</div>
|
||
|
||
<div v-if="is_edit_funnel" class="editFunnelObject hidden" style="width: 450px; position: absolute; background: white; z-index: 110; border: 1px solid rgb(67, 160, 71);display: flex ; flex-direction: column; top: 0px; left: 130px; box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;" >
|
||
<div style="display: flex; justify-content: space-between;">
|
||
<h2 style="padding: 20px; width: unset;">
|
||
Изменить воронку
|
||
</h2>
|
||
<span class="pseudo-link closer" @click="closeEdit"><i class="ti-close"></i></span>
|
||
</div>
|
||
<div class="form-block funnel-client-block" style="width: 390px; display: flex; flex-direction: column; align-items: center; padding: 20px; margin: 0">
|
||
<div class="form-block">
|
||
<div class="line price" style="display: flex; justify-content: space-between; width: unset; border-right: unset;">
|
||
<div class="label">
|
||
<span>Воронка: <span class="star" style="color: red; font-size: 20px;">*</span></span>
|
||
</div>
|
||
<div class="inputs" style="display: flex; width: 280px;">
|
||
<v-select :clearable="true" :components="{OpenIndicator}" class="vue_select" style="border: none; width: 250px;" :options="funnels" :reduce="name => name.id" label="name" v-model="selectFunnel"/>
|
||
</div>
|
||
</div>
|
||
|
||
</div>
|
||
</div>
|
||
<button @click="saveFunnel" class="big-button" type="submit">Сохранить</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
</div>';
|
||
|
||
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
echo json_encode($rez);
|
||
exit();
|
||
|
||
}
|
||
|
||
/**
|
||
* Сохранение настроек передачи клиента
|
||
*/
|
||
if($request == 'save_confirm_client_object_req'){
|
||
$user_id = (int)$data->user_id;
|
||
$client_id = (int)$data->client_id;
|
||
$is_confirm_object = (int)$data->is_confirm_object;
|
||
$is_confirm_req = (int)$data->is_confirm_req;
|
||
$who_work = 0;
|
||
$new_who_work = (int)$data->new_who_work;
|
||
|
||
if($client_id != 0){
|
||
$sql_cl = "SELECT id, who_work FROM clients WHERE id = {$client_id}";
|
||
$q_cl = mysql_query($sql_cl);
|
||
$cl = mysql_fetch_assoc($q_cl);
|
||
$who_work = $cl['who_work'];
|
||
|
||
$sql = "INSERT INTO `client_confirm_objects`(`client_id`, `confirm_objects`, `confirm_req`, `who_work`, `new_who_work`, `user_id`) VALUES
|
||
({$client_id}, {$is_confirm_object}, {$is_confirm_req}, {$who_work}, {$new_who_work}, {$user_id})";
|
||
$q = mysql_query($sql);
|
||
|
||
}
|
||
exit();
|
||
}
|
||
|
||
/**
|
||
* Сохранение настроек вида страницы
|
||
*
|
||
*/
|
||
if($request == 'set_view_page'){
|
||
$user_id = $_SESSION['id'];
|
||
$view = $data->view;
|
||
|
||
$sql = "SELECT * FROM user_views_page WHERE user_id = {$user_id}";
|
||
$q = mysql_query($sql);
|
||
if(mysql_num_rows($q) > 0){
|
||
$r = mysql_fetch_assoc($q);
|
||
$sql_up = "UPDATE user_views_page SET view_client = '{$view}' WHERE id = {$r['id']}";
|
||
mysql_query($sql_up);
|
||
} else {
|
||
$sql_in = "INSERT INTO user_views_page (user_id, view_client) values ({$user_id}, '{$view}')";
|
||
mysql_query($sql_in);
|
||
}
|
||
}
|
||
|
||
|