src/Controller/PartController.php line 115

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\CompanyClient;
  4. use App\Entity\Library;
  5. use App\Entity\Order;
  6. use App\Entity\Part;
  7. use App\Entity\Supplier;
  8. use App\Entity\CompanySupplier;
  9. use App\Entity\Equipment;
  10. use App\Entity\Material;
  11. use App\Form\OrderType;
  12. use App\Form\PartSearchType;
  13. use App\Form\PartImportType;
  14. use App\Form\PartType;
  15. use App\Repository\CompanyClientRepository;
  16. use App\Repository\PartRepository;
  17. use App\Repository\CompanySupplierRepository;
  18. use App\Service\EncryptDecryptService;
  19. use App\Service\Part\EditPartService;
  20. use App\Service\UtilService;
  21. use App\Service\PartService;
  22. use App\Service\LibraryService;
  23. use App\Security\Voter\PartVoter;
  24. use App\Entity\LicenseCompany;
  25. use PHPSTL\Handler\DimensionsHandler;
  26. use PHPSTL\Handler\SurfaceHandler;
  27. use PHPSTL\Handler\VolumeHandler;
  28. use PHPSTL\Model\STLModel;
  29. use PHPSTL\Reader\STLReader;
  30. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  31. use Symfony\Component\Form\FormInterface;
  32. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  33. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  34. use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
  35. use Symfony\Component\Filesystem\Filesystem;
  36. use Symfony\Component\HttpFoundation\Request;
  37. use Symfony\Component\HttpFoundation\Response;
  38. use Symfony\Component\HttpFoundation\JsonResponse;
  39. use Symfony\Component\Routing\Annotation\Route;
  40. use Symfony\Component\Validator\Constraints\Url as ConstraintsUrl;
  41. use Symfony\Component\HttpFoundation\StreamedResponse;
  42. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  43. use Symfony\Component\String\Slugger\AsciiSlugger;
  44. use Symfony\Contracts\Translation\TranslatorInterface;
  45. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  46. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  47. use PhpOffice\PhpSpreadsheet\IOFactory;
  48. use Knp\Component\Pager\PaginatorInterface;
  49. use Knp\Snappy\Pdf;
  50. use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
  51. use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
  52. use Doctrine\Persistence\ManagerRegistry;
  53. /**
  54.  * @Route({"en": "/part",
  55.  *          "es": "/pieza"})
  56.  */
  57. class PartController extends AbstractController
  58. {
  59.     private const PAGE_ELEMENTS 25;
  60.     private $translator;
  61.     private $util;
  62.     private $pdf;
  63.     private $partService;
  64.     private $libService;
  65.     private $csRepository;
  66.     private $em;
  67.     private $partDir;
  68.     /**
  69.      * @var EditPartService
  70.      */
  71.     private $editPartService;
  72.     /**
  73.      * PartController constructor.
  74.      * @param EditPartService $editPartService
  75.      */
  76.     public function __construct(
  77.         EditPartService $editPartService,
  78.         TranslatorInterface $translator,
  79.         UtilService $utilService,
  80.         PartService $partService,
  81.         LibraryService $libService,
  82.         CompanySupplierRepository $csRepository,
  83.         Pdf $knpSnappyPdf,
  84.         ManagerRegistry $doctrine,
  85.         string $partDir,
  86.         private EncryptDecryptService $encryptDecryptService
  87.     )
  88.     {
  89.         $this->editPartService $editPartService;
  90.         $this->translator $translator;
  91.         $this->util $utilService;
  92.         $this->partService $partService;
  93.         $this->libService $libService;
  94.         $this->csRepository $csRepository;
  95.         $this->pdf $knpSnappyPdf;
  96.         $this->em $doctrine->getManager();
  97.         $this->partDir $partDir;
  98.     }
  99.     /**
  100.      * @Route({"en": "/list",
  101.      *         "es": "/listado"}, name="part_index", methods={"GET","POST"})
  102.      */
  103.     public function index(Request $requestPartRepository $partRepositoryPaginatorInterface $paginator): Response
  104.     {
  105.         $admin $this->getUser();
  106.         $ms $this->util->getLicenseField($admin->getCompany(),'multi_select') && $admin->getRole()!='ROLE_CLIENT';
  107.         $part = [];
  108.         $form $this->createForm(PartSearchType::class, $part, ['user_admin' => $admin,'method' => 'GET']);
  109.         $form->handleRequest($request);
  110.         $orderBy null;
  111.         $filters = [
  112.             ['field'=>'company','title'=>'Empresa'],
  113.             ['field'=>'ref','title'=>'Referencia'],
  114.             ['field'=>'name','title'=>'Nombre'],
  115.             ['field'=>'description','title'=>'Descripción'],
  116.             ['field'=>'technology','title'=>'Tecnología'],
  117.             ['field'=>'material','title'=>'Material'],
  118.             ['field'=>'updated_at','title'=>'Última modificación'],
  119.         ];
  120.         if ($form->isSubmitted() && $form->isValid()) {
  121.             $orderBy $request->query->get('order_by');
  122.             $parts $partRepository->findByName($form->getData(), $admin$orderBy);
  123.         } else {
  124.             $parts $partRepository->buscarTodos($admin);
  125.         }
  126.         if($request->isMethod('POST')){
  127.             if($request->request->get('libraries_update')){
  128.                 $libraryIds $request->request->get('libraryIds',null);
  129.                 $partIds $request->request->get('partIds',null);
  130.                 $rmCurrentLibs $request->request->get('currentLibs',null) ? true false;
  131.                 if($partIds && $libraryIds){
  132.                     $parts explode(','$partIds);
  133.                     foreach($parts as $partId){
  134.                         $part $this->em->getRepository(Part::class)->find($partId);
  135.                         $this->partService->updateLibs($part,$libraryIds,$rmCurrentLibs);
  136.                     }
  137.                     $this->addFlash('success'$this->translator->trans('Bibliotecas editadas correctamente'));
  138.                     return $this->redirectToRoute('part_index');
  139.                 }
  140.             }
  141.             if($request->request->get('parts_delete')){
  142.                 $delIds $request->request->get('delIds',null);
  143.                 if($delIds){
  144.                     $parts explode(','$delIds);
  145.                     $successMsg '';
  146.                     $errorMsg '';
  147.                     foreach($parts as $partId){
  148.                         $part $this->em->getRepository(Part::class)->find($partId);
  149.                         if($part){
  150.                             if($part->getLocked()){
  151.                                 $errorMsg.= $this->translator->trans('Error pieza {ref} : ',['{ref}'=>$part->getRef()]) . $this->translator->trans('Pieza bloqueada') .'<br>';
  152.                             }
  153.                             else{
  154.                                 $rmPart $this->partService->rmPart($part);
  155.                                 if($rmPart['error']){
  156.                                     $errorMsg.= $this->translator->trans('Error pieza {ref} : ',['{ref}'=>$part->getRef()]) . $rmPart['msg'].'<br>';
  157.                                 }
  158.                                 else{
  159.                                     $successMsg.= $this->translator->trans('Pieza {ref} eliminada correctamente',['{ref}'=>$part->getRef()]).'<br>';
  160.                                 }
  161.                             }
  162.                         }
  163.                     }
  164.                     if($successMsg){
  165.                         $this->addFlash('success'$successMsg);
  166.                     }
  167.                     if($errorMsg){
  168.                         $this->addFlash('danger'$errorMsg);
  169.                     }
  170.                     return $this->redirectToRoute('part_index');
  171.                 }
  172.             }
  173.             if($request->request->get('parts_download')){
  174.                 $downIds $request->request->get('downIds',null);
  175.                 $downIds explode(','$downIds);
  176.                 $zip =$this->multiplePartZip($partRepository,$downIds);
  177.                 $response = new BinaryFileResponse($zip[0].'/'.$zip[1]);
  178.                 $response->setStatusCode(200);
  179.                 $response->headers->set('Content-Type''application/zip');
  180.                 $response->headers->set('Content-Disposition''attachment; filename="'.basename($zip[1]).'"');
  181.                 $response->headers->set('Content-Length'filesize($zip[0].'/'.$zip[1]));
  182.                 return $response;
  183.             }
  184.             if($request->request->get('parts_order')){
  185.                 $partIds $request->request->get('partIds',null);
  186.                 if($partIds){
  187.                     $partIds explode(',',$partIds);
  188.                     $partIdsChecked = [];
  189.                     foreach($partIds as $partId){
  190.                         $part $this->em->getRepository(Part::class)->find($partId);
  191.                         if($part && $part->getSupplier() && $part->getCompany()==$admin->getCompany()){
  192.                             $partIdsChecked[] = $partId;
  193.                         }
  194.                     }
  195.                     if($partIdsChecked){
  196.                         return $this->redirectToRoute('order_bulk_new',['partIds'=>base64_encode(implode(',',$partIdsChecked))]);
  197.                     }
  198.                     else{
  199.                         $this->addFlash('danger''Error inesperado');
  200.                         return $this->redirectToRoute('part_index');
  201.                     }
  202.                 }
  203.                 else{
  204.                     $this->addFlash('danger''Error inesperado');
  205.                     return $this->redirectToRoute('part_index');
  206.                 }
  207.             }
  208.         }
  209.         // Creating pagnination
  210.         $pagination $paginator->paginate(
  211.             $parts,
  212.             $request->query->getInt('page'1),
  213.             self::PAGE_ELEMENTS
  214.         );
  215.         return $this->render('part/index.html.twig', [
  216.             'pagination' => $pagination,
  217.             'search_form' => $form->createView(),
  218.             'filters' => $filters,
  219.             'order_by' => $orderBy,
  220.             'ms' => $ms,
  221.             'company' => $admin->getCompany(),
  222.             'user' => $admin,
  223.             'license' => $this->util->getActiveLicense($admin->getCompany()),
  224.             'navbarTitle' => $this->translator->trans("Piezas")
  225.         ]);
  226.     }
  227.     /**
  228.      * @Route({"en": "/new",
  229.      *         "es": "/nueva"}, name="part_new", methods={"GET","POST"})
  230.      */
  231.     public function new(Request $requestPartRepository $partRepositoryCompanyClientRepository $ccRepository): Response
  232.     {
  233.         $admin $this->getUser();
  234.         $part = new Part();
  235.         $part->setCompany($admin->getCompany());
  236.         $this->denyAccessUnlessGranted(PartVoter::CREATE$part);
  237.         $em $this->em;
  238.         $fileMaxsizes $this->util->getCompanyFileMaxsizes($part->getCompany());
  239.         $cc $ccRepository->findClient([],$admin)->getArrayResult();
  240.         $form $this->createForm(PartType::class, $part, ['user_admin' => $admin'file_maxsizes' => $fileMaxsizes'cc'=>$cc]);
  241.         $form->handleRequest($request);
  242.         $errors = [];
  243.         $errorsSubmitted = [];
  244.         if ($form->isSubmitted() && $form->isValid()) {
  245.             $data $request->request->all();
  246.             /*
  247.             "fileCadFile" => null
  248.             "fileStlFile" => Symfony\Component\HttpFoundation\File\UploadedFile {#16 ▶}
  249.             "fileFabFile" => null
  250.             "fileVerifFile" => null
  251.             "file2dFile" => null
  252.             "fileOthers" => []
  253.              */
  254.             /*
  255.             "encryptSTL" => "1"
  256.             "encryptCAD" => "1"
  257.             "encryptFAB" => "1"
  258.             "encryptVER" => "1"
  259.             "encrypt2D" => "1"
  260.             "encryptOthers" => "1"
  261.             */
  262.             /*$encryptSTL = $request->request->get('encryptSTL', false);
  263.             $encryptCAD = $request->request->get('encryptCAD', false);
  264.             $encryptFAB = $request->request->get('encryptFAB', false);
  265.             $encryptVER = $request->request->get('encryptVER', false);
  266.             $encrypt2D = $request->request->get('encrypt2D', false);
  267.             $encryptOthers = $request->request->get('encryptOthers', false);*/
  268.             $optionsEncrypt = [
  269.                 'encryptSTL' => (isset($request->request->get('part')['encryptSTL'])) ? $request->request->get('part')['encryptSTL'] : null,
  270.                 'encryptCAD' => (isset($request->request->get('part')['encryptCAD'])) ? $request->request->get('part')['encryptCAD'] : null,
  271.                 'encryptFAB' => (isset($request->request->get('part')['encryptFAB'],)) ? $request->request->get('part')['encryptFAB'] : null,
  272.                 'encryptVER' => (isset($request->request->get('part')['encryptVER'],)) ? $request->request->get('part')['encryptVER'] : null,
  273.                 'encrypt2D' => (isset($request->request->get('part')['encrypt2D'],)) ? $request->request->get('part')['encrypt2D'] : null,
  274.                 'encryptOthers' => (isset($request->request->get('part')['encryptOthers'])) ? $request->request->get('part')['encryptOthers'] : null,
  275.             ];
  276.             $libraryIds $request->request->get('libraryIds',null);
  277.             $company $form->get('company')->getData();
  278.             if(is_string($company)){
  279.                 $company $admin->getCompany();
  280.             }
  281.             $supplier $form->get('supplier')->getData();
  282.             //límites licencia
  283.             if(!($admin->getRole()=='ROLE_ADMIN')){
  284.                 $licenseLimit $this->util->getLicenseField($admin->getCompany(),'part_num');
  285.                 $currentNum count($em->getRepository(Part::class)->findBy(['company'=>$admin->getCompany()]));
  286.                 if(!$licenseLimit || ($currentNum>=$licenseLimit)){
  287.                     $this->addFlash('danger'$this->translator->trans('Ha alcanzado el límite de {name} para su licencia.',['{name}'=>$this->translator->trans('piezas')]));
  288.                     return $this->redirectToRoute('part_index');
  289.                 }
  290.             }
  291.             $fileStl $form->get('fileStlFile')->getData();
  292.             if($fileStl){
  293.                 $fileName explode('.'$fileStl->getClientOriginalName());
  294.                 if($fileName){
  295.                     $fileExt $fileName[count($fileName)-1];
  296.                     if(strtoupper($fileExt)!='STL'){
  297.                         $this->addFlash('error'$this->translator->trans('El archivo Stl adjunto no tiene la extensión correcta'));
  298.                         return $this->redirectToRoute('part_index');
  299.                     }
  300.                 }
  301.             }
  302.             $name$form->get('name')->getData();
  303.             $nameExists $partRepository->nameExists($name,$company->getId());
  304.             if($nameExists){
  305.                 $errorMsg $this->translator->trans('El nombre de la pieza ya existe');
  306.                 $errors['tab_datosbasicos']['name'][]=$errorMsg;
  307.                 $errorsSubmitted['name'][]=$errorMsg;
  308.                 $this->addFlash('error'$errorMsg);
  309.             }
  310.             else{
  311.                 $this->processOtherFiles($form$part5, !empty($optionsEncrypt['encryptOthers']));
  312.                 $this->processFiles($form,$part,false$optionsEncrypt);
  313.                 $lastRef $partRepository->findLastRef($company);
  314.                 $part->setSupplier($supplier);
  315.                 $part->setRef($lastRef);
  316.                 $part->setVersion(1);
  317.                 $part->setAutor($admin->getName());
  318.                 //START Equipos y materiales
  319.                 $eid $form->get('equipment_id')->getData();
  320.                 $mid $form->get('material_id')->getData();
  321.                 $equipo $form->get('equipo')->getData();
  322.                 $material $form->get('material')->getData();
  323.                 if($eid>&& $eid==$equipo){
  324.                     $entity $em->getRepository(Equipment::class)->find($eid);
  325.                     if($entity){
  326.                         $equipo $entity->getName();
  327.                         $part->setEquipmentId($entity);
  328.                     }
  329.                 }
  330.                 else{
  331.                     $eid null;
  332.                     $part->setEquipmentId(null);
  333.                 }
  334.                 if($mid>&& $mid==$material){
  335.                     $entity $em->getRepository(Material::class)->find($mid);
  336.                     if($entity){
  337.                         $material $entity->getName();
  338.                         $part->setMaterialId($entity);
  339.                     }
  340.                 }
  341.                 else{
  342.                     $mid null;
  343.                     $part->setMaterialId(null);
  344.                 }
  345.                 $part->setEquipo($equipo);
  346.                 $part->setMaterial($material);
  347.                 //END Equipos y materiales
  348.                 //Check supplier collab
  349.                 if($company && $supplier && !$this->csRepository->collabExist($company,$supplier)){
  350.                     $cs = new CompanySupplier();
  351.                     $cs->setCompany($company);
  352.                     $cs->setSupplier($supplier);
  353.                     $cs->setConfigStepBudget(true);
  354.                     $cs->setConfigStepChiefConfirm(true);
  355.                     $cs->setConfigStepInDelivery(true);
  356.                     $cs->setType(2);
  357.                     $cs->setCollab(true);
  358.                     $cs->setMarketplace(true);
  359.                     $em->persist($cs);
  360.                 }
  361.                 $em->persist($part);
  362.                 $em->flush();
  363.                 $this->partService->updateLibs($part,$libraryIds);
  364.                 if($part->getFileStl()) {
  365.                     $reader STLReader::forFile('parts/'.$part->getFileStl());
  366.                     $reader->setHandler(new VolumeHandler());
  367.                     $volume $reader->readModel();
  368.                     $reader->setHandler(new SurfaceHandler());
  369.                     $surface $reader->readModel();
  370.                     $reader->setHandler(new DimensionsHandler());
  371.                     $dimension $reader->readModel();
  372.                     $stlData = array(
  373.                         'volumen' => $volume,
  374.                         'surface' => $surface,
  375.                         'dimension' => $dimension
  376.                     );
  377.                     $part->setData(json_encode($stlData));
  378.                     $em->persist($part);
  379.                     $em->flush();
  380.                 }
  381.                 $this->addFlash('success'$this->translator->trans('Pieza creada correctamente'));
  382.                 $data['message']='Nueva pieza creada';
  383.                 $data['name']=$part->getName();
  384.                 $data['reference']=$part->getRef();
  385.                 $data['path_name']='part_show';
  386.                 $data['path_parameters']='id:'.$part->getId();
  387.                 $this->util->notifications($part->getCompany(), 2$data$this->getUser());
  388.                 return $this->redirectToRoute('part_index');
  389.             }
  390.         }
  391.         elseif ($form->isSubmitted()){
  392.             $errors $this->partService->processTabErrors($form);
  393.             $this->addFlash('error'$this->translator->trans('Ha habido un error al procesar el formulario, revise los campos'));
  394.         }
  395.         return $this->render('part/new.html.twig', [
  396.             'user' => $admin,
  397.             'part' => $part,
  398.             'fileMaxsizes' => $fileMaxsizes,
  399.             'form' => $form->createView(),
  400.             'errors' => json_encode($errors),
  401.             'errorsSubmitted' => json_encode($errorsSubmitted),
  402.             'license' => $this->util->getActiveLicense($admin->getCompany()),
  403.             'navbarTitle' => $this->translator->trans("Crear nueva pieza")
  404.         ]);
  405.     }
  406.     /**
  407.      * @Route({"en": "/show/{id}",
  408.      *         "es": "/mostrar/{id}"}, name="part_show", methods={"GET", "POST"})
  409.      */
  410.     public function show(Request $requestPart $partPartRepository $partRepository): Response
  411.     {
  412.         $this->denyAccessUnlessGranted(PartVoter::VIEW$part);
  413.         $em $this->em;
  414.         $user $this->getUser();
  415.         //Libraries
  416.         $libraries = [];
  417.         foreach($part->getLibraries() as $library){
  418.             $libraries[] = $this->libService->getFullPath($library);
  419.         }
  420.         if($request->query->get('download')){
  421.             $pdfData $this->htmlForPdf($part,$user);
  422.             return new PdfResponse(
  423.                 $this->pdf->getOutputFromHtml($pdfData['html'], $pdfData['options']),
  424.                 $part->getRef().'.pdf'
  425.             );
  426.         }
  427.         if ($request->isMethod('POST')) {
  428.             if($request->request->get('part_copy_submit')){
  429.                 //Versionar
  430.                 $newPart = clone $part;
  431.                 $newPart->setId(null);
  432.                 $company $part->getCompany();
  433.                 $ref $part->getRef();
  434.                 $splits explode("-"$ref);
  435.                 $refPartNumber $splits[1];
  436.                 $version $partRepository->setAmount($refPartNumber$part->getCompany(), $user);
  437.                 $splits[2] = $version;
  438.                 $newPart->setVersion(ltrim($version"0"));
  439.                 $newRef implode("-"$splits);
  440.                 $newPart->setEditRef($newRef);
  441.                 $newPart->setAutor($user->getName());
  442.                 $newPart->setLocked(null);
  443.                 $newPart->markAsCreatedAt();
  444.                 $em->persist($newPart);
  445.                 $em->flush();
  446.                 $this->addFlash('success'$this->translator->trans('Versión de pieza creada correctamente'));
  447.                 return $this->redirectToRoute('part_index');
  448.             }
  449.             if($request->request->get('libraries_update')){
  450.                 $libraryIds $request->request->get('libraryIds',null);
  451.                 $this->partService->updateLibs($part,$libraryIds);
  452.                 $this->addFlash('success'$this->translator->trans('Bibliotecas editadas correctamente'));
  453.                 return $this->redirectToRoute('part_show',['id'=>$part->getId()]);
  454.             }
  455.         }
  456.         return $this->render('part/show.html.twig', [
  457.             'part' => $part,
  458.             'libraries' => $libraries,
  459.             'user' => $user,
  460.             'edit' => $this->isGranted(PartVoter::EDIT$part),
  461.             'navbarTitle' => $this->translator->trans("Pieza").' - '.$part->getName() . ($part->getVersion()>' V'.$part->getVersion() : '')
  462.         ]);
  463.     }
  464.     /**
  465.      * @Route({"en": "/edit/{id}",
  466.      *         "es": "/editar/{id}"}, name="part_edit", methods={"GET","POST"})
  467.      */
  468.     public function edit(Request $requestPart $partPartRepository $partRepositorystring $partDirCompanyClientRepository $ccRepository): Response
  469.     {
  470.         $admin $this->getUser();
  471.         $this->denyAccessUnlessGranted(PartVoter::EDIT$part);
  472.         $em $this->em;
  473.         $fileMaxsizes $this->util->getCompanyFileMaxsizes($part->getCompany());
  474.         $cc $ccRepository->findClient([],$admin)->getArrayResult();
  475.         $form $this->createForm(PartType::class, $part, ['user_admin' => $admin'file_maxsizes' => $fileMaxsizes'cc'=>$cc]);
  476.         $form->handleRequest($request);
  477.         $errors = [];
  478.         $errorsSubmitted = [];
  479.         if ($form->isSubmitted() && $form->isValid()) {
  480.             $actionType $request->request->get('submit');
  481.             $libraryIds $request->request->get('libraryIds',null);
  482.             $company $part->getCompany();
  483.             $supplier $form->get('supplier')->getData();
  484.             $cc $form->get('client_name')->getData();
  485.             $fileStl $form->get('fileStlFile')->getData();
  486.             if($fileStl){
  487.                 $fileName explode('.'$fileStl->getClientOriginalName());
  488.                 if($fileName){
  489.                     $fileExt $fileName[count($fileName)-1];
  490.                     if(strtoupper($fileExt)!='STL'){
  491.                         $this->addFlash('error'$this->translator->trans('El archivo Stl adjunto no tiene la extensión correcta'));
  492.                         return $this->redirectToRoute('part_index');
  493.                     }
  494.                 }
  495.             }
  496.             $optionsEncrypt = [
  497.                 'encryptSTL' => (isset($request->request->get('part')['encryptSTL'])) ? $request->request->get('part')['encryptSTL'] : null,
  498.                 'encryptCAD' => (isset($request->request->get('part')['encryptCAD'])) ? $request->request->get('part')['encryptCAD'] : null,
  499.                 'encryptFAB' => (isset($request->request->get('part')['encryptFAB'],)) ? $request->request->get('part')['encryptFAB'] : null,
  500.                 'encryptVER' => (isset($request->request->get('part')['encryptVER'],)) ? $request->request->get('part')['encryptVER'] : null,
  501.                 'encrypt2D' => (isset($request->request->get('part')['encrypt2D'],)) ? $request->request->get('part')['encrypt2D'] : null,
  502.                 'encryptOthers' => (isset($request->request->get('part')['encryptOthers'])) ? $request->request->get('part')['encryptOthers'] : null,
  503.             ];
  504.             $this->processOtherFiles($form$part5, !empty($optionsEncrypt['encryptOthers']));
  505.             $this->processFiles($form,$part,$actionType==1$optionsEncrypt);
  506.             //START Equipos y materiales
  507.             $eid $form->get('equipment_id')->getData();
  508.             $mid $form->get('material_id')->getData();
  509.             $equipo $form->get('equipo')->getData();
  510.             $material $form->get('material')->getData();
  511.             if($eid>&& $eid==$equipo){
  512.                 $entity $em->getRepository(Equipment::class)->find($eid);
  513.                 if($entity){
  514.                     $equipo $entity->getName();
  515.                     $part->setEquipmentId($entity);
  516.                 }
  517.             }
  518.             else{
  519.                 $eid null;
  520.                 $part->setEquipmentId(null);
  521.             }
  522.             if($mid>&& $mid==$material){
  523.                 $entity $em->getRepository(Material::class)->find($mid);
  524.                 if($entity){
  525.                     $material $entity->getName();
  526.                     $part->setMaterialId($entity);
  527.                 }
  528.             }
  529.             else{
  530.                 $mid null;
  531.                 $part->setMaterialId(null);
  532.             }
  533.             $part->setEquipo($equipo);
  534.             $part->setMaterial($material);
  535.             //END Equipos y materiales
  536.             //Check supplier collab
  537.             if($company && $supplier && !$this->csRepository->collabExist($company,$supplier)){
  538.                 $cs = new CompanySupplier();
  539.                 $cs->setCompany($company);
  540.                 $cs->setSupplier($supplier);
  541.                 $cs->setConfigStepBudget(true);
  542.                 $cs->setConfigStepChiefConfirm(true);
  543.                 $cs->setConfigStepInDelivery(true);
  544.                 $cs->setType(2);
  545.                 $cs->setCollab(true);
  546.                 $cs->setMarketplace(true);
  547.                 $em->persist($cs);
  548.             }
  549.             //Process client
  550.             if(!empty($cc['choiceType']) || !empty($cc['choiceInput'])){
  551.                 if(!empty($cc['choiceType'])){
  552.                     $cc $em->getRepository(CompanyClient::class)->find($cc['choiceType']);
  553.                     if($cc){
  554.                         $part->setCompanyClient($cc);
  555.                     }
  556.                 }
  557.                 else{
  558.                     $part->setClientName($cc['choiceInput']);
  559.                 }
  560.             }
  561.             if($actionType==1){
  562.                 //Guardar
  563.                 $part->setSupplier($supplier);
  564.                 $part->markAsUpdated();
  565.                 $em->persist($part);
  566.                 $em->flush();
  567.                 $this->partService->updateLibs($part,$libraryIds);
  568.                 $this->addFlash('success'$this->translator->trans('Pieza editada correctamente'));
  569.                 $data['message']='Pieza editada';
  570.                 $data['name']=$part->getName();
  571.                 $data['reference']=$part->getRef();
  572.                 $data['path_name']='part_show';
  573.                 $data['path_parameters']='id:'.$part->getId();
  574.                 $this->util->notifications($part->getCompany(), 2$data$this->getUser(),$part->getId());
  575.             }
  576.             else{
  577.                 //Versionar
  578.                 $newPart = clone $part;
  579.                 $em->refresh($part);
  580.                 $newPart->setSupplier($supplier);
  581.                 $newPart->setId(null);
  582.                 $ref $part->getRef();
  583.                 $splits explode("-"$ref);
  584.                 $refPartNumber $splits[1];
  585.                 $version $partRepository->setAmount($refPartNumber$part->getCompany(), $admin);
  586.                 $splits[2] = $version;
  587.                 $newPart->setVersion(ltrim($version"0"));
  588.                 $newRef implode("-"$splits);
  589.                 $newPart->setEditRef($newRef);
  590.                 $newPart->setAutor($admin->getName());
  591.                 $newPart->setLocked(null);
  592.                 $newPart->markAsCreatedAt();
  593.                 $newPart->markAsUpdated();
  594.                 $em->persist($newPart);
  595.                 $em->flush();
  596.                 $this->partService->updateLibs($newPart$libraryIds);
  597.                 $this->addFlash('success'$this->translator->trans('Versión de pieza creada correctamente'));
  598.                 $data['message']='Pieza versionada';
  599.                 $data['name']=$part->getName();
  600.                 $data['reference']=$part->getRef();
  601.                 $data['path_name']='part_show';
  602.                 $data['path_parameters']='id:'.$part->getId();
  603.                 $this->util->notifications($part->getCompany(), 2$data$this->getUser());
  604.             }
  605.             //START Process remove
  606.             $partToRemove $actionType==&& $newPart $newPart $part;
  607.             if(!empty($request->request->get('filesToDelete'))){
  608.                 $fields explode(',',$request->request->get('filesToDelete'));
  609.                 foreach($fields as $field){
  610.                     if($field){
  611.                         $this->processRm($partToRemove$field);
  612.                     }
  613.                 }
  614.             }
  615.             if(!empty($request->request->get('filesOthersToDelete')) || $request->request->get('filesOthersToDelete')==='0'){
  616.                 $indexes explode(',',$request->request->get('filesOthersToDelete'));
  617.                 $this->processRm($partToRemove'others'$indexes);
  618.             }
  619.             //END Process remove
  620.             return $this->redirectToRoute('part_index');
  621.         }
  622.         elseif ($form->isSubmitted()){
  623.             $errors $this->partService->processTabErrors($form);
  624.             $this->addFlash('error'$this->translator->trans('Ha habido un error al procesar el formulario, revise los campos'));
  625.         }
  626.         return $this->render('part/edit.html.twig', [
  627.             'user' => $admin,
  628.             'part' => $part,
  629.             'fileMaxsizes' => $fileMaxsizes,
  630.             'form' => $form->createView(),
  631.             'errors' => json_encode($errors),
  632.             'errorsSubmitted' => json_encode($errorsSubmitted),
  633.             'license' => $this->util->getActiveLicense($admin->getCompany()),
  634.             'navbarTitle' => $this->translator->trans("Editar pieza").' - '.$part->getName() . ($part->getVersion()>' V'.$part->getVersion() : '')
  635.         ]);
  636.     }
  637.     private function processRm(Part $part$field$indexes=[]){
  638.         $result = ['error'=>false'msg'=>''];
  639.         $em $this->em;
  640.         $fs = new Filesystem();
  641.         $ds DIRECTORY_SEPARATOR;
  642.         $fields = [
  643.             'cad'=>'FileCad',
  644.             'stl'=>'FileStl',
  645.             'fab'=>'FileFab',
  646.             'verif'=>'FileVerif',
  647.             '2d'=>'File2d',
  648.             'others'=>'FileOthers'];
  649.         if(!empty($fields[$field])){
  650.             $getter 'get'.$fields[$field];
  651.             $setter 'set'.$fields[$field];
  652.             $fileToRemove $part->$getter();
  653.             $filesToRemove = [];
  654.             $setterData null;
  655.             if($field == 'others'){
  656.                 if(count($indexes)>0){
  657.                     $filenames =  explode(',',$fileToRemove);
  658.                     foreach($indexes as $index){
  659.                         if($index != '' && !empty($filenames[$index])){
  660.                             $filesToRemove[] = $filenames[$index];
  661.                             unset($filenames[$index]);
  662.                         }
  663.                     }
  664.                     $setterData count($filenames)>implode(',',$filenames) : null;
  665.                 }
  666.             }
  667.             else{
  668.                 $filesToRemove[]=$fileToRemove;
  669.             }
  670.             foreach($filesToRemove as $fileToRemove){
  671.                 if($fileToRemove){
  672.                     $part->$setter($setterData);
  673.                     $em->flush();
  674.                     //Verificamos si el archivo se usa en otra pieza versionada
  675.                     $fileInVersions $this->partService->fileInVersions($part,$field,$fileToRemove);
  676.                     if(!$fileInVersions && $fs->exists($this->partDir.$ds.$fileToRemove)){
  677.                         try {
  678.                             $fs->remove($this->partDir.$ds.$fileToRemove);
  679.                         } catch (IOExceptionInterface $exception) {
  680.                             $result = ['error'=>true,'msg'=>$this->translator->trans('No se ha podido eliminar el archivo')];
  681.                         }
  682.                     }
  683.                 }
  684.             }
  685.         }
  686.         return $result;
  687.     }
  688.     private function processOtherFiles(FormInterface $formPart $part$limit=5$encrypt false){
  689.         $files $form->get('fileOthers')->getData();
  690.         if(count($files)>0){
  691.             $slugger = new AsciiSlugger();
  692.             $filenames = !empty($part->getFileOthers()) ? explode(',',$part->getFileOthers()) : [];
  693.             try {
  694.                 foreach($files as $file)
  695.                 {
  696.                     $originalFilename pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
  697.                     $safeFilename $slugger->slug($originalFilename);
  698.                     $newFilename $safeFilename.'-'.uniqid().'.'.$file->getClientOriginalExtension();
  699.                     if(!in_array($newFilename,$filenames)){
  700.                         if(count($filenames)>$limit){
  701.                             $this->addFlash('warning'$this->translator->trans('Se excedió el ḿaximo de archivos que se pueden cargar'));
  702.                             break;
  703.                         }
  704.                         else{
  705.                             $file->move($this->partDir$newFilename);
  706.                             if ($encrypt){
  707.                                 try {
  708.                                     $this->encryptDecryptService->encryptData($newFilename);
  709.                                     $newFilename $newFilename.'.packaged';
  710.                                 } catch (\Exception $e) {
  711.                                     $this->addFlash('warning'$e->getMessage());
  712.                                 }
  713.                             }
  714.                             $filenames[]=$newFilename;
  715.                             $part->setFileOthers(implode(',',$filenames));
  716.                         }
  717.                     }
  718.                 }
  719.             }
  720.             catch (FileException $e) {
  721.                 $this->addFlash('danger'$this->translator->trans('Fallo en la carga de fichero'));
  722.             }
  723.         }
  724.     }
  725.     private function processFiles(FormInterface $formPart $partbool $checkVersions=false$optionsEncrypt=[]){
  726.         $fs = new Filesystem;
  727.         $ds DIRECTORY_SEPARATOR;
  728.         $slugger = new AsciiSlugger();
  729.         $fields = [
  730.             'fileCadFile'=>'FileCad',
  731.             'fileStlFile'=>'FileStl',
  732.             'fileFabFile'=>'FileFab',
  733.             'fileVerifFile'=>'FileVerif',
  734.             'file2dFile'=>'File2d'];
  735.         $encryptFields = [
  736.             'fileCadFile'=>'encryptCAD',
  737.             'fileStlFile'=>'encryptSTL',
  738.             'fileFabFile'=>'encryptFAB',
  739.             'fileVerifFile'=>'encryptVER',
  740.             'file2dFile'=>'encrypt2D'
  741.         ];
  742.         foreach($fields as $field=>$aux){
  743.             $setter 'set'.$aux;
  744.             $getter 'get'.$aux;
  745.             $file $form->get($field)->getData();
  746.             if ($file) {
  747.                 $originalFilename pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
  748.                 $safeFilename $slugger->slug($originalFilename);
  749.                 $newFilename $safeFilename.'-'.uniqid().'.'.($field=='fileStlFile' 'stl' $file->getClientOriginalExtension());
  750.                 try {
  751.                     $file->move($this->partDir,$newFilename);
  752.                     if(!empty($optionsEncrypt[$encryptFields[$field]])){
  753.                         try {
  754.                             $this->encryptDecryptService->encryptData($newFilename);
  755.                             $newFilename $newFilename.'.packaged';
  756.                         } catch (\Exception $e) {
  757.                             $this->addFlash('warning'$e->getMessage());
  758.                         }
  759.                     }
  760.                     //dd($this->partDir, $newFilename, $optionsEncrypt);
  761.                 } catch (FileException $e) {
  762.                     $this->addFlash('danger'$this->translator->trans('Fallo en la carga de fichero').' ['.$e->getMessage().']');
  763.                 }
  764.                 if($checkVersions && !empty($part->$getter())){
  765.                     //Verificamos si el archivo se usa en otra pieza versionada
  766.                     $fileInVersions $this->partService->fileInVersions($partstrtolower(str_replace('File','',$aux)), $part->$getter());
  767.                     $oldFilePath $this->partDir.$ds.$part->$getter();
  768.                     if(!$fileInVersions && $fs->exists($oldFilePath)){
  769.                         try {
  770.                             $fs->remove($oldFilePath);
  771.                         } catch (IOExceptionInterface $e) {
  772.                             $this->addFlash('warning'$this->translator->trans('No se ha podido eliminar el archivo'));
  773.                         }
  774.                     }
  775.                 }
  776.                 $part->$setter($newFilename);
  777.                 if($aux=='FileStl'){
  778.                     $part->setFilePreview(null);
  779.                 }
  780.             }
  781.         }
  782.     }
  783.     /**
  784.      * @Route({"en": "/delete/{id}",
  785.      *         "es": "/borrar/{id}"}, name="part_delete", methods={"DELETE"})
  786.      */
  787.     public function delete(Request $requestPart $part): Response
  788.     {
  789.         $this->denyAccessUnlessGranted(PartVoter::DELETE$part);
  790.         if($request->request->get('redirect_to_name')){
  791.             if($request->request->get('redirect_to_id')){
  792.                 $redirect_to $this->redirectToRoute(
  793.                     $request->request->get('redirect_to_name'),
  794.                     ['id'=>$request->request->get('redirect_to_id')]);
  795.             }
  796.             else{
  797.                 $redirect_to $this->redirectToRoute($request->request->get('redirect_to_name'));
  798.             }
  799.         }
  800.         else{
  801.             $redirect_to $this->redirectToRoute('part_index');
  802.         }
  803.         if ($this->isCsrfTokenValid('delete' $part->getId(), $request->request->get('_token'))) {
  804.             $rmPart $this->partService->rmPart($part);
  805.             if($rmPart['error']){
  806.                 $this->addFlash('danger'$rmPart['msg']);
  807.             }
  808.             else{
  809.                 $this->addFlash('success'$this->translator->trans('Pieza eliminada correctamente'));
  810.             }
  811.         }
  812.         return $redirect_to;
  813.     }
  814.     /**
  815.      * @Route({"en": "/preview/{id}",
  816.      *         "es": "/preview/{id}"}, name="part_preview", methods={"POST"})
  817.      */
  818.     public function partPreview(Request $requestPart $part): Response
  819.     {
  820.         $this->denyAccessUnlessGranted(PartVoter::VIEW$part);
  821.         $result = ['error'=>false,'msg'=>'','data'=>''];
  822.         $fs = new Filesystem();
  823.         $ds DIRECTORY_SEPARATOR;
  824.         $em $this->em;
  825.         $file $request->request->get('file');
  826.         if ($file && $part) {
  827.             $filedata explode(','$file);
  828.             if(count($filedata)==2){
  829.                 $filename 'part_peview_' $part->getId() . '.jpg';
  830.                 $result['file']=$filedata[1];
  831.                 $filedata base64_decode($filedata[1]);
  832.                 $filepath $this->partDir$ds $filename;
  833.                 //if(!$fs->exists($filepath)){
  834.                     $fs->dumpFile($filepath$filedata);
  835.                     $part->setFilePreview($filename);
  836.                     $em->flush();
  837.                 //}
  838.             }
  839.         }
  840.         return new JsonResponse($result);
  841.     }
  842.     /**
  843.      * @Route({"en": "/lock_unlock/{id}",
  844.      *         "es": "/bloquear_desbloquear/{id}"}, name="part_lock_unlock", methods={"POST"})
  845.      */
  846.     public function lockUnlock(Request $requestPart $part): Response
  847.     {
  848.         $this->denyAccessUnlessGranted(PartVoter::DELETE$part);
  849.         if ($this->isCsrfTokenValid('delete' $part->getId(), $request->request->get('_token'))) {
  850.             $em $this->em;
  851.             if($part->getLocked()){
  852.                 $part->setLocked(false);
  853.             }
  854.             else{
  855.                 $part->setLocked(true);
  856.             }
  857.             $part->setLockedAt(new \DateTime());
  858.             $part->setLockedUser($this->getUser());
  859.             $em->flush();
  860.             $successMsg $part->getLocked() ? 'Pieza bloqueada correctamente' 'Pieza desbloqueada correctamente';
  861.             $this->addFlash('success'$this->translator->trans($successMsg));
  862.         }
  863.         if($request->query->get('lib')){
  864.             return $this->redirectToRoute('library_show',['id'=>$request->query->get('lib')]);
  865.         }
  866.         else{
  867.             return $this->redirectToRoute('part_index');
  868.         }
  869.     }
  870.     /**
  871.      * @Route({"en": "/export/{library?}",
  872.      *         "es": "/exportar/{library?}"}, name="part_export" , methods={"GET"})
  873.      */
  874.     public function export(Request $requestPartRepository $partRepository, ?Library $library null, ?int $part)
  875.     {
  876.         $trans $this->translator;
  877.         if (null !== $library) {
  878.             $filename 'AD2_'.$trans->trans('librería').'_' $library->getName() . '_' date("dmY.His") . ".xlsx";
  879.         } else {
  880.             if (null !== $part) {
  881.                 $filename 'AD2_'.$trans->trans('pieza').'_' $part->getRef() . '_' date("dmY.His") . ".xlsx";
  882.             } else {
  883.                 $filename 'AD2_'.$trans->trans('listado').'_'.$trans->trans('piezas').'_' date("dmY.His") . ".xlsx";
  884.             }
  885.         }
  886.         $part null;
  887.         if (null !== $request->query->get('id')) {
  888.                 $part $partRepository->find($request->query->get('id'));
  889.         }
  890.         $spreadsheet $this->generateXls($library,$partRepository,$part);
  891.         $writer = new Xlsx($spreadsheet);
  892.         $response = new StreamedResponse(
  893.             function () use ($writer) {
  894.                 $writer->save('php://output');
  895.             }
  896.         );
  897.         $response->headers->set('Content-Type''application/vnd.ms-excel');
  898.         $response->headers->set('Content-Disposition''attachment;filename="' $filename);
  899.         $response->headers->set('Cache-Control''max-age=0');
  900.         return $response;
  901.     }
  902.     /**
  903.      * @Route({"en": "/import",
  904.      *         "es": "/importar"}, name="part_import" , methods={"GET", "POST"})
  905.      */
  906.     public function import(Request $requestPartRepository $partRepositorystring $excelDirstring $partDir)
  907.     {
  908.         $this->denyAccessUnlessGranted(PartVoter::IMPORT, new Part);
  909.         $fs = new Filesystem();
  910.         $admin $this->getUser();
  911.         $licenseLimit 0;
  912.         //límites licencia
  913.         if(!($admin->getRole()=='ROLE_ADMIN')){
  914.             $lc =$this->em->getRepository(LicenseCompany::class)->findOneBy(['company'=>$admin->getCompany(),'state'=>2]);
  915.             if($lc){
  916.                 $licenseData $this->util->getCompanySuscriptionAvailable($lc);
  917.                 if(!empty($licenseData['parts']['available'])){
  918.                     $licenseLimit=intval($licenseData['parts']['available']);
  919.                 }
  920.             }
  921.         }
  922.         else{
  923.             $licenseLimit=-1;
  924.         }
  925.         $report = ['loaded'=>[],'errors'=>[]];
  926.         $part = new Part();
  927.         $form $this->createForm(PartImportType::class, $part, ['user_admin' => $admin]);
  928.         $form->handleRequest($request);
  929.         if ($form->isSubmitted()) {
  930.             $filenames = [];
  931.             $up 0;
  932.             if ($stlFiles $form['stlFiles']->getData()) {
  933.                 try {
  934.                     if(!$fs->exists($partDir)){
  935.                         $fs->mkdir($partDir);
  936.                     }
  937.                     foreach($stlFiles as $stl)
  938.                     {
  939.                         $ext $stl->getClientOriginalExtension();
  940.                         if ($ext == 'stl') {
  941.                             $fileName pathinfo($stl->getClientOriginalName(), PATHINFO_FILENAME);
  942.                             $filenames[$up][0] = $fileName;
  943.                             $fileName $fileName '_' date("dmY.His") . '.' $ext;
  944.                             $filenames[$up][1] = $fileName;
  945.                             $stl->move($partDir$fileName);
  946.                             $up++;
  947.                         }
  948.                     }
  949.                 }catch (FileException $e) {
  950.                     $this->addFlash('danger'$this->translator->trans('Fallo en la carga masiva de fichero STL').' : '.$e->getMessage());
  951.                     return $this->redirectToRoute('part_import');
  952.                 }
  953.                 catch (IOExceptionInterface $e) {
  954.                     $this->addFlash('danger'$this->translator->trans('Fallo en la carga masiva de fichero STL').' : '.$e->getPath());
  955.                     return $this->redirectToRoute('part_import');
  956.                 }
  957.             }
  958.             if(empty($filenames) || (empty($form['excelFile']->getData()) || $form['excelFile']->getData()->guessExtension()!='xlsx')){
  959.                 $this->addFlash('danger'$this->translator->trans('Los ficheros Excel y STL son requeridos y deben ser del tipo establecido'));
  960.                 return $this->redirectToRoute('part_import');
  961.             }
  962.             if ($excel $form['excelFile']->getData()) {
  963.                 try {
  964.                     if(!$fs->exists($excelDir)){
  965.                         $fs->mkdir($excelDir);
  966.                     }
  967.                     //cogemos la extensión y comprobamos antes de continuar
  968.                     $fileName pathinfo($excel->getClientOriginalName(), PATHINFO_FILENAME);
  969.                     $fileName $fileName '_' date("dmY.His") . '.xlsx';
  970.                     $excel->move($excelDir$fileName);
  971.                     $routeFileName $excelDir '/' $fileName;
  972.                     /**  Identify the type of $inputFileName  **/
  973.                     $inputFileType IOFactory::identify($routeFileName);
  974.                     /**  Create a new Reader of the type that has been identified  **/
  975.                     $reader IOFactory::createReader($inputFileType);
  976.                     $reader->setReadDataOnly(false);
  977.                     /**  Load $inputFileName to a Spreadsheet Object  **/
  978.                     $spreadsheet $reader->load($routeFileName);
  979.                     $sheet $spreadsheet->getActiveSheet();
  980.                     $x 0;
  981.                     $z 0;
  982.                     foreach ($sheet->getColumnIterator() as $column) {
  983.                         $cellIterator $column->getCellIterator();
  984.                         foreach ($cellIterator as $cell) {
  985.                             $value $cell->getValue();
  986.                             $piezaMasiva[$x][$z] = $value;
  987.                             $z++;
  988.                         }
  989.                         if($x !== 0){
  990.                             $company $admin->getCompany();
  991.                             $partName $piezaMasiva[$x][1];
  992.                             if($piezaMasiva[$x][1] == ''){
  993.                                 $this->importReportProcess($report);
  994.                                 return $this->redirectToRoute('part_index');
  995.                             }
  996.                             $nameExists $partRepository->nameExists($partName,$company->getId());
  997.                             if($nameExists){
  998.                                 $report['errors'][1][] = $piezaMasiva[$x][1];
  999.                             }
  1000.                             elseif($licenseLimit==0){
  1001.                                 $report['errors'][3] = true;
  1002.                                 break;
  1003.                             }
  1004.                             else{
  1005.                                 $newMasivePart = new Part();
  1006.                                 $newMasivePart->setBulkImportFile($fileName);
  1007.                                 //Datos Básicos
  1008.                                 $newMasivePart->setCompany($company);
  1009.                                 $newMasivePart->setName($piezaMasiva[$x][1]);
  1010.                                 $piezaMasiva[$x][2] == '' null $newMasivePart->setDescription($piezaMasiva[$x][2]);
  1011.                                 $piezaMasiva[$x][3] == '' null $newMasivePart->setClientName($piezaMasiva[$x][3]);
  1012.                                 $piezaMasiva[$x][4] == '' null $newMasivePart->setClientRefPart($piezaMasiva[$x][4]);
  1013.                                 $piezaMasiva[$x][5] == '' null $newMasivePart->setPartNumber($piezaMasiva[$x][5]);
  1014.                                 $piezaMasiva[$x][6] == '' null $newMasivePart->setSerial($piezaMasiva[$x][6]);
  1015.                                 $piezaMasiva[$x][7] == '' null $newMasivePart->setNotes($piezaMasiva[$x][7]);
  1016.                                 //Fabricacion
  1017.                                 $piezaMasiva[$x][10] == '' null $newMasivePart->setTechnology($piezaMasiva[$x][10]);
  1018.                                 $piezaMasiva[$x][11] == '' null $newMasivePart->setEquipo($piezaMasiva[$x][11]);
  1019.                                 $piezaMasiva[$x][12] == '' null $newMasivePart->setMaterial($piezaMasiva[$x][12]);
  1020.                                 $piezaMasiva[$x][13] == '' null $newMasivePart->setPrintMode($piezaMasiva[$x][13]);
  1021.                                 $piezaMasiva[$x][14] == '' null $newMasivePart->setAlturaCapa($piezaMasiva[$x][14]);
  1022.                                 $piezaMasiva[$x][15] == '' null $newMasivePart->setAlturaCapaTol($piezaMasiva[$x][15]);
  1023.                                 $piezaMasiva[$x][16] == '' null $newMasivePart->setDiamBoquilla($piezaMasiva[$x][16]);
  1024.                                 $piezaMasiva[$x][17] == '' null $newMasivePart->setDiamBoquillaTol($piezaMasiva[$x][17]);
  1025.                                 $piezaMasiva[$x][18] == '' null $newMasivePart->setTmpBoquilla($piezaMasiva[$x][18]);
  1026.                                 $piezaMasiva[$x][19] == '' null $newMasivePart->setTmpBoquillaTol($piezaMasiva[$x][19]);
  1027.                                 $piezaMasiva[$x][20] == '' null $newMasivePart->setTmpCama($piezaMasiva[$x][20]);
  1028.                                 $piezaMasiva[$x][21] == '' null $newMasivePart->setTmpCamaTol($piezaMasiva[$x][21]);
  1029.                                 $piezaMasiva[$x][22] == '' null $newMasivePart->setTmpCamara($piezaMasiva[$x][22]);
  1030.                                 $piezaMasiva[$x][23] == '' null $newMasivePart->setTmpCamaraTol($piezaMasiva[$x][23]);
  1031.                                 $piezaMasiva[$x][24] == '' null $newMasivePart->setVelocidadImpresion($piezaMasiva[$x][24]);
  1032.                                 $piezaMasiva[$x][25] == '' null $newMasivePart->setVelocidadImpresionTol($piezaMasiva[$x][25]);
  1033.                                 $piezaMasiva[$x][26] == '' null $newMasivePart->setPerimetroRelleno($piezaMasiva[$x][26]);
  1034.                                 $piezaMasiva[$x][27] == '' null $newMasivePart->setSoportes($piezaMasiva[$x][27]);
  1035.                                 $piezaMasiva[$x][28] == '' null $newMasivePart->setPuntoLaser($piezaMasiva[$x][28]);
  1036.                                 $piezaMasiva[$x][29] == '' null $newMasivePart->setPuntoLaserTol($piezaMasiva[$x][29]);
  1037.                                 $piezaMasiva[$x][30] == '' null $newMasivePart->setPotenciaFuente($piezaMasiva[$x][30]);
  1038.                                 $piezaMasiva[$x][31] == '' null $newMasivePart->setPotenciaFuenteTol($piezaMasiva[$x][31]);
  1039.                                 $piezaMasiva[$x][32] == '' null $newMasivePart->setTamPixel($piezaMasiva[$x][32]);
  1040.                                 $piezaMasiva[$x][33] == '' null $newMasivePart->setTamPixelTol($piezaMasiva[$x][33]);
  1041.                                 $piezaMasiva[$x][34] == '' null $newMasivePart->setTiempoExpos($piezaMasiva[$x][34]);
  1042.                                 $piezaMasiva[$x][35] == '' null $newMasivePart->setTiempoExposTol($piezaMasiva[$x][35]);
  1043.                                 $piezaMasiva[$x][36] == '' null $newMasivePart->setDistanHatch($piezaMasiva[$x][36]);
  1044.                                 $piezaMasiva[$x][37] == '' null $newMasivePart->setDistanHatchTol($piezaMasiva[$x][37]);
  1045.                                 $piezaMasiva[$x][38] == '' null $newMasivePart->setVelocidadRecoater($piezaMasiva[$x][38]);
  1046.                                 $piezaMasiva[$x][39] == '' null $newMasivePart->setVelocidadRecoaterTol($piezaMasiva[$x][39]);
  1047.                                 $piezaMasiva[$x][40] == '' null $newMasivePart->setEnfriamiento($piezaMasiva[$x][40]);
  1048.                                 $piezaMasiva[$x][41] == '' null $newMasivePart->setAtmosfera($piezaMasiva[$x][41]);
  1049.                                 $piezaMasiva[$x][42] == '' null $newMasivePart->setSaturacion($piezaMasiva[$x][42]);
  1050.                                 $piezaMasiva[$x][43] == '' null $newMasivePart->setObservacionesFab($piezaMasiva[$x][43]);
  1051.                                 //Validación
  1052.                                 $piezaMasiva[$x][46] == '' null $newMasivePart->setCompMatPrima($piezaMasiva[$x][46]);
  1053.                                 $piezaMasiva[$x][47] == '' null $newMasivePart->setCertMatPrima($piezaMasiva[$x][47]);
  1054.                                 $piezaMasiva[$x][48] == '' null $newMasivePart->setColorMatPrima($piezaMasiva[$x][48]);
  1055.                                 $piezaMasiva[$x][49] == '' null $newMasivePart->setCertProceso($piezaMasiva[$x][49]);
  1056.                                 $piezaMasiva[$x][50] == '' null $newMasivePart->setCertPart($piezaMasiva[$x][50]);
  1057.                                 $piezaMasiva[$x][51] == '' null $newMasivePart->setApplicableRegulations($piezaMasiva[$x][51]);
  1058.                                 $piezaMasiva[$x][52] == '' null $newMasivePart->setProcAcabado($piezaMasiva[$x][52]);
  1059.                                 $piezaMasiva[$x][53] == '' null $newMasivePart->setOtrosTrat($piezaMasiva[$x][53]);
  1060.                                 $piezaMasiva[$x][54] == '' null $newMasivePart->setObsVal($piezaMasiva[$x][54]);
  1061.                                 //stl
  1062.                                 $stlFound false;
  1063.                                 if($piezaMasiva[$x][57] !== ''){
  1064.                                     foreach($filenames as $k=>$name){
  1065.                                         $fn $piezaMasiva[$x][57];
  1066.                                         if(strrpos($fn".")){
  1067.                                             $fn substr($fn0, (strrpos($fn".")));
  1068.                                         }
  1069.                                         if($name[0] == $fn){
  1070.                                             unset($filenames[$k]);
  1071.                                             $newMasivePart->setFileStl($name[1]);
  1072.                                             $stlFound true;
  1073.                                             break;
  1074.                                         }
  1075.                                     }
  1076.                                 }
  1077.                                 if(!$stlFound){
  1078.                                     $report['errors'][2][] = $piezaMasiva[$x][1];
  1079.                                 }
  1080.                                 else{
  1081.                                     //Dependientes
  1082.                                     $newMasivePart->setRef($partRepository->findLastRef($company));
  1083.                                     $newMasivePart->setVersion(1);
  1084.                                     $newMasivePart->setAutor($admin->getName());
  1085.                                     $entityManager $this->em;
  1086.                                     $entityManager->persist($newMasivePart);
  1087.                                     $entityManager->flush();
  1088.                                     $report['loaded'][] = $piezaMasiva[$x][1];
  1089.                                     $licenseLimit--;
  1090.                                 }
  1091.                             }
  1092.                         }
  1093.                         $x++;
  1094.                         $z 0;
  1095.                     }
  1096.                 } catch (FileException $e) {
  1097.                     $this->addFlash('danger'$this->translator->trans('Fallo en la carga masiva de piezas').' : '.$e->getMessage());
  1098.                     return $this->redirectToRoute('part_import');
  1099.                 }
  1100.                 catch (IOExceptionInterface $e) {
  1101.                     $this->addFlash('danger'$this->translator->trans('Fallo en la carga masiva de piezas').' : '.$e->getPath());
  1102.                     return $this->redirectToRoute('part_import');
  1103.                 }
  1104.             }
  1105.             //Si quedan archivos sin asignar los eliminamos
  1106.             if($filenames){
  1107.                 foreach($filenames as $k=>$name){
  1108.                     if(!empty($name[1])){
  1109.                         $filepath $partDir.DIRECTORY_SEPARATOR.$name[1];
  1110.                         if($fs->exists($filepath)){
  1111.                             $fs->remove($filepath);
  1112.                         }
  1113.                     }
  1114.                 }
  1115.             }
  1116.             $this->importReportProcess($report);
  1117.             return $this->redirectToRoute('part_index');
  1118.         }
  1119.         return $this->render('part/import.html.twig', [
  1120.             'user' => $admin,
  1121.             //'part' => $part,
  1122.             'locale'=> $this->translator->getLocale(),
  1123.             'excel_form' => $form->createView(),
  1124.             'navbarTitle' => $this->translator->trans("Subida masiva de piezas")
  1125.         ]);
  1126.     }
  1127.     /**
  1128.      * @Route({"en": "/zip/{library?}",
  1129.      *         "es": "/zip/{library?}"}, name="part_zip", methods={"GET"})
  1130.      */
  1131.     public function partZip(Request $requestPartRepository $partRepository, ?Library $library null,?int $part)
  1132.     {
  1133.         $user $this->getUser();
  1134.         $part $partRepository->find($request->query->get('id'));
  1135.         $part_id $part->getId();
  1136.         $company_id $part->getCompany()->getId();
  1137.         $structure 'parts/zip/'.$company_id.'/'.$part_id;
  1138.         if (!file_exists($structure)) {
  1139.             if (!mkdir($structure0777true)) {
  1140.                 die('Fallo al crear las carpetas...');
  1141.             }
  1142.         }
  1143.         // Generate PDF
  1144.         $pdfData $this->htmlForPdf($part,$user);
  1145.         $this->pdf->generateFromHtml($pdfData['html'], $structure.'/'.$part->getRef().'.pdf',$pdfData['options'],true);
  1146.         // generate XLS
  1147.         $trans $this->translator;
  1148.         if (null !== $library) {
  1149.             $filename 'AD2_'.$trans->trans('librería').'_' $library->getName() .".xlsx";
  1150.         } else {
  1151.             if (null !== $part) {
  1152.                 $filename 'AD2_'.$trans->trans('pieza').'_' $part->getRef() .".xlsx";
  1153.             } else {
  1154.                 $filename 'AD2_'.$trans->trans('listado').'_'.$trans->trans('piezas').".xlsx";
  1155.             }
  1156.         }
  1157.         $spreadsheet $this->generateXls($library,$partRepository,$part);
  1158.         $writer = new Xlsx($spreadsheet);
  1159.         $writer->save($structure.'/'.$filename);
  1160.         $basename preg_replace('/[^a-zA-Z0-9_\-\s]/'''$part->getName());
  1161.         $basename str_replace(' ''-'$basename);
  1162.         $basename $part->getRef().'_'.$basename;
  1163.         $basename substr($basename040);
  1164.         // ZIP all
  1165.         $zipName $basename.'.zip';
  1166.         $zip = new \ZipArchive();
  1167.         if ($zip->open($structure.'/'.$zipName$zip::CREATE) === TRUE)
  1168.         {
  1169.             if($part->getFileStl() && file_exists('parts/'.$part->getFileStl())) {
  1170.                 $zip->addFile('parts/'.$part->getFileStl(),'files/'.$part->getFileStl());
  1171.             }
  1172.             if($part->getFileCad() && file_exists('parts/'.$part->getFileCad())) {
  1173.                 $zip->addFile('parts/'.$part->getFileCad(),'files/'.$part->getFileCad());
  1174.             }
  1175.             if($part->getFileFab() && file_exists('parts/'.$part->getFileFab())) {
  1176.                 $zip->addFile('parts/'.$part->getFileFab(),'files/'.$part->getFileFab());
  1177.             }
  1178.             if($part->getFileVerif() && file_exists('parts/'.$part->getFileVerif())) {
  1179.                 $zip->addFile('parts/'.$part->getFileVerif(),'files/'.$part->getFileVerif());
  1180.             }
  1181.             if($part->getFile2d() && file_exists('parts/'.$part->getFile2d())) {
  1182.                 $zip->addFile('parts/'.$part->getFile2d(),'files/'.$part->getFile2d());
  1183.             }
  1184.             if($part->getFileOthers() && file_exists('parts/'.$part->getFileOthers())) {
  1185.                 $zip->addFile('parts/'.$part->getFileOthers(),'files/'.$part->getFileOthers());
  1186.             }
  1187.             if($part->getFilePreview() && file_exists('parts/'.$part->getFilePreview())) {
  1188.                 $extension pathinfo($part->getFilePreview(), PATHINFO_EXTENSION);
  1189.                 $zip->addFile('parts/'.$part->getFilePreview(),$basename.'.'.$extension);
  1190.             }
  1191.             $zip->addFile($structure.'/'.$part->getRef().'.pdf','pdfs/'.$part->getRef().'.pdf');
  1192.             $zip->addFile($structure.'/'.$filename,'xls/'.$filename);
  1193.             // All files are added, so close the zip file.
  1194.             $zip->close();
  1195.         }
  1196.         // delete temporally files
  1197.         unlink($structure.'/'.$part->getRef().'.pdf');
  1198.         unlink($structure.'/'.$filename);
  1199.         $response = new BinaryFileResponse($structure.'/'.$zipName);
  1200.         $response->setStatusCode(200);
  1201.         $response->headers->set('Content-Type''application/zip');
  1202.         $response->headers->set('Content-Disposition''attachment; filename="'.basename($zipName).'"');
  1203.         $response->headers->set('Content-Length'filesize($structure.'/'.$zipName));
  1204.         return $response;
  1205.     }
  1206.     public function multiplePartZip(PartRepository $partRepository,$partIds) {
  1207.         $user $this->getUser();
  1208.         // generate XLS
  1209.         $trans $this->translator;
  1210.         $basename preg_replace('/[^a-zA-Z0-9_\-\s]/''''AD2_Download_'.$user->getCompany()->getName());
  1211.         $basename str_replace(' ''-'$basename);
  1212.         //$basename = date('Ymdhis').'_'.$basename;
  1213.         $basename substr($basename040);
  1214.         $structure 'parts/zipPack/user/' $user->getId();
  1215.         if (!file_exists($structure)) {
  1216.             if (!mkdir($structure0777true)) {
  1217.                 die('Fallo al crear las carpetas...');
  1218.             }
  1219.         }
  1220.         $zipName $basename.'.zip';
  1221.         $zip = new \ZipArchive();
  1222.         //borramos el existente
  1223.         if(file_exists($structure.'/'.$zipName)) {
  1224.             unlink($structure.'/'.$zipName);
  1225.         }
  1226.         if ($zip->open($structure.'/'.$zipName$zip::CREATE) === TRUE) {
  1227.             foreach ($partIds as $part_id) {
  1228.                 $part $partRepository->find($part_id);
  1229.                 if($part) {
  1230.                     // Generate PDF
  1231.                     $pdfData $this->htmlForPdf($part$user);
  1232.                     $this->pdf->generateFromHtml($pdfData['html'], $structure '/' $part->getRef() . '.pdf'$pdfData['options'], true);
  1233.                     $filename 'AD2_' $trans->trans('pieza') . '_' $part->getRef() . ".xlsx";
  1234.                     $foldername 'AD2_' $part->getRef() . '_' $part->getName();
  1235.                     $foldername preg_replace('/[^a-zA-Z0-9_\-\s]/'''$foldername);
  1236.                     $foldername str_replace(' ''-'$foldername);
  1237.                     $foldername substr($foldername040);
  1238.                     $spreadsheet $this->generateXls(null$partRepository$part);
  1239.                     $writer = new Xlsx($spreadsheet);
  1240.                     $writer->save($structure '/' $filename);
  1241.                     if ($part->getFileStl() && file_exists('parts/' $part->getFileStl())) {
  1242.                         $zip->addFile('parts/' $part->getFileStl(), $foldername.'/files/'$part->getFileStl());
  1243.                     }
  1244.                     if ($part->getFileCad() && file_exists('parts/' $part->getFileCad())) {
  1245.                         $zip->addFile('parts/' $part->getFileCad(), $foldername.'/files/'$part->getFileCad());
  1246.                     }
  1247.                     if ($part->getFileFab() && file_exists('parts/' $part->getFileFab())) {
  1248.                         $zip->addFile('parts/' $part->getFileFab(), $foldername.'/files/'.  $part->getFileFab());
  1249.                     }
  1250.                     if ($part->getFileVerif() && file_exists('parts/' $part->getFileVerif())) {
  1251.                         $zip->addFile('parts/' $part->getFileVerif(), $foldername.'/files/'.  $part->getFileVerif());
  1252.                     }
  1253.                     if ($part->getFile2d() && file_exists('parts/' $part->getFile2d())) {
  1254.                         $zip->addFile('parts/' $part->getFile2d(), $foldername.'/files/'.  $part->getFile2d());
  1255.                     }
  1256.                     if ($part->getFileOthers() && file_exists('parts/' $part->getFileOthers())) {
  1257.                         $zip->addFile('parts/' $part->getFileOthers(), $foldername.'/files/'$part->getFileOthers());
  1258.                     }
  1259.                     if ($part->getFilePreview() && file_exists('parts/' $part->getFilePreview())) {
  1260.                         $extension pathinfo($part->getFilePreview(), PATHINFO_EXTENSION);
  1261.                         $zip->addFile('parts/' $part->getFilePreview(),  'AD2_' $part->getRef() . '_' $part->getName() . '.' $extension);
  1262.                     }
  1263.                     $zip->addFile($structure '/' $part->getRef() . '.pdf'$foldername.'/pdfs/'$part->getRef() . '.pdf');
  1264.                     $zip->addFile($structure '/' $filename$foldername.'/xls/' $filename);
  1265.                 }
  1266.             }//endforeach
  1267.             // All files are added, so close the zip file.
  1268.             $zip->close();
  1269.         }
  1270.         foreach ($partIds as $part_id) {
  1271.             if($part) {
  1272.                 // delete temporally files
  1273.                 $part $partRepository->find($part_id);
  1274.                 $filename 'AD2_' $trans->trans('pieza') . '_' $part->getRef() . ".xlsx";
  1275.                 unlink($structure '/' $part->getRef() . '.pdf');
  1276.                 unlink($structure '/' $filename);
  1277.             }
  1278.         }
  1279.         return array($structure,$zipName);
  1280.     }
  1281.     private function importReportProcess($report){
  1282.         //Loaded
  1283.         $loaded $report['loaded'];
  1284.         if(empty($loaded)){
  1285.             $message $nData['message'] = 'No se han podido cargado piezas';
  1286.         }
  1287.         else{
  1288.             $stringLoaded implode(', ',$loaded);
  1289.             $message "Se han cargado correctamente las siguientes piezas : $stringLoaded";
  1290.             $nData['message'] = "Se han cargado correctamente las siguientes piezas : {aux}";
  1291.             $nData['message_aux'] = $stringLoaded;
  1292.         }
  1293.         $nData['path_name']='part_index';
  1294.         $this->util->notifications($this->getUser()->getCompany(), 2$nData$this->getUser());
  1295.         $this->addFlash(empty($loaded) ? 'danger' 'success'$this->translator->trans($message));
  1296.         //Errors
  1297.         $errors $report['errors'];
  1298.         if(!empty($errors)){
  1299.             $message $this->translator->trans('Se han producido los siguientes errores : ');
  1300.             $message.= '<br>';
  1301.             if(!empty($errors[1])){
  1302.                 $error_1 count($errors[1])>array_slice($errors[1],0,5).' ...' $errors[1];
  1303.                 $message.= $this->translator->trans('Piezas con el nombre duplicado : ') . implode(', ',$error_1). '<br>';
  1304.             }
  1305.             if(!empty($errors[2])){
  1306.                 $error_2 count($errors[2])>array_slice($errors[2],0,5).' ...' $errors[2];
  1307.                 $message.= $this->translator->trans('Piezas sin archivo STL : ') . implode(', ',$error_2);
  1308.             }
  1309.             if(!empty($errors[3])){
  1310.                 $message.= $this->translator->trans("Se han agotado las piezas disponibles para su licencia") . '<br>';
  1311.             }
  1312.             $this->addFlash('danger'$this->translator->trans($message));
  1313.         }
  1314.     }
  1315.     /**
  1316.      * @param $part
  1317.      * @param $user
  1318.      * @return array
  1319.      * HTML FOR PDF
  1320.      */
  1321.     private function htmlForPdf($part,$user) {
  1322.         $url $this->generateUrl('part_show',['id'=>$part->getId()], UrlGeneratorInterface::ABSOLUTE_URL);
  1323.         $qr $this->util->generateQrCode($url);
  1324.         $header $this->renderView'part/pdf/pdf_header.html.twig',[
  1325.             'part' => $part,
  1326.             'partByCat' => $this->partService->getPartByCat($part),
  1327.             'orders' => $part->getOrders(),
  1328.             'qr' => $qr,
  1329.             'preview' => $part->getFilePreview() ? $this->partDir DIRECTORY_SEPARATOR $part->getFilePreview() : '',
  1330.             'user' => $user
  1331.         ] );
  1332.         $footer $this->renderView'part/pdf/pdf_footer.html.twig',[
  1333.             'part' => $part,
  1334.             'partByCat' => $this->partService->getPartByCat($part),
  1335.             'orders' => $part->getOrders(),
  1336.             'qr' => $qr,
  1337.             'user' => $user
  1338.         ] );
  1339.         $options = [
  1340.             'header-html' => $header,
  1341.             'footer-html' => $footer,
  1342.             'page-size' => 'A4'
  1343.         ];
  1344.         $html =$this->renderView('part/pdf/pdf.html.twig', [
  1345.             'part' => $part,
  1346.             'stl' => json_decode($part->getData(),true),
  1347.             'partByCat' => $this->partService->getPartByCat($part),
  1348.             'orders' => $part->getOrders(),
  1349.             'qr' => $qr,
  1350.             'user' => $user
  1351.         ]);
  1352.         return array(
  1353.             'html' =>$html,
  1354.             'options' => $options
  1355.         );
  1356.     }
  1357.     private function generateXls($library,PartRepository $partRepository,$part null) {
  1358.         $trans $this->translator;
  1359.         $admin $this->getUser();
  1360.         $company $admin->getCompany();
  1361.         $colorARGB $company && $company->getCorporateColor() ? str_replace('#','',$company->getCorporateColor()) : 'DD9933';
  1362.         $isSupplier in_array($admin->getRole(),['ROLE_SUPPLIER_CHIEF','ROLE_SUPPLIER']);
  1363.         $spreadsheet = new Spreadsheet();
  1364.         $sheet $spreadsheet->getActiveSheet();
  1365.         $sheet->setTitle(date("F j, Y"));
  1366.         $row 1;
  1367.         $titles = ['A'.$row];
  1368.         $sheet->setCellValue('A'.$row++, $trans->trans('Datos Básicos'));
  1369.         $sheet->setCellValue('A'.$row++, $trans->trans('Autor'));
  1370.         $sheet->setCellValue('A'.$row++, $trans->trans('Fecha Creación'));
  1371.         $sheet->setCellValue('A'.$row++, $trans->trans('Fecha Revisión'));
  1372.         $sheet->setCellValue('A'.$row++, $trans->trans('Nombre de pieza'));
  1373.         $sheet->setCellValue('A'.$row++, $trans->trans('Referencia'));
  1374.         if(!$isSupplier){
  1375.             $sheet->setCellValue('A'.$row++, $trans->trans('Descripcion'));
  1376.             $sheet->setCellValue('A'.$row++, $trans->trans('Nombre de Cliente'));
  1377.             $sheet->setCellValue('A'.$row++, $trans->trans('Referencia pieza Cliente'));
  1378.             $sheet->setCellValue('A'.$row++, $trans->trans('Part number'));
  1379.             $sheet->setCellValue('A'.$row++, $trans->trans('Serial number'));
  1380.         }
  1381.         $sheet->setCellValue('A'.$row++, $trans->trans('Observaciones'));
  1382.         $sheet->setCellValue('A'.$row++, '');
  1383.         $titles[]='A'.$row;
  1384.         $sheet->setCellValue('A'.$row++, $trans->trans('Fabricación'));
  1385.         $sheet->setCellValue('A'.$row++, $trans->trans('Centro de trabajo'));
  1386.         $sheet->setCellValue('A'.$row++, $trans->trans('Tecnología'));
  1387.         $sheet->setCellValue('A'.$row++, $trans->trans('Equipo'));
  1388.         $sheet->setCellValue('A'.$row++, $trans->trans('Material'));
  1389.         $sheet->setCellValue('A'.$row++, $trans->trans('Modo impresión'));
  1390.         $sheet->setCellValue('A'.$row++, $trans->trans('Altura capa (μm)') . ' [' $trans->trans('Tolerancia').']');
  1391.         $sheet->setCellValue('A'.$row++, $trans->trans('Diam. boquilla (mm)') . ' [' $trans->trans('Tolerancia').']');
  1392.         $sheet->setCellValue('A'.$row++, $trans->trans('Temperatura extrusor (ºC)') . ' [' $trans->trans('Tolerancia').']');
  1393.         $sheet->setCellValue('A'.$row++, $trans->trans('Temperatura cama (ºC)') . ' [' $trans->trans('Tolerancia').']');
  1394.         $sheet->setCellValue('A'.$row++, $trans->trans('Temperatura cámara (ºC)') . ' [' $trans->trans('Tolerancia').']');
  1395.         $sheet->setCellValue('A'.$row++, $trans->trans('Velocidad de impresión (mm/s)') . ' [' $trans->trans('Tolerancia').']');
  1396.         $sheet->setCellValue('A'.$row++, $trans->trans('Perímetros y relleno'));
  1397.         $sheet->setCellValue('A'.$row++, $trans->trans('Soportes'));
  1398.         $sheet->setCellValue('A'.$row++, $trans->trans('Punto láser (μm)') . ' [' $trans->trans('Tolerancia').']');
  1399.         $sheet->setCellValue('A'.$row++, $trans->trans('Potencia Fuente (%)') . ' [' $trans->trans('Tolerancia').']');
  1400.         $sheet->setCellValue('A'.$row++, $trans->trans('Tamaño pixel (μm)') . ' [' $trans->trans('Tolerancia').']');
  1401.         $sheet->setCellValue('A'.$row++, $trans->trans('Tiempo Exposición (s)') . ' [' $trans->trans('Tolerancia').']');
  1402.         $sheet->setCellValue('A'.$row++, $trans->trans('Distancia hatch (μm)') . ' [' $trans->trans('Tolerancia').']');
  1403.         $sheet->setCellValue('A'.$row++, $trans->trans('Velocidad recoater (mm/s)') . ' [' $trans->trans('Tolerancia').']');
  1404.         $sheet->setCellValue('A'.$row++, $trans->trans('Enfriamiento').' (h)');
  1405.         $sheet->setCellValue('A'.$row++, $trans->trans('Atmósfera controlada'));
  1406.         $sheet->setCellValue('A'.$row++, $trans->trans('Saturación (%)'));
  1407.         $sheet->setCellValue('A'.$row++, $trans->trans('Observaciones de fabricación'));
  1408.         $sheet->setCellValue('A'.$row++, '');
  1409.         $titles[]='A'.$row;
  1410.         $sheet->setCellValue('A'.$row++, $trans->trans('Validación'));
  1411.         $sheet->setCellValue('A'.$row++, $trans->trans('Composición materia prima'));
  1412.         $sheet->setCellValue('A'.$row++, $trans->trans('Certificación materia prima'));
  1413.         $sheet->setCellValue('A'.$row++, $trans->trans('Color materia prima'));
  1414.         $sheet->setCellValue('A'.$row++, $trans->trans('Certificación proceso'));
  1415.         $sheet->setCellValue('A'.$row++, $trans->trans('Certificación pieza'));
  1416.         $sheet->setCellValue('A'.$row++, $trans->trans('Normativa aplicable'));
  1417.         $sheet->setCellValue('A'.$row++, $trans->trans('Procesos de acabado'));
  1418.         $sheet->setCellValue('A'.$row++, $trans->trans('Otros tratamientos'));
  1419.         $sheet->setCellValue('A'.$row++, $trans->trans('Observaciones'));
  1420.         $sheet->setCellValue('A'.$row++, '');
  1421.         $titles[]='A'.$row;
  1422.         $sheet->setCellValue('A'.$row++, $trans->trans('Adjuntos'));
  1423.         $sheet->setCellValue('A'.$row++, $trans->trans('Archivo CAD (.step, otros)'));
  1424.         $sheet->setCellValue('A'.$row++, $trans->trans('Archivo Stl'));
  1425.         $sheet->setCellValue('A'.$row++, $trans->trans('Archivo Fabricación (.gcode, .pdf, otros)'));
  1426.         $sheet->setCellValue('A'.$row++, $trans->trans('Archivo Verificación (.txt, .pdf, .doc)'));
  1427.         $sheet->setCellValue('A'.$row++, $trans->trans('Planos 2D (.pdf)'));
  1428.         $sheet->setCellValue('A'.$row++, $trans->trans('Archivo N01'));
  1429.         $sheet->setCellValue('A'.$row++, $trans->trans('Archivo N02'));
  1430.         $sheet->setCellValue('A'.$row++, $trans->trans('Archivo N03'));
  1431.         $sheet->setCellValue('A'.$row++, $trans->trans('Archivo N04'));
  1432.         $sheet->setCellValue('A'.$row++, $trans->trans('Archivo N05'));
  1433.         $sheet->setCellValue('A'.$row++, '');
  1434.         if(!$isSupplier){
  1435.             $titles[]='A'.$row;
  1436.             $sheet->setCellValue('A'.$row++, $trans->trans('Biblioteca'));
  1437.             $sheet->setCellValue('A'.$row++, $trans->trans('Bibliotecas'));
  1438.         }
  1439.         $sheet->setCellValue('A'.$row++, '');
  1440.         $titles[]='A'.$row;
  1441.         $sheet->setCellValue('A'.$row++, $trans->trans('Datos STL'));
  1442.         $sheet->setCellValue('A'.$row++, $trans->trans('Volumen'));
  1443.         $sheet->setCellValue('A'.$row++, $trans->trans('Superficie'));
  1444.         $sheet->setCellValue('A'.$row++, $trans->trans('Altura'));
  1445.         $sheet->setCellValue('A'.$row++, $trans->trans('Ancho'));
  1446.         $sheet->setCellValue('A'.$row++, $trans->trans('Largo'));
  1447.         //$spreadsheet->createSheet();
  1448.         $styleArrayFirstRow = [
  1449.             'font' => [
  1450.                 'bold' => true,
  1451.             ]
  1452.         ];
  1453.         $highestColumn $sheet->getHighestColumn();
  1454.         $sheet->getStyle($titles[0])->applyFromArray($styleArrayFirstRow);
  1455.         $sheet->getStyle($titles[1])->applyFromArray($styleArrayFirstRow);
  1456.         $sheet->getStyle($titles[2])->applyFromArray($styleArrayFirstRow);
  1457.         $sheet->getStyle($titles[3])->applyFromArray($styleArrayFirstRow);
  1458.         if(!$isSupplier){
  1459.             $sheet->getStyle($titles[4])->applyFromArray($styleArrayFirstRow);
  1460.         }
  1461.         //$sheet->getStyle('A')->getFont()->setBold(true);
  1462.         $sheet->getColumnDimension('A')->setWidth(36);
  1463.         $sheet->getDefaultColumnDimension()->setWidth(30);
  1464.         $sheet->freezePaneByColumnAndRow(21);
  1465.         $styleArrayFirstRow = [
  1466.             'font' => [
  1467.                 'bold' => true,
  1468.                 'color' => array('rgb' => 'FFFFFF'),
  1469.             ]
  1470.         ];
  1471.         $sheet
  1472.             ->getStyle($titles[0])
  1473.             ->getFill()
  1474.             ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1475.             ->getStartColor()
  1476.             ->setARGB($colorARGB);
  1477.         $sheet->getStyle($titles[0])->applyFromArray($styleArrayFirstRow);
  1478.         $sheet
  1479.             ->getStyle($titles[1])
  1480.             ->getFill()
  1481.             ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1482.             ->getStartColor()
  1483.             ->setARGB($colorARGB);
  1484.         $sheet->getStyle($titles[1])->applyFromArray($styleArrayFirstRow);
  1485.         $sheet
  1486.             ->getStyle($titles[2])
  1487.             ->getFill()
  1488.             ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1489.             ->getStartColor()
  1490.             ->setARGB($colorARGB);
  1491.         $sheet->getStyle($titles[2])->applyFromArray($styleArrayFirstRow);
  1492.         $sheet
  1493.             ->getStyle($titles[3])
  1494.             ->getFill()
  1495.             ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1496.             ->getStartColor()
  1497.             ->setARGB($colorARGB);
  1498.         $sheet->getStyle($titles[3])->applyFromArray($styleArrayFirstRow);
  1499.         if(!$isSupplier){
  1500.             $sheet
  1501.                 ->getStyle($titles[4])
  1502.                 ->getFill()
  1503.                 ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1504.                 ->getStartColor()
  1505.                 ->setARGB($colorARGB);
  1506.             $sheet->getStyle($titles[4])->applyFromArray($styleArrayFirstRow);
  1507.         }
  1508.         $sheet
  1509.             ->getStyle($titles[5])
  1510.             ->getFill()
  1511.             ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1512.             ->getStartColor()
  1513.             ->setARGB($colorARGB);
  1514.         $sheet->getStyle($titles[5])->applyFromArray($styleArrayFirstRow);
  1515.         $arrayParts $partRepository->generateExport($admin$library$part);
  1516.         $column 2;
  1517.         $row 2;
  1518.         //dd($arrayParts);
  1519.         foreach ($arrayParts as $mypPart) {
  1520.             //Autor
  1521.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[42]);
  1522.             //Fecha creación
  1523.             $sheet->setCellValueByColumnAndRow($column$row++, ( $mypPart[73] ? $mypPart[73]->format('d-m-y H:i') : '' ));
  1524.             //Fecha modificación
  1525.             $sheet->setCellValueByColumnAndRow($column$row++, ( $mypPart[73] ? $mypPart[74]->format('d-m-y H:i') : '' ));
  1526.             //Nombre Pieza
  1527.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[3]);
  1528.             //Referencia
  1529.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[1]);
  1530.             if(!$isSupplier){
  1531.                 //Description
  1532.                 $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[4]);
  1533.                 //Nombre de Cliente
  1534.                 $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[7]);
  1535.                 //Referencia Pieza Cliente
  1536.                 $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[8]);
  1537.                 //Part Number
  1538.                 $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[2]);
  1539.                 //Serial Number
  1540.                 $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[9]);
  1541.             }
  1542.             //Observaciones (Notes?)
  1543.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[12]);
  1544.             $row++;
  1545.             $row++;
  1546.             //Proveedor
  1547.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[43]);
  1548.             //Tecnologia
  1549.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[13]);
  1550.             //Equipo
  1551.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[44]);
  1552.             //Material
  1553.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[5]);
  1554.             //Modo impresión
  1555.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[75]);
  1556.             //Altura Capa
  1557.             $sheet->setCellValueByColumnAndRow($column$row++, ($mypPart[45] > $mypPart[45] : '-') . ' ' . ($mypPart[76] > '[+/-'.$mypPart[76].']' ''));
  1558.             //Diam boquilla
  1559.             $sheet->setCellValueByColumnAndRow($column$row++, ($mypPart[46] > $mypPart[46] : '-') . ' ' . ($mypPart[77] > '[+/-'.$mypPart[77].']' ''));
  1560.             //Tmp extrusor
  1561.             $sheet->setCellValueByColumnAndRow($column$row++, ($mypPart[47] > $mypPart[47] : '-') . ' ' . ($mypPart[78] > '[+/-'.$mypPart[78].']' ''));
  1562.             //Tmp cama
  1563.             $sheet->setCellValueByColumnAndRow($column$row++,($mypPart[48] > $mypPart[48] : '-') . ' ' . ($mypPart[79] > '[+/-'.$mypPart[79].']' ''));
  1564.             //Tmp camara
  1565.             $sheet->setCellValueByColumnAndRow($column$row++, ($mypPart[49] > $mypPart[49] : '-') . ' ' . ($mypPart[80] > '[+/-'.$mypPart[80].']' ''));
  1566.             //Veloc Impresion
  1567.             $sheet->setCellValueByColumnAndRow($column$row++, ($mypPart[50] > $mypPart[50] : '-') . ' ' . ($mypPart[81] > '[+/-'.$mypPart[81].']' ''));
  1568.             //Perim y relleno
  1569.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[51]);
  1570.             //Soportes
  1571.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[52]);
  1572.             //Punto laser
  1573.             $sheet->setCellValueByColumnAndRow($column$row++, ($mypPart[54] > $mypPart[54] : '-') . ' ' . ($mypPart[83] > '[+/-'.$mypPart[83].']' ''));
  1574.             //Pot fuente
  1575.             $sheet->setCellValueByColumnAndRow($column$row++,  ($mypPart[55] > $mypPart[55] : '-') . ' ' . ($mypPart[84] > '[+/-'.$mypPart[84].']' ''));
  1576.             //Tam pixel
  1577.             $sheet->setCellValueByColumnAndRow($column$row++, ($mypPart[56] > $mypPart[56] : '-') . ' ' . ($mypPart[85] > '[+/-'.$mypPart[85].']' ''));
  1578.             //Tpo Expos
  1579.             $sheet->setCellValueByColumnAndRow($column$row++, ($mypPart[57] > $mypPart[57] : '-') . ' ' . ($mypPart[86] > '[+/-'.$mypPart[86].']' ''));
  1580.             //Dist HAtch
  1581.             $sheet->setCellValueByColumnAndRow($column$row++, ($mypPart[58] > $mypPart[58] : '-') . ' ' . ($mypPart[87] > '[+/-'.$mypPart[87].']' ''));
  1582.             //Vel recoaster
  1583.             $sheet->setCellValueByColumnAndRow($column$row++, ($mypPart[59] > $mypPart[59] : '-') . ' ' . ($mypPart[82] > '[+/-'.$mypPart[82].']' ''));
  1584.             //Enfriam
  1585.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[60]);
  1586.             //Atmosf
  1587.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[61]);
  1588.             //Saturac
  1589.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[62]);
  1590.             //Obs Fab
  1591.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[53]);
  1592.             $row++;
  1593.             $row++;
  1594.             //Composición materia prima
  1595.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[14]);
  1596.             //Certificación materia prima
  1597.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[15]);
  1598.             //Color materia prima
  1599.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[16]);
  1600.             //Certificación proceso
  1601.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[17]);
  1602.             //Certificación pieza
  1603.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[18]);
  1604.             //Normativa aplicable
  1605.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[19]);
  1606.             //Proceso acabado
  1607.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[20]);
  1608.             //Otros tratamientos
  1609.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[21]);
  1610.             //Observaciones
  1611.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[22]);
  1612.             $row++;
  1613.             $row++;
  1614.             //Archivo CAD (.step, otros)
  1615.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[63]);
  1616.             //Archivo STL
  1617.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[64]);
  1618.             //Archivo Fabricación (.gcode, .pdf, otros)
  1619.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[66]);
  1620.             //Archivo Verificación (.txt, .pdf, .doc)
  1621.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[67]);
  1622.             //Planos 2D (.pdf)
  1623.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[65]);
  1624.             //Archivo N01
  1625.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[68]);
  1626.             //Archivo N02
  1627.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[69]);
  1628.             //Archivo N03
  1629.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[70]);
  1630.             //Archivo N04
  1631.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[71]);
  1632.             //Archivo N05
  1633.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[72]);
  1634.             if(!$isSupplier){
  1635.                 $row++;
  1636.                 $row++;
  1637.                 //Bibliotecas
  1638.                 $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[88]);
  1639.             }
  1640.             $row++;
  1641.             $row++;
  1642.             //STL DATA
  1643.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[89]);
  1644.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[90]);
  1645.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[91]);
  1646.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[92]);
  1647.             $sheet->setCellValueByColumnAndRow($column$row++, $mypPart[93]);
  1648.             $row 2;
  1649.             $column++;
  1650.         }
  1651.         return $spreadsheet;
  1652.     }
  1653. }