src/Controller/PistolettateController.php line 1010

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\AdUser;
  4. use App\Utils\Breadcrumbs;
  5. use DateTime;
  6. use Symfony\Component\HttpFoundation\File\UploadedFile;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Doctrine\Persistence\ManagerRegistry;
  9. use FilesystemIterator;
  10. use RecursiveIteratorIterator;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
  13. use Symfony\Component\Filesystem\Filesystem;
  14. use Symfony\Component\Filesystem\Path;
  15. use Symfony\Component\Finder\Iterator\RecursiveDirectoryIterator;
  16. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  17. use Symfony\Component\HttpFoundation\File\Stream;
  18. use Symfony\Component\HttpFoundation\JsonResponse;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use App\Entity\CooPfPistolettate;
  22. use App\Entity\CooPfColli;
  23. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  24. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  25. use Symfony\Component\HttpFoundation\Response;
  26. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  27. use PHPJasper\PHPJasper;
  28. use Nelmio\ApiDocBundle\Annotation\Model;
  29. use Symfony\Component\HttpFoundation\RequestStack;
  30. use OpenApi\Annotations as OA;
  31. use Symfony\Component\Security\Core\Authentication\Token\Storage\UsageTrackingTokenStorage;
  32. use ZipArchive;
  33. class PistolettateController extends AbstractController
  34. {
  35.     private $em;
  36.     private $requestStack;
  37.     private $jsonResponse;
  38.     public function __construct(EntityManagerInterface $entityManagerRequestStack $requestStack)
  39.     {
  40.         $this->requestStack $requestStack;
  41.         $this->em $entityManager;
  42.     }
  43.     /**
  44.      * Elenco postazioni.
  45.      *
  46.      * Ritorna la lista delle postazioni
  47.      *
  48.      * @IsGranted("ROLE_USER")
  49.      * @Route("/api/postazioni", methods="GET", options={"expose"=true})
  50.      * @OA\Parameter(name="connection", in="query", description="Connessione", @OA\Schema(type="integer"))
  51.      * @OA\Response(response=200, description="Ritorna l'elenco delle postazioni.")
  52.      *
  53.      */
  54.     public function postazioniList(Request $requestManagerRegistry $doctrine)
  55.     {
  56.         $elenco = [];
  57.         $db $this->getDatabase($request);
  58.         $stabilimento $this->getStabilimento($request);
  59.         $this->jsonResponse = new JsonResponse(['error' => 'NO_CONNECTION'], 400);
  60.         if ($db === false) {
  61.             return $this->jsonResponse;
  62.         }
  63.         $postazioni $doctrine->getRepository('App:CooPfPostazioni'$db)->findBy(['isactive' => 'Y''cooStabilimentoId' => $stabilimento], ['line' => 'asc']);
  64.         //$postazioni = $doctrine->getRepository('App:CooPfPostazioni', $db)->findBy(['isactive' => 'Y'], ['line' => 'asc']);
  65.         if ($postazioni) {
  66.             foreach ($postazioni as $postazione) {
  67.                 $data $postazione->serialize();
  68.                 $elenco[] = $data;
  69.             }
  70.         }
  71.         return new JsonResponse(['totale' => count($elenco), 'elenco' => $elenco]);
  72.     }
  73.     /**
  74.      * Elenco non conformità.
  75.      *
  76.      * Ritorna la lista delle non conformità
  77.      *
  78.      * @IsGranted("ROLE_USER")
  79.      * @Route("/api/non-conformita", methods="GET", options={"expose"=true})
  80.      * @OA\Parameter(name="connection", in="query", description="Connessione", @OA\Schema(type="integer"))
  81.      * @OA\Response(response=200, description="Ritorna l'elenco delle non conformità.")
  82.      *
  83.      */
  84.     public function ncList(Request $requestManagerRegistry $doctrine)
  85.     {
  86.         $elenco = [];
  87.         $db $this->getDatabase($request);
  88.         $stabilimento $this->getStabilimento($request);
  89.         $this->jsonResponse = new JsonResponse(['error' => 'NO_CONNECTION'], 400);
  90.         if ($db === false) {
  91.             return $this->jsonResponse;
  92.         }
  93.         $ncs $doctrine->getRepository('App:CooPfNctypetab'$db)->findBy(['isactive' => 'Y'], ['name' => 'asc']);
  94.         if ($ncs) {
  95.             foreach ($ncs as $nc) {
  96.                 $data = [
  97.                     'id' => $nc->getCooPfNctypetabId(),
  98.                     'name' => $nc->getName()
  99.                 ];
  100.                 $elenco[] = $data;
  101.             }
  102.         }
  103.         return new JsonResponse(['totale' => count($elenco), 'elenco' => $elenco]);
  104.     }
  105.     /**
  106.      * Elenco lavorazioni.
  107.      *
  108.      * Ritorna la lista delle lavorazioni
  109.      *
  110.      * @IsGranted("ROLE_USER")
  111.      * @Route("/api/lavorazioni/{postazione_id}", methods="GET", options={"expose"=true})
  112.      * @OA\Parameter(name="connection", in="query", description="Connessione", @OA\Schema(type="integer"))
  113.      * @OA\Response(response=200, description="Ritorna l'elenco delle lavorazioni.")
  114.      *
  115.      */
  116.     public function lavorazioniList(int $postazione_idRequest $requestManagerRegistry $doctrine)
  117.     {
  118.     set_time_limit(60);
  119.     ini_set'memory_limit''2048M' );
  120.     $db $this->getDatabase($request);
  121.         $this->jsonResponse = new JsonResponse(['error' => 'NO_CONNECTION'], 400);
  122.         if ($db === false) {
  123.             return $this->jsonResponse;
  124.         }
  125.         $postazione $doctrine->getRepository('App:CooPfPostazioni'$db)->find($postazione_id);
  126.         $pistolettate $doctrine->getRepository('App:CooPfPistolettate'$db)->pistolettateLineaStato($postazione);
  127.         $elenco = [];
  128.         $elenco_nomi = [];
  129.         $elenco_postazioni_attuali = [];
  130.         if (isset($pistolettate)) {
  131.             $vecchiaData null;
  132.             foreach ($pistolettate as $pistolettata) {
  133.                 //$pistolettata = $doctrine->getRepository('App:CooPfPistolettate', $db)->find($pistolettata_id['coo_pf_pistolettate_id']);
  134.                 $name $pistolettata->getName();
  135.                 if (!in_array($namearray_keys($elenco_postazioni_attuali))) {
  136.                     $elenco_postazioni_attuali[$name] = $pistolettata;
  137.                 }
  138.                 if (isset($elenco_postazioni_attuali[$name]) && $pistolettata->getPostazione() && $postazione && ($pistolettata->getPostazione()->getCooPfPostazioniId() == $postazione->getCooPfPostazioniId())) {
  139.                     $data $pistolettata->serialize();
  140.                     $et $pistolettata->getCooPfEventType();
  141.                     $p_att $pistolettata->getPostazione()->getCooPfPostazioniId();
  142.                     if (($elenco_postazioni_attuali[$name])->getPostazione()->getCooPfPostazioniId() == $p_att) {
  143.                         if (!in_array($namearray_keys($elenco_nomi)) && !isset($elenco[$et][$name])) {
  144.                             if (!isset($elenco[$et])) {
  145.                                 $elenco[$et] = [];
  146.                             }
  147.                             $elenco[$et][$name] = [];
  148.                             $elenco_nomi[$name] = $et;
  149.                             $minutes 0;
  150.                         } else {
  151.                             $attualeData $pistolettata->getDataLettura();
  152.                             $interval $attualeData->diff($vecchiaData);
  153.                             $minutes $interval->format('%i');
  154.                         }
  155.                         $vecchiaData $pistolettata->getDataLettura();
  156.                         $data['duration'] = $minutes;
  157.                         $elenco[$elenco_nomi[$name]][$name][] = $data;
  158.                     }
  159.                 }
  160.             }
  161.         }
  162.         return new JsonResponse(['elenco' => $elenco]);
  163.     }
  164.     /**
  165.      * Dettaglio lavorazione.
  166.      *
  167.      * Ritorna i dati della lavorazione
  168.      *
  169.      * @IsGranted("ROLE_USER")
  170.      * @Route("/api/lavorazione/{coo_pf_pistolettate_id}", methods="GET", options={"expose"=true})
  171.      * @OA\Parameter(name="connection", in="query", description="Connessione", @OA\Schema(type="integer"))
  172.      * @OA\Response(response=200, description="Ritorna la lavorazione.")
  173.      *
  174.      */
  175.     public function lavorazioneDetails(int $coo_pf_pistolettate_idRequest $requestManagerRegistry $doctrine)
  176.     {
  177.         $db $this->getDatabase($request);
  178.         $this->jsonResponse = new JsonResponse(['error' => 'NO_CONNECTION'], 400);
  179.         if ($db === false) {
  180.             return $this->jsonResponse;
  181.         }
  182.         $pistolettata $doctrine->getRepository('App:CooPfPistolettate'$db)->find($coo_pf_pistolettate_id);
  183.         return new JsonResponse($pistolettata->serialize(true));
  184.     }
  185.     /**
  186.      * Stop lavorazione.
  187.      *
  188.      * Ferma la lavorazione
  189.      *
  190.      * @IsGranted("ROLE_USER")
  191.      * @Route("/api/stop-lavorazione", methods="POST", options={"expose"=true})
  192.      * @OA\Parameter(name="connection", in="query", description="Connessione", @OA\Schema(type="integer"))
  193.      * @OA\RequestBody(@OA\JsonContent(type="object", example={"coo_pf_pistolettate_id":""}))
  194.      * @OA\Response(response=200, description="Ritorna la lavorazione.")
  195.      *
  196.      */
  197.     public function lavorazioneStop(Request $requestManagerRegistry $doctrine)
  198.     {
  199.         $data json_decode($request->getContent(), true);
  200.         $coo_pf_pistolettate_id = isset($data['coo_pf_pistolettate_id']) ? $data['coo_pf_pistolettate_id'] : null;
  201.         $db $this->getDatabase($request);
  202.         $this->jsonResponse = new JsonResponse(['error' => 'NO_CONNECTION'], 400);
  203.         if ($db === false) {
  204.             return $this->jsonResponse;
  205.         }
  206.         $pistolettataOld $doctrine->getRepository('App:CooPfPistolettate'$db)->find($coo_pf_pistolettate_id);
  207.         $utenteloggato $doctrine->getRepository('App:AdUser'$db)->find(100);
  208.         $pistolettata = new CooPfPistolettate();
  209.         $pistolettata->setDataLettura(new DateTime());
  210.         $pistolettata->setCooPfPistolettateId($this->nextId('coo_pf_pistolettate'$db$doctrine));
  211.         $pistolettata->setAdUser($utenteloggato);
  212.         $pistolettata->setCProject($pistolettataOld->getCProject());
  213.         $pistolettata->setCProjectline($pistolettataOld->getCProjectline());
  214.         $pistolettata->setCreated(new DateTime());
  215.         $pistolettata->setCreatedby($utenteloggato->getAdUserId());
  216.         $pistolettata->setPostazione($pistolettataOld->getPostazione());
  217.         $pistolettata->setUpdated(new DateTime());
  218.         $pistolettata->setUpdatedby($utenteloggato->getAdUserId());
  219.         $pistolettata->setStatus('stop');
  220.         $pistolettata->setCooPfEventType('stop');
  221.         $pistolettata->setName($pistolettataOld->getName());
  222.         try {
  223.             $doctrine->getManager($db)->persist($pistolettata);
  224.             $doctrine->getManager($db)->flush($pistolettata);
  225.             $return = new JsonResponse(['message' => "Lavorazione conclusa correttamente"'pdf' => '''next_id' => $pistolettata->getCooPfPistolettateId()], 200);
  226.         } catch (Exception $e) {
  227.             $return = new JsonResponse(['message' => "Errore durante lo stop della lavorazione. Riprova."], 400);
  228.         }
  229.         return $return;
  230.     }
  231.     /**
  232.      * Registra azione da barcode
  233.      *
  234.      * Una volta letto il barcode inviare ID della postazione di lavoro e il valore del barcode letto
  235.      *
  236.      * @IsGranted("ROLE_USER")
  237.      * @OA\Response(response=200, description="Inserimaento andato a buon fine")
  238.      * @OA\RequestBody(@OA\JsonContent(type="object", example={"postazione_id":"", "valore":"", "evento":"", "nc_id":"", "connection": "0"}))
  239.      * @Route("/api/pistolettata", methods="POST", options={"expose"=true})
  240.      */
  241.     public function registra_azione_post(Request $requestManagerRegistry $doctrine)
  242.     {
  243.         $db $this->getDatabase($request);
  244.         $this->jsonResponse = new JsonResponse(['error' => 'NO_CONNECTION'], 400);
  245.         if ($db === false) {
  246.             return $this->jsonResponse;
  247.         }
  248.         $data json_decode($request->getContent(), true);
  249.         $postazione_id = isset($data['postazione_id']) ? $data['postazione_id'] : null;
  250.         $valoreScan = isset($data['valore']) ? $data['valore'] : '';
  251.         $evento = isset($data['evento']) ? $data['evento'] : '';
  252.         $ncId = isset($data['nc_id']) ? $data['nc_id'] : '';
  253.         $valore trim($valoreScan);
  254.         if (!$valoreScan) {
  255.             return new JsonResponse(['message' => "Inserire il codice o usare il lettore di codice a barre"], 400);
  256.         }
  257.         if (strlen($valoreScan) != 12) {
  258.             return new JsonResponse(['message' => "Inserire il codice a barre (solo 12 cifre)"], 400);
  259.         }
  260.         $utenteloggato $doctrine->getRepository('App:AdUser'$db)->find(100);
  261.         $postazione $doctrine->getRepository('App:CooPfPostazioni'$db)->find($postazione_id);
  262.         $valConfronto $postazione->fullbarcode() ? $valore substr($valore06);
  263.         $cooPfDistaglio $doctrine->getRepository('App:CooPfDistaglio'$db)->distTaglio($valConfronto);
  264.         if (!$cooPfDistaglio && !count($cooPfDistaglio)) {
  265.             $cooPfDistaglio $doctrine->getRepository('App:CooPfScansionecomm'$db)->distTaglio($valConfronto);
  266.         }
  267.         $cProjectlineId $cooPfDistaglio $cooPfDistaglio->getCProjectlineId() : 0;
  268.         if ($cProjectlineId) {
  269.             $pistolettataAttuale $doctrine->getRepository('App:CooPfPistolettate'$db)->pistolettataAttuale($valConfronto$postazione_id);
  270.             $events = [];
  271.             if ($pistolettataAttuale && $postazione) {
  272.                 if ($pistolettataAttuale->getCooPfEventType() == 'start') {
  273.                     if ($evento == 'start') {
  274.                         $events = [/*0 => 'stop', 1 => */
  275.                             'start'];
  276.                     }
  277.                     if (in_array($evento, ['stop''nc''pause'])) {
  278.                         $events = [$evento];
  279.                     }
  280.                 } else if ($pistolettataAttuale->getCooPfEventType() == 'stop') {
  281.                     if (in_array($evento, ['start'])) {
  282.                         $events = ['start'];
  283.                     }
  284.                 } else if ($pistolettataAttuale->getCooPfEventType() == 'pause') {
  285.                     if (in_array($evento, ['start''stop'])) {
  286.                         $events = [$evento];
  287.                     }
  288.                 }
  289.             } else {
  290.                 if ($evento == 'start') {
  291.                     $events = [$evento];
  292.                 }
  293.             }
  294.             if (!$events) {
  295.                 return new JsonResponse(['message' => "Errore non è possibile proseguire. Riprova."], 400);
  296.             }
  297.             $projectLine $doctrine->getRepository('App:CProjectline'$db)->find($cProjectlineId);
  298.             foreach ($events as $event) {
  299.                 //Inizio una nuova lavorazione
  300.                 if ($event == 'start') {
  301.                     if ($projectLine && $projectLine->getCProjectlineId() > 0) {
  302.                         $pistolettata = new CooPfPistolettate();
  303.                         $pistolettata->setDataLettura(new DateTime());
  304.                         $pistolettata->setCooPfPistolettateId($this->nextId('coo_pf_pistolettate'$db$doctrine));
  305.                         $pistolettata->setAdUser($utenteloggato);
  306.                         $pistolettata->setCProject($projectLine->getCProject());
  307.                         $pistolettata->setCProjectline($projectLine);
  308.                         $pistolettata->setCreated(new DateTime());
  309.                         $pistolettata->setCreatedby($utenteloggato->getAdUserId());
  310.                         $pistolettata->setPostazione($postazione);
  311.                         $pistolettata->setUpdated(new DateTime());
  312.                         $pistolettata->setUpdatedby($utenteloggato->getAdUserId());
  313.                         $pistolettata->setStatus('start');
  314.                         $pistolettata->setCooPfEventType('start');
  315.                         $pistolettata->setName($valoreScan);
  316.                         try {
  317.                             $doctrine->getManager($db)->persist($pistolettata);
  318.                             $doctrine->getManager($db)->flush($pistolettata);
  319.                             $return = new JsonResponse(['message' => "Lavorazione iniziata correttamente"], 200);
  320.                         } catch (Exception $e) {
  321.                             $return = new JsonResponse(['message' => "Errore durante lo start della lavorazione. Riprova."], 400);
  322.                         }
  323.                     } else {
  324.                         $return = new JsonResponse(['message' => "Stai tentando di iniziare una lavorazione che non esiste. Riprova."], 400);
  325.                     }
  326.                 }
  327.                 if ($event == 'nc') {
  328.                     if ($projectLine && $projectLine->getCProjectlineId() > 0) {
  329.                         $pistolettata = new CooPfPistolettate();
  330.                         $pistolettata->setDataLettura(new DateTime());
  331.                         $pisId $this->nextId('coo_pf_pistolettate'$db$doctrine);
  332.                         $pistolettata->setCooPfPistolettateId($pisId);
  333.                         $pistolettata->setAdUser($utenteloggato);
  334.                         $pistolettata->setCProject($projectLine->getCProject());
  335.                         $pistolettata->setCProjectline($projectLine);
  336.                         $pistolettata->setCreated(new DateTime());
  337.                         $pistolettata->setCreatedby($utenteloggato->getAdUserId());
  338.                         $pistolettata->setPostazione($postazione);
  339.                         $pistolettata->setUpdated(new DateTime());
  340.                         $pistolettata->setUpdatedby($utenteloggato->getAdUserId());
  341.                         $pistolettata->setStatus('stop');
  342.                         $pistolettata->setCooPfEventType('nc');
  343.                         $pistolettata->setName($valoreScan);
  344.                         $pistolettata->setDescription($ncId);
  345.                         //$pistolettata->setAdRefListId($ncId);
  346.                         try {
  347.                             $doctrine->getManager($db)->persist($pistolettata);
  348.                             $doctrine->getManager($db)->flush($pistolettata);
  349.                             $return = new JsonResponse(['coo_pf_pistolettate_id' => $pisId'message' => "Lavorazione non conforme"], 200);
  350.                         } catch (Exception $e) {
  351.                             $return = new JsonResponse(['message' => "Errore durante il salvataggio della non conformità della lavorazione. Riprova."], 400);
  352.                         }
  353.                     } else {
  354.                         $return = new JsonResponse(['message' => "Stai tentando di salvare una lavorazione che non esiste. Riprova."], 400);
  355.                     }
  356.                 }
  357.                 if ($event == 'pause') {
  358.                     if ($projectLine && $projectLine->getCProjectlineId() > 0) {
  359.                         $pistolettata = new CooPfPistolettate();
  360.                         $pistolettata->setDataLettura(new DateTime());
  361.                         $pistolettata->setCooPfPistolettateId($this->nextId('coo_pf_pistolettate'$db$doctrine));
  362.                         $pistolettata->setAdUser($utenteloggato);
  363.                         $pistolettata->setCProject($projectLine->getCProject());
  364.                         $pistolettata->setCProjectline($projectLine);
  365.                         $pistolettata->setCreated(new DateTime());
  366.                         $pistolettata->setCreatedby($utenteloggato->getAdUserId());
  367.                         $pistolettata->setPostazione($postazione);
  368.                         $pistolettata->setUpdated(new DateTime());
  369.                         $pistolettata->setUpdatedby($utenteloggato->getAdUserId());
  370.                         $pistolettata->setStatus('stop');
  371.                         $pistolettata->setCooPfEventType('pause');
  372.                         $pistolettata->setName($valoreScan);
  373.                         try {
  374.                             $doctrine->getManager($db)->persist($pistolettata);
  375.                             $doctrine->getManager($db)->flush($pistolettata);
  376.                             $return = new JsonResponse(['message' => "Lavorazione in pausa"], 200);
  377.                         } catch (Exception $e) {
  378.                             $return = new JsonResponse(['message' => "Errore durante la messa in pausa della lavorazione. Riprova."], 400);
  379.                         }
  380.                     } else {
  381.                         $return = new JsonResponse(['message' => "Stai tentando di mettere in pausa una lavorazione che non esiste. Riprova."], 400);
  382.                     }
  383.                 }
  384.                 $labelPdf '';
  385.                 //Effettuo lo stop di una lavorazione
  386.                 if ($event == 'stop') {
  387.                     if ($projectLine && $projectLine->getCProjectlineId() > 0) {
  388.                         $pistolettata = new CooPfPistolettate();
  389.                         $pistolettata->setDataLettura(new DateTime());
  390.                         $pistolettata->setCooPfPistolettateId($this->nextId('coo_pf_pistolettate'$db$doctrine));
  391.                         $pistolettata->setAdUser($utenteloggato);
  392.                         $pistolettata->setCProject($projectLine->getCProject());
  393.                         $pistolettata->setCProjectline($projectLine);
  394.                         $pistolettata->setCreated(new DateTime());
  395.                         $pistolettata->setCreatedby($utenteloggato->getAdUserId());
  396.                         $pistolettata->setPostazione($pistolettataAttuale->getPostazione());
  397.                         $pistolettata->setUpdated(new DateTime());
  398.                         $pistolettata->setUpdatedby($utenteloggato->getAdUserId());
  399.                         $pistolettata->setStatus('stop');
  400.                         $pistolettata->setCooPfEventType('stop');
  401.                         $pistolettata->setName($valoreScan);
  402.                         if ($postazione->getLine() == 5) {
  403.                             $colli $doctrine->getRepository('App:CooPfColli'$db)->findBy(['cProjectline' => $pistolettata->getCProjectline()]);
  404.                             $numeroCollo count($colli) + 1;
  405.                             $collo = new CooPfColli();
  406.                             $collo->setCooPfColliId($this->nextId('coo_pf_colli'$db$doctrine));
  407.                             //$this->addFlash("cooPfColliId", $collo->getCooPfColliId());
  408.                             $collo->setCProject($pistolettata->getCProjectline()->getCProject());
  409.                             $collo->setCreated(new DateTime());
  410.                             $collo->setCreatedby($utenteloggato->getAdUserId());
  411.                             $collo->setDescription('');
  412.                             $collo->setName($numeroCollo);
  413.                             $collo->setCProjectline($pistolettata->getCProjectline());
  414.                             $collo->setUpdated(new DateTime());
  415.                             $collo->setUpdatedby($utenteloggato->getAdUserId());
  416.                             $doctrine->getManager($db)->persist($collo);
  417.                             try {
  418.                                 $doctrine->getManager($db)->flush($collo);
  419.                                 $REPORT_FOLDER $db == 'default' '' 'industrie/';
  420.                                 $input __DIR__ '/../../../../punto-finestre/public/reports/' $REPORT_FOLDER 'item_label_punto_persiane.jasper';
  421.                                 $output __DIR__ '/../../../../punto-finestre/public/reports/' $REPORT_FOLDER;
  422.                                 /* $input = __DIR__ . '/../../public/reports/' . $REPORT_FOLDER . 'item_label_punto_persiane' . ($DB == 'DATABASE_PUGLIA_URL' ? '2' : '') . '.jasper';
  423.                                   $output = __DIR__ . '/../../public/reports/' . $REPORT_FOLDER; */
  424.                                 $options = [
  425.                                     'format' => ['pdf'],
  426.                                     'params' => ['RECORD_ID' => $collo->getCooPfColliId()],
  427.                                     'db_connection' => [
  428.                                         'driver' => 'postgres',
  429.                                         'username' => 'adempiere',
  430.                                         'password' => 'adempiere',
  431.                                         'host' => '192.168.1.3',
  432.                                         'database' => ($db == 'default' 'adempiere' 'industrie'),
  433.                                         'port' => '5432'
  434.                                     ]
  435.                                 ];
  436.                                 $jasper = new PHPJasper;
  437.                                 $jasper->process(
  438.                                     $input,
  439.                                     $output,
  440.                                     $options
  441.                                 )->execute();
  442.                                 $labelPdf 'https://adw.puntopersiane.it/reports/' $REPORT_FOLDER 'item_label_punto_persiane.pdf';
  443.                             } catch (\Exception $e) {
  444.                                 $return = new JsonResponse(['message' => "Errore durante lo stop della lavorazione. Non posso stampare. Riprova."], 400);
  445.                             }
  446.                         }
  447.                         try {
  448.                             $doctrine->getManager($db)->persist($pistolettata);
  449.                             $doctrine->getManager($db)->flush($pistolettata);
  450.                             $return = new JsonResponse(['message' => "Lavorazione conclusa correttamente"'pdf' => $labelPdf'next_id' => $pistolettata->getCooPfPistolettateId()], 200);
  451.                         } catch (Exception $e) {
  452.                             $return = new JsonResponse(['message' => "Errore durante lo stop della lavorazione. Riprova."], 400);
  453.                         }
  454.                     }
  455.                 }
  456.             }
  457.             if ($return) {
  458.                 return $return;
  459.             }
  460.         } else {
  461.             return new JsonResponse(['message' => "Il codice a barre non è associato a nessuna lavorazione"], 400);
  462.         }
  463.         return new JsonResponse(['message' => "Errore generico"], 400);
  464.     }
  465.     /**
  466.      * @IsGranted("ROLE_USER")
  467.      * @Route("/postazione/taglio", name="pistolettate0")
  468.      * @Route("/postazione/assemblaggio", name="pistolettate1")
  469.      * @Route("/postazione/controllo-qualita", name="pistolettate2")
  470.      * @Route("/postazione/imballaggio", name="pistolettate3")
  471.      */
  472.     public function index(Request $request)
  473.     {
  474.         $line str_replace('pistolettate'''$request->attributes->get('_route'));
  475.         $postazione $this->em->getRepository('App:CooPfPostazioni')->findOneBy(['line' => $line]);
  476.         $pistolettata $this->em->getRepository('App:CooPfPistolettate')->findOneBy(['postazione' => $postazione], ['dataLettura' => 'DESC']);
  477.         $collo null;
  478.         /* if ($status == 'stop' && $pistolettata && $pistolettata->getCProjectLine()) {
  479.           $collo = $this->em->getRepository('App:CooPfColli')->findOneBy(['cProjectline' => $pistolettata->getCProjectLine()], ['cooPfColliId' => 'DESC']);
  480.           } */
  481.         return $this->render('pistolettate/index.html.twig', [
  482.             'ultimoCollo' => $collo ?: null,
  483.             'pistolettata' => $pistolettata,
  484.             'project' => ($pistolettata && $pistolettata->getCProject()) ? $pistolettata->getCProject() : null,
  485.             'projectLine' => ($pistolettata && $pistolettata->getCProjectLine()) ? $pistolettata->getCProjectLine() : null,
  486.             'postazione' => $postazione,
  487.             'controller_name' => 'PistolettateController',
  488.         ]);
  489.     }
  490.     /**
  491.      * @IsGranted("ROLE_USER")
  492.      * @Route("/postazione/registra_azione", name="registra_azione")
  493.      */
  494.     public function registra_azione(Request $request)
  495.     {
  496.         $line $request->request->get('line', -1);
  497.         $valoreScan $request->request->get('valore''') ?: '';
  498.         //$valore = str_pad($valore, 12, '0', STR_PAD_LEFT);
  499.         $valoreRomania $valoreScan;
  500.         $valore '0' substr($valoreScan0, -1);
  501.         $utenteloggato $this->getUser();
  502.         $postazione $this->em->getRepository('App:CooPfPostazioni')->findOneBy(['line' => $line]);
  503.         $pistolettataAttuale $this->em->getRepository('App:CooPfPistolettate')->findOneBy(['postazione' => $postazione], ['dataLettura' => 'DESC']);
  504.         if (trim($valore)) {
  505.             $cooPfDistaglio $this->em->getRepository('App:CooPfDistaglio')->createQueryBuilder('cpd')
  506.                 ->where('cpd.cooCompressedid LIKE :value')
  507.                 ->setParameter('value'$valore '.%')
  508.                 ->getQuery();
  509.             $cooPfDistaglio count($cooPfDistaglio->getResult()) ? $cooPfDistaglio->getSingleResult() : null;
  510.             if (!$cooPfDistaglio) {
  511.                 $cooPfDistaglio $this->em->getRepository('App:CooPfDistaglio')->createQueryBuilder('cpd')
  512.                     ->where('cpd.cooCompressedid LIKE :value')
  513.                     ->setParameter('value'$valoreRomania '.%')
  514.                     ->getQuery();
  515.                 $cooPfDistaglio count($cooPfDistaglio->getResult()) ? $cooPfDistaglio->getSingleResult() : null;
  516.             }
  517.             $terzoCaso false;
  518.             if (!$cooPfDistaglio) {
  519.                 $terzoCaso true;
  520.                 $terzoVal substr($valore25);
  521.                 $cooPfDistaglio $this->em->getRepository('App:CooPfScansionecomm')->createQueryBuilder('csc');
  522.                 $cooPfDistaglio
  523.                     ->where($cooPfDistaglio->expr()->eq($cooPfDistaglio->expr()->substring("csc.cooCompressedid"35), "'" $terzoVal "'"))
  524.                     ->addOrderBy('csc.cProjectlineId''DESC');
  525.                 $cooPfDistaglio $cooPfDistaglio->getQuery()->setMaxResults(1);
  526.                 $cooPfDistaglio count($cooPfDistaglio->execute()) ? $cooPfDistaglio->getSingleResult() : null;
  527.                 if (!$cooPfDistaglio) {
  528.                     $terzoVal substr($valoreRomania25);
  529.                     $cooPfDistaglio $this->em->getRepository('App:CooPfScansionecomm')->createQueryBuilder('csc');
  530.                     $cooPfDistaglio
  531.                         ->where($cooPfDistaglio->expr()->eq($cooPfDistaglio->expr()->substring("csc.cooCompressedid"35), "'" $terzoVal "'"))
  532.                         ->addOrderBy('csc.cProjectlineId''DESC');
  533.                     $cooPfDistaglio $cooPfDistaglio->getQuery()->setMaxResults(1);
  534.                     $cooPfDistaglio count($cooPfDistaglio->execute()) ? $cooPfDistaglio->getSingleResult() : null;
  535.                 }
  536.             }
  537.             $cProjectlineId $cooPfDistaglio $cooPfDistaglio->getCProjectlineId() : 0;
  538.             if ($cProjectlineId) {
  539.                 //Inizio una nuova lavorazione
  540.                 if (!$pistolettataAttuale || ($pistolettataAttuale && $pistolettataAttuale->getStatus() == 'stop')) {
  541.                     $projectLine $this->em->getRepository('App:CProjectline')->find($cProjectlineId);
  542.                     if ($projectLine && $projectLine->getCProjectlineId() > 0) {
  543.                         $pistolettata = new CooPfPistolettate();
  544.                         $pistolettata->setDataLettura(new DateTime());
  545.                         $pistolettata->setStatus('start');
  546.                         $pistolettata->setCooPfEventType('start');
  547.                         $pistolettata->setName($valoreScan);
  548.                         $pistolettata->setCooPfPistolettateId($this->nextIdOld('coo_pf_pistolettate'));
  549.                         $pistolettata->setAdUser($utenteloggato);
  550.                         $pistolettata->setCProject($projectLine->getCProject());
  551.                         $pistolettata->setCProjectline($projectLine);
  552.                         $pistolettata->setCreated(new DateTime());
  553.                         $pistolettata->setCreatedby($utenteloggato->getAdUserId());
  554.                         $pistolettata->setPostazione($postazione);
  555.                         $pistolettata->setUpdated(new DateTime());
  556.                         $pistolettata->setUpdatedby($utenteloggato->getAdUserId());
  557.                         try {
  558.                             $this->em->persist($pistolettata);
  559.                             $this->em->flush();
  560.                             $this->addFlash("success""Lavorazione iniziata correttamente");
  561.                         } catch (Exception $e) {
  562.                             $this->addFlash("error""Errore durante lo start della lavorazione. Riprova.");
  563.                         }
  564.                     } else {
  565.                         $this->addFlash("error""Stai tentando di iniziare una lavorazione che non esiste. Riprova.");
  566.                     }
  567.                 } //Effettuo lo stop di una lavorazione
  568.                 else if ($pistolettataAttuale && $pistolettataAttuale->getStatus() == 'start' && $pistolettataAttuale->getCProjectline()->getCProjectlineId() == $cProjectlineId) {
  569.                     $pistolettata = clone $pistolettataAttuale;
  570.                     $pistolettata->setStatus('stop');
  571.                     $pistolettata->setCooPfEventType('stop');
  572.                     $pistolettata->setName($valoreScan);
  573.                     $pistolettata->setDataLettura(new DateTime());
  574.                     $pistolettata->setCooPfPistolettateId($this->nextIdOld('coo_pf_pistolettate'));
  575.                     if ($postazione->getLine() == 5) {
  576.                         $colli $this->em->getRepository('App:CooPfColli')->findBy(['cProjectline' => $pistolettata->getCProjectline()]);
  577.                         $numeroCollo count($colli) + 1;
  578.                         $collo = new CooPfColli();
  579.                         $collo->setCooPfColliId($this->nextIdOld('coo_pf_colli'));
  580.                         $this->addFlash("cooPfColliId"$collo->getCooPfColliId());
  581.                         $collo->setCProject($pistolettata->getCProjectline()->getCProject());
  582.                         $collo->setCreated(new DateTime());
  583.                         $collo->setCreatedby($utenteloggato->getAdUserId());
  584.                         $collo->setDescription('');
  585.                         $collo->setName($numeroCollo);
  586.                         $collo->setCProjectline($pistolettata->getCProjectline());
  587.                         $collo->setUpdated(new DateTime());
  588.                         $collo->setUpdatedby($utenteloggato->getAdUserId());
  589.                         $this->em->persist($collo);
  590.                     }
  591.                     try {
  592.                         $this->em->persist($pistolettata);
  593.                         $this->em->flush();
  594.                         $this->addFlash("success""Lavorazione conclusa correttamente");
  595.                     } catch (Exception $e) {
  596.                         $this->addFlash("error""Errore durante lo stop della lavorazione. Riprova.");
  597.                     }
  598.                 } else {
  599.                     $this->addFlash("error""Stai tentando di interrompere una lavorazione che non è attualmente in questa postazione. Riprova.");
  600.                 }
  601.             } else {
  602.                 $this->addFlash("warning""Il codece a barre non è associato a nessuna lavorazione");
  603.             }
  604.         } else {
  605.             $this->addFlash("warning""Inserire il codice o usare il lettore di codice a barre");
  606.         }
  607.         return $this->redirectToRoute('pistolettate' $line);
  608.     }
  609.     private function nextIdOld($name)
  610.     {
  611.         $next $this->em->getRepository('App:AdSequence')->findOneBy(['name' => $name]);
  612.         if ($next) {
  613.             $prossimo $next->getCurrentnext();
  614.             $next->setCurrentnext($next->getCurrentnext() + 1);
  615.             try {
  616.                 $this->em->persist($next);
  617.                 $this->em->flush($next);
  618.             } catch (Exception $e) {
  619.                 $this->addFlash("error""Errore nel calcolo ID. Riprova.");
  620.                 return null;
  621.             }
  622.             return $prossimo;
  623.         }
  624.         return null;
  625.     }
  626.     private function nextId($name$db$doctrine)
  627.     {
  628.         $next $doctrine->getRepository('App:AdSequence'$db)->findOneBy(['name' => $name]);
  629.         if ($next) {
  630.             $prossimo $next->getCurrentnext();
  631.             $next->setCurrentnext($next->getCurrentnext() + 1);
  632.             try {
  633.                 $doctrine->getManager($db)->persist($next);
  634.                 $doctrine->getManager($db)->flush($next);
  635.             } catch (Exception $e) {
  636.                 return null;
  637.             }
  638.             return $prossimo;
  639.         }
  640.         return null;
  641.     }
  642.     /**
  643.      * @IsGranted("ROLE_USER")
  644.      * @Route("/postazione/print_label/{id}/{stabilimento}", name="print_label", methods="GET", options={"expose"=true})
  645.      * @param int $id
  646.      */
  647.     public function print_label($id$stabilimento 'DATABASE_URL')
  648.     {
  649.         $REPORT_FOLDER $stabilimento == 'DATABASE_URL' '' 'industrie/';
  650.         $input __DIR__ '/../../public/reports/' $REPORT_FOLDER 'item_label_punto_persiane.jasper';
  651.         $output __DIR__ '/../../public/reports/' $REPORT_FOLDER;
  652.         /* $input = __DIR__ . '/../../public/reports/' . $REPORT_FOLDER . 'item_label_punto_persiane' . ($DB == 'DATABASE_PUGLIA_URL' ? '2' : '') . '.jasper';
  653.           $output = __DIR__ . '/../../public/reports/' . $REPORT_FOLDER; */
  654.         $options = [
  655.             'format' => ['pdf'],
  656.             'params' => ['RECORD_ID' => $id],
  657.             'db_connection' => [
  658.                 'driver' => 'postgres',
  659.                 'username' => 'adempiere',
  660.                 'password' => 'adempiere',
  661.                 'host' => 'localhost',
  662.                 'database' => ($stabilimento == 'DATABASE_URL' 'adempiere' 'industrie'),
  663.                 'port' => '5432'
  664.             ]
  665.         ];
  666.         $jasper = new PHPJasper;
  667.         $jasper->process(
  668.             $input,
  669.             $output,
  670.             $options
  671.         )->execute();
  672.         $filename 'label-' $id '.pdf';
  673.         $response = new Response(file_get_contents($output 'item_label_punto_persiane.pdf'));
  674.         $response->setCharset('UTF-8');
  675.         $response->headers->set('Content-Type''application/pdf');
  676.         $response->headers->set('Content-Disposition'"attachement; filename=\"{$filename}\"");
  677.         return $response;
  678.     }
  679.     private function baseImagePath($stabilimento '')
  680.     {
  681.         return "/mnt/allegatiadempiere/nc-images" . ($_SERVER["APP_IMGURL"] == 'dev' '-test' '') . "/" . ($stabilimento $stabilimento "/" "");
  682.     }
  683.     private function basePFImagePath($stabilimento '')
  684.     {
  685.         return "/mnt/allegatiadempiere/fotoprodfin" . ($_SERVER["APP_IMGURL"] == 'dev' '-test' '') . "/" . ($stabilimento $stabilimento "/" "");
  686.     }
  687.     /**
  688.      * @IsGranted("ROLE_USER")
  689.      * @OA\Parameter(name="id", in="path", description="L'ID della pistolettata non conformità", @OA\Schema(type="integer"))
  690.      * @Route("/api/nc-photo/{id}", name="zip-nc", methods="POST", options={"expose"=true})
  691.      * @OA\RequestBody(description="0 Sede, 1 Romania, 2 Puglia", @OA\JsonContent(type="object", example={"connection":"0"}))
  692.      * @param int $id
  693.      */
  694.     public function ncPhoto(Request $requestint $id null): JsonResponse
  695.     {
  696.         // Il metodo getStabilimento leggerà 'connection' da $_POST o dall'URL
  697.         $stabilimento $this->getStabilimento($request);
  698.         $filesystem = new Filesystem();
  699.         $photoDir Path::normalize($this->baseImagePath($stabilimento) . $id "/");
  700.         if (!$filesystem->exists($photoDir)) {
  701.             try {
  702.                 $filesystem->mkdir($photoDir);
  703.             } catch (IOExceptionInterface $exception) {
  704.                 // Nei controller è meglio ritornare un errore JSON invece di un echo
  705.                 return new JsonResponse(['error' => 'Impossibile creare la directory'], 500);
  706.             }
  707.         }
  708.         // In multipart/form-data, i file non sono nel body/content,
  709.         // ma dentro al sacco $request->files
  710.         $files $request->files->get('files'); // Si aspetta un array di file
  711.         if (is_array($files)) {
  712.             /** @var UploadedFile $file */
  713.             foreach ($files as $file) {
  714.                 // Verifica che il file sia stato caricato correttamente dal browser/client
  715.                 if ($file instanceof UploadedFile && $file->isValid()) {
  716.                     // Recupera il nome originale del file (es. "foto.jpg")
  717.                     $filename $file->getClientOriginalName();
  718.                     try {
  719.                         // Sposta il file dalla cartella temporanea di PHP a quella finale
  720.                         $file->move($photoDir$filename);
  721.                     } catch (FileException $e) {
  722.                         // Gestisci l'errore se il file non può essere spostato (es. permessi)
  723.                         return new JsonResponse(['error' => 'Errore durante il salvataggio del file: ' $filename], 500);
  724.                     }
  725.                 }
  726.             }
  727.         }
  728.         return new JsonResponse(['id' => $id], 200);
  729.     }
  730.     /**
  731.      * @OA\Parameter(name="id", in="path", description="L'ID della pistolettata non conformità", @OA\Schema(type="integer"))
  732.      * @Route("/api/nc-photo/{id}", name="zip-nc-list", methods="GET", options={"expose"=true})
  733.      * @OA\RequestBody(description="0 Sede, 1 Romania, 2 Puglia", @OA\JsonContent(type="object", example={"connection":"0"}))
  734.      * @param int $id
  735.      */
  736.     public function ncPhotoList(Request $requestint $id null): JsonResponse
  737.     {
  738.         $filesystem = new Filesystem();
  739.         $stabilimento $this->getStabilimento($request);
  740.         $photoDir Path::normalize($this->baseImagePath($stabilimento) . $id "/");
  741.         $filesArray = [];
  742.         if ($filesystem->exists($photoDir)) {
  743.             $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($photoDirFilesystemIterator::CURRENT_AS_FILEINFO), RecursiveIteratorIterator::LEAVES_ONLY);
  744.             if ($files) {
  745.                 foreach ($files as $file) {
  746.                     if (!$file->isDir()) {
  747.                         $filePath $file->getRealPath();
  748.                         $relativePath substr($filePathstrlen($photoDir));
  749.                         $filesArray[] = [
  750.                             'filename' => $relativePath,
  751.                             'filepath' => $filePath,
  752.                             'url' => "https://" $_SERVER['SERVER_NAME'] . "/api/nc-photo-file/" $id "/" $stabilimento "/" $relativePath
  753.                         ];
  754.                     }
  755.                 }
  756.             }
  757.             return new JsonResponse(['files' => $filesArray], 200);
  758.         }
  759.         return new JsonResponse(null400);
  760.     }
  761.     /**
  762.      * @OA\Parameter(name="id", in="path", description="L'ID della pistolettata non conformità", @OA\Schema(type="integer"))
  763.      * @OA\Parameter(name="filename", in="path", description="Il nome del file", @OA\Schema(type="string"))
  764.      * @OA\RequestBody(description="0 Sede, 1 Romania, 2 Puglia", @OA\JsonContent(type="object", example={"connection":"0"}))
  765.      * @Route("/api/nc-photo-file/{id}/{stabilimento}/{filename}", name="zip-nc-file", methods="GET", options={"expose"=true})
  766.      * @param Request $request
  767.      * @param int|null $id
  768.      * @param string $filename
  769.      * @return JsonResponse
  770.      */
  771.     public function ncPhotoFile(Request $requestint $id nullstring $stabilimento ''string $filename ''): BinaryFileResponse
  772.     {
  773.         $filesystem = new Filesystem();
  774.         $photoDir Path::normalize($this->baseImagePath($stabilimento) . $id "/");
  775.         $filesArray = [];
  776.         if ($filesystem->exists($photoDir)) {
  777.             $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($photoDirFilesystemIterator::CURRENT_AS_FILEINFO), RecursiveIteratorIterator::LEAVES_ONLY);
  778.             if ($files) {
  779.                 foreach ($files as $file) {
  780.                     if (!$file->isDir()) {
  781.                         $filePath $file->getRealPath();
  782.                         $relativePath substr($filePathstrlen($photoDir));
  783.                         if ($relativePath == $filename) {
  784.                             $stream = new Stream($photoDir $filename);
  785.                             $response = new BinaryFileResponse($stream);
  786.                             $response->headers->set('Content-Type'$file->getType());
  787.                             return $response;
  788.                         }
  789.                     }
  790.                 }
  791.             }
  792.         }
  793.         return new BinaryFileResponse(null400);
  794.     }
  795.     /**
  796.      * @IsGranted("ROLE_USER")
  797.      * @OA\Parameter(name="id", in="path", description="L'ID della pistolettata non conformità", @OA\Schema(type="integer"))
  798.      * @Route("/api/zip-nc-photo/{id}", name="zip-nc-photo", methods="GET", options={"expose"=true})
  799.      * @param int $id
  800.      */
  801.     public function zipNcPhoto(Request $requestint $id null)
  802.     {
  803.         $filesystem = new Filesystem();
  804.         $stabilimento $this->getStabilimento($request);
  805.         $photoDir Path::normalize($this->baseImagePath($stabilimento) . $id "/");
  806.         if ($filesystem->exists($photoDir)) {
  807.             $data json_decode($request->getContent(), true);
  808.             $status 200;
  809.             //$zip = new \ZipArchive();
  810.             $nomeFile tempnam(sys_get_temp_dir(), 'photo');
  811.             exec('cd ' $photoDir ' ; zip -r ' $nomeFile ' .');
  812.             //$zip->open($nomeFile, \ZipArchive::CREATE);
  813.             /* $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($photoDir, FilesystemIterator::CURRENT_AS_FILEINFO), RecursiveIteratorIterator::LEAVES_ONLY);
  814.              foreach ($files as $file) {
  815.                  if (!$file->isDir()) {
  816.                      $filePath = $file->getRealPath();
  817.                      $relativePath = substr($filePath, strlen($photoDir) + 1);
  818.                      $zip->addFile($filePath, $relativePath);
  819.                  }
  820.              }*/
  821.             $stream = new Stream($nomeFile '.zip');
  822.             $response = new BinaryFileResponse($stream);
  823.             $response->headers->set('Content-Type''application/zip');
  824.             return $response;
  825.         } else {
  826.             return new Response(null400);
  827.         }
  828.     }
  829.     /**
  830.      * @IsGranted("ROLE_USER")
  831.      * @OA\Parameter(name="id", in="path", description="L'ID della pistolettata prodotto finito", @OA\Schema(type="integer"))
  832.      * @Route("/api/pf-photo/{id}", name="zip-pf", methods="POST", options={"expose"=true})
  833.      * @OA\RequestBody(description="0 Sede, 1 Romania, 2 Puglia", @OA\JsonContent(type="object", example={"connection":"0"}))
  834.      * @param int $id
  835.      */
  836.     public function pfPhoto(Request $requestint $id null): JsonResponse
  837.     {
  838.         // Il metodo getStabilimento leggerà 'connection' da $_POST o dall'URL
  839.         $stabilimento $this->getStabilimento($request);
  840.         $filesystem = new Filesystem();
  841.         $photoDir Path::normalize($this->basePFImagePath($stabilimento) . $id "/");
  842.         if (!$filesystem->exists($photoDir)) {
  843.             try {
  844.                 $filesystem->mkdir($photoDir);
  845.             } catch (IOExceptionInterface $exception) {
  846.                 // Nei controller è meglio ritornare un errore JSON invece di un echo
  847.                 return new JsonResponse(['error' => 'Impossibile creare la directory'], 500);
  848.             }
  849.         }
  850.         // In multipart/form-data, i file non sono nel body/content,
  851.         // ma dentro al sacco $request->files
  852.         $files $request->files->get('files'); // Si aspetta un array di file
  853.         if (is_array($files)) {
  854.             /** @var UploadedFile $file */
  855.             foreach ($files as $file) {
  856.                 // Verifica che il file sia stato caricato correttamente dal browser/client
  857.                 if ($file instanceof UploadedFile && $file->isValid()) {
  858.                     // Recupera il nome originale del file (es. "foto.jpg")
  859.                     $filename $file->getClientOriginalName();
  860.                     try {
  861.                         // Sposta il file dalla cartella temporanea di PHP a quella finale
  862.                         $file->move($photoDir$filename);
  863.                     } catch (FileException $e) {
  864.                         // Gestisci l'errore se il file non può essere spostato (es. permessi)
  865.                         return new JsonResponse(['error' => 'Errore durante il salvataggio del file: ' $filename], 500);
  866.                     }
  867.                 } else {
  868.                     return new JsonResponse(['error' => 'Errore durante il salvataggio del file: ' $file->getErrorMessage()], 500);
  869.                 }
  870.             }
  871.         }
  872.         return new JsonResponse(['id' => $id], 200);
  873.     }
  874.     /**
  875.      * @OA\Parameter(name="id", in="path", description="L'ID della pistolettata prodotto finito", @OA\Schema(type="integer"))
  876.      * @Route("/api/pf-photo/{id}", name="zip-pf-list", methods="GET", options={"expose"=true})
  877.      * @OA\RequestBody(description="0 Sede, 1 Romania, 2 Puglia", @OA\JsonContent(type="object", example={"connection":"0"}))
  878.      * @param int $id
  879.      */
  880.     public function pfPhotoList(Request $requestint $id null): JsonResponse
  881.     {
  882.         $filesystem = new Filesystem();
  883.         $stabilimento $this->getStabilimento($request);
  884.         $photoDir Path::normalize($this->basePFImagePath($stabilimento) . $id "/");
  885.         $filesArray = [];
  886.         if ($filesystem->exists($photoDir)) {
  887.             $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($photoDirFilesystemIterator::CURRENT_AS_FILEINFO), RecursiveIteratorIterator::LEAVES_ONLY);
  888.             if ($files) {
  889.                 foreach ($files as $file) {
  890.                     if (!$file->isDir()) {
  891.                         $filePath $file->getRealPath();
  892.                         $relativePath substr($filePathstrlen($photoDir));
  893.                         $filesArray[] = [
  894.                             'filename' => $relativePath,
  895.                             'filepath' => $filePath,
  896.                             'url' => "https://" $_SERVER['SERVER_NAME'] . "/api/pf-photo-file/" $id "/" $stabilimento "/" $relativePath
  897.                         ];
  898.                     }
  899.                 }
  900.             }
  901.             return new JsonResponse(['files' => $filesArray], 200);
  902.         }
  903.         return new JsonResponse(null400);
  904.     }
  905.     /**
  906.      * @OA\Parameter(name="id", in="path", description="L'ID della pistolettata prodotto finito", @OA\Schema(type="integer"))
  907.      * @OA\Parameter(name="filename", in="path", description="Il nome del file", @OA\Schema(type="string"))
  908.      * @OA\RequestBody(description="0 Sede, 1 Romania, 2 Puglia", @OA\JsonContent(type="object", example={"connection":"0"}))
  909.      * @Route("/api/pf-photo-file/{id}/{stabilimento}/{filename}", name="zip-pf-file", methods="GET", options={"expose"=true})
  910.      * @param Request $request
  911.      * @param int|null $id
  912.      * @param string $filename
  913.      * @return JsonResponse
  914.      */
  915.     public function pfPhotoFile(Request $requestint $id nullstring $stabilimento ''string $filename ''): BinaryFileResponse
  916.     {
  917.         $filesystem = new Filesystem();
  918.         $photoDir Path::normalize($this->basePFImagePath($stabilimento) . $id "/");
  919.         $filesArray = [];
  920.         if ($filesystem->exists($photoDir)) {
  921.             $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($photoDirFilesystemIterator::CURRENT_AS_FILEINFO), RecursiveIteratorIterator::LEAVES_ONLY);
  922.             if ($files) {
  923.                 foreach ($files as $file) {
  924.                     if (!$file->isDir()) {
  925.                         $filePath $file->getRealPath();
  926.                         $relativePath substr($filePathstrlen($photoDir));
  927.                         if ($relativePath == $filename) {
  928.                             $stream = new Stream($photoDir $filename);
  929.                             $response = new BinaryFileResponse($stream);
  930.                             $response->headers->set('Content-Type'$file->getType());
  931.                             return $response;
  932.                         }
  933.                     }
  934.                 }
  935.             }
  936.         }
  937.         return new BinaryFileResponse(null400);
  938.     }
  939.     /**
  940.      * @IsGranted("ROLE_USER")
  941.      * @OA\Parameter(name="id", in="path", description="L'ID della pistolettata prodotto finito", @OA\Schema(type="integer"))
  942.      * @Route("/api/zip-pf-photo/{id}", name="zip-pf-photo", methods="GET", options={"expose"=true})
  943.      * @param int $id
  944.      */
  945.     public function zipPfPhoto(Request $requestint $id null)
  946.     {
  947.         $filesystem = new Filesystem();
  948.         $stabilimento $this->getStabilimento($request);
  949.         $photoDir Path::normalize($this->basePFImagePath($stabilimento) . $id "/");
  950.         if ($filesystem->exists($photoDir)) {
  951.             $data json_decode($request->getContent(), true);
  952.             $status 200;
  953.             //$zip = new \ZipArchive();
  954.             $nomeFile tempnam(sys_get_temp_dir(), 'photoProdottoFinito');
  955.             exec('cd ' $photoDir ' ; zip -r ' $nomeFile ' .');
  956.             //$zip->open($nomeFile, \ZipArchive::CREATE);
  957.             /* $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($photoDir, FilesystemIterator::CURRENT_AS_FILEINFO), RecursiveIteratorIterator::LEAVES_ONLY);
  958.              foreach ($files as $file) {
  959.                  if (!$file->isDir()) {
  960.                      $filePath = $file->getRealPath();
  961.                      $relativePath = substr($filePath, strlen($photoDir) + 1);
  962.                      $zip->addFile($filePath, $relativePath);
  963.                  }
  964.              }*/
  965.             $stream = new Stream($nomeFile '.zip');
  966.             $response = new BinaryFileResponse($stream);
  967.             $response->headers->set('Content-Type''application/zip');
  968.             return $response;
  969.         } else {
  970.             return new Response(null400);
  971.         }
  972.     }
  973.     /**
  974.      *
  975.      * Cambio sede
  976.      *
  977.      * Cambia la sede
  978.      *
  979.      * @IsGranted("ROLE_USER")
  980.      * @OA\Response(response=200, description="Tutto ok")
  981.      * @OA\RequestBody(description="0 Sede, 1 Romania, 2 Puglia", @OA\JsonContent(type="object", example={"connection":"2"}))
  982.      * @Route("/api/change-location", name="change_location", methods={"PUT", "POST"}, options={"expose"=true})
  983.      */
  984.     public
  985.     function change_location(Request $request)
  986.     {
  987.         if ($request->isMethod('POST')) {
  988.             $connection $request->request->get('connection');
  989.         } else {
  990.             $data json_decode($request->getContent(), true);
  991.             $connection $data['connection'];
  992.         }
  993.         $session $this->requestStack->getSession();
  994.         return $session->set('DB'$connection);
  995.         return new JsonResponse(['connection' => $connection], 200);
  996.     }
  997.     public
  998.     function getDatabase($request)
  999.     {
  1000.         $data json_decode($request->getContent(), true);
  1001.         $connection = isset($data['connection']) ? $data['connection'] : -1;
  1002.         if ($connection 0) {
  1003.             $connection $request->request->get('connection', -1);
  1004.             if ($connection 0) {
  1005.                 $connection $request->query->get('connection', -1);
  1006.             }
  1007.         }
  1008.         if ($connection 0) {
  1009.             return false;
  1010.         }
  1011.         $db $connection == 'puglia' 'default';
  1012.         return $db;
  1013.     }
  1014.     public
  1015.     function getStabilimento($request)
  1016.     {
  1017.         $data json_decode($request->getContent(), true);
  1018.         $content = ($request->getContent());      // body raw
  1019.         $connection = isset($data['connection']) ? $data['connection'] : -1;
  1020.         if ($connection 0) {
  1021.             if ($request->isMethod('POST')) {
  1022.                 $connection $request->request->get('connection', -1);
  1023.             } else if ($request->isMethod('GET')) {
  1024.                 $connection $request->query->get('connection', -1);
  1025.             }
  1026.         }
  1027.         if ($connection 0) {
  1028.             return false;
  1029.         }
  1030.         $stabilimenti = [=> '1000000'=> '1000001'=> '2000001'];
  1031.         return $stabilimenti[$connection];
  1032.     }
  1033. }