src/Controller/NotificationController.php line 505

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\Routing\Annotation\Route;
  6. use App\Entity\Menu;
  7. use App\Entity\LogHistoryRequest;
  8. use App\Entity\User;
  9. use App\Entity\UserToken;
  10. use App\Entity\Notification;
  11. use Symfony\Component\HttpFoundation\JsonResponse;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Doctrine\ORM\EntityManagerInterface;
  14. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  15. use App\Service\AppApiService;
  16. use App\Entity\AppPersonalAccount;
  17. use App\Entity\MediaObject;
  18. use App\Entity\AppCounterReading;
  19. use App\Entity\DataReception;
  20. use App\Entity\Accounts;
  21. use App\Entity\ServiceOrderHistory;
  22. use Symfony\Component\HttpKernel\KernelInterface
  23. class NotificationController extends AbstractController
  24. {
  25.     public $datetime;
  26.     public $entityManager;
  27.     public $passwordEncoder;
  28.     public $appApiService;
  29.     private $kernel;
  30.     public function __construct( ?\DateTimeInterface $datetimeEntityManagerInterface $entityManagerAppApiService $appApiServiceKernelInterface $kernel ){
  31.         $this->datetime $datetime;
  32.         $this->entityManager $entityManager;
  33.         $this->appApiService $appApiService;
  34.         $this->kernel $kernel;
  35.     }
  36.     public function valid($requestFilds$requiredFilds){
  37.         $errors '';
  38.         foreach($requiredFilds as $f){
  39.             if(!isset($requestFilds[$f]))
  40.                 $errors .= $f"
  41.         }
  42.         return $errors;
  43.     }
  44.     public function logHistory($id$method$data){
  45.         if(!$id){
  46.             $LogHistoryRequest = new LogHistoryRequest();
  47.             $LogHistoryRequest->setMethod($method);
  48.             $LogHistoryRequest->setRequest($data);
  49.             $LogHistoryRequest->setDate(new \DateTime());
  50.             $LogHistoryRequest->setStatus('start');
  51.             $this->entityManager->persist($LogHistoryRequest);
  52.             $this->entityManager->flush();
  53.             return $LogHistoryRequest->getId();
  54.         }else{
  55.             $LogHistoryRequest $this->entityManager->getRepository(LogHistoryRequest::class)->findOneBy(['id' => $id]);
  56.             if($LogHistoryRequest){
  57.                 $LogHistoryRequest->setStatus('finish');
  58.                 $LogHistoryRequest->setResponseAnswer($data);
  59.                 $this->entityManager->persist($LogHistoryRequest);
  60.                 $this->entityManager->flush();
  61.             }
  62.             return true;
  63.         }
  64.         
  65.     }
  66.     
  67.     private function customAuth($request){
  68.         $validUser 'loe';
  69.         $validPassword 'GE2666Mh4maRa79iMs5igRPD';
  70.         $login $request->server->get('PHP_AUTH_USER');
  71.         $password $request->server->get('PHP_AUTH_PW');
  72.         if ($login !== $validUser || $password !== $validPassword) {
  73.             return false;
  74.         }
  75.         return true;
  76.     }
  77.     #[Route('/api/create-notfication'name'create_notfication'methods: ['POST'])]
  78.     public function create_notfication(Request $request)
  79.     {
  80.         if (!$this->customAuth($request)) {
  81.             return new JsonResponse(['message' => 'Unauthorized'], 401, [
  82.                 'WWW-Authenticate' => 'Basic realm="API Access"',
  83.             ]);
  84.         }
  85.         $data json_decode($request->getContent(), true);
  86.         // $logId = $this->logHistory(false, 'createPersonalAccount', $data);
  87.         file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  "\n\n\n" .  print_r($datatrue) . "\n"FILE_APPEND);
  88.         $valid $this->valid$data, ['user''title''body'] );
  89.         if( empty($valid) ){
  90.             $find $this->entityManager->getRepository(User::class)->findOneBy(['id' => $data['user']]);
  91.             if($find){
  92.                     $notification = new Notification();
  93.                     $notification->setUsers($find);
  94.                     $notification->setTitle$data['title']);
  95.                     $notification->setBody$data['body']);
  96.                     if(!empty($data['type']))
  97.                         $notification->setType$data['type']);
  98.                     else
  99.                         $notification->setType('text');
  100.                     $notification->setDateEntered( new \DateTime() );
  101.                     $notification->setStatus('new');
  102.                     $this->entityManager->persist($notification);
  103.                     $this->entityManager->flush();
  104.                     $rez = ['rez' => true'id' => $notification->getId()];
  105.                  
  106.                 // }else{
  107.                 //     $rez = ['registered' => false, $res];
  108.                 // }
  109.             }else{
  110.                 $rez = ['rez' => false'error' => "Користувача не знайдено"];
  111.             }
  112.         }else{
  113.             $rez = ['rez' => false'error' => "Не задано поля: $valid"];
  114.         }
  115.     
  116.         $response = new JsonResponse();
  117.         $response->setData($rez);
  118.         return $response;
  119.     }
  120.     public function sendCurl ($data){
  121.         /**
  122.          * admin
  123.          * w2mWOf5Q0hX8UX6H9h37hZk6RzBtnIBMqEfU173VKIsOmPzgEp
  124.          * if (preg_match('/<[^>]+>/', $html)) {
  125.          */
  126.         $json json_encode(
  127.             [
  128.                 'token' => $data['token'],
  129.                 // 'notification' => [
  130.                 //     'title' => $data['title'],
  131.                 //     'body' => strip_tags($data['body']),
  132.                 //     // 'type_text' => $data['type'],
  133.                 //     // 'text' => $data['body'],
  134.                 //     // 'text' => "",
  135.                 //     // 'image' => ''
  136.                 // ],
  137.                 'data' => [
  138.                     'title' => $data['title'],
  139.                     'body' => strip_tags$data['body'] ),
  140.                     'type_text' => (preg_match('/<[^>]+>/'$data['body'] ))? 'html':'text',
  141.                     'text' => $data['body'],
  142.                     // 'text' => "",
  143.                     // 'image' => ''
  144.                 ],
  145.                 'apns' => [
  146.                     'payload' => [
  147.                         'aps' => [
  148.                             'content-available' => 1,                            
  149.                             "alert" => [
  150.                                 'title' => $data['title'],
  151.                                 'body' => strip_tags($data['body']),
  152.                                 // "image": "https://api-app.de-svitlo.com.ua/media/66ea934b9674c_lightbulb_red.png"
  153.                             ],
  154.                         ]
  155.                     ]
  156.                     
  157.                 ],
  158.                 'topic' => '',
  159.                 'condition' => ''
  160.                     
  161.             ]
  162.         );
  163.         // file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  "st - " .  date('H:i:s') . "\n", FILE_APPEND);
  164.         // file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  print_r($json, true) . "\n", FILE_APPEND);
  165.         $ch curl_init();
  166.         curl_setopt($chCURLOPT_URL'https://dev-firebase-proxy.inneti.net/api/message/notify');
  167.         curl_setopt($chCURLOPT_HTTPAUTHCURLAUTH_BASIC);
  168.         curl_setopt($chCURLOPT_USERPWD"admin:w2mWOf5Q0hX8UX6H9h37hZk6RzBtnIBMqEfU173VKIsOmPzgEp");
  169.         curl_setopt($chCURLOPT_CUSTOMREQUEST"POST");
  170.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  171.         curl_setopt($chCURLOPT_CONNECTTIMEOUT5);
  172.         curl_setopt($chCURLOPT_TIMEOUT5);
  173.         curl_setopt(
  174.           $ch,
  175.           CURLOPT_POSTFIELDS,
  176.           $json
  177.         );
  178.         $answer curl_exec($ch);
  179.         curl_close($ch);
  180.        return $answer
  181.     }
  182.     #[Route('/api/send-notfication'name'send_notfication'methods: ['GET'])]
  183.     public function send_notfication(Request $request)
  184.     {
  185.         $send 0;
  186.         $err 0;
  187.         file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  "************************" .  date('H:i:s') . "\n"FILE_APPEND);
  188.         $notifications $this->entityManager->getRepository(Notification::class)->findBy(['status' => 'new']);
  189.         file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  "1111111" .  date('H:i:s') . "\n"FILE_APPEND);
  190.             if($notifications){
  191.                     
  192.                 foreach($notifications as $notification){
  193.                     $send 0;
  194.                     $user $notification->getUsers();
  195.                     // $tokensArr = [];
  196.                     if($user){
  197.                         $tokens $user->getUserTokens();
  198.                         if(!empty($tokens) AND count($tokens) > 0){
  199.                             
  200.                         }else{
  201.                             $device_id $user->getDeviceId();
  202.                             $tokens $this->entityManager->getRepository(UserToken::class)->findBy(['device_id' => $device_id'active' => true]);
  203.                         }
  204.                         foreach($tokens as $token){
  205.                             if(!$token->isActive())
  206.                                 continue;
  207.                             // file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  "st - " .  date('H:i:s') . "\n", FILE_APPEND);
  208.                             $resultJson $this->sendCurl([
  209.                                 'token' => $token->getTokenFcm(),
  210.                                 'title' => $notification->getTitle(),
  211.                                 'body' => $notification->getBody(),
  212.                                 'type' => $notification->getType(),
  213.                             ]);
  214.                             // file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',   $resultJson  . "\n", FILE_APPEND);
  215.                             // file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',   "   - " . date('H:i:s') . "\n", FILE_APPEND);
  216.                             $notification->setDateSend( new \DateTime() );
  217.                             $result json_decode($resultJsontrue);
  218.                             if(!empty( $result['res'] )){
  219.                                 $send 1;
  220.                                 $notification->setStatus('send');
  221.                                 $send++;
  222.                             }elseif(!empty( $result['err'] )){
  223.                                 $send 2;
  224.                                 $token->setActive(false);
  225.                                 $notification->setStatus('error');
  226.                                 $notification->setError($notification->getError() .  "\n" date('Y-m-d H:i:s') . $token->getTokenFcm() . "\n" $resultJson);
  227.                                 $err++;
  228.                             }else{
  229.                                 $send 3;
  230.                                 $token->setActive(false);
  231.                                 $notification->setStatus('error');
  232.                                 $notification->setError($notification->getError() .  "\n" date('Y-m-d H:i:s') . $token->getTokenFcm() . "\n" $resultJson);
  233.                                 $err++;
  234.                             }
  235.                             $this->entityManager->persist($token);
  236.                             $this->entityManager->persist($notification);
  237.                             $this->entityManager->flush();
  238.                         }
  239.                         
  240.                     }
  241.                     
  242.                     /** Якщо ключа нема */
  243.                     if($send == 0){
  244.                         $notification->setStatus('not_token');
  245.                         $notification->setError($notification->getError() .  "\n" date('Y-m-d H:i:s') .  " Ключ не знайдено \n");
  246.                         $this->entityManager->persist($notification);
  247.                         $this->entityManager->flush();
  248.                     }
  249.                     // echo '222'; 
  250.                     // die('1111');
  251.                 }
  252.                     // $this->entityManager->persist($notification);
  253.                     // $this->entityManager->flush();
  254.                     // $rez = ['rez' => true, 'id' => $notification->getId()];
  255.                  
  256.                 // }else{
  257.                 //     $rez = ['registered' => false, $res];
  258.                 // }
  259.             }else{
  260.                 $rez = ['rez' => false'error' => "Незнайдено нових сповіщень!"];
  261.             }
  262.    
  263.     
  264.         $response = new JsonResponse();
  265.         $response->setData(['send' => $send'err' => $err]);
  266.         file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  "***********END*************" .  date('H:i:s') . "\n"FILE_APPEND);
  267.         return $response;
  268.     }
  269.     #[Route('/api/create-notfication-actions'name'create_notfication_account'methods: ['POST'])]
  270.     public function create_notfication_account(Request $request)
  271.     {
  272.         if (!$this->customAuth($request)) {
  273.             return new JsonResponse(['message' => 'Unauthorized'], 401, [
  274.                 'WWW-Authenticate' => 'Basic realm="API Access"',
  275.             ]);
  276.         }
  277.         // { "sender": "loe", "msg-type": "from-ns", "msg-data": { "priority": 0, "ns_msg_id": 123, "title": "шапка повідомлення", "receivers": { "account1": "текст повідомлення", "account2": "текст повідомлення", "account3": "текст повідомлення" } } }
  278.         // $arr = [
  279.         //     'sender'     => 'loe',        // від кого прийшло (ЛОЕ, вооканал і т.д.)    
  280.         //     'msg-type'     => 'from-ns',    // будуть інші типи з іншими наборами даних
  281.         //     'msg-data'     => [
  282.         //         'priority' => 0,     // пріоритет (ціле додатнє число типу tinyint)
  283.         //         'ns_msg_id' => 123, // моя ідешка (тип int)
  284.         //         'title' => 'шапка повідомлення',
  285.         //         'receivers' => [ // для даного типу повідомлення це масив, де ключ - номер особового рахунку, значення - текст повідомлення
  286.         //             'account1' => 'текст повідомлення',  
  287.         //             'account2' => 'текст повідомлення',
  288.         //             'account3' => 'текст повідомлення'
  289.         //             // ...
  290.         //         ],
  291.         //     ],
  292.         // ];
  293.       
  294.         // echo json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
  295.         // die;
  296.         $data json_decode($request->getContent(), true);
  297.         
  298.         // if(isset($data['msg-type']) AND $data['msg-type'] == 'number-phone') 
  299.         //     file_put_contents('/var/www/symfony_docker/public/media/notification-sms.log', date('Y-m-d H:i:s') . ' ' . $request->getContent() . "\n", FILE_APPEND);
  300.         // echo '<pre>';
  301.         // print_r($data);
  302.         // die;
  303.         // $logId = $this->logHistory(false, 'createPersonalAccount', $data);
  304.         // file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  "\n\n\n" .  print_r($data, true) . "\n", FILE_APPEND);
  305.         $send = [];
  306.         $err '';
  307.         $valid $this->valid$data, ['sender''msg-data'] );
  308.         if( empty($valid) ){
  309.             $title $data['msg-data']['title'];
  310.             if(isset($data['msg-data']['receivers']) AND count($data['msg-data']['receivers']) > 0){
  311.                 
  312.                 
  313.                 if($data['msg-type'] == 'from-ns'){
  314.                     $i 0;
  315.                     foreach($data['msg-data']['receivers'] as $number => $receivers){
  316.                         $AccountUser = [];
  317.                         /** Шукаю Всі особові за номером */
  318.                         $findAccounts $this->entityManager->getRepository(AppPersonalAccount::class)->findBy(['number' => $number]);
  319.                         if($findAccounts){
  320.                             foreach($findAccounts as $account){
  321.                                 $user_id $account->getOwner()->getId();
  322.                                 if(!isset( $AccountUser$user_id]  ))
  323.                                     $AccountUser[$user_id] = [];
  324.     
  325.                                 /** Перевірка якщо в користувача додано декілька однакових особових */
  326.                                 if(!isset( $AccountUser[$user_id][ $number ] )){
  327.                                     $AccountUser[$user_id][ $number ] = true;
  328.                                 
  329.                                     $notification = new Notification();
  330.                                     $notification->setUsers($account->getOwner());
  331.                                     $notification->setTitle$title );
  332.                                     $notification->setBody($receivers);
  333.     
  334.                                     if(!empty($data['msg-data']['type']))
  335.                                         $notification->setType$data['msg-data']['type']);
  336.                                     else
  337.                                         $notification->setType('text');
  338.     
  339.                                     $notification->setDateEntered( new \DateTime() );
  340.                                     $notification->setStatus('new');
  341.                                     if(!empty($data['msg-data']['priority']))
  342.                                         $notification->setPriority($data['msg-data']['priority']);
  343.     
  344.                                     if(!empty($data['msg-data']['ns_msg_id']))
  345.                                         $notification->setNsMsgId($data['msg-data']['ns_msg_id']);
  346.     
  347.                                     $this->entityManager->persist($notification);
  348.                                     // $this->entityManager->flush();
  349.                                     if(!isset($send[$number]))
  350.                                         $send[$number] = 1;
  351.                                     else
  352.                                         ++$send[$number];
  353.     
  354.     
  355.                                     $i++;
  356.                                 }
  357.     
  358.                                 if($i == 100){
  359.                                     $this->entityManager->flush();
  360.                                     $i 0;
  361.                                 }    
  362.                             }
  363.                         }   
  364.                     }
  365.                 }elseif($data['msg-type'] == 'number-phone'){
  366.                     $i 0;
  367.                     foreach($data['msg-data']['receivers'] as $number => $receivers){
  368.                         $find $this->entityManager->getRepository(User::class)->findOneBy(['phone' => $number]);
  369.                         if($find){
  370.                                 $notification = new Notification();
  371.                                 $notification->setUsers($find);
  372.                                 $notification->setTitle$title);
  373.                                 $notification->setBody$receivers );
  374.             
  375.                                 if(!empty($data['msg-data']['type']))
  376.                                     $notification->setType$data['msg-data']['type']);
  377.                                 else
  378.                                     $notification->setType('text');
  379.             
  380.                                 $notification->setDateEntered( new \DateTime() );
  381.                                 $notification->setStatus('new');
  382.                                 if(!empty($data['msg-data']['priority']))
  383.                                         $notification->setPriority($data['msg-data']['priority']);
  384.     
  385.                                 if(!empty($data['msg-data']['ns_msg_id']))
  386.                                     $notification->setNsMsgId($data['msg-data']['ns_msg_id']);
  387.             
  388.                                 $this->entityManager->persist($notification);
  389.                                 $i++;
  390.                         }
  391.                         if($i == 100){
  392.                             $this->entityManager->flush();
  393.                             $i 0;
  394.                         }
  395.                     }
  396.                 }
  397.                 
  398.                 $this->entityManager->flush();
  399.             }
  400.             $rez = ['rez' => true'send' => $send 'error' => ""];
  401.         }else{
  402.             $rez = ['rez' => false'error' => "Не задано поля: $valid"];
  403.         }
  404.         $response = new JsonResponse();
  405.         $response->setData($rez);
  406.         return $response;
  407.     }
  408.     #[Route('/api/create-data-reception'name'create_notfication_data_reception'methods: ['POST'])]
  409.     public function create_notfication_data_reception(Request $request)
  410.     {
  411.         if (!$this->customAuth($request)) {
  412.             return new JsonResponse(['message' => 'Unauthorized'], 401, [
  413.                 'WWW-Authenticate' => 'Basic realm="API Access"',
  414.             ]);
  415.         }
  416.         $data json_decode($request->getContent(), true);
  417.         // $logId = $this->logHistory(false, 'createPersonalAccount', $data);
  418.         // file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  "\n\n\n" .  print_r($data, true) . "\n", FILE_APPEND);
  419.         $valid $this->valid$data, ['method''data'] );
  420.         if( empty($valid) ){
  421.             
  422.             $DataReception = new DataReception();
  423.             $DataReception->setType$data['method']);
  424.             $DataReception->setData$data['data']);
  425.             $DataReception->setDateEntered( new \DateTime() );
  426.             $DataReception->setStatus('new');
  427.             $this->entityManager->persist($DataReception);
  428.             $this->entityManager->flush();
  429.             $rez = ['rez' => true'id' => $DataReception->getId()];
  430.                  
  431.         }else{
  432.             $rez = ['rez' => false'error' => "Не задано поля: $valid"];
  433.         }
  434.     
  435.         $response = new JsonResponse();
  436.         $response->setData($rez);
  437.         return $response;
  438.     }
  439.     public function updateStatus($inf){
  440.         $query $this->entityManager->createQuery(
  441.             'UPDATE App\Entity\Accounts d 
  442.              SET d.statusPlanning = :new_status 
  443.              WHERE d.eic IN (:ids)'
  444.         );
  445.         $query->setParameter('new_status''planned');
  446.         $query->setParameter('ids'$inf); // Масив ID
  447.         $query->execute();
  448.     }
  449.     #[Route('/cron-get-planned'name'cron_get_pllanned'methods: ['GET'])]
  450.     public function cron_get_pllanned(Request $request)
  451.     {
  452.         $query $this->entityManager->createQuery(
  453.             'UPDATE App\Entity\Accounts d SET d.statusPlanning = :new_status'
  454.         );
  455.         $query->setParameter('new_status''not_pllaned');
  456.         // $query->setParameter('old_status', 'new');
  457.         // echo '<pre>';
  458.         $query->execute();
  459.         $this->entityManager->clear();
  460.         $DataReception $this->entityManager->getRepository(DataReception::class)->findBy(['status' => 'new']);
  461.         $eic = [];
  462.         foreach($DataReception as $data){
  463.             $infos json_decode($data->getData(), true);
  464.             foreach($infos as $acc_id =>  $inf){
  465.                 array_push($eic$inf);
  466.                 if(count($eic) == 500){
  467.                     $this->updateStatus($eic);
  468.                     $eic = [];
  469.                 }
  470.             }
  471.             if(count($eic) > 0)
  472.                 $this->updateStatus($eic);
  473.             $this->entityManager->clear();
  474.             $data->setStatus('complate');
  475.             $this->entityManager->persist($data);
  476.             $this->entityManager->flush();
  477.             // print_r($infos);
  478.         }
  479.         echo count($DataReception); die;
  480.     }
  481.     #[Route('/api/get-account-all-data'name'get_account_all_data'methods: ['GET'])]
  482.     public function get_account_all_data(Request $request):Response
  483.     {   
  484.         set_time_limit(0);
  485.         // echo '<pre>';
  486.         $i 0;
  487.         $AppPersonalAccount $this->entityManager->getRepository(AppPersonalAccount::class)->findBy(['counter' => null]);
  488.         foreach($AppPersonalAccount as $account){
  489.             // if(!empty( $account->getEic() ))
  490.             //     continue;
  491.             $i++;
  492.             $data = [
  493.                 'account' => $account->getNumber()
  494.             ];
  495.             // echo $account->getId() . "<br>";
  496.             // echo $account->getNumber() . "<br>";
  497.             $res json_decode$this->appApiService->account_all_data($data) , true );  
  498.             
  499.             // print_r( $res ); 
  500.             
  501.             // if($i > 5)
  502.             //     die;
  503.             if(isset($res['rez']) AND $res['rez'] == AND isset($res['data'][0])){
  504.                 file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',   print_r($restrue)  . "\n"FILE_APPEND);
  505.                 $account->setEic($res['data'][0]['eic_kod']);  
  506.                 $account->setCounter($res['data'][0]['counter']);  
  507.                 
  508.                 $this->entityManager->persist($account);
  509.                 $this->entityManager->flush();
  510.                 // continue;
  511.                 // $accounts = $this->entityManager->getRepository(Accounts::class)->findOneBy(['number' => $account->getNumber()]);
  512.                 // if(!$accounts){
  513.                 //     $accounts = new Accounts();
  514.                 //     $accounts->setNumber($account->getNumber());
  515.                 //     $accounts->setEic($account->getEic());
  516.                 //     // $accounts->setEicParent($res_data['eic_kod_place']);
  517.                 //     $this->entityManager->persist($accounts);
  518.                 //     $this->entityManager->flush();
  519.                 //     $account->setAccounts($accounts);
  520.                 // }
  521.                 // $account->setCounter($accounts);
  522.                 // $this->entityManager->persist($account);
  523.                 // $this->entityManager->flush();
  524.             }
  525.             // print_r($res); die;
  526.         }
  527.         // echo count( $AppPersonalAccount ); die;
  528.         return new Response('1');
  529.         
  530.     }
  531.     /** Додавання id crm LOE */
  532.     #[Route('/api/update-service-id'name'update_service_id'methods: ['POST'])]
  533.     public function update_service_id(Request $request)
  534.     {
  535.         if (!$this->customAuth($request)) {
  536.             return new JsonResponse(['message' => 'Unauthorized'], 401, [
  537.                 'WWW-Authenticate' => 'Basic realm="API Access"',
  538.             ]);
  539.         }
  540.         $data json_decode($request->getContent(), true);
  541.         // $logId = $this->logHistory(false, 'createPersonalAccount', $data);
  542.         // file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  "\n\n\n" .  print_r($data, true) . "\n", FILE_APPEND);
  543.         $valid $this->valid$data, ['id''id_crm'] );
  544.         if( empty($valid) ){
  545.             
  546.             $ServiceOrderHistory $this->entityManager->getRepository(ServiceOrderHistory::class)->findOneBy(['id' => $data['id']]);
  547.             if($ServiceOrderHistory){
  548.                 $ServiceOrderHistory->setIdCrm$data['id_crm']);
  549.                 if(!empty( $data['status'] ))
  550.                     $ServiceOrderHistory->setStatus(  $data['status'] );
  551.                 else
  552.                     $ServiceOrderHistory->setStatus'in_process' );
  553.                 if(!empty( $data['description'] ))
  554.                     $ServiceOrderHistory->setDescription(  $data['description'] );
  555.     
  556.                 $ServiceOrderHistory->setDateModified( new \DateTime() );
  557.                 // $ServiceOrderHistory->setStatus('new');
  558.     
  559.                 $this->entityManager->persist($ServiceOrderHistory);
  560.                 $this->entityManager->flush();
  561.             }
  562.             $rez = ['rez' => true'id' => $ServiceOrderHistory->getId()];
  563.                  
  564.         }else{
  565.             $rez = ['rez' => false'error' => "Не задано поля: $valid"];
  566.         }
  567.     
  568.         $response = new JsonResponse();
  569.         $response->setData($rez);
  570.         return $response;
  571.     }
  572.     /** Додавання id crm LOE */
  573.     #[Route('/api/get-service-id'name'get_service_id'methods: ['GET'])]
  574.     public function get_service_id(Request $request)
  575.     {
  576.         if (!$this->customAuth($request)) {
  577.             return new JsonResponse(['message' => 'Unauthorized'], 401, [
  578.                 'WWW-Authenticate' => 'Basic realm="API Access"',
  579.             ]);
  580.         }
  581.         $arr = [];
  582.         $ServiceOrderHistory $this->entityManager->getRepository(ServiceOrderHistory::class)->findBy(['status' => 'in_process']);
  583.         
  584.         foreach($ServiceOrderHistory as $service){
  585.             $arr[] = [
  586.                 'id' => $service->getId(),
  587.                 'id_crm' => $service->getIdCrm(),
  588.             ];
  589.         }
  590.         
  591.         
  592.         $rez = ['rez' => true'data' => $arr];
  593.     
  594.         $response = new JsonResponse();
  595.         $response->setData($rez);
  596.         return $response;
  597.     }
  598.     /** Історія заявок з сторонніх систем */
  599.     #[Route('/api/create-order-history'name'create_order_history'methods: ['POST'])]
  600.     public function create_order_history(Request $request)
  601.     {
  602.         if (!$this->customAuth($request)) {
  603.             return new JsonResponse(['message' => 'Unauthorized'], 401, [
  604.                 'WWW-Authenticate' => 'Basic realm="API Access"',
  605.             ]);
  606.         }
  607.         $data json_decode($request->getContent(), true);
  608.         $valid $this->valid$data, ['phone''account''service_code''status''id_crm'] );
  609.         if( empty($valid) ){
  610.             $find $this->entityManager->getRepository(User::class)->findOneBy(['phone' => $data['phone']]);
  611.             if($find){
  612.                 $arr = [];
  613.                 
  614.                 $orderNames = [
  615.                     =>  "Встановлення зонного лічильника",
  616.                     10 =>  "Лічильник не працює",
  617.                     21 =>  "Неправильний показ",
  618.                     32 =>  "Зміна власника",
  619.                     35 =>  "Підключення електроустановок замовника після виконання ТУ",
  620.                     63 =>  "Звернення щодо підозри на крадіжку",
  621.                     79 =>  "Заміна автоматичного вимикача, який опломбований ОСР",
  622.                     85 =>  "Відсутність пломб на засобі обліку",
  623.                     86 =>  "Закриття особового рахунку",
  624.                     200 =>  "Попередній запис в електронну чергу",
  625.                 ];
  626.                 $account false;
  627.                 foreach($find->getAppPersonalAccounts() as $acc){
  628.                     if($acc->getNumber() == $data['account'])
  629.                         $account $acc;
  630.                 }
  631.                 
  632.                 if(!$account AND count($find->getAppPersonalAccounts()) > 0){
  633.                     $account $find->getAppPersonalAccounts()[0];
  634.                 }
  635.                 if($account){
  636.                     $ServiceOrderHistory = new ServiceOrderHistory();
  637.                     $ServiceOrderHistory->setName($orderNames[$data['service_code']]);
  638.                     // $ServiceOrderHistory->setRequest($data);
  639.                     $ServiceOrderHistory->setDateEntered( new \DateTime() );
  640.                     $ServiceOrderHistory->setType($data['service_code']);
  641.                     $ServiceOrderHistory->setStatus('new');
  642.                     $ServiceOrderHistory->setPersonalAccount($account);
  643.                     if(!empty( $data['id_crm'] ))
  644.                         $ServiceOrderHistory->setIdCrm$data['id_crm']);
  645.                     if(!empty( $data['status'] ))
  646.                         $ServiceOrderHistory->setStatus(  $data['status'] );
  647.                     else
  648.                         $ServiceOrderHistory->setStatus'in_process' );
  649.                     if(!empty( $data['description'] ))
  650.                         $ServiceOrderHistory->setDescription(  $data['description'] );
  651.         
  652.                     if($data['service_code'] == 200){
  653.                         $ServiceOrderHistory->setStatus('-100');
  654.                         $ServiceOrderHistory->setDescription('Виконано');
  655.                     }
  656.                     $ServiceOrderHistory->setPersonalAccount($account);
  657.                     $this->entityManager->persist($ServiceOrderHistory);
  658.                     $this->entityManager->flush();
  659.                     $data["id"] = $ServiceOrderHistory->getId();
  660.                     
  661.                     
  662.                     $rez = ['rez' => true'data' => [
  663.                         'id' => $ServiceOrderHistory->getId()
  664.                     ]];
  665.                 }else{
  666.                     $rez = ['rezult' => false'error' => "Нема жодного особового рахунку"];   
  667.                 }
  668.             }else{
  669.                 $rez = ['rezult' => false'error' => "Користувача не знайдено!"];   
  670.             }
  671.         
  672.         }else{
  673.             $rez = ['rez' => false'error' => "Не задано поля: $valid"];
  674.         }
  675.     
  676.         $response = new JsonResponse();
  677.         $response->setData($rez);
  678.         return $response;
  679.     }
  680. }