src/Controller/MainController.php line 45

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. class MainController extends AbstractController
  28. {
  29.     private $em;
  30.     private $kernel;
  31.     private $mailer;
  32.     public function __construct(EntityManagerInterface $emKernel $kernelMailerInterface $mailer){
  33.         $this->em $em;
  34.         $this->kernel $kernel;
  35.         $this->mailer $mailer;
  36.     }
  37.     /**
  38.      * @Route("/main", name="app_main")
  39.      */
  40.     public function index(): Response
  41.     {
  42.         return $this->render('main/index.html.twig', [
  43.             'controller_name' => 'MainController',
  44.         ]);
  45.     }
  46.     #[Route('/api/test/'name'app_api_test')]
  47.     public function test(Request $requestMailerInterface $mailer): Response
  48.     {
  49.         $token '452751952:AAFU-nLuoxwNlH9ugqwsTfxa253UvqhvHr4';
  50.         $chat_id '-1001982917129';
  51.         $groupObj $this->getDoctrine()->getRepository(Client::class)->find(2);
  52.         $draftObj $this->getDoctrine()->getRepository(Draft::class)->find(142);
  53.         $create_transaction $this->sendMailNonCashCheque($token$chat_id$groupObj$draftObj);
  54.         die();
  55.         $bot $this->getDoctrine()->getRepository(Bot::class)->find(1);
  56.         if($bot){
  57.             $token $bot->getToken();
  58.             $getChat ProjectUtilsController::requestToBot($token'getChat', ['chat_id' => '-4225857944']);
  59.             echo $getChat;
  60.         }
  61.         die();
  62. //        echo $this->getParameter('app.mailer.to.transaction');
  63. //        die();
  64.         $event 'newTransaction';
  65.         //$recipient = 'igor@atmapro.ru';
  66.         $recipient $this->getParameter('app.mailer.to.transaction');
  67.         $title_mail = array(
  68.             '#amount#' => '3000',
  69.             '#source#' => 'Ботская 2',
  70.             '#type#' => 'начисление ЗП'
  71.         );
  72.         $body_mail = array(
  73.             '#office#' => '1111 Бургерная',
  74.             '#type#' => 'начисление ЗП',
  75.             '#amount#' => '3000',
  76.             '#date#' => '27.06.2024',
  77.             '#source#' => 'Ботская 2',
  78.             '#comment#' => 'начисление зп за день',
  79.             '#cheque#' => 'нет'
  80.         );
  81.         $m $this->sendEmail($mailer$event$body_mail$title_mail'ru'$recipient, array());
  82.         echo $m;
  83.         die();
  84.         $basePath $this->getParameter('kernel.project_dir');
  85.         $token '452751952:AAFU-nLuoxwNlH9ugqwsTfxa253UvqhvHr4 ';
  86.         $draft $this->getDoctrine()->getRepository(Draft::class)->find(34);
  87.         $chat_id '414013565';
  88.         $group '-1001982917129';
  89.         $this->createTransaction($token$chat_id$group$draft);
  90.         die();
  91.         $message_id 3407;
  92.         $result json_decode(file_get_contents($basePath '/var/log/chatDev.txt'), true);
  93.         $text = (isset($result["message"]["text"]) ? $result["message"]["text"] : null);
  94.         $chat_id = (isset($result['message']['from']['id']) ? $result['message']['from']['id'] : null);
  95.         $typeof = (isset($result["message"]["chat"]["type"]) ? $result["message"]["chat"]["type"] : null);
  96.         $group_id = (isset($result['message']['chat']['id']) && ($typeof == 'group' || $typeof == 'supergroup') ? $result['message']['chat']['id'] : null);
  97.         if($text == '/clear'){
  98.             $this->clear($token$chat_id$group_id$message_id);
  99.             die();
  100.         }
  101.         die();
  102.         $newReport $this->getDoctrine()->getRepository(Report::class)->find(48);
  103.         $file $this->genReport($newReport);
  104.         echo $file;
  105.         die();
  106.         $token '452751952:AAFU-nLuoxwNlH9ugqwsTfxa253UvqhvHr4';
  107.         $deleteMyCommands ProjectUtilsController::requestToBot($token'deleteMyCommands', []);
  108.         echo $deleteMyCommands;
  109.         die();
  110.         $setMyCommands ProjectUtilsController::requestToBot($token'setMyCommands', ['commands' => json_encode([['command' => 'help''description' => 'Список комманд'], ['command' => 'prev''description' => 'Список комманд'], ['command' => 'next''description' => 'Список комманд'], ['command' => 'top''description' => 'Список комманд'], ['command' => 'bottom''description' => 'Список комманд']])]);
  111.         echo $setMyCommands;
  112.         $getMyCommands ProjectUtilsController::requestToBot($token'getMyCommands', []);
  113.         echo $getMyCommands;
  114.         die();
  115.         $basePath $this->getParameter('kernel.project_dir');
  116.         $fileDir '/public/images/';
  117.         // echo $basePath;
  118.         // die();
  119.         $body_mail = array(
  120.             '#app#' => $this->getParameter('app.name'),
  121.             '#logo#' => $this->getParameter('app.logo'),
  122.             '#date_with#' => '',
  123.             '#date_by#' => '',
  124.         );
  125.         $title_mail = array();
  126.         $file '0eb/2022_04_22_11_06_53_report.xlsx';
  127.         $attach = array();
  128.         $filepath $basePath $fileDir $file;
  129.         if(file_exists($filepath)){
  130.             $attach[] = $basePath $fileDir $file;
  131.         }
  132.         //отправка письма
  133.         $email 'igor@atmapro.ru';
  134.         $sendMail $this->sendEmail($this->mailer,'newReportPeriod'$body_mail$title_mail'ru'$email$attach);
  135.         //MainController::recalculateBalance($this->getDoctrine());
  136.         die();
  137.         $pay = array
  138.         (
  139.             'update_id' => 866792455,
  140.             'message' => array
  141.             (
  142.                 'message_id' => 834,
  143.                 'from' => array
  144.                 (
  145.                     'id' => 1406913295,
  146.                     'is_bot' => 0,
  147.                     'first_name' => 'Max',
  148.                     'last_name' => 'Voitov',
  149.                     'username' => 'MaxIngenieur',
  150.                     'language_code' => 'ru'
  151.                 ),
  152.                 'chat' => array
  153.                 (
  154.                     'id' => -655101877,
  155.                     'title' => 'Тест Нал Игорь',
  156.                     'type' => 'group',
  157.                     'all_members_are_administrators' => 1
  158.                 ),
  159.                 'date' => 1651841438,
  160.                 'text' => '/pay',
  161.                 'entities' => array
  162.                 (
  163.                     => array
  164.                     (
  165.                         'offset' => 0,
  166.                         'length' => 4,
  167.                         'type' => 'bot_command'
  168.                     )
  169.                 )
  170.             )
  171.         );
  172.         $report $this->getDoctrine()->getRepository(Report::class)->find(36);
  173.         echo $this->genReport($report);
  174.         die();
  175.         $bot $this->getDoctrine()->getRepository(Bot::class)->find(1);
  176.         //$this->deleteLogMessage($bot, '-1001444351695', 6);
  177.         $this->deleteLogMessage($bot'-1001444351695');
  178.         die();
  179.         $chat_id '-1001444351695';
  180.         $token '452751952:AAFU-nLuoxwNlH9ugqwsTfxa253UvqhvHr4';
  181.         $message_id '906';
  182.         $bot_id 1;
  183.         $command_id 1;
  184.         $this->deleteLogMessage($bot_id$chat_id$command_id);
  185.         die();
  186.         echo $this->addLogMessage($bot_id$chat_id$message_id);
  187.         //$deleteMessage = ProjectUtilsController::requestToBot($token, 'deleteMessage', ['chat_id' => $chat_id, 'message_id' => $message_id]);
  188.         //echo $deleteMessage;
  189.         die();
  190.     }
  191.     #[Route('/api/bot/{id}/'name'app_api_bot')]
  192.     public function bot(Request $request): Response
  193.     {
  194.         $basePath $this->getParameter('kernel.project_dir');
  195.         $id $request->get('id');
  196.         $is_group_chat $this->getParameter('app.chat.is_group');
  197.         $time_interval $this->getParameter('app.time.interval');
  198.         $result json_decode($request->getContent(), true);
  199.         if($request->get('dev') != '' && $request->get('dev') != null){
  200.             if(file_exists($basePath '/var/log/chatDev.txt')){
  201.                 $result json_decode(file_get_contents($basePath '/var/log/chatDev.txt'), true);
  202.             }
  203.         } else {
  204.             file_put_contents($basePath '/var/log/chatDev.txt'print_r($request->getContent(), true));
  205.         }
  206. //        file_put_contents($basePath . '/var/log/chatDev1.txt', print_r($result, true));
  207. //        print_r($result);
  208. //        die();
  209.         if($request->get('is_test') == '1'){
  210.             /*
  211.         $result = array
  212.         (
  213.             'update_id' => 866792513,
  214.             'message' => array
  215.             (
  216.                 'message_id' => 942,
  217.                 'from' => array
  218.                 (
  219.                     'id' => 1406913295,
  220.                     'is_bot' => 0,
  221.                     'first_name' => 'Max',
  222.                     'last_name' => 'Voitov',
  223.                     'username' => 'MaxIngenieur',
  224.                     'language_code' => 'ru'
  225.                 ),
  226.                 'chat' => array
  227.                 (
  228.                     'id' => -763088405,
  229.                     'title' => 'Тест ЗП Юлия',
  230.                     'type' => 'group',
  231.                     'all_members_are_administrators' => 1
  232.                 ),
  233.                 'date' => 1651847902,
  234.                 'text' => '/balance',
  235.                 'entities' => array
  236.                 (
  237.                     0 => array
  238.                     (
  239.                         'offset' => 0,
  240.                         'length' => 8,
  241.                         'type' => 'bot_command'
  242.                     )
  243.                 )
  244.             )
  245.         );
  246.               */
  247.             /*
  248.             $result = array(
  249.                 'update_id' => 145457792,
  250.                 'message' => array
  251.                 (
  252.                     'message_id' => 4099,
  253.                     'from'=> array
  254.                     (
  255.                         'id' => 414013565,
  256.                         'is_bot' => false,
  257.                         'first_name' => 'Igor',
  258.                         'last_name' => 'MrRedson',
  259.                         'language_code' => 'ru'
  260.                     ),
  261.                     'chat' => array
  262.                     (
  263.                         'id' => -1001444351695,
  264.                         'title' => 'ЗП Бот I',
  265.                         'type' => 'supergroup',
  266.                     ),
  267.                     'date' => 1733760426,
  268.                     'text' => 't100',
  269. //                    'entities' => [
  270. //                        0 => [
  271. //                            'offset' => 0,
  272. //                            'length' => 4,
  273. //                            'type' => 'bot_command'
  274. //                        ]
  275. //                     ]
  276.                 )
  277.             );
  278.             */
  279.             /*
  280.             $result = array(
  281.                 'update_id' => 145456044,
  282.                 'message' => array
  283.                 (
  284.                     'message_id' => 405,
  285.                     'from'=> array
  286.                     (
  287.                         'id' => 414013565,
  288.                         'is_bot' => false,
  289.                         'first_name' => 'Igor',
  290.                         'username' => 'MrRedson',
  291.                         'language_code' => 'ru'
  292.                     ),
  293.                     'chat' => array
  294.                     (
  295.                         'id' => -1001982917129,
  296.                         'title' => 'Нал Ботская 2',
  297.                         'type' => 'supergroup'
  298.                     ),
  299.                     'date' => 1719404053,
  300.                     'photo' => [
  301.                         [
  302.                             'file_id' => 'AgACAgIAAx0CdjDqCQACAZVmfAYVcer4gcTwfYczfRhj3meDGgACm98xG6Rc4Uu3TTnhA8WCwAEAAwIAA3MAAzUE',
  303.                             'file_unique_id' => 'AQADm98xG6Rc4Ut4',
  304.                             'file_size' => 574,
  305.                             'width' => 90,
  306.                             'height' => 22
  307.                         ],
  308.                         [
  309.                             'file_id' => 'AgACAgIAAx0CdjDqCQACAZVmfAYVcer4gcTwfYczfRhj3meDGgACm98xG6Rc4Uu3TTnhA8WCwAEAAwIAA20AAzUE',
  310.                             'file_unique_id' => 'AQADm98xG6Rc4Uty',
  311.                             'file_size' => 4711,
  312.                             'width' => 320,
  313.                             'height' => 80
  314.                         ],
  315.                         [
  316.                             'file_id' => 'AgACAgIAAx0CdjDqCQACAZVmfAYVcer4gcTwfYczfRhj3meDGgACm98xG6Rc4Uu3TTnhA8WCwAEAAwIAA3gAAzUE',
  317.                             'file_unique_id' => 'AQADm98xG6Rc4Ut9',
  318.                             'file_size' => 18943,
  319.                             'width' => 800,
  320.                             'height' => 199
  321.                         ],
  322.                         [
  323.                             'file_id' => 'AgACAgIAAx0CdjDqCQACAZVmfAYVcer4gcTwfYczfRhj3meDGgACm98xG6Rc4Uu3TTnhA8WCwAEAAwIAA3kAAzUE',
  324.                             'file_unique_id' => 'AQADm98xG6Rc4Ut-',
  325.                             'file_size' => 28849,
  326.                             'width' => 28849,
  327.                             'height' => 319
  328.                         ]
  329.                     ]
  330.                 )
  331.             );
  332.             */
  333.             /*
  334.             $result = array(
  335.                 'update_id' => 145457688,
  336.                 'callback_query' => [
  337.                     'id' => 1778174725879195884,
  338.                     'from'=> array
  339.                     (
  340.                         'id' => 414013565,
  341.                         'is_bot' => false,
  342.                         'first_name' => 'Igor',
  343.                         'username' => 'MrRedson',
  344.                         'language_code' => 'ru'
  345.                     ),
  346.                     'message' => array
  347.                     (
  348.                         'message_id' => 1238,
  349.                         'from'=> array
  350.                         (
  351.                             'id' => 452751952,
  352.                             'is_bot' => true,
  353.                             'first_name' => 'tatuin',
  354.                             'username' => 'SirTatuin_bot',
  355.                         ),
  356.                         'chat' => array
  357.                         (
  358.                             'id' => -1001982917129,
  359.                             'title' => 'Нал Бот I',
  360.                             'type' => 'group',
  361.                             //'all_members_are_administrators' => 1
  362.                         ),
  363.                         'date' => 1733240191,
  364.                         'text' => 'Выбрано «Расходы по Объекту». Выберите объект, по которому осуществляется расход.',
  365.                         'reply_markup' => [
  366.                             'inline_keyboard' => [
  367.                                 [
  368.                                     [
  369.                                         'text' => '27871. Тестовый',
  370.                                         'callback_data' => '{"action":"add_office","command":"bpay","id":1,"group":2}'
  371.                                     ]
  372.                                 ]
  373.                             ]
  374.                         ]
  375.                     ),
  376.                     'chat_instance' => -3430887582451155820,
  377.                     'data' => '{"action":"add_office","command":"bpay","id":1,"group":2}'
  378.                 ]
  379.             );
  380.             */
  381.             $r '{"update_id":145458295,"message":{"message_id":4490,"from":{"id":414013565,"is_bot":false,"first_name":"Igor","username":"MrRedson","language_code":"ru"},"chat":{"id":-1001444351695,"title":"\u0417\u041f \u0411\u043e\u0442 I Tatuin","type":"supergroup"},"date":1769446971,"text":"1"}}';
  382.             $result json_decode($rtrue);
  383. //            print_r($result);
  384. //            die();
  385.         }
  386.         $text = (isset($result["message"]["text"]) ? $result["message"]["text"] : null);
  387.         $chat_id = (isset($result['message']['from']['id']) ? $result['message']['from']['id'] : null);
  388.         $typeof = (isset($result["message"]["chat"]["type"]) ? $result["message"]["chat"]["type"] : null);
  389.         $group_id = (isset($result['message']['chat']['id']) && ($typeof == 'group' || $typeof == 'supergroup') ? $result['message']['chat']['id'] : null);
  390.         $group $typeof == 'group' || $typeof == 'supergroup' $group_id null;
  391.         $message_id = (isset($result["message"]["message_id"]) ? $result["message"]["message_id"] : null);
  392.         $callback_query = (isset($result["callback_query"]) ? $result["callback_query"] : array());
  393.         $callback_query_data = (isset($result["callback_query"]["data"]) ? $result["callback_query"]["data"] : null);
  394.         $photo = (isset($result["message"]["photo"]) ? $result["message"]["photo"] : []);
  395.         $caption = (isset($result["message"]["caption"]) ? $result["message"]["caption"] : null);
  396.         //file_put_contents($basePath . '/var/log/r_1.txt', print_r($result, true), FILE_APPEND);
  397.         $fileId null;
  398.         if(count($photo) > 0){
  399.             foreach ($photo as $key_ph => $itemPhoto){
  400.                 if($key_ph == count($photo) - 1){
  401.                     $fileId $itemPhoto['file_id'];
  402.                 }
  403.             }
  404.             if($caption != '' && $caption != ''){
  405.                 $text $caption;
  406.             }
  407.         }
  408.         if($message_id == null || $message_id == ''){
  409.             $message_id = (isset($callback_query["message"]["message_id"]) ? $callback_query["message"]["message_id"] : null);
  410.         }
  411.         //не пропускать двойную обрабоку сообщения
  412.         if($is_group_chat === true && $message_id != '' && $message_id != null && !($request->get('is_test') == '1')){
  413.             $chId $chat_id;
  414.             if($group != '' && $group != null){
  415.                 $chId $group;
  416.             }
  417.             $log_message $this->getDoctrine()
  418.                 ->getRepository(LogMessage::class)
  419.                 ->createQueryBuilder('lm')
  420.                 ->select('lm.id')
  421.                 ->where('lm.bot = :bot_id')
  422.                 ->andWhere('lm.message_id = :message_id')
  423.                 ->andWhere('lm.chat_id = :chat_id')
  424.                 ->setParameter('bot_id'$id)
  425.                 ->setParameter('message_id'$message_id)
  426.                 ->setParameter('chat_id'$chId)
  427.                 ->getQuery()->getArrayResult();
  428.             if(count($log_message) > 0){
  429.                 file_put_contents($basePath '/var/log/double.txt'print_r($resulttrue), FILE_APPEND);
  430.                 exit();
  431.             }
  432.         }
  433.         if(count($callback_query) > 0){
  434.             $chat_id = (isset($callback_query['message']['chat']['id']) ? $callback_query['message']['chat']['id'] : null);
  435.         }
  436.         $cq_data = array();
  437.         $thisCommand null;
  438.         if(ProjectUtilsController::isJSON($callback_query_data) === true){
  439.             $cq_data json_decode($callback_query_datatrue);
  440.             if(isset($cq_data['command'])){
  441.                 $thisCommand $cq_data['command'];
  442.             }
  443.         }
  444.         file_put_contents($basePath '/var/log/chat2.txt'print_r($resulttrue), FILE_APPEND);
  445.         file_put_contents($basePath '/var/log/callback1.txt'print_r($cq_datatrue), FILE_APPEND);
  446.         $token null;
  447.         $bot false;
  448.         if($id != null && $id != ''){
  449.             $bot $this->getDoctrine()->getRepository(Bot::class)->find($id);
  450.             $token $bot->getToken();
  451.         }
  452.         //очистка имени бота из команды <<<
  453.         if(strpos($text'@') !== false) {
  454.             $arr_t explode('@'$text);
  455.             if(count($arr_t) == 2){
  456.                 $nameBot $arr_t[count($arr_t) - 1];
  457.                 $text str_replace('@' $nameBot''$text);
  458.                 if(strpos($text'@' $nameBot) !== false) {
  459.                     $text str_replace('@' $nameBot''$text);
  460.                 }
  461.             }
  462.         }
  463.         //очистка имени бота из команды >>>
  464. //        $reply = 'Пришло ';
  465. //        $sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
  466. //        die();
  467.         $client $this->getCurClient($chat_id$typeof, (isset($result['message']['from']) ? $result['message']['from'] : array()), (isset($result['message']['chat']) ? $result['message']['chat'] : array()));
  468.         if(!empty($token) && !empty($chat_id)){
  469.             $command false;
  470.             if(count($cq_data) > 0){
  471.                 $this->resetExpected($client);
  472.                 if($thisCommand == 'setting'){
  473.                     $this->setting($token$chat_id$group_id$cq_data$message_id);
  474.                 } elseif($thisCommand == 'users'){
  475.                     $this->users($token$chat_id$group_id$cq_datafalsenull$message_id);
  476.                 } elseif($thisCommand == 'office'){
  477.                     $this->office($token$chat_id$group_id$cq_datafalsenull$message_id);
  478.                 } elseif($thisCommand == 'pay'){
  479.                     if($is_group_chat === true){
  480.                         $chat_id = (isset($callback_query['from']['id']) ? $callback_query['from']['id'] : null);
  481.                     }
  482.                     $this->pay($token$chat_id$group_id$cq_datafalsenull$message_id);
  483.                 } elseif($thisCommand == 'bpay'){
  484.                     if($is_group_chat === true){
  485.                         $chat_id = (isset($callback_query['from']['id']) ? $callback_query['from']['id'] : null);
  486.                     }
  487.                     $this->bpay($token$chat_id$group_id$cq_datafalsenull$message_id);
  488.                 } elseif($thisCommand == 'report'){
  489.                     $this->report($token$chat_id$group_id$cq_datafalsenull$message_id);
  490.                 }
  491.                 if($is_group_chat === true && $group_id != '' && $group_id != null){
  492.                     $commandObj false;
  493.                     if(!$command && $thisCommand != '' && $thisCommand != null){
  494.                         $commandObj $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => $thisCommand'is_active' => true));
  495.                     }
  496.                     $this->addLogMessage($bot$group_id$message_id$commandObj);
  497.                 }
  498.                 exit();
  499.             }
  500.             //$setMyCommands = ProjectUtilsController::requestToBot($token, 'setMyCommands', ['commands' => json_encode([['command' => '/help', 'description' => 'Список комманд'], ['command' => '/prev', 'description' => 'Список комманд'], ['command' => '/next', 'description' => 'Список комманд'], ['command' => '/top', 'description' => 'Список комманд'], ['command' => '/bottom', 'description' => 'Список комманд']])]);
  501. //            $reply = 'Тест';
  502. //            $sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
  503. //            die();
  504.             $isLog false;
  505.             if(($text != '' && $text != null) || ($fileId != '' && $fileId != null)){
  506.                 if($text == '/clear'){
  507.                     $this->addLogMessage($bot$group_id$message_idnull);
  508.                     $this->clear($token$chat_id$group_id$message_id);
  509.                     die();
  510.                 }
  511.                 $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('name' => $text'is_active' => true));
  512.                 if($command){
  513.                     $client_m $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  514.                     if($client_m){
  515.                         $this->resetExpected($client_m);
  516.                     }
  517.                     $is_access false;
  518.                     $client_i $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  519.                     $my_role null;
  520.                     if($client_i){
  521.                         if($client_i->getRole()){
  522.                             $my_role $client_i->getRole()->getId();
  523.                         }
  524.                     }
  525.                     if(count($command->getRoles()) > 0){
  526.                         foreach ($command->getRoles() as $role){
  527.                             if($role->getId() == $my_role){
  528.                                 $is_access true;
  529.                             }
  530.                         }
  531.                     }
  532.                     $sendMessage false;
  533.                     if($is_group_chat === true && $group_id != '' && $group_id != null){
  534.                         $this->addLogMessage($bot$group_id$message_id$command);
  535.                         $isLog true;
  536.                     }
  537.                     if($is_access === true){
  538.                         if($command->getTypeof() == 'start'){
  539.                             if($is_group_chat === true && $group_id != '' && $group_id != null){
  540.                                 $chat_id $group_id;
  541.                             }
  542.                             $reply 'Добро пожаловать в бот' . ($bot "«" $bot->getName() . "»." '');
  543.                             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  544.                         }elseif($command->getTypeof() == 'setting'){
  545.                             $this->setting($token$chat_id$group_id, array(), $message_id);
  546.                         } elseif($command->getTypeof() == 'help'){
  547.                             $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  548.                             $type_group null;
  549.                             if($is_group_chat === true && $group_id != '' && $group_id != null){
  550.                                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  551.                                 if($groupObj && $groupObj->getTypeGroup() != null){
  552.                                     $type_group $groupObj->getTypeGroup()->getTypeof();
  553.                                 }
  554.                             }
  555.                             $reply $this->mainMenu($clientObj, ($is_group_chat === true && $group_id != '' && $group_id != null true false), $type_group);
  556.                             if($is_group_chat === true && $group_id != '' && $group_id != null){
  557.                                 $chat_id $group_id;
  558.                             }
  559.                             if($reply != '' && $reply != null){
  560.                                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  561.                             }
  562.                         } elseif($command->getTypeof() == 'init'){
  563.                             $reply 'Вам не удалось инициализироватся у бота. Попробуйте повторить команду позже.';
  564.                             if($client){
  565.                                 $reply 'Вы упешно инициализированы ботом. Чтобы узнать какие команды вам доступны отправьте /help.';
  566.                             }
  567.                             if($is_group_chat === true && $group_id != '' && $group_id != null){
  568.                                 $chat_id $group_id;
  569.                             }
  570.                             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  571.                         } elseif($command->getTypeof() == 'users'){
  572.                             $this->users($token$chat_id$group_id, array(), falsenull$message_id);
  573.                         }  elseif($command->getTypeof() == 'office'){
  574.                             $this->office($token$chat_id$group_id, array(), falsenull$message_id);
  575.                         } elseif($command->getTypeof() == 'pay'){
  576.                             $this->pay($token$chat_id$group_id, array(), falsenull$message_id);
  577.                         } elseif($command->getTypeof() == 'bpay'){
  578.                             $type_group null;
  579.                             $groupId '';
  580.                             if($is_group_chat === true && $group_id != '' && $group_id != null){
  581.                                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  582.                                 if($groupObj){
  583.                                     if($groupObj->getTypeGroup() != null){
  584.                                         $type_group $groupObj->getTypeGroup()->getTypeof();
  585.                                     }
  586.                                     $groupId $groupObj->getId();
  587.                                 }
  588.                             }
  589.                             if($type_group == 'cash'){
  590. //                                if($is_group_chat === true){
  591. //                                    $chat_id = $group_id;
  592. //                                }
  593.                                 $cq_data = array('action' => "other"'command' => "bpay""group" => $groupId);
  594.                                 $this->bpay($token$chat_id$group_id$cq_datafalsenull$message_id);
  595.                                 //$reply = 'группа ' . $groupId;
  596.                                 //$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $group_id, 'text' => $reply, 'parse_mode' => 'HTML']);
  597.                             } else {
  598.                                 //доступа у группы типа ЗП нет к данной команде
  599.                                 $reply 'У вас нет доступа к данной команде.';
  600.                                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $group_id'text' => $reply'parse_mode' => 'HTML']);
  601.                             }
  602.                             //$this->bpay($token, $chat_id, $group_id, array(), false, null, $message_id);
  603.                         } elseif($command->getTypeof() == 'balance'){
  604.                             $this->balance($token$chat_id$group_id$client_i);
  605.                         } elseif($command->getTypeof() == 'report'){
  606.                             $this->report($token$chat_id$group_id, array(), $client_inull$message_id);
  607.                         }
  608.                         if($is_group_chat === true){
  609.                             //удаление прошлых команд, кроме данной команды
  610.                             $this->deleteLogMessage($bot$group_idnull$command->getId());
  611.                         }
  612.                     } else {
  613.                         $reply 'У вас нет доступа к данной команде.';
  614.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  615.                     }
  616.                     if($is_group_chat === true){
  617.                         $this->addLogMessageBot($bot$command$sendMessage);
  618.                         $isLog true;
  619.                     }
  620.                     if($isLog !== true){
  621.                         $this->addLogMessage($bot$group_id$message_idnull);
  622.                     }
  623.                 } else {
  624.                     $is_expected false;
  625.                     if($client){
  626.                         if($client->getExpected() != '' && $client->getExpected() != null){
  627.                             $is_expected true;
  628.                             $data_expected $this->dataExpected($client->getExpected());
  629.                             if(isset($data_expected['value'])){
  630.                                 $typeof_command null;
  631.                                 if($data_expected['value'] == 'new_office'){
  632.                                     $this->office($token$chat_id$group_id, array(), $client$text$message_id);
  633.                                     $typeof_command 'office';
  634.                                 }  elseif($data_expected['value'] == 'name_office'){
  635.                                     $this->office($token$chat_id$group_id, array(), $client$text$message_id);
  636.                                     $typeof_command 'office';
  637.                                 } elseif($data_expected['value'] == 'edit_office' || $data_expected['value'] == 'edit_n_office'){
  638.                                     $this->office($token$chat_id$group_id, array(), $client$text$message_id);
  639.                                     $typeof_command 'office';
  640.                                 } 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'){
  641.                                     $typeof_command 'pay';
  642.                                     //удаление комментария
  643.                                     /*
  644.                                     if($is_group_chat === true && $group_id != '' && $group_id != null && $data_expected['value'] == 'comment'){
  645.                                         if(!$command && $typeof_command != '' && $typeof_command != null){
  646.                                             $command = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => $typeof_command, 'is_active' => true));
  647.                                         }
  648.                                         $this->addLogMessage($bot, $group_id, $message_id, $command);
  649.                                         $isLog = true;
  650.                                     }
  651.                                     */
  652.                                     $this->pay($token$chat_id$group_id, array(), $client$text$message_id$fileId);
  653.                                 } 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'){
  654.                                     $typeof_command 'bpay';
  655.                                     //удаление комментария
  656.                                     /*
  657.                                     if($is_group_chat === true && $group_id != '' && $group_id != null && $data_expected['value'] == 'comment'){
  658.                                         if(!$command && $typeof_command != '' && $typeof_command != null){
  659.                                             $command = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => $typeof_command, 'is_active' => true));
  660.                                         }
  661.                                         $this->addLogMessage($bot, $group_id, $message_id, $command);
  662.                                         $isLog = true;
  663.                                     }
  664.                                     */
  665.                                     $this->bpay($token$chat_id$group_id, array(), $client$text$message_id$fileId);
  666.                                 } elseif($data_expected['value'] == 'email'){
  667.                                     $this->users($token$chat_id$group_id, array(), $client$text$message_id);
  668.                                     $typeof_command 'users';
  669.                                 } elseif($data_expected['value'] == 'period_report'){
  670.                                     $this->report($token$chat_id$group_id, array(), $client$text$message_id);
  671.                                     $typeof_command 'report';
  672.                                 }
  673.                                 if($is_group_chat === true && $group_id != '' && $group_id != null){
  674.                                     if(!$command && $typeof_command != '' && $typeof_command != null){
  675.                                         $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => $typeof_command'is_active' => true));
  676.                                     }
  677.                                     //чтобы не удалялись сумма, комментарий и чек транзакции
  678.                                     if($data_expected['value'] != 'amount' && $data_expected['value'] != 'comment' && $data_expected['value'] != 'file_cheque' && $data_expected['value'] != 'file_cheque_b'){
  679.                                         $this->addLogMessage($bot$group_id$message_id$command);
  680.                                     }
  681.                                     $isLog true;
  682.                                 }
  683.                             }
  684.                         }
  685.                         if($isLog !== true){
  686.                             $this->addLogMessage($bot$group_id$message_idnull);
  687.                         }
  688.                     }
  689.                     if($is_expected === false){
  690.                         if($is_group_chat === true && $group_id != '' && $group_id != null){
  691.                             $chat_id $group_id;
  692.                         }
  693.                         if(strpos($text'/') !== false){
  694.                             $reply 'Команда не найдена или неактивна, пожалуйста проверьте правильно ли вы ввели команду.';
  695.                         }
  696. //                        else {
  697. //                            $reply = 'Возможно вы ввели текст неправильно, боту не удалось его разпознать';
  698. //                        }
  699.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  700.                         if($is_group_chat === true) {
  701.                             $this->addLogMessageBot($bot$command$sendMessage);
  702.                         }
  703.                     }
  704.                 }
  705.             }
  706.             //file_put_contents($basePath . '/var/log/chat.txt', $sendMessage, FILE_APPEND);
  707.         }
  708.         exit();
  709.     }
  710.     private function clearChats($token$data){
  711.         $em $this->getDoctrine()->getManager();
  712.         if(count($data) > 0){
  713.             foreach ($data as $item){
  714.                 if($item['chat_id'] != null && $item['chat_id'] != '' && $item['message_id'] != null && $item['message_id'] != ''){
  715.                     $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $item['chat_id'], 'message_id' => $item['message_id']]);
  716.                     $deleteData = array();
  717.                     if(ProjectUtilsController::isJSON($deleteMessage) === true){
  718.                         $deleteData json_decode($deleteMessagetrue);
  719.                     }
  720.                     if(count($deleteData) > 0){
  721.                         $log_message $this->getDoctrine()->getRepository(LogMessage::class)->findOneBy(array('id' => $item['id']));
  722.                         if($log_message){
  723.                             if(isset($deleteData['ok'])){
  724.                                 if($deleteData['ok'] === true){
  725.                                     $log_message->setIsDeleted(1);
  726.                                     $log_message->setResponse($deleteMessage);
  727.                                 } else {
  728.                                     $log_message->setResponse($deleteMessage);
  729.                                 }
  730.                                 $em->persist($log_message);
  731.                                 $em->flush();
  732.                             }
  733.                         }
  734.                     }
  735.                 }
  736.             }
  737.         }
  738.     }
  739.     private function clear($token$chat_id$group_id$message_id){
  740.         $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
  741.         if($bot){
  742.             if($chat_id != '' && $chat_id != null){
  743.                 $log_messages_q $this->getDoctrine()
  744.                     ->getRepository(LogMessage::class)
  745.                     ->createQueryBuilder('lm')
  746.                     ->select('lm.id, lm.chat_id, lm.message_id')
  747.                     ->where('lm.is_deleted = 0')
  748.                     ->andWhere('lm.bot = :bot_id')
  749.                     ->andWhere('lm.chat_id = :chat_id')
  750.                     ->setParameter('chat_id'$chat_id)
  751.                     ->setParameter('bot_id'$bot->getId())
  752.                     ->setMaxResults(5)
  753.                     ->orderBy('lm.id''DESC')
  754.                     ->getQuery()->getArrayResult();
  755.                 $this->clearChats($token$log_messages_q);
  756.             }
  757.             if($group_id != '' && $group_id != null){
  758.                 $log_messages_group_q $this->getDoctrine()
  759.                     ->getRepository(LogMessage::class)
  760.                     ->createQueryBuilder('lm')
  761.                     ->select('lm.id, lm.chat_id, lm.message_id')
  762.                     ->where('lm.is_deleted = 0')
  763.                     ->andWhere('lm.bot = :bot_id')
  764.                     ->andWhere('lm.chat_id = :chat_id')
  765.                     ->setParameter('chat_id'$group_id)
  766.                     ->setParameter('bot_id'$bot->getId())
  767.                     ->setMaxResults(5)
  768.                     ->orderBy('lm.id''DESC')
  769.                     ->getQuery()->getArrayResult();
  770.                 $this->clearChats($token$log_messages_group_q);
  771.             }
  772.             $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => ($group_id != '' && $group_id != '' $group_id $chat_id), 'message_id' => $message_id]);
  773.             //$reply = 'Чат очищен от последних сообщений';
  774.             //$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => ($group_id != '' && $group_id != '' ? $group_id : $chat_id), 'text' => $reply, 'parse_mode' => 'HTML']);
  775.             //$this->addLogMessageBot($bot->getId(), null, $sendMessage);
  776.             exit();
  777.         }
  778.     }
  779.     private function addLogMessageBot($bot_id$command_id$json_data)
  780.     {
  781.         $chat_id null;
  782.         $message_id null;
  783.         if(ProjectUtilsController::isJSON($json_data) === true){
  784.             $data json_decode($json_datatrue);
  785.             if(count($data) > && isset($data['ok'])){
  786.                 if($data['ok'] === true){
  787.                     $chat_id = (isset($data['result']['chat']['id']) ? $data['result']['chat']['id'] : null);
  788.                     $message_id = (isset($data['result']['message_id']) ? $data['result']['message_id'] : null);
  789.                 }
  790.             }
  791.         }
  792.         $this->addLogMessage($bot_id$chat_id$message_id$command_id);
  793.     }
  794.     private function addLogMessage($bot_id$chat_id$message_id$command_id null)
  795.     {
  796.         $em $this->getDoctrine()->getManager();
  797.         $bot false;
  798.         if(is_object($bot_id)){
  799.             $bot $bot_id;
  800.         } elseif($bot_id != '' && $bot_id != null){
  801.             $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('id' => $bot_id));
  802.         }
  803.         $command null;
  804.         if(is_object($command_id)){
  805.             $command $command_id;
  806.         } elseif($command_id != '' && $command_id != null){
  807.             $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('id' => $command_id));
  808.         }
  809.         $resp false;
  810.         if($bot && $chat_id != '' && $chat_id != null && $message_id != '' && $message_id != null){
  811.             $log_message $this->getDoctrine()->getRepository(LogMessage::class)->findOneBy(array('chat_id' => $chat_id'message_id' => $message_id'bot' => $bot'is_deleted' => false));
  812.             if(!$log_message){
  813.                 $newLogMessage = new LogMessage();
  814.                 $newLogMessage->setChatId($chat_id);
  815.                 $newLogMessage->setMessageId($message_id);
  816.                 $newLogMessage->setBot($bot);
  817.                 $newLogMessage->setDate(new \DateTime(date('Y-m-d H:i:s')));
  818.                 $newLogMessage->setIsDeleted(0);
  819.                 $newLogMessage->setCommand($command);
  820.                 $em->persist($newLogMessage);
  821.                 $em->flush();
  822.                 if($newLogMessage){
  823.                     $resp true;
  824.                 }
  825.             } else {
  826.                 $resp true;
  827.             }
  828.         }
  829.         return $resp;
  830.     }
  831.     private function deleteLogMessage($bot_id null$chat_id null$command_id null$no_command_id null)
  832.     {
  833.         if(is_object($bot_id)){
  834.             $bot_id $bot_id->getId();
  835.         }
  836.         $log_messages_q $this->getDoctrine()
  837.             ->getRepository(LogMessage::class)
  838.             ->createQueryBuilder('lm')
  839.             ->select('lm.id, lm.chat_id, lm.message_id, b.token AS token')
  840.             ->leftJoin(Bot::class, 'b''WITH''lm.bot = b.id')
  841.             ->where('lm.is_deleted = 0');
  842.         if($command_id != '' && $command_id != null){
  843.             $log_messages_q->andWhere('lm.command = ' $command_id);
  844.         }
  845.         if($no_command_id != '' && $no_command_id != null){
  846.             $log_messages_q->andWhere('lm.command != ' $no_command_id);
  847.         }
  848.         if($bot_id != '' && $bot_id != null && $chat_id != '' && $chat_id != null){
  849.             $log_messages_q->andWhere('lm.bot = ' $bot_id)
  850.                 ->andWhere('lm.chat_id = :chat_id')
  851.                 ->setParameter('chat_id'$chat_id)
  852.             ;
  853.         } else {
  854.             $m $this->getParameter('app.delete.max_interval');
  855.             $d date('Y-m-d H:i:s',strtotime('-' $m ' minutes'strtotime(date("Y-m-d H:i:s"))));
  856.             $log_messages_q->andWhere('lm.date <= :date')
  857.                 ->setParameter('date'$d)
  858.             ;
  859.         }
  860.         $log_messages $log_messages_q->getQuery()->getArrayResult();
  861.         if(count($log_messages) > 0){
  862.             $em $this->getDoctrine()->getManager();
  863.             foreach ($log_messages as $item){
  864.                 if($item['chat_id'] != null && $item['chat_id'] != '' && $item['message_id'] != null && $item['message_id'] != ''&& $item['token'] != null && $item['token'] != ''){
  865.                     $deleteMessage ProjectUtilsController::requestToBot($item['token'], 'deleteMessage', ['chat_id' => $item['chat_id'], 'message_id' => $item['message_id']]);
  866.                     $deleteData = array();
  867.                     if(ProjectUtilsController::isJSON($deleteMessage) === true){
  868.                         $deleteData json_decode($deleteMessagetrue);
  869.                     }
  870.                     if(count($deleteData) > 0){
  871.                         $log_message $this->getDoctrine()->getRepository(LogMessage::class)->findOneBy(array('id' => $item['id']));
  872.                         if($log_message){
  873.                             if(isset($deleteData['ok'])){
  874.                                 if($deleteData['ok'] === true){
  875.                                     $log_message->setIsDeleted(1);
  876.                                     $log_message->setResponse($deleteMessage);
  877.                                 } else {
  878.                                     $log_message->setResponse($deleteMessage);
  879.                                 }
  880.                                 $em->persist($log_message);
  881.                                 $em->flush();
  882.                             }
  883.                         }
  884.                     }
  885.                 }
  886.             }
  887.         }
  888.     }
  889.     private function isValidDate($date) {
  890.         if (preg_match("/^(\d{2}).(\d{2}).(\d{4})$/"$date$matches)) {
  891.             if (checkdate($matches[2], $matches[1], $matches[3])) {
  892.                 return true;
  893.             }
  894.         }
  895.         return false;
  896.     }
  897.     private function isValidDateTime($dateTime) {
  898.         if (preg_match("/^(\d{2}).(\d{2}).(\d{4}) ([01][0-9]|2[0-3]):([0-5][0-9])$/"$dateTime$matches)) {
  899.             if (checkdate($matches[2], $matches[1], $matches[3])) {
  900.                 return true;
  901.             }
  902.         }
  903.         return false;
  904.     }
  905.     private function isValidDateTimeOrig($dateTime) {
  906.         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)) {
  907.             if (checkdate($matches[2], $matches[3], $matches[1])) {
  908.                 return true;
  909.             }
  910.         }
  911.         return false;
  912.     }
  913.     private function report($token$chat_id$group_id$cq_data = array(), $curClient false$text null$message_id null) {
  914.         $is_group_chat $this->kernel->getContainer()->getParameter('app.chat.is_group');
  915.         $basePath $this->getParameter('kernel.project_dir');
  916.         $fileDir '/public/images/';
  917.         $action null;
  918.         $p_group null;
  919.         $keyboard = array();
  920.         $em $this->getDoctrine()->getManager();
  921.         if(count($cq_data) > 0){
  922.             $action = (isset($cq_data['action']) ? $cq_data['action'] : null);
  923.             $p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
  924.         }
  925.         $expected null;
  926.         if($curClient){
  927.             $data_expected $this->dataExpected($curClient->getExpected());
  928.             if(isset($data_expected['value'])){
  929.                 $expected $data_expected['value'];
  930.             }
  931.             if(isset($data_expected['group'])){
  932.                 $p_group $data_expected['group'];
  933.             }
  934.         }
  935.         if($action == 'delete'){
  936.             $groupObj false;
  937.             if($p_group != null && $p_group != '') {
  938.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  939.             }
  940.             if($groupObj){
  941.                 $mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
  942.                 if($mes_id != '' && $mes_id != null){
  943.                     $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
  944.                 }
  945.                 if(file_exists($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt')){
  946.                     $mes_id file_get_contents($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt');
  947.                     if($mes_id != '' && $mes_id != null){
  948.                         $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
  949.                         $resp json_decode($deleteMessagetrue);
  950.                         if(isset($resp['result'])){
  951.                             if($resp['result'] == true){
  952.                                 unlink($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt');
  953.                             }
  954.                         }
  955.                     }
  956.                 }
  957.             }
  958.             exit();
  959.         }
  960.         if(count($cq_data) > && $action != 'menu'){
  961.             if($action == 'all_report'){
  962.                 if(!$curClient){
  963.                     $curClient $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  964.                 }
  965.                 $groupObj false;
  966.                 if($p_group != null && $p_group != '') {
  967.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  968.                 }
  969.                 $transactions_q $this->getDoctrine()
  970.                     ->getRepository(Transaction::class)
  971.                     ->createQueryBuilder('tr')
  972.                     ->select('tr.id')
  973.                     ->where('tr.amount != 0')
  974.                 ;
  975.                 if($groupObj){
  976.                     $transactions_q->andWhere('tr.from_group = ' $groupObj->getId() . ' OR tr.to_group = ' $groupObj->getId());
  977.                 }
  978.                 $transactions $transactions_q->getQuery()->getArrayResult();
  979.                 $count_trs count($transactions);
  980.                 if($count_trs 0){
  981.                     $newReport = new Report();
  982.                     $newReport->setClient(($curClient $curClient null));
  983.                     $newReport->setPath(null);
  984.                     $newReport->setDateWith(null);
  985.                     $newReport->setDateBy(null);
  986.                     $newReport->setIsSend(0);
  987.                     $newReport->setDate(new \DateTime(date("Y-m-d H:i:s")));
  988.                     $newReport->setClientGroup(($groupObj $groupObj null));
  989.                     $em->persist($newReport);
  990.                     $em->flush();
  991.                     $file $this->genReport($newReport);
  992.                     if($file != '' && $file != null){
  993.                         $email $curClient->getEmail();
  994.                         if($email != null && $email != ''){
  995.                             $body_mail = array(
  996.                                 '#app#' => $this->getParameter('app.name'),
  997.                                 '#logo#' => $this->getParameter('app.logo')
  998.                             );
  999.                             $title_mail = array();
  1000.                             $attach = array();
  1001.                             $filepath $basePath $fileDir $file;
  1002.                             if(file_exists($filepath)){
  1003.                                 $attach[] = $basePath $fileDir $file;
  1004.                             }
  1005.                             //отправка письма
  1006.                             //$email = 'igor@atmapro.ru';
  1007.                             $sendMail $this->sendEmail($this->mailer,'newReportAll'$body_mail$title_mail'ru'$email$attach);
  1008.                             $newReport->setIsSend(1);
  1009.                         }
  1010.                         $newReport->setPath($file);
  1011.                         $em->persist($newReport);
  1012.                         $em->flush();
  1013.                         $this->resetExpected($curClient);
  1014.                         $arr_f explode('/'$file);
  1015.                         $file_name '';
  1016.                         if(count($arr_f) == 2){
  1017.                             $file_name $arr_f[1];
  1018.                         }
  1019.                         $link_file = (isset($_SERVER['HTTPS']) ? 'https://' 'http://') . $_SERVER['HTTP_HOST'] . '/images/' $file;
  1020.                         $reply 'Файл отчета' . ($file_name != '' ' ' $file_name '') . ' успешно сформирован и отправлен на почту ' $email '. Также доступен для скачивания по ссылке ' $link_file;
  1021.                         //$reply = 'Файл отчета успешно сформирован ' . $file;
  1022.                     } else {
  1023.                         $reply 'Не удалось сформировать файл отчета, попробуйте позже.';
  1024.                         $this->resetExpected($curClient);
  1025.                     }
  1026.                 } else {
  1027.                     $reply 'Не удалось сформировать отчет, пока нет ни одной финансовой операции.';
  1028.                     $this->resetExpected($curClient);
  1029.                 }
  1030.             }
  1031.         } elseif($expected != '' && $expected != null){
  1032.             if($curClient && $text != '' && $text != null){
  1033.                 $groupObj false;
  1034.                 if($group_id != null && $group_id != ''){
  1035.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  1036.                 } elseif($p_group != null && $p_group != '') {
  1037.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  1038.                 }
  1039.                 if($is_group_chat === true && $groupObj){
  1040.                     $chat_id $groupObj->getChatId();
  1041.                 }
  1042.                 $date_with null;
  1043.                 $date_by null;
  1044.                 $is_valid_with false;
  1045.                 $is_valid_by false;
  1046.                 if($groupObj && $curClient){
  1047.                     if (strpos($text'-') !== false) {
  1048.                         $d explode('-'trim($text));
  1049.                         if(count($d) == 2){
  1050.                             if($this->isValidDate(trim($d[0])) || $this->isValidDateTime(trim($d[0]))){
  1051.                                 $date_with date("Y-m-d H:i:s"strtotime(trim($d[0])));
  1052.                                 $is_valid_with true;
  1053.                             }
  1054.                             if($this->isValidDate(trim($d[1])) || $this->isValidDateTime(trim($d[1]))){
  1055.                                 $date_by date("Y-m-d H:i:s"strtotime(trim($d[1])));
  1056.                                 $is_valid_by true;
  1057.                             }
  1058.                         }
  1059.                     }
  1060.                     if($is_valid_with === true && $is_valid_by === true){
  1061.                         $transactions_q $this->getDoctrine()
  1062.                             ->getRepository(Transaction::class)
  1063.                             ->createQueryBuilder('tr')
  1064.                             ->select('tr.id')
  1065.                             ->where('tr.amount != 0')
  1066.                         ;
  1067.                         if($date_with != '' && $date_with != null){
  1068.                             $transactions_q->andWhere('tr.date >= :date_with')
  1069.                                 ->setParameter('date_with'$date_with);
  1070.                         }
  1071.                         if($date_by != '' && $date_by != null){
  1072.                             $transactions_q->andWhere('tr.date <= :date_by')
  1073.                                 ->setParameter('date_by'$date_by);
  1074.                         }
  1075.                         if($groupObj){
  1076.                             $transactions_q->andWhere('tr.from_group = ' $groupObj->getId() . ' OR tr.to_group = ' $groupObj->getId());
  1077.                         }
  1078.                         $transactions $transactions_q->getQuery()->getArrayResult();
  1079.                         $count_trs count($transactions);
  1080.                         if($count_trs 0){
  1081.                             $newReport = new Report();
  1082.                             $newReport->setClient(($curClient $curClient null));
  1083.                             $newReport->setPath(null);
  1084.                             $newReport->setDateWith(new \DateTime($date_with));
  1085.                             $newReport->setDateBy(new \DateTime($date_by));
  1086.                             $newReport->setIsSend(0);
  1087.                             $newReport->setDate(new \DateTime(date("Y-m-d H:i:s")));
  1088.                             $newReport->setClientGroup($groupObj);
  1089.                             $em->persist($newReport);
  1090.                             $em->flush();
  1091.                             $file $this->genReport($newReport);
  1092.                             if($file != '' && $file != null){
  1093.                                 $email $curClient->getEmail();
  1094.                                 if($email != null && $email != ''){
  1095.                                     $body_mail = array(
  1096.                                         '#app#' => $this->getParameter('app.name'),
  1097.                                         '#logo#' => $this->getParameter('app.logo'),
  1098.                                         '#date_with#' => date("d.m.Y H:i"strtotime($date_with)),
  1099.                                         '#date_by#' => date("d.m.Y H:i"strtotime($date_by)),
  1100.                                     );
  1101.                                     $title_mail = array();
  1102.                                     $attach = array();
  1103.                                     $filepath $basePath $fileDir $file;
  1104.                                     if(file_exists($filepath)){
  1105.                                         $attach[] = $basePath $fileDir $file;
  1106.                                     }
  1107.                                     //отправка письма
  1108.                                     //$email = 'igor@atmapro.ru';
  1109.                                     $sendMail $this->sendEmail($this->mailer,'newReportPeriod'$body_mail$title_mail'ru'$email$attach);
  1110.                                     $newReport->setIsSend(1);
  1111.                                 }
  1112.                                 $newReport->setPath($file);
  1113.                                 $em->persist($newReport);
  1114.                                 $em->flush();
  1115.                                 $this->resetExpected($curClient);
  1116.                                 $arr_f explode('/'$file);
  1117.                                 $file_name '';
  1118.                                 if(count($arr_f) == 2){
  1119.                                     $file_name $arr_f[1];
  1120.                                 }
  1121.                                 $link_file = (isset($_SERVER['HTTPS']) ? 'https://' 'http://') . $_SERVER['HTTP_HOST'] . '/images/' $file;
  1122.                                 $reply 'Файл отчета' . ($file_name != '' ' ' $file_name '') . ' успешно сформирован и отправлен на почту ' $email '. Также доступен для скачивания по ссылке ' $link_file;
  1123.                             } else {
  1124.                                 $reply 'Не удалось сформировать файл отчета, попробуйте позже.';
  1125.                                 $this->resetExpected($curClient);
  1126.                             }
  1127.                         } else {
  1128.                             $reply 'Финансовых операций за данный период не найдено, пропробуйте повторить команду и указать другой период.';
  1129.                             $this->resetExpected($curClient);
  1130.                         }
  1131.                     } else {
  1132.                         $reply 'Введен период в неправильном формате, введите период для формирования отчета, в формате: 01.04.2022-10.04.2022';
  1133.                     }
  1134.                 }
  1135.             }
  1136.         } else {
  1137.             $groupObj false;
  1138.             if($group_id != null && $group_id != ''){
  1139.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  1140.             } elseif($p_group != null && $p_group != '') {
  1141.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  1142.             }
  1143.             if($is_group_chat === true && $groupObj){
  1144.                 $chat_id $groupObj->getChatId();
  1145.             }
  1146.             $reply 'Введите период для формирования отчета для финансовых операций. В формате: 01.04.2022-10.04.2022';
  1147.             $keyboard = array(
  1148.                 array(
  1149.                     array(
  1150.                         'text'=>'Сформировать за все время',
  1151.                         'callback_data'=> json_encode(array('action' => "all_report"'command' => "report""group" => ($groupObj $groupObj->getId() : null)))
  1152.                     )
  1153.                 ),
  1154.                 array(
  1155.                     array(
  1156.                         'text'=>'Назад',
  1157.                         'callback_data'=> json_encode(array('action' => "delete"'command' => "report"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  1158.                     )
  1159.                 )
  1160.             );
  1161.             $this->addExpected(($is_group_chat === true && $groupObj $groupObj $curClient), array("value" => "period_report""group" => ($groupObj $groupObj->getId() : null)));
  1162.         }
  1163.         $sendMessage false;
  1164.         if(count($keyboard) > 0){
  1165.             $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  1166.             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  1167.             $resp json_decode($sendMessagetrue);
  1168.             if(isset($resp['result']['message_id']) && $groupObj){
  1169.                 file_put_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt'$resp['result']['message_id']);
  1170.             }
  1171.         } else {
  1172.             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  1173.         }
  1174.         if($is_group_chat === true){
  1175.             $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
  1176.             $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'report'));
  1177.             $this->addLogMessageBot($bot$command$sendMessage);
  1178.         }
  1179.     }
  1180.     private function mainMenu($client$is_group_chat true$type_group null)
  1181.     {
  1182.         $role_id null;
  1183.         if($client){
  1184.             if($client->getRole()){
  1185.                 $role_id $client->getRole()->getId();
  1186.             }
  1187.         }
  1188.         $main_menu '';
  1189.         $commands $this->getDoctrine()->getRepository(Command::class)->findAll();
  1190.         if(count($commands) > 0){
  1191.             foreach ($commands as $command){
  1192.                 if($command->getIsActive() === true){
  1193.                     if($role_id != '' && $role_id != null){
  1194.                         if(count($command->getRoles())){
  1195.                             foreach ($command->getRoles() as $role){
  1196.                                 if($role_id == $role->getId() && $command->getTypeof() != 'start'){
  1197.                                     if((($is_group_chat === true) || ($is_group_chat === false && ($command->getTypeof() == 'help' || $command->getTypeof() == 'init')))){
  1198.                                         if(!($type_group == 'salary' && $command->getTypeof() == 'bpay')){
  1199.                                             $main_menu .= $command->getName() . ' - ' $command->getDescription() . "\n";
  1200.                                         }
  1201.                                     }
  1202.                                 }
  1203.                             }
  1204.                         }
  1205.                     } else {
  1206.                         if(!($type_group == 'salary' && $command->getTypeof() == 'bpay')){
  1207.                             $main_menu .= $command->getName() . ' - ' $command->getDescription() . "\n";
  1208.                         }
  1209.                     }
  1210.                 }
  1211.             }
  1212.         }
  1213.         return $main_menu;
  1214.     }
  1215.     private function dataExpected($expected){
  1216.         $data = array();
  1217.         if(ProjectUtilsController::isJSON($expected) === true){
  1218.             $data json_decode($expectedtrue);
  1219.         }
  1220.         return $data;
  1221.     }
  1222.     private function resetExpected($client){
  1223.         $em $this->getDoctrine()->getManager();
  1224.         $resp false;
  1225.         if($client){
  1226.             if($client->getExpected() != '' && $client->getExpected() != null){
  1227.                 $client->setExpected(null);
  1228.                 $em->persist($client);
  1229.                 $em->flush();
  1230.                 $resp true;
  1231.             }
  1232.         }
  1233.         return $resp;
  1234.     }
  1235.     private function addExpected($client$expected){
  1236.         $em $this->getDoctrine()->getManager();
  1237.         $resp false;
  1238.         if($client){
  1239.             $client->setExpected(json_encode($expected));
  1240.             $em->persist($client);
  1241.             $em->flush();
  1242.             $resp true;
  1243.         }
  1244.         return $resp;
  1245.     }
  1246.     private function balance($token$chat_id$group_id$curClient false) {
  1247.         $is_group_chat $this->getParameter('app.chat.is_group');
  1248.         if(!$curClient && $chat_id != '' && $chat_id != null){
  1249.             $curClient $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  1250.         }
  1251.         $groupObj false;
  1252.         if($group_id != null && $group_id != ''){
  1253.             $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  1254.         }
  1255.         $is_delete false;
  1256.         $group_chat_id null;
  1257.         if($curClient && $groupObj){
  1258.             $group_chat_id $groupObj->getChatId();
  1259.             $role null;
  1260.             if($curClient->getRole()){
  1261.                 $role $curClient->getRole()->getTypeof();
  1262.             }
  1263.             $type_group null;
  1264.             if($groupObj->getTypeGroup()){
  1265.                 $type_group $groupObj->getTypeGroup()->getTypeof();
  1266.             }
  1267.             if(is_numeric($groupObj->getBalance())){
  1268.                 $opt "";
  1269.                 if($groupObj->getBalance() > 0){
  1270.                     $opt "+";
  1271.                 }
  1272.                 $balance $opt str_replace(',00'''number_format(($groupObj->getBalance() / 100), 2','' '));
  1273.                 
  1274.                 /*
  1275.                 if($role == 'director'){
  1276.                     if($type_group == 'cash'){
  1277.                         $reply = 'Баланс ' . $balance;
  1278.                     } else {
  1279.                         $reply = 'Нет доступа к балансу этой группы';
  1280.                     }
  1281.                 } else
  1282.                 */
  1283.                 if($role == 'auditor' || $role == 'director' || $role == 'accountant'){
  1284.                     $reply 'Баланс ' $balance;
  1285.                 } elseif($role == 'employee'){
  1286.                     if($type_group == 'salary'){
  1287.                         $reply 'Баланс ' $balance;
  1288.                     } else {
  1289.                         $is_delete true;
  1290.                         $reply 'Нет доступа к балансу этой группы.';
  1291.                     }
  1292.                 }
  1293.             } else {
  1294.                 $is_delete true;
  1295.                 $reply 'Ошибочное значение баланса.';
  1296.             }
  1297.         } else {
  1298.             $is_delete true;
  1299.             $reply 'Невозможно получить информацию по балансу, убедитесь, что отправляете команду в группе.';
  1300.         }
  1301.         $sendMessage null;
  1302.         if($group_chat_id != '' && $group_chat_id != null){
  1303.             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $group_chat_id'text' => $reply'parse_mode' => 'HTML']);
  1304.         } else {
  1305.             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  1306.         }
  1307.         if($is_group_chat === true){
  1308.             $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
  1309.             $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'balance'));
  1310.             if($is_delete === true){
  1311.                 $this->addLogMessageBot($bot$command$sendMessage);
  1312.             }
  1313.         }
  1314.     }
  1315.     private function curCommandPermissions($user$typeCommand 'pay'){
  1316.         $list = [];
  1317.         if($user && $user->getRole() !== null){
  1318.             $role $user->getRole();
  1319.             if(count($role->getCommandPermissions()) > 0){
  1320.                 foreach ($role->getCommandPermissions() as $commandPermission){
  1321.                     if($commandPermission->getCommand() != null){
  1322.                         if($commandPermission->getCommand()->getTypeof() == $typeCommand && $commandPermission->getIsActive()){
  1323.                             $list[] = $commandPermission->getTypeof();
  1324.                         }
  1325.                     }
  1326.                 }
  1327.             }
  1328.         }
  1329.         return $list;
  1330.     }
  1331.     private function pay($token$chat_id$group_id$cq_data = array(), $curClient false$text null$message_id null$file_id null) {
  1332.         $is_group_chat $this->kernel->getContainer()->getParameter('app.chat.is_group');
  1333.         $basePath $this->getParameter('kernel.project_dir');
  1334.         $create_transaction false;
  1335.         $action null;
  1336.         $p_group null;
  1337.         $keyboard = array();
  1338.         $em $this->getDoctrine()->getManager();
  1339.         if(count($cq_data) > 0){
  1340.             $action = (isset($cq_data['action']) ? $cq_data['action'] : null);
  1341.             $p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
  1342.         }
  1343.         $expected null;
  1344.         $ss_id null;
  1345.         if($curClient){
  1346.             $data_expected $this->dataExpected($curClient->getExpected());
  1347.             if(isset($data_expected['value'])){
  1348.                 $expected $data_expected['value'];
  1349.             }
  1350.             if(isset($data_expected['group'])){
  1351.                 $p_group $data_expected['group'];
  1352.             }
  1353.             if(isset($data_expected['ss_id'])){
  1354.                 $ss_id $data_expected['ss_id'];
  1355.             }
  1356.         }
  1357.         $editMessageId null;
  1358.         if(count($cq_data) > && $action != 'menu'){
  1359.             $name_group '';
  1360.             $groupObj false;
  1361.             if($group_id != null && $group_id != ''){
  1362.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  1363.             } elseif($p_group != null && $p_group != '') {
  1364.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  1365.             }
  1366.             if($action == 'delete' && $groupObj){
  1367.                 $mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
  1368.                 if($mes_id != '' && $mes_id != null){
  1369.                     $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
  1370.                 }
  1371.                 if(file_exists($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt')){
  1372.                     $mes_id file_get_contents($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt');
  1373.                     if($mes_id != '' && $mes_id != null){
  1374.                         $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
  1375.                         $resp json_decode($deleteMessagetrue);
  1376.                         if(isset($resp['result'])){
  1377.                             if($resp['result'] == true){
  1378.                                 unlink($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt');
  1379.                             }
  1380.                         }
  1381.                     }
  1382.                 }
  1383.                 exit();
  1384.             }
  1385.             $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  1386.             if($groupObj && $clientObj){
  1387.                 $name_group $groupObj->nameClient();
  1388.                 $type_group_typeof null;
  1389.                 if($groupObj->getTypeGroup()){
  1390.                     $type_group_typeof $groupObj->getTypeGroup()->getTypeof();
  1391.                 }
  1392.                 if($is_group_chat === true){
  1393.                     $chat_id $groupObj->getChatId();
  1394.                 }
  1395.                 if($type_group_typeof != null && $type_group_typeof != ''){
  1396.                     if($type_group_typeof == 'cash'){
  1397.                         if($action == 'income'){
  1398.                             $commandPermissions $this->curCommandPermissions($clientObj'pay');
  1399.                             $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Выбрано «Приход». ' 'Выберите откуда осуществляется приход.';
  1400. //                            $keyboard = array(
  1401. //                                array(
  1402. //                                    array(
  1403. //                                        'text'=>'По Объекту',
  1404. //                                        'callback_data'=> json_encode(array('action' => "income_partner", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  1405. //                                    )
  1406. //                                ),
  1407. //                                array(
  1408. //                                    array(
  1409. //                                        'text'=>'Перевод Нал-Нал',
  1410. //                                        'callback_data'=> json_encode(array('action' => "income_group", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  1411. //                                    ),
  1412. //                                ),
  1413. //                                array(
  1414. //                                    array(
  1415. //                                        'text'=>'Перевод ЗП-Нал',
  1416. //                                        'callback_data'=> json_encode(array('action' => "income_group_salary", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  1417. //                                    ),
  1418. //                                ),
  1419. //                                array(
  1420. //                                    array(
  1421. //                                        'text'=>'Назад',
  1422. //                                        'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  1423. //                                    ),
  1424. //                                )
  1425. //                            );
  1426.                             $keyboard = [];
  1427.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_income_office'$commandPermissions))){
  1428.                                 //Приход -> По Объекту
  1429.                                 $keyboard[] = [[
  1430.                                     'text'=>'По Объекту',
  1431.                                     'callback_data'=> json_encode(array('action' => "income_partner"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  1432.                                 ]];
  1433.                             }
  1434.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_income_transfer_cash_to_cash'$commandPermissions))){
  1435.                                 //Приход -> Превод Нал-Нал
  1436.                                 $keyboard[] = [[
  1437.                                     'text'=>'Перевод Нал-Нал',
  1438.                                     'callback_data'=> json_encode(array('action' => "income_group"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  1439.                                 ]];
  1440.                             }
  1441.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_income_transfer_salary_to_cash'$commandPermissions))){
  1442.                                 //Приход -> Превод ЗП-Нал
  1443.                                 $keyboard[] = [[
  1444.                                     'text'=>'Перевод ЗП-Нал',
  1445.                                     'callback_data'=> json_encode(array('action' => "income_group_salary"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  1446.                                 ]];
  1447.                             }
  1448.                             $keyboard[] = [[
  1449.                                 'text'=>'Назад',
  1450.                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  1451.                             ]];
  1452.                         } elseif($action == 'income_group'){
  1453.                             $clients_q $this->getDoctrine()
  1454.                                 ->getRepository(Client::class)
  1455.                                 ->createQueryBuilder('cl')
  1456.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  1457.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  1458.                                 ->where('cl.typeof != :typeof')
  1459.                                 ->andWhere('cl.is_active = 1')
  1460.                                 ->setParameter('typeof'"private")
  1461.                                 ->setParameter('typeof_group'"cash")
  1462.                             ;
  1463.                             if($groupObj){
  1464.                                 $clients_q->andWhere('cl.id != ' $groupObj->getId());
  1465.                             }
  1466.                             $clients $clients_q->getQuery()->getArrayResult();
  1467.                             if(count($clients) > 0){
  1468.                                 $buttons = array();
  1469.                                 foreach ($clients as $item_client){
  1470.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  1471.                                     $buttons[][] = array(
  1472.                                         'text' => $name_client,
  1473.                                         'callback_data'=> json_encode(array("action" => "add_cgroup"'command' => "pay"'id' => $item_client['id'], "group" => $p_group))
  1474.                                     );
  1475.                                 }
  1476.                                 $buttons[][] = array(
  1477.                                     'text' => 'Назад',
  1478.                                     'callback_data'=> json_encode(array("action" => "income"'command' => "pay""group" => $p_group))
  1479.                                 );
  1480.                                 $keyboard $buttons;
  1481.                                 $reply 'Выбрано «Перевод Нал-Нал». ' 'Выберите группу из которой будет списание средств.';
  1482.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1483.                                 if($draftOld){
  1484.                                     $em->remove($draftOld);
  1485.                                     $em->flush();
  1486.                                 }
  1487.                                 $newDraft = new Draft();
  1488.                                 $newDraft->setTypeof('expense');
  1489.                                 $newDraft->setClient($clientObj);
  1490.                                 $newDraft->setClientGroup($groupObj);
  1491.                                 $newDraft->setToGroup($groupObj);
  1492.                                 $newDraft->setExpected('cgroup');
  1493.                                 $newDraft->setNote('Перевод Нал-Нал');
  1494.                                 $newDraft->setTypeTransaction('transfer');
  1495.                                 $em->persist($newDraft);
  1496.                                 $em->flush();
  1497.                             } else {
  1498.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  1499.                             }
  1500.                         } elseif($action == 'income_group_salary'){
  1501.                             $clients_q $this->getDoctrine()
  1502.                                 ->getRepository(Client::class)
  1503.                                 ->createQueryBuilder('cl')
  1504.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  1505.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  1506.                                 ->where('cl.typeof != :typeof')
  1507.                                 ->andWhere('cl.is_active = 1')
  1508.                                 ->setParameter('typeof'"private")
  1509.                                 ->setParameter('typeof_group'"salary")
  1510.                             ;
  1511.                             if($groupObj){
  1512.                                 $clients_q->andWhere('cl.id != ' $groupObj->getId());
  1513.                             }
  1514.                             $clients $clients_q->getQuery()->getArrayResult();
  1515.                             if(count($clients) > 0){
  1516.                                 $buttons = array();
  1517.                                 foreach ($clients as $item_client){
  1518.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  1519.                                     $buttons[][] = array(
  1520.                                         'text' => $name_client,
  1521.                                         'callback_data'=> json_encode(array("action" => "add_cgroup"'command' => "pay"'id' => $item_client['id'], "group" => $p_group))
  1522.                                     );
  1523.                                 }
  1524.                                 $buttons[][] = array(
  1525.                                     'text' => 'Назад',
  1526.                                     'callback_data'=> json_encode(array("action" => "income"'command' => "pay""group" => $p_group))
  1527.                                 );
  1528.                                 $keyboard $buttons;
  1529.                                 $reply 'Выбрано «Перевод ЗП-Нал». ' 'Выберите группу из которой будет списание средств.';
  1530.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1531.                                 if($draftOld){
  1532.                                     $em->remove($draftOld);
  1533.                                     $em->flush();
  1534.                                 }
  1535.                                 $newDraft = new Draft();
  1536.                                 $newDraft->setTypeof('expense');
  1537.                                 $newDraft->setClient($clientObj);
  1538.                                 $newDraft->setClientGroup($groupObj);
  1539.                                 $newDraft->setToGroup($groupObj);
  1540.                                 $newDraft->setExpected('cgroup');
  1541.                                 $newDraft->setNote('Перевод ЗП-Нал');
  1542.                                 $newDraft->setTypeTransaction('transfer');
  1543.                                 $em->persist($newDraft);
  1544.                                 $em->flush();
  1545.                             } else {
  1546.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  1547.                             }
  1548.                         } elseif($action == 'add_cgroup'){
  1549.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1550.                             $from_client false;
  1551.                             if(isset($cq_data['id'])){
  1552.                                 if($cq_data['id'] != '' && $cq_data['id'] != null){
  1553.                                     $from_client $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  1554.                                 }
  1555.                             }
  1556.                             if($draftObj && $from_client){
  1557.                                 $from_group_typeof = ($from_client->getTypeGroup() != '' && $from_client->getTypeGroup() != null $from_client->getTypeGroup() : 'cash');
  1558.                                 $groupObj false;
  1559.                                 if($p_group != '' && $p_group != null){
  1560.                                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  1561.                                 }
  1562.                                 $draftObj->setFromGroup($from_client);
  1563.                                 $draftObj->setExpected('amount');
  1564.                                 $em->persist($draftObj);
  1565.                                 $em->flush();
  1566.                                 $this->addExpected(($groupObj && $is_group_chat === true $groupObj $clientObj), array("value" => "amount""group" => $p_group));
  1567.                                 $reply 'Выбрано «Группа ' . ($from_client $from_client->nameClient() : '') . ' для списания с баланса». ' 'Введите сумму.';
  1568.                                 if($from_group_typeof != 'salary'){
  1569.                                     $buttons[][] = array(
  1570.                                         'text' => 'Назад',
  1571.                                         'callback_data'=> json_encode(array("action" => "income_group"'command' => "pay""group" => $p_group))
  1572.                                     );
  1573.                                 } else {
  1574.                                     $buttons[][] = array(
  1575.                                         'text' => 'Назад',
  1576.                                         'callback_data'=> json_encode(array("action" => "income_group_salary"'command' => "pay""group" => $p_group))
  1577.                                     );
  1578.                                 }
  1579.                                 $keyboard $buttons;
  1580.                             } else {
  1581.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  1582.                             }
  1583.                         } elseif($action == 'income_partner' || $action == 'add_client' || $action == 'other'){
  1584.                             //step 1
  1585.                             $offices $this->getDoctrine()
  1586.                                 ->getRepository(Office::class)
  1587.                                 ->createQueryBuilder('o')
  1588.                                 ->select('o.id, o.name, o.number')
  1589.                                 ->where('o.is_active = 1')
  1590.                                 ->getQuery()
  1591.                                 ->getArrayResult();
  1592.                             if(count($offices) > 0){
  1593.                                 if($action == 'income_partner'){
  1594.                                     $reply 'Выбрано «По Объекту». ' 'Выберите объект, по которому осуществляется приход.';
  1595.                                 } elseif($action == 'other'){
  1596.                                     $reply 'Выбрано «Расходы по Объекту». ' 'Выберите объект, по которому осуществляется расход.';
  1597.                                 }
  1598.                                 $buttons = array();
  1599.                                 foreach ($offices as $item_office){
  1600.                                     $buttons[][] = array(
  1601.                                         'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  1602.                                         'callback_data'=> json_encode(array("action" => "add_office"'command' => "pay"'id' => $item_office['id'], "group" => $p_group))
  1603.                                     );
  1604.                                 }
  1605.                                 if($action == 'income_partner'){
  1606.                                     $buttons[][] = array(
  1607.                                         'text' => 'Назад',
  1608.                                         'callback_data'=> json_encode(array("action" => "income"'command' => "pay""group" => $p_group))
  1609.                                     );
  1610.                                 } elseif($action == 'other'){
  1611.                                     $buttons[][] = array(
  1612.                                         'text' => 'Назад',
  1613.                                         'callback_data'=> json_encode(array("action" => "expense"'command' => "pay""group" => $p_group))
  1614.                                     );
  1615.                                 } elseif($action == 'add_client'){
  1616.                                     $buttons[][] = array(
  1617.                                         'text' => 'Назад',
  1618.                                         'callback_data'=> json_encode(array("action" => "salary"'command' => "pay""group" => $p_group))
  1619.                                     );
  1620.                                 }
  1621.                                 $keyboard $buttons;
  1622.                                 if($action == 'income_partner'){
  1623.                                     $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1624.                                     if($draftOld){
  1625.                                         $em->remove($draftOld);
  1626.                                         $em->flush();
  1627.                                     }
  1628.                                     $newDraft = new Draft();
  1629.                                     $newDraft->setTypeof('income');
  1630.                                     $newDraft->setClient($clientObj);
  1631.                                     $newDraft->setClientGroup($groupObj);
  1632.                                     $newDraft->setToGroup($groupObj);
  1633.                                     $newDraft->setExpected('office');
  1634.                                     $newDraft->setNote('Поступление средств');
  1635.                                     $newDraft->setTypeTransaction('income');
  1636.                                     $em->persist($newDraft);
  1637.                                     $em->flush();
  1638.                                 } elseif($action == 'add_client' || $action == 'other'){
  1639.                                     $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1640.                                     $to_client false;
  1641.                                     if(isset($cq_data['id'])){
  1642.                                         if($cq_data['id'] != '' && $cq_data['id'] != null){
  1643.                                             $to_client $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  1644.                                         }
  1645.                                     }
  1646.                                     if($draftObj){
  1647.                                         if($action == 'other'){
  1648.                                             $draftObj->setNote('Списание средств');
  1649.                                             $draftObj->setTypeTransaction('expense_office');
  1650.                                             $draftObj->setExpected('amount');
  1651.                                         }
  1652.                                         if($to_client){
  1653.                                             $draftObj->setToGroup($to_client);
  1654.                                             $draftObj->setExpected('office');
  1655.                                             if($action == 'add_client'){
  1656.                                                 $name_salary_client $to_client->nameClient();
  1657.                                                 $reply 'Выбрано «Группа ' $name_salary_client ' для выплаты зарплаты». ' 'Выберите объект, по которому выплачивается зарплата.';
  1658.                                             }
  1659.                                         }
  1660.                                         $em->persist($draftObj);
  1661.                                         $em->flush();
  1662.                                     }
  1663.                                 }
  1664.                             } else {
  1665.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
  1666.                             }
  1667.                         } elseif($action == 'expense'){
  1668.                             //step 1
  1669.                             $commandPermissions $this->curCommandPermissions($clientObj'pay');
  1670.                             $reply 'Выбрано «Расход». ' 'Выберите тип расхода.';
  1671. //                            $keyboard = array(
  1672. //                                array(
  1673. //                                    array(
  1674. //                                        'text'=>'Перевод Нал-ЗП',
  1675. //                                        'callback_data'=> json_encode(array('action' => "salary", 'command' => "pay", "group" => $p_group))
  1676. //                                    )
  1677. //                                ),
  1678. //                                array(
  1679. //                                    array(
  1680. //                                        'text'=>'Перевод Нал-Нал',
  1681. //                                        'callback_data'=> json_encode(array('action' => "transfer", 'command' => "pay", "group" => $p_group))
  1682. //                                    ),
  1683. //                                ),
  1684. //                                array(
  1685. //                                    array(
  1686. //                                        'text'=>'Расходы по Объекту',
  1687. //                                        'callback_data'=> json_encode(array('action' => "other", 'command' => "pay", "group" => $p_group))
  1688. //                                    ),
  1689. //                                ),
  1690. ////                                array(
  1691. ////                                    array(
  1692. ////                                        'text'=>'Расходы на компанию',
  1693. ////                                        'callback_data'=> json_encode(array('action' => "company", 'command' => "pay", "group" => $p_group))
  1694. ////                                    ),
  1695. ////                                ),
  1696. //                                array(
  1697. //                                    array(
  1698. //                                        'text'=>'Назад',
  1699. //                                        'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => $p_group))
  1700. //                                    ),
  1701. //                                )
  1702. //                            );
  1703.                             $keyboard = [];
  1704.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_expense_transfer_cash_to_salary'$commandPermissions))){
  1705.                                 //Расход -> Превод Нал-ЗП
  1706.                                 $keyboard[] = [[
  1707.                                     'text'=>'Перевод Нал-ЗП',
  1708.                                     'callback_data'=> json_encode(array('action' => "salary"'command' => "pay""group" => $p_group))
  1709.                                 ]];
  1710.                             }
  1711.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_expense_transfer_cash_to_cash'$commandPermissions))){
  1712.                                 //Расход -> Превод Нал-Нал
  1713.                                 $keyboard[] = [[
  1714.                                     'text'=>'Перевод Нал-Нал',
  1715.                                     'callback_data'=> json_encode(array('action' => "transfer"'command' => "pay""group" => $p_group))
  1716.                                 ]];
  1717.                             }
  1718.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_expense_office'$commandPermissions))){
  1719.                                 //Расход -> Расходы по Объекту
  1720.                                 $keyboard[] = [[
  1721.                                     'text'=>'Расходы по Объекту',
  1722.                                     'callback_data'=> json_encode(array('action' => "other"'command' => "pay""group" => $p_group))
  1723.                                 ]];
  1724.                             }
  1725. //                            $keyboard[] = [[
  1726. //                                'text'=>'Расходы на компанию',
  1727. //                                'callback_data'=> json_encode(array('action' => "company", 'command' => "pay", "group" => $p_group))
  1728. //                            ]];
  1729.                             $keyboard[] = [[
  1730.                                 'text'=>'Назад',
  1731.                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  1732.                             ]];
  1733.                             $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1734.                             if($draftOld){
  1735.                                 $em->remove($draftOld);
  1736.                                 $em->flush();
  1737.                             }
  1738.                             $newDraft = new Draft();
  1739.                             $newDraft->setTypeof('expense');
  1740.                             $newDraft->setClient($clientObj);
  1741.                             $newDraft->setClientGroup($groupObj);
  1742.                             $newDraft->setFromGroup($groupObj);
  1743.                             $newDraft->setExpected('type_expense');
  1744.                             $em->persist($newDraft);
  1745.                             $em->flush();
  1746.                         } elseif($action == 'add_office' || $action == 'add_director'){
  1747.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1748.                             $officeObj false;
  1749.                             $directorObj false;
  1750.                             if($action == 'add_office'){
  1751.                                 if(isset($cq_data['id'])){
  1752.                                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  1753.                                         $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  1754.                                     }
  1755.                                 }
  1756.                                 if($officeObj){
  1757.                                     $draftObj->setOffice($officeObj);
  1758.                                 }
  1759.                             } elseif($action == 'add_director'){
  1760.                                 if(isset($cq_data['id'])){
  1761.                                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  1762.                                         $directorObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  1763.                                     }
  1764.                                 }
  1765.                                 if($directorObj){
  1766.                                     $draftObj->setToGroup($directorObj);
  1767.                                 }
  1768.                             }
  1769.                             $selected '';
  1770.                             if($action == 'add_office' && $officeObj){
  1771.                                 $selected 'Выбрано «Объект ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() . '». ';
  1772.                             } elseif($action == 'add_director' && $directorObj){
  1773.                                 $name_director $directorObj->nameClient();
  1774.                                 $selected 'Выбрано «Руководитель' . ($name_director != '' && $name_director != null ' ' $name_director '') . '». ';
  1775.                             }
  1776.                             if($draftObj){
  1777.                                 $draftObj->setExpected('amount');
  1778.                                 $em->persist($draftObj);
  1779.                                 $em->flush();
  1780.                                 $this->addExpected(($is_group_chat === true && $groupObj $groupObj $clientObj), array("value" => "amount""group" => $p_group));
  1781.                                 $reply $selected 'Введите сумму';
  1782. //                                if($action == 'add_office'){
  1783. //                                    $keyboard = array(
  1784. //                                        array(
  1785. //                                            array(
  1786. //                                                'text'=>'Назад',
  1787. //                                                'callback_data'=> json_encode(array('action' => "other", 'command' => "pay", "group" => $p_group))
  1788. //                                            ),
  1789. //                                        )
  1790. //                                    );
  1791. //                                } else {
  1792. //                                    $keyboard = array(
  1793. //                                        array(
  1794. //                                            array(
  1795. //                                                'text'=>'Назад',
  1796. //                                                'callback_data'=> json_encode(array('action' => "income_partner", 'command' => "pay", "group" => $p_group))
  1797. //                                            ),
  1798. //                                        )
  1799. //                                    );
  1800. //                                }
  1801.                             } else {
  1802.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  1803.                             }
  1804.                         } elseif($action == 'salary'){
  1805.                             $clients_q $this->getDoctrine()
  1806.                                 ->getRepository(Client::class)
  1807.                                 ->createQueryBuilder('cl')
  1808.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  1809.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  1810.                                 ->where('cl.typeof != :typeof')
  1811.                                 ->andWhere('cl.is_active = 1')
  1812.                                 ->setParameter('typeof'"private")
  1813.                                 ->setParameter('typeof_group'"salary")
  1814.                             ;
  1815.                             if($groupObj){
  1816.                                 $clients_q->andWhere('cl.id != ' $groupObj->getId());
  1817.                             }
  1818.                             $clients $clients_q->getQuery()->getArrayResult();
  1819.                             if(count($clients) > 0){
  1820.                                 $buttons = array();
  1821.                                 foreach ($clients as $item_client){
  1822.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  1823.                                     $buttons[][] = array(
  1824.                                         'text' => $name_client,
  1825.                                         'callback_data'=> json_encode(array("action" => "add_client"'command' => "pay"'id' => $item_client['id'], "group" => $p_group))
  1826.                                     );
  1827.                                 }
  1828.                                 $buttons[][] = array(
  1829.                                     'text'=>'Назад',
  1830.                                     'callback_data'=> json_encode(array('action' => "expense"'command' => "pay""group" => $p_group))
  1831.                                 );
  1832.                                 $keyboard $buttons;
  1833.                                 $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1834.                                 if($draftObj){
  1835.                                     $draftObj->setNote('Перевод Нал-ЗП');
  1836.                                     $draftObj->setTypeTransaction('add_salary');
  1837.                                     $draftObj->setExpected('to_group');
  1838.                                     $em->persist($draftObj);
  1839.                                     $em->flush();
  1840.                                     $reply 'Выбрано «Перевод Нал-ЗП». ' 'Выберите группу, которой будет осуществлен перевод.';
  1841.                                 } else {
  1842.                                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  1843.                                     $keyboard = array();
  1844.                                 }
  1845.                             } else {
  1846.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  1847.                             }
  1848.                         } elseif($action == 'transfer'){
  1849.                             $clients_q $this->getDoctrine()
  1850.                                 ->getRepository(Client::class)
  1851.                                 ->createQueryBuilder('cl')
  1852.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  1853.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  1854.                                 ->where('cl.typeof != :typeof')
  1855.                                 ->andWhere('cl.is_active = 1')
  1856.                                 ->setParameter('typeof'"private")
  1857.                                 ->setParameter('typeof_group'"cash")
  1858.                             ;
  1859.                             if($groupObj){
  1860.                                 $clients_q->andWhere('cl.id != ' $groupObj->getId());
  1861.                             }
  1862.                             $clients $clients_q->getQuery()->getArrayResult();
  1863.                             if(count($clients) > 0){
  1864.                                 $buttons = array();
  1865.                                 foreach ($clients as $item_client){
  1866.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  1867.                                     $buttons[][] = array(
  1868.                                         'text' => $name_client,
  1869.                                         'callback_data'=> json_encode(array("action" => "add_director"'command' => "pay"'id' => $item_client['id'], "group" => $p_group))
  1870.                                     );
  1871.                                 }
  1872.                                 $buttons[][] =  array(
  1873.                                     'text'=>'Назад',
  1874.                                     'callback_data'=> json_encode(array('action' => "expense"'command' => "pay""group" => $p_group))
  1875.                                 );
  1876.                                 $keyboard $buttons;
  1877.                                 $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1878.                                 if($draftObj){
  1879.                                     $draftObj->setNote('Перевод Нал-Нал');
  1880.                                     $draftObj->setTypeTransaction('transfer');
  1881.                                     $draftObj->setExpected('to_group');
  1882.                                     $em->persist($draftObj);
  1883.                                     $em->flush();
  1884.                                     $reply 'Выбрано «Перевод Нал-Нал». ' 'Выберите группу для перевода';
  1885.                                 } else {
  1886.                                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  1887.                                     $keyboard = array();
  1888.                                 }
  1889.                             } else {
  1890.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  1891.                             }
  1892.                         } elseif($action == 'company'){
  1893.                             $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1894.                             if($draftOld){
  1895.                                 $em->remove($draftOld);
  1896.                                 $em->flush();
  1897.                             }
  1898.                             $newDraft = new Draft();
  1899.                             $newDraft->setTypeof('expense');
  1900.                             $newDraft->setClient($clientObj);
  1901.                             $newDraft->setClientGroup($groupObj);
  1902.                             $newDraft->setFromGroup($groupObj);
  1903.                             $newDraft->setExpected('amount');
  1904.                             $newDraft->setNote('Списание средств на компанию');
  1905.                             $newDraft->setTypeTransaction('expense_company');
  1906.                             $em->persist($newDraft);
  1907.                             $em->flush();
  1908.                             $this->addExpected(($is_group_chat === true && $groupObj $groupObj $clientObj), array("value" => "amount""group" => $p_group));
  1909.                             $reply 'Выбрано «Расходы на компанию». ' 'Введите сумму.';
  1910.                         } elseif($action == 'no_cheque' || $action == 'finish_pay'){
  1911.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1912.                             $draftObj->setExpected('finish');
  1913.                             $em->persist($draftObj);
  1914.                             $em->flush();
  1915.                             $this->resetExpected($curClient);
  1916.                             $create_transaction $this->createTransaction($token$chat_id$groupObj$draftObj);
  1917.                             if($create_transaction === true){
  1918.                                 $em->remove($draftObj);
  1919.                                 $em->flush();
  1920.                             }
  1921.                             $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Транзакция успешно добавлена.';
  1922.                         }
  1923.                     } elseif($type_group_typeof == 'salary'){
  1924.                         if($action == 'income'){
  1925.                             $offices $this->getDoctrine()
  1926.                                 ->getRepository(Office::class)
  1927.                                 ->createQueryBuilder('o')
  1928.                                 ->select('o.id, o.name, o.number')
  1929.                                 ->where('o.is_active = 1')
  1930.                                 ->getQuery()
  1931.                                 ->getArrayResult();
  1932.                             if(count($offices) > 0){
  1933.                                 $reply 'Выбрано «Перевод в группу ЗП». ' 'Выберите объект, по которому осуществляется выплата зарплаты.';
  1934.                                 $buttons = array();
  1935.                                 foreach ($offices as $item_office){
  1936.                                     $buttons[][] = array(
  1937.                                         'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  1938.                                         'callback_data'=> json_encode(array("action" => "add_office"'command' => "pay"'id' => $item_office['id'], "group" => $p_group))
  1939.                                     );
  1940.                                 }
  1941.                                 $buttons[][] =  array(
  1942.                                     'text'=>'Назад',
  1943.                                     'callback_data'=> json_encode(array('action' => "delete"'command' => "pay""group" => $p_group))
  1944.                                 );
  1945.                                 $keyboard $buttons;
  1946.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1947.                                 if($draftOld){
  1948.                                     $em->remove($draftOld);
  1949.                                     $em->flush();
  1950.                                 }
  1951.                                 $newDraft = new Draft();
  1952.                                 $newDraft->setTypeof('expense');
  1953.                                 $newDraft->setClient($clientObj);
  1954.                                 $newDraft->setClientGroup($groupObj);
  1955.                                 $newDraft->setToGroup($groupObj);
  1956.                                 $newDraft->setExpected('office');
  1957.                                 $newDraft->setNote('Перевод в группу ЗП');
  1958.                                 $newDraft->setTypeTransaction('add_salary');
  1959.                                 $em->persist($newDraft);
  1960.                                 $em->flush();
  1961.                             } else {
  1962.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
  1963.                             }
  1964.                         } elseif($action == 'income_cash'){
  1965.                             $offices $this->getDoctrine()
  1966.                                 ->getRepository(Office::class)
  1967.                                 ->createQueryBuilder('o')
  1968.                                 ->select('o.id, o.name, o.number')
  1969.                                 ->where('o.is_active = 1')
  1970.                                 ->getQuery()
  1971.                                 ->getArrayResult();
  1972.                             if(count($offices) > 0){
  1973.                                 $reply 'Выбрано «Перевод в группу Нал». ' 'Выберите объект, по которому осуществляется выплата зарплаты.';
  1974.                                 $buttons = array();
  1975.                                 foreach ($offices as $item_office){
  1976.                                     $buttons[][] = array(
  1977.                                         'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  1978.                                         'callback_data'=> json_encode(array("action" => "add_office"'command' => "pay"'id' => $item_office['id'], "group" => $p_group))
  1979.                                     );
  1980.                                 }
  1981.                                 $buttons[][] =  array(
  1982.                                     'text'=>'Назад',
  1983.                                     'callback_data'=> json_encode(array('action' => "delete"'command' => "pay""group" => $p_group))
  1984.                                 );
  1985.                                 $keyboard $buttons;
  1986.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  1987.                                 if($draftOld){
  1988.                                     $em->remove($draftOld);
  1989.                                     $em->flush();
  1990.                                 }
  1991.                                 $newDraft = new Draft();
  1992. //                                $newDraft->setTypeof('expense');
  1993.                                 $newDraft->setTypeof('income');
  1994.                                 $newDraft->setClient($clientObj);
  1995.                                 $newDraft->setClientGroup($groupObj);
  1996.                                 $newDraft->setToGroup($groupObj);
  1997.                                 $newDraft->setExpected('office');
  1998.                                 $newDraft->setNote('Перевод в группу Нал');
  1999.                                 $newDraft->setTypeTransaction('add_salary_cash');
  2000.                                 $em->persist($newDraft);
  2001.                                 $em->flush();
  2002.                             } else {
  2003.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
  2004.                             }
  2005.                         } elseif($action == 'add_office'){
  2006.                             $clients_q $this->getDoctrine()
  2007.                                 ->getRepository(Client::class)
  2008.                                 ->createQueryBuilder('cl')
  2009.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  2010.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  2011.                                 ->where('cl.typeof != :typeof')
  2012.                                 ->andWhere('cl.is_active = 1')
  2013.                                 ->setParameter('typeof'"private")
  2014.                                 ->setParameter('typeof_group'"cash")
  2015.                             ;
  2016.                             $clients $clients_q->getQuery()->getArrayResult();
  2017.                             if(count($clients) > 0){
  2018.                                 $buttons = array();
  2019.                                 foreach ($clients as $item_client){
  2020.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  2021.                                     $buttons[][] = array(
  2022.                                         'text' => $name_client,
  2023.                                         'callback_data'=> json_encode(array("action" => "add_client"'command' => "pay"'id' => $item_client['id'], "group" => $p_group))
  2024.                                     );
  2025.                                 }
  2026.                                 $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2027.                                 if($draftObj){
  2028.                                     $officeObj false;
  2029.                                     if(isset($cq_data['id'])){
  2030.                                         if($cq_data['id'] != '' && $cq_data['id'] != null){
  2031.                                             $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  2032.                                         }
  2033.                                     }
  2034.                                     if($officeObj){
  2035.                                         $draftObj->setOffice($officeObj);
  2036.                                     }
  2037.                                     $draftObj->setExpected('from_group');
  2038.                                     $em->persist($draftObj);
  2039.                                     $em->flush();
  2040.                                     if($draftObj->getTypeTransaction() != 'add_salary_cash'){
  2041.                                         $buttons[][] =  array(
  2042.                                             'text'=>'Назад',
  2043.                                             'callback_data'=> json_encode(array('action' => "income"'command' => "pay""group" => $p_group))
  2044.                                         );
  2045.                                         $keyboard $buttons;
  2046.                                         $reply 'Выбрано «Объект' . ($officeObj ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() : '') . '». ' 'Выберите группу, c которой будут списаны средства.';
  2047.                                     } else {
  2048.                                         $buttons[][] =  array(
  2049.                                             'text'=>'Назад',
  2050.                                             'callback_data'=> json_encode(array('action' => "income_cash"'command' => "pay""group" => $p_group))
  2051.                                         );
  2052.                                         $keyboard $buttons;
  2053.                                         $reply 'Выбрано «Объект' . ($officeObj ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() : '') . '». ' 'Выберите группу, в которую будут переведены средства.';
  2054.                                     }
  2055.                                 } else {
  2056.                                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  2057.                                     $keyboard = array();
  2058.                                 }
  2059.                             } else {
  2060.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  2061.                             }
  2062.                         } elseif($action == 'add_client'){
  2063.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2064.                             $to_client false;
  2065.                             if(isset($cq_data['id'])){
  2066.                                 if($cq_data['id'] != '' && $cq_data['id'] != null){
  2067.                                     $to_client $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  2068.                                 }
  2069.                             }
  2070.                             if($draftObj && $to_client){
  2071.                                 $groupObj false;
  2072.                                 if($p_group != '' && $p_group != null){
  2073.                                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  2074.                                 }
  2075.                                 $draftObj->setFromGroup($to_client);
  2076.                                 $draftObj->setExpected('amount');
  2077.                                 $em->persist($draftObj);
  2078.                                 $em->flush();
  2079.                                 $this->addExpected(($groupObj && $is_group_chat === true $groupObj $clientObj), array("value" => "amount""group" => $p_group));
  2080.                                 if($draftObj->getTypeTransaction() != 'add_salary_cash'){
  2081.                                     $reply 'Выбрано «Группа ' . ($to_client $to_client->nameClient() : '') . ' для списания средств». ' 'Введите сумму.';
  2082.                                 } else {
  2083.                                     $reply 'Выбрано «Группа ' . ($to_client $to_client->nameClient() : '') . ' для перевода средств». ' 'Введите сумму.';
  2084.                                 }
  2085.                             } else {
  2086.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  2087.                             }
  2088.                         } elseif($action == 'expense'){
  2089.                             $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2090.                             if($draftOld){
  2091.                                 $em->remove($draftOld);
  2092.                                 $em->flush();
  2093.                             }
  2094.                             $newDraft = new Draft();
  2095.                             $newDraft->setTypeof('expense');
  2096.                             $newDraft->setClient($clientObj);
  2097.                             $newDraft->setClientGroup($groupObj);
  2098.                             $newDraft->setToGroup($groupObj);
  2099.                             //$newDraft->setFromGroup($groupObj);
  2100.                             $newDraft->setExpected('add_office_expense');
  2101.                             $newDraft->setNote('Начисление зарплаты');
  2102.                             $newDraft->setTypeTransaction('payment_salary');
  2103.                             $em->persist($newDraft);
  2104.                             $em->flush();
  2105.                             $offices $this->getDoctrine()
  2106.                                 ->getRepository(Office::class)
  2107.                                 ->createQueryBuilder('o')
  2108.                                 ->select('o.id, o.name, o.number')
  2109.                                 ->where('o.is_active = 1')
  2110.                                 ->getQuery()
  2111.                                 ->getArrayResult();
  2112.                             if(count($offices) > 0){
  2113.                                 $reply 'Выбрано «Начисление зарплаты». ' 'Выберите объект, по которому осуществляется начисление зарплаты.';
  2114.                                 $keyboard = array();
  2115.                                 $buttons = array();
  2116.                                 foreach ($offices as $item_office){
  2117.                                     $buttons[][] = array(
  2118.                                         'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  2119.                                         'callback_data'=> json_encode(array("action" => "add_office_exp"'command' => "pay"'id' => $item_office['id'], "group" => $p_group))
  2120.                                     );
  2121.                                 }
  2122.                                 $buttons[][] =  array(
  2123.                                     'text'=>'Назад',
  2124.                                     'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2125.                                 );
  2126.                                 $keyboard $buttons;
  2127.                             } else {
  2128.                                 $reply 'Нет объектов для начисление зарплаты по ним.';
  2129.                             }
  2130.                             /*
  2131.                             $groupObj = false;
  2132.                             if($p_group != '' && $p_group != null){
  2133.                                 $groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  2134.                             }
  2135.                             $this->addExpected(($groupObj && $is_group_chat === true ? $groupObj : $clientObj), array("value" => "amount", "group" => $p_group));
  2136.                             $reply = 'Выбрано «Начисление зарплаты». ' . 'Введите сумму';
  2137.                             */
  2138.                         } elseif($action == 'expense_salary') {
  2139.                             //операция начисление оклада
  2140.                             $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
  2141.                             if(count($salarySchedule) > 0){
  2142.                                 $max_ss $this->getParameter('app.max.salary_schedule');
  2143.                                 if(count($salarySchedule) < $max_ss){
  2144.                                     $reply 'Выбрано «Начисление оклада». Можете отредактировать условия начисления оклада по нужным числам месяца, добавить новое или удалить лишнее';
  2145.                                     $keyboard = array(
  2146.                                         array(
  2147.                                             array(
  2148.                                                 'text'=>'Редактировать условие начисления',
  2149.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_date"'command' => "pay""group" => $p_group))
  2150.                                             )
  2151.                                         ),
  2152.                                         array(
  2153.                                             array(
  2154.                                                 'text'=>'Новое условие начисления',
  2155.                                                 'callback_data'=> json_encode(array('action' => "new_ss_date"'command' => "pay""group" => $p_group))
  2156.                                             )
  2157.                                         ),
  2158.                                         array(
  2159.                                             array(
  2160.                                                 'text'=>'Удалить условие начисления',
  2161.                                                 'callback_data'=> json_encode(array('action' => "rem_ss_date"'command' => "pay""group" => $p_group))
  2162.                                             )
  2163.                                         ),
  2164.                                         array(
  2165.                                             array(
  2166.                                                 'text'=>'Назад',
  2167.                                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2168.                                             )
  2169.                                         )
  2170.                                     );
  2171.                                 } else {
  2172.                                     $reply 'Выбрано «Начисление оклада». Можете отредактировать условия начисления оклада по нужным числам месяца или удалить лишнее';
  2173.                                     $keyboard = array(
  2174.                                         array(
  2175.                                             array(
  2176.                                                 'text'=>'Редактировать условие начисления',
  2177.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_date"'command' => "pay""group" => $p_group))
  2178.                                             )
  2179.                                         ),
  2180.                                         array(
  2181.                                             array(
  2182.                                                 'text'=>'Удалить условие начисления',
  2183.                                                 'callback_data'=> json_encode(array('action' => "rem_ss_date"'command' => "pay""group" => $p_group))
  2184.                                             )
  2185.                                         ),
  2186.                                         array(
  2187.                                             array(
  2188.                                                 'text'=>'Назад',
  2189.                                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2190.                                             )
  2191.                                         )
  2192.                                     );
  2193.                                 }
  2194.                             } else {
  2195.                                 $reply 'Выбрано «Начисление оклада». Для начисления оклада по нужным числам месяца необходимо добавить условие начисления';
  2196.                                 $keyboard = array(array(
  2197.                                         array(
  2198.                                             'text'=>'Новое условие начисления',
  2199.                                             'callback_data'=> json_encode(array('action' => "new_ss_date"'command' => "pay""group" => $p_group))
  2200.                                         )
  2201.                                     ),
  2202.                                     array(
  2203.                                         array(
  2204.                                             'text'=>'Назад',
  2205.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2206.                                         )
  2207.                                     )
  2208.                                 );
  2209.                             }
  2210.                         } elseif($action == 'new_ss_date') {
  2211.                             //новое условие начисления оклада
  2212.                             $reply 'Введите число дня месяца, в который будет осуществляться начисления оклада';
  2213.                             $keyboard = array(
  2214.                                 array(
  2215.                                     array(
  2216.                                         'text'=>'Назад',
  2217.                                         'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "pay""group" => $p_group))
  2218.                                     )
  2219.                                 )
  2220.                             );
  2221.                             $groupObj false;
  2222.                             if($p_group != '' && $p_group != null){
  2223.                                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  2224.                             }
  2225.                             $this->addExpected(($groupObj && $is_group_chat === true $groupObj $clientObj), array("value" => "new_date""group" => $p_group));
  2226.                         } elseif($action == 'edit_ss_date') {
  2227.                             //изменить условие начисления оклада
  2228.                             $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
  2229.                             if(count($salarySchedule) > 0){
  2230.                                 $reply 'Выберите из списка условие для начисления оклада, которое хотите отредактировать';
  2231.                                 $buttons = array();
  2232.                                 foreach ($salarySchedule as $item_ss){
  2233.                                     $buttons[][] = array(
  2234.                                         'text' => $item_ss['day'] . ' числа каждого месяца по ' $item_ss['amount'] . ' руб',
  2235.                                         'callback_data'=> json_encode(array("action" => "edit_ss"'command' => "pay"'ss_id' => $item_ss['id'], "group" => $p_group))
  2236.                                     );
  2237.                                 }
  2238.                                 $buttons[][] =  array(
  2239.                                     'text'=>'Назад',
  2240.                                     'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "pay""group" => $p_group))
  2241.                                 );
  2242.                                 $keyboard $buttons;
  2243.                             } else {
  2244.                                 $reply 'Условий для начисления оклада не найдено, можете создать новое';
  2245.                                 $keyboard = array(array(
  2246.                                     array(
  2247.                                         'text'=>'Новое условие начисления',
  2248.                                         'callback_data'=> json_encode(array('action' => "new_ss_date"'command' => "pay""group" => $p_group))
  2249.                                     )
  2250.                                 ),
  2251.                                     array(
  2252.                                         array(
  2253.                                             'text'=>'Назад',
  2254.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2255.                                         )
  2256.                                     )
  2257.                                 );
  2258.                             }
  2259.                         } elseif($action == 'rem_ss_date') {
  2260.                             //удалить условие начисления оклада
  2261.                             $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
  2262.                             if(count($salarySchedule) > 0){
  2263.                                 $reply 'Выберите из списка условие для начисления оклада, которое хотите удалить';
  2264.                                 $buttons = array();
  2265.                                 foreach ($salarySchedule as $item_ss){
  2266.                                     $buttons[][] = array(
  2267.                                         'text' => $item_ss['day'] . ' числа каждого месяца по ' $item_ss['amount'] . ' руб',
  2268.                                         'callback_data'=> json_encode(array("action" => "rem_ss"'command' => "pay"'ss_id' => $item_ss['id'], "group" => $p_group))
  2269.                                     );
  2270.                                 }
  2271.                                 $buttons[][] =  array(
  2272.                                     'text'=>'Назад',
  2273.                                     'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "pay""group" => $p_group))
  2274.                                 );
  2275.                                 $keyboard $buttons;
  2276.                             } else {
  2277.                                 $reply 'Условий для начисления оклада не найдено, можете создать новое';
  2278.                                 $keyboard = array(array(
  2279.                                     array(
  2280.                                         'text'=>'Новое условие начисления',
  2281.                                         'callback_data'=> json_encode(array('action' => "new_ss_date"'command' => "pay""group" => $p_group))
  2282.                                     )
  2283.                                 ),
  2284.                                     array(
  2285.                                         array(
  2286.                                             'text'=>'Назад',
  2287.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2288.                                         )
  2289.                                     )
  2290.                                 );
  2291.                             }
  2292.                         } elseif($action == 'edit_ss'){
  2293.                             //изменить условие начисления оклада
  2294.                             $id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
  2295.                             $isExistSs false;
  2296.                             if($id != '' && $id != null){
  2297.                                 $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
  2298.                                 if($salarySchedule){
  2299.                                     $isExistSs true;
  2300.                                     $reply 'Выбрано для редактирования условие для начисления «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() .  ' руб». Выберите, что нужно отредактировать';
  2301.                                     $keyboard = array(
  2302.                                         array(
  2303.                                             array(
  2304.                                                 'text'=>'Число месяца',
  2305.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_d"'command' => "pay"'ss_id' => $salarySchedule->getId(), "group" => $p_group))
  2306.                                             ),
  2307.                                             array(
  2308.                                                 'text'=>'Сумму начисления',
  2309.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_a"'command' => "pay"'ss_id' => $salarySchedule->getId(), "group" => $p_group))
  2310.                                             )
  2311.                                         ),
  2312.                                         array(
  2313.                                             array(
  2314.                                                 'text'=>'Назад',
  2315.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_date"'command' => "pay""group" => $p_group))
  2316.                                             )
  2317.                                         )
  2318.                                     );
  2319.                                 }
  2320.                             }
  2321.                             if(!$isExistSs){
  2322.                                 $reply 'Не удалось найти условий для начисления оклада';
  2323.                                 $keyboard = array(
  2324.                                     array(
  2325.                                         array(
  2326.                                             'text'=>'В основное меню',
  2327.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2328.                                         )
  2329.                                     )
  2330.                                 );
  2331.                             }
  2332.                         } elseif($action == 'edit_ss_d' || $action == 'edit_ss_a') {
  2333.                             //изменить условие начисления оклада
  2334.                             $id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
  2335.                             $isExistSs false;
  2336.                             if($id != '' && $id != null){
  2337.                                 $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
  2338.                                 if($salarySchedule){
  2339.                                     $isExistSs true;
  2340.                                     if($action == 'edit_ss_d'){
  2341.                                         $reply 'Введите новое число дня месяца для условия начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() .  ' руб»';
  2342.                                         $this->addExpected(($is_group_chat === true && $groupObj $groupObj $clientObj), array("value" => "edit_ss_d""ss_id" => $salarySchedule->getId(), "group" => $p_group));
  2343.                                     } else {
  2344.                                         $reply 'Введите новую сумму для условия начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() .  ' руб»';
  2345.                                         $this->addExpected(($is_group_chat === true && $groupObj $groupObj $clientObj), array("value" => "edit_ss_a""ss_id" => $salarySchedule->getId(), "group" => $p_group));
  2346.                                     }
  2347.                                 }
  2348.                             }
  2349.                             if(!$isExistSs){
  2350.                                 $reply 'Не удалось найти условий для начисления оклада';
  2351.                                 $keyboard = array(
  2352.                                     array(
  2353.                                         array(
  2354.                                             'text'=>'В основное меню',
  2355.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2356.                                         )
  2357.                                     )
  2358.                                 );
  2359.                             }
  2360.                         } elseif($action == 'rem_ss'){
  2361.                             //удалить условие начисления оклада
  2362.                             $id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
  2363.                             $isExistSs false;
  2364.                             if($id != '' && $id != null){
  2365.                                 $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
  2366.                                 if($salarySchedule){
  2367.                                     $isExistSs true;
  2368.                                     $reply 'Условие для начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() .  ' руб» успешно удалено';
  2369.                                     $em->remove($salarySchedule);
  2370.                                     $em->flush();
  2371.                                     $keyboard = array(
  2372.                                         array(
  2373.                                             array(
  2374.                                                 'text'=>'Назад',
  2375.                                                 'callback_data'=> json_encode(array('action' => "rem_ss_date"'command' => "pay""group" => $p_group))
  2376.                                             )
  2377.                                         ),
  2378.                                         array(
  2379.                                             array(
  2380.                                                 'text'=>'В основное меню',
  2381.                                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2382.                                             )
  2383.                                         )
  2384.                                     );
  2385.                                 }
  2386.                             }
  2387.                             if(!$isExistSs){
  2388.                                 $reply 'Не удалось найти условий для начисления оклада';
  2389.                                 $keyboard = array(
  2390.                                     array(
  2391.                                         array(
  2392.                                             'text'=>'В основное меню',
  2393.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2394.                                         )
  2395.                                     )
  2396.                                 );
  2397.                             }
  2398.                         } elseif($action == 'add_office_exp'){
  2399.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2400.                             if($draftObj){
  2401.                                 $officeObj false;
  2402.                                 if(isset($cq_data['id'])){
  2403.                                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  2404.                                         $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  2405.                                     }
  2406.                                 }
  2407.                                 if($officeObj){
  2408.                                     $draftObj->setOffice($officeObj);
  2409.                                 }
  2410.                                 $draftObj->setExpected('amount');
  2411.                                 $em->persist($draftObj);
  2412.                                 $em->flush();
  2413.                                 $reply 'Выбрано «Объект' . ($officeObj ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() : '') . ' для начисления зарплаты». ' 'Введите сумму.';
  2414.                                 $groupObj false;
  2415.                                 if($p_group != '' && $p_group != null){
  2416.                                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  2417.                                 }
  2418.                                 $this->addExpected(($groupObj && $is_group_chat === true $groupObj $clientObj), array("value" => "amount""group" => $p_group));
  2419.                             } else {
  2420.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  2421.                                 $keyboard = array();
  2422.                             }
  2423.                         }
  2424.                     }
  2425.                 } else {
  2426.                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить добавление финансовой операции, у данной группы не выбран тип группы. Пожалуйста укажите тип группы данной группе и начните добавление операции занова.';
  2427.                 }
  2428.             } else {
  2429.                 $reply 'Финансовые операции начинаются из группы, пожалуйста отправьте команду для начала операции в нужной группе.';
  2430.             }
  2431.         } elseif($expected != '' && $expected != null){
  2432.             $curClientObj false;
  2433.             if($is_group_chat === true){
  2434.                 $curClientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  2435.             }
  2436.             if($curClient && (($text != '' && $text != null) || ($file_id != '' && $file_id != null))){
  2437.                 $groupObj false;
  2438.                 if($group_id != null && $group_id != ''){
  2439.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  2440.                 } elseif($p_group != null && $p_group != '') {
  2441.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  2442.                 }
  2443.                 if($groupObj && $curClient){
  2444.                     $name_group $groupObj->nameClient();
  2445.                     $type_group_typeof null;
  2446.                     if($groupObj->getTypeGroup()){
  2447.                         $type_group_typeof $groupObj->getTypeGroup()->getTypeof();
  2448.                     }
  2449.                     if($is_group_chat === true && $groupObj){
  2450.                         $chat_id $groupObj->getChatId();
  2451.                     }
  2452.                     $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => ($curClientObj $curClientObj->getId() : $curClient->getId()), 'client_group' => $groupObj));
  2453.                     if($draftObj){
  2454.                         if($expected == 'amount'){
  2455.                             $amount = (float) $text;
  2456.                             if($amount || $draftObj->getTypeTransaction() == 'payment_salary'){
  2457.                                 $draftObj->setAmount($amount 100);
  2458.                                 $draftObj->setExpected('comment');
  2459.                                 $em->persist($draftObj);
  2460.                                 $em->flush();
  2461.                                 $this->addExpected($curClient, array("value" => "comment""group" => $p_group));
  2462.                                 $sum str_replace(',00'''number_format(($draftObj->getAmount() / 100), 2','' '));
  2463.                                 $reply 'Введено «Сумма ' $sum '». ' 'Введите комментарий';
  2464.                             } else {
  2465.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Неправильно указана сумма, укажите сумму числом.';
  2466.                             }
  2467.                         } elseif($expected == 'comment') {
  2468.                             if($draftObj->getTypeTransaction() == 'expense_office'){
  2469.                                 $draftObj->setComment(trim($text));
  2470.                                 $draftObj->setExpected('file_cheque');
  2471.                                 $em->persist($draftObj);
  2472.                                 $em->flush();
  2473.                                 $this->addExpected($curClient, array("value" => "file_cheque""group" => $p_group));
  2474.                                 $keyboard = [
  2475.                                     [
  2476.                                         [
  2477.                                             'text'=>'Без чека',
  2478.                                             'callback_data'=> json_encode(array('action' => "no_cheque"'command' => "pay""group" => $p_group))
  2479.                                         ]
  2480.                                     ]
  2481.                                 ];
  2482.                                 $reply 'Сделайте или прикрепите фото чека';
  2483.                             } else {
  2484.                                 $draftObj->setComment(trim($text));
  2485.                                 $draftObj->setExpected('finish');
  2486.                                 $em->persist($draftObj);
  2487.                                 $em->flush();
  2488.                                 $this->resetExpected($curClient);
  2489.                                 $create_transaction $this->createTransaction($token$chat_id$groupObj$draftObj);
  2490.                                 if($create_transaction === true){
  2491.                                     $em->remove($draftObj);
  2492.                                     $em->flush();
  2493.                                 }
  2494.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Транзакция успешно добавлена.';
  2495.                             }
  2496.                         } elseif($expected == 'file_cheque') {
  2497.                             $file null;
  2498.                             if($file_id != '' && $file_id != null){
  2499.                                 $file $this->uploadFileBot($token$file_id);
  2500.                             }
  2501.                             if($file != null){
  2502.                                 $draftObj->setFile(($draftObj->getFile() != null && $draftObj->getFile() != '' $draftObj->getFile() . ';' $file $file));
  2503.                                 $em->persist($draftObj);
  2504.                                 $em->flush();
  2505.                                 $reply 'Фото чека успешно прикреплено. Чтобы добавить ещё фото чека, сделайте или прикрепите фото чека.';
  2506.                             } else {
  2507.                                 $reply 'Фото чека не удалось прикрепить. Чтобы добавить фото чека снова, сделайте или прикрепите фото чека.';
  2508.                             }
  2509.                             $editMessageId $draftObj->getLastMessageId();
  2510.                             $this->addExpected($curClient, array("value" => "file_cheque""group" => $p_group));
  2511.                             $keyboard = [
  2512.                                 [
  2513.                                     [
  2514.                                         'text'=> 'Завершить операцию',
  2515.                                         'callback_data'=> json_encode(array('action' => "finish_pay"'command' => "pay""group" => $p_group))
  2516.                                     ]
  2517.                                 ]
  2518.                             ];
  2519.                             /*
  2520.                             //окончание финансовой операции
  2521.                             $draftObj->setExpected('finish');
  2522.                             $em->persist($draftObj);
  2523.                             $em->flush();
  2524.                             $this->resetExpected($curClient);
  2525.                             $create_transaction = $this->createTransaction($token, $chat_id, $groupObj, $draftObj);
  2526.                             if($create_transaction === true){
  2527.                                 $em->remove($draftObj);
  2528.                                 $em->flush();
  2529.                             }
  2530.                             $reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Транзакция успешно добавлена.';
  2531.                             */
  2532.                         }
  2533.                     } elseif($expected == 'new_date'){
  2534.                         if(is_numeric(trim($text)) && trim($text) <= 31){
  2535.                             $reply 'Введите сумму начисления оклада';
  2536.                             $newSalarySchedule = new SalarySchedule();
  2537.                             $newSalarySchedule->setClient(($groupObj && $is_group_chat === true $groupObj $curClient))
  2538.                                 ->setDay(trim($text))
  2539.                                 ->setIsEdit(true)
  2540.                             ;
  2541.                             $em->persist($newSalarySchedule);
  2542.                             $em->flush();
  2543.                             $groupObj false;
  2544.                             if($p_group != '' && $p_group != null){
  2545.                                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  2546.                             }
  2547.                             $this->addExpected(($groupObj && $is_group_chat === true $groupObj $curClient), array("value" => "new_amount""group" => $p_group));
  2548.                         } else {
  2549.                             if(is_numeric(trim($text)) && trim($text) > 31){
  2550.                                 $reply 'День месяца не должен быть больше 31';
  2551.                             } else {
  2552.                                 $reply 'Введите день числом, в который будет осуществляться начисления оклада';
  2553.                             }
  2554.                             $keyboard = array(
  2555.                                 array(
  2556.                                     array(
  2557.                                         'text'=>'Назад',
  2558.                                         'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "pay""group" => $p_group))
  2559.                                     )
  2560.                                 )
  2561.                             );
  2562.                         }
  2563.                     } elseif($expected == 'new_amount'){
  2564.                         $amount = (float) $text;
  2565.                         $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(array('client' => ($groupObj && $is_group_chat === true $groupObj $curClient), 'is_edit' => true));
  2566.                         if($amount && $salarySchedule){
  2567.                             $salarySchedule->setAmount($amount)
  2568.                                 ->setIsEdit(false);
  2569.                             $em->persist($salarySchedule);
  2570.                             $em->flush();
  2571.                             $this->resetExpected(($groupObj && $is_group_chat === true $groupObj $curClient));
  2572.                             $reply 'Условие начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() . ' руб» успешно добавлено';
  2573.                         } else {
  2574.                             $reply 'Не удалось добавить информацию для начисления оклада, попробуйте повторить операцию снова';
  2575.                         }
  2576.                     } elseif($expected == 'edit_ss_d' || $expected == 'edit_ss_a') {
  2577.                         if(is_numeric($text)){
  2578.                             $isExistSs false;
  2579.                             if($ss_id != null && $ss_id != ''){
  2580.                                 $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(array('id' => $ss_id));
  2581.                                 if($salarySchedule){
  2582.                                     $isExistSs true;
  2583.                                     if($expected == 'edit_ss_d'){
  2584.                                         $salarySchedule->setDay($text);
  2585.                                     } else {
  2586.                                         $salarySchedule->setAmount($text);
  2587.                                     }
  2588.                                     $em->persist($salarySchedule);
  2589.                                     $em->flush();
  2590.                                     $reply 'Условие начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() . ' руб» успешно отредактировано';
  2591.                                     $keyboard = array(
  2592.                                         array(
  2593.                                             array(
  2594.                                                 'text'=>'Назад',
  2595.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_date"'command' => "pay""group" => $p_group))
  2596.                                             )
  2597.                                         ),
  2598.                                         array(
  2599.                                             array(
  2600.                                                 'text'=>'В основное меню',
  2601.                                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2602.                                             )
  2603.                                         )
  2604.                                     );
  2605.                                     $this->resetExpected($curClient);
  2606.                                 }
  2607.                             }
  2608.                             if(!$isExistSs){
  2609.                                 $reply 'Не удалось отредактировать условий для начисления оклада';
  2610.                                 $keyboard = array(
  2611.                                     array(
  2612.                                         array(
  2613.                                             'text'=>'В основное меню',
  2614.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "pay""group" => $p_group))
  2615.                                         )
  2616.                                     )
  2617.                                 );
  2618.                             }
  2619.                         } else {
  2620.                             $reply 'Данные для ввода должны быть числом. Повторите ввод';
  2621.                         }
  2622.                     } else {
  2623.                         $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  2624.                     }
  2625.                 }
  2626.             }
  2627.         } else {
  2628.             $groupObj false;
  2629.             if($group_id != '' && $group_id != null){
  2630.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  2631.             } elseif($p_group != '' && $p_group != null){
  2632.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  2633.             }
  2634.             if($groupObj){
  2635.                 if($is_group_chat === true && $groupObj){
  2636.                     $chat_id $groupObj->getChatId();
  2637.                 }
  2638.                 $name_group '';
  2639.                 $type_group_typeof null;
  2640.                 if($groupObj->getTypeGroup()){
  2641.                     $type_group_typeof $groupObj->getTypeGroup()->getTypeof();
  2642.                     $name_group $groupObj->nameClient();
  2643.                 }
  2644.                 if($type_group_typeof != null && $type_group_typeof != ''){
  2645.                     if($type_group_typeof == 'cash'){
  2646.                         $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Выберите финансовую операцию.';
  2647.                         $keyboard = array(
  2648.                             array(
  2649.                                 array(
  2650.                                     'text'=>'Приход',
  2651.                                     'callback_data'=> json_encode(array('action' => "income"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  2652.                                 )
  2653.                             ),
  2654.                             array(
  2655.                                 array(
  2656.                                     'text'=>'Расход',
  2657.                                     'callback_data'=> json_encode(array('action' => "expense"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  2658.                                 ),
  2659.                             ),
  2660.                             array(
  2661.                                 array(
  2662.                                     'text'=>'Назад',
  2663.                                     'callback_data'=> json_encode(array('action' => "delete"'command' => "pay"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  2664.                                 )
  2665.                             )
  2666.                         );
  2667.                     } elseif($type_group_typeof == 'salary') {
  2668.                         $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  2669.                         $commandPermissions $this->curCommandPermissions($clientObj'pay');
  2670.                         $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Выберите финансовую операцию.';
  2671. //                        $keyboard = array(
  2672. //                            array(
  2673. //                                array(
  2674. //                                    'text'=>'Перевод в группу ЗП',
  2675. //                                    'callback_data'=> json_encode(array('action' => "income", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  2676. //                                )
  2677. //                            ),
  2678. //                            array(
  2679. //                                array(
  2680. //                                    'text'=>'Перевод в группу Нал',
  2681. //                                    'callback_data'=> json_encode(array('action' => "income_cash", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  2682. //                                )
  2683. //                            ),
  2684. //                            array(
  2685. //                                array(
  2686. //                                    'text'=>'Начисление зарплаты',
  2687. //                                    'callback_data'=> json_encode(array('action' => "expense", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  2688. //                                ),
  2689. //                            ),
  2690. //                            array(
  2691. //                                array(
  2692. //                                    'text'=>'Начисление оклада',
  2693. //                                    'callback_data'=> json_encode(array('action' => "expense_salary", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  2694. //                                ),
  2695. //                            ),
  2696. //                            array(
  2697. //                                array(
  2698. //                                    'text'=>'Назад',
  2699. //                                    'callback_data'=> json_encode(array('action' => "delete", 'command' => "pay", 'mes_id' => $message_id, "group" => ($groupObj ? $groupObj->getId() : null)))
  2700. //                                )
  2701. //                            )
  2702. //                        );
  2703.                         $keyboard = [];
  2704.                         if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('salary_pay_transfer_to_salary'$commandPermissions))){
  2705.                             //Перевод в группу ЗП
  2706.                             $keyboard[] = [[
  2707.                                 'text'=>'Перевод в группу ЗП',
  2708.                                 'callback_data'=> json_encode(array('action' => "income"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  2709.                             ]];
  2710.                         }
  2711.                         if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('salary_pay_transfer_to_cash'$commandPermissions))){
  2712.                             //Перевод в группу Нал
  2713.                             $keyboard[] = [[
  2714.                                 'text'=>'Перевод в группу Нал',
  2715.                                 'callback_data'=> json_encode(array('action' => "income_cash"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  2716.                             ]];
  2717.                         }
  2718.                         if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('salary_pay_accrual_salary'$commandPermissions))){
  2719.                             //Начисление зарплаты
  2720.                             $keyboard[] = [[
  2721.                                 'text'=>'Начисление зарплаты',
  2722.                                 'callback_data'=> json_encode(array('action' => "expense"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  2723.                             ]];
  2724.                         }
  2725.                         if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('salary_pay_accrual_payday'$commandPermissions))){
  2726.                             //Начисление оклада
  2727.                             $keyboard[] = [[
  2728.                                 'text'=>'Начисление оклада',
  2729.                                 'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "pay""group" => ($groupObj $groupObj->getId() : null)))
  2730.                             ]];
  2731.                         }
  2732.                         $keyboard[] = [[
  2733.                             'text'=>'Назад',
  2734.                             'callback_data'=> json_encode(array('action' => "delete"'command' => "pay"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  2735.                         ]];
  2736.                     }
  2737.                 } else {
  2738.                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить действие, у данной группы не выбран тип группы. Пожалуйста укажите тип группы и начните данную команду заново.';
  2739.                 }
  2740.             } else {
  2741.                 $reply 'Финансовые операции начинаются из группы, пожалуйста отправьте команду для начала операции в нужной группе.';
  2742.             }
  2743.         }
  2744.         if(!isset($reply) || $reply == '' || $reply == null){
  2745.             $reply 'Что то пошло не так, начните выполнение операции заново';
  2746.         }
  2747.         $sendMessage false;
  2748.         if(count($keyboard) > 0){
  2749.             $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  2750.             if($editMessageId != null){
  2751.                 //редактировать уже существующее сообщение
  2752.                 $sendMessage ProjectUtilsController::requestToBot($token'editMessageText', ['chat_id' => $chat_id'message_id' => $editMessageId'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  2753.             } else {
  2754.                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  2755.             }
  2756.             $resp json_decode($sendMessagetrue);
  2757.             if(isset($resp['result']['message_id']) && $groupObj){
  2758.                 file_put_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt'$resp['result']['message_id']);
  2759.             }
  2760. //            if($draftObj && $file_id != null && $file_id != '' && isset($resp['result']['message_id'])){
  2761. //                $draftObj->setLastMessageId($resp['result']['message_id']);
  2762. //                $em->persist($draftObj);
  2763. //                $em->flush();
  2764. //            }
  2765.         } else {
  2766.             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  2767.         }
  2768.         if($is_group_chat === true){
  2769.             $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
  2770.             $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'pay'));
  2771.             $this->addLogMessageBot($bot$command$sendMessage);
  2772.             if($create_transaction === true){
  2773.                 $this->deleteLogMessage($bot$chat_id$command->getId());
  2774.             }
  2775.         }
  2776.     }
  2777.     private function bpay($token$chat_id$group_id$cq_data = array(), $curClient false$text null$message_id null$file_id null) {
  2778.         $is_group_chat $this->kernel->getContainer()->getParameter('app.chat.is_group');
  2779.         $basePath $this->getParameter('kernel.project_dir');
  2780.         $create_transaction false;
  2781.         $action null;
  2782.         $p_group null;
  2783.         $keyboard = array();
  2784.         $em $this->getDoctrine()->getManager();
  2785.         if(count($cq_data) > 0){
  2786.             $action = (isset($cq_data['action']) ? $cq_data['action'] : null);
  2787.             $p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
  2788.         }
  2789.         $expected null;
  2790.         $ss_id null;
  2791.         if($curClient){
  2792.             $data_expected $this->dataExpected($curClient->getExpected());
  2793.             if(isset($data_expected['value'])){
  2794.                 $expected $data_expected['value'];
  2795.             }
  2796.             if(isset($data_expected['group'])){
  2797.                 $p_group $data_expected['group'];
  2798.             }
  2799.             if(isset($data_expected['ss_id'])){
  2800.                 $ss_id $data_expected['ss_id'];
  2801.             }
  2802.         }
  2803.         $editMessageId null;
  2804.         if(count($cq_data) > && $action != 'menu'){
  2805.             $name_group '';
  2806.             $groupObj false;
  2807.             if($group_id != null && $group_id != ''){
  2808.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  2809.             } elseif($p_group != null && $p_group != '') {
  2810.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  2811.             }
  2812.             if($action == 'delete' && $groupObj){
  2813.                 $mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
  2814.                 if($mes_id != '' && $mes_id != null){
  2815.                     $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
  2816.                 }
  2817.                 if(file_exists($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt')){
  2818.                     $mes_id file_get_contents($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt');
  2819.                     if($mes_id != '' && $mes_id != null){
  2820.                         $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
  2821.                         $resp json_decode($deleteMessagetrue);
  2822.                         if(isset($resp['result'])){
  2823.                             if($resp['result'] == true){
  2824.                                 unlink($basePath '/var/log/' $groupObj->getChatId() . '-' $groupObj->getId() . '.txt');
  2825.                             }
  2826.                         }
  2827.                     }
  2828.                 }
  2829.                 exit();
  2830.             }
  2831.             $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  2832.             if($groupObj && $clientObj){
  2833.                 $name_group $groupObj->nameClient();
  2834.                 $type_group_typeof null;
  2835.                 if($groupObj->getTypeGroup()){
  2836.                     $type_group_typeof $groupObj->getTypeGroup()->getTypeof();
  2837.                 }
  2838.                 if($is_group_chat === true){
  2839.                     $chat_id $groupObj->getChatId();
  2840.                 }
  2841.                 if($type_group_typeof != null && $type_group_typeof != ''){
  2842.                     if($type_group_typeof == 'cash'){
  2843.                         if($action == 'income'){
  2844.                             $commandPermissions $this->curCommandPermissions($clientObj'bpay');
  2845.                             $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Выбрано «Приход». ' 'Выберите откуда осуществляется приход.';
  2846. //                            $keyboard = array(
  2847. //                                array(
  2848. //                                    array(
  2849. //                                        'text'=>'По Объекту',
  2850. //                                        'callback_data'=> json_encode(array('action' => "income_partner", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  2851. //                                    )
  2852. //                                ),
  2853. //                                array(
  2854. //                                    array(
  2855. //                                        'text'=>'Перевод Нал-Нал',
  2856. //                                        'callback_data'=> json_encode(array('action' => "income_group", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  2857. //                                    ),
  2858. //                                ),
  2859. //                                array(
  2860. //                                    array(
  2861. //                                        'text'=>'Перевод ЗП-Нал',
  2862. //                                        'callback_data'=> json_encode(array('action' => "income_group_salary", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  2863. //                                    ),
  2864. //                                ),
  2865. //                                array(
  2866. //                                    array(
  2867. //                                        'text'=>'Назад',
  2868. //                                        'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
  2869. //                                    ),
  2870. //                                )
  2871. //                            );
  2872.                             $keyboard = [];
  2873.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_income_office'$commandPermissions))){
  2874.                                 //Приход -> По Объекту
  2875.                                 $keyboard[] = [[
  2876.                                     'text'=>'По Объекту',
  2877.                                     'callback_data'=> json_encode(array('action' => "income_partner"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  2878.                                 ]];
  2879.                             }
  2880.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_income_transfer_cash_to_cash'$commandPermissions))){
  2881.                                 //Приход -> Превод Нал-Нал
  2882.                                 $keyboard[] = [[
  2883.                                     'text'=>'Перевод Нал-Нал',
  2884.                                     'callback_data'=> json_encode(array('action' => "income_group"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  2885.                                 ]];
  2886.                             }
  2887.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_income_transfer_salary_to_cash'$commandPermissions))){
  2888.                                 //Приход -> Превод ЗП-Нал
  2889.                                 $keyboard[] = [[
  2890.                                     'text'=>'Перевод ЗП-Нал',
  2891.                                     'callback_data'=> json_encode(array('action' => "income_group_salary"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  2892.                                 ]];
  2893.                             }
  2894.                             $keyboard[] = [[
  2895.                                 'text'=>'Назад',
  2896.                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  2897.                             ]];
  2898.                         } elseif($action == 'income_group'){
  2899.                             $clients_q $this->getDoctrine()
  2900.                                 ->getRepository(Client::class)
  2901.                                 ->createQueryBuilder('cl')
  2902.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  2903.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  2904.                                 ->where('cl.typeof != :typeof')
  2905.                                 ->andWhere('cl.is_active = 1')
  2906.                                 ->setParameter('typeof'"private")
  2907.                                 ->setParameter('typeof_group'"cash")
  2908.                             ;
  2909.                             if($groupObj){
  2910.                                 $clients_q->andWhere('cl.id != ' $groupObj->getId());
  2911.                             }
  2912.                             $clients $clients_q->getQuery()->getArrayResult();
  2913.                             if(count($clients) > 0){
  2914.                                 $buttons = array();
  2915.                                 foreach ($clients as $item_client){
  2916.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  2917.                                     $buttons[][] = array(
  2918.                                         'text' => $name_client,
  2919.                                         'callback_data'=> json_encode(array("action" => "add_cgroup"'command' => "bpay"'id' => $item_client['id'], "group" => $p_group))
  2920.                                     );
  2921.                                 }
  2922.                                 $buttons[][] = array(
  2923.                                     'text' => 'Назад',
  2924.                                     'callback_data'=> json_encode(array("action" => "income"'command' => "bpay""group" => $p_group))
  2925.                                 );
  2926.                                 $keyboard $buttons;
  2927.                                 $reply 'Выбрано «Перевод Нал-Нал». ' 'Выберите группу из которой будет списание средств.';
  2928.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2929.                                 if($draftOld){
  2930.                                     $em->remove($draftOld);
  2931.                                     $em->flush();
  2932.                                 }
  2933.                                 $newDraft = new Draft();
  2934.                                 $newDraft->setTypeof('expense');
  2935.                                 $newDraft->setClient($clientObj);
  2936.                                 $newDraft->setClientGroup($groupObj);
  2937.                                 $newDraft->setToGroup($groupObj);
  2938.                                 $newDraft->setExpected('cgroup');
  2939.                                 $newDraft->setNote('Перевод Нал-Нал');
  2940.                                 $newDraft->setTypeTransaction('transfer');
  2941.                                 $em->persist($newDraft);
  2942.                                 $em->flush();
  2943.                             } else {
  2944.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  2945.                             }
  2946.                         } elseif($action == 'income_group_salary'){
  2947.                             $clients_q $this->getDoctrine()
  2948.                                 ->getRepository(Client::class)
  2949.                                 ->createQueryBuilder('cl')
  2950.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  2951.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  2952.                                 ->where('cl.typeof != :typeof')
  2953.                                 ->andWhere('cl.is_active = 1')
  2954.                                 ->setParameter('typeof'"private")
  2955.                                 ->setParameter('typeof_group'"salary")
  2956.                             ;
  2957.                             if($groupObj){
  2958.                                 $clients_q->andWhere('cl.id != ' $groupObj->getId());
  2959.                             }
  2960.                             $clients $clients_q->getQuery()->getArrayResult();
  2961.                             if(count($clients) > 0){
  2962.                                 $buttons = array();
  2963.                                 foreach ($clients as $item_client){
  2964.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  2965.                                     $buttons[][] = array(
  2966.                                         'text' => $name_client,
  2967.                                         'callback_data'=> json_encode(array("action" => "add_cgroup"'command' => "bpay"'id' => $item_client['id'], "group" => $p_group))
  2968.                                     );
  2969.                                 }
  2970.                                 $buttons[][] = array(
  2971.                                     'text' => 'Назад',
  2972.                                     'callback_data'=> json_encode(array("action" => "income"'command' => "bpay""group" => $p_group))
  2973.                                 );
  2974.                                 $keyboard $buttons;
  2975.                                 $reply 'Выбрано «Перевод ЗП-Нал». ' 'Выберите группу из которой будет списание средств.';
  2976.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2977.                                 if($draftOld){
  2978.                                     $em->remove($draftOld);
  2979.                                     $em->flush();
  2980.                                 }
  2981.                                 $newDraft = new Draft();
  2982.                                 $newDraft->setTypeof('expense');
  2983.                                 $newDraft->setClient($clientObj);
  2984.                                 $newDraft->setClientGroup($groupObj);
  2985.                                 $newDraft->setToGroup($groupObj);
  2986.                                 $newDraft->setExpected('cgroup');
  2987.                                 $newDraft->setNote('Перевод ЗП-Нал');
  2988.                                 $newDraft->setTypeTransaction('transfer');
  2989.                                 $em->persist($newDraft);
  2990.                                 $em->flush();
  2991.                             } else {
  2992.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  2993.                             }
  2994.                         } elseif($action == 'add_cgroup'){
  2995.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  2996.                             $from_client false;
  2997.                             if(isset($cq_data['id'])){
  2998.                                 if($cq_data['id'] != '' && $cq_data['id'] != null){
  2999.                                     $from_client $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  3000.                                 }
  3001.                             }
  3002.                             if($draftObj && $from_client){
  3003.                                 $from_group_typeof = ($from_client->getTypeGroup() != '' && $from_client->getTypeGroup() != null $from_client->getTypeGroup() : 'cash');
  3004.                                 $groupObj false;
  3005.                                 if($p_group != '' && $p_group != null){
  3006.                                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  3007.                                 }
  3008.                                 $draftObj->setFromGroup($from_client);
  3009.                                 $draftObj->setExpected('amount_b');
  3010.                                 $em->persist($draftObj);
  3011.                                 $em->flush();
  3012.                                 $this->addExpected(($groupObj && $is_group_chat === true $groupObj $clientObj), array("value" => "amount_b""group" => $p_group));
  3013.                                 $reply 'Выбрано «Группа ' . ($from_client $from_client->nameClient() : '') . ' для списания с баланса». ' 'Введите сумму.';
  3014.                                 if($from_group_typeof != 'salary'){
  3015.                                     $buttons[][] = array(
  3016.                                         'text' => 'Назад',
  3017.                                         'callback_data'=> json_encode(array("action" => "income_group"'command' => "bpay""group" => $p_group))
  3018.                                     );
  3019.                                 } else {
  3020.                                     $buttons[][] = array(
  3021.                                         'text' => 'Назад',
  3022.                                         'callback_data'=> json_encode(array("action" => "income_group_salary"'command' => "bpay""group" => $p_group))
  3023.                                     );
  3024.                                 }
  3025.                                 $keyboard $buttons;
  3026.                             } else {
  3027.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  3028.                             }
  3029.                         } elseif($action == 'income_partner' || $action == 'add_client' || $action == 'other'){
  3030.                             //step 1
  3031.                             $offices $this->getDoctrine()
  3032.                                 ->getRepository(Office::class)
  3033.                                 ->createQueryBuilder('o')
  3034.                                 ->select('o.id, o.name, o.number')
  3035.                                 ->where('o.is_active = 1')
  3036.                                 ->getQuery()
  3037.                                 ->getArrayResult();
  3038.                             if(count($offices) > 0){
  3039.                                 if($action == 'income_partner'){
  3040.                                     $reply 'Выбрано «По Объекту». ' 'Выберите объект, по которому осуществляется приход.';
  3041.                                 } elseif($action == 'other'){
  3042.                                     $name_group '';
  3043.                                     if($p_group != '' && $p_group != null){
  3044.                                         $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  3045.                                         if($groupObj){
  3046.                                             if($groupObj->getTypeGroup()){
  3047.                                                 $name_group $groupObj->nameClient();
  3048.                                             }
  3049.                                         }
  3050.                                     }
  3051.                                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Выберите объект, по которому осуществляется расход.';
  3052.                                     //$reply = 'Выбрано «Расходы по Объекту». ' . 'Выберите объект, по которому осуществляется расход.';
  3053.                                 }
  3054.                                 $buttons = array();
  3055.                                 foreach ($offices as $item_office){
  3056.                                     $buttons[][] = array(
  3057.                                         'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  3058.                                         'callback_data'=> json_encode(array("action" => "add_office"'command' => "bpay"'id' => $item_office['id'], "group" => $p_group))
  3059.                                     );
  3060.                                 }
  3061.                                 if($action == 'income_partner'){
  3062.                                     $buttons[][] = array(
  3063.                                         'text' => 'Назад',
  3064.                                         'callback_data'=> json_encode(array("action" => "income"'command' => "bay""group" => $p_group))
  3065.                                     );
  3066.                                 } elseif($action == 'other'){
  3067. //                                    $buttons[][] = array(
  3068. //                                        'text' => 'Назад',
  3069. //                                        'callback_data'=> json_encode(array("action" => "expense", 'command' => "bpay", "group" => $p_group))
  3070. //                                    );
  3071.                                 } elseif($action == 'add_client'){
  3072.                                     $buttons[][] = array(
  3073.                                         'text' => 'Назад',
  3074.                                         'callback_data'=> json_encode(array("action" => "salary"'command' => "bpay""group" => $p_group))
  3075.                                     );
  3076.                                 }
  3077.                                 $keyboard $buttons;
  3078.                                 if($action == 'income_partner'){
  3079.                                     $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3080.                                     if($draftOld){
  3081.                                         $em->remove($draftOld);
  3082.                                         $em->flush();
  3083.                                     }
  3084.                                     $newDraft = new Draft();
  3085.                                     $newDraft->setTypeof('income');
  3086.                                     $newDraft->setClient($clientObj);
  3087.                                     $newDraft->setClientGroup($groupObj);
  3088.                                     $newDraft->setToGroup($groupObj);
  3089.                                     $newDraft->setExpected('office_b');
  3090.                                     $newDraft->setNote('Поступление средств');
  3091.                                     $newDraft->setTypeTransaction('income');
  3092.                                     $em->persist($newDraft);
  3093.                                     $em->flush();
  3094.                                 } elseif($action == 'add_client' || $action == 'other'){
  3095.                                     $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3096.                                     $to_client false;
  3097.                                     if(isset($cq_data['id'])){
  3098.                                         if($cq_data['id'] != '' && $cq_data['id'] != null){
  3099.                                             $to_client $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  3100.                                         }
  3101.                                     }
  3102.                                     //если сразу выбирается объект
  3103.                                     $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3104.                                     if($draftOld){
  3105.                                         $em->remove($draftOld);
  3106.                                         $em->flush();
  3107.                                     }
  3108.                                     $newDraft = new Draft();
  3109.                                     $newDraft->setTypeof('expense');
  3110.                                     $newDraft->setClient($clientObj);
  3111.                                     $newDraft->setClientGroup($groupObj);
  3112.                                     $newDraft->setFromGroup($groupObj);
  3113.                                     $newDraft->setExpected('type_expense_b');
  3114.                                     $em->persist($newDraft);
  3115.                                     $em->flush();
  3116.                                     $draftObj $newDraft;
  3117.                                     //если сразу выбирается объект
  3118.                                     if($draftObj){
  3119.                                         if($action == 'other'){
  3120.                                             $draftObj->setNote('Списание средств');
  3121.                                             $draftObj->setTypeTransaction('expense_office');
  3122.                                             $draftObj->setExpected('amount_b');
  3123.                                         }
  3124.                                         if($to_client){
  3125.                                             $draftObj->setToGroup($to_client);
  3126.                                             $draftObj->setExpected('office_b');
  3127.                                             if($action == 'add_client'){
  3128.                                                 $name_salary_client $to_client->nameClient();
  3129.                                                 $reply 'Выбрано «Группа ' $name_salary_client ' для выплаты зарплаты». ' 'Выберите объект, по которому выплачивается зарплата.';
  3130.                                             }
  3131.                                         }
  3132.                                         $em->persist($draftObj);
  3133.                                         $em->flush();
  3134.                                     }
  3135.                                 }
  3136.                             } else {
  3137.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
  3138.                             }
  3139.                         } elseif($action == 'expense'){
  3140.                             //step 1
  3141.                             $commandPermissions $this->curCommandPermissions($clientObj'bpay');
  3142.                             $reply 'Выбрано «Расход». ' 'Выберите тип расхода.';
  3143. //                            $keyboard = array(
  3144. //                                array(
  3145. //                                    array(
  3146. //                                        'text'=>'Перевод Нал-ЗП',
  3147. //                                        'callback_data'=> json_encode(array('action' => "salary", 'command' => "bpay", "group" => $p_group))
  3148. //                                    )
  3149. //                                ),
  3150. //                                array(
  3151. //                                    array(
  3152. //                                        'text'=>'Перевод Нал-Нал',
  3153. //                                        'callback_data'=> json_encode(array('action' => "transfer", 'command' => "bpay", "group" => $p_group))
  3154. //                                    ),
  3155. //                                ),
  3156. //                                array(
  3157. //                                    array(
  3158. //                                        'text'=>'Расходы по Объекту',
  3159. //                                        'callback_data'=> json_encode(array('action' => "other", 'command' => "bpay", "group" => $p_group))
  3160. //                                    ),
  3161. //                                ),
  3162. ////                                array(
  3163. ////                                    array(
  3164. ////                                        'text'=>'Расходы на компанию',
  3165. ////                                        'callback_data'=> json_encode(array('action' => "company", 'command' => "bpay", "group" => $p_group))
  3166. ////                                    ),
  3167. ////                                ),
  3168. //                                array(
  3169. //                                    array(
  3170. //                                        'text'=>'Назад',
  3171. //                                        'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => $p_group))
  3172. //                                    ),
  3173. //                                )
  3174. //                            );
  3175.                             $keyboard = [];
  3176. //                            if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('cash_pay_expense_transfer_cash_to_salary', $commandPermissions))){
  3177. //                                //Расход -> Превод Нал-ЗП
  3178. //                                $keyboard[] = [[
  3179. //                                    'text'=>'Перевод Нал-ЗП',
  3180. //                                    'callback_data'=> json_encode(array('action' => "salary", 'command' => "bpay", "group" => $p_group))
  3181. //                                ]];
  3182. //                            }
  3183. //                            if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('cash_pay_expense_transfer_cash_to_cash', $commandPermissions))){
  3184. //                                //Расход -> Превод Нал-Нал
  3185. //                                $keyboard[] = [[
  3186. //                                    'text'=>'Перевод Нал-Нал',
  3187. //                                    'callback_data'=> json_encode(array('action' => "transfer", 'command' => "bpay", "group" => $p_group))
  3188. //                                ]];
  3189. //                            }
  3190.                             if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('cash_pay_expense_office'$commandPermissions))){
  3191.                                 //Расход -> Расходы по Объекту
  3192.                                 $keyboard[] = [[
  3193.                                     'text'=>'Расходы по Объекту',
  3194.                                     'callback_data'=> json_encode(array('action' => "other"'command' => "bpay""group" => $p_group))
  3195.                                 ]];
  3196.                             }
  3197. //                            $keyboard[] = [[
  3198. //                                'text'=>'Расходы на компанию',
  3199. //                                'callback_data'=> json_encode(array('action' => "company", 'command' => "bpay", "group" => $p_group))
  3200. //                            ]];
  3201.                             $keyboard[] = [[
  3202.                                 'text'=>'Назад',
  3203.                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3204.                             ]];
  3205.                             $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3206.                             if($draftOld){
  3207.                                 $em->remove($draftOld);
  3208.                                 $em->flush();
  3209.                             }
  3210.                             $newDraft = new Draft();
  3211.                             $newDraft->setTypeof('expense');
  3212.                             $newDraft->setClient($clientObj);
  3213.                             $newDraft->setClientGroup($groupObj);
  3214.                             $newDraft->setFromGroup($groupObj);
  3215.                             $newDraft->setExpected('type_expense_b');
  3216.                             $em->persist($newDraft);
  3217.                             $em->flush();
  3218.                         } elseif($action == 'add_office' || $action == 'add_director'){
  3219.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3220.                             $officeObj false;
  3221.                             $directorObj false;
  3222.                             if($action == 'add_office'){
  3223.                                 if(isset($cq_data['id'])){
  3224.                                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  3225.                                         $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  3226.                                     }
  3227.                                 }
  3228.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3229.                                 if($draftOld){
  3230.                                     $em->remove($draftOld);
  3231.                                     $em->flush();
  3232.                                 }
  3233.                                 if($officeObj){
  3234.                                     $draftObj->setOffice($officeObj);
  3235.                                 }
  3236.                             } elseif($action == 'add_director'){
  3237.                                 if(isset($cq_data['id'])){
  3238.                                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  3239.                                         $directorObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  3240.                                     }
  3241.                                 }
  3242.                                 if($directorObj){
  3243.                                     $draftObj->setToGroup($directorObj);
  3244.                                 }
  3245.                             }
  3246.                             $selected '';
  3247.                             if($action == 'add_office' && $officeObj){
  3248.                                 $selected 'Выбрано «Объект ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() . '». ';
  3249.                             } elseif($action == 'add_director' && $directorObj){
  3250.                                 $name_director $directorObj->nameClient();
  3251.                                 $selected 'Выбрано «Руководитель' . ($name_director != '' && $name_director != null ' ' $name_director '') . '». ';
  3252.                             }
  3253.                             if($draftObj){
  3254.                                 $draftObj->setExpected('amount_b');
  3255.                                 $em->persist($draftObj);
  3256.                                 $em->flush();
  3257.                                 $this->addExpected(($is_group_chat === true && $groupObj $groupObj $clientObj), array("value" => "amount_b""group" => $p_group));
  3258.                                 $reply $selected 'Введите сумму';
  3259. //                                if($action == 'add_office'){
  3260. //                                    $keyboard = array(
  3261. //                                        array(
  3262. //                                            array(
  3263. //                                                'text'=>'Назад',
  3264. //                                                'callback_data'=> json_encode(array('action' => "other", 'command' => "bpay", "group" => $p_group))
  3265. //                                            ),
  3266. //                                        )
  3267. //                                    );
  3268. //                                } else {
  3269. //                                    $keyboard = array(
  3270. //                                        array(
  3271. //                                            array(
  3272. //                                                'text'=>'Назад',
  3273. //                                                'callback_data'=> json_encode(array('action' => "income_partner", 'command' => "bpay", "group" => $p_group))
  3274. //                                            ),
  3275. //                                        )
  3276. //                                    );
  3277. //                                }
  3278.                             } else {
  3279.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  3280.                             }
  3281.                         } elseif($action == 'salary'){
  3282.                             $clients_q $this->getDoctrine()
  3283.                                 ->getRepository(Client::class)
  3284.                                 ->createQueryBuilder('cl')
  3285.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  3286.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  3287.                                 ->where('cl.typeof != :typeof')
  3288.                                 ->andWhere('cl.is_active = 1')
  3289.                                 ->setParameter('typeof'"private")
  3290.                                 ->setParameter('typeof_group'"salary")
  3291.                             ;
  3292.                             if($groupObj){
  3293.                                 $clients_q->andWhere('cl.id != ' $groupObj->getId());
  3294.                             }
  3295.                             $clients $clients_q->getQuery()->getArrayResult();
  3296.                             if(count($clients) > 0){
  3297.                                 $buttons = array();
  3298.                                 foreach ($clients as $item_client){
  3299.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  3300.                                     $buttons[][] = array(
  3301.                                         'text' => $name_client,
  3302.                                         'callback_data'=> json_encode(array("action" => "add_client"'command' => "bpay"'id' => $item_client['id'], "group" => $p_group))
  3303.                                     );
  3304.                                 }
  3305.                                 $buttons[][] = array(
  3306.                                     'text'=>'Назад',
  3307.                                     'callback_data'=> json_encode(array('action' => "expense"'command' => "bpay""group" => $p_group))
  3308.                                 );
  3309.                                 $keyboard $buttons;
  3310.                                 $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3311.                                 if($draftObj){
  3312.                                     $draftObj->setNote('Перевод Нал-ЗП');
  3313.                                     $draftObj->setTypeTransaction('add_salary');
  3314.                                     $draftObj->setExpected('to_group_b');
  3315.                                     $em->persist($draftObj);
  3316.                                     $em->flush();
  3317.                                     $reply 'Выбрано «Перевод Нал-ЗП». ' 'Выберите группу, которой будет осуществлен перевод.';
  3318.                                 } else {
  3319.                                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  3320.                                     $keyboard = array();
  3321.                                 }
  3322.                             } else {
  3323.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  3324.                             }
  3325.                         } elseif($action == 'transfer'){
  3326.                             $clients_q $this->getDoctrine()
  3327.                                 ->getRepository(Client::class)
  3328.                                 ->createQueryBuilder('cl')
  3329.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  3330.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  3331.                                 ->where('cl.typeof != :typeof')
  3332.                                 ->andWhere('cl.is_active = 1')
  3333.                                 ->setParameter('typeof'"private")
  3334.                                 ->setParameter('typeof_group'"cash")
  3335.                             ;
  3336.                             if($groupObj){
  3337.                                 $clients_q->andWhere('cl.id != ' $groupObj->getId());
  3338.                             }
  3339.                             $clients $clients_q->getQuery()->getArrayResult();
  3340.                             if(count($clients) > 0){
  3341.                                 $buttons = array();
  3342.                                 foreach ($clients as $item_client){
  3343.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  3344.                                     $buttons[][] = array(
  3345.                                         'text' => $name_client,
  3346.                                         'callback_data'=> json_encode(array("action" => "add_director"'command' => "bpay"'id' => $item_client['id'], "group" => $p_group))
  3347.                                     );
  3348.                                 }
  3349.                                 $buttons[][] =  array(
  3350.                                     'text'=>'Назад',
  3351.                                     'callback_data'=> json_encode(array('action' => "expense"'command' => "bpay""group" => $p_group))
  3352.                                 );
  3353.                                 $keyboard $buttons;
  3354.                                 $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3355.                                 if($draftObj){
  3356.                                     $draftObj->setNote('Перевод Нал-Нал');
  3357.                                     $draftObj->setTypeTransaction('transfer');
  3358.                                     $draftObj->setExpected('to_group_b');
  3359.                                     $em->persist($draftObj);
  3360.                                     $em->flush();
  3361.                                     $reply 'Выбрано «Перевод Нал-Нал». ' 'Выберите группу для перевода';
  3362.                                 } else {
  3363.                                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  3364.                                     $keyboard = array();
  3365.                                 }
  3366.                             } else {
  3367.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  3368.                             }
  3369.                         } elseif($action == 'company'){
  3370.                             $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3371.                             if($draftOld){
  3372.                                 $em->remove($draftOld);
  3373.                                 $em->flush();
  3374.                             }
  3375.                             $newDraft = new Draft();
  3376.                             $newDraft->setTypeof('expense');
  3377.                             $newDraft->setClient($clientObj);
  3378.                             $newDraft->setClientGroup($groupObj);
  3379.                             $newDraft->setFromGroup($groupObj);
  3380.                             $newDraft->setExpected('amount_b');
  3381.                             $newDraft->setNote('Списание средств на компанию');
  3382.                             $newDraft->setTypeTransaction('expense_company');
  3383.                             $em->persist($newDraft);
  3384.                             $em->flush();
  3385.                             $this->addExpected(($is_group_chat === true && $groupObj $groupObj $clientObj), array("value" => "amount_b""group" => $p_group));
  3386.                             $reply 'Выбрано «Расходы на компанию». ' 'Введите сумму.';
  3387.                         } elseif($action == 'no_cheque' || $action == 'finish_pay'){
  3388.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3389.                             $draftObj->setExpected('finish_b');
  3390.                             $em->persist($draftObj);
  3391.                             $em->flush();
  3392.                             $this->resetExpected($curClient);
  3393. //                            $create_transaction = $this->createTransaction($token, $chat_id, $groupObj, $draftObj);
  3394. //                            if($create_transaction === true){
  3395. //                                $em->remove($draftObj);
  3396. //                                $em->flush();
  3397. //                            }
  3398.                             $create_transaction $this->sendMailNonCashCheque($token$chat_id$groupObj$draftObj);
  3399.                             if($create_transaction === true){
  3400.                                 $em->remove($draftObj);
  3401.                                 $em->flush();
  3402.                             }
  3403.                             $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Письмо с безналичным чеком успешно отправлено.';
  3404.                         }
  3405.                     } elseif($type_group_typeof == 'salary'){
  3406.                         if($action == 'income'){
  3407.                             $offices $this->getDoctrine()
  3408.                                 ->getRepository(Office::class)
  3409.                                 ->createQueryBuilder('o')
  3410.                                 ->select('o.id, o.name')
  3411.                                 ->where('o.is_active = 1')
  3412.                                 ->getQuery()
  3413.                                 ->getArrayResult();
  3414.                             if(count($offices) > 0){
  3415.                                 $reply 'Выбрано «Перевод в группу ЗП». ' 'Выберите объект, по которому осуществляется выплата зарплаты.';
  3416.                                 $buttons = array();
  3417.                                 foreach ($offices as $item_office){
  3418.                                     $buttons[][] = array(
  3419.                                         'text' => $item_office['name'],
  3420.                                         'callback_data'=> json_encode(array("action" => "add_office"'command' => "bpay"'id' => $item_office['id'], "group" => $p_group))
  3421.                                     );
  3422.                                 }
  3423.                                 $buttons[][] =  array(
  3424.                                     'text'=>'Назад',
  3425.                                     'callback_data'=> json_encode(array('action' => "delete"'command' => "bpay""group" => $p_group))
  3426.                                 );
  3427.                                 $keyboard $buttons;
  3428.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3429.                                 if($draftOld){
  3430.                                     $em->remove($draftOld);
  3431.                                     $em->flush();
  3432.                                 }
  3433.                                 $newDraft = new Draft();
  3434.                                 $newDraft->setTypeof('expense');
  3435.                                 $newDraft->setClient($clientObj);
  3436.                                 $newDraft->setClientGroup($groupObj);
  3437.                                 $newDraft->setToGroup($groupObj);
  3438.                                 $newDraft->setExpected('office_b');
  3439.                                 $newDraft->setNote('Перевод в группу ЗП');
  3440.                                 $newDraft->setTypeTransaction('add_salary');
  3441.                                 $em->persist($newDraft);
  3442.                                 $em->flush();
  3443.                             } else {
  3444.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
  3445.                             }
  3446.                         } elseif($action == 'income_cash'){
  3447.                             $offices $this->getDoctrine()
  3448.                                 ->getRepository(Office::class)
  3449.                                 ->createQueryBuilder('o')
  3450.                                 ->select('o.id, o.name, o.number')
  3451.                                 ->where('o.is_active = 1')
  3452.                                 ->getQuery()
  3453.                                 ->getArrayResult();
  3454.                             if(count($offices) > 0){
  3455.                                 $reply 'Выбрано «Перевод в группу Нал». ' 'Выберите объект, по которому осуществляется выплата зарплаты.';
  3456.                                 $buttons = array();
  3457.                                 foreach ($offices as $item_office){
  3458.                                     $buttons[][] = array(
  3459.                                         'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  3460.                                         'callback_data'=> json_encode(array("action" => "add_office"'command' => "bpay"'id' => $item_office['id'], "group" => $p_group))
  3461.                                     );
  3462.                                 }
  3463.                                 $buttons[][] =  array(
  3464.                                     'text'=>'Назад',
  3465.                                     'callback_data'=> json_encode(array('action' => "delete"'command' => "bpay""group" => $p_group))
  3466.                                 );
  3467.                                 $keyboard $buttons;
  3468.                                 $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3469.                                 if($draftOld){
  3470.                                     $em->remove($draftOld);
  3471.                                     $em->flush();
  3472.                                 }
  3473.                                 $newDraft = new Draft();
  3474. //                                $newDraft->setTypeof('expense');
  3475.                                 $newDraft->setTypeof('income');
  3476.                                 $newDraft->setClient($clientObj);
  3477.                                 $newDraft->setClientGroup($groupObj);
  3478.                                 $newDraft->setToGroup($groupObj);
  3479.                                 $newDraft->setExpected('office_b');
  3480.                                 $newDraft->setNote('Перевод в группу Нал');
  3481.                                 $newDraft->setTypeTransaction('add_salary_cash');
  3482.                                 $em->persist($newDraft);
  3483.                                 $em->flush();
  3484.                             } else {
  3485.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
  3486.                             }
  3487.                         } elseif($action == 'add_office'){
  3488.                             $clients_q $this->getDoctrine()
  3489.                                 ->getRepository(Client::class)
  3490.                                 ->createQueryBuilder('cl')
  3491.                                 ->select('cl.id, cl.first_name, cl.last_name, cl.username')
  3492.                                 ->innerJoin(TypeGroup::class, 'tg''WITH''cl.type_group = tg.id AND tg.typeof = :typeof_group')
  3493.                                 ->where('cl.typeof != :typeof')
  3494.                                 ->andWhere('cl.is_active = 1')
  3495.                                 ->setParameter('typeof'"private")
  3496.                                 ->setParameter('typeof_group'"cash")
  3497.                             ;
  3498.                             $clients $clients_q->getQuery()->getArrayResult();
  3499.                             if(count($clients) > 0){
  3500.                                 $buttons = array();
  3501.                                 foreach ($clients as $item_client){
  3502.                                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  3503.                                     $buttons[][] = array(
  3504.                                         'text' => $name_client,
  3505.                                         'callback_data'=> json_encode(array("action" => "add_client"'command' => "bpay"'id' => $item_client['id'], "group" => $p_group))
  3506.                                     );
  3507.                                 }
  3508.                                 $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3509.                                 if($draftObj){
  3510.                                     $officeObj false;
  3511.                                     if(isset($cq_data['id'])){
  3512.                                         if($cq_data['id'] != '' && $cq_data['id'] != null){
  3513.                                             $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  3514.                                         }
  3515.                                     }
  3516.                                     if($officeObj){
  3517.                                         $draftObj->setOffice($officeObj);
  3518.                                     }
  3519.                                     $draftObj->setExpected('from_group_b');
  3520.                                     $em->persist($draftObj);
  3521.                                     $em->flush();
  3522.                                     if($draftObj->getTypeTransaction() != 'add_salary_cash'){
  3523.                                         $buttons[][] =  array(
  3524.                                             'text'=>'Назад',
  3525.                                             'callback_data'=> json_encode(array('action' => "income"'command' => "bpay""group" => $p_group))
  3526.                                         );
  3527.                                         $keyboard $buttons;
  3528.                                         $reply 'Выбрано «Объект' . ($officeObj ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() : '') . '». ' 'Выберите группу, c которой будут списаны средства.';
  3529.                                     } else {
  3530.                                         $buttons[][] =  array(
  3531.                                             'text'=>'Назад',
  3532.                                             'callback_data'=> json_encode(array('action' => "income_cash"'command' => "bpay""group" => $p_group))
  3533.                                         );
  3534.                                         $keyboard $buttons;
  3535.                                         $reply 'Выбрано «Объект' . ($officeObj ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() : '') . '». ' 'Выберите группу, в которую будут переведены средства.';
  3536.                                     }
  3537.                                 } else {
  3538.                                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  3539.                                     $keyboard = array();
  3540.                                 }
  3541.                             } else {
  3542.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
  3543.                             }
  3544.                         } elseif($action == 'add_client'){
  3545.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3546.                             $to_client false;
  3547.                             if(isset($cq_data['id'])){
  3548.                                 if($cq_data['id'] != '' && $cq_data['id'] != null){
  3549.                                     $to_client $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  3550.                                 }
  3551.                             }
  3552.                             if($draftObj && $to_client){
  3553.                                 $groupObj false;
  3554.                                 if($p_group != '' && $p_group != null){
  3555.                                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  3556.                                 }
  3557.                                 $draftObj->setFromGroup($to_client);
  3558.                                 $draftObj->setExpected('amount_b');
  3559.                                 $em->persist($draftObj);
  3560.                                 $em->flush();
  3561.                                 $this->addExpected(($groupObj && $is_group_chat === true $groupObj $clientObj), array("value" => "amount_b""group" => $p_group));
  3562.                                 if($draftObj->getTypeTransaction() != 'add_salary_cash'){
  3563.                                     $reply 'Выбрано «Группа ' . ($to_client $to_client->nameClient() : '') . ' для списания средств». ' 'Введите сумму.';
  3564.                                 } else {
  3565.                                     $reply 'Выбрано «Группа ' . ($to_client $to_client->nameClient() : '') . ' для перевода средств». ' 'Введите сумму.';
  3566.                                 }
  3567.                             } else {
  3568.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  3569.                             }
  3570.                         } elseif($action == 'expense'){
  3571.                             $draftOld $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3572.                             if($draftOld){
  3573.                                 $em->remove($draftOld);
  3574.                                 $em->flush();
  3575.                             }
  3576.                             $newDraft = new Draft();
  3577.                             $newDraft->setTypeof('expense');
  3578.                             $newDraft->setClient($clientObj);
  3579.                             $newDraft->setClientGroup($groupObj);
  3580.                             $newDraft->setToGroup($groupObj);
  3581.                             //$newDraft->setFromGroup($groupObj);
  3582.                             $newDraft->setExpected('add_office_expense_b');
  3583.                             $newDraft->setNote('Начисление зарплаты');
  3584.                             $newDraft->setTypeTransaction('payment_salary');
  3585.                             $em->persist($newDraft);
  3586.                             $em->flush();
  3587.                             $offices $this->getDoctrine()
  3588.                                 ->getRepository(Office::class)
  3589.                                 ->createQueryBuilder('o')
  3590.                                 ->select('o.id, o.name, o.number')
  3591.                                 ->where('o.is_active = 1')
  3592.                                 ->getQuery()
  3593.                                 ->getArrayResult();
  3594.                             if(count($offices) > 0){
  3595.                                 $reply 'Выбрано «Начисление зарплаты». ' 'Выберите объект, по которому осуществляется начисление зарплаты.';
  3596.                                 $keyboard = array();
  3597.                                 $buttons = array();
  3598.                                 foreach ($offices as $item_office){
  3599.                                     $buttons[][] = array(
  3600.                                         'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  3601.                                         'callback_data'=> json_encode(array("action" => "add_office_exp"'command' => "bpay"'id' => $item_office['id'], "group" => $p_group))
  3602.                                     );
  3603.                                 }
  3604.                                 $buttons[][] =  array(
  3605.                                     'text'=>'Назад',
  3606.                                     'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3607.                                 );
  3608.                                 $keyboard $buttons;
  3609.                             } else {
  3610.                                 $reply 'Нет объектов для начисление зарплаты по ним.';
  3611.                             }
  3612.                             /*
  3613.                             $groupObj = false;
  3614.                             if($p_group != '' && $p_group != null){
  3615.                                 $groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  3616.                             }
  3617.                             $this->addExpected(($groupObj && $is_group_chat === true ? $groupObj : $clientObj), array("value" => "amount", "group" => $p_group));
  3618.                             $reply = 'Выбрано «Начисление зарплаты». ' . 'Введите сумму';
  3619.                             */
  3620.                         } elseif($action == 'expense_salary') {
  3621.                             //операция начисление оклада
  3622.                             $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
  3623.                             if(count($salarySchedule) > 0){
  3624.                                 $max_ss $this->getParameter('app.max.salary_schedule');
  3625.                                 if(count($salarySchedule) < $max_ss){
  3626.                                     $reply 'Выбрано «Начисление оклада». Можете отредактировать условия начисления оклада по нужным числам месяца, добавить новое или удалить лишнее';
  3627.                                     $keyboard = array(
  3628.                                         array(
  3629.                                             array(
  3630.                                                 'text'=>'Редактировать условие начисления',
  3631.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_date"'command' => "bpay""group" => $p_group))
  3632.                                             )
  3633.                                         ),
  3634.                                         array(
  3635.                                             array(
  3636.                                                 'text'=>'Новое условие начисления',
  3637.                                                 'callback_data'=> json_encode(array('action' => "new_ss_date"'command' => "bpay""group" => $p_group))
  3638.                                             )
  3639.                                         ),
  3640.                                         array(
  3641.                                             array(
  3642.                                                 'text'=>'Удалить условие начисления',
  3643.                                                 'callback_data'=> json_encode(array('action' => "rem_ss_date"'command' => "bpay""group" => $p_group))
  3644.                                             )
  3645.                                         ),
  3646.                                         array(
  3647.                                             array(
  3648.                                                 'text'=>'Назад',
  3649.                                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3650.                                             )
  3651.                                         )
  3652.                                     );
  3653.                                 } else {
  3654.                                     $reply 'Выбрано «Начисление оклада». Можете отредактировать условия начисления оклада по нужным числам месяца или удалить лишнее';
  3655.                                     $keyboard = array(
  3656.                                         array(
  3657.                                             array(
  3658.                                                 'text'=>'Редактировать условие начисления',
  3659.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_date"'command' => "bpay""group" => $p_group))
  3660.                                             )
  3661.                                         ),
  3662.                                         array(
  3663.                                             array(
  3664.                                                 'text'=>'Удалить условие начисления',
  3665.                                                 'callback_data'=> json_encode(array('action' => "rem_ss_date"'command' => "bpay""group" => $p_group))
  3666.                                             )
  3667.                                         ),
  3668.                                         array(
  3669.                                             array(
  3670.                                                 'text'=>'Назад',
  3671.                                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3672.                                             )
  3673.                                         )
  3674.                                     );
  3675.                                 }
  3676.                             } else {
  3677.                                 $reply 'Выбрано «Начисление оклада». Для начисления оклада по нужным числам месяца необходимо добавить условие начисления';
  3678.                                 $keyboard = array(array(
  3679.                                     array(
  3680.                                         'text'=>'Новое условие начисления',
  3681.                                         'callback_data'=> json_encode(array('action' => "new_ss_date"'command' => "bpay""group" => $p_group))
  3682.                                     )
  3683.                                 ),
  3684.                                     array(
  3685.                                         array(
  3686.                                             'text'=>'Назад',
  3687.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3688.                                         )
  3689.                                     )
  3690.                                 );
  3691.                             }
  3692.                         } elseif($action == 'new_ss_date') {
  3693.                             //новое условие начисления оклада
  3694.                             $reply 'Введите число дня месяца, в который будет осуществляться начисления оклада';
  3695.                             $keyboard = array(
  3696.                                 array(
  3697.                                     array(
  3698.                                         'text'=>'Назад',
  3699.                                         'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "bpay""group" => $p_group))
  3700.                                     )
  3701.                                 )
  3702.                             );
  3703.                             $groupObj false;
  3704.                             if($p_group != '' && $p_group != null){
  3705.                                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  3706.                             }
  3707.                             $this->addExpected(($groupObj && $is_group_chat === true $groupObj $clientObj), array("value" => "new_date""group" => $p_group));
  3708.                         } elseif($action == 'edit_ss_date') {
  3709.                             //изменить условие начисления оклада
  3710.                             $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
  3711.                             if(count($salarySchedule) > 0){
  3712.                                 $reply 'Выберите из списка условие для начисления оклада, которое хотите отредактировать';
  3713.                                 $buttons = array();
  3714.                                 foreach ($salarySchedule as $item_ss){
  3715.                                     $buttons[][] = array(
  3716.                                         'text' => $item_ss['day'] . ' числа каждого месяца по ' $item_ss['amount'] . ' руб',
  3717.                                         'callback_data'=> json_encode(array("action" => "edit_ss"'command' => "bpay"'ss_id' => $item_ss['id'], "group" => $p_group))
  3718.                                     );
  3719.                                 }
  3720.                                 $buttons[][] =  array(
  3721.                                     'text'=>'Назад',
  3722.                                     'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "bpay""group" => $p_group))
  3723.                                 );
  3724.                                 $keyboard $buttons;
  3725.                             } else {
  3726.                                 $reply 'Условий для начисления оклада не найдено, можете создать новое';
  3727.                                 $keyboard = array(array(
  3728.                                     array(
  3729.                                         'text'=>'Новое условие начисления',
  3730.                                         'callback_data'=> json_encode(array('action' => "new_ss_date"'command' => "bpay""group" => $p_group))
  3731.                                     )
  3732.                                 ),
  3733.                                     array(
  3734.                                         array(
  3735.                                             'text'=>'Назад',
  3736.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3737.                                         )
  3738.                                     )
  3739.                                 );
  3740.                             }
  3741.                         } elseif($action == 'rem_ss_date') {
  3742.                             //удалить условие начисления оклада
  3743.                             $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
  3744.                             if(count($salarySchedule) > 0){
  3745.                                 $reply 'Выберите из списка условие для начисления оклада, которое хотите удалить';
  3746.                                 $buttons = array();
  3747.                                 foreach ($salarySchedule as $item_ss){
  3748.                                     $buttons[][] = array(
  3749.                                         'text' => $item_ss['day'] . ' числа каждого месяца по ' $item_ss['amount'] . ' руб',
  3750.                                         'callback_data'=> json_encode(array("action" => "rem_ss"'command' => "bpay"'ss_id' => $item_ss['id'], "group" => $p_group))
  3751.                                     );
  3752.                                 }
  3753.                                 $buttons[][] =  array(
  3754.                                     'text'=>'Назад',
  3755.                                     'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "bpay""group" => $p_group))
  3756.                                 );
  3757.                                 $keyboard $buttons;
  3758.                             } else {
  3759.                                 $reply 'Условий для начисления оклада не найдено, можете создать новое';
  3760.                                 $keyboard = array(array(
  3761.                                     array(
  3762.                                         'text'=>'Новое условие начисления',
  3763.                                         'callback_data'=> json_encode(array('action' => "new_ss_date"'command' => "bpay""group" => $p_group))
  3764.                                     )
  3765.                                 ),
  3766.                                     array(
  3767.                                         array(
  3768.                                             'text'=>'Назад',
  3769.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3770.                                         )
  3771.                                     )
  3772.                                 );
  3773.                             }
  3774.                         } elseif($action == 'edit_ss'){
  3775.                             //изменить условие начисления оклада
  3776.                             $id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
  3777.                             $isExistSs false;
  3778.                             if($id != '' && $id != null){
  3779.                                 $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
  3780.                                 if($salarySchedule){
  3781.                                     $isExistSs true;
  3782.                                     $reply 'Выбрано для редактирования условие для начисления «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() .  ' руб». Выберите, что нужно отредактировать';
  3783.                                     $keyboard = array(
  3784.                                         array(
  3785.                                             array(
  3786.                                                 'text'=>'Число месяца',
  3787.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_d"'command' => "bpay"'ss_id' => $salarySchedule->getId(), "group" => $p_group))
  3788.                                             ),
  3789.                                             array(
  3790.                                                 'text'=>'Сумму начисления',
  3791.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_a"'command' => "bpay"'ss_id' => $salarySchedule->getId(), "group" => $p_group))
  3792.                                             )
  3793.                                         ),
  3794.                                         array(
  3795.                                             array(
  3796.                                                 'text'=>'Назад',
  3797.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_date"'command' => "bpay""group" => $p_group))
  3798.                                             )
  3799.                                         )
  3800.                                     );
  3801.                                 }
  3802.                             }
  3803.                             if(!$isExistSs){
  3804.                                 $reply 'Не удалось найти условий для начисления оклада';
  3805.                                 $keyboard = array(
  3806.                                     array(
  3807.                                         array(
  3808.                                             'text'=>'В основное меню',
  3809.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3810.                                         )
  3811.                                     )
  3812.                                 );
  3813.                             }
  3814.                         } elseif($action == 'edit_ss_d' || $action == 'edit_ss_a') {
  3815.                             //изменить условие начисления оклада
  3816.                             $id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
  3817.                             $isExistSs false;
  3818.                             if($id != '' && $id != null){
  3819.                                 $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
  3820.                                 if($salarySchedule){
  3821.                                     $isExistSs true;
  3822.                                     if($action == 'edit_ss_d'){
  3823.                                         $reply 'Введите новое число дня месяца для условия начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() .  ' руб»';
  3824.                                         $this->addExpected(($is_group_chat === true && $groupObj $groupObj $clientObj), array("value" => "edit_ss_d""ss_id" => $salarySchedule->getId(), "group" => $p_group));
  3825.                                     } else {
  3826.                                         $reply 'Введите новую сумму для условия начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() .  ' руб»';
  3827.                                         $this->addExpected(($is_group_chat === true && $groupObj $groupObj $clientObj), array("value" => "edit_ss_a""ss_id" => $salarySchedule->getId(), "group" => $p_group));
  3828.                                     }
  3829.                                 }
  3830.                             }
  3831.                             if(!$isExistSs){
  3832.                                 $reply 'Не удалось найти условий для начисления оклада';
  3833.                                 $keyboard = array(
  3834.                                     array(
  3835.                                         array(
  3836.                                             'text'=>'В основное меню',
  3837.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3838.                                         )
  3839.                                     )
  3840.                                 );
  3841.                             }
  3842.                         } elseif($action == 'rem_ss'){
  3843.                             //удалить условие начисления оклада
  3844.                             $id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
  3845.                             $isExistSs false;
  3846.                             if($id != '' && $id != null){
  3847.                                 $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
  3848.                                 if($salarySchedule){
  3849.                                     $isExistSs true;
  3850.                                     $reply 'Условие для начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() .  ' руб» успешно удалено';
  3851.                                     $em->remove($salarySchedule);
  3852.                                     $em->flush();
  3853.                                     $keyboard = array(
  3854.                                         array(
  3855.                                             array(
  3856.                                                 'text'=>'Назад',
  3857.                                                 'callback_data'=> json_encode(array('action' => "rem_ss_date"'command' => "bpay""group" => $p_group))
  3858.                                             )
  3859.                                         ),
  3860.                                         array(
  3861.                                             array(
  3862.                                                 'text'=>'В основное меню',
  3863.                                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3864.                                             )
  3865.                                         )
  3866.                                     );
  3867.                                 }
  3868.                             }
  3869.                             if(!$isExistSs){
  3870.                                 $reply 'Не удалось найти условий для начисления оклада';
  3871.                                 $keyboard = array(
  3872.                                     array(
  3873.                                         array(
  3874.                                             'text'=>'В основное меню',
  3875.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  3876.                                         )
  3877.                                     )
  3878.                                 );
  3879.                             }
  3880.                         } elseif($action == 'add_office_exp'){
  3881.                             $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj'client_group' => $groupObj));
  3882.                             if($draftObj){
  3883.                                 $officeObj false;
  3884.                                 if(isset($cq_data['id'])){
  3885.                                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  3886.                                         $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  3887.                                     }
  3888.                                 }
  3889.                                 if($officeObj){
  3890.                                     $draftObj->setOffice($officeObj);
  3891.                                 }
  3892.                                 $draftObj->setExpected('amount_b');
  3893.                                 $em->persist($draftObj);
  3894.                                 $em->flush();
  3895.                                 $reply 'Выбрано «Объект' . ($officeObj ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() : '') . ' для начисления зарплаты». ' 'Введите сумму.';
  3896.                                 $groupObj false;
  3897.                                 if($p_group != '' && $p_group != null){
  3898.                                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  3899.                                 }
  3900.                                 $this->addExpected(($groupObj && $is_group_chat === true $groupObj $clientObj), array("value" => "amount_b""group" => $p_group));
  3901.                             } else {
  3902.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  3903.                                 $keyboard = array();
  3904.                             }
  3905.                         }
  3906.                     }
  3907.                 } else {
  3908.                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить добавление финансовой операции, у данной группы не выбран тип группы. Пожалуйста укажите тип группы данной группе и начните добавление операции занова.';
  3909.                 }
  3910.             } else {
  3911.                 $reply 'Финансовые операции начинаются из группы, пожалуйста отправьте команду для начала операции в нужной группе.';
  3912.             }
  3913.         } elseif($expected != '' && $expected != null){
  3914.             $curClientObj false;
  3915.             if($is_group_chat === true){
  3916.                 $curClientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  3917.             }
  3918.             if($curClient && (($text != '' && $text != null) || ($file_id != '' && $file_id != null))){
  3919.                 $groupObj false;
  3920.                 if($group_id != null && $group_id != ''){
  3921.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  3922.                 } elseif($p_group != null && $p_group != '') {
  3923.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  3924.                 }
  3925.                 if($groupObj && $curClient){
  3926.                     $name_group $groupObj->nameClient();
  3927.                     $type_group_typeof null;
  3928.                     if($groupObj->getTypeGroup()){
  3929.                         $type_group_typeof $groupObj->getTypeGroup()->getTypeof();
  3930.                     }
  3931.                     if($is_group_chat === true && $groupObj){
  3932.                         $chat_id $groupObj->getChatId();
  3933.                     }
  3934.                     $draftObj $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => ($curClientObj $curClientObj->getId() : $curClient->getId()), 'client_group' => $groupObj));
  3935.                     if($draftObj){
  3936.                         if($expected == 'amount_b'){
  3937.                             $amount = (float) $text;
  3938.                             if($amount || $draftObj->getTypeTransaction() == 'payment_salary'){
  3939.                                 $draftObj->setAmount($amount 100);
  3940.                                 $draftObj->setExpected('comment_b');
  3941.                                 $em->persist($draftObj);
  3942.                                 $em->flush();
  3943.                                 $this->addExpected($curClient, array("value" => "comment_b""group" => $p_group));
  3944.                                 $sum str_replace(',00'''number_format(($draftObj->getAmount() / 100), 2','' '));
  3945.                                 $reply 'Введено «Сумма ' $sum '». ' 'Введите комментарий';
  3946.                             } else {
  3947.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Неправильно указана сумма, укажите сумму числом.';
  3948.                             }
  3949.                         } elseif($expected == 'comment_b') {
  3950.                             if($draftObj->getTypeTransaction() == 'expense_office'){
  3951.                                 $draftObj->setComment(trim($text));
  3952.                                 $draftObj->setExpected('file_cheque_b');
  3953.                                 $em->persist($draftObj);
  3954.                                 $em->flush();
  3955.                                 $this->addExpected($curClient, array("value" => "file_cheque_b""group" => $p_group));
  3956.                                 $keyboard = [
  3957. //                                    [
  3958. //                                        [
  3959. //                                            'text'=>'Без чека',
  3960. //                                            'callback_data'=> json_encode(array('action' => "no_cheque", 'command' => "bpay", "group" => $p_group))
  3961. //                                        ]
  3962. //                                    ]
  3963.                                 ];
  3964.                                 $reply 'Сделайте или прикрепите фото чека';
  3965.                             } else {
  3966.                                 $draftObj->setComment(trim($text));
  3967.                                 $draftObj->setExpected('finish_b');
  3968.                                 $em->persist($draftObj);
  3969.                                 $em->flush();
  3970.                                 $this->resetExpected($curClient);
  3971. //                                $create_transaction = $this->createTransaction($token, $chat_id, $groupObj, $draftObj);
  3972. //                                if($create_transaction === true){
  3973. //                                    $em->remove($draftObj);
  3974. //                                    $em->flush();
  3975. //                                }
  3976.                                 $create_transaction $this->sendMailNonCashCheque($token$chat_id$groupObj$draftObj);
  3977.                                 if($create_transaction === true){
  3978.                                     $em->remove($draftObj);
  3979.                                     $em->flush();
  3980.                                 }
  3981.                                 $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Письмо с безналичным чеком успешно отправлено.';
  3982.                             }
  3983.                         } elseif($expected == 'file_cheque_b') {
  3984.                             $file null;
  3985.                             if($file_id != '' && $file_id != null){
  3986.                                 $file $this->uploadFileBot($token$file_id);
  3987.                             }
  3988.                             if($file != null){
  3989.                                 $draftObj->setFile(($draftObj->getFile() != null && $draftObj->getFile() != '' $draftObj->getFile() . ';' $file $file));
  3990.                                 $em->persist($draftObj);
  3991.                                 $em->flush();
  3992.                                 $reply 'Фото чека успешно прикреплено. Чтобы добавить ещё фото чека, сделайте или прикрепите фото чека.';
  3993.                             } else {
  3994.                                 $reply 'Фото чека не удалось прикрепить. Чтобы добавить фото чека снова, сделайте или прикрепите фото чека.';
  3995.                             }
  3996.                             $editMessageId $draftObj->getLastMessageId();
  3997.                             $this->addExpected($curClient, array("value" => "file_cheque_b""group" => $p_group));
  3998.                             $keyboard = [
  3999.                                 [
  4000.                                     [
  4001.                                         'text'=> 'Завершить операцию',
  4002.                                         'callback_data'=> json_encode(array('action' => "finish_pay"'command' => "bpay""group" => $p_group))
  4003.                                     ]
  4004.                                 ]
  4005.                             ];
  4006.                             /*
  4007.                             //окончание финансовой операции
  4008.                             $draftObj->setExpected('finish_b');
  4009.                             $em->persist($draftObj);
  4010.                             $em->flush();
  4011.                             $this->resetExpected($curClient);
  4012.                             $create_transaction = $this->createTransaction($token, $chat_id, $groupObj, $draftObj);
  4013.                             if($create_transaction === true){
  4014.                                 $em->remove($draftObj);
  4015.                                 $em->flush();
  4016.                             }
  4017.                             $reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Транзакция успешно добавлена.';
  4018.                             */
  4019.                         }
  4020.                     } elseif($expected == 'new_date_b'){
  4021.                         if(is_numeric(trim($text)) && trim($text) <= 31){
  4022.                             $reply 'Введите сумму начисления оклада';
  4023.                             $newSalarySchedule = new SalarySchedule();
  4024.                             $newSalarySchedule->setClient(($groupObj && $is_group_chat === true $groupObj $curClient))
  4025.                                 ->setDay(trim($text))
  4026.                                 ->setIsEdit(true)
  4027.                             ;
  4028.                             $em->persist($newSalarySchedule);
  4029.                             $em->flush();
  4030.                             $groupObj false;
  4031.                             if($p_group != '' && $p_group != null){
  4032.                                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  4033.                             }
  4034.                             $this->addExpected(($groupObj && $is_group_chat === true $groupObj $curClient), array("value" => "new_amount_b""group" => $p_group));
  4035.                         } else {
  4036.                             if(is_numeric(trim($text)) && trim($text) > 31){
  4037.                                 $reply 'День месяца не должен быть больше 31';
  4038.                             } else {
  4039.                                 $reply 'Введите день числом, в который будет осуществляться начисления оклада';
  4040.                             }
  4041.                             $keyboard = array(
  4042.                                 array(
  4043.                                     array(
  4044.                                         'text'=>'Назад',
  4045.                                         'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "bpay""group" => $p_group))
  4046.                                     )
  4047.                                 )
  4048.                             );
  4049.                         }
  4050.                     } elseif($expected == 'new_amount_b'){
  4051.                         $amount = (float) $text;
  4052.                         $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(array('client' => ($groupObj && $is_group_chat === true $groupObj $curClient), 'is_edit' => true));
  4053.                         if($amount && $salarySchedule){
  4054.                             $salarySchedule->setAmount($amount)
  4055.                                 ->setIsEdit(false);
  4056.                             $em->persist($salarySchedule);
  4057.                             $em->flush();
  4058.                             $this->resetExpected(($groupObj && $is_group_chat === true $groupObj $curClient));
  4059.                             $reply 'Условие начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() . ' руб» успешно добавлено';
  4060.                         } else {
  4061.                             $reply 'Не удалось добавить информацию для начисления оклада, попробуйте повторить операцию снова';
  4062.                         }
  4063.                     } elseif($expected == 'edit_ss_d_b' || $expected == 'edit_ss_a_b') {
  4064.                         if(is_numeric($text)){
  4065.                             $isExistSs false;
  4066.                             if($ss_id != null && $ss_id != ''){
  4067.                                 $salarySchedule $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(array('id' => $ss_id));
  4068.                                 if($salarySchedule){
  4069.                                     $isExistSs true;
  4070.                                     if($expected == 'edit_ss_d_b'){
  4071.                                         $salarySchedule->setDay($text);
  4072.                                     } else {
  4073.                                         $salarySchedule->setAmount($text);
  4074.                                     }
  4075.                                     $em->persist($salarySchedule);
  4076.                                     $em->flush();
  4077.                                     $reply 'Условие начисления оклада «' $salarySchedule->getDay() . ' числа каждого месяца по ' $salarySchedule->getAmount() . ' руб» успешно отредактировано';
  4078.                                     $keyboard = array(
  4079.                                         array(
  4080.                                             array(
  4081.                                                 'text'=>'Назад',
  4082.                                                 'callback_data'=> json_encode(array('action' => "edit_ss_date"'command' => "bpay""group" => $p_group))
  4083.                                             )
  4084.                                         ),
  4085.                                         array(
  4086.                                             array(
  4087.                                                 'text'=>'В основное меню',
  4088.                                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  4089.                                             )
  4090.                                         )
  4091.                                     );
  4092.                                     $this->resetExpected($curClient);
  4093.                                 }
  4094.                             }
  4095.                             if(!$isExistSs){
  4096.                                 $reply 'Не удалось отредактировать условий для начисления оклада';
  4097.                                 $keyboard = array(
  4098.                                     array(
  4099.                                         array(
  4100.                                             'text'=>'В основное меню',
  4101.                                             'callback_data'=> json_encode(array('action' => "menu"'command' => "bpay""group" => $p_group))
  4102.                                         )
  4103.                                     )
  4104.                                 );
  4105.                             }
  4106.                         } else {
  4107.                             $reply 'Данные для ввода должны быть числом. Повторите ввод';
  4108.                         }
  4109.                     } else {
  4110.                         $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
  4111.                     }
  4112.                 }
  4113.             }
  4114.         } else {
  4115.             $groupObj false;
  4116.             if($group_id != '' && $group_id != null){
  4117.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  4118.             } elseif($p_group != '' && $p_group != null){
  4119.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  4120.             }
  4121.             if($groupObj){
  4122.                 if($is_group_chat === true && $groupObj){
  4123.                     $chat_id $groupObj->getChatId();
  4124.                 }
  4125.                 $name_group '';
  4126.                 $type_group_typeof null;
  4127.                 if($groupObj->getTypeGroup()){
  4128.                     $type_group_typeof $groupObj->getTypeGroup()->getTypeof();
  4129.                     $name_group $groupObj->nameClient();
  4130.                 }
  4131.                 if($type_group_typeof != null && $type_group_typeof != ''){
  4132.                     if($type_group_typeof == 'cash'){
  4133.                         $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Выберите финансовую операцию.';
  4134.                         $keyboard = array(
  4135. //                            array(
  4136. //                                array(
  4137. //                                    'text'=>'Приход',
  4138. //                                    'callback_data'=> json_encode(array('action' => "income", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
  4139. //                                )
  4140. //                            ),
  4141.                             array(
  4142.                                 array(
  4143.                                     'text'=>'Расход',
  4144.                                     'callback_data'=> json_encode(array('action' => "expense"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  4145.                                 ),
  4146.                             ),
  4147.                             array(
  4148.                                 array(
  4149.                                     'text'=>'Назад',
  4150.                                     'callback_data'=> json_encode(array('action' => "delete"'command' => "bpay"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  4151.                                 )
  4152.                             )
  4153.                         );
  4154.                     } elseif($type_group_typeof == 'salary') {
  4155.                         $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  4156.                         $commandPermissions $this->curCommandPermissions($clientObj'bpay');
  4157.                         $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Выберите финансовую операцию.';
  4158. //                        $keyboard = array(
  4159. //                            array(
  4160. //                                array(
  4161. //                                    'text'=>'Перевод в группу ЗП',
  4162. //                                    'callback_data'=> json_encode(array('action' => "income", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
  4163. //                                )
  4164. //                            ),
  4165. //                            array(
  4166. //                                array(
  4167. //                                    'text'=>'Перевод в группу Нал',
  4168. //                                    'callback_data'=> json_encode(array('action' => "income_cash", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
  4169. //                                )
  4170. //                            ),
  4171. //                            array(
  4172. //                                array(
  4173. //                                    'text'=>'Начисление зарплаты',
  4174. //                                    'callback_data'=> json_encode(array('action' => "expense", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
  4175. //                                ),
  4176. //                            ),
  4177. //                            array(
  4178. //                                array(
  4179. //                                    'text'=>'Начисление оклада',
  4180. //                                    'callback_data'=> json_encode(array('action' => "expense_salary", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
  4181. //                                ),
  4182. //                            ),
  4183. //                            array(
  4184. //                                array(
  4185. //                                    'text'=>'Назад',
  4186. //                                    'callback_data'=> json_encode(array('action' => "delete", 'command' => "bpay", 'mes_id' => $message_id, "group" => ($groupObj ? $groupObj->getId() : null)))
  4187. //                                )
  4188. //                            )
  4189. //                        );
  4190.                         $keyboard = [];
  4191.                         if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('salary_pay_transfer_to_salary'$commandPermissions))){
  4192.                             //Перевод в группу ЗП
  4193.                             $keyboard[] = [[
  4194.                                 'text'=>'Перевод в группу ЗП',
  4195.                                 'callback_data'=> json_encode(array('action' => "income"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  4196.                             ]];
  4197.                         }
  4198.                         if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('salary_pay_transfer_to_cash'$commandPermissions))){
  4199.                             //Перевод в группу Нал
  4200.                             $keyboard[] = [[
  4201.                                 'text'=>'Перевод в группу Нал',
  4202.                                 'callback_data'=> json_encode(array('action' => "income_cash"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  4203.                             ]];
  4204.                         }
  4205.                         if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('salary_pay_accrual_salary'$commandPermissions))){
  4206.                             //Начисление зарплаты
  4207.                             $keyboard[] = [[
  4208.                                 'text'=>'Начисление зарплаты',
  4209.                                 'callback_data'=> json_encode(array('action' => "expense"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  4210.                             ]];
  4211.                         }
  4212.                         if(count($commandPermissions) <= || (count($commandPermissions) > && in_array('salary_pay_accrual_payday'$commandPermissions))){
  4213.                             //Начисление оклада
  4214.                             $keyboard[] = [[
  4215.                                 'text'=>'Начисление оклада',
  4216.                                 'callback_data'=> json_encode(array('action' => "expense_salary"'command' => "bpay""group" => ($groupObj $groupObj->getId() : null)))
  4217.                             ]];
  4218.                         }
  4219.                         $keyboard[] = [[
  4220.                             'text'=>'Назад',
  4221.                             'callback_data'=> json_encode(array('action' => "delete"'command' => "bpay"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  4222.                         ]];
  4223.                     }
  4224.                 } else {
  4225.                     $reply = ($name_group != '' && $name_group != null 'Работаете с группой «' $name_group '». ' '') . 'Невозможно продолжить действие, у данной группы не выбран тип группы. Пожалуйста укажите тип группы и начните данную команду заново.';
  4226.                 }
  4227.             } else {
  4228.                 $reply 'Финансовые операции начинаются из группы, пожалуйста отправьте команду для начала операции в нужной группе.';
  4229.             }
  4230.         }
  4231.         if(!isset($reply) || $reply == '' || $reply == null){
  4232.             $reply 'Что то пошло не так, начните выполнение операции заново';
  4233.         }
  4234.         $sendMessage false;
  4235.         if(count($keyboard) > 0){
  4236.             $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  4237.             if($editMessageId != null){
  4238.                 //редактировать уже существующее сообщение
  4239.                 $sendMessage ProjectUtilsController::requestToBot($token'editMessageText', ['chat_id' => $chat_id'message_id' => $editMessageId'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  4240.             } else {
  4241.                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  4242.             }
  4243.             $resp json_decode($sendMessagetrue);
  4244.             if(isset($resp['result']['message_id']) && $groupObj){
  4245.                 file_put_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt'$resp['result']['message_id']);
  4246.             }
  4247. //            if($draftObj && $file_id != null && $file_id != '' && isset($resp['result']['message_id'])){
  4248. //                $draftObj->setLastMessageId($resp['result']['message_id']);
  4249. //                $em->persist($draftObj);
  4250. //                $em->flush();
  4251. //            }
  4252.         } else {
  4253.             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  4254.         }
  4255.         if($is_group_chat === true){
  4256.             $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
  4257.             $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'bpay'));
  4258.             $this->addLogMessageBot($bot$command$sendMessage);
  4259.             if($create_transaction === true){
  4260.                 $this->deleteLogMessage($bot$chat_id$command->getId());
  4261.             }
  4262.         }
  4263.     }
  4264.     private function sendMailNonCashCheque($token$chat_id$group$draft){
  4265.         $basePath $this->getParameter('kernel.project_dir');
  4266.         $fileDir '/public/images/';
  4267.         $is_group_chat $this->getParameter('app.chat.is_group');
  4268.         $resp false;
  4269.         $em $this->getDoctrine()->getManager();
  4270.         $isSendMail false;
  4271.         $typeMail 'newTransaction';
  4272.         if($token != '' && $token != null && $chat_id != '' && $chat_id != null && $group && $draft){
  4273.             if($draft->getExpected() == 'finish_b'){
  4274.                 $amount $draft->getAmount();
  4275.                 if($draft->getTypeof() == 'expense'){
  4276.                     $amount '-' $draft->getAmount();
  4277.                 }
  4278.                 $is_income false;
  4279.                 //если приход по Объекту, или начисление ЗП
  4280.                 if(!$draft->getFromGroup() && $draft->getToGroup()){
  4281.                     $is_income true;
  4282.                 }
  4283.                 $office_name '';
  4284.                 $office_number '';
  4285.                 if($draft->getOffice()){
  4286.                     $office_name $draft->getOffice()->getName();
  4287.                     $office_number $draft->getOffice()->getNumber();
  4288.                 }
  4289.                 $from_chat_id null;
  4290.                 $from_name '';
  4291.                 $type_group_from null;
  4292.                 if($draft->getFromGroup()){
  4293.                     $from_chat_id $draft->getFromGroup()->getChatId();
  4294.                     $from_name $draft->getFromGroup()->nameClient();
  4295.                     $type_group_from = ($draft->getFromGroup()->getTypeGroup() != null $draft->getFromGroup()->getTypeGroup()->getTypeof() : null);
  4296.                 }
  4297.                 $to_chat_id null;
  4298.                 $to_name '';
  4299.                 $type_group_to null;
  4300.                 if($draft->getToGroup()){
  4301.                     $to_chat_id $draft->getToGroup()->getChatId();
  4302.                     $to_name $draft->getToGroup()->nameClient();
  4303.                     $type_group_to = ($draft->getToGroup()->getTypeGroup() != null $draft->getToGroup()->getTypeGroup()->getTypeof() : null);
  4304.                 }
  4305.                 //если приход по Объекту, или начисление ЗП
  4306.                 if($is_income === true && $draft->getToGroup()){
  4307.                     $from_chat_id $draft->getToGroup()->getChatId();
  4308.                     $from_name $draft->getToGroup()->nameClient();
  4309.                 }
  4310.                 $m_source '';
  4311.                 $m_type '';
  4312.                 if($draft->getTypeTransaction() == 'expense_office' || ($draft->getTypeTransaction() == 'income' && $draft->getTypeof() == 'income') || ($draft->getTypeTransaction() == 'add_salary' && $draft->getTypeof() == 'expense')){
  4313.                     $isSendMail true;
  4314.                     $m_source = ($draft->getFromGroup() != null $draft->getFromGroup()->getFirstName() : '');
  4315.                     if($draft->getTypeTransaction() == 'expense_office'){
  4316.                         // +300 (Нал бот, 444. Бургерная, тестовый коммент)
  4317.                         $cm $amount " (" $from_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ", " $draft->getComment() . ")";
  4318.                         if($draft->getFile() != '' && $draft->getFile() != null){
  4319.                             $typeMail 'newTransactionIncomeCashСheque';
  4320.                             $m_type 'расход Чек';
  4321.                         } else {
  4322.                             $typeMail 'newTransactionIncomeCashNoСheque';
  4323.                             $m_type 'расход Нал';
  4324.                         }
  4325.                     } elseif($draft->getTypeTransaction() == 'income' && $draft->getTypeof() == 'income'){
  4326.                         // +555 (Нал Бот, 24195. Пробник, тест коммент)
  4327.                         $cm $amount " (" $from_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ", " $draft->getComment() . ")";
  4328.                         //$m_source = ($draft->getFromGroup() != null ? $draft->getFromGroup()->getFirstName() : '');
  4329.                         $m_source = ($draft->getToGroup() != null $draft->getToGroup()->getFirstName() : '');
  4330.                         $m_type 'приход Нал';
  4331.                         $typeMail 'newTransactionIncomeCash';
  4332.                     } elseif($draft->getTypeTransaction() == 'add_salary' && $draft->getTypeof() == 'expense'){
  4333.                         // -333 (Нал Бот - ЗП Бот, тест коммент)
  4334.                         $cm '-' $amount " (" $from_name " - " $to_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ", " $draft->getComment() . ")";
  4335.                         $m_source = ($draft->getToGroup() != null $draft->getToGroup()->getFirstName() : '');
  4336.                         $m_type 'расход ЗП';
  4337.                         $typeMail 'newTransactionExpenseSalary';
  4338.                     }
  4339.                 }
  4340.                 if($draft->getAmount() < && $draft->getTypeTransaction() == 'payment_salary' && $draft->getTypeof() == 'expense'){
  4341.                     $draft->setTypeof('income');
  4342.                     $draft->setAmount(abs($draft->getAmount()));
  4343.                     $em->persist($draft);
  4344.                     $em->flush();
  4345.                 }
  4346.                 $amount_reverse 0;
  4347.                 if($draft->getToGroup() && $draft->getFromGroup()){
  4348.                     $typeof_reverse null;
  4349.                     if($draft->getTypeof() == 'expense'){
  4350.                         $typeof_reverse 'income';
  4351.                     } elseif($draft->getTypeof() == 'income'){
  4352.                         $typeof_reverse 'expense';
  4353.                     }
  4354.                     $amount_reverse $draft->getAmount();
  4355.                     if($typeof_reverse == 'expense'){
  4356.                         $amount_reverse '-' $draft->getAmount();
  4357.                     }
  4358.                 }
  4359.                 $from_group $draft->getFromGroup();
  4360.                 //если приход по Объекту, или начисление ЗП
  4361.                 if($is_income === true && $draft->getToGroup()){
  4362.                     $from_group $draft->getToGroup();
  4363.                 }
  4364.                 if ($draft->getTypeof() == 'expense' && $draft->getToGroup() && $is_income === false) {
  4365.                     $to_group $draft->getToGroup();
  4366.                 }
  4367.                 $resp true;
  4368.                 if($isSendMail){
  4369.                     //отправка письма по операциям
  4370.                     $recipient $this->getParameter('app.mailer.to.transaction');
  4371.                     $m_amount $draft->getAmount();
  4372.                     $m_office = ($draft->getOffice() != null ? ($draft->getOffice()->getNumber() != '' && $draft->getOffice()->getNumber() != null $draft->getOffice()->getNumber() . '. ' '') . $draft->getOffice()->getName() : '');
  4373.                     $author '';
  4374.                     if($draft->getClient() != null){
  4375.                         if($draft->getClient()->getUsername() != null && $draft->getClient()->getUsername() != ''){
  4376.                             $author $draft->getClient()->getUsername();
  4377.                         }
  4378.                     }
  4379.                     $title_mail = array(
  4380.                         '#amount#' => str_replace(',00'''number_format((abs($m_amount) / 100), 2','' ')),
  4381.                         '#source#' => $m_source,
  4382.                         '#type#' => $m_type,
  4383.                         '#comment#' => $draft->getComment()
  4384.                     );
  4385.                     $body_mail = array(
  4386.                         '#office#' => $m_office,
  4387.                         '#type#' => $m_type,
  4388.                         '#amount#' => str_replace(',00'''number_format((abs($m_amount) / 100), 2','' ')),
  4389.                         '#date#' => ($draft->getCreatedAt() != null $draft->getCreatedAt()->format('d.m.Y') : ''),
  4390.                         '#source#' => $m_source,
  4391.                         '#comment#' => $draft->getComment(),
  4392.                         '#author#' => $author
  4393.                     );
  4394.                     $attach = [];
  4395.                     if($draft->getFile() != null && $draft->getFile() != ''){
  4396.                         if (strpos($draft->getFile(), ';') !== false) {
  4397.                             $filesList explode(';'$draft->getFile());
  4398.                             if(count($filesList) > 0){
  4399.                                 foreach ($filesList as $fileItem){
  4400.                                     $filepath $basePath $fileDir trim($fileItem);
  4401.                                     if(file_exists($filepath)){
  4402.                                         $attach[] = $basePath $fileDir trim($fileItem);
  4403.                                     }
  4404.                                 }
  4405.                             }
  4406.                         } else {
  4407.                             $filepath $basePath $fileDir $draft->getFile();
  4408.                             if(file_exists($filepath)){
  4409.                                 $attach[] = $basePath $fileDir $draft->getFile();
  4410.                             }
  4411.                         }
  4412.                     }
  4413.                     $this->sendEmail($this->mailer$typeMail$body_mail$title_mail'ru'$recipient$attach);
  4414.                 }
  4415.                 if($draft->getTypeTransaction() == 'add_salary'){
  4416.                     //- 5 000 ЗП Бас Иванов.  Сидоров
  4417.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4418.                     //$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') .  $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
  4419.                     $reply $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4420.                     // -333 (Нал Бот - ЗП Бот, тест коммент)
  4421.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4422.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4423.                     }
  4424.                     //+7 500 ЗП Бас Иванов. Петров
  4425.                     $amount "+" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4426.                     //$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
  4427.                     $reply $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4428.                     if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
  4429.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $to_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4430.                     }
  4431.                 } elseif($draft->getTypeTransaction() == 'add_salary_cash'){
  4432.                     //+5 000 ЗП Бас Иванов.  Сидоров
  4433.                     $amount "+" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4434.                     //$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
  4435.                     $reply $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4436.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4437.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4438.                     }
  4439.                     //-7 500 ЗП Бас Иванов. Петров
  4440.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4441.                     //$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
  4442.                     $reply $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4443.                     if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
  4444.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $to_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4445.                     }
  4446.                 } elseif($draft->getTypeTransaction() == 'payment_salary'){
  4447.                     //Начисление зарплаты, вызывается из группы ЗП
  4448.                     //-7 500 ЗП Рук Иванов. Петров
  4449.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4450.                     //$reply = $amount .  " (ЗП, " . $draft->getComment() . ". " . $from_name . ".)";
  4451.                     $reply $amount .  " (Начисл ЗП. " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4452.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4453.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4454.                     }
  4455.                 } elseif($draft->getTypeTransaction() == 'transfer'){
  4456.                     //- 1 000 Петрову и + 1 000 от Иванова
  4457.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4458.                     //$reply = $amount  . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name  . ".";
  4459.                     //if($type_group_from == 'salary' && $type_group_to == 'cash'){
  4460.                     //    $reply = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
  4461.                     // } else {
  4462.                     $reply $amount " (" $from_name " - " $to_name . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4463.                     //}
  4464.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4465.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4466.                     }
  4467.                     $amount "+" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4468.                     //$reply = $amount . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . " от " . $from_name . ".";
  4469.                     //if($type_group_from == 'salary' && $type_group_to == 'cash'){
  4470.                     //    $reply = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
  4471.                     //} else {
  4472.                     $reply $amount " (" $from_name " - " $to_name . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4473.                     //}
  4474.                     if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
  4475.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $to_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4476.                     }
  4477.                 } elseif($draft->getTypeTransaction() == 'income'){
  4478.                     //+ 10 000 Бас Иванов. Предоплата ++
  4479.                     $amount "+" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4480.                     //$reply = $amount . ($office_name != '' ? " (" . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : ""). ". " . $from_name . ".)";
  4481.                     $reply $amount " (" $from_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4482.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4483.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4484.                     }
  4485.                 } elseif($draft->getTypeTransaction() == 'expense_office'){
  4486.                     //- 3 500 Бас Иванов. Гвозди
  4487.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4488.                     //$reply = $amount . ($office_name != '' ? " (" . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ". " . $draft->getComment() . ".)";
  4489.                     $reply $amount " (" $from_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ", " $draft->getComment() . ")";
  4490.                     // +300 (Нал бот, 444. Бургерная, тестовый коммент)
  4491.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4492.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4493.                     }
  4494.                 } elseif($draft->getTypeTransaction() == 'expense_company'){
  4495.                     //- 1 000 Бизнес. Оплата связи
  4496.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4497.                     //$reply = $amount . " (Бизнес. " . $draft->getComment() . ".)";
  4498.                     $reply $amount " (Бизнес. " $draft->getComment() . ".)";
  4499.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4500.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4501.                     }
  4502.                 }
  4503.             }
  4504.         }
  4505.         return $resp;
  4506.     }
  4507.     private function uploadFileBot($token$file_id){
  4508.         $basePath $this->getParameter('kernel.project_dir');
  4509.         $project_dir $basePath '/public/images/';
  4510.         $getFile ProjectUtilsController::requestToBot($token'getFile', ['file_id' => $file_id]);
  4511.         $resp json_decode($getFiletrue);
  4512.         //file_put_contents($basePath . '/var/log/file_resp.txt', print_r($resp, true), FILE_APPEND);
  4513.         $filepath null;
  4514.         if(isset($resp['result']['file_path']) && isset($resp['ok']) && $resp['ok'] == true){
  4515.             $ext strtolower(substr($resp['result']['file_path'], strrpos($resp['result']['file_path'], '.')));
  4516.             if($ext === '.jpg' || $ext === '.jpeg' || $ext === '.png' || $ext === '.gif'){
  4517.                 $filename ProjectUtilsController::generateUuid();
  4518.                 $dir substr($filename03);
  4519.                 if (!is_dir($project_dir $dir)) {
  4520.                     @mkdir($project_dir);
  4521.                     @mkdir($project_dir $dir);
  4522.                 }
  4523.                 $file ProjectUtilsController::fileToBot($token$resp['result']['file_path']);
  4524.                 file_put_contents($project_dir $dir '/' $filename $ext$file);
  4525.                 if(file_exists($project_dir $dir '/' $filename $ext)){
  4526.                     $filepath '/' $dir '/' $filename $ext;
  4527.                 }
  4528.             }
  4529.         }
  4530.         return $filepath;
  4531.     }
  4532.     private function createTransaction($token$chat_id$group$draft){
  4533.         $basePath $this->getParameter('kernel.project_dir');
  4534.         $fileDir '/public/images/';
  4535.         $is_group_chat $this->getParameter('app.chat.is_group');
  4536.         $resp false;
  4537.         $em $this->getDoctrine()->getManager();
  4538.         $isSendMail false;
  4539.         $typeMail 'newTransaction';
  4540.         if($token != '' && $token != null && $chat_id != '' && $chat_id != null && $group && $draft){
  4541.             if($draft->getExpected() == 'finish'){
  4542.                 $amount $draft->getAmount();
  4543.                 if($draft->getTypeof() == 'expense'){
  4544.                     $amount '-' $draft->getAmount();
  4545.                 }
  4546.                 $is_income false;
  4547.                 //если приход по Объекту, или начисление ЗП
  4548.                 if(!$draft->getFromGroup() && $draft->getToGroup()){
  4549.                     $is_income true;
  4550.                 }
  4551.                 $office_name '';
  4552.                 $office_number '';
  4553.                 if($draft->getOffice()){
  4554.                     $office_name $draft->getOffice()->getName();
  4555.                     $office_number $draft->getOffice()->getNumber();
  4556.                 }
  4557.                 $from_chat_id null;
  4558.                 $from_name '';
  4559.                 $type_group_from null;
  4560.                 if($draft->getFromGroup()){
  4561.                     $from_chat_id $draft->getFromGroup()->getChatId();
  4562.                     $from_name $draft->getFromGroup()->nameClient();
  4563.                     $type_group_from = ($draft->getFromGroup()->getTypeGroup() != null $draft->getFromGroup()->getTypeGroup()->getTypeof() : null);
  4564.                 }
  4565.                 $to_chat_id null;
  4566.                 $to_name '';
  4567.                 $type_group_to null;
  4568.                 if($draft->getToGroup()){
  4569.                     $to_chat_id $draft->getToGroup()->getChatId();
  4570.                     $to_name $draft->getToGroup()->nameClient();
  4571.                     $type_group_to = ($draft->getToGroup()->getTypeGroup() != null $draft->getToGroup()->getTypeGroup()->getTypeof() : null);
  4572.                 }
  4573.                 //если приход по Объекту, или начисление ЗП
  4574.                 if($is_income === true && $draft->getToGroup()){
  4575.                     $from_chat_id $draft->getToGroup()->getChatId();
  4576.                     $from_name $draft->getToGroup()->nameClient();
  4577.                 }
  4578.                 $m_source '';
  4579.                 $m_type '';
  4580.                 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')){
  4581.                     $isSendMail true;
  4582.                     $m_source = ($draft->getFromGroup() != null $draft->getFromGroup()->getFirstName() : '');
  4583.                     if($draft->getTypeTransaction() == 'expense_office'){
  4584.                         // +300 (Нал бот, 444. Бургерная, тестовый коммент)
  4585.                         $cm $amount " (" $from_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ", " $draft->getComment() . ")";
  4586.                         if($draft->getFile() != '' && $draft->getFile() != null){
  4587.                             $typeMail 'newTransactionIncomeCashСheque';
  4588.                             $m_type 'расход Чек';
  4589.                         } else {
  4590.                             $typeMail 'newTransactionIncomeCashNoСheque';
  4591.                             $m_type 'расход Нал';
  4592.                         }
  4593.                     } elseif($draft->getTypeTransaction() == 'income' && $draft->getTypeof() == 'income'){
  4594.                         // +555 (Нал Бот, 24195. Пробник, тест коммент)
  4595.                         $cm $amount " (" $from_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ", " $draft->getComment() . ")";
  4596.                         //$m_source = ($draft->getFromGroup() != null ? $draft->getFromGroup()->getFirstName() : '');
  4597.                         $m_source = ($draft->getToGroup() != null $draft->getToGroup()->getFirstName() : '');
  4598.                         $m_type 'приход Нал';
  4599.                         $typeMail 'newTransactionIncomeCash';
  4600.                     } elseif($draft->getTypeTransaction() == 'add_salary' && $draft->getTypeof() == 'expense'){
  4601.                         // -333 (Нал Бот - ЗП Бот, тест коммент)
  4602.                         $cm '-' $amount " (" $from_name " - " $to_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ", " $draft->getComment() . ")";
  4603.                         $m_source = ($draft->getToGroup() != null $draft->getToGroup()->getFirstName() : '');
  4604.                         $m_type 'расход ЗП';
  4605.                         $typeMail 'newTransactionExpenseSalary';
  4606.                     } elseif($draft->getTypeTransaction() == 'transfer' && $draft->getTypeof() == 'expense'){
  4607.                         $isSendMail false//просили отключить
  4608.                         // - 1 000 Петрову и + 1 000 от Иванова
  4609.                         $cm $amount " (" $from_name " - " $to_name . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4610.                         $m_source = ($draft->getFromGroup() != null $draft->getFromGroup()->getFirstName() : '');
  4611.                         $m_type 'списание ЗП';
  4612.                         $typeMail 'newTransactionTransferSalary';
  4613.                     } elseif($draft->getTypeTransaction() == 'add_salary_cash' && $draft->getTypeof() == 'income'){
  4614.                         //+5 000 ЗП Бас Иванов.  Сидоров
  4615.                         $cm $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4616.                         $m_source = ($draft->getToGroup() != null $draft->getToGroup()->getFirstName() : '');
  4617.                         $m_type 'списание ЗП';
  4618.                         $typeMail 'newTransactionAddSalaryCash';
  4619.                     }
  4620.                 }
  4621.                 $isReverseAmount false;
  4622.                 //просили убрать чтоб начисление ЗП с отрицательным знаком чтоб корректировать сумму начислений в сторону уменьшения
  4623.                 if($draft->getAmount() < && $draft->getTypeTransaction() == 'payment_salary' && $draft->getTypeof() == 'expense'){
  4624.                     $draft->setTypeof('income');
  4625.                     $draft->setAmount(abs($draft->getAmount()));
  4626.                     $em->persist($draft);
  4627.                     $em->flush();
  4628.                     $amount $draft->getAmount();
  4629.                     $isReverseAmount true;
  4630.                 }
  4631.                 $newTransaction = new Transaction();
  4632.                 if($draft->getClient()){
  4633.                     $newTransaction->setSender($draft->getClient());
  4634.                 }
  4635.                 if($draft->getFromGroup()){
  4636.                     $newTransaction->setFromGroup($draft->getFromGroup());
  4637.                 }
  4638.                 if($draft->getToGroup()){
  4639.                     $newTransaction->setToGroup($draft->getToGroup());
  4640.                 }
  4641.                 if($draft->getOffice()){
  4642.                     $newTransaction->setOffice($draft->getOffice());
  4643.                 }
  4644.                 $newTransaction->setTypeof($draft->getTypeof());
  4645.                 $newTransaction->setAmount($amount);
  4646.                 $newTransaction->setComment($draft->getComment());
  4647.                 $newTransaction->setNote($draft->getNote());
  4648.                 $newTransaction->setDate(new \DateTime(date('Y-m-d H:i:s')));
  4649.                 if($is_income === false){
  4650.                     $newTransaction->setRecipient($draft->getFromGroup());
  4651.                 } else {
  4652.                     $newTransaction->setRecipient($draft->getToGroup());
  4653.                 }
  4654.                 if($draft->getFile() != '' && $draft->getFile() != null){
  4655.                     $newTransaction->setFile($draft->getFile());
  4656.                 }
  4657.                 $em->persist($newTransaction);
  4658.                 $em->flush();
  4659.                 $amount_reverse 0;
  4660.                 if($draft->getToGroup() && $draft->getFromGroup()){
  4661.                     $typeof_reverse null;
  4662.                     if($draft->getTypeof() == 'expense'){
  4663.                         $typeof_reverse 'income';
  4664.                     } elseif($draft->getTypeof() == 'income'){
  4665.                         $typeof_reverse 'expense';
  4666.                     }
  4667.                     $amount_reverse $draft->getAmount();
  4668.                     if($typeof_reverse == 'expense'){
  4669.                         $amount_reverse '-' $draft->getAmount();
  4670.                     }
  4671.                     $newTransactionReverse = new Transaction();
  4672.                     if($draft->getClient()){
  4673.                         $newTransactionReverse->setSender($draft->getClient());
  4674.                     }
  4675.                     if($draft->getFromGroup()){
  4676.                         $newTransactionReverse->setFromGroup($draft->getFromGroup());
  4677.                     }
  4678.                     if($draft->getToGroup()){
  4679.                         $newTransactionReverse->setToGroup($draft->getToGroup());
  4680.                     }
  4681.                     if($draft->getOffice()){
  4682.                         $newTransactionReverse->setOffice($draft->getOffice());
  4683.                     }
  4684.                     $newTransactionReverse->setTypeof($typeof_reverse);
  4685.                     $newTransactionReverse->setAmount($amount_reverse);
  4686.                     $newTransactionReverse->setComment($draft->getComment());
  4687.                     $newTransactionReverse->setNote($draft->getNote());
  4688.                     $newTransactionReverse->setDate(new \DateTime(date('Y-m-d H:i:s')));
  4689.                     $newTransactionReverse->setRecipient($draft->getToGroup());
  4690.                     $em->persist($newTransactionReverse);
  4691.                     $em->flush();
  4692.                 }
  4693.                 if($newTransaction) {
  4694.                     $balance false;
  4695.                     $from_group $draft->getFromGroup();
  4696.                     //если приход по Объекту, или начисление ЗП
  4697.                     if($is_income === true && $draft->getToGroup()){
  4698.                         $from_group $draft->getToGroup();
  4699.                     }
  4700.                     if ($draft->getTypeof() == 'expense') {
  4701.                         $balance $from_group->getBalance() - $draft->getAmount();
  4702.                     } elseif ($draft->getTypeof() == 'income') {
  4703.                         $balance $from_group->getBalance() + $draft->getAmount();
  4704.                     }
  4705.                     if ($balance != $from_group->getBalance()) {
  4706.                         $from_group->setBalance($balance);
  4707.                         $em->persist($from_group);
  4708.                         $em->flush();
  4709.                     }
  4710.                     if ($draft->getTypeof() == 'expense' && $draft->getToGroup() && $is_income === false) {
  4711.                         $to_group $draft->getToGroup();
  4712.                         $to_balance $to_group->getBalance() + $draft->getAmount();
  4713.                         if ($to_balance != $to_group->getBalance()) {
  4714.                             $to_group->setBalance($to_balance);
  4715.                             $em->persist($to_group);
  4716.                             $em->flush();
  4717.                         }
  4718.                     }
  4719.                     $resp true;
  4720.                     if($isSendMail){
  4721.                         //отправка письма по операциям
  4722.                         $recipient $this->getParameter('app.mailer.to.transaction');
  4723.                         $m_amount $newTransaction->getAmount();
  4724.                         $m_office = ($newTransaction->getOffice() != null ? ($newTransaction->getOffice()->getNumber() != '' && $newTransaction->getOffice()->getNumber() != null $newTransaction->getOffice()->getNumber() . '. ' '') . $newTransaction->getOffice()->getName() : '');
  4725.                         $is_cheque = ($newTransaction->getFile() != null && $newTransaction != '' && file_exists($basePath $fileDir $newTransaction->getFile()) ? true false);
  4726.                         $author '';
  4727.                         if($newTransaction->getSender() != null){
  4728.                             if($newTransaction->getSender()->getUsername() != null && $newTransaction->getSender()->getUsername() != ''){
  4729.                                 $author $newTransaction->getSender()->getUsername();
  4730.                             }
  4731.                         }
  4732.                         $title_mail = array(
  4733.                             '#amount#' => str_replace(',00'''number_format((abs($m_amount) / 100), 2','' ')),
  4734.                             '#source#' => $m_source,
  4735.                             '#type#' => $m_type,
  4736.                             '#comment#' => $newTransaction->getComment()
  4737.                         );
  4738.                         $body_mail = array(
  4739.                             '#office#' => $m_office,
  4740.                             '#type#' => $m_type,
  4741.                             '#amount#' => str_replace(',00'''number_format((abs($m_amount) / 100), 2','' ')),
  4742.                             '#date#' => ($newTransaction->getDate() != null $newTransaction->getDate()->format('d.m.Y') : ''),
  4743.                             '#source#' => $m_source,
  4744.                             '#comment#' => $newTransaction->getComment(),
  4745.                             //'#cheque#' => ($is_cheque ? 'есть' : 'нет'),
  4746.                             '#author#' => $author
  4747.                         );
  4748.                         $attach = [];
  4749.                         if($newTransaction->getFile() != null && $newTransaction->getFile() != ''){
  4750.                             if (strpos($newTransaction->getFile(), ';') !== false) {
  4751.                                 $filesList explode(';'$newTransaction->getFile());
  4752.                                 if(count($filesList) > 0){
  4753.                                     foreach ($filesList as $fileItem){
  4754.                                         $filepath $basePath $fileDir trim($fileItem);
  4755.                                         if(file_exists($filepath)){
  4756.                                             $attach[] = $basePath $fileDir trim($fileItem);
  4757.                                         }
  4758.                                     }
  4759.                                 }
  4760.                             } else {
  4761.                                 $filepath $basePath $fileDir $newTransaction->getFile();
  4762.                                 if(file_exists($filepath)){
  4763.                                     $attach[] = $basePath $fileDir $newTransaction->getFile();
  4764.                                 }
  4765.                             }
  4766.                         }
  4767.                         $this->sendEmail($this->mailer$typeMail$body_mail$title_mail'ru'$recipient$attach);
  4768.                     }
  4769.                 }
  4770.                 if($draft->getTypeTransaction() == 'add_salary'){
  4771.                     //- 5 000 ЗП Бас Иванов.  Сидоров
  4772.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4773.                     //$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') .  $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
  4774.                     $reply $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4775.                     // -333 (Нал Бот - ЗП Бот, тест коммент)
  4776.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4777.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4778.                     }
  4779.                     //+7 500 ЗП Бас Иванов. Петров
  4780.                     $amount "+" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4781.                     //$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
  4782.                     $reply $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4783.                     if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
  4784.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $to_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4785.                     }
  4786.                 } elseif($draft->getTypeTransaction() == 'add_salary_cash'){
  4787.                     //+5 000 ЗП Бас Иванов.  Сидоров
  4788.                     $amount "+" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4789.                     //$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
  4790.                     $reply $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4791.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4792.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4793.                     }
  4794.                     //-7 500 ЗП Бас Иванов. Петров
  4795.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4796.                     //$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
  4797.                     $reply $amount " (" $from_name " - " $to_name . ($office_name != '' ", " . ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4798.                     if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
  4799.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $to_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4800.                     }
  4801.                 } elseif($draft->getTypeTransaction() == 'payment_salary'){
  4802.                     //-7 500 ЗП Рук Иванов. Петров
  4803.                     $amount = (!$isReverseAmount "-" "") . str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4804.                     //$reply = $amount .  " (ЗП, " . $draft->getComment() . ". " . $from_name . ".)";
  4805.                     $reply $amount .  " (Начисл ЗП. " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4806.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4807.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4808.                     }
  4809.                 } elseif($draft->getTypeTransaction() == 'transfer'){
  4810.                     //- 1 000 Петрову и + 1 000 от Иванова
  4811.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4812.                     //$reply = $amount  . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name  . ".";
  4813.                     //if($type_group_from == 'salary' && $type_group_to == 'cash'){
  4814.                     //    $reply = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
  4815.                    // } else {
  4816.                         $reply $amount " (" $from_name " - " $to_name . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4817.                     //}
  4818.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4819.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4820.                     }
  4821.                     $amount "+" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4822.                     //$reply = $amount . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . " от " . $from_name . ".";
  4823.                     //if($type_group_from == 'salary' && $type_group_to == 'cash'){
  4824.                     //    $reply = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
  4825.                     //} else {
  4826.                         $reply $amount " (" $from_name " - " $to_name . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4827.                     //}
  4828.                     if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
  4829.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $to_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4830.                     }
  4831.                 } elseif($draft->getTypeTransaction() == 'income'){
  4832.                     //+ 10 000 Бас Иванов. Предоплата ++
  4833.                     $amount "+" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4834.                     //$reply = $amount . ($office_name != '' ? " (" . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : ""). ". " . $from_name . ".)";
  4835.                     $reply $amount " (" $from_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ($draft->getComment() != null && $draft->getComment() != '' ", " $draft->getComment() : "") . ")";
  4836.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4837.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4838.                     }
  4839.                 } elseif($draft->getTypeTransaction() == 'expense_office'){
  4840.                     //- 3 500 Бас Иванов. Гвозди
  4841.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4842.                     //$reply = $amount . ($office_name != '' ? " (" . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ". " . $draft->getComment() . ".)";
  4843.                     $reply $amount " (" $from_name ", " . ($office_name != '' ? ($office_number != '' && $office_number != null $office_number '. ' '') . $office_name "") . ", " $draft->getComment() . ")";
  4844.                     // +300 (Нал бот, 444. Бургерная, тестовый коммент)
  4845.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4846.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4847.                     }
  4848.                 } elseif($draft->getTypeTransaction() == 'expense_company'){
  4849.                     //- 1 000 Бизнес. Оплата связи
  4850.                     $amount "-" str_replace(',00'''number_format(($draft->getAmount() / 100), 2','' '));
  4851.                     //$reply = $amount . " (Бизнес. " . $draft->getComment() . ".)";
  4852.                     $reply $amount " (Бизнес. " $draft->getComment() . ".)";
  4853.                     if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
  4854.                         $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $from_chat_id'text' => $reply'parse_mode' => 'HTML']);
  4855.                     }
  4856.                 }
  4857.             }
  4858.         }
  4859.         return $resp;
  4860.     }
  4861.     private function office($token$chat_id$group_id$cq_data = array(), $curClient false$text null$message_id null) {
  4862.         $basePath $this->getParameter('kernel.project_dir');
  4863.         $is_group_chat $this->kernel->getContainer()->getParameter('app.chat.is_group');
  4864.         $action null;
  4865.         $p_group null;
  4866.         $keyboard = array();
  4867.         $em $this->getDoctrine()->getManager();
  4868.         if(count($cq_data) > 0){
  4869.             $action = (isset($cq_data['action']) ? $cq_data['action'] : null);
  4870.             $p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
  4871.         }
  4872.         $expected null;
  4873.         $p_id null;
  4874.         if($curClient){
  4875.             $data_expected $this->dataExpected($curClient->getExpected());
  4876.             if(isset($data_expected['value'])){
  4877.                 $expected $data_expected['value'];
  4878.             }
  4879.             if(isset($data_expected['group'])){
  4880.                 $p_group $data_expected['group'];
  4881.             }
  4882.             if(isset($data_expected['id'])){
  4883.                 $p_id $data_expected['id'];
  4884.             }
  4885.         }
  4886.         if(count($cq_data) > && $action != 'menu'){
  4887.             $groupObj false;
  4888.             if($group_id != null && $group_id != ''){
  4889.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  4890.             } elseif($p_group != null && $p_group != '') {
  4891.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  4892.             }
  4893.             if($is_group_chat === true && $groupObj){
  4894.                 $chat_id $groupObj->getChatId();
  4895.             }
  4896.             if($action == 'add'){
  4897.                 $reply 'Введите уникальный номер объекта';
  4898.                 $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  4899.                 $this->addExpected($clientObj, array("value" => "new_office""group" => $p_group));
  4900.                 $keyboard = array(
  4901.                     array(
  4902.                         array(
  4903.                             'text'=>'Назад',
  4904.                             'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  4905.                         )
  4906.                     )
  4907.                 );
  4908. //                $reply = 'Введите название нового объекта';
  4909. //                $clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  4910. //                $this->addExpected($clientObj, array("value" => "new_office", "group" => $p_group));
  4911. //                $keyboard = array(
  4912. //                    array(
  4913. //                        array(
  4914. //                            'text'=>'Назад',
  4915. //                            'callback_data'=> json_encode(array('action' => "menu", 'command' => "office", "group" => $p_group))
  4916. //                        )
  4917. //                    )
  4918. //                );
  4919.             } elseif($action == 'edit_list' || $action == 'rem_list') {
  4920.                 $offices $this->getDoctrine()
  4921.                     ->getRepository(Office::class)
  4922.                     ->createQueryBuilder('o')
  4923.                     ->select('o.id, o.name, o.number')
  4924.                     ->where('o.is_active = 1')
  4925.                     ->getQuery()
  4926.                     ->getArrayResult();
  4927.                 if(count($offices) > 0){
  4928.                     $reply 'Выберите из списка объект для ' . ($action == 'rem_list' 'удаления' 'редактирования') . ".";
  4929.                     $buttons = array();
  4930.                     foreach ($offices as $item_office){
  4931.                         $buttons[][] = array(
  4932.                             'text' => ($item_office['number'] != '' && $item_office['number'] != null $item_office['number'] . '. ' '') . $item_office['name'],
  4933.                             'callback_data'=> json_encode(array('action' => ($action == 'rem_list' "rem" "edit"), 'command' => "office"'id' => $item_office['id'], "group" => $p_group))
  4934.                         );
  4935.                     }
  4936.                     $keyboard $buttons;
  4937.                     $keyboard[] = array(
  4938.                         array(
  4939.                             'text'=> 'Назад',
  4940.                             'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  4941.                         )
  4942.                     );
  4943.                 } else {
  4944.                     $reply 'Для ' . ($action == 'rem_list' 'удаления' 'редактирования') . ' нет ни одного объекта.';
  4945.                     $keyboard = array(
  4946.                         array(
  4947.                             array(
  4948.                                 'text'=>'Создать объект',
  4949.                                 'callback_data'=> json_encode(array('action' => "add"'command' => "office""group" => $p_group))
  4950.                             )
  4951.                         )
  4952.                     );
  4953.                 }
  4954.             } elseif($action == 'edit' || $action == 'rem') {
  4955.                 $officeObj false;
  4956.                 if(isset($cq_data['id'])){
  4957.                     $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  4958.                 }
  4959.                 $is_rem false;
  4960.                 if($officeObj){
  4961.                     if($action == 'rem'){
  4962.                         $reply 'Вы действительно хотите удалить объект «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() . '»?';
  4963.                         $is_rem true;
  4964.                     } else {
  4965.                         $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  4966.                         $reply 'Выберите, что хотите отредатировать у объекта «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() . '»';
  4967.                         $keyboard = array(
  4968.                             array(
  4969.                                 array(
  4970.                                     'text'=>'Номер объекта',
  4971.                                     'callback_data'=> json_encode(array('action' => "edit_number"'command' => "office""id" => $officeObj->getId(), "group" => $p_group))
  4972.                                 ),
  4973.                                 array(
  4974.                                     'text'=>'Название объекта',
  4975.                                     'callback_data'=> json_encode(array('action' => "edit_name"'command' => "office""id" => $officeObj->getId(), "group" => $p_group))
  4976.                                 ),
  4977.                             )
  4978.                         );
  4979. //                        $clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  4980. //                        $reply = 'Введите новое название для объекта «'  . $officeObj->getName() . '»';
  4981. //                        $this->addExpected($clientObj, array("value" => "edit_office", "id" => $officeObj->getId(), "group" => $p_group));
  4982.                     }
  4983.                 } else {
  4984.                     $reply 'Не удалось найти данный объект. Попробуйте повторить попытку ' . ($action == 'rem' 'удаления' 'редактирования') . ' данного объекта позже.';
  4985.                 }
  4986.                 if($is_rem === true){
  4987.                     $keyboard = array(
  4988.                         array(
  4989.                             array(
  4990.                                 'text'=>'Да, удалить',
  4991.                                 'callback_data'=> json_encode(array('action' => "rem_ok"'command' => "office""id" => $officeObj->getId(), "group" => $p_group))
  4992.                             )
  4993.                         )
  4994.                     );
  4995.                 }
  4996.                 $keyboard[] = array(
  4997.                     array(
  4998.                         'text'=> ($is_rem === false 'Назад' 'Нет, назад'),
  4999.                         'callback_data'=> json_encode(array('action' => ($action == 'rem' "rem_list" "edit_list"), 'command' => "office""group" => $p_group))
  5000.                     )
  5001.                 );
  5002.                 $keyboard[] = array(
  5003.                     array(
  5004.                         'text'=> ($is_rem === false 'В основное меню объектов' 'Нет, в основное меню объектов'),
  5005.                         'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  5006.                     )
  5007.                 );
  5008.             } elseif($action == 'rem_ok') {
  5009.                 $officeObj false;
  5010.                 if(isset($cq_data['id'])){
  5011.                     $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  5012.                 }
  5013.                 if($officeObj){
  5014.                     $reply 'Объект «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() . '» успешно удален.';
  5015.                     $officeObj->setIsActive(0);
  5016.                     $em->persist($officeObj);
  5017.                     $em->flush();
  5018.                     $keyboard = array(
  5019.                         array(
  5020.                             array(
  5021.                                 'text'=> 'Назад',
  5022.                                 'callback_data'=> json_encode(array('action' => "rem_list"'command' => "office""group" => $p_group))
  5023.                             )
  5024.                         ),
  5025.                         array(
  5026.                             array(
  5027.                                 'text'=> 'В основное меню объектов',
  5028.                                 'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  5029.                             )
  5030.                         )
  5031.                     );
  5032.                 } else {
  5033.                     $reply 'Не удалось найти данный объект. Попробуйте повторить попытку удаления данного объекта позже.';
  5034.                 }
  5035.             } elseif($action == 'delete'){
  5036.                 $mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
  5037.                 if($mes_id != '' && $mes_id != null){
  5038.                     $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $chat_id'message_id' => $mes_id]);
  5039.                 }
  5040.                 if($cq_data['group'] != '' && $cq_data['group'] != null){
  5041.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
  5042.                     if($groupObj){
  5043.                         if(file_exists($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt')){
  5044.                             $mes_id file_get_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt');
  5045.                             if($mes_id != '' && $mes_id != null){
  5046.                                 $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $chat_id'message_id' => $mes_id]);
  5047.                                 $resp json_decode($deleteMessagetrue);
  5048.                                 if(isset($resp['result'])){
  5049.                                     if($resp['result'] == true){
  5050.                                         unlink($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt');
  5051.                                     }
  5052.                                 }
  5053.                             }
  5054.                         }
  5055.                     }
  5056.                 }
  5057.             } elseif($action == 'edit_number' || $action == 'edit_name'){
  5058.                 $officeObj false;
  5059.                 if(isset($cq_data['id'])){
  5060.                     $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
  5061.                 }
  5062.                 $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  5063.                 if($action == 'edit_name'){
  5064.                     $reply 'Введите новое название для объекта «' . ($officeObj->getNumber() != null && $officeObj->getName() != '' $officeObj->getName() . '. ' '') . $officeObj->getName() . '»';
  5065.                     $this->addExpected($clientObj, array("value" => "edit_office""id" => $officeObj->getId(), "group" => $p_group));
  5066.                 } else {
  5067.                     $reply 'Введите новый номер для объекта «'  . ($officeObj->getNumber() != null && $officeObj->getName() != '' $officeObj->getName() . '. ' '') . $officeObj->getName() . '»';
  5068.                     $this->addExpected($clientObj, array("value" => "edit_n_office""id" => $officeObj->getId(), "group" => $p_group));
  5069.                 }
  5070.                 $keyboard[] = array(
  5071.                     array(
  5072.                         'text'=> 'Назад',
  5073.                         'callback_data'=> json_encode(array('action' => 'edit'"id" => $officeObj->getId(), 'command' => "office""group" => $p_group))
  5074.                     )
  5075.                 );
  5076.                 $keyboard[] = array(
  5077.                     array(
  5078.                         'text'=> 'В основное меню объектов',
  5079.                         'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  5080.                     )
  5081.                 );
  5082.             }
  5083.         } elseif($expected != '' && $expected != null){
  5084.             $groupObj false;
  5085.             if($group_id != '' && $group_id != null){
  5086.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  5087.             } elseif($p_group != '' && $p_group != null){
  5088.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  5089.             }
  5090.             if($is_group_chat === true && $groupObj){
  5091.                 $chat_id $groupObj->getChatId();
  5092.             }
  5093.             if($expected == 'new_office'){
  5094.                 if($curClient && $text != '' && $text != null){
  5095.                     $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('number' => trim($text)));
  5096.                     if($officeObj){
  5097.                         if($officeObj->getIsActive() == '1'){
  5098.                             $reply 'Объект c номером «' $officeObj->getName() . '» уже существует. Введите другой номер объекта.';
  5099.                         } else {
  5100.                             $officeObj->setIsActive(1);
  5101.                             $em->persist($officeObj);
  5102.                             $em->flush();
  5103.                             $reply 'Объект «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() . '» снова активен.';
  5104.                         }
  5105.                     } else {
  5106.                         $newOffice = new Office();
  5107.                         $newOffice->setName('');
  5108.                         $newOffice->setNumber(trim($text));
  5109.                         $newOffice->setIsActive(0);
  5110.                         $em->persist($newOffice);
  5111.                         $em->flush();
  5112.                         $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  5113.                         $reply 'Введите название объекта';
  5114.                         $this->addExpected($clientObj, array("value" => "name_office""id" => $newOffice->getId(), "group" => $p_group));
  5115.                     }
  5116.                     //$this->resetExpected($curClient);
  5117.                 } elseif($expected == 'new_office') {
  5118.                     $reply 'Введите номер нового объекта.';
  5119.                 }
  5120. //                if($curClient && $text != '' && $text != null){
  5121. //                    $officeObj = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('name' => trim($text)));
  5122. //                    if($officeObj){
  5123. //                        if($officeObj->getIsActive() == '1'){
  5124. //                            $reply = 'Объект «' . $officeObj->getName() . '» уже существует. Введите другое название объекта.';
  5125. //                        } else {
  5126. //                            $officeObj->setIsActive(1);
  5127. //                            $em->persist($officeObj);
  5128. //                            $em->flush();
  5129. //
  5130. //                            $reply = 'Объект «' . $officeObj->getName() . '» снова активен.';
  5131. //                        }
  5132. //                    } else {
  5133. //                        $newOffice = new Office();
  5134. //                        $newOffice->setName(trim($text));
  5135. //                        $newOffice->setIsActive(1);
  5136. //                        $em->persist($newOffice);
  5137. //                        $em->flush();
  5138. //
  5139. //                        $reply = 'Добавлен новый объект «' . $newOffice->getName() . '».';
  5140. //                    }
  5141. //
  5142. //                    $this->resetExpected($curClient);
  5143. //                } elseif($expected == 'new_office') {
  5144. //                    $reply = 'Введите название нового объекта.';
  5145. //                }
  5146.                 $keyboard = array(
  5147.                     array(
  5148.                         array(
  5149.                             'text'=> 'Назад',
  5150.                             'callback_data'=> json_encode(array('action' => "edit_list"'command' => "office""group" => $p_group))
  5151.                         )
  5152.                     ),
  5153.                     array(
  5154.                         array(
  5155.                             'text'=> 'В основное меню объектов',
  5156.                             'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  5157.                         )
  5158.                     )
  5159.                 );
  5160.             } elseif($expected == 'edit_office') {
  5161.                 $officeObj false;
  5162.                 if(isset($data_expected['id'])){
  5163.                     $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $data_expected['id']));
  5164.                 }
  5165.                 if($officeObj && $curClient && $text != '' && $text != null){
  5166.                     $name_last = ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName();
  5167.                     $officeTmp $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('name' => trim($text)));
  5168.                     if(!$officeTmp){
  5169.                         $officeObj->setName(trim($text));
  5170.                         if($officeObj->getIsActive() != '1'){
  5171.                             $officeObj->setIsActive(1);
  5172.                         }
  5173.                         $em->persist($officeObj);
  5174.                         $em->flush();
  5175.                         $reply 'Объект «' $name_last '» успешно переименован в «' . ($officeObj->getNumber() != null && $officeObj->getNumber() != '' $officeObj->getNumber() . '. ' '') . trim($text) . '».';
  5176.                         $this->resetExpected($curClient);
  5177.                     } else {
  5178.                         $reply 'Невозможно объект «' $name_last '» переименовать в  «' . ($officeObj->getNumber() != null && $officeObj->getNumber() != '' $officeObj->getNumber() . '. ' '') . trim($text) . '», объект с таким названием уже существует. Введите другое название.';
  5179.                     }
  5180.                 }
  5181.                 $keyboard = array(
  5182.                     array(
  5183.                         array(
  5184.                             'text'=> 'Назад',
  5185.                             'callback_data'=> json_encode(array('action' => "edit_list"'command' => "office""group" => $p_group))
  5186.                         )
  5187.                     ),
  5188.                     array(
  5189.                         array(
  5190.                             'text'=> 'В основное меню объектов',
  5191.                             'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  5192.                         )
  5193.                     )
  5194.                 );
  5195.             } elseif($expected == 'edit_n_office') {
  5196.                 $officeObj false;
  5197.                 if(isset($data_expected['id'])){
  5198.                     $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $data_expected['id']));
  5199.                 }
  5200.                 if($officeObj && $curClient && $text != '' && $text != null){
  5201.                     $name_last = ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') .  $officeObj->getName();
  5202.                     $officeTmp $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('number' => trim($text), 'name' => $officeObj->getName()));
  5203.                     if(!$officeTmp){
  5204.                         $officeObj->setNumber(trim($text));
  5205.                         if($officeObj->getIsActive() != '1'){
  5206.                             $officeObj->setIsActive(1);
  5207.                         }
  5208.                         $em->persist($officeObj);
  5209.                         $em->flush();
  5210.                         $reply 'Объект «' $name_last '» успешно переименован в «' . ($officeObj->getNumber() != null && $officeObj->getNumber() != '' $officeObj->getNumber() . '. ' '') .  $officeObj->getName() . '».';
  5211.                         $this->resetExpected($curClient);
  5212.                     } else {
  5213.                         $reply 'Невозможно объект «' $name_last '» переименовать в  «' trim($text) . '. ' .  $officeObj->getName() . '», объект с таким названием уже существует. Введите другое название.';
  5214.                     }
  5215.                 }
  5216.                 $keyboard = array(
  5217.                     array(
  5218.                         array(
  5219.                             'text'=> 'Назад',
  5220.                             'callback_data'=> json_encode(array('action' => "edit_list"'command' => "office""group" => $p_group))
  5221.                         )
  5222.                     ),
  5223.                     array(
  5224.                         array(
  5225.                             'text'=> 'В основное меню объектов',
  5226.                             'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  5227.                         )
  5228.                     )
  5229.                 );
  5230.             } elseif($expected == 'name_office'){
  5231.                 if($curClient && $text != '' && $text != null){
  5232.                     if($p_id != '' && $p_id != null){
  5233.                         $officeObj $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $p_id));
  5234.                         if($officeObj){
  5235.                             $officeObj->setName(trim($text))
  5236.                                 ->setIsActive(1);
  5237.                             $em->persist($officeObj);
  5238.                             $em->flush();
  5239.                             $reply 'Добавлен новый объект «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null $officeObj->getNumber() . '. ' '') . $officeObj->getName() . '».';
  5240.                         }
  5241.                     }
  5242.                     $this->resetExpected($curClient);
  5243.                 } elseif($expected == 'new_office') {
  5244.                     $reply 'Введите название нового объекта.';
  5245.                 }
  5246.                 $keyboard = array(
  5247.                     array(
  5248.                         array(
  5249.                             'text'=> 'В основное меню объектов',
  5250.                             'callback_data'=> json_encode(array('action' => "menu"'command' => "office""group" => $p_group))
  5251.                         )
  5252.                     )
  5253.                 );
  5254.             }
  5255.         } else {
  5256.             $groupObj false;
  5257.             if($group_id != '' && $group_id != null){
  5258.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  5259.             } elseif($p_group != '' && $p_group != null){
  5260.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  5261.             }
  5262.             if($is_group_chat === true && $groupObj){
  5263.                 $chat_id $groupObj->getChatId();
  5264.             }
  5265.             $reply 'Выберите действие над объектом.';
  5266.             $offices $this->getDoctrine()
  5267.                 ->getRepository(Office::class)
  5268.                 ->createQueryBuilder('o')
  5269.                 ->select('o.id, o.name')
  5270.                 ->where('o.is_active = 1')
  5271.                 ->getQuery()
  5272.                 ->getArrayResult();
  5273.             $keyboard = array(
  5274.                 array(
  5275.                     array(
  5276.                         'text'=>'Создать объект',
  5277.                         'callback_data'=> json_encode(array('action' => "add"'command' => "office""group" => ($groupObj $groupObj->getId() : null)))
  5278.                     )
  5279.                 )
  5280.             );
  5281.             if(count($offices) > 0){
  5282.                 $keyboard[] = array(
  5283.                     array(
  5284.                         'text'=>'Редактировать объект',
  5285.                         'callback_data'=> json_encode(array('action' => "edit_list"'command' => "office""group" => ($groupObj $groupObj->getId() : null)))
  5286.                     ),
  5287.                 );
  5288.                 $keyboard[] = array(
  5289.                     array(
  5290.                         'text'=>'Удалить объект',
  5291.                         'callback_data'=> json_encode(array('action' => "rem_list"'command' => "office""group" => ($groupObj $groupObj->getId() : null)))
  5292.                     ),
  5293.                 );
  5294.                 $keyboard[] = array(
  5295.                     array(
  5296.                         'text'=>'Назад',
  5297.                         'callback_data'=> json_encode(array('action' => "delete"'command' => "office"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  5298.                     )
  5299.                 );
  5300.             }
  5301.         }
  5302.         $sendMessage false;
  5303.         if(count($keyboard) > 0){
  5304.             $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5305.             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5306.             $resp json_decode($sendMessagetrue);
  5307.             if(isset($resp['result']['message_id']) && $groupObj){
  5308.                 file_put_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt'$resp['result']['message_id']);
  5309.             }
  5310.         } else {
  5311.             $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5312.         }
  5313.         if($is_group_chat === true){
  5314.             $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
  5315.             $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'office'));
  5316.             $this->addLogMessageBot($bot$command$sendMessage);
  5317.         }
  5318.     }
  5319.     private function users($token$chat_id$group_id$cq_data = array(), $curClient false$text null$message_id null) {
  5320.         $basePath $this->getParameter('kernel.project_dir');
  5321.         $is_group_chat $this->kernel->getContainer()->getParameter('app.chat.is_group');
  5322.         $action null;
  5323.         $p_group null;
  5324.         $keyboard = array();
  5325.         $em $this->getDoctrine()->getManager();
  5326.         $expected null;
  5327.         if(count($cq_data) > 0){
  5328.             $action = (isset($cq_data['action']) ? $cq_data['action'] : null);
  5329.             $p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
  5330.         }
  5331.         if($curClient){
  5332.             $data_expected $this->dataExpected($curClient->getExpected());
  5333.             if(isset($data_expected['value'])){
  5334.                 $expected $data_expected['value'];
  5335.             }
  5336.             if(isset($data_expected['group'])){
  5337.                 $p_group $data_expected['group'];
  5338.             }
  5339.         }
  5340.         $sendMessage false;
  5341.         if(count($cq_data) > && $action != 'list'){
  5342.             $groupObj false;
  5343.             if($group_id != '' && $group_id != null){
  5344.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  5345.             } elseif($p_group != '' && $p_group != null && $action == 'list'){
  5346.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  5347.             }
  5348.             if($is_group_chat === true && $groupObj){
  5349.                 $chat_id $groupObj->getChatId();
  5350.             }
  5351.             $em $this->getDoctrine()->getManager();
  5352.             $reply 'Не удалось получить информацию о пользователе.';
  5353.             if($action == 'show'){
  5354.                 $clientObj false;
  5355.                 if(isset($cq_data['id'])){
  5356.                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  5357.                         $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  5358.                     }
  5359.                 }
  5360.                 if($clientObj){
  5361.                     $name_client $clientObj->nameClient();
  5362.                     $reply 'Выберите, что хотите изменить у пользователя ' $name_client ".";
  5363.                     $keyboard = array(
  5364.                         array(
  5365.                             array(
  5366.                                 'text'=>'Изменить роль',
  5367.                                 'callback_data'=> json_encode(array('action' => "role"'command' => "users"'id' => $clientObj->getId(), "group" => $p_group))
  5368.                             )
  5369.                         ),
  5370. //                        array(
  5371. //                            array(
  5372. //                                'text'=>'Изменить email',
  5373. //                                'callback_data'=> json_encode(array('action' => "email", 'id' => $clientObj->getId(), 'command' => "users", "group" => $p_group))
  5374. //                            ),
  5375. //                        ),
  5376.                         array(
  5377.                             array(
  5378.                                 'text'=>'К списку всех пользователей',
  5379.                                 'callback_data'=> json_encode(array('action' => "list"'command' => "users""group" => $p_group))
  5380.                             ),
  5381.                         )
  5382.                     );
  5383.                 } else {
  5384.                     $reply 'Невозможно продолжить действие, пользователь не найден.';
  5385.                 }
  5386.                 if(count($keyboard) > 0){
  5387.                     $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5388.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5389.                 } else {
  5390.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5391.                 }
  5392.             } elseif($action == 'role'){
  5393.                 $clientObj false;
  5394.                 if(isset($cq_data['id'])){
  5395.                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  5396.                         $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  5397.                     }
  5398.                 }
  5399.                 if($clientObj){
  5400.                     $name_client $clientObj->nameClient();
  5401.                     $name_role null;
  5402.                     if($clientObj->getRole()){
  5403.                         $name_role $clientObj->getRole()->getName();
  5404.                     }
  5405.                     $buttons = array();
  5406.                     $roles $this->getDoctrine()
  5407.                         ->getRepository(Role::class)
  5408.                         ->createQueryBuilder('r')
  5409.                         ->select('r.id, r.name')
  5410.                         ->getQuery()
  5411.                         ->getArrayResult();
  5412.                     if(count($roles) > 0){
  5413.                         foreach ($roles as $item_role){
  5414.                             $buttons[][] = array(
  5415.                                 'text' => $item_role['name'],
  5416.                                 '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()))
  5417.                             );
  5418.                         }
  5419.                         $buttons[][] = array(
  5420.                             'text'=>'Назад',
  5421.                             'callback_data'=> json_encode(array('action' => "show"'command' => "users"'id' => $clientObj->getId(), "group" => ($groupObj $groupObj->getId() : null)))
  5422.                         );
  5423.                     }
  5424.                     if($name_client != '' && $name_client != null){
  5425.                         $reply 'У пользователя ' $name_client ' пока нет роли.';
  5426.                         if($name_role != '' && $name_role != null){
  5427.                             $reply 'У пользователя ' $name_client ' текущая роль «'  $name_role '». Чтобы поменять роль выберите необходимую из списка.';
  5428.                         }
  5429.                     }
  5430.                     if(count($buttons) > 0){
  5431.                         if($name_role != '' && $name_role != null){
  5432.                             $reply $reply ' Чтобы поменять роль выберите необходимую из списка.';
  5433.                         } else {
  5434.                             $reply $reply ' Выберите необходимую роль из списка.';
  5435.                         }
  5436.                     } else {
  5437.                         $reply $reply ' Ролей для выбора пока нет, попробуйте выбрать позже.';
  5438.                     }
  5439.                     $keyboard $buttons;
  5440.                 }
  5441.                 if(count($keyboard) > 0){
  5442.                     $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5443.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5444.                 } else {
  5445.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5446.                 }
  5447.             } elseif($action == 'add'){
  5448.                 $reply 'При попытке поменять роль у пользователя произошла ошибка. Попробуйте повторить попытку позже.';
  5449.                 $keyboard = array();
  5450.                 if(isset($cq_data['client']) && isset($cq_data['id'])){
  5451.                     if($cq_data['client'] != '' && $cq_data['client'] != null && $cq_data['id'] != '' && $cq_data['client'] != null){
  5452.                         $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['client'], 'typeof' => 'private'));
  5453.                         $roleObj $this->getDoctrine()->getRepository(Role::class)->findOneBy(array('id' => $cq_data['id']));
  5454.                         if($clientObj && $roleObj){
  5455.                             $clientObj->setRole($roleObj);
  5456.                             $em->persist($clientObj);
  5457.                             $em->flush();
  5458.                             $name_role $roleObj->getName();
  5459.                             $name_client $clientObj->nameClient();
  5460.                             $reply 'У пользователя ' $name_client ' выбрана роль «'  $name_role '».';
  5461.                             $keyboard = array(
  5462.                                 array(
  5463.                                     array(
  5464.                                         'text'=>'Выбрать новую роль',
  5465.                                         'callback_data'=> json_encode(array('action' => "show"'command' => "users"'id' => $clientObj->getId(), "group" => $p_group))
  5466.                                     )
  5467.                                 ),
  5468.                                 array(
  5469.                                     array(
  5470.                                         'text'=>'К списку всех пользователей',
  5471.                                         'callback_data'=> json_encode(array('action' => "list"'command' => "users""group" => $p_group))
  5472.                                     ),
  5473.                                 )
  5474.                             );
  5475.                         }
  5476.                     }
  5477.                 }
  5478.                 if(count($keyboard) > 0){
  5479.                     $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5480.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5481.                 } else {
  5482.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5483.                 }
  5484.             } elseif($action == 'email'){
  5485.                 $clientObj false;
  5486.                 if(isset($cq_data['id'])){
  5487.                     if($cq_data['id'] != '' && $cq_data['id'] != null){
  5488.                         $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  5489.                     }
  5490.                 }
  5491.                 $keyboard = array();
  5492.                 if($clientObj){
  5493.                     $name_client $clientObj->nameClient();
  5494.                     $email $clientObj->getEmail();
  5495.                     if($email != '' && $email != null){
  5496.                         $reply 'У пользователя ' $name_client ' указан email «'  $email '», можете поменять его.';
  5497.                         $keyboard = array(
  5498.                             array(
  5499.                                 array(
  5500.                                     'text'=>'Изменить email',
  5501.                                     'callback_data'=> json_encode(array('action' => "edit_email"'id' => $clientObj->getId(), 'command' => "users""group" => $p_group))
  5502.                                 ),
  5503.                             ),
  5504.                             array(
  5505.                                 array(
  5506.                                     'text'=>'К списку всех пользователей',
  5507.                                     'callback_data'=> json_encode(array('action' => "list"'command' => "users""group" => $p_group))
  5508.                                 ),
  5509.                             )
  5510.                         );
  5511.                     } else {
  5512.                         $reply 'У пользователя ' $name_client ' не указан email, можете добавить его.';
  5513.                         $keyboard = array(
  5514.                             array(
  5515.                                 array(
  5516.                                     'text'=>'Добавить email',
  5517.                                     'callback_data'=> json_encode(array('action' => "add_email"'id' => $clientObj->getId(), 'command' => "users""group" => $p_group))
  5518.                                 ),
  5519.                             ),
  5520.                             array(
  5521.                                 array(
  5522.                                     'text'=>'К списку всех пользователей',
  5523.                                     'callback_data'=> json_encode(array('action' => "list"'command' => "users""group" => $p_group))
  5524.                                 ),
  5525.                             )
  5526.                         );
  5527.                     }
  5528.                 } else {
  5529.                     $reply 'Невозможно продолжить действие, пользователь не найден.';
  5530.                 }
  5531.                 if(count($keyboard) > 0){
  5532.                     $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5533.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5534.                 } else {
  5535.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5536.                 }
  5537.             } elseif($action == 'add_email' || $action == 'edit_email'){
  5538.                 $clientObj false;
  5539.                 if($is_group_chat === true){
  5540.                     if(isset($cq_data['group'])){
  5541.                         if($cq_data['group'] != '' && $cq_data['group'] != null){
  5542.                             $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
  5543.                         }
  5544.                     } elseif(isset($cq_data['id'])){
  5545.                         if($cq_data['id'] != '' && $cq_data['id'] != null){
  5546.                             $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  5547.                         }
  5548.                     }
  5549.                 } else {
  5550.                     if(isset($cq_data['id'])){
  5551.                         if($cq_data['id'] != '' && $cq_data['id'] != null){
  5552.                             $clientObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
  5553.                         }
  5554.                     }
  5555.                 }
  5556.                 $keyboard = array();
  5557.                 if($clientObj){
  5558.                     $name_client $clientObj->nameClient();
  5559.                     $reply 'Введите email, который хотите добавить пользователю ' $name_client ".";
  5560.                     $this->addExpected($clientObj, array("value" => "email""group" => $p_group));
  5561.                 } else {
  5562.                     $reply 'Невозможно продолжить действие, пользователь не найден.';
  5563.                 }
  5564.                 if(count($keyboard) > 0){
  5565.                     $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5566.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5567.                 } else {
  5568.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5569.                 }
  5570.             } elseif($action == 'delete'){
  5571.                 $mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
  5572.                 if($mes_id != '' && $mes_id != null){
  5573.                     $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $chat_id'message_id' => $mes_id]);
  5574.                 }
  5575.                 if($cq_data['group'] != '' && $cq_data['group'] != null){
  5576.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
  5577.                     if($groupObj){
  5578.                         if(file_exists($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt')){
  5579.                             $mes_id file_get_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt');
  5580.                             if($mes_id != '' && $mes_id != null){
  5581.                                 $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $chat_id'message_id' => $mes_id]);
  5582.                                 $resp json_decode($deleteMessagetrue);
  5583.                                 if(isset($resp['result'])){
  5584.                                     if($resp['result'] == true){
  5585.                                         unlink($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt');
  5586.                                     }
  5587.                                 }
  5588.                             }
  5589.                         }
  5590.                     }
  5591.                 }
  5592.             }
  5593.         } elseif($expected != '' && $expected != null){
  5594.             $groupObj false;
  5595.             if($group_id != '' && $group_id != null){
  5596.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  5597.             } elseif($p_group != '' && $p_group != null && $action == 'list'){
  5598.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  5599.             }
  5600.             if($is_group_chat === true && $groupObj){
  5601.                 $chat_id $groupObj->getChatId();
  5602.             }
  5603.             if($expected == 'email'){
  5604.                 if($curClient && $text != '' && $text != null){
  5605.                     $name_client $curClient->nameClient();
  5606.                     $reply 'Email ' $text ' успешно добавлен пользователю ' $name_client ".";
  5607.                     $curClient->setEmail(trim($text));
  5608.                     $em->persist($curClient);
  5609.                     $em->flush();
  5610.                     $this->resetExpected($curClient);
  5611.                     $keyboard = array(
  5612.                         array(
  5613.                             array(
  5614.                                 'text'=>'К списку всех пользователей',
  5615.                                 'callback_data'=> json_encode(array('action' => "list"'command' => "users""group" => $p_group))
  5616.                             ),
  5617.                         )
  5618.                     );
  5619.                 } elseif(!$curClient) {
  5620.                     $reply 'Невозможно продолжить действие, пользователь не найден.';
  5621.                 }
  5622.             }
  5623.             if(count($keyboard) > 0){
  5624.                 $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5625.                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5626.             } else {
  5627.                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5628.             }
  5629.         } else {
  5630.             $reply 'Пока нет ни одного пользователя для редактирования у него роли.';
  5631.             $clients $this->getDoctrine()
  5632.                 ->getRepository(Client::class)
  5633.                 ->createQueryBuilder('c')
  5634.                 ->select('c.id, c.first_name, c.last_name, c.username, r.name AS name_role')
  5635.                 ->where('c.typeof = :typeof')
  5636.                 ->leftJoin(Role::class, 'r''WITH''c.role = r.id')
  5637.                 ->setParameter('typeof''private')
  5638.                 ->getQuery()
  5639.                 ->getArrayResult();
  5640.             $groupObj false;
  5641.             if($group_id != '' && $group_id != null){
  5642.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  5643.             } elseif($p_group != '' && $p_group != null && $action == 'list'){
  5644.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  5645.             }
  5646.             if($is_group_chat === true && $groupObj){
  5647.                 $chat_id $groupObj->getChatId();
  5648.             }
  5649.             $buttons = array();
  5650.             if(count($clients) > 0){
  5651.                 $reply 'Выберите пользователя, у которого хотите отредактировать информацию.';
  5652.                 foreach ($clients as $item_client){
  5653.                     $name_client $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
  5654.                     if($name_client != '' && $name_client != null){
  5655.                         $buttons[][] = array(
  5656.                             'text' => $name_client . ($item_client['name_role'] != '' && $item_client['name_role'] != null ' (' $item_client['name_role'] . ')' ''),
  5657.                             'callback_data'=> json_encode(array('action' => "show"'command' => "users"'id' => $item_client['id'], "group" => ($groupObj $groupObj->getId() : null)))
  5658.                         );
  5659.                     }
  5660.                 }
  5661.                 $buttons[][] = array(
  5662.                     'text'=>'Назад',
  5663.                     'callback_data'=> json_encode(array('action' => "delete"'command' => "setting"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  5664.                 );
  5665.             }
  5666.             $keyboard $buttons;
  5667.             if(count($keyboard) > 0){
  5668.                 $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5669.                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5670.                 $resp json_decode($sendMessagetrue);
  5671.                 if(isset($resp['result']['message_id']) && $groupObj){
  5672.                     file_put_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt'$resp['result']['message_id']);
  5673.                 }
  5674.             } else {
  5675.                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5676.             }
  5677.         }
  5678.         if($is_group_chat === true){
  5679.             $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
  5680.             $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'users'));
  5681.             $this->addLogMessageBot($bot$command$sendMessage);
  5682.         }
  5683.     }
  5684.     private function nameClient($first_name$last_name$username){
  5685.         $name_client = ($first_name != '' && $first_name != null $first_name '');
  5686.         if($name_client != '' && $last_name != '' && $last_name != null){
  5687.             $name_client $name_client ' ' $last_name;
  5688.         }
  5689.         if($name_client == ''){
  5690.             $name_client =  $username;
  5691.         }
  5692.         return $name_client;
  5693.     }
  5694.     private function setting($token$chat_id$group_id$cq_data = array(), $message_id null) {
  5695.         $basePath $this->getParameter('kernel.project_dir');
  5696.         $is_group_chat $this->getParameter('app.chat.is_group');
  5697.         $sendMessage false;
  5698.         $action null;
  5699.         $p_group null;
  5700.         if(count($cq_data) > 0){
  5701.             $action = (isset($cq_data['action']) ? $cq_data['action'] : null);
  5702.             $p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
  5703.             if($action == '' || $action == "null" || $action == null){
  5704.                 $action null;
  5705.             }
  5706.         }
  5707.         if(count($cq_data) > && $action != null){
  5708.             $action = (isset($cq_data['action']) ? $cq_data['action'] : null);
  5709.             $p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
  5710.             $em $this->getDoctrine()->getManager();
  5711.             if($is_group_chat === true && $p_group != '' && $p_group != null){
  5712.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  5713.                 if($groupObj){
  5714.                     $chat_id $groupObj->getChatId();
  5715.                 }
  5716.             }
  5717.             if($action == 'list'){
  5718.                 $reply 'Типов группы для выбора пока нет.';
  5719.                 $type_groups $this->getDoctrine()
  5720.                     ->getRepository(TypeGroup::class)
  5721.                     ->createQueryBuilder('tg')
  5722.                     ->select('tg.id, tg.title')
  5723.                     ->getQuery()
  5724.                     ->getArrayResult();
  5725.                 $buttons = array();
  5726.                 if(count($type_groups) > 0){
  5727.                     $reply 'Выберите тип группы из списка.';
  5728.                     foreach ($type_groups as $type_group){
  5729.                         $buttons[][] = array(
  5730.                             'text' => $type_group['title'],
  5731.                             'callback_data'=> json_encode(array('action' => "add"'command' => "setting"'id' => $type_group['id'], "group" => $p_group))
  5732.                         );
  5733.                     }
  5734.                     $buttons[][] = array(
  5735.                         'text'=>'Назад',
  5736.                         'callback_data'=> json_encode(array('action' => "null"'command' => "setting""group" => $p_group))
  5737.                     );
  5738.                 }
  5739.                 $keyboard $buttons;
  5740.                 if(count($keyboard) > 0){
  5741.                     $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5742.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5743.                 } else {
  5744.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5745.                 }
  5746.             } elseif($action == 'add'){
  5747.                 $reply 'Не удалось добавить тип группы к групповому чату. Попробуйте повторить попытку позже.';
  5748.                 $keyboard = array();
  5749.                 $groupObj false;
  5750.                 if(isset($cq_data['id']) && isset($cq_data['group'])){
  5751.                     if($cq_data['id'] != '' && $cq_data['id'] != null && $cq_data['group'] != '' && $cq_data['group'] != null){
  5752.                         $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
  5753.                         $type_group $this->getDoctrine()->getRepository(TypeGroup::class)->findOneBy(array('id' => $cq_data['id']));
  5754.                         if($groupObj && $type_group){
  5755.                             $groupObj->setTypeGroup($type_group);
  5756.                             $em->persist($groupObj);
  5757.                             $em->flush();
  5758.                             $reply 'Тип группы «'  $type_group->getTitle() . '» успешно добавлен к групповому чату.';
  5759.                             $keyboard = array(
  5760.                                 array(
  5761.                                     array(
  5762.                                         'text'=>'Новый тип группы',
  5763.                                         'callback_data'=> json_encode(array('action' => "list"'command' => "setting""group" => ($groupObj $groupObj->getId() : null)))
  5764.                                     ),
  5765.                                     array(
  5766.                                         'text'=>'Удалить тип группы',
  5767.                                         'callback_data'=> json_encode(array('action' => "rem"'command' => "setting""group" => ($groupObj $groupObj->getId() : null)))
  5768.                                     ),
  5769.                                     array(
  5770.                                         'text'=>'Назад',
  5771.                                         'callback_data'=> json_encode(array('action' => "delete"'command' => "setting"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  5772.                                     )
  5773.                                 )
  5774.                             );
  5775.                         }
  5776.                     }
  5777.                 }
  5778.                 if(count($keyboard) > 0){
  5779.                     $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5780.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5781.                     $resp json_decode($sendMessagetrue);
  5782.                     if(isset($resp['result']['message_id']) && $groupObj){
  5783.                         file_put_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt'$resp['result']['message_id']);
  5784.                     }
  5785.                 } else {
  5786.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5787.                 }
  5788.             } elseif($action == 'rem'){
  5789.                 $reply 'Не удалось удалить тип группы у данного группового чата.';
  5790.                 if($cq_data['group'] != '' && $cq_data['group'] != null){
  5791.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
  5792.                     $groupObj->setTypeGroup(null);
  5793.                     $em->persist($groupObj);
  5794.                     $em->flush();
  5795.                     $reply 'Тип группы у данного группового чата успешно удален.';
  5796.                     $keyboard = array(
  5797.                         array(
  5798.                             array(
  5799.                                 'text'=>'Добавить тип группы',
  5800.                                 'callback_data'=> json_encode(array('action' => "list"'command' => "setting""group" => ($groupObj $groupObj->getId() : null)))
  5801.                             )
  5802.                         )
  5803.                     );
  5804.                 }
  5805.                 if(count($keyboard) > 0){
  5806.                     $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5807.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5808.                 } else {
  5809.                     $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5810.                 }
  5811.             } elseif($action == 'delete') {
  5812.                 $mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
  5813.                 if($mes_id != '' && $mes_id != null){
  5814.                     $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $chat_id'message_id' => $mes_id]);
  5815.                 }
  5816.                 if($cq_data['group'] != '' && $cq_data['group'] != null){
  5817.                     $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
  5818.                     if($groupObj){
  5819.                         if(file_exists($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt')){
  5820.                             $mes_id file_get_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt');
  5821.                             if($mes_id != '' && $mes_id != null){
  5822.                                 $deleteMessage ProjectUtilsController::requestToBot($token'deleteMessage', ['chat_id' => $chat_id'message_id' => $mes_id]);
  5823.                                 $resp json_decode($deleteMessagetrue);
  5824.                                 if(isset($resp['result'])){
  5825.                                     if($resp['result'] == true){
  5826.                                         unlink($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt');
  5827.                                     }
  5828.                                 }
  5829.                             }
  5830.                         }
  5831.                     }
  5832.                 }
  5833.             }
  5834.         } else {
  5835.             $groupObj false;
  5836.             if($group_id != '' && $group_id != null){
  5837.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
  5838.             }
  5839.             if(!$groupObj && $p_group != null && $p_group != ''){
  5840.                 $groupObj $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
  5841.             }
  5842.             if($is_group_chat === true && $groupObj){
  5843.                 $chat_id $groupObj->getChatId();
  5844.             }
  5845.             $reply 'У данной группы пока не выбран тип группы. Можете добавить тип группы.';
  5846.             $name_type_group null;
  5847.             $no_keyboard false;
  5848.             if($groupObj){
  5849.                 if($groupObj->getTypeGroup()){
  5850.                     $reply 'У данной группы выбран тип группы «' $groupObj->getTypeGroup()->getTitle() . '». Можете поменять на другой или удалить.';
  5851.                     $name_type_group $groupObj->getTypeGroup()->getTitle();
  5852.                 }
  5853.             } else {
  5854.                 $no_keyboard true;
  5855.                 $reply 'Отредактировать тип группы можно только из группы. Пожалуйста повторите данную команду в нужно группе.';
  5856.             }
  5857.             $reply_markup = array();
  5858.             if($no_keyboard === false){
  5859.                 $keyboard = array(
  5860.                     array(
  5861.                         array(
  5862.                             'text'=> ($name_type_group != null 'Новый тип группы' 'Добавить тип группы'),
  5863.                             'callback_data'=> json_encode(array('action' => "list"'command' => "setting""group" => ($groupObj $groupObj->getId() : null)))
  5864.                         ),
  5865.                         array(
  5866.                             'text'=>'Удалить тип группы',
  5867.                             'callback_data'=> json_encode(array('action' => "rem"'command' => "setting""group" => ($groupObj $groupObj->getId() : null)))
  5868.                         ),
  5869.                         array(
  5870.                             'text'=>'Назад',
  5871.                             'callback_data'=> json_encode(array('action' => "delete"'command' => "setting"'mes_id' => $message_id"group" => ($groupObj $groupObj->getId() : null)))
  5872.                         )
  5873.                     )
  5874.                 );
  5875.                 $reply_markup ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
  5876.                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML''reply_markup' => $reply_markup]);
  5877.                 $resp json_decode($sendMessagetrue);
  5878.                 if(isset($resp['result']['message_id']) && $groupObj){
  5879.                     file_put_contents($basePath '/var/log/' $chat_id '-' $groupObj->getId() . '.txt'$resp['result']['message_id']);
  5880.                 }
  5881.             } else {
  5882.                 $sendMessage ProjectUtilsController::requestToBot($token'sendMessage', ['chat_id' => $chat_id'text' => $reply'parse_mode' => 'HTML']);
  5883.             }
  5884.         }
  5885.         if($is_group_chat === true){
  5886.             $bot $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
  5887.             $command $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'setting'));
  5888.             $this->addLogMessageBot($bot$command$sendMessage);
  5889.         }
  5890.     }
  5891.     private function updateClient($chat_id$typeof$data){
  5892.         $em $this->getDoctrine()->getManager();
  5893.         $client false;
  5894.         if(count($data) > && $chat_id != null && $chat_id != ''){
  5895.             $client $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
  5896.             if(!$client){
  5897.                 $newClient = new Client();
  5898.                 $newClient->setChatId($chat_id);
  5899.                 if($typeof == 'private'){
  5900.                     $newClient->setFirstName((isset($data['first_name']) ? $data['first_name'] : null));
  5901.                     $newClient->setLastName((isset($data['last_name']) ? $data['last_name'] : null));
  5902.                     $newClient->setUsername((isset($data['username']) ? $data['username'] : null));
  5903.                     $role $this->getDoctrine()->getRepository(Role::class)->findOneBy(array('typeof' => 'employee'));
  5904.                     if($role){
  5905.                         $newClient->setRole($role);
  5906.                     }
  5907.                     $newClient->setBalance(0);
  5908.                 } else {
  5909.                     $newClient->setFirstName((isset($data['title']) ? $data['title'] : null));
  5910.                     $newClient->setBalance(0);
  5911.                 }
  5912.                 $newClient->setTypeof($typeof);
  5913.                 $newClient->setIsActive(1);
  5914.                 $em->persist($newClient);
  5915.                 $em->flush();
  5916.                 $client $newClient;
  5917.             } else {
  5918.                 if($typeof == 'private'){
  5919.                     if(isset($data['first_name'])){
  5920.                         if($data['first_name'] != $client->getFirstName()){
  5921.                             $client->setFirstName($data['first_name']);
  5922.                         }
  5923.                     }
  5924.                     if(isset($data['last_name'])){
  5925.                         if($data['last_name'] != $client->getLastName()){
  5926.                             $client->setLastName($data['last_name']);
  5927.                         }
  5928.                     }
  5929.                     if(isset($data['username'])){
  5930.                         if($data['username'] != $client->getUsername()){
  5931.                             $client->setUsername($data['username']);
  5932.                         }
  5933.                     }
  5934.                     if(!$client->getRole()){
  5935.                         $role $this->getDoctrine()->getRepository(Role::class)->findOneBy(array('typeof' => 'employee'));
  5936.                         if($role){
  5937.                             $client->setRole($role);
  5938.                         }
  5939.                     }
  5940.                 } else {
  5941.                     if(isset($data['title'])){
  5942.                         if($data['title'] != $client->getFirstName()){
  5943.                             $client->setFirstName($data['title']);
  5944.                         }
  5945.                     }
  5946.                 }
  5947.                 if($typeof != $client->getTypeof()){
  5948.                     $client->setTypeof($typeof);
  5949.                 }
  5950.                 $em->persist($client);
  5951.                 $em->flush();
  5952.             }
  5953.         }
  5954.         return $client;
  5955.     }
  5956.     private function getCurClient($chat_id$typeof$from_data$chat_data){
  5957.         $em $this->getDoctrine()->getManager();
  5958.         $client false;
  5959.         if(count($from_data) > && $chat_id != null && $chat_id != ''){
  5960.             $tmp_typeof $typeof;
  5961.             if($typeof == 'supergroup' || $typeof == 'group'){
  5962.                 $tmp_typeof 'private';
  5963.             }
  5964.             $client $this->updateClient($chat_id$tmp_typeof$from_data);
  5965.         }
  5966.         if(count($chat_data) > && $chat_id != null && $chat_id != '' && ($typeof == 'supergroup' || $typeof == 'group')){
  5967.             $tmp_chat_id $chat_id;
  5968.             if(isset($chat_data['id'])){
  5969.                 $tmp_chat_id $chat_data['id'];
  5970.             }
  5971.             $client $this->updateClient($tmp_chat_id$typeof$chat_data);
  5972.         }
  5973.         return $client;
  5974.     }
  5975.     private function genReport($report false){
  5976.         $basePath $this->getParameter('kernel.project_dir');
  5977.         $date_with null;
  5978.         $date_by null;
  5979.         $client_group_id null;
  5980.         if($report){
  5981.             $date_with_d $report->getDateWith();
  5982.             if($date_with_d != '' && $date_with_d != null){
  5983.                 $date_with_dates = (array) $date_with_d;
  5984.                 if(isset($date_with_dates['date'])){
  5985.                     $date_with $date_with_dates['date'];
  5986.                 }
  5987.             }
  5988.             $date_by_d $report->getDateBy();
  5989.             if($date_by_d != '' && $date_by_d != null){
  5990.                 $date_by_dates = (array) $date_by_d;
  5991.                 if(isset($date_by_dates['date'])){
  5992.                     $date_by $date_by_dates['date'];
  5993.                 }
  5994.             }
  5995.             if($report->getClientGroup()){
  5996.                 $client_group_id $report->getClientGroup()->getId();
  5997.             }
  5998.         }
  5999.         $transactions_q $this->getDoctrine()
  6000.             ->getRepository(Transaction::class)
  6001.             ->createQueryBuilder('tr')
  6002.             ->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')
  6003.             ->leftJoin(Client::class, 'c1''WITH''tr.from_group = c1.id')
  6004.             ->leftJoin(Client::class, 'c2''WITH''tr.to_group = c2.id')
  6005.             ->leftJoin(Client::class, 'c3''WITH''tr.sender = c3.id')
  6006.             ->leftJoin(Office::class, 'o''WITH''tr.office = o.id')
  6007.             //->where('tr.amount != 0')
  6008.         ;
  6009.         if($client_group_id != null && $client_group_id != ''){
  6010.             $transactions_q->andWhere('tr.recipient = ' $client_group_id);
  6011.             if($date_with != '' && $date_with != null){
  6012.                 $transactions_q->andWhere('tr.date >= :date_with')
  6013.                     ->setParameter('date_with'$date_with);
  6014.             }
  6015.             /*
  6016.             $transactions_q->andWhere('tr.from_group = ' . $client_group_id);
  6017.             if($date_with != '' && $date_with != null){
  6018.                 $transactions_q->andWhere('tr.date >= :date_with')
  6019.                     ->setParameter('date_with', $date_with);
  6020.             }
  6021.             if($date_by != '' && $date_by != null){
  6022.                 $transactions_q->andWhere('tr.date <= :date_by')
  6023.                     ->setParameter('date_by', $date_by);
  6024.             }
  6025.             $transactions_q->orWhere('tr.to_group = ' . $client_group_id);
  6026.             if($date_with != '' && $date_with != null){
  6027.                 $transactions_q->andWhere('tr.date >= :date_with')
  6028.                     ->setParameter('date_with', $date_with);
  6029.             }
  6030.             if($date_by != '' && $date_by != null){
  6031.                 $transactions_q->andWhere('tr.date <= :date_by')
  6032.                     ->setParameter('date_by', $date_by);
  6033.             }
  6034.             */
  6035.         } else {
  6036.             if($date_with != '' && $date_with != null){
  6037.                 $transactions_q->andWhere('tr.date >= :date_with')
  6038.                     ->setParameter('date_with'$date_with);
  6039.             }
  6040.             if($date_by != '' && $date_by != null){
  6041.                 $transactions_q->andWhere('tr.date <= :date_by')
  6042.                     ->setParameter('date_by'$date_by);
  6043.             }
  6044.         }
  6045.         $transactions_q->orderBy('tr.date''ASC');
  6046.         $transactions $transactions_q->getQuery()->getArrayResult();
  6047.         $types = array(
  6048.             'income' => 'Начисление',
  6049.             'expense' => 'Списание'
  6050.         );
  6051.         $file '';
  6052.         if(count($transactions) > 0){
  6053.             foreach ($transactions as $key => $item){
  6054.                 $transactions[$key]['from_name'] = $this->nameClient($item['f_first_name'], $item['f_last_name'], $item['f_username']);
  6055.                 $transactions[$key]['to_name'] = $this->nameClient($item['t_first_name'], $item['t_last_name'], $item['t_username']);
  6056.                 $transactions[$key]['sender'] = $this->nameClient($item['s_first_name'], $item['s_last_name'], $item['s_username']);
  6057.                 $date '';
  6058.                 $dates = (array)$item['date'];
  6059.                 if(isset($dates['date'])){
  6060.                     $date date("d.m.Y H:i"strtotime($dates['date']));
  6061.                 }
  6062.                 $opt "";
  6063.                 if($item['typeof'] == 'income'){
  6064.                     $opt "+";
  6065.                 }
  6066.                 //$transactions[$key]['amount'] = $opt . str_replace(',00', '', number_format(($item['amount'] / 100), 2, ',', ' '));
  6067.                 $transactions[$key]['amount'] = str_replace(',00'''number_format(($item['amount'] / 100), 2','''));
  6068.                 $transactions[$key]['type'] = $item['typeof'];
  6069.                 $transactions[$key]['typeof'] = (isset($types[$item['typeof']]) ? $types[$item['typeof']] : '');
  6070.                 //$transactions[$key]['typeof'] = ($item['note'] != '' && $item['note'] != null ? $item['note'] : (isset($types[$item['typeof']]) ? $types[$item['typeof']] : ''));
  6071.                 $transactions[$key]['date'] = $date;
  6072.                 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']);
  6073.             }
  6074.             //$date_with = '2022-04-01 15:20:00';
  6075.             //$date_by = '2022-04-11 10:00:00';
  6076.             $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));
  6077.         }
  6078.         return $file;
  6079.     }
  6080.     public static function genExcel($data$basePath$date_with null$date_by null){
  6081.         $styleArrayTopBold = array(
  6082.             'font' => array(
  6083.                 'bold' => true,
  6084.                 'size' => 12
  6085.             )
  6086.         );
  6087.         $styleArrayTop = array(
  6088.             'font' => array(
  6089.                 'size' => 11
  6090.             )
  6091.         );
  6092.         $styleArrayBold = array(
  6093.             'font' => array(
  6094.                 'bold' => true
  6095.             )
  6096.         );
  6097.         $styleArrayBorderMinSize = array(
  6098.             'borders' => array(
  6099.                 'outline' => array(
  6100.                     'style' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
  6101.                     'color' => array('argb' => '000000'),
  6102.                 ),
  6103.             ),
  6104.             'font' => array(
  6105.                 'size' => 10
  6106.             )
  6107.         );
  6108.         //$PHPExcel = new \PHPExcel();
  6109.         $PHPExcel = new Spreadsheet();
  6110.         $PHPExcel->getDefaultStyle()->getFont()->setName('Calibri')->setSize(11);
  6111.         $PHPExcel->getDefaultStyle()->getAlignment()->setWrapText(true);
  6112.         $PHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  6113.         $PHPExcel->createSheet(0);
  6114.         $sheet $PHPExcel->getSheet(0);
  6115.         $PHPExcel->setActiveSheetIndex(0);
  6116.         $sheet_title 'Отчет по операциям';
  6117.         $sheet->setTitle($sheet_title);
  6118.         $title_report 'Отчет по финансовым операциям от ' MainController::rusDate(date("Y-m-d H:i:s"), 'ru'truefalsetrue);
  6119.         $sheet->mergeCells('A1:C1');
  6120.         $sheet->mergeCells('A2:C2');
  6121.         $sheet->getStyleByColumnAndRow(01)->applyFromArray($styleArrayTop);
  6122.         $sheet->getStyleByColumnAndRow(02)->applyFromArray($styleArrayTop);
  6123.         $sheet
  6124.             ->getStyleByColumnAndRow(01)
  6125.             ->getAlignment()
  6126.             ->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER)
  6127.         ;
  6128.         $sheet
  6129.             ->getStyleByColumnAndRow(02)
  6130.             ->getAlignment()
  6131.             ->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER)
  6132.         ;
  6133.         $n_row 3;
  6134.         foreach (array('A') as $symbol){
  6135.             $sheet->getColumnDimension($symbol)->setWidth(5);
  6136.         }
  6137.         foreach (array('B') as $symbol){
  6138.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6139.         }
  6140.         foreach (array('C') as $symbol){
  6141.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6142.         }
  6143.         foreach (array('D') as $symbol){
  6144.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6145.         }
  6146.         foreach (array('E') as $symbol){
  6147.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6148.         }
  6149.         foreach (array('F') as $symbol){
  6150.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6151.         }
  6152.         foreach (array('G') as $symbol){
  6153.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6154.         }
  6155.         foreach (array('H') as $symbol){
  6156.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6157.         }
  6158.         foreach (array('I') as $symbol){
  6159.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6160.         }
  6161.         foreach (array('J') as $symbol){
  6162.             $sheet->getColumnDimension($symbol)->setWidth(30);
  6163.         }
  6164.         $sheet->mergeCells('A3:J3');
  6165.         $sheet->getCellByColumnAndRow(1$n_row)->setValue($title_report);
  6166.         $sheet->getStyleByColumnAndRow(1$n_row)->applyFromArray($styleArrayTopBold);
  6167.         $sheet
  6168.             ->getStyleByColumnAndRow(1$n_row)
  6169.             ->getAlignment()
  6170.             ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)
  6171.         ;
  6172.         if(($date_with != '' && $date_with != null) || ($date_by != '' && $date_by != null)){
  6173.             $n_row += 2;
  6174.             $sheet->mergeCells('A5:J5');
  6175.             $sheet->getCellByColumnAndRow(1$n_row)->setValue('за период c ' $date_with ' по ' $date_by);
  6176.             $sheet->getStyleByColumnAndRow(1$n_row)->applyFromArray($styleArrayTopBold);
  6177.             $sheet
  6178.                 ->getStyleByColumnAndRow(1$n_row)
  6179.                 ->getAlignment()
  6180.                 ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)
  6181.             ;
  6182.         }
  6183.         $n_row += 2;
  6184.         if(count($data) > 0){
  6185.             $arr_columns = array('A''B''C''D''E''F''G''H''I''J');
  6186.             foreach ($arr_columns as $column){
  6187.                 $PHPExcel->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
  6188.             }
  6189. //                $n_row = 1;
  6190.             $sheet->getCellByColumnAndRow(1$n_row)->setValue('№ п/п');
  6191.             $sheet->getCellByColumnAndRow(2$n_row)->setValue('Тип операции');
  6192.             $sheet->getCellByColumnAndRow(3$n_row)->setValue('Добавил');
  6193.             $sheet->getCellByColumnAndRow(4$n_row)->setValue('Дата операции');
  6194.             $sheet->getCellByColumnAndRow(5$n_row)->setValue('Сумма');
  6195.             //$sheet->getCellByColumnAndRow(6, $n_row)->setValue('Группа');
  6196.             $sheet->getCellByColumnAndRow(6$n_row)->setValue('Откуда');
  6197.             $sheet->getCellByColumnAndRow(7$n_row)->setValue('Куда');
  6198.             $sheet->getCellByColumnAndRow(8$n_row)->setValue('№ объекта');
  6199.             $sheet->getCellByColumnAndRow(9$n_row)->setValue('Объект');
  6200.             $sheet->getCellByColumnAndRow(10$n_row)->setValue('Коментарий');
  6201.             for($c 1$c <= 10$c++){
  6202.                 $sheet->getStyleByColumnAndRow($c$n_row)
  6203.                     ->applyFromArray($styleArrayBorderMinSize)
  6204.                     ->getAlignment()
  6205.                     ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)
  6206.                 ;
  6207.             }
  6208.             $sheet
  6209.                 ->getStyle('A' $n_row ':J' $n_row)
  6210.                 ->getFill()
  6211.                 ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  6212.                 ->getStartColor()
  6213.                 ->setRGB('C2E9F6')
  6214.             ;
  6215.             $n 1;
  6216.             foreach ($data as $item){
  6217.                 $n_row += 1;
  6218.                 $groupName '';
  6219.                 if($item['type'] == 'income'){
  6220.                     if($item['to_name'] != '' && $item['to_name'] != null){
  6221.                         $groupName $item['to_name'];
  6222.                     } else {
  6223.                         $groupName $item['from_name'];
  6224.                     }
  6225.                 } elseif($item['type'] == 'expense'){
  6226.                     if($item['from_name'] != '' && $item['from_name'] != null ){
  6227.                         $groupName $item['from_name'];
  6228.                     } else {
  6229.                         $groupName $item['to_name'];
  6230.                     }
  6231.                 }
  6232.                 $sheet->getCellByColumnAndRow(1$n_row)->setValue($n);
  6233.                 $sheet->getCellByColumnAndRow(2$n_row)->setValue($item['typeof']);
  6234.                 $sheet->getCellByColumnAndRow(3$n_row)->setValue($item['sender']);
  6235.                 $sheet->getCellByColumnAndRow(4$n_row)->setValue($item['date']);
  6236.                 $sheet->getCellByColumnAndRow(5$n_row)->setValue($item['amount']);
  6237.                 //$sheet->getCellByColumnAndRow(6, $n_row)->setValue($groupName);
  6238.                 $sheet->getCellByColumnAndRow(6$n_row)->setValue($item['from_name']);
  6239.                 $sheet->getCellByColumnAndRow(7$n_row)->setValue($item['to_name']);
  6240.                 $sheet->getCellByColumnAndRow(8$n_row)->setValue($item['office_number']);
  6241.                 $sheet->getCellByColumnAndRow(9$n_row)->setValue($item['office_name']);
  6242.                 $sheet->getCellByColumnAndRow(10$n_row)->setValue($item['comment']);
  6243.                 $n++;
  6244.                 for($c 1$c <= 10$c++){
  6245.                     $sheet->getStyleByColumnAndRow($c$n_row)->applyFromArray($styleArrayBorderMinSize);
  6246.                 }
  6247. //                $sheet
  6248. //                    ->getStyleByColumnAndRow(8, $n_row)
  6249. //                    ->getAlignment()
  6250. //                    ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)
  6251. //                    ->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER)
  6252. //                ;
  6253.             }
  6254.         }
  6255.         $PHPExcel->setActiveSheetIndex(0);
  6256.         $fileDir '/public/images/';
  6257.         if (!is_dir($basePath '/public/images/')) {
  6258.             mkdir($basePath '/public/images/');
  6259.         }
  6260.         if (!is_dir($basePath $fileDir)) {
  6261.             mkdir($basePath $fileDir);
  6262.         }
  6263.         $uuid ProjectUtilsController::generateUuid();
  6264.         $predir substr($uuid03);
  6265.         if (!is_dir($basePath $fileDir '/' $predir '/')) {
  6266.             mkdir($basePath $fileDir '/' $predir '/');
  6267.         }
  6268.         //$filename = $predir . '/' . $uuid . '.xlsx';
  6269.         $filename $predir '/' date("Y_m_d_H_i_s") . '_report.xlsx';
  6270.         //$filename = 'test.xlsx';
  6271.         $filepath $basePath $fileDir '/' $filename;
  6272.         //$objWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel2007');
  6273.         $objWriter \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($PHPExcel,  'Xlsx');
  6274.         $objWriter->save($filepath);
  6275.         return $filename;
  6276.     }
  6277.     private function sendEmail(MailerInterface $mailer$event$body_mail$theme_mail$locale 'ru'$recipient false$attach = array())
  6278.     {
  6279.         $mailerFrom $this->getParameter('app.mailer.from');
  6280.         $mail_template_q $this->getDoctrine()
  6281.             ->getRepository(MailTemplate::class)
  6282.             ->createQueryBuilder('mt')
  6283.             ->select('mt.id, mt.title, mt.body, mt.copy')
  6284.             ->where('mt.event = :event')
  6285.             ->setParameter('event'$event)
  6286.             ->getQuery()->getResult();
  6287.         $theme '';
  6288.         $body '';
  6289.         $mail_template = array();
  6290.         if(isset($mail_template_q[0])){
  6291.             $mail_template $mail_template_q[0];
  6292.             $theme $mail_template['title'];
  6293.             $body $mail_template['body'];
  6294.             if(count($body_mail) > 0){
  6295.                 foreach ($body_mail as $ket_b => $b_mail){
  6296.                     $body str_replace($ket_b$b_mail $body);
  6297.                 }
  6298.             }
  6299.             if(count($theme_mail) > 0){
  6300.                 foreach ($theme_mail as $ket_th => $th_mail){
  6301.                     $theme str_replace($ket_th$th_mail $theme);
  6302.                 }
  6303.             }
  6304.         }
  6305.         if($recipient === false){
  6306.             $recipient $this->getParameter('app.mailer.to');
  6307.         }
  6308.         $email = (new Email())
  6309.             ->from($mailerFrom)
  6310.             ->to($recipient)
  6311.             //->cc('max.linwa@gmail.com')
  6312.             //->addTo('igor@atmapro.ru')
  6313.             //->bcc('igor@atmapro.ru')
  6314.             //->replyTo('fabien@example.com')
  6315.             //->priority(Email::PRIORITY_HIGH)
  6316.             ->subject($theme)
  6317.             ->text('Sending emails is fun again!')
  6318.             ->html($body);
  6319.         if(count($mail_template) > 0){
  6320.             if($mail_template['copy'] != '' && $mail_template['copy'] != null){
  6321.                 $email->cc($mail_template['copy']);
  6322.             }
  6323.         }
  6324.         if(count($attach) > 0){
  6325.             foreach ($attach as $item){
  6326.                 $email->attachFromPath($item);
  6327.             }
  6328.         }
  6329.         
  6330.         $is_send false;
  6331.         try {
  6332.             $mailer->send($email);
  6333.             $is_send true;
  6334.         } catch (TransportExceptionInterface $e) {
  6335.             echo $e->getMessage();
  6336.             // некая ошибка предотвратила отправку письма; отобразить сообщение
  6337.             // об ошибке или попробовать отправить сообщение повторно
  6338.         }
  6339.         return $is_send;
  6340.     }
  6341.     public static function rusDate($date$lang 'ru'$time false$time_prefix false$with_year false)
  6342.     {
  6343.         if ($lang == 'ru') {
  6344.             $a = array('01' => 'января''02' => 'февраля''03' => 'марта''04' => 'апреля''05' => 'мая''06' => 'июня''07' => 'июля''08' => 'августа''09' => 'сентября''10' => 'октября''11' => 'ноября''12' => 'декабря',);
  6345.         } elseif ($lang == 'en') {
  6346.             $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');
  6347.         }
  6348.         $ex explode(' '$date);
  6349.         $timeex explode(':'$ex[1]);
  6350.         $ex explode('-'$ex[0]);
  6351.         $year = ($ex[0] != date('Y') ? ' ' $ex[0] : '');
  6352.         if ($with_year) {
  6353.             $year ', ' $ex[0];
  6354.         }
  6355.         return intval($ex[2]) . ' ' $a[$ex[1]] . $year . ($time ? ($time_prefix $time_prefix ' ') . $timeex[0] . ':' $timeex[1] : '');
  6356.     }
  6357.     #[Route('/user-create/'name'app_user_create')]
  6358.     public function userCreate(Request $requestUserPasswordEncoderInterface $encoder): Response
  6359.     {
  6360.         $em $this->getDoctrine()->getManager();
  6361.         $login $request->get('login');
  6362.         $password $request->get('password');
  6363.         if (!empty($login) && !empty($password)) {
  6364.             $user $this->getDoctrine()->getRepository(User::class)->findOneBy(['username' => $login]);
  6365.             if (!$user) {
  6366.                 $newUser = new User();
  6367.                 $newUser->setUsername($login);
  6368.                 $encoded $encoder->encodePassword($newUser$password);
  6369.                 $newUser->setPassword($encoded);
  6370.                 $newUser->setRoles(array('ROLE_ADMIN'));
  6371.                 $em->persist($newUser);
  6372.                 $em->flush();
  6373.                 echo 'Пользователь успешно создан';
  6374.             } else {
  6375.                 echo 'Пользователь уже есть';
  6376.             }
  6377.         } else {
  6378.             echo 'Не достаточно данных';
  6379.         }
  6380.         die();
  6381.     }
  6382.     public static function recalculateBalance($doctrine$ids = array())
  6383.     {
  6384.         $em $doctrine->getManager();
  6385.         $clients_qq $doctrine
  6386.             ->getRepository(Client::class)
  6387.             ->createQueryBuilder('cl')
  6388.             ->select('cl.id, cl.balance')
  6389.             ->where('cl.typeof != :typeof')
  6390.             ->setParameter('typeof'"private");
  6391.         if(count($ids) > 0){
  6392.             $clients_qq->andWhere('tr.id IN (' implode(","$ids) . ')');
  6393.         }
  6394.         $clients_q $clients_qq->getQuery()->getResult();
  6395.         if(count($clients_q) > 0){
  6396.             foreach ($clients_q as $item_client){
  6397.                 $transaction_q $doctrine
  6398.                     ->getRepository(Transaction::class)
  6399.                     ->createQueryBuilder('tr')
  6400.                     ->select('tr.id, SUM(tr.amount) AS balance')
  6401.                     ->where('tr.recipient = ' $item_client['id'])
  6402.                     ->getQuery()->getResult();
  6403.                 if(count($transaction_q) == 1){
  6404.                     $transaction $transaction_q[0];
  6405.                     if($transaction['balance'] != $item_client['balance']){
  6406.                         //echo 'У клиента ' . $item_client['id'] . ' балансы не совпадают, фактический ' . $transaction['balance'] . ', по операциям ' . $item_client['balance'] . "\n";
  6407.                         $client $doctrine->getRepository(Client::class)->findOneBy(['id' => $item_client['id']]);
  6408.                         if($client){
  6409.                             $client->setBalance($transaction['balance']);
  6410.                             $em->persist($client);
  6411.                             $em->flush();
  6412.                             //echo 'У клиента ' . $client->getId() . ' был изменен баланс на ' . $transaction['balance'] . "\n";
  6413.                         }
  6414.                     } else {
  6415.                         //echo 'У клиента ' . $item_client['id'] . ' баланс правильный' . "\n";
  6416.                     }
  6417.                 }
  6418.             }
  6419.         }
  6420.         //print_r($clients_q);
  6421.     }
  6422.     private function actualBalance($client){
  6423.         $balance false;
  6424.         if($client){
  6425.             $client_id null;
  6426.             if(is_object($client)){
  6427.                 $client_id $client->getId();
  6428.                 if($client_id != '' && $client_id != null){
  6429.                     $transaction_q $this->getDoctrine()
  6430.                         ->getRepository(Transaction::class)
  6431.                         ->createQueryBuilder('tr')
  6432.                         ->select('tr.id, SUM(tr.amount) AS balance')
  6433.                         ->where('tr.recipient = ' $client_id)
  6434.                         ->getQuery()->getResult();
  6435.                     if(isset($transaction_q[0]['balance'])){
  6436.                         $balance $transaction_q[0]['balance'];
  6437.                     }
  6438.                 }
  6439.             }
  6440.         }
  6441.         return $balance;
  6442.     }
  6443. }