src/Controller/Telegram/AgentPublicBot/ManagementController.php line 202

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Telegram\AgentPublicBot;
  3. use App\DependencyInjection\JDF;
  4. use App\Entity\Generic\User;
  5. use App\Entity\Telegram\AgentPublicBot\Bot;
  6. use App\Entity\Telegram\AgentPublicBot\BotAnalytics;
  7. use App\Entity\Telegram\AgentPublicBot\BotNotification;
  8. use App\Entity\Telegram\AgentPublicBot\BotPlan;
  9. use App\Entity\Telegram\AgentPublicBot\BotTransaction;
  10. use App\Entity\Telegram\AgentPublicBot\BotUser;
  11. use App\Entity\VPN\Service\Plan;
  12. use App\Form\Telegram\BotAdsFormType;
  13. use App\Form\Telegram\BotInfoType;
  14. use App\Form\UserChargeAdminType;
  15. use App\Repository\Domains\DomainRepository;
  16. use App\Repository\Telegram\AgentPublicBot\BotAnalyticsRepository;
  17. use App\Repository\Telegram\AgentPublicBot\BotPlanRepository;
  18. use App\Repository\Telegram\AgentPublicBot\BotRepository;
  19. use App\Repository\Telegram\UserRepository;
  20. use App\Repository\VPN\Service\ServiceRepository;
  21. use App\Service\SettingService;
  22. use App\Service\Telegram\AgentPublicBot\BotCampaignService;
  23. use App\Service\Telegram\AgentPublicBot\BotService;
  24. use App\Service\Telegram\AgentPublicBot\BotUserService;
  25. use App\Service\TransactionService;
  26. use App\Service\Util\DynamicPriceCalculation;
  27. use App\Service\Util\NotificationService;
  28. use App\Service\Util\Telegram;
  29. use App\ViewModel\Telegram\AgentPublicBot\BotCampaignViewModel;
  30. use App\ViewModel\Telegram\AgentPublicBot\BotUserViewModel;
  31. use Doctrine\ORM\EntityManagerInterface;
  32. use Doctrine\Persistence\ManagerRegistry;
  33. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  34. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  35. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  36. use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
  37. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  38. use Symfony\Component\Form\Extension\Core\Type\NumberType;
  39. use Symfony\Component\Form\Extension\Core\Type\TextareaType;
  40. use Symfony\Component\HttpFoundation\Request;
  41. use Symfony\Component\HttpFoundation\RequestStack;
  42. use Symfony\Component\HttpFoundation\Response;
  43. use Symfony\Component\Notifier\Notification\Notification;
  44. use Symfony\Component\Routing\Annotation\Route;
  45. use Symfony\Component\Validator\Constraints\LessThanOrEqual;
  46. #[IsGranted('ROLE_USER')]
  47. #[Route('/telegram/agent-public-bot/management/{botId}')]
  48. class ManagementController extends AbstractController
  49. {
  50.     public ?Request $request;
  51.     public Bot $bot;
  52.     public BotUserService $botUserService;
  53.     public BotCampaignService $botCampaignService;
  54.     public EntityManagerInterface $entityManager;
  55.     public BotService $service;
  56.     public DynamicPriceCalculation $dynamicPriceCalculation;
  57.     public function __construct(DynamicPriceCalculation $dynamicPriceCalculation BotUserService $botUserService,BotCampaignService $botCampaignService RequestStack $requestStackManagerRegistry $managerRegistryEntityManagerInterface $entityManagerTelegram $telegramBotService $botServiceTransactionService $transactionService\App\Repository\Generic\UserRepository $agentRepositoryUserRepository $userRepository)
  58.     {
  59.         $this->dynamicPriceCalculation $dynamicPriceCalculation;
  60.         $this->botCampaignService $botCampaignService;
  61.         $this->request $requestStack->getCurrentRequest();
  62.         $this->botUserService $botUserService;
  63.         $this->bot $managerRegistry->getRepository(Bot::class)->findOneBy(['id' => $requestStack->getCurrentRequest()->get('botId')]);
  64.         $adminTelegram = new Telegram($entityManager);
  65.         $setting = new SettingService($entityManager);
  66.         $this->entityManager $entityManager;
  67.         $this->service $botService;
  68.     }
  69.     #[Route('/'name'app_telegram_agent_public_bot_management_general')]
  70.     public function app_telegram_agent_public_bot_management(ServiceRepository $serviceRepository): Response
  71.     {
  72.         /**
  73.          * @var User $user
  74.          */
  75.         $user $this->getUser();
  76.         if ($user->getConnectedTelegramUserId() === null || $user->getConnectedTelegramUserId() ===[]){
  77.             $this->addFlash('error' 'لطفا ابتدا حساب خود را به تلگرام متصل فرمایید');
  78.             return  $this->redirectToRoute('app_user_dashboard');
  79.         }
  80.         $botUsers $this->getDoctrine()->getRepository(BotUser::class)->findBy(['active' => 1'bot' => $this->bot]);
  81.         $services $serviceRepository->findBy(['isEnabled' => 'creatorBot' => $this->bot]);
  82.         return $this->render('panel/pages/user/telegram/agent-public-bot/management.html.twig', [
  83.             'bot' => $this->bot,
  84.             'botUsers' => count($botUsers),
  85.             'services' => ($services),
  86.         ]);
  87.     }
  88.     #[Route('/edit'name'app_telegram_agent_public_bot_management_edit'methods: ['GET''POST'])]
  89.     public function app_telegram_agent_public_bot_management_edit(Request $requestDomainRepository $domainRepositoryEntityManagerInterface $entityManager): Response
  90.     {
  91.         $object $this->bot;
  92.         $user $this->getUser();
  93.         $domains $domainRepository->findBy(['owner' => $user'isConnected' => true]);
  94.         $form $this->createForm(BotInfoType::class, $object, ['user' => $this->getUser(),'thisBot' => $this->bot 'domains' => $domains'entityManager' => $entityManager]);
  95.         $form->handleRequest($request);
  96.         if ($form->isSubmitted() && $form->isValid()) {
  97.             $this->service->save($object);
  98.             return $this->redirectToRoute('app_telegram_agent_public_bot_management_edit', ['botId' => $object->getId()], Response::HTTP_SEE_OTHER);
  99.         }
  100.         return $this->render('panel/pages/user/telegram/agent-public-bot/management-edit.html.twig', [
  101.             'form' => $form->createView(),
  102.             'edit' => true,
  103.             'object' => $object,
  104.             'bot' => $this->bot
  105.         ]);
  106.     }
  107.     #[Route('/marketing'name'app_telegram_agent_public_bot_management_marketing'methods: ['GET''POST'])]
  108.     public function app_telegram_agent_public_bot_management_marketing(Request $requestDomainRepository $domainRepositoryEntityManagerInterface $entityManager): Response
  109.     {
  110.         $this->addFlash('warning' 'این پیام ها هر روز برای کاربران ساعت ۲۰ ارسال خواهند شد');
  111.         $object $this->bot;
  112.         $user $this->getUser();
  113.         $form $this->createForm(BotAdsFormType::class, $object);
  114.         $form->handleRequest($request);
  115.         if ($form->isSubmitted() && $form->isValid()) {
  116.             $this->service->save($object);
  117.             return $this->redirectToRoute('app_telegram_agent_public_bot_management_marketing', ['botId' => $object->getId()], Response::HTTP_SEE_OTHER);
  118.         }
  119.         return $this->render('panel/pages/user/telegram/agent-public-bot/marketing.html.twig', [
  120.             'form' => $form->createView(),
  121.             'edit' => true,
  122.             'object' => $object,
  123.             'bot' => $this->bot
  124.         ]);
  125.     }
  126.     #[Route('/analytics'name'app_telegram_agent_public_bot_management_analytics'methods: ['GET''POST'])]
  127.     public function app_telegram_agent_public_bot_management_analytics(Request $request,BotAnalyticsRepository $analyticsRepositoryEntityManagerInterface $entityManager): Response
  128.     {
  129.         $now = new \DateTimeImmutable();
  130.         $jdf = new JDF();
  131.         $monthNumber $request->query->get('month') ?: $jdf->trNum($jdf->date('m'));
  132.         $startJalali '1404/' $monthNumber '/1';
  133.         $endJalali '1404/' $monthNumber '/' $jdf->trNum($jdf->date('t''''fa'$monthNumber));
  134.         $startDateTime $jdf->jalaliToGregorian(explode('/'$startJalali)[0], explode('/'$startJalali)[1], explode('/'$startJalali)[2])[0] . '-' $jdf->jalaliToGregorian(explode('/'$startJalali)[0], explode('/'$startJalali)[1], explode('/'$startJalali)[2])[1] . '-' $jdf->jalaliToGregorian(explode('/'$startJalali)[0], explode('/'$startJalali)[1], explode('/'$startJalali)[2])[2] . ' 00:00:00';
  135.         $startDateTime = new \DateTime($startDateTime);
  136.         $endDateTime $jdf->jalaliToGregorian(explode('/'$endJalali)[0], explode('/'$endJalali)[1], explode('/'$endJalali)[2])[0] . '-' $jdf->jalaliToGregorian(explode('/'$endJalali)[0], explode('/'$endJalali)[1], explode('/'$endJalali)[2])[1] . '-' $jdf->jalaliToGregorian(explode('/'$endJalali)[0], explode('/'$endJalali)[1], explode('/'$endJalali)[2])[2] . ' 00:00:00';
  137.         $endDateTime = new \DateTime($endDateTime);
  138.         $data = [];
  139. //        var_dump(count($analyticsRepository->getBetweenDays($startDateTime, $endDateTime,$this->bot)));die;
  140.         foreach ($analyticsRepository->getBetweenDays($startDateTime$endDateTime,$this->bot) as $item) {
  141.             /**
  142.              * @var BotAnalytics $item
  143.              */
  144.             $data[] = [
  145.                 'date' => $item->getDate(),
  146.                 'lastMonthWallet' => $this->getLastMonthChargeFromDate($item->getDate() , $this->bot),
  147.                 'wallet' => $item->getWalletIncrease(),
  148.                 'service' => $item->getBoughtService(),
  149.                 'lastMonthService' => $this->getLastMonthTotalServicesFromDate($item->getDate() , $this->bot),
  150.                 'lastMonthVolume' => $this->getLastMonthVolumeFromDate($item->getDate() , $this->bot),
  151.                 'v2ray' => $item->getV2ray(),
  152.                 'ocServ' => $item->getOcServ(),
  153.                 'open' => $item->getOpen(),
  154.                 'v2rayUnlimited' => $item->getV2rayUnlimited(),
  155.                 'ocServUnlimited' => $item->getOcServUnlimited(),
  156.                 'openUnlimited' => $item->getOpenUnlimited(),
  157.                 'vip' => $item->getVip(),
  158.                 'boughtVolume' => $item->getBoughtVolume(),
  159.                 'gotTest' => $item->getTestService()
  160.             ];
  161.         }
  162.         return $this->render('panel/pages/user/telegram/agent-public-bot/analytics.html.twig', [
  163.             'data' => $data,
  164.             'month' => $monthNumber,
  165.             'bot' => $this->bot
  166.         ]);
  167.     }
  168.     #[Route('/delete-plans'name'app_telegram_agent_public_bot_management_price_delete_all')]
  169.     public function deleteAttPlans(BotPlanRepository $botPlanRepository)
  170.     {
  171.         foreach ($botPlanRepository->findBy(['bot' => $this->bot]) as $item) {
  172.             $this->entityManager->remove($item);
  173.         }
  174.         $this->entityManager->flush();
  175.         return $this->redirectToRoute('app_telegram_agent_public_bot_management_price' , ['botId' => $this->bot->getId()]);
  176.     }
  177.     #[Route('/price'name'app_telegram_agent_public_bot_management_price'methods: ['GET''POST'])]
  178.     public function app_telegram_agent_public_bot_management_price(Request $request): Response
  179.     {
  180.         $object $this->bot;
  181.         /**
  182.          * @var User $user
  183.          */
  184.         $user $this->getUser();
  185.         $autoPriceForm $this->createFormBuilder()
  186.             ->add('number'NumberType::class, [
  187.                 'label' => 'عدد مدنظر برای اضافه شدن به قیمت ها',
  188.             ])
  189.             ->add('type'ChoiceType::class, [
  190.                 'label' => 'نوع قیمت گذاری',
  191.                 'choices' => [
  192.                     'افزودن درصد ثابت به قیمت ها' => 'percentage',
  193.                     'افزودن عدد ثابت به قیمت ها' => 'manual'
  194.                 ]
  195.             ])
  196.             ->add('protocols'ChoiceType::class, [
  197.                 'label' => 'پروتکل مدنظر برای فروش',
  198.                 'multiple' => true,   // اجازه انتخاب چند گزینه
  199.                 'expanded' => true,   // نمایش به صورت چک‌باکس (اگه false باشه، multi-select میشه)
  200.                 'choices' => [
  201.                     'v2ray' => 'v2ray',
  202.                     'cisco' => 'ocserv',
  203.                     'openvpn' => 'open',
  204.                     'vip' => 'vip',
  205.                 ]
  206.             ])
  207.             ->getForm();
  208.         $autoPriceForm->handleRequest($request);
  209.         if ($autoPriceForm->isSubmitted() && $autoPriceForm->isValid()) {
  210.             foreach ($this->getDoctrine()->getRepository(BotPlan::class)->findBy(['bot' => $object]) as $botPlan) {
  211.                 $botPlan->setActive(false);
  212.                 $botPlan->setDeletedAt(new \DateTime());
  213.             }
  214.             $this->getDoctrine()->getManager()->flush();
  215.             $protocols = [
  216.            'v2ray',
  217.            'ocserv',
  218.              'open',
  219.          'vip',
  220.             ];
  221.             foreach ($protocols as $protocol) {
  222.                 if (in_array($protocol $autoPriceForm->get('protocols')->getData())) {
  223.                     $condition = [
  224.                         'active' => 1,
  225.                         'protocol' => $protocol,
  226.                     ];
  227.                     foreach ($this->getDoctrine()->getRepository(Plan::class)->findBy($condition) as $plan) {
  228.                         if (
  229.                             $plan->getServiceType() && $plan->getServiceType() !== ''
  230.                             &&
  231.                             $plan->getProtocol() && $plan->getProtocol() !== ''
  232.                             &&
  233.                             ($plan->hasCisco() || $plan->hasV2ray() || $plan->hasOpenVpn())
  234.                         ) {
  235.                             $planObject $this->getDoctrine()->getRepository(BotPlan::class)->findOneBy(['bot' => $object'active' => 1'plan' => $plan]);
  236.                             if (!$planObject) {
  237.                                 $planObject = new BotPlan();
  238.                             }
  239.                             $planObject->setBot($object);
  240.                             $planObject->setPlan($plan);
  241.                             $planPrice $this->dynamicPriceCalculation->calculatePrice($user$plan false);
  242.                             if ($autoPriceForm->get('type')->getData() == 'percentage') {
  243.                                 if ($autoPriceForm->get('number')->getData() >100){
  244.                                     $this->addFlash('error' 'درصد نمیتواند بیشتر از ۱۰۰ باشد');
  245.                                     return  $this->redirectToRoute('app_telegram_agent_public_bot_management_price' , ['botId' => $object->getId()], Response::HTTP_BAD_REQUEST);
  246.                                 }
  247.                                 $price $planPrice + (($planPrice * (int)$autoPriceForm->get('number')->getData()) / 100);
  248.                             } else {
  249.                                 $price $planPrice + (int)$autoPriceForm->get('number')->getData();
  250.                             }
  251.                             $planObject->setPrice($price);
  252.                             $this->getDoctrine()->getManager()->persist($planObject);
  253.                             $this->getDoctrine()->getManager()->flush();
  254.                         }
  255.                     }
  256.                 }
  257.             }
  258.             return $this->redirectToRoute('app_telegram_agent_public_bot_management_price', ['botId' => $object->getId()]);
  259.         }
  260.         $vipPlans $this->getDoctrine()->getRepository(Plan::class)->createQueryBuilder('u')
  261.             ->andWhere('u.deletedAt IS null')
  262.             ->andWhere('u.active  = 1')
  263.             ->andWhere('u.serviceType  IS NOT NULL')
  264.             ->andWhere('u.protocol IS NOT NULL')
  265.             ->andWhere('u.hasOpenVpn != 0 OR u.hasCisco != 0 OR u.hasV2ray != 0')
  266.             ->addOrderBy('u.protocol''ASC')
  267.             ->addOrderBy('u.days''ASC')
  268.             ->addOrderBy('u.size''ASC')
  269.             ->getQuery()->getResult();
  270.         $vipOptions = [
  271.             'plans' => $vipPlans,
  272.             'user' => $user,
  273.             'entityManager' => $this->getDoctrine()->getManager(),
  274.         ];
  275.         $vipForm $this->createFormBuilder()
  276.             ->add('plan'EntityType::class, [
  277.                 'class' => Plan::class,
  278.                 'label' => 'انتخاب بسته ',
  279.                 'choices' => $vipOptions['plans'],
  280.                 'choice_label' => function ($plan) use ($vipOptions) {
  281.                     $er $vipOptions['entityManager'];
  282.                     /**
  283.                      * @var Plan $plan
  284.                      * @var User $user
  285.                      */
  286.                     $user $vipOptions['user'];
  287.                     $startPrice $plan->getPrice();
  288. //                    foreach ($user->getUserTrace() as $email) {
  289. //                        $thisUser = $er->getRepository(User::class)->findOneBy(['email' => $email]);
  290. //                        $startPrice = $startPrice + (($startPrice * $thisUser->getInterestRate()) / 100);
  291. //                    }
  292. //                    $title =
  293. //                        "مولتی پروتکل ({$plan->formatSizeUnits($plan->getSize())})" .
  294. //                        'زمان : ' .
  295. //                        $plan->getDays() . ' روز ' .
  296. //                        'حجم : ' .
  297. //                        $plan->formatSizeUnits($plan->getSize()) . ' ' .
  298. //                        'قیمت : ' .
  299. //                        number_format($startPrice) . ' تومان';
  300.                     return $plan->__toString() ;
  301. //                    number_format($this->dynamicPriceCalculation->calculatePrice($user, $plan))
  302. //                    .' تومان';
  303.                 }
  304.             ])
  305.             ->add('sellPrice'NumberType::class, [
  306.                 'label' => 'قیمت فروش در ربات'
  307.             ])
  308.             ->getForm();
  309.         $vipForm->handleRequest($request);
  310.         if ($vipForm->isSubmitted() && $vipForm->isValid()) {
  311.             $vipPlanPrice  $this->dynamicPriceCalculation->calculatePrice($user$vipForm->get('plan')->getData());
  312.             if (($vipPlanPrice >= $vipForm->get('sellPrice')->getData()) && !$user->hasRole('ROLE_ADMIN')) {
  313.                 $this->addFlash('error''قیمت فروش در ربات باید افزایش یابد');
  314.                 return $this->redirectToRoute('app_telegram_agent_public_bot_management_price', ['botId' => $object->getId()]);
  315.             }
  316.             $planObject $this->getDoctrine()->getRepository(BotPlan::class)->findOneBy(['bot' => $object'active' => 1'plan' => $vipForm->get('plan')->getData()]);
  317.             if (!$planObject) {
  318.                 $planObject = new BotPlan();
  319.             }
  320.             $planObject->setBot($object);
  321.             $planObject->setPrice($vipForm->get('sellPrice')->getData());
  322.             $planObject->setPlan($vipForm->get('plan')->getData());
  323.             $this->getDoctrine()->getManager()->persist($planObject);
  324.             $this->getDoctrine()->getManager()->flush();
  325.             $this->addFlash('success''بسته فروش به ربات اضافه شد');
  326.             return $this->redirectToRoute('app_telegram_agent_public_bot_management_price', ['botId' => $object->getId()]);
  327.         }
  328.         $botPlans $this->getDoctrine()->getRepository(BotPlan::class)->findBy(['bot' => $object'active' => 1]);
  329.         foreach ($botPlans as $key => $botPlan) {
  330.             if ($botPlan->getPlan() == null || !$botPlan->getPlan()->isActive()){
  331.                 unset($botPlans[$key]);
  332.             }
  333.         }
  334.         return $this->render('panel/pages/user/telegram/agent-public-bot/management-price.html.twig', [
  335.             'vipForm' => $vipForm->createView(),
  336.             'vipPlans' => $vipPlans,
  337.             'edit' => true,
  338.             'object' => $object,
  339.             'bot' => $this->bot,
  340.             'botPlans' => $botPlans,
  341.             'autoPrice' => $autoPriceForm->createView()
  342.         ]);
  343.     }
  344.     public function getFilters(): array
  345.     {
  346.         return [
  347.             [
  348.                 'name' => 'search',
  349.                 'type' => 'text',
  350.                 'label' => 'کلیدواژه',
  351.                 'class' => '',
  352.                 'value' => $this->request->get('search')
  353.             ],
  354.             [
  355.                 'name' => 'active',
  356.                 'type' => 'radio',
  357.                 'label' => 'وضعیت',
  358.                 'class' => '',
  359.                 'radio' => [
  360.                     ['name' => 'همه''value' => 'all'],
  361.                     ['name' => 'فعال''value' => 'true'],
  362.                     ['name' => 'غیرفعال''value' => 'false'],
  363.                 ],
  364.                 'value' => $this->request->get('active')
  365.             ]
  366.         ];
  367.     }
  368.     public function getLists(): array
  369.     {
  370.         $array = [
  371.             [
  372.                 'name' => 'name',
  373.                 'label' => 'نام',
  374.                 'class' => '',
  375.             ],
  376.             [
  377.                 'name' => 'username',
  378.                 'label' => 'نام کاربری تلگرام',
  379.                 'class' => '',
  380.             ],
  381.             [
  382.                 'name' => 'userId',
  383.                 'label' => 'شناسه کاربر',
  384.                 'class' => '',
  385.             ],
  386.             [
  387.                 'name' => 'wallet',
  388.                 'label' => 'کیف پول',
  389.                 'class' => '',
  390.                 'type' => 'price'
  391.             ],
  392.             [
  393.                 'name' => 'createdAt',
  394.                 'label' => 'تاریخ عضویت',
  395.                 'class' => '',
  396.                 'type' => 'date'
  397.             ],
  398.             [
  399.                 'name' => 'campaign',
  400.                 'label' => 'کمپین',
  401.                 'class' => '',
  402.             ],
  403.         ];
  404.         return $array;
  405.     }
  406.     #[Route('/users'name'app_telegram_agent_public_bot_management_users'methods: ['GET''POST'])]
  407.     public function app_telegram_agent_public_bot_management_users(Request $request): Response
  408.     {
  409.         $object $this->bot;
  410.         /**
  411.          * @var User $user
  412.          */
  413.         $user $this->getUser();
  414.         $info = new BotUserViewModel($request);
  415.         $data $this->botUserService->getList($info$this->bot);
  416.         return $this->render('panel/pages/user/telegram/agent-public-bot/management-users.html.twig', [
  417.             'paginator' => $data,
  418.             'currentPage' => 'app_telegram_agent_public_bot_management_users',
  419.             'bot' => $this->bot,
  420.             'parameters' => $info,
  421.             'filters' => $this->getFilters(),
  422.             'lists' => $this->getLists(),
  423.         ]);
  424.     }
  425.     #[Route('/notification'name'app_telegram_agent_public_bot_management_notification'methods: ['GET''POST'])]
  426.     public function app_telegram_agent_public_bot_management_notification(Request $request): Response
  427.     {
  428.         $form $this->createFormBuilder()
  429.             ->add('message'TextareaType::class, [
  430.                 'label' => 'متن پیام همگانی'
  431.             ])
  432.             ->getForm();
  433.         $form->handleRequest($request);
  434.         if ($form->isSubmitted() && $form->isValid()) {
  435.             $notification = new BotNotification();
  436.             $notification->setBot($this->bot);
  437.             $notification->setMessage($form->get('message')->getData());
  438.             $notification->setIsSent(0);
  439.             $this->entityManager->persist($notification);
  440.             $this->entityManager->flush();
  441.             $text 'پیام شما در صف تلگرام قرار گرفت و بزودی ارسال همگانی خواهد شد....';
  442.             $this->addFlash('success'$text);
  443.             return $this->redirectToRoute('app_telegram_agent_public_bot_management_notification', ['botId' => $this->bot->getId()]);
  444.         }
  445.         return $this->render('panel/pages/user/telegram/agent-public-bot/management-users-notification.html.twig', [
  446.             'form' => $form->createView(),
  447.             'bot' => $this->bot
  448.         ]);
  449.     }
  450.     #[Route('/users/{userId}'name'app_telegram_agent_public_bot_management_users_transaction'methods: ['GET''POST'])]
  451.     public function app_telegram_agent_public_bot_management_users_transaction(Request $request$userId): Response
  452.     {
  453.         $botUser $this->getDoctrine()->getRepository(BotUser::class)->findOneBy(['userId' => $userId'bot' => $this->bot]);
  454.         $form $this->createFormBuilder()
  455.             ->add('type'ChoiceType::class, [
  456.                 'label' => 'نوع تراکنش',
  457.                 'choices' => [
  458.                     'افزایش' => 1,
  459.                     'کاهش' => 0,
  460.                 ]
  461.             ])
  462.             ->add('price'NumberType::class, [
  463.                 'label' => 'مبلغ به تومان'
  464.             ])
  465.             ->add('description'TextareaType::class, [
  466.                 'label' => 'توضیحات تراکنش'
  467.             ])->getForm();
  468.         $form->handleRequest($request);
  469.         if ($form->isSubmitted() && $form->isSubmitted()) {
  470.             $price $form->getData()['price'];
  471.             $type $form->getData()['type'];
  472.             $description $form->getData()['description'];
  473.             $transaction = new BotTransaction();
  474.             $transaction->setBot($this->bot);
  475.             $transaction->setBotUser($botUser);
  476.             $transaction->setPrice($price);
  477.             $transaction->setType($type);
  478.             $transaction->setDescription($description);
  479.             if ($type == 1) {
  480.                 $transaction->setType(1);
  481.                 $transaction->setBeforeWallet($botUser->getWallet());
  482.                 $transaction->setAfterWallet($botUser->getWallet() + $price);
  483.                 $transaction->setPrice($price);
  484.                 $transaction->setDescription($description);
  485.                 $botUser->setWallet($botUser->getWallet() + $price);
  486.             } else {
  487.                 $transaction->setType(0);
  488.                 $transaction->setBeforeWallet($botUser->getWallet());
  489.                 $transaction->setPrice($price);
  490.                 $transaction->setAfterWallet($botUser->getWallet() - $price);
  491.                 $botUser->setWallet($botUser->getWallet() - $price);
  492.                 $transaction->setDescription($description);
  493.             }
  494.             $this->getDoctrine()->getManager()->persist($transaction);
  495.             $this->getDoctrine()->getManager()->flush();
  496.             $this->addFlash('success''با موفقیت ثبت شد');
  497.             return $this->redirectToRoute('app_telegram_agent_public_bot_management_users', ['botId' => $this->bot->getId()]);
  498.         }
  499.         return $this->render('panel/pages/user/telegram/agent-public-bot/management-users-transaction.html.twig', [
  500.             'form' => $form->createView(),
  501.             'user' => $botUser,
  502.             'bot' => $this->bot
  503.         ]);
  504.     }
  505.     #[Route('/users-message/{userId}'name'app_telegram_agent_public_bot_management_users_send_message'methods: ['GET''POST'])]
  506.     public function app_telegram_agent_public_bot_management_users_send_message(NotificationService $notificationService ,Request $request$userId): Response
  507.     {
  508.         $botUser $this->getDoctrine()->getRepository(BotUser::class)->findOneBy(['userId' => $userId'bot' => $this->bot]);
  509.         $form $this->createFormBuilder()
  510.             ->add('message'TextareaType::class, [
  511.                 'label' => 'متن'
  512.             ])
  513.             ->getForm();
  514.         $form->handleRequest($request);
  515.         if ($form->isSubmitted() && $form->isValid()) {
  516.             try {
  517.                 $keyboard json_encode([
  518.                     "inline_keyboard" => [
  519.                         [
  520.                             [
  521.                                 "text" => "شروع",
  522.                                 "callback_data" => "/start"
  523.                             ]
  524.                         ]
  525.                     ]
  526.                 ]);
  527.                 $this->bot('sendMessage', [
  528.                     'chat_id' => $botUser->getUserId(),
  529.                     'text' => $form->getData()['message'],
  530.                     'reply_markup' => $keyboard
  531.                 ], $botUser->getBot()->getToken());
  532.             } catch (\Exception $exception) {
  533.                 $notificationService->exception($exception);
  534.                 $botUser->setActive(false);
  535.                 $botUser->setdeletedAt(new \DateTime());
  536.                 $this->getDoctrine()->getManager()->flush();
  537.             }
  538.             $text 'پیام با موفقیت ارسال شد';
  539.             $this->addFlash('success'$text);
  540.             return $this->redirectToRoute('app_telegram_agent_public_bot_management_users', ['botId' => $this->bot->getId()]);
  541.         }
  542.         return $this->render('panel/pages/user/telegram/agent-public-bot/management-users-transaction.html.twig', [
  543.             'form' => $form->createView(),
  544.             'user' => $botUser,
  545.             'bot' => $this->bot
  546.         ]);
  547.     }
  548.     public function bot($method$data$token)
  549.     {
  550.         $setting = new SettingService($this->entityManager);
  551.         $telegramApiUrl 'https://api.telegram.org/bot' $token '/';
  552.         return file_get_contents($telegramApiUrl $method '?' str_replace('&amp;''&'http_build_query($data)));
  553.     }
  554.     #[Route('/campaigns'name'app_telegram_agent_public_bot_management_campaigns'methods: ['GET''POST'])]
  555.     public function app_telegram_agent_public_bot_management_campaigns(Request $request): Response
  556.     {
  557.         $object $this->bot;
  558.         /**
  559.          * @var User $user
  560.          */
  561.         $user $this->getUser();
  562.         $info = new BotCampaignViewModel($request);
  563.         $data $this->botCampaignService->getList($info$this->bot);
  564.         return $this->render('panel/pages/user/telegram/agent-public-bot/management-campaigns.html.twig', [
  565.             'paginator' => $data,
  566.             'currentPage' => 'app_telegram_agent_public_bot_management_campaigns',
  567.             'bot' => $this->bot,
  568.             'parameters' => $info,
  569.             'filters' => $this->getFilters(),
  570.             'lists' => [
  571.                 [
  572.                     'name' => 'title',
  573.                     'label' => 'نام',
  574.                     'class' => '',
  575.                 ],
  576.                 [
  577.                     'name' => 'botUsersCount',
  578.                     'label' => 'تعداد کاربران',
  579.                     'class' => '',
  580.                 ],
  581.                 [
  582.                     'name' => 'createdAt',
  583.                     'label' => 'تاریخ ثبت کمپین',
  584.                     'class' => '',
  585.                     'type' => 'date'
  586.                 ],
  587.             ],
  588.         ]);
  589.     }
  590.     #[Route('/remove-plan/{planId}'name'app_user_agent_bot_plan_remove')]
  591.     public function app_user_agent_bot_plan_remove($planId): Response
  592.     {
  593.         $object $this->getDoctrine()->getRepository(BotPlan::class)->find($planId);
  594.         $object->setActive(0);
  595.         $object->setDeletedAt(new \DateTime());
  596.         $this->getDoctrine()->getManager()->flush();
  597.         return $this->redirectToRoute('app_telegram_agent_public_bot_management_price', ['botId' => $object->getBot()->getId()], Response::HTTP_SEE_OTHER);
  598.     }
  599.     public function getLastMonthChargeFromDate($date $bot)
  600.     {
  601.         $jdf = new JDF();
  602.         $jalaliArray $jdf->gregorianToJalali($date->format('Y'), $date->format('m'), $date->format('d'));
  603.         $jalaliArray[1] = $jalaliArray[1] - 1;
  604.         $gregorianArray $jdf->jalaliToGregorian($jalaliArray[0], $jalaliArray[1], $jalaliArray[2]);
  605.         $analyticsItem $this->getDoctrine()->getRepository(BotAnalytics::class)->findOneBy([
  606.             'bot' => $bot,
  607.             'date' => new \DateTimeImmutable($gregorianArray[0] . '-' $gregorianArray[1] . '-' $gregorianArray[2] . ' 00:00:00')]);
  608.         return $analyticsItem $analyticsItem->getWalletIncrease() : 0;
  609.     }
  610.     public function getLastMonthVolumeFromDate($date $bot)
  611.     {
  612.         $jdf = new JDF();
  613.         $jalaliArray $jdf->gregorianToJalali($date->format('Y'), $date->format('m'), $date->format('d'));
  614.         $jalaliArray[1] = $jalaliArray[1] - 1;
  615.         $gregorianArray $jdf->jalaliToGregorian($jalaliArray[0], $jalaliArray[1], $jalaliArray[2]);
  616.         $analyticsItem $this->getDoctrine()->getRepository(BotAnalytics::class)->findOneBy([
  617.             'bot' => $bot,
  618.             'date' => new \DateTimeImmutable($gregorianArray[0] . '-' $gregorianArray[1] . '-' $gregorianArray[2] . ' 00:00:00')]);
  619.         return $analyticsItem $analyticsItem->getBoughtVolume() : 0;
  620.     }
  621.     public function getLastMonthTotalServicesFromDate($date $bot)
  622.     {
  623.         $jdf = new JDF();
  624.         $jalaliArray $jdf->gregorianToJalali($date->format('Y'), $date->format('m'), $date->format('d'));
  625.         $jalaliArray[1] = $jalaliArray[1] - 1;
  626.         $gregorianArray $jdf->jalaliToGregorian($jalaliArray[0], $jalaliArray[1], $jalaliArray[2]);
  627.         $analyticsItem $this->getDoctrine()->getRepository(BotAnalytics::class)->findOneBy([
  628.             'bot' => $bot,
  629.             'date' => new \DateTimeImmutable($gregorianArray[0] . '-' $gregorianArray[1] . '-' $gregorianArray[2] . ' 00:00:00')]);
  630.         return $analyticsItem $analyticsItem->getBoughtService() : 0;
  631.     }
  632. }