src/Controller/CustomProductController.php line 53
<?phpnamespace App\Controller;use App\Entity\Order;use App\Entity\Product;use App\Enum\NotificationContent;use App\Form\AdressType;use App\Form\CustomProductAddFileType;use App\Form\CustomProductStepTwoType;use App\Form\CustomProductType;use App\Form\CustomProdutStepAdressType;use App\Repository\AcierOptionsRepository;use App\Repository\AdressRepository;use App\Repository\AluminiumOptionsRepository;use App\Repository\InoxOptionsRepository;use App\Repository\NotificationsRepository;use App\Repository\OptionsRepository;use App\Repository\TexteFirstPageRepository;use App\Service\SaveFile;use App\Service\SendEmailNotification;use DateInterval;use DateTimeImmutable;use Doctrine\ORM\EntityManagerInterface;use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;use Symfony\Component\Form\Extension\Core\Type\CollectionType;use Symfony\Component\Form\Extension\Core\Type\SubmitType;use Symfony\Component\HttpFoundation\JsonResponse;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\RequestStack;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\Mailer\MailerInterface;use Symfony\Component\Mime\Address;use Symfony\Component\Mime\Email;use Symfony\Component\Mime\Part\DataPart;use Symfony\Component\Mime\Part\Multipart\FormDataPart;use Symfony\Component\Routing\Annotation\Route;use Symfony\Contracts\HttpClient\HttpClientInterface;class CustomProductController extends AbstractController{private $requestStack;public function __construct(RequestStack $requestStack){$this->requestStack = $requestStack;}#[Route('/custom-product', name: 'custom_product')]public function index(Request $request, EntityManagerInterface $manager, NotificationsRepository $notificationRepo, TexteFirstPageRepository $tfpr, SaveFile $saveFile): Response{$this->denyAccessUnlessGranted('ROLE_USER');$customProduct = $this->createForm(CustomProductType::class);$customProduct->handleRequest($request);$user = $this->getUser();// dd($request->request->all());if ($customProduct->isSubmitted() && $customProduct->isValid()) {$data = $customProduct->getData();$order = new Order();$order->setName($data["devis_name"]);$order->setUserOf($user);$manager->persist($order);$manager->flush();$resultSaveFile = $saveFile->addFilesToOrder($data['fileIdentifiant'], $order);if ($resultSaveFile) {return $this->redirectToRoute('custom_product_2', array('id' => $order->getID()));} else {$this->addFlash('error', 'Veuillez ajouter un fichier au minimum pour continuer');return $this->redirectToRoute('custom_product');}}return $this->render('custom_product/index.html.twig', ['customProductForm' => $customProduct->createView(),'textFirstPage' => $tfpr->find(1),'notifications' => $notificationRepo->getNotifications($user),'fileIdentifiant' => uniqid() . uniqid()]);}#[Route('/custom-product/upload-image/{id}', name: 'custom_product_uploadImage', methods: ['POST'])]public function uploadImage(string $id, Request $request, EntityManagerInterface $manager, SaveFile $saveFile): JsonResponse{$this->denyAccessUnlessGranted('ROLE_USER');if ($request->files->get('file')) {foreach ($request->files->get('file') as $value) {$saveFile->addTempFile($value, $id);}}return new JsonResponse('Ok');}public function metalOptions($values){$toReturn = [];foreach ($values as $value) {$toReturn[] = [$value->getName(), array($value->getEpaisseur(), $value->getEpaisseurSupDix()), $value->getRadName()];}return $toReturn;}#[Route('/custom-product-2/get-data', name: 'custom_product_2_data')]public function dataStep2(AcierOptionsRepository $acierOptionsRepository, AluminiumOptionsRepository $aluminiumOptionsRepository, InoxOptionsRepository $inoxOptionsRepository, OptionsRepository $optionsRepository): Response{$matiere_reference_acier = $this->metalOptions($acierOptionsRepository->findAll());$matiere_reference_aluminium = $this->metalOptions($aluminiumOptionsRepository->findAll());$matiere_reference_inox = $this->metalOptions($inoxOptionsRepository->findAll());$matiereType = $optionsRepository->findOneBy(['name' => 'matiereType']);$gravure = $optionsRepository->findOneBy(['name' => 'gravure']);$laminage_brossage = $optionsRepository->findOneBy(['name' => 'sens_de_brossage']);$destinationPiece = $optionsRepository->findOneBy(['name' => 'destination_piece']);$pieceAspect = $optionsRepository->findOneBy(['name' => 'piece_aspect']);$thermoRef = $optionsRepository->findOneBy(['name' => 'thermoRef']);$thmermoFace = $optionsRepository->findOneBy(['name' => 'thermoFace']);$matiereModele = $optionsRepository->findOneBy(['name' => 'matiereModele']);$matiereEpaisseur = $optionsRepository->findOneBy(['name' => 'matiereEpaisseur']);$pdfTech = $optionsRepository->findOneBy(['name' => 'pdfTech']);$toReturn = [$matiere_reference_acier, $matiere_reference_aluminium, $matiere_reference_inox, (array)$matiereType, (array)$gravure, (array)$laminage_brossage, (array)$destinationPiece, (array)$pieceAspect, (array)$thermoRef, (array)$thmermoFace, (array)$matiereModele, (array)$matiereEpaisseur, (array)$pdfTech];return new Response(json_encode($toReturn));}#[Route('/custom-product-2/add/{id}', name: 'custom_product_2_add')]public function addStep2(Order $order, EntityManagerInterface $manager, SaveFile $saveFile, Request $request): JsonResponse{$toReturn = [];for ($i = 0; $i < count($request->files->get('file')); $i++) {$file = $saveFile->saveInPublic($request->files->get('file')[$i], $order, 'plan');$product = new Product();$product->setRelateOrder($order);$product->addFile($file);$manager->persist($product);$manager->flush();$toReturn[] = [$product->getId(), $file->getOriginalName()];}return new JsonResponse($toReturn);}#[Route('/custom-product-2/remove/{id}', name: 'custom_product_2_remove')]public function removeStep2(Product $product, EntityManagerInterface $manager, SaveFile $saveFile): Response{$order = $product->getRelateOrder();$order->removeProduct($product);$plan = $product->getFiles()[0];$dateOrder = $order->getCreatedAt();$year = $dateOrder->format('Y');$month = $dateOrder->format('m');$file_path = '/public/uploads/' . $year . "/" . $month . '/' . $order->getId() . '/' . $plan->getFileName();$saveFile->removeFile($file_path);$manager->remove($product);$manager->flush();$manager->persist($order);$manager->flush();return new Response('Order deleted');}#[Security("is_granted('ROLE_USER') and (user === order.getUserOf() or is_granted('ROLE_ADMIN'))")]#[Route('/custom-product-2/{id}', name: 'custom_product_2')]public function step2(Order $order, Request $request, EntityManagerInterface $manager, NotificationsRepository $notificationRepo, SaveFile $saveFile, AcierOptionsRepository $acierOptionsRepository, InoxOptionsRepository $inoxOptionsRepository, AluminiumOptionsRepository $aluminiumOptionsRepository): Response{$this->denyAccessUnlessGranted('ROLE_USER');$isAdmin = $this->isGranted('ROLE_ADMIN');if (($this->getUser() !== $order->getUserOf()) && !$isAdmin) {return $this->redirectToRoute('home');}$products = $order->getProducts();foreach ($products as $value) {switch ($value->getMatiereType()) {case 'Acier':$value->setMatiereReferenceAcier($acierOptionsRepository->findOneBy(['RadName' => $value->getMatiereReference()]));break;case 'Aluminium':$value->setMatiereReferenceAlu($aluminiumOptionsRepository->findOneBy(['RadName' => $value->getMatiereReference()]));break;case 'Inox':$value->setMatiereReferenceInox($inoxOptionsRepository->findOneBy(['RadName' => $value->getMatiereReference()]));break;default:$value->setMatiereReferenceAcier($acierOptionsRepository->findOneBy(['RadName' => $value->getMatiereReference()]));break;}}$session = $request->getSession();$session->set('order-id', $order->getId());$addProductForm = $this->createForm(CustomProductAddFileType::class);$addProductForm->handleRequest($request);$customProduct = $this->createFormBuilder()->add('products', CollectionType::class, ['entry_type' => CustomProductStepTwoType::class,'allow_add' => true,'data' => $products,])->add('submit', SubmitType::class, ['attr' => ['class' => 'btn custom_product_submit_button']])->getForm();$customProduct->handleRequest($request);$filesTitle = [];foreach ($products as $value) {$file = $value->getFiles();$filesTitle[] = [$file[0]->getOriginalName(), $value->getId(), $value->getMatiereEpaisseur()];}if ($addProductForm->isSubmitted() && $addProductForm->isValid()) {$data = $addProductForm->getData();foreach ($request->files->get("custom_product_add_file")["file"] as $value) {$file = $saveFile->saveInPublic($value, $order, 'plan');$product = new Product();$product->setRelateOrder($order);$product->addFile($file);$manager->persist($product);$manager->flush();}return $this->redirectToRoute('custom_product_2', array('id' => $order->getID()));}if ($customProduct->isSubmitted() && $customProduct->isValid()) {$data = $customProduct->getData();$allProducts = $data['products'];// dd($allProducts->getValues());foreach ($allProducts as $value) {$matiereType = $value->getMatiereType();switch ($matiereType) {case 'Aluminium':$value->setMatiereReference($value->getMatiereReferenceAlu()->getRadName());break;case 'Inox':$value->setMatiereReference($value->getMatiereReferenceInox()->getRadName());break;case 'Acier':$value->setMatiereReference($value->getMatiereReferenceAcier()->getRadName());break;default:# code...break;}$manager->persist($value);}$order->setStatus('step2');$manager->persist($order);$manager->flush();return $this->redirectToRoute('custom_product_3', array('id' => $order->getId()));}return $this->render('custom_product/step2.html.twig', ['customProductForm' => $customProduct->createView(),'addProductForm' => $addProductForm->createView(),'devis' => $order,'filesTitle' => $filesTitle,'notifications' => $notificationRepo->getNotifications($order->getUserOf()),]);}#[Security("is_granted('ROLE_USER') and (user === order.getUserOf() or is_granted('ROLE_ADMIN'))")]#[Route('/custom-product-3/{id}', name: 'custom_product_3')]public function step3(Order $order, Request $request, EntityManagerInterface $manager, NotificationsRepository $notificationRepo, AdressRepository $adressRepository, OptionsRepository $optionsRepository): Response{$this->denyAccessUnlessGranted('ROLE_USER');$isAdmin = $this->isGranted('ROLE_ADMIN');if (($this->getUser() !== $order->getUserOf()) && !$isAdmin) {return $this->redirectToRoute('home');}$user = $this->getUser();$session = $request->getSession();$session->set('order-id', $order->getId());$urgence = $optionsRepository->findOneBy(['name' => 'urgence'])->getInfoBulle();if ($user) {$userAdress = $adressRepository->findBy(['atUser' => $user]);$formAdress = $this->createForm(AdressType::class);$selectAdress = $this->createForm(CustomProdutStepAdressType::class);$formAdress->handleRequest($request);$selectAdress->handleRequest($request);if ($selectAdress->isSubmitted() && $selectAdress->isValid()) {$data = $selectAdress->getData();if ($data['adress'] && $data['adressFacturation']) {$order->setAdress($data['adress']);$order->setFacturationAdress($data['adressFacturation']);$order->setIsUrgence($data['isUrgence']);$order->setStatus('step3');$order->setUserOf($user);$manager->persist($order);$manager->flush();return $this->redirectToRoute('custom_product_4', array('id' => $order->getId()));} else {$this->addFlash('error','Vous devez ajouter une adresse pour passer continuer en cliquant sur le bouton ajouter une adresse en haut à droite');return $this->redirectToRoute('custom_product_3', array('id' => $order->getId()));}}if ($formAdress->isSubmitted() && $formAdress->isValid()) {$adress = $formAdress->getData();$adress->setAtUser($user);$manager->persist($adress);$manager->flush();$this->addFlash('success','Vous avez bien modifié votre profil');return $this->redirectToRoute('custom_product_3', array('id' => $order->getId()));}return $this->render('custom_product/step3.html.twig', ['formAdress' => $formAdress->createView(),'selectAdress' => $selectAdress->createView(),'userAdress' => $userAdress,'devis' => $order,'notifications' => $notificationRepo->getNotifications($order->getUserOf()),'urgenceTips' => $urgence,]);} else {$session = $this->requestStack->getSession();$session->set('redirection_url', 'custom_product_3');return $this->redirectToRoute('app_login');}}#[Security("is_granted('ROLE_USER') and user === order.getUserOf()")]#[Route('/custom-product-4/{id}', name: 'custom_product_4')]public function step4(Order $order, HttpClientInterface $client, EntityManagerInterface $manager, NotificationsRepository $notificationRepo, MailerInterface $mailer): Response{$this->denyAccessUnlessGranted('ROLE_USER');$isAdmin = $this->isGranted('ROLE_ADMIN');if (($this->getUser() !== $order->getUserOf()) && !$isAdmin) {return $this->redirectToRoute('home');}if ($order->getStatus() === 'send_to_radan') {return $this->render('custom_product/step4.html.twig', ['devis' => $order,'notifications' => $notificationRepo->getNotifications($order->getUserOf()),]);} elseif ($order->getStatus() === 'step3' || $order->getStatus() === 'waitToLongForDevis') {$products = $order->getProducts();$user = $order->getUserOf();$adressLivraison = $order->getAdress();$csvFile = $order->getCsvFile();$fileName = uniqid();$dateOrder = $order->getCreatedAt();$year = $dateOrder->format('Y');$month = $dateOrder->format('m');$myfile = fopen($this->getParameter('kernel.project_dir') . '/public/uploads/' . $year . "/" . $month . '/' . $order->getId() . '/' . $fileName . '.csv', "w") or die("Unable to open file!");fprintf($myfile, chr(0xEF) . chr(0xBB) . chr(0xBF));$txt = "Id;CustomerId;CustomerName;VatNumber;CustomerAdressLine1;CustomerAdressLine2;CustomerAdressLine3;Postcode;City;State;Country;Civility;FirstName;LastName;Mail;Phone;CadFilePath;MaterialName;Thickness;Quantity;NestOrientation;PartOperations;QuoteOperations;QuoteComment;PartComment\n";fwrite($myfile, $txt);foreach ($products as $product) {$file = $product->getFiles();$fileN = $file[0]->getFileName();$txt = $product->getId() . ";" . $user->getId() . ";" . $user->getFirstName() . " " . $user->getLastName() . ";;" . $adressLivraison->getAdressOne() . ";" . $adressLivraison->getAdressTwo() . ";;" . $adressLivraison->getCp() . ";" . $adressLivraison->getCity() . ";;" . $adressLivraison->getCountry() . ";;" . $user->getFirstName() . ";" . $user->getLastName() . ";" . $user->getEmail() . ";" . $adressLivraison->getPhone() . ";\\\pc-webquote\Radan\Configuration_Data\Webshop\Cad\\" . $fileName . "\\" . $fileN . ";" . $product->getMatiereReference() . ";" . $product->getMatiereEpaisseur() . ";" . $product->getQuantity() . ";" . $product->getSensDeBrossage() . ";Matiere,Laser" . ($order->getIsUrgence() ? ', Urgence' : '') . ($product->getThermoFace() === "null" ? '' : ", " . $product->getThermoFace()) . ";;f;" . 'Destination: ' . $product->getDestinationPiece() . ", Gravure: " . $product->getGravure() . ", Commentaire:" . $product->getComments() . ", RAL thermolaquage:" . $product->getthermoRef() . ", Piece d'aspect:" . ($product->getPieceAspect() ? 'oui' : 'non') . "\n";fwrite($myfile, $txt);}fclose($myfile);$order->setCsvFile($fileName . '.csv');$order->setStatus('send_to_radan');$manager->persist($order);$manager->flush();$csvFile = $fileName . '.csv';$file3d = [];// Transfert de fichierforeach ($products as $value) {$f = $value->getFiles();foreach ($f as $value) {$formData = new FormDataPart(['files' => DataPart::fromPath($this->getParameter('kernel.project_dir') . '/public/uploads/' . $year . "/" . $month . '/' . $order->getId() . '/' . $value->getFileName())]);try {$client->request('POST', 'http://' . $_ENV['RADQUOTEIP'] . ':80/uploadFile', ['headers' => $formData->getPreparedHeaders()->toArray(),'body' => $formData->bodyToIterable(),]);array_push($file3d, $value->getFileName());} catch (\Exception $e) {$email = (new Email())->from(new Address('metalead@preprod.my-site-web.com', 'Problème Metalead'))->to('julien@bim-digital.com')->priority(Email::PRIORITY_HIGH)->subject('ERREUR API METALEAD')->text('Attention l api de Metalead a un problème, veuillez vérifier son état');$mailer->send($email);$this->addFlash('error', 'Oups, nous avons eu un soucis, veuillez réessayer dans quelques minutes');return $this->redirectToRoute('custom_product_3', ['id' => $order->getId()]);}}}$formData = new FormDataPart(['files' => DataPart::fromPath($this->getParameter('kernel.project_dir') . '/public/uploads/' . $year . "/" . $month . '/' . $order->getId() . '/' . $csvFile),'orderId' => strval($order->getId()),'filesName' => $file3d]);try {$client->request('POST', 'http://' . $_ENV['RADQUOTEIP'] . ':80/uploadCsv', ['headers' => $formData->getPreparedHeaders()->toArray(),'body' => $formData->bodyToIterable(),]);} catch (\Exception $e) {$email = (new Email())->from(new Address('metalead@preprod.my-site-web.com', 'Problème Metalead'))->to('julien@bim-digital.com')->priority(Email::PRIORITY_HIGH)->subject('ERREUR API METALEAD')->text('Attention l api de Metalead a un problème, veuillez vérifier son état');$mailer->send($email);$this->addFlash('error', 'Oups, nous avons eu un soucis, veuillez réessayer dans quelques minutes');return $this->redirectToRoute('custom_product_3', ['id' => $order->getId()]);}return $this->render('custom_product/step4.html.twig', ['devis' => $order,'notifications' => $notificationRepo->getNotifications($order->getUserOf()),]);} else if ($order->getStatus() == "backFromRQ") {return $this->redirectToRoute('custom_product_5', array('id' => $order->getID()));} else if ($order->getStatus() == "ErrorSendingRQ") {return $this->redirectToRoute('custom_product_5', array('id' => $order->getID()));} else {return $this->redirectToRoute('devis_list');}}#[Security("is_granted('ROLE_USER') and user === order.getUserOf() or is_granted('ROLE_ADMIN')")]#[Route('/custom-product-5/{id}', name: 'custom_product_5')]public function step5(Order $order, EntityManagerInterface $manager, NotificationsRepository $notificationRepo): Response{$this->denyAccessUnlessGranted('ROLE_USER');$isAdmin = $this->isGranted('ROLE_ADMIN');if (($this->getUser() !== $order->getUserOf()) && !$isAdmin) {return $this->redirectToRoute('home');}if ($order->getStatus() !== 'backFromRQ' or $order->getStatus() !== 'ErrorSendingRQ') {$this->redirectToRoute('devis_list');}$isPayable = true;if ($order->getStatus() === 'backFromRQ' or $order->getStatus() === 'orderCanceled') {$dateOrder = $order->getCreatedAt();$year = $dateOrder->format('Y');$month = $dateOrder->format('m');if ($order->getDevisDate() && ($order->getDevisDate()->add(new DateInterval('P2D')) < new \DateTimeImmutable())) {$order->setStatus('waitToLongForDevis');$manager->persist($order);$manager->flush();}$pdf = '/uploads/' . $year . "/" . $month . '/' . $order->getId() . '/' . $order->getPdfFromRQ()->getFileName();$isPayable = !($order->getPriceHT() < 500 && $order->getAdress()->getCountry() === "Suisse");if (!$isPayable) {$order->setStatus('orderCanceled');$manager->persist($order);$manager->flush();$message = "Pour une commande en suisse, le montant minimum est de 500€, il n'est donc pas possible de poursuivre cet achat";}} else {$dateOrder = $order->getCreatedAt();$year = $dateOrder->format('Y');$month = $dateOrder->format('m');$pdf = '/uploads/' . $year . "/" . $month . '/' . $order->getId() . '/erroFile.txt';$isPayable = false;}return $this->render('custom_product/step5.html.twig', ['pdfFromRq' => $pdf,'devis' => $order,'isPayable' => $isPayable,'message' => $message,'notifications' => $notificationRepo->getNotifications($order->getUserOf()),]);}#[Security("is_granted('ROLE_USER') and user === order.getUserOf()")]#[Route('/get-status/{id}', name: 'custom_product_get_status', methods: ['GET'])]public function getStatus(Order $order): JsonResponse{return new JsonResponse(['status' => $order->getStatus()]);}#[Route('/returnOfFile/{id}', name: 'custom_product_returnFile')]public function returnOfFiles(Order $order, Request $request, EntityManagerInterface $manager, SaveFile $saveFile, SendEmailNotification $notif){if ($request->request->get('error') && $request->request->get('error') === "502") {$saveFile->saveErrorFile($order, $request->request->get('errorContent'));$order->setStatus('ErrorSendingRQ');$manager->flush();$notif->sendBoth(NotificationContent::NOTFINISH, $order);return new Response('Ok pas good', 200, array('Content-Type' => 'application/json'));} else {foreach ($request->files->all() as $value) {$file = $saveFile->saveInPublic($value, $order, 'backFromRQ');if (substr($file->getFileName(), -3) === 'pdf') {$order->setPdfFromRQ($file);} else {$order->setCsvFromRQ($file);}}$order->setStatus('backFromRQ');$order->setDevisDate(new DateTimeImmutable());$manager->persist($order);$manager->flush();$csv = $order->getCsvFromRQ()->getFileName();$dateOrder = $order->getCreatedAt();$year = $dateOrder->format('Y');$month = $dateOrder->format('m');$path = $this->getParameter('kernel.project_dir') . '/public/uploads/' . $year . "/" . $month . '/' . $order->getId() . '/' . $csv;$handle = fopen($path, "r"); // open in readonly mode$i = 0;$priceT = 0;while (($row = fgetcsv($handle, 0, ';')) !== false) {if ($i > 0) {$priceT += $row[14] * $row[5];foreach ($order->getProducts() as $value) {if ($value->getId() == $row[0]) {$value->setUnitPrice($row[14]);$manager->persist($value);$manager->flush();}}}$i++;}fclose($handle);$order->setPriceHT($priceT);$manager->persist($order);$notif->sendBoth(NotificationContent::FINISH, $order);return new Response('Ok c est good', 200, array('Content-Type' => 'application/json'));}}}