src/Controller/ScriptController.php line 180

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Slave\Intervention;
  4. use App\Entity\Slave\OperationKeyMapping;
  5. use App\Entity\Slave\TicketSuspension;
  6. use App\Service\CompanyService;
  7. use App\Service\EncryptionService;
  8. use App\Service\TicketService;
  9. use App\Service\UtilitiesService;
  10. use Doctrine\Persistence\ManagerRegistry;
  11. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  12. use Symfony\Bundle\FrameworkBundle\Console\Application;
  13. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  14. use Symfony\Component\Console\Input\ArrayInput;
  15. use Symfony\Component\Console\Output\BufferedOutput;
  16. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\HttpKernel\KernelInterface;
  20. use Symfony\Component\Mailer\MailerInterface;
  21. use Symfony\Component\Routing\Annotation\Route;
  22. use Symfony\Component\Form\FormError;
  23. /**
  24.  * @Route("/script")
  25. */
  26. class ScriptController extends AbstractController
  27. {
  28.     protected $mr;
  29.     private $params;
  30.     public function __construct(ManagerRegistry $managerRegistryParameterBagInterface $params)
  31.     {
  32.         $this->mr $managerRegistry;
  33.         $this->params $params;
  34.     }
  35.     
  36.     /**
  37.      * @Route("/aggiorna_master_db", name="admin_update_master_db")
  38.      */
  39.     public function adminUpdateMasterDb(Request $requestKernelInterface $kernel)
  40.     {        
  41.         $application = new Application($kernel);
  42.         $application->setAutoExit(false);
  43.         $input = new ArrayInput(array(
  44.             'command' => 'doctrine:schema:update',
  45.             '--force' => true,
  46.             '--dump-sql' => true,
  47.             '--complete' => true,
  48.             '--em' => 'master'
  49.         ));
  50.         
  51.         $output = new BufferedOutput();
  52.         $application->run($input$output);
  53.         $content $output->fetch();
  54.         return new Response($content);
  55.     }
  56.     
  57.     /**
  58.      * @Route("/aggiorna_tutti_db", name="admin_update_all_db")
  59.      */
  60.     public function adminUpdateAllDb(Request $requestKernelInterface $kernel)
  61.     {    
  62.         $application = new Application($kernel);
  63.         $application->setAutoExit(false);
  64.         
  65.         $emMaster $this->mr->getManager('master');
  66.         $companies $emMaster->getRepository("App\Entity\Master\Company")->findAll();
  67.         $content "{ \"database aggiornati\" : [";
  68.         $first true;
  69.         foreach($companies as $company){
  70.             if($first$first false; else $content.=", ";
  71.             $this->mr->getConnection('slave')->changeDatabase($this->getParameter('slave_database_host'), $this->getParameter('slave_database_port'), $this->getParameter('slave_database_user'), $this->getParameter('slave_database_password'), $company->getDbName());
  72.             
  73.             $input = new ArrayInput(array(
  74.                 'command' => 'doctrine:schema:update',
  75.                 '--force' => true,
  76.                 '--dump-sql' => true,
  77.                 '--complete' => true,
  78.                 '--em' => 'slave'
  79.             ));
  80.             $output = new BufferedOutput();
  81.             $application->run($input$output);
  82.             
  83.             $content.= "{\"Nome database\" : ".json_encode($company->getDbName()).", \"output\" : ".json_encode($output->fetch())."}";
  84.         }
  85.         $content.="]}";
  86.         return new Response(json_encode($content));
  87.     }
  88.     // LICENZE
  89.         /**
  90.          * @Route("/licenze-funzionalita/controlla", name="script_licenses_features_check")
  91.          */
  92.         public function scriptLicensesFeaturesCheck(Request $request)
  93.         {
  94.             $em $this->mr->getManager();
  95.             $today = new \Datetime();
  96.             $licenses $em->getRepository('App\Entity\Master\License')->findAllActive();
  97.             $jtlfs $em->getRepository('App\Entity\Master\JoinTableLicenseFeature')->findAllActive();
  98.             foreach($licenses as $license){
  99.                 if($license->getExpirationDate()->format('Ymd') < $today->format('Ymd')){
  100.                     $license->setActive(false);
  101.                 }
  102.             }
  103.             foreach($jtlfs as $jtlf){
  104.                 if($jtlf->getExpirationDate()->format('Ymd') < $today->format('Ymd')){
  105.                     $jtlf->setActive(false);
  106.                 }
  107.             }
  108.             $em->flush();
  109.             return $this->redirectToRoute("homepage");
  110.         }
  111.     //
  112.     // TICKET
  113.         /**
  114.          * @Route("/ticket/scarica-da-email", name="script_ticket_download_email")
  115.          */
  116.         /*public function scriptTicketDownloadEmail(Request $request)
  117.         {
  118.             $emMaster = $this->mr->getManager('master');
  119.             $session = $request->getSession();
  120.             $companies = $emMaster->getRepository('App\Entity\Master\Company')->findAll();
  121.             $mailbox = "{in.postassl.it:993/imap/ssl}INBOX";
  122.             $first = true;
  123.             $json = "[";
  124.             foreach($companies as $company){
  125.                 $session->set('companyId', $company->getId());
  126.                 $em = CompanyService::getSlaveManagerByCompany($this->mr, $this->params, $company);
  127.                 foreach($company->getMailers() as $mailer){
  128.                     $count = 0;
  129.                     $countTicket = 0;
  130.                     $countTicketError = 0;
  131.                     $inbox = imap_open($mailbox, $mailer->getUser(), EncryptionService::decrypt($mailer->getPassword())) or die('Impossibile connettersi alla casella email: '.imap_last_error()); // Connessione alla casella email
  132.                     $emails = imap_search($inbox, 'UNSEEN'); // Cerca tutte le email da leggere
  133.                     $testing = $this->params->get('ticket_download_script_testing');
  134.                     $error = false;
  135.                     if($emails){
  136.                         rsort($emails); // Ordino con la più nuova in cima
  137.                         foreach($emails as $email){
  138.                             if($count < 600)
  139.                                 [$countTicket, $countTicketError] = TicketService::downloadTicket($em, $emMaster, $inbox, $email, $mailer, $testing, $company,$countTicket, $countTicketError);
  140.                             else
  141.                                 break;
  142.                             $count++;
  143.                         }
  144.                     }
  145.                     if(!$testing){
  146.                         imap_expunge($inbox); // Elimina le mail "marcate"
  147.                         imap_close($inbox); // Chiude la connessione
  148.                     }
  149.                     if($first) $first = false; else $json.=", ";
  150.                     
  151.                     $json.= '{"Account": "'.$mailer->getUser().'", "E-mail processate":"'.$count.'", "Ticket scaricati":"'.$countTicket.'", "Ticket con errori":"'.$countTicketError.'"}';
  152.                 }
  153.             }
  154.             $json.= "]";
  155.             return  new Response(json_encode(array("scriptTicketDownloadEmail" => $json)));
  156.         }*/
  157.         
  158.         /**
  159.          * @Route("/ticket/scarica-da-email-per-mailer/{mailerNickname}", name="script_ticket_download_email_by_mailer")
  160.          */
  161.         public function scriptTicketDownloadEmailByMailer(Request $requestMailerInterface $theburMailer$mailerNickname)
  162.         {
  163.             $emMaster $this->mr->getManager('master');
  164.             $mailer =  $emMaster->getRepository('App\Entity\Master\CompanyMailer')->findOneByNickname($mailerNickname);
  165.             $mailbox "{in.postassl.it:993/imap/ssl}INBOX";
  166.             $em CompanyService::getSlaveManagerByCompany($this->mr$this->params$mailer->getCompany());
  167.             $count 0;
  168.             $countTicket 0;
  169.             $countTicketError 0;
  170.             $inbox imap_open($mailbox$mailer->getUser(), EncryptionService::decrypt($mailer->getPassword())) or die('Impossibile connettersi alla casella email: '.imap_last_error()); // Connessione alla casella email
  171.             $emails imap_search($inbox'UNSEEN'); // Cerca tutte le email da leggere
  172.             $testing $this->params->get('ticket_download_script_testing');
  173.             $error false;
  174.             if($emails){
  175.                 rsort($emails); // Ordino con la più nuova in cima
  176.                 foreach($emails as $email){
  177.                     if($count 600){
  178.                         // INOLTRO A THEBURMANUTENZIONE@GMAIL.COM
  179.                         if($mailerNickname == "thebursrl"){
  180.                             $overview imap_fetch_overview($inbox$email0);
  181.                             $isRead = isset($overview[0]->seen) && $overview[0]->seen == 1;
  182.                             if(!$isRead){
  183.                                 $header imap_headerinfo($inbox$email); // Gestisco l'header                            
  184.                                 // Serve per skippare le email che non hanno mittente o di spam
  185.                                 if(property_exists($header'from') && property_exists($header->from[0], 'host'))
  186.                                     $sender $header->from[0]->mailbox."@".$header->from[0]->host;
  187.                                 if($sender == "thebur.manutenzioni@gmail.com"){
  188.                                     $body imap_fetchbody($inbox$email1.2);
  189.                                     $subject $header->subject;
  190.                                     $to 'thebur.integrations@gmail.com';
  191.                                     $headers "From: $sender\r\n";
  192.                                     $headers .= "Reply-To: $sender\r\n";
  193.                                     $headers .= "X-Mailer: PHP/" phpversion();
  194.                                     mail($to$subject$body$headers);
  195.                                     imap_setflag_full($inbox$email"\\SEEN");
  196.                                 }
  197.                             }
  198.                         }
  199.                         [$countTicket$countTicketError] = TicketService::downloadTicket($em$emMaster$inbox$email$mailer$testing$mailer->getCompany(), $countTicket$countTicketError);
  200.                     }
  201.                     else
  202.                         break;
  203.                     $count++;
  204.                 }
  205.             }
  206.             if(!$testing){
  207.                 imap_expunge($inbox); // Elimina le mail "marcate"
  208.                 imap_close($inbox); // Chiude la connessione
  209.             }
  210.             
  211.             $json'{"Account": "'.$mailer->getUser().'", "E-mail processate":"'.$count.'", "Ticket scaricati":"'.$countTicket.'", "Ticket con errori":"'.$countTicketError.'"}';
  212.             return  new Response(json_encode(array("scriptTicketDownloadEmailByMailer" => $json)));
  213.         }
  214.         /**
  215.          * @Route("/ticket/sblocca-sospensioni-approvate-e-concluse", name="script_ticket_unlock_approved_and_expired_suspensions")
  216.          */
  217.         public function scriptTicketUnlockApprovedAndExpiredSuspensions(Request $request)
  218.         {
  219.             $emMaster $this->mr->getManager('master');
  220.             $session $request->getSession();
  221.             $companies $emMaster->getRepository('App\Entity\Master\Company')->findAll();
  222.             $first true;
  223.             $json='[';
  224.             foreach($companies as $company){
  225.                 $session->set('companyId'$company->getId());
  226.                 $em CompanyService::getSlaveManagerByCompany($this->mr$this->params$company);
  227.                 $approvedAndLockedSuspensionsExpired $em->getRepository('App\Entity\Slave\TicketSuspension')->findAllApprovedLockedExpired();
  228.                 foreach($approvedAndLockedSuspensionsExpired as $sus){
  229.                     if($first$first false; else $json.= ', ';
  230.                     $json.='{"ticket":"'.$sus->getTicket()->getNumber().'", "Motivo":"Sospensione terminata"}';
  231.                     $unlockCausal "Sbloccato automaticamente per fine sospensione";
  232.                     $sus->unlock($unlockCausal$sus->getDatetimeTo(), $em);
  233.                 }
  234.                 $em->flush();
  235.             }
  236.             $json.=']';
  237.             return  new Response(json_encode(array("script_ticket_unlock_approved_and_expired_suspensions" => $json)));
  238.         }
  239.         /**
  240.          * @Route("/ticket/notifica-prendi-in-carico/{companyCode}", name="script_ticket_notify_take_charge")
  241.          */
  242.         public function scriptTicketNotifyTakeCharge(Request $requestMailerInterface $mailer$companyCode)
  243.         {
  244.             $emMaster $this->mr->getManager('master');
  245.             $company $emMaster->getRepository('App\Entity\Master\Company')->findOneByCode($companyCode);
  246.             $now = new \Datetime();
  247.             $first true;
  248.             $json='{';
  249.             $em CompanyService::getSlaveManagerByCompany($this->mr$this->params$company);
  250.             $technicians $em->getRepository("App\Entity\Slave\User")->findTechniciansActive();
  251.             $settingMinutesTakeCharge $em->getRepository('App\Entity\Slave\Setting')->findOneBy(array('slug' => 'ticket_technician_minutes_take_charge'));
  252.             $settingSunday $em->getRepository('App\Entity\Slave\Setting')->findOneBy(array('slug' => 'script_sunday_active'));
  253.             $json.= '"Frequenza":"'.$settingMinutesTakeCharge->getValue().'","Invia la domenica":"'.$settingSunday->getValue().'","Da prendere in carico":[';
  254.             if($settingMinutesTakeCharge->getValue() != 'never' && ($now->format('i') % $settingMinutesTakeCharge->getValue() == 0) && ($settingSunday->getValue() == || ($settingSunday->getValue() == && $now->format('N') != 7))){
  255.                 $users = array();
  256.                 foreach($technicians as $t){
  257.                     $onHoliday false;
  258.                     foreach($t->getHolidays() as $h){
  259.                         if($now->format('Ymd') >= $h->getDateFrom()->format('Ymd') && $now->format('Ymd') <= $h->getDateTo()->format('Ymd')){
  260.                             $onHoliday true;
  261.                             break;
  262.                         }
  263.                     }
  264.                     if(!$onHoliday){
  265.                         $tickets $em->getRepository('App\Entity\Slave\Ticket')->findByUserAndStatus($t->getId(), 'assigned');
  266.                         if(sizeof($tickets) > 0)
  267.                             array_push($users, array($t$tickets));
  268.                     }
  269.                 }
  270.                 
  271.                 foreach($users as $u){
  272.                     if($first$first false; else $json.= ', ';
  273.                     $json.='{"Tecnico":"'.$u[0].'", "E-mail":"'.$u[0]->getEmail().'", "Ticket da prendere in carico":"'.sizeof($u[1]).'"}';
  274.                     $message = (new TemplatedEmail())
  275.                         ->subject($this->params->get('subject_ticket_take_charge'))
  276.                         ->from($this->params->get('email_noreply'))
  277.                         ->to($u[0]->getEmail())
  278.                         ->htmlTemplate('email/technician_tickets.html.twig')
  279.                         ->context(['user' => $u[0], 'tickets' => $u[1]]);
  280.                     $mailer->send($message);
  281.                 }
  282.             }
  283.             $json.=']}';
  284.             return  new Response(json_encode(array("script_ticket_notify_take_charge" => $json)));
  285.         }
  286.         /**
  287.          * @Route("/chiavi-mappatura/aggiungi", name="script_mapping_key_add")
  288.          */        
  289.         public function scriptMappingKeyAdd(Request $request)
  290.         {    
  291.             //return false;
  292.             $emMaster $this->mr->getManager('master');
  293.             $session $request->getSession();
  294.             $companies $emMaster->getRepository('App\Entity\Master\Company')->findAll();
  295.             $now = new \Datetime();
  296.             $first true;
  297.             $json='[';
  298.             foreach($companies as $company){
  299.                 $em CompanyService::getSlaveManagerByCompany($this->mr$this->params$company);
  300.                 $addCount 0;
  301.                 $skipCount 0;
  302.                 $session->set('companyId'$company->getId());
  303.                 $operations $em->getRepository("App\Entity\Slave\Operation")->findAll();
  304.                 foreach($operations as $operation){
  305.                     // SE NON E UAV -> INSERISCO I KEY MAPPING
  306.                     if(!$operation->isUav()){
  307.                         $arrayKeyMappings = array(
  308.                             //0 => array('Cluster', '122', '0', '0', '0')
  309.                         );
  310.                         foreach($arrayKeyMappings as $km){
  311.                             $operationKeyMapping $em->getRepository("App\Entity\Slave\OperationKeyMapping")->findOneByOperationAndColumn($operation->getId(), $km[0]);
  312.                             if($operationKeyMapping == null){
  313.                                 $addCount++;
  314.                                 $operationKeyMapping = new OperationKeyMapping();
  315.                                 $operationKeyMapping->setOperation($operation);
  316.                                 $operationKeyMapping->setTicketColumn($km[0]);
  317.                                 $operationKeyMapping->setPriority($km[1]);
  318.                                 $operationKeyMapping->setKeyRequired($km[2]);
  319.                                 $operationKeyMapping->setTicketNumber($km[3]);
  320.                                 $operationKeyMapping->setTermid($km[4]);
  321.                                 $em->persist($operationKeyMapping);
  322.                             }
  323.                             else
  324.                                 $skipCount++;
  325.                         }
  326.                     }
  327.                     else
  328.                         $skipCount++;
  329.                 }
  330.                 $em->flush();
  331.                 
  332.                 if($first$first false; else $json.=', ';
  333.                 $json.='{"Azienda":"'.$company->getName().'", "Chiavi inserite":"'.$addCount.'", "Chiavi già presenti":"'.$skipCount.'"}';
  334.             }
  335.             $json.=']';
  336.             return  new Response(json_encode(array("script_mapping_key_add" => $json)));
  337.         }
  338.     //
  339. }