src/Controller/MainController.php line 46

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Bot;
  4. use App\Entity\Client;
  5. use App\Entity\Command;
  6. use App\Entity\Draft;
  7. use App\Entity\LogMessage;
  8. use App\Entity\MailTemplate;
  9. use App\Entity\Office;
  10. use App\Entity\Report;
  11. use App\Entity\Role;
  12. use App\Entity\SalarySchedule;
  13. use App\Entity\Transaction;
  14. use App\Entity\TypeGroup;
  15. use App\Entity\User;
  16. use App\Kernel;
  17. use Doctrine\ORM\EntityManagerInterface;
  18. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  19. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\HttpFoundation\Response;
  22. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  23. use Symfony\Component\Mailer\MailerInterface;
  24. use Symfony\Component\Mime\Email;
  25. use Symfony\Component\Routing\Annotation\Route;
  26. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  27. use Symfony\Contracts\HttpClient\HttpClientInterface;
  28. class MainController extends AbstractController
  29. {
  30.     private $em;
  31.     private $kernel;
  32.     private $mailer;
  33.     public function __construct(EntityManagerInterface $emKernel $kernelMailerInterface $mailer){
  34.         $this->em $em;
  35.         $this->kernel $kernel;
  36.         $this->mailer $mailer;
  37.     }
  38.     /**
  39.      * @Route("/main", name="app_main")
  40.      */
  41.     public function index(): Response
  42.     {
  43.         return $this->render('main/index.html.twig', [
  44.             'controller_name' => 'MainController',
  45.         ]);
  46.     }
  47.     #[Route('/api/test/'name'app_api_test')]
  48.     public function test(Request $requestMailerInterface $mailerHttpClientInterface $client): Response
  49.     {
  50. //        $bot = $this->getDoctrine()->getRepository(Bot::class)->find(1);
  51. //        $chat_id = '414013565';
  52. //        $token = $bot->getToken();
  53. //        $reply = 'Добро пожаловать в бот' . ($bot ? "«" . $bot->getName() . "»." : '');
  54. //        $sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
  55. //        print_r($sendMessage);
  56. //        die();
  57.         $f '{"update_id":665653065,"message":{"message_id":1049,"from":{"id":414013565,"is_bot":false,"first_name":"Igor","username":"MrRedson","language_code":"ru"},"chat":{"id":414013565,"first_name":"Igor","username":"MrRedson","type":"private"},"date":1778655439,"text":"\/start","entities":[{"offset":0,"length":6,"type":"bot_command"}]}}';
  58.         $p json_decode($ftrue);
  59.         // Создаём "виртуальный" Request
  60.         $request Request::create('/api/bot/1/''POST', [], [], [], [], json_encode($p));
  61.         $request->attributes->set('id'1);
  62.         $request->headers->set('Content-Type''application/json');
  63.         // Вызываем контроллер напрямую
  64.         $response $this->bot($request); // $this->bot — твой контроллер
  65.         echo $response->getContent();
  66. //        print_r($p);
  67. //        die();
  68. //        $url = 'https://linwabot.atma-dev.ru/api/bot/1/';
  69. //
  70. //        try {
  71. //            $response = $client->request('POST', $url, [
  72. //                'json' => $p
  73. //            ]);
  74. //
  75. //            $content = $response->getContent(); // Возвращает ответ сервера
  76. //            echo "Response: $content";
  77. //
  78. //        } catch (\Exception $e) {
  79. //            echo "Error: " . $e->getMessage();
  80. //        }
  81. //        $url = 'https://linwabot.atma-dev.ru/api/bot/1/';
  82. //
  83. //        $ch = curl_init();
  84. //        curl_setopt($ch, CURLOPT_URL, $url);
  85. //        curl_setopt($ch, CURLOPT_POST, true);
  86. //        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($p));
  87. //        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  88. //        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
  89. //
  90. //        $response = curl_exec($ch);
  91. //        $err = curl_error($ch);
  92. //        curl_close($ch);
  93. //
  94. //        if ($err) {
  95. //            echo "cURL Error: $err";
  96. //        } else {
  97. //            echo "Response: $response";
  98. //        }
  99.         die();
  100.     }
  101.     #[Route('/api/bot/{id}/'name'app_api_bot')]
  102.     public function bot(Request $request): Response
  103.     {
  104. //        echo json_encode(['state' => 'success']);
  105. //        die();
  106.         $basePath $this->getParameter('kernel.project_dir');
  107.         $id $request->get('id');
  108.         if($id === null || $id == ''){
  109.             $id $request->attributes->get('id');
  110.         }
  111.         $is_group_chat $this->getParameter('app.chat.is_group');
  112.         $time_interval $this->getParameter('app.time.interval');
  113.         $result json_decode($request->getContent(), true);
  114.         if($request->get('dev') != '' && $request->get('dev') != null){
  115.             if(file_exists($basePath '/var/log/chatDev.txt')){
  116.                 $result json_decode(file_get_contents($basePath '/var/log/chatDev.txt'), true);
  117.             }
  118.         } else {
  119.             file_put_contents($basePath '/var/log/chatDev.txt'print_r($request->getContent(), true));
  120.             file_put_contents($basePath '/var/log/chatDev.txt'print_r('test'true));
  121.         }
  122.         file_put_contents($basePath '/var/log/chatDev1.txt'print_r($resulttrue), FILE_APPEND);
  123.         if($request->get('is_test') == '1'){
  124.             $r '{"update_id":145458808,"message":{"message_id":17519,"from":{"id":414013565,"is_bot":false,"first_name":"Igor","username":"MrRedson","language_code":"ru"},"chat":{"id":-5159830091,"title":"\u0417\u041f \u0411\u043e\u0442 2","type":"group","all_members_are_administrators":false,"accepted_gift_types":{"unlimited_gifts":false,"limited_gifts":false,"unique_gifts":false,"premium_subscription":false,"gifts_from_channels":false}},"date":1778694278,"text":"\/balance","entities":[{"offset":0,"length":8,"type":"bot_command"}]}}';
  125.             $result json_decode($rtrue);
  126.         }
  127.         $text = (isset($result["message"]["text"]) ? $result["message"]["text"] : null);
  128.         $chat_id = (isset($result['message']['from']['id']) ? $result['message']['from']['id'] : null);
  129.         $typeof = (isset($result["message"]["chat"]["type"]) ? $result["message"]["chat"]["type"] : null);
  130.         $group_id = (isset($result['message']['chat']['id']) && ($typeof == 'group' || $typeof == 'supergroup') ? $result['message']['chat']['id'] : null);
  131.         $group $typeof == 'group' || $typeof == 'supergroup' $group_id null;
  132.         $message_id = (isset($result["message"]["message_id"]) ? $result["message"]["message_id"] : null);
  133.         $callback_query = (isset($result["callback_query"]) ? $result["callback_query"] : array());
  134.         $callback_query_data = (isset($result["callback_query"]["data"]) ? $result["callback_query"]["data"] : null);
  135.         $photo = (isset($result["message"]["photo"]) ? $result["message"]["photo"] : []);
  136.         $caption = (isset($result["message"]["caption"]) ? $result["message"]["caption"] : null);
  137.         //file_put_contents($basePath . '/var/log/r_1.txt', print_r($result, true), FILE_APPEND);
  138.         $fileId null;
  139.         if(count($photo) > 0){
  140.             foreach ($photo as $key_ph => $itemPhoto){
  141.                 if($key_ph == count($photo) - 1){
  142.                     $fileId $itemPhoto['file_id'];
  143.                 }
  144.             }
  145.             if($caption != '' && $caption != ''){
  146.                 $text $caption;
  147.             }
  148.         }
  149.         if($message_id == null || $message_id == ''){
  150.             $message_id = (isset($callback_query["message"]["message_id"]) ? $callback_query["message"]["message_id"] : null);
  151.         }
  152.         //не пропускать двойную обрабоку сообщения
  153.         if($is_group_chat === true && $message_id != '' && $message_id != null && !($request->get('is_test') == '1')){
  154.             $chId $chat_id;
  155.             if($group != '' && $group != null){
  156.                 $chId $group;
  157.             }
  158.             $log_message $this->getDoctrine()
  159.                 ->getRepository(LogMessage::class)
  160.                 ->createQueryBuilder('lm')
  161.                 ->select('lm.id')
  162.                 ->where('lm.bot = :bot_id')
  163.                 ->andWhere('lm.message_id = :message_id')
  164.                 ->andWhere('lm.chat_id = :chat_id')
  165.                 ->setParameter('bot_id'$id)
  166.                 ->setParameter('message_id'$message_id)
  167.                 ->setParameter('chat_id'$chId)
  168.                 ->getQuery()->getArrayResult();
  169.             if(count($log_message) > 0){
  170.                 file_put_contents($basePath '/var/log/double.txt'print_r($resulttrue), FILE_APPEND);
  171.                 return new Response('OK'200);
  172.             }
  173.         }
  174.         //echo $message_id;
  175. //        echo $is_group_chat . ' ' . $message_id . ' ' . $id . ' ' . $chId;
  176. //        die();
  177.         if(count($callback_query) > 0){
  178.             $chat_id = (isset($callback_query['message']['chat']['id']) ? $callback_query['message']['chat']['id'] : null);
  179.         }
  180.         $cq_data = array();
  181.         $thisCommand null;
  182.         if(ProjectUtilsController::isJSON($callback_query_data) === true){
  183.             $cq_data json_decode($callback_query_datatrue);
  184.             if(isset($cq_data['command'])){
  185.                 $thisCommand $cq_data['command'];
  186.             }
  187.         }
  188.         file_put_contents($basePath '/var/log/chat2.txt'print_r($resulttrue), FILE_APPEND);
  189.         file_put_contents($basePath '/var/log/callback1.txt'print_r($cq_datatrue), FILE_APPEND);
  190.         $token null;
  191.         $bot false;
  192.         if($id != null && $id != ''){
  193.             $bot $this->getDoctrine()->getRepository(Bot::class)->find($id);
  194.             $token $bot->getToken();
  195.         }
  196.         //очистка имени бота из команды <<<
  197.         if(strpos($text'@') !== false) {
  198.             $arr_t explode('@'$text);
  199.             if(count($arr_t) == 2){
  200.                 $nameBot $arr_t[count($arr_t) - 1];
  201.                 $text str_replace('@' $nameBot''$text);
  202.                 if(strpos($text'@' $nameBot) !== false) {
  203.                     $text str_replace('@' $nameBot''$text);
  204.                 }
  205.             }
  206.         }
  207.         //очистка имени бота из команды >>>
  208.         $reply 'Пришло ';
  209.         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  210.         return new Response('OK'200);
  211.         $client $this->getCurClient($chat_id$typeof, (isset($result['message']['from']) ? $result['message']['from'] : array()), (isset($result['message']['chat']) ? $result['message']['chat'] : array()));
  212.         if(!empty($token) && !empty($chat_id)){
  213.             $command false;
  214.             if(count($cq_data) > 0){
  215.                 $this->resetExpected($client);
  216.                 if($thisCommand == 'setting'){
  217.                     $this->setting($token$chat_id$group_id$cq_data$message_id);
  218.                 } elseif($thisCommand == 'users'){
  219.                     $this->users($token$chat_id$group_id$cq_datafalsenull$message_id);
  220.                 } elseif($thisCommand == 'office'){
  221.                     $this->office($token$chat_id$group_id$cq_datafalsenull$message_id);
  222.                 } elseif($thisCommand == 'pay'){
  223.                     if($is_group_chat === true){
  224.                         $chat_id = (isset($callback_query['from']['id']) ? $callback_query['from']['id'] : null);
  225.                     }
  226.                     $this->pay($token$chat_id$group_id$cq_datafalsenull$message_id);
  227.                 } elseif($thisCommand == 'bpay'){
  228.                     if($is_group_chat === true){
  229.                         $chat_id = (isset($callback_query['from']['id']) ? $callback_query['from']['id'] : null);
  230.                     }
  231.                     $this->bpay($token$chat_id$group_id$cq_datafalsenull$message_id);
  232.                 } elseif($thisCommand == 'report'){
  233.                     $this->report($token$chat_id$group_id$cq_datafalsenull$message_id);
  234.                 }
  235.                 if($is_group_chat === true && $group_id != '' && $group_id != null){
  236.                     $commandObj false;
  237.                     if(!$command && $thisCommand != '' && $thisCommand != null){
  238.                         $commandObj $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => $thisCommand'is_active' => true));
  239.                     }
  240.                     $this->addLogMessage($bot$group_id$message_id$commandObj);
  241.                 }
  242.                 return new Response('OK'200);
  243.             }
  244.             //$setMyCommands = ProjectUtilsController::requestToBot($token, 'setMyCommands', ['commands' => json_encode([['command' => '/help', 'description' => 'Список комманд'], ['command' => '/prev', 'description' => 'Список комманд'], ['command' => '/next', 'description' => 'Список комманд'], ['command' => '/top', 'description' => 'Список комманд'], ['command' => '/bottom', 'description' => 'Список комманд']])]);
  245. //            $reply = 'Тест';
  246. //            $sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
  247. //            die();
  248.             $isLog false;
  249.             if(($text != '' && $text != null) || ($fileId != '' && $fileId != null)){
  250.                 if($text == '/clear'){
  251.                     $this->addLogMessage($bot$group_id$message_idnull);
  252.                     $this->clear($token$chat_id$group_id$message_id);
  253.                     return new Response('OK'200);
  254.                 }
  255.                 $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('name' => $text'is_active' => true));
  256.                 if($command){
  257.                     $client_m $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  258.                     if($client_m){
  259.                         $this->resetExpected($client_m);
  260.                     }
  261.                     $is_access false;
  262.                     $client_i $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  263.                     $my_role null;
  264.                     if($client_i){
  265.                         if($client_i->getRole()){
  266.                             $my_role $client_i->getRole()->getId();
  267.                         }
  268.                     }
  269.                     if(count($command->getRoles()) > 0){
  270.                         foreach ($command->getRoles() as $role){
  271.                             if($role->getId() == $my_role){
  272.                                 $is_access true;
  273.                             }
  274.                         }
  275.                     }
  276.                     $sendMessage false;
  277.                     if($is_group_chat === true && $group_id != '' && $group_id != null){
  278.                         $this->addLogMessage($bot$group_id$message_id$command);
  279.                         $isLog true;
  280.                     }
  281.                     if($is_access === true){
  282.                         if($command->getTypeof() == 'start'){
  283.                             if($is_group_chat === true && $group_id != '' && $group_id != null){
  284.                                 $chat_id $group_id;
  285.                             }
  286.                             $reply 'Добро пожаловать в бот' . ($bot "«" $bot->getName() . "»." '');
  287.                             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  288.                         }elseif($command->getTypeof() == 'setting'){
  289.                             $this->setting($token$chat_id$group_id, array(), $message_id);
  290.                         } elseif($command->getTypeof() == 'help'){
  291. //                            $reply = 'Пришло 1';
  292. //                            $sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
  293. //                            return new Response('OK', 200);
  294.                             $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  295.                             $type_group null;
  296.                             if($is_group_chat === true && $group_id != '' && $group_id != null){
  297.                                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  298.                                 if($groupObj && $groupObj->getTypeGroup() != null){
  299.                                     $type_group $groupObj->getTypeGroup()->getTypeof();
  300.                                 }
  301.                             }
  302.                             $reply $this->mainMenu($clientObj, ($is_group_chat === true && $group_id != '' && $group_id != null true false), $type_group);
  303.                             if($is_group_chat === true && $group_id != '' && $group_id != null){
  304.                                 $chat_id $group_id;
  305.                             }
  306.                             if($reply != '' && $reply != null){
  307.                                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  308.                                 echo $sendMessage;
  309.                                 return new Response('OK'200);
  310.                             }
  311.                         } elseif($command->getTypeof() == 'init'){
  312.                             $reply 'Вам не удалось инициализироватся у бота. Попробуйте повторить команду позже.';
  313.                             if($client){
  314.                                 $reply 'Вы упешно инициализированы ботом. Чтобы узнать какие команды вам доступны отправьте /help.';
  315.                             }
  316.                             if($is_group_chat === true && $group_id != '' && $group_id != null){
  317.                                 $chat_id $group_id;
  318.                             }
  319.                             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  320.                         } elseif($command->getTypeof() == 'users'){
  321.                             $this->users($token$chat_id$group_id, array(), falsenull$message_id);
  322.                         }  elseif($command->getTypeof() == 'office'){
  323.                             $this->office($token$chat_id$group_id, array(), falsenull$message_id);
  324.                         } elseif($command->getTypeof() == 'pay'){
  325.                             $this->pay($token$chat_id$group_id, array(), falsenull$message_id);
  326.                         } elseif($command->getTypeof() == 'bpay'){
  327.                             $type_group null;
  328.                             $groupId '';
  329.                             if($is_group_chat === true && $group_id != '' && $group_id != null){
  330.                                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  331.                                 if($groupObj){
  332.                                     if($groupObj->getTypeGroup() != null){
  333.                                         $type_group $groupObj->getTypeGroup()->getTypeof();
  334.                                     }
  335.                                     $groupId $groupObj->getId();
  336.                                 }
  337.                             }
  338.                             if($type_group == 'cash'){
  339. //                                if($is_group_chat === true){
  340. //                                    $chat_id = $group_id;
  341. //                                }
  342.                                 $cq_data = array('action' => "other"'command' => "bpay""group" => $groupId);
  343.                                 $this->bpay($token$chat_id$group_id$cq_datafalsenull$message_id);
  344.                                 //$reply = 'группа ' . $groupId;
  345.                                 //$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $group_id, 'text' => $reply, 'parse_mode' => 'HTML']);
  346.                             } else {
  347.                                 //доступа у группы типа ЗП нет к данной команде
  348.                                 $reply 'У вас нет доступа к данной команде.';
  349.                                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $group_id'text' => $reply'parse_mode' => 'HTML']);
  350.                             }
  351.                             //$this->bpay($token, $chat_id, $group_id, array(), false, null, $message_id);
  352.                         } elseif($command->getTypeof() == 'balance'){
  353.                             $this->balance($token$chat_id$group_id$client_i);
  354.                         } elseif($command->getTypeof() == 'report'){
  355.                             $this->report($token$chat_id$group_id, array(), $client_inull$message_id);
  356.                         }
  357.                         if($is_group_chat === true){
  358.                             //удаление прошлых команд, кроме данной команды
  359.                             $this->deleteLogMessage($bot$group_idnull$command->getId());
  360.                         }
  361.                     } else {
  362.                         $reply 'У вас нет доступа к данной команде.';
  363.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  364.                     }
  365.                     if($is_group_chat === true){
  366.                         $this->addLogMessageBot($bot$command$sendMessage);
  367.                         $isLog true;
  368.                     }
  369.                     if($isLog !== true){
  370.                         $this->addLogMessage($bot$group_id$message_idnull);
  371.                     }
  372.                 } else {
  373.                     $is_expected false;
  374.                     if($client){
  375.                         if($client->getExpected() != '' && $client->getExpected() != null){
  376.                             $is_expected true;
  377.                             $data_expected $this->dataExpected($client->getExpected());
  378.                             if(isset($data_expected['value'])){
  379.                                 $typeof_command null;
  380.                                 if($data_expected['value'] == 'new_office'){
  381.                                     $this->office($token$chat_id$group_id, array(), $client$text$message_id);
  382.                                     $typeof_command 'office';
  383.                                 }  elseif($data_expected['value'] == 'name_office'){
  384.                                     $this->office($token$chat_id$group_id, array(), $client$text$message_id);
  385.                                     $typeof_command 'office';
  386.                                 } elseif($data_expected['value'] == 'edit_office' || $data_expected['value'] == 'edit_n_office'){
  387.                                     $this->office($token$chat_id$group_id, array(), $client$text$message_id);
  388.                                     $typeof_command 'office';
  389.                                 } elseif($data_expected['value'] == 'amount' || $data_expected['value'] == 'comment' || $data_expected['value'] == 'file_cheque' || $data_expected['value'] == 'new_date' || $data_expected['value'] == 'new_amount' || $data_expected['value'] == 'edit_ss_d' || $data_expected['value'] == 'edit_ss_a'){
  390.                                     $typeof_command 'pay';
  391.                                     //удаление комментария
  392.                                     /*
  393.                                     if($is_group_chat === true && $group_id != '' && $group_id != null && $data_expected['value'] == 'comment'){
  394.                                         if(!$command && $typeof_command != '' && $typeof_command != null){
  395.                                             $command = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => $typeof_command, 'is_active' => true));
  396.                                         }
  397.                                         $this->addLogMessage($bot, $group_id, $message_id, $command);
  398.                                         $isLog = true;
  399.                                     }
  400.                                     */
  401.                                     $this->pay($token$chat_id$group_id, array(), $client$text$message_id$fileId);
  402.                                 } elseif($data_expected['value'] == 'amount_b' || $data_expected['value'] == 'comment_b' || $data_expected['value'] == 'file_cheque_b' || $data_expected['value'] == 'new_date_b' || $data_expected['value'] == 'new_amount_b' || $data_expected['value'] == 'edit_ss_d_b' || $data_expected['value'] == 'edit_ss_a_b'){
  403.                                     $typeof_command 'bpay';
  404.                                     //удаление комментария
  405.                                     /*
  406.                                     if($is_group_chat === true && $group_id != '' && $group_id != null && $data_expected['value'] == 'comment'){
  407.                                         if(!$command && $typeof_command != '' && $typeof_command != null){
  408.                                             $command = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => $typeof_command, 'is_active' => true));
  409.                                         }
  410.                                         $this->addLogMessage($bot, $group_id, $message_id, $command);
  411.                                         $isLog = true;
  412.                                     }
  413.                                     */
  414.                                     $this->bpay($token$chat_id$group_id, array(), $client$text$message_id$fileId);
  415.                                 } elseif($data_expected['value'] == 'email'){
  416.                                     $this->users($token$chat_id$group_id, array(), $client$text$message_id);
  417.                                     $typeof_command 'users';
  418.                                 } elseif($data_expected['value'] == 'period_report'){
  419.                                     $this->report($token$chat_id$group_id, array(), $client$text$message_id);
  420.                                     $typeof_command 'report';
  421.                                 }
  422.                                 if($is_group_chat === true && $group_id != '' && $group_id != null){
  423.                                     if(!$command && $typeof_command != '' && $typeof_command != null){
  424.                                         $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => $typeof_command'is_active' => true));
  425.                                     }
  426.                                     //чтобы не удалялись сумма, комментарий и чек транзакции
  427.                                     if($data_expected['value'] != 'amount' && $data_expected['value'] != 'comment' && $data_expected['value'] != 'file_cheque' && $data_expected['value'] != 'file_cheque_b'){
  428.                                         $this->addLogMessage($bot$group_id$message_id$command);
  429.                                     }
  430.                                     $isLog true;
  431.                                 }
  432.                             }
  433.                         }
  434.                         if($isLog !== true){
  435.                             $this->addLogMessage($bot$group_id$message_idnull);
  436.                         }
  437.                     }
  438.                     if($is_expected === false){
  439.                         if($is_group_chat === true && $group_id != '' && $group_id != null){
  440.                             $chat_id $group_id;
  441.                         }
  442.                         if(strpos($text'/') !== false){
  443.                             $reply 'Команда не найдена или неактивна, пожалуйста проверьте правильно ли вы ввели команду.';
  444.                         }
  445.                         else {
  446.                             $reply 'Возможно вы ввели текст неправильно, боту не удалось его разпознать';
  447.                         }
  448.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  449.                         if($is_group_chat === true) {
  450.                             $this->addLogMessageBot($bot$command$sendMessage);
  451.                         }
  452.                     }
  453.                 }
  454.             }
  455.             //file_put_contents($basePath . '/var/log/chat.txt', $sendMessage, FILE_APPEND);
  456.         }
  457.         return new Response('OK'200);
  458.     }
  459.     private function clearChats($token$data){
  460.         $em $this->getDoctrine()->getManager();
  461.         if(count($data) > 0){
  462.             foreach ($data as $item){
  463.                 if($item['chat_id'] != null && $item['chat_id'] != '' && $item['message_id'] != null && $item['message_id'] != ''){
  464.                     $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $item['chat_id'], 'message_id' => $item['message_id']]);
  465.                     $deleteData = array();
  466.                     if(ProjectUtilsController::isJSON($deleteMessage) === true){
  467.                         $deleteData json_decode($deleteMessagetrue);
  468.                     }
  469.                     if(count($deleteData) > 0){
  470.                         $log_message $this->getDoctrine()->getRepository(LogMessage::class)->findOneBy(array('id' => $item['id']));
  471.                         if($log_message){
  472.                             if(isset($deleteData['ok'])){
  473.                                 if($deleteData['ok'] === true){
  474.                                     $log_message->setIsDeleted(1);
  475.                                     $log_message->setResponse($deleteMessage);
  476.                                 } else {
  477.                                     $log_message->setResponse($deleteMessage);
  478.                                 }
  479.                                 $em->persist($log_message);
  480.                                 $em->flush();
  481.                             }
  482.                         }
  483.                     }
  484.                 }
  485.             }
  486.         }
  487.     }
  488.     private function clear($token$chat_id$group_id$message_id){
  489.         $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
  490.         if($bot){
  491.             if($chat_id != '' && $chat_id != null){
  492.                 $log_messages_q $this->getDoctrine()
  493.                     ->getRepository(LogMessage::class)
  494.                     ->createQueryBuilder('lm')
  495.                     ->select('lm.id, lm.chat_id, lm.message_id')
  496.                     ->where('lm.is_deleted = 0')
  497.                     ->andWhere('lm.bot = :bot_id')
  498.                     ->andWhere('lm.chat_id = :chat_id')
  499.                     ->setParameter('chat_id'$chat_id)
  500.                     ->setParameter('bot_id'$bot->getId())
  501.                     ->setMaxResults(5)
  502.                     ->orderBy('lm.id''DESC')
  503.                     ->getQuery()->getArrayResult();
  504.                 $this->clearChats($token$log_messages_q);
  505.             }
  506.             if($group_id != '' && $group_id != null){
  507.                 $log_messages_group_q $this->getDoctrine()
  508.                     ->getRepository(LogMessage::class)
  509.                     ->createQueryBuilder('lm')
  510.                     ->select('lm.id, lm.chat_id, lm.message_id')
  511.                     ->where('lm.is_deleted = 0')
  512.                     ->andWhere('lm.bot = :bot_id')
  513.                     ->andWhere('lm.chat_id = :chat_id')
  514.                     ->setParameter('chat_id'$group_id)
  515.                     ->setParameter('bot_id'$bot->getId())
  516.                     ->setMaxResults(5)
  517.                     ->orderBy('lm.id''DESC')
  518.                     ->getQuery()->getArrayResult();
  519.                 $this->clearChats($token$log_messages_group_q);
  520.             }
  521.             $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => ($group_id != '' && $group_id != '' $group_id $chat_id), 'message_id' => $message_id]);
  522.             //$reply = 'Чат очищен от последних сообщений';
  523.             //$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => ($group_id != '' && $group_id != '' ? $group_id : $chat_id), 'text' => $reply, 'parse_mode' => 'HTML']);
  524.             //$this->addLogMessageBot($bot->getId(), null, $sendMessage);
  525.             exit();
  526.         }
  527.     }
  528.     private function addLogMessageBot($bot_id$command_id$json_data)
  529.     {
  530.         $chat_id null;
  531.         $message_id null;
  532.         if(ProjectUtilsController::isJSON($json_data) === true){
  533.             $data json_decode($json_datatrue);
  534.             if(count($data) > && isset($data['ok'])){
  535.                 if($data['ok'] === true){
  536.                     $chat_id = (isset($data['result']['chat']['id']) ? $data['result']['chat']['id'] : null);
  537.                     $message_id = (isset($data['result']['message_id']) ? $data['result']['message_id'] : null);
  538.                 }
  539.             }
  540.         }
  541.         $this->addLogMessage($bot_id$chat_id$message_id$command_id);
  542.     }
  543.     private function addLogMessage($bot_id$chat_id$message_id$command_id null)
  544.     {
  545.         $em $this->getDoctrine()->getManager();
  546.         $bot false;
  547.         if(is_object($bot_id)){
  548.             $bot $bot_id;
  549.         } elseif($bot_id != '' && $bot_id != null){
  550.             $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('id' => $bot_id));
  551.         }
  552.         $command null;
  553.         if(is_object($command_id)){
  554.             $command $command_id;
  555.         } elseif($command_id != '' && $command_id != null){
  556.             $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('id' => $command_id));
  557.         }
  558.         $resp false;
  559.         if($bot && $chat_id != '' && $chat_id != null && $message_id != '' && $message_id != null){
  560.             $log_message $this->getDoctrine()->getRepository(LogMessage::class)->findOneBy(array('chat_id' => $chat_id'message_id' => $message_id'bot' => $bot'is_deleted' => false));
  561.             if(!$log_message){
  562.                 $newLogMessage = new LogMessage();
  563.                 $newLogMessage->setChatId($chat_id);
  564.                 $newLogMessage->setMessageId($message_id);
  565.                 $newLogMessage->setBot($bot);
  566.                 $newLogMessage->setDate(new \DateTime(date('Y-m-d H:i:s')));
  567.                 $newLogMessage->setIsDeleted(0);
  568.                 $newLogMessage->setCommand($command);
  569.                 $em->persist($newLogMessage);
  570.                 $em->flush();
  571.                 if($newLogMessage){
  572.                     $resp true;
  573.                 }
  574.             } else {
  575.                 $resp true;
  576.             }
  577.         }
  578.         return $resp;
  579.     }
  580.     private function deleteLogMessage($bot_id null$chat_id null$command_id null$no_command_id null)
  581.     {
  582.         if(is_object($bot_id)){
  583.             $bot_id $bot_id->getId();
  584.         }
  585.         $log_messages_q $this->getDoctrine()
  586.             ->getRepository(LogMessage::class)
  587.             ->createQueryBuilder('lm')
  588.             ->select('lm.id, lm.chat_id, lm.message_id, b.token AS token')
  589.             ->leftJoin(Bot::class, 'b''WITH''lm.bot = b.id')
  590.             ->where('lm.is_deleted = 0');
  591.         if($command_id != '' && $command_id != null){
  592.             $log_messages_q->andWhere('lm.command = ' $command_id);
  593.         }
  594.         if($no_command_id != '' && $no_command_id != null){
  595.             $log_messages_q->andWhere('lm.command != ' $no_command_id);
  596.         }
  597.         if($bot_id != '' && $bot_id != null && $chat_id != '' && $chat_id != null){
  598.             $log_messages_q->andWhere('lm.bot = ' $bot_id)
  599.                 ->andWhere('lm.chat_id = :chat_id')
  600.                 ->setParameter('chat_id'$chat_id)
  601.             ;
  602.         } else {
  603.             $m $this->getParameter('app.delete.max_interval');
  604.             $d date('Y-m-d H:i:s',strtotime('-' $m ' minutes'strtotime(date("Y-m-d H:i:s"))));
  605.             $log_messages_q->andWhere('lm.date <= :date')
  606.                 ->setParameter('date'$d)
  607.             ;
  608.         }
  609.         $log_messages $log_messages_q->getQuery()->getArrayResult();
  610.         if(count($log_messages) > 0){
  611.             $em $this->getDoctrine()->getManager();
  612.             foreach ($log_messages as $item){
  613.                 if($item['chat_id'] != null && $item['chat_id'] != '' && $item['message_id'] != null && $item['message_id'] != ''&& $item['token'] != null && $item['token'] != ''){
  614.                     $deleteMessage ProjectUtilsController::requestToBot($item['token'], 'deleteMessage', ['chat_id' => $item['chat_id'], 'message_id' => $item['message_id']]);
  615.                     $deleteData = array();
  616.                     if(ProjectUtilsController::isJSON($deleteMessage) === true){
  617.                         $deleteData json_decode($deleteMessagetrue);
  618.                     }
  619.                     if(count($deleteData) > 0){
  620.                         $log_message $this->getDoctrine()->getRepository(LogMessage::class)->findOneBy(array('id' => $item['id']));
  621.                         if($log_message){
  622.                             if(isset($deleteData['ok'])){
  623.                                 if($deleteData['ok'] === true){
  624.                                     $log_message->setIsDeleted(1);
  625.                                     $log_message->setResponse($deleteMessage);
  626.                                 } else {
  627.                                     $log_message->setResponse($deleteMessage);
  628.                                 }
  629.                                 $em->persist($log_message);
  630.                                 $em->flush();
  631.                             }
  632.                         }
  633.                     }
  634.                 }
  635.             }
  636.         }
  637.     }
  638.     private function isValidDate($date) {
  639.         if (preg_match("/^(\d{2}).(\d{2}).(\d{4})$/"$date$matches)) {
  640.             if (checkdate($matches[2], $matches[1], $matches[3])) {
  641.                 return true;
  642.             }
  643.         }
  644.         return false;
  645.     }
  646.     private function isValidDateTime($dateTime) {
  647.         if (preg_match("/^(\d{2}).(\d{2}).(\d{4}) ([01][0-9]|2[0-3]):([0-5][0-9])$/"$dateTime$matches)) {
  648.             if (checkdate($matches[2], $matches[1], $matches[3])) {
  649.                 return true;
  650.             }
  651.         }
  652.         return false;
  653.     }
  654.     private function isValidDateTimeOrig($dateTime) {
  655.         if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/"$dateTime$matches)) {
  656.             if (checkdate($matches[2], $matches[3], $matches[1])) {
  657.                 return true;
  658.             }
  659.         }
  660.         return false;
  661.     }
  662.     private function report($token$chat_id$group_id$cq_data = array(), $curClient false$text null$message_id null) {
  663.         $is_group_chat $this->kernel->getContainer()->getParameter('app.chat.is_group');
  664.         $basePath $this->getParameter('kernel.project_dir');
  665.         $fileDir '/public/images/';
  666.         $action null;
  667.         $p_group null;
  668.         $keyboard = array();
  669.         $em $this->getDoctrine()->getManager();
  670.         if(count($cq_data) > 0){
  671.             $action = (isset($cq_data['action']) ? $cq_data['action'] : null);
  672.             $p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
  673.         }
  674.         $expected null;
  675.         if($curClient){
  676.             $data_expected $this->dataExpected($curClient->getExpected());
  677.             if(isset($data_expected['value'])){
  678.                 $expected $data_expected['value'];
  679.             }
  680.             if(isset($data_expected['group'])){
  681.                 $p_group $data_expected['group'];
  682.             }
  683.         }
  684.         if($action == 'delete'){
  685.             $groupObj false;
  686.             if($p_group != null && $p_group != '') {
  687.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  688.             }
  689.             if($groupObj){
  690.                 $mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
  691.                 if($mes_id != '' && $mes_id != null){
  692.                     $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
  693.                 }
  694.                 if(file_exists($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt')){
  695.                     $mes_id file_get_contents($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt');
  696.                     if($mes_id != '' && $mes_id != null){
  697.                         $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
  698.                         $resp json_decode($deleteMessagetrue);
  699.                         if(isset($resp['result'])){
  700.                             if($resp['result'] == true){
  701.                                 unlink($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt');
  702.                             }
  703.                         }
  704.                     }
  705.                 }
  706.             }
  707.             exit();
  708.         }
  709.         if(count($cq_data) > && $action != 'menu'){
  710.             if($action == 'all_report'){
  711.                 if(!$curClient){
  712.                     $curClient $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  713.                 }
  714.                 $groupObj false;
  715.                 if($p_group != null && $p_group != '') {
  716.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  717.                 }
  718.                 $transactions_q $this->getDoctrine()
  719.                     ->getRepository(Transaction::class)
  720.                     ->createQueryBuilder('tr')
  721.                     ->select('tr.id')
  722.                     ->where('tr.amount != 0')
  723.                 ;
  724.                 if($groupObj){
  725.                     $transactions_q->andWhere('tr.from_group = ' $groupObj->getId() . ' OR tr.to_group = ' $groupObj->getId());
  726.                 }
  727.                 $transactions $transactions_q->getQuery()->getArrayResult();
  728.                 $count_trs count($transactions);
  729.                 if($count_trs 0){
  730.                     $newReport = new Report();
  731.                     $newReport->setClient(($curClient $curClient null));
  732.                     $newReport->setPath(null);
  733.                     $newReport->setDateWith(null);
  734.                     $newReport->setDateBy(null);
  735.                     $newReport->setIsSend(0);
  736.                     $newReport->setDate(new \DateTime(date("Y-m-d H:i:s")));
  737.                     $newReport->setClientGroup(($groupObj $groupObj null));
  738.                     $em->persist($newReport);
  739.                     $em->flush();
  740.                     $file $this->genReport($newReport);
  741.                     if($file != '' && $file != null){
  742.                         $email $curClient->getEmail();
  743.                         if($email != null && $email != ''){
  744.                             $body_mail = array(
  745.                                 '#app#' => $this->getParameter('app.name'),
  746.                                 '#logo#' => $this->getParameter('app.logo')
  747.                             );
  748.                             $title_mail = array();
  749.                             $attach = array();
  750.                             $filepath $basePath $fileDir $file;
  751.                             if(file_exists($filepath)){
  752.                                 $attach[] = $basePath $fileDir $file;
  753.                             }
  754.                             //отправка письма
  755.                             //$email = 'igor@atmapro.ru';
  756.                             $sendMail $this->sendEmail($this->mailer,'newReportAll'$body_mail$title_mail'ru'$email$attach);
  757.                             $newReport->setIsSend(1);
  758.                         }
  759.                         $newReport->setPath($file);
  760.                         $em->persist($newReport);
  761.                         $em->flush();
  762.                         $this->resetExpected($curClient);
  763.                         $arr_f explode('/'$file);
  764.                         $file_name '';
  765.                         if(count($arr_f) == 2){
  766.                             $file_name $arr_f[1];
  767.                         }
  768.                         $link_file = (isset($_SERVER['HTTPS']) ? 'https://' 'http://') . $_SERVER['HTTP_HOST'] . '/images/' $file;
  769.                         $reply 'Файл отчета' . ($file_name != '' ' ' $file_name '') . ' успешно сформирован и отправлен на почту ' $email '. Также доступен для скачивания по ссылке ' $link_file;
  770.                         //$reply = 'Файл отчета успешно сформирован ' . $file;
  771.                     } else {
  772.                         $reply 'Не удалось сформировать файл отчета, попробуйте позже.';
  773.                         $this->resetExpected($curClient);
  774.                     }
  775.                 } else {
  776.                     $reply 'Не удалось сформировать отчет, пока нет ни одной финансовой операции.';
  777.                     $this->resetExpected($curClient);
  778.                 }
  779.             }
  780.         } elseif($expected != '' && $expected != null){
  781.             if($curClient && $text != '' && $text != null){
  782.                 $groupObj false;
  783.                 if($group_id != null && $group_id != ''){
  784.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  785.                 } elseif($p_group != null && $p_group != '') {
  786.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  787.                 }
  788.                 if($is_group_chat === true && $groupObj){
  789.                     $chat_id $groupObj->getChatId();
  790.                 }
  791.                 $date_with null;
  792.                 $date_by null;
  793.                 $is_valid_with false;
  794.                 $is_valid_by false;
  795.                 if($groupObj && $curClient){
  796.                     if (strpos($text'-') !== false) {
  797.                         $d explode('-'trim($text));
  798.                         if(count($d) == 2){
  799.                             if($this->isValidDate(trim($d[0])) || $this->isValidDateTime(trim($d[0]))){
  800.                                 $date_with date("Y-m-d H:i:s"strtotime(trim($d[0])));
  801.                                 $is_valid_with true;
  802.                             }
  803.                             if($this->isValidDate(trim($d[1])) || $this->isValidDateTime(trim($d[1]))){
  804.                                 $date_by date("Y-m-d H:i:s"strtotime(trim($d[1])));
  805.                                 $is_valid_by true;
  806.                             }
  807.                         }
  808.                     }
  809.                     if($is_valid_with === true && $is_valid_by === true){
  810.                         $transactions_q $this->getDoctrine()
  811.                             ->getRepository(Transaction::class)
  812.                             ->createQueryBuilder('tr')
  813.                             ->select('tr.id')
  814.                             ->where('tr.amount != 0')
  815.                         ;
  816.                         if($date_with != '' && $date_with != null){
  817.                             $transactions_q->andWhere('tr.date >= :date_with')
  818.                                 ->setParameter('date_with'$date_with);
  819.                         }
  820.                         if($date_by != '' && $date_by != null){
  821.                             $transactions_q->andWhere('tr.date <= :date_by')
  822.                                 ->setParameter('date_by'$date_by);
  823.                         }
  824.                         if($groupObj){
  825.                             $transactions_q->andWhere('tr.from_group = ' $groupObj->getId() . ' OR tr.to_group = ' $groupObj->getId());
  826.                         }
  827.                         $transactions $transactions_q->getQuery()->getArrayResult();
  828.                         $count_trs count($transactions);
  829.                         if($count_trs 0){
  830.                             $newReport = new Report();
  831.                             $newReport->setClient(($curClient $curClient null));
  832.                             $newReport->setPath(null);
  833.                             $newReport->setDateWith(new \DateTime($date_with));
  834.                             $newReport->setDateBy(new \DateTime($date_by));
  835.                             $newReport->setIsSend(0);
  836.                             $newReport->setDate(new \DateTime(date("Y-m-d H:i:s")));
  837.                             $newReport->setClientGroup($groupObj);
  838.                             $em->persist($newReport);
  839.                             $em->flush();
  840.                             $file $this->genReport($newReport);
  841.                             if($file != '' && $file != null){
  842.                                 $email $curClient->getEmail();
  843.                                 if($email != null && $email != ''){
  844.                                     $body_mail = array(
  845.                                         '#app#' => $this->getParameter('app.name'),
  846.                                         '#logo#' => $this->getParameter('app.logo'),
  847.                                         '#date_with#' => date("d.m.Y H:i"strtotime($date_with)),
  848.                                         '#date_by#' => date("d.m.Y H:i"strtotime($date_by)),
  849.                                     );
  850.                                     $title_mail = array();
  851.                                     $attach = array();
  852.                                     $filepath $basePath $fileDir $file;
  853.                                     if(file_exists($filepath)){
  854.                                         $attach[] = $basePath $fileDir $file;
  855.                                     }
  856.                                     //отправка письма
  857.                                     //$email = 'igor@atmapro.ru';
  858.                                     $sendMail $this->sendEmail($this->mailer,'newReportPeriod'$body_mail$title_mail'ru'$email$attach);
  859.                                     $newReport->setIsSend(1);
  860.                                 }
  861.                                 $newReport->setPath($file);
  862.                                 $em->persist($newReport);
  863.                                 $em->flush();
  864.                                 $this->resetExpected($curClient);
  865.                                 $arr_f explode('/'$file);
  866.                                 $file_name '';
  867.                                 if(count($arr_f) == 2){
  868.                                     $file_name $arr_f[1];
  869.                                 }
  870.                                 $link_file = (isset($_SERVER['HTTPS']) ? 'https://' 'http://') . $_SERVER['HTTP_HOST'] . '/images/' $file;
  871.                                 $reply 'Файл отчета' . ($file_name != '' ' ' $file_name '') . ' успешно сформирован и отправлен на почту ' $email '. Также доступен для скачивания по ссылке ' $link_file;
  872.                             } else {
  873.                                 $reply 'Не удалось сформировать файл отчета, попробуйте позже.';
  874.                                 $this->resetExpected($curClient);
  875.                             }
  876.                         } else {
  877.                             $reply 'Финансовых операций за данный период не найдено, пропробуйте повторить команду и указать другой период.';
  878.                             $this->resetExpected($curClient);
  879.                         }
  880.                     } else {
  881.                         $reply 'Введен период в неправильном формате, введите период для формирования отчета, в формате: 01.04.2022-10.04.2022';
  882.                     }
  883.                 }
  884.             }
  885.         } else {
  886.             $groupObj false;
  887.             if($group_id != null && $group_id != ''){
  888.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  889.             } elseif($p_group != null && $p_group != '') {
  890.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  891.             }
  892.             if($is_group_chat === true && $groupObj){
  893.                 $chat_id $groupObj->getChatId();
  894.             }
  895.             $reply 'Введите период для формирования отчета для финансовых операций. В формате: 01.04.2022-10.04.2022';
  896.             $keyboard = array(
  897.                 array(
  898.                     array(
  899.                         'text'=>'Сформировать за все время',
  900.                         'callback_data'=> json_encode(array('action' => "all_report"'command' => "report""group" => ($groupObj $groupObj->getId() : null)))
  901.                     )
  902.                 ),
  903.                 array(
  904.                     array(
  905.                         'text'=>'Назад',
  906.                         'callback_data'=> json_encode(array('action' => "delete"'command' => "report"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  907.                     )
  908.                 )
  909.             );
  910.             $this->addExpected(($is_group_chat === true && $groupObj $groupObj $curClient), array("value" => "period_report""group" => ($groupObj $groupObj->getId() : null)));
  911.         }
  912.         $sendMessage false;
  913.         if(count($keyboard) > 0){
  914.             $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  915.             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  916.             $resp json_decode($sendMessagetrue);
  917.             if(isset($resp['result']['message_id']) && $groupObj){
  918.                 file_put_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt'$resp['result']['message_id']);
  919.             }
  920.         } else {
  921.             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  922.         }
  923.         if($is_group_chat === true){
  924.             $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
  925.             $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'report'));
  926.             $this->addLogMessageBot($bot$command$sendMessage);
  927.         }
  928.     }
  929.     private function mainMenu($client$is_group_chat true$type_group null)
  930.     {
  931.         $role_id null;
  932.         if($client){
  933.             if($client->getRole()){
  934.                 $role_id $client->getRole()->getId();
  935.             }
  936.         }
  937.         $main_menu '';
  938.         $commands $this->getDoctrine()->getRepository(Command::class)->findAll();
  939.         if(count($commands) > 0){
  940.             foreach ($commands as $command){
  941.                 if($command->getIsActive() === true){
  942.                     if($role_id != '' && $role_id != null){
  943.                         if(count($command->getRoles())){
  944.                             foreach ($command->getRoles() as $role){
  945.                                 if($role_id == $role->getId() && $command->getTypeof() != 'start'){
  946.                                     if((($is_group_chat === true) || ($is_group_chat === false && ($command->getTypeof() == 'help' || $command->getTypeof() == 'init')))){
  947.                                         if(!($type_group == 'salary' && $command->getTypeof() == 'bpay')){
  948.                                             $main_menu .= $command->getName() . ' - ' $command->getDescription() . "\n";
  949.                                         }
  950.                                     }
  951.                                 }
  952.                             }
  953.                         }
  954.                     } else {
  955.                         if(!($type_group == 'salary' && $command->getTypeof() == 'bpay')){
  956.                             $main_menu .= $command->getName() . ' - ' $command->getDescription() . "\n";
  957.                         }
  958.                     }
  959.                 }
  960.             }
  961.         }
  962.         return $main_menu;
  963.     }
  964.     private function dataExpected($expected){
  965.         $data = array();
  966.         if(ProjectUtilsController::isJSON($expected) === true){
  967.             $data json_decode($expectedtrue);
  968.         }
  969.         return $data;
  970.     }
  971.     private function resetExpected($client){
  972.         $em $this->getDoctrine()->getManager();
  973.         $resp false;
  974.         if($client){
  975.             if($client->getExpected() != '' && $client->getExpected() != null){
  976.                 $client->setExpected(null);
  977.                 $em->persist($client);
  978.                 $em->flush();
  979.                 $resp true;
  980.             }
  981.         }
  982.         return $resp;
  983.     }
  984.     private function addExpected($client$expected){
  985.         $em $this->getDoctrine()->getManager();
  986.         $resp false;
  987.         if($client){
  988.             $client->setExpected(json_encode($expected));
  989.             $em->persist($client);
  990.             $em->flush();
  991.             $resp true;
  992.         }
  993.         return $resp;
  994.     }
  995.     private function balance($token$chat_id$group_id$curClient false) {
  996.         $is_group_chat $this->getParameter('app.chat.is_group');
  997.         if(!$curClient && $chat_id != '' && $chat_id != null){
  998.             $curClient $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  999.         }
  1000.         $groupObj false;
  1001.         if($group_id != null && $group_id != ''){
  1002.             $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  1003.         }
  1004.         $is_delete false;
  1005.         $group_chat_id null;
  1006.         if($curClient && $groupObj){
  1007.             $group_chat_id $groupObj->getChatId();
  1008.             $role null;
  1009.             if($curClient->getRole()){
  1010.                 $role $curClient->getRole()->getTypeof();
  1011.             }
  1012.             $type_group null;
  1013.             if($groupObj->getTypeGroup()){
  1014.                 $type_group $groupObj->getTypeGroup()->getTypeof();
  1015.             }
  1016.             if(is_numeric($groupObj->getBalance())){
  1017.                 $opt "";
  1018.                 if($groupObj->getBalance() > 0){
  1019.                     $opt "+";
  1020.                 }
  1021.                 $balance $opt str_replace(',00'''number_format(($groupObj->getBalance() / 100), 2','' '));
  1022.                 
  1023.                 /*
  1024.                 if($role == 'director'){
  1025.                     if($type_group == 'cash'){
  1026.                         $reply = 'Баланс ' . $balance;
  1027.                     } else {
  1028.                         $reply = 'Нет доступа к балансу этой группы';
  1029.                     }
  1030.                 } else
  1031.                 */
  1032.                 if($role == 'auditor' || $role == 'director' || $role == 'accountant'){
  1033.                     $reply 'Баланс ' $balance;
  1034.                 } elseif($role == 'employee'){
  1035.                     if($type_group == 'salary'){
  1036.                         $reply 'Баланс ' $balance;
  1037.                     } else {
  1038.                         $is_delete true;
  1039.                         $reply 'Нет доступа к балансу этой группы.';
  1040.                     }
  1041.                 }
  1042.             } else {
  1043.                 $is_delete true;
  1044.                 $reply 'Ошибочное значение баланса.';
  1045.             }
  1046.         } else {
  1047.             $is_delete true;
  1048.             $reply 'Невозможно получить информацию по балансу, убедитесь, что отправляете команду в группе.';
  1049.         }
  1050.         $sendMessage null;
  1051.         if($group_chat_id != '' && $group_chat_id != null){
  1052.             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $group_chat_id'text' => $reply'parse_mode' => 'HTML']);
  1053.         } else {
  1054.             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  1055.         }
  1056.         if($is_group_chat === true){
  1057.             $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
  1058.             $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'balance'));
  1059.             if($is_delete === true){
  1060.                 $this->addLogMessageBot($bot$command$sendMessage);
  1061.             }
  1062.         }
  1063.     }
  1064.     private function curCommandPermissions($user$typeCommand 'pay'){
  1065.         $list = [];
  1066.         if($user && $user->getRole() !== null){
  1067.             $role $user->getRole();
  1068.             if(count($role->getCommandPermissions()) > 0){
  1069.                 foreach ($role->getCommandPermissions() as $commandPermission){
  1070.                     if($commandPermission->getCommand() != null){
  1071.                         if($commandPermission->getCommand()->getTypeof() == $typeCommand && $commandPermission->getIsActive()){
  1072.                             $list[] = $commandPermission->getTypeof();
  1073.                         }
  1074.                     }
  1075.                 }
  1076.             }
  1077.         }
  1078.         return $list;
  1079.     }
  1080.     private function pay($token$chat_id$group_id$cq_data = array(), $curClient false$text null$message_id null$file_id null) {
  1081.         $is_group_chat $this->kernel->getContainer()->getParameter('app.chat.is_group');
  1082.         $basePath $this->getParameter('kernel.project_dir');
  1083.         $create_transaction false;
  1084.         $action null;
  1085.         $p_group null;
  1086.         $keyboard = array();
  1087.         $em $this->getDoctrine()->getManager();
  1088.         if(count($cq_data) > 0){
  1089.             $action = (isset($cq_data['action']) ? $cq_data['action'] : null);
  1090.             $p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
  1091.         }
  1092.         $expected null;
  1093.         $ss_id null;
  1094.         if($curClient){
  1095.             $data_expected $this->dataExpected($curClient->getExpected());
  1096.             if(isset($data_expected['value'])){
  1097.                 $expected $data_expected['value'];
  1098.             }
  1099.             if(isset($data_expected['group'])){
  1100.                 $p_group $data_expected['group'];
  1101.             }
  1102.             if(isset($data_expected['ss_id'])){
  1103.                 $ss_id $data_expected['ss_id'];
  1104.             }
  1105.         }
  1106.         $editMessageId null;
  1107.         if(count($cq_data) > && $action != 'menu'){
  1108.             $name_group '';
  1109.             $groupObj false;
  1110.             if($group_id != null && $group_id != ''){
  1111.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  1112.             } elseif($p_group != null && $p_group != '') {
  1113.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  1114.             }
  1115.             if($action == 'delete' && $groupObj){
  1116.                 $mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
  1117.                 if($mes_id != '' && $mes_id != null){
  1118.                     $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
  1119.                 }
  1120.                 if(file_exists($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt')){
  1121.                     $mes_id file_get_contents($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt');
  1122.                     if($mes_id != '' && $mes_id != null){
  1123.                         $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
  1124.                         $resp json_decode($deleteMessagetrue);
  1125.                         if(isset($resp['result'])){
  1126.                             if($resp['result'] == true){
  1127.                                 unlink($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt');
  1128.                             }
  1129.                         }
  1130.                     }
  1131.                 }
  1132.                 exit();
  1133.             }
  1134.             $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  1135.             if($groupObj && $clientObj){
  1136.                 $name_group $groupObj->nameClient();
  1137.                 $type_group_typeof null;
  1138.                 if($groupObj->getTypeGroup()){
  1139.                     $type_group_typeof $groupObj->getTypeGroup()->getTypeof();
  1140.                 }
  1141.                 if($is_group_chat === true){
  1142.                     $chat_id $groupObj->getChatId();
  1143.                 }
  1144.                 if($type_group_typeof != null && $type_group_typeof != ''){
  1145.                     if($type_group_typeof == 'cash'){
  1146.                         if($action == 'income'){
  1147.                             $commandPermissions $this->curCommandPermissions($clientObj'pay');
  1148.                             $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Выбрано «Приход». ' 'Выберите откуда осуществляется приход.';
  1149. //                            $keyboard = array(
  1150. //                                array(
  1151. //                                    array(
  1152. //                                        'text'=>'По Объекту',
  1153. //                                        'callback_data'=> json_encode(array('action' => "income_partner", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  1154. //                                    )
  1155. //                                ),
  1156. //                                array(
  1157. //                                    array(
  1158. //                                        'text'=>'Перевод Нал-Нал',
  1159. //                                        'callback_data'=> json_encode(array('action' => "income_group", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  1160. //                                    ),
  1161. //                                ),
  1162. //                                array(
  1163. //                                    array(
  1164. //                                        'text'=>'Перевод ЗП-Нал',
  1165. //                                        'callback_data'=> json_encode(array('action' => "income_group_salary", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  1166. //                                    ),
  1167. //                                ),
  1168. //                                array(
  1169. //                                    array(
  1170. //                                        'text'=>'Назад',
  1171. //                                        'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  1172. //                                    ),
  1173. //                                )
  1174. //                            );
  1175.                             $keyboard = [];
  1176.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_income_office'$commandPermissions))){
  1177.                                 //Приход -> По Объекту
  1178.                                 $keyboard[] = [[
  1179.                                     'text'=>'По Объекту',
  1180.                                     'callback_data'=> json_encode(array('action' => "income_partner"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  1181.                                 ]];
  1182.                             }
  1183.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_income_transfer_cash_to_cash'$commandPermissions))){
  1184.                                 //Приход -> Превод Нал-Нал
  1185.                                 $keyboard[] = [[
  1186.                                     'text'=>'Перевод Нал-Нал',
  1187.                                     'callback_data'=> json_encode(array('action' => "income_group"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  1188.                                 ]];
  1189.                             }
  1190.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_income_transfer_salary_to_cash'$commandPermissions))){
  1191.                                 //Приход -> Превод ЗП-Нал
  1192.                                 $keyboard[] = [[
  1193.                                     'text'=>'Перевод ЗП-Нал',
  1194.                                     'callback_data'=> json_encode(array('action' => "income_group_salary"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  1195.                                 ]];
  1196.                             }
  1197.                             $keyboard[] = [[
  1198.                                 'text'=>'Назад',
  1199.                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  1200.                             ]];
  1201.                         } elseif($action == 'income_group'){
  1202.                             $clients_q $this->getDoctrine()
  1203.                                 ->getRepository(Client::class)
  1204.                                 ->createQueryBuilder('cl')
  1205.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  1206.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  1207.                                 ->where('cl.typeof != :typeof')
  1208.                                 ->andWhere('cl.is_active = 1')
  1209.                                 ->setParameter('typeof'"private")
  1210.                                 ->setParameter('typeof_group'"cash")
  1211.                             ;
  1212.                             if($groupObj){
  1213.                                 $clients_q->andWhere('cl.id != ' $groupObj->getId());
  1214.                             }
  1215.                             $clients $clients_q->getQuery()->getArrayResult();
  1216.                             if(count($clients) > 0){
  1217.                                 $buttons = array();
  1218.                                 foreach ($clients as $item_client){
  1219.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  1220.                                     $buttons[][] = array(
  1221.                                         'text' => $name_client,
  1222.                                         'callback_data'=> json_encode(array("action" => "add_cgroup"'command' => "pay"'id' => $item_client['id'], "group" => $p_group))
  1223.                                     );
  1224.                                 }
  1225.                                 $buttons[][] = array(
  1226.                                     'text' => 'Назад',
  1227.                                     'callback_data'=> json_encode(array("action" => "income"'command' => "pay""group" => $p_group))
  1228.                                 );
  1229.                                 $keyboard $buttons;
  1230.                                 $reply 'Выбрано «Перевод Нал-Нал». ' 'Выберите группу из которой будет списание средств.';
  1231.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1232.                                 if($draftOld){
  1233.                                     $em->remove($draftOld);
  1234.                                     $em->flush();
  1235.                                 }
  1236.                                 $newDraft = new Draft();
  1237.                                 $newDraft->setTypeof('expense');
  1238.                                 $newDraft->setClient($clientObj);
  1239.                                 $newDraft->setClientGroup($groupObj);
  1240.                                 $newDraft->setToGroup($groupObj);
  1241.                                 $newDraft->setExpected('cgroup');
  1242.                                 $newDraft->setNote('Перевод Нал-Нал');
  1243.                                 $newDraft->setTypeTransaction('transfer');
  1244.                                 $em->persist($newDraft);
  1245.                                 $em->flush();
  1246.                             } else {
  1247.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  1248.                             }
  1249.                         } elseif($action == 'income_group_salary'){
  1250.                             $clients_q $this->getDoctrine()
  1251.                                 ->getRepository(Client::class)
  1252.                                 ->createQueryBuilder('cl')
  1253.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  1254.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  1255.                                 ->where('cl.typeof != :typeof')
  1256.                                 ->andWhere('cl.is_active = 1')
  1257.                                 ->setParameter('typeof'"private")
  1258.                                 ->setParameter('typeof_group'"salary")
  1259.                             ;
  1260.                             if($groupObj){
  1261.                                 $clients_q->andWhere('cl.id != ' $groupObj->getId());
  1262.                             }
  1263.                             $clients $clients_q->getQuery()->getArrayResult();
  1264.                             if(count($clients) > 0){
  1265.                                 $buttons = array();
  1266.                                 foreach ($clients as $item_client){
  1267.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  1268.                                     $buttons[][] = array(
  1269.                                         'text' => $name_client,
  1270.                                         'callback_data'=> json_encode(array("action" => "add_cgroup"'command' => "pay"'id' => $item_client['id'], "group" => $p_group))
  1271.                                     );
  1272.                                 }
  1273.                                 $buttons[][] = array(
  1274.                                     'text' => 'Назад',
  1275.                                     'callback_data'=> json_encode(array("action" => "income"'command' => "pay""group" => $p_group))
  1276.                                 );
  1277.                                 $keyboard $buttons;
  1278.                                 $reply 'Выбрано «Перевод ЗП-Нал». ' 'Выберите группу из которой будет списание средств.';
  1279.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1280.                                 if($draftOld){
  1281.                                     $em->remove($draftOld);
  1282.                                     $em->flush();
  1283.                                 }
  1284.                                 $newDraft = new Draft();
  1285.                                 $newDraft->setTypeof('expense');
  1286.                                 $newDraft->setClient($clientObj);
  1287.                                 $newDraft->setClientGroup($groupObj);
  1288.                                 $newDraft->setToGroup($groupObj);
  1289.                                 $newDraft->setExpected('cgroup');
  1290.                                 $newDraft->setNote('Перевод ЗП-Нал');
  1291.                                 $newDraft->setTypeTransaction('transfer');
  1292.                                 $em->persist($newDraft);
  1293.                                 $em->flush();
  1294.                             } else {
  1295.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  1296.                             }
  1297.                         } elseif($action == 'add_cgroup'){
  1298.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1299.                             $from_client false;
  1300.                             if(isset($cq_data['id'])){
  1301.                                 if($cq_data['id'] != '' && $cq_data['id'] != null){
  1302.                                     $from_client $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  1303.                                 }
  1304.                             }
  1305.                             if($draftObj && $from_client){
  1306.                                 $from_group_typeof = ($from_client->getTypeGroup() != '' && $from_client->getTypeGroup() != null $from_client->getTypeGroup() : 'cash');
  1307.                                 $groupObj false;
  1308.                                 if($p_group != '' && $p_group != null){
  1309.                                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  1310.                                 }
  1311.                                 $draftObj->setFromGroup($from_client);
  1312.                                 $draftObj->setExpected('amount');
  1313.                                 $em->persist($draftObj);
  1314.                                 $em->flush();
  1315.                                 $this->addExpected(($groupObj && $is_group_chat === true $groupObj $clientObj), array("value" => "amount""group" => $p_group));
  1316.                                 $reply 'Выбрано «Группа ' . ($from_client $from_client->nameClient() : '') . ' для списания с баланса». ' 'Введите сумму.';
  1317.                                 if($from_group_typeof != 'salary'){
  1318.                                     $buttons[][] = array(
  1319.                                         'text' => 'Назад',
  1320.                                         'callback_data'=> json_encode(array("action" => "income_group"'command' => "pay""group" => $p_group))
  1321.                                     );
  1322.                                 } else {
  1323.                                     $buttons[][] = array(
  1324.                                         'text' => 'Назад',
  1325.                                         'callback_data'=> json_encode(array("action" => "income_group_salary"'command' => "pay""group" => $p_group))
  1326.                                     );
  1327.                                 }
  1328.                                 $keyboard $buttons;
  1329.                             } else {
  1330.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  1331.                             }
  1332.                         } elseif($action == 'income_partner' || $action == 'add_client' || $action == 'other'){
  1333.                             //step 1
  1334.                             $offices $this->getDoctrine()
  1335.                                 ->getRepository(Office::class)
  1336.                                 ->createQueryBuilder('o')
  1337.                                 ->select('o.id, o.name, o.number')
  1338.                                 ->where('o.is_active = 1')
  1339.                                 ->andWhere('o.deleted_at IS NULL')
  1340.                                 ->getQuery()
  1341.                                 ->getArrayResult();
  1342.                             if(count($offices) > 0){
  1343.                                 if($action == 'income_partner'){
  1344.                                     $reply 'Выбрано «По Объекту». ' 'Выберите объект, по которому осуществляется приход.';
  1345.                                 } elseif($action == 'other'){
  1346.                                     $reply 'Выбрано «Расходы по Объекту». ' 'Выберите объект, по которому осуществляется расход.';
  1347.                                 }
  1348.                                 $buttons = array();
  1349.                                 foreach ($offices as $item_office){
  1350.                                     $buttons[][] = array(
  1351.                                         'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  1352.                                         'callback_data'=> json_encode(array("action" => "add_office"'command' => "pay"'id' => $item_office['id'], "group" => $p_group))
  1353.                                     );
  1354.                                 }
  1355.                                 if($action == 'income_partner'){
  1356.                                     $buttons[][] = array(
  1357.                                         'text' => 'Назад',
  1358.                                         'callback_data'=> json_encode(array("action" => "income"'command' => "pay""group" => $p_group))
  1359.                                     );
  1360.                                 } elseif($action == 'other'){
  1361.                                     $buttons[][] = array(
  1362.                                         'text' => 'Назад',
  1363.                                         'callback_data'=> json_encode(array("action" => "expense"'command' => "pay""group" => $p_group))
  1364.                                     );
  1365.                                 } elseif($action == 'add_client'){
  1366.                                     $buttons[][] = array(
  1367.                                         'text' => 'Назад',
  1368.                                         'callback_data'=> json_encode(array("action" => "salary"'command' => "pay""group" => $p_group))
  1369.                                     );
  1370.                                 }
  1371.                                 $keyboard $buttons;
  1372.                                 if($action == 'income_partner'){
  1373.                                     $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1374.                                     if($draftOld){
  1375.                                         $em->remove($draftOld);
  1376.                                         $em->flush();
  1377.                                     }
  1378.                                     $newDraft = new Draft();
  1379.                                     $newDraft->setTypeof('income');
  1380.                                     $newDraft->setClient($clientObj);
  1381.                                     $newDraft->setClientGroup($groupObj);
  1382.                                     $newDraft->setToGroup($groupObj);
  1383.                                     $newDraft->setExpected('office');
  1384.                                     $newDraft->setNote('Поступление средств');
  1385.                                     $newDraft->setTypeTransaction('income');
  1386.                                     $em->persist($newDraft);
  1387.                                     $em->flush();
  1388.                                 } elseif($action == 'add_client' || $action == 'other'){
  1389.                                     $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1390.                                     $to_client false;
  1391.                                     if(isset($cq_data['id'])){
  1392.                                         if($cq_data['id'] != '' && $cq_data['id'] != null){
  1393.                                             $to_client $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  1394.                                         }
  1395.                                     }
  1396.                                     if($draftObj){
  1397.                                         if($action == 'other'){
  1398.                                             $draftObj->setNote('Списание средств');
  1399.                                             $draftObj->setTypeTransaction('expense_office');
  1400.                                             $draftObj->setExpected('amount');
  1401.                                         }
  1402.                                         if($to_client){
  1403.                                             $draftObj->setToGroup($to_client);
  1404.                                             $draftObj->setExpected('office');
  1405.                                             if($action == 'add_client'){
  1406.                                                 $name_salary_client $to_client->nameClient();
  1407.                                                 $reply 'Выбрано «Группа ' $name_salary_client ' для выплаты зарплаты». ' 'Выберите объект, по которому выплачивается зарплата.';
  1408.                                             }
  1409.                                         }
  1410.                                         $em->persist($draftObj);
  1411.                                         $em->flush();
  1412.                                     }
  1413.                                 }
  1414.                             } else {
  1415.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
  1416.                             }
  1417.                         } elseif($action == 'expense'){
  1418.                             //step 1
  1419.                             $commandPermissions $this->curCommandPermissions($clientObj'pay');
  1420.                             $reply 'Выбрано «Расход». ' 'Выберите тип расхода.';
  1421. //                            $keyboard = array(
  1422. //                                array(
  1423. //                                    array(
  1424. //                                        'text'=>'Перевод Нал-ЗП',
  1425. //                                        'callback_data'=> json_encode(array('action' => "salary", 'command' => "pay", "group" => $p_group))
  1426. //                                    )
  1427. //                                ),
  1428. //                                array(
  1429. //                                    array(
  1430. //                                        'text'=>'Перевод Нал-Нал',
  1431. //                                        'callback_data'=> json_encode(array('action' => "transfer", 'command' => "pay", "group" => $p_group))
  1432. //                                    ),
  1433. //                                ),
  1434. //                                array(
  1435. //                                    array(
  1436. //                                        'text'=>'Расходы по Объекту',
  1437. //                                        'callback_data'=> json_encode(array('action' => "other", 'command' => "pay", "group" => $p_group))
  1438. //                                    ),
  1439. //                                ),
  1440. ////                                array(
  1441. ////                                    array(
  1442. ////                                        'text'=>'Расходы на компанию',
  1443. ////                                        'callback_data'=> json_encode(array('action' => "company", 'command' => "pay", "group" => $p_group))
  1444. ////                                    ),
  1445. ////                                ),
  1446. //                                array(
  1447. //                                    array(
  1448. //                                        'text'=>'Назад',
  1449. //                                        'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => $p_group))
  1450. //                                    ),
  1451. //                                )
  1452. //                            );
  1453.                             $keyboard = [];
  1454.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_expense_transfer_cash_to_salary'$commandPermissions))){
  1455.                                 //Расход -> Превод Нал-ЗП
  1456.                                 $keyboard[] = [[
  1457.                                     'text'=>'Перевод Нал-ЗП',
  1458.                                     'callback_data'=> json_encode(array('action' => "salary"'command' => "pay""group" => $p_group))
  1459.                                 ]];
  1460.                             }
  1461.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_expense_transfer_cash_to_cash'$commandPermissions))){
  1462.                                 //Расход -> Превод Нал-Нал
  1463.                                 $keyboard[] = [[
  1464.                                     'text'=>'Перевод Нал-Нал',
  1465.                                     'callback_data'=> json_encode(array('action' => "transfer"'command' => "pay""group" => $p_group))
  1466.                                 ]];
  1467.                             }
  1468.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_expense_office'$commandPermissions))){
  1469.                                 //Расход -> Расходы по Объекту
  1470.                                 $keyboard[] = [[
  1471.                                     'text'=>'Расходы по Объекту',
  1472.                                     'callback_data'=> json_encode(array('action' => "other"'command' => "pay""group" => $p_group))
  1473.                                 ]];
  1474.                             }
  1475. //                            $keyboard[] = [[
  1476. //                                'text'=>'Расходы на компанию',
  1477. //                                'callback_data'=> json_encode(array('action' => "company", 'command' => "pay", "group" => $p_group))
  1478. //                            ]];
  1479.                             $keyboard[] = [[
  1480.                                 'text'=>'Назад',
  1481.                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  1482.                             ]];
  1483.                             $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1484.                             if($draftOld){
  1485.                                 $em->remove($draftOld);
  1486.                                 $em->flush();
  1487.                             }
  1488.                             $newDraft = new Draft();
  1489.                             $newDraft->setTypeof('expense');
  1490.                             $newDraft->setClient($clientObj);
  1491.                             $newDraft->setClientGroup($groupObj);
  1492.                             $newDraft->setFromGroup($groupObj);
  1493.                             $newDraft->setExpected('type_expense');
  1494.                             $em->persist($newDraft);
  1495.                             $em->flush();
  1496.                         } elseif($action == 'add_office' || $action == 'add_director'){
  1497.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1498.                             $officeObj false;
  1499.                             $directorObj false;
  1500.                             if($action == 'add_office'){
  1501.                                 if(isset($cq_data['id'])){
  1502.                                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  1503.                                         $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  1504.                                     }
  1505.                                 }
  1506.                                 if($officeObj){
  1507.                                     $draftObj->setOffice($officeObj);
  1508.                                 }
  1509.                             } elseif($action == 'add_director'){
  1510.                                 if(isset($cq_data['id'])){
  1511.                                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  1512.                                         $directorObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  1513.                                     }
  1514.                                 }
  1515.                                 if($directorObj){
  1516.                                     $draftObj->setToGroup($directorObj);
  1517.                                 }
  1518.                             }
  1519.                             $selected '';
  1520.                             if($action == 'add_office' && $officeObj){
  1521.                                 $selected 'Выбрано «Объект ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() . '». ';
  1522.                             } elseif($action == 'add_director' && $directorObj){
  1523.                                 $name_director $directorObj->nameClient();
  1524.                                 $selected 'Выбрано «Руководитель' . ($name_director != '' && $name_director != null ' ' $name_director '') . '». ';
  1525.                             }
  1526.                             if($draftObj){
  1527.                                 $draftObj->setExpected('amount');
  1528.                                 $em->persist($draftObj);
  1529.                                 $em->flush();
  1530.                                 $this->addExpected(($is_group_chat === true && $groupObj $groupObj $clientObj), array("value" => "amount""group" => $p_group));
  1531.                                 $reply $selected 'Введите сумму';
  1532. //                                if($action == 'add_office'){
  1533. //                                    $keyboard = array(
  1534. //                                        array(
  1535. //                                            array(
  1536. //                                                'text'=>'Назад',
  1537. //                                                'callback_data'=> json_encode(array('action' => "other", 'command' => "pay", "group" => $p_group))
  1538. //                                            ),
  1539. //                                        )
  1540. //                                    );
  1541. //                                } else {
  1542. //                                    $keyboard = array(
  1543. //                                        array(
  1544. //                                            array(
  1545. //                                                'text'=>'Назад',
  1546. //                                                'callback_data'=> json_encode(array('action' => "income_partner", 'command' => "pay", "group" => $p_group))
  1547. //                                            ),
  1548. //                                        )
  1549. //                                    );
  1550. //                                }
  1551.                             } else {
  1552.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  1553.                             }
  1554.                         } elseif($action == 'salary'){
  1555.                             $clients_q $this->getDoctrine()
  1556.                                 ->getRepository(Client::class)
  1557.                                 ->createQueryBuilder('cl')
  1558.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  1559.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  1560.                                 ->where('cl.typeof != :typeof')
  1561.                                 ->andWhere('cl.is_active = 1')
  1562.                                 ->setParameter('typeof'"private")
  1563.                                 ->setParameter('typeof_group'"salary")
  1564.                             ;
  1565.                             if($groupObj){
  1566.                                 $clients_q->andWhere('cl.id != ' $groupObj->getId());
  1567.                             }
  1568.                             $clients $clients_q->getQuery()->getArrayResult();
  1569.                             if(count($clients) > 0){
  1570.                                 $buttons = array();
  1571.                                 foreach ($clients as $item_client){
  1572.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  1573.                                     $buttons[][] = array(
  1574.                                         'text' => $name_client,
  1575.                                         'callback_data'=> json_encode(array("action" => "add_client"'command' => "pay"'id' => $item_client['id'], "group" => $p_group))
  1576.                                     );
  1577.                                 }
  1578.                                 $buttons[][] = array(
  1579.                                     'text'=>'Назад',
  1580.                                     'callback_data'=> json_encode(array('action' => "expense"'command' => "pay""group" => $p_group))
  1581.                                 );
  1582.                                 $keyboard $buttons;
  1583.                                 $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1584.                                 if($draftObj){
  1585.                                     $draftObj->setNote('Перевод Нал-ЗП');
  1586.                                     $draftObj->setTypeTransaction('add_salary');
  1587.                                     $draftObj->setExpected('to_group');
  1588.                                     $em->persist($draftObj);
  1589.                                     $em->flush();
  1590.                                     $reply 'Выбрано «Перевод Нал-ЗП». ' 'Выберите группу, которой будет осуществлен перевод.';
  1591.                                 } else {
  1592.                                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  1593.                                     $keyboard = array();
  1594.                                 }
  1595.                             } else {
  1596.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  1597.                             }
  1598.                         } elseif($action == 'transfer'){
  1599.                             $clients_q $this->getDoctrine()
  1600.                                 ->getRepository(Client::class)
  1601.                                 ->createQueryBuilder('cl')
  1602.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  1603.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  1604.                                 ->where('cl.typeof != :typeof')
  1605.                                 ->andWhere('cl.is_active = 1')
  1606.                                 ->setParameter('typeof'"private")
  1607.                                 ->setParameter('typeof_group'"cash")
  1608.                             ;
  1609.                             if($groupObj){
  1610.                                 $clients_q->andWhere('cl.id != ' $groupObj->getId());
  1611.                             }
  1612.                             $clients $clients_q->getQuery()->getArrayResult();
  1613.                             if(count($clients) > 0){
  1614.                                 $buttons = array();
  1615.                                 foreach ($clients as $item_client){
  1616.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  1617.                                     $buttons[][] = array(
  1618.                                         'text' => $name_client,
  1619.                                         'callback_data'=> json_encode(array("action" => "add_director"'command' => "pay"'id' => $item_client['id'], "group" => $p_group))
  1620.                                     );
  1621.                                 }
  1622.                                 $buttons[][] =  array(
  1623.                                     'text'=>'Назад',
  1624.                                     'callback_data'=> json_encode(array('action' => "expense"'command' => "pay""group" => $p_group))
  1625.                                 );
  1626.                                 $keyboard $buttons;
  1627.                                 $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1628.                                 if($draftObj){
  1629.                                     $draftObj->setNote('Перевод Нал-Нал');
  1630.                                     $draftObj->setTypeTransaction('transfer');
  1631.                                     $draftObj->setExpected('to_group');
  1632.                                     $em->persist($draftObj);
  1633.                                     $em->flush();
  1634.                                     $reply 'Выбрано «Перевод Нал-Нал». ' 'Выберите группу для перевода';
  1635.                                 } else {
  1636.                                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  1637.                                     $keyboard = array();
  1638.                                 }
  1639.                             } else {
  1640.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  1641.                             }
  1642.                         } elseif($action == 'company'){
  1643.                             $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1644.                             if($draftOld){
  1645.                                 $em->remove($draftOld);
  1646.                                 $em->flush();
  1647.                             }
  1648.                             $newDraft = new Draft();
  1649.                             $newDraft->setTypeof('expense');
  1650.                             $newDraft->setClient($clientObj);
  1651.                             $newDraft->setClientGroup($groupObj);
  1652.                             $newDraft->setFromGroup($groupObj);
  1653.                             $newDraft->setExpected('amount');
  1654.                             $newDraft->setNote('Списание средств на компанию');
  1655.                             $newDraft->setTypeTransaction('expense_company');
  1656.                             $em->persist($newDraft);
  1657.                             $em->flush();
  1658.                             $this->addExpected(($is_group_chat === true && $groupObj $groupObj $clientObj), array("value" => "amount""group" => $p_group));
  1659.                             $reply 'Выбрано «Расходы на компанию». ' 'Введите сумму.';
  1660.                         } elseif($action == 'no_cheque' || $action == 'finish_pay'){
  1661.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1662.                             $draftObj->setExpected('finish');
  1663.                             $em->persist($draftObj);
  1664.                             $em->flush();
  1665.                             $this->resetExpected($curClient);
  1666.                             $create_transaction $this->createTransaction($token$chat_id$groupObj$draftObj);
  1667.                             if($create_transaction === true){
  1668.                                 $em->remove($draftObj);
  1669.                                 $em->flush();
  1670.                             }
  1671.                             $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Транзакция успешно добавлена.';
  1672.                         }
  1673.                     } elseif($type_group_typeof == 'salary'){
  1674.                         if($action == 'income'){
  1675.                             $offices $this->getDoctrine()
  1676.                                 ->getRepository(Office::class)
  1677.                                 ->createQueryBuilder('o')
  1678.                                 ->select('o.id, o.name, o.number')
  1679.                                 ->where('o.is_active = 1')
  1680.                                 ->andWhere('o.deleted_at IS NULL')
  1681.                                 ->getQuery()
  1682.                                 ->getArrayResult();
  1683.                             if(count($offices) > 0){
  1684.                                 $reply 'Выбрано «Перевод в группу ЗП». ' 'Выберите объект, по которому осуществляется выплата зарплаты.';
  1685.                                 $buttons = array();
  1686.                                 foreach ($offices as $item_office){
  1687.                                     $buttons[][] = array(
  1688.                                         'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  1689.                                         'callback_data'=> json_encode(array("action" => "add_office"'command' => "pay"'id' => $item_office['id'], "group" => $p_group))
  1690.                                     );
  1691.                                 }
  1692.                                 $buttons[][] =  array(
  1693.                                     'text'=>'Назад',
  1694.                                     'callback_data'=> json_encode(array('action' => "delete"'command' => "pay""group" => $p_group))
  1695.                                 );
  1696.                                 $keyboard $buttons;
  1697.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1698.                                 if($draftOld){
  1699.                                     $em->remove($draftOld);
  1700.                                     $em->flush();
  1701.                                 }
  1702.                                 $newDraft = new Draft();
  1703.                                 $newDraft->setTypeof('expense');
  1704.                                 $newDraft->setClient($clientObj);
  1705.                                 $newDraft->setClientGroup($groupObj);
  1706.                                 $newDraft->setToGroup($groupObj);
  1707.                                 $newDraft->setExpected('office');
  1708.                                 $newDraft->setNote('Перевод в группу ЗП');
  1709.                                 $newDraft->setTypeTransaction('add_salary');
  1710.                                 $em->persist($newDraft);
  1711.                                 $em->flush();
  1712.                             } else {
  1713.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
  1714.                             }
  1715.                         } elseif($action == 'income_cash'){
  1716.                             $offices $this->getDoctrine()
  1717.                                 ->getRepository(Office::class)
  1718.                                 ->createQueryBuilder('o')
  1719.                                 ->select('o.id, o.name, o.number')
  1720.                                 ->where('o.is_active = 1')
  1721.                                 ->andWhere('o.deleted_at IS NULL')
  1722.                                 ->getQuery()
  1723.                                 ->getArrayResult();
  1724.                             if(count($offices) > 0){
  1725.                                 $reply 'Выбрано «Перевод в группу Нал». ' 'Выберите объект, по которому осуществляется выплата зарплаты.';
  1726.                                 $buttons = array();
  1727.                                 foreach ($offices as $item_office){
  1728.                                     $buttons[][] = array(
  1729.                                         'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  1730.                                         'callback_data'=> json_encode(array("action" => "add_office"'command' => "pay"'id' => $item_office['id'], "group" => $p_group))
  1731.                                     );
  1732.                                 }
  1733.                                 $buttons[][] =  array(
  1734.                                     'text'=>'Назад',
  1735.                                     'callback_data'=> json_encode(array('action' => "delete"'command' => "pay""group" => $p_group))
  1736.                                 );
  1737.                                 $keyboard $buttons;
  1738.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1739.                                 if($draftOld){
  1740.                                     $em->remove($draftOld);
  1741.                                     $em->flush();
  1742.                                 }
  1743.                                 $newDraft = new Draft();
  1744. //                                $newDraft->setTypeof('expense');
  1745.                                 $newDraft->setTypeof('income');
  1746.                                 $newDraft->setClient($clientObj);
  1747.                                 $newDraft->setClientGroup($groupObj);
  1748.                                 $newDraft->setToGroup($groupObj);
  1749.                                 $newDraft->setExpected('office');
  1750.                                 $newDraft->setNote('Перевод в группу Нал');
  1751.                                 $newDraft->setTypeTransaction('add_salary_cash');
  1752.                                 $em->persist($newDraft);
  1753.                                 $em->flush();
  1754.                             } else {
  1755.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
  1756.                             }
  1757.                         } elseif($action == 'add_office'){
  1758.                             $clients_q $this->getDoctrine()
  1759.                                 ->getRepository(Client::class)
  1760.                                 ->createQueryBuilder('cl')
  1761.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  1762.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  1763.                                 ->where('cl.typeof != :typeof')
  1764.                                 ->andWhere('cl.is_active = 1')
  1765.                                 ->setParameter('typeof'"private")
  1766.                                 ->setParameter('typeof_group'"cash")
  1767.                             ;
  1768.                             $clients $clients_q->getQuery()->getArrayResult();
  1769.                             if(count($clients) > 0){
  1770.                                 $buttons = array();
  1771.                                 foreach ($clients as $item_client){
  1772.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  1773.                                     $buttons[][] = array(
  1774.                                         'text' => $name_client,
  1775.                                         'callback_data'=> json_encode(array("action" => "add_client"'command' => "pay"'id' => $item_client['id'], "group" => $p_group))
  1776.                                     );
  1777.                                 }
  1778.                                 $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1779.                                 if($draftObj){
  1780.                                     $officeObj false;
  1781.                                     if(isset($cq_data['id'])){
  1782.                                         if($cq_data['id'] != '' && $cq_data['id'] != null){
  1783.                                             $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  1784.                                         }
  1785.                                     }
  1786.                                     if($officeObj){
  1787.                                         $draftObj->setOffice($officeObj);
  1788.                                     }
  1789.                                     $draftObj->setExpected('from_group');
  1790.                                     $em->persist($draftObj);
  1791.                                     $em->flush();
  1792.                                     if($draftObj->getTypeTransaction() != 'add_salary_cash'){
  1793.                                         $buttons[][] =  array(
  1794.                                             'text'=>'Назад',
  1795.                                             'callback_data'=> json_encode(array('action' => "income"'command' => "pay""group" => $p_group))
  1796.                                         );
  1797.                                         $keyboard $buttons;
  1798.                                         $reply 'Выбрано «Объект' . ($officeObj ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() : '') . '». ' 'Выберите группу, c которой будут списаны средства.';
  1799.                                     } else {
  1800.                                         $buttons[][] =  array(
  1801.                                             'text'=>'Назад',
  1802.                                             'callback_data'=> json_encode(array('action' => "income_cash"'command' => "pay""group" => $p_group))
  1803.                                         );
  1804.                                         $keyboard $buttons;
  1805.                                         $reply 'Выбрано «Объект' . ($officeObj ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() : '') . '». ' 'Выберите группу, в которую будут переведены средства.';
  1806.                                     }
  1807.                                 } else {
  1808.                                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  1809.                                     $keyboard = array();
  1810.                                 }
  1811.                             } else {
  1812.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  1813.                             }
  1814.                         } elseif($action == 'add_client'){
  1815.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1816.                             $to_client false;
  1817.                             if(isset($cq_data['id'])){
  1818.                                 if($cq_data['id'] != '' && $cq_data['id'] != null){
  1819.                                     $to_client $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  1820.                                 }
  1821.                             }
  1822.                             if($draftObj && $to_client){
  1823.                                 $groupObj false;
  1824.                                 if($p_group != '' && $p_group != null){
  1825.                                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  1826.                                 }
  1827.                                 $draftObj->setFromGroup($to_client);
  1828.                                 $draftObj->setExpected('amount');
  1829.                                 $em->persist($draftObj);
  1830.                                 $em->flush();
  1831.                                 $this->addExpected(($groupObj && $is_group_chat === true $groupObj $clientObj), array("value" => "amount""group" => $p_group));
  1832.                                 if($draftObj->getTypeTransaction() != 'add_salary_cash'){
  1833.                                     $reply 'Выбрано «Группа ' . ($to_client $to_client->nameClient() : '') . ' для списания средств». ' 'Введите сумму.';
  1834.                                 } else {
  1835.                                     $reply 'Выбрано «Группа ' . ($to_client $to_client->nameClient() : '') . ' для перевода средств». ' 'Введите сумму.';
  1836.                                 }
  1837.                             } else {
  1838.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  1839.                             }
  1840.                         } elseif($action == 'expense'){
  1841.                             $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1842.                             if($draftOld){
  1843.                                 $em->remove($draftOld);
  1844.                                 $em->flush();
  1845.                             }
  1846.                             $newDraft = new Draft();
  1847.                             $newDraft->setTypeof('expense');
  1848.                             $newDraft->setClient($clientObj);
  1849.                             $newDraft->setClientGroup($groupObj);
  1850.                             $newDraft->setToGroup($groupObj);
  1851.                             //$newDraft->setFromGroup($groupObj);
  1852.                             $newDraft->setExpected('add_office_expense');
  1853.                             $newDraft->setNote('Начисление зарплаты');
  1854.                             $newDraft->setTypeTransaction('payment_salary');
  1855.                             $em->persist($newDraft);
  1856.                             $em->flush();
  1857.                             $offices $this->getDoctrine()
  1858.                                 ->getRepository(Office::class)
  1859.                                 ->createQueryBuilder('o')
  1860.                                 ->select('o.id, o.name, o.number')
  1861.                                 ->where('o.is_active = 1')
  1862.                                 ->andWhere('o.deleted_at IS NULL')
  1863.                                 ->getQuery()
  1864.                                 ->getArrayResult();
  1865.                             if(count($offices) > 0){
  1866.                                 $reply 'Выбрано «Начисление зарплаты». ' 'Выберите объект, по которому осуществляется начисление зарплаты.';
  1867.                                 $keyboard = array();
  1868.                                 $buttons = array();
  1869.                                 foreach ($offices as $item_office){
  1870.                                     $buttons[][] = array(
  1871.                                         'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  1872.                                         'callback_data'=> json_encode(array("action" => "add_office_exp"'command' => "pay"'id' => $item_office['id'], "group" => $p_group))
  1873.                                     );
  1874.                                 }
  1875.                                 $buttons[][] =  array(
  1876.                                     'text'=>'Назад',
  1877.                                     'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  1878.                                 );
  1879.                                 $keyboard $buttons;
  1880.                             } else {
  1881.                                 $reply 'Нет объектов для начисление зарплаты по ним.';
  1882.                             }
  1883.                             /*
  1884.                             $groupObj = false;
  1885.                             if($p_group != '' && $p_group != null){
  1886.                                 $groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  1887.                             }
  1888.                             $this->addExpected(($groupObj && $is_group_chat === true ? $groupObj : $clientObj), array("value" => "amount", "group" => $p_group));
  1889.                             $reply = 'Выбрано «Начисление зарплаты». ' . 'Введите сумму';
  1890.                             */
  1891.                         } elseif($action == 'expense_salary') {
  1892.                             //операция начисление оклада
  1893.                             $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
  1894.                             if(count($salarySchedule) > 0){
  1895.                                 $max_ss $this->getParameter('app.max.salary_schedule');
  1896.                                 if(count($salarySchedule) < $max_ss){
  1897.                                     $reply 'Выбрано «Начисление оклада». Можете отредактировать условия начисления оклада по нужным числам месяца, добавить новое или удалить лишнее';
  1898.                                     $keyboard = array(
  1899.                                         array(
  1900.                                             array(
  1901.                                                 'text'=>'Редактировать условие начисления',
  1902.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_date"'command' => "pay""group" => $p_group))
  1903.                                             )
  1904.                                         ),
  1905.                                         array(
  1906.                                             array(
  1907.                                                 'text'=>'Новое условие начисления',
  1908.                                                 'callback_data'=> json_encode(array('action' => "new_ss_date"'command' => "pay""group" => $p_group))
  1909.                                             )
  1910.                                         ),
  1911.                                         array(
  1912.                                             array(
  1913.                                                 'text'=>'Удалить условие начисления',
  1914.                                                 'callback_data'=> json_encode(array('action' => "rem_ss_date"'command' => "pay""group" => $p_group))
  1915.                                             )
  1916.                                         ),
  1917.                                         array(
  1918.                                             array(
  1919.                                                 'text'=>'Назад',
  1920.                                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  1921.                                             )
  1922.                                         )
  1923.                                     );
  1924.                                 } else {
  1925.                                     $reply 'Выбрано «Начисление оклада». Можете отредактировать условия начисления оклада по нужным числам месяца или удалить лишнее';
  1926.                                     $keyboard = array(
  1927.                                         array(
  1928.                                             array(
  1929.                                                 'text'=>'Редактировать условие начисления',
  1930.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_date"'command' => "pay""group" => $p_group))
  1931.                                             )
  1932.                                         ),
  1933.                                         array(
  1934.                                             array(
  1935.                                                 'text'=>'Удалить условие начисления',
  1936.                                                 'callback_data'=> json_encode(array('action' => "rem_ss_date"'command' => "pay""group" => $p_group))
  1937.                                             )
  1938.                                         ),
  1939.                                         array(
  1940.                                             array(
  1941.                                                 'text'=>'Назад',
  1942.                                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  1943.                                             )
  1944.                                         )
  1945.                                     );
  1946.                                 }
  1947.                             } else {
  1948.                                 $reply 'Выбрано «Начисление оклада». Для начисления оклада по нужным числам месяца необходимо добавить условие начисления';
  1949.                                 $keyboard = array(array(
  1950.                                         array(
  1951.                                             'text'=>'Новое условие начисления',
  1952.                                             'callback_data'=> json_encode(array('action' => "new_ss_date"'command' => "pay""group" => $p_group))
  1953.                                         )
  1954.                                     ),
  1955.                                     array(
  1956.                                         array(
  1957.                                             'text'=>'Назад',
  1958.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  1959.                                         )
  1960.                                     )
  1961.                                 );
  1962.                             }
  1963.                         } elseif($action == 'new_ss_date') {
  1964.                             //новое условие начисления оклада
  1965.                             $reply 'Введите число дня месяца, в который будет осуществляться начисления оклада';
  1966.                             $keyboard = array(
  1967.                                 array(
  1968.                                     array(
  1969.                                         'text'=>'Назад',
  1970.                                         'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "pay""group" => $p_group))
  1971.                                     )
  1972.                                 )
  1973.                             );
  1974.                             $groupObj false;
  1975.                             if($p_group != '' && $p_group != null){
  1976.                                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  1977.                             }
  1978.                             $this->addExpected(($groupObj && $is_group_chat === true $groupObj $clientObj), array("value" => "new_date""group" => $p_group));
  1979.                         } elseif($action == 'edit_ss_date') {
  1980.                             //изменить условие начисления оклада
  1981.                             $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
  1982.                             if(count($salarySchedule) > 0){
  1983.                                 $reply 'Выберите из списка условие для начисления оклада, которое хотите отредактировать';
  1984.                                 $buttons = array();
  1985.                                 foreach ($salarySchedule as $item_ss){
  1986.                                     $buttons[][] = array(
  1987.                                         'text' => $item_ss['day'] . ' числа каждого месяца по ' $item_ss['amount'] . ' руб',
  1988.                                         'callback_data'=> json_encode(array("action" => "edit_ss"'command' => "pay"'ss_id' => $item_ss['id'], "group" => $p_group))
  1989.                                     );
  1990.                                 }
  1991.                                 $buttons[][] =  array(
  1992.                                     'text'=>'Назад',
  1993.                                     'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "pay""group" => $p_group))
  1994.                                 );
  1995.                                 $keyboard $buttons;
  1996.                             } else {
  1997.                                 $reply 'Условий для начисления оклада не найдено, можете создать новое';
  1998.                                 $keyboard = array(array(
  1999.                                     array(
  2000.                                         'text'=>'Новое условие начисления',
  2001.                                         'callback_data'=> json_encode(array('action' => "new_ss_date"'command' => "pay""group" => $p_group))
  2002.                                     )
  2003.                                 ),
  2004.                                     array(
  2005.                                         array(
  2006.                                             'text'=>'Назад',
  2007.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2008.                                         )
  2009.                                     )
  2010.                                 );
  2011.                             }
  2012.                         } elseif($action == 'rem_ss_date') {
  2013.                             //удалить условие начисления оклада
  2014.                             $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
  2015.                             if(count($salarySchedule) > 0){
  2016.                                 $reply 'Выберите из списка условие для начисления оклада, которое хотите удалить';
  2017.                                 $buttons = array();
  2018.                                 foreach ($salarySchedule as $item_ss){
  2019.                                     $buttons[][] = array(
  2020.                                         'text' => $item_ss['day'] . ' числа каждого месяца по ' $item_ss['amount'] . ' руб',
  2021.                                         'callback_data'=> json_encode(array("action" => "rem_ss"'command' => "pay"'ss_id' => $item_ss['id'], "group" => $p_group))
  2022.                                     );
  2023.                                 }
  2024.                                 $buttons[][] =  array(
  2025.                                     'text'=>'Назад',
  2026.                                     'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "pay""group" => $p_group))
  2027.                                 );
  2028.                                 $keyboard $buttons;
  2029.                             } else {
  2030.                                 $reply 'Условий для начисления оклада не найдено, можете создать новое';
  2031.                                 $keyboard = array(array(
  2032.                                     array(
  2033.                                         'text'=>'Новое условие начисления',
  2034.                                         'callback_data'=> json_encode(array('action' => "new_ss_date"'command' => "pay""group" => $p_group))
  2035.                                     )
  2036.                                 ),
  2037.                                     array(
  2038.                                         array(
  2039.                                             'text'=>'Назад',
  2040.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2041.                                         )
  2042.                                     )
  2043.                                 );
  2044.                             }
  2045.                         } elseif($action == 'edit_ss'){
  2046.                             //изменить условие начисления оклада
  2047.                             $id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
  2048.                             $isExistSs false;
  2049.                             if($id != '' && $id != null){
  2050.                                 $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
  2051.                                 if($salarySchedule){
  2052.                                     $isExistSs true;
  2053.                                     $reply 'Выбрано для редактирования условие для начисления «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() .  ' руб». Выберите, что нужно отредактировать';
  2054.                                     $keyboard = array(
  2055.                                         array(
  2056.                                             array(
  2057.                                                 'text'=>'Число месяца',
  2058.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_d"'command' => "pay"'ss_id' => $salarySchedule->getId(), "group" => $p_group))
  2059.                                             ),
  2060.                                             array(
  2061.                                                 'text'=>'Сумму начисления',
  2062.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_a"'command' => "pay"'ss_id' => $salarySchedule->getId(), "group" => $p_group))
  2063.                                             )
  2064.                                         ),
  2065.                                         array(
  2066.                                             array(
  2067.                                                 'text'=>'Назад',
  2068.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_date"'command' => "pay""group" => $p_group))
  2069.                                             )
  2070.                                         )
  2071.                                     );
  2072.                                 }
  2073.                             }
  2074.                             if(!$isExistSs){
  2075.                                 $reply 'Не удалось найти условий для начисления оклада';
  2076.                                 $keyboard = array(
  2077.                                     array(
  2078.                                         array(
  2079.                                             'text'=>'В основное меню',
  2080.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2081.                                         )
  2082.                                     )
  2083.                                 );
  2084.                             }
  2085.                         } elseif($action == 'edit_ss_d' || $action == 'edit_ss_a') {
  2086.                             //изменить условие начисления оклада
  2087.                             $id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
  2088.                             $isExistSs false;
  2089.                             if($id != '' && $id != null){
  2090.                                 $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
  2091.                                 if($salarySchedule){
  2092.                                     $isExistSs true;
  2093.                                     if($action == 'edit_ss_d'){
  2094.                                         $reply 'Введите новое число дня месяца для условия начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() .  ' руб»';
  2095.                                         $this->addExpected(($is_group_chat === true && $groupObj $groupObj $clientObj), array("value" => "edit_ss_d""ss_id" => $salarySchedule->getId(), "group" => $p_group));
  2096.                                     } else {
  2097.                                         $reply 'Введите новую сумму для условия начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() .  ' руб»';
  2098.                                         $this->addExpected(($is_group_chat === true && $groupObj $groupObj $clientObj), array("value" => "edit_ss_a""ss_id" => $salarySchedule->getId(), "group" => $p_group));
  2099.                                     }
  2100.                                 }
  2101.                             }
  2102.                             if(!$isExistSs){
  2103.                                 $reply 'Не удалось найти условий для начисления оклада';
  2104.                                 $keyboard = array(
  2105.                                     array(
  2106.                                         array(
  2107.                                             'text'=>'В основное меню',
  2108.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2109.                                         )
  2110.                                     )
  2111.                                 );
  2112.                             }
  2113.                         } elseif($action == 'rem_ss'){
  2114.                             //удалить условие начисления оклада
  2115.                             $id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
  2116.                             $isExistSs false;
  2117.                             if($id != '' && $id != null){
  2118.                                 $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
  2119.                                 if($salarySchedule){
  2120.                                     $isExistSs true;
  2121.                                     $reply 'Условие для начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() .  ' руб» успешно удалено';
  2122.                                     $em->remove($salarySchedule);
  2123.                                     $em->flush();
  2124.                                     $keyboard = array(
  2125.                                         array(
  2126.                                             array(
  2127.                                                 'text'=>'Назад',
  2128.                                                 'callback_data'=> json_encode(array('action' => "rem_ss_date"'command' => "pay""group" => $p_group))
  2129.                                             )
  2130.                                         ),
  2131.                                         array(
  2132.                                             array(
  2133.                                                 'text'=>'В основное меню',
  2134.                                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2135.                                             )
  2136.                                         )
  2137.                                     );
  2138.                                 }
  2139.                             }
  2140.                             if(!$isExistSs){
  2141.                                 $reply 'Не удалось найти условий для начисления оклада';
  2142.                                 $keyboard = array(
  2143.                                     array(
  2144.                                         array(
  2145.                                             'text'=>'В основное меню',
  2146.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2147.                                         )
  2148.                                     )
  2149.                                 );
  2150.                             }
  2151.                         } elseif($action == 'add_office_exp'){
  2152.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2153.                             if($draftObj){
  2154.                                 $officeObj false;
  2155.                                 if(isset($cq_data['id'])){
  2156.                                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  2157.                                         $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  2158.                                     }
  2159.                                 }
  2160.                                 if($officeObj){
  2161.                                     $draftObj->setOffice($officeObj);
  2162.                                 }
  2163.                                 $draftObj->setExpected('amount');
  2164.                                 $em->persist($draftObj);
  2165.                                 $em->flush();
  2166.                                 $reply 'Выбрано «Объект' . ($officeObj ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() : '') . ' для начисления зарплаты». ' 'Введите сумму.';
  2167.                                 $groupObj false;
  2168.                                 if($p_group != '' && $p_group != null){
  2169.                                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  2170.                                 }
  2171.                                 $this->addExpected(($groupObj && $is_group_chat === true $groupObj $clientObj), array("value" => "amount""group" => $p_group));
  2172.                             } else {
  2173.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  2174.                                 $keyboard = array();
  2175.                             }
  2176.                         }
  2177.                     }
  2178.                 } else {
  2179.                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить добавление финансовой операции, у данной группы не выбран тип группы. Пожалуйста укажите тип группы данной группе и начните добавление операции занова.';
  2180.                 }
  2181.             } else {
  2182.                 $reply 'Финансовые операции начинаются из группы, пожалуйста отправьте команду для начала операции в нужной группе.';
  2183.             }
  2184.         } elseif($expected != '' && $expected != null){
  2185.             $curClientObj false;
  2186.             if($is_group_chat === true){
  2187.                 $curClientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  2188.             }
  2189.             if($curClient && (($text != '' && $text != null) || ($file_id != '' && $file_id != null))){
  2190.                 $groupObj false;
  2191.                 if($group_id != null && $group_id != ''){
  2192.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  2193.                 } elseif($p_group != null && $p_group != '') {
  2194.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  2195.                 }
  2196.                 if($groupObj && $curClient){
  2197.                     $name_group $groupObj->nameClient();
  2198.                     $type_group_typeof null;
  2199.                     if($groupObj->getTypeGroup()){
  2200.                         $type_group_typeof $groupObj->getTypeGroup()->getTypeof();
  2201.                     }
  2202.                     if($is_group_chat === true && $groupObj){
  2203.                         $chat_id $groupObj->getChatId();
  2204.                     }
  2205.                     $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => ($curClientObj $curClientObj->getId() : $curClient->getId()), 'client_group' => $groupObj));
  2206.                     if($draftObj){
  2207.                         if($expected == 'amount'){
  2208.                             $amount = (float) $text;
  2209.                             if($amount || $amount /*|| $draftObj->getTypeTransaction() == 'payment_salary'*/){
  2210.                                 $draftObj->setAmount($amount 100);
  2211.                                 $draftObj->setExpected('comment');
  2212.                                 $em->persist($draftObj);
  2213.                                 $em->flush();
  2214.                                 $this->addExpected($curClient, array("value" => "comment""group" => $p_group));
  2215.                                 $sum str_replace(',00'''number_format(($draftObj->getAmount() / 100), 2','' '));
  2216.                                 $reply 'Введено «Сумма ' $sum '». ' 'Введите комментарий';
  2217.                             } else {
  2218.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Неправильно указана сумма, укажите сумму числом.';
  2219.                             }
  2220.                         } elseif($expected == 'comment') {
  2221.                             if($draftObj->getTypeTransaction() == 'expense_office'){
  2222.                                 $draftObj->setComment(trim($text));
  2223.                                 $draftObj->setExpected('file_cheque');
  2224.                                 $em->persist($draftObj);
  2225.                                 $em->flush();
  2226.                                 $this->addExpected($curClient, array("value" => "file_cheque""group" => $p_group));
  2227.                                 $keyboard = [
  2228.                                     [
  2229.                                         [
  2230.                                             'text'=>'Без чека',
  2231.                                             'callback_data'=> json_encode(array('action' => "no_cheque"'command' => "pay""group" => $p_group))
  2232.                                         ]
  2233.                                     ]
  2234.                                 ];
  2235.                                 $reply 'Сделайте или прикрепите фото чека';
  2236.                             } else {
  2237.                                 $draftObj->setComment(trim($text));
  2238.                                 $draftObj->setExpected('finish');
  2239.                                 $em->persist($draftObj);
  2240.                                 $em->flush();
  2241.                                 $this->resetExpected($curClient);
  2242.                                 $create_transaction $this->createTransaction($token$chat_id$groupObj$draftObj);
  2243.                                 if($create_transaction === true){
  2244.                                     $em->remove($draftObj);
  2245.                                     $em->flush();
  2246.                                 }
  2247.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Транзакция успешно добавлена.';
  2248.                             }
  2249.                         } elseif($expected == 'file_cheque') {
  2250.                             $file null;
  2251.                             if($file_id != '' && $file_id != null){
  2252.                                 $file $this->uploadFileBot($token$file_id);
  2253.                             }
  2254.                             if($file != null){
  2255.                                 $draftObj->setFile(($draftObj->getFile() != null && $draftObj->getFile() != '' $draftObj->getFile() . ';' $file $file));
  2256.                                 $em->persist($draftObj);
  2257.                                 $em->flush();
  2258.                                 $reply 'Фото чека успешно прикреплено. Чтобы добавить ещё фото чека, сделайте или прикрепите фото чека.';
  2259.                             } else {
  2260.                                 $reply 'Фото чека не удалось прикрепить. Чтобы добавить фото чека снова, сделайте или прикрепите фото чека.';
  2261.                             }
  2262.                             $editMessageId $draftObj->getLastMessageId();
  2263.                             $this->addExpected($curClient, array("value" => "file_cheque""group" => $p_group));
  2264.                             $keyboard = [
  2265.                                 [
  2266.                                     [
  2267.                                         'text'=> 'Завершить операцию',
  2268.                                         'callback_data'=> json_encode(array('action' => "finish_pay"'command' => "pay""group" => $p_group))
  2269.                                     ]
  2270.                                 ]
  2271.                             ];
  2272.                             /*
  2273.                             //окончание финансовой операции
  2274.                             $draftObj->setExpected('finish');
  2275.                             $em->persist($draftObj);
  2276.                             $em->flush();
  2277.                             $this->resetExpected($curClient);
  2278.                             $create_transaction = $this->createTransaction($token, $chat_id, $groupObj, $draftObj);
  2279.                             if($create_transaction === true){
  2280.                                 $em->remove($draftObj);
  2281.                                 $em->flush();
  2282.                             }
  2283.                             $reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Транзакция успешно добавлена.';
  2284.                             */
  2285.                         }
  2286.                     } elseif($expected == 'new_date'){
  2287.                         if(is_numeric(trim($text)) && trim($text) <= 31){
  2288.                             $reply 'Введите сумму начисления оклада';
  2289.                             $newSalarySchedule = new SalarySchedule();
  2290.                             $newSalarySchedule->setClient(($groupObj && $is_group_chat === true $groupObj $curClient))
  2291.                                 ->setDay(trim($text))
  2292.                                 ->setIsEdit(true)
  2293.                             ;
  2294.                             $em->persist($newSalarySchedule);
  2295.                             $em->flush();
  2296.                             $groupObj false;
  2297.                             if($p_group != '' && $p_group != null){
  2298.                                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  2299.                             }
  2300.                             $this->addExpected(($groupObj && $is_group_chat === true $groupObj $curClient), array("value" => "new_amount""group" => $p_group));
  2301.                         } else {
  2302.                             if(is_numeric(trim($text)) && trim($text) > 31){
  2303.                                 $reply 'День месяца не должен быть больше 31';
  2304.                             } else {
  2305.                                 $reply 'Введите день числом, в который будет осуществляться начисления оклада';
  2306.                             }
  2307.                             $keyboard = array(
  2308.                                 array(
  2309.                                     array(
  2310.                                         'text'=>'Назад',
  2311.                                         'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "pay""group" => $p_group))
  2312.                                     )
  2313.                                 )
  2314.                             );
  2315.                         }
  2316.                     } elseif($expected == 'new_amount'){
  2317.                         $amount = (float) $text;
  2318.                         $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(array('client' => ($groupObj && $is_group_chat === true $groupObj $curClient), 'is_edit' => true));
  2319.                         if($amount && $salarySchedule){
  2320.                             $salarySchedule->setAmount($amount)
  2321.                                 ->setIsEdit(false);
  2322.                             $em->persist($salarySchedule);
  2323.                             $em->flush();
  2324.                             $this->resetExpected(($groupObj && $is_group_chat === true $groupObj $curClient));
  2325.                             $reply 'Условие начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() . ' руб» успешно добавлено';
  2326.                         } else {
  2327.                             $reply 'Не удалось добавить информацию для начисления оклада, попробуйте повторить операцию снова';
  2328.                         }
  2329.                     } elseif($expected == 'edit_ss_d' || $expected == 'edit_ss_a') {
  2330.                         if(is_numeric($text)){
  2331.                             $isExistSs false;
  2332.                             if($ss_id != null && $ss_id != ''){
  2333.                                 $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(array('id' => $ss_id));
  2334.                                 if($salarySchedule){
  2335.                                     $isExistSs true;
  2336.                                     if($expected == 'edit_ss_d'){
  2337.                                         $salarySchedule->setDay($text);
  2338.                                     } else {
  2339.                                         $salarySchedule->setAmount($text);
  2340.                                     }
  2341.                                     $em->persist($salarySchedule);
  2342.                                     $em->flush();
  2343.                                     $reply 'Условие начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() . ' руб» успешно отредактировано';
  2344.                                     $keyboard = array(
  2345.                                         array(
  2346.                                             array(
  2347.                                                 'text'=>'Назад',
  2348.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_date"'command' => "pay""group" => $p_group))
  2349.                                             )
  2350.                                         ),
  2351.                                         array(
  2352.                                             array(
  2353.                                                 'text'=>'В основное меню',
  2354.                                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2355.                                             )
  2356.                                         )
  2357.                                     );
  2358.                                     $this->resetExpected($curClient);
  2359.                                 }
  2360.                             }
  2361.                             if(!$isExistSs){
  2362.                                 $reply 'Не удалось отредактировать условий для начисления оклада';
  2363.                                 $keyboard = array(
  2364.                                     array(
  2365.                                         array(
  2366.                                             'text'=>'В основное меню',
  2367.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2368.                                         )
  2369.                                     )
  2370.                                 );
  2371.                             }
  2372.                         } else {
  2373.                             $reply 'Данные для ввода должны быть числом. Повторите ввод';
  2374.                         }
  2375.                     } else {
  2376.                         $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  2377.                     }
  2378.                 }
  2379.             }
  2380.         } else {
  2381.             $groupObj false;
  2382.             if($group_id != '' && $group_id != null){
  2383.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  2384.             } elseif($p_group != '' && $p_group != null){
  2385.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  2386.             }
  2387.             if($groupObj){
  2388.                 if($is_group_chat === true && $groupObj){
  2389.                     $chat_id $groupObj->getChatId();
  2390.                 }
  2391.                 $name_group '';
  2392.                 $type_group_typeof null;
  2393.                 if($groupObj->getTypeGroup()){
  2394.                     $type_group_typeof $groupObj->getTypeGroup()->getTypeof();
  2395.                     $name_group $groupObj->nameClient();
  2396.                 }
  2397.                 if($type_group_typeof != null && $type_group_typeof != ''){
  2398.                     if($type_group_typeof == 'cash'){
  2399.                         $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Выберите финансовую операцию.';
  2400.                         $keyboard = array(
  2401.                             array(
  2402.                                 array(
  2403.                                     'text'=>'Приход',
  2404.                                     'callback_data'=> json_encode(array('action' => "income"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  2405.                                 )
  2406.                             ),
  2407.                             array(
  2408.                                 array(
  2409.                                     'text'=>'Расход',
  2410.                                     'callback_data'=> json_encode(array('action' => "expense"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  2411.                                 ),
  2412.                             ),
  2413.                             array(
  2414.                                 array(
  2415.                                     'text'=>'Назад',
  2416.                                     'callback_data'=> json_encode(array('action' => "delete"'command' => "pay"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  2417.                                 )
  2418.                             )
  2419.                         );
  2420.                     } elseif($type_group_typeof == 'salary') {
  2421.                         $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  2422.                         $commandPermissions $this->curCommandPermissions($clientObj'pay');
  2423.                         $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Выберите финансовую операцию.';
  2424. //                        $keyboard = array(
  2425. //                            array(
  2426. //                                array(
  2427. //                                    'text'=>'Перевод в группу ЗП',
  2428. //                                    'callback_data'=> json_encode(array('action' => "income", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  2429. //                                )
  2430. //                            ),
  2431. //                            array(
  2432. //                                array(
  2433. //                                    'text'=>'Перевод в группу Нал',
  2434. //                                    'callback_data'=> json_encode(array('action' => "income_cash", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  2435. //                                )
  2436. //                            ),
  2437. //                            array(
  2438. //                                array(
  2439. //                                    'text'=>'Начисление зарплаты',
  2440. //                                    'callback_data'=> json_encode(array('action' => "expense", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  2441. //                                ),
  2442. //                            ),
  2443. //                            array(
  2444. //                                array(
  2445. //                                    'text'=>'Начисление оклада',
  2446. //                                    'callback_data'=> json_encode(array('action' => "expense_salary", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  2447. //                                ),
  2448. //                            ),
  2449. //                            array(
  2450. //                                array(
  2451. //                                    'text'=>'Назад',
  2452. //                                    'callback_data'=> json_encode(array('action' => "delete", 'command' => "pay", 'mes_id' => $message_id, "group" => ($groupObj ? $groupObj->getId() : null)))
  2453. //                                )
  2454. //                            )
  2455. //                        );
  2456.                         $keyboard = [];
  2457.                         if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('salary_pay_transfer_to_salary'$commandPermissions))){
  2458.                             //Перевод в группу ЗП
  2459.                             $keyboard[] = [[
  2460.                                 'text'=>'Перевод в группу ЗП',
  2461.                                 'callback_data'=> json_encode(array('action' => "income"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  2462.                             ]];
  2463.                         }
  2464.                         if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('salary_pay_transfer_to_cash'$commandPermissions))){
  2465.                             //Перевод в группу Нал
  2466.                             $keyboard[] = [[
  2467.                                 'text'=>'Перевод в группу Нал',
  2468.                                 'callback_data'=> json_encode(array('action' => "income_cash"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  2469.                             ]];
  2470.                         }
  2471.                         if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('salary_pay_accrual_salary'$commandPermissions))){
  2472.                             //Начисление зарплаты
  2473.                             $keyboard[] = [[
  2474.                                 'text'=>'Начисление зарплаты',
  2475.                                 'callback_data'=> json_encode(array('action' => "expense"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  2476.                             ]];
  2477.                         }
  2478.                         if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('salary_pay_accrual_payday'$commandPermissions))){
  2479.                             //Начисление оклада
  2480.                             $keyboard[] = [[
  2481.                                 'text'=>'Начисление оклада',
  2482.                                 'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  2483.                             ]];
  2484.                         }
  2485.                         $keyboard[] = [[
  2486.                             'text'=>'Назад',
  2487.                             'callback_data'=> json_encode(array('action' => "delete"'command' => "pay"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  2488.                         ]];
  2489.                     }
  2490.                 } else {
  2491.                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить действие, у данной группы не выбран тип группы. Пожалуйста укажите тип группы и начните данную команду заново.';
  2492.                 }
  2493.             } else {
  2494.                 $reply 'Финансовые операции начинаются из группы, пожалуйста отправьте команду для начала операции в нужной группе.';
  2495.             }
  2496.         }
  2497.         if(!isset($reply) || $reply == '' || $reply == null){
  2498.             $reply 'Что то пошло не так, начните выполнение операции заново';
  2499.         }
  2500.         $sendMessage false;
  2501.         if(count($keyboard) > 0){
  2502.             $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  2503.             if($editMessageId != null){
  2504.                 //редактировать уже существующее сообщение
  2505.                 $sendMessage ProjectUtilsController::requestToBot($token'editMessageText', ['chat_id' => $chat_id'message_id' => $editMessageId'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  2506.             } else {
  2507.                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  2508.             }
  2509.             $resp json_decode($sendMessagetrue);
  2510.             if(isset($resp['result']['message_id']) && $groupObj){
  2511.                 file_put_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt'$resp['result']['message_id']);
  2512.             }
  2513. //            if($draftObj && $file_id != null && $file_id != '' && isset($resp['result']['message_id'])){
  2514. //                $draftObj->setLastMessageId($resp['result']['message_id']);
  2515. //                $em->persist($draftObj);
  2516. //                $em->flush();
  2517. //            }
  2518.         } else {
  2519.             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  2520.         }
  2521.         if($is_group_chat === true){
  2522.             $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
  2523.             $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'pay'));
  2524.             $this->addLogMessageBot($bot$command$sendMessage);
  2525.             if($create_transaction === true){
  2526.                 $this->deleteLogMessage($bot$chat_id$command->getId());
  2527.             }
  2528.         }
  2529.     }
  2530.     private function bpay($token$chat_id$group_id$cq_data = array(), $curClient false$text null$message_id null$file_id null) {
  2531.         $is_group_chat $this->kernel->getContainer()->getParameter('app.chat.is_group');
  2532.         $basePath $this->getParameter('kernel.project_dir');
  2533.         $create_transaction false;
  2534.         $action null;
  2535.         $p_group null;
  2536.         $keyboard = array();
  2537.         $em $this->getDoctrine()->getManager();
  2538.         if(count($cq_data) > 0){
  2539.             $action = (isset($cq_data['action']) ? $cq_data['action'] : null);
  2540.             $p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
  2541.         }
  2542.         $expected null;
  2543.         $ss_id null;
  2544.         if($curClient){
  2545.             $data_expected $this->dataExpected($curClient->getExpected());
  2546.             if(isset($data_expected['value'])){
  2547.                 $expected $data_expected['value'];
  2548.             }
  2549.             if(isset($data_expected['group'])){
  2550.                 $p_group $data_expected['group'];
  2551.             }
  2552.             if(isset($data_expected['ss_id'])){
  2553.                 $ss_id $data_expected['ss_id'];
  2554.             }
  2555.         }
  2556.         $editMessageId null;
  2557.         if(count($cq_data) > && $action != 'menu'){
  2558.             $name_group '';
  2559.             $groupObj false;
  2560.             if($group_id != null && $group_id != ''){
  2561.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  2562.             } elseif($p_group != null && $p_group != '') {
  2563.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  2564.             }
  2565.             if($action == 'delete' && $groupObj){
  2566.                 $mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
  2567.                 if($mes_id != '' && $mes_id != null){
  2568.                     $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
  2569.                 }
  2570.                 if(file_exists($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt')){
  2571.                     $mes_id file_get_contents($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt');
  2572.                     if($mes_id != '' && $mes_id != null){
  2573.                         $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
  2574.                         $resp json_decode($deleteMessagetrue);
  2575.                         if(isset($resp['result'])){
  2576.                             if($resp['result'] == true){
  2577.                                 unlink($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt');
  2578.                             }
  2579.                         }
  2580.                     }
  2581.                 }
  2582.                 exit();
  2583.             }
  2584.             $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  2585.             if($groupObj && $clientObj){
  2586.                 $name_group $groupObj->nameClient();
  2587.                 $type_group_typeof null;
  2588.                 if($groupObj->getTypeGroup()){
  2589.                     $type_group_typeof $groupObj->getTypeGroup()->getTypeof();
  2590.                 }
  2591.                 if($is_group_chat === true){
  2592.                     $chat_id $groupObj->getChatId();
  2593.                 }
  2594.                 if($type_group_typeof != null && $type_group_typeof != ''){
  2595.                     if($type_group_typeof == 'cash'){
  2596.                         if($action == 'income'){
  2597.                             $commandPermissions $this->curCommandPermissions($clientObj'bpay');
  2598.                             $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Выбрано «Приход». ' 'Выберите откуда осуществляется приход.';
  2599. //                            $keyboard = array(
  2600. //                                array(
  2601. //                                    array(
  2602. //                                        'text'=>'По Объекту',
  2603. //                                        'callback_data'=> json_encode(array('action' => "income_partner", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  2604. //                                    )
  2605. //                                ),
  2606. //                                array(
  2607. //                                    array(
  2608. //                                        'text'=>'Перевод Нал-Нал',
  2609. //                                        'callback_data'=> json_encode(array('action' => "income_group", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  2610. //                                    ),
  2611. //                                ),
  2612. //                                array(
  2613. //                                    array(
  2614. //                                        'text'=>'Перевод ЗП-Нал',
  2615. //                                        'callback_data'=> json_encode(array('action' => "income_group_salary", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  2616. //                                    ),
  2617. //                                ),
  2618. //                                array(
  2619. //                                    array(
  2620. //                                        'text'=>'Назад',
  2621. //                                        'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  2622. //                                    ),
  2623. //                                )
  2624. //                            );
  2625.                             $keyboard = [];
  2626.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_income_office'$commandPermissions))){
  2627.                                 //Приход -> По Объекту
  2628.                                 $keyboard[] = [[
  2629.                                     'text'=>'По Объекту',
  2630.                                     'callback_data'=> json_encode(array('action' => "income_partner"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  2631.                                 ]];
  2632.                             }
  2633.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_income_transfer_cash_to_cash'$commandPermissions))){
  2634.                                 //Приход -> Превод Нал-Нал
  2635.                                 $keyboard[] = [[
  2636.                                     'text'=>'Перевод Нал-Нал',
  2637.                                     'callback_data'=> json_encode(array('action' => "income_group"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  2638.                                 ]];
  2639.                             }
  2640.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_income_transfer_salary_to_cash'$commandPermissions))){
  2641.                                 //Приход -> Превод ЗП-Нал
  2642.                                 $keyboard[] = [[
  2643.                                     'text'=>'Перевод ЗП-Нал',
  2644.                                     'callback_data'=> json_encode(array('action' => "income_group_salary"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  2645.                                 ]];
  2646.                             }
  2647.                             $keyboard[] = [[
  2648.                                 'text'=>'Назад',
  2649.                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  2650.                             ]];
  2651.                         } elseif($action == 'income_group'){
  2652.                             $clients_q $this->getDoctrine()
  2653.                                 ->getRepository(Client::class)
  2654.                                 ->createQueryBuilder('cl')
  2655.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  2656.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  2657.                                 ->where('cl.typeof != :typeof')
  2658.                                 ->andWhere('cl.is_active = 1')
  2659.                                 ->setParameter('typeof'"private")
  2660.                                 ->setParameter('typeof_group'"cash")
  2661.                             ;
  2662.                             if($groupObj){
  2663.                                 $clients_q->andWhere('cl.id != ' $groupObj->getId());
  2664.                             }
  2665.                             $clients $clients_q->getQuery()->getArrayResult();
  2666.                             if(count($clients) > 0){
  2667.                                 $buttons = array();
  2668.                                 foreach ($clients as $item_client){
  2669.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  2670.                                     $buttons[][] = array(
  2671.                                         'text' => $name_client,
  2672.                                         'callback_data'=> json_encode(array("action" => "add_cgroup"'command' => "bpay"'id' => $item_client['id'], "group" => $p_group))
  2673.                                     );
  2674.                                 }
  2675.                                 $buttons[][] = array(
  2676.                                     'text' => 'Назад',
  2677.                                     'callback_data'=> json_encode(array("action" => "income"'command' => "bpay""group" => $p_group))
  2678.                                 );
  2679.                                 $keyboard $buttons;
  2680.                                 $reply 'Выбрано «Перевод Нал-Нал». ' 'Выберите группу из которой будет списание средств.';
  2681.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2682.                                 if($draftOld){
  2683.                                     $em->remove($draftOld);
  2684.                                     $em->flush();
  2685.                                 }
  2686.                                 $newDraft = new Draft();
  2687.                                 $newDraft->setTypeof('expense');
  2688.                                 $newDraft->setClient($clientObj);
  2689.                                 $newDraft->setClientGroup($groupObj);
  2690.                                 $newDraft->setToGroup($groupObj);
  2691.                                 $newDraft->setExpected('cgroup');
  2692.                                 $newDraft->setNote('Перевод Нал-Нал');
  2693.                                 $newDraft->setTypeTransaction('transfer');
  2694.                                 $em->persist($newDraft);
  2695.                                 $em->flush();
  2696.                             } else {
  2697.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  2698.                             }
  2699.                         } elseif($action == 'income_group_salary'){
  2700.                             $clients_q $this->getDoctrine()
  2701.                                 ->getRepository(Client::class)
  2702.                                 ->createQueryBuilder('cl')
  2703.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  2704.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  2705.                                 ->where('cl.typeof != :typeof')
  2706.                                 ->andWhere('cl.is_active = 1')
  2707.                                 ->setParameter('typeof'"private")
  2708.                                 ->setParameter('typeof_group'"salary")
  2709.                             ;
  2710.                             if($groupObj){
  2711.                                 $clients_q->andWhere('cl.id != ' $groupObj->getId());
  2712.                             }
  2713.                             $clients $clients_q->getQuery()->getArrayResult();
  2714.                             if(count($clients) > 0){
  2715.                                 $buttons = array();
  2716.                                 foreach ($clients as $item_client){
  2717.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  2718.                                     $buttons[][] = array(
  2719.                                         'text' => $name_client,
  2720.                                         'callback_data'=> json_encode(array("action" => "add_cgroup"'command' => "bpay"'id' => $item_client['id'], "group" => $p_group))
  2721.                                     );
  2722.                                 }
  2723.                                 $buttons[][] = array(
  2724.                                     'text' => 'Назад',
  2725.                                     'callback_data'=> json_encode(array("action" => "income"'command' => "bpay""group" => $p_group))
  2726.                                 );
  2727.                                 $keyboard $buttons;
  2728.                                 $reply 'Выбрано «Перевод ЗП-Нал». ' 'Выберите группу из которой будет списание средств.';
  2729.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2730.                                 if($draftOld){
  2731.                                     $em->remove($draftOld);
  2732.                                     $em->flush();
  2733.                                 }
  2734.                                 $newDraft = new Draft();
  2735.                                 $newDraft->setTypeof('expense');
  2736.                                 $newDraft->setClient($clientObj);
  2737.                                 $newDraft->setClientGroup($groupObj);
  2738.                                 $newDraft->setToGroup($groupObj);
  2739.                                 $newDraft->setExpected('cgroup');
  2740.                                 $newDraft->setNote('Перевод ЗП-Нал');
  2741.                                 $newDraft->setTypeTransaction('transfer');
  2742.                                 $em->persist($newDraft);
  2743.                                 $em->flush();
  2744.                             } else {
  2745.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  2746.                             }
  2747.                         } elseif($action == 'add_cgroup'){
  2748.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2749.                             $from_client false;
  2750.                             if(isset($cq_data['id'])){
  2751.                                 if($cq_data['id'] != '' && $cq_data['id'] != null){
  2752.                                     $from_client $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  2753.                                 }
  2754.                             }
  2755.                             if($draftObj && $from_client){
  2756.                                 $from_group_typeof = ($from_client->getTypeGroup() != '' && $from_client->getTypeGroup() != null $from_client->getTypeGroup() : 'cash');
  2757.                                 $groupObj false;
  2758.                                 if($p_group != '' && $p_group != null){
  2759.                                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  2760.                                 }
  2761.                                 $draftObj->setFromGroup($from_client);
  2762.                                 $draftObj->setExpected('amount_b');
  2763.                                 $em->persist($draftObj);
  2764.                                 $em->flush();
  2765.                                 $this->addExpected(($groupObj && $is_group_chat === true $groupObj $clientObj), array("value" => "amount_b""group" => $p_group));
  2766.                                 $reply 'Выбрано «Группа ' . ($from_client $from_client->nameClient() : '') . ' для списания с баланса». ' 'Введите сумму.';
  2767.                                 if($from_group_typeof != 'salary'){
  2768.                                     $buttons[][] = array(
  2769.                                         'text' => 'Назад',
  2770.                                         'callback_data'=> json_encode(array("action" => "income_group"'command' => "bpay""group" => $p_group))
  2771.                                     );
  2772.                                 } else {
  2773.                                     $buttons[][] = array(
  2774.                                         'text' => 'Назад',
  2775.                                         'callback_data'=> json_encode(array("action" => "income_group_salary"'command' => "bpay""group" => $p_group))
  2776.                                     );
  2777.                                 }
  2778.                                 $keyboard $buttons;
  2779.                             } else {
  2780.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  2781.                             }
  2782.                         } elseif($action == 'income_partner' || $action == 'add_client' || $action == 'other'){
  2783.                             //step 1
  2784.                             $offices $this->getDoctrine()
  2785.                                 ->getRepository(Office::class)
  2786.                                 ->createQueryBuilder('o')
  2787.                                 ->select('o.id, o.name, o.number')
  2788.                                 ->where('o.is_active = 1')
  2789.                                 ->andWhere('o.deleted_at IS NULL')
  2790.                                 ->getQuery()
  2791.                                 ->getArrayResult();
  2792.                             if(count($offices) > 0){
  2793.                                 if($action == 'income_partner'){
  2794.                                     $reply 'Выбрано «По Объекту». ' 'Выберите объект, по которому осуществляется приход.';
  2795.                                 } elseif($action == 'other'){
  2796.                                     $name_group '';
  2797.                                     if($p_group != '' && $p_group != null){
  2798.                                         $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  2799.                                         if($groupObj){
  2800.                                             if($groupObj->getTypeGroup()){
  2801.                                                 $name_group $groupObj->nameClient();
  2802.                                             }
  2803.                                         }
  2804.                                     }
  2805.                                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Выберите объект, по которому осуществляется расход.';
  2806.                                     //$reply = 'Выбрано «Расходы по Объекту». ' . 'Выберите объект, по которому осуществляется расход.';
  2807.                                 }
  2808.                                 $buttons = array();
  2809.                                 foreach ($offices as $item_office){
  2810.                                     $buttons[][] = array(
  2811.                                         'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  2812.                                         'callback_data'=> json_encode(array("action" => "add_office"'command' => "bpay"'id' => $item_office['id'], "group" => $p_group))
  2813.                                     );
  2814.                                 }
  2815.                                 if($action == 'income_partner'){
  2816.                                     $buttons[][] = array(
  2817.                                         'text' => 'Назад',
  2818.                                         'callback_data'=> json_encode(array("action" => "income"'command' => "bay""group" => $p_group))
  2819.                                     );
  2820.                                 } elseif($action == 'other'){
  2821. //                                    $buttons[][] = array(
  2822. //                                        'text' => 'Назад',
  2823. //                                        'callback_data'=> json_encode(array("action" => "expense", 'command' => "bpay", "group" => $p_group))
  2824. //                                    );
  2825.                                 } elseif($action == 'add_client'){
  2826.                                     $buttons[][] = array(
  2827.                                         'text' => 'Назад',
  2828.                                         'callback_data'=> json_encode(array("action" => "salary"'command' => "bpay""group" => $p_group))
  2829.                                     );
  2830.                                 }
  2831.                                 $keyboard $buttons;
  2832.                                 if($action == 'income_partner'){
  2833.                                     $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2834.                                     if($draftOld){
  2835.                                         $em->remove($draftOld);
  2836.                                         $em->flush();
  2837.                                     }
  2838.                                     $newDraft = new Draft();
  2839.                                     $newDraft->setTypeof('income');
  2840.                                     $newDraft->setClient($clientObj);
  2841.                                     $newDraft->setClientGroup($groupObj);
  2842.                                     $newDraft->setToGroup($groupObj);
  2843.                                     $newDraft->setExpected('office_b');
  2844.                                     $newDraft->setNote('Поступление средств');
  2845.                                     $newDraft->setTypeTransaction('income');
  2846.                                     $em->persist($newDraft);
  2847.                                     $em->flush();
  2848.                                 } elseif($action == 'add_client' || $action == 'other'){
  2849.                                     $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2850.                                     $to_client false;
  2851.                                     if(isset($cq_data['id'])){
  2852.                                         if($cq_data['id'] != '' && $cq_data['id'] != null){
  2853.                                             $to_client $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  2854.                                         }
  2855.                                     }
  2856.                                     //если сразу выбирается объект
  2857.                                     $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2858.                                     if($draftOld){
  2859.                                         $em->remove($draftOld);
  2860.                                         $em->flush();
  2861.                                     }
  2862.                                     $newDraft = new Draft();
  2863.                                     $newDraft->setTypeof('expense');
  2864.                                     $newDraft->setClient($clientObj);
  2865.                                     $newDraft->setClientGroup($groupObj);
  2866.                                     $newDraft->setFromGroup($groupObj);
  2867.                                     $newDraft->setExpected('type_expense_b');
  2868.                                     $em->persist($newDraft);
  2869.                                     $em->flush();
  2870.                                     $draftObj $newDraft;
  2871.                                     //если сразу выбирается объект
  2872.                                     if($draftObj){
  2873.                                         if($action == 'other'){
  2874.                                             $draftObj->setNote('Списание средств');
  2875.                                             $draftObj->setTypeTransaction('expense_office');
  2876.                                             $draftObj->setExpected('amount_b');
  2877.                                         }
  2878.                                         if($to_client){
  2879.                                             $draftObj->setToGroup($to_client);
  2880.                                             $draftObj->setExpected('office_b');
  2881.                                             if($action == 'add_client'){
  2882.                                                 $name_salary_client $to_client->nameClient();
  2883.                                                 $reply 'Выбрано «Группа ' $name_salary_client ' для выплаты зарплаты». ' 'Выберите объект, по которому выплачивается зарплата.';
  2884.                                             }
  2885.                                         }
  2886.                                         $em->persist($draftObj);
  2887.                                         $em->flush();
  2888.                                     }
  2889.                                 }
  2890.                             } else {
  2891.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
  2892.                             }
  2893.                         } elseif($action == 'expense'){
  2894.                             //step 1
  2895.                             $commandPermissions $this->curCommandPermissions($clientObj'bpay');
  2896.                             $reply 'Выбрано «Расход». ' 'Выберите тип расхода.';
  2897. //                            $keyboard = array(
  2898. //                                array(
  2899. //                                    array(
  2900. //                                        'text'=>'Перевод Нал-ЗП',
  2901. //                                        'callback_data'=> json_encode(array('action' => "salary", 'command' => "bpay", "group" => $p_group))
  2902. //                                    )
  2903. //                                ),
  2904. //                                array(
  2905. //                                    array(
  2906. //                                        'text'=>'Перевод Нал-Нал',
  2907. //                                        'callback_data'=> json_encode(array('action' => "transfer", 'command' => "bpay", "group" => $p_group))
  2908. //                                    ),
  2909. //                                ),
  2910. //                                array(
  2911. //                                    array(
  2912. //                                        'text'=>'Расходы по Объекту',
  2913. //                                        'callback_data'=> json_encode(array('action' => "other", 'command' => "bpay", "group" => $p_group))
  2914. //                                    ),
  2915. //                                ),
  2916. ////                                array(
  2917. ////                                    array(
  2918. ////                                        'text'=>'Расходы на компанию',
  2919. ////                                        'callback_data'=> json_encode(array('action' => "company", 'command' => "bpay", "group" => $p_group))
  2920. ////                                    ),
  2921. ////                                ),
  2922. //                                array(
  2923. //                                    array(
  2924. //                                        'text'=>'Назад',
  2925. //                                        'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => $p_group))
  2926. //                                    ),
  2927. //                                )
  2928. //                            );
  2929.                             $keyboard = [];
  2930. //                            if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('cash_pay_expense_transfer_cash_to_salary', $commandPermissions))){
  2931. //                                //Расход -> Превод Нал-ЗП
  2932. //                                $keyboard[] = [[
  2933. //                                    'text'=>'Перевод Нал-ЗП',
  2934. //                                    'callback_data'=> json_encode(array('action' => "salary", 'command' => "bpay", "group" => $p_group))
  2935. //                                ]];
  2936. //                            }
  2937. //                            if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('cash_pay_expense_transfer_cash_to_cash', $commandPermissions))){
  2938. //                                //Расход -> Превод Нал-Нал
  2939. //                                $keyboard[] = [[
  2940. //                                    'text'=>'Перевод Нал-Нал',
  2941. //                                    'callback_data'=> json_encode(array('action' => "transfer", 'command' => "bpay", "group" => $p_group))
  2942. //                                ]];
  2943. //                            }
  2944.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_expense_office'$commandPermissions))){
  2945.                                 //Расход -> Расходы по Объекту
  2946.                                 $keyboard[] = [[
  2947.                                     'text'=>'Расходы по Объекту',
  2948.                                     'callback_data'=> json_encode(array('action' => "other"'command' => "bpay""group" => $p_group))
  2949.                                 ]];
  2950.                             }
  2951. //                            $keyboard[] = [[
  2952. //                                'text'=>'Расходы на компанию',
  2953. //                                'callback_data'=> json_encode(array('action' => "company", 'command' => "bpay", "group" => $p_group))
  2954. //                            ]];
  2955.                             $keyboard[] = [[
  2956.                                 'text'=>'Назад',
  2957.                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  2958.                             ]];
  2959.                             $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2960.                             if($draftOld){
  2961.                                 $em->remove($draftOld);
  2962.                                 $em->flush();
  2963.                             }
  2964.                             $newDraft = new Draft();
  2965.                             $newDraft->setTypeof('expense');
  2966.                             $newDraft->setClient($clientObj);
  2967.                             $newDraft->setClientGroup($groupObj);
  2968.                             $newDraft->setFromGroup($groupObj);
  2969.                             $newDraft->setExpected('type_expense_b');
  2970.                             $em->persist($newDraft);
  2971.                             $em->flush();
  2972.                         } elseif($action == 'add_office' || $action == 'add_director'){
  2973.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2974.                             $officeObj false;
  2975.                             $directorObj false;
  2976.                             if($action == 'add_office'){
  2977.                                 if(isset($cq_data['id'])){
  2978.                                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  2979.                                         $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  2980.                                     }
  2981.                                 }
  2982.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2983.                                 if($draftOld){
  2984.                                     $em->remove($draftOld);
  2985.                                     $em->flush();
  2986.                                 }
  2987.                                 if($officeObj){
  2988.                                     $draftObj->setOffice($officeObj);
  2989.                                 }
  2990.                             } elseif($action == 'add_director'){
  2991.                                 if(isset($cq_data['id'])){
  2992.                                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  2993.                                         $directorObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  2994.                                     }
  2995.                                 }
  2996.                                 if($directorObj){
  2997.                                     $draftObj->setToGroup($directorObj);
  2998.                                 }
  2999.                             }
  3000.                             $selected '';
  3001.                             if($action == 'add_office' && $officeObj){
  3002.                                 $selected 'Выбрано «Объект ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() . '». ';
  3003.                             } elseif($action == 'add_director' && $directorObj){
  3004.                                 $name_director $directorObj->nameClient();
  3005.                                 $selected 'Выбрано «Руководитель' . ($name_director != '' && $name_director != null ' ' $name_director '') . '». ';
  3006.                             }
  3007.                             if($draftObj){
  3008.                                 $draftObj->setExpected('amount_b');
  3009.                                 $em->persist($draftObj);
  3010.                                 $em->flush();
  3011.                                 $this->addExpected(($is_group_chat === true && $groupObj $groupObj $clientObj), array("value" => "amount_b""group" => $p_group));
  3012.                                 $reply $selected 'Введите сумму';
  3013. //                                if($action == 'add_office'){
  3014. //                                    $keyboard = array(
  3015. //                                        array(
  3016. //                                            array(
  3017. //                                                'text'=>'Назад',
  3018. //                                                'callback_data'=> json_encode(array('action' => "other", 'command' => "bpay", "group" => $p_group))
  3019. //                                            ),
  3020. //                                        )
  3021. //                                    );
  3022. //                                } else {
  3023. //                                    $keyboard = array(
  3024. //                                        array(
  3025. //                                            array(
  3026. //                                                'text'=>'Назад',
  3027. //                                                'callback_data'=> json_encode(array('action' => "income_partner", 'command' => "bpay", "group" => $p_group))
  3028. //                                            ),
  3029. //                                        )
  3030. //                                    );
  3031. //                                }
  3032.                             } else {
  3033.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  3034.                             }
  3035.                         } elseif($action == 'salary'){
  3036.                             $clients_q $this->getDoctrine()
  3037.                                 ->getRepository(Client::class)
  3038.                                 ->createQueryBuilder('cl')
  3039.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  3040.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  3041.                                 ->where('cl.typeof != :typeof')
  3042.                                 ->andWhere('cl.is_active = 1')
  3043.                                 ->setParameter('typeof'"private")
  3044.                                 ->setParameter('typeof_group'"salary")
  3045.                             ;
  3046.                             if($groupObj){
  3047.                                 $clients_q->andWhere('cl.id != ' $groupObj->getId());
  3048.                             }
  3049.                             $clients $clients_q->getQuery()->getArrayResult();
  3050.                             if(count($clients) > 0){
  3051.                                 $buttons = array();
  3052.                                 foreach ($clients as $item_client){
  3053.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  3054.                                     $buttons[][] = array(
  3055.                                         'text' => $name_client,
  3056.                                         'callback_data'=> json_encode(array("action" => "add_client"'command' => "bpay"'id' => $item_client['id'], "group" => $p_group))
  3057.                                     );
  3058.                                 }
  3059.                                 $buttons[][] = array(
  3060.                                     'text'=>'Назад',
  3061.                                     'callback_data'=> json_encode(array('action' => "expense"'command' => "bpay""group" => $p_group))
  3062.                                 );
  3063.                                 $keyboard $buttons;
  3064.                                 $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3065.                                 if($draftObj){
  3066.                                     $draftObj->setNote('Перевод Нал-ЗП');
  3067.                                     $draftObj->setTypeTransaction('add_salary');
  3068.                                     $draftObj->setExpected('to_group_b');
  3069.                                     $em->persist($draftObj);
  3070.                                     $em->flush();
  3071.                                     $reply 'Выбрано «Перевод Нал-ЗП». ' 'Выберите группу, которой будет осуществлен перевод.';
  3072.                                 } else {
  3073.                                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  3074.                                     $keyboard = array();
  3075.                                 }
  3076.                             } else {
  3077.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  3078.                             }
  3079.                         } elseif($action == 'transfer'){
  3080.                             $clients_q $this->getDoctrine()
  3081.                                 ->getRepository(Client::class)
  3082.                                 ->createQueryBuilder('cl')
  3083.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  3084.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  3085.                                 ->where('cl.typeof != :typeof')
  3086.                                 ->andWhere('cl.is_active = 1')
  3087.                                 ->setParameter('typeof'"private")
  3088.                                 ->setParameter('typeof_group'"cash")
  3089.                             ;
  3090.                             if($groupObj){
  3091.                                 $clients_q->andWhere('cl.id != ' $groupObj->getId());
  3092.                             }
  3093.                             $clients $clients_q->getQuery()->getArrayResult();
  3094.                             if(count($clients) > 0){
  3095.                                 $buttons = array();
  3096.                                 foreach ($clients as $item_client){
  3097.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  3098.                                     $buttons[][] = array(
  3099.                                         'text' => $name_client,
  3100.                                         'callback_data'=> json_encode(array("action" => "add_director"'command' => "bpay"'id' => $item_client['id'], "group" => $p_group))
  3101.                                     );
  3102.                                 }
  3103.                                 $buttons[][] =  array(
  3104.                                     'text'=>'Назад',
  3105.                                     'callback_data'=> json_encode(array('action' => "expense"'command' => "bpay""group" => $p_group))
  3106.                                 );
  3107.                                 $keyboard $buttons;
  3108.                                 $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3109.                                 if($draftObj){
  3110.                                     $draftObj->setNote('Перевод Нал-Нал');
  3111.                                     $draftObj->setTypeTransaction('transfer');
  3112.                                     $draftObj->setExpected('to_group_b');
  3113.                                     $em->persist($draftObj);
  3114.                                     $em->flush();
  3115.                                     $reply 'Выбрано «Перевод Нал-Нал». ' 'Выберите группу для перевода';
  3116.                                 } else {
  3117.                                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  3118.                                     $keyboard = array();
  3119.                                 }
  3120.                             } else {
  3121.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  3122.                             }
  3123.                         } elseif($action == 'company'){
  3124.                             $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3125.                             if($draftOld){
  3126.                                 $em->remove($draftOld);
  3127.                                 $em->flush();
  3128.                             }
  3129.                             $newDraft = new Draft();
  3130.                             $newDraft->setTypeof('expense');
  3131.                             $newDraft->setClient($clientObj);
  3132.                             $newDraft->setClientGroup($groupObj);
  3133.                             $newDraft->setFromGroup($groupObj);
  3134.                             $newDraft->setExpected('amount_b');
  3135.                             $newDraft->setNote('Списание средств на компанию');
  3136.                             $newDraft->setTypeTransaction('expense_company');
  3137.                             $em->persist($newDraft);
  3138.                             $em->flush();
  3139.                             $this->addExpected(($is_group_chat === true && $groupObj $groupObj $clientObj), array("value" => "amount_b""group" => $p_group));
  3140.                             $reply 'Выбрано «Расходы на компанию». ' 'Введите сумму.';
  3141.                         } elseif($action == 'no_cheque' || $action == 'finish_pay'){
  3142.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3143.                             $draftObj->setExpected('finish_b');
  3144.                             $em->persist($draftObj);
  3145.                             $em->flush();
  3146.                             $this->resetExpected($curClient);
  3147. //                            $create_transaction = $this->createTransaction($token, $chat_id, $groupObj, $draftObj);
  3148. //                            if($create_transaction === true){
  3149. //                                $em->remove($draftObj);
  3150. //                                $em->flush();
  3151. //                            }
  3152.                             $create_transaction $this->sendMailNonCashCheque($token$chat_id$groupObj$draftObj);
  3153.                             if($create_transaction === true){
  3154.                                 $em->remove($draftObj);
  3155.                                 $em->flush();
  3156.                             }
  3157.                             $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Письмо с безналичным чеком успешно отправлено.';
  3158.                         }
  3159.                     } elseif($type_group_typeof == 'salary'){
  3160.                         if($action == 'income'){
  3161.                             $offices $this->getDoctrine()
  3162.                                 ->getRepository(Office::class)
  3163.                                 ->createQueryBuilder('o')
  3164.                                 ->select('o.id, o.name')
  3165.                                 ->where('o.is_active = 1')
  3166.                                 ->andWhere('o.deleted_at IS NULL')
  3167.                                 ->getQuery()
  3168.                                 ->getArrayResult();
  3169.                             if(count($offices) > 0){
  3170.                                 $reply 'Выбрано «Перевод в группу ЗП». ' 'Выберите объект, по которому осуществляется выплата зарплаты.';
  3171.                                 $buttons = array();
  3172.                                 foreach ($offices as $item_office){
  3173.                                     $buttons[][] = array(
  3174.                                         'text' => $item_office['name'],
  3175.                                         'callback_data'=> json_encode(array("action" => "add_office"'command' => "bpay"'id' => $item_office['id'], "group" => $p_group))
  3176.                                     );
  3177.                                 }
  3178.                                 $buttons[][] =  array(
  3179.                                     'text'=>'Назад',
  3180.                                     'callback_data'=> json_encode(array('action' => "delete"'command' => "bpay""group" => $p_group))
  3181.                                 );
  3182.                                 $keyboard $buttons;
  3183.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3184.                                 if($draftOld){
  3185.                                     $em->remove($draftOld);
  3186.                                     $em->flush();
  3187.                                 }
  3188.                                 $newDraft = new Draft();
  3189.                                 $newDraft->setTypeof('expense');
  3190.                                 $newDraft->setClient($clientObj);
  3191.                                 $newDraft->setClientGroup($groupObj);
  3192.                                 $newDraft->setToGroup($groupObj);
  3193.                                 $newDraft->setExpected('office_b');
  3194.                                 $newDraft->setNote('Перевод в группу ЗП');
  3195.                                 $newDraft->setTypeTransaction('add_salary');
  3196.                                 $em->persist($newDraft);
  3197.                                 $em->flush();
  3198.                             } else {
  3199.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
  3200.                             }
  3201.                         } elseif($action == 'income_cash'){
  3202.                             $offices $this->getDoctrine()
  3203.                                 ->getRepository(Office::class)
  3204.                                 ->createQueryBuilder('o')
  3205.                                 ->select('o.id, o.name, o.number')
  3206.                                 ->where('o.is_active = 1')
  3207.                                 ->andWhere('o.deleted_at IS NULL')
  3208.                                 ->getQuery()
  3209.                                 ->getArrayResult();
  3210.                             if(count($offices) > 0){
  3211.                                 $reply 'Выбрано «Перевод в группу Нал». ' 'Выберите объект, по которому осуществляется выплата зарплаты.';
  3212.                                 $buttons = array();
  3213.                                 foreach ($offices as $item_office){
  3214.                                     $buttons[][] = array(
  3215.                                         'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  3216.                                         'callback_data'=> json_encode(array("action" => "add_office"'command' => "bpay"'id' => $item_office['id'], "group" => $p_group))
  3217.                                     );
  3218.                                 }
  3219.                                 $buttons[][] =  array(
  3220.                                     'text'=>'Назад',
  3221.                                     'callback_data'=> json_encode(array('action' => "delete"'command' => "bpay""group" => $p_group))
  3222.                                 );
  3223.                                 $keyboard $buttons;
  3224.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3225.                                 if($draftOld){
  3226.                                     $em->remove($draftOld);
  3227.                                     $em->flush();
  3228.                                 }
  3229.                                 $newDraft = new Draft();
  3230. //                                $newDraft->setTypeof('expense');
  3231.                                 $newDraft->setTypeof('income');
  3232.                                 $newDraft->setClient($clientObj);
  3233.                                 $newDraft->setClientGroup($groupObj);
  3234.                                 $newDraft->setToGroup($groupObj);
  3235.                                 $newDraft->setExpected('office_b');
  3236.                                 $newDraft->setNote('Перевод в группу Нал');
  3237.                                 $newDraft->setTypeTransaction('add_salary_cash');
  3238.                                 $em->persist($newDraft);
  3239.                                 $em->flush();
  3240.                             } else {
  3241.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
  3242.                             }
  3243.                         } elseif($action == 'add_office'){
  3244.                             $clients_q $this->getDoctrine()
  3245.                                 ->getRepository(Client::class)
  3246.                                 ->createQueryBuilder('cl')
  3247.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  3248.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  3249.                                 ->where('cl.typeof != :typeof')
  3250.                                 ->andWhere('cl.is_active = 1')
  3251.                                 ->setParameter('typeof'"private")
  3252.                                 ->setParameter('typeof_group'"cash")
  3253.                             ;
  3254.                             $clients $clients_q->getQuery()->getArrayResult();
  3255.                             if(count($clients) > 0){
  3256.                                 $buttons = array();
  3257.                                 foreach ($clients as $item_client){
  3258.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  3259.                                     $buttons[][] = array(
  3260.                                         'text' => $name_client,
  3261.                                         'callback_data'=> json_encode(array("action" => "add_client"'command' => "bpay"'id' => $item_client['id'], "group" => $p_group))
  3262.                                     );
  3263.                                 }
  3264.                                 $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3265.                                 if($draftObj){
  3266.                                     $officeObj false;
  3267.                                     if(isset($cq_data['id'])){
  3268.                                         if($cq_data['id'] != '' && $cq_data['id'] != null){
  3269.                                             $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  3270.                                         }
  3271.                                     }
  3272.                                     if($officeObj){
  3273.                                         $draftObj->setOffice($officeObj);
  3274.                                     }
  3275.                                     $draftObj->setExpected('from_group_b');
  3276.                                     $em->persist($draftObj);
  3277.                                     $em->flush();
  3278.                                     if($draftObj->getTypeTransaction() != 'add_salary_cash'){
  3279.                                         $buttons[][] =  array(
  3280.                                             'text'=>'Назад',
  3281.                                             'callback_data'=> json_encode(array('action' => "income"'command' => "bpay""group" => $p_group))
  3282.                                         );
  3283.                                         $keyboard $buttons;
  3284.                                         $reply 'Выбрано «Объект' . ($officeObj ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() : '') . '». ' 'Выберите группу, c которой будут списаны средства.';
  3285.                                     } else {
  3286.                                         $buttons[][] =  array(
  3287.                                             'text'=>'Назад',
  3288.                                             'callback_data'=> json_encode(array('action' => "income_cash"'command' => "bpay""group" => $p_group))
  3289.                                         );
  3290.                                         $keyboard $buttons;
  3291.                                         $reply 'Выбрано «Объект' . ($officeObj ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() : '') . '». ' 'Выберите группу, в которую будут переведены средства.';
  3292.                                     }
  3293.                                 } else {
  3294.                                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  3295.                                     $keyboard = array();
  3296.                                 }
  3297.                             } else {
  3298.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  3299.                             }
  3300.                         } elseif($action == 'add_client'){
  3301.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3302.                             $to_client false;
  3303.                             if(isset($cq_data['id'])){
  3304.                                 if($cq_data['id'] != '' && $cq_data['id'] != null){
  3305.                                     $to_client $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  3306.                                 }
  3307.                             }
  3308.                             if($draftObj && $to_client){
  3309.                                 $groupObj false;
  3310.                                 if($p_group != '' && $p_group != null){
  3311.                                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  3312.                                 }
  3313.                                 $draftObj->setFromGroup($to_client);
  3314.                                 $draftObj->setExpected('amount_b');
  3315.                                 $em->persist($draftObj);
  3316.                                 $em->flush();
  3317.                                 $this->addExpected(($groupObj && $is_group_chat === true $groupObj $clientObj), array("value" => "amount_b""group" => $p_group));
  3318.                                 if($draftObj->getTypeTransaction() != 'add_salary_cash'){
  3319.                                     $reply 'Выбрано «Группа ' . ($to_client $to_client->nameClient() : '') . ' для списания средств». ' 'Введите сумму.';
  3320.                                 } else {
  3321.                                     $reply 'Выбрано «Группа ' . ($to_client $to_client->nameClient() : '') . ' для перевода средств». ' 'Введите сумму.';
  3322.                                 }
  3323.                             } else {
  3324.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  3325.                             }
  3326.                         } elseif($action == 'expense'){
  3327.                             $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3328.                             if($draftOld){
  3329.                                 $em->remove($draftOld);
  3330.                                 $em->flush();
  3331.                             }
  3332.                             $newDraft = new Draft();
  3333.                             $newDraft->setTypeof('expense');
  3334.                             $newDraft->setClient($clientObj);
  3335.                             $newDraft->setClientGroup($groupObj);
  3336.                             $newDraft->setToGroup($groupObj);
  3337.                             //$newDraft->setFromGroup($groupObj);
  3338.                             $newDraft->setExpected('add_office_expense_b');
  3339.                             $newDraft->setNote('Начисление зарплаты');
  3340.                             $newDraft->setTypeTransaction('payment_salary');
  3341.                             $em->persist($newDraft);
  3342.                             $em->flush();
  3343.                             $offices $this->getDoctrine()
  3344.                                 ->getRepository(Office::class)
  3345.                                 ->createQueryBuilder('o')
  3346.                                 ->select('o.id, o.name, o.number')
  3347.                                 ->where('o.is_active = 1')
  3348.                                 ->andWhere('o.deleted_at IS NULL')
  3349.                                 ->getQuery()
  3350.                                 ->getArrayResult();
  3351.                             if(count($offices) > 0){
  3352.                                 $reply 'Выбрано «Начисление зарплаты». ' 'Выберите объект, по которому осуществляется начисление зарплаты.';
  3353.                                 $keyboard = array();
  3354.                                 $buttons = array();
  3355.                                 foreach ($offices as $item_office){
  3356.                                     $buttons[][] = array(
  3357.                                         'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  3358.                                         'callback_data'=> json_encode(array("action" => "add_office_exp"'command' => "bpay"'id' => $item_office['id'], "group" => $p_group))
  3359.                                     );
  3360.                                 }
  3361.                                 $buttons[][] =  array(
  3362.                                     'text'=>'Назад',
  3363.                                     'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3364.                                 );
  3365.                                 $keyboard $buttons;
  3366.                             } else {
  3367.                                 $reply 'Нет объектов для начисление зарплаты по ним.';
  3368.                             }
  3369.                             /*
  3370.                             $groupObj = false;
  3371.                             if($p_group != '' && $p_group != null){
  3372.                                 $groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  3373.                             }
  3374.                             $this->addExpected(($groupObj && $is_group_chat === true ? $groupObj : $clientObj), array("value" => "amount", "group" => $p_group));
  3375.                             $reply = 'Выбрано «Начисление зарплаты». ' . 'Введите сумму';
  3376.                             */
  3377.                         } elseif($action == 'expense_salary') {
  3378.                             //операция начисление оклада
  3379.                             $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
  3380.                             if(count($salarySchedule) > 0){
  3381.                                 $max_ss $this->getParameter('app.max.salary_schedule');
  3382.                                 if(count($salarySchedule) < $max_ss){
  3383.                                     $reply 'Выбрано «Начисление оклада». Можете отредактировать условия начисления оклада по нужным числам месяца, добавить новое или удалить лишнее';
  3384.                                     $keyboard = array(
  3385.                                         array(
  3386.                                             array(
  3387.                                                 'text'=>'Редактировать условие начисления',
  3388.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_date"'command' => "bpay""group" => $p_group))
  3389.                                             )
  3390.                                         ),
  3391.                                         array(
  3392.                                             array(
  3393.                                                 'text'=>'Новое условие начисления',
  3394.                                                 'callback_data'=> json_encode(array('action' => "new_ss_date"'command' => "bpay""group" => $p_group))
  3395.                                             )
  3396.                                         ),
  3397.                                         array(
  3398.                                             array(
  3399.                                                 'text'=>'Удалить условие начисления',
  3400.                                                 'callback_data'=> json_encode(array('action' => "rem_ss_date"'command' => "bpay""group" => $p_group))
  3401.                                             )
  3402.                                         ),
  3403.                                         array(
  3404.                                             array(
  3405.                                                 'text'=>'Назад',
  3406.                                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3407.                                             )
  3408.                                         )
  3409.                                     );
  3410.                                 } else {
  3411.                                     $reply 'Выбрано «Начисление оклада». Можете отредактировать условия начисления оклада по нужным числам месяца или удалить лишнее';
  3412.                                     $keyboard = array(
  3413.                                         array(
  3414.                                             array(
  3415.                                                 'text'=>'Редактировать условие начисления',
  3416.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_date"'command' => "bpay""group" => $p_group))
  3417.                                             )
  3418.                                         ),
  3419.                                         array(
  3420.                                             array(
  3421.                                                 'text'=>'Удалить условие начисления',
  3422.                                                 'callback_data'=> json_encode(array('action' => "rem_ss_date"'command' => "bpay""group" => $p_group))
  3423.                                             )
  3424.                                         ),
  3425.                                         array(
  3426.                                             array(
  3427.                                                 'text'=>'Назад',
  3428.                                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3429.                                             )
  3430.                                         )
  3431.                                     );
  3432.                                 }
  3433.                             } else {
  3434.                                 $reply 'Выбрано «Начисление оклада». Для начисления оклада по нужным числам месяца необходимо добавить условие начисления';
  3435.                                 $keyboard = array(array(
  3436.                                     array(
  3437.                                         'text'=>'Новое условие начисления',
  3438.                                         'callback_data'=> json_encode(array('action' => "new_ss_date"'command' => "bpay""group" => $p_group))
  3439.                                     )
  3440.                                 ),
  3441.                                     array(
  3442.                                         array(
  3443.                                             'text'=>'Назад',
  3444.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3445.                                         )
  3446.                                     )
  3447.                                 );
  3448.                             }
  3449.                         } elseif($action == 'new_ss_date') {
  3450.                             //новое условие начисления оклада
  3451.                             $reply 'Введите число дня месяца, в который будет осуществляться начисления оклада';
  3452.                             $keyboard = array(
  3453.                                 array(
  3454.                                     array(
  3455.                                         'text'=>'Назад',
  3456.                                         'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "bpay""group" => $p_group))
  3457.                                     )
  3458.                                 )
  3459.                             );
  3460.                             $groupObj false;
  3461.                             if($p_group != '' && $p_group != null){
  3462.                                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  3463.                             }
  3464.                             $this->addExpected(($groupObj && $is_group_chat === true $groupObj $clientObj), array("value" => "new_date""group" => $p_group));
  3465.                         } elseif($action == 'edit_ss_date') {
  3466.                             //изменить условие начисления оклада
  3467.                             $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
  3468.                             if(count($salarySchedule) > 0){
  3469.                                 $reply 'Выберите из списка условие для начисления оклада, которое хотите отредактировать';
  3470.                                 $buttons = array();
  3471.                                 foreach ($salarySchedule as $item_ss){
  3472.                                     $buttons[][] = array(
  3473.                                         'text' => $item_ss['day'] . ' числа каждого месяца по ' $item_ss['amount'] . ' руб',
  3474.                                         'callback_data'=> json_encode(array("action" => "edit_ss"'command' => "bpay"'ss_id' => $item_ss['id'], "group" => $p_group))
  3475.                                     );
  3476.                                 }
  3477.                                 $buttons[][] =  array(
  3478.                                     'text'=>'Назад',
  3479.                                     'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "bpay""group" => $p_group))
  3480.                                 );
  3481.                                 $keyboard $buttons;
  3482.                             } else {
  3483.                                 $reply 'Условий для начисления оклада не найдено, можете создать новое';
  3484.                                 $keyboard = array(array(
  3485.                                     array(
  3486.                                         'text'=>'Новое условие начисления',
  3487.                                         'callback_data'=> json_encode(array('action' => "new_ss_date"'command' => "bpay""group" => $p_group))
  3488.                                     )
  3489.                                 ),
  3490.                                     array(
  3491.                                         array(
  3492.                                             'text'=>'Назад',
  3493.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3494.                                         )
  3495.                                     )
  3496.                                 );
  3497.                             }
  3498.                         } elseif($action == 'rem_ss_date') {
  3499.                             //удалить условие начисления оклада
  3500.                             $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
  3501.                             if(count($salarySchedule) > 0){
  3502.                                 $reply 'Выберите из списка условие для начисления оклада, которое хотите удалить';
  3503.                                 $buttons = array();
  3504.                                 foreach ($salarySchedule as $item_ss){
  3505.                                     $buttons[][] = array(
  3506.                                         'text' => $item_ss['day'] . ' числа каждого месяца по ' $item_ss['amount'] . ' руб',
  3507.                                         'callback_data'=> json_encode(array("action" => "rem_ss"'command' => "bpay"'ss_id' => $item_ss['id'], "group" => $p_group))
  3508.                                     );
  3509.                                 }
  3510.                                 $buttons[][] =  array(
  3511.                                     'text'=>'Назад',
  3512.                                     'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "bpay""group" => $p_group))
  3513.                                 );
  3514.                                 $keyboard $buttons;
  3515.                             } else {
  3516.                                 $reply 'Условий для начисления оклада не найдено, можете создать новое';
  3517.                                 $keyboard = array(array(
  3518.                                     array(
  3519.                                         'text'=>'Новое условие начисления',
  3520.                                         'callback_data'=> json_encode(array('action' => "new_ss_date"'command' => "bpay""group" => $p_group))
  3521.                                     )
  3522.                                 ),
  3523.                                     array(
  3524.                                         array(
  3525.                                             'text'=>'Назад',
  3526.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3527.                                         )
  3528.                                     )
  3529.                                 );
  3530.                             }
  3531.                         } elseif($action == 'edit_ss'){
  3532.                             //изменить условие начисления оклада
  3533.                             $id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
  3534.                             $isExistSs false;
  3535.                             if($id != '' && $id != null){
  3536.                                 $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
  3537.                                 if($salarySchedule){
  3538.                                     $isExistSs true;
  3539.                                     $reply 'Выбрано для редактирования условие для начисления «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() .  ' руб». Выберите, что нужно отредактировать';
  3540.                                     $keyboard = array(
  3541.                                         array(
  3542.                                             array(
  3543.                                                 'text'=>'Число месяца',
  3544.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_d"'command' => "bpay"'ss_id' => $salarySchedule->getId(), "group" => $p_group))
  3545.                                             ),
  3546.                                             array(
  3547.                                                 'text'=>'Сумму начисления',
  3548.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_a"'command' => "bpay"'ss_id' => $salarySchedule->getId(), "group" => $p_group))
  3549.                                             )
  3550.                                         ),
  3551.                                         array(
  3552.                                             array(
  3553.                                                 'text'=>'Назад',
  3554.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_date"'command' => "bpay""group" => $p_group))
  3555.                                             )
  3556.                                         )
  3557.                                     );
  3558.                                 }
  3559.                             }
  3560.                             if(!$isExistSs){
  3561.                                 $reply 'Не удалось найти условий для начисления оклада';
  3562.                                 $keyboard = array(
  3563.                                     array(
  3564.                                         array(
  3565.                                             'text'=>'В основное меню',
  3566.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3567.                                         )
  3568.                                     )
  3569.                                 );
  3570.                             }
  3571.                         } elseif($action == 'edit_ss_d' || $action == 'edit_ss_a') {
  3572.                             //изменить условие начисления оклада
  3573.                             $id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
  3574.                             $isExistSs false;
  3575.                             if($id != '' && $id != null){
  3576.                                 $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
  3577.                                 if($salarySchedule){
  3578.                                     $isExistSs true;
  3579.                                     if($action == 'edit_ss_d'){
  3580.                                         $reply 'Введите новое число дня месяца для условия начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() .  ' руб»';
  3581.                                         $this->addExpected(($is_group_chat === true && $groupObj $groupObj $clientObj), array("value" => "edit_ss_d""ss_id" => $salarySchedule->getId(), "group" => $p_group));
  3582.                                     } else {
  3583.                                         $reply 'Введите новую сумму для условия начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() .  ' руб»';
  3584.                                         $this->addExpected(($is_group_chat === true && $groupObj $groupObj $clientObj), array("value" => "edit_ss_a""ss_id" => $salarySchedule->getId(), "group" => $p_group));
  3585.                                     }
  3586.                                 }
  3587.                             }
  3588.                             if(!$isExistSs){
  3589.                                 $reply 'Не удалось найти условий для начисления оклада';
  3590.                                 $keyboard = array(
  3591.                                     array(
  3592.                                         array(
  3593.                                             'text'=>'В основное меню',
  3594.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3595.                                         )
  3596.                                     )
  3597.                                 );
  3598.                             }
  3599.                         } elseif($action == 'rem_ss'){
  3600.                             //удалить условие начисления оклада
  3601.                             $id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
  3602.                             $isExistSs false;
  3603.                             if($id != '' && $id != null){
  3604.                                 $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
  3605.                                 if($salarySchedule){
  3606.                                     $isExistSs true;
  3607.                                     $reply 'Условие для начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() .  ' руб» успешно удалено';
  3608.                                     $em->remove($salarySchedule);
  3609.                                     $em->flush();
  3610.                                     $keyboard = array(
  3611.                                         array(
  3612.                                             array(
  3613.                                                 'text'=>'Назад',
  3614.                                                 'callback_data'=> json_encode(array('action' => "rem_ss_date"'command' => "bpay""group" => $p_group))
  3615.                                             )
  3616.                                         ),
  3617.                                         array(
  3618.                                             array(
  3619.                                                 'text'=>'В основное меню',
  3620.                                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3621.                                             )
  3622.                                         )
  3623.                                     );
  3624.                                 }
  3625.                             }
  3626.                             if(!$isExistSs){
  3627.                                 $reply 'Не удалось найти условий для начисления оклада';
  3628.                                 $keyboard = array(
  3629.                                     array(
  3630.                                         array(
  3631.                                             'text'=>'В основное меню',
  3632.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3633.                                         )
  3634.                                     )
  3635.                                 );
  3636.                             }
  3637.                         } elseif($action == 'add_office_exp'){
  3638.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3639.                             if($draftObj){
  3640.                                 $officeObj false;
  3641.                                 if(isset($cq_data['id'])){
  3642.                                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  3643.                                         $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  3644.                                     }
  3645.                                 }
  3646.                                 if($officeObj){
  3647.                                     $draftObj->setOffice($officeObj);
  3648.                                 }
  3649.                                 $draftObj->setExpected('amount_b');
  3650.                                 $em->persist($draftObj);
  3651.                                 $em->flush();
  3652.                                 $reply 'Выбрано «Объект' . ($officeObj ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() : '') . ' для начисления зарплаты». ' 'Введите сумму.';
  3653.                                 $groupObj false;
  3654.                                 if($p_group != '' && $p_group != null){
  3655.                                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  3656.                                 }
  3657.                                 $this->addExpected(($groupObj && $is_group_chat === true $groupObj $clientObj), array("value" => "amount_b""group" => $p_group));
  3658.                             } else {
  3659.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  3660.                                 $keyboard = array();
  3661.                             }
  3662.                         }
  3663.                     }
  3664.                 } else {
  3665.                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить добавление финансовой операции, у данной группы не выбран тип группы. Пожалуйста укажите тип группы данной группе и начните добавление операции занова.';
  3666.                 }
  3667.             } else {
  3668.                 $reply 'Финансовые операции начинаются из группы, пожалуйста отправьте команду для начала операции в нужной группе.';
  3669.             }
  3670.         } elseif($expected != '' && $expected != null){
  3671.             $curClientObj false;
  3672.             if($is_group_chat === true){
  3673.                 $curClientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  3674.             }
  3675.             if($curClient && (($text != '' && $text != null) || ($file_id != '' && $file_id != null))){
  3676.                 $groupObj false;
  3677.                 if($group_id != null && $group_id != ''){
  3678.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  3679.                 } elseif($p_group != null && $p_group != '') {
  3680.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  3681.                 }
  3682.                 if($groupObj && $curClient){
  3683.                     $name_group $groupObj->nameClient();
  3684.                     $type_group_typeof null;
  3685.                     if($groupObj->getTypeGroup()){
  3686.                         $type_group_typeof $groupObj->getTypeGroup()->getTypeof();
  3687.                     }
  3688.                     if($is_group_chat === true && $groupObj){
  3689.                         $chat_id $groupObj->getChatId();
  3690.                     }
  3691.                     $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => ($curClientObj $curClientObj->getId() : $curClient->getId()), 'client_group' => $groupObj));
  3692.                     if($draftObj){
  3693.                         if($expected == 'amount_b'){
  3694.                             $amount = (float) $text;
  3695.                             if($amount || $draftObj->getTypeTransaction() == 'payment_salary'){
  3696.                                 $draftObj->setAmount($amount 100);
  3697.                                 $draftObj->setExpected('comment_b');
  3698.                                 $em->persist($draftObj);
  3699.                                 $em->flush();
  3700.                                 $this->addExpected($curClient, array("value" => "comment_b""group" => $p_group));
  3701.                                 $sum str_replace(',00'''number_format(($draftObj->getAmount() / 100), 2','' '));
  3702.                                 $reply 'Введено «Сумма ' $sum '». ' 'Введите комментарий';
  3703.                             } else {
  3704.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Неправильно указана сумма, укажите сумму числом.';
  3705.                             }
  3706.                         } elseif($expected == 'comment_b') {
  3707.                             if($draftObj->getTypeTransaction() == 'expense_office'){
  3708.                                 $draftObj->setComment(trim($text));
  3709.                                 $draftObj->setExpected('file_cheque_b');
  3710.                                 $em->persist($draftObj);
  3711.                                 $em->flush();
  3712.                                 $this->addExpected($curClient, array("value" => "file_cheque_b""group" => $p_group));
  3713.                                 $keyboard = [
  3714. //                                    [
  3715. //                                        [
  3716. //                                            'text'=>'Без чека',
  3717. //                                            'callback_data'=> json_encode(array('action' => "no_cheque", 'command' => "bpay", "group" => $p_group))
  3718. //                                        ]
  3719. //                                    ]
  3720.                                 ];
  3721.                                 $reply 'Сделайте или прикрепите фото чека';
  3722.                             } else {
  3723.                                 $draftObj->setComment(trim($text));
  3724.                                 $draftObj->setExpected('finish_b');
  3725.                                 $em->persist($draftObj);
  3726.                                 $em->flush();
  3727.                                 $this->resetExpected($curClient);
  3728. //                                $create_transaction = $this->createTransaction($token, $chat_id, $groupObj, $draftObj);
  3729. //                                if($create_transaction === true){
  3730. //                                    $em->remove($draftObj);
  3731. //                                    $em->flush();
  3732. //                                }
  3733.                                 $create_transaction $this->sendMailNonCashCheque($token$chat_id$groupObj$draftObj);
  3734.                                 if($create_transaction === true){
  3735.                                     $em->remove($draftObj);
  3736.                                     $em->flush();
  3737.                                 }
  3738.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Письмо с безналичным чеком успешно отправлено.';
  3739.                             }
  3740.                         } elseif($expected == 'file_cheque_b') {
  3741.                             $file null;
  3742.                             if($file_id != '' && $file_id != null){
  3743.                                 $file $this->uploadFileBot($token$file_id);
  3744.                             }
  3745.                             if($file != null){
  3746.                                 $draftObj->setFile(($draftObj->getFile() != null && $draftObj->getFile() != '' $draftObj->getFile() . ';' $file $file));
  3747.                                 $em->persist($draftObj);
  3748.                                 $em->flush();
  3749.                                 $reply 'Фото чека успешно прикреплено. Чтобы добавить ещё фото чека, сделайте или прикрепите фото чека.';
  3750.                             } else {
  3751.                                 $reply 'Фото чека не удалось прикрепить. Чтобы добавить фото чека снова, сделайте или прикрепите фото чека.';
  3752.                             }
  3753.                             $editMessageId $draftObj->getLastMessageId();
  3754.                             $this->addExpected($curClient, array("value" => "file_cheque_b""group" => $p_group));
  3755.                             $keyboard = [
  3756.                                 [
  3757.                                     [
  3758.                                         'text'=> 'Завершить операцию',
  3759.                                         'callback_data'=> json_encode(array('action' => "finish_pay"'command' => "bpay""group" => $p_group))
  3760.                                     ]
  3761.                                 ]
  3762.                             ];
  3763.                             /*
  3764.                             //окончание финансовой операции
  3765.                             $draftObj->setExpected('finish_b');
  3766.                             $em->persist($draftObj);
  3767.                             $em->flush();
  3768.                             $this->resetExpected($curClient);
  3769.                             $create_transaction = $this->createTransaction($token, $chat_id, $groupObj, $draftObj);
  3770.                             if($create_transaction === true){
  3771.                                 $em->remove($draftObj);
  3772.                                 $em->flush();
  3773.                             }
  3774.                             $reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Транзакция успешно добавлена.';
  3775.                             */
  3776.                         }
  3777.                     } elseif($expected == 'new_date_b'){
  3778.                         if(is_numeric(trim($text)) && trim($text) <= 31){
  3779.                             $reply 'Введите сумму начисления оклада';
  3780.                             $newSalarySchedule = new SalarySchedule();
  3781.                             $newSalarySchedule->setClient(($groupObj && $is_group_chat === true $groupObj $curClient))
  3782.                                 ->setDay(trim($text))
  3783.                                 ->setIsEdit(true)
  3784.                             ;
  3785.                             $em->persist($newSalarySchedule);
  3786.                             $em->flush();
  3787.                             $groupObj false;
  3788.                             if($p_group != '' && $p_group != null){
  3789.                                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  3790.                             }
  3791.                             $this->addExpected(($groupObj && $is_group_chat === true $groupObj $curClient), array("value" => "new_amount_b""group" => $p_group));
  3792.                         } else {
  3793.                             if(is_numeric(trim($text)) && trim($text) > 31){
  3794.                                 $reply 'День месяца не должен быть больше 31';
  3795.                             } else {
  3796.                                 $reply 'Введите день числом, в который будет осуществляться начисления оклада';
  3797.                             }
  3798.                             $keyboard = array(
  3799.                                 array(
  3800.                                     array(
  3801.                                         'text'=>'Назад',
  3802.                                         'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "bpay""group" => $p_group))
  3803.                                     )
  3804.                                 )
  3805.                             );
  3806.                         }
  3807.                     } elseif($expected == 'new_amount_b'){
  3808.                         $amount = (float) $text;
  3809.                         $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(array('client' => ($groupObj && $is_group_chat === true $groupObj $curClient), 'is_edit' => true));
  3810.                         if($amount && $salarySchedule){
  3811.                             $salarySchedule->setAmount($amount)
  3812.                                 ->setIsEdit(false);
  3813.                             $em->persist($salarySchedule);
  3814.                             $em->flush();
  3815.                             $this->resetExpected(($groupObj && $is_group_chat === true $groupObj $curClient));
  3816.                             $reply 'Условие начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() . ' руб» успешно добавлено';
  3817.                         } else {
  3818.                             $reply 'Не удалось добавить информацию для начисления оклада, попробуйте повторить операцию снова';
  3819.                         }
  3820.                     } elseif($expected == 'edit_ss_d_b' || $expected == 'edit_ss_a_b') {
  3821.                         if(is_numeric($text)){
  3822.                             $isExistSs false;
  3823.                             if($ss_id != null && $ss_id != ''){
  3824.                                 $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(array('id' => $ss_id));
  3825.                                 if($salarySchedule){
  3826.                                     $isExistSs true;
  3827.                                     if($expected == 'edit_ss_d_b'){
  3828.                                         $salarySchedule->setDay($text);
  3829.                                     } else {
  3830.                                         $salarySchedule->setAmount($text);
  3831.                                     }
  3832.                                     $em->persist($salarySchedule);
  3833.                                     $em->flush();
  3834.                                     $reply 'Условие начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() . ' руб» успешно отредактировано';
  3835.                                     $keyboard = array(
  3836.                                         array(
  3837.                                             array(
  3838.                                                 'text'=>'Назад',
  3839.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_date"'command' => "bpay""group" => $p_group))
  3840.                                             )
  3841.                                         ),
  3842.                                         array(
  3843.                                             array(
  3844.                                                 'text'=>'В основное меню',
  3845.                                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3846.                                             )
  3847.                                         )
  3848.                                     );
  3849.                                     $this->resetExpected($curClient);
  3850.                                 }
  3851.                             }
  3852.                             if(!$isExistSs){
  3853.                                 $reply 'Не удалось отредактировать условий для начисления оклада';
  3854.                                 $keyboard = array(
  3855.                                     array(
  3856.                                         array(
  3857.                                             'text'=>'В основное меню',
  3858.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3859.                                         )
  3860.                                     )
  3861.                                 );
  3862.                             }
  3863.                         } else {
  3864.                             $reply 'Данные для ввода должны быть числом. Повторите ввод';
  3865.                         }
  3866.                     } else {
  3867.                         $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  3868.                     }
  3869.                 }
  3870.             }
  3871.         } else {
  3872.             $groupObj false;
  3873.             if($group_id != '' && $group_id != null){
  3874.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  3875.             } elseif($p_group != '' && $p_group != null){
  3876.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  3877.             }
  3878.             if($groupObj){
  3879.                 if($is_group_chat === true && $groupObj){
  3880.                     $chat_id $groupObj->getChatId();
  3881.                 }
  3882.                 $name_group '';
  3883.                 $type_group_typeof null;
  3884.                 if($groupObj->getTypeGroup()){
  3885.                     $type_group_typeof $groupObj->getTypeGroup()->getTypeof();
  3886.                     $name_group $groupObj->nameClient();
  3887.                 }
  3888.                 if($type_group_typeof != null && $type_group_typeof != ''){
  3889.                     if($type_group_typeof == 'cash'){
  3890.                         $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Выберите финансовую операцию.';
  3891.                         $keyboard = array(
  3892. //                            array(
  3893. //                                array(
  3894. //                                    'text'=>'Приход',
  3895. //                                    'callback_data'=> json_encode(array('action' => "income", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
  3896. //                                )
  3897. //                            ),
  3898.                             array(
  3899.                                 array(
  3900.                                     'text'=>'Расход',
  3901.                                     'callback_data'=> json_encode(array('action' => "expense"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  3902.                                 ),
  3903.                             ),
  3904.                             array(
  3905.                                 array(
  3906.                                     'text'=>'Назад',
  3907.                                     'callback_data'=> json_encode(array('action' => "delete"'command' => "bpay"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  3908.                                 )
  3909.                             )
  3910.                         );
  3911.                     } elseif($type_group_typeof == 'salary') {
  3912.                         $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  3913.                         $commandPermissions $this->curCommandPermissions($clientObj'bpay');
  3914.                         $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Выберите финансовую операцию.';
  3915. //                        $keyboard = array(
  3916. //                            array(
  3917. //                                array(
  3918. //                                    'text'=>'Перевод в группу ЗП',
  3919. //                                    'callback_data'=> json_encode(array('action' => "income", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
  3920. //                                )
  3921. //                            ),
  3922. //                            array(
  3923. //                                array(
  3924. //                                    'text'=>'Перевод в группу Нал',
  3925. //                                    'callback_data'=> json_encode(array('action' => "income_cash", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
  3926. //                                )
  3927. //                            ),
  3928. //                            array(
  3929. //                                array(
  3930. //                                    'text'=>'Начисление зарплаты',
  3931. //                                    'callback_data'=> json_encode(array('action' => "expense", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
  3932. //                                ),
  3933. //                            ),
  3934. //                            array(
  3935. //                                array(
  3936. //                                    'text'=>'Начисление оклада',
  3937. //                                    'callback_data'=> json_encode(array('action' => "expense_salary", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
  3938. //                                ),
  3939. //                            ),
  3940. //                            array(
  3941. //                                array(
  3942. //                                    'text'=>'Назад',
  3943. //                                    'callback_data'=> json_encode(array('action' => "delete", 'command' => "bpay", 'mes_id' => $message_id, "group" => ($groupObj ? $groupObj->getId() : null)))
  3944. //                                )
  3945. //                            )
  3946. //                        );
  3947.                         $keyboard = [];
  3948.                         if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('salary_pay_transfer_to_salary'$commandPermissions))){
  3949.                             //Перевод в группу ЗП
  3950.                             $keyboard[] = [[
  3951.                                 'text'=>'Перевод в группу ЗП',
  3952.                                 'callback_data'=> json_encode(array('action' => "income"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  3953.                             ]];
  3954.                         }
  3955.                         if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('salary_pay_transfer_to_cash'$commandPermissions))){
  3956.                             //Перевод в группу Нал
  3957.                             $keyboard[] = [[
  3958.                                 'text'=>'Перевод в группу Нал',
  3959.                                 'callback_data'=> json_encode(array('action' => "income_cash"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  3960.                             ]];
  3961.                         }
  3962.                         if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('salary_pay_accrual_salary'$commandPermissions))){
  3963.                             //Начисление зарплаты
  3964.                             $keyboard[] = [[
  3965.                                 'text'=>'Начисление зарплаты',
  3966.                                 'callback_data'=> json_encode(array('action' => "expense"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  3967.                             ]];
  3968.                         }
  3969.                         if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('salary_pay_accrual_payday'$commandPermissions))){
  3970.                             //Начисление оклада
  3971.                             $keyboard[] = [[
  3972.                                 'text'=>'Начисление оклада',
  3973.                                 'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  3974.                             ]];
  3975.                         }
  3976.                         $keyboard[] = [[
  3977.                             'text'=>'Назад',
  3978.                             'callback_data'=> json_encode(array('action' => "delete"'command' => "bpay"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  3979.                         ]];
  3980.                     }
  3981.                 } else {
  3982.                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить действие, у данной группы не выбран тип группы. Пожалуйста укажите тип группы и начните данную команду заново.';
  3983.                 }
  3984.             } else {
  3985.                 $reply 'Финансовые операции начинаются из группы, пожалуйста отправьте команду для начала операции в нужной группе.';
  3986.             }
  3987.         }
  3988.         if(!isset($reply) || $reply == '' || $reply == null){
  3989.             $reply 'Что то пошло не так, начните выполнение операции заново';
  3990.         }
  3991.         $sendMessage false;
  3992.         if(count($keyboard) > 0){
  3993.             $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  3994.             if($editMessageId != null){
  3995.                 //редактировать уже существующее сообщение
  3996.                 $sendMessage ProjectUtilsController::requestToBot($token'editMessageText', ['chat_id' => $chat_id'message_id' => $editMessageId'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  3997.             } else {
  3998.                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  3999.             }
  4000.             $resp json_decode($sendMessagetrue);
  4001.             if(isset($resp['result']['message_id']) && $groupObj){
  4002.                 file_put_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt'$resp['result']['message_id']);
  4003.             }
  4004. //            if($draftObj && $file_id != null && $file_id != '' && isset($resp['result']['message_id'])){
  4005. //                $draftObj->setLastMessageId($resp['result']['message_id']);
  4006. //                $em->persist($draftObj);
  4007. //                $em->flush();
  4008. //            }
  4009.         } else {
  4010.             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  4011.         }
  4012.         if($is_group_chat === true){
  4013.             $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
  4014.             $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'bpay'));
  4015.             $this->addLogMessageBot($bot$command$sendMessage);
  4016.             if($create_transaction === true){
  4017.                 $this->deleteLogMessage($bot$chat_id$command->getId());
  4018.             }
  4019.         }
  4020.     }
  4021.     private function sendMailNonCashCheque($token$chat_id$group$draft){
  4022.         $basePath $this->getParameter('kernel.project_dir');
  4023.         $fileDir '/public/images/';
  4024.         $is_group_chat $this->getParameter('app.chat.is_group');
  4025.         $resp false;
  4026.         $em $this->getDoctrine()->getManager();
  4027.         $isSendMail false;
  4028.         $typeMail 'newTransaction';
  4029.         if($token != '' && $token != null && $chat_id != '' && $chat_id != null && $group && $draft){
  4030.             if($draft->getExpected() == 'finish_b'){
  4031.                 $amount $draft->getAmount();
  4032.                 if($draft->getTypeof() == 'expense'){
  4033.                     $amount '-' $draft->getAmount();
  4034.                 }
  4035.                 $is_income false;
  4036.                 //если приход по Объекту, или начисление ЗП
  4037.                 if(!$draft->getFromGroup() && $draft->getToGroup()){
  4038.                     $is_income true;
  4039.                 }
  4040.                 $office_name '';
  4041.                 $office_number '';
  4042.                 if($draft->getOffice()){
  4043.                     $office_name $draft->getOffice()->getName();
  4044.                     $office_number $draft->getOffice()->getNumber();
  4045.                 }
  4046.                 $from_chat_id null;
  4047.                 $from_name '';
  4048.                 $type_group_from null;
  4049.                 if($draft->getFromGroup()){
  4050.                     $from_chat_id $draft->getFromGroup()->getChatId();
  4051.                     $from_name $draft->getFromGroup()->nameClient();
  4052.                     $type_group_from = ($draft->getFromGroup()->getTypeGroup() != null $draft->getFromGroup()->getTypeGroup()->getTypeof() : null);
  4053.                 }
  4054.                 $to_chat_id null;
  4055.                 $to_name '';
  4056.                 $type_group_to null;
  4057.                 if($draft->getToGroup()){
  4058.                     $to_chat_id $draft->getToGroup()->getChatId();
  4059.                     $to_name $draft->getToGroup()->nameClient();
  4060.                     $type_group_to = ($draft->getToGroup()->getTypeGroup() != null $draft->getToGroup()->getTypeGroup()->getTypeof() : null);
  4061.                 }
  4062.                 //если приход по Объекту, или начисление ЗП
  4063.                 if($is_income === true && $draft->getToGroup()){
  4064.                     $from_chat_id $draft->getToGroup()->getChatId();
  4065.                     $from_name $draft->getToGroup()->nameClient();
  4066.                 }
  4067.                 $m_source '';
  4068.                 $m_type '';
  4069.                 if($draft->getTypeTransaction() == 'expense_office' || ($draft->getTypeTransaction() == 'income' && $draft->getTypeof() == 'income') || ($draft->getTypeTransaction() == 'add_salary' && $draft->getTypeof() == 'expense')){
  4070.                     $isSendMail true;
  4071.                     $m_source = ($draft->getFromGroup() != null $draft->getFromGroup()->getFirstName() : '');
  4072.                     if($draft->getTypeTransaction() == 'expense_office'){
  4073.                         // +300 (Нал бот, 444. Бургерная, тестовый коммент)
  4074.                         $cm $amount " (" $from_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ", " $draft->getComment() . ")";
  4075.                         if($draft->getFile() != '' && $draft->getFile() != null){
  4076.                             $typeMail 'newTransactionIncomeCashСheque';
  4077.                             $m_type 'расход Чек';
  4078.                         } else {
  4079.                             $typeMail 'newTransactionIncomeCashNoСheque';
  4080.                             $m_type 'расход Нал';
  4081.                         }
  4082.                     } elseif($draft->getTypeTransaction() == 'income' && $draft->getTypeof() == 'income'){
  4083.                         // +555 (Нал Бот, 24195. Пробник, тест коммент)
  4084.                         $cm $amount " (" $from_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ", " $draft->getComment() . ")";
  4085.                         //$m_source = ($draft->getFromGroup() != null ? $draft->getFromGroup()->getFirstName() : '');
  4086.                         $m_source = ($draft->getToGroup() != null $draft->getToGroup()->getFirstName() : '');
  4087.                         $m_type 'приход Нал';
  4088.                         $typeMail 'newTransactionIncomeCash';
  4089.                     } elseif($draft->getTypeTransaction() == 'add_salary' && $draft->getTypeof() == 'expense'){
  4090.                         // -333 (Нал Бот - ЗП Бот, тест коммент)
  4091.                         $cm '-' $amount " (" $from_name " - " $to_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ", " $draft->getComment() . ")";
  4092.                         $m_source = ($draft->getToGroup() != null $draft->getToGroup()->getFirstName() : '');
  4093.                         $m_type 'расход ЗП';
  4094.                         $typeMail 'newTransactionExpenseSalary';
  4095.                     }
  4096.                 }
  4097.                 if($draft->getAmount() < && $draft->getTypeTransaction() == 'payment_salary' && $draft->getTypeof() == 'expense'){
  4098.                     $draft->setTypeof('income');
  4099.                     $draft->setAmount(abs($draft->getAmount()));
  4100.                     $em->persist($draft);
  4101.                     $em->flush();
  4102.                 }
  4103.                 $amount_reverse 0;
  4104.                 if($draft->getToGroup() && $draft->getFromGroup()){
  4105.                     $typeof_reverse null;
  4106.                     if($draft->getTypeof() == 'expense'){
  4107.                         $typeof_reverse 'income';
  4108.                     } elseif($draft->getTypeof() == 'income'){
  4109.                         $typeof_reverse 'expense';
  4110.                     }
  4111.                     $amount_reverse $draft->getAmount();
  4112.                     if($typeof_reverse == 'expense'){
  4113.                         $amount_reverse '-' $draft->getAmount();
  4114.                     }
  4115.                 }
  4116.                 $from_group $draft->getFromGroup();
  4117.                 //если приход по Объекту, или начисление ЗП
  4118.                 if($is_income === true && $draft->getToGroup()){
  4119.                     $from_group $draft->getToGroup();
  4120.                 }
  4121.                 if ($draft->getTypeof() == 'expense' && $draft->getToGroup() && $is_income === false) {
  4122.                     $to_group $draft->getToGroup();
  4123.                 }
  4124.                 $resp true;
  4125.                 if($isSendMail){
  4126.                     //отправка письма по операциям
  4127.                     $recipient $this->getParameter('app.mailer.to.transaction');
  4128.                     $m_amount $draft->getAmount();
  4129.                     $m_office = ($draft->getOffice() != null ? ($draft->getOffice()->getNumber() != '' && $draft->getOffice()->getNumber() != null $draft->getOffice()->getNumber() . '. ' '') . $draft->getOffice()->getName() : '');
  4130.                     $author '';
  4131.                     if($draft->getClient() != null){
  4132.                         if($draft->getClient()->getUsername() != null && $draft->getClient()->getUsername() != ''){
  4133.                             $author $draft->getClient()->getUsername();
  4134.                         }
  4135.                     }
  4136.                     $title_mail = array(
  4137.                         '#amount#' => str_replace(',00'''number_format((abs($m_amount) / 100), 2','' ')),
  4138.                         '#source#' => $m_source,
  4139.                         '#type#' => $m_type,
  4140.                         '#comment#' => $draft->getComment()
  4141.                     );
  4142.                     $body_mail = array(
  4143.                         '#office#' => $m_office,
  4144.                         '#type#' => $m_type,
  4145.                         '#amount#' => str_replace(',00'''number_format((abs($m_amount) / 100), 2','' ')),
  4146.                         '#date#' => ($draft->getCreatedAt() != null $draft->getCreatedAt()->format('d.m.Y') : ''),
  4147.                         '#source#' => $m_source,
  4148.                         '#comment#' => $draft->getComment(),
  4149.                         '#author#' => $author
  4150.                     );
  4151.                     $attach = [];
  4152.                     if($draft->getFile() != null && $draft->getFile() != ''){
  4153.                         if (strpos($draft->getFile(), ';') !== false) {
  4154.                             $filesList explode(';'$draft->getFile());
  4155.                             if(count($filesList) > 0){
  4156.                                 foreach ($filesList as $fileItem){
  4157.                                     $filepath $basePath $fileDir trim($fileItem);
  4158.                                     if(file_exists($filepath)){
  4159.                                         $attach[] = $basePath $fileDir trim($fileItem);
  4160.                                     }
  4161.                                 }
  4162.                             }
  4163.                         } else {
  4164.                             $filepath $basePath $fileDir $draft->getFile();
  4165.                             if(file_exists($filepath)){
  4166.                                 $attach[] = $basePath $fileDir $draft->getFile();
  4167.                             }
  4168.                         }
  4169.                     }
  4170.                     $this->sendEmail($this->mailer$typeMail$body_mail$title_mail'ru'$recipient$attach);
  4171.                 }
  4172.                 if($draft->getTypeTransaction() == 'add_salary'){
  4173.                     //- 5 000 ЗП Бас Иванов.  Сидоров
  4174.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4175.                     //$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') .  $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
  4176.                     $reply $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4177.                     // -333 (Нал Бот - ЗП Бот, тест коммент)
  4178.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4179.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4180.                     }
  4181.                     //+7 500 ЗП Бас Иванов. Петров
  4182.                     $amount "+" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4183.                     //$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
  4184.                     $reply $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4185.                     if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
  4186.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $to_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4187.                     }
  4188.                 } elseif($draft->getTypeTransaction() == 'add_salary_cash'){
  4189.                     //+5 000 ЗП Бас Иванов.  Сидоров
  4190.                     $amount "+" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4191.                     //$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
  4192.                     $reply $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4193.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4194.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4195.                     }
  4196.                     //-7 500 ЗП Бас Иванов. Петров
  4197.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4198.                     //$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
  4199.                     $reply $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4200.                     if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
  4201.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $to_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4202.                     }
  4203.                 } elseif($draft->getTypeTransaction() == 'payment_salary'){
  4204.                     //Начисление зарплаты, вызывается из группы ЗП
  4205.                     //-7 500 ЗП Рук Иванов. Петров
  4206.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4207.                     //$reply = $amount .  " (ЗП, " . $draft->getComment() . ". " . $from_name . ".)";
  4208.                     $reply $amount .  " (Начисл ЗП. " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4209.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4210.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4211.                     }
  4212.                 } elseif($draft->getTypeTransaction() == 'transfer'){
  4213.                     //- 1 000 Петрову и + 1 000 от Иванова
  4214.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4215.                     //$reply = $amount  . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name  . ".";
  4216.                     //if($type_group_from == 'salary' && $type_group_to == 'cash'){
  4217.                     //    $reply = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
  4218.                     // } else {
  4219.                     $reply $amount " (" $from_name " - " $to_name . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4220.                     //}
  4221.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4222.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4223.                     }
  4224.                     $amount "+" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4225.                     //$reply = $amount . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . " от " . $from_name . ".";
  4226.                     //if($type_group_from == 'salary' && $type_group_to == 'cash'){
  4227.                     //    $reply = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
  4228.                     //} else {
  4229.                     $reply $amount " (" $from_name " - " $to_name . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4230.                     //}
  4231.                     if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
  4232.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $to_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4233.                     }
  4234.                 } elseif($draft->getTypeTransaction() == 'income'){
  4235.                     //+ 10 000 Бас Иванов. Предоплата ++
  4236.                     $amount "+" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4237.                     //$reply = $amount . ($office_name != '' ? " (" . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : ""). ". " . $from_name . ".)";
  4238.                     $reply $amount " (" $from_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4239.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4240.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4241.                     }
  4242.                 } elseif($draft->getTypeTransaction() == 'expense_office'){
  4243.                     //- 3 500 Бас Иванов. Гвозди
  4244.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4245.                     //$reply = $amount . ($office_name != '' ? " (" . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ". " . $draft->getComment() . ".)";
  4246.                     $reply $amount " (" $from_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ", " $draft->getComment() . ")";
  4247.                     // +300 (Нал бот, 444. Бургерная, тестовый коммент)
  4248.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4249.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4250.                     }
  4251.                 } elseif($draft->getTypeTransaction() == 'expense_company'){
  4252.                     //- 1 000 Бизнес. Оплата связи
  4253.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4254.                     //$reply = $amount . " (Бизнес. " . $draft->getComment() . ".)";
  4255.                     $reply $amount " (Бизнес. " $draft->getComment() . ".)";
  4256.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4257.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4258.                     }
  4259.                 }
  4260.             }
  4261.         }
  4262.         return $resp;
  4263.     }
  4264.     private function uploadFileBot($token$file_id){
  4265.         $basePath $this->getParameter('kernel.project_dir');
  4266.         $project_dir $basePath '/public/images/';
  4267.         $getFile ProjectUtilsController::requestToBot($token'getFile', ['file_id' => $file_id]);
  4268.         $resp json_decode($getFiletrue);
  4269.         //file_put_contents($basePath . '/var/log/file_resp.txt', print_r($resp, true), FILE_APPEND);
  4270.         $filepath null;
  4271.         if(isset($resp['result']['file_path']) && isset($resp['ok']) && $resp['ok'] == true){
  4272.             $ext strtolower(substr($resp['result']['file_path'], strrpos($resp['result']['file_path'], '.')));
  4273.             if($ext === '.jpg' || $ext === '.jpeg' || $ext === '.png' || $ext === '.gif'){
  4274.                 $filename ProjectUtilsController::generateUuid();
  4275.                 $dir substr($filename03);
  4276.                 if (!is_dir($project_dir $dir)) {
  4277.                     @mkdir($project_dir);
  4278.                     @mkdir($project_dir $dir);
  4279.                 }
  4280.                 $file ProjectUtilsController::fileToBot($token$resp['result']['file_path']);
  4281.                 file_put_contents($project_dir $dir '/' $filename $ext$file);
  4282.                 if(file_exists($project_dir $dir '/' $filename $ext)){
  4283.                     $filepath '/' $dir '/' $filename $ext;
  4284.                 }
  4285.             }
  4286.         }
  4287.         return $filepath;
  4288.     }
  4289.     private function createTransaction($token$chat_id$group$draft){
  4290.         $basePath $this->getParameter('kernel.project_dir');
  4291.         $fileDir '/public/images/';
  4292.         $is_group_chat $this->getParameter('app.chat.is_group');
  4293.         $resp false;
  4294.         $em $this->getDoctrine()->getManager();
  4295.         $isSendMail false;
  4296.         $typeMail 'newTransaction';
  4297.         if($token != '' && $token != null && $chat_id != '' && $chat_id != null && $group && $draft){
  4298.             if($draft->getExpected() == 'finish'){
  4299.                 $amount $draft->getAmount();
  4300.                 if($draft->getTypeof() == 'expense'){
  4301.                     $amount '-' $draft->getAmount();
  4302.                 }
  4303.                 $is_income false;
  4304.                 //если приход по Объекту, или начисление ЗП
  4305.                 if(!$draft->getFromGroup() && $draft->getToGroup()){
  4306.                     $is_income true;
  4307.                 }
  4308.                 $office_name '';
  4309.                 $office_number '';
  4310.                 if($draft->getOffice()){
  4311.                     $office_name $draft->getOffice()->getName();
  4312.                     $office_number $draft->getOffice()->getNumber();
  4313.                 }
  4314.                 $from_chat_id null;
  4315.                 $from_name '';
  4316.                 $type_group_from null;
  4317.                 if($draft->getFromGroup()){
  4318.                     $from_chat_id $draft->getFromGroup()->getChatId();
  4319.                     $from_name $draft->getFromGroup()->nameClient();
  4320.                     $type_group_from = ($draft->getFromGroup()->getTypeGroup() != null $draft->getFromGroup()->getTypeGroup()->getTypeof() : null);
  4321.                 }
  4322.                 $to_chat_id null;
  4323.                 $to_name '';
  4324.                 $type_group_to null;
  4325.                 if($draft->getToGroup()){
  4326.                     $to_chat_id $draft->getToGroup()->getChatId();
  4327.                     $to_name $draft->getToGroup()->nameClient();
  4328.                     $type_group_to = ($draft->getToGroup()->getTypeGroup() != null $draft->getToGroup()->getTypeGroup()->getTypeof() : null);
  4329.                 }
  4330.                 //если приход по Объекту, или начисление ЗП
  4331.                 if($is_income === true && $draft->getToGroup()){
  4332.                     $from_chat_id $draft->getToGroup()->getChatId();
  4333.                     $from_name $draft->getToGroup()->nameClient();
  4334.                 }
  4335.                 $m_source '';
  4336.                 $m_type '';
  4337.                 if($draft->getTypeTransaction() == 'expense_office' || ($draft->getTypeTransaction() == 'income' && $draft->getTypeof() == 'income') || ($draft->getTypeTransaction() == 'add_salary' && $draft->getTypeof() == 'expense') || ($draft->getTypeTransaction() == 'transfer' && $draft->getTypeof() == 'expense') || ($draft->getTypeTransaction() == 'add_salary_cash' && $draft->getTypeof() == 'income')){
  4338.                     $isSendMail true;
  4339.                     $m_source = ($draft->getFromGroup() != null $draft->getFromGroup()->getFirstName() : '');
  4340.                     if($draft->getTypeTransaction() == 'expense_office'){
  4341.                         // +300 (Нал бот, 444. Бургерная, тестовый коммент)
  4342.                         $cm $amount " (" $from_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ", " $draft->getComment() . ")";
  4343.                         if($draft->getFile() != '' && $draft->getFile() != null){
  4344.                             $typeMail 'newTransactionIncomeCashСheque';
  4345.                             $m_type 'расход Чек';
  4346.                         } else {
  4347.                             $typeMail 'newTransactionIncomeCashNoСheque';
  4348.                             $m_type 'расход Нал';
  4349.                         }
  4350.                     } elseif($draft->getTypeTransaction() == 'income' && $draft->getTypeof() == 'income'){
  4351.                         // +555 (Нал Бот, 24195. Пробник, тест коммент)
  4352.                         $cm $amount " (" $from_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ", " $draft->getComment() . ")";
  4353.                         //$m_source = ($draft->getFromGroup() != null ? $draft->getFromGroup()->getFirstName() : '');
  4354.                         $m_source = ($draft->getToGroup() != null $draft->getToGroup()->getFirstName() : '');
  4355.                         $m_type 'приход Нал';
  4356.                         $typeMail 'newTransactionIncomeCash';
  4357.                     } elseif($draft->getTypeTransaction() == 'add_salary' && $draft->getTypeof() == 'expense'){
  4358.                         // -333 (Нал Бот - ЗП Бот, тест коммент)
  4359.                         $cm '-' $amount " (" $from_name " - " $to_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ", " $draft->getComment() . ")";
  4360.                         $m_source = ($draft->getToGroup() != null $draft->getToGroup()->getFirstName() : '');
  4361.                         $m_type 'расход ЗП';
  4362.                         $typeMail 'newTransactionExpenseSalary';
  4363.                     } elseif($draft->getTypeTransaction() == 'transfer' && $draft->getTypeof() == 'expense'){
  4364.                         $isSendMail false//просили отключить
  4365.                         // - 1 000 Петрову и + 1 000 от Иванова
  4366.                         $cm $amount " (" $from_name " - " $to_name . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4367.                         $m_source = ($draft->getFromGroup() != null $draft->getFromGroup()->getFirstName() : '');
  4368.                         $m_type 'списание ЗП';
  4369.                         $typeMail 'newTransactionTransferSalary';
  4370.                     } elseif($draft->getTypeTransaction() == 'add_salary_cash' && $draft->getTypeof() == 'income'){
  4371.                         //+5 000 ЗП Бас Иванов.  Сидоров
  4372.                         $cm $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4373.                         $m_source = ($draft->getToGroup() != null $draft->getToGroup()->getFirstName() : '');
  4374.                         $m_type 'списание ЗП';
  4375.                         $typeMail 'newTransactionAddSalaryCash';
  4376.                     }
  4377.                 }
  4378.                 $isReverseAmount false;
  4379.                 /*
  4380.                  * стала неактуальна после доработок от 06.03.2026
  4381.                 //просили убрать чтоб начисление ЗП с отрицательным знаком чтоб корректировать сумму начислений в сторону уменьшения
  4382.                 if($draft->getAmount() < 0 && $draft->getTypeTransaction() == 'payment_salary' && $draft->getTypeof() == 'expense'){
  4383.                     $draft->setTypeof('income');
  4384.                     $draft->setAmount(abs($draft->getAmount()));
  4385.                     $em->persist($draft);
  4386.                     $em->flush();
  4387.                     $amount = $draft->getAmount();
  4388.                     $isReverseAmount = true;
  4389.                 }
  4390.                 */
  4391.                 if($draft->getAmount() < 0){
  4392.                     if($draft->getTypeof() == 'expense'){
  4393.                         $draft->setTypeof('income');
  4394.                     } elseif($draft->getTypeof() == 'income'){
  4395.                         $draft->setTypeof('expense');
  4396.                     }
  4397.                     $draft->setAmount(abs($draft->getAmount()));
  4398.                     $em->persist($draft);
  4399.                     $em->flush();
  4400.                     $amount $draft->getAmount();
  4401.                     $isReverseAmount true;
  4402.                 }
  4403.                 $newTransaction = new Transaction();
  4404.                 if($draft->getClient()){
  4405.                     $newTransaction->setSender($draft->getClient());
  4406.                 }
  4407.                 if($draft->getFromGroup()){
  4408.                     $newTransaction->setFromGroup($draft->getFromGroup());
  4409.                 }
  4410.                 if($draft->getToGroup()){
  4411.                     $newTransaction->setToGroup($draft->getToGroup());
  4412.                 }
  4413.                 if($draft->getOffice()){
  4414.                     $newTransaction->setOffice($draft->getOffice());
  4415.                 }
  4416.                 $newTransaction->setTypeof($draft->getTypeof());
  4417.                 $newTransaction->setAmount($amount);
  4418.                 $newTransaction->setComment($draft->getComment());
  4419.                 $newTransaction->setNote($draft->getNote());
  4420.                 $newTransaction->setDate(new \DateTime(date('Y-m-d H:i:s')));
  4421.                 if($is_income === false){
  4422.                     $newTransaction->setRecipient($draft->getFromGroup());
  4423.                 } else {
  4424.                     $newTransaction->setRecipient($draft->getToGroup());
  4425.                 }
  4426.                 if($draft->getFile() != '' && $draft->getFile() != null){
  4427.                     $newTransaction->setFile($draft->getFile());
  4428.                 }
  4429.                 $em->persist($newTransaction);
  4430.                 $em->flush();
  4431.                 $amount_reverse 0;
  4432.                 if($draft->getToGroup() && $draft->getFromGroup()){
  4433.                     $typeof_reverse null;
  4434.                     if($draft->getTypeof() == 'expense'){
  4435.                         $typeof_reverse 'income';
  4436.                     } elseif($draft->getTypeof() == 'income'){
  4437.                         $typeof_reverse 'expense';
  4438.                     }
  4439.                     $amount_reverse $draft->getAmount();
  4440.                     if($typeof_reverse == 'expense'){
  4441.                         $amount_reverse '-' $draft->getAmount();
  4442.                     }
  4443.                     $newTransactionReverse = new Transaction();
  4444.                     if($draft->getClient()){
  4445.                         $newTransactionReverse->setSender($draft->getClient());
  4446.                     }
  4447.                     if($draft->getFromGroup()){
  4448.                         $newTransactionReverse->setFromGroup($draft->getFromGroup());
  4449.                     }
  4450.                     if($draft->getToGroup()){
  4451.                         $newTransactionReverse->setToGroup($draft->getToGroup());
  4452.                     }
  4453.                     if($draft->getOffice()){
  4454.                         $newTransactionReverse->setOffice($draft->getOffice());
  4455.                     }
  4456.                     $newTransactionReverse->setTypeof($typeof_reverse);
  4457.                     $newTransactionReverse->setAmount($amount_reverse);
  4458.                     $newTransactionReverse->setComment($draft->getComment());
  4459.                     $newTransactionReverse->setNote($draft->getNote());
  4460.                     $newTransactionReverse->setDate(new \DateTime(date('Y-m-d H:i:s')));
  4461.                     $newTransactionReverse->setRecipient($draft->getToGroup());
  4462.                     $em->persist($newTransactionReverse);
  4463.                     $em->flush();
  4464.                 }
  4465.                 if($newTransaction) {
  4466.                     $balance false;
  4467.                     $from_group $draft->getFromGroup();
  4468.                     //если приход по Объекту, или начисление ЗП
  4469.                     if($is_income === true && $draft->getToGroup()){
  4470.                         $from_group $draft->getToGroup();
  4471.                     }
  4472.                     if ($draft->getTypeof() == 'expense') {
  4473.                         $balance $from_group->getBalance() - $draft->getAmount();
  4474.                     } elseif ($draft->getTypeof() == 'income') {
  4475.                         $balance $from_group->getBalance() + $draft->getAmount();
  4476.                     }
  4477.                     if ($balance != $from_group->getBalance()) {
  4478.                         $from_group->setBalance($balance);
  4479.                         $em->persist($from_group);
  4480.                         $em->flush();
  4481.                     }
  4482.                     if (($draft->getTypeof() == 'expense' && $draft->getToGroup() && $is_income === false) || $isReverseAmount) {
  4483.                         $to_group $draft->getToGroup();
  4484.                         if($isReverseAmount){
  4485.                             $to_balance $to_group->getBalance() - $draft->getAmount();
  4486.                         } else {
  4487.                             $to_balance $to_group->getBalance() + $draft->getAmount();
  4488.                         }
  4489.                         if ($to_balance != $to_group->getBalance()) {
  4490.                             $to_group->setBalance($to_balance);
  4491.                             $em->persist($to_group);
  4492.                             $em->flush();
  4493.                         }
  4494.                     }
  4495.                     $resp true;
  4496.                     if($isSendMail){
  4497.                         //отправка письма по операциям
  4498.                         $recipient $this->getParameter('app.mailer.to.transaction');
  4499.                         $m_amount $newTransaction->getAmount();
  4500.                         $m_office = ($newTransaction->getOffice() != null ? ($newTransaction->getOffice()->getNumber() != '' && $newTransaction->getOffice()->getNumber() != null $newTransaction->getOffice()->getNumber() . '. ' '') . $newTransaction->getOffice()->getName() : '');
  4501.                         $is_cheque = ($newTransaction->getFile() != null && $newTransaction != '' && file_exists($basePath $fileDir $newTransaction->getFile()) ? true false);
  4502.                         $author '';
  4503.                         if($newTransaction->getSender() != null){
  4504.                             if($newTransaction->getSender()->getUsername() != null && $newTransaction->getSender()->getUsername() != ''){
  4505.                                 $author $newTransaction->getSender()->getUsername();
  4506.                             }
  4507.                         }
  4508.                         $title_mail = array(
  4509.                             '#amount#' => str_replace(',00'''number_format((abs($m_amount) / 100), 2','' ')),
  4510.                             '#source#' => $m_source,
  4511.                             '#type#' => $m_type,
  4512.                             '#comment#' => $newTransaction->getComment()
  4513.                         );
  4514.                         $body_mail = array(
  4515.                             '#office#' => $m_office,
  4516.                             '#type#' => $m_type,
  4517.                             '#amount#' => str_replace(',00'''number_format((abs($m_amount) / 100), 2','' ')),
  4518.                             '#date#' => ($newTransaction->getDate() != null $newTransaction->getDate()->format('d.m.Y') : ''),
  4519.                             '#source#' => $m_source,
  4520.                             '#comment#' => $newTransaction->getComment(),
  4521.                             //'#cheque#' => ($is_cheque ? 'есть' : 'нет'),
  4522.                             '#author#' => $author
  4523.                         );
  4524.                         $attach = [];
  4525.                         if($newTransaction->getFile() != null && $newTransaction->getFile() != ''){
  4526.                             if (strpos($newTransaction->getFile(), ';') !== false) {
  4527.                                 $filesList explode(';'$newTransaction->getFile());
  4528.                                 if(count($filesList) > 0){
  4529.                                     foreach ($filesList as $fileItem){
  4530.                                         $filepath $basePath $fileDir trim($fileItem);
  4531.                                         if(file_exists($filepath)){
  4532.                                             $attach[] = $basePath $fileDir trim($fileItem);
  4533.                                         }
  4534.                                     }
  4535.                                 }
  4536.                             } else {
  4537.                                 $filepath $basePath $fileDir $newTransaction->getFile();
  4538.                                 if(file_exists($filepath)){
  4539.                                     $attach[] = $basePath $fileDir $newTransaction->getFile();
  4540.                                 }
  4541.                             }
  4542.                         }
  4543.                         $this->sendEmail($this->mailer$typeMail$body_mail$title_mail'ru'$recipient$attach);
  4544.                     }
  4545.                 }
  4546.                 if($draft->getTypeTransaction() == 'add_salary'){
  4547.                     //- 5 000 ЗП Бас Иванов.  Сидоров
  4548.                     $amount = (!$isReverseAmount "-" "+") . str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4549.                     //$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') .  $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
  4550.                     $reply $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4551.                     // -333 (Нал Бот - ЗП Бот, тест коммент)
  4552.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4553.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4554.                     }
  4555.                     //+7 500 ЗП Бас Иванов. Петров
  4556.                     $amount = (!$isReverseAmount "+" "-") . str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4557.                     //$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
  4558.                     $reply $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4559.                     if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
  4560.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $to_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4561.                     }
  4562.                 } elseif($draft->getTypeTransaction() == 'add_salary_cash'){
  4563.                     //+5 000 ЗП Бас Иванов.  Сидоров
  4564.                     $amount = (!$isReverseAmount "+" "-") . str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4565.                     //$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
  4566.                     $reply $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4567.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4568.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4569.                     }
  4570.                     //-7 500 ЗП Бас Иванов. Петров
  4571.                     $amount = (!$isReverseAmount "-" "+") . str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4572.                     //$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
  4573.                     $reply $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4574.                     if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
  4575.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $to_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4576.                     }
  4577.                 } elseif($draft->getTypeTransaction() == 'payment_salary'){
  4578.                     //-7 500 ЗП Рук Иванов. Петров
  4579.                     $amount = (!$isReverseAmount "-" "+") . str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4580.                     //$reply = $amount .  " (ЗП, " . $draft->getComment() . ". " . $from_name . ".)";
  4581.                     $reply $amount .  " (Начисл ЗП. " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4582.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4583.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4584.                     }
  4585.                 } elseif($draft->getTypeTransaction() == 'transfer'){
  4586.                     //- 1 000 Петрову и + 1 000 от Иванова
  4587.                     $amount = (!$isReverseAmount "-" "+") . str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4588.                     //$reply = $amount  . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name  . ".";
  4589.                     //if($type_group_from == 'salary' && $type_group_to == 'cash'){
  4590.                     //    $reply = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
  4591.                    // } else {
  4592.                         $reply $amount " (" $from_name " - " $to_name . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4593.                     //}
  4594.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4595.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4596.                     }
  4597.                     $amount = (!$isReverseAmount "+" "-") . str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4598.                     //$reply = $amount . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . " от " . $from_name . ".";
  4599.                     //if($type_group_from == 'salary' && $type_group_to == 'cash'){
  4600.                     //    $reply = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
  4601.                     //} else {
  4602.                         $reply $amount " (" $from_name " - " $to_name . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4603.                     //}
  4604.                     if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
  4605.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $to_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4606.                     }
  4607.                 } elseif($draft->getTypeTransaction() == 'income'){
  4608.                     //+ 10 000 Бас Иванов. Предоплата ++
  4609.                     $amount = (!$isReverseAmount "+" "-") . str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4610.                     //$reply = $amount . ($office_name != '' ? " (" . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : ""). ". " . $from_name . ".)";
  4611.                     $reply $amount " (" $from_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4612.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4613.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4614.                     }
  4615.                 } elseif($draft->getTypeTransaction() == 'expense_office'){
  4616.                     //- 3 500 Бас Иванов. Гвозди
  4617.                     $amount = (!$isReverseAmount "-" "+") . str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4618.                     //$reply = $amount . ($office_name != '' ? " (" . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ". " . $draft->getComment() . ".)";
  4619.                     $reply $amount " (" $from_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ", " $draft->getComment() . ")";
  4620.                     // +300 (Нал бот, 444. Бургерная, тестовый коммент)
  4621.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4622.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4623.                     }
  4624.                 } elseif($draft->getTypeTransaction() == 'expense_company'){
  4625.                     //- 1 000 Бизнес. Оплата связи
  4626.                     $amount = (!$isReverseAmount "-" "+") . str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4627.                     //$reply = $amount . " (Бизнес. " . $draft->getComment() . ".)";
  4628.                     $reply $amount " (Бизнес. " $draft->getComment() . ".)";
  4629.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4630.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4631.                     }
  4632.                 }
  4633.             }
  4634.         }
  4635.         return $resp;
  4636.     }
  4637.     private function office($token$chat_id$group_id$cq_data = array(), $curClient false$text null$message_id null) {
  4638.         $basePath $this->getParameter('kernel.project_dir');
  4639.         $is_group_chat $this->kernel->getContainer()->getParameter('app.chat.is_group');
  4640.         $action null;
  4641.         $p_group null;
  4642.         $keyboard = array();
  4643.         $em $this->getDoctrine()->getManager();
  4644.         if(count($cq_data) > 0){
  4645.             $action = (isset($cq_data['action']) ? $cq_data['action'] : null);
  4646.             $p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
  4647.         }
  4648.         $expected null;
  4649.         $p_id null;
  4650.         if($curClient){
  4651.             $data_expected $this->dataExpected($curClient->getExpected());
  4652.             if(isset($data_expected['value'])){
  4653.                 $expected $data_expected['value'];
  4654.             }
  4655.             if(isset($data_expected['group'])){
  4656.                 $p_group $data_expected['group'];
  4657.             }
  4658.             if(isset($data_expected['id'])){
  4659.                 $p_id $data_expected['id'];
  4660.             }
  4661.         }
  4662.         if(count($cq_data) > && $action != 'menu'){
  4663.             $groupObj false;
  4664.             if($group_id != null && $group_id != ''){
  4665.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  4666.             } elseif($p_group != null && $p_group != '') {
  4667.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  4668.             }
  4669.             if($is_group_chat === true && $groupObj){
  4670.                 $chat_id $groupObj->getChatId();
  4671.             }
  4672.             if($action == 'add'){
  4673.                 $reply 'Введите уникальный номер объекта';
  4674.                 $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  4675.                 $this->addExpected($clientObj, array("value" => "new_office""group" => $p_group));
  4676.                 $keyboard = array(
  4677.                     array(
  4678.                         array(
  4679.                             'text'=>'Назад',
  4680.                             'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  4681.                         )
  4682.                     )
  4683.                 );
  4684. //                $reply = 'Введите название нового объекта';
  4685. //                $clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  4686. //                $this->addExpected($clientObj, array("value" => "new_office", "group" => $p_group));
  4687. //                $keyboard = array(
  4688. //                    array(
  4689. //                        array(
  4690. //                            'text'=>'Назад',
  4691. //                            'callback_data'=> json_encode(array('action' => "menu", 'command' => "office", "group" => $p_group))
  4692. //                        )
  4693. //                    )
  4694. //                );
  4695.             } elseif($action == 'edit_list' || $action == 'rem_list') {
  4696.                 $offices $this->getDoctrine()
  4697.                     ->getRepository(Office::class)
  4698.                     ->createQueryBuilder('o')
  4699.                     ->select('o.id, o.name, o.number')
  4700.                     ->where('o.is_active = 1')
  4701.                     ->andWhere('o.deleted_at IS NULL')
  4702.                     ->getQuery()
  4703.                     ->getArrayResult();
  4704.                 if(count($offices) > 0){
  4705.                     $reply 'Выберите из списка объект для ' . ($action == 'rem_list' 'деактивации' 'редактирования') . ".";
  4706.                     $buttons = array();
  4707.                     foreach ($offices as $item_office){
  4708.                         $buttons[][] = array(
  4709.                             'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  4710.                             'callback_data'=> json_encode(array('action' => ($action == 'rem_list' "rem" "edit"), 'command' => "office"'id' => $item_office['id'], "group" => $p_group))
  4711.                         );
  4712.                     }
  4713.                     $keyboard $buttons;
  4714.                     $keyboard[] = array(
  4715.                         array(
  4716.                             'text'=> 'Назад',
  4717.                             'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  4718.                         )
  4719.                     );
  4720.                 } else {
  4721.                     $reply 'Для ' . ($action == 'rem_list' 'деактивации' 'редактирования') . ' нет ни одного объекта.';
  4722.                     $keyboard = array(
  4723.                         array(
  4724.                             array(
  4725.                                 'text'=>'Создать объект',
  4726.                                 'callback_data'=> json_encode(array('action' => "add"'command' => "office""group" => $p_group))
  4727.                             )
  4728.                         )
  4729.                     );
  4730.                 }
  4731.             } elseif($action == 'edit' || $action == 'rem') {
  4732.                 $officeObj false;
  4733.                 if(isset($cq_data['id'])){
  4734.                     $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  4735.                 }
  4736.                 $is_rem false;
  4737.                 if($officeObj){
  4738.                     if($action == 'rem'){
  4739.                         $reply 'Вы действительно хотите деактивировать объект «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() . '»?';
  4740.                         $is_rem true;
  4741.                     } else {
  4742.                         $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  4743.                         $reply 'Выберите, что хотите отредатировать у объекта «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() . '»';
  4744.                         $keyboard = array(
  4745.                             array(
  4746.                                 array(
  4747.                                     'text'=>'Номер объекта',
  4748.                                     'callback_data'=> json_encode(array('action' => "edit_number"'command' => "office""id" => $officeObj->getId(), "group" => $p_group))
  4749.                                 ),
  4750.                                 array(
  4751.                                     'text'=>'Название объекта',
  4752.                                     'callback_data'=> json_encode(array('action' => "edit_name"'command' => "office""id" => $officeObj->getId(), "group" => $p_group))
  4753.                                 ),
  4754.                             )
  4755.                         );
  4756. //                        $clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  4757. //                        $reply = 'Введите новое название для объекта «'  . $officeObj->getName() . '»';
  4758. //                        $this->addExpected($clientObj, array("value" => "edit_office", "id" => $officeObj->getId(), "group" => $p_group));
  4759.                     }
  4760.                 } else {
  4761.                     $reply 'Не удалось найти данный объект. Попробуйте повторить попытку ' . ($action == 'rem' 'деактивировать' 'редактирования') . ' данного объекта позже.';
  4762.                 }
  4763.                 if($is_rem === true){
  4764.                     $keyboard = array(
  4765.                         array(
  4766.                             array(
  4767.                                 'text'=>'Да, деактивировать',
  4768.                                 'callback_data'=> json_encode(array('action' => "rem_ok"'command' => "office""id" => $officeObj->getId(), "group" => $p_group))
  4769.                             )
  4770.                         )
  4771.                     );
  4772.                 }
  4773.                 $keyboard[] = array(
  4774.                     array(
  4775.                         'text'=> ($is_rem === false 'Назад' 'Нет, назад'),
  4776.                         'callback_data'=> json_encode(array('action' => ($action == 'rem' "rem_list" "edit_list"), 'command' => "office""group" => $p_group))
  4777.                     )
  4778.                 );
  4779.                 $keyboard[] = array(
  4780.                     array(
  4781.                         'text'=> ($is_rem === false 'В основное меню объектов' 'Нет, в основное меню объектов'),
  4782.                         'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  4783.                     )
  4784.                 );
  4785.             } elseif($action == 'rem_ok') {
  4786.                 $officeObj false;
  4787.                 if(isset($cq_data['id'])){
  4788.                     $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  4789.                 }
  4790.                 if($officeObj){
  4791.                     $reply 'Объект «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() . '» успешно деактивирован.';
  4792.                     $officeObj->setIsActive(0);
  4793.                     $em->persist($officeObj);
  4794.                     $em->flush();
  4795.                     $keyboard = array(
  4796.                         array(
  4797.                             array(
  4798.                                 'text'=> 'Назад',
  4799.                                 'callback_data'=> json_encode(array('action' => "rem_list"'command' => "office""group" => $p_group))
  4800.                             )
  4801.                         ),
  4802.                         array(
  4803.                             array(
  4804.                                 'text'=> 'В основное меню объектов',
  4805.                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  4806.                             )
  4807.                         )
  4808.                     );
  4809.                 } else {
  4810.                     $reply 'Не удалось найти данный объект. Попробуйте повторить попытку деактивации данного объекта позже.';
  4811.                 }
  4812.             } elseif($action == 'delete'){
  4813.                 $mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
  4814.                 if($mes_id != '' && $mes_id != null){
  4815.                     $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $chat_id'message_id' => $mes_id]);
  4816.                 }
  4817.                 if($cq_data['group'] != '' && $cq_data['group'] != null){
  4818.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
  4819.                     if($groupObj){
  4820.                         if(file_exists($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt')){
  4821.                             $mes_id file_get_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt');
  4822.                             if($mes_id != '' && $mes_id != null){
  4823.                                 $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $chat_id'message_id' => $mes_id]);
  4824.                                 $resp json_decode($deleteMessagetrue);
  4825.                                 if(isset($resp['result'])){
  4826.                                     if($resp['result'] == true){
  4827.                                         unlink($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt');
  4828.                                     }
  4829.                                 }
  4830.                             }
  4831.                         }
  4832.                     }
  4833.                 }
  4834.             } elseif($action == 'edit_number' || $action == 'edit_name'){
  4835.                 $officeObj false;
  4836.                 if(isset($cq_data['id'])){
  4837.                     $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  4838.                 }
  4839.                 $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  4840.                 if($action == 'edit_name'){
  4841.                     $reply 'Введите новое название для объекта «' . ($officeObj->getNumber() != null && $officeObj->getName() != '' $officeObj->getName() . '. ' '') . $officeObj->getName() . '»';
  4842.                     $this->addExpected($clientObj, array("value" => "edit_office""id" => $officeObj->getId(), "group" => $p_group));
  4843.                 } else {
  4844.                     $reply 'Введите новый номер для объекта «'  . ($officeObj->getNumber() != null && $officeObj->getName() != '' $officeObj->getName() . '. ' '') . $officeObj->getName() . '»';
  4845.                     $this->addExpected($clientObj, array("value" => "edit_n_office""id" => $officeObj->getId(), "group" => $p_group));
  4846.                 }
  4847.                 $keyboard[] = array(
  4848.                     array(
  4849.                         'text'=> 'Назад',
  4850.                         'callback_data'=> json_encode(array('action' => 'edit'"id" => $officeObj->getId(), 'command' => "office""group" => $p_group))
  4851.                     )
  4852.                 );
  4853.                 $keyboard[] = array(
  4854.                     array(
  4855.                         'text'=> 'В основное меню объектов',
  4856.                         'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  4857.                     )
  4858.                 );
  4859.             } elseif($action == 'activ_list'){
  4860.                 $offices $this->getDoctrine()
  4861.                     ->getRepository(Office::class)
  4862.                     ->createQueryBuilder('o')
  4863.                     ->select('o.id, o.number, o.name')
  4864.                     ->where('o.is_active = 0')
  4865.                     ->getQuery()
  4866.                     ->getArrayResult();
  4867.                 if(count($offices) > 0){
  4868.                     $reply 'Выберите из списка объект для активации.';
  4869.                     $buttons = array();
  4870.                     foreach ($offices as $item_office){
  4871.                         $buttons[][] = array(
  4872.                             'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  4873.                             'callback_data'=> json_encode(array('action' => "activ"'command' => "office"'id' => $item_office['id'], "group" => $p_group))
  4874.                         );
  4875.                     }
  4876.                     $keyboard $buttons;
  4877.                     $keyboard[] = array(
  4878.                         array(
  4879.                             'text'=> 'Назад',
  4880.                             'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  4881.                         )
  4882.                     );
  4883.                 } else {
  4884.                     $reply 'Для активации нет ни одного деактивированного объекта.';
  4885.                     $keyboard = array(
  4886.                         array(
  4887.                             array(
  4888.                                 'text'=> 'Назад',
  4889.                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  4890.                             )
  4891.                         )
  4892.                     );
  4893.                 }
  4894.             } elseif($action == 'activ'){
  4895.                 $officeObj false;
  4896.                 if(isset($cq_data['id'])){
  4897.                     $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  4898.                 }
  4899.                 $is_rem false;
  4900.                 if($officeObj){
  4901.                     $reply 'Вы действительно хотите активировать объект «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() . '»?';
  4902.                     $is_rem true;
  4903.                 } else {
  4904.                     $reply 'Не удалось найти данный объект. Попробуйте повторить попытку активировать данного объекта позже.';
  4905.                 }
  4906.                 $keyboard = array(
  4907.                     array(
  4908.                         array(
  4909.                             'text'=>'Да, активировать',
  4910.                             'callback_data'=> json_encode(array('action' => "activ_ok"'command' => "office""id" => $officeObj->getId(), "group" => $p_group))
  4911.                         )
  4912.                     )
  4913.                 );
  4914.                 $keyboard[] = array(
  4915.                     array(
  4916.                         'text'=> ($is_rem === false 'Назад' 'Нет, назад'),
  4917.                         'callback_data'=> json_encode(array('action' => "activ_list"'command' => "office""group" => $p_group))
  4918.                     )
  4919.                 );
  4920.                 $keyboard[] = array(
  4921.                     array(
  4922.                         'text'=> ($is_rem === false 'В основное меню объектов' 'Нет, в основное меню объектов'),
  4923.                         'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  4924.                     )
  4925.                 );
  4926.             } elseif($action == 'activ_ok'){
  4927.                 $officeObj false;
  4928.                 if(isset($cq_data['id'])){
  4929.                     $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  4930.                 }
  4931.                 if($officeObj){
  4932.                     $reply 'Объект «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() . '» успешно активирован.';
  4933.                     $officeObj->setIsActive(1);
  4934.                     $em->persist($officeObj);
  4935.                     $em->flush();
  4936.                     $keyboard = array(
  4937.                         array(
  4938.                             array(
  4939.                                 'text'=> 'Назад',
  4940.                                 'callback_data'=> json_encode(array('action' => "activ_list"'command' => "office""group" => $p_group))
  4941.                             )
  4942.                         ),
  4943.                         array(
  4944.                             array(
  4945.                                 'text'=> 'В основное меню объектов',
  4946.                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  4947.                             )
  4948.                         )
  4949.                     );
  4950.                 } else {
  4951.                     $reply 'Не удалось найти данный объект. Попробуйте повторить попытку активации данного объекта позже.';
  4952.                 }
  4953.             }
  4954.         } elseif($expected != '' && $expected != null){
  4955.             $groupObj false;
  4956.             if($group_id != '' && $group_id != null){
  4957.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  4958.             } elseif($p_group != '' && $p_group != null){
  4959.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  4960.             }
  4961.             if($is_group_chat === true && $groupObj){
  4962.                 $chat_id $groupObj->getChatId();
  4963.             }
  4964.             if($expected == 'new_office'){
  4965.                 if($curClient && $text != '' && $text != null){
  4966.                     $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('number' => trim($text)));
  4967.                     if($officeObj){
  4968.                         if($officeObj->getIsActive() == '1'){
  4969.                             $reply 'Объект c номером «' $officeObj->getName() . '» уже существует. Введите другой номер объекта.';
  4970.                         } else {
  4971.                             $officeObj->setIsActive(1);
  4972.                             $em->persist($officeObj);
  4973.                             $em->flush();
  4974.                             $reply 'Объект «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() . '» снова активен.';
  4975.                         }
  4976.                     } else {
  4977.                         $newOffice = new Office();
  4978.                         $newOffice->setName('');
  4979.                         $newOffice->setNumber(trim($text));
  4980.                         $newOffice->setIsActive(0);
  4981.                         $em->persist($newOffice);
  4982.                         $em->flush();
  4983.                         $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  4984.                         $reply 'Введите название объекта';
  4985.                         $this->addExpected($clientObj, array("value" => "name_office""id" => $newOffice->getId(), "group" => $p_group));
  4986.                     }
  4987.                     //$this->resetExpected($curClient);
  4988.                 } elseif($expected == 'new_office') {
  4989.                     $reply 'Введите номер нового объекта.';
  4990.                 }
  4991. //                if($curClient && $text != '' && $text != null){
  4992. //                    $officeObj = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('name' => trim($text)));
  4993. //                    if($officeObj){
  4994. //                        if($officeObj->getIsActive() == '1'){
  4995. //                            $reply = 'Объект «' . $officeObj->getName() . '» уже существует. Введите другое название объекта.';
  4996. //                        } else {
  4997. //                            $officeObj->setIsActive(1);
  4998. //                            $em->persist($officeObj);
  4999. //                            $em->flush();
  5000. //
  5001. //                            $reply = 'Объект «' . $officeObj->getName() . '» снова активен.';
  5002. //                        }
  5003. //                    } else {
  5004. //                        $newOffice = new Office();
  5005. //                        $newOffice->setName(trim($text));
  5006. //                        $newOffice->setIsActive(1);
  5007. //                        $em->persist($newOffice);
  5008. //                        $em->flush();
  5009. //
  5010. //                        $reply = 'Добавлен новый объект «' . $newOffice->getName() . '».';
  5011. //                    }
  5012. //
  5013. //                    $this->resetExpected($curClient);
  5014. //                } elseif($expected == 'new_office') {
  5015. //                    $reply = 'Введите название нового объекта.';
  5016. //                }
  5017.                 $keyboard = array(
  5018.                     array(
  5019.                         array(
  5020.                             'text'=> 'Назад',
  5021.                             'callback_data'=> json_encode(array('action' => "edit_list"'command' => "office""group" => $p_group))
  5022.                         )
  5023.                     ),
  5024.                     array(
  5025.                         array(
  5026.                             'text'=> 'В основное меню объектов',
  5027.                             'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  5028.                         )
  5029.                     )
  5030.                 );
  5031.             } elseif($expected == 'edit_office') {
  5032.                 $officeObj false;
  5033.                 if(isset($data_expected['id'])){
  5034.                     $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $data_expected['id']));
  5035.                 }
  5036.                 if($officeObj && $curClient && $text != '' && $text != null){
  5037.                     $name_last = ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName();
  5038.                     $officeTmp $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('name' => trim($text)));
  5039.                     if(!$officeTmp){
  5040.                         $officeObj->setName(trim($text));
  5041.                         if($officeObj->getIsActive() != '1'){
  5042.                             $officeObj->setIsActive(1);
  5043.                         }
  5044.                         $em->persist($officeObj);
  5045.                         $em->flush();
  5046.                         $reply 'Объект «' $name_last '» успешно переименован в «' . ($officeObj->getNumber() != null && $officeObj->getNumber() != '' $officeObj->getNumber() . '. ' '') . trim($text) . '».';
  5047.                         $this->resetExpected($curClient);
  5048.                     } else {
  5049.                         $reply 'Невозможно объект «' $name_last '» переименовать в  «' . ($officeObj->getNumber() != null && $officeObj->getNumber() != '' $officeObj->getNumber() . '. ' '') . trim($text) . '», объект с таким названием уже существует. Введите другое название.';
  5050.                     }
  5051.                 }
  5052.                 $keyboard = array(
  5053.                     array(
  5054.                         array(
  5055.                             'text'=> 'Назад',
  5056.                             'callback_data'=> json_encode(array('action' => "edit_list"'command' => "office""group" => $p_group))
  5057.                         )
  5058.                     ),
  5059.                     array(
  5060.                         array(
  5061.                             'text'=> 'В основное меню объектов',
  5062.                             'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  5063.                         )
  5064.                     )
  5065.                 );
  5066.             } elseif($expected == 'edit_n_office') {
  5067.                 $officeObj false;
  5068.                 if(isset($data_expected['id'])){
  5069.                     $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $data_expected['id']));
  5070.                 }
  5071.                 if($officeObj && $curClient && $text != '' && $text != null){
  5072.                     $name_last = ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') .  $officeObj->getName();
  5073.                     $officeTmp $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('number' => trim($text), 'name' => $officeObj->getName()));
  5074.                     if(!$officeTmp){
  5075.                         $officeObj->setNumber(trim($text));
  5076.                         if($officeObj->getIsActive() != '1'){
  5077.                             $officeObj->setIsActive(1);
  5078.                         }
  5079.                         $em->persist($officeObj);
  5080.                         $em->flush();
  5081.                         $reply 'Объект «' $name_last '» успешно переименован в «' . ($officeObj->getNumber() != null && $officeObj->getNumber() != '' $officeObj->getNumber() . '. ' '') .  $officeObj->getName() . '».';
  5082.                         $this->resetExpected($curClient);
  5083.                     } else {
  5084.                         $reply 'Невозможно объект «' $name_last '» переименовать в  «' trim($text) . '. ' .  $officeObj->getName() . '», объект с таким названием уже существует. Введите другое название.';
  5085.                     }
  5086.                 }
  5087.                 $keyboard = array(
  5088.                     array(
  5089.                         array(
  5090.                             'text'=> 'Назад',
  5091.                             'callback_data'=> json_encode(array('action' => "edit_list"'command' => "office""group" => $p_group))
  5092.                         )
  5093.                     ),
  5094.                     array(
  5095.                         array(
  5096.                             'text'=> 'В основное меню объектов',
  5097.                             'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  5098.                         )
  5099.                     )
  5100.                 );
  5101.             } elseif($expected == 'name_office'){
  5102.                 if($curClient && $text != '' && $text != null){
  5103.                     if($p_id != '' && $p_id != null){
  5104.                         $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $p_id));
  5105.                         if($officeObj){
  5106.                             $officeObj->setName(trim($text))
  5107.                                 ->setIsActive(1);
  5108.                             $em->persist($officeObj);
  5109.                             $em->flush();
  5110.                             $reply 'Добавлен новый объект «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() . '».';
  5111.                         }
  5112.                     }
  5113.                     $this->resetExpected($curClient);
  5114.                 } elseif($expected == 'new_office') {
  5115.                     $reply 'Введите название нового объекта.';
  5116.                 }
  5117.                 $keyboard = array(
  5118.                     array(
  5119.                         array(
  5120.                             'text'=> 'В основное меню объектов',
  5121.                             'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  5122.                         )
  5123.                     )
  5124.                 );
  5125.             }
  5126.         } else {
  5127.             $groupObj false;
  5128.             if($group_id != '' && $group_id != null){
  5129.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  5130.             } elseif($p_group != '' && $p_group != null){
  5131.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  5132.             }
  5133.             if($is_group_chat === true && $groupObj){
  5134.                 $chat_id $groupObj->getChatId();
  5135.             }
  5136.             $reply 'Выберите действие над объектом.';
  5137.             $offices $this->getDoctrine()
  5138.                 ->getRepository(Office::class)
  5139.                 ->createQueryBuilder('o')
  5140.                 ->select('o.id, o.name')
  5141.                 ->where('o.is_active = 1')
  5142.                 ->andWhere('o.deleted_at IS NULL')
  5143.                 ->getQuery()
  5144.                 ->getArrayResult();
  5145.             $keyboard = [];
  5146.             $offices_na $this->getDoctrine()
  5147.                 ->getRepository(Office::class)
  5148.                 ->createQueryBuilder('o')
  5149.                 ->select('o.id')
  5150.                 ->where('o.is_active = 0')
  5151.                 ->getQuery()
  5152.                 ->getArrayResult();
  5153.             if(count($offices_na) > 0){
  5154.                 $keyboard[] = array(
  5155.                     array(
  5156.                         'text'=>'Активировать объект',
  5157.                         'callback_data'=> json_encode(array('action' => "activ_list"'command' => "office""group" => ($groupObj $groupObj->getId() : null)))
  5158.                     )
  5159.                 );
  5160.             }
  5161.             $keyboard[] = array(
  5162.                 array(
  5163.                     'text'=>'Создать объект',
  5164.                     'callback_data'=> json_encode(array('action' => "add"'command' => "office""group" => ($groupObj $groupObj->getId() : null)))
  5165.                 )
  5166.             );
  5167.             if(count($offices) > 0){
  5168.                 $keyboard[] = array(
  5169.                     array(
  5170.                         'text'=>'Редактировать объект',
  5171.                         'callback_data'=> json_encode(array('action' => "edit_list"'command' => "office""group" => ($groupObj $groupObj->getId() : null)))
  5172.                     ),
  5173.                 );
  5174.                 $keyboard[] = array(
  5175.                     array(
  5176.                         'text'=>'Деактивировать объект',
  5177.                         'callback_data'=> json_encode(array('action' => "rem_list"'command' => "office""group" => ($groupObj $groupObj->getId() : null)))
  5178.                     ),
  5179.                 );
  5180.                 $keyboard[] = array(
  5181.                     array(
  5182.                         'text'=>'Назад',
  5183.                         'callback_data'=> json_encode(array('action' => "delete"'command' => "office"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  5184.                     )
  5185.                 );
  5186.             }
  5187.         }
  5188.         $sendMessage false;
  5189.         if(count($keyboard) > 0){
  5190.             $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5191.             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5192.             $resp json_decode($sendMessagetrue);
  5193.             if(isset($resp['result']['message_id']) && $groupObj){
  5194.                 file_put_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt'$resp['result']['message_id']);
  5195.             }
  5196.         } else {
  5197.             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5198.         }
  5199.         if($is_group_chat === true){
  5200.             $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
  5201.             $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'office'));
  5202.             $this->addLogMessageBot($bot$command$sendMessage);
  5203.         }
  5204.     }
  5205.     private function users($token$chat_id$group_id$cq_data = array(), $curClient false$text null$message_id null) {
  5206.         $basePath $this->getParameter('kernel.project_dir');
  5207.         $is_group_chat $this->kernel->getContainer()->getParameter('app.chat.is_group');
  5208.         $action null;
  5209.         $p_group null;
  5210.         $keyboard = array();
  5211.         $em $this->getDoctrine()->getManager();
  5212.         $expected null;
  5213.         if(count($cq_data) > 0){
  5214.             $action = (isset($cq_data['action']) ? $cq_data['action'] : null);
  5215.             $p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
  5216.         }
  5217.         if($curClient){
  5218.             $data_expected $this->dataExpected($curClient->getExpected());
  5219.             if(isset($data_expected['value'])){
  5220.                 $expected $data_expected['value'];
  5221.             }
  5222.             if(isset($data_expected['group'])){
  5223.                 $p_group $data_expected['group'];
  5224.             }
  5225.         }
  5226.         $sendMessage false;
  5227.         if(count($cq_data) > && $action != 'list'){
  5228.             $groupObj false;
  5229.             if($group_id != '' && $group_id != null){
  5230.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  5231.             } elseif($p_group != '' && $p_group != null && $action == 'list'){
  5232.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  5233.             }
  5234.             if($is_group_chat === true && $groupObj){
  5235.                 $chat_id $groupObj->getChatId();
  5236.             }
  5237.             $em $this->getDoctrine()->getManager();
  5238.             $reply 'Не удалось получить информацию о пользователе.';
  5239.             if($action == 'show'){
  5240.                 $clientObj false;
  5241.                 if(isset($cq_data['id'])){
  5242.                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  5243.                         $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  5244.                     }
  5245.                 }
  5246.                 if($clientObj){
  5247.                     $name_client $clientObj->nameClient();
  5248.                     $reply 'Выберите, что хотите изменить у пользователя ' $name_client ".";
  5249.                     $keyboard = array(
  5250.                         array(
  5251.                             array(
  5252.                                 'text'=>'Изменить роль',
  5253.                                 'callback_data'=> json_encode(array('action' => "role"'command' => "users"'id' => $clientObj->getId(), "group" => $p_group))
  5254.                             )
  5255.                         ),
  5256. //                        array(
  5257. //                            array(
  5258. //                                'text'=>'Изменить email',
  5259. //                                'callback_data'=> json_encode(array('action' => "email", 'id' => $clientObj->getId(), 'command' => "users", "group" => $p_group))
  5260. //                            ),
  5261. //                        ),
  5262.                         array(
  5263.                             array(
  5264.                                 'text'=>'К списку всех пользователей',
  5265.                                 'callback_data'=> json_encode(array('action' => "list"'command' => "users""group" => $p_group))
  5266.                             ),
  5267.                         )
  5268.                     );
  5269.                 } else {
  5270.                     $reply 'Невозможно продолжить действие, пользователь не найден.';
  5271.                 }
  5272.                 if(count($keyboard) > 0){
  5273.                     $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5274.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5275.                 } else {
  5276.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5277.                 }
  5278.             } elseif($action == 'role'){
  5279.                 $clientObj false;
  5280.                 if(isset($cq_data['id'])){
  5281.                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  5282.                         $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  5283.                     }
  5284.                 }
  5285.                 if($clientObj){
  5286.                     $name_client $clientObj->nameClient();
  5287.                     $name_role null;
  5288.                     if($clientObj->getRole()){
  5289.                         $name_role $clientObj->getRole()->getName();
  5290.                     }
  5291.                     $buttons = array();
  5292.                     $roles $this->getDoctrine()
  5293.                         ->getRepository(Role::class)
  5294.                         ->createQueryBuilder('r')
  5295.                         ->select('r.id, r.name')
  5296.                         ->getQuery()
  5297.                         ->getArrayResult();
  5298.                     if(count($roles) > 0){
  5299.                         foreach ($roles as $item_role){
  5300.                             $buttons[][] = array(
  5301.                                 'text' => $item_role['name'],
  5302.                                 'callback_data'=> json_encode(array('action' => "add"'command' => "users"'id' => $item_role['id'], "group" => ($p_group != null && $p_group != '' && $p_group $p_group ""), "client" => $clientObj->getId()))
  5303.                             );
  5304.                         }
  5305.                         $buttons[][] = array(
  5306.                             'text'=>'Назад',
  5307.                             'callback_data'=> json_encode(array('action' => "show"'command' => "users"'id' => $clientObj->getId(), "group" => ($groupObj $groupObj->getId() : null)))
  5308.                         );
  5309.                     }
  5310.                     if($name_client != '' && $name_client != null){
  5311.                         $reply 'У пользователя ' $name_client ' пока нет роли.';
  5312.                         if($name_role != '' && $name_role != null){
  5313.                             $reply 'У пользователя ' $name_client ' текущая роль «'  $name_role '». Чтобы поменять роль выберите необходимую из списка.';
  5314.                         }
  5315.                     }
  5316.                     if(count($buttons) > 0){
  5317.                         if($name_role != '' && $name_role != null){
  5318.                             $reply $reply ' Чтобы поменять роль выберите необходимую из списка.';
  5319.                         } else {
  5320.                             $reply $reply ' Выберите необходимую роль из списка.';
  5321.                         }
  5322.                     } else {
  5323.                         $reply $reply ' Ролей для выбора пока нет, попробуйте выбрать позже.';
  5324.                     }
  5325.                     $keyboard $buttons;
  5326.                 }
  5327.                 if(count($keyboard) > 0){
  5328.                     $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5329.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5330.                 } else {
  5331.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5332.                 }
  5333.             } elseif($action == 'add'){
  5334.                 $reply 'При попытке поменять роль у пользователя произошла ошибка. Попробуйте повторить попытку позже.';
  5335.                 $keyboard = array();
  5336.                 if(isset($cq_data['client']) && isset($cq_data['id'])){
  5337.                     if($cq_data['client'] != '' && $cq_data['client'] != null && $cq_data['id'] != '' && $cq_data['client'] != null){
  5338.                         $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['client'], 'typeof' => 'private'));
  5339.                         $roleObj $this->getDoctrine()->getRepository(Role::class)->findOneBy(array('id' => $cq_data['id']));
  5340.                         if($clientObj && $roleObj){
  5341.                             $clientObj->setRole($roleObj);
  5342.                             $em->persist($clientObj);
  5343.                             $em->flush();
  5344.                             $name_role $roleObj->getName();
  5345.                             $name_client $clientObj->nameClient();
  5346.                             $reply 'У пользователя ' $name_client ' выбрана роль «'  $name_role '».';
  5347.                             $keyboard = array(
  5348.                                 array(
  5349.                                     array(
  5350.                                         'text'=>'Выбрать новую роль',
  5351.                                         'callback_data'=> json_encode(array('action' => "show"'command' => "users"'id' => $clientObj->getId(), "group" => $p_group))
  5352.                                     )
  5353.                                 ),
  5354.                                 array(
  5355.                                     array(
  5356.                                         'text'=>'К списку всех пользователей',
  5357.                                         'callback_data'=> json_encode(array('action' => "list"'command' => "users""group" => $p_group))
  5358.                                     ),
  5359.                                 )
  5360.                             );
  5361.                         }
  5362.                     }
  5363.                 }
  5364.                 if(count($keyboard) > 0){
  5365.                     $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5366.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5367.                 } else {
  5368.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5369.                 }
  5370.             } elseif($action == 'email'){
  5371.                 $clientObj false;
  5372.                 if(isset($cq_data['id'])){
  5373.                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  5374.                         $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  5375.                     }
  5376.                 }
  5377.                 $keyboard = array();
  5378.                 if($clientObj){
  5379.                     $name_client $clientObj->nameClient();
  5380.                     $email $clientObj->getEmail();
  5381.                     if($email != '' && $email != null){
  5382.                         $reply 'У пользователя ' $name_client ' указан email «'  $email '», можете поменять его.';
  5383.                         $keyboard = array(
  5384.                             array(
  5385.                                 array(
  5386.                                     'text'=>'Изменить email',
  5387.                                     'callback_data'=> json_encode(array('action' => "edit_email"'id' => $clientObj->getId(), 'command' => "users""group" => $p_group))
  5388.                                 ),
  5389.                             ),
  5390.                             array(
  5391.                                 array(
  5392.                                     'text'=>'К списку всех пользователей',
  5393.                                     'callback_data'=> json_encode(array('action' => "list"'command' => "users""group" => $p_group))
  5394.                                 ),
  5395.                             )
  5396.                         );
  5397.                     } else {
  5398.                         $reply 'У пользователя ' $name_client ' не указан email, можете добавить его.';
  5399.                         $keyboard = array(
  5400.                             array(
  5401.                                 array(
  5402.                                     'text'=>'Добавить email',
  5403.                                     'callback_data'=> json_encode(array('action' => "add_email"'id' => $clientObj->getId(), 'command' => "users""group" => $p_group))
  5404.                                 ),
  5405.                             ),
  5406.                             array(
  5407.                                 array(
  5408.                                     'text'=>'К списку всех пользователей',
  5409.                                     'callback_data'=> json_encode(array('action' => "list"'command' => "users""group" => $p_group))
  5410.                                 ),
  5411.                             )
  5412.                         );
  5413.                     }
  5414.                 } else {
  5415.                     $reply 'Невозможно продолжить действие, пользователь не найден.';
  5416.                 }
  5417.                 if(count($keyboard) > 0){
  5418.                     $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5419.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5420.                 } else {
  5421.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5422.                 }
  5423.             } elseif($action == 'add_email' || $action == 'edit_email'){
  5424.                 $clientObj false;
  5425.                 if($is_group_chat === true){
  5426.                     if(isset($cq_data['group'])){
  5427.                         if($cq_data['group'] != '' && $cq_data['group'] != null){
  5428.                             $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
  5429.                         }
  5430.                     } elseif(isset($cq_data['id'])){
  5431.                         if($cq_data['id'] != '' && $cq_data['id'] != null){
  5432.                             $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  5433.                         }
  5434.                     }
  5435.                 } else {
  5436.                     if(isset($cq_data['id'])){
  5437.                         if($cq_data['id'] != '' && $cq_data['id'] != null){
  5438.                             $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  5439.                         }
  5440.                     }
  5441.                 }
  5442.                 $keyboard = array();
  5443.                 if($clientObj){
  5444.                     $name_client $clientObj->nameClient();
  5445.                     $reply 'Введите email, который хотите добавить пользователю ' $name_client ".";
  5446.                     $this->addExpected($clientObj, array("value" => "email""group" => $p_group));
  5447.                 } else {
  5448.                     $reply 'Невозможно продолжить действие, пользователь не найден.';
  5449.                 }
  5450.                 if(count($keyboard) > 0){
  5451.                     $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5452.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5453.                 } else {
  5454.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5455.                 }
  5456.             } elseif($action == 'delete'){
  5457.                 $mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
  5458.                 if($mes_id != '' && $mes_id != null){
  5459.                     $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $chat_id'message_id' => $mes_id]);
  5460.                 }
  5461.                 if($cq_data['group'] != '' && $cq_data['group'] != null){
  5462.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
  5463.                     if($groupObj){
  5464.                         if(file_exists($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt')){
  5465.                             $mes_id file_get_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt');
  5466.                             if($mes_id != '' && $mes_id != null){
  5467.                                 $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $chat_id'message_id' => $mes_id]);
  5468.                                 $resp json_decode($deleteMessagetrue);
  5469.                                 if(isset($resp['result'])){
  5470.                                     if($resp['result'] == true){
  5471.                                         unlink($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt');
  5472.                                     }
  5473.                                 }
  5474.                             }
  5475.                         }
  5476.                     }
  5477.                 }
  5478.             }
  5479.         } elseif($expected != '' && $expected != null){
  5480.             $groupObj false;
  5481.             if($group_id != '' && $group_id != null){
  5482.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  5483.             } elseif($p_group != '' && $p_group != null && $action == 'list'){
  5484.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  5485.             }
  5486.             if($is_group_chat === true && $groupObj){
  5487.                 $chat_id $groupObj->getChatId();
  5488.             }
  5489.             if($expected == 'email'){
  5490.                 if($curClient && $text != '' && $text != null){
  5491.                     $name_client $curClient->nameClient();
  5492.                     $reply 'Email ' $text ' успешно добавлен пользователю ' $name_client ".";
  5493.                     $curClient->setEmail(trim($text));
  5494.                     $em->persist($curClient);
  5495.                     $em->flush();
  5496.                     $this->resetExpected($curClient);
  5497.                     $keyboard = array(
  5498.                         array(
  5499.                             array(
  5500.                                 'text'=>'К списку всех пользователей',
  5501.                                 'callback_data'=> json_encode(array('action' => "list"'command' => "users""group" => $p_group))
  5502.                             ),
  5503.                         )
  5504.                     );
  5505.                 } elseif(!$curClient) {
  5506.                     $reply 'Невозможно продолжить действие, пользователь не найден.';
  5507.                 }
  5508.             }
  5509.             if(count($keyboard) > 0){
  5510.                 $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5511.                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5512.             } else {
  5513.                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5514.             }
  5515.         } else {
  5516.             $reply 'Пока нет ни одного пользователя для редактирования у него роли.';
  5517.             $clients $this->getDoctrine()
  5518.                 ->getRepository(Client::class)
  5519.                 ->createQueryBuilder('c')
  5520.                 ->select('c.id, c.first_name, c.last_name, c.username, r.name AS name_role')
  5521.                 ->where('c.typeof = :typeof')
  5522.                 ->leftJoin(Role::class, 'r''WITH''c.role = r.id')
  5523.                 ->setParameter('typeof''private')
  5524.                 ->getQuery()
  5525.                 ->getArrayResult();
  5526.             $groupObj false;
  5527.             if($group_id != '' && $group_id != null){
  5528.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  5529.             } elseif($p_group != '' && $p_group != null && $action == 'list'){
  5530.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  5531.             }
  5532.             if($is_group_chat === true && $groupObj){
  5533.                 $chat_id $groupObj->getChatId();
  5534.             }
  5535.             $buttons = array();
  5536.             if(count($clients) > 0){
  5537.                 $reply 'Выберите пользователя, у которого хотите отредактировать информацию.';
  5538.                 foreach ($clients as $item_client){
  5539.                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  5540.                     if($name_client != '' && $name_client != null){
  5541.                         $buttons[][] = array(
  5542.                             'text' => $name_client . ($item_client['name_role'] != '' && $item_client['name_role'] != null ' (' $item_client['name_role'] . ')' ''),
  5543.                             'callback_data'=> json_encode(array('action' => "show"'command' => "users"'id' => $item_client['id'], "group" => ($groupObj $groupObj->getId() : null)))
  5544.                         );
  5545.                     }
  5546.                 }
  5547.                 $buttons[][] = array(
  5548.                     'text'=>'Назад',
  5549.                     'callback_data'=> json_encode(array('action' => "delete"'command' => "setting"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  5550.                 );
  5551.             }
  5552.             $keyboard $buttons;
  5553.             if(count($keyboard) > 0){
  5554.                 $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5555.                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5556.                 $resp json_decode($sendMessagetrue);
  5557.                 if(isset($resp['result']['message_id']) && $groupObj){
  5558.                     file_put_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt'$resp['result']['message_id']);
  5559.                 }
  5560.             } else {
  5561.                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5562.             }
  5563.         }
  5564.         if($is_group_chat === true){
  5565.             $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
  5566.             $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'users'));
  5567.             $this->addLogMessageBot($bot$command$sendMessage);
  5568.         }
  5569.     }
  5570.     private function nameClient($first_name$last_name$username){
  5571.         $name_client = ($first_name != '' && $first_name != null $first_name '');
  5572.         if($name_client != '' && $last_name != '' && $last_name != null){
  5573.             $name_client $name_client ' ' $last_name;
  5574.         }
  5575.         if($name_client == ''){
  5576.             $name_client =  $username;
  5577.         }
  5578.         return $name_client;
  5579.     }
  5580.     private function setting($token$chat_id$group_id$cq_data = array(), $message_id null) {
  5581.         $basePath $this->getParameter('kernel.project_dir');
  5582.         $is_group_chat $this->getParameter('app.chat.is_group');
  5583.         $sendMessage false;
  5584.         $action null;
  5585.         $p_group null;
  5586.         if(count($cq_data) > 0){
  5587.             $action = (isset($cq_data['action']) ? $cq_data['action'] : null);
  5588.             $p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
  5589.             if($action == '' || $action == "null" || $action == null){
  5590.                 $action null;
  5591.             }
  5592.         }
  5593.         if(count($cq_data) > && $action != null){
  5594.             $action = (isset($cq_data['action']) ? $cq_data['action'] : null);
  5595.             $p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
  5596.             $em $this->getDoctrine()->getManager();
  5597.             if($is_group_chat === true && $p_group != '' && $p_group != null){
  5598.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  5599.                 if($groupObj){
  5600.                     $chat_id $groupObj->getChatId();
  5601.                 }
  5602.             }
  5603.             if($action == 'list'){
  5604.                 $reply 'Типов группы для выбора пока нет.';
  5605.                 $type_groups $this->getDoctrine()
  5606.                     ->getRepository(TypeGroup::class)
  5607.                     ->createQueryBuilder('tg')
  5608.                     ->select('tg.id, tg.title')
  5609.                     ->getQuery()
  5610.                     ->getArrayResult();
  5611.                 $buttons = array();
  5612.                 if(count($type_groups) > 0){
  5613.                     $reply 'Выберите тип группы из списка.';
  5614.                     foreach ($type_groups as $type_group){
  5615.                         $buttons[][] = array(
  5616.                             'text' => $type_group['title'],
  5617.                             'callback_data'=> json_encode(array('action' => "add"'command' => "setting"'id' => $type_group['id'], "group" => $p_group))
  5618.                         );
  5619.                     }
  5620.                     $buttons[][] = array(
  5621.                         'text'=>'Назад',
  5622.                         'callback_data'=> json_encode(array('action' => "null"'command' => "setting""group" => $p_group))
  5623.                     );
  5624.                 }
  5625.                 $keyboard $buttons;
  5626.                 if(count($keyboard) > 0){
  5627.                     $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5628.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5629.                 } else {
  5630.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5631.                 }
  5632.             } elseif($action == 'add'){
  5633.                 $reply 'Не удалось добавить тип группы к групповому чату. Попробуйте повторить попытку позже.';
  5634.                 $keyboard = array();
  5635.                 $groupObj false;
  5636.                 if(isset($cq_data['id']) && isset($cq_data['group'])){
  5637.                     if($cq_data['id'] != '' && $cq_data['id'] != null && $cq_data['group'] != '' && $cq_data['group'] != null){
  5638.                         $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
  5639.                         $type_group $this->getDoctrine()->getRepository(TypeGroup::class)->findOneBy(array('id' => $cq_data['id']));
  5640.                         if($groupObj && $type_group){
  5641.                             $groupObj->setTypeGroup($type_group);
  5642.                             $em->persist($groupObj);
  5643.                             $em->flush();
  5644.                             $reply 'Тип группы «'  $type_group->getTitle() . '» успешно добавлен к групповому чату.';
  5645.                             $keyboard = array(
  5646.                                 array(
  5647.                                     array(
  5648.                                         'text'=>'Новый тип группы',
  5649.                                         'callback_data'=> json_encode(array('action' => "list"'command' => "setting""group" => ($groupObj $groupObj->getId() : null)))
  5650.                                     ),
  5651.                                     array(
  5652.                                         'text'=>'Удалить тип группы',
  5653.                                         'callback_data'=> json_encode(array('action' => "rem"'command' => "setting""group" => ($groupObj $groupObj->getId() : null)))
  5654.                                     ),
  5655.                                     array(
  5656.                                         'text'=>'Назад',
  5657.                                         'callback_data'=> json_encode(array('action' => "delete"'command' => "setting"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  5658.                                     )
  5659.                                 )
  5660.                             );
  5661.                         }
  5662.                     }
  5663.                 }
  5664.                 if(count($keyboard) > 0){
  5665.                     $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5666.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5667.                     $resp json_decode($sendMessagetrue);
  5668.                     if(isset($resp['result']['message_id']) && $groupObj){
  5669.                         file_put_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt'$resp['result']['message_id']);
  5670.                     }
  5671.                 } else {
  5672.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5673.                 }
  5674.             } elseif($action == 'rem'){
  5675.                 $reply 'Не удалось удалить тип группы у данного группового чата.';
  5676.                 if($cq_data['group'] != '' && $cq_data['group'] != null){
  5677.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
  5678.                     $groupObj->setTypeGroup(null);
  5679.                     $em->persist($groupObj);
  5680.                     $em->flush();
  5681.                     $reply 'Тип группы у данного группового чата успешно удален.';
  5682.                     $keyboard = array(
  5683.                         array(
  5684.                             array(
  5685.                                 'text'=>'Добавить тип группы',
  5686.                                 'callback_data'=> json_encode(array('action' => "list"'command' => "setting""group" => ($groupObj $groupObj->getId() : null)))
  5687.                             )
  5688.                         )
  5689.                     );
  5690.                 }
  5691.                 if(count($keyboard) > 0){
  5692.                     $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5693.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5694.                 } else {
  5695.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5696.                 }
  5697.             } elseif($action == 'delete') {
  5698.                 $mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
  5699.                 if($mes_id != '' && $mes_id != null){
  5700.                     $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $chat_id'message_id' => $mes_id]);
  5701.                 }
  5702.                 if($cq_data['group'] != '' && $cq_data['group'] != null){
  5703.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
  5704.                     if($groupObj){
  5705.                         if(file_exists($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt')){
  5706.                             $mes_id file_get_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt');
  5707.                             if($mes_id != '' && $mes_id != null){
  5708.                                 $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $chat_id'message_id' => $mes_id]);
  5709.                                 $resp json_decode($deleteMessagetrue);
  5710.                                 if(isset($resp['result'])){
  5711.                                     if($resp['result'] == true){
  5712.                                         unlink($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt');
  5713.                                     }
  5714.                                 }
  5715.                             }
  5716.                         }
  5717.                     }
  5718.                 }
  5719.             }
  5720.         } else {
  5721.             $groupObj false;
  5722.             if($group_id != '' && $group_id != null){
  5723.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  5724.             }
  5725.             if(!$groupObj && $p_group != null && $p_group != ''){
  5726.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  5727.             }
  5728.             if($is_group_chat === true && $groupObj){
  5729.                 $chat_id $groupObj->getChatId();
  5730.             }
  5731.             $reply 'У данной группы пока не выбран тип группы. Можете добавить тип группы.';
  5732.             $name_type_group null;
  5733.             $no_keyboard false;
  5734.             if($groupObj){
  5735.                 if($groupObj->getTypeGroup()){
  5736.                     $reply 'У данной группы выбран тип группы «' $groupObj->getTypeGroup()->getTitle() . '». Можете поменять на другой или удалить.';
  5737.                     $name_type_group $groupObj->getTypeGroup()->getTitle();
  5738.                 }
  5739.             } else {
  5740.                 $no_keyboard true;
  5741.                 $reply 'Отредактировать тип группы можно только из группы. Пожалуйста повторите данную команду в нужно группе.';
  5742.             }
  5743.             $reply_markup = array();
  5744.             if($no_keyboard === false){
  5745.                 $keyboard = array(
  5746.                     array(
  5747.                         array(
  5748.                             'text'=> ($name_type_group != null 'Новый тип группы' 'Добавить тип группы'),
  5749.                             'callback_data'=> json_encode(array('action' => "list"'command' => "setting""group" => ($groupObj $groupObj->getId() : null)))
  5750.                         ),
  5751.                         array(
  5752.                             'text'=>'Удалить тип группы',
  5753.                             'callback_data'=> json_encode(array('action' => "rem"'command' => "setting""group" => ($groupObj $groupObj->getId() : null)))
  5754.                         ),
  5755.                         array(
  5756.                             'text'=>'Назад',
  5757.                             'callback_data'=> json_encode(array('action' => "delete"'command' => "setting"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  5758.                         )
  5759.                     )
  5760.                 );
  5761.                 $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5762.                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5763.                 $resp json_decode($sendMessagetrue);
  5764.                 if(isset($resp['result']['message_id']) && $groupObj){
  5765.                     file_put_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt'$resp['result']['message_id']);
  5766.                 }
  5767.             } else {
  5768.                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5769.             }
  5770.         }
  5771.         if($is_group_chat === true){
  5772.             $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
  5773.             $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'setting'));
  5774.             $this->addLogMessageBot($bot$command$sendMessage);
  5775.         }
  5776.     }
  5777.     private function updateClient($chat_id$typeof$data){
  5778.         $em $this->getDoctrine()->getManager();
  5779.         $client false;
  5780.         if(count($data) > && $chat_id != null && $chat_id != ''){
  5781.             $client $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  5782.             if(!$client){
  5783.                 $newClient = new Client();
  5784.                 $newClient->setChatId($chat_id);
  5785.                 if($typeof == 'private'){
  5786.                     $newClient->setFirstName((isset($data['first_name']) ? $data['first_name'] : null));
  5787.                     $newClient->setLastName((isset($data['last_name']) ? $data['last_name'] : null));
  5788.                     $newClient->setUsername((isset($data['username']) ? $data['username'] : null));
  5789.                     $role $this->getDoctrine()->getRepository(Role::class)->findOneBy(array('typeof' => 'employee'));
  5790.                     if($role){
  5791.                         $newClient->setRole($role);
  5792.                     }
  5793.                     $newClient->setBalance(0);
  5794.                 } else {
  5795.                     $newClient->setFirstName((isset($data['title']) ? $data['title'] : null));
  5796.                     $newClient->setBalance(0);
  5797.                 }
  5798.                 $newClient->setTypeof($typeof);
  5799.                 $newClient->setIsActive(1);
  5800.                 $em->persist($newClient);
  5801.                 $em->flush();
  5802.                 $client $newClient;
  5803.             } else {
  5804.                 if($typeof == 'private'){
  5805.                     if(isset($data['first_name'])){
  5806.                         if($data['first_name'] != $client->getFirstName()){
  5807.                             $client->setFirstName($data['first_name']);
  5808.                         }
  5809.                     }
  5810.                     if(isset($data['last_name'])){
  5811.                         if($data['last_name'] != $client->getLastName()){
  5812.                             $client->setLastName($data['last_name']);
  5813.                         }
  5814.                     }
  5815.                     if(isset($data['username'])){
  5816.                         if($data['username'] != $client->getUsername()){
  5817.                             $client->setUsername($data['username']);
  5818.                         }
  5819.                     }
  5820.                     if(!$client->getRole()){
  5821.                         $role $this->getDoctrine()->getRepository(Role::class)->findOneBy(array('typeof' => 'employee'));
  5822.                         if($role){
  5823.                             $client->setRole($role);
  5824.                         }
  5825.                     }
  5826.                 } else {
  5827.                     if(isset($data['title'])){
  5828.                         if($data['title'] != $client->getFirstName()){
  5829.                             $client->setFirstName($data['title']);
  5830.                         }
  5831.                     }
  5832.                 }
  5833.                 if($typeof != $client->getTypeof()){
  5834.                     $client->setTypeof($typeof);
  5835.                 }
  5836.                 $em->persist($client);
  5837.                 $em->flush();
  5838.             }
  5839.         }
  5840.         return $client;
  5841.     }
  5842.     private function getCurClient($chat_id$typeof$from_data$chat_data){
  5843.         $em $this->getDoctrine()->getManager();
  5844.         $client false;
  5845.         if(count($from_data) > && $chat_id != null && $chat_id != ''){
  5846.             $tmp_typeof $typeof;
  5847.             if($typeof == 'supergroup' || $typeof == 'group'){
  5848.                 $tmp_typeof 'private';
  5849.             }
  5850.             $client $this->updateClient($chat_id$tmp_typeof$from_data);
  5851.         }
  5852.         if(count($chat_data) > && $chat_id != null && $chat_id != '' && ($typeof == 'supergroup' || $typeof == 'group')){
  5853.             $tmp_chat_id $chat_id;
  5854.             if(isset($chat_data['id'])){
  5855.                 $tmp_chat_id $chat_data['id'];
  5856.             }
  5857.             $client $this->updateClient($tmp_chat_id$typeof$chat_data);
  5858.         }
  5859.         return $client;
  5860.     }
  5861.     private function genReport($report false){
  5862.         $basePath $this->getParameter('kernel.project_dir');
  5863.         $date_with null;
  5864.         $date_by null;
  5865.         $client_group_id null;
  5866.         if($report){
  5867.             $date_with_d $report->getDateWith();
  5868.             if($date_with_d != '' && $date_with_d != null){
  5869.                 $date_with_dates = (array) $date_with_d;
  5870.                 if(isset($date_with_dates['date'])){
  5871.                     $date_with $date_with_dates['date'];
  5872.                 }
  5873.             }
  5874.             $date_by_d $report->getDateBy();
  5875.             if($date_by_d != '' && $date_by_d != null){
  5876.                 $date_by_dates = (array) $date_by_d;
  5877.                 if(isset($date_by_dates['date'])){
  5878.                     $date_by $date_by_dates['date'];
  5879.                 }
  5880.             }
  5881.             if($report->getClientGroup()){
  5882.                 $client_group_id $report->getClientGroup()->getId();
  5883.             }
  5884.         }
  5885.         $transactions_q $this->getDoctrine()
  5886.             ->getRepository(Transaction::class)
  5887.             ->createQueryBuilder('tr')
  5888.             ->select('tr.id, tr.amount, tr.typeof, tr.comment, tr.note, tr.date, c1.first_name AS f_first_name, c1.last_name AS f_last_name, c1.username AS f_username, c2.first_name AS t_first_name, c2.last_name AS t_last_name, c2.username AS t_username, c3.first_name AS s_first_name, c3.last_name AS s_last_name, c3.username AS s_username, o.name AS office_name, o.number AS office_number')
  5889.             ->leftJoin(Client::class, 'c1''WITH''tr.from_group = c1.id')
  5890.             ->leftJoin(Client::class, 'c2''WITH''tr.to_group = c2.id')
  5891.             ->leftJoin(Client::class, 'c3''WITH''tr.sender = c3.id')
  5892.             ->leftJoin(Office::class, 'o''WITH''tr.office = o.id')
  5893.             //->where('tr.amount != 0')
  5894.         ;
  5895.         if($client_group_id != null && $client_group_id != ''){
  5896.             $transactions_q->andWhere('tr.recipient = ' $client_group_id);
  5897.             if($date_with != '' && $date_with != null){
  5898.                 $transactions_q->andWhere('tr.date >= :date_with')
  5899.                     ->setParameter('date_with'$date_with);
  5900.             }
  5901.             /*
  5902.             $transactions_q->andWhere('tr.from_group = ' . $client_group_id);
  5903.             if($date_with != '' && $date_with != null){
  5904.                 $transactions_q->andWhere('tr.date >= :date_with')
  5905.                     ->setParameter('date_with', $date_with);
  5906.             }
  5907.             if($date_by != '' && $date_by != null){
  5908.                 $transactions_q->andWhere('tr.date <= :date_by')
  5909.                     ->setParameter('date_by', $date_by);
  5910.             }
  5911.             $transactions_q->orWhere('tr.to_group = ' . $client_group_id);
  5912.             if($date_with != '' && $date_with != null){
  5913.                 $transactions_q->andWhere('tr.date >= :date_with')
  5914.                     ->setParameter('date_with', $date_with);
  5915.             }
  5916.             if($date_by != '' && $date_by != null){
  5917.                 $transactions_q->andWhere('tr.date <= :date_by')
  5918.                     ->setParameter('date_by', $date_by);
  5919.             }
  5920.             */
  5921.         } else {
  5922.             if($date_with != '' && $date_with != null){
  5923.                 $transactions_q->andWhere('tr.date >= :date_with')
  5924.                     ->setParameter('date_with'$date_with);
  5925.             }
  5926.             if($date_by != '' && $date_by != null){
  5927.                 $transactions_q->andWhere('tr.date <= :date_by')
  5928.                     ->setParameter('date_by'$date_by);
  5929.             }
  5930.         }
  5931.         $transactions_q->orderBy('tr.date''ASC');
  5932.         $transactions $transactions_q->getQuery()->getArrayResult();
  5933.         $types = array(
  5934.             'income' => 'Начисление',
  5935.             'expense' => 'Списание'
  5936.         );
  5937.         $file '';
  5938.         if(count($transactions) > 0){
  5939.             foreach ($transactions as $key => $item){
  5940.                 $transactions[$key]['from_name'] = $this->nameClient($item['f_first_name'], $item['f_last_name'], $item['f_username']);
  5941.                 $transactions[$key]['to_name'] = $this->nameClient($item['t_first_name'], $item['t_last_name'], $item['t_username']);
  5942.                 $transactions[$key]['sender'] = $this->nameClient($item['s_first_name'], $item['s_last_name'], $item['s_username']);
  5943.                 $date '';
  5944.                 $dates = (array)$item['date'];
  5945.                 if(isset($dates['date'])){
  5946.                     $date date("d.m.Y H:i"strtotime($dates['date']));
  5947.                 }
  5948.                 $opt "";
  5949.                 if($item['typeof'] == 'income'){
  5950.                     $opt "+";
  5951.                 }
  5952.                 //$transactions[$key]['amount'] = $opt . str_replace(',00', '', number_format(($item['amount'] / 100), 2, ',', ' '));
  5953.                 $transactions[$key]['amount'] = str_replace(',00'''number_format(($item['amount'] / 100), 2','''));
  5954.                 $transactions[$key]['type'] = $item['typeof'];
  5955.                 $transactions[$key]['typeof'] = (isset($types[$item['typeof']]) ? $types[$item['typeof']] : '');
  5956.                 //$transactions[$key]['typeof'] = ($item['note'] != '' && $item['note'] != null ? $item['note'] : (isset($types[$item['typeof']]) ? $types[$item['typeof']] : ''));
  5957.                 $transactions[$key]['date'] = $date;
  5958.                 unset($transactions[$key]['f_first_name'], $transactions[$key]['f_last_name'], $transactions[$key]['f_username'], $transactions[$key]['t_first_name'], $transactions[$key]['t_last_name'], $transactions[$key]['t_username']);
  5959.             }
  5960.             //$date_with = '2022-04-01 15:20:00';
  5961.             //$date_by = '2022-04-11 10:00:00';
  5962.             $file MainController::genExcel($transactions$basePath, ($date_with != '' && $date_with != null ? (MainController::rusDate(date("Y-m-d H:i:s"strtotime($date_with)), 'ru'truefalsetrue)) : null), ($date_by != '' && $date_by != null ? (MainController::rusDate(date("Y-m-d H:i:s"strtotime($date_by)), 'ru'truefalsetrue)) : null));
  5963.         }
  5964.         return $file;
  5965.     }
  5966.     public static function genExcel($data$basePath$date_with null$date_by null){
  5967.         $styleArrayTopBold = array(
  5968.             'font' => array(
  5969.                 'bold' => true,
  5970.                 'size' => 12
  5971.             )
  5972.         );
  5973.         $styleArrayTop = array(
  5974.             'font' => array(
  5975.                 'size' => 11
  5976.             )
  5977.         );
  5978.         $styleArrayBold = array(
  5979.             'font' => array(
  5980.                 'bold' => true
  5981.             )
  5982.         );
  5983.         $styleArrayBorderMinSize = array(
  5984.             'borders' => array(
  5985.                 'outline' => array(
  5986.                     'style' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
  5987.                     'color' => array('argb' => '000000'),
  5988.                 ),
  5989.             ),
  5990.             'font' => array(
  5991.                 'size' => 10
  5992.             )
  5993.         );
  5994.         //$PHPExcel = new \PHPExcel();
  5995.         $PHPExcel = new Spreadsheet();
  5996.         $PHPExcel->getDefaultStyle()->getFont()->setName('Calibri')->setSize(11);
  5997.         $PHPExcel->getDefaultStyle()->getAlignment()->setWrapText(true);
  5998.         $PHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  5999.         $PHPExcel->createSheet(0);
  6000.         $sheet $PHPExcel->getSheet(0);
  6001.         $PHPExcel->setActiveSheetIndex(0);
  6002.         $sheet_title 'Отчет по операциям';
  6003.         $sheet->setTitle($sheet_title);
  6004.         $title_report 'Отчет по финансовым операциям от ' MainController::rusDate(date("Y-m-d H:i:s"), 'ru'truefalsetrue);
  6005.         $sheet->mergeCells('A1:C1');
  6006.         $sheet->mergeCells('A2:C2');
  6007.         $sheet->getStyleByColumnAndRow(01)->applyFromArray($styleArrayTop);
  6008.         $sheet->getStyleByColumnAndRow(02)->applyFromArray($styleArrayTop);
  6009.         $sheet
  6010.             ->getStyleByColumnAndRow(01)
  6011.             ->getAlignment()
  6012.             ->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER)
  6013.         ;
  6014.         $sheet
  6015.             ->getStyleByColumnAndRow(02)
  6016.             ->getAlignment()
  6017.             ->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER)
  6018.         ;
  6019.         $n_row 3;
  6020.         foreach (array('A') as $symbol){
  6021.             $sheet->getColumnDimension($symbol)->setWidth(5);
  6022.         }
  6023.         foreach (array('B') as $symbol){
  6024.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6025.         }
  6026.         foreach (array('C') as $symbol){
  6027.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6028.         }
  6029.         foreach (array('D') as $symbol){
  6030.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6031.         }
  6032.         foreach (array('E') as $symbol){
  6033.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6034.         }
  6035.         foreach (array('F') as $symbol){
  6036.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6037.         }
  6038.         foreach (array('G') as $symbol){
  6039.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6040.         }
  6041.         foreach (array('H') as $symbol){
  6042.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6043.         }
  6044.         foreach (array('I') as $symbol){
  6045.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6046.         }
  6047.         foreach (array('J') as $symbol){
  6048.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6049.         }
  6050.         $sheet->mergeCells('A3:J3');
  6051.         $sheet->getCellByColumnAndRow(1$n_row)->setValue($title_report);
  6052.         $sheet->getStyleByColumnAndRow(1$n_row)->applyFromArray($styleArrayTopBold);
  6053.         $sheet
  6054.             ->getStyleByColumnAndRow(1$n_row)
  6055.             ->getAlignment()
  6056.             ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)
  6057.         ;
  6058.         if(($date_with != '' && $date_with != null) || ($date_by != '' && $date_by != null)){
  6059.             $n_row += 2;
  6060.             $sheet->mergeCells('A5:J5');
  6061.             $sheet->getCellByColumnAndRow(1$n_row)->setValue('за период c ' $date_with ' по ' $date_by);
  6062.             $sheet->getStyleByColumnAndRow(1$n_row)->applyFromArray($styleArrayTopBold);
  6063.             $sheet
  6064.                 ->getStyleByColumnAndRow(1$n_row)
  6065.                 ->getAlignment()
  6066.                 ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)
  6067.             ;
  6068.         }
  6069.         $n_row += 2;
  6070.         if(count($data) > 0){
  6071.             $arr_columns = array('A''B''C''D''E''F''G''H''I''J');
  6072.             foreach ($arr_columns as $column){
  6073.                 $PHPExcel->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
  6074.             }
  6075. //                $n_row = 1;
  6076.             $sheet->getCellByColumnAndRow(1$n_row)->setValue('№ п/п');
  6077.             $sheet->getCellByColumnAndRow(2$n_row)->setValue('Тип операции');
  6078.             $sheet->getCellByColumnAndRow(3$n_row)->setValue('Добавил');
  6079.             $sheet->getCellByColumnAndRow(4$n_row)->setValue('Дата операции');
  6080.             $sheet->getCellByColumnAndRow(5$n_row)->setValue('Сумма');
  6081.             //$sheet->getCellByColumnAndRow(6, $n_row)->setValue('Группа');
  6082.             $sheet->getCellByColumnAndRow(6$n_row)->setValue('Откуда');
  6083.             $sheet->getCellByColumnAndRow(7$n_row)->setValue('Куда');
  6084.             $sheet->getCellByColumnAndRow(8$n_row)->setValue('№ объекта');
  6085.             $sheet->getCellByColumnAndRow(9$n_row)->setValue('Объект');
  6086.             $sheet->getCellByColumnAndRow(10$n_row)->setValue('Коментарий');
  6087.             for($c 1$c <= 10$c++){
  6088.                 $sheet->getStyleByColumnAndRow($c$n_row)
  6089.                     ->applyFromArray($styleArrayBorderMinSize)
  6090.                     ->getAlignment()
  6091.                     ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)
  6092.                 ;
  6093.             }
  6094.             $sheet
  6095.                 ->getStyle('A' $n_row ':J' $n_row)
  6096.                 ->getFill()
  6097.                 ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  6098.                 ->getStartColor()
  6099.                 ->setRGB('C2E9F6')
  6100.             ;
  6101.             $n 1;
  6102.             foreach ($data as $item){
  6103.                 $n_row += 1;
  6104.                 $groupName '';
  6105.                 if($item['type'] == 'income'){
  6106.                     if($item['to_name'] != '' && $item['to_name'] != null){
  6107.                         $groupName $item['to_name'];
  6108.                     } else {
  6109.                         $groupName $item['from_name'];
  6110.                     }
  6111.                 } elseif($item['type'] == 'expense'){
  6112.                     if($item['from_name'] != '' && $item['from_name'] != null ){
  6113.                         $groupName $item['from_name'];
  6114.                     } else {
  6115.                         $groupName $item['to_name'];
  6116.                     }
  6117.                 }
  6118.                 $sheet->getCellByColumnAndRow(1$n_row)->setValue($n);
  6119.                 $sheet->getCellByColumnAndRow(2$n_row)->setValue($item['typeof']);
  6120.                 $sheet->getCellByColumnAndRow(3$n_row)->setValue($item['sender']);
  6121.                 $sheet->getCellByColumnAndRow(4$n_row)->setValue($item['date']);
  6122.                 $sheet->getCellByColumnAndRow(5$n_row)->setValue($item['amount']);
  6123.                 //$sheet->getCellByColumnAndRow(6, $n_row)->setValue($groupName);
  6124.                 $sheet->getCellByColumnAndRow(6$n_row)->setValue($item['from_name']);
  6125.                 $sheet->getCellByColumnAndRow(7$n_row)->setValue($item['to_name']);
  6126.                 $sheet->getCellByColumnAndRow(8$n_row)->setValue($item['office_number']);
  6127.                 $sheet->getCellByColumnAndRow(9$n_row)->setValue($item['office_name']);
  6128.                 $sheet->getCellByColumnAndRow(10$n_row)->setValue($item['comment']);
  6129.                 $n++;
  6130.                 for($c 1$c <= 10$c++){
  6131.                     $sheet->getStyleByColumnAndRow($c$n_row)->applyFromArray($styleArrayBorderMinSize);
  6132.                 }
  6133. //                $sheet
  6134. //                    ->getStyleByColumnAndRow(8, $n_row)
  6135. //                    ->getAlignment()
  6136. //                    ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)
  6137. //                    ->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER)
  6138. //                ;
  6139.             }
  6140.         }
  6141.         $PHPExcel->setActiveSheetIndex(0);
  6142.         $fileDir '/public/images/';
  6143.         if (!is_dir($basePath '/public/images/')) {
  6144.             mkdir($basePath '/public/images/');
  6145.         }
  6146.         if (!is_dir($basePath $fileDir)) {
  6147.             mkdir($basePath $fileDir);
  6148.         }
  6149.         $uuid ProjectUtilsController::generateUuid();
  6150.         $predir substr($uuid03);
  6151.         if (!is_dir($basePath $fileDir '/' $predir '/')) {
  6152.             mkdir($basePath $fileDir '/' $predir '/');
  6153.         }
  6154.         //$filename = $predir . '/' . $uuid . '.xlsx';
  6155.         $filename $predir '/' date("Y_m_d_H_i_s") . '_report.xlsx';
  6156.         //$filename = 'test.xlsx';
  6157.         $filepath $basePath $fileDir '/' $filename;
  6158.         //$objWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel2007');
  6159.         $objWriter \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($PHPExcel,  'Xlsx');
  6160.         $objWriter->save($filepath);
  6161.         return $filename;
  6162.     }
  6163.     private function sendEmail(MailerInterface $mailer$event$body_mail$theme_mail$locale 'ru'$recipient false$attach = array())
  6164.     {
  6165.         $mailerFrom $this->getParameter('app.mailer.from');
  6166.         $mail_template_q $this->getDoctrine()
  6167.             ->getRepository(MailTemplate::class)
  6168.             ->createQueryBuilder('mt')
  6169.             ->select('mt.id, mt.title, mt.body, mt.copy')
  6170.             ->where('mt.event = :event')
  6171.             ->setParameter('event'$event)
  6172.             ->getQuery()->getResult();
  6173.         $theme '';
  6174.         $body '';
  6175.         $mail_template = array();
  6176.         if(isset($mail_template_q[0])){
  6177.             $mail_template $mail_template_q[0];
  6178.             $theme $mail_template['title'];
  6179.             $body $mail_template['body'];
  6180.             if(count($body_mail) > 0){
  6181.                 foreach ($body_mail as $ket_b => $b_mail){
  6182.                     $body str_replace($ket_b$b_mail $body);
  6183.                 }
  6184.             }
  6185.             if(count($theme_mail) > 0){
  6186.                 foreach ($theme_mail as $ket_th => $th_mail){
  6187.                     $theme str_replace($ket_th$th_mail $theme);
  6188.                 }
  6189.             }
  6190.         }
  6191.         if($recipient === false){
  6192.             $recipient $this->getParameter('app.mailer.to');
  6193.         }
  6194.         $email = (new Email())
  6195.             ->from($mailerFrom)
  6196.             ->to($recipient)
  6197.             //->cc('max.linwa@gmail.com')
  6198.             //->addTo('igor@atmapro.ru')
  6199.             //->bcc('igor@atmapro.ru')
  6200.             //->replyTo('fabien@example.com')
  6201.             //->priority(Email::PRIORITY_HIGH)
  6202.             ->subject($theme)
  6203.             ->text('Sending emails is fun again!')
  6204.             ->html($body);
  6205.         if(count($mail_template) > 0){
  6206.             if($mail_template['copy'] != '' && $mail_template['copy'] != null){
  6207.                 $email->cc($mail_template['copy']);
  6208.             }
  6209.         }
  6210.         if(count($attach) > 0){
  6211.             foreach ($attach as $item){
  6212.                 $email->attachFromPath($item);
  6213.             }
  6214.         }
  6215.         
  6216.         $is_send false;
  6217.         try {
  6218.             $mailer->send($email);
  6219.             $is_send true;
  6220.         } catch (TransportExceptionInterface $e) {
  6221.             echo $e->getMessage();
  6222.             // некая ошибка предотвратила отправку письма; отобразить сообщение
  6223.             // об ошибке или попробовать отправить сообщение повторно
  6224.         }
  6225.         return $is_send;
  6226.     }
  6227.     public static function rusDate($date$lang 'ru'$time false$time_prefix false$with_year false)
  6228.     {
  6229.         if ($lang == 'ru') {
  6230.             $a = array('01' => 'января''02' => 'февраля''03' => 'марта''04' => 'апреля''05' => 'мая''06' => 'июня''07' => 'июля''08' => 'августа''09' => 'сентября''10' => 'октября''11' => 'ноября''12' => 'декабря',);
  6231.         } elseif ($lang == 'en') {
  6232.             $a = array('01' => 'January''02' => 'February''03' => 'March''04' => 'April''05' => 'May''06' => 'June''07' => 'July''08' => 'August''09' => 'September''10' => 'October''11' => 'November''12' => 'December');
  6233.         }
  6234.         $ex explode(' '$date);
  6235.         $timeex explode(':'$ex[1]);
  6236.         $ex explode('-'$ex[0]);
  6237.         $year = ($ex[0] != date('Y') ? ' ' $ex[0] : '');
  6238.         if ($with_year) {
  6239.             $year ', ' $ex[0];
  6240.         }
  6241.         return intval($ex[2]) . ' ' $a[$ex[1]] . $year . ($time ? ($time_prefix $time_prefix ' ') . $timeex[0] . ':' $timeex[1] : '');
  6242.     }
  6243.     #[Route('/user-create/'name'app_user_create')]
  6244.     public function userCreate(Request $requestUserPasswordEncoderInterface $encoder): Response
  6245.     {
  6246.         $em $this->getDoctrine()->getManager();
  6247.         $login $request->get('login');
  6248.         $password $request->get('password');
  6249.         if (!empty($login) && !empty($password)) {
  6250.             $user $this->getDoctrine()->getRepository(User::class)->findOneBy(['username' => $login]);
  6251.             if (!$user) {
  6252.                 $newUser = new User();
  6253.                 $newUser->setUsername($login);
  6254.                 $encoded $encoder->encodePassword($newUser$password);
  6255.                 $newUser->setPassword($encoded);
  6256.                 $newUser->setRoles(array('ROLE_ADMIN'));
  6257.                 $em->persist($newUser);
  6258.                 $em->flush();
  6259.                 echo 'Пользователь успешно создан';
  6260.             } else {
  6261.                 echo 'Пользователь уже есть';
  6262.             }
  6263.         } else {
  6264.             echo 'Не достаточно данных';
  6265.         }
  6266.         die();
  6267.     }
  6268.     public static function recalculateBalance($doctrine$ids = array())
  6269.     {
  6270.         $em $doctrine->getManager();
  6271.         $clients_qq $doctrine
  6272.             ->getRepository(Client::class)
  6273.             ->createQueryBuilder('cl')
  6274.             ->select('cl.id, cl.balance')
  6275.             ->where('cl.typeof != :typeof')
  6276.             ->setParameter('typeof'"private");
  6277.         if(count($ids) > 0){
  6278.             $clients_qq->andWhere('tr.id IN (' implode(","$ids) . ')');
  6279.         }
  6280.         $clients_q $clients_qq->getQuery()->getResult();
  6281.         if(count($clients_q) > 0){
  6282.             foreach ($clients_q as $item_client){
  6283.                 $transaction_q $doctrine
  6284.                     ->getRepository(Transaction::class)
  6285.                     ->createQueryBuilder('tr')
  6286.                     ->select('tr.id, SUM(tr.amount) AS balance')
  6287.                     ->where('tr.recipient = ' $item_client['id'])
  6288.                     ->getQuery()->getResult();
  6289.                 if(count($transaction_q) == 1){
  6290.                     $transaction $transaction_q[0];
  6291.                     if($transaction['balance'] != $item_client['balance']){
  6292.                         //echo 'У клиента ' . $item_client['id'] . ' балансы не совпадают, фактический ' . $transaction['balance'] . ', по операциям ' . $item_client['balance'] . "\n";
  6293.                         $client $doctrine->getRepository(Client::class)->findOneBy(['id' => $item_client['id']]);
  6294.                         if($client){
  6295.                             $client->setBalance($transaction['balance']);
  6296.                             $em->persist($client);
  6297.                             $em->flush();
  6298.                             //echo 'У клиента ' . $client->getId() . ' был изменен баланс на ' . $transaction['balance'] . "\n";
  6299.                         }
  6300.                     } else {
  6301.                         //echo 'У клиента ' . $item_client['id'] . ' баланс правильный' . "\n";
  6302.                     }
  6303.                 }
  6304.             }
  6305.         }
  6306.         //print_r($clients_q);
  6307.     }
  6308.     private function actualBalance($client){
  6309.         $balance false;
  6310.         if($client){
  6311.             $client_id null;
  6312.             if(is_object($client)){
  6313.                 $client_id $client->getId();
  6314.                 if($client_id != '' && $client_id != null){
  6315.                     $transaction_q $this->getDoctrine()
  6316.                         ->getRepository(Transaction::class)
  6317.                         ->createQueryBuilder('tr')
  6318.                         ->select('tr.id, SUM(tr.amount) AS balance')
  6319.                         ->where('tr.recipient = ' $client_id)
  6320.                         ->getQuery()->getResult();
  6321.                     if(isset($transaction_q[0]['balance'])){
  6322.                         $balance $transaction_q[0]['balance'];
  6323.                     }
  6324.                 }
  6325.             }
  6326.         }
  6327.         return $balance;
  6328.     }
  6329. }