<?php
namespace App\Controller;
use App\Entity\CompanyClient;
use App\Entity\Library;
use App\Entity\Order;
use App\Entity\Part;
use App\Entity\Supplier;
use App\Entity\CompanySupplier;
use App\Entity\Equipment;
use App\Entity\Material;
use App\Form\OrderType;
use App\Form\PartSearchType;
use App\Form\PartImportType;
use App\Form\PartType;
use App\Repository\CompanyClientRepository;
use App\Repository\PartRepository;
use App\Repository\CompanySupplierRepository;
use App\Service\EncryptDecryptService;
use App\Service\Part\EditPartService;
use App\Service\UtilService;
use App\Service\PartService;
use App\Service\LibraryService;
use App\Security\Voter\PartVoter;
use App\Entity\LicenseCompany;
use PHPSTL\Handler\DimensionsHandler;
use PHPSTL\Handler\SurfaceHandler;
use PHPSTL\Handler\VolumeHandler;
use PHPSTL\Model\STLModel;
use PHPSTL\Reader\STLReader;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Constraints\Url as ConstraintsUrl;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\String\Slugger\AsciiSlugger;
use Symfony\Contracts\Translation\TranslatorInterface;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Knp\Component\Pager\PaginatorInterface;
use Knp\Snappy\Pdf;
use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
use Doctrine\Persistence\ManagerRegistry;
/**
* @Route({"en": "/part",
* "es": "/pieza"})
*/
class PartController extends AbstractController
{
private const PAGE_ELEMENTS = 25;
private $translator;
private $util;
private $pdf;
private $partService;
private $libService;
private $csRepository;
private $em;
private $partDir;
/**
* @var EditPartService
*/
private $editPartService;
/**
* PartController constructor.
* @param EditPartService $editPartService
*/
public function __construct(
EditPartService $editPartService,
TranslatorInterface $translator,
UtilService $utilService,
PartService $partService,
LibraryService $libService,
CompanySupplierRepository $csRepository,
Pdf $knpSnappyPdf,
ManagerRegistry $doctrine,
string $partDir,
private EncryptDecryptService $encryptDecryptService
)
{
$this->editPartService = $editPartService;
$this->translator = $translator;
$this->util = $utilService;
$this->partService = $partService;
$this->libService = $libService;
$this->csRepository = $csRepository;
$this->pdf = $knpSnappyPdf;
$this->em = $doctrine->getManager();
$this->partDir = $partDir;
}
/**
* @Route({"en": "/list",
* "es": "/listado"}, name="part_index", methods={"GET","POST"})
*/
public function index(Request $request, PartRepository $partRepository, PaginatorInterface $paginator): Response
{
$admin = $this->getUser();
$ms = $this->util->getLicenseField($admin->getCompany(),'multi_select') && $admin->getRole()!='ROLE_CLIENT';
$part = [];
$form = $this->createForm(PartSearchType::class, $part, ['user_admin' => $admin,'method' => 'GET']);
$form->handleRequest($request);
$orderBy = null;
$filters = [
['field'=>'company','title'=>'Empresa'],
['field'=>'ref','title'=>'Referencia'],
['field'=>'name','title'=>'Nombre'],
['field'=>'description','title'=>'Descripción'],
['field'=>'technology','title'=>'Tecnología'],
['field'=>'material','title'=>'Material'],
['field'=>'updated_at','title'=>'Última modificación'],
];
if ($form->isSubmitted() && $form->isValid()) {
$orderBy = $request->query->get('order_by');
$parts = $partRepository->findByName($form->getData(), $admin, $orderBy);
} else {
$parts = $partRepository->buscarTodos($admin);
}
if($request->isMethod('POST')){
if($request->request->get('libraries_update')){
$libraryIds = $request->request->get('libraryIds',null);
$partIds = $request->request->get('partIds',null);
$rmCurrentLibs = $request->request->get('currentLibs',null) ? true : false;
if($partIds && $libraryIds){
$parts = explode(',', $partIds);
foreach($parts as $partId){
$part = $this->em->getRepository(Part::class)->find($partId);
$this->partService->updateLibs($part,$libraryIds,$rmCurrentLibs);
}
$this->addFlash('success', $this->translator->trans('Bibliotecas editadas correctamente'));
return $this->redirectToRoute('part_index');
}
}
if($request->request->get('parts_delete')){
$delIds = $request->request->get('delIds',null);
if($delIds){
$parts = explode(',', $delIds);
$successMsg = '';
$errorMsg = '';
foreach($parts as $partId){
$part = $this->em->getRepository(Part::class)->find($partId);
if($part){
if($part->getLocked()){
$errorMsg.= $this->translator->trans('Error pieza {ref} : ',['{ref}'=>$part->getRef()]) . $this->translator->trans('Pieza bloqueada') .'<br>';
}
else{
$rmPart = $this->partService->rmPart($part);
if($rmPart['error']){
$errorMsg.= $this->translator->trans('Error pieza {ref} : ',['{ref}'=>$part->getRef()]) . $rmPart['msg'].'<br>';
}
else{
$successMsg.= $this->translator->trans('Pieza {ref} eliminada correctamente',['{ref}'=>$part->getRef()]).'<br>';
}
}
}
}
if($successMsg){
$this->addFlash('success', $successMsg);
}
if($errorMsg){
$this->addFlash('danger', $errorMsg);
}
return $this->redirectToRoute('part_index');
}
}
if($request->request->get('parts_download')){
$downIds = $request->request->get('downIds',null);
$downIds = explode(',', $downIds);
$zip =$this->multiplePartZip($partRepository,$downIds);
$response = new BinaryFileResponse($zip[0].'/'.$zip[1]);
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'application/zip');
$response->headers->set('Content-Disposition', 'attachment; filename="'.basename($zip[1]).'"');
$response->headers->set('Content-Length', filesize($zip[0].'/'.$zip[1]));
return $response;
}
if($request->request->get('parts_order')){
$partIds = $request->request->get('partIds',null);
if($partIds){
$partIds = explode(',',$partIds);
$partIdsChecked = [];
foreach($partIds as $partId){
$part = $this->em->getRepository(Part::class)->find($partId);
if($part && $part->getSupplier() && $part->getCompany()==$admin->getCompany()){
$partIdsChecked[] = $partId;
}
}
if($partIdsChecked){
return $this->redirectToRoute('order_bulk_new',['partIds'=>base64_encode(implode(',',$partIdsChecked))]);
}
else{
$this->addFlash('danger', 'Error inesperado');
return $this->redirectToRoute('part_index');
}
}
else{
$this->addFlash('danger', 'Error inesperado');
return $this->redirectToRoute('part_index');
}
}
}
// Creating pagnination
$pagination = $paginator->paginate(
$parts,
$request->query->getInt('page', 1),
self::PAGE_ELEMENTS
);
return $this->render('part/index.html.twig', [
'pagination' => $pagination,
'search_form' => $form->createView(),
'filters' => $filters,
'order_by' => $orderBy,
'ms' => $ms,
'company' => $admin->getCompany(),
'user' => $admin,
'license' => $this->util->getActiveLicense($admin->getCompany()),
'navbarTitle' => $this->translator->trans("Piezas")
]);
}
/**
* @Route({"en": "/new",
* "es": "/nueva"}, name="part_new", methods={"GET","POST"})
*/
public function new(Request $request, PartRepository $partRepository, CompanyClientRepository $ccRepository): Response
{
$admin = $this->getUser();
$part = new Part();
$part->setCompany($admin->getCompany());
$this->denyAccessUnlessGranted(PartVoter::CREATE, $part);
$em = $this->em;
$fileMaxsizes = $this->util->getCompanyFileMaxsizes($part->getCompany());
$cc = $ccRepository->findClient([],$admin)->getArrayResult();
$form = $this->createForm(PartType::class, $part, ['user_admin' => $admin, 'file_maxsizes' => $fileMaxsizes, 'cc'=>$cc]);
$form->handleRequest($request);
$errors = [];
$errorsSubmitted = [];
if ($form->isSubmitted() && $form->isValid()) {
$data = $request->request->all();
/*
"fileCadFile" => null
"fileStlFile" => Symfony\Component\HttpFoundation\File\UploadedFile {#16 ▶}
"fileFabFile" => null
"fileVerifFile" => null
"file2dFile" => null
"fileOthers" => []
*/
/*
"encryptSTL" => "1"
"encryptCAD" => "1"
"encryptFAB" => "1"
"encryptVER" => "1"
"encrypt2D" => "1"
"encryptOthers" => "1"
*/
/*$encryptSTL = $request->request->get('encryptSTL', false);
$encryptCAD = $request->request->get('encryptCAD', false);
$encryptFAB = $request->request->get('encryptFAB', false);
$encryptVER = $request->request->get('encryptVER', false);
$encrypt2D = $request->request->get('encrypt2D', false);
$encryptOthers = $request->request->get('encryptOthers', false);*/
$optionsEncrypt = [
'encryptSTL' => (isset($request->request->get('part')['encryptSTL'])) ? $request->request->get('part')['encryptSTL'] : null,
'encryptCAD' => (isset($request->request->get('part')['encryptCAD'])) ? $request->request->get('part')['encryptCAD'] : null,
'encryptFAB' => (isset($request->request->get('part')['encryptFAB'],)) ? $request->request->get('part')['encryptFAB'] : null,
'encryptVER' => (isset($request->request->get('part')['encryptVER'],)) ? $request->request->get('part')['encryptVER'] : null,
'encrypt2D' => (isset($request->request->get('part')['encrypt2D'],)) ? $request->request->get('part')['encrypt2D'] : null,
'encryptOthers' => (isset($request->request->get('part')['encryptOthers'])) ? $request->request->get('part')['encryptOthers'] : null,
];
$libraryIds = $request->request->get('libraryIds',null);
$company = $form->get('company')->getData();
if(is_string($company)){
$company = $admin->getCompany();
}
$supplier = $form->get('supplier')->getData();
//límites licencia
if(!($admin->getRole()=='ROLE_ADMIN')){
$licenseLimit = $this->util->getLicenseField($admin->getCompany(),'part_num');
$currentNum = count($em->getRepository(Part::class)->findBy(['company'=>$admin->getCompany()]));
if(!$licenseLimit || ($currentNum>=$licenseLimit)){
$this->addFlash('danger', $this->translator->trans('Ha alcanzado el límite de {name} para su licencia.',['{name}'=>$this->translator->trans('piezas')]));
return $this->redirectToRoute('part_index');
}
}
$fileStl = $form->get('fileStlFile')->getData();
if($fileStl){
$fileName = explode('.', $fileStl->getClientOriginalName());
if($fileName){
$fileExt = $fileName[count($fileName)-1];
if(strtoupper($fileExt)!='STL'){
$this->addFlash('error', $this->translator->trans('El archivo Stl adjunto no tiene la extensión correcta'));
return $this->redirectToRoute('part_index');
}
}
}
$name= $form->get('name')->getData();
$nameExists = $partRepository->nameExists($name,$company->getId());
if($nameExists){
$errorMsg = $this->translator->trans('El nombre de la pieza ya existe');
$errors['tab_datosbasicos']['name'][]=$errorMsg;
$errorsSubmitted['name'][]=$errorMsg;
$this->addFlash('error', $errorMsg);
}
else{
$this->processOtherFiles($form, $part, 5, !empty($optionsEncrypt['encryptOthers']));
$this->processFiles($form,$part,false, $optionsEncrypt);
$lastRef = $partRepository->findLastRef($company);
$part->setSupplier($supplier);
$part->setRef($lastRef);
$part->setVersion(1);
$part->setAutor($admin->getName());
//START Equipos y materiales
$eid = $form->get('equipment_id')->getData();
$mid = $form->get('material_id')->getData();
$equipo = $form->get('equipo')->getData();
$material = $form->get('material')->getData();
if($eid>0 && $eid==$equipo){
$entity = $em->getRepository(Equipment::class)->find($eid);
if($entity){
$equipo = $entity->getName();
$part->setEquipmentId($entity);
}
}
else{
$eid = null;
$part->setEquipmentId(null);
}
if($mid>0 && $mid==$material){
$entity = $em->getRepository(Material::class)->find($mid);
if($entity){
$material = $entity->getName();
$part->setMaterialId($entity);
}
}
else{
$mid = null;
$part->setMaterialId(null);
}
$part->setEquipo($equipo);
$part->setMaterial($material);
//END Equipos y materiales
//Check supplier collab
if($company && $supplier && !$this->csRepository->collabExist($company,$supplier)){
$cs = new CompanySupplier();
$cs->setCompany($company);
$cs->setSupplier($supplier);
$cs->setConfigStepBudget(true);
$cs->setConfigStepChiefConfirm(true);
$cs->setConfigStepInDelivery(true);
$cs->setType(2);
$cs->setCollab(true);
$cs->setMarketplace(true);
$em->persist($cs);
}
$em->persist($part);
$em->flush();
$this->partService->updateLibs($part,$libraryIds);
if($part->getFileStl()) {
$reader = STLReader::forFile('parts/'.$part->getFileStl());
$reader->setHandler(new VolumeHandler());
$volume = $reader->readModel();
$reader->setHandler(new SurfaceHandler());
$surface = $reader->readModel();
$reader->setHandler(new DimensionsHandler());
$dimension = $reader->readModel();
$stlData = array(
'volumen' => $volume,
'surface' => $surface,
'dimension' => $dimension
);
$part->setData(json_encode($stlData));
$em->persist($part);
$em->flush();
}
$this->addFlash('success', $this->translator->trans('Pieza creada correctamente'));
$data['message']='Nueva pieza creada';
$data['name']=$part->getName();
$data['reference']=$part->getRef();
$data['path_name']='part_show';
$data['path_parameters']='id:'.$part->getId();
$this->util->notifications($part->getCompany(), 2, $data, $this->getUser());
return $this->redirectToRoute('part_index');
}
}
elseif ($form->isSubmitted()){
$errors = $this->partService->processTabErrors($form);
$this->addFlash('error', $this->translator->trans('Ha habido un error al procesar el formulario, revise los campos'));
}
return $this->render('part/new.html.twig', [
'user' => $admin,
'part' => $part,
'fileMaxsizes' => $fileMaxsizes,
'form' => $form->createView(),
'errors' => json_encode($errors),
'errorsSubmitted' => json_encode($errorsSubmitted),
'license' => $this->util->getActiveLicense($admin->getCompany()),
'navbarTitle' => $this->translator->trans("Crear nueva pieza")
]);
}
/**
* @Route({"en": "/show/{id}",
* "es": "/mostrar/{id}"}, name="part_show", methods={"GET", "POST"})
*/
public function show(Request $request, Part $part, PartRepository $partRepository): Response
{
$this->denyAccessUnlessGranted(PartVoter::VIEW, $part);
$em = $this->em;
$user = $this->getUser();
//Libraries
$libraries = [];
foreach($part->getLibraries() as $library){
$libraries[] = $this->libService->getFullPath($library);
}
if($request->query->get('download')){
$pdfData = $this->htmlForPdf($part,$user);
return new PdfResponse(
$this->pdf->getOutputFromHtml($pdfData['html'], $pdfData['options']),
$part->getRef().'.pdf'
);
}
if ($request->isMethod('POST')) {
if($request->request->get('part_copy_submit')){
//Versionar
$newPart = clone $part;
$newPart->setId(null);
$company = $part->getCompany();
$ref = $part->getRef();
$splits = explode("-", $ref);
$refPartNumber = $splits[1];
$version = $partRepository->setAmount($refPartNumber, $part->getCompany(), $user);
$splits[2] = $version;
$newPart->setVersion(ltrim($version, "0"));
$newRef = implode("-", $splits);
$newPart->setEditRef($newRef);
$newPart->setAutor($user->getName());
$newPart->setLocked(null);
$newPart->markAsCreatedAt();
$em->persist($newPart);
$em->flush();
$this->addFlash('success', $this->translator->trans('Versión de pieza creada correctamente'));
return $this->redirectToRoute('part_index');
}
if($request->request->get('libraries_update')){
$libraryIds = $request->request->get('libraryIds',null);
$this->partService->updateLibs($part,$libraryIds);
$this->addFlash('success', $this->translator->trans('Bibliotecas editadas correctamente'));
return $this->redirectToRoute('part_show',['id'=>$part->getId()]);
}
}
return $this->render('part/show.html.twig', [
'part' => $part,
'libraries' => $libraries,
'user' => $user,
'edit' => $this->isGranted(PartVoter::EDIT, $part),
'navbarTitle' => $this->translator->trans("Pieza").' - '.$part->getName() . ($part->getVersion()>1 ? ' V'.$part->getVersion() : '')
]);
}
/**
* @Route({"en": "/edit/{id}",
* "es": "/editar/{id}"}, name="part_edit", methods={"GET","POST"})
*/
public function edit(Request $request, Part $part, PartRepository $partRepository, string $partDir, CompanyClientRepository $ccRepository): Response
{
$admin = $this->getUser();
$this->denyAccessUnlessGranted(PartVoter::EDIT, $part);
$em = $this->em;
$fileMaxsizes = $this->util->getCompanyFileMaxsizes($part->getCompany());
$cc = $ccRepository->findClient([],$admin)->getArrayResult();
$form = $this->createForm(PartType::class, $part, ['user_admin' => $admin, 'file_maxsizes' => $fileMaxsizes, 'cc'=>$cc]);
$form->handleRequest($request);
$errors = [];
$errorsSubmitted = [];
if ($form->isSubmitted() && $form->isValid()) {
$actionType = $request->request->get('submit');
$libraryIds = $request->request->get('libraryIds',null);
$company = $part->getCompany();
$supplier = $form->get('supplier')->getData();
$cc = $form->get('client_name')->getData();
$fileStl = $form->get('fileStlFile')->getData();
if($fileStl){
$fileName = explode('.', $fileStl->getClientOriginalName());
if($fileName){
$fileExt = $fileName[count($fileName)-1];
if(strtoupper($fileExt)!='STL'){
$this->addFlash('error', $this->translator->trans('El archivo Stl adjunto no tiene la extensión correcta'));
return $this->redirectToRoute('part_index');
}
}
}
$optionsEncrypt = [
'encryptSTL' => (isset($request->request->get('part')['encryptSTL'])) ? $request->request->get('part')['encryptSTL'] : null,
'encryptCAD' => (isset($request->request->get('part')['encryptCAD'])) ? $request->request->get('part')['encryptCAD'] : null,
'encryptFAB' => (isset($request->request->get('part')['encryptFAB'],)) ? $request->request->get('part')['encryptFAB'] : null,
'encryptVER' => (isset($request->request->get('part')['encryptVER'],)) ? $request->request->get('part')['encryptVER'] : null,
'encrypt2D' => (isset($request->request->get('part')['encrypt2D'],)) ? $request->request->get('part')['encrypt2D'] : null,
'encryptOthers' => (isset($request->request->get('part')['encryptOthers'])) ? $request->request->get('part')['encryptOthers'] : null,
];
$this->processOtherFiles($form, $part, 5, !empty($optionsEncrypt['encryptOthers']));
$this->processFiles($form,$part,$actionType==1, $optionsEncrypt);
//START Equipos y materiales
$eid = $form->get('equipment_id')->getData();
$mid = $form->get('material_id')->getData();
$equipo = $form->get('equipo')->getData();
$material = $form->get('material')->getData();
if($eid>0 && $eid==$equipo){
$entity = $em->getRepository(Equipment::class)->find($eid);
if($entity){
$equipo = $entity->getName();
$part->setEquipmentId($entity);
}
}
else{
$eid = null;
$part->setEquipmentId(null);
}
if($mid>0 && $mid==$material){
$entity = $em->getRepository(Material::class)->find($mid);
if($entity){
$material = $entity->getName();
$part->setMaterialId($entity);
}
}
else{
$mid = null;
$part->setMaterialId(null);
}
$part->setEquipo($equipo);
$part->setMaterial($material);
//END Equipos y materiales
//Check supplier collab
if($company && $supplier && !$this->csRepository->collabExist($company,$supplier)){
$cs = new CompanySupplier();
$cs->setCompany($company);
$cs->setSupplier($supplier);
$cs->setConfigStepBudget(true);
$cs->setConfigStepChiefConfirm(true);
$cs->setConfigStepInDelivery(true);
$cs->setType(2);
$cs->setCollab(true);
$cs->setMarketplace(true);
$em->persist($cs);
}
//Process client
if(!empty($cc['choiceType']) || !empty($cc['choiceInput'])){
if(!empty($cc['choiceType'])){
$cc = $em->getRepository(CompanyClient::class)->find($cc['choiceType']);
if($cc){
$part->setCompanyClient($cc);
}
}
else{
$part->setClientName($cc['choiceInput']);
}
}
if($actionType==1){
//Guardar
$part->setSupplier($supplier);
$part->markAsUpdated();
$em->persist($part);
$em->flush();
$this->partService->updateLibs($part,$libraryIds);
$this->addFlash('success', $this->translator->trans('Pieza editada correctamente'));
$data['message']='Pieza editada';
$data['name']=$part->getName();
$data['reference']=$part->getRef();
$data['path_name']='part_show';
$data['path_parameters']='id:'.$part->getId();
$this->util->notifications($part->getCompany(), 2, $data, $this->getUser(),$part->getId());
}
else{
//Versionar
$newPart = clone $part;
$em->refresh($part);
$newPart->setSupplier($supplier);
$newPart->setId(null);
$ref = $part->getRef();
$splits = explode("-", $ref);
$refPartNumber = $splits[1];
$version = $partRepository->setAmount($refPartNumber, $part->getCompany(), $admin);
$splits[2] = $version;
$newPart->setVersion(ltrim($version, "0"));
$newRef = implode("-", $splits);
$newPart->setEditRef($newRef);
$newPart->setAutor($admin->getName());
$newPart->setLocked(null);
$newPart->markAsCreatedAt();
$newPart->markAsUpdated();
$em->persist($newPart);
$em->flush();
$this->partService->updateLibs($newPart, $libraryIds);
$this->addFlash('success', $this->translator->trans('Versión de pieza creada correctamente'));
$data['message']='Pieza versionada';
$data['name']=$part->getName();
$data['reference']=$part->getRef();
$data['path_name']='part_show';
$data['path_parameters']='id:'.$part->getId();
$this->util->notifications($part->getCompany(), 2, $data, $this->getUser());
}
//START Process remove
$partToRemove = $actionType==2 && $newPart ? $newPart : $part;
if(!empty($request->request->get('filesToDelete'))){
$fields = explode(',',$request->request->get('filesToDelete'));
foreach($fields as $field){
if($field){
$this->processRm($partToRemove, $field);
}
}
}
if(!empty($request->request->get('filesOthersToDelete')) || $request->request->get('filesOthersToDelete')==='0'){
$indexes = explode(',',$request->request->get('filesOthersToDelete'));
$this->processRm($partToRemove, 'others', $indexes);
}
//END Process remove
return $this->redirectToRoute('part_index');
}
elseif ($form->isSubmitted()){
$errors = $this->partService->processTabErrors($form);
$this->addFlash('error', $this->translator->trans('Ha habido un error al procesar el formulario, revise los campos'));
}
return $this->render('part/edit.html.twig', [
'user' => $admin,
'part' => $part,
'fileMaxsizes' => $fileMaxsizes,
'form' => $form->createView(),
'errors' => json_encode($errors),
'errorsSubmitted' => json_encode($errorsSubmitted),
'license' => $this->util->getActiveLicense($admin->getCompany()),
'navbarTitle' => $this->translator->trans("Editar pieza").' - '.$part->getName() . ($part->getVersion()>1 ? ' V'.$part->getVersion() : '')
]);
}
private function processRm(Part $part, $field, $indexes=[]){
$result = ['error'=>false, 'msg'=>''];
$em = $this->em;
$fs = new Filesystem();
$ds = DIRECTORY_SEPARATOR;
$fields = [
'cad'=>'FileCad',
'stl'=>'FileStl',
'fab'=>'FileFab',
'verif'=>'FileVerif',
'2d'=>'File2d',
'others'=>'FileOthers'];
if(!empty($fields[$field])){
$getter = 'get'.$fields[$field];
$setter = 'set'.$fields[$field];
$fileToRemove = $part->$getter();
$filesToRemove = [];
$setterData = null;
if($field == 'others'){
if(count($indexes)>0){
$filenames = explode(',',$fileToRemove);
foreach($indexes as $index){
if($index != '' && !empty($filenames[$index])){
$filesToRemove[] = $filenames[$index];
unset($filenames[$index]);
}
}
$setterData = count($filenames)>0 ? implode(',',$filenames) : null;
}
}
else{
$filesToRemove[]=$fileToRemove;
}
foreach($filesToRemove as $fileToRemove){
if($fileToRemove){
$part->$setter($setterData);
$em->flush();
//Verificamos si el archivo se usa en otra pieza versionada
$fileInVersions = $this->partService->fileInVersions($part,$field,$fileToRemove);
if(!$fileInVersions && $fs->exists($this->partDir.$ds.$fileToRemove)){
try {
$fs->remove($this->partDir.$ds.$fileToRemove);
} catch (IOExceptionInterface $exception) {
$result = ['error'=>true,'msg'=>$this->translator->trans('No se ha podido eliminar el archivo')];
}
}
}
}
}
return $result;
}
private function processOtherFiles(FormInterface $form, Part $part, $limit=5, $encrypt = false){
$files = $form->get('fileOthers')->getData();
if(count($files)>0){
$slugger = new AsciiSlugger();
$filenames = !empty($part->getFileOthers()) ? explode(',',$part->getFileOthers()) : [];
try {
foreach($files as $file)
{
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = $slugger->slug($originalFilename);
$newFilename = $safeFilename.'-'.uniqid().'.'.$file->getClientOriginalExtension();
if(!in_array($newFilename,$filenames)){
if(count($filenames)>$limit){
$this->addFlash('warning', $this->translator->trans('Se excedió el ḿaximo de archivos que se pueden cargar'));
break;
}
else{
$file->move($this->partDir, $newFilename);
if ($encrypt){
try {
$this->encryptDecryptService->encryptData($newFilename);
$newFilename = $newFilename.'.packaged';
} catch (\Exception $e) {
$this->addFlash('warning', $e->getMessage());
}
}
$filenames[]=$newFilename;
$part->setFileOthers(implode(',',$filenames));
}
}
}
}
catch (FileException $e) {
$this->addFlash('danger', $this->translator->trans('Fallo en la carga de fichero'));
}
}
}
private function processFiles(FormInterface $form, Part $part, bool $checkVersions=false, $optionsEncrypt=[]){
$fs = new Filesystem;
$ds = DIRECTORY_SEPARATOR;
$slugger = new AsciiSlugger();
$fields = [
'fileCadFile'=>'FileCad',
'fileStlFile'=>'FileStl',
'fileFabFile'=>'FileFab',
'fileVerifFile'=>'FileVerif',
'file2dFile'=>'File2d'];
$encryptFields = [
'fileCadFile'=>'encryptCAD',
'fileStlFile'=>'encryptSTL',
'fileFabFile'=>'encryptFAB',
'fileVerifFile'=>'encryptVER',
'file2dFile'=>'encrypt2D'
];
foreach($fields as $field=>$aux){
$setter = 'set'.$aux;
$getter = 'get'.$aux;
$file = $form->get($field)->getData();
if ($file) {
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = $slugger->slug($originalFilename);
$newFilename = $safeFilename.'-'.uniqid().'.'.($field=='fileStlFile' ? 'stl' : $file->getClientOriginalExtension());
try {
$file->move($this->partDir,$newFilename);
if(!empty($optionsEncrypt[$encryptFields[$field]])){
try {
$this->encryptDecryptService->encryptData($newFilename);
$newFilename = $newFilename.'.packaged';
} catch (\Exception $e) {
$this->addFlash('warning', $e->getMessage());
}
}
//dd($this->partDir, $newFilename, $optionsEncrypt);
} catch (FileException $e) {
$this->addFlash('danger', $this->translator->trans('Fallo en la carga de fichero').' ['.$e->getMessage().']');
}
if($checkVersions && !empty($part->$getter())){
//Verificamos si el archivo se usa en otra pieza versionada
$fileInVersions = $this->partService->fileInVersions($part, strtolower(str_replace('File','',$aux)), $part->$getter());
$oldFilePath = $this->partDir.$ds.$part->$getter();
if(!$fileInVersions && $fs->exists($oldFilePath)){
try {
$fs->remove($oldFilePath);
} catch (IOExceptionInterface $e) {
$this->addFlash('warning', $this->translator->trans('No se ha podido eliminar el archivo'));
}
}
}
$part->$setter($newFilename);
if($aux=='FileStl'){
$part->setFilePreview(null);
}
}
}
}
/**
* @Route({"en": "/delete/{id}",
* "es": "/borrar/{id}"}, name="part_delete", methods={"DELETE"})
*/
public function delete(Request $request, Part $part): Response
{
$this->denyAccessUnlessGranted(PartVoter::DELETE, $part);
if($request->request->get('redirect_to_name')){
if($request->request->get('redirect_to_id')){
$redirect_to = $this->redirectToRoute(
$request->request->get('redirect_to_name'),
['id'=>$request->request->get('redirect_to_id')]);
}
else{
$redirect_to = $this->redirectToRoute($request->request->get('redirect_to_name'));
}
}
else{
$redirect_to = $this->redirectToRoute('part_index');
}
if ($this->isCsrfTokenValid('delete' . $part->getId(), $request->request->get('_token'))) {
$rmPart = $this->partService->rmPart($part);
if($rmPart['error']){
$this->addFlash('danger', $rmPart['msg']);
}
else{
$this->addFlash('success', $this->translator->trans('Pieza eliminada correctamente'));
}
}
return $redirect_to;
}
/**
* @Route({"en": "/preview/{id}",
* "es": "/preview/{id}"}, name="part_preview", methods={"POST"})
*/
public function partPreview(Request $request, Part $part): Response
{
$this->denyAccessUnlessGranted(PartVoter::VIEW, $part);
$result = ['error'=>false,'msg'=>'','data'=>''];
$fs = new Filesystem();
$ds = DIRECTORY_SEPARATOR;
$em = $this->em;
$file = $request->request->get('file');
if ($file && $part) {
$filedata = explode(',', $file);
if(count($filedata)==2){
$filename = 'part_peview_' . $part->getId() . '.jpg';
$result['file']=$filedata[1];
$filedata = base64_decode($filedata[1]);
$filepath = $this->partDir. $ds . $filename;
//if(!$fs->exists($filepath)){
$fs->dumpFile($filepath, $filedata);
$part->setFilePreview($filename);
$em->flush();
//}
}
}
return new JsonResponse($result);
}
/**
* @Route({"en": "/lock_unlock/{id}",
* "es": "/bloquear_desbloquear/{id}"}, name="part_lock_unlock", methods={"POST"})
*/
public function lockUnlock(Request $request, Part $part): Response
{
$this->denyAccessUnlessGranted(PartVoter::DELETE, $part);
if ($this->isCsrfTokenValid('delete' . $part->getId(), $request->request->get('_token'))) {
$em = $this->em;
if($part->getLocked()){
$part->setLocked(false);
}
else{
$part->setLocked(true);
}
$part->setLockedAt(new \DateTime());
$part->setLockedUser($this->getUser());
$em->flush();
$successMsg = $part->getLocked() ? 'Pieza bloqueada correctamente' : 'Pieza desbloqueada correctamente';
$this->addFlash('success', $this->translator->trans($successMsg));
}
if($request->query->get('lib')){
return $this->redirectToRoute('library_show',['id'=>$request->query->get('lib')]);
}
else{
return $this->redirectToRoute('part_index');
}
}
/**
* @Route({"en": "/export/{library?}",
* "es": "/exportar/{library?}"}, name="part_export" , methods={"GET"})
*/
public function export(Request $request, PartRepository $partRepository, ?Library $library = null, ?int $part)
{
$trans = $this->translator;
if (null !== $library) {
$filename = 'AD2_'.$trans->trans('librería').'_' . $library->getName() . '_' . date("dmY.His") . ".xlsx";
} else {
if (null !== $part) {
$filename = 'AD2_'.$trans->trans('pieza').'_' . $part->getRef() . '_' . date("dmY.His") . ".xlsx";
} else {
$filename = 'AD2_'.$trans->trans('listado').'_'.$trans->trans('piezas').'_' . date("dmY.His") . ".xlsx";
}
}
$part = null;
if (null !== $request->query->get('id')) {
$part = $partRepository->find($request->query->get('id'));
}
$spreadsheet = $this->generateXls($library,$partRepository,$part);
$writer = new Xlsx($spreadsheet);
$response = new StreamedResponse(
function () use ($writer) {
$writer->save('php://output');
}
);
$response->headers->set('Content-Type', 'application/vnd.ms-excel');
$response->headers->set('Content-Disposition', 'attachment;filename="' . $filename);
$response->headers->set('Cache-Control', 'max-age=0');
return $response;
}
/**
* @Route({"en": "/import",
* "es": "/importar"}, name="part_import" , methods={"GET", "POST"})
*/
public function import(Request $request, PartRepository $partRepository, string $excelDir, string $partDir)
{
$this->denyAccessUnlessGranted(PartVoter::IMPORT, new Part);
$fs = new Filesystem();
$admin = $this->getUser();
$licenseLimit = 0;
//límites licencia
if(!($admin->getRole()=='ROLE_ADMIN')){
$lc =$this->em->getRepository(LicenseCompany::class)->findOneBy(['company'=>$admin->getCompany(),'state'=>2]);
if($lc){
$licenseData = $this->util->getCompanySuscriptionAvailable($lc);
if(!empty($licenseData['parts']['available'])){
$licenseLimit=intval($licenseData['parts']['available']);
}
}
}
else{
$licenseLimit=-1;
}
$report = ['loaded'=>[],'errors'=>[]];
$part = new Part();
$form = $this->createForm(PartImportType::class, $part, ['user_admin' => $admin]);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$filenames = [];
$up = 0;
if ($stlFiles = $form['stlFiles']->getData()) {
try {
if(!$fs->exists($partDir)){
$fs->mkdir($partDir);
}
foreach($stlFiles as $stl)
{
$ext = $stl->getClientOriginalExtension();
if ($ext == 'stl') {
$fileName = pathinfo($stl->getClientOriginalName(), PATHINFO_FILENAME);
$filenames[$up][0] = $fileName;
$fileName = $fileName . '_' . date("dmY.His") . '.' . $ext;
$filenames[$up][1] = $fileName;
$stl->move($partDir, $fileName);
$up++;
}
}
}catch (FileException $e) {
$this->addFlash('danger', $this->translator->trans('Fallo en la carga masiva de fichero STL').' : '.$e->getMessage());
return $this->redirectToRoute('part_import');
}
catch (IOExceptionInterface $e) {
$this->addFlash('danger', $this->translator->trans('Fallo en la carga masiva de fichero STL').' : '.$e->getPath());
return $this->redirectToRoute('part_import');
}
}
if(empty($filenames) || (empty($form['excelFile']->getData()) || $form['excelFile']->getData()->guessExtension()!='xlsx')){
$this->addFlash('danger', $this->translator->trans('Los ficheros Excel y STL son requeridos y deben ser del tipo establecido'));
return $this->redirectToRoute('part_import');
}
if ($excel = $form['excelFile']->getData()) {
try {
if(!$fs->exists($excelDir)){
$fs->mkdir($excelDir);
}
//cogemos la extensión y comprobamos antes de continuar
$fileName = pathinfo($excel->getClientOriginalName(), PATHINFO_FILENAME);
$fileName = $fileName . '_' . date("dmY.His") . '.xlsx';
$excel->move($excelDir, $fileName);
$routeFileName = $excelDir . '/' . $fileName;
/** Identify the type of $inputFileName **/
$inputFileType = IOFactory::identify($routeFileName);
/** Create a new Reader of the type that has been identified **/
$reader = IOFactory::createReader($inputFileType);
$reader->setReadDataOnly(false);
/** Load $inputFileName to a Spreadsheet Object **/
$spreadsheet = $reader->load($routeFileName);
$sheet = $spreadsheet->getActiveSheet();
$x = 0;
$z = 0;
foreach ($sheet->getColumnIterator() as $column) {
$cellIterator = $column->getCellIterator();
foreach ($cellIterator as $cell) {
$value = $cell->getValue();
$piezaMasiva[$x][$z] = $value;
$z++;
}
if($x !== 0){
$company = $admin->getCompany();
$partName = $piezaMasiva[$x][1];
if($piezaMasiva[$x][1] == ''){
$this->importReportProcess($report);
return $this->redirectToRoute('part_index');
}
$nameExists = $partRepository->nameExists($partName,$company->getId());
if($nameExists){
$report['errors'][1][] = $piezaMasiva[$x][1];
}
elseif($licenseLimit==0){
$report['errors'][3] = true;
break;
}
else{
$newMasivePart = new Part();
$newMasivePart->setBulkImportFile($fileName);
//Datos Básicos
$newMasivePart->setCompany($company);
$newMasivePart->setName($piezaMasiva[$x][1]);
$piezaMasiva[$x][2] == '' ? null : $newMasivePart->setDescription($piezaMasiva[$x][2]);
$piezaMasiva[$x][3] == '' ? null : $newMasivePart->setClientName($piezaMasiva[$x][3]);
$piezaMasiva[$x][4] == '' ? null : $newMasivePart->setClientRefPart($piezaMasiva[$x][4]);
$piezaMasiva[$x][5] == '' ? null : $newMasivePart->setPartNumber($piezaMasiva[$x][5]);
$piezaMasiva[$x][6] == '' ? null : $newMasivePart->setSerial($piezaMasiva[$x][6]);
$piezaMasiva[$x][7] == '' ? null : $newMasivePart->setNotes($piezaMasiva[$x][7]);
//Fabricacion
$piezaMasiva[$x][10] == '' ? null : $newMasivePart->setTechnology($piezaMasiva[$x][10]);
$piezaMasiva[$x][11] == '' ? null : $newMasivePart->setEquipo($piezaMasiva[$x][11]);
$piezaMasiva[$x][12] == '' ? null : $newMasivePart->setMaterial($piezaMasiva[$x][12]);
$piezaMasiva[$x][13] == '' ? null : $newMasivePart->setPrintMode($piezaMasiva[$x][13]);
$piezaMasiva[$x][14] == '' ? null : $newMasivePart->setAlturaCapa($piezaMasiva[$x][14]);
$piezaMasiva[$x][15] == '' ? null : $newMasivePart->setAlturaCapaTol($piezaMasiva[$x][15]);
$piezaMasiva[$x][16] == '' ? null : $newMasivePart->setDiamBoquilla($piezaMasiva[$x][16]);
$piezaMasiva[$x][17] == '' ? null : $newMasivePart->setDiamBoquillaTol($piezaMasiva[$x][17]);
$piezaMasiva[$x][18] == '' ? null : $newMasivePart->setTmpBoquilla($piezaMasiva[$x][18]);
$piezaMasiva[$x][19] == '' ? null : $newMasivePart->setTmpBoquillaTol($piezaMasiva[$x][19]);
$piezaMasiva[$x][20] == '' ? null : $newMasivePart->setTmpCama($piezaMasiva[$x][20]);
$piezaMasiva[$x][21] == '' ? null : $newMasivePart->setTmpCamaTol($piezaMasiva[$x][21]);
$piezaMasiva[$x][22] == '' ? null : $newMasivePart->setTmpCamara($piezaMasiva[$x][22]);
$piezaMasiva[$x][23] == '' ? null : $newMasivePart->setTmpCamaraTol($piezaMasiva[$x][23]);
$piezaMasiva[$x][24] == '' ? null : $newMasivePart->setVelocidadImpresion($piezaMasiva[$x][24]);
$piezaMasiva[$x][25] == '' ? null : $newMasivePart->setVelocidadImpresionTol($piezaMasiva[$x][25]);
$piezaMasiva[$x][26] == '' ? null : $newMasivePart->setPerimetroRelleno($piezaMasiva[$x][26]);
$piezaMasiva[$x][27] == '' ? null : $newMasivePart->setSoportes($piezaMasiva[$x][27]);
$piezaMasiva[$x][28] == '' ? null : $newMasivePart->setPuntoLaser($piezaMasiva[$x][28]);
$piezaMasiva[$x][29] == '' ? null : $newMasivePart->setPuntoLaserTol($piezaMasiva[$x][29]);
$piezaMasiva[$x][30] == '' ? null : $newMasivePart->setPotenciaFuente($piezaMasiva[$x][30]);
$piezaMasiva[$x][31] == '' ? null : $newMasivePart->setPotenciaFuenteTol($piezaMasiva[$x][31]);
$piezaMasiva[$x][32] == '' ? null : $newMasivePart->setTamPixel($piezaMasiva[$x][32]);
$piezaMasiva[$x][33] == '' ? null : $newMasivePart->setTamPixelTol($piezaMasiva[$x][33]);
$piezaMasiva[$x][34] == '' ? null : $newMasivePart->setTiempoExpos($piezaMasiva[$x][34]);
$piezaMasiva[$x][35] == '' ? null : $newMasivePart->setTiempoExposTol($piezaMasiva[$x][35]);
$piezaMasiva[$x][36] == '' ? null : $newMasivePart->setDistanHatch($piezaMasiva[$x][36]);
$piezaMasiva[$x][37] == '' ? null : $newMasivePart->setDistanHatchTol($piezaMasiva[$x][37]);
$piezaMasiva[$x][38] == '' ? null : $newMasivePart->setVelocidadRecoater($piezaMasiva[$x][38]);
$piezaMasiva[$x][39] == '' ? null : $newMasivePart->setVelocidadRecoaterTol($piezaMasiva[$x][39]);
$piezaMasiva[$x][40] == '' ? null : $newMasivePart->setEnfriamiento($piezaMasiva[$x][40]);
$piezaMasiva[$x][41] == '' ? null : $newMasivePart->setAtmosfera($piezaMasiva[$x][41]);
$piezaMasiva[$x][42] == '' ? null : $newMasivePart->setSaturacion($piezaMasiva[$x][42]);
$piezaMasiva[$x][43] == '' ? null : $newMasivePart->setObservacionesFab($piezaMasiva[$x][43]);
//Validación
$piezaMasiva[$x][46] == '' ? null : $newMasivePart->setCompMatPrima($piezaMasiva[$x][46]);
$piezaMasiva[$x][47] == '' ? null : $newMasivePart->setCertMatPrima($piezaMasiva[$x][47]);
$piezaMasiva[$x][48] == '' ? null : $newMasivePart->setColorMatPrima($piezaMasiva[$x][48]);
$piezaMasiva[$x][49] == '' ? null : $newMasivePart->setCertProceso($piezaMasiva[$x][49]);
$piezaMasiva[$x][50] == '' ? null : $newMasivePart->setCertPart($piezaMasiva[$x][50]);
$piezaMasiva[$x][51] == '' ? null : $newMasivePart->setApplicableRegulations($piezaMasiva[$x][51]);
$piezaMasiva[$x][52] == '' ? null : $newMasivePart->setProcAcabado($piezaMasiva[$x][52]);
$piezaMasiva[$x][53] == '' ? null : $newMasivePart->setOtrosTrat($piezaMasiva[$x][53]);
$piezaMasiva[$x][54] == '' ? null : $newMasivePart->setObsVal($piezaMasiva[$x][54]);
//stl
$stlFound = false;
if($piezaMasiva[$x][57] !== ''){
foreach($filenames as $k=>$name){
$fn = $piezaMasiva[$x][57];
if(strrpos($fn, ".")){
$fn = substr($fn, 0, (strrpos($fn, ".")));
}
if($name[0] == $fn){
unset($filenames[$k]);
$newMasivePart->setFileStl($name[1]);
$stlFound = true;
break;
}
}
}
if(!$stlFound){
$report['errors'][2][] = $piezaMasiva[$x][1];
}
else{
//Dependientes
$newMasivePart->setRef($partRepository->findLastRef($company));
$newMasivePart->setVersion(1);
$newMasivePart->setAutor($admin->getName());
$entityManager = $this->em;
$entityManager->persist($newMasivePart);
$entityManager->flush();
$report['loaded'][] = $piezaMasiva[$x][1];
$licenseLimit--;
}
}
}
$x++;
$z = 0;
}
} catch (FileException $e) {
$this->addFlash('danger', $this->translator->trans('Fallo en la carga masiva de piezas').' : '.$e->getMessage());
return $this->redirectToRoute('part_import');
}
catch (IOExceptionInterface $e) {
$this->addFlash('danger', $this->translator->trans('Fallo en la carga masiva de piezas').' : '.$e->getPath());
return $this->redirectToRoute('part_import');
}
}
//Si quedan archivos sin asignar los eliminamos
if($filenames){
foreach($filenames as $k=>$name){
if(!empty($name[1])){
$filepath = $partDir.DIRECTORY_SEPARATOR.$name[1];
if($fs->exists($filepath)){
$fs->remove($filepath);
}
}
}
}
$this->importReportProcess($report);
return $this->redirectToRoute('part_index');
}
return $this->render('part/import.html.twig', [
'user' => $admin,
//'part' => $part,
'locale'=> $this->translator->getLocale(),
'excel_form' => $form->createView(),
'navbarTitle' => $this->translator->trans("Subida masiva de piezas")
]);
}
/**
* @Route({"en": "/zip/{library?}",
* "es": "/zip/{library?}"}, name="part_zip", methods={"GET"})
*/
public function partZip(Request $request, PartRepository $partRepository, ?Library $library = null,?int $part)
{
$user = $this->getUser();
$part = $partRepository->find($request->query->get('id'));
$part_id = $part->getId();
$company_id = $part->getCompany()->getId();
$structure = 'parts/zip/'.$company_id.'/'.$part_id;
if (!file_exists($structure)) {
if (!mkdir($structure, 0777, true)) {
die('Fallo al crear las carpetas...');
}
}
// Generate PDF
$pdfData = $this->htmlForPdf($part,$user);
$this->pdf->generateFromHtml($pdfData['html'], $structure.'/'.$part->getRef().'.pdf',$pdfData['options'],true);
// generate XLS
$trans = $this->translator;
if (null !== $library) {
$filename = 'AD2_'.$trans->trans('librería').'_' . $library->getName() .".xlsx";
} else {
if (null !== $part) {
$filename = 'AD2_'.$trans->trans('pieza').'_' . $part->getRef() .".xlsx";
} else {
$filename = 'AD2_'.$trans->trans('listado').'_'.$trans->trans('piezas').".xlsx";
}
}
$spreadsheet = $this->generateXls($library,$partRepository,$part);
$writer = new Xlsx($spreadsheet);
$writer->save($structure.'/'.$filename);
$basename = preg_replace('/[^a-zA-Z0-9_\-\s]/', '', $part->getName());
$basename = str_replace(' ', '-', $basename);
$basename = $part->getRef().'_'.$basename;
$basename = substr($basename, 0, 40);
// ZIP all
$zipName = $basename.'.zip';
$zip = new \ZipArchive();
if ($zip->open($structure.'/'.$zipName, $zip::CREATE) === TRUE)
{
if($part->getFileStl() && file_exists('parts/'.$part->getFileStl())) {
$zip->addFile('parts/'.$part->getFileStl(),'files/'.$part->getFileStl());
}
if($part->getFileCad() && file_exists('parts/'.$part->getFileCad())) {
$zip->addFile('parts/'.$part->getFileCad(),'files/'.$part->getFileCad());
}
if($part->getFileFab() && file_exists('parts/'.$part->getFileFab())) {
$zip->addFile('parts/'.$part->getFileFab(),'files/'.$part->getFileFab());
}
if($part->getFileVerif() && file_exists('parts/'.$part->getFileVerif())) {
$zip->addFile('parts/'.$part->getFileVerif(),'files/'.$part->getFileVerif());
}
if($part->getFile2d() && file_exists('parts/'.$part->getFile2d())) {
$zip->addFile('parts/'.$part->getFile2d(),'files/'.$part->getFile2d());
}
if($part->getFileOthers() && file_exists('parts/'.$part->getFileOthers())) {
$zip->addFile('parts/'.$part->getFileOthers(),'files/'.$part->getFileOthers());
}
if($part->getFilePreview() && file_exists('parts/'.$part->getFilePreview())) {
$extension = pathinfo($part->getFilePreview(), PATHINFO_EXTENSION);
$zip->addFile('parts/'.$part->getFilePreview(),$basename.'.'.$extension);
}
$zip->addFile($structure.'/'.$part->getRef().'.pdf','pdfs/'.$part->getRef().'.pdf');
$zip->addFile($structure.'/'.$filename,'xls/'.$filename);
// All files are added, so close the zip file.
$zip->close();
}
// delete temporally files
unlink($structure.'/'.$part->getRef().'.pdf');
unlink($structure.'/'.$filename);
$response = new BinaryFileResponse($structure.'/'.$zipName);
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'application/zip');
$response->headers->set('Content-Disposition', 'attachment; filename="'.basename($zipName).'"');
$response->headers->set('Content-Length', filesize($structure.'/'.$zipName));
return $response;
}
public function multiplePartZip(PartRepository $partRepository,$partIds) {
$user = $this->getUser();
// generate XLS
$trans = $this->translator;
$basename = preg_replace('/[^a-zA-Z0-9_\-\s]/', '', 'AD2_Download_'.$user->getCompany()->getName());
$basename = str_replace(' ', '-', $basename);
//$basename = date('Ymdhis').'_'.$basename;
$basename = substr($basename, 0, 40);
$structure = 'parts/zipPack/user/' . $user->getId();
if (!file_exists($structure)) {
if (!mkdir($structure, 0777, true)) {
die('Fallo al crear las carpetas...');
}
}
$zipName = $basename.'.zip';
$zip = new \ZipArchive();
//borramos el existente
if(file_exists($structure.'/'.$zipName)) {
unlink($structure.'/'.$zipName);
}
if ($zip->open($structure.'/'.$zipName, $zip::CREATE) === TRUE) {
foreach ($partIds as $part_id) {
$part = $partRepository->find($part_id);
if($part) {
// Generate PDF
$pdfData = $this->htmlForPdf($part, $user);
$this->pdf->generateFromHtml($pdfData['html'], $structure . '/' . $part->getRef() . '.pdf', $pdfData['options'], true);
$filename = 'AD2_' . $trans->trans('pieza') . '_' . $part->getRef() . ".xlsx";
$foldername = 'AD2_' . $part->getRef() . '_' . $part->getName();
$foldername = preg_replace('/[^a-zA-Z0-9_\-\s]/', '', $foldername);
$foldername = str_replace(' ', '-', $foldername);
$foldername = substr($foldername, 0, 40);
$spreadsheet = $this->generateXls(null, $partRepository, $part);
$writer = new Xlsx($spreadsheet);
$writer->save($structure . '/' . $filename);
if ($part->getFileStl() && file_exists('parts/' . $part->getFileStl())) {
$zip->addFile('parts/' . $part->getFileStl(), $foldername.'/files/'. $part->getFileStl());
}
if ($part->getFileCad() && file_exists('parts/' . $part->getFileCad())) {
$zip->addFile('parts/' . $part->getFileCad(), $foldername.'/files/'. $part->getFileCad());
}
if ($part->getFileFab() && file_exists('parts/' . $part->getFileFab())) {
$zip->addFile('parts/' . $part->getFileFab(), $foldername.'/files/'. $part->getFileFab());
}
if ($part->getFileVerif() && file_exists('parts/' . $part->getFileVerif())) {
$zip->addFile('parts/' . $part->getFileVerif(), $foldername.'/files/'. $part->getFileVerif());
}
if ($part->getFile2d() && file_exists('parts/' . $part->getFile2d())) {
$zip->addFile('parts/' . $part->getFile2d(), $foldername.'/files/'. $part->getFile2d());
}
if ($part->getFileOthers() && file_exists('parts/' . $part->getFileOthers())) {
$zip->addFile('parts/' . $part->getFileOthers(), $foldername.'/files/'. $part->getFileOthers());
}
if ($part->getFilePreview() && file_exists('parts/' . $part->getFilePreview())) {
$extension = pathinfo($part->getFilePreview(), PATHINFO_EXTENSION);
$zip->addFile('parts/' . $part->getFilePreview(), 'AD2_' . $part->getRef() . '_' . $part->getName() . '.' . $extension);
}
$zip->addFile($structure . '/' . $part->getRef() . '.pdf', $foldername.'/pdfs/'. $part->getRef() . '.pdf');
$zip->addFile($structure . '/' . $filename, $foldername.'/xls/' . $filename);
}
}//endforeach
// All files are added, so close the zip file.
$zip->close();
}
foreach ($partIds as $part_id) {
if($part) {
// delete temporally files
$part = $partRepository->find($part_id);
$filename = 'AD2_' . $trans->trans('pieza') . '_' . $part->getRef() . ".xlsx";
unlink($structure . '/' . $part->getRef() . '.pdf');
unlink($structure . '/' . $filename);
}
}
return array($structure,$zipName);
}
private function importReportProcess($report){
//Loaded
$loaded = $report['loaded'];
if(empty($loaded)){
$message = $nData['message'] = 'No se han podido cargado piezas';
}
else{
$stringLoaded = implode(', ',$loaded);
$message = "Se han cargado correctamente las siguientes piezas : $stringLoaded";
$nData['message'] = "Se han cargado correctamente las siguientes piezas : {aux}";
$nData['message_aux'] = $stringLoaded;
}
$nData['path_name']='part_index';
$this->util->notifications($this->getUser()->getCompany(), 2, $nData, $this->getUser());
$this->addFlash(empty($loaded) ? 'danger' : 'success', $this->translator->trans($message));
//Errors
$errors = $report['errors'];
if(!empty($errors)){
$message = $this->translator->trans('Se han producido los siguientes errores : ');
$message.= '<br>';
if(!empty($errors[1])){
$error_1 = count($errors[1])>5 ? array_slice($errors[1],0,5).' ...' : $errors[1];
$message.= $this->translator->trans('Piezas con el nombre duplicado : ') . implode(', ',$error_1). '<br>';
}
if(!empty($errors[2])){
$error_2 = count($errors[2])>5 ? array_slice($errors[2],0,5).' ...' : $errors[2];
$message.= $this->translator->trans('Piezas sin archivo STL : ') . implode(', ',$error_2);
}
if(!empty($errors[3])){
$message.= $this->translator->trans("Se han agotado las piezas disponibles para su licencia") . '<br>';
}
$this->addFlash('danger', $this->translator->trans($message));
}
}
/**
* @param $part
* @param $user
* @return array
* HTML FOR PDF
*/
private function htmlForPdf($part,$user) {
$url = $this->generateUrl('part_show',['id'=>$part->getId()], UrlGeneratorInterface::ABSOLUTE_URL);
$qr = $this->util->generateQrCode($url);
$header = $this->renderView( 'part/pdf/pdf_header.html.twig',[
'part' => $part,
'partByCat' => $this->partService->getPartByCat($part),
'orders' => $part->getOrders(),
'qr' => $qr,
'preview' => $part->getFilePreview() ? $this->partDir . DIRECTORY_SEPARATOR . $part->getFilePreview() : '',
'user' => $user
] );
$footer = $this->renderView( 'part/pdf/pdf_footer.html.twig',[
'part' => $part,
'partByCat' => $this->partService->getPartByCat($part),
'orders' => $part->getOrders(),
'qr' => $qr,
'user' => $user
] );
$options = [
'header-html' => $header,
'footer-html' => $footer,
'page-size' => 'A4'
];
$html =$this->renderView('part/pdf/pdf.html.twig', [
'part' => $part,
'stl' => json_decode($part->getData(),true),
'partByCat' => $this->partService->getPartByCat($part),
'orders' => $part->getOrders(),
'qr' => $qr,
'user' => $user
]);
return array(
'html' =>$html,
'options' => $options
);
}
private function generateXls($library,PartRepository $partRepository,$part = null) {
$trans = $this->translator;
$admin = $this->getUser();
$company = $admin->getCompany();
$colorARGB = $company && $company->getCorporateColor() ? str_replace('#','',$company->getCorporateColor()) : 'DD9933';
$isSupplier = in_array($admin->getRole(),['ROLE_SUPPLIER_CHIEF','ROLE_SUPPLIER']);
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle(date("F j, Y"));
$row = 1;
$titles = ['A'.$row];
$sheet->setCellValue('A'.$row++, $trans->trans('Datos Básicos'));
$sheet->setCellValue('A'.$row++, $trans->trans('Autor'));
$sheet->setCellValue('A'.$row++, $trans->trans('Fecha Creación'));
$sheet->setCellValue('A'.$row++, $trans->trans('Fecha Revisión'));
$sheet->setCellValue('A'.$row++, $trans->trans('Nombre de pieza'));
$sheet->setCellValue('A'.$row++, $trans->trans('Referencia'));
if(!$isSupplier){
$sheet->setCellValue('A'.$row++, $trans->trans('Descripcion'));
$sheet->setCellValue('A'.$row++, $trans->trans('Nombre de Cliente'));
$sheet->setCellValue('A'.$row++, $trans->trans('Referencia pieza Cliente'));
$sheet->setCellValue('A'.$row++, $trans->trans('Part number'));
$sheet->setCellValue('A'.$row++, $trans->trans('Serial number'));
}
$sheet->setCellValue('A'.$row++, $trans->trans('Observaciones'));
$sheet->setCellValue('A'.$row++, '');
$titles[]='A'.$row;
$sheet->setCellValue('A'.$row++, $trans->trans('Fabricación'));
$sheet->setCellValue('A'.$row++, $trans->trans('Centro de trabajo'));
$sheet->setCellValue('A'.$row++, $trans->trans('Tecnología'));
$sheet->setCellValue('A'.$row++, $trans->trans('Equipo'));
$sheet->setCellValue('A'.$row++, $trans->trans('Material'));
$sheet->setCellValue('A'.$row++, $trans->trans('Modo impresión'));
$sheet->setCellValue('A'.$row++, $trans->trans('Altura capa (μm)') . ' [' . $trans->trans('Tolerancia').']');
$sheet->setCellValue('A'.$row++, $trans->trans('Diam. boquilla (mm)') . ' [' . $trans->trans('Tolerancia').']');
$sheet->setCellValue('A'.$row++, $trans->trans('Temperatura extrusor (ºC)') . ' [' . $trans->trans('Tolerancia').']');
$sheet->setCellValue('A'.$row++, $trans->trans('Temperatura cama (ºC)') . ' [' . $trans->trans('Tolerancia').']');
$sheet->setCellValue('A'.$row++, $trans->trans('Temperatura cámara (ºC)') . ' [' . $trans->trans('Tolerancia').']');
$sheet->setCellValue('A'.$row++, $trans->trans('Velocidad de impresión (mm/s)') . ' [' . $trans->trans('Tolerancia').']');
$sheet->setCellValue('A'.$row++, $trans->trans('Perímetros y relleno'));
$sheet->setCellValue('A'.$row++, $trans->trans('Soportes'));
$sheet->setCellValue('A'.$row++, $trans->trans('Punto láser (μm)') . ' [' . $trans->trans('Tolerancia').']');
$sheet->setCellValue('A'.$row++, $trans->trans('Potencia Fuente (%)') . ' [' . $trans->trans('Tolerancia').']');
$sheet->setCellValue('A'.$row++, $trans->trans('Tamaño pixel (μm)') . ' [' . $trans->trans('Tolerancia').']');
$sheet->setCellValue('A'.$row++, $trans->trans('Tiempo Exposición (s)') . ' [' . $trans->trans('Tolerancia').']');
$sheet->setCellValue('A'.$row++, $trans->trans('Distancia hatch (μm)') . ' [' . $trans->trans('Tolerancia').']');
$sheet->setCellValue('A'.$row++, $trans->trans('Velocidad recoater (mm/s)') . ' [' . $trans->trans('Tolerancia').']');
$sheet->setCellValue('A'.$row++, $trans->trans('Enfriamiento').' (h)');
$sheet->setCellValue('A'.$row++, $trans->trans('Atmósfera controlada'));
$sheet->setCellValue('A'.$row++, $trans->trans('Saturación (%)'));
$sheet->setCellValue('A'.$row++, $trans->trans('Observaciones de fabricación'));
$sheet->setCellValue('A'.$row++, '');
$titles[]='A'.$row;
$sheet->setCellValue('A'.$row++, $trans->trans('Validación'));
$sheet->setCellValue('A'.$row++, $trans->trans('Composición materia prima'));
$sheet->setCellValue('A'.$row++, $trans->trans('Certificación materia prima'));
$sheet->setCellValue('A'.$row++, $trans->trans('Color materia prima'));
$sheet->setCellValue('A'.$row++, $trans->trans('Certificación proceso'));
$sheet->setCellValue('A'.$row++, $trans->trans('Certificación pieza'));
$sheet->setCellValue('A'.$row++, $trans->trans('Normativa aplicable'));
$sheet->setCellValue('A'.$row++, $trans->trans('Procesos de acabado'));
$sheet->setCellValue('A'.$row++, $trans->trans('Otros tratamientos'));
$sheet->setCellValue('A'.$row++, $trans->trans('Observaciones'));
$sheet->setCellValue('A'.$row++, '');
$titles[]='A'.$row;
$sheet->setCellValue('A'.$row++, $trans->trans('Adjuntos'));
$sheet->setCellValue('A'.$row++, $trans->trans('Archivo CAD (.step, otros)'));
$sheet->setCellValue('A'.$row++, $trans->trans('Archivo Stl'));
$sheet->setCellValue('A'.$row++, $trans->trans('Archivo Fabricación (.gcode, .pdf, otros)'));
$sheet->setCellValue('A'.$row++, $trans->trans('Archivo Verificación (.txt, .pdf, .doc)'));
$sheet->setCellValue('A'.$row++, $trans->trans('Planos 2D (.pdf)'));
$sheet->setCellValue('A'.$row++, $trans->trans('Archivo N01'));
$sheet->setCellValue('A'.$row++, $trans->trans('Archivo N02'));
$sheet->setCellValue('A'.$row++, $trans->trans('Archivo N03'));
$sheet->setCellValue('A'.$row++, $trans->trans('Archivo N04'));
$sheet->setCellValue('A'.$row++, $trans->trans('Archivo N05'));
$sheet->setCellValue('A'.$row++, '');
if(!$isSupplier){
$titles[]='A'.$row;
$sheet->setCellValue('A'.$row++, $trans->trans('Biblioteca'));
$sheet->setCellValue('A'.$row++, $trans->trans('Bibliotecas'));
}
$sheet->setCellValue('A'.$row++, '');
$titles[]='A'.$row;
$sheet->setCellValue('A'.$row++, $trans->trans('Datos STL'));
$sheet->setCellValue('A'.$row++, $trans->trans('Volumen'));
$sheet->setCellValue('A'.$row++, $trans->trans('Superficie'));
$sheet->setCellValue('A'.$row++, $trans->trans('Altura'));
$sheet->setCellValue('A'.$row++, $trans->trans('Ancho'));
$sheet->setCellValue('A'.$row++, $trans->trans('Largo'));
//$spreadsheet->createSheet();
$styleArrayFirstRow = [
'font' => [
'bold' => true,
]
];
$highestColumn = $sheet->getHighestColumn();
$sheet->getStyle($titles[0])->applyFromArray($styleArrayFirstRow);
$sheet->getStyle($titles[1])->applyFromArray($styleArrayFirstRow);
$sheet->getStyle($titles[2])->applyFromArray($styleArrayFirstRow);
$sheet->getStyle($titles[3])->applyFromArray($styleArrayFirstRow);
if(!$isSupplier){
$sheet->getStyle($titles[4])->applyFromArray($styleArrayFirstRow);
}
//$sheet->getStyle('A')->getFont()->setBold(true);
$sheet->getColumnDimension('A')->setWidth(36);
$sheet->getDefaultColumnDimension()->setWidth(30);
$sheet->freezePaneByColumnAndRow(2, 1);
$styleArrayFirstRow = [
'font' => [
'bold' => true,
'color' => array('rgb' => 'FFFFFF'),
]
];
$sheet
->getStyle($titles[0])
->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
->getStartColor()
->setARGB($colorARGB);
$sheet->getStyle($titles[0])->applyFromArray($styleArrayFirstRow);
$sheet
->getStyle($titles[1])
->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
->getStartColor()
->setARGB($colorARGB);
$sheet->getStyle($titles[1])->applyFromArray($styleArrayFirstRow);
$sheet
->getStyle($titles[2])
->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
->getStartColor()
->setARGB($colorARGB);
$sheet->getStyle($titles[2])->applyFromArray($styleArrayFirstRow);
$sheet
->getStyle($titles[3])
->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
->getStartColor()
->setARGB($colorARGB);
$sheet->getStyle($titles[3])->applyFromArray($styleArrayFirstRow);
if(!$isSupplier){
$sheet
->getStyle($titles[4])
->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
->getStartColor()
->setARGB($colorARGB);
$sheet->getStyle($titles[4])->applyFromArray($styleArrayFirstRow);
}
$sheet
->getStyle($titles[5])
->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
->getStartColor()
->setARGB($colorARGB);
$sheet->getStyle($titles[5])->applyFromArray($styleArrayFirstRow);
$arrayParts = $partRepository->generateExport($admin, $library, $part);
$column = 2;
$row = 2;
//dd($arrayParts);
foreach ($arrayParts as $mypPart) {
//Autor
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[42]);
//Fecha creación
$sheet->setCellValueByColumnAndRow($column, $row++, ( $mypPart[73] ? $mypPart[73]->format('d-m-y H:i') : '' ));
//Fecha modificación
$sheet->setCellValueByColumnAndRow($column, $row++, ( $mypPart[73] ? $mypPart[74]->format('d-m-y H:i') : '' ));
//Nombre Pieza
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[3]);
//Referencia
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[1]);
if(!$isSupplier){
//Description
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[4]);
//Nombre de Cliente
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[7]);
//Referencia Pieza Cliente
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[8]);
//Part Number
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[2]);
//Serial Number
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[9]);
}
//Observaciones (Notes?)
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[12]);
$row++;
$row++;
//Proveedor
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[43]);
//Tecnologia
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[13]);
//Equipo
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[44]);
//Material
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[5]);
//Modo impresión
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[75]);
//Altura Capa
$sheet->setCellValueByColumnAndRow($column, $row++, ($mypPart[45] > 0 ? $mypPart[45] : '-') . ' ' . ($mypPart[76] > 0 ? '[+/-'.$mypPart[76].']' : ''));
//Diam boquilla
$sheet->setCellValueByColumnAndRow($column, $row++, ($mypPart[46] > 0 ? $mypPart[46] : '-') . ' ' . ($mypPart[77] > 0 ? '[+/-'.$mypPart[77].']' : ''));
//Tmp extrusor
$sheet->setCellValueByColumnAndRow($column, $row++, ($mypPart[47] > 0 ? $mypPart[47] : '-') . ' ' . ($mypPart[78] > 0 ? '[+/-'.$mypPart[78].']' : ''));
//Tmp cama
$sheet->setCellValueByColumnAndRow($column, $row++,($mypPart[48] > 0 ? $mypPart[48] : '-') . ' ' . ($mypPart[79] > 0 ? '[+/-'.$mypPart[79].']' : ''));
//Tmp camara
$sheet->setCellValueByColumnAndRow($column, $row++, ($mypPart[49] > 0 ? $mypPart[49] : '-') . ' ' . ($mypPart[80] > 0 ? '[+/-'.$mypPart[80].']' : ''));
//Veloc Impresion
$sheet->setCellValueByColumnAndRow($column, $row++, ($mypPart[50] > 0 ? $mypPart[50] : '-') . ' ' . ($mypPart[81] > 0 ? '[+/-'.$mypPart[81].']' : ''));
//Perim y relleno
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[51]);
//Soportes
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[52]);
//Punto laser
$sheet->setCellValueByColumnAndRow($column, $row++, ($mypPart[54] > 0 ? $mypPart[54] : '-') . ' ' . ($mypPart[83] > 0 ? '[+/-'.$mypPart[83].']' : ''));
//Pot fuente
$sheet->setCellValueByColumnAndRow($column, $row++, ($mypPart[55] > 0 ? $mypPart[55] : '-') . ' ' . ($mypPart[84] > 0 ? '[+/-'.$mypPart[84].']' : ''));
//Tam pixel
$sheet->setCellValueByColumnAndRow($column, $row++, ($mypPart[56] > 0 ? $mypPart[56] : '-') . ' ' . ($mypPart[85] > 0 ? '[+/-'.$mypPart[85].']' : ''));
//Tpo Expos
$sheet->setCellValueByColumnAndRow($column, $row++, ($mypPart[57] > 0 ? $mypPart[57] : '-') . ' ' . ($mypPart[86] > 0 ? '[+/-'.$mypPart[86].']' : ''));
//Dist HAtch
$sheet->setCellValueByColumnAndRow($column, $row++, ($mypPart[58] > 0 ? $mypPart[58] : '-') . ' ' . ($mypPart[87] > 0 ? '[+/-'.$mypPart[87].']' : ''));
//Vel recoaster
$sheet->setCellValueByColumnAndRow($column, $row++, ($mypPart[59] > 0 ? $mypPart[59] : '-') . ' ' . ($mypPart[82] > 0 ? '[+/-'.$mypPart[82].']' : ''));
//Enfriam
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[60]);
//Atmosf
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[61]);
//Saturac
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[62]);
//Obs Fab
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[53]);
$row++;
$row++;
//Composición materia prima
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[14]);
//Certificación materia prima
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[15]);
//Color materia prima
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[16]);
//Certificación proceso
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[17]);
//Certificación pieza
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[18]);
//Normativa aplicable
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[19]);
//Proceso acabado
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[20]);
//Otros tratamientos
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[21]);
//Observaciones
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[22]);
$row++;
$row++;
//Archivo CAD (.step, otros)
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[63]);
//Archivo STL
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[64]);
//Archivo Fabricación (.gcode, .pdf, otros)
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[66]);
//Archivo Verificación (.txt, .pdf, .doc)
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[67]);
//Planos 2D (.pdf)
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[65]);
//Archivo N01
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[68]);
//Archivo N02
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[69]);
//Archivo N03
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[70]);
//Archivo N04
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[71]);
//Archivo N05
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[72]);
if(!$isSupplier){
$row++;
$row++;
//Bibliotecas
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[88]);
}
$row++;
$row++;
//STL DATA
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[89]);
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[90]);
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[91]);
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[92]);
$sheet->setCellValueByColumnAndRow($column, $row++, $mypPart[93]);
$row = 2;
$column++;
}
return $spreadsheet;
}
}