<?php
namespace App\Controller;
use App\Entity\Bot;
use App\Entity\Client;
use App\Entity\Command;
use App\Entity\Draft;
use App\Entity\LogMessage;
use App\Entity\MailTemplate;
use App\Entity\Office;
use App\Entity\Report;
use App\Entity\Role;
use App\Entity\SalarySchedule;
use App\Entity\Transaction;
use App\Entity\TypeGroup;
use App\Entity\User;
use App\Kernel;
use Doctrine\ORM\EntityManagerInterface;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class MainController extends AbstractController
{
private $em;
private $kernel;
private $mailer;
public function __construct(EntityManagerInterface $em, Kernel $kernel, MailerInterface $mailer){
$this->em = $em;
$this->kernel = $kernel;
$this->mailer = $mailer;
}
/**
* @Route("/main", name="app_main")
*/
public function index(): Response
{
return $this->render('main/index.html.twig', [
'controller_name' => 'MainController',
]);
}
#[Route('/api/test/', name: 'app_api_test')]
public function test(Request $request, MailerInterface $mailer): Response
{
$token = '452751952:AAFU-nLuoxwNlH9ugqwsTfxa253UvqhvHr4';
$chat_id = '-1001982917129';
$groupObj = $this->getDoctrine()->getRepository(Client::class)->find(2);
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->find(142);
$create_transaction = $this->sendMailNonCashCheque($token, $chat_id, $groupObj, $draftObj);
die();
$bot = $this->getDoctrine()->getRepository(Bot::class)->find(1);
if($bot){
$token = $bot->getToken();
$getChat = ProjectUtilsController::requestToBot($token, 'getChat', ['chat_id' => '-4225857944']);
echo $getChat;
}
die();
// echo $this->getParameter('app.mailer.to.transaction');
// die();
$event = 'newTransaction';
//$recipient = 'igor@atmapro.ru';
$recipient = $this->getParameter('app.mailer.to.transaction');
$title_mail = array(
'#amount#' => '3000',
'#source#' => 'Ботская 2',
'#type#' => 'начисление ЗП'
);
$body_mail = array(
'#office#' => '1111 Бургерная',
'#type#' => 'начисление ЗП',
'#amount#' => '3000',
'#date#' => '27.06.2024',
'#source#' => 'Ботская 2',
'#comment#' => 'начисление зп за день',
'#cheque#' => 'нет'
);
$m = $this->sendEmail($mailer, $event, $body_mail, $title_mail, 'ru', $recipient, array());
echo $m;
die();
$basePath = $this->getParameter('kernel.project_dir');
$token = '452751952:AAFU-nLuoxwNlH9ugqwsTfxa253UvqhvHr4 ';
$draft = $this->getDoctrine()->getRepository(Draft::class)->find(34);
$chat_id = '414013565';
$group = '-1001982917129';
$this->createTransaction($token, $chat_id, $group, $draft);
die();
$message_id = 3407;
$result = json_decode(file_get_contents($basePath . '/var/log/chatDev.txt'), true);
$text = (isset($result["message"]["text"]) ? $result["message"]["text"] : null);
$chat_id = (isset($result['message']['from']['id']) ? $result['message']['from']['id'] : null);
$typeof = (isset($result["message"]["chat"]["type"]) ? $result["message"]["chat"]["type"] : null);
$group_id = (isset($result['message']['chat']['id']) && ($typeof == 'group' || $typeof == 'supergroup') ? $result['message']['chat']['id'] : null);
if($text == '/clear'){
$this->clear($token, $chat_id, $group_id, $message_id);
die();
}
die();
$newReport = $this->getDoctrine()->getRepository(Report::class)->find(48);
$file = $this->genReport($newReport);
echo $file;
die();
$token = '452751952:AAFU-nLuoxwNlH9ugqwsTfxa253UvqhvHr4';
$deleteMyCommands = ProjectUtilsController::requestToBot($token, 'deleteMyCommands', []);
echo $deleteMyCommands;
die();
$setMyCommands = ProjectUtilsController::requestToBot($token, 'setMyCommands', ['commands' => json_encode([['command' => 'help', 'description' => 'Список комманд'], ['command' => 'prev', 'description' => 'Список комманд'], ['command' => 'next', 'description' => 'Список комманд'], ['command' => 'top', 'description' => 'Список комманд'], ['command' => 'bottom', 'description' => 'Список комманд']])]);
echo $setMyCommands;
$getMyCommands = ProjectUtilsController::requestToBot($token, 'getMyCommands', []);
echo $getMyCommands;
die();
$basePath = $this->getParameter('kernel.project_dir');
$fileDir = '/public/images/';
// echo $basePath;
// die();
$body_mail = array(
'#app#' => $this->getParameter('app.name'),
'#logo#' => $this->getParameter('app.logo'),
'#date_with#' => '',
'#date_by#' => '',
);
$title_mail = array();
$file = '0eb/2022_04_22_11_06_53_report.xlsx';
$attach = array();
$filepath = $basePath . $fileDir . $file;
if(file_exists($filepath)){
$attach[] = $basePath . $fileDir . $file;
}
//отправка письма
$email = 'igor@atmapro.ru';
$sendMail = $this->sendEmail($this->mailer,'newReportPeriod', $body_mail, $title_mail, 'ru', $email, $attach);
//MainController::recalculateBalance($this->getDoctrine());
die();
$pay = array
(
'update_id' => 866792455,
'message' => array
(
'message_id' => 834,
'from' => array
(
'id' => 1406913295,
'is_bot' => 0,
'first_name' => 'Max',
'last_name' => 'Voitov',
'username' => 'MaxIngenieur',
'language_code' => 'ru'
),
'chat' => array
(
'id' => -655101877,
'title' => 'Тест Нал Игорь',
'type' => 'group',
'all_members_are_administrators' => 1
),
'date' => 1651841438,
'text' => '/pay',
'entities' => array
(
0 => array
(
'offset' => 0,
'length' => 4,
'type' => 'bot_command'
)
)
)
);
$report = $this->getDoctrine()->getRepository(Report::class)->find(36);
echo $this->genReport($report);
die();
$bot = $this->getDoctrine()->getRepository(Bot::class)->find(1);
//$this->deleteLogMessage($bot, '-1001444351695', 6);
$this->deleteLogMessage($bot, '-1001444351695');
die();
$chat_id = '-1001444351695';
$token = '452751952:AAFU-nLuoxwNlH9ugqwsTfxa253UvqhvHr4';
$message_id = '906';
$bot_id = 1;
$command_id = 1;
$this->deleteLogMessage($bot_id, $chat_id, $command_id);
die();
echo $this->addLogMessage($bot_id, $chat_id, $message_id);
//$deleteMessage = ProjectUtilsController::requestToBot($token, 'deleteMessage', ['chat_id' => $chat_id, 'message_id' => $message_id]);
//echo $deleteMessage;
die();
}
#[Route('/api/bot/{id}/', name: 'app_api_bot')]
public function bot(Request $request): Response
{
$basePath = $this->getParameter('kernel.project_dir');
$id = $request->get('id');
$is_group_chat = $this->getParameter('app.chat.is_group');
$time_interval = $this->getParameter('app.time.interval');
$result = json_decode($request->getContent(), true);
if($request->get('dev') != '' && $request->get('dev') != null){
if(file_exists($basePath . '/var/log/chatDev.txt')){
$result = json_decode(file_get_contents($basePath . '/var/log/chatDev.txt'), true);
}
} else {
file_put_contents($basePath . '/var/log/chatDev.txt', print_r($request->getContent(), true));
}
// file_put_contents($basePath . '/var/log/chatDev1.txt', print_r($result, true));
// print_r($result);
// die();
if($request->get('is_test') == '1'){
/*
$result = array
(
'update_id' => 866792513,
'message' => array
(
'message_id' => 942,
'from' => array
(
'id' => 1406913295,
'is_bot' => 0,
'first_name' => 'Max',
'last_name' => 'Voitov',
'username' => 'MaxIngenieur',
'language_code' => 'ru'
),
'chat' => array
(
'id' => -763088405,
'title' => 'Тест ЗП Юлия',
'type' => 'group',
'all_members_are_administrators' => 1
),
'date' => 1651847902,
'text' => '/balance',
'entities' => array
(
0 => array
(
'offset' => 0,
'length' => 8,
'type' => 'bot_command'
)
)
)
);
*/
/*
$result = array(
'update_id' => 145457792,
'message' => array
(
'message_id' => 4099,
'from'=> array
(
'id' => 414013565,
'is_bot' => false,
'first_name' => 'Igor',
'last_name' => 'MrRedson',
'language_code' => 'ru'
),
'chat' => array
(
'id' => -1001444351695,
'title' => 'ЗП Бот I',
'type' => 'supergroup',
),
'date' => 1733760426,
'text' => 't100',
// 'entities' => [
// 0 => [
// 'offset' => 0,
// 'length' => 4,
// 'type' => 'bot_command'
// ]
// ]
)
);
*/
/*
$result = array(
'update_id' => 145456044,
'message' => array
(
'message_id' => 405,
'from'=> array
(
'id' => 414013565,
'is_bot' => false,
'first_name' => 'Igor',
'username' => 'MrRedson',
'language_code' => 'ru'
),
'chat' => array
(
'id' => -1001982917129,
'title' => 'Нал Ботская 2',
'type' => 'supergroup'
),
'date' => 1719404053,
'photo' => [
[
'file_id' => 'AgACAgIAAx0CdjDqCQACAZVmfAYVcer4gcTwfYczfRhj3meDGgACm98xG6Rc4Uu3TTnhA8WCwAEAAwIAA3MAAzUE',
'file_unique_id' => 'AQADm98xG6Rc4Ut4',
'file_size' => 574,
'width' => 90,
'height' => 22
],
[
'file_id' => 'AgACAgIAAx0CdjDqCQACAZVmfAYVcer4gcTwfYczfRhj3meDGgACm98xG6Rc4Uu3TTnhA8WCwAEAAwIAA20AAzUE',
'file_unique_id' => 'AQADm98xG6Rc4Uty',
'file_size' => 4711,
'width' => 320,
'height' => 80
],
[
'file_id' => 'AgACAgIAAx0CdjDqCQACAZVmfAYVcer4gcTwfYczfRhj3meDGgACm98xG6Rc4Uu3TTnhA8WCwAEAAwIAA3gAAzUE',
'file_unique_id' => 'AQADm98xG6Rc4Ut9',
'file_size' => 18943,
'width' => 800,
'height' => 199
],
[
'file_id' => 'AgACAgIAAx0CdjDqCQACAZVmfAYVcer4gcTwfYczfRhj3meDGgACm98xG6Rc4Uu3TTnhA8WCwAEAAwIAA3kAAzUE',
'file_unique_id' => 'AQADm98xG6Rc4Ut-',
'file_size' => 28849,
'width' => 28849,
'height' => 319
]
]
)
);
*/
/*
$result = array(
'update_id' => 145457688,
'callback_query' => [
'id' => 1778174725879195884,
'from'=> array
(
'id' => 414013565,
'is_bot' => false,
'first_name' => 'Igor',
'username' => 'MrRedson',
'language_code' => 'ru'
),
'message' => array
(
'message_id' => 1238,
'from'=> array
(
'id' => 452751952,
'is_bot' => true,
'first_name' => 'tatuin',
'username' => 'SirTatuin_bot',
),
'chat' => array
(
'id' => -1001982917129,
'title' => 'Нал Бот I',
'type' => 'group',
//'all_members_are_administrators' => 1
),
'date' => 1733240191,
'text' => 'Выбрано «Расходы по Объекту». Выберите объект, по которому осуществляется расход.',
'reply_markup' => [
'inline_keyboard' => [
[
[
'text' => '27871. Тестовый',
'callback_data' => '{"action":"add_office","command":"bpay","id":1,"group":2}'
]
]
]
]
),
'chat_instance' => -3430887582451155820,
'data' => '{"action":"add_office","command":"bpay","id":1,"group":2}'
]
);
*/
$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"}}';
$result = json_decode($r, true);
// print_r($result);
// die();
}
$text = (isset($result["message"]["text"]) ? $result["message"]["text"] : null);
$chat_id = (isset($result['message']['from']['id']) ? $result['message']['from']['id'] : null);
$typeof = (isset($result["message"]["chat"]["type"]) ? $result["message"]["chat"]["type"] : null);
$group_id = (isset($result['message']['chat']['id']) && ($typeof == 'group' || $typeof == 'supergroup') ? $result['message']['chat']['id'] : null);
$group = $typeof == 'group' || $typeof == 'supergroup' ? $group_id : null;
$message_id = (isset($result["message"]["message_id"]) ? $result["message"]["message_id"] : null);
$callback_query = (isset($result["callback_query"]) ? $result["callback_query"] : array());
$callback_query_data = (isset($result["callback_query"]["data"]) ? $result["callback_query"]["data"] : null);
$photo = (isset($result["message"]["photo"]) ? $result["message"]["photo"] : []);
$caption = (isset($result["message"]["caption"]) ? $result["message"]["caption"] : null);
//file_put_contents($basePath . '/var/log/r_1.txt', print_r($result, true), FILE_APPEND);
$fileId = null;
if(count($photo) > 0){
foreach ($photo as $key_ph => $itemPhoto){
if($key_ph == count($photo) - 1){
$fileId = $itemPhoto['file_id'];
}
}
if($caption != '' && $caption != ''){
$text = $caption;
}
}
if($message_id == null || $message_id == ''){
$message_id = (isset($callback_query["message"]["message_id"]) ? $callback_query["message"]["message_id"] : null);
}
//не пропускать двойную обрабоку сообщения
if($is_group_chat === true && $message_id != '' && $message_id != null && !($request->get('is_test') == '1')){
$chId = $chat_id;
if($group != '' && $group != null){
$chId = $group;
}
$log_message = $this->getDoctrine()
->getRepository(LogMessage::class)
->createQueryBuilder('lm')
->select('lm.id')
->where('lm.bot = :bot_id')
->andWhere('lm.message_id = :message_id')
->andWhere('lm.chat_id = :chat_id')
->setParameter('bot_id', $id)
->setParameter('message_id', $message_id)
->setParameter('chat_id', $chId)
->getQuery()->getArrayResult();
if(count($log_message) > 0){
file_put_contents($basePath . '/var/log/double.txt', print_r($result, true), FILE_APPEND);
exit();
}
}
if(count($callback_query) > 0){
$chat_id = (isset($callback_query['message']['chat']['id']) ? $callback_query['message']['chat']['id'] : null);
}
$cq_data = array();
$thisCommand = null;
if(ProjectUtilsController::isJSON($callback_query_data) === true){
$cq_data = json_decode($callback_query_data, true);
if(isset($cq_data['command'])){
$thisCommand = $cq_data['command'];
}
}
file_put_contents($basePath . '/var/log/chat2.txt', print_r($result, true), FILE_APPEND);
file_put_contents($basePath . '/var/log/callback1.txt', print_r($cq_data, true), FILE_APPEND);
$token = null;
$bot = false;
if($id != null && $id != ''){
$bot = $this->getDoctrine()->getRepository(Bot::class)->find($id);
$token = $bot->getToken();
}
//очистка имени бота из команды <<<
if(strpos($text, '@') !== false) {
$arr_t = explode('@', $text);
if(count($arr_t) == 2){
$nameBot = $arr_t[count($arr_t) - 1];
$text = str_replace('@' . $nameBot, '', $text);
if(strpos($text, '@' . $nameBot) !== false) {
$text = str_replace('@' . $nameBot, '', $text);
}
}
}
//очистка имени бота из команды >>>
// $reply = 'Пришло ';
// $sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
// die();
$client = $this->getCurClient($chat_id, $typeof, (isset($result['message']['from']) ? $result['message']['from'] : array()), (isset($result['message']['chat']) ? $result['message']['chat'] : array()));
if(!empty($token) && !empty($chat_id)){
$command = false;
if(count($cq_data) > 0){
$this->resetExpected($client);
if($thisCommand == 'setting'){
$this->setting($token, $chat_id, $group_id, $cq_data, $message_id);
} elseif($thisCommand == 'users'){
$this->users($token, $chat_id, $group_id, $cq_data, false, null, $message_id);
} elseif($thisCommand == 'office'){
$this->office($token, $chat_id, $group_id, $cq_data, false, null, $message_id);
} elseif($thisCommand == 'pay'){
if($is_group_chat === true){
$chat_id = (isset($callback_query['from']['id']) ? $callback_query['from']['id'] : null);
}
$this->pay($token, $chat_id, $group_id, $cq_data, false, null, $message_id);
} elseif($thisCommand == 'bpay'){
if($is_group_chat === true){
$chat_id = (isset($callback_query['from']['id']) ? $callback_query['from']['id'] : null);
}
$this->bpay($token, $chat_id, $group_id, $cq_data, false, null, $message_id);
} elseif($thisCommand == 'report'){
$this->report($token, $chat_id, $group_id, $cq_data, false, null, $message_id);
}
if($is_group_chat === true && $group_id != '' && $group_id != null){
$commandObj = false;
if(!$command && $thisCommand != '' && $thisCommand != null){
$commandObj = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => $thisCommand, 'is_active' => true));
}
$this->addLogMessage($bot, $group_id, $message_id, $commandObj);
}
exit();
}
//$setMyCommands = ProjectUtilsController::requestToBot($token, 'setMyCommands', ['commands' => json_encode([['command' => '/help', 'description' => 'Список комманд'], ['command' => '/prev', 'description' => 'Список комманд'], ['command' => '/next', 'description' => 'Список комманд'], ['command' => '/top', 'description' => 'Список комманд'], ['command' => '/bottom', 'description' => 'Список комманд']])]);
// $reply = 'Тест';
// $sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
// die();
$isLog = false;
if(($text != '' && $text != null) || ($fileId != '' && $fileId != null)){
if($text == '/clear'){
$this->addLogMessage($bot, $group_id, $message_id, null);
$this->clear($token, $chat_id, $group_id, $message_id);
die();
}
$command = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('name' => $text, 'is_active' => true));
if($command){
$client_m = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
if($client_m){
$this->resetExpected($client_m);
}
$is_access = false;
$client_i = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
$my_role = null;
if($client_i){
if($client_i->getRole()){
$my_role = $client_i->getRole()->getId();
}
}
if(count($command->getRoles()) > 0){
foreach ($command->getRoles() as $role){
if($role->getId() == $my_role){
$is_access = true;
}
}
}
$sendMessage = false;
if($is_group_chat === true && $group_id != '' && $group_id != null){
$this->addLogMessage($bot, $group_id, $message_id, $command);
$isLog = true;
}
if($is_access === true){
if($command->getTypeof() == 'start'){
if($is_group_chat === true && $group_id != '' && $group_id != null){
$chat_id = $group_id;
}
$reply = 'Добро пожаловать в бот' . ($bot ? "«" . $bot->getName() . "»." : '');
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}elseif($command->getTypeof() == 'setting'){
$this->setting($token, $chat_id, $group_id, array(), $message_id);
} elseif($command->getTypeof() == 'help'){
$clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
$type_group = null;
if($is_group_chat === true && $group_id != '' && $group_id != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
if($groupObj && $groupObj->getTypeGroup() != null){
$type_group = $groupObj->getTypeGroup()->getTypeof();
}
}
$reply = $this->mainMenu($clientObj, ($is_group_chat === true && $group_id != '' && $group_id != null ? true : false), $type_group);
if($is_group_chat === true && $group_id != '' && $group_id != null){
$chat_id = $group_id;
}
if($reply != '' && $reply != null){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($command->getTypeof() == 'init'){
$reply = 'Вам не удалось инициализироватся у бота. Попробуйте повторить команду позже.';
if($client){
$reply = 'Вы упешно инициализированы ботом. Чтобы узнать какие команды вам доступны отправьте /help.';
}
if($is_group_chat === true && $group_id != '' && $group_id != null){
$chat_id = $group_id;
}
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
} elseif($command->getTypeof() == 'users'){
$this->users($token, $chat_id, $group_id, array(), false, null, $message_id);
} elseif($command->getTypeof() == 'office'){
$this->office($token, $chat_id, $group_id, array(), false, null, $message_id);
} elseif($command->getTypeof() == 'pay'){
$this->pay($token, $chat_id, $group_id, array(), false, null, $message_id);
} elseif($command->getTypeof() == 'bpay'){
$type_group = null;
$groupId = '';
if($is_group_chat === true && $group_id != '' && $group_id != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
if($groupObj){
if($groupObj->getTypeGroup() != null){
$type_group = $groupObj->getTypeGroup()->getTypeof();
}
$groupId = $groupObj->getId();
}
}
if($type_group == 'cash'){
// if($is_group_chat === true){
// $chat_id = $group_id;
// }
$cq_data = array('action' => "other", 'command' => "bpay", "group" => $groupId);
$this->bpay($token, $chat_id, $group_id, $cq_data, false, null, $message_id);
//$reply = 'группа ' . $groupId;
//$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $group_id, 'text' => $reply, 'parse_mode' => 'HTML']);
} else {
//доступа у группы типа ЗП нет к данной команде
$reply = 'У вас нет доступа к данной команде.';
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $group_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
//$this->bpay($token, $chat_id, $group_id, array(), false, null, $message_id);
} elseif($command->getTypeof() == 'balance'){
$this->balance($token, $chat_id, $group_id, $client_i);
} elseif($command->getTypeof() == 'report'){
$this->report($token, $chat_id, $group_id, array(), $client_i, null, $message_id);
}
if($is_group_chat === true){
//удаление прошлых команд, кроме данной команды
$this->deleteLogMessage($bot, $group_id, null, $command->getId());
}
} else {
$reply = 'У вас нет доступа к данной команде.';
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
if($is_group_chat === true){
$this->addLogMessageBot($bot, $command, $sendMessage);
$isLog = true;
}
if($isLog !== true){
$this->addLogMessage($bot, $group_id, $message_id, null);
}
} else {
$is_expected = false;
if($client){
if($client->getExpected() != '' && $client->getExpected() != null){
$is_expected = true;
$data_expected = $this->dataExpected($client->getExpected());
if(isset($data_expected['value'])){
$typeof_command = null;
if($data_expected['value'] == 'new_office'){
$this->office($token, $chat_id, $group_id, array(), $client, $text, $message_id);
$typeof_command = 'office';
} elseif($data_expected['value'] == 'name_office'){
$this->office($token, $chat_id, $group_id, array(), $client, $text, $message_id);
$typeof_command = 'office';
} elseif($data_expected['value'] == 'edit_office' || $data_expected['value'] == 'edit_n_office'){
$this->office($token, $chat_id, $group_id, array(), $client, $text, $message_id);
$typeof_command = 'office';
} 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'){
$typeof_command = 'pay';
//удаление комментария
/*
if($is_group_chat === true && $group_id != '' && $group_id != null && $data_expected['value'] == 'comment'){
if(!$command && $typeof_command != '' && $typeof_command != null){
$command = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => $typeof_command, 'is_active' => true));
}
$this->addLogMessage($bot, $group_id, $message_id, $command);
$isLog = true;
}
*/
$this->pay($token, $chat_id, $group_id, array(), $client, $text, $message_id, $fileId);
} 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'){
$typeof_command = 'bpay';
//удаление комментария
/*
if($is_group_chat === true && $group_id != '' && $group_id != null && $data_expected['value'] == 'comment'){
if(!$command && $typeof_command != '' && $typeof_command != null){
$command = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => $typeof_command, 'is_active' => true));
}
$this->addLogMessage($bot, $group_id, $message_id, $command);
$isLog = true;
}
*/
$this->bpay($token, $chat_id, $group_id, array(), $client, $text, $message_id, $fileId);
} elseif($data_expected['value'] == 'email'){
$this->users($token, $chat_id, $group_id, array(), $client, $text, $message_id);
$typeof_command = 'users';
} elseif($data_expected['value'] == 'period_report'){
$this->report($token, $chat_id, $group_id, array(), $client, $text, $message_id);
$typeof_command = 'report';
}
if($is_group_chat === true && $group_id != '' && $group_id != null){
if(!$command && $typeof_command != '' && $typeof_command != null){
$command = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => $typeof_command, 'is_active' => true));
}
//чтобы не удалялись сумма, комментарий и чек транзакции
if($data_expected['value'] != 'amount' && $data_expected['value'] != 'comment' && $data_expected['value'] != 'file_cheque' && $data_expected['value'] != 'file_cheque_b'){
$this->addLogMessage($bot, $group_id, $message_id, $command);
}
$isLog = true;
}
}
}
if($isLog !== true){
$this->addLogMessage($bot, $group_id, $message_id, null);
}
}
if($is_expected === false){
if($is_group_chat === true && $group_id != '' && $group_id != null){
$chat_id = $group_id;
}
if(strpos($text, '/') !== false){
$reply = 'Команда не найдена или неактивна, пожалуйста проверьте правильно ли вы ввели команду.';
}
// else {
// $reply = 'Возможно вы ввели текст неправильно, боту не удалось его разпознать';
// }
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
if($is_group_chat === true) {
$this->addLogMessageBot($bot, $command, $sendMessage);
}
}
}
}
//file_put_contents($basePath . '/var/log/chat.txt', $sendMessage, FILE_APPEND);
}
exit();
}
private function clearChats($token, $data){
$em = $this->getDoctrine()->getManager();
if(count($data) > 0){
foreach ($data as $item){
if($item['chat_id'] != null && $item['chat_id'] != '' && $item['message_id'] != null && $item['message_id'] != ''){
$deleteMessage = ProjectUtilsController::requestToBot($token, 'deleteMessage', ['chat_id' => $item['chat_id'], 'message_id' => $item['message_id']]);
$deleteData = array();
if(ProjectUtilsController::isJSON($deleteMessage) === true){
$deleteData = json_decode($deleteMessage, true);
}
if(count($deleteData) > 0){
$log_message = $this->getDoctrine()->getRepository(LogMessage::class)->findOneBy(array('id' => $item['id']));
if($log_message){
if(isset($deleteData['ok'])){
if($deleteData['ok'] === true){
$log_message->setIsDeleted(1);
$log_message->setResponse($deleteMessage);
} else {
$log_message->setResponse($deleteMessage);
}
$em->persist($log_message);
$em->flush();
}
}
}
}
}
}
}
private function clear($token, $chat_id, $group_id, $message_id){
$bot = $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
if($bot){
if($chat_id != '' && $chat_id != null){
$log_messages_q = $this->getDoctrine()
->getRepository(LogMessage::class)
->createQueryBuilder('lm')
->select('lm.id, lm.chat_id, lm.message_id')
->where('lm.is_deleted = 0')
->andWhere('lm.bot = :bot_id')
->andWhere('lm.chat_id = :chat_id')
->setParameter('chat_id', $chat_id)
->setParameter('bot_id', $bot->getId())
->setMaxResults(5)
->orderBy('lm.id', 'DESC')
->getQuery()->getArrayResult();
$this->clearChats($token, $log_messages_q);
}
if($group_id != '' && $group_id != null){
$log_messages_group_q = $this->getDoctrine()
->getRepository(LogMessage::class)
->createQueryBuilder('lm')
->select('lm.id, lm.chat_id, lm.message_id')
->where('lm.is_deleted = 0')
->andWhere('lm.bot = :bot_id')
->andWhere('lm.chat_id = :chat_id')
->setParameter('chat_id', $group_id)
->setParameter('bot_id', $bot->getId())
->setMaxResults(5)
->orderBy('lm.id', 'DESC')
->getQuery()->getArrayResult();
$this->clearChats($token, $log_messages_group_q);
}
$deleteMessage = ProjectUtilsController::requestToBot($token, 'deleteMessage', ['chat_id' => ($group_id != '' && $group_id != '' ? $group_id : $chat_id), 'message_id' => $message_id]);
//$reply = 'Чат очищен от последних сообщений';
//$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => ($group_id != '' && $group_id != '' ? $group_id : $chat_id), 'text' => $reply, 'parse_mode' => 'HTML']);
//$this->addLogMessageBot($bot->getId(), null, $sendMessage);
exit();
}
}
private function addLogMessageBot($bot_id, $command_id, $json_data)
{
$chat_id = null;
$message_id = null;
if(ProjectUtilsController::isJSON($json_data) === true){
$data = json_decode($json_data, true);
if(count($data) > 0 && isset($data['ok'])){
if($data['ok'] === true){
$chat_id = (isset($data['result']['chat']['id']) ? $data['result']['chat']['id'] : null);
$message_id = (isset($data['result']['message_id']) ? $data['result']['message_id'] : null);
}
}
}
$this->addLogMessage($bot_id, $chat_id, $message_id, $command_id);
}
private function addLogMessage($bot_id, $chat_id, $message_id, $command_id = null)
{
$em = $this->getDoctrine()->getManager();
$bot = false;
if(is_object($bot_id)){
$bot = $bot_id;
} elseif($bot_id != '' && $bot_id != null){
$bot = $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('id' => $bot_id));
}
$command = null;
if(is_object($command_id)){
$command = $command_id;
} elseif($command_id != '' && $command_id != null){
$command = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('id' => $command_id));
}
$resp = false;
if($bot && $chat_id != '' && $chat_id != null && $message_id != '' && $message_id != null){
$log_message = $this->getDoctrine()->getRepository(LogMessage::class)->findOneBy(array('chat_id' => $chat_id, 'message_id' => $message_id, 'bot' => $bot, 'is_deleted' => false));
if(!$log_message){
$newLogMessage = new LogMessage();
$newLogMessage->setChatId($chat_id);
$newLogMessage->setMessageId($message_id);
$newLogMessage->setBot($bot);
$newLogMessage->setDate(new \DateTime(date('Y-m-d H:i:s')));
$newLogMessage->setIsDeleted(0);
$newLogMessage->setCommand($command);
$em->persist($newLogMessage);
$em->flush();
if($newLogMessage){
$resp = true;
}
} else {
$resp = true;
}
}
return $resp;
}
private function deleteLogMessage($bot_id = null, $chat_id = null, $command_id = null, $no_command_id = null)
{
if(is_object($bot_id)){
$bot_id = $bot_id->getId();
}
$log_messages_q = $this->getDoctrine()
->getRepository(LogMessage::class)
->createQueryBuilder('lm')
->select('lm.id, lm.chat_id, lm.message_id, b.token AS token')
->leftJoin(Bot::class, 'b', 'WITH', 'lm.bot = b.id')
->where('lm.is_deleted = 0');
if($command_id != '' && $command_id != null){
$log_messages_q->andWhere('lm.command = ' . $command_id);
}
if($no_command_id != '' && $no_command_id != null){
$log_messages_q->andWhere('lm.command != ' . $no_command_id);
}
if($bot_id != '' && $bot_id != null && $chat_id != '' && $chat_id != null){
$log_messages_q->andWhere('lm.bot = ' . $bot_id)
->andWhere('lm.chat_id = :chat_id')
->setParameter('chat_id', $chat_id)
;
} else {
$m = $this->getParameter('app.delete.max_interval');
$d = date('Y-m-d H:i:s',strtotime('-' . $m . ' minutes', strtotime(date("Y-m-d H:i:s"))));
$log_messages_q->andWhere('lm.date <= :date')
->setParameter('date', $d)
;
}
$log_messages = $log_messages_q->getQuery()->getArrayResult();
if(count($log_messages) > 0){
$em = $this->getDoctrine()->getManager();
foreach ($log_messages as $item){
if($item['chat_id'] != null && $item['chat_id'] != '' && $item['message_id'] != null && $item['message_id'] != ''&& $item['token'] != null && $item['token'] != ''){
$deleteMessage = ProjectUtilsController::requestToBot($item['token'], 'deleteMessage', ['chat_id' => $item['chat_id'], 'message_id' => $item['message_id']]);
$deleteData = array();
if(ProjectUtilsController::isJSON($deleteMessage) === true){
$deleteData = json_decode($deleteMessage, true);
}
if(count($deleteData) > 0){
$log_message = $this->getDoctrine()->getRepository(LogMessage::class)->findOneBy(array('id' => $item['id']));
if($log_message){
if(isset($deleteData['ok'])){
if($deleteData['ok'] === true){
$log_message->setIsDeleted(1);
$log_message->setResponse($deleteMessage);
} else {
$log_message->setResponse($deleteMessage);
}
$em->persist($log_message);
$em->flush();
}
}
}
}
}
}
}
private function isValidDate($date) {
if (preg_match("/^(\d{2}).(\d{2}).(\d{4})$/", $date, $matches)) {
if (checkdate($matches[2], $matches[1], $matches[3])) {
return true;
}
}
return false;
}
private function isValidDateTime($dateTime) {
if (preg_match("/^(\d{2}).(\d{2}).(\d{4}) ([01][0-9]|2[0-3]):([0-5][0-9])$/", $dateTime, $matches)) {
if (checkdate($matches[2], $matches[1], $matches[3])) {
return true;
}
}
return false;
}
private function isValidDateTimeOrig($dateTime) {
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)) {
if (checkdate($matches[2], $matches[3], $matches[1])) {
return true;
}
}
return false;
}
private function report($token, $chat_id, $group_id, $cq_data = array(), $curClient = false, $text = null, $message_id = null) {
$is_group_chat = $this->kernel->getContainer()->getParameter('app.chat.is_group');
$basePath = $this->getParameter('kernel.project_dir');
$fileDir = '/public/images/';
$action = null;
$p_group = null;
$keyboard = array();
$em = $this->getDoctrine()->getManager();
if(count($cq_data) > 0){
$action = (isset($cq_data['action']) ? $cq_data['action'] : null);
$p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
}
$expected = null;
if($curClient){
$data_expected = $this->dataExpected($curClient->getExpected());
if(isset($data_expected['value'])){
$expected = $data_expected['value'];
}
if(isset($data_expected['group'])){
$p_group = $data_expected['group'];
}
}
if($action == 'delete'){
$groupObj = false;
if($p_group != null && $p_group != '') {
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
if($groupObj){
$mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
if($mes_id != '' && $mes_id != null){
$deleteMessage = ProjectUtilsController::requestToBot($token, 'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
}
if(file_exists($basePath . '/var/log/' . $groupObj->getChatId() . '-' . $groupObj->getId() . '.txt')){
$mes_id = file_get_contents($basePath . '/var/log/' . $groupObj->getChatId() . '-' . $groupObj->getId() . '.txt');
if($mes_id != '' && $mes_id != null){
$deleteMessage = ProjectUtilsController::requestToBot($token, 'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
$resp = json_decode($deleteMessage, true);
if(isset($resp['result'])){
if($resp['result'] == true){
unlink($basePath . '/var/log/' . $groupObj->getChatId() . '-' . $groupObj->getId() . '.txt');
}
}
}
}
}
exit();
}
if(count($cq_data) > 0 && $action != 'menu'){
if($action == 'all_report'){
if(!$curClient){
$curClient = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
}
$groupObj = false;
if($p_group != null && $p_group != '') {
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
$transactions_q = $this->getDoctrine()
->getRepository(Transaction::class)
->createQueryBuilder('tr')
->select('tr.id')
->where('tr.amount != 0')
;
if($groupObj){
$transactions_q->andWhere('tr.from_group = ' . $groupObj->getId() . ' OR tr.to_group = ' . $groupObj->getId());
}
$transactions = $transactions_q->getQuery()->getArrayResult();
$count_trs = count($transactions);
if($count_trs > 0){
$newReport = new Report();
$newReport->setClient(($curClient ? $curClient : null));
$newReport->setPath(null);
$newReport->setDateWith(null);
$newReport->setDateBy(null);
$newReport->setIsSend(0);
$newReport->setDate(new \DateTime(date("Y-m-d H:i:s")));
$newReport->setClientGroup(($groupObj ? $groupObj : null));
$em->persist($newReport);
$em->flush();
$file = $this->genReport($newReport);
if($file != '' && $file != null){
$email = $curClient->getEmail();
if($email != null && $email != ''){
$body_mail = array(
'#app#' => $this->getParameter('app.name'),
'#logo#' => $this->getParameter('app.logo')
);
$title_mail = array();
$attach = array();
$filepath = $basePath . $fileDir . $file;
if(file_exists($filepath)){
$attach[] = $basePath . $fileDir . $file;
}
//отправка письма
//$email = 'igor@atmapro.ru';
$sendMail = $this->sendEmail($this->mailer,'newReportAll', $body_mail, $title_mail, 'ru', $email, $attach);
$newReport->setIsSend(1);
}
$newReport->setPath($file);
$em->persist($newReport);
$em->flush();
$this->resetExpected($curClient);
$arr_f = explode('/', $file);
$file_name = '';
if(count($arr_f) == 2){
$file_name = $arr_f[1];
}
$link_file = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . '/images/' . $file;
$reply = 'Файл отчета' . ($file_name != '' ? ' ' . $file_name : '') . ' успешно сформирован и отправлен на почту ' . $email . '. Также доступен для скачивания по ссылке ' . $link_file;
//$reply = 'Файл отчета успешно сформирован ' . $file;
} else {
$reply = 'Не удалось сформировать файл отчета, попробуйте позже.';
$this->resetExpected($curClient);
}
} else {
$reply = 'Не удалось сформировать отчет, пока нет ни одной финансовой операции.';
$this->resetExpected($curClient);
}
}
} elseif($expected != '' && $expected != null){
if($curClient && $text != '' && $text != null){
$groupObj = false;
if($group_id != null && $group_id != ''){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
} elseif($p_group != null && $p_group != '') {
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
if($is_group_chat === true && $groupObj){
$chat_id = $groupObj->getChatId();
}
$date_with = null;
$date_by = null;
$is_valid_with = false;
$is_valid_by = false;
if($groupObj && $curClient){
if (strpos($text, '-') !== false) {
$d = explode('-', trim($text));
if(count($d) == 2){
if($this->isValidDate(trim($d[0])) || $this->isValidDateTime(trim($d[0]))){
$date_with = date("Y-m-d H:i:s", strtotime(trim($d[0])));
$is_valid_with = true;
}
if($this->isValidDate(trim($d[1])) || $this->isValidDateTime(trim($d[1]))){
$date_by = date("Y-m-d H:i:s", strtotime(trim($d[1])));
$is_valid_by = true;
}
}
}
if($is_valid_with === true && $is_valid_by === true){
$transactions_q = $this->getDoctrine()
->getRepository(Transaction::class)
->createQueryBuilder('tr')
->select('tr.id')
->where('tr.amount != 0')
;
if($date_with != '' && $date_with != null){
$transactions_q->andWhere('tr.date >= :date_with')
->setParameter('date_with', $date_with);
}
if($date_by != '' && $date_by != null){
$transactions_q->andWhere('tr.date <= :date_by')
->setParameter('date_by', $date_by);
}
if($groupObj){
$transactions_q->andWhere('tr.from_group = ' . $groupObj->getId() . ' OR tr.to_group = ' . $groupObj->getId());
}
$transactions = $transactions_q->getQuery()->getArrayResult();
$count_trs = count($transactions);
if($count_trs > 0){
$newReport = new Report();
$newReport->setClient(($curClient ? $curClient : null));
$newReport->setPath(null);
$newReport->setDateWith(new \DateTime($date_with));
$newReport->setDateBy(new \DateTime($date_by));
$newReport->setIsSend(0);
$newReport->setDate(new \DateTime(date("Y-m-d H:i:s")));
$newReport->setClientGroup($groupObj);
$em->persist($newReport);
$em->flush();
$file = $this->genReport($newReport);
if($file != '' && $file != null){
$email = $curClient->getEmail();
if($email != null && $email != ''){
$body_mail = array(
'#app#' => $this->getParameter('app.name'),
'#logo#' => $this->getParameter('app.logo'),
'#date_with#' => date("d.m.Y H:i", strtotime($date_with)),
'#date_by#' => date("d.m.Y H:i", strtotime($date_by)),
);
$title_mail = array();
$attach = array();
$filepath = $basePath . $fileDir . $file;
if(file_exists($filepath)){
$attach[] = $basePath . $fileDir . $file;
}
//отправка письма
//$email = 'igor@atmapro.ru';
$sendMail = $this->sendEmail($this->mailer,'newReportPeriod', $body_mail, $title_mail, 'ru', $email, $attach);
$newReport->setIsSend(1);
}
$newReport->setPath($file);
$em->persist($newReport);
$em->flush();
$this->resetExpected($curClient);
$arr_f = explode('/', $file);
$file_name = '';
if(count($arr_f) == 2){
$file_name = $arr_f[1];
}
$link_file = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . '/images/' . $file;
$reply = 'Файл отчета' . ($file_name != '' ? ' ' . $file_name : '') . ' успешно сформирован и отправлен на почту ' . $email . '. Также доступен для скачивания по ссылке ' . $link_file;
} else {
$reply = 'Не удалось сформировать файл отчета, попробуйте позже.';
$this->resetExpected($curClient);
}
} else {
$reply = 'Финансовых операций за данный период не найдено, пропробуйте повторить команду и указать другой период.';
$this->resetExpected($curClient);
}
} else {
$reply = 'Введен период в неправильном формате, введите период для формирования отчета, в формате: 01.04.2022-10.04.2022';
}
}
}
} else {
$groupObj = false;
if($group_id != null && $group_id != ''){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
} elseif($p_group != null && $p_group != '') {
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
if($is_group_chat === true && $groupObj){
$chat_id = $groupObj->getChatId();
}
$reply = 'Введите период для формирования отчета для финансовых операций. В формате: 01.04.2022-10.04.2022';
$keyboard = array(
array(
array(
'text'=>'Сформировать за все время',
'callback_data'=> json_encode(array('action' => "all_report", 'command' => "report", "group" => ($groupObj ? $groupObj->getId() : null)))
)
),
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "delete", 'command' => "report", 'mes_id' => $message_id, "group" => ($groupObj ? $groupObj->getId() : null)))
)
)
);
$this->addExpected(($is_group_chat === true && $groupObj ? $groupObj : $curClient), array("value" => "period_report", "group" => ($groupObj ? $groupObj->getId() : null)));
}
$sendMessage = false;
if(count($keyboard) > 0){
$reply_markup = ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
$resp = json_decode($sendMessage, true);
if(isset($resp['result']['message_id']) && $groupObj){
file_put_contents($basePath . '/var/log/' . $chat_id . '-' . $groupObj->getId() . '.txt', $resp['result']['message_id']);
}
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
if($is_group_chat === true){
$bot = $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
$command = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'report'));
$this->addLogMessageBot($bot, $command, $sendMessage);
}
}
private function mainMenu($client, $is_group_chat = true, $type_group = null)
{
$role_id = null;
if($client){
if($client->getRole()){
$role_id = $client->getRole()->getId();
}
}
$main_menu = '';
$commands = $this->getDoctrine()->getRepository(Command::class)->findAll();
if(count($commands) > 0){
foreach ($commands as $command){
if($command->getIsActive() === true){
if($role_id != '' && $role_id != null){
if(count($command->getRoles())){
foreach ($command->getRoles() as $role){
if($role_id == $role->getId() && $command->getTypeof() != 'start'){
if((($is_group_chat === true) || ($is_group_chat === false && ($command->getTypeof() == 'help' || $command->getTypeof() == 'init')))){
if(!($type_group == 'salary' && $command->getTypeof() == 'bpay')){
$main_menu .= $command->getName() . ' - ' . $command->getDescription() . "\n";
}
}
}
}
}
} else {
if(!($type_group == 'salary' && $command->getTypeof() == 'bpay')){
$main_menu .= $command->getName() . ' - ' . $command->getDescription() . "\n";
}
}
}
}
}
return $main_menu;
}
private function dataExpected($expected){
$data = array();
if(ProjectUtilsController::isJSON($expected) === true){
$data = json_decode($expected, true);
}
return $data;
}
private function resetExpected($client){
$em = $this->getDoctrine()->getManager();
$resp = false;
if($client){
if($client->getExpected() != '' && $client->getExpected() != null){
$client->setExpected(null);
$em->persist($client);
$em->flush();
$resp = true;
}
}
return $resp;
}
private function addExpected($client, $expected){
$em = $this->getDoctrine()->getManager();
$resp = false;
if($client){
$client->setExpected(json_encode($expected));
$em->persist($client);
$em->flush();
$resp = true;
}
return $resp;
}
private function balance($token, $chat_id, $group_id, $curClient = false) {
$is_group_chat = $this->getParameter('app.chat.is_group');
if(!$curClient && $chat_id != '' && $chat_id != null){
$curClient = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
}
$groupObj = false;
if($group_id != null && $group_id != ''){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
}
$is_delete = false;
$group_chat_id = null;
if($curClient && $groupObj){
$group_chat_id = $groupObj->getChatId();
$role = null;
if($curClient->getRole()){
$role = $curClient->getRole()->getTypeof();
}
$type_group = null;
if($groupObj->getTypeGroup()){
$type_group = $groupObj->getTypeGroup()->getTypeof();
}
if(is_numeric($groupObj->getBalance())){
$opt = "";
if($groupObj->getBalance() > 0){
$opt = "+";
}
$balance = $opt . str_replace(',00', '', number_format(($groupObj->getBalance() / 100), 2, ',', ' '));
/*
if($role == 'director'){
if($type_group == 'cash'){
$reply = 'Баланс ' . $balance;
} else {
$reply = 'Нет доступа к балансу этой группы';
}
} else
*/
if($role == 'auditor' || $role == 'director' || $role == 'accountant'){
$reply = 'Баланс ' . $balance;
} elseif($role == 'employee'){
if($type_group == 'salary'){
$reply = 'Баланс ' . $balance;
} else {
$is_delete = true;
$reply = 'Нет доступа к балансу этой группы.';
}
}
} else {
$is_delete = true;
$reply = 'Ошибочное значение баланса.';
}
} else {
$is_delete = true;
$reply = 'Невозможно получить информацию по балансу, убедитесь, что отправляете команду в группе.';
}
$sendMessage = null;
if($group_chat_id != '' && $group_chat_id != null){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $group_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
if($is_group_chat === true){
$bot = $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
$command = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'balance'));
if($is_delete === true){
$this->addLogMessageBot($bot, $command, $sendMessage);
}
}
}
private function curCommandPermissions($user, $typeCommand = 'pay'){
$list = [];
if($user && $user->getRole() !== null){
$role = $user->getRole();
if(count($role->getCommandPermissions()) > 0){
foreach ($role->getCommandPermissions() as $commandPermission){
if($commandPermission->getCommand() != null){
if($commandPermission->getCommand()->getTypeof() == $typeCommand && $commandPermission->getIsActive()){
$list[] = $commandPermission->getTypeof();
}
}
}
}
}
return $list;
}
private function pay($token, $chat_id, $group_id, $cq_data = array(), $curClient = false, $text = null, $message_id = null, $file_id = null) {
$is_group_chat = $this->kernel->getContainer()->getParameter('app.chat.is_group');
$basePath = $this->getParameter('kernel.project_dir');
$create_transaction = false;
$action = null;
$p_group = null;
$keyboard = array();
$em = $this->getDoctrine()->getManager();
if(count($cq_data) > 0){
$action = (isset($cq_data['action']) ? $cq_data['action'] : null);
$p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
}
$expected = null;
$ss_id = null;
if($curClient){
$data_expected = $this->dataExpected($curClient->getExpected());
if(isset($data_expected['value'])){
$expected = $data_expected['value'];
}
if(isset($data_expected['group'])){
$p_group = $data_expected['group'];
}
if(isset($data_expected['ss_id'])){
$ss_id = $data_expected['ss_id'];
}
}
$editMessageId = null;
if(count($cq_data) > 0 && $action != 'menu'){
$name_group = '';
$groupObj = false;
if($group_id != null && $group_id != ''){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
} elseif($p_group != null && $p_group != '') {
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
if($action == 'delete' && $groupObj){
$mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
if($mes_id != '' && $mes_id != null){
$deleteMessage = ProjectUtilsController::requestToBot($token, 'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
}
if(file_exists($basePath . '/var/log/' . $groupObj->getChatId() . '-' . $groupObj->getId() . '.txt')){
$mes_id = file_get_contents($basePath . '/var/log/' . $groupObj->getChatId() . '-' . $groupObj->getId() . '.txt');
if($mes_id != '' && $mes_id != null){
$deleteMessage = ProjectUtilsController::requestToBot($token, 'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
$resp = json_decode($deleteMessage, true);
if(isset($resp['result'])){
if($resp['result'] == true){
unlink($basePath . '/var/log/' . $groupObj->getChatId() . '-' . $groupObj->getId() . '.txt');
}
}
}
}
exit();
}
$clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
if($groupObj && $clientObj){
$name_group = $groupObj->nameClient();
$type_group_typeof = null;
if($groupObj->getTypeGroup()){
$type_group_typeof = $groupObj->getTypeGroup()->getTypeof();
}
if($is_group_chat === true){
$chat_id = $groupObj->getChatId();
}
if($type_group_typeof != null && $type_group_typeof != ''){
if($type_group_typeof == 'cash'){
if($action == 'income'){
$commandPermissions = $this->curCommandPermissions($clientObj, 'pay');
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Выбрано «Приход». ' . 'Выберите откуда осуществляется приход.';
// $keyboard = array(
// array(
// array(
// 'text'=>'По Объекту',
// 'callback_data'=> json_encode(array('action' => "income_partner", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
// )
// ),
// array(
// array(
// 'text'=>'Перевод Нал-Нал',
// 'callback_data'=> json_encode(array('action' => "income_group", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
// ),
// ),
// array(
// array(
// 'text'=>'Перевод ЗП-Нал',
// 'callback_data'=> json_encode(array('action' => "income_group_salary", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
// ),
// ),
// array(
// array(
// 'text'=>'Назад',
// 'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
// ),
// )
// );
$keyboard = [];
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('cash_pay_income_office', $commandPermissions))){
//Приход -> По Объекту
$keyboard[] = [[
'text'=>'По Объекту',
'callback_data'=> json_encode(array('action' => "income_partner", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
]];
}
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('cash_pay_income_transfer_cash_to_cash', $commandPermissions))){
//Приход -> Превод Нал-Нал
$keyboard[] = [[
'text'=>'Перевод Нал-Нал',
'callback_data'=> json_encode(array('action' => "income_group", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
]];
}
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('cash_pay_income_transfer_salary_to_cash', $commandPermissions))){
//Приход -> Превод ЗП-Нал
$keyboard[] = [[
'text'=>'Перевод ЗП-Нал',
'callback_data'=> json_encode(array('action' => "income_group_salary", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
]];
}
$keyboard[] = [[
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
]];
} elseif($action == 'income_group'){
$clients_q = $this->getDoctrine()
->getRepository(Client::class)
->createQueryBuilder('cl')
->select('cl.id, cl.first_name, cl.last_name, cl.username')
->innerJoin(TypeGroup::class, 'tg', 'WITH', 'cl.type_group = tg.id AND tg.typeof = :typeof_group')
->where('cl.typeof != :typeof')
->andWhere('cl.is_active = 1')
->setParameter('typeof', "private")
->setParameter('typeof_group', "cash")
;
if($groupObj){
$clients_q->andWhere('cl.id != ' . $groupObj->getId());
}
$clients = $clients_q->getQuery()->getArrayResult();
if(count($clients) > 0){
$buttons = array();
foreach ($clients as $item_client){
$name_client = $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
$buttons[][] = array(
'text' => $name_client,
'callback_data'=> json_encode(array("action" => "add_cgroup", 'command' => "pay", 'id' => $item_client['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text' => 'Назад',
'callback_data'=> json_encode(array("action" => "income", 'command' => "pay", "group" => $p_group))
);
$keyboard = $buttons;
$reply = 'Выбрано «Перевод Нал-Нал». ' . 'Выберите группу из которой будет списание средств.';
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
$newDraft->setTypeof('expense');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setToGroup($groupObj);
$newDraft->setExpected('cgroup');
$newDraft->setNote('Перевод Нал-Нал');
$newDraft->setTypeTransaction('transfer');
$em->persist($newDraft);
$em->flush();
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
}
} elseif($action == 'income_group_salary'){
$clients_q = $this->getDoctrine()
->getRepository(Client::class)
->createQueryBuilder('cl')
->select('cl.id, cl.first_name, cl.last_name, cl.username')
->innerJoin(TypeGroup::class, 'tg', 'WITH', 'cl.type_group = tg.id AND tg.typeof = :typeof_group')
->where('cl.typeof != :typeof')
->andWhere('cl.is_active = 1')
->setParameter('typeof', "private")
->setParameter('typeof_group', "salary")
;
if($groupObj){
$clients_q->andWhere('cl.id != ' . $groupObj->getId());
}
$clients = $clients_q->getQuery()->getArrayResult();
if(count($clients) > 0){
$buttons = array();
foreach ($clients as $item_client){
$name_client = $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
$buttons[][] = array(
'text' => $name_client,
'callback_data'=> json_encode(array("action" => "add_cgroup", 'command' => "pay", 'id' => $item_client['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text' => 'Назад',
'callback_data'=> json_encode(array("action" => "income", 'command' => "pay", "group" => $p_group))
);
$keyboard = $buttons;
$reply = 'Выбрано «Перевод ЗП-Нал». ' . 'Выберите группу из которой будет списание средств.';
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
$newDraft->setTypeof('expense');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setToGroup($groupObj);
$newDraft->setExpected('cgroup');
$newDraft->setNote('Перевод ЗП-Нал');
$newDraft->setTypeTransaction('transfer');
$em->persist($newDraft);
$em->flush();
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
}
} elseif($action == 'add_cgroup'){
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
$from_client = false;
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$from_client = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
}
}
if($draftObj && $from_client){
$from_group_typeof = ($from_client->getTypeGroup() != '' && $from_client->getTypeGroup() != null ? $from_client->getTypeGroup() : 'cash');
$groupObj = false;
if($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
$draftObj->setFromGroup($from_client);
$draftObj->setExpected('amount');
$em->persist($draftObj);
$em->flush();
$this->addExpected(($groupObj && $is_group_chat === true ? $groupObj : $clientObj), array("value" => "amount", "group" => $p_group));
$reply = 'Выбрано «Группа ' . ($from_client ? $from_client->nameClient() : '') . ' для списания с баланса». ' . 'Введите сумму.';
if($from_group_typeof != 'salary'){
$buttons[][] = array(
'text' => 'Назад',
'callback_data'=> json_encode(array("action" => "income_group", 'command' => "pay", "group" => $p_group))
);
} else {
$buttons[][] = array(
'text' => 'Назад',
'callback_data'=> json_encode(array("action" => "income_group_salary", 'command' => "pay", "group" => $p_group))
);
}
$keyboard = $buttons;
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
}
} elseif($action == 'income_partner' || $action == 'add_client' || $action == 'other'){
//step 1
$offices = $this->getDoctrine()
->getRepository(Office::class)
->createQueryBuilder('o')
->select('o.id, o.name, o.number')
->where('o.is_active = 1')
->getQuery()
->getArrayResult();
if(count($offices) > 0){
if($action == 'income_partner'){
$reply = 'Выбрано «По Объекту». ' . 'Выберите объект, по которому осуществляется приход.';
} elseif($action == 'other'){
$reply = 'Выбрано «Расходы по Объекту». ' . 'Выберите объект, по которому осуществляется расход.';
}
$buttons = array();
foreach ($offices as $item_office){
$buttons[][] = array(
'text' => ($item_office['number'] != '' && $item_office['number'] != null ? $item_office['number'] . '. ' : '') . $item_office['name'],
'callback_data'=> json_encode(array("action" => "add_office", 'command' => "pay", 'id' => $item_office['id'], "group" => $p_group))
);
}
if($action == 'income_partner'){
$buttons[][] = array(
'text' => 'Назад',
'callback_data'=> json_encode(array("action" => "income", 'command' => "pay", "group" => $p_group))
);
} elseif($action == 'other'){
$buttons[][] = array(
'text' => 'Назад',
'callback_data'=> json_encode(array("action" => "expense", 'command' => "pay", "group" => $p_group))
);
} elseif($action == 'add_client'){
$buttons[][] = array(
'text' => 'Назад',
'callback_data'=> json_encode(array("action" => "salary", 'command' => "pay", "group" => $p_group))
);
}
$keyboard = $buttons;
if($action == 'income_partner'){
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
$newDraft->setTypeof('income');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setToGroup($groupObj);
$newDraft->setExpected('office');
$newDraft->setNote('Поступление средств');
$newDraft->setTypeTransaction('income');
$em->persist($newDraft);
$em->flush();
} elseif($action == 'add_client' || $action == 'other'){
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
$to_client = false;
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$to_client = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
}
}
if($draftObj){
if($action == 'other'){
$draftObj->setNote('Списание средств');
$draftObj->setTypeTransaction('expense_office');
$draftObj->setExpected('amount');
}
if($to_client){
$draftObj->setToGroup($to_client);
$draftObj->setExpected('office');
if($action == 'add_client'){
$name_salary_client = $to_client->nameClient();
$reply = 'Выбрано «Группа ' . $name_salary_client . ' для выплаты зарплаты». ' . 'Выберите объект, по которому выплачивается зарплата.';
}
}
$em->persist($draftObj);
$em->flush();
}
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
}
} elseif($action == 'expense'){
//step 1
$commandPermissions = $this->curCommandPermissions($clientObj, 'pay');
$reply = 'Выбрано «Расход». ' . 'Выберите тип расхода.';
// $keyboard = array(
// array(
// array(
// 'text'=>'Перевод Нал-ЗП',
// 'callback_data'=> json_encode(array('action' => "salary", 'command' => "pay", "group" => $p_group))
// )
// ),
// array(
// array(
// 'text'=>'Перевод Нал-Нал',
// 'callback_data'=> json_encode(array('action' => "transfer", 'command' => "pay", "group" => $p_group))
// ),
// ),
// array(
// array(
// 'text'=>'Расходы по Объекту',
// 'callback_data'=> json_encode(array('action' => "other", 'command' => "pay", "group" => $p_group))
// ),
// ),
//// array(
//// array(
//// 'text'=>'Расходы на компанию',
//// 'callback_data'=> json_encode(array('action' => "company", 'command' => "pay", "group" => $p_group))
//// ),
//// ),
// array(
// array(
// 'text'=>'Назад',
// 'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => $p_group))
// ),
// )
// );
$keyboard = [];
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('cash_pay_expense_transfer_cash_to_salary', $commandPermissions))){
//Расход -> Превод Нал-ЗП
$keyboard[] = [[
'text'=>'Перевод Нал-ЗП',
'callback_data'=> json_encode(array('action' => "salary", 'command' => "pay", "group" => $p_group))
]];
}
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('cash_pay_expense_transfer_cash_to_cash', $commandPermissions))){
//Расход -> Превод Нал-Нал
$keyboard[] = [[
'text'=>'Перевод Нал-Нал',
'callback_data'=> json_encode(array('action' => "transfer", 'command' => "pay", "group" => $p_group))
]];
}
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('cash_pay_expense_office', $commandPermissions))){
//Расход -> Расходы по Объекту
$keyboard[] = [[
'text'=>'Расходы по Объекту',
'callback_data'=> json_encode(array('action' => "other", 'command' => "pay", "group" => $p_group))
]];
}
// $keyboard[] = [[
// 'text'=>'Расходы на компанию',
// 'callback_data'=> json_encode(array('action' => "company", 'command' => "pay", "group" => $p_group))
// ]];
$keyboard[] = [[
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => $p_group))
]];
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
$newDraft->setTypeof('expense');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setFromGroup($groupObj);
$newDraft->setExpected('type_expense');
$em->persist($newDraft);
$em->flush();
} elseif($action == 'add_office' || $action == 'add_director'){
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
$officeObj = false;
$directorObj = false;
if($action == 'add_office'){
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$officeObj = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
}
}
if($officeObj){
$draftObj->setOffice($officeObj);
}
} elseif($action == 'add_director'){
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$directorObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
}
}
if($directorObj){
$draftObj->setToGroup($directorObj);
}
}
$selected = '';
if($action == 'add_office' && $officeObj){
$selected = 'Выбрано «Объект ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null ? $officeObj->getNumber() . '. ' : '') . $officeObj->getName() . '». ';
} elseif($action == 'add_director' && $directorObj){
$name_director = $directorObj->nameClient();
$selected = 'Выбрано «Руководитель' . ($name_director != '' && $name_director != null ? ' ' . $name_director : '') . '». ';
}
if($draftObj){
$draftObj->setExpected('amount');
$em->persist($draftObj);
$em->flush();
$this->addExpected(($is_group_chat === true && $groupObj ? $groupObj : $clientObj), array("value" => "amount", "group" => $p_group));
$reply = $selected . 'Введите сумму';
// if($action == 'add_office'){
// $keyboard = array(
// array(
// array(
// 'text'=>'Назад',
// 'callback_data'=> json_encode(array('action' => "other", 'command' => "pay", "group" => $p_group))
// ),
// )
// );
// } else {
// $keyboard = array(
// array(
// array(
// 'text'=>'Назад',
// 'callback_data'=> json_encode(array('action' => "income_partner", 'command' => "pay", "group" => $p_group))
// ),
// )
// );
// }
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
}
} elseif($action == 'salary'){
$clients_q = $this->getDoctrine()
->getRepository(Client::class)
->createQueryBuilder('cl')
->select('cl.id, cl.first_name, cl.last_name, cl.username')
->innerJoin(TypeGroup::class, 'tg', 'WITH', 'cl.type_group = tg.id AND tg.typeof = :typeof_group')
->where('cl.typeof != :typeof')
->andWhere('cl.is_active = 1')
->setParameter('typeof', "private")
->setParameter('typeof_group', "salary")
;
if($groupObj){
$clients_q->andWhere('cl.id != ' . $groupObj->getId());
}
$clients = $clients_q->getQuery()->getArrayResult();
if(count($clients) > 0){
$buttons = array();
foreach ($clients as $item_client){
$name_client = $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
$buttons[][] = array(
'text' => $name_client,
'callback_data'=> json_encode(array("action" => "add_client", 'command' => "pay", 'id' => $item_client['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "expense", 'command' => "pay", "group" => $p_group))
);
$keyboard = $buttons;
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftObj){
$draftObj->setNote('Перевод Нал-ЗП');
$draftObj->setTypeTransaction('add_salary');
$draftObj->setExpected('to_group');
$em->persist($draftObj);
$em->flush();
$reply = 'Выбрано «Перевод Нал-ЗП». ' . 'Выберите группу, которой будет осуществлен перевод.';
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
$keyboard = array();
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
}
} elseif($action == 'transfer'){
$clients_q = $this->getDoctrine()
->getRepository(Client::class)
->createQueryBuilder('cl')
->select('cl.id, cl.first_name, cl.last_name, cl.username')
->innerJoin(TypeGroup::class, 'tg', 'WITH', 'cl.type_group = tg.id AND tg.typeof = :typeof_group')
->where('cl.typeof != :typeof')
->andWhere('cl.is_active = 1')
->setParameter('typeof', "private")
->setParameter('typeof_group', "cash")
;
if($groupObj){
$clients_q->andWhere('cl.id != ' . $groupObj->getId());
}
$clients = $clients_q->getQuery()->getArrayResult();
if(count($clients) > 0){
$buttons = array();
foreach ($clients as $item_client){
$name_client = $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
$buttons[][] = array(
'text' => $name_client,
'callback_data'=> json_encode(array("action" => "add_director", 'command' => "pay", 'id' => $item_client['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "expense", 'command' => "pay", "group" => $p_group))
);
$keyboard = $buttons;
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftObj){
$draftObj->setNote('Перевод Нал-Нал');
$draftObj->setTypeTransaction('transfer');
$draftObj->setExpected('to_group');
$em->persist($draftObj);
$em->flush();
$reply = 'Выбрано «Перевод Нал-Нал». ' . 'Выберите группу для перевода';
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
$keyboard = array();
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
}
} elseif($action == 'company'){
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
$newDraft->setTypeof('expense');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setFromGroup($groupObj);
$newDraft->setExpected('amount');
$newDraft->setNote('Списание средств на компанию');
$newDraft->setTypeTransaction('expense_company');
$em->persist($newDraft);
$em->flush();
$this->addExpected(($is_group_chat === true && $groupObj ? $groupObj : $clientObj), array("value" => "amount", "group" => $p_group));
$reply = 'Выбрано «Расходы на компанию». ' . 'Введите сумму.';
} elseif($action == 'no_cheque' || $action == 'finish_pay'){
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
$draftObj->setExpected('finish');
$em->persist($draftObj);
$em->flush();
$this->resetExpected($curClient);
$create_transaction = $this->createTransaction($token, $chat_id, $groupObj, $draftObj);
if($create_transaction === true){
$em->remove($draftObj);
$em->flush();
}
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Транзакция успешно добавлена.';
}
} elseif($type_group_typeof == 'salary'){
if($action == 'income'){
$offices = $this->getDoctrine()
->getRepository(Office::class)
->createQueryBuilder('o')
->select('o.id, o.name, o.number')
->where('o.is_active = 1')
->getQuery()
->getArrayResult();
if(count($offices) > 0){
$reply = 'Выбрано «Перевод в группу ЗП». ' . 'Выберите объект, по которому осуществляется выплата зарплаты.';
$buttons = array();
foreach ($offices as $item_office){
$buttons[][] = array(
'text' => ($item_office['number'] != '' && $item_office['number'] != null ? $item_office['number'] . '. ' : '') . $item_office['name'],
'callback_data'=> json_encode(array("action" => "add_office", 'command' => "pay", 'id' => $item_office['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "delete", 'command' => "pay", "group" => $p_group))
);
$keyboard = $buttons;
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
$newDraft->setTypeof('expense');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setToGroup($groupObj);
$newDraft->setExpected('office');
$newDraft->setNote('Перевод в группу ЗП');
$newDraft->setTypeTransaction('add_salary');
$em->persist($newDraft);
$em->flush();
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
}
} elseif($action == 'income_cash'){
$offices = $this->getDoctrine()
->getRepository(Office::class)
->createQueryBuilder('o')
->select('o.id, o.name, o.number')
->where('o.is_active = 1')
->getQuery()
->getArrayResult();
if(count($offices) > 0){
$reply = 'Выбрано «Перевод в группу Нал». ' . 'Выберите объект, по которому осуществляется выплата зарплаты.';
$buttons = array();
foreach ($offices as $item_office){
$buttons[][] = array(
'text' => ($item_office['number'] != '' && $item_office['number'] != null ? $item_office['number'] . '. ' : '') . $item_office['name'],
'callback_data'=> json_encode(array("action" => "add_office", 'command' => "pay", 'id' => $item_office['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "delete", 'command' => "pay", "group" => $p_group))
);
$keyboard = $buttons;
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
// $newDraft->setTypeof('expense');
$newDraft->setTypeof('income');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setToGroup($groupObj);
$newDraft->setExpected('office');
$newDraft->setNote('Перевод в группу Нал');
$newDraft->setTypeTransaction('add_salary_cash');
$em->persist($newDraft);
$em->flush();
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
}
} elseif($action == 'add_office'){
$clients_q = $this->getDoctrine()
->getRepository(Client::class)
->createQueryBuilder('cl')
->select('cl.id, cl.first_name, cl.last_name, cl.username')
->innerJoin(TypeGroup::class, 'tg', 'WITH', 'cl.type_group = tg.id AND tg.typeof = :typeof_group')
->where('cl.typeof != :typeof')
->andWhere('cl.is_active = 1')
->setParameter('typeof', "private")
->setParameter('typeof_group', "cash")
;
$clients = $clients_q->getQuery()->getArrayResult();
if(count($clients) > 0){
$buttons = array();
foreach ($clients as $item_client){
$name_client = $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
$buttons[][] = array(
'text' => $name_client,
'callback_data'=> json_encode(array("action" => "add_client", 'command' => "pay", 'id' => $item_client['id'], "group" => $p_group))
);
}
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftObj){
$officeObj = false;
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$officeObj = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
}
}
if($officeObj){
$draftObj->setOffice($officeObj);
}
$draftObj->setExpected('from_group');
$em->persist($draftObj);
$em->flush();
if($draftObj->getTypeTransaction() != 'add_salary_cash'){
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "income", 'command' => "pay", "group" => $p_group))
);
$keyboard = $buttons;
$reply = 'Выбрано «Объект' . ($officeObj ? ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null ? $officeObj->getNumber() . '. ' : '') . $officeObj->getName() : '') . '». ' . 'Выберите группу, c которой будут списаны средства.';
} else {
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "income_cash", 'command' => "pay", "group" => $p_group))
);
$keyboard = $buttons;
$reply = 'Выбрано «Объект' . ($officeObj ? ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null ? $officeObj->getNumber() . '. ' : '') . $officeObj->getName() : '') . '». ' . 'Выберите группу, в которую будут переведены средства.';
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
$keyboard = array();
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
}
} elseif($action == 'add_client'){
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
$to_client = false;
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$to_client = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
}
}
if($draftObj && $to_client){
$groupObj = false;
if($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
$draftObj->setFromGroup($to_client);
$draftObj->setExpected('amount');
$em->persist($draftObj);
$em->flush();
$this->addExpected(($groupObj && $is_group_chat === true ? $groupObj : $clientObj), array("value" => "amount", "group" => $p_group));
if($draftObj->getTypeTransaction() != 'add_salary_cash'){
$reply = 'Выбрано «Группа ' . ($to_client ? $to_client->nameClient() : '') . ' для списания средств». ' . 'Введите сумму.';
} else {
$reply = 'Выбрано «Группа ' . ($to_client ? $to_client->nameClient() : '') . ' для перевода средств». ' . 'Введите сумму.';
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
}
} elseif($action == 'expense'){
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
$newDraft->setTypeof('expense');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setToGroup($groupObj);
//$newDraft->setFromGroup($groupObj);
$newDraft->setExpected('add_office_expense');
$newDraft->setNote('Начисление зарплаты');
$newDraft->setTypeTransaction('payment_salary');
$em->persist($newDraft);
$em->flush();
$offices = $this->getDoctrine()
->getRepository(Office::class)
->createQueryBuilder('o')
->select('o.id, o.name, o.number')
->where('o.is_active = 1')
->getQuery()
->getArrayResult();
if(count($offices) > 0){
$reply = 'Выбрано «Начисление зарплаты». ' . 'Выберите объект, по которому осуществляется начисление зарплаты.';
$keyboard = array();
$buttons = array();
foreach ($offices as $item_office){
$buttons[][] = array(
'text' => ($item_office['number'] != '' && $item_office['number'] != null ? $item_office['number'] . '. ' : '') . $item_office['name'],
'callback_data'=> json_encode(array("action" => "add_office_exp", 'command' => "pay", 'id' => $item_office['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => $p_group))
);
$keyboard = $buttons;
} else {
$reply = 'Нет объектов для начисление зарплаты по ним.';
}
/*
$groupObj = false;
if($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
$this->addExpected(($groupObj && $is_group_chat === true ? $groupObj : $clientObj), array("value" => "amount", "group" => $p_group));
$reply = 'Выбрано «Начисление зарплаты». ' . 'Введите сумму';
*/
} elseif($action == 'expense_salary') {
//операция начисление оклада
$salarySchedule = $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
if(count($salarySchedule) > 0){
$max_ss = $this->getParameter('app.max.salary_schedule');
if(count($salarySchedule) < $max_ss){
$reply = 'Выбрано «Начисление оклада». Можете отредактировать условия начисления оклада по нужным числам месяца, добавить новое или удалить лишнее';
$keyboard = array(
array(
array(
'text'=>'Редактировать условие начисления',
'callback_data'=> json_encode(array('action' => "edit_ss_date", 'command' => "pay", "group" => $p_group))
)
),
array(
array(
'text'=>'Новое условие начисления',
'callback_data'=> json_encode(array('action' => "new_ss_date", 'command' => "pay", "group" => $p_group))
)
),
array(
array(
'text'=>'Удалить условие начисления',
'callback_data'=> json_encode(array('action' => "rem_ss_date", 'command' => "pay", "group" => $p_group))
)
),
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => $p_group))
)
)
);
} else {
$reply = 'Выбрано «Начисление оклада». Можете отредактировать условия начисления оклада по нужным числам месяца или удалить лишнее';
$keyboard = array(
array(
array(
'text'=>'Редактировать условие начисления',
'callback_data'=> json_encode(array('action' => "edit_ss_date", 'command' => "pay", "group" => $p_group))
)
),
array(
array(
'text'=>'Удалить условие начисления',
'callback_data'=> json_encode(array('action' => "rem_ss_date", 'command' => "pay", "group" => $p_group))
)
),
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => $p_group))
)
)
);
}
} else {
$reply = 'Выбрано «Начисление оклада». Для начисления оклада по нужным числам месяца необходимо добавить условие начисления';
$keyboard = array(array(
array(
'text'=>'Новое условие начисления',
'callback_data'=> json_encode(array('action' => "new_ss_date", 'command' => "pay", "group" => $p_group))
)
),
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => $p_group))
)
)
);
}
} elseif($action == 'new_ss_date') {
//новое условие начисления оклада
$reply = 'Введите число дня месяца, в который будет осуществляться начисления оклада';
$keyboard = array(
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "expense_salary", 'command' => "pay", "group" => $p_group))
)
)
);
$groupObj = false;
if($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
$this->addExpected(($groupObj && $is_group_chat === true ? $groupObj : $clientObj), array("value" => "new_date", "group" => $p_group));
} elseif($action == 'edit_ss_date') {
//изменить условие начисления оклада
$salarySchedule = $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
if(count($salarySchedule) > 0){
$reply = 'Выберите из списка условие для начисления оклада, которое хотите отредактировать';
$buttons = array();
foreach ($salarySchedule as $item_ss){
$buttons[][] = array(
'text' => $item_ss['day'] . ' числа каждого месяца по ' . $item_ss['amount'] . ' руб',
'callback_data'=> json_encode(array("action" => "edit_ss", 'command' => "pay", 'ss_id' => $item_ss['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "expense_salary", 'command' => "pay", "group" => $p_group))
);
$keyboard = $buttons;
} else {
$reply = 'Условий для начисления оклада не найдено, можете создать новое';
$keyboard = array(array(
array(
'text'=>'Новое условие начисления',
'callback_data'=> json_encode(array('action' => "new_ss_date", 'command' => "pay", "group" => $p_group))
)
),
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => $p_group))
)
)
);
}
} elseif($action == 'rem_ss_date') {
//удалить условие начисления оклада
$salarySchedule = $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
if(count($salarySchedule) > 0){
$reply = 'Выберите из списка условие для начисления оклада, которое хотите удалить';
$buttons = array();
foreach ($salarySchedule as $item_ss){
$buttons[][] = array(
'text' => $item_ss['day'] . ' числа каждого месяца по ' . $item_ss['amount'] . ' руб',
'callback_data'=> json_encode(array("action" => "rem_ss", 'command' => "pay", 'ss_id' => $item_ss['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "expense_salary", 'command' => "pay", "group" => $p_group))
);
$keyboard = $buttons;
} else {
$reply = 'Условий для начисления оклада не найдено, можете создать новое';
$keyboard = array(array(
array(
'text'=>'Новое условие начисления',
'callback_data'=> json_encode(array('action' => "new_ss_date", 'command' => "pay", "group" => $p_group))
)
),
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => $p_group))
)
)
);
}
} elseif($action == 'edit_ss'){
//изменить условие начисления оклада
$id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
$isExistSs = false;
if($id != '' && $id != null){
$salarySchedule = $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
if($salarySchedule){
$isExistSs = true;
$reply = 'Выбрано для редактирования условие для начисления «' . $salarySchedule->getDay() . ' числа каждого месяца по ' . $salarySchedule->getAmount() . ' руб». Выберите, что нужно отредактировать';
$keyboard = array(
array(
array(
'text'=>'Число месяца',
'callback_data'=> json_encode(array('action' => "edit_ss_d", 'command' => "pay", 'ss_id' => $salarySchedule->getId(), "group" => $p_group))
),
array(
'text'=>'Сумму начисления',
'callback_data'=> json_encode(array('action' => "edit_ss_a", 'command' => "pay", 'ss_id' => $salarySchedule->getId(), "group" => $p_group))
)
),
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "edit_ss_date", 'command' => "pay", "group" => $p_group))
)
)
);
}
}
if(!$isExistSs){
$reply = 'Не удалось найти условий для начисления оклада';
$keyboard = array(
array(
array(
'text'=>'В основное меню',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => $p_group))
)
)
);
}
} elseif($action == 'edit_ss_d' || $action == 'edit_ss_a') {
//изменить условие начисления оклада
$id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
$isExistSs = false;
if($id != '' && $id != null){
$salarySchedule = $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
if($salarySchedule){
$isExistSs = true;
if($action == 'edit_ss_d'){
$reply = 'Введите новое число дня месяца для условия начисления оклада «' . $salarySchedule->getDay() . ' числа каждого месяца по ' . $salarySchedule->getAmount() . ' руб»';
$this->addExpected(($is_group_chat === true && $groupObj ? $groupObj : $clientObj), array("value" => "edit_ss_d", "ss_id" => $salarySchedule->getId(), "group" => $p_group));
} else {
$reply = 'Введите новую сумму для условия начисления оклада «' . $salarySchedule->getDay() . ' числа каждого месяца по ' . $salarySchedule->getAmount() . ' руб»';
$this->addExpected(($is_group_chat === true && $groupObj ? $groupObj : $clientObj), array("value" => "edit_ss_a", "ss_id" => $salarySchedule->getId(), "group" => $p_group));
}
}
}
if(!$isExistSs){
$reply = 'Не удалось найти условий для начисления оклада';
$keyboard = array(
array(
array(
'text'=>'В основное меню',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => $p_group))
)
)
);
}
} elseif($action == 'rem_ss'){
//удалить условие начисления оклада
$id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
$isExistSs = false;
if($id != '' && $id != null){
$salarySchedule = $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
if($salarySchedule){
$isExistSs = true;
$reply = 'Условие для начисления оклада «' . $salarySchedule->getDay() . ' числа каждого месяца по ' . $salarySchedule->getAmount() . ' руб» успешно удалено';
$em->remove($salarySchedule);
$em->flush();
$keyboard = array(
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "rem_ss_date", 'command' => "pay", "group" => $p_group))
)
),
array(
array(
'text'=>'В основное меню',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => $p_group))
)
)
);
}
}
if(!$isExistSs){
$reply = 'Не удалось найти условий для начисления оклада';
$keyboard = array(
array(
array(
'text'=>'В основное меню',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => $p_group))
)
)
);
}
} elseif($action == 'add_office_exp'){
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftObj){
$officeObj = false;
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$officeObj = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
}
}
if($officeObj){
$draftObj->setOffice($officeObj);
}
$draftObj->setExpected('amount');
$em->persist($draftObj);
$em->flush();
$reply = 'Выбрано «Объект' . ($officeObj ? ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null ? $officeObj->getNumber() . '. ' : '') . $officeObj->getName() : '') . ' для начисления зарплаты». ' . 'Введите сумму.';
$groupObj = false;
if($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
$this->addExpected(($groupObj && $is_group_chat === true ? $groupObj : $clientObj), array("value" => "amount", "group" => $p_group));
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
$keyboard = array();
}
}
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно продолжить добавление финансовой операции, у данной группы не выбран тип группы. Пожалуйста укажите тип группы данной группе и начните добавление операции занова.';
}
} else {
$reply = 'Финансовые операции начинаются из группы, пожалуйста отправьте команду для начала операции в нужной группе.';
}
} elseif($expected != '' && $expected != null){
$curClientObj = false;
if($is_group_chat === true){
$curClientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
}
if($curClient && (($text != '' && $text != null) || ($file_id != '' && $file_id != null))){
$groupObj = false;
if($group_id != null && $group_id != ''){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
} elseif($p_group != null && $p_group != '') {
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
if($groupObj && $curClient){
$name_group = $groupObj->nameClient();
$type_group_typeof = null;
if($groupObj->getTypeGroup()){
$type_group_typeof = $groupObj->getTypeGroup()->getTypeof();
}
if($is_group_chat === true && $groupObj){
$chat_id = $groupObj->getChatId();
}
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => ($curClientObj ? $curClientObj->getId() : $curClient->getId()), 'client_group' => $groupObj));
if($draftObj){
if($expected == 'amount'){
$amount = (float) $text;
if($amount > 0 || $draftObj->getTypeTransaction() == 'payment_salary'){
$draftObj->setAmount($amount * 100);
$draftObj->setExpected('comment');
$em->persist($draftObj);
$em->flush();
$this->addExpected($curClient, array("value" => "comment", "group" => $p_group));
$sum = str_replace(',00', '', number_format(($draftObj->getAmount() / 100), 2, ',', ' '));
$reply = 'Введено «Сумма ' . $sum . '». ' . 'Введите комментарий';
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Неправильно указана сумма, укажите сумму числом.';
}
} elseif($expected == 'comment') {
if($draftObj->getTypeTransaction() == 'expense_office'){
$draftObj->setComment(trim($text));
$draftObj->setExpected('file_cheque');
$em->persist($draftObj);
$em->flush();
$this->addExpected($curClient, array("value" => "file_cheque", "group" => $p_group));
$keyboard = [
[
[
'text'=>'Без чека',
'callback_data'=> json_encode(array('action' => "no_cheque", 'command' => "pay", "group" => $p_group))
]
]
];
$reply = 'Сделайте или прикрепите фото чека';
} else {
$draftObj->setComment(trim($text));
$draftObj->setExpected('finish');
$em->persist($draftObj);
$em->flush();
$this->resetExpected($curClient);
$create_transaction = $this->createTransaction($token, $chat_id, $groupObj, $draftObj);
if($create_transaction === true){
$em->remove($draftObj);
$em->flush();
}
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Транзакция успешно добавлена.';
}
} elseif($expected == 'file_cheque') {
$file = null;
if($file_id != '' && $file_id != null){
$file = $this->uploadFileBot($token, $file_id);
}
if($file != null){
$draftObj->setFile(($draftObj->getFile() != null && $draftObj->getFile() != '' ? $draftObj->getFile() . ';' . $file : $file));
$em->persist($draftObj);
$em->flush();
$reply = 'Фото чека успешно прикреплено. Чтобы добавить ещё фото чека, сделайте или прикрепите фото чека.';
} else {
$reply = 'Фото чека не удалось прикрепить. Чтобы добавить фото чека снова, сделайте или прикрепите фото чека.';
}
$editMessageId = $draftObj->getLastMessageId();
$this->addExpected($curClient, array("value" => "file_cheque", "group" => $p_group));
$keyboard = [
[
[
'text'=> 'Завершить операцию',
'callback_data'=> json_encode(array('action' => "finish_pay", 'command' => "pay", "group" => $p_group))
]
]
];
/*
//окончание финансовой операции
$draftObj->setExpected('finish');
$em->persist($draftObj);
$em->flush();
$this->resetExpected($curClient);
$create_transaction = $this->createTransaction($token, $chat_id, $groupObj, $draftObj);
if($create_transaction === true){
$em->remove($draftObj);
$em->flush();
}
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Транзакция успешно добавлена.';
*/
}
} elseif($expected == 'new_date'){
if(is_numeric(trim($text)) && trim($text) <= 31){
$reply = 'Введите сумму начисления оклада';
$newSalarySchedule = new SalarySchedule();
$newSalarySchedule->setClient(($groupObj && $is_group_chat === true ? $groupObj : $curClient))
->setDay(trim($text))
->setIsEdit(true)
;
$em->persist($newSalarySchedule);
$em->flush();
$groupObj = false;
if($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
$this->addExpected(($groupObj && $is_group_chat === true ? $groupObj : $curClient), array("value" => "new_amount", "group" => $p_group));
} else {
if(is_numeric(trim($text)) && trim($text) > 31){
$reply = 'День месяца не должен быть больше 31';
} else {
$reply = 'Введите день числом, в который будет осуществляться начисления оклада';
}
$keyboard = array(
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "expense_salary", 'command' => "pay", "group" => $p_group))
)
)
);
}
} elseif($expected == 'new_amount'){
$amount = (float) $text;
$salarySchedule = $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(array('client' => ($groupObj && $is_group_chat === true ? $groupObj : $curClient), 'is_edit' => true));
if($amount > 0 && $salarySchedule){
$salarySchedule->setAmount($amount)
->setIsEdit(false);
$em->persist($salarySchedule);
$em->flush();
$this->resetExpected(($groupObj && $is_group_chat === true ? $groupObj : $curClient));
$reply = 'Условие начисления оклада «' . $salarySchedule->getDay() . ' числа каждого месяца по ' . $salarySchedule->getAmount() . ' руб» успешно добавлено';
} else {
$reply = 'Не удалось добавить информацию для начисления оклада, попробуйте повторить операцию снова';
}
} elseif($expected == 'edit_ss_d' || $expected == 'edit_ss_a') {
if(is_numeric($text)){
$isExistSs = false;
if($ss_id != null && $ss_id != ''){
$salarySchedule = $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(array('id' => $ss_id));
if($salarySchedule){
$isExistSs = true;
if($expected == 'edit_ss_d'){
$salarySchedule->setDay($text);
} else {
$salarySchedule->setAmount($text);
}
$em->persist($salarySchedule);
$em->flush();
$reply = 'Условие начисления оклада «' . $salarySchedule->getDay() . ' числа каждого месяца по ' . $salarySchedule->getAmount() . ' руб» успешно отредактировано';
$keyboard = array(
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "edit_ss_date", 'command' => "pay", "group" => $p_group))
)
),
array(
array(
'text'=>'В основное меню',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => $p_group))
)
)
);
$this->resetExpected($curClient);
}
}
if(!$isExistSs){
$reply = 'Не удалось отредактировать условий для начисления оклада';
$keyboard = array(
array(
array(
'text'=>'В основное меню',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => $p_group))
)
)
);
}
} else {
$reply = 'Данные для ввода должны быть числом. Повторите ввод';
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
}
}
}
} else {
$groupObj = false;
if($group_id != '' && $group_id != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
} elseif($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
if($groupObj){
if($is_group_chat === true && $groupObj){
$chat_id = $groupObj->getChatId();
}
$name_group = '';
$type_group_typeof = null;
if($groupObj->getTypeGroup()){
$type_group_typeof = $groupObj->getTypeGroup()->getTypeof();
$name_group = $groupObj->nameClient();
}
if($type_group_typeof != null && $type_group_typeof != ''){
if($type_group_typeof == 'cash'){
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Выберите финансовую операцию.';
$keyboard = array(
array(
array(
'text'=>'Приход',
'callback_data'=> json_encode(array('action' => "income", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
)
),
array(
array(
'text'=>'Расход',
'callback_data'=> json_encode(array('action' => "expense", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
),
),
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "delete", 'command' => "pay", 'mes_id' => $message_id, "group" => ($groupObj ? $groupObj->getId() : null)))
)
)
);
} elseif($type_group_typeof == 'salary') {
$clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
$commandPermissions = $this->curCommandPermissions($clientObj, 'pay');
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Выберите финансовую операцию.';
// $keyboard = array(
// array(
// array(
// 'text'=>'Перевод в группу ЗП',
// 'callback_data'=> json_encode(array('action' => "income", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
// )
// ),
// array(
// array(
// 'text'=>'Перевод в группу Нал',
// 'callback_data'=> json_encode(array('action' => "income_cash", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
// )
// ),
// array(
// array(
// 'text'=>'Начисление зарплаты',
// 'callback_data'=> json_encode(array('action' => "expense", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
// ),
// ),
// array(
// array(
// 'text'=>'Начисление оклада',
// 'callback_data'=> json_encode(array('action' => "expense_salary", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
// ),
// ),
// array(
// array(
// 'text'=>'Назад',
// 'callback_data'=> json_encode(array('action' => "delete", 'command' => "pay", 'mes_id' => $message_id, "group" => ($groupObj ? $groupObj->getId() : null)))
// )
// )
// );
$keyboard = [];
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('salary_pay_transfer_to_salary', $commandPermissions))){
//Перевод в группу ЗП
$keyboard[] = [[
'text'=>'Перевод в группу ЗП',
'callback_data'=> json_encode(array('action' => "income", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
]];
}
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('salary_pay_transfer_to_cash', $commandPermissions))){
//Перевод в группу Нал
$keyboard[] = [[
'text'=>'Перевод в группу Нал',
'callback_data'=> json_encode(array('action' => "income_cash", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
]];
}
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('salary_pay_accrual_salary', $commandPermissions))){
//Начисление зарплаты
$keyboard[] = [[
'text'=>'Начисление зарплаты',
'callback_data'=> json_encode(array('action' => "expense", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
]];
}
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('salary_pay_accrual_payday', $commandPermissions))){
//Начисление оклада
$keyboard[] = [[
'text'=>'Начисление оклада',
'callback_data'=> json_encode(array('action' => "expense_salary", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
]];
}
$keyboard[] = [[
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "delete", 'command' => "pay", 'mes_id' => $message_id, "group" => ($groupObj ? $groupObj->getId() : null)))
]];
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно продолжить действие, у данной группы не выбран тип группы. Пожалуйста укажите тип группы и начните данную команду заново.';
}
} else {
$reply = 'Финансовые операции начинаются из группы, пожалуйста отправьте команду для начала операции в нужной группе.';
}
}
if(!isset($reply) || $reply == '' || $reply == null){
$reply = 'Что то пошло не так, начните выполнение операции заново';
}
$sendMessage = false;
if(count($keyboard) > 0){
$reply_markup = ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
if($editMessageId != null){
//редактировать уже существующее сообщение
$sendMessage = ProjectUtilsController::requestToBot($token, 'editMessageText', ['chat_id' => $chat_id, 'message_id' => $editMessageId, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
}
$resp = json_decode($sendMessage, true);
if(isset($resp['result']['message_id']) && $groupObj){
file_put_contents($basePath . '/var/log/' . $chat_id . '-' . $groupObj->getId() . '.txt', $resp['result']['message_id']);
}
// if($draftObj && $file_id != null && $file_id != '' && isset($resp['result']['message_id'])){
// $draftObj->setLastMessageId($resp['result']['message_id']);
// $em->persist($draftObj);
// $em->flush();
// }
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
if($is_group_chat === true){
$bot = $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
$command = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'pay'));
$this->addLogMessageBot($bot, $command, $sendMessage);
if($create_transaction === true){
$this->deleteLogMessage($bot, $chat_id, $command->getId());
}
}
}
private function bpay($token, $chat_id, $group_id, $cq_data = array(), $curClient = false, $text = null, $message_id = null, $file_id = null) {
$is_group_chat = $this->kernel->getContainer()->getParameter('app.chat.is_group');
$basePath = $this->getParameter('kernel.project_dir');
$create_transaction = false;
$action = null;
$p_group = null;
$keyboard = array();
$em = $this->getDoctrine()->getManager();
if(count($cq_data) > 0){
$action = (isset($cq_data['action']) ? $cq_data['action'] : null);
$p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
}
$expected = null;
$ss_id = null;
if($curClient){
$data_expected = $this->dataExpected($curClient->getExpected());
if(isset($data_expected['value'])){
$expected = $data_expected['value'];
}
if(isset($data_expected['group'])){
$p_group = $data_expected['group'];
}
if(isset($data_expected['ss_id'])){
$ss_id = $data_expected['ss_id'];
}
}
$editMessageId = null;
if(count($cq_data) > 0 && $action != 'menu'){
$name_group = '';
$groupObj = false;
if($group_id != null && $group_id != ''){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
} elseif($p_group != null && $p_group != '') {
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
if($action == 'delete' && $groupObj){
$mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
if($mes_id != '' && $mes_id != null){
$deleteMessage = ProjectUtilsController::requestToBot($token, 'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
}
if(file_exists($basePath . '/var/log/' . $groupObj->getChatId() . '-' . $groupObj->getId() . '.txt')){
$mes_id = file_get_contents($basePath . '/var/log/' . $groupObj->getChatId() . '-' . $groupObj->getId() . '.txt');
if($mes_id != '' && $mes_id != null){
$deleteMessage = ProjectUtilsController::requestToBot($token, 'deleteMessage', ['chat_id' => $groupObj->getChatId(), 'message_id' => $mes_id]);
$resp = json_decode($deleteMessage, true);
if(isset($resp['result'])){
if($resp['result'] == true){
unlink($basePath . '/var/log/' . $groupObj->getChatId() . '-' . $groupObj->getId() . '.txt');
}
}
}
}
exit();
}
$clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
if($groupObj && $clientObj){
$name_group = $groupObj->nameClient();
$type_group_typeof = null;
if($groupObj->getTypeGroup()){
$type_group_typeof = $groupObj->getTypeGroup()->getTypeof();
}
if($is_group_chat === true){
$chat_id = $groupObj->getChatId();
}
if($type_group_typeof != null && $type_group_typeof != ''){
if($type_group_typeof == 'cash'){
if($action == 'income'){
$commandPermissions = $this->curCommandPermissions($clientObj, 'bpay');
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Выбрано «Приход». ' . 'Выберите откуда осуществляется приход.';
// $keyboard = array(
// array(
// array(
// 'text'=>'По Объекту',
// 'callback_data'=> json_encode(array('action' => "income_partner", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
// )
// ),
// array(
// array(
// 'text'=>'Перевод Нал-Нал',
// 'callback_data'=> json_encode(array('action' => "income_group", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
// ),
// ),
// array(
// array(
// 'text'=>'Перевод ЗП-Нал',
// 'callback_data'=> json_encode(array('action' => "income_group_salary", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
// ),
// ),
// array(
// array(
// 'text'=>'Назад',
// 'callback_data'=> json_encode(array('action' => "menu", 'command' => "pay", "group" => ($groupObj ? $groupObj->getId() : null)))
// ),
// )
// );
$keyboard = [];
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('cash_pay_income_office', $commandPermissions))){
//Приход -> По Объекту
$keyboard[] = [[
'text'=>'По Объекту',
'callback_data'=> json_encode(array('action' => "income_partner", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
]];
}
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('cash_pay_income_transfer_cash_to_cash', $commandPermissions))){
//Приход -> Превод Нал-Нал
$keyboard[] = [[
'text'=>'Перевод Нал-Нал',
'callback_data'=> json_encode(array('action' => "income_group", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
]];
}
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('cash_pay_income_transfer_salary_to_cash', $commandPermissions))){
//Приход -> Превод ЗП-Нал
$keyboard[] = [[
'text'=>'Перевод ЗП-Нал',
'callback_data'=> json_encode(array('action' => "income_group_salary", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
]];
}
$keyboard[] = [[
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
]];
} elseif($action == 'income_group'){
$clients_q = $this->getDoctrine()
->getRepository(Client::class)
->createQueryBuilder('cl')
->select('cl.id, cl.first_name, cl.last_name, cl.username')
->innerJoin(TypeGroup::class, 'tg', 'WITH', 'cl.type_group = tg.id AND tg.typeof = :typeof_group')
->where('cl.typeof != :typeof')
->andWhere('cl.is_active = 1')
->setParameter('typeof', "private")
->setParameter('typeof_group', "cash")
;
if($groupObj){
$clients_q->andWhere('cl.id != ' . $groupObj->getId());
}
$clients = $clients_q->getQuery()->getArrayResult();
if(count($clients) > 0){
$buttons = array();
foreach ($clients as $item_client){
$name_client = $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
$buttons[][] = array(
'text' => $name_client,
'callback_data'=> json_encode(array("action" => "add_cgroup", 'command' => "bpay", 'id' => $item_client['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text' => 'Назад',
'callback_data'=> json_encode(array("action" => "income", 'command' => "bpay", "group" => $p_group))
);
$keyboard = $buttons;
$reply = 'Выбрано «Перевод Нал-Нал». ' . 'Выберите группу из которой будет списание средств.';
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
$newDraft->setTypeof('expense');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setToGroup($groupObj);
$newDraft->setExpected('cgroup');
$newDraft->setNote('Перевод Нал-Нал');
$newDraft->setTypeTransaction('transfer');
$em->persist($newDraft);
$em->flush();
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
}
} elseif($action == 'income_group_salary'){
$clients_q = $this->getDoctrine()
->getRepository(Client::class)
->createQueryBuilder('cl')
->select('cl.id, cl.first_name, cl.last_name, cl.username')
->innerJoin(TypeGroup::class, 'tg', 'WITH', 'cl.type_group = tg.id AND tg.typeof = :typeof_group')
->where('cl.typeof != :typeof')
->andWhere('cl.is_active = 1')
->setParameter('typeof', "private")
->setParameter('typeof_group', "salary")
;
if($groupObj){
$clients_q->andWhere('cl.id != ' . $groupObj->getId());
}
$clients = $clients_q->getQuery()->getArrayResult();
if(count($clients) > 0){
$buttons = array();
foreach ($clients as $item_client){
$name_client = $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
$buttons[][] = array(
'text' => $name_client,
'callback_data'=> json_encode(array("action" => "add_cgroup", 'command' => "bpay", 'id' => $item_client['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text' => 'Назад',
'callback_data'=> json_encode(array("action" => "income", 'command' => "bpay", "group" => $p_group))
);
$keyboard = $buttons;
$reply = 'Выбрано «Перевод ЗП-Нал». ' . 'Выберите группу из которой будет списание средств.';
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
$newDraft->setTypeof('expense');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setToGroup($groupObj);
$newDraft->setExpected('cgroup');
$newDraft->setNote('Перевод ЗП-Нал');
$newDraft->setTypeTransaction('transfer');
$em->persist($newDraft);
$em->flush();
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
}
} elseif($action == 'add_cgroup'){
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
$from_client = false;
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$from_client = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
}
}
if($draftObj && $from_client){
$from_group_typeof = ($from_client->getTypeGroup() != '' && $from_client->getTypeGroup() != null ? $from_client->getTypeGroup() : 'cash');
$groupObj = false;
if($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
$draftObj->setFromGroup($from_client);
$draftObj->setExpected('amount_b');
$em->persist($draftObj);
$em->flush();
$this->addExpected(($groupObj && $is_group_chat === true ? $groupObj : $clientObj), array("value" => "amount_b", "group" => $p_group));
$reply = 'Выбрано «Группа ' . ($from_client ? $from_client->nameClient() : '') . ' для списания с баланса». ' . 'Введите сумму.';
if($from_group_typeof != 'salary'){
$buttons[][] = array(
'text' => 'Назад',
'callback_data'=> json_encode(array("action" => "income_group", 'command' => "bpay", "group" => $p_group))
);
} else {
$buttons[][] = array(
'text' => 'Назад',
'callback_data'=> json_encode(array("action" => "income_group_salary", 'command' => "bpay", "group" => $p_group))
);
}
$keyboard = $buttons;
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
}
} elseif($action == 'income_partner' || $action == 'add_client' || $action == 'other'){
//step 1
$offices = $this->getDoctrine()
->getRepository(Office::class)
->createQueryBuilder('o')
->select('o.id, o.name, o.number')
->where('o.is_active = 1')
->getQuery()
->getArrayResult();
if(count($offices) > 0){
if($action == 'income_partner'){
$reply = 'Выбрано «По Объекту». ' . 'Выберите объект, по которому осуществляется приход.';
} elseif($action == 'other'){
$name_group = '';
if($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
if($groupObj){
if($groupObj->getTypeGroup()){
$name_group = $groupObj->nameClient();
}
}
}
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Выберите объект, по которому осуществляется расход.';
//$reply = 'Выбрано «Расходы по Объекту». ' . 'Выберите объект, по которому осуществляется расход.';
}
$buttons = array();
foreach ($offices as $item_office){
$buttons[][] = array(
'text' => ($item_office['number'] != '' && $item_office['number'] != null ? $item_office['number'] . '. ' : '') . $item_office['name'],
'callback_data'=> json_encode(array("action" => "add_office", 'command' => "bpay", 'id' => $item_office['id'], "group" => $p_group))
);
}
if($action == 'income_partner'){
$buttons[][] = array(
'text' => 'Назад',
'callback_data'=> json_encode(array("action" => "income", 'command' => "bay", "group" => $p_group))
);
} elseif($action == 'other'){
// $buttons[][] = array(
// 'text' => 'Назад',
// 'callback_data'=> json_encode(array("action" => "expense", 'command' => "bpay", "group" => $p_group))
// );
} elseif($action == 'add_client'){
$buttons[][] = array(
'text' => 'Назад',
'callback_data'=> json_encode(array("action" => "salary", 'command' => "bpay", "group" => $p_group))
);
}
$keyboard = $buttons;
if($action == 'income_partner'){
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
$newDraft->setTypeof('income');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setToGroup($groupObj);
$newDraft->setExpected('office_b');
$newDraft->setNote('Поступление средств');
$newDraft->setTypeTransaction('income');
$em->persist($newDraft);
$em->flush();
} elseif($action == 'add_client' || $action == 'other'){
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
$to_client = false;
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$to_client = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
}
}
//если сразу выбирается объект
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
$newDraft->setTypeof('expense');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setFromGroup($groupObj);
$newDraft->setExpected('type_expense_b');
$em->persist($newDraft);
$em->flush();
$draftObj = $newDraft;
//если сразу выбирается объект
if($draftObj){
if($action == 'other'){
$draftObj->setNote('Списание средств');
$draftObj->setTypeTransaction('expense_office');
$draftObj->setExpected('amount_b');
}
if($to_client){
$draftObj->setToGroup($to_client);
$draftObj->setExpected('office_b');
if($action == 'add_client'){
$name_salary_client = $to_client->nameClient();
$reply = 'Выбрано «Группа ' . $name_salary_client . ' для выплаты зарплаты». ' . 'Выберите объект, по которому выплачивается зарплата.';
}
}
$em->persist($draftObj);
$em->flush();
}
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
}
} elseif($action == 'expense'){
//step 1
$commandPermissions = $this->curCommandPermissions($clientObj, 'bpay');
$reply = 'Выбрано «Расход». ' . 'Выберите тип расхода.';
// $keyboard = array(
// array(
// array(
// 'text'=>'Перевод Нал-ЗП',
// 'callback_data'=> json_encode(array('action' => "salary", 'command' => "bpay", "group" => $p_group))
// )
// ),
// array(
// array(
// 'text'=>'Перевод Нал-Нал',
// 'callback_data'=> json_encode(array('action' => "transfer", 'command' => "bpay", "group" => $p_group))
// ),
// ),
// array(
// array(
// 'text'=>'Расходы по Объекту',
// 'callback_data'=> json_encode(array('action' => "other", 'command' => "bpay", "group" => $p_group))
// ),
// ),
//// array(
//// array(
//// 'text'=>'Расходы на компанию',
//// 'callback_data'=> json_encode(array('action' => "company", 'command' => "bpay", "group" => $p_group))
//// ),
//// ),
// array(
// array(
// 'text'=>'Назад',
// 'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => $p_group))
// ),
// )
// );
$keyboard = [];
// if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('cash_pay_expense_transfer_cash_to_salary', $commandPermissions))){
// //Расход -> Превод Нал-ЗП
// $keyboard[] = [[
// 'text'=>'Перевод Нал-ЗП',
// 'callback_data'=> json_encode(array('action' => "salary", 'command' => "bpay", "group" => $p_group))
// ]];
// }
// if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('cash_pay_expense_transfer_cash_to_cash', $commandPermissions))){
// //Расход -> Превод Нал-Нал
// $keyboard[] = [[
// 'text'=>'Перевод Нал-Нал',
// 'callback_data'=> json_encode(array('action' => "transfer", 'command' => "bpay", "group" => $p_group))
// ]];
// }
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('cash_pay_expense_office', $commandPermissions))){
//Расход -> Расходы по Объекту
$keyboard[] = [[
'text'=>'Расходы по Объекту',
'callback_data'=> json_encode(array('action' => "other", 'command' => "bpay", "group" => $p_group))
]];
}
// $keyboard[] = [[
// 'text'=>'Расходы на компанию',
// 'callback_data'=> json_encode(array('action' => "company", 'command' => "bpay", "group" => $p_group))
// ]];
$keyboard[] = [[
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => $p_group))
]];
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
$newDraft->setTypeof('expense');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setFromGroup($groupObj);
$newDraft->setExpected('type_expense_b');
$em->persist($newDraft);
$em->flush();
} elseif($action == 'add_office' || $action == 'add_director'){
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
$officeObj = false;
$directorObj = false;
if($action == 'add_office'){
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$officeObj = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
}
}
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
if($officeObj){
$draftObj->setOffice($officeObj);
}
} elseif($action == 'add_director'){
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$directorObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
}
}
if($directorObj){
$draftObj->setToGroup($directorObj);
}
}
$selected = '';
if($action == 'add_office' && $officeObj){
$selected = 'Выбрано «Объект ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null ? $officeObj->getNumber() . '. ' : '') . $officeObj->getName() . '». ';
} elseif($action == 'add_director' && $directorObj){
$name_director = $directorObj->nameClient();
$selected = 'Выбрано «Руководитель' . ($name_director != '' && $name_director != null ? ' ' . $name_director : '') . '». ';
}
if($draftObj){
$draftObj->setExpected('amount_b');
$em->persist($draftObj);
$em->flush();
$this->addExpected(($is_group_chat === true && $groupObj ? $groupObj : $clientObj), array("value" => "amount_b", "group" => $p_group));
$reply = $selected . 'Введите сумму';
// if($action == 'add_office'){
// $keyboard = array(
// array(
// array(
// 'text'=>'Назад',
// 'callback_data'=> json_encode(array('action' => "other", 'command' => "bpay", "group" => $p_group))
// ),
// )
// );
// } else {
// $keyboard = array(
// array(
// array(
// 'text'=>'Назад',
// 'callback_data'=> json_encode(array('action' => "income_partner", 'command' => "bpay", "group" => $p_group))
// ),
// )
// );
// }
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
}
} elseif($action == 'salary'){
$clients_q = $this->getDoctrine()
->getRepository(Client::class)
->createQueryBuilder('cl')
->select('cl.id, cl.first_name, cl.last_name, cl.username')
->innerJoin(TypeGroup::class, 'tg', 'WITH', 'cl.type_group = tg.id AND tg.typeof = :typeof_group')
->where('cl.typeof != :typeof')
->andWhere('cl.is_active = 1')
->setParameter('typeof', "private")
->setParameter('typeof_group', "salary")
;
if($groupObj){
$clients_q->andWhere('cl.id != ' . $groupObj->getId());
}
$clients = $clients_q->getQuery()->getArrayResult();
if(count($clients) > 0){
$buttons = array();
foreach ($clients as $item_client){
$name_client = $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
$buttons[][] = array(
'text' => $name_client,
'callback_data'=> json_encode(array("action" => "add_client", 'command' => "bpay", 'id' => $item_client['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "expense", 'command' => "bpay", "group" => $p_group))
);
$keyboard = $buttons;
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftObj){
$draftObj->setNote('Перевод Нал-ЗП');
$draftObj->setTypeTransaction('add_salary');
$draftObj->setExpected('to_group_b');
$em->persist($draftObj);
$em->flush();
$reply = 'Выбрано «Перевод Нал-ЗП». ' . 'Выберите группу, которой будет осуществлен перевод.';
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
$keyboard = array();
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
}
} elseif($action == 'transfer'){
$clients_q = $this->getDoctrine()
->getRepository(Client::class)
->createQueryBuilder('cl')
->select('cl.id, cl.first_name, cl.last_name, cl.username')
->innerJoin(TypeGroup::class, 'tg', 'WITH', 'cl.type_group = tg.id AND tg.typeof = :typeof_group')
->where('cl.typeof != :typeof')
->andWhere('cl.is_active = 1')
->setParameter('typeof', "private")
->setParameter('typeof_group', "cash")
;
if($groupObj){
$clients_q->andWhere('cl.id != ' . $groupObj->getId());
}
$clients = $clients_q->getQuery()->getArrayResult();
if(count($clients) > 0){
$buttons = array();
foreach ($clients as $item_client){
$name_client = $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
$buttons[][] = array(
'text' => $name_client,
'callback_data'=> json_encode(array("action" => "add_director", 'command' => "bpay", 'id' => $item_client['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "expense", 'command' => "bpay", "group" => $p_group))
);
$keyboard = $buttons;
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftObj){
$draftObj->setNote('Перевод Нал-Нал');
$draftObj->setTypeTransaction('transfer');
$draftObj->setExpected('to_group_b');
$em->persist($draftObj);
$em->flush();
$reply = 'Выбрано «Перевод Нал-Нал». ' . 'Выберите группу для перевода';
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
$keyboard = array();
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
}
} elseif($action == 'company'){
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
$newDraft->setTypeof('expense');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setFromGroup($groupObj);
$newDraft->setExpected('amount_b');
$newDraft->setNote('Списание средств на компанию');
$newDraft->setTypeTransaction('expense_company');
$em->persist($newDraft);
$em->flush();
$this->addExpected(($is_group_chat === true && $groupObj ? $groupObj : $clientObj), array("value" => "amount_b", "group" => $p_group));
$reply = 'Выбрано «Расходы на компанию». ' . 'Введите сумму.';
} elseif($action == 'no_cheque' || $action == 'finish_pay'){
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
$draftObj->setExpected('finish_b');
$em->persist($draftObj);
$em->flush();
$this->resetExpected($curClient);
// $create_transaction = $this->createTransaction($token, $chat_id, $groupObj, $draftObj);
// if($create_transaction === true){
// $em->remove($draftObj);
// $em->flush();
// }
$create_transaction = $this->sendMailNonCashCheque($token, $chat_id, $groupObj, $draftObj);
if($create_transaction === true){
$em->remove($draftObj);
$em->flush();
}
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Письмо с безналичным чеком успешно отправлено.';
}
} elseif($type_group_typeof == 'salary'){
if($action == 'income'){
$offices = $this->getDoctrine()
->getRepository(Office::class)
->createQueryBuilder('o')
->select('o.id, o.name')
->where('o.is_active = 1')
->getQuery()
->getArrayResult();
if(count($offices) > 0){
$reply = 'Выбрано «Перевод в группу ЗП». ' . 'Выберите объект, по которому осуществляется выплата зарплаты.';
$buttons = array();
foreach ($offices as $item_office){
$buttons[][] = array(
'text' => $item_office['name'],
'callback_data'=> json_encode(array("action" => "add_office", 'command' => "bpay", 'id' => $item_office['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "delete", 'command' => "bpay", "group" => $p_group))
);
$keyboard = $buttons;
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
$newDraft->setTypeof('expense');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setToGroup($groupObj);
$newDraft->setExpected('office_b');
$newDraft->setNote('Перевод в группу ЗП');
$newDraft->setTypeTransaction('add_salary');
$em->persist($newDraft);
$em->flush();
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
}
} elseif($action == 'income_cash'){
$offices = $this->getDoctrine()
->getRepository(Office::class)
->createQueryBuilder('o')
->select('o.id, o.name, o.number')
->where('o.is_active = 1')
->getQuery()
->getArrayResult();
if(count($offices) > 0){
$reply = 'Выбрано «Перевод в группу Нал». ' . 'Выберите объект, по которому осуществляется выплата зарплаты.';
$buttons = array();
foreach ($offices as $item_office){
$buttons[][] = array(
'text' => ($item_office['number'] != '' && $item_office['number'] != null ? $item_office['number'] . '. ' : '') . $item_office['name'],
'callback_data'=> json_encode(array("action" => "add_office", 'command' => "bpay", 'id' => $item_office['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "delete", 'command' => "bpay", "group" => $p_group))
);
$keyboard = $buttons;
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
// $newDraft->setTypeof('expense');
$newDraft->setTypeof('income');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setToGroup($groupObj);
$newDraft->setExpected('office_b');
$newDraft->setNote('Перевод в группу Нал');
$newDraft->setTypeTransaction('add_salary_cash');
$em->persist($newDraft);
$em->flush();
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Нет объектов для выбора, пожалуйста добавьте нужный объект и начните операцию занова.';
}
} elseif($action == 'add_office'){
$clients_q = $this->getDoctrine()
->getRepository(Client::class)
->createQueryBuilder('cl')
->select('cl.id, cl.first_name, cl.last_name, cl.username')
->innerJoin(TypeGroup::class, 'tg', 'WITH', 'cl.type_group = tg.id AND tg.typeof = :typeof_group')
->where('cl.typeof != :typeof')
->andWhere('cl.is_active = 1')
->setParameter('typeof', "private")
->setParameter('typeof_group', "cash")
;
$clients = $clients_q->getQuery()->getArrayResult();
if(count($clients) > 0){
$buttons = array();
foreach ($clients as $item_client){
$name_client = $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
$buttons[][] = array(
'text' => $name_client,
'callback_data'=> json_encode(array("action" => "add_client", 'command' => "bpay", 'id' => $item_client['id'], "group" => $p_group))
);
}
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftObj){
$officeObj = false;
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$officeObj = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
}
}
if($officeObj){
$draftObj->setOffice($officeObj);
}
$draftObj->setExpected('from_group_b');
$em->persist($draftObj);
$em->flush();
if($draftObj->getTypeTransaction() != 'add_salary_cash'){
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "income", 'command' => "bpay", "group" => $p_group))
);
$keyboard = $buttons;
$reply = 'Выбрано «Объект' . ($officeObj ? ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null ? $officeObj->getNumber() . '. ' : '') . $officeObj->getName() : '') . '». ' . 'Выберите группу, c которой будут списаны средства.';
} else {
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "income_cash", 'command' => "bpay", "group" => $p_group))
);
$keyboard = $buttons;
$reply = 'Выбрано «Объект' . ($officeObj ? ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null ? $officeObj->getNumber() . '. ' : '') . $officeObj->getName() : '') . '». ' . 'Выберите группу, в которую будут переведены средства.';
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
$keyboard = array();
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно продолжить, пока нет ни одной группы нужного типа.';
}
} elseif($action == 'add_client'){
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
$to_client = false;
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$to_client = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
}
}
if($draftObj && $to_client){
$groupObj = false;
if($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
$draftObj->setFromGroup($to_client);
$draftObj->setExpected('amount_b');
$em->persist($draftObj);
$em->flush();
$this->addExpected(($groupObj && $is_group_chat === true ? $groupObj : $clientObj), array("value" => "amount_b", "group" => $p_group));
if($draftObj->getTypeTransaction() != 'add_salary_cash'){
$reply = 'Выбрано «Группа ' . ($to_client ? $to_client->nameClient() : '') . ' для списания средств». ' . 'Введите сумму.';
} else {
$reply = 'Выбрано «Группа ' . ($to_client ? $to_client->nameClient() : '') . ' для перевода средств». ' . 'Введите сумму.';
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
}
} elseif($action == 'expense'){
$draftOld = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftOld){
$em->remove($draftOld);
$em->flush();
}
$newDraft = new Draft();
$newDraft->setTypeof('expense');
$newDraft->setClient($clientObj);
$newDraft->setClientGroup($groupObj);
$newDraft->setToGroup($groupObj);
//$newDraft->setFromGroup($groupObj);
$newDraft->setExpected('add_office_expense_b');
$newDraft->setNote('Начисление зарплаты');
$newDraft->setTypeTransaction('payment_salary');
$em->persist($newDraft);
$em->flush();
$offices = $this->getDoctrine()
->getRepository(Office::class)
->createQueryBuilder('o')
->select('o.id, o.name, o.number')
->where('o.is_active = 1')
->getQuery()
->getArrayResult();
if(count($offices) > 0){
$reply = 'Выбрано «Начисление зарплаты». ' . 'Выберите объект, по которому осуществляется начисление зарплаты.';
$keyboard = array();
$buttons = array();
foreach ($offices as $item_office){
$buttons[][] = array(
'text' => ($item_office['number'] != '' && $item_office['number'] != null ? $item_office['number'] . '. ' : '') . $item_office['name'],
'callback_data'=> json_encode(array("action" => "add_office_exp", 'command' => "bpay", 'id' => $item_office['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => $p_group))
);
$keyboard = $buttons;
} else {
$reply = 'Нет объектов для начисление зарплаты по ним.';
}
/*
$groupObj = false;
if($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
$this->addExpected(($groupObj && $is_group_chat === true ? $groupObj : $clientObj), array("value" => "amount", "group" => $p_group));
$reply = 'Выбрано «Начисление зарплаты». ' . 'Введите сумму';
*/
} elseif($action == 'expense_salary') {
//операция начисление оклада
$salarySchedule = $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
if(count($salarySchedule) > 0){
$max_ss = $this->getParameter('app.max.salary_schedule');
if(count($salarySchedule) < $max_ss){
$reply = 'Выбрано «Начисление оклада». Можете отредактировать условия начисления оклада по нужным числам месяца, добавить новое или удалить лишнее';
$keyboard = array(
array(
array(
'text'=>'Редактировать условие начисления',
'callback_data'=> json_encode(array('action' => "edit_ss_date", 'command' => "bpay", "group" => $p_group))
)
),
array(
array(
'text'=>'Новое условие начисления',
'callback_data'=> json_encode(array('action' => "new_ss_date", 'command' => "bpay", "group" => $p_group))
)
),
array(
array(
'text'=>'Удалить условие начисления',
'callback_data'=> json_encode(array('action' => "rem_ss_date", 'command' => "bpay", "group" => $p_group))
)
),
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => $p_group))
)
)
);
} else {
$reply = 'Выбрано «Начисление оклада». Можете отредактировать условия начисления оклада по нужным числам месяца или удалить лишнее';
$keyboard = array(
array(
array(
'text'=>'Редактировать условие начисления',
'callback_data'=> json_encode(array('action' => "edit_ss_date", 'command' => "bpay", "group" => $p_group))
)
),
array(
array(
'text'=>'Удалить условие начисления',
'callback_data'=> json_encode(array('action' => "rem_ss_date", 'command' => "bpay", "group" => $p_group))
)
),
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => $p_group))
)
)
);
}
} else {
$reply = 'Выбрано «Начисление оклада». Для начисления оклада по нужным числам месяца необходимо добавить условие начисления';
$keyboard = array(array(
array(
'text'=>'Новое условие начисления',
'callback_data'=> json_encode(array('action' => "new_ss_date", 'command' => "bpay", "group" => $p_group))
)
),
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => $p_group))
)
)
);
}
} elseif($action == 'new_ss_date') {
//новое условие начисления оклада
$reply = 'Введите число дня месяца, в который будет осуществляться начисления оклада';
$keyboard = array(
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "expense_salary", 'command' => "bpay", "group" => $p_group))
)
)
);
$groupObj = false;
if($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
$this->addExpected(($groupObj && $is_group_chat === true ? $groupObj : $clientObj), array("value" => "new_date", "group" => $p_group));
} elseif($action == 'edit_ss_date') {
//изменить условие начисления оклада
$salarySchedule = $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
if(count($salarySchedule) > 0){
$reply = 'Выберите из списка условие для начисления оклада, которое хотите отредактировать';
$buttons = array();
foreach ($salarySchedule as $item_ss){
$buttons[][] = array(
'text' => $item_ss['day'] . ' числа каждого месяца по ' . $item_ss['amount'] . ' руб',
'callback_data'=> json_encode(array("action" => "edit_ss", 'command' => "bpay", 'ss_id' => $item_ss['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "expense_salary", 'command' => "bpay", "group" => $p_group))
);
$keyboard = $buttons;
} else {
$reply = 'Условий для начисления оклада не найдено, можете создать новое';
$keyboard = array(array(
array(
'text'=>'Новое условие начисления',
'callback_data'=> json_encode(array('action' => "new_ss_date", 'command' => "bpay", "group" => $p_group))
)
),
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => $p_group))
)
)
);
}
} elseif($action == 'rem_ss_date') {
//удалить условие начисления оклада
$salarySchedule = $this->getDoctrine()->getRepository(SalarySchedule::class)->getItems($p_group);
if(count($salarySchedule) > 0){
$reply = 'Выберите из списка условие для начисления оклада, которое хотите удалить';
$buttons = array();
foreach ($salarySchedule as $item_ss){
$buttons[][] = array(
'text' => $item_ss['day'] . ' числа каждого месяца по ' . $item_ss['amount'] . ' руб',
'callback_data'=> json_encode(array("action" => "rem_ss", 'command' => "bpay", 'ss_id' => $item_ss['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "expense_salary", 'command' => "bpay", "group" => $p_group))
);
$keyboard = $buttons;
} else {
$reply = 'Условий для начисления оклада не найдено, можете создать новое';
$keyboard = array(array(
array(
'text'=>'Новое условие начисления',
'callback_data'=> json_encode(array('action' => "new_ss_date", 'command' => "bpay", "group" => $p_group))
)
),
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => $p_group))
)
)
);
}
} elseif($action == 'edit_ss'){
//изменить условие начисления оклада
$id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
$isExistSs = false;
if($id != '' && $id != null){
$salarySchedule = $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
if($salarySchedule){
$isExistSs = true;
$reply = 'Выбрано для редактирования условие для начисления «' . $salarySchedule->getDay() . ' числа каждого месяца по ' . $salarySchedule->getAmount() . ' руб». Выберите, что нужно отредактировать';
$keyboard = array(
array(
array(
'text'=>'Число месяца',
'callback_data'=> json_encode(array('action' => "edit_ss_d", 'command' => "bpay", 'ss_id' => $salarySchedule->getId(), "group" => $p_group))
),
array(
'text'=>'Сумму начисления',
'callback_data'=> json_encode(array('action' => "edit_ss_a", 'command' => "bpay", 'ss_id' => $salarySchedule->getId(), "group" => $p_group))
)
),
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "edit_ss_date", 'command' => "bpay", "group" => $p_group))
)
)
);
}
}
if(!$isExistSs){
$reply = 'Не удалось найти условий для начисления оклада';
$keyboard = array(
array(
array(
'text'=>'В основное меню',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => $p_group))
)
)
);
}
} elseif($action == 'edit_ss_d' || $action == 'edit_ss_a') {
//изменить условие начисления оклада
$id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
$isExistSs = false;
if($id != '' && $id != null){
$salarySchedule = $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
if($salarySchedule){
$isExistSs = true;
if($action == 'edit_ss_d'){
$reply = 'Введите новое число дня месяца для условия начисления оклада «' . $salarySchedule->getDay() . ' числа каждого месяца по ' . $salarySchedule->getAmount() . ' руб»';
$this->addExpected(($is_group_chat === true && $groupObj ? $groupObj : $clientObj), array("value" => "edit_ss_d", "ss_id" => $salarySchedule->getId(), "group" => $p_group));
} else {
$reply = 'Введите новую сумму для условия начисления оклада «' . $salarySchedule->getDay() . ' числа каждого месяца по ' . $salarySchedule->getAmount() . ' руб»';
$this->addExpected(($is_group_chat === true && $groupObj ? $groupObj : $clientObj), array("value" => "edit_ss_a", "ss_id" => $salarySchedule->getId(), "group" => $p_group));
}
}
}
if(!$isExistSs){
$reply = 'Не удалось найти условий для начисления оклада';
$keyboard = array(
array(
array(
'text'=>'В основное меню',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => $p_group))
)
)
);
}
} elseif($action == 'rem_ss'){
//удалить условие начисления оклада
$id = (isset($cq_data['ss_id']) ? $cq_data['ss_id'] : null);
$isExistSs = false;
if($id != '' && $id != null){
$salarySchedule = $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(['id' => $id]);
if($salarySchedule){
$isExistSs = true;
$reply = 'Условие для начисления оклада «' . $salarySchedule->getDay() . ' числа каждого месяца по ' . $salarySchedule->getAmount() . ' руб» успешно удалено';
$em->remove($salarySchedule);
$em->flush();
$keyboard = array(
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "rem_ss_date", 'command' => "bpay", "group" => $p_group))
)
),
array(
array(
'text'=>'В основное меню',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => $p_group))
)
)
);
}
}
if(!$isExistSs){
$reply = 'Не удалось найти условий для начисления оклада';
$keyboard = array(
array(
array(
'text'=>'В основное меню',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => $p_group))
)
)
);
}
} elseif($action == 'add_office_exp'){
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => $clientObj, 'client_group' => $groupObj));
if($draftObj){
$officeObj = false;
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$officeObj = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
}
}
if($officeObj){
$draftObj->setOffice($officeObj);
}
$draftObj->setExpected('amount_b');
$em->persist($draftObj);
$em->flush();
$reply = 'Выбрано «Объект' . ($officeObj ? ' ' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null ? $officeObj->getNumber() . '. ' : '') . $officeObj->getName() : '') . ' для начисления зарплаты». ' . 'Введите сумму.';
$groupObj = false;
if($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
$this->addExpected(($groupObj && $is_group_chat === true ? $groupObj : $clientObj), array("value" => "amount_b", "group" => $p_group));
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
$keyboard = array();
}
}
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно продолжить добавление финансовой операции, у данной группы не выбран тип группы. Пожалуйста укажите тип группы данной группе и начните добавление операции занова.';
}
} else {
$reply = 'Финансовые операции начинаются из группы, пожалуйста отправьте команду для начала операции в нужной группе.';
}
} elseif($expected != '' && $expected != null){
$curClientObj = false;
if($is_group_chat === true){
$curClientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
}
if($curClient && (($text != '' && $text != null) || ($file_id != '' && $file_id != null))){
$groupObj = false;
if($group_id != null && $group_id != ''){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
} elseif($p_group != null && $p_group != '') {
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
if($groupObj && $curClient){
$name_group = $groupObj->nameClient();
$type_group_typeof = null;
if($groupObj->getTypeGroup()){
$type_group_typeof = $groupObj->getTypeGroup()->getTypeof();
}
if($is_group_chat === true && $groupObj){
$chat_id = $groupObj->getChatId();
}
$draftObj = $this->getDoctrine()->getRepository(Draft::class)->findOneBy(array('client' => ($curClientObj ? $curClientObj->getId() : $curClient->getId()), 'client_group' => $groupObj));
if($draftObj){
if($expected == 'amount_b'){
$amount = (float) $text;
if($amount > 0 || $draftObj->getTypeTransaction() == 'payment_salary'){
$draftObj->setAmount($amount * 100);
$draftObj->setExpected('comment_b');
$em->persist($draftObj);
$em->flush();
$this->addExpected($curClient, array("value" => "comment_b", "group" => $p_group));
$sum = str_replace(',00', '', number_format(($draftObj->getAmount() / 100), 2, ',', ' '));
$reply = 'Введено «Сумма ' . $sum . '». ' . 'Введите комментарий';
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Неправильно указана сумма, укажите сумму числом.';
}
} elseif($expected == 'comment_b') {
if($draftObj->getTypeTransaction() == 'expense_office'){
$draftObj->setComment(trim($text));
$draftObj->setExpected('file_cheque_b');
$em->persist($draftObj);
$em->flush();
$this->addExpected($curClient, array("value" => "file_cheque_b", "group" => $p_group));
$keyboard = [
// [
// [
// 'text'=>'Без чека',
// 'callback_data'=> json_encode(array('action' => "no_cheque", 'command' => "bpay", "group" => $p_group))
// ]
// ]
];
$reply = 'Сделайте или прикрепите фото чека';
} else {
$draftObj->setComment(trim($text));
$draftObj->setExpected('finish_b');
$em->persist($draftObj);
$em->flush();
$this->resetExpected($curClient);
// $create_transaction = $this->createTransaction($token, $chat_id, $groupObj, $draftObj);
// if($create_transaction === true){
// $em->remove($draftObj);
// $em->flush();
// }
$create_transaction = $this->sendMailNonCashCheque($token, $chat_id, $groupObj, $draftObj);
if($create_transaction === true){
$em->remove($draftObj);
$em->flush();
}
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Письмо с безналичным чеком успешно отправлено.';
}
} elseif($expected == 'file_cheque_b') {
$file = null;
if($file_id != '' && $file_id != null){
$file = $this->uploadFileBot($token, $file_id);
}
if($file != null){
$draftObj->setFile(($draftObj->getFile() != null && $draftObj->getFile() != '' ? $draftObj->getFile() . ';' . $file : $file));
$em->persist($draftObj);
$em->flush();
$reply = 'Фото чека успешно прикреплено. Чтобы добавить ещё фото чека, сделайте или прикрепите фото чека.';
} else {
$reply = 'Фото чека не удалось прикрепить. Чтобы добавить фото чека снова, сделайте или прикрепите фото чека.';
}
$editMessageId = $draftObj->getLastMessageId();
$this->addExpected($curClient, array("value" => "file_cheque_b", "group" => $p_group));
$keyboard = [
[
[
'text'=> 'Завершить операцию',
'callback_data'=> json_encode(array('action' => "finish_pay", 'command' => "bpay", "group" => $p_group))
]
]
];
/*
//окончание финансовой операции
$draftObj->setExpected('finish_b');
$em->persist($draftObj);
$em->flush();
$this->resetExpected($curClient);
$create_transaction = $this->createTransaction($token, $chat_id, $groupObj, $draftObj);
if($create_transaction === true){
$em->remove($draftObj);
$em->flush();
}
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Транзакция успешно добавлена.';
*/
}
} elseif($expected == 'new_date_b'){
if(is_numeric(trim($text)) && trim($text) <= 31){
$reply = 'Введите сумму начисления оклада';
$newSalarySchedule = new SalarySchedule();
$newSalarySchedule->setClient(($groupObj && $is_group_chat === true ? $groupObj : $curClient))
->setDay(trim($text))
->setIsEdit(true)
;
$em->persist($newSalarySchedule);
$em->flush();
$groupObj = false;
if($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
$this->addExpected(($groupObj && $is_group_chat === true ? $groupObj : $curClient), array("value" => "new_amount_b", "group" => $p_group));
} else {
if(is_numeric(trim($text)) && trim($text) > 31){
$reply = 'День месяца не должен быть больше 31';
} else {
$reply = 'Введите день числом, в который будет осуществляться начисления оклада';
}
$keyboard = array(
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "expense_salary", 'command' => "bpay", "group" => $p_group))
)
)
);
}
} elseif($expected == 'new_amount_b'){
$amount = (float) $text;
$salarySchedule = $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(array('client' => ($groupObj && $is_group_chat === true ? $groupObj : $curClient), 'is_edit' => true));
if($amount > 0 && $salarySchedule){
$salarySchedule->setAmount($amount)
->setIsEdit(false);
$em->persist($salarySchedule);
$em->flush();
$this->resetExpected(($groupObj && $is_group_chat === true ? $groupObj : $curClient));
$reply = 'Условие начисления оклада «' . $salarySchedule->getDay() . ' числа каждого месяца по ' . $salarySchedule->getAmount() . ' руб» успешно добавлено';
} else {
$reply = 'Не удалось добавить информацию для начисления оклада, попробуйте повторить операцию снова';
}
} elseif($expected == 'edit_ss_d_b' || $expected == 'edit_ss_a_b') {
if(is_numeric($text)){
$isExistSs = false;
if($ss_id != null && $ss_id != ''){
$salarySchedule = $this->getDoctrine()->getRepository(SalarySchedule::class)->findOneBy(array('id' => $ss_id));
if($salarySchedule){
$isExistSs = true;
if($expected == 'edit_ss_d_b'){
$salarySchedule->setDay($text);
} else {
$salarySchedule->setAmount($text);
}
$em->persist($salarySchedule);
$em->flush();
$reply = 'Условие начисления оклада «' . $salarySchedule->getDay() . ' числа каждого месяца по ' . $salarySchedule->getAmount() . ' руб» успешно отредактировано';
$keyboard = array(
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "edit_ss_date", 'command' => "bpay", "group" => $p_group))
)
),
array(
array(
'text'=>'В основное меню',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => $p_group))
)
)
);
$this->resetExpected($curClient);
}
}
if(!$isExistSs){
$reply = 'Не удалось отредактировать условий для начисления оклада';
$keyboard = array(
array(
array(
'text'=>'В основное меню',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "bpay", "group" => $p_group))
)
)
);
}
} else {
$reply = 'Данные для ввода должны быть числом. Повторите ввод';
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно подолжить финансовую операцию, начните ее заново.';
}
}
}
} else {
$groupObj = false;
if($group_id != '' && $group_id != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
} elseif($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
if($groupObj){
if($is_group_chat === true && $groupObj){
$chat_id = $groupObj->getChatId();
}
$name_group = '';
$type_group_typeof = null;
if($groupObj->getTypeGroup()){
$type_group_typeof = $groupObj->getTypeGroup()->getTypeof();
$name_group = $groupObj->nameClient();
}
if($type_group_typeof != null && $type_group_typeof != ''){
if($type_group_typeof == 'cash'){
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Выберите финансовую операцию.';
$keyboard = array(
// array(
// array(
// 'text'=>'Приход',
// 'callback_data'=> json_encode(array('action' => "income", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
// )
// ),
array(
array(
'text'=>'Расход',
'callback_data'=> json_encode(array('action' => "expense", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
),
),
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "delete", 'command' => "bpay", 'mes_id' => $message_id, "group" => ($groupObj ? $groupObj->getId() : null)))
)
)
);
} elseif($type_group_typeof == 'salary') {
$clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
$commandPermissions = $this->curCommandPermissions($clientObj, 'bpay');
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Выберите финансовую операцию.';
// $keyboard = array(
// array(
// array(
// 'text'=>'Перевод в группу ЗП',
// 'callback_data'=> json_encode(array('action' => "income", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
// )
// ),
// array(
// array(
// 'text'=>'Перевод в группу Нал',
// 'callback_data'=> json_encode(array('action' => "income_cash", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
// )
// ),
// array(
// array(
// 'text'=>'Начисление зарплаты',
// 'callback_data'=> json_encode(array('action' => "expense", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
// ),
// ),
// array(
// array(
// 'text'=>'Начисление оклада',
// 'callback_data'=> json_encode(array('action' => "expense_salary", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
// ),
// ),
// array(
// array(
// 'text'=>'Назад',
// 'callback_data'=> json_encode(array('action' => "delete", 'command' => "bpay", 'mes_id' => $message_id, "group" => ($groupObj ? $groupObj->getId() : null)))
// )
// )
// );
$keyboard = [];
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('salary_pay_transfer_to_salary', $commandPermissions))){
//Перевод в группу ЗП
$keyboard[] = [[
'text'=>'Перевод в группу ЗП',
'callback_data'=> json_encode(array('action' => "income", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
]];
}
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('salary_pay_transfer_to_cash', $commandPermissions))){
//Перевод в группу Нал
$keyboard[] = [[
'text'=>'Перевод в группу Нал',
'callback_data'=> json_encode(array('action' => "income_cash", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
]];
}
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('salary_pay_accrual_salary', $commandPermissions))){
//Начисление зарплаты
$keyboard[] = [[
'text'=>'Начисление зарплаты',
'callback_data'=> json_encode(array('action' => "expense", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
]];
}
if(count($commandPermissions) <= 0 || (count($commandPermissions) > 0 && in_array('salary_pay_accrual_payday', $commandPermissions))){
//Начисление оклада
$keyboard[] = [[
'text'=>'Начисление оклада',
'callback_data'=> json_encode(array('action' => "expense_salary", 'command' => "bpay", "group" => ($groupObj ? $groupObj->getId() : null)))
]];
}
$keyboard[] = [[
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "delete", 'command' => "bpay", 'mes_id' => $message_id, "group" => ($groupObj ? $groupObj->getId() : null)))
]];
}
} else {
$reply = ($name_group != '' && $name_group != null ? 'Работаете с группой «' . $name_group . '». ' : '') . 'Невозможно продолжить действие, у данной группы не выбран тип группы. Пожалуйста укажите тип группы и начните данную команду заново.';
}
} else {
$reply = 'Финансовые операции начинаются из группы, пожалуйста отправьте команду для начала операции в нужной группе.';
}
}
if(!isset($reply) || $reply == '' || $reply == null){
$reply = 'Что то пошло не так, начните выполнение операции заново';
}
$sendMessage = false;
if(count($keyboard) > 0){
$reply_markup = ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
if($editMessageId != null){
//редактировать уже существующее сообщение
$sendMessage = ProjectUtilsController::requestToBot($token, 'editMessageText', ['chat_id' => $chat_id, 'message_id' => $editMessageId, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
}
$resp = json_decode($sendMessage, true);
if(isset($resp['result']['message_id']) && $groupObj){
file_put_contents($basePath . '/var/log/' . $chat_id . '-' . $groupObj->getId() . '.txt', $resp['result']['message_id']);
}
// if($draftObj && $file_id != null && $file_id != '' && isset($resp['result']['message_id'])){
// $draftObj->setLastMessageId($resp['result']['message_id']);
// $em->persist($draftObj);
// $em->flush();
// }
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
if($is_group_chat === true){
$bot = $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
$command = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'bpay'));
$this->addLogMessageBot($bot, $command, $sendMessage);
if($create_transaction === true){
$this->deleteLogMessage($bot, $chat_id, $command->getId());
}
}
}
private function sendMailNonCashCheque($token, $chat_id, $group, $draft){
$basePath = $this->getParameter('kernel.project_dir');
$fileDir = '/public/images/';
$is_group_chat = $this->getParameter('app.chat.is_group');
$resp = false;
$em = $this->getDoctrine()->getManager();
$isSendMail = false;
$typeMail = 'newTransaction';
if($token != '' && $token != null && $chat_id != '' && $chat_id != null && $group && $draft){
if($draft->getExpected() == 'finish_b'){
$amount = $draft->getAmount();
if($draft->getTypeof() == 'expense'){
$amount = '-' . $draft->getAmount();
}
$is_income = false;
//если приход по Объекту, или начисление ЗП
if(!$draft->getFromGroup() && $draft->getToGroup()){
$is_income = true;
}
$office_name = '';
$office_number = '';
if($draft->getOffice()){
$office_name = $draft->getOffice()->getName();
$office_number = $draft->getOffice()->getNumber();
}
$from_chat_id = null;
$from_name = '';
$type_group_from = null;
if($draft->getFromGroup()){
$from_chat_id = $draft->getFromGroup()->getChatId();
$from_name = $draft->getFromGroup()->nameClient();
$type_group_from = ($draft->getFromGroup()->getTypeGroup() != null ? $draft->getFromGroup()->getTypeGroup()->getTypeof() : null);
}
$to_chat_id = null;
$to_name = '';
$type_group_to = null;
if($draft->getToGroup()){
$to_chat_id = $draft->getToGroup()->getChatId();
$to_name = $draft->getToGroup()->nameClient();
$type_group_to = ($draft->getToGroup()->getTypeGroup() != null ? $draft->getToGroup()->getTypeGroup()->getTypeof() : null);
}
//если приход по Объекту, или начисление ЗП
if($is_income === true && $draft->getToGroup()){
$from_chat_id = $draft->getToGroup()->getChatId();
$from_name = $draft->getToGroup()->nameClient();
}
$m_source = '';
$m_type = '';
if($draft->getTypeTransaction() == 'expense_office' || ($draft->getTypeTransaction() == 'income' && $draft->getTypeof() == 'income') || ($draft->getTypeTransaction() == 'add_salary' && $draft->getTypeof() == 'expense')){
$isSendMail = true;
$m_source = ($draft->getFromGroup() != null ? $draft->getFromGroup()->getFirstName() : '');
if($draft->getTypeTransaction() == 'expense_office'){
// +300 (Нал бот, 444. Бургерная, тестовый коммент)
$cm = $amount . " (" . $from_name . ", " . ($office_name != '' ? ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ", " . $draft->getComment() . ")";
if($draft->getFile() != '' && $draft->getFile() != null){
$typeMail = 'newTransactionIncomeCashСheque';
$m_type = 'расход Чек';
} else {
$typeMail = 'newTransactionIncomeCashNoСheque';
$m_type = 'расход Нал';
}
} elseif($draft->getTypeTransaction() == 'income' && $draft->getTypeof() == 'income'){
// +555 (Нал Бот, 24195. Пробник, тест коммент)
$cm = $amount . " (" . $from_name . ", " . ($office_name != '' ? ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ", " . $draft->getComment() . ")";
//$m_source = ($draft->getFromGroup() != null ? $draft->getFromGroup()->getFirstName() : '');
$m_source = ($draft->getToGroup() != null ? $draft->getToGroup()->getFirstName() : '');
$m_type = 'приход Нал';
$typeMail = 'newTransactionIncomeCash';
} elseif($draft->getTypeTransaction() == 'add_salary' && $draft->getTypeof() == 'expense'){
// -333 (Нал Бот - ЗП Бот, тест коммент)
$cm = '-' . $amount . " (" . $from_name . " - " . $to_name . ", " . ($office_name != '' ? ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ", " . $draft->getComment() . ")";
$m_source = ($draft->getToGroup() != null ? $draft->getToGroup()->getFirstName() : '');
$m_type = 'расход ЗП';
$typeMail = 'newTransactionExpenseSalary';
}
}
if($draft->getAmount() < 0 && $draft->getTypeTransaction() == 'payment_salary' && $draft->getTypeof() == 'expense'){
$draft->setTypeof('income');
$draft->setAmount(abs($draft->getAmount()));
$em->persist($draft);
$em->flush();
}
$amount_reverse = 0;
if($draft->getToGroup() && $draft->getFromGroup()){
$typeof_reverse = null;
if($draft->getTypeof() == 'expense'){
$typeof_reverse = 'income';
} elseif($draft->getTypeof() == 'income'){
$typeof_reverse = 'expense';
}
$amount_reverse = $draft->getAmount();
if($typeof_reverse == 'expense'){
$amount_reverse = '-' . $draft->getAmount();
}
}
$from_group = $draft->getFromGroup();
//если приход по Объекту, или начисление ЗП
if($is_income === true && $draft->getToGroup()){
$from_group = $draft->getToGroup();
}
if ($draft->getTypeof() == 'expense' && $draft->getToGroup() && $is_income === false) {
$to_group = $draft->getToGroup();
}
$resp = true;
if($isSendMail){
//отправка письма по операциям
$recipient = $this->getParameter('app.mailer.to.transaction');
$m_amount = $draft->getAmount();
$m_office = ($draft->getOffice() != null ? ($draft->getOffice()->getNumber() != '' && $draft->getOffice()->getNumber() != null ? $draft->getOffice()->getNumber() . '. ' : '') . $draft->getOffice()->getName() : '');
$author = '';
if($draft->getClient() != null){
if($draft->getClient()->getUsername() != null && $draft->getClient()->getUsername() != ''){
$author = $draft->getClient()->getUsername();
}
}
$title_mail = array(
'#amount#' => str_replace(',00', '', number_format((abs($m_amount) / 100), 2, ',', ' ')),
'#source#' => $m_source,
'#type#' => $m_type,
'#comment#' => $draft->getComment()
);
$body_mail = array(
'#office#' => $m_office,
'#type#' => $m_type,
'#amount#' => str_replace(',00', '', number_format((abs($m_amount) / 100), 2, ',', ' ')),
'#date#' => ($draft->getCreatedAt() != null ? $draft->getCreatedAt()->format('d.m.Y') : ''),
'#source#' => $m_source,
'#comment#' => $draft->getComment(),
'#author#' => $author
);
$attach = [];
if($draft->getFile() != null && $draft->getFile() != ''){
if (strpos($draft->getFile(), ';') !== false) {
$filesList = explode(';', $draft->getFile());
if(count($filesList) > 0){
foreach ($filesList as $fileItem){
$filepath = $basePath . $fileDir . trim($fileItem);
if(file_exists($filepath)){
$attach[] = $basePath . $fileDir . trim($fileItem);
}
}
}
} else {
$filepath = $basePath . $fileDir . $draft->getFile();
if(file_exists($filepath)){
$attach[] = $basePath . $fileDir . $draft->getFile();
}
}
}
$this->sendEmail($this->mailer, $typeMail, $body_mail, $title_mail, 'ru', $recipient, $attach);
}
if($draft->getTypeTransaction() == 'add_salary'){
//- 5 000 ЗП Бас Иванов. Сидоров
$amount = "-" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
$reply = $amount . " (" . $from_name . " - " . $to_name . ($office_name != '' ? ", " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
// -333 (Нал Бот - ЗП Бот, тест коммент)
if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $from_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
//+7 500 ЗП Бас Иванов. Петров
$amount = "+" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
$reply = $amount . " (" . $from_name . " - " . $to_name . ($office_name != '' ? ", " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $to_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($draft->getTypeTransaction() == 'add_salary_cash'){
//+5 000 ЗП Бас Иванов. Сидоров
$amount = "+" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
$reply = $amount . " (" . $from_name . " - " . $to_name . ($office_name != '' ? ", " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $from_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
//-7 500 ЗП Бас Иванов. Петров
$amount = "-" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
$reply = $amount . " (" . $from_name . " - " . $to_name . ($office_name != '' ? ", " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $to_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($draft->getTypeTransaction() == 'payment_salary'){
//Начисление зарплаты, вызывается из группы ЗП
//-7 500 ЗП Рук Иванов. Петров
$amount = "-" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . " (ЗП, " . $draft->getComment() . ". " . $from_name . ".)";
$reply = $amount . " (Начисл ЗП. " . ($office_name != '' ? ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $from_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($draft->getTypeTransaction() == 'transfer'){
//- 1 000 Петрову и + 1 000 от Иванова
$amount = "-" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".";
//if($type_group_from == 'salary' && $type_group_to == 'cash'){
// $reply = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
// } else {
$reply = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
//}
if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $from_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
$amount = "+" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . " от " . $from_name . ".";
//if($type_group_from == 'salary' && $type_group_to == 'cash'){
// $reply = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
//} else {
$reply = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
//}
if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $to_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($draft->getTypeTransaction() == 'income'){
//+ 10 000 Бас Иванов. Предоплата ++
$amount = "+" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . ($office_name != '' ? " (" . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : ""). ". " . $from_name . ".)";
$reply = $amount . " (" . $from_name . ", " . ($office_name != '' ? ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $from_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($draft->getTypeTransaction() == 'expense_office'){
//- 3 500 Бас Иванов. Гвозди
$amount = "-" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . ($office_name != '' ? " (" . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ". " . $draft->getComment() . ".)";
$reply = $amount . " (" . $from_name . ", " . ($office_name != '' ? ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ", " . $draft->getComment() . ")";
// +300 (Нал бот, 444. Бургерная, тестовый коммент)
if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $from_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($draft->getTypeTransaction() == 'expense_company'){
//- 1 000 Бизнес. Оплата связи
$amount = "-" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . " (Бизнес. " . $draft->getComment() . ".)";
$reply = $amount . " (Бизнес. " . $draft->getComment() . ".)";
if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $from_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
}
}
}
return $resp;
}
private function uploadFileBot($token, $file_id){
$basePath = $this->getParameter('kernel.project_dir');
$project_dir = $basePath . '/public/images/';
$getFile = ProjectUtilsController::requestToBot($token, 'getFile', ['file_id' => $file_id]);
$resp = json_decode($getFile, true);
//file_put_contents($basePath . '/var/log/file_resp.txt', print_r($resp, true), FILE_APPEND);
$filepath = null;
if(isset($resp['result']['file_path']) && isset($resp['ok']) && $resp['ok'] == true){
$ext = strtolower(substr($resp['result']['file_path'], strrpos($resp['result']['file_path'], '.')));
if($ext === '.jpg' || $ext === '.jpeg' || $ext === '.png' || $ext === '.gif'){
$filename = ProjectUtilsController::generateUuid();
$dir = substr($filename, 0, 3);
if (!is_dir($project_dir . $dir)) {
@mkdir($project_dir);
@mkdir($project_dir . $dir);
}
$file = ProjectUtilsController::fileToBot($token, $resp['result']['file_path']);
file_put_contents($project_dir . $dir . '/' . $filename . $ext, $file);
if(file_exists($project_dir . $dir . '/' . $filename . $ext)){
$filepath = '/' . $dir . '/' . $filename . $ext;
}
}
}
return $filepath;
}
private function createTransaction($token, $chat_id, $group, $draft){
$basePath = $this->getParameter('kernel.project_dir');
$fileDir = '/public/images/';
$is_group_chat = $this->getParameter('app.chat.is_group');
$resp = false;
$em = $this->getDoctrine()->getManager();
$isSendMail = false;
$typeMail = 'newTransaction';
if($token != '' && $token != null && $chat_id != '' && $chat_id != null && $group && $draft){
if($draft->getExpected() == 'finish'){
$amount = $draft->getAmount();
if($draft->getTypeof() == 'expense'){
$amount = '-' . $draft->getAmount();
}
$is_income = false;
//если приход по Объекту, или начисление ЗП
if(!$draft->getFromGroup() && $draft->getToGroup()){
$is_income = true;
}
$office_name = '';
$office_number = '';
if($draft->getOffice()){
$office_name = $draft->getOffice()->getName();
$office_number = $draft->getOffice()->getNumber();
}
$from_chat_id = null;
$from_name = '';
$type_group_from = null;
if($draft->getFromGroup()){
$from_chat_id = $draft->getFromGroup()->getChatId();
$from_name = $draft->getFromGroup()->nameClient();
$type_group_from = ($draft->getFromGroup()->getTypeGroup() != null ? $draft->getFromGroup()->getTypeGroup()->getTypeof() : null);
}
$to_chat_id = null;
$to_name = '';
$type_group_to = null;
if($draft->getToGroup()){
$to_chat_id = $draft->getToGroup()->getChatId();
$to_name = $draft->getToGroup()->nameClient();
$type_group_to = ($draft->getToGroup()->getTypeGroup() != null ? $draft->getToGroup()->getTypeGroup()->getTypeof() : null);
}
//если приход по Объекту, или начисление ЗП
if($is_income === true && $draft->getToGroup()){
$from_chat_id = $draft->getToGroup()->getChatId();
$from_name = $draft->getToGroup()->nameClient();
}
$m_source = '';
$m_type = '';
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')){
$isSendMail = true;
$m_source = ($draft->getFromGroup() != null ? $draft->getFromGroup()->getFirstName() : '');
if($draft->getTypeTransaction() == 'expense_office'){
// +300 (Нал бот, 444. Бургерная, тестовый коммент)
$cm = $amount . " (" . $from_name . ", " . ($office_name != '' ? ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ", " . $draft->getComment() . ")";
if($draft->getFile() != '' && $draft->getFile() != null){
$typeMail = 'newTransactionIncomeCashСheque';
$m_type = 'расход Чек';
} else {
$typeMail = 'newTransactionIncomeCashNoСheque';
$m_type = 'расход Нал';
}
} elseif($draft->getTypeTransaction() == 'income' && $draft->getTypeof() == 'income'){
// +555 (Нал Бот, 24195. Пробник, тест коммент)
$cm = $amount . " (" . $from_name . ", " . ($office_name != '' ? ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ", " . $draft->getComment() . ")";
//$m_source = ($draft->getFromGroup() != null ? $draft->getFromGroup()->getFirstName() : '');
$m_source = ($draft->getToGroup() != null ? $draft->getToGroup()->getFirstName() : '');
$m_type = 'приход Нал';
$typeMail = 'newTransactionIncomeCash';
} elseif($draft->getTypeTransaction() == 'add_salary' && $draft->getTypeof() == 'expense'){
// -333 (Нал Бот - ЗП Бот, тест коммент)
$cm = '-' . $amount . " (" . $from_name . " - " . $to_name . ", " . ($office_name != '' ? ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ", " . $draft->getComment() . ")";
$m_source = ($draft->getToGroup() != null ? $draft->getToGroup()->getFirstName() : '');
$m_type = 'расход ЗП';
$typeMail = 'newTransactionExpenseSalary';
} elseif($draft->getTypeTransaction() == 'transfer' && $draft->getTypeof() == 'expense'){
$isSendMail = false; //просили отключить
// - 1 000 Петрову и + 1 000 от Иванова
$cm = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
$m_source = ($draft->getFromGroup() != null ? $draft->getFromGroup()->getFirstName() : '');
$m_type = 'списание ЗП';
$typeMail = 'newTransactionTransferSalary';
} elseif($draft->getTypeTransaction() == 'add_salary_cash' && $draft->getTypeof() == 'income'){
//+5 000 ЗП Бас Иванов. Сидоров
$cm = $amount . " (" . $from_name . " - " . $to_name . ($office_name != '' ? ", " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
$m_source = ($draft->getToGroup() != null ? $draft->getToGroup()->getFirstName() : '');
$m_type = 'списание ЗП';
$typeMail = 'newTransactionAddSalaryCash';
}
}
$isReverseAmount = false;
//просили убрать чтоб начисление ЗП с отрицательным знаком чтоб корректировать сумму начислений в сторону уменьшения
if($draft->getAmount() < 0 && $draft->getTypeTransaction() == 'payment_salary' && $draft->getTypeof() == 'expense'){
$draft->setTypeof('income');
$draft->setAmount(abs($draft->getAmount()));
$em->persist($draft);
$em->flush();
$amount = $draft->getAmount();
$isReverseAmount = true;
}
$newTransaction = new Transaction();
if($draft->getClient()){
$newTransaction->setSender($draft->getClient());
}
if($draft->getFromGroup()){
$newTransaction->setFromGroup($draft->getFromGroup());
}
if($draft->getToGroup()){
$newTransaction->setToGroup($draft->getToGroup());
}
if($draft->getOffice()){
$newTransaction->setOffice($draft->getOffice());
}
$newTransaction->setTypeof($draft->getTypeof());
$newTransaction->setAmount($amount);
$newTransaction->setComment($draft->getComment());
$newTransaction->setNote($draft->getNote());
$newTransaction->setDate(new \DateTime(date('Y-m-d H:i:s')));
if($is_income === false){
$newTransaction->setRecipient($draft->getFromGroup());
} else {
$newTransaction->setRecipient($draft->getToGroup());
}
if($draft->getFile() != '' && $draft->getFile() != null){
$newTransaction->setFile($draft->getFile());
}
$em->persist($newTransaction);
$em->flush();
$amount_reverse = 0;
if($draft->getToGroup() && $draft->getFromGroup()){
$typeof_reverse = null;
if($draft->getTypeof() == 'expense'){
$typeof_reverse = 'income';
} elseif($draft->getTypeof() == 'income'){
$typeof_reverse = 'expense';
}
$amount_reverse = $draft->getAmount();
if($typeof_reverse == 'expense'){
$amount_reverse = '-' . $draft->getAmount();
}
$newTransactionReverse = new Transaction();
if($draft->getClient()){
$newTransactionReverse->setSender($draft->getClient());
}
if($draft->getFromGroup()){
$newTransactionReverse->setFromGroup($draft->getFromGroup());
}
if($draft->getToGroup()){
$newTransactionReverse->setToGroup($draft->getToGroup());
}
if($draft->getOffice()){
$newTransactionReverse->setOffice($draft->getOffice());
}
$newTransactionReverse->setTypeof($typeof_reverse);
$newTransactionReverse->setAmount($amount_reverse);
$newTransactionReverse->setComment($draft->getComment());
$newTransactionReverse->setNote($draft->getNote());
$newTransactionReverse->setDate(new \DateTime(date('Y-m-d H:i:s')));
$newTransactionReverse->setRecipient($draft->getToGroup());
$em->persist($newTransactionReverse);
$em->flush();
}
if($newTransaction) {
$balance = false;
$from_group = $draft->getFromGroup();
//если приход по Объекту, или начисление ЗП
if($is_income === true && $draft->getToGroup()){
$from_group = $draft->getToGroup();
}
if ($draft->getTypeof() == 'expense') {
$balance = $from_group->getBalance() - $draft->getAmount();
} elseif ($draft->getTypeof() == 'income') {
$balance = $from_group->getBalance() + $draft->getAmount();
}
if ($balance != $from_group->getBalance()) {
$from_group->setBalance($balance);
$em->persist($from_group);
$em->flush();
}
if ($draft->getTypeof() == 'expense' && $draft->getToGroup() && $is_income === false) {
$to_group = $draft->getToGroup();
$to_balance = $to_group->getBalance() + $draft->getAmount();
if ($to_balance != $to_group->getBalance()) {
$to_group->setBalance($to_balance);
$em->persist($to_group);
$em->flush();
}
}
$resp = true;
if($isSendMail){
//отправка письма по операциям
$recipient = $this->getParameter('app.mailer.to.transaction');
$m_amount = $newTransaction->getAmount();
$m_office = ($newTransaction->getOffice() != null ? ($newTransaction->getOffice()->getNumber() != '' && $newTransaction->getOffice()->getNumber() != null ? $newTransaction->getOffice()->getNumber() . '. ' : '') . $newTransaction->getOffice()->getName() : '');
$is_cheque = ($newTransaction->getFile() != null && $newTransaction != '' && file_exists($basePath . $fileDir . $newTransaction->getFile()) ? true : false);
$author = '';
if($newTransaction->getSender() != null){
if($newTransaction->getSender()->getUsername() != null && $newTransaction->getSender()->getUsername() != ''){
$author = $newTransaction->getSender()->getUsername();
}
}
$title_mail = array(
'#amount#' => str_replace(',00', '', number_format((abs($m_amount) / 100), 2, ',', ' ')),
'#source#' => $m_source,
'#type#' => $m_type,
'#comment#' => $newTransaction->getComment()
);
$body_mail = array(
'#office#' => $m_office,
'#type#' => $m_type,
'#amount#' => str_replace(',00', '', number_format((abs($m_amount) / 100), 2, ',', ' ')),
'#date#' => ($newTransaction->getDate() != null ? $newTransaction->getDate()->format('d.m.Y') : ''),
'#source#' => $m_source,
'#comment#' => $newTransaction->getComment(),
//'#cheque#' => ($is_cheque ? 'есть' : 'нет'),
'#author#' => $author
);
$attach = [];
if($newTransaction->getFile() != null && $newTransaction->getFile() != ''){
if (strpos($newTransaction->getFile(), ';') !== false) {
$filesList = explode(';', $newTransaction->getFile());
if(count($filesList) > 0){
foreach ($filesList as $fileItem){
$filepath = $basePath . $fileDir . trim($fileItem);
if(file_exists($filepath)){
$attach[] = $basePath . $fileDir . trim($fileItem);
}
}
}
} else {
$filepath = $basePath . $fileDir . $newTransaction->getFile();
if(file_exists($filepath)){
$attach[] = $basePath . $fileDir . $newTransaction->getFile();
}
}
}
$this->sendEmail($this->mailer, $typeMail, $body_mail, $title_mail, 'ru', $recipient, $attach);
}
}
if($draft->getTypeTransaction() == 'add_salary'){
//- 5 000 ЗП Бас Иванов. Сидоров
$amount = "-" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
$reply = $amount . " (" . $from_name . " - " . $to_name . ($office_name != '' ? ", " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
// -333 (Нал Бот - ЗП Бот, тест коммент)
if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $from_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
//+7 500 ЗП Бас Иванов. Петров
$amount = "+" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
$reply = $amount . " (" . $from_name . " - " . $to_name . ($office_name != '' ? ", " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $to_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($draft->getTypeTransaction() == 'add_salary_cash'){
//+5 000 ЗП Бас Иванов. Сидоров
$amount = "+" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
$reply = $amount . " (" . $from_name . " - " . $to_name . ($office_name != '' ? ", " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $from_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
//-7 500 ЗП Бас Иванов. Петров
$amount = "-" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . " (ЗП" . ($office_name != '' ? " " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".)";
$reply = $amount . " (" . $from_name . " - " . $to_name . ($office_name != '' ? ", " . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $to_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($draft->getTypeTransaction() == 'payment_salary'){
//-7 500 ЗП Рук Иванов. Петров
$amount = (!$isReverseAmount ? "-" : "") . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . " (ЗП, " . $draft->getComment() . ". " . $from_name . ".)";
$reply = $amount . " (Начисл ЗП. " . ($office_name != '' ? ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $from_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($draft->getTypeTransaction() == 'transfer'){
//- 1 000 Петрову и + 1 000 от Иванова
$amount = "-" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ". " . $to_name . ".";
//if($type_group_from == 'salary' && $type_group_to == 'cash'){
// $reply = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
// } else {
$reply = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
//}
if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $from_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
$amount = "+" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . " от " . $from_name . ".";
//if($type_group_from == 'salary' && $type_group_to == 'cash'){
// $reply = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
//} else {
$reply = $amount . " (" . $from_name . " - " . $to_name . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
//}
if($to_chat_id != '' && $to_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $to_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($draft->getTypeTransaction() == 'income'){
//+ 10 000 Бас Иванов. Предоплата ++
$amount = "+" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . ($office_name != '' ? " (" . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : ""). ". " . $from_name . ".)";
$reply = $amount . " (" . $from_name . ", " . ($office_name != '' ? ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ($draft->getComment() != null && $draft->getComment() != '' ? ", " . $draft->getComment() : "") . ")";
if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $from_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($draft->getTypeTransaction() == 'expense_office'){
//- 3 500 Бас Иванов. Гвозди
$amount = "-" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . ($office_name != '' ? " (" . ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ". " . $draft->getComment() . ".)";
$reply = $amount . " (" . $from_name . ", " . ($office_name != '' ? ($office_number != '' && $office_number != null ? $office_number . '. ' : '') . $office_name : "") . ", " . $draft->getComment() . ")";
// +300 (Нал бот, 444. Бургерная, тестовый коммент)
if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $from_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($draft->getTypeTransaction() == 'expense_company'){
//- 1 000 Бизнес. Оплата связи
$amount = "-" . str_replace(',00', '', number_format(($draft->getAmount() / 100), 2, ',', ' '));
//$reply = $amount . " (Бизнес. " . $draft->getComment() . ".)";
$reply = $amount . " (Бизнес. " . $draft->getComment() . ".)";
if($from_chat_id != '' && $from_chat_id != null && $reply != ''){
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $from_chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
}
}
}
return $resp;
}
private function office($token, $chat_id, $group_id, $cq_data = array(), $curClient = false, $text = null, $message_id = null) {
$basePath = $this->getParameter('kernel.project_dir');
$is_group_chat = $this->kernel->getContainer()->getParameter('app.chat.is_group');
$action = null;
$p_group = null;
$keyboard = array();
$em = $this->getDoctrine()->getManager();
if(count($cq_data) > 0){
$action = (isset($cq_data['action']) ? $cq_data['action'] : null);
$p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
}
$expected = null;
$p_id = null;
if($curClient){
$data_expected = $this->dataExpected($curClient->getExpected());
if(isset($data_expected['value'])){
$expected = $data_expected['value'];
}
if(isset($data_expected['group'])){
$p_group = $data_expected['group'];
}
if(isset($data_expected['id'])){
$p_id = $data_expected['id'];
}
}
if(count($cq_data) > 0 && $action != 'menu'){
$groupObj = false;
if($group_id != null && $group_id != ''){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
} elseif($p_group != null && $p_group != '') {
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
if($is_group_chat === true && $groupObj){
$chat_id = $groupObj->getChatId();
}
if($action == 'add'){
$reply = 'Введите уникальный номер объекта';
$clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
$this->addExpected($clientObj, array("value" => "new_office", "group" => $p_group));
$keyboard = array(
array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "office", "group" => $p_group))
)
)
);
// $reply = 'Введите название нового объекта';
// $clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
// $this->addExpected($clientObj, array("value" => "new_office", "group" => $p_group));
// $keyboard = array(
// array(
// array(
// 'text'=>'Назад',
// 'callback_data'=> json_encode(array('action' => "menu", 'command' => "office", "group" => $p_group))
// )
// )
// );
} elseif($action == 'edit_list' || $action == 'rem_list') {
$offices = $this->getDoctrine()
->getRepository(Office::class)
->createQueryBuilder('o')
->select('o.id, o.name, o.number')
->where('o.is_active = 1')
->getQuery()
->getArrayResult();
if(count($offices) > 0){
$reply = 'Выберите из списка объект для ' . ($action == 'rem_list' ? 'удаления' : 'редактирования') . ".";
$buttons = array();
foreach ($offices as $item_office){
$buttons[][] = array(
'text' => ($item_office['number'] != '' && $item_office['number'] != null ? $item_office['number'] . '. ' : '') . $item_office['name'],
'callback_data'=> json_encode(array('action' => ($action == 'rem_list' ? "rem" : "edit"), 'command' => "office", 'id' => $item_office['id'], "group" => $p_group))
);
}
$keyboard = $buttons;
$keyboard[] = array(
array(
'text'=> 'Назад',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "office", "group" => $p_group))
)
);
} else {
$reply = 'Для ' . ($action == 'rem_list' ? 'удаления' : 'редактирования') . ' нет ни одного объекта.';
$keyboard = array(
array(
array(
'text'=>'Создать объект',
'callback_data'=> json_encode(array('action' => "add", 'command' => "office", "group" => $p_group))
)
)
);
}
} elseif($action == 'edit' || $action == 'rem') {
$officeObj = false;
if(isset($cq_data['id'])){
$officeObj = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
}
$is_rem = false;
if($officeObj){
if($action == 'rem'){
$reply = 'Вы действительно хотите удалить объект «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null ? $officeObj->getNumber() . '. ' : '') . $officeObj->getName() . '»?';
$is_rem = true;
} else {
$clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
$reply = 'Выберите, что хотите отредатировать у объекта «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null ? $officeObj->getNumber() . '. ' : '') . $officeObj->getName() . '»';
$keyboard = array(
array(
array(
'text'=>'Номер объекта',
'callback_data'=> json_encode(array('action' => "edit_number", 'command' => "office", "id" => $officeObj->getId(), "group" => $p_group))
),
array(
'text'=>'Название объекта',
'callback_data'=> json_encode(array('action' => "edit_name", 'command' => "office", "id" => $officeObj->getId(), "group" => $p_group))
),
)
);
// $clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
// $reply = 'Введите новое название для объекта «' . $officeObj->getName() . '»';
// $this->addExpected($clientObj, array("value" => "edit_office", "id" => $officeObj->getId(), "group" => $p_group));
}
} else {
$reply = 'Не удалось найти данный объект. Попробуйте повторить попытку ' . ($action == 'rem' ? 'удаления' : 'редактирования') . ' данного объекта позже.';
}
if($is_rem === true){
$keyboard = array(
array(
array(
'text'=>'Да, удалить',
'callback_data'=> json_encode(array('action' => "rem_ok", 'command' => "office", "id" => $officeObj->getId(), "group" => $p_group))
)
)
);
}
$keyboard[] = array(
array(
'text'=> ($is_rem === false ? 'Назад' : 'Нет, назад'),
'callback_data'=> json_encode(array('action' => ($action == 'rem' ? "rem_list" : "edit_list"), 'command' => "office", "group" => $p_group))
)
);
$keyboard[] = array(
array(
'text'=> ($is_rem === false ? 'В основное меню объектов' : 'Нет, в основное меню объектов'),
'callback_data'=> json_encode(array('action' => "menu", 'command' => "office", "group" => $p_group))
)
);
} elseif($action == 'rem_ok') {
$officeObj = false;
if(isset($cq_data['id'])){
$officeObj = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
}
if($officeObj){
$reply = 'Объект «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null ? $officeObj->getNumber() . '. ' : '') . $officeObj->getName() . '» успешно удален.';
$officeObj->setIsActive(0);
$em->persist($officeObj);
$em->flush();
$keyboard = array(
array(
array(
'text'=> 'Назад',
'callback_data'=> json_encode(array('action' => "rem_list", 'command' => "office", "group" => $p_group))
)
),
array(
array(
'text'=> 'В основное меню объектов',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "office", "group" => $p_group))
)
)
);
} else {
$reply = 'Не удалось найти данный объект. Попробуйте повторить попытку удаления данного объекта позже.';
}
} elseif($action == 'delete'){
$mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
if($mes_id != '' && $mes_id != null){
$deleteMessage = ProjectUtilsController::requestToBot($token, 'deleteMessage', ['chat_id' => $chat_id, 'message_id' => $mes_id]);
}
if($cq_data['group'] != '' && $cq_data['group'] != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
if($groupObj){
if(file_exists($basePath . '/var/log/' . $chat_id . '-' . $groupObj->getId() . '.txt')){
$mes_id = file_get_contents($basePath . '/var/log/' . $chat_id . '-' . $groupObj->getId() . '.txt');
if($mes_id != '' && $mes_id != null){
$deleteMessage = ProjectUtilsController::requestToBot($token, 'deleteMessage', ['chat_id' => $chat_id, 'message_id' => $mes_id]);
$resp = json_decode($deleteMessage, true);
if(isset($resp['result'])){
if($resp['result'] == true){
unlink($basePath . '/var/log/' . $chat_id . '-' . $groupObj->getId() . '.txt');
}
}
}
}
}
}
} elseif($action == 'edit_number' || $action == 'edit_name'){
$officeObj = false;
if(isset($cq_data['id'])){
$officeObj = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $cq_data['id']));
}
$clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
if($action == 'edit_name'){
$reply = 'Введите новое название для объекта «' . ($officeObj->getNumber() != null && $officeObj->getName() != '' ? $officeObj->getName() . '. ' : '') . $officeObj->getName() . '»';
$this->addExpected($clientObj, array("value" => "edit_office", "id" => $officeObj->getId(), "group" => $p_group));
} else {
$reply = 'Введите новый номер для объекта «' . ($officeObj->getNumber() != null && $officeObj->getName() != '' ? $officeObj->getName() . '. ' : '') . $officeObj->getName() . '»';
$this->addExpected($clientObj, array("value" => "edit_n_office", "id" => $officeObj->getId(), "group" => $p_group));
}
$keyboard[] = array(
array(
'text'=> 'Назад',
'callback_data'=> json_encode(array('action' => 'edit', "id" => $officeObj->getId(), 'command' => "office", "group" => $p_group))
)
);
$keyboard[] = array(
array(
'text'=> 'В основное меню объектов',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "office", "group" => $p_group))
)
);
}
} elseif($expected != '' && $expected != null){
$groupObj = false;
if($group_id != '' && $group_id != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
} elseif($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
if($is_group_chat === true && $groupObj){
$chat_id = $groupObj->getChatId();
}
if($expected == 'new_office'){
if($curClient && $text != '' && $text != null){
$officeObj = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('number' => trim($text)));
if($officeObj){
if($officeObj->getIsActive() == '1'){
$reply = 'Объект c номером «' . $officeObj->getName() . '» уже существует. Введите другой номер объекта.';
} else {
$officeObj->setIsActive(1);
$em->persist($officeObj);
$em->flush();
$reply = 'Объект «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null ? $officeObj->getNumber() . '. ' : '') . $officeObj->getName() . '» снова активен.';
}
} else {
$newOffice = new Office();
$newOffice->setName('');
$newOffice->setNumber(trim($text));
$newOffice->setIsActive(0);
$em->persist($newOffice);
$em->flush();
$clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
$reply = 'Введите название объекта';
$this->addExpected($clientObj, array("value" => "name_office", "id" => $newOffice->getId(), "group" => $p_group));
}
//$this->resetExpected($curClient);
} elseif($expected == 'new_office') {
$reply = 'Введите номер нового объекта.';
}
// if($curClient && $text != '' && $text != null){
// $officeObj = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('name' => trim($text)));
// if($officeObj){
// if($officeObj->getIsActive() == '1'){
// $reply = 'Объект «' . $officeObj->getName() . '» уже существует. Введите другое название объекта.';
// } else {
// $officeObj->setIsActive(1);
// $em->persist($officeObj);
// $em->flush();
//
// $reply = 'Объект «' . $officeObj->getName() . '» снова активен.';
// }
// } else {
// $newOffice = new Office();
// $newOffice->setName(trim($text));
// $newOffice->setIsActive(1);
// $em->persist($newOffice);
// $em->flush();
//
// $reply = 'Добавлен новый объект «' . $newOffice->getName() . '».';
// }
//
// $this->resetExpected($curClient);
// } elseif($expected == 'new_office') {
// $reply = 'Введите название нового объекта.';
// }
$keyboard = array(
array(
array(
'text'=> 'Назад',
'callback_data'=> json_encode(array('action' => "edit_list", 'command' => "office", "group" => $p_group))
)
),
array(
array(
'text'=> 'В основное меню объектов',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "office", "group" => $p_group))
)
)
);
} elseif($expected == 'edit_office') {
$officeObj = false;
if(isset($data_expected['id'])){
$officeObj = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $data_expected['id']));
}
if($officeObj && $curClient && $text != '' && $text != null){
$name_last = ($officeObj->getNumber() != '' && $officeObj->getNumber() != null ? $officeObj->getNumber() . '. ' : '') . $officeObj->getName();
$officeTmp = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('name' => trim($text)));
if(!$officeTmp){
$officeObj->setName(trim($text));
if($officeObj->getIsActive() != '1'){
$officeObj->setIsActive(1);
}
$em->persist($officeObj);
$em->flush();
$reply = 'Объект «' . $name_last . '» успешно переименован в «' . ($officeObj->getNumber() != null && $officeObj->getNumber() != '' ? $officeObj->getNumber() . '. ' : '') . trim($text) . '».';
$this->resetExpected($curClient);
} else {
$reply = 'Невозможно объект «' . $name_last . '» переименовать в «' . ($officeObj->getNumber() != null && $officeObj->getNumber() != '' ? $officeObj->getNumber() . '. ' : '') . trim($text) . '», объект с таким названием уже существует. Введите другое название.';
}
}
$keyboard = array(
array(
array(
'text'=> 'Назад',
'callback_data'=> json_encode(array('action' => "edit_list", 'command' => "office", "group" => $p_group))
)
),
array(
array(
'text'=> 'В основное меню объектов',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "office", "group" => $p_group))
)
)
);
} elseif($expected == 'edit_n_office') {
$officeObj = false;
if(isset($data_expected['id'])){
$officeObj = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $data_expected['id']));
}
if($officeObj && $curClient && $text != '' && $text != null){
$name_last = ($officeObj->getNumber() != '' && $officeObj->getNumber() != null ? $officeObj->getNumber() . '. ' : '') . $officeObj->getName();
$officeTmp = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('number' => trim($text), 'name' => $officeObj->getName()));
if(!$officeTmp){
$officeObj->setNumber(trim($text));
if($officeObj->getIsActive() != '1'){
$officeObj->setIsActive(1);
}
$em->persist($officeObj);
$em->flush();
$reply = 'Объект «' . $name_last . '» успешно переименован в «' . ($officeObj->getNumber() != null && $officeObj->getNumber() != '' ? $officeObj->getNumber() . '. ' : '') . $officeObj->getName() . '».';
$this->resetExpected($curClient);
} else {
$reply = 'Невозможно объект «' . $name_last . '» переименовать в «' . trim($text) . '. ' . $officeObj->getName() . '», объект с таким названием уже существует. Введите другое название.';
}
}
$keyboard = array(
array(
array(
'text'=> 'Назад',
'callback_data'=> json_encode(array('action' => "edit_list", 'command' => "office", "group" => $p_group))
)
),
array(
array(
'text'=> 'В основное меню объектов',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "office", "group" => $p_group))
)
)
);
} elseif($expected == 'name_office'){
if($curClient && $text != '' && $text != null){
if($p_id != '' && $p_id != null){
$officeObj = $this->getDoctrine()->getRepository(Office::class)->findOneBy(array('id' => $p_id));
if($officeObj){
$officeObj->setName(trim($text))
->setIsActive(1);
$em->persist($officeObj);
$em->flush();
$reply = 'Добавлен новый объект «' . ($officeObj->getNumber() != '' && $officeObj->getNumber() != null ? $officeObj->getNumber() . '. ' : '') . $officeObj->getName() . '».';
}
}
$this->resetExpected($curClient);
} elseif($expected == 'new_office') {
$reply = 'Введите название нового объекта.';
}
$keyboard = array(
array(
array(
'text'=> 'В основное меню объектов',
'callback_data'=> json_encode(array('action' => "menu", 'command' => "office", "group" => $p_group))
)
)
);
}
} else {
$groupObj = false;
if($group_id != '' && $group_id != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
} elseif($p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
if($is_group_chat === true && $groupObj){
$chat_id = $groupObj->getChatId();
}
$reply = 'Выберите действие над объектом.';
$offices = $this->getDoctrine()
->getRepository(Office::class)
->createQueryBuilder('o')
->select('o.id, o.name')
->where('o.is_active = 1')
->getQuery()
->getArrayResult();
$keyboard = array(
array(
array(
'text'=>'Создать объект',
'callback_data'=> json_encode(array('action' => "add", 'command' => "office", "group" => ($groupObj ? $groupObj->getId() : null)))
)
)
);
if(count($offices) > 0){
$keyboard[] = array(
array(
'text'=>'Редактировать объект',
'callback_data'=> json_encode(array('action' => "edit_list", 'command' => "office", "group" => ($groupObj ? $groupObj->getId() : null)))
),
);
$keyboard[] = array(
array(
'text'=>'Удалить объект',
'callback_data'=> json_encode(array('action' => "rem_list", 'command' => "office", "group" => ($groupObj ? $groupObj->getId() : null)))
),
);
$keyboard[] = array(
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "delete", 'command' => "office", 'mes_id' => $message_id, "group" => ($groupObj ? $groupObj->getId() : null)))
)
);
}
}
$sendMessage = false;
if(count($keyboard) > 0){
$reply_markup = ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
$resp = json_decode($sendMessage, true);
if(isset($resp['result']['message_id']) && $groupObj){
file_put_contents($basePath . '/var/log/' . $chat_id . '-' . $groupObj->getId() . '.txt', $resp['result']['message_id']);
}
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
if($is_group_chat === true){
$bot = $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
$command = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'office'));
$this->addLogMessageBot($bot, $command, $sendMessage);
}
}
private function users($token, $chat_id, $group_id, $cq_data = array(), $curClient = false, $text = null, $message_id = null) {
$basePath = $this->getParameter('kernel.project_dir');
$is_group_chat = $this->kernel->getContainer()->getParameter('app.chat.is_group');
$action = null;
$p_group = null;
$keyboard = array();
$em = $this->getDoctrine()->getManager();
$expected = null;
if(count($cq_data) > 0){
$action = (isset($cq_data['action']) ? $cq_data['action'] : null);
$p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
}
if($curClient){
$data_expected = $this->dataExpected($curClient->getExpected());
if(isset($data_expected['value'])){
$expected = $data_expected['value'];
}
if(isset($data_expected['group'])){
$p_group = $data_expected['group'];
}
}
$sendMessage = false;
if(count($cq_data) > 0 && $action != 'list'){
$groupObj = false;
if($group_id != '' && $group_id != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
} elseif($p_group != '' && $p_group != null && $action == 'list'){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
if($is_group_chat === true && $groupObj){
$chat_id = $groupObj->getChatId();
}
$em = $this->getDoctrine()->getManager();
$reply = 'Не удалось получить информацию о пользователе.';
if($action == 'show'){
$clientObj = false;
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
}
}
if($clientObj){
$name_client = $clientObj->nameClient();
$reply = 'Выберите, что хотите изменить у пользователя ' . $name_client . ".";
$keyboard = array(
array(
array(
'text'=>'Изменить роль',
'callback_data'=> json_encode(array('action' => "role", 'command' => "users", 'id' => $clientObj->getId(), "group" => $p_group))
)
),
// array(
// array(
// 'text'=>'Изменить email',
// 'callback_data'=> json_encode(array('action' => "email", 'id' => $clientObj->getId(), 'command' => "users", "group" => $p_group))
// ),
// ),
array(
array(
'text'=>'К списку всех пользователей',
'callback_data'=> json_encode(array('action' => "list", 'command' => "users", "group" => $p_group))
),
)
);
} else {
$reply = 'Невозможно продолжить действие, пользователь не найден.';
}
if(count($keyboard) > 0){
$reply_markup = ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($action == 'role'){
$clientObj = false;
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
}
}
if($clientObj){
$name_client = $clientObj->nameClient();
$name_role = null;
if($clientObj->getRole()){
$name_role = $clientObj->getRole()->getName();
}
$buttons = array();
$roles = $this->getDoctrine()
->getRepository(Role::class)
->createQueryBuilder('r')
->select('r.id, r.name')
->getQuery()
->getArrayResult();
if(count($roles) > 0){
foreach ($roles as $item_role){
$buttons[][] = array(
'text' => $item_role['name'],
'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()))
);
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "show", 'command' => "users", 'id' => $clientObj->getId(), "group" => ($groupObj ? $groupObj->getId() : null)))
);
}
if($name_client != '' && $name_client != null){
$reply = 'У пользователя ' . $name_client . ' пока нет роли.';
if($name_role != '' && $name_role != null){
$reply = 'У пользователя ' . $name_client . ' текущая роль «' . $name_role . '». Чтобы поменять роль выберите необходимую из списка.';
}
}
if(count($buttons) > 0){
if($name_role != '' && $name_role != null){
$reply = $reply . ' Чтобы поменять роль выберите необходимую из списка.';
} else {
$reply = $reply . ' Выберите необходимую роль из списка.';
}
} else {
$reply = $reply . ' Ролей для выбора пока нет, попробуйте выбрать позже.';
}
$keyboard = $buttons;
}
if(count($keyboard) > 0){
$reply_markup = ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($action == 'add'){
$reply = 'При попытке поменять роль у пользователя произошла ошибка. Попробуйте повторить попытку позже.';
$keyboard = array();
if(isset($cq_data['client']) && isset($cq_data['id'])){
if($cq_data['client'] != '' && $cq_data['client'] != null && $cq_data['id'] != '' && $cq_data['client'] != null){
$clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['client'], 'typeof' => 'private'));
$roleObj = $this->getDoctrine()->getRepository(Role::class)->findOneBy(array('id' => $cq_data['id']));
if($clientObj && $roleObj){
$clientObj->setRole($roleObj);
$em->persist($clientObj);
$em->flush();
$name_role = $roleObj->getName();
$name_client = $clientObj->nameClient();
$reply = 'У пользователя ' . $name_client . ' выбрана роль «' . $name_role . '».';
$keyboard = array(
array(
array(
'text'=>'Выбрать новую роль',
'callback_data'=> json_encode(array('action' => "show", 'command' => "users", 'id' => $clientObj->getId(), "group" => $p_group))
)
),
array(
array(
'text'=>'К списку всех пользователей',
'callback_data'=> json_encode(array('action' => "list", 'command' => "users", "group" => $p_group))
),
)
);
}
}
}
if(count($keyboard) > 0){
$reply_markup = ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($action == 'email'){
$clientObj = false;
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
}
}
$keyboard = array();
if($clientObj){
$name_client = $clientObj->nameClient();
$email = $clientObj->getEmail();
if($email != '' && $email != null){
$reply = 'У пользователя ' . $name_client . ' указан email «' . $email . '», можете поменять его.';
$keyboard = array(
array(
array(
'text'=>'Изменить email',
'callback_data'=> json_encode(array('action' => "edit_email", 'id' => $clientObj->getId(), 'command' => "users", "group" => $p_group))
),
),
array(
array(
'text'=>'К списку всех пользователей',
'callback_data'=> json_encode(array('action' => "list", 'command' => "users", "group" => $p_group))
),
)
);
} else {
$reply = 'У пользователя ' . $name_client . ' не указан email, можете добавить его.';
$keyboard = array(
array(
array(
'text'=>'Добавить email',
'callback_data'=> json_encode(array('action' => "add_email", 'id' => $clientObj->getId(), 'command' => "users", "group" => $p_group))
),
),
array(
array(
'text'=>'К списку всех пользователей',
'callback_data'=> json_encode(array('action' => "list", 'command' => "users", "group" => $p_group))
),
)
);
}
} else {
$reply = 'Невозможно продолжить действие, пользователь не найден.';
}
if(count($keyboard) > 0){
$reply_markup = ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($action == 'add_email' || $action == 'edit_email'){
$clientObj = false;
if($is_group_chat === true){
if(isset($cq_data['group'])){
if($cq_data['group'] != '' && $cq_data['group'] != null){
$clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
}
} elseif(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
}
}
} else {
if(isset($cq_data['id'])){
if($cq_data['id'] != '' && $cq_data['id'] != null){
$clientObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['id']));
}
}
}
$keyboard = array();
if($clientObj){
$name_client = $clientObj->nameClient();
$reply = 'Введите email, который хотите добавить пользователю ' . $name_client . ".";
$this->addExpected($clientObj, array("value" => "email", "group" => $p_group));
} else {
$reply = 'Невозможно продолжить действие, пользователь не найден.';
}
if(count($keyboard) > 0){
$reply_markup = ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($action == 'delete'){
$mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
if($mes_id != '' && $mes_id != null){
$deleteMessage = ProjectUtilsController::requestToBot($token, 'deleteMessage', ['chat_id' => $chat_id, 'message_id' => $mes_id]);
}
if($cq_data['group'] != '' && $cq_data['group'] != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
if($groupObj){
if(file_exists($basePath . '/var/log/' . $chat_id . '-' . $groupObj->getId() . '.txt')){
$mes_id = file_get_contents($basePath . '/var/log/' . $chat_id . '-' . $groupObj->getId() . '.txt');
if($mes_id != '' && $mes_id != null){
$deleteMessage = ProjectUtilsController::requestToBot($token, 'deleteMessage', ['chat_id' => $chat_id, 'message_id' => $mes_id]);
$resp = json_decode($deleteMessage, true);
if(isset($resp['result'])){
if($resp['result'] == true){
unlink($basePath . '/var/log/' . $chat_id . '-' . $groupObj->getId() . '.txt');
}
}
}
}
}
}
}
} elseif($expected != '' && $expected != null){
$groupObj = false;
if($group_id != '' && $group_id != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
} elseif($p_group != '' && $p_group != null && $action == 'list'){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
if($is_group_chat === true && $groupObj){
$chat_id = $groupObj->getChatId();
}
if($expected == 'email'){
if($curClient && $text != '' && $text != null){
$name_client = $curClient->nameClient();
$reply = 'Email ' . $text . ' успешно добавлен пользователю ' . $name_client . ".";
$curClient->setEmail(trim($text));
$em->persist($curClient);
$em->flush();
$this->resetExpected($curClient);
$keyboard = array(
array(
array(
'text'=>'К списку всех пользователей',
'callback_data'=> json_encode(array('action' => "list", 'command' => "users", "group" => $p_group))
),
)
);
} elseif(!$curClient) {
$reply = 'Невозможно продолжить действие, пользователь не найден.';
}
}
if(count($keyboard) > 0){
$reply_markup = ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} else {
$reply = 'Пока нет ни одного пользователя для редактирования у него роли.';
$clients = $this->getDoctrine()
->getRepository(Client::class)
->createQueryBuilder('c')
->select('c.id, c.first_name, c.last_name, c.username, r.name AS name_role')
->where('c.typeof = :typeof')
->leftJoin(Role::class, 'r', 'WITH', 'c.role = r.id')
->setParameter('typeof', 'private')
->getQuery()
->getArrayResult();
$groupObj = false;
if($group_id != '' && $group_id != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
} elseif($p_group != '' && $p_group != null && $action == 'list'){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
if($is_group_chat === true && $groupObj){
$chat_id = $groupObj->getChatId();
}
$buttons = array();
if(count($clients) > 0){
$reply = 'Выберите пользователя, у которого хотите отредактировать информацию.';
foreach ($clients as $item_client){
$name_client = $this->nameClient($item_client['first_name'], $item_client['last_name'], $item_client['username']);
if($name_client != '' && $name_client != null){
$buttons[][] = array(
'text' => $name_client . ($item_client['name_role'] != '' && $item_client['name_role'] != null ? ' (' . $item_client['name_role'] . ')' : ''),
'callback_data'=> json_encode(array('action' => "show", 'command' => "users", 'id' => $item_client['id'], "group" => ($groupObj ? $groupObj->getId() : null)))
);
}
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "delete", 'command' => "setting", 'mes_id' => $message_id, "group" => ($groupObj ? $groupObj->getId() : null)))
);
}
$keyboard = $buttons;
if(count($keyboard) > 0){
$reply_markup = ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
$resp = json_decode($sendMessage, true);
if(isset($resp['result']['message_id']) && $groupObj){
file_put_contents($basePath . '/var/log/' . $chat_id . '-' . $groupObj->getId() . '.txt', $resp['result']['message_id']);
}
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
}
if($is_group_chat === true){
$bot = $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
$command = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'users'));
$this->addLogMessageBot($bot, $command, $sendMessage);
}
}
private function nameClient($first_name, $last_name, $username){
$name_client = ($first_name != '' && $first_name != null ? $first_name : '');
if($name_client != '' && $last_name != '' && $last_name != null){
$name_client = $name_client . ' ' . $last_name;
}
if($name_client == ''){
$name_client = $username;
}
return $name_client;
}
private function setting($token, $chat_id, $group_id, $cq_data = array(), $message_id = null) {
$basePath = $this->getParameter('kernel.project_dir');
$is_group_chat = $this->getParameter('app.chat.is_group');
$sendMessage = false;
$action = null;
$p_group = null;
if(count($cq_data) > 0){
$action = (isset($cq_data['action']) ? $cq_data['action'] : null);
$p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
if($action == '' || $action == "null" || $action == null){
$action = null;
}
}
if(count($cq_data) > 0 && $action != null){
$action = (isset($cq_data['action']) ? $cq_data['action'] : null);
$p_group = (isset($cq_data['group']) ? $cq_data['group'] : null);
$em = $this->getDoctrine()->getManager();
if($is_group_chat === true && $p_group != '' && $p_group != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
if($groupObj){
$chat_id = $groupObj->getChatId();
}
}
if($action == 'list'){
$reply = 'Типов группы для выбора пока нет.';
$type_groups = $this->getDoctrine()
->getRepository(TypeGroup::class)
->createQueryBuilder('tg')
->select('tg.id, tg.title')
->getQuery()
->getArrayResult();
$buttons = array();
if(count($type_groups) > 0){
$reply = 'Выберите тип группы из списка.';
foreach ($type_groups as $type_group){
$buttons[][] = array(
'text' => $type_group['title'],
'callback_data'=> json_encode(array('action' => "add", 'command' => "setting", 'id' => $type_group['id'], "group" => $p_group))
);
}
$buttons[][] = array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "null", 'command' => "setting", "group" => $p_group))
);
}
$keyboard = $buttons;
if(count($keyboard) > 0){
$reply_markup = ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($action == 'add'){
$reply = 'Не удалось добавить тип группы к групповому чату. Попробуйте повторить попытку позже.';
$keyboard = array();
$groupObj = false;
if(isset($cq_data['id']) && isset($cq_data['group'])){
if($cq_data['id'] != '' && $cq_data['id'] != null && $cq_data['group'] != '' && $cq_data['group'] != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
$type_group = $this->getDoctrine()->getRepository(TypeGroup::class)->findOneBy(array('id' => $cq_data['id']));
if($groupObj && $type_group){
$groupObj->setTypeGroup($type_group);
$em->persist($groupObj);
$em->flush();
$reply = 'Тип группы «' . $type_group->getTitle() . '» успешно добавлен к групповому чату.';
$keyboard = array(
array(
array(
'text'=>'Новый тип группы',
'callback_data'=> json_encode(array('action' => "list", 'command' => "setting", "group" => ($groupObj ? $groupObj->getId() : null)))
),
array(
'text'=>'Удалить тип группы',
'callback_data'=> json_encode(array('action' => "rem", 'command' => "setting", "group" => ($groupObj ? $groupObj->getId() : null)))
),
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "delete", 'command' => "setting", 'mes_id' => $message_id, "group" => ($groupObj ? $groupObj->getId() : null)))
)
)
);
}
}
}
if(count($keyboard) > 0){
$reply_markup = ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
$resp = json_decode($sendMessage, true);
if(isset($resp['result']['message_id']) && $groupObj){
file_put_contents($basePath . '/var/log/' . $chat_id . '-' . $groupObj->getId() . '.txt', $resp['result']['message_id']);
}
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($action == 'rem'){
$reply = 'Не удалось удалить тип группы у данного группового чата.';
if($cq_data['group'] != '' && $cq_data['group'] != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
$groupObj->setTypeGroup(null);
$em->persist($groupObj);
$em->flush();
$reply = 'Тип группы у данного группового чата успешно удален.';
$keyboard = array(
array(
array(
'text'=>'Добавить тип группы',
'callback_data'=> json_encode(array('action' => "list", 'command' => "setting", "group" => ($groupObj ? $groupObj->getId() : null)))
)
)
);
}
if(count($keyboard) > 0){
$reply_markup = ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
} elseif($action == 'delete') {
$mes_id = (isset($cq_data['mes_id']) ? $cq_data['mes_id'] : null);
if($mes_id != '' && $mes_id != null){
$deleteMessage = ProjectUtilsController::requestToBot($token, 'deleteMessage', ['chat_id' => $chat_id, 'message_id' => $mes_id]);
}
if($cq_data['group'] != '' && $cq_data['group'] != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $cq_data['group']));
if($groupObj){
if(file_exists($basePath . '/var/log/' . $chat_id . '-' . $groupObj->getId() . '.txt')){
$mes_id = file_get_contents($basePath . '/var/log/' . $chat_id . '-' . $groupObj->getId() . '.txt');
if($mes_id != '' && $mes_id != null){
$deleteMessage = ProjectUtilsController::requestToBot($token, 'deleteMessage', ['chat_id' => $chat_id, 'message_id' => $mes_id]);
$resp = json_decode($deleteMessage, true);
if(isset($resp['result'])){
if($resp['result'] == true){
unlink($basePath . '/var/log/' . $chat_id . '-' . $groupObj->getId() . '.txt');
}
}
}
}
}
}
}
} else {
$groupObj = false;
if($group_id != '' && $group_id != null){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $group_id));
}
if(!$groupObj && $p_group != null && $p_group != ''){
$groupObj = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('id' => $p_group));
}
if($is_group_chat === true && $groupObj){
$chat_id = $groupObj->getChatId();
}
$reply = 'У данной группы пока не выбран тип группы. Можете добавить тип группы.';
$name_type_group = null;
$no_keyboard = false;
if($groupObj){
if($groupObj->getTypeGroup()){
$reply = 'У данной группы выбран тип группы «' . $groupObj->getTypeGroup()->getTitle() . '». Можете поменять на другой или удалить.';
$name_type_group = $groupObj->getTypeGroup()->getTitle();
}
} else {
$no_keyboard = true;
$reply = 'Отредактировать тип группы можно только из группы. Пожалуйста повторите данную команду в нужно группе.';
}
$reply_markup = array();
if($no_keyboard === false){
$keyboard = array(
array(
array(
'text'=> ($name_type_group != null ? 'Новый тип группы' : 'Добавить тип группы'),
'callback_data'=> json_encode(array('action' => "list", 'command' => "setting", "group" => ($groupObj ? $groupObj->getId() : null)))
),
array(
'text'=>'Удалить тип группы',
'callback_data'=> json_encode(array('action' => "rem", 'command' => "setting", "group" => ($groupObj ? $groupObj->getId() : null)))
),
array(
'text'=>'Назад',
'callback_data'=> json_encode(array('action' => "delete", 'command' => "setting", 'mes_id' => $message_id, "group" => ($groupObj ? $groupObj->getId() : null)))
)
)
);
$reply_markup = ProjectUtilsController::keyboardMarkup(array('inline_keyboard' => $keyboard));
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML', 'reply_markup' => $reply_markup]);
$resp = json_decode($sendMessage, true);
if(isset($resp['result']['message_id']) && $groupObj){
file_put_contents($basePath . '/var/log/' . $chat_id . '-' . $groupObj->getId() . '.txt', $resp['result']['message_id']);
}
} else {
$sendMessage = ProjectUtilsController::requestToBot($token, 'sendMessage', ['chat_id' => $chat_id, 'text' => $reply, 'parse_mode' => 'HTML']);
}
}
if($is_group_chat === true){
$bot = $this->getDoctrine()->getRepository(Bot::class)->findOneBy(array('token' => $token));
$command = $this->getDoctrine()->getRepository(Command::class)->findOneBy(array('typeof' => 'setting'));
$this->addLogMessageBot($bot, $command, $sendMessage);
}
}
private function updateClient($chat_id, $typeof, $data){
$em = $this->getDoctrine()->getManager();
$client = false;
if(count($data) > 0 && $chat_id != null && $chat_id != ''){
$client = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array('chat_id' => $chat_id));
if(!$client){
$newClient = new Client();
$newClient->setChatId($chat_id);
if($typeof == 'private'){
$newClient->setFirstName((isset($data['first_name']) ? $data['first_name'] : null));
$newClient->setLastName((isset($data['last_name']) ? $data['last_name'] : null));
$newClient->setUsername((isset($data['username']) ? $data['username'] : null));
$role = $this->getDoctrine()->getRepository(Role::class)->findOneBy(array('typeof' => 'employee'));
if($role){
$newClient->setRole($role);
}
$newClient->setBalance(0);
} else {
$newClient->setFirstName((isset($data['title']) ? $data['title'] : null));
$newClient->setBalance(0);
}
$newClient->setTypeof($typeof);
$newClient->setIsActive(1);
$em->persist($newClient);
$em->flush();
$client = $newClient;
} else {
if($typeof == 'private'){
if(isset($data['first_name'])){
if($data['first_name'] != $client->getFirstName()){
$client->setFirstName($data['first_name']);
}
}
if(isset($data['last_name'])){
if($data['last_name'] != $client->getLastName()){
$client->setLastName($data['last_name']);
}
}
if(isset($data['username'])){
if($data['username'] != $client->getUsername()){
$client->setUsername($data['username']);
}
}
if(!$client->getRole()){
$role = $this->getDoctrine()->getRepository(Role::class)->findOneBy(array('typeof' => 'employee'));
if($role){
$client->setRole($role);
}
}
} else {
if(isset($data['title'])){
if($data['title'] != $client->getFirstName()){
$client->setFirstName($data['title']);
}
}
}
if($typeof != $client->getTypeof()){
$client->setTypeof($typeof);
}
$em->persist($client);
$em->flush();
}
}
return $client;
}
private function getCurClient($chat_id, $typeof, $from_data, $chat_data){
$em = $this->getDoctrine()->getManager();
$client = false;
if(count($from_data) > 0 && $chat_id != null && $chat_id != ''){
$tmp_typeof = $typeof;
if($typeof == 'supergroup' || $typeof == 'group'){
$tmp_typeof = 'private';
}
$client = $this->updateClient($chat_id, $tmp_typeof, $from_data);
}
if(count($chat_data) > 0 && $chat_id != null && $chat_id != '' && ($typeof == 'supergroup' || $typeof == 'group')){
$tmp_chat_id = $chat_id;
if(isset($chat_data['id'])){
$tmp_chat_id = $chat_data['id'];
}
$client = $this->updateClient($tmp_chat_id, $typeof, $chat_data);
}
return $client;
}
private function genReport($report = false){
$basePath = $this->getParameter('kernel.project_dir');
$date_with = null;
$date_by = null;
$client_group_id = null;
if($report){
$date_with_d = $report->getDateWith();
if($date_with_d != '' && $date_with_d != null){
$date_with_dates = (array) $date_with_d;
if(isset($date_with_dates['date'])){
$date_with = $date_with_dates['date'];
}
}
$date_by_d = $report->getDateBy();
if($date_by_d != '' && $date_by_d != null){
$date_by_dates = (array) $date_by_d;
if(isset($date_by_dates['date'])){
$date_by = $date_by_dates['date'];
}
}
if($report->getClientGroup()){
$client_group_id = $report->getClientGroup()->getId();
}
}
$transactions_q = $this->getDoctrine()
->getRepository(Transaction::class)
->createQueryBuilder('tr')
->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')
->leftJoin(Client::class, 'c1', 'WITH', 'tr.from_group = c1.id')
->leftJoin(Client::class, 'c2', 'WITH', 'tr.to_group = c2.id')
->leftJoin(Client::class, 'c3', 'WITH', 'tr.sender = c3.id')
->leftJoin(Office::class, 'o', 'WITH', 'tr.office = o.id')
//->where('tr.amount != 0')
;
if($client_group_id != null && $client_group_id != ''){
$transactions_q->andWhere('tr.recipient = ' . $client_group_id);
if($date_with != '' && $date_with != null){
$transactions_q->andWhere('tr.date >= :date_with')
->setParameter('date_with', $date_with);
}
/*
$transactions_q->andWhere('tr.from_group = ' . $client_group_id);
if($date_with != '' && $date_with != null){
$transactions_q->andWhere('tr.date >= :date_with')
->setParameter('date_with', $date_with);
}
if($date_by != '' && $date_by != null){
$transactions_q->andWhere('tr.date <= :date_by')
->setParameter('date_by', $date_by);
}
$transactions_q->orWhere('tr.to_group = ' . $client_group_id);
if($date_with != '' && $date_with != null){
$transactions_q->andWhere('tr.date >= :date_with')
->setParameter('date_with', $date_with);
}
if($date_by != '' && $date_by != null){
$transactions_q->andWhere('tr.date <= :date_by')
->setParameter('date_by', $date_by);
}
*/
} else {
if($date_with != '' && $date_with != null){
$transactions_q->andWhere('tr.date >= :date_with')
->setParameter('date_with', $date_with);
}
if($date_by != '' && $date_by != null){
$transactions_q->andWhere('tr.date <= :date_by')
->setParameter('date_by', $date_by);
}
}
$transactions_q->orderBy('tr.date', 'ASC');
$transactions = $transactions_q->getQuery()->getArrayResult();
$types = array(
'income' => 'Начисление',
'expense' => 'Списание'
);
$file = '';
if(count($transactions) > 0){
foreach ($transactions as $key => $item){
$transactions[$key]['from_name'] = $this->nameClient($item['f_first_name'], $item['f_last_name'], $item['f_username']);
$transactions[$key]['to_name'] = $this->nameClient($item['t_first_name'], $item['t_last_name'], $item['t_username']);
$transactions[$key]['sender'] = $this->nameClient($item['s_first_name'], $item['s_last_name'], $item['s_username']);
$date = '';
$dates = (array)$item['date'];
if(isset($dates['date'])){
$date = date("d.m.Y H:i", strtotime($dates['date']));
}
$opt = "";
if($item['typeof'] == 'income'){
$opt = "+";
}
//$transactions[$key]['amount'] = $opt . str_replace(',00', '', number_format(($item['amount'] / 100), 2, ',', ' '));
$transactions[$key]['amount'] = str_replace(',00', '', number_format(($item['amount'] / 100), 2, ',', ''));
$transactions[$key]['type'] = $item['typeof'];
$transactions[$key]['typeof'] = (isset($types[$item['typeof']]) ? $types[$item['typeof']] : '');
//$transactions[$key]['typeof'] = ($item['note'] != '' && $item['note'] != null ? $item['note'] : (isset($types[$item['typeof']]) ? $types[$item['typeof']] : ''));
$transactions[$key]['date'] = $date;
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']);
}
//$date_with = '2022-04-01 15:20:00';
//$date_by = '2022-04-11 10:00:00';
$file = MainController::genExcel($transactions, $basePath, ($date_with != '' && $date_with != null ? (MainController::rusDate(date("Y-m-d H:i:s", strtotime($date_with)), 'ru', true, false, true)) : null), ($date_by != '' && $date_by != null ? (MainController::rusDate(date("Y-m-d H:i:s", strtotime($date_by)), 'ru', true, false, true)) : null));
}
return $file;
}
public static function genExcel($data, $basePath, $date_with = null, $date_by = null){
$styleArrayTopBold = array(
'font' => array(
'bold' => true,
'size' => 12
)
);
$styleArrayTop = array(
'font' => array(
'size' => 11
)
);
$styleArrayBold = array(
'font' => array(
'bold' => true
)
);
$styleArrayBorderMinSize = array(
'borders' => array(
'outline' => array(
'style' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
'color' => array('argb' => '000000'),
),
),
'font' => array(
'size' => 10
)
);
//$PHPExcel = new \PHPExcel();
$PHPExcel = new Spreadsheet();
$PHPExcel->getDefaultStyle()->getFont()->setName('Calibri')->setSize(11);
$PHPExcel->getDefaultStyle()->getAlignment()->setWrapText(true);
$PHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
$PHPExcel->createSheet(0);
$sheet = $PHPExcel->getSheet(0);
$PHPExcel->setActiveSheetIndex(0);
$sheet_title = 'Отчет по операциям';
$sheet->setTitle($sheet_title);
$title_report = 'Отчет по финансовым операциям от ' . MainController::rusDate(date("Y-m-d H:i:s"), 'ru', true, false, true);
$sheet->mergeCells('A1:C1');
$sheet->mergeCells('A2:C2');
$sheet->getStyleByColumnAndRow(0, 1)->applyFromArray($styleArrayTop);
$sheet->getStyleByColumnAndRow(0, 2)->applyFromArray($styleArrayTop);
$sheet
->getStyleByColumnAndRow(0, 1)
->getAlignment()
->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER)
;
$sheet
->getStyleByColumnAndRow(0, 2)
->getAlignment()
->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER)
;
$n_row = 3;
foreach (array('A') as $symbol){
$sheet->getColumnDimension($symbol)->setWidth(5);
}
foreach (array('B') as $symbol){
$sheet->getColumnDimension($symbol)->setWidth(30);
}
foreach (array('C') as $symbol){
$sheet->getColumnDimension($symbol)->setWidth(30);
}
foreach (array('D') as $symbol){
$sheet->getColumnDimension($symbol)->setWidth(30);
}
foreach (array('E') as $symbol){
$sheet->getColumnDimension($symbol)->setWidth(30);
}
foreach (array('F') as $symbol){
$sheet->getColumnDimension($symbol)->setWidth(30);
}
foreach (array('G') as $symbol){
$sheet->getColumnDimension($symbol)->setWidth(30);
}
foreach (array('H') as $symbol){
$sheet->getColumnDimension($symbol)->setWidth(30);
}
foreach (array('I') as $symbol){
$sheet->getColumnDimension($symbol)->setWidth(30);
}
foreach (array('J') as $symbol){
$sheet->getColumnDimension($symbol)->setWidth(30);
}
$sheet->mergeCells('A3:J3');
$sheet->getCellByColumnAndRow(1, $n_row)->setValue($title_report);
$sheet->getStyleByColumnAndRow(1, $n_row)->applyFromArray($styleArrayTopBold);
$sheet
->getStyleByColumnAndRow(1, $n_row)
->getAlignment()
->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)
;
if(($date_with != '' && $date_with != null) || ($date_by != '' && $date_by != null)){
$n_row += 2;
$sheet->mergeCells('A5:J5');
$sheet->getCellByColumnAndRow(1, $n_row)->setValue('за период c ' . $date_with . ' по ' . $date_by);
$sheet->getStyleByColumnAndRow(1, $n_row)->applyFromArray($styleArrayTopBold);
$sheet
->getStyleByColumnAndRow(1, $n_row)
->getAlignment()
->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)
;
}
$n_row += 2;
if(count($data) > 0){
$arr_columns = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
foreach ($arr_columns as $column){
$PHPExcel->getActiveSheet()->getColumnDimension($column)->setAutoSize(true);
}
// $n_row = 1;
$sheet->getCellByColumnAndRow(1, $n_row)->setValue('№ п/п');
$sheet->getCellByColumnAndRow(2, $n_row)->setValue('Тип операции');
$sheet->getCellByColumnAndRow(3, $n_row)->setValue('Добавил');
$sheet->getCellByColumnAndRow(4, $n_row)->setValue('Дата операции');
$sheet->getCellByColumnAndRow(5, $n_row)->setValue('Сумма');
//$sheet->getCellByColumnAndRow(6, $n_row)->setValue('Группа');
$sheet->getCellByColumnAndRow(6, $n_row)->setValue('Откуда');
$sheet->getCellByColumnAndRow(7, $n_row)->setValue('Куда');
$sheet->getCellByColumnAndRow(8, $n_row)->setValue('№ объекта');
$sheet->getCellByColumnAndRow(9, $n_row)->setValue('Объект');
$sheet->getCellByColumnAndRow(10, $n_row)->setValue('Коментарий');
for($c = 1; $c <= 10; $c++){
$sheet->getStyleByColumnAndRow($c, $n_row)
->applyFromArray($styleArrayBorderMinSize)
->getAlignment()
->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)
;
}
$sheet
->getStyle('A' . $n_row . ':J' . $n_row)
->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
->getStartColor()
->setRGB('C2E9F6')
;
$n = 1;
foreach ($data as $item){
$n_row += 1;
$groupName = '';
if($item['type'] == 'income'){
if($item['to_name'] != '' && $item['to_name'] != null){
$groupName = $item['to_name'];
} else {
$groupName = $item['from_name'];
}
} elseif($item['type'] == 'expense'){
if($item['from_name'] != '' && $item['from_name'] != null ){
$groupName = $item['from_name'];
} else {
$groupName = $item['to_name'];
}
}
$sheet->getCellByColumnAndRow(1, $n_row)->setValue($n);
$sheet->getCellByColumnAndRow(2, $n_row)->setValue($item['typeof']);
$sheet->getCellByColumnAndRow(3, $n_row)->setValue($item['sender']);
$sheet->getCellByColumnAndRow(4, $n_row)->setValue($item['date']);
$sheet->getCellByColumnAndRow(5, $n_row)->setValue($item['amount']);
//$sheet->getCellByColumnAndRow(6, $n_row)->setValue($groupName);
$sheet->getCellByColumnAndRow(6, $n_row)->setValue($item['from_name']);
$sheet->getCellByColumnAndRow(7, $n_row)->setValue($item['to_name']);
$sheet->getCellByColumnAndRow(8, $n_row)->setValue($item['office_number']);
$sheet->getCellByColumnAndRow(9, $n_row)->setValue($item['office_name']);
$sheet->getCellByColumnAndRow(10, $n_row)->setValue($item['comment']);
$n++;
for($c = 1; $c <= 10; $c++){
$sheet->getStyleByColumnAndRow($c, $n_row)->applyFromArray($styleArrayBorderMinSize);
}
// $sheet
// ->getStyleByColumnAndRow(8, $n_row)
// ->getAlignment()
// ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)
// ->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER)
// ;
}
}
$PHPExcel->setActiveSheetIndex(0);
$fileDir = '/public/images/';
if (!is_dir($basePath . '/public/images/')) {
mkdir($basePath . '/public/images/');
}
if (!is_dir($basePath . $fileDir)) {
mkdir($basePath . $fileDir);
}
$uuid = ProjectUtilsController::generateUuid();
$predir = substr($uuid, 0, 3);
if (!is_dir($basePath . $fileDir . '/' . $predir . '/')) {
mkdir($basePath . $fileDir . '/' . $predir . '/');
}
//$filename = $predir . '/' . $uuid . '.xlsx';
$filename = $predir . '/' . date("Y_m_d_H_i_s") . '_report.xlsx';
//$filename = 'test.xlsx';
$filepath = $basePath . $fileDir . '/' . $filename;
//$objWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel2007');
$objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($PHPExcel, 'Xlsx');
$objWriter->save($filepath);
return $filename;
}
private function sendEmail(MailerInterface $mailer, $event, $body_mail, $theme_mail, $locale = 'ru', $recipient = false, $attach = array())
{
$mailerFrom = $this->getParameter('app.mailer.from');
$mail_template_q = $this->getDoctrine()
->getRepository(MailTemplate::class)
->createQueryBuilder('mt')
->select('mt.id, mt.title, mt.body, mt.copy')
->where('mt.event = :event')
->setParameter('event', $event)
->getQuery()->getResult();
$theme = '';
$body = '';
$mail_template = array();
if(isset($mail_template_q[0])){
$mail_template = $mail_template_q[0];
$theme = $mail_template['title'];
$body = $mail_template['body'];
if(count($body_mail) > 0){
foreach ($body_mail as $ket_b => $b_mail){
$body = str_replace($ket_b, $b_mail , $body);
}
}
if(count($theme_mail) > 0){
foreach ($theme_mail as $ket_th => $th_mail){
$theme = str_replace($ket_th, $th_mail , $theme);
}
}
}
if($recipient === false){
$recipient = $this->getParameter('app.mailer.to');
}
$email = (new Email())
->from($mailerFrom)
->to($recipient)
//->cc('max.linwa@gmail.com')
//->addTo('igor@atmapro.ru')
//->bcc('igor@atmapro.ru')
//->replyTo('fabien@example.com')
//->priority(Email::PRIORITY_HIGH)
->subject($theme)
->text('Sending emails is fun again!')
->html($body);
if(count($mail_template) > 0){
if($mail_template['copy'] != '' && $mail_template['copy'] != null){
$email->cc($mail_template['copy']);
}
}
if(count($attach) > 0){
foreach ($attach as $item){
$email->attachFromPath($item);
}
}
$is_send = false;
try {
$mailer->send($email);
$is_send = true;
} catch (TransportExceptionInterface $e) {
echo $e->getMessage();
// некая ошибка предотвратила отправку письма; отобразить сообщение
// об ошибке или попробовать отправить сообщение повторно
}
return $is_send;
}
public static function rusDate($date, $lang = 'ru', $time = false, $time_prefix = false, $with_year = false)
{
if ($lang == 'ru') {
$a = array('01' => 'января', '02' => 'февраля', '03' => 'марта', '04' => 'апреля', '05' => 'мая', '06' => 'июня', '07' => 'июля', '08' => 'августа', '09' => 'сентября', '10' => 'октября', '11' => 'ноября', '12' => 'декабря',);
} elseif ($lang == 'en') {
$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');
}
$ex = explode(' ', $date);
$timeex = explode(':', $ex[1]);
$ex = explode('-', $ex[0]);
$year = ($ex[0] != date('Y') ? ' ' . $ex[0] : '');
if ($with_year) {
$year = ', ' . $ex[0];
}
return intval($ex[2]) . ' ' . $a[$ex[1]] . $year . ($time ? ($time_prefix ? $time_prefix : ' ') . $timeex[0] . ':' . $timeex[1] : '');
}
#[Route('/user-create/', name: 'app_user_create')]
public function userCreate(Request $request, UserPasswordEncoderInterface $encoder): Response
{
$em = $this->getDoctrine()->getManager();
$login = $request->get('login');
$password = $request->get('password');
if (!empty($login) && !empty($password)) {
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(['username' => $login]);
if (!$user) {
$newUser = new User();
$newUser->setUsername($login);
$encoded = $encoder->encodePassword($newUser, $password);
$newUser->setPassword($encoded);
$newUser->setRoles(array('ROLE_ADMIN'));
$em->persist($newUser);
$em->flush();
echo 'Пользователь успешно создан';
} else {
echo 'Пользователь уже есть';
}
} else {
echo 'Не достаточно данных';
}
die();
}
public static function recalculateBalance($doctrine, $ids = array())
{
$em = $doctrine->getManager();
$clients_qq = $doctrine
->getRepository(Client::class)
->createQueryBuilder('cl')
->select('cl.id, cl.balance')
->where('cl.typeof != :typeof')
->setParameter('typeof', "private");
if(count($ids) > 0){
$clients_qq->andWhere('tr.id IN (' . implode(",", $ids) . ')');
}
$clients_q = $clients_qq->getQuery()->getResult();
if(count($clients_q) > 0){
foreach ($clients_q as $item_client){
$transaction_q = $doctrine
->getRepository(Transaction::class)
->createQueryBuilder('tr')
->select('tr.id, SUM(tr.amount) AS balance')
->where('tr.recipient = ' . $item_client['id'])
->getQuery()->getResult();
if(count($transaction_q) == 1){
$transaction = $transaction_q[0];
if($transaction['balance'] != $item_client['balance']){
//echo 'У клиента ' . $item_client['id'] . ' балансы не совпадают, фактический ' . $transaction['balance'] . ', по операциям ' . $item_client['balance'] . "\n";
$client = $doctrine->getRepository(Client::class)->findOneBy(['id' => $item_client['id']]);
if($client){
$client->setBalance($transaction['balance']);
$em->persist($client);
$em->flush();
//echo 'У клиента ' . $client->getId() . ' был изменен баланс на ' . $transaction['balance'] . "\n";
}
} else {
//echo 'У клиента ' . $item_client['id'] . ' баланс правильный' . "\n";
}
}
}
}
//print_r($clients_q);
}
private function actualBalance($client){
$balance = false;
if($client){
$client_id = null;
if(is_object($client)){
$client_id = $client->getId();
if($client_id != '' && $client_id != null){
$transaction_q = $this->getDoctrine()
->getRepository(Transaction::class)
->createQueryBuilder('tr')
->select('tr.id, SUM(tr.amount) AS balance')
->where('tr.recipient = ' . $client_id)
->getQuery()->getResult();
if(isset($transaction_q[0]['balance'])){
$balance = $transaction_q[0]['balance'];
}
}
}
}
return $balance;
}
}