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.          */
  125.         $json json_encode(
  126.             [
  127.                 'token' => $data['token'],
  128.                 'data' => [
  129.                     'title' => $data['title'],
  130.                     'body' => $data['body'],
  131.                     'type_text' => $data['type'],
  132.                     'text' => $data['body'],
  133.                     // 'text' => "",
  134.                     // 'image' => ''
  135.                 ],
  136.                 'apns' => [
  137.                     'payload' => [
  138.                         'aps' => [
  139.                             'content-available' => 1
  140.                         ]
  141.                     ]
  142.                 ],
  143.                 'topic' => '',
  144.                 'condition' => ''
  145.                     
  146.             ]
  147.         );
  148.         $ch curl_init();
  149.         curl_setopt($chCURLOPT_URL'https://dev-firebase-proxy.inneti.net/api/message/notify');
  150.         curl_setopt($chCURLOPT_HTTPAUTHCURLAUTH_BASIC);
  151.         curl_setopt($chCURLOPT_USERPWD"admin:w2mWOf5Q0hX8UX6H9h37hZk6RzBtnIBMqEfU173VKIsOmPzgEp");
  152.         curl_setopt($chCURLOPT_CUSTOMREQUEST"POST");
  153.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  154.         curl_setopt($chCURLOPT_CONNECTTIMEOUT5);
  155.         curl_setopt($chCURLOPT_TIMEOUT5);
  156.         curl_setopt(
  157.           $ch,
  158.           CURLOPT_POSTFIELDS,
  159.           $json
  160.         );
  161.         $answer curl_exec($ch);
  162.         curl_close($ch);
  163.        return $answer
  164.     }
  165.     #[Route('/api/send-notfication'name'send_notfication'methods: ['GET'])]
  166.     public function send_notfication(Request $request)
  167.     {
  168.         $send 0;
  169.         $err 0;
  170.         file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  "************************" .  date('H:i:s') . "\n"FILE_APPEND);
  171.         $notifications $this->entityManager->getRepository(Notification::class)->findBy(['status' => 'new']);
  172.         file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  "1111111" .  date('H:i:s') . "\n"FILE_APPEND);
  173.             if($notifications){
  174.                     
  175.                 foreach($notifications as $notification){
  176.                     $send 0;
  177.                     $user $notification->getUsers();
  178.                     // $tokensArr = [];
  179.                     if($user){
  180.                         $tokens $user->getUserTokens();
  181.                         if(!empty($tokens) AND count($tokens) > 0){
  182.                             
  183.                         }else{
  184.                             $device_id $user->getDeviceId();
  185.                             $tokens $this->entityManager->getRepository(UserToken::class)->findBy(['device_id' => $device_id'active' => true]);
  186.                         }
  187.                         foreach($tokens as $token){
  188.                             if(!$token->isActive())
  189.                                 continue;
  190.                             file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  "st - " .  date('H:i:s') . "\n"FILE_APPEND);
  191.                             $resultJson $this->sendCurl([
  192.                                 'token' => $token->getTokenFcm(),
  193.                                 'title' => $notification->getTitle(),
  194.                                 'body' => $notification->getBody(),
  195.                                 'type' => $notification->getType(),
  196.                             ]);
  197.                             file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',   $resultJson  "\n"FILE_APPEND);
  198.                             file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',   "   - " date('H:i:s') . "\n"FILE_APPEND);
  199.                             $notification->setDateSend( new \DateTime() );
  200.                             $result json_decode($resultJsontrue);
  201.                             if(!empty( $result['res'] )){
  202.                                 $send 1;
  203.                                 $notification->setStatus('send');
  204.                                 $send++;
  205.                             }elseif(!empty( $result['err'] )){
  206.                                 $send 2;
  207.                                 $token->setActive(false);
  208.                                 $notification->setStatus('error');
  209.                                 $notification->setError($notification->getError() .  "\n" date('Y-m-d H:i:s') . $token->getTokenFcm() . "\n" $resultJson);
  210.                                 $err++;
  211.                             }else{
  212.                                 $send 3;
  213.                                 $token->setActive(false);
  214.                                 $notification->setStatus('error');
  215.                                 $notification->setError($notification->getError() .  "\n" date('Y-m-d H:i:s') . $token->getTokenFcm() . "\n" $resultJson);
  216.                                 $err++;
  217.                             }
  218.                             $this->entityManager->persist($token);
  219.                             $this->entityManager->persist($notification);
  220.                             $this->entityManager->flush();
  221.                         }
  222.                         
  223.                     }
  224.                     
  225.                     /** Якщо ключа нема */
  226.                     if($send == 0){
  227.                         $notification->setStatus('not_token');
  228.                         $notification->setError($notification->getError() .  "\n" date('Y-m-d H:i:s') .  " Ключ не знайдено \n");
  229.                         $this->entityManager->persist($notification);
  230.                         $this->entityManager->flush();
  231.                     }
  232.                     // echo '222'; 
  233.                     // die('1111');
  234.                 }
  235.                     // $this->entityManager->persist($notification);
  236.                     // $this->entityManager->flush();
  237.                     // $rez = ['rez' => true, 'id' => $notification->getId()];
  238.                  
  239.                 // }else{
  240.                 //     $rez = ['registered' => false, $res];
  241.                 // }
  242.             }else{
  243.                 $rez = ['rez' => false'error' => "Незнайдено нових сповіщень!"];
  244.             }
  245.    
  246.     
  247.         $response = new JsonResponse();
  248.         $response->setData(['send' => $send'err' => $err]);
  249.         file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  "***********END*************" .  date('H:i:s') . "\n"FILE_APPEND);
  250.         return $response;
  251.     }
  252.     #[Route('/api/create-notfication-actions'name'create_notfication_account'methods: ['POST'])]
  253.     public function create_notfication_account(Request $request)
  254.     {
  255.         if (!$this->customAuth($request)) {
  256.             return new JsonResponse(['message' => 'Unauthorized'], 401, [
  257.                 'WWW-Authenticate' => 'Basic realm="API Access"',
  258.             ]);
  259.         }
  260.         // { "sender": "loe", "msg-type": "from-ns", "msg-data": { "priority": 0, "ns_msg_id": 123, "title": "шапка повідомлення", "receivers": { "account1": "текст повідомлення", "account2": "текст повідомлення", "account3": "текст повідомлення" } } }
  261.         // $arr = [
  262.         //     'sender'     => 'loe',        // від кого прийшло (ЛОЕ, вооканал і т.д.)    
  263.         //     'msg-type'     => 'from-ns',    // будуть інші типи з іншими наборами даних
  264.         //     'msg-data'     => [
  265.         //         'priority' => 0,     // пріоритет (ціле додатнє число типу tinyint)
  266.         //         'ns_msg_id' => 123, // моя ідешка (тип int)
  267.         //         'title' => 'шапка повідомлення',
  268.         //         'receivers' => [ // для даного типу повідомлення це масив, де ключ - номер особового рахунку, значення - текст повідомлення
  269.         //             'account1' => 'текст повідомлення',  
  270.         //             'account2' => 'текст повідомлення',
  271.         //             'account3' => 'текст повідомлення'
  272.         //             // ...
  273.         //         ],
  274.         //     ],
  275.         // ];
  276.       
  277.         // echo json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
  278.         // die;
  279.         $data json_decode($request->getContent(), true);
  280.         
  281.         // if(isset($data['msg-type']) AND $data['msg-type'] == 'number-phone') 
  282.         //     file_put_contents('/var/www/symfony_docker/public/media/notification-sms.log', date('Y-m-d H:i:s') . ' ' . $request->getContent() . "\n", FILE_APPEND);
  283.         // echo '<pre>';
  284.         // print_r($data);
  285.         // die;
  286.         // $logId = $this->logHistory(false, 'createPersonalAccount', $data);
  287.         // file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  "\n\n\n" .  print_r($data, true) . "\n", FILE_APPEND);
  288.         $send = [];
  289.         $err '';
  290.         $valid $this->valid$data, ['sender''msg-data'] );
  291.         if( empty($valid) ){
  292.             $title $data['msg-data']['title'];
  293.             if(isset($data['msg-data']['receivers']) AND count($data['msg-data']['receivers']) > 0){
  294.                 
  295.                 
  296.                 if($data['msg-type'] == 'from-ns'){
  297.                     $i 0;
  298.                     foreach($data['msg-data']['receivers'] as $number => $receivers){
  299.                         $AccountUser = [];
  300.                         /** Шукаю Всі особові за номером */
  301.                         $findAccounts $this->entityManager->getRepository(AppPersonalAccount::class)->findBy(['number' => $number]);
  302.                         if($findAccounts){
  303.                             foreach($findAccounts as $account){
  304.                                 $user_id $account->getOwner()->getId();
  305.                                 if(!isset( $AccountUser$user_id]  ))
  306.                                     $AccountUser[$user_id] = [];
  307.     
  308.                                 /** Перевірка якщо в користувача додано декілька однакових особових */
  309.                                 if(!isset( $AccountUser[$user_id][ $number ] )){
  310.                                     $AccountUser[$user_id][ $number ] = true;
  311.                                 
  312.                                     $notification = new Notification();
  313.                                     $notification->setUsers($account->getOwner());
  314.                                     $notification->setTitle$title );
  315.                                     $notification->setBody($receivers);
  316.     
  317.                                     if(!empty($data['msg-data']['type']))
  318.                                         $notification->setType$data['msg-data']['type']);
  319.                                     else
  320.                                         $notification->setType('text');
  321.     
  322.                                     $notification->setDateEntered( new \DateTime() );
  323.                                     $notification->setStatus('new');
  324.                                     if(!empty($data['msg-data']['priority']))
  325.                                         $notification->setPriority($data['msg-data']['priority']);
  326.     
  327.                                     if(!empty($data['msg-data']['ns_msg_id']))
  328.                                         $notification->setNsMsgId($data['msg-data']['ns_msg_id']);
  329.     
  330.                                     $this->entityManager->persist($notification);
  331.                                     // $this->entityManager->flush();
  332.                                     if(!isset($send[$number]))
  333.                                         $send[$number] = 1;
  334.                                     else
  335.                                         ++$send[$number];
  336.     
  337.     
  338.                                     $i++;
  339.                                 }
  340.     
  341.                                 if($i == 100){
  342.                                     $this->entityManager->flush();
  343.                                     $i 0;
  344.                                 }    
  345.                             }
  346.                         }   
  347.                     }
  348.                 }elseif($data['msg-type'] == 'number-phone'){
  349.                     $i 0;
  350.                     foreach($data['msg-data']['receivers'] as $number => $receivers){
  351.                         $find $this->entityManager->getRepository(User::class)->findOneBy(['phone' => $number]);
  352.                         if($find){
  353.                                 $notification = new Notification();
  354.                                 $notification->setUsers($find);
  355.                                 $notification->setTitle$title);
  356.                                 $notification->setBody$receivers );
  357.             
  358.                                 if(!empty($data['msg-data']['type']))
  359.                                     $notification->setType$data['msg-data']['type']);
  360.                                 else
  361.                                     $notification->setType('text');
  362.             
  363.                                 $notification->setDateEntered( new \DateTime() );
  364.                                 $notification->setStatus('new');
  365.                                 if(!empty($data['msg-data']['priority']))
  366.                                         $notification->setPriority($data['msg-data']['priority']);
  367.     
  368.                                 if(!empty($data['msg-data']['ns_msg_id']))
  369.                                     $notification->setNsMsgId($data['msg-data']['ns_msg_id']);
  370.             
  371.                                 $this->entityManager->persist($notification);
  372.                                 $i++;
  373.                         }
  374.                         if($i == 100){
  375.                             $this->entityManager->flush();
  376.                             $i 0;
  377.                         }
  378.                     }
  379.                 }
  380.                 
  381.                 $this->entityManager->flush();
  382.             }
  383.             $rez = ['rez' => true'send' => $send 'error' => ""];
  384.         }else{
  385.             $rez = ['rez' => false'error' => "Не задано поля: $valid"];
  386.         }
  387.         $response = new JsonResponse();
  388.         $response->setData($rez);
  389.         return $response;
  390.     }
  391.     #[Route('/api/create-data-reception'name'create_notfication_data_reception'methods: ['POST'])]
  392.     public function create_notfication_data_reception(Request $request)
  393.     {
  394.         if (!$this->customAuth($request)) {
  395.             return new JsonResponse(['message' => 'Unauthorized'], 401, [
  396.                 'WWW-Authenticate' => 'Basic realm="API Access"',
  397.             ]);
  398.         }
  399.         $data json_decode($request->getContent(), true);
  400.         // $logId = $this->logHistory(false, 'createPersonalAccount', $data);
  401.         // file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  "\n\n\n" .  print_r($data, true) . "\n", FILE_APPEND);
  402.         $valid $this->valid$data, ['method''data'] );
  403.         if( empty($valid) ){
  404.             
  405.             $DataReception = new DataReception();
  406.             $DataReception->setType$data['method']);
  407.             $DataReception->setData$data['data']);
  408.             $DataReception->setDateEntered( new \DateTime() );
  409.             $DataReception->setStatus('new');
  410.             $this->entityManager->persist($DataReception);
  411.             $this->entityManager->flush();
  412.             $rez = ['rez' => true'id' => $DataReception->getId()];
  413.                  
  414.         }else{
  415.             $rez = ['rez' => false'error' => "Не задано поля: $valid"];
  416.         }
  417.     
  418.         $response = new JsonResponse();
  419.         $response->setData($rez);
  420.         return $response;
  421.     }
  422.     public function updateStatus($inf){
  423.         $query $this->entityManager->createQuery(
  424.             'UPDATE App\Entity\Accounts d 
  425.              SET d.statusPlanning = :new_status 
  426.              WHERE d.eic IN (:ids)'
  427.         );
  428.         $query->setParameter('new_status''planned');
  429.         $query->setParameter('ids'$inf); // Масив ID
  430.         $query->execute();
  431.     }
  432.     #[Route('/cron-get-planned'name'cron_get_pllanned'methods: ['GET'])]
  433.     public function cron_get_pllanned(Request $request)
  434.     {
  435.         $query $this->entityManager->createQuery(
  436.             'UPDATE App\Entity\Accounts d SET d.statusPlanning = :new_status'
  437.         );
  438.         $query->setParameter('new_status''not_pllaned');
  439.         // $query->setParameter('old_status', 'new');
  440.         // echo '<pre>';
  441.         $query->execute();
  442.         $this->entityManager->clear();
  443.         $DataReception $this->entityManager->getRepository(DataReception::class)->findBy(['status' => 'new']);
  444.         $eic = [];
  445.         foreach($DataReception as $data){
  446.             $infos json_decode($data->getData(), true);
  447.             foreach($infos as $acc_id =>  $inf){
  448.                 array_push($eic$inf);
  449.                 if(count($eic) == 500){
  450.                     $this->updateStatus($eic);
  451.                     $eic = [];
  452.                 }
  453.             }
  454.             if(count($eic) > 0)
  455.                 $this->updateStatus($eic);
  456.             $this->entityManager->clear();
  457.             $data->setStatus('complate');
  458.             $this->entityManager->persist($data);
  459.             $this->entityManager->flush();
  460.             // print_r($infos);
  461.         }
  462.         echo count($DataReception); die;
  463.     }
  464.     #[Route('/api/get-account-all-data'name'get_account_all_data'methods: ['GET'])]
  465.     public function get_account_all_data(Request $request)
  466.     {   
  467.         // echo '<pre>';
  468.         $AppPersonalAccount $this->entityManager->getRepository(AppPersonalAccount::class)->findBy(['active' => true]);
  469.         foreach($AppPersonalAccount as $account){
  470.             // if(!empty( $account->getEic() ))
  471.             //     continue;
  472.             $data = [
  473.                 'account' => $account->getNumber()
  474.             ];
  475.             $res json_decode$this->appApiService->account_all_data($data) , true );    
  476.             if(isset($res['rez']) AND $res['rez'] == 1){
  477.                 file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',   print_r($restrue)  . "\n"FILE_APPEND);
  478.                 // $account->setEic($res['data'][0]['eic_kod']);  
  479.                 
  480.                 $this->entityManager->persist($account);
  481.                 $this->entityManager->flush();
  482.                 $accounts $this->entityManager->getRepository(Accounts::class)->findOneBy(['number' => $account->getNumber()]);
  483.                 if(!$accounts){
  484.                     $accounts = new Accounts();
  485.                     $accounts->setNumber($account->getNumber());
  486.                     $accounts->setEic($account->getEic());
  487.                     // $accounts->setEicParent($res_data['eic_kod_place']);
  488.                     $this->entityManager->persist($accounts);
  489.                     $this->entityManager->flush();
  490.                 }
  491.                 $account->setAccounts($accounts);
  492.                 $this->entityManager->persist($account);
  493.                 $this->entityManager->flush();
  494.             }
  495.             // print_r($res); die;
  496.         }
  497.         echo count$AppPersonalAccount ); die;
  498.         echo 1; die;
  499.         
  500.     }
  501.     /** Додавання id crm LOE */
  502.     #[Route('/api/update-service-id'name'update_service_id'methods: ['POST'])]
  503.     public function update_service_id(Request $request)
  504.     {
  505.         if (!$this->customAuth($request)) {
  506.             return new JsonResponse(['message' => 'Unauthorized'], 401, [
  507.                 'WWW-Authenticate' => 'Basic realm="API Access"',
  508.             ]);
  509.         }
  510.         $data json_decode($request->getContent(), true);
  511.         // $logId = $this->logHistory(false, 'createPersonalAccount', $data);
  512.         // file_put_contents('/var/www/symfony_docker/public/errorrrrrr.log',  "\n\n\n" .  print_r($data, true) . "\n", FILE_APPEND);
  513.         $valid $this->valid$data, ['id''id_crm'] );
  514.         if( empty($valid) ){
  515.             
  516.             $ServiceOrderHistory $this->entityManager->getRepository(ServiceOrderHistory::class)->findOneBy(['id' => $data['id']]);
  517.             if($ServiceOrderHistory){
  518.                 $ServiceOrderHistory->setIdCrm$data['id_crm']);
  519.                 if(!empty( $data['status'] ))
  520.                     $ServiceOrderHistory->setStatus(  $data['status'] );
  521.                 else
  522.                     $ServiceOrderHistory->setStatus'in_process' );
  523.                 if(!empty( $data['description'] ))
  524.                     $ServiceOrderHistory->setDescription(  $data['description'] );
  525.     
  526.                 $ServiceOrderHistory->setDateModified( new \DateTime() );
  527.                 // $ServiceOrderHistory->setStatus('new');
  528.     
  529.                 $this->entityManager->persist($ServiceOrderHistory);
  530.                 $this->entityManager->flush();
  531.             }
  532.             $rez = ['rez' => true'id' => $ServiceOrderHistory->getId()];
  533.                  
  534.         }else{
  535.             $rez = ['rez' => false'error' => "Не задано поля: $valid"];
  536.         }
  537.     
  538.         $response = new JsonResponse();
  539.         $response->setData($rez);
  540.         return $response;
  541.     }
  542.     /** Додавання id crm LOE */
  543.     #[Route('/api/get-service-id'name'get_service_id'methods: ['GET'])]
  544.     public function get_service_id(Request $request)
  545.     {
  546.         if (!$this->customAuth($request)) {
  547.             return new JsonResponse(['message' => 'Unauthorized'], 401, [
  548.                 'WWW-Authenticate' => 'Basic realm="API Access"',
  549.             ]);
  550.         }
  551.         $arr = [];
  552.         $ServiceOrderHistory $this->entityManager->getRepository(ServiceOrderHistory::class)->findBy(['status' => 'in_process']);
  553.         
  554.         foreach($ServiceOrderHistory as $service){
  555.             $arr[] = [
  556.                 'id' => $service->getId(),
  557.                 'id_crm' => $service->getIdCrm(),
  558.             ];
  559.         }
  560.         
  561.         
  562.         $rez = ['rez' => true'data' => $arr];
  563.     
  564.         $response = new JsonResponse();
  565.         $response->setData($rez);
  566.         return $response;
  567.     }
  568.     /** Історія заявок з сторонніх систем */
  569.     #[Route('/api/create-order-history'name'create_order_history'methods: ['POST'])]
  570.     public function create_order_history(Request $request)
  571.     {
  572.         if (!$this->customAuth($request)) {
  573.             return new JsonResponse(['message' => 'Unauthorized'], 401, [
  574.                 'WWW-Authenticate' => 'Basic realm="API Access"',
  575.             ]);
  576.         }
  577.         $data json_decode($request->getContent(), true);
  578.         $valid $this->valid$data, ['phone''account''service_code''status''id_crm' 'pdf'] );
  579.         if( empty($valid) ){
  580.             $find $this->entityManager->getRepository(User::class)->findOneBy(['phone' => $data['phone']]);
  581.             if($find){
  582.                 $arr = [];
  583.                 $orderNames = [
  584.                     =>  "Встановлення зонного лічильника",
  585.                     10 =>  "Лічильник не працює",
  586.                     21 =>  "Неправильний показ",
  587.                     32 =>  "Зміна власника",
  588.                     35 =>  "Підключення електроустановок замовника після виконання ТУ",
  589.                     63 =>  "Звернення щодо підозри на крадіжку",
  590.                     79 =>  "Заміна автоматичного вимикача, який опломбований ОСР",
  591.                     85 =>  "Відсутність пломб на засобі обліку",
  592.                     86 =>  "Закриття особового рахунку",
  593.                 ];
  594.                 foreach($find->getAppPersonalAccounts() as $acc){
  595.                     if($acc->getNumber() == $data['account'])
  596.                         $account $acc;
  597.                 }
  598.                 if($account){
  599.                     $ServiceOrderHistory = new ServiceOrderHistory();
  600.                     $ServiceOrderHistory->setName($orderNames[$data['service_code']]);
  601.                     // $ServiceOrderHistory->setRequest($data);
  602.                     $ServiceOrderHistory->setDateEntered( new \DateTime() );
  603.                     $ServiceOrderHistory->setType($data['service_code']);
  604.                     $ServiceOrderHistory->setStatus('new');
  605.                     $ServiceOrderHistory->setPersonalAccount($account);
  606.                     if(!empty( $data['id_crm'] ))
  607.                         $ServiceOrderHistory->setIdCrm$data['id_crm']);
  608.                     if(!empty( $data['status'] ))
  609.                         $ServiceOrderHistory->setStatus(  $data['status'] );
  610.                     else
  611.                         $ServiceOrderHistory->setStatus'in_process' );
  612.                     if(!empty( $data['description'] ))
  613.                         $ServiceOrderHistory->setDescription(  $data['description'] );
  614.         
  615.                     $ServiceOrderHistory->setPersonalAccount($account);
  616.                     $this->entityManager->persist($ServiceOrderHistory);
  617.                     $this->entityManager->flush();
  618.                     $data["id"] = $ServiceOrderHistory->getId();
  619.                     
  620.                     
  621.                     $rez = ['rez' => true'data' => $arr];
  622.                 }
  623.             }else{
  624.                 $rez = ['rezult' => false'error' => "Користувача не знайдено!"];   
  625.             }
  626.         
  627.         }else{
  628.             $rez = ['rez' => false'error' => "Не задано поля: $valid"];
  629.         }
  630.     
  631.         $response = new JsonResponse();
  632.         $response->setData($rez);
  633.         return $response;
  634.     }
  635. }